docs: 阶段计划书拆分到 docs/upgrade-plan 并合并缺陷台账
- 方案第 4 章 P0-P8 拆为 9 份独立阶段计划书,原文件只保留索引与横切章节 - 《项目完善报告》《评审与收编清单》内容拆入各阶段计划书后删除 - 统一缺陷台账 F-01…F-76(历史 71 条 + 方案补充 5 条),保留历史编号对照 - 新增 README 作为路线图索引:阶段清单、执行顺序、第 0 天清扫、台账、迭代约定
This commit is contained in:
File diff suppressed because it is too large
Load Diff
572
docs/upgrade-plan/P0-运行时内核.md
Normal file
572
docs/upgrade-plan/P0-运行时内核.md
Normal file
@@ -0,0 +1,572 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](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`](P1-工具网关.md)
|
||||
|
||||
|
||||
# 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`
|
||||
|
||||
```go
|
||||
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 }
|
||||
```
|
||||
|
||||
```go
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
// 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)
|
||||
|
||||
现在的分派逻辑:
|
||||
|
||||
```go
|
||||
// 现状:(*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)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
改为:
|
||||
|
||||
```go
|
||||
// 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`):
|
||||
|
||||
```go
|
||||
// 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`):
|
||||
|
||||
```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 增强):
|
||||
|
||||
```bash
|
||||
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 接口演进(破坏性,阶段内闭环)
|
||||
|
||||
```go
|
||||
// 旧: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` 改为:
|
||||
|
||||
```go
|
||||
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 |
|
||||
|
||||
## 配置变更(全部可选,有默认值)
|
||||
|
||||
```yaml
|
||||
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`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-01 流式取消时 `OpenAIClient.Stream` goroutine 泄漏
|
||||
|
||||
**位置**:`Stream` in `internal/infrastructure/ai/openai_client.go`,尤其:
|
||||
|
||||
```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`:
|
||||
|
||||
```go
|
||||
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`
|
||||
|
||||
```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 | **状态**:✅
|
||||
682
docs/upgrade-plan/P1-工具网关.md
Normal file
682
docs/upgrade-plan/P1-工具网关.md
Normal file
@@ -0,0 +1,682 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P1 · 工具网关:把「能调通」变成「调不坏」 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.2 节
|
||||
> **本阶段收编缺陷**:F-10、F-11、F-12、F-13、F-14、F-15、F-16、F-17、F-18、F-19、F-20、F-21、F-22(共 13 条,明细见文末附录)
|
||||
> 上一阶段:[`P0`](P0-运行时内核.md) | 下一阶段:[`P2`](P2-会话持久化.md)
|
||||
|
||||
|
||||
# 4.2 P1 · 工具网关:把"能调通"变成"调不坏"
|
||||
|
||||
## 目标
|
||||
|
||||
工具调用从"一次 try-call,失败即整轮失败"升级为**带 schema 校验、超时、指数退避、熔断、分级降级**的网关。这是面试官 A 第一个追问点("模型调工具报错、参数不符合 schema、下游超时,代码怎么做异常处理")的直接答案。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 证据 | 问题 |
|
||||
|---|---|
|
||||
| `encodeTools` in `internal/infrastructure/ai/openai_client.go` | 所有工具只暴露一个 `query` 字符串参数,模型无法填结构化参数,也没有可校验的 schema(F-15) |
|
||||
| `(*MCPSSEClient).ListTools` in `internal/infrastructure/ai/mcp_sse_client.go` | `tools/list` 只取 name,丢弃 `description`/`inputSchema`(F-10) |
|
||||
| `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go` | 任一工具失败 `return nil, err`,整轮终止(F-21) |
|
||||
| `tools.go` `normalizeTimeout` | 默认 300s,无单工具超时控制(F-22) |
|
||||
| `(*MCPSSEClient).callRPC` in `internal/infrastructure/ai/mcp_sse_client.go` | `pending` map 泄漏(F-11) |
|
||||
| `MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go` | Router 无锁(F-16) |
|
||||
| `ai/tools.go` 的 `SkillTool` | Skill 注册成工具但没有 `Invoke`,调用即空转;本阶段改为只注入 instruction(见 4.2.8) |
|
||||
| 全局 | 无重试、无熔断、无幂等、无结果大小限制 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.2.1 `ToolSpec`:工具的完整契约
|
||||
|
||||
```go
|
||||
// internal/domain/tool/spec.go
|
||||
package tool
|
||||
|
||||
type SideEffect string
|
||||
|
||||
const (
|
||||
EffectRead SideEffect = "read" // 可随意重试
|
||||
EffectWrite SideEffect = "write" // 重试需幂等键
|
||||
EffectDestructive SideEffect = "destructive" // 默认需人工确认
|
||||
EffectExternal SideEffect = "external" // 外发(邮件/Webhook)
|
||||
)
|
||||
|
||||
type Spec struct {
|
||||
Name string // 全局唯一,`server.tool` 命名空间
|
||||
Title string
|
||||
Description string // 必填,模型靠它选工具
|
||||
InputSchema json.RawMessage // JSON Schema 2020-12,来自 MCP tools/list
|
||||
OutputSchema json.RawMessage // 可选,有则校验
|
||||
SideEffect SideEffect
|
||||
Timeout time.Duration // 默认 30s
|
||||
Retry RetryPolicy
|
||||
Idempotency IdempotencyMode // none | key | natural
|
||||
Result ResultPolicy // 截断/摘要
|
||||
Approval ApprovalPolicy // P6 使用,P1 仅占位
|
||||
Visibility Visibility // model | human_only(P6 使用)
|
||||
Version string // 工具契约版本,用于缓存与审计
|
||||
}
|
||||
|
||||
type RetryPolicy struct {
|
||||
MaxAttempts int // 默认 3(含首次)
|
||||
BaseDelay time.Duration // 200ms
|
||||
MaxDelay time.Duration // 5s
|
||||
Multiplier float64 // 2.0
|
||||
Jitter float64 // 0.2,full jitter
|
||||
RetryOn []ErrorClass // 默认 transient/rate_limited/timeout
|
||||
}
|
||||
|
||||
type ResultPolicy struct {
|
||||
MaxBytes int // 默认 32768
|
||||
MaxLines int // 默认 2000
|
||||
Strategy string // truncate | head_tail | summarize(P7)
|
||||
}
|
||||
```
|
||||
|
||||
### 4.2.2 错误分类(重试与降级的前提)
|
||||
|
||||
统一 `Failure` 结构,贯穿 P0 运行时、P1 工具、P5 工作流:
|
||||
|
||||
```go
|
||||
// internal/domain/runtime/errors.go
|
||||
type ErrorClass string
|
||||
|
||||
const (
|
||||
ErrTransient ErrorClass = "transient" // 网络抖动、连接重置
|
||||
ErrRateLimited ErrorClass = "rate_limited" // 429 / 限流
|
||||
ErrTimeout ErrorClass = "timeout" // 单工具超时
|
||||
ErrInvalidInput ErrorClass = "invalid_input" // 参数不符合 schema
|
||||
ErrNotFound ErrorClass = "not_found" // 资源不存在
|
||||
ErrPermission ErrorClass = "permission" // 鉴权/策略拒绝
|
||||
ErrUpstream ErrorClass = "upstream" // 下游 4xx(非 429)
|
||||
ErrSchema ErrorClass = "schema" // 返回结果不符合 OutputSchema
|
||||
ErrInternal ErrorClass = "internal" // 本地 bug
|
||||
)
|
||||
|
||||
type Failure struct {
|
||||
Class ErrorClass
|
||||
Code string // TOOL_TIMEOUT / TOOL_SCHEMA_INVALID / ...
|
||||
Message string
|
||||
ToolName string
|
||||
Attempt int
|
||||
Retryable bool
|
||||
Cause error
|
||||
}
|
||||
```
|
||||
|
||||
| 错误类 | 典型来源 | 可重试 | 默认降级动作 |
|
||||
|---|---|---|---|
|
||||
| `transient` | 连接重置、EOF | ✅ | 指数退避重试 |
|
||||
| `rate_limited` | 429 | ✅(尊重 `Retry-After`) | 退避 + 限流排队 |
|
||||
| `timeout` | 单工具 deadline | ✅ | 重试 1 次后换备用工具 |
|
||||
| `invalid_input` | schema 校验失败 | ❌(但可让模型修参) | 回灌错误给模型修复重试 1 次 |
|
||||
| `not_found` | 404 / 空结果 | ❌ | 走备用工具 |
|
||||
| `permission` | 策略拒绝/401/403 | ❌ | 直接终止该工具,转人工或拒绝 |
|
||||
| `upstream` | 下游 400/500 非临时 | ⚠️ 仅 5xx | 熔断计数 |
|
||||
| `schema` | 返回体不符 OutputSchema | ❌ | 保留原始结果 + 标记 `_validation_warning` |
|
||||
| `internal` | 本地 panic/序列化 | ❌ | 终止该工具并告警 |
|
||||
|
||||
### 4.2.3 网关流水线(12 步,顺序即设计)
|
||||
|
||||
```
|
||||
调用请求
|
||||
│
|
||||
1. Resolve 查注册表,取 Spec;未注册 → not_found(不再"静默失败")
|
||||
2. Visibility 模型可见性检查(P6 生效,P1 恒 true)
|
||||
3. ValidateArgs 按 InputSchema 校验 + 轻量类型纠正("5"→5)
|
||||
4. SizeGuard 参数体积上限(默认 64KB)
|
||||
5. Approval 需人工确认 → 挂起 Run(P6)
|
||||
6. Breaker 熔断器状态检查(open → 直接走降级 L4)
|
||||
7. RateLimit 每工具/每租户令牌桶
|
||||
8. Invoke 带 per-call timeout 执行(ctx 派生)
|
||||
9. ValidateResult 有 OutputSchema 则校验
|
||||
10. Normalize 截断/head-tail/合并多段文本
|
||||
11. Classify 错误归类为 Failure
|
||||
12. Retry/Degrade 退避重试 → 降级阶梯
|
||||
│
|
||||
调用结果(永不 panic,永不静默丢错)
|
||||
```
|
||||
|
||||
```go
|
||||
// internal/domain/tool/gateway.go
|
||||
type Invocation struct {
|
||||
RunID string
|
||||
SessionID string
|
||||
TenantID string
|
||||
UserID string
|
||||
ToolName string
|
||||
Args json.RawMessage
|
||||
IdempotencyKey string // sha256(run_id + tool + args)
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Content string // 归一化后的文本,喂给模型的就是它
|
||||
Raw json.RawMessage // 原始返回,落审计
|
||||
Degraded bool // 是否走过降级阶梯(L4/L5)
|
||||
Attempts int
|
||||
}
|
||||
|
||||
type Gateway interface {
|
||||
// Invoke 是模型工具调用的唯一出口:失败已归类为 Failure 并走完降级阶梯。
|
||||
Invoke(ctx context.Context, inv Invocation) (Result, error)
|
||||
// Specs 返回当前可见的工具集(P1 返回全部,P6 按 Subject 过滤)。
|
||||
Specs(ctx context.Context) []Spec
|
||||
}
|
||||
```
|
||||
|
||||
`adk/tool_loop.go` 改造后不再直接调 `router.CallTool`,而是 `gw.Invoke(...)`——这是"所有工具来源收敛到一个出口"的落地形态。
|
||||
|
||||
```go
|
||||
// internal/domain/tool/registry.go
|
||||
type Registration struct {
|
||||
Spec Spec
|
||||
Invoker func(ctx context.Context, args json.RawMessage) (string, error)
|
||||
}
|
||||
|
||||
type Registry interface {
|
||||
Register(reg Registration) error // 同名返回 ErrDuplicateTool,不再静默成功
|
||||
Get(name string) (Registration, bool)
|
||||
List() []Spec
|
||||
}
|
||||
```
|
||||
|
||||
三种工具来源(MCP / Skill / 内置 Go 函数)都只需产出 `Registration`,`Gateway` 不关心它从哪来。
|
||||
|
||||
|
||||
### 4.2.4 重试算法(面试可讲的细节)
|
||||
|
||||
```go
|
||||
func backoff(p RetryPolicy, attempt int, retryAfter time.Duration) time.Duration {
|
||||
if retryAfter > 0 { return min(retryAfter, p.MaxDelay) } // 尊重服务端
|
||||
d := float64(p.BaseDelay) * math.Pow(p.Multiplier, float64(attempt-1))
|
||||
if d > float64(p.MaxDelay) { d = float64(p.MaxDelay) }
|
||||
// full jitter:避免重试风暴同步
|
||||
return time.Duration(rand.Float64() * d * (1 + p.Jitter))
|
||||
}
|
||||
```
|
||||
|
||||
三条容易漏的工程细节:
|
||||
|
||||
1. **只对幂等操作重试**:`EffectRead` 直接重试;`EffectWrite` 必须带幂等键(`run_id + tool + sha256(args)`,Redis 存 24h),重放时返回缓存结果而不是再执行一次。
|
||||
2. **重试要计入 Step 的 `Attempt` 与事件**(`tool.retry`),否则线上无法判断"慢"是网络还是下游。
|
||||
3. **总耗时要受 Run 预算约束**:`attempt` 循环内每轮检查 `rc.Deadline()`,避免重试把 3 分钟预算吃光。
|
||||
|
||||
### 4.2.5 降级阶梯(L0–L6)
|
||||
|
||||
| 级别 | 动作 | 触发 | 用户感知 |
|
||||
|---|---|---|---|
|
||||
| L0 | **参数自愈**:把校验错误作为 tool 结果回灌,让模型改参重试(限 1 次) | `invalid_input` | 无感,多 1 次 LLM 调用 |
|
||||
| L1 | **退避重试** | `transient`/`rate_limited`/`timeout` | 无感,延迟增加 |
|
||||
| L2 | **熔断短路** | 滑动窗口 10 次失败 ≥5 | 立即失败,不再排队 |
|
||||
| L3 | **备用工具**(`fallback: [search_backup]`) | L1 耗尽 / `not_found` | 结果来源变化,需在结果里标注 |
|
||||
| L4 | **陈旧/缓存结果**(read-only,`stale-while-error`) | 熔断开 + 有缓存 | 结果标注 `stale: true` |
|
||||
| L5 | **结构化降级**:返回 `{"status":"unavailable","reason":"..."}` 给模型 | 以上皆失败 | 模型自行改计划(例如换关键词/跳过) |
|
||||
| L6 | **人工兜底**:写类/外发类不可降级 → 转审批队列,Run 挂起 | `permission` 或 `destructive` 失败 | 提示"已转人工处理" |
|
||||
|
||||
**关键决策**:L5 之后 **run 不失败**,只有预算耗尽或显式致命错误才失败。这是"异常收敛"的核心——把工具故障转化为模型的输入,而不是系统的异常。
|
||||
|
||||
### 4.2.6 MCP schema 透传(修复 F-10)
|
||||
|
||||
```go
|
||||
// ai/mcp_sse_client.go 改造
|
||||
type ServerTool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema json.RawMessage `json:"inputSchema"`
|
||||
Annotations struct {
|
||||
SideEffect string `json:"sideEffectHint"` // 非标准字段,可选
|
||||
} `json:"annotations"`
|
||||
}
|
||||
|
||||
func (c *MCPSSEClient) ListTools(ctx context.Context) ([]ServerTool, error)
|
||||
```
|
||||
|
||||
`RegisterAndExpand` 改用 `[]ServerTool`,注册为 `tool.Registration{Spec, Invoker}`;同名冲突返回错误而非 `nil`(修复 F-13);`pending` map 在 defer 中删除(修复 F-11);`MCPToolRouter` 加 `sync.RWMutex`(修复 F-16)。
|
||||
|
||||
同时修复 `encodeTools`:
|
||||
|
||||
```go
|
||||
// 现状:encodeTools in internal/infrastructure/ai/openai_client.go 让所有工具共用 {query: string}
|
||||
// 改为:
|
||||
func encodeTools(specs []tool.Spec) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(specs))
|
||||
for _, s := range specs {
|
||||
schema := s.InputSchema
|
||||
if len(schema) == 0 {
|
||||
schema = json.RawMessage(`{"type":"object","properties":{},"additionalProperties":false}`)
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": s.Name,
|
||||
"description": s.Description,
|
||||
"parameters": schema,
|
||||
"strict": true, // OpenAI 结构化输出约束
|
||||
},
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
```
|
||||
|
||||
### 4.2.7 结果校验与规整
|
||||
|
||||
- 有 `OutputSchema` 且校验失败:**不丢弃结果**,保留原文并在 tool 消息上加 `{"_validation_warning": "..."}`,同时发 `tool.result` 事件带 `valid=false`。理由:线上工具常返回"多一个字段/少一个字段",直接判失败比容错更伤可用性。
|
||||
- 截断策略:`head_tail`(保留前 24KB + 后 8KB,中间标注省略字节数),对日志/HTML 类结果体验最好。
|
||||
- 大结果**标记为"可摘要"**:P7 接 LLM 摘要,P1 先只截断。
|
||||
|
||||
### 4.2.8 Skill 的定位:本阶段只做 instruction 注入(已决策)
|
||||
|
||||
**决策**:P1 阶段 `SKILL.md` 只作为**提示词侧的能力包**注入 system instruction,不注册为 function tool。"Skill 可被调用"这件事延后到 P6 沙箱就绪之后。
|
||||
|
||||
三条理由:
|
||||
|
||||
1. **Skill 的产物是方法论,不是函数**。`SKILL.md` 给的是步骤、判据与参考文档,没有稳定的输入/输出契约。当前 `SkillTool` 只暴露一个自由文本 `query`,模型"调用"它等于请求一段说明,却要付一次模型往返和一次工具调用预算——收益低于直接把正文放进上下文。
|
||||
2. **现在根本没有执行面**。`SkillTool` 没有 `Invoke`,脚本与附件无人执行。把"看起来能调、实际调不出东西"的工具注册给模型,正是缺陷 F-14 指出的功能谎言;先删暴露面,才是诚实的降级。
|
||||
3. **可调用 Skill 必须先有沙箱**。真正的 Skill 要跑脚本(生成 drawio、转 PDF、执行分析),只能落在 P6 的 `sandbox.Runner` 里。在沙箱之前实现,只能是宿主机 `exec.Command`——正好是 P6 要消除的风险面。
|
||||
|
||||
**P1 的落地方式**:
|
||||
|
||||
| 动作 | 位置 | 说明 |
|
||||
|---|---|---|
|
||||
| 新增端口 | `internal/domain/skill/loader.go` | `Loader{Load(name string) (Skill, error)}`;`Skill{Name, Description, Instruction, Resources, Scripts}` |
|
||||
| 新增适配器 | `internal/infrastructure/skill/fs_loader.go` | 读 `SKILL.md`(YAML front matter + 正文),解析 `scripts/`、`resources/` |
|
||||
| 修改装配 | `armory/agent_node.go` | 构造 instruction 时把选中 Skill 的正文追加到 system prompt,带 `## 技能:<name>` 分隔标题 |
|
||||
| 修改语义 | `ChatModelConfig.ToolSkillsList` | 字段名不变,含义从"注册成工具"改为"注入为技能";行为变更需 release note + 开关 `skills.mode: inject|expose`,默认 `inject` |
|
||||
| 保留不暴露 | `ai/tools.go` 的 `SkillTool` | 保留类型但**不注册**到模型可见工具集,`Visibility: human_only` 占位,`Invoke` 留给 P6 |
|
||||
|
||||
注入的正文计入 P4 的 token 预算(单个 Skill 正文建议 ≤ 4k token,超出截断并告警);同一 Skill 在一次 Run 内只注入一次,避免重复占用预算。
|
||||
|
||||
**P6 的升级路径(本阶段只预留接口)**:
|
||||
|
||||
```go
|
||||
// internal/domain/skill/exec.go(P6 引入)
|
||||
type Runner interface {
|
||||
Run(ctx context.Context, skill Skill, script string, args []string) (Result, error)
|
||||
}
|
||||
```
|
||||
|
||||
`SKILL.md` 增加可选 front matter `scripts: [{name, entry, timeout}]`;P6 把每个 script 包装成 `tool.Spec{Name: "skill.<skill>.<script>"}` 走同一个 Gateway,执行体是 `sandbox.Runner`。这样"所有工具来源统一收敛到 `tool.Spec`"的架构目标在 P6 闭环,而不需要 P1 先造半成品。
|
||||
|
||||
**回滚**:`skills.mode=expose` 时恢复旧行为(把 Skill 注册为工具),用于对比与紧急回退;P6 完成后移除该开关。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/tool/spec.go` | Spec/RetryPolicy/ResultPolicy |
|
||||
| 新增 | `internal/domain/tool/gateway.go` | Gateway 接口 + 12 步流水线编排 |
|
||||
| 新增 | `internal/domain/tool/registry.go` | 注册表、命名空间、版本 |
|
||||
| 新增 | `internal/domain/tool/errors.go` | 错误归类(`Classify`) |
|
||||
| 新增 | `internal/domain/tool/ports.go` | Invoker/Result/SchemaValidator |
|
||||
| 新增 | `internal/infrastructure/tool/schema.go` | JSON Schema 校验(`santhosh-tekuri/jsonschema/v6`) |
|
||||
| 新增 | `internal/infrastructure/tool/retry.go` | backoff + 幂等键 |
|
||||
| 新增 | `internal/infrastructure/tool/breaker.go` | 滑动窗口熔断 |
|
||||
| 新增 | `internal/infrastructure/tool/ratelimit.go` | 令牌桶(本地 + Redis) |
|
||||
| 新增 | `internal/infrastructure/tool/degrade.go` | 降级阶梯 L3–L5 |
|
||||
| 新增 | `internal/infrastructure/tool/truncate.go` | head_tail 截断 |
|
||||
| 新增 | `internal/infrastructure/tool/mcp_adapter.go` | MCP ServerTool → Spec |
|
||||
| 修改 | `internal/infrastructure/ai/mcp_sse_client.go` | schema 透传、pending 泄漏、加锁、错误而非 nil |
|
||||
| 修改 | `internal/infrastructure/ai/tools.go` | `SkillTool` 不注册为 function tool(见 4.2.8);新增 `SkillSpec` 描述;stdio/local 注册 Spec |
|
||||
| 新增 | `internal/domain/skill/loader.go`、`internal/infrastructure/skill/fs_loader.go` | Skill 加载与 instruction 注入 |
|
||||
| 修改 | `internal/infrastructure/ai/openai_client.go` | `encodeTools` 用真实 schema |
|
||||
| 修改 | `internal/infrastructure/ai/eino_adapter.go` | `toolDefs` 改为从 Registry 取 Spec |
|
||||
| 修改 | `internal/infrastructure/adk/tool_loop.go` | 失败不再中断 run,改为 tool 消息 `is_error` |
|
||||
| 修改 | `internal/domain/agent/model/config.go` | Tool 配置扩展(timeout/retry/fallback/effect) |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Registry + Gateway |
|
||||
| 修改 | `configs/agent/*.yaml` | 显式声明工具策略(示例见下) |
|
||||
|
||||
## 配置示例
|
||||
|
||||
```yaml
|
||||
# configs/application.yaml 新增
|
||||
tool-defaults:
|
||||
timeout: 30s
|
||||
retry:
|
||||
max-attempts: 3
|
||||
base-delay: 200ms
|
||||
max-delay: 5s
|
||||
multiplier: 2
|
||||
jitter: 0.2
|
||||
result:
|
||||
max-bytes: 32768
|
||||
strategy: head_tail
|
||||
circuit-breaker:
|
||||
window: 10
|
||||
failure-threshold: 5
|
||||
open-for: 30s
|
||||
|
||||
# configs/agent/xxx.yaml 单个工具覆盖
|
||||
tools:
|
||||
- name: baidu-search.search
|
||||
timeout: 8s
|
||||
effect: read
|
||||
fallback: [echoLocalTool]
|
||||
retry: {max-attempts: 2}
|
||||
- name: crm.updateOrder
|
||||
effect: write
|
||||
idempotency: key
|
||||
approval: required # P6 生效
|
||||
```
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **故障注入测试集 ≥ 15 个场景**(超时、429、5xx、连接重置、坏 JSON、schema 不符、空结果、超大结果、重复注册、并发注册),全部断言:run **不失败**、错误被归类、降级动作符合预期。
|
||||
2. 失败注入 30% 时,任务成功率从当前 ~70% 提升到 **≥ 95%**(同一评测集)。
|
||||
3. 重试间隔符合退避公式(测试用 mock clock,断言 200/400/800ms ± jitter)。
|
||||
4. 写类工具重放同一幂等键,实际执行次数 = 1。
|
||||
5. 熔断:连续 5 次失败后 30s 内直接快速失败(P99 延迟从 30s 降到 < 5ms)。
|
||||
6. 工具描述与 schema 100% 透传到模型(抓包断言 `parameters.properties` 非空)。
|
||||
7. `go test -race` 通过,Router 无 data race。
|
||||
8. **Skill 只注入不暴露**:抓包断言 `tools` 数组不含 `skill_*`;system prompt 含 `SKILL.md` 正文与 `## 技能:` 标题;`skills.mode=expose` 时回到旧行为(回滚开关可用)。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- `internal/infrastructure/tool/testdata/` 下用 `httptest` 起**可编程 SSE MCP Server**(按脚本返回失败/延迟/坏 schema)。
|
||||
- 单测覆盖:`backoff` 表驱动、`Classify` 表驱动、截断边界(0B/32KB/1MB)、幂等键碰撞。
|
||||
- 集成测试:真实 MCP(baidu-search)跑 10 次,记录成功率与 p95。
|
||||
- 混沌:在 CI 中把注入概率设为 0.3 跑评测集,失败则阻断合并。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 真实 MCP 返回的 schema 不规范(draft-04/缺 type) | 校验前做 schema 归一化;校验失败按 `schema` 类处理并降级,不阻断 |
|
||||
| 重试放大下游压力 | 默认仅 3 次 + 全抖动;熔断 + 令牌桶双限流 |
|
||||
| 参数"自愈"让模型陷入改参循环 | 硬限 1 次,且计入 Run 的 tool 预算 |
|
||||
| 引入 JSON Schema 库增大体积 | `santhosh-tekuri/jsonschema/v6` 无第三方依赖,约 400KB |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(13 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-10 工具描述全部丢失,模型只能看到兜底描述
|
||||
|
||||
**位置**:
|
||||
|
||||
- 接口定义:`ToolDescriptor` in `internal/domain/agent/ports/ports.go`
|
||||
- 消费方:`toolDefs` in `internal/infrastructure/ai/eino_adapter.go` `toolDefs()`
|
||||
- 工具实现:`internal/infrastructure/ai/tools.go`(`MCPTool`、`SkillTool`)、`eino_adapter.go`(`EinoTool`)
|
||||
|
||||
**问题概述**:`toolDefs()` 里用 `tool.(ports.ToolDescriptor)` 取描述,但**项目中没有任何类型实现了 `Description() string`**:
|
||||
|
||||
```go
|
||||
desc := ""
|
||||
if d, ok := tool.(ports.ToolDescriptor); ok {
|
||||
desc = d.Description() // 永远走不到
|
||||
}
|
||||
defs = append(defs, OpenAIToolDef{Name: tool.Name(), Description: desc})
|
||||
```
|
||||
|
||||
`SkillTool` 虽然有 `Description` 字段,但没有 `Description()` 方法;`MCPTool` 和 `EinoTool` 连字段都没有。结果所有工具描述都是空,`fallbackDescription` 统一返回「外部工具 X,参数 query 为自由文本」。
|
||||
|
||||
**影响**:模型无法区分各工具用途(比如百度搜索、drawio 绘图工具都被描述成同样的自由文本),工具选择准确率显著下降,而这是当前 demo 场景(多工具 + 多 Agent)的核心体验问题。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- 给 `SkillTool` 加 `func (t SkillTool) Description() string { return t.Description }`。
|
||||
- 给 `EinoTool` 增加 `Description` 字段并实现方法;在 `MCPToolRouter.RegisterAndExpand` 从 `tools/list` 的 `description` 填充。
|
||||
- 给 `MCPTool` 实现 `Description()` 并保存 SSE 配置里的描述。
|
||||
- 保留 `eino_adapter.go` 的类型断言,同时提供统一的描述访问方式,避免以后再漏。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-3
|
||||
|
||||
### F-11 MCP `pending` map 在超时/提前返回路径泄漏
|
||||
|
||||
**位置**:`callRPC` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
```go
|
||||
c.mu.Lock()
|
||||
postURL := c.postURL
|
||||
c.pending[id] = ch
|
||||
c.mu.Unlock()
|
||||
if postURL == "" {
|
||||
return nil, fmt.Errorf("mcp post url is not set") // <- 未删除 pending[id]
|
||||
}
|
||||
...
|
||||
select {
|
||||
case msg, ok := <-ch:
|
||||
...
|
||||
case <-waitCtx.Done():
|
||||
return nil, fmt.Errorf("mcp call %s timeout: %w", method, waitCtx.Err()) // <- 未删除 pending[id]
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:`pending[id]` 在注册后,只有在 `handleMessage` 收到响应或 `signalStreamErr` 广播时才会被删除。超时、`postURL` 为空等提前返回路径都不会清理。
|
||||
|
||||
**影响**:MCP Server 慢/挂掉时,每次超时都会在 `pending` 里留下一个带缓冲 channel,长跑进程持续占用内存,属于慢性内存泄漏。残留条目还会让 `signalStreamErr` 在断线时向已无人等待的 channel 写入。
|
||||
|
||||
**修复方案**:在 `callRPC` 内用 `defer` 清理:
|
||||
|
||||
```go
|
||||
c.mu.Lock()
|
||||
c.pending[id] = ch
|
||||
c.mu.Unlock()
|
||||
defer func() {
|
||||
c.mu.Lock()
|
||||
delete(c.pending, id)
|
||||
c.mu.Unlock()
|
||||
}()
|
||||
```
|
||||
|
||||
注意避免重复关闭 channel;推荐让「所有权持有者」关闭,或用 `sync.Once`。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-4
|
||||
|
||||
### F-12 `ensureStarted` 并发首次调用会失败
|
||||
|
||||
**位置**:`ensureStarted` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
```go
|
||||
c.mu.Lock()
|
||||
if c.started { // goroutine B 看到 true
|
||||
c.mu.Unlock()
|
||||
return nil // <- B 直接返回成功
|
||||
}
|
||||
...
|
||||
c.started = true // A 先标记,再在锁外做耗时连接
|
||||
c.mu.Unlock() // <- B 此刻可能已经进入 callRPC
|
||||
```
|
||||
|
||||
**问题概述**:第一个调用者(A)在锁内置 `started = true` 后释放锁,然后在锁外做 `openSSE`、等待 `endpoint`、`initialize`(可能数百毫秒到数秒)。此时第二个并发调用者(B)会看到 `started == true` 而直接返回 nil,随后 B 进入 `callRPC` 时 `postURL` 仍为空,报 `mcp post url is not set`。
|
||||
|
||||
**影响**:并发首次调用工具(如 parallel workflow 同时触发工具,或第一个请求尚未完成时的第二个请求)会随机失败。当前 demo 不易触发,但一旦上线就是间歇性报错。
|
||||
|
||||
**修复方案**:把「标记」与「完成」分开,使用 `sync.Once` + 初始化结果,或引入 `started`/`ready` 两个状态 + `sync.Cond`,让并发调用者等待初始化完成或拿到同一个初始化错误。
|
||||
|
||||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P0-5
|
||||
>
|
||||
> P1 先修并发正确性(`sync.Once` 或双状态),P6 的 MCP 生命周期重构会重写这段
|
||||
|
||||
### F-13 重复注册 MCP SSE 工具导致第二张表拿到不可调用占位工具
|
||||
|
||||
**位置**:`RegisterAndExpand` in `internal/infrastructure/ai/mcp_sse_client.go` 与 `BuildTools` in `internal/infrastructure/ai/tools.go`
|
||||
|
||||
```go
|
||||
if _, exists := r.clients[mcp.ToolName]; exists {
|
||||
return nil // <- 第二次注册直接返回 nil
|
||||
}
|
||||
```
|
||||
|
||||
`BuildTools` 里:
|
||||
|
||||
```go
|
||||
ts := f.router.RegisterAndExpand(t)
|
||||
if len(ts) == 0 { continue } // 展开为空 -> 被跳过
|
||||
...
|
||||
if len(expanded) > 0 { return expanded, nil }
|
||||
return tools, nil // <- 回退成原始 MCPTool 占位符
|
||||
```
|
||||
|
||||
**问题概述**:`MCPToolRouter` 在 `bootstrap.Build` 中是全局单例。当前两个示例表都配置了同名 `baidu-search` SSE 工具。第二张表注册时命中 `exists` 分支返回 nil,`BuildTools` 的 `expanded` 为空,于是回退返回原始 `MCPTool{ToolName:"baidu-search"}`(不是 `tools/list` 发现的真实工具)。
|
||||
|
||||
**影响**:第二张表拿到的是配置名 `baidu-search` 这个占位工具,而不是 `tools/list` 发现的真实工具名。由于 `CallTool` 会先查 `r.clients[name]`(第 565 行),而 `baidu-search` 恰好在第一张表注册时已写入 `clients`,所以调用不会走 `case MCPTool:` 分支,而是被转发成 `tools/call {name:"baidu-search"}`——但 `baidu-search` 只是「服务端标签」,不是 MCP Server 上真实存在的工具名,服务端会返回「工具不存在」,最终表现为「Agent 一调工具就报错」。注意:这与 F-37 的 stdio/local「transport not supported」是两条不同的错误路径。
|
||||
|
||||
**修复方案**(任一):
|
||||
|
||||
1. `RegisterAndExpand` 命中已存在时,返回该 client 已展开的真实工具列表(需要缓存 `expandedByServer`)。
|
||||
2. `BuildTools` 在 `len(ts) == 0` 时不要静默跳过,而是报错提示「工具已被注册」。
|
||||
3. 更彻底:把 MCP client 的复用键改为 `baseURI+endpoint`,工具名到 client 的映射独立维护。
|
||||
|
||||
推荐方案 1 或 3,并为「多表共享同名 MCP」补测试。
|
||||
|
||||
---
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-9
|
||||
>
|
||||
> 同名注册命中即返回错误;P6 用 `server.tool` 命名空间彻底隔离
|
||||
|
||||
### F-14 Skill 工具只暴露、不可执行
|
||||
|
||||
**位置**:`internal/infrastructure/ai/tools.go`(`SkillFactory`)、`CallTool` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
**问题概述**:Skill 被解析为 `SkillTool`(实现了 `ports.Tool`),会作为 function 暴露给模型;但它没有注册到 `MCPToolRouter` 的 `clients` map 中,运行时 `CallTool` 找不到客户端,返回 `tool %q is not callable in current runtime`。
|
||||
|
||||
**影响**:模型一旦选择 skill 工具就必然失败,用户侧看到「工具调用报错」。当前两个示例 skill(battle-plan、pdf)实际都不可用。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- 明确 Skill 的执行语义:要么实现本地执行器(按 `SKILL.md` 指令执行脚本/读取文档),要么在装配阶段就不要把 Skill 暴露为 function。
|
||||
- 短期最稳:把 Skill 从 tool 列表移除,改为注入 instruction 上下文;长期:新增 `SkillToolExecutor` 注册到 `ToolRouter`。
|
||||
- 无论选哪种,都应消除「暴露但不可执行」的不一致状态。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-1
|
||||
>
|
||||
> 2026-11-02 决策:P1 只注入 instruction(4.2.8),P6 沙箱就绪后再做成可调用工具
|
||||
|
||||
### F-15 工具参数 schema 硬编码为 `query`
|
||||
|
||||
**位置**:`encodeTools` in `internal/infrastructure/ai/openai_client.go`
|
||||
|
||||
**问题概述**:所有工具的参数 schema 都被写成单一 `query: string`:
|
||||
|
||||
```go
|
||||
"parameters": map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"query": map[string]any{"type": "string", ...},
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
但真实 MCP 工具的 `inputSchema` 各异(百度搜索可能要求 `query`,其他工具可能是别的字段)。
|
||||
|
||||
**影响**:模型按 schema 生成的参数可能与 MCP Server 期望不符,工具调用失败;同时丢失了 MCP `tools/list` 返回的真实 schema。
|
||||
|
||||
**修复方案**:`MCPToolRouter.RegisterAndExpand` 在 `tools/list` 时同时保留 `inputSchema`;`EinoChatModel.toolDefs` 传递完整 schema;`encodeTools` 直接使用它。若暂时拿不到 schema,至少保留参数名与描述。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-9
|
||||
|
||||
### F-16 `MCPToolRouter` 无锁
|
||||
|
||||
**位置**:`MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
**问题概述**:`clients` / `tools` / `registered` / `listFailures` 都是普通 map,没有任何互斥保护。当前写入只发生在启动阶段(单 goroutine),运行时只读,勉强安全;但一旦支持热更新、延迟注册或并发 `BuildTools`,就是数据竞争。
|
||||
|
||||
**影响**:潜在 `fatal error: concurrent map read and map write`,进程直接崩溃。
|
||||
|
||||
**修复方案**:给 `MCPToolRouter` 加 `sync.RWMutex`,所有读写走锁;`CallTool` 读路径用 RLock。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P2-10
|
||||
|
||||
### F-17 MCP 启动期工具发现失败时,会把「服务端标签」当工具暴露给模型且不告警
|
||||
|
||||
**位置**:`RegisterAndExpand` in `internal/infrastructure/ai/mcp_sse_client.go`、`BuildTools` in `internal/infrastructure/ai/tools.go`
|
||||
|
||||
```go
|
||||
names, err := client.ListTools(ctx)
|
||||
if err != nil {
|
||||
r.listFailures[mcp.ToolName] = err // 只记录,从不读取、从不告警
|
||||
r.tools = append(r.tools, mcp) // 把配置名当工具塞回去
|
||||
return []ports.Tool{mcp}
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:MCP Server 启动时不可达/超时(或如 F-13 的重复注册)时,`BuildTools` 会把 `MCPTool{ToolName:"baidu-search"}` 作为「工具」返回给 ChatModel。模型看到一个名为 `baidu-search` 的 function,但该名字不是服务端真实工具,运行时 `tools/call` 必然失败;`listFailures` 只写不读,启动既不失败也不打日志。
|
||||
|
||||
**影响**:把不可用工具暴露给模型导致运行期报错;「降级保留占位工具」的初衷(启动不中断 + 错误清晰)没有达成,属于静默劣化。
|
||||
|
||||
**修复方案**:启动期区分「连接失败」与「无工具」,失败时记 `listFailures` 并打警告日志,或按 `required` 语义 fail fast;不要把配置名当可调用工具暴露;若保留占位,运行时应给出「MCP Server 未就绪」的明确错误。
|
||||
|
||||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-14
|
||||
>
|
||||
> `listFailures` 参与告警与 fail fast;探活逻辑在 P6 重写
|
||||
|
||||
### F-18 `io.ReadAll` 无上限读取上游响应体
|
||||
|
||||
**位置**:`Generate` in `internal/infrastructure/ai/openai_client.go`、`openSSE` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
**问题概述**:三处都用 `io.ReadAll` 把响应体一次性读入内存,没有任何大小限制。`truncate(...,400)` 只截断错误文案,读入本身仍是全量。
|
||||
|
||||
**影响**:异常/恶意上游返回超大响应(或错误页)时可导致内存快速膨胀,属于 DoS 面;对非流式 `Generate` 尤其明显。
|
||||
|
||||
**修复方案**:用 `io.LimitReader`(如 4~8 MiB)限制读取并在超限时返回明确错误;错误体只需读几百字节。
|
||||
|
||||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P2-22
|
||||
>
|
||||
> 入站有 `MaxBytesReader`;出站 `io.LimitReader` 上限写进 P1 的模型客户端加固
|
||||
|
||||
### F-19 流式请求没有发送 `Accept: text/event-stream`
|
||||
|
||||
**位置**:`do` in `internal/infrastructure/ai/openai_client.go` `do()`
|
||||
|
||||
```go
|
||||
func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, error) {
|
||||
...
|
||||
req.Header.Set("Accept", "application/json") // 流式/非流式共用
|
||||
```
|
||||
|
||||
**问题概述**:`do()` 被 `Generate` 与 `Stream` 共用,`Accept` 恒为 `application/json`,流式调用没有声明 `text/event-stream`。
|
||||
|
||||
**影响**:OpenAI 官方端点通常宽容,但部分兼容实现/网关会依据 `Accept` 决定是否返回 SSE,可能表现为流式请求拿不到事件流或直接被拒。
|
||||
|
||||
**修复方案**:`do()` 增加 `accept string` 参数,流式传 `text/event-stream`、非流式传 `application/json`;或校验返回的 `Content-Type` 并给出明确错误。
|
||||
|
||||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P2-23
|
||||
>
|
||||
> `Accept: text/event-stream` 写进 P1 的模型客户端加固
|
||||
|
||||
### F-20 `MCPToolRouter` 的 `registered` / `listFailures` 是死字段,`notify` 不校验状态码
|
||||
|
||||
**位置**:`MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go`、`notify` 在 `:458-485`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `registered map[string]struct{}` 只写不读(第 548 行写、无任何读取);
|
||||
- `listFailures map[string]error` 只写不读(第 540 行写、无任何读取);
|
||||
- `notify()` 丢弃响应体后不检查 `StatusCode`。
|
||||
|
||||
**影响**:死字段误导读者;`notifications/initialized` 若被服务端拒绝(4xx/5xx),客户端仍认为握手成功,后续调用才报莫名的错。
|
||||
|
||||
**修复方案**:删除死字段(或让 `listFailures` 真正参与启动告警);`notify` 增加状态码校验。
|
||||
|
||||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P3-15
|
||||
>
|
||||
> `listFailures` 改为告警后自然解决;`notify` 的状态码校验在 P1 补
|
||||
|
||||
### F-21 任一工具失败即整轮失败(`executeToolCalls`)
|
||||
|
||||
**位置**:`(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:工具调用循环里任何一个工具返回错误,`executeToolCalls` 直接 `return nil, fmt.Errorf("tool %q: %w", call.Name, err)`,整个 run 终止,没有重试、没有降级、没有把失败结果作为 observation 回灌给模型。
|
||||
|
||||
**影响**:一个下游 5xx、一次限流、一次超时就能让整轮对话失败;而模型其实完全有能力基于「工具不可用」这个observation 给出替代答案。
|
||||
|
||||
**修复方案**:P1 的 `tool.Gateway` 把失败分类后走六层降级(P1 设计中的 L0–L6)。L5 结构化降级之后必须把结果作为工具输出回灌给模型,而不是让 run 失败——「工具故障是模型要处理的信息,不是 run 的终态」。
|
||||
|
||||
> **归属**:P1 | **状态**:✅
|
||||
|
||||
### F-22 工具调用无单次超时,只靠 HTTP 客户端整体超时
|
||||
|
||||
**位置**:`internal/infrastructure/ai/mcp_sse_client.go` 的 `RequestTimeout`(默认 300s)
|
||||
|
||||
**问题概述**:工具级超时只有一个默认 300 秒的 `RequestTimeout`,实际调用路径上没有被单独施加 deadline 的地方;一次工具挂起会一直占用一个 step,直到外层 HTTP 客户端超时。
|
||||
|
||||
**影响**:单个慢工具能把整个 run 拖到分钟级;并发场景下直接耗尽连接与 goroutine。
|
||||
|
||||
**修复方案**:P1 的 `tool.Spec.Timeout` 成为唯一事实源(默认 30s,可按工具覆盖),Gateway 在 `Invoke` 前用 `context.WithTimeout` 施加 deadline;超时归类为 `timeout`(可重试),并计入 `Budget.MaxWallClock`。
|
||||
|
||||
> **归属**:P1 | **状态**:✅
|
||||
446
docs/upgrade-plan/P2-会话持久化.md
Normal file
446
docs/upgrade-plan/P2-会话持久化.md
Normal file
@@ -0,0 +1,446 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P2 · 会话生命周期与持久化:让 Agent 记得住、找得回 | **预估**:8–10 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.3 节
|
||||
> **本阶段收编缺陷**:F-23、F-24、F-25、F-26、F-27、F-28、F-29、F-30、F-31(共 9 条,明细见文末附录)
|
||||
> 上一阶段:[`P1`](P1-工具网关.md) | 下一阶段:[`P3`](P3-记忆与知识.md)
|
||||
|
||||
|
||||
# 4.3 P2 · 会话生命周期与持久化:让 Agent 记得住、找得回
|
||||
|
||||
## 目标
|
||||
|
||||
把"会话"从一张 `map[userID:agentID]sessionID` 升级为**有生命周期、有归属、有消息历史、可恢复**的领域聚合,并真正接上已经写好但从未被调用的 MySQL / Redis 适配器。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 证据 | 问题 |
|
||||
|---|---|
|
||||
| `InMemoryAgentRegistry`/`InMemorySessionStore` in `internal/domain/agent/ports/ports.go` | `InMemorySessionStore` 只有 `Get/Set`,重启即丢(F-24) |
|
||||
| `(*Service).CreateSession` in `internal/domain/agent/service/chat/service.go` | `CreateSession` 先 Get 再 Set,无锁无唯一约束(F-25) |
|
||||
| `(*Service).resolveRunnerSession` in `internal/domain/agent/service/chat/service.go` | `resolveRunnerSession` 直接用请求里的 `sessionID`,不校验归属(F-23) |
|
||||
| `(*Runner).CreateSession` in `internal/infrastructure/adk/adapter.go` | `appName:userID:counter` 拼 ID,无租户、可能撞号(F-31) |
|
||||
| `Build` in `internal/app/bootstrap/bootstrap.go` | 写死 `NewInMemorySessionStore()`,MySQL/Redis 适配器未接线 |
|
||||
| 全局 | 无消息表、无历史查询、无 TTL、无归档 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.3.1 会话聚合与状态机
|
||||
|
||||
```go
|
||||
// internal/domain/session/session.go
|
||||
type Status int8
|
||||
|
||||
const (
|
||||
StatusActive Status = 1
|
||||
StatusArchived Status = 2
|
||||
StatusExpired Status = 3
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
ID string // ULID,26 字符
|
||||
TenantID string
|
||||
UserID string
|
||||
AgentID string
|
||||
Title string
|
||||
Status Status
|
||||
LastSeq int // 消息序号水位(乐观并发)
|
||||
MessageCount int
|
||||
PromptTokens, CompletionTokens int
|
||||
Meta map[string]any
|
||||
CreatedAt, UpdatedAt, LastActiveAt time.Time
|
||||
ExpiresAt *time.Time
|
||||
}
|
||||
|
||||
// 状态迁移:active --idle-timeout--> archived --retention--> expired
|
||||
// 反向:archived --new message--> active(复用会话,不新建)
|
||||
```
|
||||
|
||||
### 4.3.2 端口定义
|
||||
|
||||
```go
|
||||
// internal/domain/session/ports.go
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, s *Session) error // 唯一键冲突返回 ErrSessionExists
|
||||
Get(ctx context.Context, id string) (*Session, error) // 不存在返回 ErrSessionNotFound
|
||||
GetActive(ctx context.Context, tenant, user, agent string) (*Session, error)
|
||||
Touch(ctx context.Context, id string, at time.Time, tokens Usage) error
|
||||
UpdateStatus(ctx context.Context, id string, from, to Status) error
|
||||
ListByUser(ctx context.Context, tenant, user string, cursor string, limit int) ([]*Session, string, error)
|
||||
Sweep(ctx context.Context, now time.Time, idleAfter, retention time.Duration) (archived, expired int, err error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
// Append 在一个事务内分配连续 seq,保证 (session_id, seq) 唯一。
|
||||
Append(ctx context.Context, sessionID string, msgs []Message) ([]Message, error)
|
||||
ListRange(ctx context.Context, sessionID string, fromSeq, toSeq int) ([]Message, error)
|
||||
ListRecent(ctx context.Context, sessionID string, limit int) ([]Message, error) // 内部 DESC 后反转
|
||||
CountTokens(ctx context.Context, sessionID string, fromSeq int) (int, error)
|
||||
}
|
||||
|
||||
type RunRepository interface {
|
||||
Create(ctx context.Context, r *runtime.Run) error
|
||||
Finish(ctx context.Context, r *runtime.Run) error
|
||||
Get(ctx context.Context, id string) (*runtime.Run, error)
|
||||
ListBySession(ctx context.Context, sessionID string, limit int) ([]*runtime.Run, error)
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3.3 表结构(MySQL 8.0)
|
||||
|
||||
```sql
|
||||
-- migrations/0001_session.up.sql
|
||||
CREATE TABLE `agent_session` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`user_id` VARCHAR(64) NOT NULL,
|
||||
`agent_id` VARCHAR(64) NOT NULL,
|
||||
`title` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '1=active 2=archived 3=expired',
|
||||
-- 生成列:只在 active 时为 1,archived/expired 为 NULL,
|
||||
-- 从而"同一用户同一 Agent 仅一个活跃会话"可用唯一索引表达(MySQL 唯一索引允许多个 NULL)
|
||||
`active_flag` TINYINT GENERATED ALWAYS AS (IF(`status` = 1, 1, NULL)) STORED,
|
||||
`last_seq` INT NOT NULL DEFAULT 0,
|
||||
`message_count` INT NOT NULL DEFAULT 0,
|
||||
`prompt_tokens` INT NOT NULL DEFAULT 0,
|
||||
`completion_tokens` INT NOT NULL DEFAULT 0,
|
||||
`meta` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
`last_active_at` DATETIME(3) NOT NULL,
|
||||
`expires_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_active_user_agent` (`tenant_id`,`user_id`,`agent_id`,`active_flag`),
|
||||
KEY `idx_user_recent` (`tenant_id`,`user_id`,`status`,`last_active_at`),
|
||||
KEY `idx_sweep` (`status`,`last_active_at`),
|
||||
KEY `idx_expires` (`expires_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
|
||||
CREATE TABLE `agent_message` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`session_id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`seq` INT NOT NULL,
|
||||
`role` VARCHAR(16) NOT NULL COMMENT 'system|user|assistant|tool',
|
||||
`name` VARCHAR(128) NOT NULL DEFAULT '',
|
||||
`content` MEDIUMTEXT NULL,
|
||||
`tool_calls` JSON NULL,
|
||||
`tool_call_id` VARCHAR(128) NOT NULL DEFAULT '',
|
||||
`token_count` INT NOT NULL DEFAULT 0,
|
||||
`finish_reason` VARCHAR(32) NOT NULL DEFAULT '',
|
||||
`pinned` TINYINT NOT NULL DEFAULT 0 COMMENT '关键信息,压缩时永不丢弃',
|
||||
`meta` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_session_seq` (`session_id`,`seq`),
|
||||
KEY `idx_session_id` (`session_id`,`id`),
|
||||
KEY `idx_run` (`run_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE `agent_run` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`session_id` CHAR(26) NOT NULL,
|
||||
`turn_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`agent_id` VARCHAR(64) NOT NULL,
|
||||
`status` VARCHAR(24) NOT NULL,
|
||||
`steps` INT NOT NULL DEFAULT 0,
|
||||
`tool_calls` INT NOT NULL DEFAULT 0,
|
||||
`prompt_tokens` INT NOT NULL DEFAULT 0,
|
||||
`completion_tokens` INT NOT NULL DEFAULT 0,
|
||||
`failure_class` VARCHAR(32) NOT NULL DEFAULT '',
|
||||
`failure_code` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`started_at` DATETIME(3) NOT NULL,
|
||||
`ended_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_session_started` (`session_id`,`started_at`),
|
||||
KEY `idx_status_started` (`status`,`started_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
### 4.3.4 序号分配:唯一索引 + 事务内自增
|
||||
|
||||
不引入发号器,直接利用会话行的 `last_seq`:
|
||||
|
||||
```sql
|
||||
-- 事务内
|
||||
SELECT last_seq FROM agent_session WHERE id = ? FOR UPDATE;
|
||||
-- 应用层 seq = last_seq+1 ... +N
|
||||
INSERT INTO agent_message (...) VALUES (...);
|
||||
UPDATE agent_session SET last_seq = ?, message_count = message_count + ?, updated_at = ? WHERE id = ?;
|
||||
```
|
||||
|
||||
`FOR UPDATE` 把同一会话的并发写串行化(单会话写入本就是串行语义),跨会话完全并行。`uk_session_seq` 是最后一道防线:任何越界写入都会失败而不是产生重复。
|
||||
|
||||
### 4.3.5 幂等创建(修复 F-25)
|
||||
|
||||
```go
|
||||
func (s *Service) EnsureSession(ctx context.Context, req EnsureRequest) (*Session, error) {
|
||||
if s := s.repo.FindActive(ctx, req.Tenant, req.User, req.Agent); s != nil {
|
||||
return s, nil
|
||||
}
|
||||
sess := NewSession(req)
|
||||
err := s.repo.Create(ctx, sess)
|
||||
if errors.Is(err, ErrSessionExists) { // 并发下唯一键冲突 → 回到读路径
|
||||
return s.repo.GetActive(ctx, req.Tenant, req.User, req.Agent)
|
||||
}
|
||||
return sess, err
|
||||
}
|
||||
```
|
||||
|
||||
不依赖 Redis 锁即可保证正确性;Redis 锁(`lock:session:create:{tenant}:{user}:{agent}`,3s)只用于**降低冲突率**,不是正确性来源。这是面试里"为什么不用分布式锁保证唯一"的标准答案:唯一约束才是真相,锁只是优化。
|
||||
|
||||
### 4.3.6 归属校验(修复 F-23 越权)
|
||||
|
||||
```go
|
||||
var ErrSessionForbidden = errors.New("session does not belong to caller")
|
||||
|
||||
func (s *Service) Authorize(ctx context.Context, tenant, user, agent, sessionID string) (*Session, error) {
|
||||
sess, err := s.repo.Get(ctx, sessionID)
|
||||
if err != nil { return nil, err }
|
||||
if sess.TenantID != tenant || sess.UserID != user || sess.AgentID != agent {
|
||||
return nil, ErrSessionForbidden // → HTTP 403 / code 4003
|
||||
}
|
||||
return sess, nil
|
||||
}
|
||||
```
|
||||
|
||||
**配套**:`ChatCommand` 增加 `TenantID`;HTTP 层在 P8 从 token 取,P2 阶段从 `X-Tenant-ID` 取(默认 `default`)。
|
||||
|
||||
### 4.3.7 Redis 的四个职责(不是"缓存一下"这么简单)
|
||||
|
||||
| 用途 | Key | TTL | 说明 |
|
||||
|---|---|---|---|
|
||||
| 会话读缓存 | `sess:{id}` | 10m | Cache-aside,写后失效;命中率目标 > 80% |
|
||||
| 最近消息缓存 | `sess:recent:{id}` | 10m | List,只存最近 40 条,供 P4 装配器热路径使用 |
|
||||
| 创建锁 | `lock:sess:create:{t}:{u}:{a}` | 3s | 仅降冲突,不是正确性来源 |
|
||||
| 幂等键 | `idem:run:{t}:{key}` | 24h | 重复提交返回同一 run_id |
|
||||
|
||||
**降级策略**:Redis 不可用时**必须**回落到"直连 MySQL + 进程内 LRU",不允许因此拒绝请求。用 `golang.org/x/sync/singleflight` 合并同一会话的并发回源。
|
||||
|
||||
### 4.3.8 持久化模式与优雅降级
|
||||
|
||||
```yaml
|
||||
persistence:
|
||||
mode: mysql+redis # memory | mysql | mysql+redis
|
||||
mysql:
|
||||
required: true # false 且连接失败 → 降级 memory 并打 WARN + 指标
|
||||
redis:
|
||||
required: false
|
||||
```
|
||||
|
||||
`bootstrap.Build()` 中的装配逻辑:
|
||||
|
||||
```go
|
||||
switch cfg.Persistence.Mode {
|
||||
case "mysql+redis":
|
||||
db := mysql.Open(ctx, cfg.Database) // 失败且 required=false → 降级
|
||||
rdb := redis.Open(ctx, cfg.Redis) // 失败 → 继续,日志告警
|
||||
sessionRepo = mysqlrepo.NewSessionRepo(db)
|
||||
...
|
||||
default:
|
||||
sessionRepo = ports.NewInMemorySessionStore() // 保持现有能力,供单测/本地
|
||||
}
|
||||
```
|
||||
|
||||
注意:`configs/application.yaml` 现有 `database.required: false`,语义正好可用于"本地无 MySQL 也能起"。
|
||||
|
||||
### 4.3.9 新增只读 API(不影响老端点)
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
|---|---|---|
|
||||
| GET | `/api/v1/sessions` | 当前用户会话列表(游标分页) |
|
||||
| GET | `/api/v1/sessions/{id}` | 会话详情 + 统计 |
|
||||
| GET | `/api/v1/sessions/{id}/messages?after_seq=&limit=` | 历史消息(前端"加载更多") |
|
||||
| DELETE | `/api/v1/sessions/{id}` | 软归档 |
|
||||
| GET | `/api/v1/runs/{id}` | Run 状态与用量 |
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/session/session.go` | 聚合、状态迁移、不变量 |
|
||||
| 新增 | `internal/domain/session/ports.go` | 三个 Repository 接口 |
|
||||
| 新增 | `internal/domain/session/service.go` | Ensure/Authorize/Touch/Sweep |
|
||||
| 新增 | `internal/domain/session/message.go` | Message 领域模型 + 角色校验 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/db.go` | 连接池、健康检查、指标 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/session_repo.go` | 会话 CRUD + Sweep |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/message_repo.go` | seq 分配、区间查询 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/run_repo.go` | Run 落库 |
|
||||
| 新增 | `migrations/0001_session.up.sql` / `.down.sql` | 上述 DDL |
|
||||
| 新增 | `cmd/migrate/main.go` | 迁移执行(启动参数 `-migrate`) |
|
||||
| 修改 | `internal/infrastructure/cache/redis.go` | 增加通用客户端、缓存、锁、幂等封装 |
|
||||
| 修改 | `internal/infrastructure/persistence/mysql.go` | 改为薄封装或删除(逻辑移入 `mysql/` 包) |
|
||||
| 修改 | `internal/domain/agent/model/command.go` | `ChatCommand` 加 `TenantID` |
|
||||
| 修改 | `internal/domain/agent/service/chat/service.go` | 改用 session.Service,鉴权后再建会话 |
|
||||
| 修改 | `internal/infrastructure/adk/runner.go` | Run 落库、消息落库时机 |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | 新增 5 个只读端点、错误映射 4003 |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 按 `persistence.mode` 装配 + 健康检查 |
|
||||
| 修改 | `cmd/server/main.go` | 启动时执行迁移(可选)、关闭时释放连接池 |
|
||||
| 修改 | `pkg/types/codes.go` | 新增 4003(越权)/4004(会话不存在)/5001(存储不可用) |
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **重启不丢**:`kill -9` 后重启,同一 `session_id` 的历史消息完整返回(seq 连续)。
|
||||
2. **并发唯一**:100 goroutine 同时 `EnsureSession(tenant,user,agent)`,数据库最终只有 1 条 active。
|
||||
3. **越权拒绝**:用户 B 带用户 A 的 session_id 请求,返回 403/4003,且**不产生任何用户 A 的消息写入**。
|
||||
4. **seq 无重复**:并发 append 1000 条消息,`(session_id, seq)` 唯一,无空洞以外的异常。
|
||||
5. **降级可用**:MySQL 关闭且 `required: false` 时服务正常启动,日志 WARN,指标 `persistence_degraded=1`。
|
||||
6. Redis 关闭时,功能全部可用,仅延迟上升(p95 < 50ms)。
|
||||
7. 会话清理任务:手动把 `last_active_at` 改为 31 天前,跑 Sweep 后状态变 `archived`。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **仓储集成测试**:testcontainers-go 起 MySQL 8.0 + Redis 6.2,跑真实 SQL;CI 用 docker-compose 复用 `deployments/docker-compose.yml`(顺手修掉其中 redis `networks: voice-input-net` 的引用错误)。
|
||||
- **并发测试**:`-race` + 100 并发 Ensure/Append。
|
||||
- **迁移测试**:up → down → up 幂等;对空库与有数据分别验证。
|
||||
- **降级测试**:用 `sqlmock` 注入连接失败,断言回落内存实现。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 消息表膨胀(单会话万级消息) | 按 `session_id` 分区/归档;P4 压缩后老消息移到冷表 |
|
||||
| `FOR UPDATE` 热点 | 单会话串行是语义要求;跨会话无竞争;若仍不足,改 `INSERT ... SELECT MAX(seq)+1` 乐观重试 |
|
||||
| 迁移失败阻塞启动 | 迁移与启动解耦:`-migrate` 单独执行;启动只做 `schema_version` 校验 |
|
||||
| gorm 与 sqlx 混用 | 新仓储统一 `sqlx`;`mysql.go` 的 gorm 代码冻结不再扩展,下一个版本删除依赖 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(9 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-23 `sessionId` 不校验归属
|
||||
|
||||
**位置**:`resolveRunnerSession` in `internal/domain/agent/service/chat/service.go`
|
||||
|
||||
**问题概述**:只要 `command.SessionID != ""` 就直接使用,不校验它是否属于该 `userId` / `agentId`,也不校验是否存在。
|
||||
|
||||
**影响**:任意调用方可传入他人 sessionId;虽然当前 session 无状态、危害有限,但一旦引入对话历史(F-24)或计费,就是越权访问。
|
||||
|
||||
**修复方案**:`SessionStore` 增加 `Validate(userID, agentID, sessionID) bool` 或让 `Get` 返回后比对;`resolveRunnerSession` 中先校验再使用,不匹配返回 `CodeIllegalParameter`。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P1-5
|
||||
|
||||
### F-24 Session 无对话历史(Agent 实际无状态)
|
||||
|
||||
**位置**:`InMemorySessionStore` in `internal/domain/agent/ports/ports.go`、`applyVars` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:`SessionStore` 只保存 `userID:agentID -> sessionID` 字符串,不保存消息历史;`runLLM` 每次都从 `[system, user]` 重建消息。
|
||||
|
||||
**影响**:看似支持多轮对话,实则每轮独立;前端「上下文」只能靠把上一轮 XML 拼进 message 来绕过。这是产品能力的核心缺口。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- 新增 `ConversationStore` 端口,保存 `sessionID -> []ChatMessage`。
|
||||
- `Runner.Run` 前加载历史并追加到 `initialMessages` 之后;执行完成后把 user + assistant 消息写回。
|
||||
- 内存实现先用带锁 map,后续可替换 Redis/MySQL。
|
||||
- 注意消息裁剪(token 预算)与并发写同一 session 的顺序问题。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P1-6
|
||||
>
|
||||
> P2 落消息持久化,P4 落预算装配,两者合起来才是完整的多轮
|
||||
|
||||
### F-25 `CreateSession` 并发竞态
|
||||
|
||||
**位置**:`CreateSession` in `internal/domain/agent/service/chat/service.go`
|
||||
|
||||
**问题概述**:`Get` 未命中后创建再 `Set`,两个并发请求可能都未命中,各自创建 session,后写覆盖先写。
|
||||
|
||||
**影响**:同一用户同一 Agent 出现 session 抖动,前一个 session 的 ID 被覆盖后客户端可能拿到「已经不存在」的 ID。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- `SessionStore` 增加 `GetOrCreate(userID, agentID, creator func() (string,error))`,内部加锁(或 Redis `SetNX`)。
|
||||
- 或在 `chat.Service` 内为 `userID:agentID` 加 per-key `singleflight`。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P1-7
|
||||
|
||||
### F-26 MySQL / Redis 适配器未接入
|
||||
|
||||
**位置**:`Build` in `internal/app/bootstrap/bootstrap.go`
|
||||
|
||||
**问题概述**:始终使用 `NewInMemoryAgentRegistry()` / `NewInMemorySessionStore()`,`persistence.OpenMySQL` 与 `cache.OpenRedis` 无人调用。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 重启丢会话;
|
||||
- 多实例无法共享;
|
||||
- 适配器代码长期未被验证,可能已腐化。
|
||||
|
||||
**修复方案**:在 `bootstrap.Build` 中根据 `appCfg.Database.Required/DSN`、`appCfg.Redis.Required/Addr` 决定是否打开,并让 `SessionStore` 走 Redis 实现(需先解决 F-29 的 context 问题)。`Required=false` 时保持内存实现并打日志说明。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P2-8
|
||||
|
||||
### F-27 空内容错误码不准确 + 先建 Session 后校验内容
|
||||
|
||||
**位置**:`resolveRunnerSession` in `internal/domain/agent/service/chat/service.go`
|
||||
|
||||
```go
|
||||
if sessionID == "" {
|
||||
sessionID, err = s.CreateSession(...) // 先建会话
|
||||
}
|
||||
...
|
||||
if ... 内容为空 {
|
||||
return ..., fmt.Errorf("chat content is required") // 非法参数却报 0001
|
||||
}
|
||||
```
|
||||
|
||||
**影响**:空消息请求会创建一个无用 Session;错误码是 `0001 unknown` 而非 `0002 illegal parameter`。
|
||||
|
||||
**修复方案**:把内容校验提到 `CreateSession` 之前;错误改为 `types.NewAppError(types.CodeIllegalParameter, "chat content is required")`。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P2-11
|
||||
>
|
||||
> 参数校验前置 + 错误码 `1001`(§5.1)
|
||||
|
||||
### F-28 `CreateSession` 不校验 Agent 是否仍存在
|
||||
|
||||
**位置**:`CreateSession` in `internal/domain/agent/service/chat/service.go`
|
||||
|
||||
**问题概述**:命中缓存直接返回旧 session,不检查 `registry` 中 Agent 是否还在。
|
||||
|
||||
**影响**:当前 registry 只增不删,问题不显现;支持热更新/下线后会出现「Agent 已下线仍可用」的不一致。
|
||||
|
||||
**修复方案**:命中缓存后仍做一次 `registry.Get(agentID)` 校验。
|
||||
|
||||
> **归属**:P2 | **状态**:🟡 | **历史编号**:P2-16
|
||||
>
|
||||
> 方案未点名;`CreateSession` 顺手加 `registry.Get` 校验
|
||||
|
||||
### F-29 `ports.SessionStore` 无 context
|
||||
|
||||
**为什么优化**:接口无 context,Redis/MySQL 实现只能内部用 `context.Background()`,无法随请求取消/超时。
|
||||
|
||||
**方案**:`Get(ctx, ...)` / `Set(ctx, ...)`,同步改内存实现与调用方。
|
||||
|
||||
**改动量**:小-中。
|
||||
|
||||
**影响**:为 F-26 的 Redis 接入铺路。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P3-7
|
||||
|
||||
### F-30 Session key 用 `:` 拼接存在歧义
|
||||
|
||||
**为什么优化**:`userID + ":" + agentID`,当 ID 自身含 `:` 时可能碰撞(如 `a:b` + `c` 与 `a` + `b:c`)。
|
||||
|
||||
**方案**:改用长度前缀编码、`\x00` 分隔或 `struct{userID, agentID string}` 作为 map key。
|
||||
|
||||
**改动量**:很小。
|
||||
|
||||
**影响**:消除边界情况。
|
||||
|
||||
> **归属**:P2 | **状态**:✅ | **历史编号**:P3-13
|
||||
|
||||
### F-31 Session ID 用全局原子计数拼接,无租户维度且跨 Agent 撞号
|
||||
|
||||
**位置**:`(*Runner).CreateSession` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:会话 ID 由 `fmt.Sprintf("%s:%s:%d", appName, userID, counter.Add(1))` 生成。计数器是进程内全局的,重启即归零;ID 里没有租户维度,也不能用于分布式部署(多实例各自从 1 开始)。
|
||||
|
||||
**影响**:重启后可能与历史会话 ID 重复;多实例部署必然撞号;ID 本身携带用户信息,属于不必要的泄露面。
|
||||
|
||||
**修复方案**:P2 起会话 ID 改为应用层生成的 ULID(`CHAR(26)`),租户与用户信息入库而不进主键;旧格式 ID 在迁移期由 `session.Repository.Get` 兼容读取(前缀解析),迁移完成后删除兼容分支。
|
||||
|
||||
> **归属**:P2 | **状态**:✅
|
||||
407
docs/upgrade-plan/P3-记忆与知识.md
Normal file
407
docs/upgrade-plan/P3-记忆与知识.md
Normal file
@@ -0,0 +1,407 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P3 · 记忆与知识:三层记忆 + 可检索知识库 | **预估**:12–15 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.4 节
|
||||
> **本阶段收编缺陷**:F-32(共 1 条,明细见文末附录)
|
||||
> 上一阶段:[`P2`](P2-会话持久化.md) | 下一阶段:[`P4`](P4-上下文工程.md)
|
||||
|
||||
|
||||
# 4.4 P3 · 记忆与知识:三层记忆 + 可检索知识库
|
||||
|
||||
## 目标
|
||||
|
||||
让 Agent 具备**跨轮、跨会话的记忆能力**,以及**基于文档的知识检索能力**(覆盖面试官 A 的"数据层:知识库怎么清洗、按什么切分"与"记忆层:多轮上下文怎么管理")。
|
||||
|
||||
## 当前问题
|
||||
|
||||
- 无任何记忆抽象:`ChatMessage` 只在单次 Run 的内存里存在(F-24)。
|
||||
- `AiAPIConfig.EmbeddingsPath` 定义了却从未使用(`model/config.go`)——说明作者预留了位置但没实现。
|
||||
- 无文档入库、切片、索引、召回的任何代码。
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.4.1 记忆分层模型
|
||||
|
||||
| 层 | 内容 | 存储 | 生命周期 | 何时读 | 何时写 |
|
||||
|---|---|---|---|---|---|
|
||||
| **L0 工作记忆** | 当前 Run 的 scope 变量、工具中间结果、计划 | 内存(`runtime.Scope`) | Run 级 | 每个 Step | 每个 Step |
|
||||
| **L1 短期记忆** | 原始消息流(user/assistant/tool) | `agent_message` | 会话级 | 每轮装配最近窗口 | 每轮(P2 已做) |
|
||||
| **L2 情节记忆** | 分段摘要(带时间、主题、决策) | `agent_memory_summary` | 会话级,长留存 | 装配时按需 | 触发压缩时(P4) |
|
||||
| **L3 语义记忆** | 事实:偏好/实体/决策/约束/未完成任务 | `agent_memory_fact` | 用户级,长期 | 每轮按相关性召回 | Run 结束后异步抽取 |
|
||||
| **L4 知识库** | 外部文档切片 + 向量 | `kb_document` / `kb_chunk` | 租户级 | 每轮检索 | 离线 ingest |
|
||||
|
||||
**为什么分三层而不是两层**:L1 解决"最近说了什么",L2 解决"这段聊了什么",L3 解决"这个用户是谁、他定过什么规矩"。三者检索代价与更新频率完全不同,混在一张表里会导致"要么全量塞上下文,要么全丢"。
|
||||
|
||||
### 4.4.2 语义记忆表(支持改写而非删除)
|
||||
|
||||
```sql
|
||||
-- migrations/0002_memory.up.sql
|
||||
CREATE TABLE `agent_memory_fact` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`user_id` VARCHAR(64) NOT NULL,
|
||||
`agent_id` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`scope` VARCHAR(16) NOT NULL COMMENT 'user|session|agent|tenant',
|
||||
`scope_id` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`kind` VARCHAR(32) NOT NULL COMMENT 'preference|entity|decision|constraint|open_task|correction',
|
||||
`subject` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`predicate` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`object` TEXT NULL,
|
||||
`content` TEXT NOT NULL COMMENT '自然语言陈述,供模型直接读',
|
||||
`importance` TINYINT NOT NULL DEFAULT 3 COMMENT '1..5',
|
||||
`confidence` DECIMAL(3,2) NOT NULL DEFAULT 1.00,
|
||||
`source_message_id` BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
`source_run_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`valid_from` DATETIME(3) NOT NULL,
|
||||
`valid_to` DATETIME(3) NULL COMMENT '非空表示已失效,但保留以便回溯',
|
||||
`superseded_by` CHAR(26) NULL,
|
||||
`access_count` INT NOT NULL DEFAULT 0,
|
||||
`last_accessed_at` DATETIME(3) NULL,
|
||||
`embedding` MEDIUMBLOB NULL COMMENT 'float32 小端拼接,维度见 embedding_dim',
|
||||
`embedding_dim` SMALLINT NOT NULL DEFAULT 0,
|
||||
`embedding_model` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`content_hash` CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256(content),去重用',
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_content_hash` (`tenant_id`,`user_id`,`scope`,`scope_id`,`content_hash`),
|
||||
KEY `idx_semantic` (`tenant_id`,`user_id`,`kind`,`valid_to`,`importance`),
|
||||
KEY `idx_recall` (`tenant_id`,`user_id`,`importance`,`last_accessed_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE `agent_memory_summary` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`session_id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`level` TINYINT NOT NULL COMMENT '1=分段 2=会话级 3=用户画像',
|
||||
`from_seq` INT NOT NULL,
|
||||
`to_seq` INT NOT NULL,
|
||||
`message_count` INT NOT NULL DEFAULT 0,
|
||||
`content` TEXT NOT NULL,
|
||||
`token_count` INT NOT NULL DEFAULT 0,
|
||||
`model` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`parent_id` CHAR(26) NULL COMMENT '递归压缩的上游摘要',
|
||||
`pinned_facts` JSON NULL COMMENT '压缩时被固化的事实快照',
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_session_range` (`session_id`,`level`,`from_seq`,`to_seq`),
|
||||
KEY `idx_session_level` (`session_id`,`level`,`to_seq`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- 记忆异步处理任务(outbox,保证不丢)
|
||||
CREATE TABLE `agent_memory_job` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`kind` VARCHAR(24) NOT NULL COMMENT 'extract_facts|summarize|embed',
|
||||
`payload` JSON NULL,
|
||||
`status` TINYINT NOT NULL DEFAULT 0 COMMENT '0=pending 1=running 2=done 3=failed',
|
||||
`attempts` TINYINT NOT NULL DEFAULT 0,
|
||||
`last_error` VARCHAR(512) NOT NULL DEFAULT '',
|
||||
`next_run_at` DATETIME(3) NOT NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_pending` (`status`,`next_run_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
### 4.4.3 知识库表(覆盖"数据层")
|
||||
|
||||
```sql
|
||||
CREATE TABLE `kb_document` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`title` VARCHAR(512) NOT NULL,
|
||||
`source` VARCHAR(1024) NOT NULL COMMENT '文件路径/URL/上传 ID',
|
||||
`mime` VARCHAR(64) NOT NULL,
|
||||
`content_hash` CHAR(64) NOT NULL,
|
||||
`size_bytes` BIGINT NOT NULL DEFAULT 0,
|
||||
`status` TINYINT NOT NULL DEFAULT 0 COMMENT '0=ingesting 1=ready 2=failed',
|
||||
`chunk_count` INT NOT NULL DEFAULT 0,
|
||||
`meta` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_tenant_hash` (`tenant_id`,`content_hash`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE `kb_chunk` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`doc_id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`seq` INT NOT NULL,
|
||||
`content` MEDIUMTEXT NOT NULL,
|
||||
`token_count` INT NOT NULL DEFAULT 0,
|
||||
`heading_path` VARCHAR(512) NOT NULL DEFAULT '' COMMENT '标题层级,如 "3.2 退换货/时限"',
|
||||
`chunk_strategy` VARCHAR(32) NOT NULL DEFAULT 'recursive',
|
||||
`embedding` MEDIUMBLOB NULL,
|
||||
`embedding_dim` SMALLINT NOT NULL DEFAULT 0,
|
||||
`meta` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_doc_seq` (`doc_id`,`seq`),
|
||||
KEY `idx_tenant_doc` (`tenant_id`,`doc_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
### 4.4.4 文档入库流水线(清洗 → 切分 → 向量化)
|
||||
|
||||
```
|
||||
上传/挂载 ──► Parse ──► Normalize ──► Chunk ──► Embed ──► Index ──► Ready
|
||||
│ │ │ │
|
||||
PDF/DOCX 去页眉页脚 策略可选 批量 64 条
|
||||
MD/HTML 合并断行 带 heading 失败重试 3 次
|
||||
纯文本 去重复空行 路径元数据
|
||||
```
|
||||
|
||||
**切分策略**(面试常问,必须能说出取舍):
|
||||
|
||||
| 策略 | 适用 | 参数 | 缺点 |
|
||||
|---|---|---|---|
|
||||
| `fixed` 定长 | 日志、无结构文本 | 512 token / overlap 64 | 切断语义 |
|
||||
| `recursive` 递归分隔(默认) | 通用文档 | `\n\n` → `\n` → `。` → 空格 | 可能超长块 |
|
||||
| `heading` 标题感知 | 手册、规范 | 按 `#/##/###` 分层,保留 `heading_path` | 依赖文档结构 |
|
||||
| `parent-child` 父子块 | 问答精度要求高 | 子块 256(检索),父块 1024(喂模型) | 存储翻倍 |
|
||||
| `semantic` 语义切分 | 长文、主题跳跃 | 相邻句 embedding 距离阈值 | 成本高、慢 |
|
||||
|
||||
默认 `recursive` + `heading` 混合:先按标题切,再对超长段递归切,overlap 10%。
|
||||
|
||||
**清洗规则**(可配置,顺序执行):去页眉页脚(按重复行检测)→ 合并硬换行(中文行尾无标点则拼接)→ 去连续空行 → 去零宽字符 → 表格转 Markdown → 图片 OCR(可选)→ 去重(SimHash,阈值 0.9)。
|
||||
|
||||
### 4.4.5 端口定义
|
||||
|
||||
```go
|
||||
// internal/domain/memory/ports.go
|
||||
type Fact struct {
|
||||
ID, TenantID, UserID, AgentID string
|
||||
Scope, ScopeID string
|
||||
Kind Kind
|
||||
Subject, Predicate, Object string
|
||||
Content string
|
||||
Importance int
|
||||
Confidence float64
|
||||
SourceMessageID int64
|
||||
SourceRunID string
|
||||
ValidFrom time.Time
|
||||
ValidTo *time.Time
|
||||
}
|
||||
|
||||
type FactStore interface {
|
||||
Upsert(ctx context.Context, facts []Fact) (inserted, superseded int, err error)
|
||||
Search(ctx context.Context, q FactQuery) ([]Fact, error)
|
||||
Touch(ctx context.Context, ids []string, at time.Time) error
|
||||
Forget(ctx context.Context, q ForgetQuery) (int, error) // 软失效
|
||||
}
|
||||
|
||||
type SummaryStore interface {
|
||||
Put(ctx context.Context, s Summary) error
|
||||
Latest(ctx context.Context, sessionID string, level int) (*Summary, error)
|
||||
ListRange(ctx context.Context, sessionID string, fromSeq, toSeq int) ([]Summary, error)
|
||||
}
|
||||
|
||||
type Retriever interface {
|
||||
Retrieve(ctx context.Context, q Query) ([]Hit, error)
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
TenantID, UserID, AgentID, SessionID string
|
||||
Text string
|
||||
Kinds []Kind
|
||||
TopK int
|
||||
MinScore float64
|
||||
IncludeKB bool
|
||||
KBFilter map[string]string // doc_id/heading 前缀过滤
|
||||
}
|
||||
|
||||
type Hit struct {
|
||||
Ref Ref // fact / summary / chunk
|
||||
Content string
|
||||
Score float64
|
||||
Breakdown ScoreBreakdown
|
||||
}
|
||||
|
||||
type Extractor interface {
|
||||
// Extract 从一段对话中抽取事实,必须返回结构化 JSON(受 schema 约束)
|
||||
Extract(ctx context.Context, in ExtractInput) ([]Fact, error)
|
||||
}
|
||||
|
||||
type Embedder interface {
|
||||
Embed(ctx context.Context, texts []string) ([][]float32, error)
|
||||
Dim() int
|
||||
}
|
||||
```
|
||||
|
||||
### 4.4.6 混合检索打分(不依赖向量库也能跑)
|
||||
|
||||
```go
|
||||
// 综合分 = 相关性 0.55 + 重要性 0.25 + 时效性 0.20,再做 MMR 去冗余
|
||||
score = 0.55*relevance + 0.25*float64(importance)/5 + 0.20*recencyDecay
|
||||
|
||||
recencyDecay = math.Exp(-ageDays / halfLifeDays) // 默认 halfLife = 30 天
|
||||
relevance = max(cosine(queryEmb, factEmb), bm25(query, content)/normBM25)
|
||||
```
|
||||
|
||||
- **有 embedding**:余弦相似度;无 embedding(或未配置 `embeddings-path`):回落 BM25(Go 侧内存倒排,按租户分片,万级文档足够)。
|
||||
- **MMR 去冗余**:`λ*score - (1-λ)*max_sim(已选)`,λ=0.7,避免召回 5 条几乎相同的事实。
|
||||
- **向量规模**:单用户事实 < 2 万条时,Go 内暴力余弦(2 万 × 1536 维 ≈ 120MB 内存/全量扫描 30ms),足够;超过则通过 `VectorIndex` 端口切 Qdrant/pgvector,不改上层。
|
||||
|
||||
### 4.4.7 写入路径:异步、可重试、不阻塞响应
|
||||
|
||||
```
|
||||
Run 结束
|
||||
└─► 事务内写 agent_memory_job(kind=extract_facts) ← 与 assistant 消息同事务,保证不丢
|
||||
└─► worker(每 5s 拉 pending,最多 4 并发)
|
||||
├─► Extractor:用**便宜模型**(可配)按 JSON schema 抽事实
|
||||
├─► 去重/消解:content_hash 唯一;subject+predicate 相同 → 旧的置 valid_to
|
||||
├─► Embed(批量 64,失败重试 3 次,指数退避)
|
||||
└─► 更新 job=done
|
||||
```
|
||||
|
||||
**为什么异步**:抽取要多一次 LLM 调用(几百 ms 到数秒),放主链路会显著抬高 p95。用户感知的是"下一轮才想起来",这是可接受的取舍——但要在产品上明确("记忆在下一轮生效")。
|
||||
|
||||
**为什么用 outbox 表而不是直接 goroutine**:进程崩溃会丢任务;表 + 轮询是零依赖的可靠队列,配 `FOR UPDATE SKIP LOCKED` 支持多实例。
|
||||
|
||||
```sql
|
||||
SELECT * FROM agent_memory_job
|
||||
WHERE status = 0 AND next_run_at <= NOW()
|
||||
ORDER BY next_run_at LIMIT 20
|
||||
FOR UPDATE SKIP LOCKED;
|
||||
```
|
||||
|
||||
### 4.4.8 抽取的 prompt 契约(结构化,防幻觉)
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"facts": {
|
||||
"type": "array",
|
||||
"maxItems": 8,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["kind", "content", "importance", "evidence_seq"],
|
||||
"properties": {
|
||||
"kind": {"enum": ["preference","entity","decision","constraint","open_task","correction"]},
|
||||
"subject": {"type": "string"},
|
||||
"predicate": {"type": "string"},
|
||||
"object": {"type": "string"},
|
||||
"content": {"type": "string", "maxLength": 300},
|
||||
"importance": {"type": "integer", "minimum": 1, "maximum": 5},
|
||||
"evidence_seq": {"type": "integer", "description": "该事实来自第几条消息,必须真实存在"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
三条硬规则:**只抽用户明确表达的内容**(不抽模型自己的推测)、**每条必须带 evidence_seq**(可回溯、可审计)、**importance 有明确定义**(见下表),避免模型全打 5 分。
|
||||
|
||||
| 分值 | 含义 | 例子 |
|
||||
|---|---|---|
|
||||
| 5 | 硬约束/禁令 | "以后不要用 emoji"、"金额必须保留两位小数" |
|
||||
| 4 | 稳定偏好/身份 | "我是后端工程师"、"偏好 Go" |
|
||||
| 3 | 项目事实 | "这个项目用 MySQL 8" |
|
||||
| 2 | 一次性上下文 | "这次先看 3 个文件" |
|
||||
| 1 | 闲聊 | "今天天气不错" |
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/memory/fact.go` | Fact/Kind/校验 |
|
||||
| 新增 | `internal/domain/memory/summary.go` | Summary/层级 |
|
||||
| 新增 | `internal/domain/memory/ports.go` | FactStore/SummaryStore/Retriever/Extractor/Embedder |
|
||||
| 新增 | `internal/domain/memory/service.go` | Consume(run) 编排、去重消解 |
|
||||
| 新增 | `internal/domain/memory/extractor.go` | 结构化抽取 + evidence 校验 |
|
||||
| 新增 | `internal/domain/memory/retriever.go` | 混合检索 + MMR |
|
||||
| 新增 | `internal/domain/memory/scoring.go` | BM25、余弦、时效衰减 |
|
||||
| 新增 | `internal/domain/knowledge/{document.go,chunk.go,parser.go,chunker.go,service.go}` | 文档入库 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/fact_repo.go` | 事实 CRUD + 唯一键消解 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/summary_repo.go` | 摘要读写 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/job_repo.go` | outbox(SKIP LOCKED) |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/kb_repo.go` | 文档/切片 |
|
||||
| 新增 | `internal/infrastructure/ai/embedding_client.go` | 复用 `EmbeddingsPath`、批量、缓存、重试 |
|
||||
| 新增 | `internal/infrastructure/memory/worker.go` | 轮询 worker + 优雅退出 |
|
||||
| 新增 | `migrations/0002_memory.up.sql` | 上述 DDL |
|
||||
| 修改 | `internal/domain/agent/model/config.go` | 新增 `MemoryConfig`、`KnowledgeConfig` |
|
||||
| 修改 | `internal/app/config/application.go` | 解析 `memory:` / `knowledge:` |
|
||||
| 修改 | `internal/infrastructure/adk/runner.go` | Run 成功后投递 job(同事务) |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Retriever/Store/Worker(`memory.enabled` 开关) |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | 新增 `POST /api/v1/knowledge/documents`、`GET /api/v1/memory/facts` |
|
||||
|
||||
## 配置
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
extract:
|
||||
model: gpt-4o-mini # 便宜模型
|
||||
max-facts-per-run: 8
|
||||
worker-concurrency: 4
|
||||
poll-interval: 5s
|
||||
retrieve:
|
||||
top-k: 6
|
||||
min-score: 0.35
|
||||
half-life-days: 30
|
||||
mmr-lambda: 0.7
|
||||
embedding:
|
||||
path: v1/embeddings # 复用 AiAPIConfig.EmbeddingsPath
|
||||
model: text-embedding-3-small
|
||||
dim: 1536
|
||||
batch-size: 64
|
||||
|
||||
knowledge:
|
||||
enabled: false
|
||||
chunk:
|
||||
strategy: recursive # fixed|recursive|heading|parent_child|semantic
|
||||
max-tokens: 512
|
||||
overlap-tokens: 64
|
||||
ingest:
|
||||
max-file-size: 20MB
|
||||
allowed-mime: [text/plain, text/markdown, application/pdf]
|
||||
```
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **跨轮记忆**:脚本第 2 轮说"我叫小林,以后叫我小林",第 25 轮问"我叫什么",回答必须包含"小林"(连续 10 次运行 10 次通过)。
|
||||
2. **约束遵守**:第 3 轮说"不要用表格",第 20 轮输出不含 markdown 表格。
|
||||
3. **事实去重**:同一事实重复 5 次,`agent_memory_fact` 只有 1 条有效记录,其余 `valid_to` 非空。
|
||||
4. **改写而非删除**:"预算 100 万" → 后续改口"预算改成 200 万",检索只返回 200 万,且旧记录可查。
|
||||
5. **知识库**:上传 50 页 PDF,切分出 300± 块,问 10 个跨页问题,命中率 ≥ 8/10,答案带 `doc_id + heading_path` 引用。
|
||||
6. **异步不阻塞**:开启记忆后 `/chat` p95 延迟增幅 < 5%。
|
||||
7. **可删除**:`Forget(user)` 后检索不到该用户任何事实(软失效 + 检索过滤)。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **评测驱动**:`testdata/memory/scenarios/*.yaml` 定义多轮脚本与断言,`go test ./internal/domain/memory -tags=eval`。
|
||||
- **抽取质量**:构造 50 段对话,人工标注期望事实,测 precision/recall(目标 P ≥ 0.85,R ≥ 0.7);抽取结果必须 100% 带合法 `evidence_seq`。
|
||||
- **检索**:20 条 query 的 recall@6、MRR;BM25 与向量两路分别跑,再跑融合。
|
||||
- **切分**:对同一文档跑 5 种策略,输出块数/平均长度/边界截断率对比表。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 抽取幻觉(编造用户没说的事) | 强制 `evidence_seq` 且回查原文包含关键实体;不匹配则丢弃并计数 |
|
||||
| 记忆污染(错误事实长期生效) | 提供"忘记这条"指令;`agent_memory_fact` 管理接口;importance×confidence 双阈值召回 |
|
||||
| 向量维度/模型变更 | 表内记录 `embedding_model/dim`;变更时后台重算,双写过渡 |
|
||||
| MySQL 存向量性能 | 单用户 < 2 万条内存暴力扫;超限切 `VectorIndex` 端口 |
|
||||
| 隐私合规 | 租户级隔离 + `Forget` + 留存期配置;PII 字段入库前脱敏(P7 guard 复用) |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(1 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-32 `EmbeddingsPath` 定义但未使用
|
||||
|
||||
**为什么优化**:配置项存在但不生效会让使用者误以为支持 embedding。
|
||||
|
||||
**方案**:实现 embedding 客户端并在 Armory 中新增节点,或暂时从配置与文档中移除。
|
||||
|
||||
**改动量**:移除很小;实现则中等(新客户端 + 新节点 + 端口)。
|
||||
|
||||
**影响**:配置语义变清晰,或新增 RAG 能力。
|
||||
|
||||
> **归属**:P3 | **状态**:✅ | **历史编号**:P3-3
|
||||
271
docs/upgrade-plan/P4-上下文工程.md
Normal file
271
docs/upgrade-plan/P4-上下文工程.md
Normal file
@@ -0,0 +1,271 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P4 · 上下文工程:20 轮之后还记得第一句话 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.5 节
|
||||
> **本阶段收编缺陷**:F-33(共 1 条,明细见文末附录)
|
||||
> 上一阶段:[`P3`](P3-记忆与知识.md) | 下一阶段:[`P5`](P5-工作流编排.md)
|
||||
|
||||
|
||||
# 4.5 P4 · 上下文工程:20 轮之后还记得第一句话
|
||||
|
||||
## 目标
|
||||
|
||||
用**确定性预算装配 + 滚动摘要压缩 + 关键信息优先召回**,替换现在"每轮只有 system+user"的做法(F-24),让上下文长度稳定、关键信息不丢、Token 成本可控。这是"记忆分层、上下文压缩、关键信息优先召回"三连问的完整答案。
|
||||
|
||||
## 当前问题
|
||||
|
||||
```go
|
||||
// 现状:initialMessages in internal/infrastructure/adk/adapter.go
|
||||
func initialMessages(instruction, userText string) []ports.ChatMessage {
|
||||
messages := make([]ports.ChatMessage, 0, 2)
|
||||
if strings.TrimSpace(instruction) != "" {
|
||||
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleSystem, Content: instruction})
|
||||
}
|
||||
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleUser, Content: userText})
|
||||
return messages
|
||||
}
|
||||
```
|
||||
|
||||
后果:
|
||||
- 第 2 轮起,模型完全不知道上一轮说了什么(连自己刚生成的答案都不知道)。
|
||||
- `ChatCommand.SessionID` 传了个寂寞——`resolveRunnerSession` 拿到 ID 后没查任何历史。
|
||||
- 工具调用结果也不落历史,多轮追问"刚才那个链接"必然失败。
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.5.1 装配器输入输出
|
||||
|
||||
```go
|
||||
// internal/domain/contextasm/assembler.go
|
||||
type Request struct {
|
||||
TenantID, UserID, AgentID, SessionID string
|
||||
Query string // 本轮用户输入
|
||||
SystemPrompt string
|
||||
Tools []tool.Spec
|
||||
Window int // 模型上下文窗口,默认 32768
|
||||
MaxOutput int // 预留输出,默认 2048
|
||||
Policy Policy
|
||||
}
|
||||
|
||||
type Bundle struct {
|
||||
Messages []ports.ChatMessage
|
||||
Tokens int
|
||||
Breakdown Breakdown // 每层用了多少 token,供观测与调优
|
||||
Refs []memory.Ref // 引用来源,用于前端"依据"展示与审计
|
||||
}
|
||||
|
||||
type Breakdown struct {
|
||||
System, Tools, Pinned, Summary, Anchors, Recent, Retrieved int
|
||||
Compacted bool
|
||||
Dropped int // 被裁剪的候选消息数
|
||||
}
|
||||
|
||||
type Assembler interface {
|
||||
Assemble(ctx context.Context, req Request) (Bundle, error)
|
||||
}
|
||||
```
|
||||
|
||||
> 包名取 `contextasm` 而非 `context`:若目录名即包名,`Assemble(ctx context.Context, ...)` 这类函数只能靠别名 import 标准库,读起来别扭且容易与 `runtime.Context` 混淆。
|
||||
|
||||
### 4.5.2 预算分配(先算再取,绝不"塞到爆")
|
||||
|
||||
```
|
||||
available = Window - MaxOutput - Safety(5%)
|
||||
```
|
||||
|
||||
| 层 | 内容 | 配额 | 超限策略 |
|
||||
|---|---|---:|---|
|
||||
| S | system prompt + 工具 schema | 固定,先扣 | 工具过多时按使用频次裁剪(P1 的 `Visibility`) |
|
||||
| P | **Pinned 事实**(importance ≥ 4 或本轮实体命中) | ≤ 15% | 按 importance 降序,超出则只留 5 条 |
|
||||
| M | 最新会话摘要 | ≤ 20% | 摘要本身超限 → 触发递归压缩(level 2) |
|
||||
| A | **锚点消息**(用户原话/纠正/带数字与 ID 的消息) | ≤ 15% | 按 `pinned` 标记优先,其余丢弃 |
|
||||
| R | 最近对话窗口 | ≤ 40% | 从最新往回取整轮(user+assistant+tool 成组) |
|
||||
| T | 检索到的情节/知识 | 剩余 | 按综合分取 top-k,低于 `min-score` 不取 |
|
||||
|
||||
**"成组"很重要**:assistant 的 `tool_calls` 与对应 `tool` 结果必须一起进或一起出,否则 OpenAI 协议直接 400(`tool_call_id` 无对应结果)。
|
||||
|
||||
### 4.5.3 装配顺序(为 prefix cache 优化)
|
||||
|
||||
```
|
||||
[system] ← 稳定
|
||||
[pinned facts](按 fact_id 排序) ← 半稳定,只增不改
|
||||
[summary](最新一条) ← 每次压缩才变
|
||||
[retrieved docs/facts] ← 每轮变化
|
||||
[anchors](按 seq 升序) ← 半稳定
|
||||
[recent window](时序) ← 每轮变化
|
||||
[user query] ← 最后
|
||||
```
|
||||
|
||||
设计理由(面试可讲):
|
||||
|
||||
1. **稳定前缀在前**:OpenAI/DeepSeek 的 prefix caching 按前缀匹配,`system + pinned` 不变即可命中缓存,输入成本可降 30%–50%。
|
||||
2. **pinned 按 ID 稳定排序**:绝不按"相关度"重排,否则每次都 miss。
|
||||
3. **U 型注意力**:关键约束放开头(system 之后紧跟 pinned),最新问题放结尾,符合长上下文"中间信息易丢"的经验规律。
|
||||
4. **不要把摘要放在最前面**:摘要会随压缩变化,放前面会让整段前缀失效。
|
||||
|
||||
### 4.5.4 压缩流水线(trigger → segment → summarize → verify → store)
|
||||
|
||||
```go
|
||||
type Compactor interface {
|
||||
ShouldCompact(ctx context.Context, s SessionStats) bool
|
||||
Compact(ctx context.Context, req CompactRequest) (Summary, error)
|
||||
}
|
||||
```
|
||||
|
||||
**触发条件**(满足任一):
|
||||
|
||||
- `session_tokens > 0.6 * Window`
|
||||
- 距上次摘要新增轮次 ≥ `compact.every-n-turns`(默认 8)
|
||||
- 单轮工具结果总量 > 8k token
|
||||
|
||||
**分段**:优先按"话题边界"切(连续两条用户消息 embedding 距离 > 阈值,或用户显式切换任务);退化方案按固定 8 轮。
|
||||
|
||||
**摘要模板**(结构化,避免自由发挥):
|
||||
|
||||
```markdown
|
||||
## 任务目标
|
||||
## 已确认的决策(含理由)
|
||||
## 硬约束与偏好(逐条,保留原话关键短语)
|
||||
## 关键实体(人名/项目/ID/数字,逐个列出)
|
||||
## 已完成 / 未完成
|
||||
## 产出物(文件/链接/代码片段摘要)
|
||||
```
|
||||
|
||||
**校验(关键一步,多数实现会漏)**:
|
||||
|
||||
1. 把该段的 **pinned 事实清单** 逐条检查是否出现在摘要里,缺失则**抽取式回填原句**(不重新生成,避免二次幻觉)。
|
||||
2. 用规则检查数字/ID/URL 是否保留(正则比对原文)。
|
||||
3. 摘要 token 必须 ≤ 原文的 `compact.ratio`(默认 0.25),否则重试一次更激进的模板。
|
||||
4. 校验不通过 → 降级为"抽取式摘要"(取每轮用户消息 + assistant 结论句),保证**信息不丢但可能啰嗦**。
|
||||
|
||||
**存储**:写 `agent_memory_summary(level=1, from_seq, to_seq)`,幂等(唯一键);递归压缩时 `level=2` 引用 `parent_id`。
|
||||
|
||||
### 4.5.5 关键信息优先召回(pinning 规则)
|
||||
|
||||
哪些消息在写入时就打 `pinned=1`(P2 表已有字段):
|
||||
|
||||
| 触发 | 判定 | 例子 |
|
||||
|---|---|---|
|
||||
| 用户显式指令 | 含"以后/始终/永远/不要/必须/记住" | "以后回答都用中文" |
|
||||
| 纠正 | 含"不对/不是/改成/应该是" | "不是 100 万,是 200 万" |
|
||||
| 数字与标识 | 正则命中金额/日期/订单号/URL | "订单 A12345" |
|
||||
| 自报身份/偏好 | 抽取器判定 `preference/entity` | "我是后端工程师" |
|
||||
| 任务目标 | 每轮第一条 user 消息 | "帮我把这个需求拆成任务" |
|
||||
|
||||
**召回增强**:把本轮 query 与"当前任务目标 + pinned 事实里的实体名"拼接后再检索(query rewriting),避免"它怎么样了"这类指代无法检索。
|
||||
|
||||
### 4.5.6 Token 计量与校准
|
||||
|
||||
- **估算**:装配阶段用轻量分词器估算(中文约 1 token/字,英文 1 token/4 字符,或用 `tiktoken-go` 精确算)。
|
||||
- **实际**:从 API 响应的 `usage` 读真值,回写 `Step.Usage` 与 `agent_message.token_count`。
|
||||
- **校准**:维护 `estimate/actual` 比值滑动平均,偏差 > 15% 时自动调整估算系数(不同模型分词器不同)。
|
||||
- **成本可控**:每轮装配产出 `Breakdown`,可直接回答"这个 6k token 里,2.1k 是工具 schema、1.8k 是最近窗口"。
|
||||
|
||||
### 4.5.7 可观测:上下文预览接口
|
||||
|
||||
```
|
||||
GET /api/v1/sessions/{id}/context_preview?query=...&window=32768
|
||||
```
|
||||
|
||||
返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"tokens": 6120,
|
||||
"breakdown": {"system":820,"tools":1650,"pinned":430,"summary":960,"anchors":0,"recent":1980,"retrieved":280},
|
||||
"compacted": true,
|
||||
"messages": [{"role":"system","tokens":820,"preview":"你是..."}],
|
||||
"refs": [{"type":"fact","id":"01J...","content":"用户偏好中文回答","score":0.82}]
|
||||
}
|
||||
```
|
||||
|
||||
这个接口在演示与排障时价值极高:能直接看到"为什么模型忘了"。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/contextasm/assembler.go` | 装配主流程 + 成组裁剪 |
|
||||
| 新增 | `internal/domain/contextasm/budget.go` | 配额计算与扣减 |
|
||||
| 新增 | `internal/domain/contextasm/pinning.go` | pin 判定规则 |
|
||||
| 新增 | `internal/domain/contextasm/compactor.go` | 触发/分段/摘要/校验 |
|
||||
| 新增 | `internal/domain/contextasm/token.go` | 估算、校准 |
|
||||
| 新增 | `internal/domain/contextasm/rewrite.go` | query 重写 |
|
||||
| 修改 | `internal/infrastructure/adk/executor_llm.go` | `initialMessages` → `assembler.Assemble` |
|
||||
| 修改 | `internal/infrastructure/adk/prompt.go` | 保留旧实现作为 fallback |
|
||||
| 修改 | `internal/domain/agent/service/chat/service.go` | 传入 session 与 query,触发压缩 |
|
||||
| 修改 | `internal/infrastructure/ai/openai_client.go` | 解析 `usage` 回填;支持 `max_tokens`/`temperature` 透传 |
|
||||
| 修改 | `internal/domain/agent/ports/ports.go` | `ChatModel` 增加 `Window() int`、`CountTokens()` |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Assembler/Compactor |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | `context_preview` 端点 |
|
||||
| 修改 | `internal/domain/agent/model/config.go` | `ContextConfig` |
|
||||
|
||||
## 配置
|
||||
|
||||
```yaml
|
||||
context:
|
||||
assembler:
|
||||
enabled: true
|
||||
window: 32768
|
||||
max-output: 2048
|
||||
quotas: # 百分比,合计 ≤ 100
|
||||
pinned: 15
|
||||
summary: 20
|
||||
anchors: 15
|
||||
recent: 40
|
||||
compact:
|
||||
trigger-ratio: 0.6
|
||||
every-n-turns: 8
|
||||
ratio: 0.25 # 摘要/原文 token 比
|
||||
model: gpt-4o-mini
|
||||
verify: true
|
||||
fallback: extractive # extractive | none
|
||||
cache:
|
||||
stable-prefix: true
|
||||
```
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **20 轮回归**:固定脚本 25 轮,第 1 轮注入 5 条关键信息(称呼、预算、日期、禁令、订单号),第 25 轮逐一追问,**全部答对**(10 次运行全通过)。
|
||||
2. **Token 稳定**:25 轮对话总输入 token 曲线在 5.5k–7k 之间波动,**不超过 8k**(当前实现第 25 轮虽然小,但会直接丢信息;对照实验见下)。
|
||||
3. **压缩保真**:对 50 段对话做压缩,pinned 事实召回率 100%(校验器保证),数字/ID 保留率 100%。
|
||||
4. **缓存命中**:连续 5 轮对话,第 2 轮起 prefix cache 命中率 ≥ 60%(以 provider 返回的 `cached_tokens` 为准,没有则用成本对比估算)。
|
||||
5. **协议合法**:装配结果中每个 `tool_calls` 都有配对的 `tool_call_id` 结果,回放 100 轮不出现 400。
|
||||
6. **延迟**:装配本身 p95 < 15ms(不含检索);开检索后 p95 < 80ms。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **黄金用例**:`testdata/context/turns_25.jsonl` + 断言文件,`-tags=eval` 跑真实模型,CI 每日跑一次。
|
||||
- **离线断言**:用 fake Retriever 返回固定事实,单测装配顺序、配额、成组裁剪、pinning 规则(表驱动 30 例)。
|
||||
- **压缩测试**:构造含 12 条关键信息的 50 轮对话,压缩后检查校验器 12/12 通过;故意删掉一条验证校验器能发现。
|
||||
- **Token 对齐**:对比估算与实际 usage,偏差 < 15%。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 摘要丢关键信息 | 三层校验 + 抽取式回填;`pinned` 永不进摘要只做保留 |
|
||||
| 压缩本身很贵 | 用便宜模型 + 只在阈值触发 + 结果缓存(同一 from/to 不重算) |
|
||||
| 装配顺序影响模型表现 | A/B:`stable-prefix` 开关对比任务成功率与成本 |
|
||||
| 工具 schema 占满预算 | 工具 > 20 个时按使用频次动态裁剪;`human_only` 工具不进 schema |
|
||||
| 老数据无 pinned 标记 | 一次性 backfill 任务:对历史 user 消息跑 pinning 规则 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(1 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-33 无法配置任何生成参数
|
||||
|
||||
**位置**:`ChatModelConfig` in `internal/domain/agent/model/config.go`、`buildRequestBody` in `internal/infrastructure/ai/openai_client.go`
|
||||
|
||||
**问题概述**:`buildRequestBody` 只发送 `model` / `messages` / `stream` / `tools`,没有 `temperature`、`max_tokens`、`top_p`、`stop`、`response_format`、`seed` 等参数,YAML 也无处可配(`grep "temperature|max_tokens|top_p" internal/ configs/` 无命中)。
|
||||
|
||||
**影响**:无法控制确定性与成本上限;drawio 这类「要求严格只输出 XML」的场景无法用 `response_format` 或低 `temperature` 提升稳定性,也无法用 `max_tokens` 控制成本。
|
||||
|
||||
**修复方案**:`ChatModelConfig` 增加 `params`/`generation` 子结构(用指针字段区分「未设置」与「零值」),透传到 `buildRequestBody`。改动集中在 model + provider + client 三处,向后兼容。
|
||||
|
||||
> **归属**:P4 | **状态**:🟡 | **历史编号**:P2-24
|
||||
>
|
||||
> 只覆盖了 `max_output`;`temperature`/`max_tokens`/`response_format` 透传写进 P4
|
||||
407
docs/upgrade-plan/P5-工作流编排.md
Normal file
407
docs/upgrade-plan/P5-工作流编排.md
Normal file
@@ -0,0 +1,407 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P5 · 工作流编排:从「线性 Chain」到「可补偿的状态机」 | **预估**:12–15 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.6 节
|
||||
> **本阶段收编缺陷**:F-34、F-35、F-36(共 3 条,明细见文末附录)
|
||||
> 上一阶段:[`P4`](P4-上下文工程.md) | 下一阶段:[`P6`](P6-工具治理.md)
|
||||
|
||||
|
||||
# 4.6 P5 · 工作流编排:从"线性 Chain"到"可补偿的状态机"
|
||||
|
||||
## 目标
|
||||
|
||||
把现在"sequential 能跑、parallel 假并发、loop 无迭代"的编排(F-34、F-35)升级为**显式图执行 + 节点级重试 + Saga 补偿 + 检查点续跑**。这是面试官 A "为什么选状态机而不是线性 Chain / 分支失败怎么回滚"的唯一可信答案。
|
||||
|
||||
## 当前问题
|
||||
|
||||
```go
|
||||
// 现状:(*Agent).runFanOut in internal/infrastructure/adk/adapter.go,parallel 与 loop 走同一个串行 fan-out
|
||||
func (a *Agent) runFanOut(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
|
||||
parts := make([]string, 0, len(a.subAgents))
|
||||
for _, sub := range a.subAgents { // ← 串行
|
||||
impl, ok := sub.(*Agent) // ← 只能接同包具体类型
|
||||
if !ok { return "", fmt.Errorf("sub-agent %q is not a runnable agent", sub.Name()) }
|
||||
text, err := impl.runWithVars(ctx, content, vars)
|
||||
if err != nil { return "", err } // ← 一个失败全失败
|
||||
parts = append(parts, fmt.Sprintf("[%s] %s", sub.Name(), text))
|
||||
}
|
||||
return strings.Join(parts, "\n"), nil
|
||||
}
|
||||
```
|
||||
|
||||
| 问题 | 证据 | 影响 |
|
||||
|---|---|---|
|
||||
| parallel 串行执行 | `(*Agent).runFanOut` in `internal/infrastructure/adk/adapter.go` | 3 分支各 10s,实际 30s |
|
||||
| `max-iterations` 从未使用 | 同上 + `model/config.go` | loop 配置形同虚设 |
|
||||
| 无节点级重试 | 同上 | 一个分支抖动毁掉整条链 |
|
||||
| 无补偿/回滚 | 全局无 | 第 3 步失败,前 2 步的副作用留在系统里 |
|
||||
| 无检查点 | 全局无 | 进程重启后只能从头跑,重复产生副作用 |
|
||||
| 无分支/条件 | 只有顺序执行 | 无法表达"评审不通过则回到绘制" |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.6.1 图模型
|
||||
|
||||
```go
|
||||
// internal/domain/workflow/graph.go
|
||||
type NodeID string
|
||||
|
||||
type NodeKind string
|
||||
|
||||
const (
|
||||
NodeAgent NodeKind = "agent" // 调用一个 Agent
|
||||
NodeTool NodeKind = "tool" // 直接调工具(不经模型)
|
||||
NodeBranch NodeKind = "branch" // 条件分支
|
||||
NodeJoin NodeKind = "join" // 汇聚
|
||||
NodeLoop NodeKind = "loop" // 循环子图
|
||||
NodeHuman NodeKind = "human" // 人工确认(P6)
|
||||
NodeSubgraph NodeKind = "subgraph" // 复用子图
|
||||
)
|
||||
|
||||
type Graph struct {
|
||||
ID string
|
||||
Version string // 配置版本,检查点据此判断兼容性
|
||||
Nodes map[NodeID]Node
|
||||
Edges []Edge
|
||||
Entry NodeID
|
||||
Vars map[string]VarSpec
|
||||
}
|
||||
|
||||
type Node struct {
|
||||
ID NodeID
|
||||
Kind NodeKind
|
||||
Agent string // Kind=agent
|
||||
Tool string // Kind=tool
|
||||
Inputs map[string]Binding // 形参 → 表达式("{analysis_result}" / "$.nodes.draw.output")
|
||||
OutputKey string
|
||||
Retry RetryPolicy
|
||||
Timeout time.Duration
|
||||
OnError ErrorPolicy // fail | skip | fallback | compensate | escalate
|
||||
Compensate NodeID // Saga 补偿节点
|
||||
Loop *LoopSpec
|
||||
When *Condition
|
||||
}
|
||||
|
||||
type LoopSpec struct {
|
||||
MaxIterations int
|
||||
Until *Condition // 为空则跑满次数(保持旧 loop 语义)
|
||||
StateKey string // 每轮写入的变量,用于无进展检测
|
||||
}
|
||||
|
||||
type Edge struct {
|
||||
From NodeID
|
||||
To NodeID
|
||||
When *Condition // 为空表示无条件
|
||||
Default bool // 所有条件不满足时走这条
|
||||
}
|
||||
```
|
||||
|
||||
### 4.6.2 条件表达式
|
||||
|
||||
用 `github.com/expr-lang/expr`(纯 Go、无反射逃逸、编译期检查变量),而不是 `text/template` 或自研 DSL:
|
||||
|
||||
```yaml
|
||||
when: "nodes.review.output.ok == false && attempt < 3"
|
||||
when: "vars.budget_remaining > 1000"
|
||||
when: "run.usage.steps < 12"
|
||||
```
|
||||
|
||||
环境变量只暴露白名单(`nodes` / `vars` / `run` / `attempt`),**不允许**访问 OS、文件、环境变量。表达式编译结果缓存,避免每次求值重新解析。
|
||||
|
||||
### 4.6.3 执行状态机
|
||||
|
||||
```
|
||||
┌──────────┐
|
||||
│ pending │
|
||||
└────┬─────┘
|
||||
前置满足 │
|
||||
┌────▼─────┐ retry ┌──────────┐
|
||||
│ running ├──────────►│ retrying │
|
||||
└────┬─────┘ └────┬─────┘
|
||||
成功 │ │ 失败 │
|
||||
┌────▼──┐ ▼ │
|
||||
│ done │ ┌──────────┐ │
|
||||
└───┬───┘ │ failed │◄────────────┘
|
||||
│ └────┬─────┘
|
||||
│ │ on_error=compensate
|
||||
│ ┌────▼────────┐
|
||||
│ │ compensating│──► compensated
|
||||
│ └─────────────┘
|
||||
└──────────► 下一个节点
|
||||
```
|
||||
|
||||
**关键决策:节点状态机而不是整图状态机**。整图状态机(如 Temporal 的 workflow)语义更严格,但改造成本高;节点级状态机 + 检查点表已经能满足"失败可定位、可重试、可续跑",且与现有 YAML 结构最贴近。
|
||||
|
||||
### 4.6.4 与旧配置的兼容映射
|
||||
|
||||
| 旧配置 | 新图 | 行为变化 | 兼容处理 |
|
||||
|---|---|---|---|
|
||||
| `type: sequential` + `sub-agents` | 线性链 `n1→n2→n3` | 无 | 直接映射 |
|
||||
| `type: parallel` + `sub-agents` | `fanout → n1..nk → join` | **真并发**(默认并发度 4) | 输出仍按 `sub-agents` 声明顺序拼接,保证 golden 一致;`workflow.execution-mode=legacy` 时走旧实现 |
|
||||
| `type: loop` + `max-iterations` | `loop` 节点 | `max-iterations` **真正生效** | 旧语义是"跑一次 fan-out",属 bug;修复需在 release note 标注,默认 `execution-mode=legacy` 保持一版 |
|
||||
| `output-key` | `OutputKey` + 变量写入 `scope` | 无 | 直接映射;同时支持 `$.nodes.x.output` 引用 |
|
||||
| `{key}` 模板 | `Binding` 表达式 | 无 | `"{key}"` 等价 `vars.key`,旧写法继续可用 |
|
||||
|
||||
### 4.6.5 检查点与续跑
|
||||
|
||||
```sql
|
||||
-- migrations/0003_workflow.up.sql
|
||||
CREATE TABLE `wf_instance` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`session_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`graph_id` VARCHAR(128) NOT NULL,
|
||||
`graph_version` VARCHAR(32) NOT NULL,
|
||||
`status` VARCHAR(24) NOT NULL COMMENT 'running|waiting|succeeded|failed|compensated',
|
||||
`current_node` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`vars` JSON NULL,
|
||||
`started_at` DATETIME(3) NOT NULL,
|
||||
`ended_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_run` (`run_id`),
|
||||
KEY `idx_status` (`status`,`started_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE `wf_node_exec` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`instance_id` CHAR(26) NOT NULL,
|
||||
`node_id` VARCHAR(64) NOT NULL,
|
||||
`attempt` SMALLINT NOT NULL DEFAULT 1,
|
||||
`status` VARCHAR(16) NOT NULL,
|
||||
`input` JSON NULL,
|
||||
`output` JSON NULL,
|
||||
`failure_class` VARCHAR(32) NOT NULL DEFAULT '',
|
||||
`failure_msg` VARCHAR(1024) NOT NULL DEFAULT '',
|
||||
`started_at` DATETIME(3) NOT NULL,
|
||||
`ended_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_node_attempt` (`instance_id`,`node_id`,`attempt`),
|
||||
KEY `idx_instance` (`instance_id`,`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
**续跑算法**:
|
||||
|
||||
```
|
||||
resume(instanceID):
|
||||
1. 读 wf_instance.vars(已完成的输出变量)
|
||||
2. 读所有 status='succeeded' 的 node 集合 S
|
||||
3. 从 Entry 做拓扑遍历,跳过 S 中节点,从第一个非 S 且前置全部 ∈ S 的节点开始
|
||||
4. 若该节点 status='running'(上次崩在半路)→ 按幂等键判断:副作用是否已发生?
|
||||
- 有幂等键 → 重放安全,attempt+1 重跑
|
||||
- 无幂等键 → 标记 needs_review,转人工(宁可漏跑不可重跑)
|
||||
5. 图版本不一致 → 拒绝续跑,返回 GRAPH_VERSION_MISMATCH
|
||||
```
|
||||
|
||||
**副作用安全**是这里最容易被忽略的点:续跑只对**幂等节点**自动重放;写类节点必须有幂等键(P1 的 `Idempotency`),否则转人工。这与 P1 的设计是同一个机制,复用即可。
|
||||
|
||||
### 4.6.6 真并发(errgroup + 部分失败策略)
|
||||
|
||||
```go
|
||||
g, gctx := errgroup.WithContext(rc.Context())
|
||||
g.SetLimit(policy.Concurrency) // 默认 4,来自配置
|
||||
for _, n := range branches {
|
||||
n := n
|
||||
g.Go(func() error {
|
||||
_, err := e.execNode(gctx, n)
|
||||
switch policy.PartialFailure {
|
||||
case "all": return err // 任一失败即取消其余
|
||||
case "any": return nil // 任一成功即算分支成功(记录其余失败)
|
||||
case "best_effort": return nil // 全部跑完,失败项降级为 remark
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
return g.Wait()
|
||||
```
|
||||
|
||||
三条约束:
|
||||
|
||||
1. **每个分支独立 `Step`,但共享 `Run.Budget`**(原子扣减),否则 k 个分支各自花光预算。
|
||||
2. **取消传播**:`all` 模式下任一失败要 `cancel()` 其余分支,并等待它们退出(`errgroup` 自带),避免 goroutine 泄漏。
|
||||
3. **输出顺序稳定**:结果按 `branches` 声明顺序收集,不按完成顺序,保证同样输入得到同样输出(可重放、可对比)。
|
||||
|
||||
### 4.6.7 循环的终止保证(回答"死循环")
|
||||
|
||||
三层终止:
|
||||
|
||||
| 层 | 机制 |
|
||||
|---|---|
|
||||
| 硬上限 | `MaxIterations`(配置,默认 3,硬顶 20),到点退出并标记 `loop_exhausted` |
|
||||
| 预算 | 每轮消耗 Run 预算,预算耗尽即退出(P0 已保证) |
|
||||
| **无进展检测** | 每轮结束计算 `state_hash = sha256(StateKey 的值)`;连续 2 轮相同 → 判定"原地打转",退出并记录 `no_progress`,把控制权交回(默认让模型总结当前进展) |
|
||||
|
||||
第三层是实践中最有用的:模型经常在两三个状态间来回,硬上限只会浪费 token,无进展检测能在第 3 轮就止损。
|
||||
|
||||
### 4.6.8 Saga 补偿
|
||||
|
||||
```yaml
|
||||
nodes:
|
||||
- id: reserve
|
||||
kind: tool
|
||||
tool: inventory.reserve
|
||||
compensate: release
|
||||
- id: charge
|
||||
kind: tool
|
||||
tool: payment.charge
|
||||
compensate: refund
|
||||
- id: notify
|
||||
kind: tool
|
||||
tool: notify.send
|
||||
```
|
||||
|
||||
失败从后往前执行补偿节点(逆序),每个补偿:
|
||||
|
||||
- 必须幂等(补偿本身可能重试)。
|
||||
- 失败不阻断后续补偿(记录 `compensation_failed`,最终统一告警)。
|
||||
- 补偿结果写 `wf_node_exec`,形成完整审计链。
|
||||
|
||||
对 Agent 场景,很多"步骤"没有真正的副作用(纯 LLM 调用),补偿节点可省略;真正需要补偿的是**工具写操作**与**外部通知**。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/workflow/graph.go` | Graph/Node/Edge/Condition |
|
||||
| 新增 | `internal/domain/workflow/builder.go` | 配置 → 图(兼容旧 type) |
|
||||
| 新增 | `internal/domain/workflow/executor.go` | 调度主循环、状态机 |
|
||||
| 新增 | `internal/domain/workflow/node_exec.go` | 单节点执行、重试、超时 |
|
||||
| 新增 | `internal/domain/workflow/state.go` | 实例状态、变量作用域、无进展检测 |
|
||||
| 新增 | `internal/domain/workflow/saga.go` | 逆序补偿 |
|
||||
| 新增 | `internal/domain/workflow/checkpoint.go` | 检查点存取与续跑 |
|
||||
| 新增 | `internal/domain/workflow/condition.go` | expr 编译缓存与白名单 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/workflow_repo.go` | wf_instance/wf_node_exec |
|
||||
| 新增 | `migrations/0003_workflow.up.sql` | 上述 DDL |
|
||||
| 修改 | `internal/infrastructure/adk/adapter.go` | 删除 `runSequential`/`runFanOut`(迁入 workflow) |
|
||||
| 修改 | `internal/domain/agent/service/armory/workflow/*.go` | 从"建 Agent"改为"建 Graph" |
|
||||
| 修改 | `internal/domain/agent/service/armory/agent_node.go` | 支持 graph 类型 |
|
||||
| 修改 | `internal/domain/agent/model/config.go` | `AgentWorkflowConfig` 增加 `Nodes/Edges/Version/PartialFailure/Concurrency` |
|
||||
| 修改 | `internal/app/config/loader.go` | graph 校验(节点唯一、边引用存在、入口可达、无环除 loop) |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | `GET /api/v1/runs/{id}/workflow`、`POST /runs/{id}/resume` |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Graph builder + Executor |
|
||||
| 修改 | `configs/agent/agent-draw-io.yaml` | 增加 graph 版本示例(保留旧配置作为 legacy 对照) |
|
||||
|
||||
## 配置
|
||||
|
||||
```yaml
|
||||
workflow:
|
||||
execution-mode: legacy # legacy | graph
|
||||
concurrency: 4
|
||||
partial-failure: all # all | any | best_effort
|
||||
loop:
|
||||
hard-max-iterations: 20
|
||||
no-progress-threshold: 2
|
||||
checkpoint:
|
||||
enabled: true
|
||||
store: mysql
|
||||
```
|
||||
|
||||
### 等价改写示例(draw-io 流程)
|
||||
|
||||
```yaml
|
||||
# 旧(现状)
|
||||
agent-workflows:
|
||||
- type: loop
|
||||
name: loop_refinement
|
||||
max-iterations: 3
|
||||
description: 循环优化绘图结果
|
||||
sub-agents: [agent_drawer, agent_reviewer]
|
||||
|
||||
# 新(graph)——循环体带退出条件与无进展检测
|
||||
agent-workflows:
|
||||
- type: graph
|
||||
version: "2"
|
||||
name: loop_refinement_v2
|
||||
entry: analyze
|
||||
nodes:
|
||||
- {id: analyze, kind: agent, agent: agent_analyst, output-key: analysis_result}
|
||||
- {id: draw, kind: agent, agent: agent_drawer, inputs: {analysis: "{analysis_result}"}, output-key: draft_diagram,
|
||||
retry: {max-attempts: 3, retry-on: [transient, timeout]}, timeout: 120s}
|
||||
- {id: review, kind: agent, agent: agent_reviewer, inputs: {draft: "{draft_diagram}"}, output-key: review_result}
|
||||
- {id: decide, kind: branch, when: "nodes.review.output.passed == true"}
|
||||
edges:
|
||||
- {from: analyze, to: draw}
|
||||
- {from: draw, to: review}
|
||||
- {from: review, to: decide}
|
||||
- {from: decide, to: END, when: "nodes.review.output.passed == true"}
|
||||
- {from: decide, to: draw, default: true}
|
||||
loop: {max-iterations: 3, state-key: draft_diagram}
|
||||
```
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **真并发**:3 个各耗时 2s 的分支,`concurrency=3` 时总耗时 < 2.5s;`legacy` 模式下 ≈ 6s(对照)。
|
||||
2. **循环生效**:`max-iterations: 3` 的 loop 实际执行 3 轮(事件中 3 组 `step.started/finished`)。
|
||||
3. **无进展退出**:构造"每轮输出相同"的假 Agent,第 3 轮检测到 `no_progress` 并退出,不跑满 20 轮。
|
||||
4. **节点重试**:第 2 个节点注入 2 次超时后成功,整图成功,`attempt=3` 出现在事件里。
|
||||
5. **补偿逆序**:5 节点图在第 4 节点失败,补偿按 3→2→1 执行(顺序断言),`wf_node_exec` 有 3 条 compensating 记录。
|
||||
6. **断点续跑**:在第 3 节点执行中 `kill -9`,重启 `POST /resume`,从第 3 节点继续,前 2 节点**不重复执行**(用计数器断言)。
|
||||
7. **版本不匹配拒绝续跑**:改 `graph_version` 后 resume 返回 `GRAPH_VERSION_MISMATCH`。
|
||||
8. `go test -race` 通过;100 次并发图执行无 goroutine 泄漏(`goleak`)。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **图构造单测**:配置 → 图的映射(旧 type 三种、非法边、环检测、入口不可达)。
|
||||
- **确定性执行测试**:fake Executor 按脚本返回,断言节点调用顺序、变量传递、事件序列。
|
||||
- **故障注入**:第 N 节点失败/超时/panic,验证重试、降级、补偿、整图状态。
|
||||
- **续跑测试**:用真实 MySQL 存检查点,在中间状态重启进程(`exec.Command` 起子进程)验证恢复。
|
||||
- **并发**:`goleak` + 1000 次图执行,断言无泄漏、预算不超。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 旧配置行为变化(loop 从 1 次变 N 次) | `execution-mode=legacy` 默认;release note 明确;灰度按 agent 切 |
|
||||
| 真并发导致下游限流 | 并发度默认 4 + 每工具令牌桶(P1);`partial-failure=all` 时快速取消 |
|
||||
| 补偿逻辑误删数据 | 补偿节点默认"只允许幂等、只允许反向操作"白名单;高危补偿需审批(P6) |
|
||||
| 检查点表写入放大 | 只在节点开始时写、结束更新,不逐 token 落;按 `run_id` 归档 |
|
||||
| expr 表达式注入 | 白名单环境 + 只读 AST 求值,禁止函数调用副作用 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(3 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-34 `max-iterations` 配置无效
|
||||
|
||||
**位置**:`normalizeDefaults` in `internal/app/config/loader.go`(补默认值)、`NewLoopAgent` in `internal/infrastructure/adk/adapter.go`(构建与分发)
|
||||
|
||||
**问题概述**:YAML 支持 `max-iterations`,loader 也会补默认值 3,但 `adk.Agent` 没有该字段,`NewLoopAgent` 不读取它,`runWithVars` 把 `loop` 和 `parallel` 一起丢给 `runFanOut`,导致 `max-iterations` 完全无效。
|
||||
|
||||
**影响**:用户以为配置了循环优化(如 drawio 的 `loop_refinement`),实际上只执行一次 fan-out,配置产生误导。
|
||||
|
||||
**修复方案**:按参考文档实现真正的 `runLoop`:
|
||||
|
||||
1. `adk.Agent` 增加 `maxIterations int`;
|
||||
2. `newWorkflowAgent` 按 kind 保存该值(或拆分构建方法);
|
||||
3. `runWithVars` 增加 `case "loop": return a.runLoop(...)`;
|
||||
4. `runLoop` 内按迭代次数执行并把上一轮结果写入 scope。
|
||||
|
||||
> **归属**:P5 | **状态**:✅ | **历史编号**:P1-2
|
||||
|
||||
### F-35 `parallel` 并非真正并发
|
||||
|
||||
**位置**:`runFanOut` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:`runFanOut` 是普通 for 循环,子 Agent 串行执行;`parallel` 命名与实际行为不符。
|
||||
|
||||
**影响**:并行工作流没有加速效果,多子 Agent 场景延迟线性叠加。
|
||||
|
||||
**修复方案**:`runFanOut` 改为 `goroutine + sync.WaitGroup + 有序结果切片`,并考虑子 Agent 的失败策略(快速失败 or 全部收集)。注意 `router`/`chatModel` 的并发安全性——当前 `OpenAIClient` 并发安全(只读字段),`MCPToolRouter` 需加锁(见 F-16)。
|
||||
|
||||
> **归属**:P5 | **状态**:✅ | **历史编号**:P1-3
|
||||
|
||||
### F-36 `AgentWorkflowNode.Apply` 递归实现
|
||||
|
||||
**位置**:`Apply` in `internal/domain/agent/service/armory/workflow/agent_workflow_node.go`
|
||||
|
||||
**问题概述**:用尾递归遍历 workflows,逻辑隐晦;虽然当前 `NewDynamicContext()` 每次全新、递归深度可控,但可读性差。
|
||||
|
||||
**影响**:维护成本,且未来若支持复用 context 会引入「从中间继续」的隐式语义。
|
||||
|
||||
**修复方案**:按参考文档改为 for 循环版本,并同步清理 `currentStepIndex`(若采用「循环版本一」)。改动量很小(单文件),行为等价。
|
||||
|
||||
> **归属**:P5 | **状态**:🟡 | **历史编号**:P2-1
|
||||
>
|
||||
> P5 图模型替换递归装配,需显式删除 `AgentWorkflowNode.Apply` 的递归实现
|
||||
365
docs/upgrade-plan/P6-工具治理.md
Normal file
365
docs/upgrade-plan/P6-工具治理.md
Normal file
@@ -0,0 +1,365 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P6 · 工具治理:可见范围、人工确认、沙箱与密钥 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.7 节
|
||||
> **本阶段收编缺陷**:F-37、F-38(共 2 条,明细见文末附录)
|
||||
> 上一阶段:[`P5`](P5-工作流编排.md) | 下一阶段:[`P7`](P7-可观测与评测.md)
|
||||
|
||||
|
||||
# 4.7 P6 · 工具治理:可见范围、人工确认、沙箱与密钥
|
||||
|
||||
## 目标
|
||||
|
||||
把"所有注册的工具对所有 Agent 全开放、密钥明文躺在 YAML 里、stdio 工具直接跑在宿主机"的现状,升级为**统一治理面**:谁能看见哪些工具、调用要不要人批、在什么环境里执行、密钥从哪来。对应面试官 B 的第三阶段(MCP / Worker / 执行环境安全 / Vault / 持久化记忆 / Session 生命周期)。
|
||||
|
||||
本阶段同时兑现 P1 留下的决策:Skill 从"仅注入 instruction"升级为"沙箱内可调用"(见 `P1-工具网关.md` 的 4.2.8 节),并移除 `skills.mode` 开关。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 问题 | 证据 |
|
||||
|---|---|
|
||||
| 无工具可见范围:`ChatModelNode` 把 `tool-mcp-list` 里的工具全部注册给模型 | `armory/chat_model_node.go` |
|
||||
| 无权限/审批:任何工具只要注册即可被调用 | `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go`、`ToolRouter` in `internal/domain/agent/ports/ports.go` |
|
||||
| 无沙箱:`stdio` MCP 通过 `exec.Command` 直接在宿主进程组里跑 | `ai/tools.go` |
|
||||
| 无密钥托管:API Key 来自 YAML + `.env` | `configs/agent/*.yaml`、`.env.example` 含疑似真实密钥 |
|
||||
| 无审计:谁在什么时候调了什么工具,无记录 | 全局 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.7.1 三层治理模型
|
||||
|
||||
```
|
||||
① 可见范围(Visibility):模型能不能"看到"这个工具
|
||||
↓
|
||||
② 调用策略(Policy):看到之后,这次调用 allow / deny / require_approval
|
||||
↓
|
||||
③ 执行隔离(Sandbox):批准之后,在哪个环境里、以什么权限执行
|
||||
```
|
||||
|
||||
三层职责分离的好处:可见范围是**静态配置**(启动时定),策略是**运行时判定**(按主体/参数/上下文),沙箱是**执行细节**(与策略解耦)。面试里能讲清这个分层,比笼统说"做了权限控制"高一个档次。
|
||||
|
||||
### 4.7.2 策略模型与求值
|
||||
|
||||
```go
|
||||
// internal/domain/security/policy.go
|
||||
type Effect string
|
||||
|
||||
const (
|
||||
EffectAllow Effect = "allow"
|
||||
EffectDeny Effect = "deny"
|
||||
EffectRequireApproval Effect = "require_approval"
|
||||
)
|
||||
|
||||
type Subject struct {
|
||||
TenantID string
|
||||
UserID string
|
||||
Roles []string
|
||||
AgentID string
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
Subject Subject
|
||||
Tool string
|
||||
Effect tool.SideEffect
|
||||
Args json.RawMessage
|
||||
RunID string
|
||||
SessionID string
|
||||
Context map[string]any // 时间、渠道、风险分等
|
||||
}
|
||||
|
||||
type Decision struct {
|
||||
Effect Effect
|
||||
RuleID string
|
||||
Reason string
|
||||
Approvers []string
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
type Engine interface {
|
||||
Evaluate(ctx context.Context, req Request) (Decision, error)
|
||||
}
|
||||
```
|
||||
|
||||
**求值顺序(必须确定)**:
|
||||
|
||||
```
|
||||
1. 显式 deny 规则(任一命中 → deny,短路)
|
||||
2. 显式 require_approval 规则(任一命中 → 需审批)
|
||||
3. 显式 allow 规则(任一命中 → allow)
|
||||
4. 默认策略:EffectRead → allow;Write/Destructive/External → require_approval(可配 deny)
|
||||
```
|
||||
|
||||
**"deny 优先"是安全默认**:规则有冲突时永远取最严格的。规则本身用 YAML 声明 + expr 条件:
|
||||
|
||||
```yaml
|
||||
# configs/policies.yaml
|
||||
version: 1
|
||||
defaults:
|
||||
read: allow
|
||||
write: require_approval
|
||||
destructive: deny
|
||||
external: require_approval
|
||||
|
||||
rules:
|
||||
- id: deny-pii-export
|
||||
match:
|
||||
tool: ["crm.export*", "user.dump*"]
|
||||
effect: deny
|
||||
reason: "禁止导出用户明细"
|
||||
|
||||
- id: auto-allow-internal-search
|
||||
match:
|
||||
tool: ["search.*", "kb.search"]
|
||||
effect: [read]
|
||||
effect: allow
|
||||
|
||||
- id: big-refund-needs-manager
|
||||
match:
|
||||
tool: ["payment.refund"]
|
||||
when: "args.amount > 1000"
|
||||
effect: require_approval
|
||||
approvers: [manager]
|
||||
ttl: 30m
|
||||
|
||||
- id: deny-off-hours-writes
|
||||
match:
|
||||
effect: [write, destructive]
|
||||
when: "now().Hour() < 9 || now().Hour() > 19"
|
||||
effect: deny
|
||||
reason: "非工作时段禁止写操作"
|
||||
```
|
||||
|
||||
`match.tool` 支持通配,`when` 是 expr(环境变量 `args` / `subject` / `now` / `context`)。规则编译期校验、求值 p99 < 1ms,结果可按 `(tool, effect, 参数哈希)` 缓存。
|
||||
|
||||
### 4.7.3 人工确认(HITL)流程
|
||||
|
||||
```
|
||||
工具调用 → Policy 判定 require_approval
|
||||
│
|
||||
├─ 写 agent_approval(status=pending, expires_at=now+ttl)
|
||||
├─ Run 状态 → waiting_approval
|
||||
├─ 发事件 approval.required(含工具名、参数摘要、风险说明)
|
||||
└─ 挂起(保存检查点,释放 goroutine)
|
||||
│
|
||||
├─ 用户批准 → 写 decision=approved → 唤醒 Run(从检查点续跑)→ 执行工具
|
||||
├─ 用户拒绝 → decision=rejected → 工具返回 "denied by user" → 模型改计划(L5 降级)
|
||||
└─ 超时 → decision=expired → 同拒绝,且记录指标
|
||||
```
|
||||
|
||||
```sql
|
||||
CREATE TABLE `agent_approval` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`step_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`user_id` VARCHAR(64) NOT NULL,
|
||||
`session_id` CHAR(26) NOT NULL DEFAULT '',
|
||||
`tool_name` VARCHAR(128) NOT NULL,
|
||||
`args_digest` CHAR(64) NOT NULL COMMENT '参数 sha256,避免存敏感原文',
|
||||
`args_preview` TEXT NULL COMMENT '脱敏后的参数预览',
|
||||
`risk` VARCHAR(16) NOT NULL DEFAULT 'medium',
|
||||
`status` VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT 'pending|approved|rejected|expired',
|
||||
`decided_by` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`decided_at` DATETIME(3) NULL,
|
||||
`reason` VARCHAR(512) NOT NULL DEFAULT '',
|
||||
`expires_at` DATETIME(3) NOT NULL,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_pending` (`tenant_id`,`status`,`expires_at`),
|
||||
KEY `idx_run` (`run_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
API:
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| GET | `/api/v1/approvals?status=pending` | 待办列表 |
|
||||
| POST | `/api/v1/approvals/{id}/approve` | `{reason, remember_for: session\|never}` |
|
||||
| POST | `/api/v1/approvals/{id}/reject` | `{reason}` |
|
||||
|
||||
**`remember_for: session`** 是体验关键:同一个会话内同类工具不再重复弹窗(存 `session` 级豁免表),否则用户会被审批疲劳拖死。
|
||||
|
||||
**挂起不能占资源**:Run 挂起时**不持有 goroutine**,靠检查点 + 事件驱动恢复。这是"waiting_approval 状态"存在的意义——如果用 `time.Sleep` 轮询,1000 个待审批请求就是 1000 个阻塞的 goroutine。
|
||||
|
||||
### 4.7.4 沙箱执行
|
||||
|
||||
```go
|
||||
// internal/domain/sandbox/ports.go
|
||||
type Spec struct {
|
||||
Image string
|
||||
Cmd []string
|
||||
Env map[string]string // 只允许白名单注入
|
||||
WorkDir string
|
||||
Timeout time.Duration
|
||||
MemoryMB int
|
||||
CPUShares int
|
||||
NetworkMode string // none | egress-proxy | host(仅 dev)
|
||||
ReadOnlyFS bool
|
||||
Mounts []Mount // 只读挂载输入,可写挂载输出
|
||||
}
|
||||
|
||||
type Runner interface {
|
||||
Run(ctx context.Context, spec Spec, stdin []byte) (Result, error)
|
||||
Kill(ctx context.Context, id string) error
|
||||
}
|
||||
```
|
||||
|
||||
三种实现,按风险分级选择:
|
||||
|
||||
| 实现 | 隔离级别 | 适用 | 依赖 |
|
||||
|---|---|---|---|
|
||||
| `local` | 无(仅超时+资源限制) | 本地开发 | — |
|
||||
| `docker` | 容器(只读根、无网、内存/CPU 限额、非 root) | stdio MCP、代码执行 | Docker |
|
||||
| `wasm`(wazero) | 进程内沙箱 | 纯计算型插件 | 无 |
|
||||
|
||||
默认:`stdio` MCP 与"执行代码"类工具走 `docker`;`local` 仅在 `env=local` 且显式开启时可用。
|
||||
|
||||
**出口网络**:`egress-proxy` 模式通过一个白名单代理(只允许配置的域名)出网,防止工具被诱导外发数据(prompt injection 的常见利用链)。
|
||||
|
||||
### 4.7.5 密钥托管(Vault)
|
||||
|
||||
```go
|
||||
// internal/domain/security/secret.go
|
||||
type Ref struct {
|
||||
Provider string // env | file | kms
|
||||
Path string // e.g. "agent/testAgent03/api-key"
|
||||
Key string
|
||||
}
|
||||
|
||||
type Resolver interface {
|
||||
Resolve(ctx context.Context, ref Ref) (string, error)
|
||||
}
|
||||
```
|
||||
|
||||
配置里不再写明文:
|
||||
|
||||
```yaml
|
||||
ai-api:
|
||||
base-url: ${BAIDU_BASE_URL}
|
||||
api-key: ${vault:agents/testAgent03#api_key}
|
||||
```
|
||||
|
||||
四条规则:
|
||||
|
||||
1. **懒解析**:只在真正调用时解析,不启动时全量解密(减少密钥驻留时间)。
|
||||
2. **绝不落日志**:日志/事件/trace 统一过 `Redact` 中间件,按正则与已知密钥值做掩码(`sk-****abcd`)。
|
||||
3. **可轮换**:`file` provider 监听文件变更热重载;KMS 按 TTL 缓存。
|
||||
4. **最小暴露**:只有需要工具的 Executor 能拿到解引用能力,模型永远看不到密钥。
|
||||
|
||||
### 4.7.6 MCP 生命周期治理
|
||||
|
||||
| 能力 | 说明 |
|
||||
|---|---|
|
||||
| Server 注册表 | 每个 MCP Server 一条记录:名称、传输、健康状态、工具清单、最后发现时间 |
|
||||
| 健康检查 | 每 30s `tools/list` 探活;连续 3 次失败标记 `unhealthy`,其工具从模型可见列表移除 |
|
||||
| 工具热刷新 | 定时(5min)或手动 `POST /admin/mcp/{name}/refresh` 重新发现 |
|
||||
| 熔断开关 | `POST /admin/mcp/{name}/disable` 立即摘除该 Server 的所有工具 |
|
||||
| 命名空间 | 工具名统一 `server.tool`,避免不同 Server 同名覆盖(修复 F-13) |
|
||||
| 速率限制 | 每 Server 独立令牌桶,防止一个 Server 拖垮全局 |
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/domain/security/policy.go` | Subject/Request/Decision/Engine |
|
||||
| 新增 | `internal/domain/security/approval.go` | Approval 聚合、状态机、TTL |
|
||||
| 新增 | `internal/domain/security/secret.go` | Ref/Resolver 端口 |
|
||||
| 新增 | `internal/domain/security/redact.go` | 脱敏规则 |
|
||||
| 新增 | `internal/domain/sandbox/ports.go` | Spec/Runner |
|
||||
| 新增 | `internal/domain/skill/exec.go` | Skill Runner(脚本执行契约,见 `P1-工具网关.md` 的 4.2.8 节) |
|
||||
| 新增 | `internal/infrastructure/skill/executor.go` | 把 Skill script 包装为 `tool.Spec`,执行体走 `sandbox.Runner` |
|
||||
| 新增 | `internal/infrastructure/security/policy_yaml.go` | 规则加载、expr 求值、缓存 |
|
||||
| 新增 | `internal/infrastructure/security/approval_repo.go` | approval 表读写 |
|
||||
| 新增 | `internal/infrastructure/security/vault_env.go` / `vault_file.go` | 两种 Resolver |
|
||||
| 新增 | `internal/infrastructure/sandbox/local.go` / `docker.go` / `wasm.go` | 三种 Runner |
|
||||
| 新增 | `internal/infrastructure/sandbox/egress.go` | 出口白名单代理 |
|
||||
| 新增 | `internal/domain/tool/approval_gate.go` | 网关第 5 步的实现 |
|
||||
| 新增 | `migrations/0004_security.up.sql` | agent_approval / agent_audit |
|
||||
| 修改 | `internal/domain/tool/gateway.go` | 接入 Policy 与 Approval |
|
||||
| 修改 | `internal/domain/agent/service/armory/chat_model_node.go` | 只注册 `Visibility=model` 的工具 |
|
||||
| 修改 | `internal/infrastructure/ai/tools.go` | stdio 执行改走 sandbox.Runner |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Policy/Vault/Sandbox |
|
||||
| 修改 | `internal/trigger/http/*` | approvals/admin 端点 + 鉴权中间件 |
|
||||
| 修改 | `configs/agent/*.yaml` | 密钥改 `${vault:...}`;工具加 `visibility` |
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. **可见范围**:给 Agent 配 `visibility: human_only` 的工具,模型请求中**不出现**该工具(抓包断言),但人工可以直接调用。
|
||||
2. **策略生效**:`deny` 规则命中时工具不执行(下游 mock 零调用),返回 `permission` 错误且 Run 继续(模型改计划)。
|
||||
3. **审批闭环**:写类工具触发 `waiting_approval`,批准后 3s 内继续执行;拒绝则模型收到 denied 并改口;超时自动拒绝。
|
||||
4. **挂起不占资源**:10 个并发待审批 Run,进程 goroutine 数不增长(对比基线 < +5)。
|
||||
5. **沙箱隔离**:stdio 工具尝试 `curl` 外网被拒;尝试写 `/etc` 失败;内存超 256MB 被杀;超时被杀。
|
||||
6. **密钥不泄露**:全量日志 grep 不到任何真实 key;`args_preview` 中敏感字段已掩码。
|
||||
7. **MCP 摘除**:disable 某 Server 后 1s 内其工具从模型可见列表消失,调用返回 `not_found` 而非挂起。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- 策略引擎:50 条规则冲突矩阵表驱动测试,断言"deny 优先"。
|
||||
- 审批:状态机单测 + 集成(真 DB + HTTP)。
|
||||
- 沙箱:用 alpine 镜像跑 `sh -c` 测试网络/写盘/资源三类限制;CI 标记 `-tags=sandbox`,无 Docker 时跳过。
|
||||
- 安全:`gosec` + 自写测试断言日志脱敏(构造假密钥写入日志,断言输出为掩码)。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 审批导致体验断崖 | `remember_for: session`;只对 write/destructive 默认审批;read 全自动 |
|
||||
| 沙箱性能开销(容器启动 ~300ms) | 预热容器池;纯计算走 wasm;非高风险工具走 local+超时 |
|
||||
| 策略规则写错导致全拒 | 启动时 dry-run 校验 + `policy.mode=shadow`(只记录不拦截)灰度 |
|
||||
| Vault 不可用导致全站不可用 | 本地缓存 + 启动时预热 + 降级为 env(告警) |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(2 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-37 `stdio` / `local` 传输运行时不可执行
|
||||
|
||||
**位置**:`validateMCPConfig` in `internal/infrastructure/ai/tools.go`(构建)、`CallTool` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||||
|
||||
**问题概述**:配置层支持 stdio/local,`buildStdioMCPTools` 会构建 `MCPTool`,但运行时 `CallTool` 只处理 `clients` 里的 SSE 客户端,stdio/local 一律报「transport not supported in runtime」/「not callable」。此外 local 传输是更彻底的桩:`buildLocalMCPTools`(`validateMCPConfig` in `internal/infrastructure/ai/tools.go`)只认识硬编码的 `echoLocalTool`,其他名字直接报 `local mcp tool %q is not registered in go`,而即便是 `echoLocalTool` 也没注册到 `clients`,调用时同样落到「transport not supported」。
|
||||
|
||||
**影响**:`stdio` 与 `local` 是「能配置不能跑」的假功能;文档(CLAUDE.md/README)却宣称支持三种传输,存在误导。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
- 要么实现 stdio(启动子进程 + JSON-RPC over stdin/stdout)与 local(内置 Go 工具注册表)执行器;
|
||||
- 要么在配置校验阶段直接拒绝 stdio/local,并同步修正文档,避免用户踩坑。
|
||||
|
||||
---
|
||||
|
||||
> **归属**:P6 | **状态**:✅ | **历史编号**:P1-10
|
||||
>
|
||||
> stdio MCP 走 docker 沙箱;local 内置工具注册表在 P6 一并补齐
|
||||
|
||||
### F-38 MCP 客户端连接状态没有「代际」隔离,旧连接的错误会污染新连接
|
||||
|
||||
**位置**:`internal/infrastructure/ai/mcp_sse_client.go`(`pending` / `streamErr` 为共享字段,`signalStreamErr` 广播)
|
||||
|
||||
```go
|
||||
func (c *MCPSSEClient) signalStreamErr(err error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
select {
|
||||
case c.streamErr <- err:
|
||||
default:
|
||||
}
|
||||
for id, ch := range c.pending { // <- 可能已经是「新一代」的 pending
|
||||
ch <- mustJSON(...)
|
||||
close(ch)
|
||||
delete(c.pending, id)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:`pending`、`streamErr`、`postURL` 都是客户端上的可变字段,没有按连接代际隔离。场景:连接 A 断开并触发重连(`shutdown` + 新 `ensureStarted` 生成新 `pending`/`streamErr`),但旧 `readLoop(A)` 退出前仍会执行 `signalStreamErr`,此时它遍历/写入的已经是新一代的 `pending`/`streamErr`,从而把「A 已断开」的错误广播给正在等 B 的请求。
|
||||
|
||||
**影响**:偶发的「刚连上却收到 stream closed / 请求失败」,难以复现和排查;并发重连时概率上升。
|
||||
|
||||
**修复方案**:为每次启动引入 `generation uint64`,把 `pending`/`streamErr`/`cancelFn` 收进 `connState` 结构体,`readLoop` 闭包捕获自己那一代,`signalStreamErr` 只操作自己那一代;或用 `context` 取消 + 带代际的 channel。
|
||||
|
||||
> **归属**:P6 | **状态**:🟡 | **历史编号**:P2-21
|
||||
>
|
||||
> P6 的 `connState` 代际隔离重构会覆盖,需点名
|
||||
357
docs/upgrade-plan/P7-可观测与评测.md
Normal file
357
docs/upgrade-plan/P7-可观测与评测.md
Normal file
@@ -0,0 +1,357 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P7 · 可观测、断言与评测:让「跑偏」可被发现 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.8 节
|
||||
> **本阶段收编缺陷**:F-39、F-40、F-41(共 3 条,明细见文末附录)
|
||||
> 上一阶段:[`P6`](P6-工具治理.md) | 下一阶段:[`P8`](P8-生产化.md)
|
||||
|
||||
|
||||
# 4.8 P7 · 可观测、断言与评测:让"跑偏"可被发现
|
||||
|
||||
## 目标
|
||||
|
||||
建立"**看得见 → 查得到 → 测得准 → 改得掉**"的闭环:全链路 trace、事件日志重放、关键节点断言、Bad Case 归集、评测集回归、内容安全。这是面试官 A "日志重放机制、关键节点断言、Bad Case 闭环复盘"三件套的完整落地。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 问题 | 证据 |
|
||||
|---|---|
|
||||
| 日志是 `fmt.Printf`,无 run_id/step_id | `(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go`(`myTestPlugin`) |
|
||||
| 无 trace,跨 LLM/工具调用无法串联 | 全局 |
|
||||
| 无断言,模型答非所问无人发现 | 全局 |
|
||||
| 无评测,改动靠"感觉" | 零测试 |
|
||||
| 无内容安全,违规输出直接返回 | 全局 |
|
||||
| 无成本度量 | 全局 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.8.1 Trace 模型(OpenTelemetry)
|
||||
|
||||
| Span | 关键属性 |
|
||||
|---|---|
|
||||
| `agent.run` | `run.id`, `session.id`, `agent.id`, `tenant.id`, `run.status`, `run.steps`, `tokens.total` |
|
||||
| `agent.step` | `step.kind`, `step.name`, `step.attempt`, `step.duration_ms` |
|
||||
| `llm.call` | `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `output_tokens`, `cache.read_tokens` |
|
||||
| `tool.call` | `tool.name`, `tool.effect`, `tool.attempt`, `tool.result_bytes`, `tool.degraded_level` |
|
||||
| `memory.assemble` | `memory.tokens`, `memory.breakdown.*`, `memory.compacted` |
|
||||
| `memory.retrieve` | `memory.hits`, `memory.top_score`, `memory.latency_ms` |
|
||||
| `policy.evaluate` | `policy.rule_id`, `policy.effect` |
|
||||
|
||||
采样策略:默认 `parentbased_traceidratio=0.1`;**出错与超预算的 Run 强制 100% 采样**(尾部采样需 collector,简化为"错误路径升级采样率")。
|
||||
|
||||
### 4.8.2 结构化日志规范
|
||||
|
||||
```go
|
||||
logger.Info("tool call failed",
|
||||
zap.String("event", "tool.call.failed"),
|
||||
zap.String("run_id", rc.Run.ID),
|
||||
zap.String("step_id", step.ID),
|
||||
zap.String("session_id", rc.Run.SessionID),
|
||||
zap.String("tenant_id", rc.Run.TenantID),
|
||||
zap.String("tool", call.Name),
|
||||
zap.Int("attempt", attempt),
|
||||
zap.String("error_class", failure.Class),
|
||||
zap.Duration("duration", elapsed),
|
||||
)
|
||||
```
|
||||
|
||||
**统一字段**(漏一个就没法关联):`event`、`run_id`、`step_id`、`session_id`、`tenant_id`、`agent_id`。用 `zap` 的 `With()` 在 Run 入口一次性挂上,后续全继承。
|
||||
|
||||
**禁止**:日志里出现 prompt 全文、工具原始返回、任何密钥。需要时用 `_debug=true` 开关 + 脱敏。
|
||||
|
||||
### 4.8.3 关键节点断言(Assertion)
|
||||
|
||||
```go
|
||||
// internal/domain/evals/assertion.go
|
||||
type Phase string // pre_llm | post_tool | post_step | post_run
|
||||
|
||||
type Assertion interface {
|
||||
Name() string
|
||||
Phase() Phase
|
||||
Check(ctx context.Context, env *Env) error
|
||||
}
|
||||
|
||||
type Env struct {
|
||||
Run *runtime.Run
|
||||
Step *runtime.Step
|
||||
Input string
|
||||
Output string
|
||||
Tools []ToolObservation
|
||||
Context contextasm.Bundle
|
||||
}
|
||||
```
|
||||
|
||||
内置断言(配置开关,默认只告警不阻断):
|
||||
|
||||
| 断言 | 阶段 | 规则 | 失败后果 |
|
||||
|---|---|---|---|
|
||||
| `non_empty_output` | post_run | 最终答案非空且 ≥ 10 字符 | 阻断,返回兜底话术 |
|
||||
| `budget_respected` | post_run | steps ≤ max,tokens ≤ max | 告警(说明预算配小了) |
|
||||
| `tool_result_valid` | post_tool | 符合 OutputSchema | 告警 + 标记 |
|
||||
| `no_policy_violation` | post_tool | 未调用被拒工具 | 阻断 |
|
||||
| `must_include` | post_run | 必须包含配置的关键词/事实 | 阻断(可配) |
|
||||
| `must_exclude` | post_run | 不得包含违禁内容 | 阻断 |
|
||||
| `citation_present` | post_run | 知识库问答必须带引用 | 告警 |
|
||||
| `no_tool_loop` | post_step | 同一工具同参数连续 3 次 | 阻断(防死循环,P0 预算的第二道保险) |
|
||||
| `latency_budget` | post_run | p95 超过阈值 | 告警 |
|
||||
|
||||
```yaml
|
||||
# configs/agents/testAgent03.assertions.yaml
|
||||
assertions:
|
||||
- {name: non_empty_output, action: block}
|
||||
- {name: no_tool_loop, action: block}
|
||||
- {name: must_exclude, patterns: ["<script>", "SELECT * FROM"], action: block}
|
||||
- {name: must_include, keywords: ["小林"], action: warn}
|
||||
```
|
||||
|
||||
**"关键节点断言"的本质**:把"事后人工发现"变成"运行时机器拦截"。断言失败不是崩溃,而是产生一条 `assertion.failed` 事件 +(可选)一条 Bad Case 记录。
|
||||
|
||||
### 4.8.4 确定性重放(record & replay)
|
||||
|
||||
只靠事件日志能还原"发生了什么",但还原不了"模型当时为什么这么答"。所以要记录 LLM 往返:
|
||||
|
||||
```sql
|
||||
CREATE TABLE `agent_llm_record` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`step_id` CHAR(26) NOT NULL,
|
||||
`call_index` INT NOT NULL,
|
||||
`prompt_hash` CHAR(64) NOT NULL COMMENT 'messages+tools 的 sha256',
|
||||
`request` MEDIUMBLOB NULL COMMENT '压缩后的请求(可脱敏)',
|
||||
`response` MEDIUMBLOB NULL,
|
||||
`model` VARCHAR(64) NOT NULL,
|
||||
`tokens_in` INT NOT NULL DEFAULT 0,
|
||||
`tokens_out` INT NOT NULL DEFAULT 0,
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_run_call` (`run_id`,`call_index`),
|
||||
KEY `idx_prompt_hash` (`prompt_hash`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
**重放器**:`cmd/replay -run <id> -mode deterministic` 时,`ChatModel` 被替换为 `recordedModel`:按 `call_index` 顺序返回录制响应,**不发起真实请求**。
|
||||
|
||||
用途(三个都很实用):
|
||||
|
||||
1. **回归**:改了 prompt/装配逻辑,重放同一 run,输出应一致(或差异可解释)。
|
||||
2. **调试**:线上出问题,本地重放 30 秒复现,不需要重新烧 token。
|
||||
3. **评测**:录一批真实轨迹作为评测基线,避免"评测结果随机"。
|
||||
|
||||
**成本控制**:只录 `run.status != succeeded` 或采样 5% 的成功 run;请求体压缩(zstd)+ 30 天 TTL。
|
||||
|
||||
### 4.8.5 Bad Case 闭环
|
||||
|
||||
```sql
|
||||
CREATE TABLE `agent_badcase` (
|
||||
`id` CHAR(26) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`tenant_id` VARCHAR(64) NOT NULL DEFAULT 'default',
|
||||
`agent_id` VARCHAR(64) NOT NULL,
|
||||
`symptom` VARCHAR(64) NOT NULL COMMENT 'wrong_answer|tool_error|timeout|loop|policy|format|hallucination',
|
||||
`severity` TINYINT NOT NULL DEFAULT 3,
|
||||
`root_cause` VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'prompt|context|tool|model|config|code',
|
||||
`detail` TEXT NULL,
|
||||
`fix_commit` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`regression_case` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '关联的评测用例 ID',
|
||||
`status` VARCHAR(16) NOT NULL DEFAULT 'open' COMMENT 'open|analyzing|fixed|wontfix',
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
`closed_at` DATETIME(3) NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_status` (`status`,`severity`),
|
||||
KEY `idx_agent` (`agent_id`,`created_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
**闭环规则(写进团队流程,不只是建表)**:
|
||||
|
||||
1. 每个断言失败 / 用户点踩 / 线上 5xx 自动生成或手工登记 Bad Case。
|
||||
2. 定位 `root_cause`(五选一),**不允许填"模型不稳定"**。
|
||||
3. 修复必须附一条评测用例(`regression_case` 必填),否则不许关单。
|
||||
4. 每周看板:新增/关闭数、按 `root_cause` 分布、Top3 高频问题。
|
||||
|
||||
### 4.8.6 评测集与 CI 门禁
|
||||
|
||||
```yaml
|
||||
# testdata/evals/drawio/basic.yaml
|
||||
id: drawio-basic-001
|
||||
agent: drawIoAgent
|
||||
turns:
|
||||
- "画一个用户登录流程图"
|
||||
expect:
|
||||
task_success: true
|
||||
max_steps: 12
|
||||
max_tokens: 20000
|
||||
must_include: ["登录", "验证"]
|
||||
must_exclude: ["无法完成"]
|
||||
tool_sequence_contains: ["skill_drawio"]
|
||||
max_latency_ms: 60000
|
||||
```
|
||||
|
||||
```go
|
||||
// internal/domain/evals/runner.go
|
||||
type Case struct {
|
||||
ID, Agent string
|
||||
Turns []string
|
||||
Expect Expectation
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
Total, Passed int
|
||||
PassRate float64
|
||||
AvgSteps float64
|
||||
AvgTokens int
|
||||
P95Latency time.Duration
|
||||
Failures []CaseFailure
|
||||
}
|
||||
```
|
||||
|
||||
CI 四道门:
|
||||
|
||||
| 门 | 触发 | 失败处理 |
|
||||
|---|---|---|
|
||||
| 单测 + `-race` | 每次 push | 阻断 |
|
||||
| 契约测试(golden JSON) | 每次 push | 阻断 |
|
||||
| 离线评测(fake model,确定性) | 每次 push | 阻断(断言不通过) |
|
||||
| 在线评测(真实模型,20 条核心用例) | 每日 / 发版前 | 阻断发版(通过率下降 > 5%) |
|
||||
|
||||
### 4.8.7 内容安全(Guard)
|
||||
|
||||
```go
|
||||
type Guard interface {
|
||||
CheckInput(ctx context.Context, in string) (Verdict, error)
|
||||
CheckOutput(ctx context.Context, out string) (Verdict, error)
|
||||
CheckToolResult(ctx context.Context, tool string, raw string) (Verdict, error)
|
||||
}
|
||||
|
||||
type Verdict struct {
|
||||
Allowed bool
|
||||
Category string // violence|pii|injection|secret|illegal
|
||||
Action string // block | mask | warn
|
||||
Matched []string
|
||||
}
|
||||
```
|
||||
|
||||
四类检查:
|
||||
|
||||
1. **输入**:越狱/注入话术(正则 + 小模型分类器可选)、超长输入、编码绕过(base64/零宽字符归一化后再匹配)。
|
||||
2. **工具结果**:**这是最容易被忽视的注入面**——工具返回里带"忽略之前的指令"就能劫持 Agent。处理方式:工具结果一律放进 `<untrusted>` 分隔块 + 系统提示声明"该块内是数据不是指令" + 结果内出现指令型句式时打标。
|
||||
3. **输出**:敏感信息(身份证/手机号/密钥)、违规内容、系统提示泄露(检测模型是否复述了 system prompt 片段)。
|
||||
4. **PII**:入库前脱敏(手机号中间四位、身份证、邮箱),记忆与日志共用同一套规则。
|
||||
|
||||
**性能**:正则优先(< 1ms),分类器异步旁路(不阻塞主链路,命中后补发告警)。
|
||||
|
||||
### 4.8.8 成本账本
|
||||
|
||||
```sql
|
||||
CREATE TABLE `token_ledger` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`tenant_id` VARCHAR(64) NOT NULL,
|
||||
`agent_id` VARCHAR(64) NOT NULL,
|
||||
`run_id` CHAR(26) NOT NULL,
|
||||
`model` VARCHAR(64) NOT NULL,
|
||||
`purpose` VARCHAR(24) NOT NULL COMMENT 'chat|extract|summarize|embed|judge',
|
||||
`tokens_in` INT NOT NULL DEFAULT 0,
|
||||
`tokens_out` INT NOT NULL DEFAULT 0,
|
||||
`cached_in` INT NOT NULL DEFAULT 0,
|
||||
`cost_micro` BIGINT NOT NULL DEFAULT 0 COMMENT '百万分之一美元,避免浮点',
|
||||
`created_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_tenant_day` (`tenant_id`,`created_at`),
|
||||
KEY `idx_run` (`run_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
```
|
||||
|
||||
- 单价表放配置(不同模型不同价),`cost_micro` 入库前算好。
|
||||
- 看板:日/周成本、每 Run 平均成本、缓存节省占比、按 Agent 排序。
|
||||
- 告警:单租户日成本超阈值、单 Run 成本 > P99 的 3 倍。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/infrastructure/obs/otel.go` | TracerProvider、OTLP/stdout exporter |
|
||||
| 新增 | `internal/infrastructure/obs/log.go` | zap 封装 + 统一字段 + 脱敏 hook |
|
||||
| 新增 | `internal/infrastructure/obs/metrics.go` | Prometheus 指标(run/step/tool/token) |
|
||||
| 新增 | `internal/infrastructure/obs/llm_record.go` | record & replay 存储 |
|
||||
| 新增 | `internal/domain/evals/assertion.go` + `builtin.go` | 断言框架与内置断言 |
|
||||
| 新增 | `internal/domain/evals/runner.go` | 评测执行与报告 |
|
||||
| 新增 | `internal/domain/evals/report.go` | Markdown/JSON 报告 |
|
||||
| 新增 | `internal/domain/guard/guard.go` + `rules.go` + `pii.go` | 内容安全 |
|
||||
| 新增 | `internal/infrastructure/persistence/mysql/badcase_repo.go` / `ledger_repo.go` / `llm_record_repo.go` | 三张表 |
|
||||
| 新增 | `migrations/0005_observability.up.sql` | 上述 DDL |
|
||||
| 修改 | `internal/domain/runtime/context.go` | Step 内自动开 span、挂日志字段 |
|
||||
| 修改 | `internal/infrastructure/adk/*.go` | 所有 LLM/工具调用埋点 |
|
||||
| 修改 | `internal/trigger/http/*` | 追踪中间件、错误 metric |
|
||||
| 修改 | `cmd/replay/main.go` | deterministic 模式 |
|
||||
| 修改 | `.github/workflows/ci.yml` | 四道门 |
|
||||
| 修改 | `internal/infrastructure/logging/logger.go` | 可配置级别/采样/输出 |
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. 给定 `run_id`,能在 trace 中看到完整 span 树(≥ 8 个 span),跨 LLM/工具/记忆调用。
|
||||
2. 任意一次失败 Run,`cmd/replay -mode deterministic` 能在本地复现同样输出,**零真实 API 调用**。
|
||||
3. 断言:构造"空输出"与"死循环"两个用例,运行时被拦截并产生 Bad Case。
|
||||
4. 评测:20 条核心用例,本地跑 3 次通过率方差 < 5%(确定性由 fake model 保证)。
|
||||
5. 安全:10 个注入样本(含工具结果注入),拦截率 ≥ 9/10;PII 输出被掩码。
|
||||
6. 成本:任意 Run 可查到 `cost_micro`,日汇总误差 < 2%(对比账单)。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 埋点影响性能 | span 默认采样 10%;日志异步;基准测试保证 p95 增幅 < 3% |
|
||||
| 记录 LLM 往返带来存储与隐私风险 | 压缩 + 30 天 TTL + 脱敏 + 按租户隔离;可只记 hash |
|
||||
| 断言误杀 | 默认 `warn`,灰度 `block`;每条断言可单独开关 |
|
||||
| 评测集过拟合 | 保留 30% 未公开 holdout;定期补充真实 Bad Case |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(3 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-39 SSE 无心跳、未处理客户端断连
|
||||
|
||||
**位置**:`chatStream` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
**问题概述**:`chatStream` 只是 range outputs 并 flush,未发送心跳注释行,也未监听 `c.Request.Context().Done()`。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 反向代理(Nginx/网关)可能因长时间无数据断开连接;
|
||||
- 客户端断开后后端仍继续生成,浪费模型调用。
|
||||
|
||||
**修复方案**:启动 `time.Ticker` 定期写 `: ping\n\n`;监听 `c.Request.Context().Done()` 并取消下游(依赖 F-02)。
|
||||
|
||||
> **归属**:P7 | **状态**:✅ | **历史编号**:P2-13
|
||||
>
|
||||
> 附录 B 的 15s heartbeat
|
||||
|
||||
### F-40 日志体系不完善
|
||||
|
||||
**位置**:`internal/infrastructure/logging/logger.go`、`bootstrap.newRouter`、`newMyTestPlugin` in `internal/infrastructure/adk/adapter.go`、`main` in `cmd/server/main.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- 日志级别/格式/输出目标不可配;
|
||||
- Gin 访问日志用 `gin.Logger()`,未接 zap;
|
||||
- `myTestPlugin`、`adkRunnerPlugin` 用 `fmt.Printf`,绕过日志系统;
|
||||
- `logger.Fatal` 内部 `os.Exit(1)` 会跳过 `defer logger.Sync()`。
|
||||
|
||||
**影响**:生产环境日志无法集中采集/检索;关键上下文缺失;`Sync` 未执行可能丢最后几条日志。
|
||||
|
||||
**修复方案**:按参考文档把 `logging.New(env, cfg)` 扩展为可配置(level/encoding/outputPaths);新增 `ZapLogger(logger)` 中间件替换 `gin.Logger()`;插件注入 `*zap.Logger`;`main` 中用 `logger.Error + return` 或显式 `Sync` 后再 `os.Exit`。
|
||||
|
||||
> **归属**:P7 | **状态**:✅ | **历史编号**:P2-15
|
||||
|
||||
### F-41 无 run_id / trace_id,日志无法关联一次执行
|
||||
|
||||
**位置**:`(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go`
|
||||
|
||||
**问题概述**:插件与运行时的日志只有 `fmt.Printf` 的零散输出,没有 run_id、step_id、session_id,也没有 trace 上下文;一次失败执行在日志里无法还原成一条链路。
|
||||
|
||||
**影响**:线上问题只能靠时间戳猜;多用户并发时日志互相穿插,无法归因。
|
||||
|
||||
**修复方案**:P7 统一 6 个必填日志字段(event/run_id/step_id/session_id/tenant_id/agent_id)+ 7 类 span;P0 的 `runtime.Event` 已经带 run_id/step_id,P7 只需把它接到 zap 与 OTel。
|
||||
|
||||
> **归属**:P7 | **状态**:✅
|
||||
655
docs/upgrade-plan/P8-生产化.md
Normal file
655
docs/upgrade-plan/P8-生产化.md
Normal file
@@ -0,0 +1,655 @@
|
||||
> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md)
|
||||
> **阶段**:P8 · 生产化:从「能跑」到「敢上线」 | **预估**:6–8 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.9 节
|
||||
> **本阶段收编缺陷**:F-42、F-43、F-44、F-45、F-46、F-47、F-48、F-49、F-50、F-51、F-52、F-53、F-54、F-55、F-56、F-57、F-58、F-59、F-60、F-61、F-62、F-63、F-64、F-65、F-66(共 25 条,明细见文末附录)
|
||||
> 上一阶段:[`P7`](P7-可观测与评测.md)
|
||||
|
||||
|
||||
# 4.9 P8 · 生产化:从"能跑"到"敢上线"
|
||||
|
||||
## 目标
|
||||
|
||||
补齐上线必需但"不出彩"的能力:鉴权、限流、优雅停机、健康检查、迁移、配置强校验、安全加固、部署形态。
|
||||
|
||||
## 当前问题
|
||||
|
||||
| 问题 | 证据 |
|
||||
|---|---|
|
||||
| 无鉴权:任何人可调 `/chat` | `trigger/http/agent_handler.go` |
|
||||
| CORS 反射任意 Origin + `Allow-Credentials: true` | `corsMiddleware` in `internal/app/bootstrap/bootstrap.go`(F-42) |
|
||||
| 无优雅停机:`kill` 即丢请求、MCP 连接不复位 | `(*Engine).Run` in `internal/app/bootstrap/bootstrap.go`(F-45) |
|
||||
| `writeError(c, nil)` 会 panic | `writeError` in `internal/trigger/http/agent_handler.go`(F-44) |
|
||||
| `.env.example` 含疑似真实密钥与推广链接 | `.env.example` |
|
||||
| 配置校验弱:`application.yaml` 不做 `${VAR}` 展开 | `app/config/application.go` |
|
||||
| 无健康检查、无指标端点 | 全局 |
|
||||
| 无迁移工具 | 全局 |
|
||||
|
||||
## 设计
|
||||
|
||||
### 4.9.1 鉴权与租户
|
||||
|
||||
```go
|
||||
// internal/trigger/http/middleware/auth.go
|
||||
type Principal struct {
|
||||
TenantID string
|
||||
UserID string
|
||||
Roles []string
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
func Authenticate(cfg AuthConfig) gin.HandlerFunc
|
||||
```
|
||||
|
||||
| 模式 | 用途 | 说明 |
|
||||
|---|---|---|
|
||||
| `api_key` | 服务间调用 | `Authorization: Bearer <key>`,key 存 DB(hash),带租户与 scope |
|
||||
| `jwt` | 终端用户 | HS256/RS256,claim 含 `tenant_id`/`sub`/`roles` |
|
||||
| `none` | 本地开发 | 仅 `env=local` 允许,启动打 WARN |
|
||||
|
||||
租户来源**只从凭证取**,绝不信任请求头(当前若加 `X-Tenant-ID` 必须仅在 `env=local` 生效)。
|
||||
|
||||
### 4.9.2 限流
|
||||
|
||||
| 维度 | Key | 默认 |
|
||||
|---|---|---|
|
||||
| 租户级 QPS | `rl:t:{tenant}` | 50 |
|
||||
| 用户级并发 Run | `rl:u:{tenant}:{user}` | 4 |
|
||||
| Agent 级 QPS | `rl:a:{tenant}:{agent}` | 20 |
|
||||
| 模型 token/分钟 | `rl:tok:{tenant}` | 按套餐 |
|
||||
|
||||
算法:Redis 令牌桶(Lua 脚本保证原子),Redis 不可用时退化为进程内 `golang.org/x/time/rate` 并降额。
|
||||
|
||||
超额返回 `429 + Retry-After`,并计入 `token_ledger` 的"被限流"指标。
|
||||
|
||||
### 4.9.3 优雅停机
|
||||
|
||||
```go
|
||||
func (e *Engine) Run(ctx context.Context) error {
|
||||
srv := &http.Server{
|
||||
Addr: e.cfg.Server.Addr,
|
||||
Handler: e.Router,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- srv.ListenAndServe() }()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
// 1. 停止接收新请求
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), e.cfg.Server.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil { ... }
|
||||
|
||||
// 2. 取消所有在途 Run(触发 P0 的 run.canceled + 检查点)
|
||||
e.runtime.CancelAll(shutdownCtx)
|
||||
|
||||
// 3. 关闭顺序:worker → MCP 客户端 → Redis → MySQL
|
||||
return e.closeAll(shutdownCtx)
|
||||
}
|
||||
```
|
||||
|
||||
关闭顺序很重要:**先停入口,再停工作,最后停存储**。反了会出现"消息已落库但 run 状态没更新"。
|
||||
|
||||
`main.go` 接 `signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)`。
|
||||
|
||||
### 4.9.4 健康检查与指标
|
||||
|
||||
| 端点 | 语义 |
|
||||
|---|---|
|
||||
| `GET /healthz` | 进程存活(永远 200) |
|
||||
| `GET /readyz` | 依赖就绪(DB/Redis/至少一个 MCP 可用),未就绪 503 |
|
||||
| `GET /metrics` | Prometheus 指标(内网/鉴权) |
|
||||
|
||||
关键指标:`agent_run_total{status}`、`agent_run_duration_seconds`、`tool_call_total{tool,status}`、`llm_tokens_total{model,type}`、`memory_hit_ratio`、`approval_pending`、`budget_exhausted_total`。
|
||||
|
||||
### 4.9.5 配置强校验与迁移
|
||||
|
||||
- `application.yaml` 支持 `${VAR}` / `${VAR:-default}`(复用 loader 已有实现,抽成公共包)。
|
||||
- 启动时 `--strict-config`:未知字段、缺失必填、引用不存在(子 Agent/工具/策略/模型)一律启动失败,并打印可定位的错误路径(`agents.agent_drawer.inputs.analysis -> 未定义的 output_key`)。
|
||||
- 迁移:`cmd/migrate` + `golang-migrate`,启动时只校验 `schema_version` 是否与代码期望一致,**不在启动时自动改表**(避免多实例并发迁移)。
|
||||
|
||||
### 4.9.6 安全加固清单
|
||||
|
||||
| 项 | 处理 |
|
||||
|---|---|
|
||||
| CORS | 白名单 Origin 配置;`Allow-Credentials` 仅对白名单生效;默认关闭通配 |
|
||||
| 请求体大小 | `http.MaxBytesReader` 默认 1MB(附件另走上传端点) |
|
||||
| 超时 | ReadHeader 5s、Write 由 Run 预算控制、Idle 120s |
|
||||
| 错误回显 | 生产只返回 code + 通用信息,详细错误进日志(含 `trace_id` 供用户报障) |
|
||||
| 依赖扫描 | `govulncheck` + `gosec` 进 CI |
|
||||
| 密钥 | `.env.example` 只留占位;仓库加 `gitleaks` pre-commit |
|
||||
| 越权 | P2 的 `Authorize` 全覆盖;新增端点默认要求鉴权 |
|
||||
| 日志 | 脱敏中间件(P6 的 `Redact`) |
|
||||
|
||||
### 4.9.7 部署形态
|
||||
|
||||
```yaml
|
||||
# docker-compose 增加 app 服务(生产用 K8s)
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
environment:
|
||||
APP_CONFIG: /etc/agent/application.yaml
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:8091/readyz"]
|
||||
interval: 10s
|
||||
deploy:
|
||||
replicas: 2
|
||||
resources: { limits: { cpus: "2", memory: 2G } }
|
||||
```
|
||||
|
||||
多实例注意:会话缓存(Redis 共享)、`FOR UPDATE SKIP LOCKED` 的 worker(天然多实例安全)、审批与挂起状态在 DB(无粘性会话需求)、限流在 Redis(全局生效)。
|
||||
|
||||
## 涉及的代码模块
|
||||
|
||||
| 类型 | 文件 | 改动要点 |
|
||||
|---|---|---|
|
||||
| 新增 | `internal/trigger/http/middleware/auth.go` | API Key / JWT / none |
|
||||
| 新增 | `internal/trigger/http/middleware/ratelimit.go` | 令牌桶 + Redis Lua |
|
||||
| 新增 | `internal/trigger/http/middleware/recover.go` | panic 恢复 + 统一错误 |
|
||||
| 新增 | `internal/trigger/http/middleware/trace.go` | trace_id 注入与回传 |
|
||||
| 新增 | `internal/trigger/http/health.go` | healthz/readyz/metrics |
|
||||
| 新增 | `internal/app/config/expand.go` | `${VAR}` 展开(从 loader 抽出复用) |
|
||||
| 新增 | `internal/app/config/strict.go` | 严格校验与错误路径 |
|
||||
| 新增 | `internal/domain/security/auth.go` | Principal / Token 校验端口 |
|
||||
| 新增 | `cmd/migrate/main.go` | 迁移 CLI |
|
||||
| 修改 | `cmd/server/main.go` | signal.NotifyContext + 优雅停机 |
|
||||
| 修改 | `internal/app/bootstrap/bootstrap.go` | http.Server、中间件链、关闭顺序、CORS 白名单 |
|
||||
| 修改 | `internal/trigger/http/agent_handler.go` | 鉴权、参数校验、错误码映射、修 `writeError(nil)` |
|
||||
| 修改 | `internal/api/response/response.go` | 统一错误结构(code/message/trace_id) |
|
||||
| 修改 | `.env.example` | 去真实密钥 |
|
||||
| 修改 | `deployments/docker-compose.yml` | 修 redis networks 引用、加 app 服务 |
|
||||
| 修改 | `Dockerfile`(新增) | 多阶段构建、非 root、只读根 |
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. 无凭证请求返回 401;跨租户访问返回 403;`env=local` 下 `auth.mode=none` 可用。
|
||||
2. 限流:单租户 100 QPS 打 10s,通过率≈配置值,超额 429 且带 `Retry-After`。
|
||||
3. 优雅停机:`kill -TERM` 时在途 20 个请求全部正常返回(无 502),进程 30s 内退出。
|
||||
4. `writeError(c, nil)` 构造用例不再 panic(有单测)。
|
||||
5. CORS:非白名单 Origin 预检被拒;白名单通过。
|
||||
6. `--strict-config` 下故意写错一个字段,启动失败并打印精确路径。
|
||||
7. `readyz` 在 MySQL 断开时返回 503,恢复后 10s 内转 200。
|
||||
8. 压测:2 副本各 2C2G,200 QPS 持续 5min,p95 < 2s(不含 LLM 耗时),错误率 < 0.1%。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 开启鉴权导致现有前端 401 | 前端与后端同步发版;`auth.mode=api_key` 只对 `/api/v1/**` 生效,静态资源豁免 |
|
||||
| 严格配置校验阻断老配置 | 提供 `--migrate-config` 自动补默认值;`strict` 默认关闭一个版本 |
|
||||
| 限流误伤内部批处理 | 内部调用走独立 API Key + 更高配额 |
|
||||
| 优雅停机时间不够 | `shutdown-timeout` 默认 30s,可配;超过则强制取消并落检查点 |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 附录:本阶段收编的缺陷(25 条)
|
||||
|
||||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||||
|
||||
### F-42 CORS 允许任意 Origin 携带凭证
|
||||
|
||||
**位置**:`corsMiddleware` in `internal/app/bootstrap/bootstrap.go` `corsMiddleware()`
|
||||
|
||||
```go
|
||||
origin := c.GetHeader("Origin")
|
||||
if origin != "" {
|
||||
c.Header("Access-Control-Allow-Origin", origin) // 反射任意 Origin
|
||||
c.Header("Vary", "Origin")
|
||||
} else {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
}
|
||||
...
|
||||
c.Header("Access-Control-Allow-Credentials", "true") // 且允许凭证
|
||||
```
|
||||
|
||||
**问题概述**:把请求方 `Origin` 原样回显到 `Access-Control-Allow-Origin`,同时打开 `Allow-Credentials: true`,等价于允许互联网上任意站点带着用户凭证(Cookie/Authorization)跨源读取本服务响应。
|
||||
|
||||
**影响**:任何恶意网页都能以受害者身份调用 `/api/v1/*`,属于典型的跨源凭证泄露,必须修。当前项目虽无登录态 Cookie,但前端登录信息存在 Cookie、且 Authorization 头被允许,风险真实存在。
|
||||
|
||||
**修复方案**:引入 Origin 白名单配置(如 `server.allowed-origins`),仅当 `origin` 命中白名单时才回显,并同时设置 `Vary: Origin`;未命中直接不回 `Allow-Origin`。默认只允许 `http://localhost:3000`。示例:
|
||||
|
||||
```go
|
||||
allowed := map[string]bool{"http://localhost:3000": true}
|
||||
if origin != "" && allowed[origin] {
|
||||
c.Header("Access-Control-Allow-Origin", origin)
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
}
|
||||
c.Header("Vary", "Origin")
|
||||
```
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P0-1
|
||||
|
||||
### F-43 `.env.example` 被 git 跟踪且含疑似密钥与推广链接
|
||||
|
||||
**位置**:`.env.example:16,25`(已被 git 跟踪)
|
||||
|
||||
```text
|
||||
OPENAI_API_KEY=sk-A7B5Wv41qabcdefg**********7yoCxlcU
|
||||
BAIDU_SEARCH_MCP_SSE_ENDPOINT=sse?api_key=bce-v3/ALTAK-wSdZlzasdfghjkl**********
|
||||
...
|
||||
# 中转站推荐:https://codez.zwenooo.link/register?aff=c3yW
|
||||
```
|
||||
|
||||
**问题概述**:`.env` 已在 `.gitignore` 中,但 `.env.example` 反而把疑似真实 Key(虽被 `*` 部分打码)和推广/返利链接提交进了仓库历史。即使 `*` 是打码,前缀 `sk-A7B5Wv41q...` 与 `ALTAK-wSdZl...` 仍可能泄露账号线索。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 仓库公开/共享时等于泄露密钥线索;若曾用过真实 Key,存在被滥用的可能。
|
||||
- `.env.example` 本应是「可复制的模板」,现在却会让 `cp .env.example .env` 的用户直接拿到错误/失效配置。
|
||||
- 推广链接进入代码仓库不符合工程规范。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
1. 把 `.env.example` 中真实值全部改为 `replace-me` / `your-model-name`。
|
||||
2. 移除推广链接。
|
||||
3. 若这些 Key 曾真实可用,立即在供应商侧吊销并轮换。
|
||||
4. 加 pre-commit / CI 检查,扫描 `sk-`、`ALTAK`、`api_key=` 等模式。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P0-2
|
||||
|
||||
### F-44 `writeError(c, nil)` 会 panic
|
||||
|
||||
**位置**:`writeError` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
```go
|
||||
func writeError(c *gin.Context, err error) {
|
||||
var appErr *types.AppError
|
||||
if errors.As(err, &appErr) { ... }
|
||||
c.JSON(http.StatusOK, response.Failure(types.CodeUnknownError, err.Error())) // err 为 nil 时 panic
|
||||
}
|
||||
```
|
||||
|
||||
**问题概述**:`errors.As(nil, ...)` 返回 false,随后调用 `err.Error()` 触发 nil 指针 panic。虽然当前调用方都传非 nil,但这是库函数级别的隐患。
|
||||
|
||||
**修复方案**:
|
||||
|
||||
```go
|
||||
if err == nil {
|
||||
c.JSON(http.StatusOK, response.Failure(types.CodeUnknownError, types.InfoUnknownError))
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P0-7
|
||||
>
|
||||
> 统一 `response.Error(c, err)`,内部做 nil 保护
|
||||
|
||||
### F-45 没有优雅停机
|
||||
|
||||
**位置**:`main` in `cmd/server/main.go`、`Run` in `internal/app/bootstrap/bootstrap.go` `Engine.Run`
|
||||
|
||||
```go
|
||||
if err := engine.Run(); err != nil { logger.Fatal(...) }
|
||||
// Engine.Run -> e.Router.Run(addr) // 阻塞,没有 Shutdown
|
||||
```
|
||||
|
||||
**问题概述**:没有监听 `SIGINT` / `SIGTERM`,没有 `http.Server.Shutdown(ctx)`,没有等待在途请求。进程被 `Ctrl+C` 或容器编排 `SIGTERM` 时会直接中断。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 正在执行的 Agent 请求(可能已经调用 LLM / 写库)被硬中断,产生半成品状态。
|
||||
- SSE 连接被立即切断。
|
||||
- 容器滚动发布期间出现请求失败。
|
||||
|
||||
**修复方案**:在 `Engine.Run` 中改用显式 `http.Server`:
|
||||
|
||||
```go
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: e.Router,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
go srv.ListenAndServe()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
return srv.Shutdown(shutdownCtx)
|
||||
```
|
||||
|
||||
这同时解决 F-54(`http.Server` 无超时)。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P0-8
|
||||
|
||||
### F-46 配置校验缺失
|
||||
|
||||
**位置**:`validateTable` in `internal/app/config/loader.go`
|
||||
|
||||
**问题概述**:只校验了必填字段、workflow type、MCP 传输类型,未校验:
|
||||
|
||||
- `agent-workflows[].sub-agents` 是否为空;
|
||||
- 子 Agent 名称是否存在;
|
||||
- Agent name 是否重复;
|
||||
- `runner.agent-name` 是否存在于 agents 或 workflows;
|
||||
- `tool-skills-list[].path` 是否存在、`type` 是否合法;
|
||||
- workflow 名称是否重复。
|
||||
|
||||
**影响**:错误配置延迟到 Armory 装配甚至运行时才暴露;`sub-agents` 写错会「少一个子 Agent 甚至空 workflow」但启动不报错。
|
||||
|
||||
**修复方案**:在 `validateTable` 中构建 agent/workflow 名称集合,做存在性与重复性校验;把 `runner.agent-name`、`sub-agents` 校验前置到配置加载阶段,让报错信息精确定位到 YAML 字段。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P1-8
|
||||
>
|
||||
> `--strict-config` 收口;建议前移到 P2 之前执行,见 `README.md` 的执行顺序
|
||||
|
||||
### F-47 跨文件同名 table 静默覆盖
|
||||
|
||||
**位置**:`loadAgentTables` in `internal/app/bootstrap/bootstrap.go`
|
||||
|
||||
```go
|
||||
for name, table := range tables {
|
||||
merged[name] = table // 后加载文件覆盖先加载
|
||||
}
|
||||
```
|
||||
|
||||
**影响**:两个 YAML 文件里写了同名 table 时,前者被静默丢弃,排查困难。
|
||||
|
||||
**修复方案**:合并时检测重复并报错,或明确「后者覆盖前者」并打警告日志。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P2-4
|
||||
>
|
||||
> `--strict-config` 可覆盖,需显式加「跨文件同名 table 即报错」
|
||||
|
||||
### F-48 环境变量在 YAML 解析前展开
|
||||
|
||||
**位置**:`LoadAgentTables` in `internal/app/config/loader.go`
|
||||
|
||||
**问题概述**:`expandEnvPlaceholders(string(data))` 先做字符串替换,再 `yaml.Unmarshal`。
|
||||
|
||||
**影响**:环境变量值包含 YAML 特殊字符(`:`、`#`、换行、引号)时会破坏 YAML 结构,报错信息指向解析失败而非环境变量。
|
||||
|
||||
**修复方案**:给 `.env` 值加引号的约定(文档化);或改为「先解析,再对字符串字段做展开」,从根上避免注入破坏结构。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-5
|
||||
|
||||
### F-49 YAML 非严格解析
|
||||
|
||||
**位置**:`LoadAgentTables` in `internal/app/config/loader.go`、`LoadApplication` in `internal/app/config/application.go`
|
||||
|
||||
**问题概述**:`yaml.Unmarshal` 忽略未知字段,字段名拼错不会报错。
|
||||
|
||||
**影响**:如 `base-url` 写成 `base_url` 会静默取零值,最终表现为「必填校验失败」或运行异常,定位成本高。
|
||||
|
||||
**修复方案**:使用 `yaml.NewDecoder(bytes.NewReader(...))` + `dec.KnownFields(true)` 开启严格模式。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-6
|
||||
|
||||
### F-50 `application.yaml` 不做环境变量替换
|
||||
|
||||
**位置**:`LoadApplication` in `internal/app/config/application.go`
|
||||
|
||||
**问题概述**:直接 `yaml.Unmarshal`,`configs/application.yaml` 里的值写死;`.env` 中 `MYSQL_DSN`、`REDIS_ADDR` 实际未被 bootstrap 使用。
|
||||
|
||||
**影响**:不同环境(local/test/prod)需要改文件,无法用 env 覆盖;也导致 `.env.example` 里的 `MYSQL_DSN`/`REDIS_ADDR` 形同虚设。
|
||||
|
||||
**修复方案**:复用 `loader.go` 的 `expandEnvPlaceholders`,在 `LoadApplication` 解析前对内容做展开,把 DSN/Redis 地址改成 `${MYSQL_DSN}` 等占位符。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-7
|
||||
|
||||
### F-51 应用配置校验偏弱
|
||||
|
||||
**位置**:`LoadApplication` in `internal/app/config/application.go`
|
||||
|
||||
**问题概述**:只校验 `llm.request-timeout`,未校验 `app.name`、`server.addr` 合法性、`agent.config-paths` 非空、`required=true` 时 DSN/Addr 非空。
|
||||
|
||||
**影响**:错误配置延迟到 bootstrap 或运行时,报错不明确。
|
||||
|
||||
**修复方案**:在 `LoadApplication` 末尾统一做一次语义校验,返回聚合错误(含字段名),让启动即失败、失败信息可操作。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-9
|
||||
|
||||
### F-52 DTO 缺少 binding 校验 / GET 接口无校验
|
||||
|
||||
**位置**:`internal/api/dto/agent.go`、`createSession` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `CreateSessionRequest`、`ChatRequest` 都没有 `binding:"required"`;
|
||||
- `GET /create_session` 直接取 query 参数,为空要到下游才报错;
|
||||
- `message` 无长度限制。
|
||||
|
||||
**影响**:无效请求返回 `0001` 而不是 `0002`;超长 message 直接送入模型,浪费 token 并可能触发上游 400。
|
||||
|
||||
**修复方案**:给必填字段加 `binding:"required"`;给 `Message` 加 `binding:"max=..."`;GET 接口显式校验或改为 POST 单一入口。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P2-12
|
||||
>
|
||||
> 方案提了 `MaxBytesReader`;DTO 的 `binding` tag 与字段长度上限需点名
|
||||
|
||||
### F-53 未知错误直接回显内部信息
|
||||
|
||||
**位置**:`writeError` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
```go
|
||||
c.JSON(http.StatusOK, response.Failure(types.CodeUnknownError, err.Error()))
|
||||
```
|
||||
|
||||
**问题概述**:把内部错误原文返回给客户端,可能包含上游 URL、响应片段(`openai upstream 500: {...}`)、文件路径等。
|
||||
|
||||
**影响**:信息泄露,攻击者可据此探测上游服务。
|
||||
|
||||
**修复方案**:对外返回 `types.InfoUnknownError` 之类的通用文案,详细错误只写日志(配合 request id)。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-14
|
||||
|
||||
### F-54 `http.Server` 缺少超时、`Engine` 无 Close
|
||||
|
||||
**位置**:`Run` in `internal/app/bootstrap/bootstrap.go` `Engine.Run`
|
||||
|
||||
**问题概述**:`gin.Engine.Run` 内部创建默认 `http.Server`,无 `ReadHeaderTimeout`/`ReadTimeout`/`WriteTimeout`/`IdleTimeout`,存在慢速攻击与连接堆积风险;同时没有 `Close`/`Shutdown` 句柄。
|
||||
|
||||
**修复方案**:与 F-45 一并改为显式 `http.Server` 并设置合理超时;为 `Engine` 增加 `Close(ctx)`。
|
||||
|
||||
---
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-18
|
||||
|
||||
### F-55 CORS 缺少 `Expose-Headers` / `Max-Age`
|
||||
|
||||
**为什么优化**:预检结果无法缓存,增加 OPTIONS 请求;若未来返回自定义头前端读不到。
|
||||
|
||||
**方案**:与 F-42 一起补 `Access-Control-Max-Age` 和必要的 `Access-Control-Expose-Headers`。
|
||||
|
||||
**改动量**:很小。
|
||||
|
||||
**影响**:减少预检开销,前端可用性更完整。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P3-10
|
||||
|
||||
### F-56 `docker-compose.yml` 中 redis 引用了未声明的网络,compose 无法启动
|
||||
|
||||
**位置**:`deployments/docker-compose.yml`
|
||||
|
||||
```yaml
|
||||
redis:
|
||||
networks:
|
||||
- voice-input-net # <- 未在顶层 networks 中声明
|
||||
...
|
||||
networks:
|
||||
ai-agent-scaffold: # <- 只声明了这个
|
||||
driver: bridge
|
||||
```
|
||||
|
||||
**问题概述**:redis 服务引用的 `voice-input-net` 在顶层 `networks:` 中不存在(明显是从别的项目复制过来的)。`docker compose -f deployments/docker-compose.yml up -d` 会因为 “service redis refers to undefined network” 而校验失败,MySQL 能起、Redis 起不来(或需手工创建该网络)。
|
||||
|
||||
**影响**:CLAUDE.md 与 README 推荐的本地基础设施启动命令直接不可用;即使手工绕过,Redis 与 MySQL 也不在同一网络,无法互访。
|
||||
|
||||
**修复方案**:把 redis 的 `networks` 改为 `ai-agent-scaffold`(与 mysql 一致),删除遗留的 `voice-input-net`。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P1-11
|
||||
|
||||
### F-57 全项目没有鉴权,`userId` 完全由客户端控制
|
||||
|
||||
**位置**:`internal/trigger/http/agent_handler.go`(无认证中间件)、`CreateSessionRequest` in `internal/api/dto/agent.go`
|
||||
|
||||
**问题概述**:所有 `/api/v1/*` 接口完全开放;`userId` 直接取自请求体/query,服务端不校验其真实性,也不与任何凭证绑定。前端登录页只是把 `user` 写进 Cookie,后端完全不感知(`grep "Auth|middleware" internal/trigger internal/app` 只命中 CORS 里的 `Authorization` 头名)。
|
||||
|
||||
**影响**:
|
||||
|
||||
- 任何调用方可伪造任意 `userId`,以他人身份创建会话、发消息、读同一 Session 上下文(F-23 的 sessionId 不校验会进一步放大);
|
||||
- 一旦引入对话历史/计费/审计,就是越权与数据泄露;
|
||||
- `createSessionQuery` 允许 GET 传 `userId`,更易被日志/Referer 泄露。
|
||||
|
||||
**修复方案**:接入认证中间件(JWT / API Key / 网关透传身份),从凭证解析 `userId` 而非信任入参;至少在 `chat.Service` 层校验 `userId` 与凭证一致。CORS 已允许 `Authorization` 头,具备接入条件。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P1-12
|
||||
|
||||
### F-58 MySQL 库名与端口在三个文件里互不一致
|
||||
|
||||
**位置**:`deployments/docker-compose.yml`、`configs/application.yaml`、`.env.example:6` / `.env:6`
|
||||
|
||||
**问题概述**:同一套本地环境出现三种库名与两种端口:
|
||||
|
||||
| 来源 | 库名 | 端口 |
|
||||
|---|---|---|
|
||||
| `deployments/docker-compose.yml` | `ai-agent-scaffold` | 13306:3306 |
|
||||
| `configs/application.yaml` | `ai-agent-scaffold-go` | 13306 |
|
||||
| `.env` / `.env.example` | `ai_agent_scaffold_go` | `.env` 用 3306 |
|
||||
|
||||
由于 MySQL 目前未接入,问题被掩盖;一旦按 F-26 启用 MySQL,连接会直接失败(库不存在)。
|
||||
|
||||
**影响**:启用持久化时立刻踩坑;三处配置让排查成本变高。
|
||||
|
||||
**修复方案**:统一为一个库名(建议 `ai_agent_scaffold_go`)与一个端口(compose `13306`),并让 `application.yaml` 用 `${MYSQL_DSN}` 占位符(依赖 F-50),使 `.env` 成为唯一事实来源。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P2-19
|
||||
>
|
||||
> 统一库名 + Redis 端口(6379/16379),写进 P8 部署清单
|
||||
|
||||
### F-59 `.env` 里的 `APP_ENV` 与 `SERVER_ADDR` 根本不生效
|
||||
|
||||
**位置**:`main` in `cmd/server/main.go`、`LoadApplication` in `internal/app/config/application.go`
|
||||
|
||||
**问题概述**:`logging.New(appCfg.App.Env)` 的 `appCfg.App.Env` 来自 `configs/application.yaml` 的 `app.env`;监听地址来自 `server.addr`。`.env` 里的 `APP_ENV` / `SERVER_ADDR` 在 Go 代码中**从未被读取**(`grep "APP_ENV|SERVER_ADDR" *.go` 无命中)。
|
||||
|
||||
**影响**:把 `.env` 的 `APP_ENV` 改成 `prod` 不会切换日志级别、也不会关闭 Gin debug 日志;改 `SERVER_ADDR` 不会改端口。属于典型的「看似可配实际无效」,与 F-50 同源但影响面更直接。
|
||||
|
||||
**修复方案**:让 `LoadApplication` 展开 `${APP_ENV}` / `${SERVER_ADDR}` 占位符(F-50 的统一解法),或在文档中明确这两个变量无需配置并从 `.env.example` 删除以免误导。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P2-20
|
||||
|
||||
### F-60 本地路径解析依赖进程 CWD,从其他目录启动会失败
|
||||
|
||||
**位置**:`resolveSkillRoot` in `internal/infrastructure/ai/tools.go`(`os.Getwd()`)、`loadAgentTables` in `internal/app/bootstrap/bootstrap.go`(`os.ExpandEnv(path)` 后直接 `os.ReadFile`)
|
||||
|
||||
**问题概述**:技能路径通过「从当前工作目录逐级向上找候选」解析;`agent.config-paths` 与 `.env` 路径也相对 CWD。代码没有以可执行文件位置或配置目录为基准。
|
||||
|
||||
**影响**:用 systemd / 容器 / IDE 以不同 `WORKDIR` 启动时可能找不到技能或 Agent 配置;`skillPathCandidates` 里硬编码的 `ai-agent-scaffold-go` 目录名让解析逻辑对仓库名敏感。
|
||||
|
||||
**修复方案**:以「配置文件所在目录」或显式 `APP_BASE_DIR` 环境变量为基准解析相对路径;技能路径优先支持绝对路径并给出清晰错误;去掉硬编码的仓库目录名候选。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P2-25
|
||||
>
|
||||
> 容器化 + 配置路径绝对化,写进 P8 部署清单
|
||||
|
||||
### F-61 `prod` 环境判断在多处重复
|
||||
|
||||
**位置**:`newRouter` in `internal/app/bootstrap/bootstrap.go`、`New` in `internal/infrastructure/logging/logger.go`
|
||||
|
||||
**问题概述**:`env == "prod" || env == "production"` 出现了三次,且 `bootstrap` 还要正反各判断一遍。
|
||||
|
||||
**影响**:新增环境名(如 `staging`/`release`)需要改多处,易漏。
|
||||
|
||||
**修复方案**:抽 `func isProduction(env string) bool`(放在 `app/config` 或 `pkg`),三处复用。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P3-17
|
||||
>
|
||||
> `isProduction` 收敛到单一实现
|
||||
|
||||
### F-62 工作区 `.env` 含真实密钥,且缺少 CI / 后端 Dockerfile / Makefile
|
||||
|
||||
**位置**:`.env`(未跟踪但存在于工作区)、仓库根目录
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `.env` 里有 2 处真实感密钥(`grep -c "sk-\|ALTAK" .env` = 2)。虽然 `.env` 已被 gitignore,但工作区若被打包/分享就会泄露;
|
||||
- 仓库没有 `.github/workflows`、没有后端 `Dockerfile`、没有 `Makefile`(只有 frontend 有 Dockerfile/build.sh)。
|
||||
|
||||
**影响**:密钥有泄露面;构建、测试、镜像化、CI 校验都没有标准化入口,新人上手和发布一致性靠人肉。
|
||||
|
||||
**修复方案**:轮换 `.env` 中的密钥并仅保留在本地/密钥管理;补最小 CI(`go build` + `go vet` + `gofmt -l` 校验)和后端多阶段 `Dockerfile`;可选加 `Makefile` 统一 `build/test/run/lint`。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P3-19
|
||||
|
||||
### F-63 `validateTable` 错误顺序随机,timeout 校验文案与行为不符
|
||||
|
||||
**位置**:`validateTable` in `internal/app/config/loader.go`、`validateMCPEntry` in `internal/app/config/loader.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- 必填字段放在 `map[string]string` 里遍历,Go map 顺序随机,同一份错误配置每次报错字段可能不同;
|
||||
- `request-timeout < 0` 才报错,文案却是 "must be positive",即 `0` 被允许(随后被 `normalizeTimeout` 改成 300000)。
|
||||
|
||||
**影响**:错误信息不稳定,测试/排障时对不上;文案误导用户以为 0 非法。
|
||||
|
||||
**修复方案**:必填校验改为有序 `[]struct{name, value string}`;明确 `0` 的语义(「使用默认值」)并把文案改为 `must not be negative`。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P3-20
|
||||
>
|
||||
> 严格校验重写时一并统一报错顺序与文案
|
||||
|
||||
### F-64 缺少就绪探针/指标,SSE 响应头不完整
|
||||
|
||||
**位置**:`newRouter` in `internal/app/bootstrap/bootstrap.go`(`/healthz`)、`chatStream` in `internal/trigger/http/agent_handler.go`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- 只有 `/healthz` 恒返回 `{"status":"ok"}`,不检查任何依赖(MCP/LLM 连通性),也没有 `/readyz` 与 `/metrics`;
|
||||
- `chatStream` 只设置 `Content-Type: text/event-stream`,缺少 `Cache-Control: no-cache`、`Connection: keep-alive`、`X-Accel-Buffering: no` 等常见 SSE 头。
|
||||
|
||||
**影响**:编排系统无法区分「进程活着」与「可以接流量」;经过 Nginx 等反代时 SSE 可能被缓冲,破坏「逐字输出」体验。
|
||||
|
||||
**修复方案**:补 `/readyz`(可选地探测关键依赖)与基础指标;`chatStream` 补齐 SSE 标准响应头。
|
||||
|
||||
> **归属**:P8 | **状态**:✅ | **历史编号**:P3-21
|
||||
|
||||
### F-65 本地基础设施配置存在遗留项与弱口令
|
||||
|
||||
**位置**:`deployments/mysql/my.cnf:16-18,22-24`、`deployments/redis/redis.conf`
|
||||
|
||||
**问题概述**:
|
||||
|
||||
- `my.cnf` 里留着 `binlog-do-db = big_market_01` / `big_market_02`(明显从其他项目复制),与本项目无关;
|
||||
- 自定义 `slow-query-log-file` / `log-error` 指向 `/var/log/mysql/`,在官方镜像中该目录可能不存在或不可写,可能导致容器启动异常;
|
||||
- `redis.conf` 只有 `bind 0.0.0.0` 与 `port 6379`,没有 `requirepass`,而 compose 把 6379 映射到宿主机;
|
||||
- `MYSQL_ROOT_PASSWORD: 123456` 为弱口令,且与 `application.yaml` 中的 DSN 明文一致。
|
||||
|
||||
**影响**:本地环境可能起不来(日志路径/库名)或存在弱口令暴露面;这些配置会被当作「模板」复制到真实环境。
|
||||
|
||||
**修复方案**:清理 `my.cnf` 中与本项目无关的 binlog/slow-log 配置;Redis 增加 `requirepass` 并在配置中用 `${REDIS_PASSWORD}`;弱口令改为 `.env` 注入,并在 README 标注「仅本地示例」。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P3-22
|
||||
>
|
||||
> 弱口令与遗留配置写进 P8 安全清单
|
||||
|
||||
### F-66 其他值得顺手处理的小问题
|
||||
|
||||
**位置**:多处
|
||||
|
||||
| 问题 | 位置 | 说明 / 建议 |
|
||||
|---|---|---|
|
||||
| 入站请求体无大小限制 | `internal/trigger/http/agent_handler.go` 的 `ShouldBindJSON` | 未使用 `http.MaxBytesReader` 或 Gin body limit,超大 JSON 可导致内存膨胀;与 F-18 对称,建议加统一上限 |
|
||||
| 没有编译期接口断言 | `ports/ports.go` 及各 adapter | 建议加 `var _ ports.ChatModel = (*EinoChatModel)(nil)` 之类的断言,避免接口漂移在运行期才暴露 |
|
||||
| `Eino*` 命名与实际实现不符 | `internal/infrastructure/ai/eino_adapter.go` | 类型叫 `EinoProvider`/`EinoChatModel`/`EinoTool`,但实现完全基于自研 `OpenAIClient`,Eino 未被使用(见 F-67);建议改名为 `OpenAIProvider` 等,减少误导 |
|
||||
| `AgentWorkflowNode.build` 的 `buildOrder` 冗余 | `build` in `internal/domain/agent/service/armory/workflow/agent_workflow_node.go` | 已有 `builders map[WorkflowType]workflowBuilder`,可直接 `n.builders[workflow.Type]` 查表,无需再维护 `buildOrder` 列表并循环匹配 |
|
||||
| `DynamicContext` 封装风格不一致 | `DynamicContext` in `internal/domain/agent/service/armory/context.go` | `ModelAPI`/`ChatModel` 是导出的可变字段,其余状态都走带锁方法;建议统一(要么都走方法,要么明确这两者只在装配期单线程写入) |
|
||||
| MySQL healthcheck 未带密码、MySQL 8 参数已弃用 | `deployments/docker-compose.yml`、`deployments/mysql/my.cnf` | healthcheck 用 `mysqladmin ping -h localhost` 无 `-p`(部分版本会产生告警);`--default-authentication-plugin` 在 MySQL 8.4 将被移除,8.0 下也会告警,建议按需清理 |
|
||||
| `ToolFactory.BuildTools` 存在不可达分支 | `BuildTools` in `internal/infrastructure/ai/tools.go` | `validateMCPConfig` 已保证 `kind` 是 local/sse/stdio 之一,后面 `case config.SSE != nil` / `case config.Stdio != nil` 是永远走不到的历史兼容分支,建议删除 |
|
||||
| `LoadApplication` 忽略 `app/llm` 以外的语义校验 | `LoadApplication` in `internal/app/config/application.go` | 与 F-51 同源,建议一次性补齐并集中 |
|
||||
|
||||
**影响**:均为小问题,不阻塞运行,但会累积成维护噪音。
|
||||
|
||||
**修复方案**:按上表逐项小改;建议与 F-67、F-61 一起作为一个「代码整洁」批次处理。
|
||||
|
||||
> **归属**:P8 | **状态**:🟡 | **历史编号**:P3-23
|
||||
>
|
||||
> `MaxBytesReader` 已覆盖;编译期断言、`Eino*` 改名、不可达分支进第 0 天清单
|
||||
169
docs/upgrade-plan/README.md
Normal file
169
docs/upgrade-plan/README.md
Normal file
@@ -0,0 +1,169 @@
|
||||
> **文档类型**:plan(路线图与缺陷台账索引)| **总方案**:[`../agent-platform-upgrade-plan.md`](../agent-platform-upgrade-plan.md)
|
||||
|
||||
# Agent 平台升级 · 阶段规划清单
|
||||
|
||||
这套文档是「按顺序迭代」的入口:九个阶段各一份计划书(`P0-…md` 到 `P8-…md`),每份都自包含「为什么改、改成什么、改哪些文件、怎么验收」,并把历史审计里的缺陷按编号收编进来(`F-xx`)。
|
||||
|
||||
## 怎么用
|
||||
|
||||
1. 想了解全局(现状、蓝图、路线图、横切专题、面试映射):读 [`../agent-platform-upgrade-plan.md`](../agent-platform-upgrade-plan.md)。
|
||||
2. 想开工某一阶段:读该阶段计划书;「当前问题」告诉你为什么,「设计」告诉你怎么做,「涉及的代码模块」告诉你在哪改,「验收标准」告诉你什么时候算完。
|
||||
3. 想知道某条历史缺陷落到哪了:查本文第 4 节的台账,或直接搜 `F-xx`。
|
||||
4. 每完成一个阶段:把台账里对应条目的状态从 🟡 改为 ✅,并在阶段计划书的「验收标准」下方勾选。
|
||||
|
||||
## 1. 阶段清单
|
||||
|
||||
| 阶段 | 计划书 | 主题 | 预估 | 前置 | 收编缺陷 |
|
||||
|---|---|---|---|---|---|
|
||||
| P0 | [`P0-运行时内核.md`](P0-运行时内核.md) | 运行时内核:让每一次执行都成为一等公民 | 8–10 人日 | — | 9 条 |
|
||||
| P1 | [`P1-工具网关.md`](P1-工具网关.md) | 工具网关:把「能调通」变成「调不坏」 | 10–12 人日 | P0 | 13 条 |
|
||||
| P2 | [`P2-会话持久化.md`](P2-会话持久化.md) | 会话生命周期与持久化:让 Agent 记得住、找得回 | 8–10 人日 | P0 | 9 条 |
|
||||
| P3 | [`P3-记忆与知识.md`](P3-记忆与知识.md) | 记忆与知识:三层记忆 + 可检索知识库 | 12–15 人日 | P2 | 1 条 |
|
||||
| P4 | [`P4-上下文工程.md`](P4-上下文工程.md) | 上下文工程:20 轮之后还记得第一句话 | 10–12 人日 | P2、P3 | 1 条 |
|
||||
| P5 | [`P5-工作流编排.md`](P5-工作流编排.md) | 工作流编排:从「线性 Chain」到「可补偿的状态机」 | 12–15 人日 | P2 | 3 条 |
|
||||
| P6 | [`P6-工具治理.md`](P6-工具治理.md) | 工具治理:可见范围、人工确认、沙箱与密钥 | 10–12 人日 | P1、P2 | 2 条 |
|
||||
| P7 | [`P7-可观测与评测.md`](P7-可观测与评测.md) | 可观测、断言与评测:让「跑偏」可被发现 | 10–12 人日 | P0 | 3 条 |
|
||||
| P8 | [`P8-生产化.md`](P8-生产化.md) | 生产化:从「能跑」到「敢上线」 | 6–8 人日 | P0–P7 | 25 条 |
|
||||
|
||||
合计 85–110 人日(单人 4–5 个月,双人约 10 周,排期见总方案第 7 章)。
|
||||
|
||||
## 2. 执行顺序
|
||||
|
||||
- **必须先做**:第 0 天技术债清扫(0.5–1 人日)→ P0 运行时内核。P0 是后八个阶段的挂载点,它定义的 `Run/Step/Event/Budget` 是全系统的公共语言。
|
||||
- **建议前移**:P8 里的「配置严格校验」提前到 P2 之前做。P3 的 embedding、P5 的图引用、P6 的策略规则都以「配置引用正确」为前提,晚做会让后三个阶段建立在一堆可能指向不存在节点的配置上。
|
||||
- **可以并行**:P3(记忆)与 P5(工作流)之间没有强依赖,P4 依赖 P3 的检索端口但不依赖其实现,可先按端口开发。
|
||||
- **串行依赖链**:P0 → P1 → P2 → P4(P4 需要 P2 的消息持久化与 P3 的检索),P5 / P6 / P7 在 P2 之后可任意顺序。
|
||||
|
||||
## 3. 第 0 天:技术债清扫(P0 之前,0.5–1 人日)
|
||||
|
||||
这些改动零行为变更,但能让后续每个 PR 的 diff 干净(否则 CRLF 会把改动变成全文件 diff)。
|
||||
|
||||
| 缺陷 | 动作 | 状态 |
|
||||
|---|---|---|
|
||||
| F-67 | 第 0 天删除 `internal/infrastructure/dependencies` 并 `go mod tidy` | ⬜ 待做 |
|
||||
| F-68 | 第 0 天清理死代码清单(13 项) | ⬜ 待做 |
|
||||
| F-69 | `.gitattributes` + CI `gofmt -l` 门 | ⬜ 待做 |
|
||||
| F-70 | P2 的 DTO 层显式拒绝 + 「明确不支持」清单 | ⬜ 待做 |
|
||||
| F-71 | P0 拆包会顺带删除一部分,其余进第 0 天清理清单 | ⬜ 待做 |
|
||||
| F-72 | 已由 `52e9387` 修复,仅需在清单中标注完成 | ✅ 已在 `52e9387` 完成 |
|
||||
|
||||
## 4. 缺陷台账索引(76 条)
|
||||
|
||||
来源:历史审计 71 条(原编号 `P0-1…P3-23`,见「历史编号」列)+ 本方案补充 5 条(无历史编号)。状态:✅ 已被某阶段完整收编 50 条;🟡 部分收编、需在执行时点名 21 条;❌ 未收编、需单独立项 5 条。
|
||||
|
||||
| 编号 | 历史编号 | 症状 | 归属 | 状态 |
|
||||
|---|---|---|---|---|
|
||||
| F-01 | P0-6 | 流式取消时 `OpenAIClient.Stream` goroutine 泄漏 | P0 | 🟡 |
|
||||
| F-02 | P1-4 | HTTP 请求 context 未传递到 Agent | P0 | ✅ |
|
||||
| F-03 | P2-2 | `DynamicContext.agentGroup` 名称覆盖与静默跳过 | P0 | ✅ |
|
||||
| F-04 | P2-3 | 装配与加载顺序不确定 | P0 | ✅ |
|
||||
| F-05 | P2-17 | Service 层方法无 context | P0 | ✅ |
|
||||
| F-06 | P3-4 | `AgentFactory` 为三种 workflow 各定义一个方法 | P0 | ✅ |
|
||||
| F-07 | P3-12 | `InMemoryAgentRegistry.Register` 无校验且恒返回 nil | P0 | 🟡 |
|
||||
| F-08 | P1-13 | `adkRunnerPlugin` 是空壳,`myLogPlugin` 实际没有任何 ADK 日志能力 | P0 | 🟡 |
|
||||
| F-09 | (新增) | tool-calling 循环上限硬编码为 4 次 | P0 | ✅ |
|
||||
| F-10 | P0-3 | 工具描述全部丢失,模型只能看到兜底描述 | P1 | ✅ |
|
||||
| F-11 | P0-4 | MCP `pending` map 在超时/提前返回路径泄漏 | P1 | ✅ |
|
||||
| F-12 | P0-5 | `ensureStarted` 并发首次调用会失败 | P1 | 🟡 |
|
||||
| F-13 | P0-9 | 重复注册 MCP SSE 工具导致第二张表拿到不可调用占位工具 | P1 | ✅ |
|
||||
| F-14 | P1-1 | Skill 工具只暴露、不可执行 | P1 | ✅ |
|
||||
| F-15 | P1-9 | 工具参数 schema 硬编码为 `query` | P1 | ✅ |
|
||||
| F-16 | P2-10 | `MCPToolRouter` 无锁 | P1 | ✅ |
|
||||
| F-17 | P1-14 | MCP 启动期工具发现失败时,会把「服务端标签」当工具暴露给模型且不告警 | P1 | ✅ |
|
||||
| F-18 | P2-22 | `io.ReadAll` 无上限读取上游响应体 | P1 | 🟡 |
|
||||
| F-19 | P2-23 | 流式请求没有发送 `Accept: text/event-stream` | P1 | 🟡 |
|
||||
| F-20 | P3-15 | `MCPToolRouter` 的 `registered` / `listFailures` 是死字段,`notify` 不校验状态码 | P1 | 🟡 |
|
||||
| F-21 | (新增) | 任一工具失败即整轮失败(`executeToolCalls`) | P1 | ✅ |
|
||||
| F-22 | (新增) | 工具调用无单次超时,只靠 HTTP 客户端整体超时 | P1 | ✅ |
|
||||
| F-23 | P1-5 | `sessionId` 不校验归属 | P2 | ✅ |
|
||||
| F-24 | P1-6 | Session 无对话历史(Agent 实际无状态) | P2 | ✅ |
|
||||
| F-25 | P1-7 | `CreateSession` 并发竞态 | P2 | ✅ |
|
||||
| F-26 | P2-8 | MySQL / Redis 适配器未接入 | P2 | ✅ |
|
||||
| F-27 | P2-11 | 空内容错误码不准确 + 先建 Session 后校验内容 | P2 | ✅ |
|
||||
| F-28 | P2-16 | `CreateSession` 不校验 Agent 是否仍存在 | P2 | 🟡 |
|
||||
| F-29 | P3-7 | `ports.SessionStore` 无 context | P2 | ✅ |
|
||||
| F-30 | P3-13 | Session key 用 `:` 拼接存在歧义 | P2 | ✅ |
|
||||
| F-31 | (新增) | Session ID 用全局原子计数拼接,无租户维度且跨 Agent 撞号 | P2 | ✅ |
|
||||
| F-32 | P3-3 | `EmbeddingsPath` 定义但未使用 | P3 | ✅ |
|
||||
| F-33 | P2-24 | 无法配置任何生成参数 | P4 | 🟡 |
|
||||
| F-34 | P1-2 | `max-iterations` 配置无效 | P5 | ✅ |
|
||||
| F-35 | P1-3 | `parallel` 并非真正并发 | P5 | ✅ |
|
||||
| F-36 | P2-1 | `AgentWorkflowNode.Apply` 递归实现 | P5 | 🟡 |
|
||||
| F-37 | P1-10 | `stdio` / `local` 传输运行时不可执行 | P6 | ✅ |
|
||||
| F-38 | P2-21 | MCP 客户端连接状态没有「代际」隔离,旧连接的错误会污染新连接 | P6 | 🟡 |
|
||||
| F-39 | P2-13 | SSE 无心跳、未处理客户端断连 | P7 | ✅ |
|
||||
| F-40 | P2-15 | 日志体系不完善 | P7 | ✅ |
|
||||
| F-41 | (新增) | 无 run_id / trace_id,日志无法关联一次执行 | P7 | ✅ |
|
||||
| F-42 | P0-1 | CORS 允许任意 Origin 携带凭证 | P8 | ✅ |
|
||||
| F-43 | P0-2 | `.env.example` 被 git 跟踪且含疑似密钥与推广链接 | P8 | ✅ |
|
||||
| F-44 | P0-7 | `writeError(c, nil)` 会 panic | P8 | ✅ |
|
||||
| F-45 | P0-8 | 没有优雅停机 | P8 | ✅ |
|
||||
| F-46 | P1-8 | 配置校验缺失 | P8 | ✅ |
|
||||
| F-47 | P2-4 | 跨文件同名 table 静默覆盖 | P8 | 🟡 |
|
||||
| F-48 | P2-5 | 环境变量在 YAML 解析前展开 | P8 | ✅ |
|
||||
| F-49 | P2-6 | YAML 非严格解析 | P8 | ✅ |
|
||||
| F-50 | P2-7 | `application.yaml` 不做环境变量替换 | P8 | ✅ |
|
||||
| F-51 | P2-9 | 应用配置校验偏弱 | P8 | ✅ |
|
||||
| F-52 | P2-12 | DTO 缺少 binding 校验 / GET 接口无校验 | P8 | 🟡 |
|
||||
| F-53 | P2-14 | 未知错误直接回显内部信息 | P8 | ✅ |
|
||||
| F-54 | P2-18 | `http.Server` 缺少超时、`Engine` 无 Close | P8 | ✅ |
|
||||
| F-55 | P3-10 | CORS 缺少 `Expose-Headers` / `Max-Age` | P8 | ✅ |
|
||||
| F-56 | P1-11 | `docker-compose.yml` 中 redis 引用了未声明的网络,compose 无法启动 | P8 | ✅ |
|
||||
| F-57 | P1-12 | 全项目没有鉴权,`userId` 完全由客户端控制 | P8 | ✅ |
|
||||
| F-58 | P2-19 | MySQL 库名与端口在三个文件里互不一致 | P8 | 🟡 |
|
||||
| F-59 | P2-20 | `.env` 里的 `APP_ENV` 与 `SERVER_ADDR` 根本不生效 | P8 | ✅ |
|
||||
| F-60 | P2-25 | 本地路径解析依赖进程 CWD,从其他目录启动会失败 | P8 | 🟡 |
|
||||
| F-61 | P3-17 | `prod` 环境判断在多处重复 | P8 | 🟡 |
|
||||
| F-62 | P3-19 | 工作区 `.env` 含真实密钥,且缺少 CI / 后端 Dockerfile / Makefile | P8 | ✅ |
|
||||
| F-63 | P3-20 | `validateTable` 错误顺序随机,timeout 校验文案与行为不符 | P8 | 🟡 |
|
||||
| F-64 | P3-21 | 缺少就绪探针/指标,SSE 响应头不完整 | P8 | ✅ |
|
||||
| F-65 | P3-22 | 本地基础设施配置存在遗留项与弱口令 | P8 | 🟡 |
|
||||
| F-66 | P3-23 | 其他值得顺手处理的小问题 | P8 | 🟡 |
|
||||
| F-67 | P3-1 | `internal/infrastructure/dependencies` 从未被 import | DAY0 | ❌ |
|
||||
| F-68 | P3-2 | 全局死代码与未使用接口 | DAY0 | ❌ |
|
||||
| F-69 | P3-9 | `gofmt -l .` 报告所有文件(CRLF) | DAY0 | ❌ |
|
||||
| F-70 | P3-11 | `ChatContent` 的 Files / InlineDatas 被静默忽略 | DAY0 | ❌ |
|
||||
| F-71 | P3-14 | 未使用的接口方法 | DAY0 | 🟡 |
|
||||
| F-72 | P3-18 | `.gitignore` 忽略了 `docs/`,`CLAUDE.md` 也被忽略 | DAY0 | ❌ |
|
||||
| F-73 | P3-5 | 错误码体系过少、`Code` 为裸 string | GLOBAL | ✅ |
|
||||
| F-74 | P3-6 | `AppError` 不含上下文与错误链 | GLOBAL | ✅ |
|
||||
| F-75 | P3-8 | 项目零测试 | GLOBAL | ✅ |
|
||||
| F-76 | P3-16 | 空列表响应会缺少 `data` 字段,与前端约定的响应契约不一致 | GLOBAL | 🟡 |
|
||||
|
||||
跨阶段条目(`GLOBAL`)不归属任何单一阶段,落点是总方案的横切章节:
|
||||
|
||||
| 编号 | 落点 |
|
||||
|---|---|
|
||||
| F-73 | §5.1 错误码扩展 |
|
||||
| F-74 | §5.1 `Error{TraceID,Details,Cause}` |
|
||||
| F-75 | §5.6 测试金字塔 |
|
||||
| F-76 | §5.1 的响应契约需明确 `data` 空值策略 |
|
||||
|
||||
## 5. 历史评审记录(已归档)
|
||||
|
||||
两份历史文档(`项目完善报告.md`、`完善报告-评审与收编清单.md`)的内容已于 2026-11-02 全部拆入本目录并删除,结论保留如下:
|
||||
|
||||
- 历史审计共 71 条,逐条抽查 15 条**全部属实**,无虚报;综合质量 8.2/10(事实准确性 9、证据强度 9、可执行性 7、完整性 8、结构与自洽 8)。
|
||||
- 原始判断「45 条会被阶段天然消化 / 21 条需点名 / 5 条未收编」已落实为本文台账的 ✅ / 🟡 / ❌ 三档。
|
||||
- 审计本身有 5 个可改进点(同根因重复计 3 组、混用「会崩/会越权/功能谎言」三种性质、缺验收标准、约 5 条属代码整洁、配置单一事实源未升格),本次合并时已按「一条一编号、带状态、带归属」的格式消解。
|
||||
|
||||
## 6. 迭代约定
|
||||
|
||||
- **一阶段一 PR(或一组 PR)**:阶段计划书里的「验收标准」是合并条件,不是建议。
|
||||
- **开关先行**:每阶段新行为都必须有开关且默认保旧一个版本(开关表见总方案 2.5)。
|
||||
- **缺陷回填**:阶段完成后更新本文第 4 节状态列与阶段文件里的 `> **状态**` 行,这是唯一的进度事实源。
|
||||
- **不新增行号引用**:仓库约定用「反引号标识符 + 文件路径」定位代码,不用 `文件:行号`(行号必然漂移)。
|
||||
|
||||
## 7. 状态看板
|
||||
|
||||
| 阶段 | 状态 | 开始 | 完成 | 备注 |
|
||||
|---|---|---|---|---|
|
||||
| P0 | ⬜ 未开始 | — | — | |
|
||||
| P1 | ⬜ 未开始 | — | — | |
|
||||
| P2 | ⬜ 未开始 | — | — | |
|
||||
| P3 | ⬜ 未开始 | — | — | |
|
||||
| P4 | ⬜ 未开始 | — | — | |
|
||||
| P5 | ⬜ 未开始 | — | — | |
|
||||
| P6 | ⬜ 未开始 | — | — | |
|
||||
| P7 | ⬜ 未开始 | — | — | |
|
||||
| P8 | ⬜ 未开始 | — | — | |
|
||||
@@ -1,265 +0,0 @@
|
||||
# 《项目完善报告》评审与升级方案收编清单
|
||||
|
||||
> 评审对象:`docs/项目完善报告.md`(71 条,P0×9 / P1×14 / P2×25 / P3×23,基于 commit `adf5fdb`)
|
||||
> 参照方案:`docs/agent-platform-upgrade-plan.md`(v1.0,9 个阶段 P0–P8)
|
||||
> 评审日期:2026-11-01(2026-11-02 更新:P1-1 决策落地,统计由 44/22/5 修正为 45/21/5)
|
||||
> Doc type: plan(工程文档:评审结论、缺陷台账映射、收编建议)
|
||||
|
||||
---
|
||||
|
||||
## 1. 结论
|
||||
|
||||
**这是一份可以直接当施工台账用的缺陷报告**:71 条全部带 `file:line`,绝大多数附了代码片段与修复代码,还有第二轮复核与死代码附录。我抽查了 15 条(占 21%),**全部与代码一致**,只发现一处遗漏(见 3.5)。
|
||||
|
||||
| 维度 | 评分 | 说明 |
|
||||
|---|---|---|
|
||||
| 事实准确性 | 9/10 | 15 处抽查全中;仅 P2-19 未覆盖 Redis 端口不一致 |
|
||||
| 证据强度 | 9/10 | 每条都有 file:line + 关键代码;部分还给了修复片段 |
|
||||
| 可执行性 | 7/10 | 修复方案清楚,但**没有验收标准与测试归属**,改完算不算好无法判定 |
|
||||
| 完整性 | 8/10 | 缺陷面覆盖很全;架构级能力缺口(预算、事件、审批、沙箱、评测)不在其射程内——这是定位差异,不算遗漏 |
|
||||
| 结构与自洽 | 8/10 | 严重度分层 + 二轮复核 + 落地顺序,结构成熟;有少量同根因重复计 |
|
||||
|
||||
**综合 8.2/10。** 与升级方案是**互补关系**,不是替代关系:
|
||||
|
||||
- 报告是**横切诊断**:按严重程度排,回答"现在哪里坏了";
|
||||
- 方案是**纵向处方**:按能力演进排,回答"怎么长成运行时"。
|
||||
|
||||
所以正确用法是:**报告当缺陷台账,方案当施工计划**,把编号收编进阶段,避免两份文档各自漂移。
|
||||
|
||||
---
|
||||
|
||||
## 2. 抽查记录(15 条)
|
||||
|
||||
| 编号 | 报告声明 | 核对结果 | 证据 |
|
||||
|---|---|---|---|
|
||||
| P0-1 | CORS 反射 Origin + 允许凭证 | ✅ 属实 | `corsMiddleware` in `internal/app/bootstrap/bootstrap.go`,`Access-Control-Allow-Origin: origin` + `Allow-Credentials: true` |
|
||||
| P0-4 | `pending` 在提前返回/超时路径泄漏 | ✅ 属实 | `(*MCPSSEClient).callRPC` in `internal/infrastructure/ai/mcp_sse_client.go`:`c.pending[id] = ch` 之后才判 `postURL == ""` 并直接 return |
|
||||
| P0-5 | `ensureStarted` 并发首次调用失败 | ✅ 属实 | `(*MCPSSEClient).ensureStarted` in `internal/infrastructure/ai/mcp_sse_client.go`:锁内置 `c.started = true`,锁外才 `openSSE`;并发者看到 true 直接返回,`postURL` 仍空 |
|
||||
| P0-7 | `writeError(c, nil)` panic | ✅ 属实 | `writeError` in `internal/trigger/http/agent_handler.go`:`errors.As(nil, ...)` 为 false 后走 `err.Error()` |
|
||||
| P0-8 | 无优雅停机 | ✅ 属实 | `(*Engine).Run` in `internal/app/bootstrap/bootstrap.go` 直接 `e.Router.Run(addr)`;`main.go` 无 signal |
|
||||
| P1-4 | ctx 未透传 | ✅ 属实 | `(*Runner).Run`、`(*Runner).Stream`、`(*Runner).notifyPlugins` in `internal/infrastructure/adk/adapter.go` 三处 `context.Background()` |
|
||||
| P1-13 | `adkRunnerPlugin` 是空壳 | ✅ 属实 | `(*adkRunnerPlugin).OnUserMessage`/`BeforeAgent` in `internal/infrastructure/adk/adapter.go`:只判 `OnUserMessageCallback() != nil`,从未调用它 |
|
||||
| P1-14 | MCP 发现失败静默降级 | ✅ 属实 | `RegisterAndExpand` 里 `listFailures` 只写不读,失败时把配置名当工具返回 |
|
||||
| P2-19 | 三处库名/端口不一致 | ✅ 属实(且比报告更糟) | compose `ai-agent-scaffold`、yaml `ai-agent-scaffold-go`、`.env` `ai_agent_scaffold_go`;`.env` 还指向 3306/6379 |
|
||||
| P2-23 | 流式未发 `Accept: text/event-stream` | ✅ 属实 | `(*OpenAIClient).do` in `internal/infrastructure/ai/openai_client.go` 恒为 `application/json` |
|
||||
| P3-9 | `gofmt -l` 全量误报(CRLF) | ✅ 属实 | 无 `.gitattributes`;`bootstrap.go` 前 200 字节含 CRLF |
|
||||
| P3-16 | 空列表响应缺 `data` 字段 | ✅ 属实 | `Envelope` in `internal/api/response/response.go` 的 `Data T \`json:"data,omitempty"\`` |
|
||||
| P3-20 | `validateTable` 必填校验顺序随机 | ✅ 属实 | `validateTable` in `internal/app/config/loader.go` 遍历 `map[string]string` 报错 |
|
||||
| P3-21 | 只有 `/healthz`,无 `/readyz` | ✅ 属实 | 全仓库仅 `newRouter` in `internal/app/bootstrap/bootstrap.go` 一处 |
|
||||
| P1-11 | compose redis 引用未声明网络 | ✅ 属实 | `deployments/docker-compose.yml`,`voice-input-net` 未在顶层声明 |
|
||||
|
||||
**抽查结论**:没有发现误报,也没有发现"看起来严重其实无害"的虚高条目。报告的判断力是可信的。
|
||||
|
||||
---
|
||||
|
||||
## 3. 报告本身值得改进的 5 点
|
||||
|
||||
### 3.1 同根因重复计(影响"里有多少活"的判断)
|
||||
|
||||
| 被拆开的条目 | 实际是 |
|
||||
|---|---|
|
||||
| P0-9 + P1-14 | 同一个根因:`RegisterAndExpand` 用"工具名"复用 client,且失败后回退占位工具 |
|
||||
| P0-3 + P1-9 + P1-10 | 同一主题"工具系统只做了壳"的三个面:描述、schema、传输执行 |
|
||||
| P0-5 + P0-4 + P2-21 | 都是 `MCPSSEClient` 的连接状态管理缺一致性(初始化竞态、清理、代际) |
|
||||
|
||||
修复时如果按编号逐条改,会出现"改三次同一段代码"。建议合并为 3 个工作包(工具系统 / MCP 连接 / 会话),而不是 6–8 个独立缺陷。
|
||||
|
||||
### 3.2 严重度定义混用
|
||||
|
||||
P0 里混了三种性质的缺陷:
|
||||
|
||||
- **会崩/会泄漏**:P0-4、P0-6、P0-7;
|
||||
- **会越权/泄密**:P0-1、P0-2;
|
||||
- **"能配置不能跑"的功能谎言**:P0-3、P0-9、P1-1、P1-10。
|
||||
|
||||
第三类不会让进程崩,但会让"配了就以为能用"的判断失真,实际杀伤力不低于崩溃。建议加一个 `L`(Lie / 一致性)标签,与 P0–P3 正交使用。
|
||||
|
||||
### 3.3 缺验收标准与测试归属
|
||||
|
||||
71 条里只有极少数给了"改完怎么验证"。比如 P0-5 的修复方案写得很清楚,但没有"并发 10 个 goroutine 调用 `callRPC`,断言全部成功且无 `post url is not set`"这样的断言。这是报告与方案**互补的最大空间**:方案的每阶段验收标准可以反向挂到缺陷编号上。
|
||||
|
||||
### 3.4 P3 里有约 5 条与架构演进无关
|
||||
|
||||
P3-4(`AgentFactory` 接口冗余)、P3-12(`Register` 无校验)、P3-14(未使用接口)、P3-17(`isProduction` 重复)、P3-23 表中的命名类建议(`Eino*` 改名、`buildOrder` 冗余)——这些是"代码整洁"而非"能力演进",建议单独成批,避免污染阶段计划。
|
||||
|
||||
反过来,P3 里真正的**横切项**只有一条没被单独提炼:**配置单一事实源**(P2-7 + P2-19 + P2-20 三处说的是同一件事:`.env` 应该是唯一事实来源,YAML 只做占位)。建议升格为独立条目。
|
||||
|
||||
### 3.5 一处遗漏(我核对 P2-19 时发现)
|
||||
|
||||
`.env` 的 `REDIS_ADDR=127.0.0.1:6379`,而 compose 把 Redis 映射到 `16379`。报告只对比了 MySQL 的库名/端口,Redis 端口不一致没被点名——但和 MySQL 一样,一旦按 P2-8 接入就会立刻连不上。
|
||||
|
||||
---
|
||||
|
||||
## 4. 与升级方案的映射(核心)
|
||||
|
||||
### 4.1 统计
|
||||
|
||||
| 覆盖状态 | 数量 | 含义 |
|
||||
|---|---|---|
|
||||
| ✅ 完全覆盖 | **45** | 方案里点名或结构性地会解决 |
|
||||
| 🟡 部分覆盖 | **21** | 会被阶段重构"顺带"解决,但方案没点名,存在漏做风险 |
|
||||
| ❌ 未覆盖 | **5** | 方案完全不涉及,需要显式补 |
|
||||
| 合计 | 71 | — |
|
||||
|
||||
也就是说:**升级方案天然会消化掉 63% 的缺陷,另有 30% 需要"点名"才安全,剩下 7% 必须额外补。**
|
||||
|
||||
### 4.2 全量矩阵
|
||||
|
||||
#### P0(9 条,全部收编)
|
||||
|
||||
| 编号 | 收编阶段 | 状态 | 说明 |
|
||||
|---|---|---|---|
|
||||
| P0-1 CORS 反射 | P8 安全加固 | ✅ | 方案 S10 + `server.allowed-origins` 白名单 |
|
||||
| P0-2 `.env.example` 密钥 | P8 安全加固 | ✅ | 方案 S13 + gitleaks |
|
||||
| P0-3 工具描述丢失 | P1 工具网关 | ✅ | MCP `ListTools` 返回 `ServerTool{Name,Description,InputSchema}`;`SkillTool` 补 `Description()` |
|
||||
| P0-4 `pending` 泄漏 | P1 工具网关 | ✅ | `defer` 清理 |
|
||||
| P0-5 `ensureStarted` 竞态 | P1 / P6 | 🟡 | 方案未点名;P6 的 MCP 生命周期重构会重写这段,但在 P1 就该修(并发安全问题不该等到 P6) |
|
||||
| P0-6 流式 goroutine 泄漏 | P0 / P1 | 🟡 | P0 的 ctx 透传能收口,但 `emitToolCalls` 的裸发送需点名 |
|
||||
| P0-7 `writeError(nil)` | P8 + §5.1 | ✅ | 统一 `response.Error(c, err)`,内部 nil 保护 |
|
||||
| P0-8 无优雅停机 | P8 | ✅ | `signal.NotifyContext` + `srv.Shutdown` + CancelAll |
|
||||
| P0-9 重复注册 | P1 | ✅ | `RegisterAndExpand` 命中即返回错误;P6 用 `server.tool` 命名空间彻底解 |
|
||||
|
||||
#### P1(14 条,14 收编)
|
||||
|
||||
| 编号 | 收编阶段 | 状态 | 说明 |
|
||||
|---|---|---|---|
|
||||
| P1-1 Skill 只暴露不可执行 | P1 / P6 | ✅ | 2026-11-02 已决策(方案 4.2.8):P1 移除 function 暴露、只注入 instruction;P6 沙箱就绪后实现可调用 Skill |
|
||||
| P1-2 `max-iterations` 无效 | P5 | ✅ | 真循环 + 三层终止 |
|
||||
| P1-3 `parallel` 假并发 | P5 | ✅ | errgroup + SetLimit |
|
||||
| P1-4 ctx 未透传 | P0 | ✅ | `runtime.Runner` 全部带 ctx |
|
||||
| P1-5 session 不校验归属 | P2 | ✅ | `Authorize` → 403 |
|
||||
| P1-6 无对话历史 | P2 + P4 | ✅ | 消息持久化 + 预算装配 |
|
||||
| P1-7 `CreateSession` 竞态 | P2 | ✅ | 唯一索引 + `ErrSessionExists` 回读 |
|
||||
| P1-8 配置校验缺失 | P8 | ✅ | `--strict-config`;但**建议前移**,因为 P3/P5 都依赖正确配置 |
|
||||
| P1-9 schema 硬编码 query | P1 | ✅ | 真实 JSON Schema + `strict: true` |
|
||||
| P1-10 stdio/local 不可执行 | P6 | ✅ | stdio MCP 走 docker 沙箱;local 内置工具注册表在 P6 一并补 |
|
||||
| P1-11 redis 网络引用 | P8 | ✅ | compose 修正 |
|
||||
| P1-12 无鉴权、userId 客户端可控 | P8 | ✅ | 三种鉴权模式,租户只从凭证取 |
|
||||
| P1-13 插件空壳 | P0 | 🟡 | 方案只做 `plugin.go` 拆分搬迁,没说要重写语义 |
|
||||
| P1-14 MCP 发现失败静默 | P1 | ✅ | `listFailures` 参与告警 / fail fast |
|
||||
|
||||
#### P2(25 条,14 收编 / 11 部分)
|
||||
|
||||
| 编号 | 收编阶段 | 状态 | 说明 |
|
||||
|---|---|---|---|
|
||||
| P2-1 递归装配 | P5 | 🟡 | 图模型重构会替换掉,但方案没点名 |
|
||||
| P2-2 重名覆盖 | P8 / P0 | ✅ | 严格校验 + 确定性装配 |
|
||||
| P2-3 map 顺序 | P0 | ✅ | `sort.Strings` |
|
||||
| P2-4 同名 table 覆盖 | P8 | 🟡 | `--strict-config` 可覆盖,需显式加"重复即报错" |
|
||||
| P2-5 env 展开破坏 YAML | P8 | ✅ | `expand.go` 复用 |
|
||||
| P2-6 非严格解析 | P8 | ✅ | `KnownFields(true)` |
|
||||
| P2-7 `application.yaml` 无 env | P8 | ✅ | 同上 |
|
||||
| P2-8 MySQL/Redis 未接入 | P2 | ✅ | `persistence.mode` |
|
||||
| P2-9 应用配置校验弱 | P8 | ✅ | `--strict-config` |
|
||||
| P2-10 Router 无锁 | P1 | ✅ | `sync.RWMutex` |
|
||||
| P2-11 空内容错误码 + 先建 session | §5.1 + P2 | ✅ | 参数校验前置 + `1001` |
|
||||
| P2-12 DTO 无 binding | P8 | 🟡 | 方案提了 MaxBytesReader,未提 `binding` tag 与 max 长度 |
|
||||
| P2-13 SSE 无心跳 | P7 | ✅ | 附录 B 的 15s heartbeat |
|
||||
| P2-14 错误回显内部信息 | P8 | ✅ | 只回 code + trace_id |
|
||||
| P2-15 日志不可配 | P7 | ✅ | zap 统一 6 字段 |
|
||||
| P2-16 `CreateSession` 不校验 agent | P2 | 🟡 | 方案未点名;顺手加 `registry.Get` |
|
||||
| P2-17 Service 无 ctx | P0 | ✅ | 一并透传 |
|
||||
| P2-18 `http.Server` 无超时 | P8 | ✅ | ReadHeader 5s / Idle 120s |
|
||||
| P2-19 库名/端口不一致 | P8 | 🟡 | 方案没点名"统一库名 + Redis 端口",但部署清单里会碰到 |
|
||||
| P2-20 `APP_ENV` 不生效 | P8 | ✅ | 同 P2-7 解法 |
|
||||
| P2-21 连接代际未隔离 | P6 | 🟡 | P6 的 `connState` 重构会覆盖,需点名 |
|
||||
| P2-22 `io.ReadAll` 无上限 | P1 / P8 | 🟡 | 入站有 `MaxBytesReader`;**出站响应读取上限未提** |
|
||||
| P2-23 流式无 `Accept` | P1 | 🟡 | 客户层重写会覆盖,未点名 |
|
||||
| P2-24 无生成参数 | P4 | 🟡 | 只覆盖了 `max_output`;`temperature`/`response_format` 未提 |
|
||||
| P2-25 CWD 解析 | P8 | 🟡 | 部署章节可覆盖,未点名 |
|
||||
|
||||
#### P3(23 条,8 收编 / 12 部分 / 5 未覆盖)
|
||||
|
||||
| 编号 | 收编阶段 | 状态 | 说明 |
|
||||
|---|---|---|---|
|
||||
| P3-1 `dependencies` 包未被 import | — | ❌ | 无人认领 |
|
||||
| P3-2 全局死代码 | — | ❌ | 方案不做清理(P0 拆分可顺带,但没列) |
|
||||
| P3-3 `EmbeddingsPath` 未用 | P3 | ✅ | embedding 客户端落地 |
|
||||
| P3-4 `AgentFactory` 冗余 | P0 | ✅ | 执行器 `Registry` 替代 |
|
||||
| P3-5 错误码体系 | §5.1 | ✅ | 4 位扩展 + 兼容码 |
|
||||
| P3-6 `AppError` 无上下文 | §5.1 | ✅ | `TraceID`/`Details`/`Cause` |
|
||||
| P3-7 `SessionStore` 无 ctx | P2 | ✅ | 新 `session.Repository` 全带 ctx |
|
||||
| P3-8 零测试 | §5.6 | ✅ | 测试金字塔 + 每阶段资产表 |
|
||||
| P3-9 CRLF / `gofmt` 全量误报 | — | ❌ | CI 只提了 govulncheck/gosec,没提 gofmt 与 `.gitattributes` |
|
||||
| P3-10 CORS 头不全 | P8 | ✅ | 白名单实现时一并补 Max-Age |
|
||||
| P3-11 Files/InlineDatas 静默忽略 | — | ❌ | 多模态完全不在方案里 |
|
||||
| P3-12 `Register` 无校验 | P0 / P8 | 🟡 | 新 Runner 不用旧 registry,但旧 registry 会留一版 |
|
||||
| P3-13 session key 歧义 | P2 | ✅ | 新 schema 用 CHAR(26) 主键 |
|
||||
| P3-14 未使用接口 | — | 🟡 | P0 拆包会删一部分,未系统清理 |
|
||||
| P3-15 `registered`/`listFailures` 死字段 | P1 | 🟡 | `listFailures` 改为告警后自然解决;`notify` 状态码未提 |
|
||||
| P3-16 空列表缺 `data` | §5.1 | 🟡 | 方案说"新增字段全部可选",但没处理旧 `data` 缺失 |
|
||||
| P3-17 `isProduction` 重复 | P8 | 🟡 | 顺手可做,未列 |
|
||||
| P3-18 `.gitignore` 忽略 `docs/` | — | ❌ | **注意:本方案文档自己在 `docs/` 下,当前不会进版本库** |
|
||||
| P3-19 `.env` 密钥 + 无 CI/Dockerfile | P8 | ✅ | Dockerfile + CI + gitleaks |
|
||||
| P3-20 `validateTable` 顺序/文案 | P8 | 🟡 | 严格校验重写时一并解决 |
|
||||
| P3-21 缺 readyz/metrics + SSE 头 | P8 | ✅ | `/readyz` `/metrics` + 附录 B |
|
||||
| P3-22 本地基础设施遗留配置 | P8 | 🟡 | 部署章节可覆盖,未点名 |
|
||||
| P3-23 其他小问题 | P8 / — | 🟡 | `MaxBytesReader` ✅;编译期断言、`Eino*` 改名、不可达分支 ❌ |
|
||||
|
||||
### 4.3 必须显式补的 5 项
|
||||
|
||||
| 编号 | 问题 | 建议归属 | 成本 |
|
||||
|---|---|---|---|
|
||||
| P3-1 | `dependencies` 包从未被 import,Eino 直接依赖虚挂 | **P0 前"第 0 天"清理** | 30 分钟 + `go mod tidy` |
|
||||
| P3-2 | 全局死代码(附录 13 项) | 同上,与 P0 拆分合并一个 PR | 2 小时 |
|
||||
| P3-9 | CRLF 导致 `gofmt -l` 全量误报 | P8 CI 门(顺带做,越早越好) | 30 分钟 |
|
||||
| P3-11 | `Files`/`InlineDatas` 声明支持却静默丢弃 | P2 的 DTO 层显式拒绝,或列入"明确不支持"清单 | 1 小时 |
|
||||
| P3-18 | `.gitignore` 忽略 `docs/` | **立即**(否则本方案与报告都不入库) | 1 分钟 |
|
||||
|
||||
### 4.4 需要"点名"的 7 个部分覆盖项
|
||||
|
||||
这 21 个 🟡 里,有 14 个会被阶段重构天然吸收(比如 P2-1 递归会被 P5 图模型替换、P2-25 CWD 解析会在 P8 容器化时修正),不必单独列。真正需要写进阶段任务的是这 7 个:
|
||||
|
||||
1. **P0-6**:`emitToolCalls` 与 `Done` 事件的发送要 `select ctx.Done()` —— 写进 P0 验收("取消后 goroutine 数回落")。
|
||||
2. **P0-5**:`ensureStarted` 的 `started` 双状态或 `sync.Once` —— 写进 P1 的 MCP 修复包。
|
||||
3. **P2-22**:出站响应体 `io.LimitReader` 上限 —— 写进 P1 的"模型客户端加固"。
|
||||
4. **P2-23**:`Accept: text/event-stream` —— 同上一包。
|
||||
5. **P2-24**:`temperature`/`max_tokens`/`response_format` 透传 —— 写进 P4 的模型参数化。
|
||||
6. **P2-19**:统一库名 + Redis 端口(含我补的 6379/16379)—— 写进 P8 部署清单。
|
||||
7. **P3-16**:`data` 字段空值策略 —— 写进 §5.1 的响应契约。
|
||||
|
||||
> P1-1(Skill 执行语义)原在此列,已于 2026-11-02 决策并写入方案 4.2.8,故状态从 🟡 升为 ✅。
|
||||
|
||||
---
|
||||
|
||||
## 5. 对升级方案的 4 条修订建议
|
||||
|
||||
### 5.1 增加"第 0 天:技术债清扫"(半个到 1 个工作日)
|
||||
|
||||
在 P0 动工前先做一个不改变行为的 PR:
|
||||
|
||||
- 删除 `internal/infrastructure/dependencies`,`go mod tidy`(P3-1、P3-2);
|
||||
- 清理附录 13 项死代码(P3-2、P3-14);
|
||||
- 加 `.gitattributes`(`*.go text eol=lf`)并在 CI 加 `gofmt -l` 门(P3-9);
|
||||
- 修 `.gitignore` 放行 `docs/`(P3-18);
|
||||
- 修 `.env.example` 密钥与 compose 的 redis 网络(P0-2、P1-11)。
|
||||
|
||||
**为什么值得单独一步**:这些改动零风险、零行为变更,但能让后续所有 PR 的 diff 干净(否则 CRLF 会把每次改动变成全文件 diff),也让 `go test` 的基线从"什么都没有"变成"能跑"。
|
||||
|
||||
### 5.2 把 P1-8(配置校验)从 P8 前移到 P2 之前
|
||||
|
||||
P3(记忆)、P5(工作流)、P6(治理)都依赖"配置引用正确"的前提。当前 `validateTable` 连子 Agent 是否存在都不校验,P5 的图校验会建立在一堆"可能指向不存在节点"的配置上。配置严格校验是**其他阶段的安全网**,不该等到最后。
|
||||
|
||||
### 5.3 每阶段加一行"顺手修复"字段
|
||||
|
||||
方案的阶段小节已有"涉及的代码模块",建议再加一行"**本阶段收编的缺陷**",直接引用报告编号。好处:不需要维护第二份文档,报告编号成为可追溯的工单号。
|
||||
|
||||
### 5.4 把报告降级为"附录台账"
|
||||
|
||||
`docs/项目完善报告.md` 保留但标注"已被升级方案收编,编号 P0-x/P1-x 为历史工单号"。否则半年后会出现"报告说有问题但代码已改"的困惑。
|
||||
|
||||
---
|
||||
|
||||
## 6. 现在就能做的三件事(10 分钟内)
|
||||
|
||||
| 顺序 | 动作 | 原因 |
|
||||
|---|---|---|
|
||||
| 1 | `.gitignore` 放行 `docs/`(或改为只忽略 `docs/personal/`) | **本方案与评审文档目前都不在版本库里**,交付/评审时看不到 |
|
||||
| 2 | `.env.example` 换占位符、删推广链接 | 泄露面 + 新人 `cp` 后拿到错误配置 |
|
||||
| 3 | `deployments/docker-compose.yml` 的 redis `networks` 改为 `ai-agent-scaffold` | 官方推荐的上手命令当前直接失败 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 一句话总结
|
||||
|
||||
> 报告把"哪里坏了"讲清楚了,方案把"怎么长"讲清楚了;**缺的是把两者用编号缝起来的那一针**。缝上之后,71 条缺陷里有 45 条会被阶段天然消化,21 条需要点名,5 条要单独补——总工作量大约 1.5 人日,可以塞进 P0 的第一天。
|
||||
1262
docs/项目完善报告.md
1262
docs/项目完善报告.md
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user