第 3 章

模型总览

这一页把整个模型一次性摊开:有哪些聚合、有哪些服务、模块之间谁依赖谁、 以及"一次执行"到底是怎么被驱动的。看完这页,后面四章就是放大镜。

3.1数字速览

领域模块
4 个
感知 / 行动 / 规划 / 记忆
分层
2 层
应用层 / 基础设施层
聚合
13 个
每个聚合都有自己的不变量(红线)
领域服务
3 个
纯规则:装配、计划校验、验证链
应用用例 / 组件
8 / 17
用例编排与执行循环
端口
24 个
应用层定义,基础设施实现
领域事件
17 个
由聚合根发出,代表状态真的变了
应用事件
2 个
过程通知,不对应状态变化

3.2领域模型总图

图按模块分组。实线菱形是"组合"(同一个聚合内部), 虚线箭头是"引用"(跨聚合/跨模块,只存 ID)。

classDiagram
    namespace 感知模块 {
        class Session {
            <<AggregateRoot>>
            -SessionId id
            -SessionId parentSessionId
            -AgentId agentId
            -ModelId activeModelId
            -String title
            -Date createdDate
            -List~Record~ records
            -SystemPromptSnapshot systemPromptSnapshot
            +appendRecord(RecordRole, String, ToolResultPayload) Record
            +buildContextForLlm(TokenEstimator, int) ContextWindow
            +markSummarized(String summary, int coveredThroughSequence)
            +switchModel(ModelId)
            +cancel()
        }
        class Record {
            <<Entity>>
            -RecordId id
            -RecordRole role
            -String content
            -String reasoning
            -String turnId
            -String producerModelId
            -ToolResultPayload toolPayload
            -int summaryCoversUpTo
            -int sequence
            -Date date
        }
        class ToolResultPayload {
            <<ValueObject>>
            -boolean isTruncated
            -String resourceUri
        }
        class SystemPromptSnapshot {
            <<ValueObject>>
            -String renderedPrompt
            -List~ToolSchemaSnapshot~ toolList
            -List~SkillSummarySnapshot~ skillList
        }
        class ToolSchemaSnapshot {
            <<ValueObject>>
            -String name
            -String description
            -String parametersJsonSchema
            -String outputDescription
        }
        class SkillSummarySnapshot {
            <<ValueObject>>
            -String name
            -String description
        }
        class ContextWindow {
            <<ValueObject>>
            -List~Record~ records
            -ContextUsage usage
        }
        class ContextUsage {
            <<ValueObject>>
            -int usedTokens
            -int inputCeiling
            -int systemTokens
            -int summaryTokens
            -int windowRecordCount
        }
        class RuntimePolicy {
            <<AggregateRoot>>
            +int maxRetries
            +int reflectionThreshold
            +int maxReplanGeneration
            +int maxReActRounds
            +int summarizationTokenThreshold
            +int inputSafetyMargin
            +int collapseRetainRecordCount
            +int toolResultTruncateLength
            +int subagentExecutionTimeoutMillis
            +int experienceCapacity
            +int experienceTopN
            +int experiencePerPlan
            +double experienceInitialConfidence
            +double experienceConfidenceStep
            +double experienceRetireThreshold
            +double budgetWarnRatio
            +long budgetLimitTokens
            +int skillCapacity
            +List~ModelId~ modelFallbackChain
            +List~ToolId~ trustedToolIds
            +isToolTrusted(ToolId) boolean
            +needsReflection(int) boolean
            +adjust(...)
        }
        class RecordRole {
            <<Enumeration>>
            SYSTEM
            USER
            ASSISTANT
            TOOL_REQUEST
            TOOL_RESULT
            SUMMARY
        }
        class AgentSnapshotInput {
            <<ValueObject>>
            -AgentId agentId
            -PromptTemplate basePrompt
            -Map promptVariables
            -List~ToolSchemaSnapshot~ activeTools
            -List~SkillSummarySnapshot~ activeSkills
            -List~String~ sopReferencedToolNames
        }
        class StartSessionUseCase {
            <<ApplicationService>>
            +start(AgentId, ModelId, String) Session
            +startSubSession(SessionId, AgentId, ModelId, String) Session
        }
        class SessionTitleGenerator {
            <<DomainService>>
            +generate(Session) String
        }
        class SystemPromptAssembler {
            <<DomainService>>
            +assemble(AgentSnapshotInput) SystemPromptSnapshot
        }
        class ContextWindowService {
            <<DomainService>>
            +ensureWithinLimit(Session) void
            +forceCollapse(Session) void
        }
        class SwitchModelUseCase {
            <<ApplicationService>>
            +switchTo(SessionId, ModelId) Result
        }
    }

    namespace 行动模块 {
        class ToolDefinition {
            <<AggregateRoot>>
            -ToolId id
            -String name
            -String description
            -ToolSchema inputSchema
            -ToolSchema outputSchema
            -ToolSource source
            -SideEffectLevel sideEffect
            -int timeoutMillis
            -ToolStatus status
            +updateMetadata(String, ToolSchema)
            +activate()
            +deprecate()
            +validateArgs(Map)
        }
        class ToolSchema {
            <<ValueObject>>
            -String jsonSchemaString
        }
        class ToolSource {
            <<ValueObject>>
            -SourceType type
            -String endpointOrIdentifier
        }
        class SourceType {
            <<Enumeration>>
            INTERNAL
            NATIVE
            REST
            MCP
            PLUGIN
        }
        class SideEffectLevel {
            <<Enumeration>>
            READ_ONLY
            REPEATABLE
            IRREVERSIBLE
        }
        class ToolStatus {
            <<Enumeration>>
            DRAFT
            ACTIVE
            DEPRECATED
        }
        class PluginManifest {
            <<AggregateRoot>>
            -PluginId id
            -String version
            -int apiVersion
            -boolean trusted
            -Date grantedAt
            -Set~ToolId~ toolIds
            -Set~String~ declaredCapabilities
            -Set~String~ grantedCapabilities
            +create(PluginId, String, int, Set~ToolId~, Set~String~, boolean, Date) PluginManifest
            +grant(String)
            +revoke(String)
            +isTrusted() boolean
        }
        class Provider {
            <<AggregateRoot>>
            -ProviderId id
            -String name
            -String apiEndpoint
            -ChatProtocol protocol
            -ApiCredential credential
            -ProviderStatus status
            +updateCredential(ApiCredential)
            +activate()
            +deprecate()
        }
        class Model {
            <<AggregateRoot>>
            -ModelId id
            -ProviderId providerId
            -String modelName
            -ModelStatus status
            -ContextLimit contextLimit
            -List~ModelCapability~ capabilities
            +hasCapability(ModelCapability) boolean
            +activate()
            +deprecate()
        }
        class ApiCredential {
            <<ValueObject>>
            -String apiKeyRef
        }
        class ContextLimit {
            <<ValueObject>>
            -int maxInputTokens
            -int maxOutputTokens
        }
        class ModelCapability {
            <<ValueObject>>
            -String capabilityName
        }
        class ProviderStatus {
            <<Enumeration>>
            ACTIVE
            DEPRECATED
        }
        class ChatProtocol {
            <<Enumeration>>
            OPENAI_CHAT
            ANTHROPIC_MESSAGES
            GEMINI
        }
        class ModelStatus {
            <<Enumeration>>
            ACTIVE
            DEPRECATED
        }
        class AgentDefinition {
            <<AggregateRoot>>
            -AgentId id
            -String name
            -AgentSource source
            -PromptTemplate basePrompt
            -AgentStatus status
            -List~ToolId~ toolIds
            -List~SkillId~ skillIds
            +listBoundToolIds() List~ToolId~
            +listBoundSkillIds() List~SkillId~
            +bindTool(ToolId)
            +unbindTool(ToolId)
            +bindSkill(SkillId)
            +updatePrompt(PromptTemplate)
            +activate()
            +deprecate()
        }
        class PromptTemplate {
            <<ValueObject>>
            -String templateText
            -List~String~ variables
            +render(Map) String
        }
        class AgentSource {
            <<Enumeration>>
            USER_DEFINED
            BUILT_IN
        }
        class AgentStatus {
            <<Enumeration>>
            DRAFT
            ACTIVE
            DEPRECATED
        }
        class Budget {
            <<AggregateRoot>>
            -BudgetId id
            -SessionId sessionFamilyRootId
            -long consumedTokens
            -boolean warned
            +recordUsage(long tokens, RuntimePolicy policy)
            +shouldWarn(RuntimePolicy) boolean
        }
        class ToolExecOutcome {
            <<ValueObject>>
            -String content
            -boolean isTruncated
            -String resourceUri
        }
        class ModelInvocationRequest {
            <<ValueObject>>
            -ModelId targetModelId
            -String systemPrompt
            -List~ChatMessage~ messages
            -List~ToolSchemaSnapshot~ tools
            -int estimatedPromptTokens
            -ModelCapability requiredCapability
        }
        class ModelInvocationResult {
            <<ValueObject>>
            -String text
            -List~ToolCall~ toolCalls
            -String reasoning
            -ModelUsage usage
            -ModelId servedModelId
        }
        class ChatMessage {
            <<ValueObject>>
            -RecordRole role
            -String content
            -List~ToolCall~ toolCalls
            -String toolCallId
            -String reasoning
        }
        class ToolCall {
            <<ValueObject>>
            -String callId
            -String name
            -String argumentsJson
        }
        class ModelUsage {
            <<ValueObject>>
            -long inputTokens
            -long outputTokens
        }
        class ToolExecutor {
            <<DomainService>>
            +execute(Session, ToolDefinition, Map) ToolExecOutcome
        }
        class ModelInvoker {
            <<DomainService>>
            +invoke(ModelInvocationRequest) ModelInvocationResult
        }
        class BudgetService {
            <<DomainService>>
            +recordUsage(SessionId, long)
            +settleFromSubSession(SessionId, long)
        }
    }

    namespace 规划模块 {
        class Plan {
            <<AggregateRoot>>
            -PlanId id
            -SessionId sessionId
            -String goal
            -PlanStatus status
            -int replanGeneration
            -List~PlanStep~ steps
            +getCurrentStep() PlanStep
            +assignExperiences(StepId, List~ExperienceId~)
            +markStepSucceeded(StepId, String, VerificationReportId)
            +markStepFailed(StepId, VerificationReportId)
            +recordReflection(StepId, int, ReflectionId)
            +recordSkillUsage(StepId, int, SkillId)
            +applyReplan(List~PlanStep~)
            +terminate(String)
        }
        class PlanStep {
            <<Entity>>
            -StepId id
            -int sequence
            -String description
            -String goal
            -String expectedOutcome
            -String verificationCriteria
            -Set~VerificationType~ requiredVerifications
            -StepStatus status
            -List~Attempt~ attempts
            -List~ExperienceId~ assignedExperienceIds
            -String finalOutput
            -VerificationReportId finalVerificationReportId
        }
        class Attempt {
            <<Entity>>
            -int attemptNo
            -RecordRange recordRange
            -List~SkillId~ usedSkillIds
            -VerificationReportId verificationReportId
            -ReflectionId reflectionId
            -AttemptOutcome outcome
        }
        class RecordRange {
            <<ValueObject>>
            -RecordId startRecordId
            -RecordId endRecordId
        }
        class VerificationReport {
            <<AggregateRoot>>
            -VerificationReportId id
            -PlanId planId
            -StepId stepId
            -int attemptNo
            -VerificationOutcome outcome
            -VerificationType failedType
            -String failureReason
            -Date decidedAt
        }
        class PlanStatus {
            <<Enumeration>>
            EXECUTING
            REPLANNING
            COMPLETED
            FAILED
        }
        class StepStatus {
            <<Enumeration>>
            PENDING
            RUNNING
            VERIFYING
            SUCCEEDED
            FAILED
            SUPERSEDED
        }
        class AttemptOutcome {
            <<Enumeration>>
            SUCCEEDED
            FAILED
        }
        class VerificationOutcome {
            <<Enumeration>>
            PASSED
            FAILED
            UNDETERMINED
        }
        class VerificationType {
            <<Enumeration>>
            DETERMINISTIC
            ENV_FEEDBACK
            LLM_JUDGE
            HUMAN_APPROVAL
        }
        class IterationResult {
            <<ValueObject>>
            -boolean isConverged
            -boolean submitted
            -String submittedSummary
            -int round
            -List~SkillId~ usedSkillIds
        }
        class SessionRunner {
            <<ExtensionPoint>>
            +run(Session, ChunkSink, CancellationToken, RunContext) RunOutcome
        }
        class RunOutcome {
            <<Enumeration>>
            CONVERGED
            SUSPENDED
            ROUNDS_EXHAUSTED
        }
        class RunContext {
            <<ValueObject>>
            -Session session
            -ChunkSink sink
            -CancellationToken cancellation
            -ModelInvocationPort model
            -ToolInvoker tools
            -HumanInteractionPort human
            -ProgressPort progress
            -PlanRepository plans
            -ContextWindowService contextWindow
        }
        class ExecutionLoop {
            <<ApplicationService>>
            +run(Session, ChunkSink, CancellationToken, RunContext) RunOutcome
        }
        class ReActLoop {
            <<ApplicationService>>
            +runIteration(Session, PlanStep) IterationResult
        }
        class VerificationRunner {
            <<ApplicationService>>
            +verify(PlanStep, Attempt) VerificationReport
        }
        class PlanFactory {
            <<DomainService>>
            +create(Session, Map) Plan
        }
    }

    namespace 记忆模块 {
        class Experience {
            <<AggregateRoot>>
            -ExperienceId id
            -String applicableScenario
            -LessonLearned lesson
            -ConfidenceScore confidence
            -ExperienceStatus status
            -int appliedCount
            -Date createdAt
            +reinforce()
            +penalize()
            +archive()
            +mergeWith(Experience)
        }
        class LessonLearned {
            <<ValueObject>>
            -String instruction
            -String expectedOutcome
        }
        class ConfidenceScore {
            <<ValueObject>>
            -double value
        }
        class ExperienceStatus {
            <<Enumeration>>
            ACTIVE
            ARCHIVED
        }
        class Reflection {
            <<AggregateRoot>>
            -ReflectionId id
            -PlanId planId
            -StepId stepId
            -int attemptNo
            -String conclusion
            -Date createdAt
        }
        class SkillDefinition {
            <<AggregateRoot>>
            -SkillId id
            -String name
            -String description
            -String triggerCondition
            -InstructionTemplate sopTemplate
            -SkillStatus status
            -boolean mutable
            +create(SkillId, String, String, String, String) SkillDefinition
            +revise(String, String, String, String)
            +isActive() boolean
            +isMutable() boolean
        }
        class InstructionTemplate {
            <<ValueObject>>
            -String rawMarkdown
        }
        class SkillStatus {
            <<Enumeration>>
            DRAFT
            ACTIVE
            DEPRECATED
        }
        class RetrievalInput {
            <<ValueObject>>
            -PlanId planId
            -List~StepBrief~ steps
        }
        class StepBrief {
            <<ValueObject>>
            -StepId stepId
            -String description
        }
        class DistillationInput {
            <<ValueObject>>
            -PlanId planId
            -SessionId sessionId
            -String goal
            -PlanStatus outcome
            -List~StepTrace~ stepTraces
        }
        class StepTrace {
            <<ValueObject>>
            -StepId stepId
            -String description
            -StepStatus outcome
            -RecordRange recordRange
            -List~SkillId~ usedSkillIds
            -String failureReason
            -String reflectionConclusion
        }
        class FeedbackInput {
            <<ValueObject>>
            -StepId stepId
            -List~ExperienceId~ experienceIds
        }
        class ExperienceRetriever {
            <<ApplicationService>>
            +retrieveAndAssign(RetrievalInput) Map
        }
        class PlanCompletionCurator {
            <<ApplicationService>>
            +curate(Session, DistillationInput) DistillationOutcome
        }
        class ExperienceDistillationService {
            <<ApplicationService>>
            +apply(ExperienceDraft, SessionId)
        }
        class SkillDistillationService {
            <<ApplicationService>>
            +apply(SkillDraft, SessionId)
        }
        class ExperienceFeedbackService {
            <<ApplicationService>>
            +onStepSucceeded(FeedbackInput)
            +onStepFailed(FeedbackInput)
        }
        class SkillSopProvider {
            <<Port>>
            +sop(String skillId) String
        }
    }

    namespace 端口 {
        class ModelInvocationPort {
            <<Port>>
            +invoke(ModelInvocationRequest) ModelInvocationResult
            +describe(ModelId) ModelProfile
        }
        class ModelProfile {
            <<ValueObject>>
            -int maxInputTokens
            -int maxOutputTokens
        }
        class ExternalToolPort {
            <<Port>>
            +invoke(ToolDefinition, Map) String
        }
        class HumanInteractionPort {
            <<Port>>
            +ask(Question) Answer
        }
        class PluginRepository {
            <<Port>>
            +list() List~PluginManifest~
            +load(PluginId) PluginManifest
            +save(PluginManifest)
        }
        class PluginRuntimePort {
            <<Port>>
            +discover() List~PluginDescriptor~
            +toolsOf(PluginId) List~ToolDefinition~
            +start(PluginId)
            +stop(PluginId)
            +unload(PluginId)
            +extension(PluginId, String) Object
            +conflictsOf(PluginId) List~String~
        }
        class PluginDescriptor {
            <<ValueObject>>
            -PluginId id
            -String version
            -int apiVersion
            -boolean loaded
        }
        class ToolInvoker {
            <<ExtensionPoint>>
            +execute(Session, String, Map, RecordId) ToolExecOutcome
        }
    }

    namespace 领域事件 {
        class PlanCreated
        class PlanCompleted
        class PlanFailed
        class StepFailed
        class VerificationRejected
        class ReflectionRecorded
        class ExperienceCreated
        class ExperienceReinforced
        class SkillLearned
        class SkillRevised
        class ExperiencePenalized
        class BudgetWarning
        class SummarizationCompleted
        class SessionCancelled
        class ModelSwitched
        class PolicyAdjusted
        class ToolDefinitionUpdatedEvent
    }

    namespace 应用事件 {
        class SummarizationStarted
        class ExperienceDistillationFinished
    }

    %% ---------- 感知内部 ----------
    Session "1" *-- "0..*" Record : append-only
    Session "1" *-- "1" SystemPromptSnapshot : 会话开启时冻结
    Record *-- ToolResultPayload
    SystemPromptSnapshot *-- ToolSchemaSnapshot
    SystemPromptSnapshot *-- SkillSummarySnapshot
    Record --> RecordRole
    Session ..> ContextWindow : buildContextForLlm 推导
    ContextWindow *-- ContextUsage
    SystemPromptAssembler ..> AgentSnapshotInput : 入参
    SystemPromptAssembler ..> SystemPromptSnapshot : 产出

    %% ---------- 跨模块 ID 引用 ----------
    Session "0..1" --> "0..*" Session : parentSessionId
    Session ..> AgentDefinition : agentId
    Session ..> Model : activeModelId
    Plan ..> Session : sessionId
    Budget ..> Session : sessionFamilyRootId
    Model ..> Provider : providerId
    AgentDefinition ..> ToolDefinition : toolIds
    AgentDefinition ..> SkillDefinition : skillIds
    Attempt ..> Reflection : reflectionId
    Attempt ..> VerificationReport : verificationReportId
    PlanStep ..> Experience : assignedExperienceIds

    %% ---------- 规划内部 ----------
    ExecutionLoop ..> SessionRunner : 实现(默认编排)
    SessionRunner ..> RunContext : 入参
    SessionRunner ..> RunOutcome : 产出
    Plan "1" *-- "1..*" PlanStep
    PlanStep "1" *-- "0..*" Attempt
    Attempt *-- RecordRange
    Plan --> PlanStatus
    PlanStep --> StepStatus
    Attempt --> AttemptOutcome
    PlanStep ..> VerificationType
    VerificationReport --> VerificationOutcome
    VerificationReport --> VerificationType

    %% ---------- 行动内部 ----------
    PluginManifest --> ToolDefinition : toolIds(只记归属,不改工具定义)
    PluginRuntimePort ..> PluginDescriptor : 产出
    ToolExecutor ..> ToolInvoker : 实现
    ToolDefinition *-- ToolSchema
    ToolDefinition *-- ToolSource
    ToolDefinition --> SideEffectLevel
    ToolDefinition --> ToolStatus
    ToolSource --> SourceType
    Provider *-- ApiCredential
    Provider --> ProviderStatus
    Provider --> ChatProtocol
    Model *-- ContextLimit
    Model *-- ModelCapability
    Model --> ModelStatus
    AgentDefinition *-- PromptTemplate
    AgentDefinition --> AgentSource
    AgentDefinition --> AgentStatus

    ModelInvocationRequest *-- ChatMessage
    ModelInvocationResult *-- ToolCall
    ModelInvocationResult *-- ModelUsage
    ChatMessage *-- ToolCall
    ChatMessage ..> RecordRole : role(复用流水角色)

    %% ---------- 记忆内部 ----------
    Experience *-- LessonLearned
    Experience *-- ConfidenceScore
    Experience --> ExperienceStatus
    SkillDefinition *-- InstructionTemplate
    SkillDefinition --> SkillStatus
    DistillationInput *-- StepTrace

    %% ---------- 事件 raise ----------
    Plan ..> PlanCreated : raises
    Plan ..> PlanCompleted : raises
    Plan ..> PlanFailed : raises
    Plan ..> StepFailed : raises
    VerificationReport ..> VerificationRejected : raises
    Reflection ..> ReflectionRecorded : raises
    Experience ..> ExperienceCreated : raises
    Experience ..> ExperienceReinforced : raises
    Experience ..> ExperiencePenalized : raises
    SkillDefinition ..> SkillLearned : raises
    SkillDefinition ..> SkillRevised : raises
    Budget ..> BudgetWarning : raises
    Session ..> SummarizationCompleted : raises
    Session ..> SessionCancelled : raises
    Session ..> ModelSwitched : raises
    RuntimePolicy ..> PolicyAdjusted : raises
    ToolDefinition ..> ToolDefinitionUpdatedEvent : raises

图 3-1 领域模型总图(按模块分组;虚线 = 引用,只存 ID)

3.3服务与端口协作图

flowchart LR
    subgraph 感知
        SF[StartSessionUseCase]
        TG[SessionTitleGenerator]
        SA[SystemPromptAssembler]
        CW[ContextWindowService]
        S[(Session)]
        RP[(RuntimePolicy)]
    end
    subgraph 行动
        TE[ToolExecutor]
        MI[ModelInvoker]
        BS[BudgetService]
        TD[(ToolDefinition)]
        AG[(AgentDefinition)]
        MD[(Model)]
        PV[(Provider)]
        BU[(Budget)]
    end
    subgraph 规划
        OL[ExecutionLoop]
        IL[ReActLoop]
        VS[VerificationRunner]
        PF[PlanFactory]
        P[(Plan)]
        VR[(VerificationReport)]
    end
    subgraph 记忆
        R[ExperienceRetriever]
        DS[ExperienceDistillationService]
        FB[ExperienceFeedbackService]
        SL[SkillSopProvider]
        E[(Experience)]
        RF[(Reflection)]
        SK[(SkillDefinition)]
    end
    P1[[ModelInvocationPort]]
    P2[[SkillSopProvider]]
    P3[[HumanInteractionPort]]

    OL --> CW
    OL --> IL
    OL --> VS
    OL --> R
    OL --> DS
    OL --> FB
    OL --> P
    IL --> S
    IL --> TE
    IL --> MI
    IL --> BS
    IL --> P3
    VS --> VR
    VS --> RP
    VS --> TE
    VS --> P3
    PF --> P
    SF --> S
    SF --> BU
    SF --> SA
    SF --> TG
    TG --> P1
    CW --> S
    CW --> RP
    CW --> P1
    TE --> TD
    TE --> AG
    TE --> RP
    TE --> BU
    TE --> P2
    TE --> P3
    MI -.实现.-> P1
    MI --> MD
    MI --> PV
    MI -.返回 usage.-> BS
    BS --> BU
    SL -.实现.-> P2
    SL --> SK
    R --> E
    DS --> E
    DS --> RF
    DS --> S
    FB --> E
    

图 3-2 十五个领域服务与三个端口的协作关系

3.4模块与分层归属表

归属定位聚合服务 / 组件端口
感知 模型此刻能看到什么:上下文流水 + 快照 + 窗口折叠 + 运行环境策略 Session、RuntimePolicy SystemPromptAssembler(领域);StartSessionUseCase、ContextWindowService、SessionTitleGenerator(应用) 声明 ModelInvocationPort
行动 能做什么 / 用什么做 / 花多少钱:工具、模型、代理、预算、插件 ToolDefinition、Provider、Model、AgentDefinition、Budget、PluginManifest ToolExecutor、BudgetService(应用);ModelInvoker(基础设施,实现 ModelInvocationPort) ExternalToolPort、PluginRepository、PluginRuntimePort
规划 想怎么做 / 做到哪 / 算不算做成 Plan、VerificationReport PlanFactory、VerificationChain(领域);ExecutionLoop、ReActLoop、VerificationRunner(应用) —
记忆 学到的东西如何留存与复用(经验 + 技能自动沉淀) Experience、Reflection、SkillDefinition ExperienceRetriever、PlanCompletionCurator、ExperienceDistillationService、SkillDistillationService、ExperienceFeedbackService(应用) 声明 SkillSopProvider(由基础设施 FileSkillSopProvider 实现)
应用层 用例编排、事务与提交顺序、端口契约、并发 —(只编排,不持有聚合) 8 个用例 + 17 个组件(见 第 8 章) 定义并被基础设施实现
基础设施层 端口背后:文件、模型、终端、时钟 — 22 个适配器(见 第 9 章) 实现 21 个端口(HumanInteractionPort / ProgressPort 由外壳实现,CancellationRegistry 由应用层实现)

3.5依赖方向与三条纪律

flowchart LR
    规划 --> 感知
    规划 --> 行动
    规划 --> 记忆
    记忆 --> 感知
    记忆 --> 行动
    行动 --> 感知
    

图 3-3 单向依赖:感知是叶子,谁都依赖它,它不依赖任何人

维持这张无环图的三个纪律
  1. 需要别人的内容 → 让调用方取好,用值对象传进来。 例:AgentSnapshotInput、DistillationInput、RetrievalInput、FeedbackInput、ModelInvocationRequest。
  2. 需要别人的动作 → 走端口。 例:ModelInvocationPort(应用层声明 / 基础设施实现)、ExternalToolPort、SkillSopProvider、HumanInteractionPort。
  3. 只读别人的聚合不算依赖。 例:记忆按 RecordRange 只读 Session.Record;但绝不追写。

3.6生命周期节点全景

四份模块文档里,"每个聚合的生命周期"都用同一套节点词表。这里汇总一次。

节点含义涉及聚合
平台初始化应用启动:载入策略,播种内置代理 / 工具 / 技能RuntimePolicy、AgentDefinition、ToolDefinition、Provider、Model
策略调整用户修改策略,立即生效RuntimePolicy
会话开启建会话 + 台账 + 冻结快照 + 生成标题Session、Budget
会话续跑重启后继续;半截工具调用视为失败Session、Plan、Budget
子代理派遣派生子会话(并行,各自独立超时)Session
计划诞生校验通过创建计划,并分配经验Plan、Experience
步骤启动取当前步骤,创建一次尝试Plan、Attempt
步骤提交验收submit_step → 触发验证 / 或免验证直接完成VerificationReport、Plan
步骤固化 / 判败步骤的两种结束Plan、Attempt
步骤重试失败后新建尝试;达阈值产生反思Attempt、Reflection
计划重划代次 +1,未执行的步骤置为 SUPERSEDED 并重分配经验;以“无 step 内循环 + replan_plan”发起,成功后发进度事件 PLAN_REPLANPlan、Experience
计划完结成功或失败,触发经验沉淀;成功且本次未用技能时另判技能沉淀Plan、Experience、SkillDefinition
上下文折叠估算用量(含摘要指令)超有效上限 → 以“影子主请求”生成摘要(记覆盖边界)→ 窗口收回到配置条数Session
模型降级故障命中备用模型链Session
归档 / 会话销毁归档(压成 zip 移走,应用不再认识)/ 物理删除(经验保留)Session、Budget

3.7跨模块只靠 ID 说话

从到持有什么用途
SessionAgentDefinitionagentId这个会话用哪个角色
SessionModelactiveModelId当前用哪个模型(可降级切换)
PlanSessionsessionId这个计划属于哪个会话
BudgetSessionsessionFamilyRootId这个台账属于哪个会话族
AttemptVerificationReportverificationReportId这次尝试的验收结论
AttemptReflectionreflectionId这次尝试的复盘结论
PlanStepExperienceassignedExperienceIds这一步分配到了哪些历史经验
AgentDefinitionToolDefinition / SkillDefinitiontoolIds / skillIds这个角色能用什么
ModelProviderproviderId这个模型属于哪个供应商

3.8事件全景

领域事件由聚合根在状态真的改变后发出,代表"这件事已经发生了"。 应用层在事务提交后才发布,订阅方只看 ID 和事件内容。

总口径:领域事件只通知
事件不得驱动任何 IO,也不得作为跨模块协作的触发手段;需要别的模块做事时,由应用层显式调用(ExecutionLoop 调检索 / 沉淀 / 反馈,ManageSessionUseCase 做级联终止)。因此下表的「谁关心」一列只列界面 / 审计这类无副作用消费。
事件谁发出什么时候谁关心
PlanCreatedPlan计划校验通过并创建无功能性订阅方:经验分配由 ExecutionLoop 显式调用;事件只供界面/审计
PlanCompletedPlan所有步骤成功无功能性订阅方:沉淀由 ExecutionLoop 显式调用;事件只供界面/审计
PlanFailedPlan外循环判定重划用尽并终止无功能性订阅方:沉淀由 ExecutionLoop 显式调用;界面 / 审计
StepFailedPlan标记步骤失败无功能性订阅方:外循环读标记后的聚合状态
VerificationRejectedVerificationReport结论为不通过 / 无法判定无功能性订阅方:外循环直接用验证返回值
ReflectionRecordedReflection反思结论落库无功能性订阅方:回注与沉淀素材均由外循环显式读取
ExperienceCreatedExperience归纳产出新经验界面
ExperienceReinforcedExperience加分成功 / 合并去重界面
ExperiencePenalizedExperience减分成功界面
SkillLearnedSkillDefinition沉淀出新技能界面 / 审计
SkillRevisedSkillDefinition改写了可变技能界面 / 审计
BudgetWarningBudget首次越过预警阈值内循环 → 问用户(同一调用栈内的即时通知,等价于记账方法的返回值,不是异步订阅)
SummarizationCompletedSession摘要记录已追加界面 / 审计
SessionCancelledSession会话被终止(Esc / 预算拒绝 / 级联)无功能性订阅方:级联终止由 ManageSessionUseCase 在同一事务内逐个处理
ModelSwitchedSession降级命中备用链审计 / 界面
PolicyAdjustedRuntimePolicy用户修改策略成功只失效本地读取缓存(缓存必须可失效),不驱动任何动作
ToolDefinitionUpdatedEventToolDefinition元数据或 schema 更新运行中会话不订阅(快照已冻结)

应用事件(不进领域模型):SummarizationStarted(压缩开始,无状态转换)、ExperienceDistillationFinished(沉淀流程跑完)。

接下来

后面四章是放大镜:每章都会给出本模块的总览图、对象操作图、聚合与服务清单、 事件清单、生命周期规则,以及关键服务的时序图。

3.9分层视图与端口全景

flowchart TD
    SHELL["外壳<br/>本期 TUI"] --> APP["应用层<br/>8 用例 + 17 组件"]
    APP --> DOM["领域层<br/>13 聚合 + 领域服务 + 领域策略"]
    APP --> PORTS["24 个端口"]
    PORTS --> INF["基础设施层<br/>22 个适配器"]
    INF -.实现.-> PORTS

图 3-4 三层依赖:应用层只认端口,基础设施只实现端口,领域层谁都不认

组端口
持久化CommitScope、SessionRepository、RecordStore、PlanRepository、VerificationReportRepository、ReflectionRepository、ExperienceRepository、BudgetRepository、PolicyRepository、CatalogRepository、ArtifactStore、PluginRepository
模型与外部ModelInvocationPort(invoke / invokeStreaming)、ExternalToolPort、SkillSopProvider、PluginRuntimePort
人机与进度HumanInteractionPort、ProgressPort(实现方:外壳)、DomainEventPublisher
时间与生命周期Clock、TokenCounter、InstanceLock、SchemaMigrator
终止CancellationRegistry(实现方:应用层;模型调用与工具执行据此判断本轮是否已被终止)