Files
ai-agent-scaffold-go/docs/upgrade-plan/P0-运行时内核.md
huanghaosheng a36e91d0dc docs: 阶段计划书拆分到 docs/upgrade-plan 并合并缺陷台账
- 方案第 4 章 P0-P8 拆为 9 份独立阶段计划书,原文件只保留索引与横切章节
- 《项目完善报告》《评审与收编清单》内容拆入各阶段计划书后删除
- 统一缺陷台账 F-01…F-76(历史 71 条 + 方案补充 5 条),保留历史编号对照
- 新增 README 作为路线图索引:阶段清单、执行顺序、第 0 天清扫、台账、迭代约定
2026-11-02 12:08:18 +08:00

23 KiB
Raw Permalink Blame History

文档类型:plan(阶段计划书)| 所属路线图:README.md 阶段:P0 · 运行时内核:让每一次执行都成为一等公民 | 预估:8–10 人日 | 本文件对应:总方案 ../agent-platform-upgrade-plan.md 的第 4.1 节 本阶段收编缺陷:F-01、F-02、F-03、F-04、F-05、F-06、F-07、F-08、F-09(共 9 条,明细见文末附录) 下一阶段:P1

4.1 P0 · 运行时内核:让每一次执行都成为一等公民

目标

把"一次函数调用"升级为"一个有状态、有预算、可观测、可中断、可重放的 Run"。这是后面所有能力的地基:没有 Step 就没有节点级重试(P5),没有事件就没有回放(P7),没有 ctx 就没有流式取消。

当前问题

证据 问题
(*Runner).Run、(*Runner).Stream、(*Runner).notifyPlugins in internal/infrastructure/adk/adapter.go 三处 context.Background(),请求取消传不进去(F-02)
maxToolCallIterations in internal/infrastructure/adk/adapter.go maxToolCallIterations = 4 硬编码(F-09)
adk/adapter.go 全文 572 行 定义/执行/流程/插件混在一个文件,无法单测
(*Runner).notifyPlugins in internal/infrastructure/adk/adapter.go 插件输出走 fmt.Printf,无 run 上下文(F-41)
armory/service.go map 遍历装配,顺序随机(F-04)
SessionStore in internal/domain/agent/ports/ports.go SessionStore 无 ctx,存储层无法超时/取消

设计

4.1.1 新增领域包 internal/domain/runtime

package runtime

type RunID string
type StepID string

type RunStatus string

const (
    RunPending          RunStatus = "pending"
    RunRunning          RunStatus = "running"
    RunWaitingApproval  RunStatus = "waiting_approval"
    RunWaitingHuman     RunStatus = "waiting_human"
    RunSucceeded        RunStatus = "succeeded"
    RunFailed           RunStatus = "failed"
    RunCanceled         RunStatus = "canceled"
    RunExhausted        RunStatus = "exhausted" // 预算耗尽,非错误
)

// Run 是一次执行的聚合根。
type Run struct {
    ID        RunID
    TenantID  string
    UserID    string
    AgentID   string
    SessionID string
    TurnID    string
    Status    RunStatus
    Budget    Budget
    Usage     Usage
    Labels    map[string]string // 业务透传,如 trace_id、实验分组
    StartedAt time.Time
    EndedAt   *time.Time
    Failure   *Failure
}

// Budget 只减不增;任何 Executor 不得自行放大。
type Budget struct {
    MaxSteps     int           // 默认 24
    MaxToolCalls int           // 默认 16
    MaxTokens    int           // prompt+completion 合计,默认 200_000
    MaxWallClock time.Duration // 默认 3m
}

type Usage struct {
    Steps, ToolCalls               int
    PromptTokens, CompletionTokens int
}

func (u *Usage) Total() int { return u.PromptTokens + u.CompletionTokens }
type StepKind string

const (
    StepLLM        StepKind = "llm"
    StepTool       StepKind = "tool"
    StepAgent      StepKind = "agent"
    StepWorkflow   StepKind = "workflow"
    StepApproval   StepKind = "approval"
    StepCompaction StepKind = "compaction"
)

type Step struct {
    ID       StepID
    RunID    RunID
    Index    int
    Kind     StepKind
    Name     string          // 工具名 / Agent 名 / 节点 ID
    Status   StepStatus
    Input    json.RawMessage // 脱敏后
    Output   json.RawMessage
    Usage    Usage
    Attempt  int
    Failure  *Failure
    StartedAt time.Time
    EndedAt  *time.Time
}
// Event 追加写、不可变。P0 落 JSONL,P2 落库,P7 接 OTel。
type Event struct {
    RunID   RunID
    Seq     int64
    At      time.Time
    Type    EventType
    StepID  StepID
    Payload json.RawMessage
}

type EventType string

const (
    EvRunStarted      EventType = "run.started"
    EvRunFinished     EventType = "run.finished"
    EvRunCanceled     EventType = "run.canceled"
    EvRunExhausted    EventType = "run.exhausted"
    EvStepStarted     EventType = "step.started"
    EvStepFinished    EventType = "step.finished"
    EvLLMDelta        EventType = "llm.delta"
    EvLLMUsage        EventType = "llm.usage"
    EvToolRequested   EventType = "tool.requested"
    EvToolResult      EventType = "tool.result"
    EvToolRetry       EventType = "tool.retry"
    EvToolDegraded    EventType = "tool.degraded"
    EvApprovalRequired EventType = "approval.required"
    EvMemoryAssembled EventType = "memory.assembled"
    EvMemoryCompacted EventType = "memory.compacted"
)

4.1.2 执行器插件化(替换 runWithVars 的 switch)

现在的分派逻辑:

// 现状:(*Agent).runWithVars in internal/infrastructure/adk/adapter.go
func (a *Agent) runWithVars(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
    switch a.kind {
    case "llm":              return a.runLLM(ctx, content, vars)
    case "sequential":       return a.runSequential(ctx, content, vars)
    case "loop", "parallel":  return a.runFanOut(ctx, content, vars)
    default:                 return "", fmt.Errorf("agent %q has unknown kind %q", a.name, a.kind)
    }
}

改为:

// internal/domain/runtime/executor.go
type Kind string

type Input struct {
    UserMessage string
    Vars        map[string]string
    Attachments []Attachment
}

type Output struct {
    Text    string
    Vars    map[string]string
    Payload json.RawMessage // 结构化输出(P5 图执行用)
}

type Executor interface {
    Kind() Kind
    Execute(rc *Context, in Input) (Output, error)
}

type Registry struct {
    mu sync.RWMutex
    m  map[Kind]Executor
}

func (r *Registry) Register(e Executor) error // 重复注册返回错误
func (r *Registry) Get(k Kind) (Executor, bool)

Context 是把 Run/Step/预算/事件/工具/记忆一次性注入的唯一入口(类似 *gin.Context):

// internal/domain/runtime/context.go
type Context struct {
    ctx context.Context // 私有,禁止外部取出 Background

    Run    *Run
    Budget *Budget
    Scope  *Scope // {key} 变量作用域,goroutine 安全
    Events EventSink
    Tools  tool.Gateway
    Memory memory.Retriever // P3 的检索端口:事实/摘要/知识库统一召回
    Clock  clock.Clock // 测试注入
}

// Step 开启一个 Step,返回结束回调;正常/panic 都会关闭 Step。
// 这是全项目唯一允许创建 Step 的入口,保证 index 单调与成对。
func (c *Context) Step(kind StepKind, name string) (*StepHandle, error)

func (h *StepHandle) Finish(out Output, err error) error

// Scope 是 {key} 变量作用域;并行分支各持一份副本,join 时显式合并。
type Scope struct {
    mu   sync.RWMutex
    vars map[string]string
}

func (s *Scope) Get(k string) (string, bool)
func (s *Scope) Set(k, v string)
func (s *Scope) Snapshot() map[string]string
func (s *Scope) Merge(branch *Scope) // 并行分支回填,冲突以显式规则处理

用法(executor_llm.go):

step, err := rc.Step(runtime.StepLLM, agentName)
if err != nil { return Output{}, err }
defer step.Finish(...)

reply, err := model.Generate(rc.Context(), msgs, tools)

收益:Step 序号、耗时、token 记账、事件发射、错误归类五件事全部收敛到一处,Executor 只需实现业务逻辑。

4.1.3 终止保证(回答"死循环会不会烧 token")

四道闸门,任一触发即终止,且终止不是异常:

闸门 触发条件 终止动作 状态
墙钟 ctx.Deadline 到期(runtime.budget.max-wall-clock) 取消 ctx run.canceled
步数 Usage.Steps >= MaxSteps 拒绝下一个 Step() run.exhausted
工具次数 Usage.ToolCalls >= MaxToolCalls 后续工具调用直接返回"预算耗尽" run.exhausted
Token Usage.Total() >= MaxTokens 在 LLM 调用前检查,拒绝新调用 run.exhausted

关键实现细节(面试可讲):

  • 检查点放在 LLM 调用之前而不是之后:token 是"调用后才知道"的,所以用「上一轮实际用量 + 本轮 prompt 估算」做预测,超限则先压缩上下文(P4)而不是直接失败。
  • 预算检查必须是原子的:Budget 用 atomic.Int64 或 Context 内锁,避免并发分支各自判断都通过。
  • run.exhausted 仍要落最终 assistant 消息,内容为"已达执行上限,以下是已完成部分:……",让用户拿到部分结果而不是空白。

4.1.4 事件日志与重放

P0 落 JSONL(每行一个事件,按 run_id 分文件),零依赖、可 tail -f、可直接喂给 P7:

data/events/2026-10-30/01J9...jsonl
{"run_id":"01J9...","seq":1,"type":"run.started","payload":{"agent":"testAgent03","session":"..."}}
{"run_id":"01J9...","seq":2,"type":"step.started","payload":{"kind":"llm","name":"onlyAgent"}}

cmd/replay/main.go 的 P0 能力(P7 增强):

go run ./cmd/replay -run 01J9... -format timeline
# 输出:
# 000ms  run.started          agent=testAgent03
# 012ms  step.started         llm:onlyAgent
# 480ms  step.finished        llm:onlyAgent tokens=1204/86
# 481ms  step.started         tool:baidu_search
# 1203ms tool.retry           attempt=2 backoff=400ms reason=timeout
# 1650ms step.finished        tool:baidu_search ok
...

4.1.5 拆分 572 行巨石(机械搬迁,不改语义)

原 adk/adapter.go 的组成 新文件 说明
Agent 定义与构造(Agent、Factory) adk/agent.go、adk/factory.go 只留数据结构与构建
runWithVars / runLLM adk/executor_llm.go 改为实现 runtime.Executor
streamLLM adk/executor_llm_stream.go 同上,流式变体
executeToolCalls adk/tool_loop.go P1 在此挂网关
runSequential / runFanOut adk/executor_workflow.go P5 整体替换为图执行
applyVars / initialMessages adk/prompt.go P4 用装配器替换 initialMessages
Runner 与插件(myTestPlugin、myLogPlugin) adk/runner.go、adk/plugin.go 插件改用 zap + run 上下文

目标:adapter.go 保留为兼容壳 < 80 行(构造 Executor 注册表、把旧 Runner 接口适配到新 Runtime),P2 后再删除。

4.1.6 接口演进(破坏性,阶段内闭环)

// 旧:internal/domain/agent/model/command.go
type Runner interface {
    CreateSession(userID string) (string, error)
    Run(userID, sessionID string, content ChatContent) ([]string, error)
    Stream(userID, sessionID string, content ChatContent) (<-chan string, <-chan error)
}

// 新:internal/domain/runtime/ports.go
type Session struct { ID, TenantID, UserID, AgentID string }

type SubmitRequest struct {
    TenantID  string
    UserID    string
    AgentID   string
    SessionID string // 空则自动创建(幂等,P2 保证)
    Content   model.ChatContent
    IdempotencyKey string
}

type SubmitResult struct {
    RunID     string
    SessionID string
    Output    string
}

type Runner interface {
    Submit(ctx context.Context, req SubmitRequest) (SubmitResult, error)
    Stream(ctx context.Context, req SubmitRequest) (<-chan runtime.Event, error)
    GetRun(ctx context.Context, runID string) (*runtime.Run, error)
    Cancel(ctx context.Context, runID string) error
}

chat.Service 与 trigger/http 在同一阶段改为调用新接口,旧 Run/Stream 方法保留为 // Deprecated 适配层一个版本。

4.1.7 确定性装配

armory/service.go 的 AcceptArmoryAgents 改为:

func (s *Service) AcceptArmoryAgents(ctx context.Context, tables map[string]model.AiAgentConfigTable) error {
    names := make([]string, 0, len(tables))
    for name := range tables { names = append(names, name) }   // 入参是 map[string]table
    sort.Strings(names)                                        // 确定性:map 遍历顺序随机
    for _, name := range names {
        _, err := s.handler.Apply(ctx, model.ArmoryCommand{Table: tables[name]}, NewDynamicContext())
        if err != nil { return fmt.Errorf("apply agent table %q: %w", name, err) }
    }
    return nil
}

并对工作流按 (type, name) 排序,保证同一份配置每次装配出的链完全一致。

涉及的代码模块

类型 文件 改动要点
新增 internal/domain/runtime/run.go Run/Step/Status/Usage
新增 internal/domain/runtime/budget.go 预算与原子扣减
新增 internal/domain/runtime/event.go Event/EventType/EventSink
新增 internal/domain/runtime/executor.go Executor/Registry/Input/Output
新增 internal/domain/runtime/context.go Context/Scope/StepHandle
新增 internal/domain/runtime/errors.go Failure/ErrorClass(P1 复用)
新增 internal/domain/runtime/ids.go ULID 生成
新增 internal/domain/runtime/ports.go 新 Runner 接口
新增 internal/infrastructure/obs/eventstore_jsonl.go JSONL 追加写 + 按日分片
新增 cmd/replay/main.go timeline 重放
修改 internal/infrastructure/adk/adapter.go 拆分为 7 个文件(见 4.1.5)
修改 internal/domain/agent/model/command.go Runner 接口替换 + Deprecated 适配
修改 internal/domain/agent/service/chat/service.go 适配新 Runner,透传 ctx
修改 internal/trigger/http/agent_handler.go 改用新 Runner,修复 writeError(c,nil)
修改 internal/domain/agent/service/armory/service.go 确定性排序
修改 internal/app/bootstrap/bootstrap.go 注册 Executor、构造 Runtime、注入 EventStore
修改 internal/domain/agent/model/config.go 新增 RuntimeConfig(budget/events)
修改 internal/app/config/application.go 解析 runtime: 段
修改 cmd/server/main.go 传入可取消的 root ctx

配置变更(全部可选,有默认值)

runtime:
  enabled: true
  budget:
    max-steps: 24
    max-tool-calls: 16
    max-tokens: 200000
    max-wall-clock: 3m
  events:
    enabled: true
    dir: ./data/events
    retention-days: 14
    include-llm-deltas: false   # 生产默认关闭,避免日志膨胀

验收标准

  1. go build ./... 通过;adk/adapter.go ≤ 80 行且仅含兼容代码。
  2. 新增 internal/domain/runtime/*_test.go ≥ 12 用例,覆盖:预算耗尽、ctx 取消、Step 嵌套、事件顺序、并发分支预算正确。
  3. 同一输入运行两次,事件序列(剔除时间戳/ID)完全一致(确定性)。
  4. 客户端断开 SSE 后 ≤ 300ms 服务端取消,事件中出现 run.canceled,且不再发起新的工具调用。
  5. /api/v1/chat 对两个样例 Agent 的输出与改造前逐字节一致(golden test)。
  6. 启动日志显示 Agent 装配顺序与配置书写顺序无关(按名称排序)。
  7. go run ./cmd/replay -run <id> 能还原出完整 Step 时间线。

测试策略

  • 表驱动单测:fake ChatModel(返回预设 reply/tool_calls)+ fake ToolRouter,断言 Step 与 Usage。
  • 并发测试:go test -race 跑 100 个并发 Run,验证预算原子性。
  • 契约测试:录制改造前的 /chat 响应为 golden JSON,改造后 diff。
  • 取消测试:context.WithTimeout(50ms) 触发,断言错误链为 context.DeadlineExceeded 且 Run 状态正确。

风险与回滚

风险 缓解
接口破坏导致前端 500 兼容壳保留旧 Runner 实现一个版本;runtime.enabled=false 回退
预算过紧导致正常任务被截断 默认值按现有 draw-io 流程实测得出(~7 步),留 3 倍余量;支持 per-agent 覆盖
事件日志写盘拖慢主链路 异步 channel + 批量 flush(100 条/50ms),队列满则丢弃 llm.delta 类低价值事件并计数


附录:本阶段收编的缺陷(9 条)

编号 F-xx 是全局缺陷台账,索引见 README.md。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。

F-01 流式取消时 OpenAIClient.Stream goroutine 泄漏

位置:Stream in internal/infrastructure/ai/openai_client.go,尤其:

if delta.Content != "" {
    select {
    case events <- ports.ChatStreamEvent{Delta: delta.Content}:
    case <-ctx.Done():
        errs <- ctx.Err()
        return
    }
}
...
emitToolCalls(events, toolCallBuf)          // <- 无 ctx 保护,直接阻塞写入
events <- ports.ChatStreamEvent{Done: true} // <- 无 ctx 保护

问题概述:emitToolCalls 和最后的 Done 事件都是无保护的阻塞发送。当消费方(streamLLM)因 ctx.Done() 提前退出、不再读取 events 时,若 events 缓冲(8)已满,生产 goroutine 会永久阻塞在 events <- ...,导致 goroutine 泄漏。

影响:客户端频繁断开/取消时,泄漏的 goroutine 与底层 HTTP 连接会持续累积。

修复方案:给 emitToolCalls 传入 ctx 并用 select;对 [DONE] 分支的发送也加 select:

func emitToolCalls(ctx context.Context, events chan<- ports.ChatStreamEvent, buf map[int]*ports.ChatToolCall) {
    ...
    select {
    case events <- ports.ChatStreamEvent{ToolCalls: calls}:
    case <-ctx.Done():
    }
}

归属:P0 | 状态:🟡 | 历史编号:P0-6

P0 的 ctx 透传能收口;emitToolCalls 与 Done 的裸发送要补 select ctx.Done(),验收项为「取消后 goroutine 数回落」

F-02 HTTP 请求 context 未传递到 Agent

位置:Run in internal/infrastructure/adk/adapter.go Runner.Run、:429-453 Runner.Stream、:460-470 notifyPlugins(全部用 context.Background())

问题概述:Runner.Run/Stream/notifyPlugins 都丢弃了调用方 context,改用 context.Background()。

影响:客户端断开、请求超时都无法中断正在进行的 LLM/工具调用,资源被无效占用;application.yaml 的 llm.request-timeout 只能覆盖单次 HTTP,不能覆盖整个请求生命周期。

修复方案:Runner 接口签名增加 ctx context.Context(model.Runner),chat.Service 各方法也加 ctx,HTTP handler 传 c.Request.Context(),一路透传到 runLLM / executeToolCalls / notifyPlugins。

归属:P0 | 状态:✅ | 历史编号:P1-4

F-03 DynamicContext.agentGroup 名称覆盖与静默跳过

位置:AddAgent in internal/domain/agent/service/armory/context.go

问题概述:

  • agentGroup[agent.Name()] 同名覆盖,后注册的赢;
  • QueryAgentList 对不存在的名字静默跳过,可能构造出缺子 Agent 甚至空 workflow。

影响:配置错误被掩盖,运行时行为与预期不符。

修复方案:AddAgent 检测重名并报错(或在 loader 校验 Agent 唯一性);QueryAgentList 返回缺失的名称列表,由调用方决定是否报错。

归属:P0 | 状态:✅ | 历史编号:P2-2

P0 确定性装配 + P8 --strict-config 重名即报错

F-04 装配与加载顺序不确定

位置:AcceptArmoryAgents in internal/domain/agent/service/armory/service.go、LoadAgentTables in internal/app/config/loader.go、loadAgentTables in internal/app/bootstrap/bootstrap.go

问题概述:多处 for name, table := range tables,Go map 遍历顺序随机。

影响:多表装配顺序、注册顺序不稳定;对依赖注册顺序的扩展(如后注册覆盖前注册)会不确定。

修复方案:把 tables 改为按 name 排序后的切片再遍历,保证确定性。

归属:P0 | 状态:✅ | 历史编号:P2-3

F-05 Service 层方法无 context

位置:internal/domain/agent/service/chat/service.go 全部方法

问题概述:CreateSession、HandleMessage、HandleCommand、HandleMessageStream、HandleCommandStream 都不接收 context。

影响:无法实现超时/取消,与 F-02 同源。

修复方案:统一加 ctx context.Context 作为首参,并透传。

归属:P0 | 状态:✅ | 历史编号:P2-17

F-06 AgentFactory 为三种 workflow 各定义一个方法

为什么优化:新增 workflow 类型要同时改端口、实现、Armory 节点,扩展成本高。

方案:统一为 NewWorkflowAgent(ctx, workflowType, config, subAgents),由实现内部按 type 分派;或让 AgentFactory 只保留 NewLLMAgent + NewWorkflowAgent。

改动量:小-中(端口 + factory + 三个 node 文件)。

影响:扩展新 workflow 只需改一处;接口更内聚。

归属:P0 | 状态:✅ | 历史编号:P3-4

F-07 InMemoryAgentRegistry.Register 无校验且恒返回 nil

为什么优化:Register 声明返回 error 但永远 nil;空 AgentID 会互相覆盖到 ""。

方案:校验 AgentID 非空、重复注册报错(或显式允许覆盖)。

改动量:很小。

影响:装配期即可发现 Agent 配置问题。

归属:P0 | 状态:🟡 | 历史编号:P3-12

新 Runner 不再用旧 registry;旧 InMemoryAgentRegistry 保留一版并补校验

F-08 adkRunnerPlugin 是空壳,myLogPlugin 实际没有任何 ADK 日志能力

位置:Name in internal/infrastructure/adk/adapter.go

func (p adkRunnerPlugin) OnUserMessage(...) error {
	if p.plugin.OnUserMessageCallback() != nil {
		fmt.Printf("[%s] USER MESSAGE RECEIVED %s\n", p.name, firstText(content))
	}
	return nil
}

问题概述:代码只判断「ADK 回调是否非 nil」,然后打印自己的硬编码文案,从未真正调用 p.plugin.OnUserMessageCallback();BeforeAgent 同样。也就是说 loggingplugin.New("myLogPlugin") 创建出来的 ADK 插件除了被拿来做非 nil 判断外,没有任何实际作用。

影响:README/CLAUDE.md 宣称的插件生命周期(OnUserMessage / BeforeAgent)在 myLogPlugin 路径下是假的;用户配置了 myLogPlugin 却得不到 ADK 的日志输出,而且是 fmt.Printf 而非结构化日志。

修复方案:真正调用 ADK 回调(按其签名构造参数),或移除该包装;同时把输出改为注入的 *zap.Logger(与 F-40 合并处理)。

归属:P0 | 状态:🟡 | 历史编号:P1-13

P0 只做 plugin.go 的拆分搬迁,未重写插件语义;插件语义由 P7 的 run/step 事件取代

F-09 tool-calling 循环上限硬编码为 4 次

位置:maxToolCallIterations in internal/infrastructure/adk/adapter.go

问题概述:runLLM 的 tool-calling 循环上限是包级常量 4,既不进配置,也不进 Run 的预算,无法按 Agent 的复杂度调整;复杂任务在第 4 轮被强行截断且没有任何提示。

影响:需要多轮工具编排的 Agent(检索→读文件→计算→再检索)必然早退;且截断时模型不知道「为什么停」,会给出半截答案。

修复方案:并入 P0 的 runtime.Budget{MaxSteps,MaxToolCalls,...},由预算而非常量控制;耗尽时以 RunStatus=exhausted + run.exhausted 事件明确结束,并在最后一条系统提示里告知模型「已达到步数上限,请基于现有信息作答」。

归属:P0 | 状态:✅