diff --git a/docs/mermaid/Agent执行引擎位置与启动装配.md b/docs/mermaid/Agent执行引擎位置与启动装配.md new file mode 100644 index 0000000..811779d --- /dev/null +++ b/docs/mermaid/Agent执行引擎位置与启动装配.md @@ -0,0 +1,59 @@ +# Agent 执行引擎位置与启动装配 + +> 源码: +`internal/app/bootstrap/bootstrap.go` +`internal/infrastructure/adk/adapter.go` + + +Agent 执行引擎是“HTTP 请求进来后,真正驱动大模型和工具执行”的核心模块。它向上承接 ChatService,向下连接 OpenAI 客户端与 MCP 工具系统;项目启动时通过 Armory 装配链把它创建并注册到内存 Registry。 + +## 整体调用链图 + +```mermaid +flowchart LR + HTTP["trigger/http/agent_handler.go"] --> Chat["domain/agent/service/chat/service.go"] + Chat --> Runner["model.Runner"] + Runner --> ADK["adk.Runner"] + ADK --> Agent["adk.Agent"] + Agent --> ChatModel["ports.ChatModel"] + ChatModel --> Eino["ai/EinoChatModel"] + Eino --> OpenAI["ai/OpenAIClient"] + Agent --> ToolRouter["ports.ToolRouter"] + ToolRouter --> MCP["ai/MCPToolRouter/MCPSSEClient"] +``` + +- `HTTP`:Gin HTTP Handler,接收 `/chat` 与 `/chat_stream` 请求。 +- `Chat`:ChatService,负责会话管理和消息路由。 +- `Runner`:领域层定义的 Runner 接口。 +- `ADK`:`adk.Runner`,负责生命周期管理。 +- `Agent`:`adk.Agent`,负责 LLM 调用、工具调用和工作流编排。 +- `ChatModel`:实际由 `EinoChatModel` 实现,内部使用 `OpenAIClient`。 +- `ToolRouter`:实际由 `MCPToolRouter` 实现,内部使用 `MCPSSEClient`。 + +因此,这个文件是整条链路中的“调度核心”,而不是单纯的 HTTP 客户端或模型客户端。 + +--- + +## 启动装配时序图 + +```mermaid +sequenceDiagram + participant B as bootstrap.Build + participant F as adk.Factory + participant Armory as Armory 装配链 + participant R as RunnerRegistry + + B->>F: NewFactory() + B->>F: UseToolRouter(MCPToolRouter) + B->>Armory: AcceptArmoryAgents() + Armory->>F: NewLLMAgent(config, chatModel) + Armory->>F: NewSequentialAgent(config, subAgents) + Armory->>F: NewRunner(appName, entryAgent, plugins) + Armory->>R: Register(RegisteredAgent{Runner: runner}) +``` + +- `bootstrap.Build` 是启动装配入口。 +- `adk.Factory` 负责创建 Agent 与 Runner。 +- Armory 装配链负责把 YAML 配置解析并调用 Factory 创建对象。 +- `RunnerRegistry` 是 `ports.InMemoryAgentRegistry`,保存注册后的 Agent 与 Runner。 +- 整个装配发生在启动阶段,运行时只从 Registry 中取 Runner 执行。 diff --git a/docs/mermaid/Agent执行引擎流式执行.md b/docs/mermaid/Agent执行引擎流式执行.md new file mode 100644 index 0000000..599d0dd --- /dev/null +++ b/docs/mermaid/Agent执行引擎流式执行.md @@ -0,0 +1,129 @@ +# Agent 执行引擎流式执行 + +> 源码: +> `internal/trigger/http/agent_handler.go` +> `internal/infrastructure/adk/adapter.go` +> `internal/infrastructure/ai/openai_client.go` +> `internal/infrastructure/ai/eino_adapter.go` + +流式聊天请求会经过 HTTP → ChatService → Runner → Agent → ChatModel → OpenAIClient 多层。每层的“流式”语义不同: + +- `Runner.Stream`:应用层流式入口,负责用户会话、插件通知和 channel 生命周期。 +- `Agent.streamLLM`:Agent 编排层流式执行,负责 Tool-Calling Loop、消息历史和工具结果回灌。 +- `OpenAIClient.Stream`:协议层流式实现,负责 HTTP SSE 解析、`[DONE]` 处理和工具调用分片累积。 + +--- + +## 流式执行分层 + +`Agent.stream` 中只有 `kind == "llm"` 走真正的逐 token 流式;workflow Agent 先完整执行再一次性推送结果。 + +```mermaid +flowchart LR + HTTP["trigger/http chatStream"] --> Chat["chat.Service.HandleCommandStream"] + Chat --> RunnerStream["adk.Runner.Stream"] + RunnerStream --> AgentStream["Agent.stream"] + AgentStream -->|"kind == llm"| StreamLLM["Agent.streamLLM"] + AgentStream -->|"kind != llm"| RunFallback["Agent.run(workflow 整体输出)"] + StreamLLM --> ChatModelStream["ports.ChatModel.Stream"] + ChatModelStream --> Eino["EinoChatModel.Stream"] + Eino --> OpenAIClientStream["OpenAIClient.Stream"] + OpenAIClientStream --> Upstream["OpenAI-compatible HTTP API"] +``` + +| 层 | 方法 | 关注点 | 输出单位 | +|---|---|---|---| +| 协议 / 网络层 | `OpenAIClient.Stream` | HTTP SSE、OpenAI 协议、工具调用分片累积 | `ChatStreamEvent` | +| Agent 编排层 | `Agent.streamLLM` | Tool-Calling Loop、消息历史、工具执行 | `string` 增量 | +| 应用 / 会话层 | `Runner.Stream` | 用户、会话、插件、channel 生命周期 | `string` | + +--- + +## streamLLM 流程图 + +`streamLLM` 在最多 4 轮循环中流式调用模型;边收文本边转发给前端;同时累积工具调用;如果有工具调用,就执行工具并把结果回灌,再进入下一轮。 + +```mermaid +flowchart TD + Start["streamLLM 开始"] --> Init["messages = system + user"] + Init --> Loop{"iter < 4?"} + Loop -->|是| Stream["chatModel.Stream(messages)"] + Stream --> Read["循环读取 events / errs"] + Read --> Delta{"ev.Delta 非空?"} + Delta -->|是| Out["finalText += Delta
out <- Delta"] + Delta -->|否| ToolCheck + Out --> ToolCheck{"ev.ToolCalls 非空?"} + ToolCheck -->|是| Collect["toolCalls 累加"] + ToolCheck -->|否| Read + Collect --> Read + Read --> End{"events 关闭 / errs / ctx.Done"} + End --> StreamErr{"streamErr?"} + StreamErr -->|有| Err["返回错误"] + StreamErr -->|无| HasTool{"len(toolCalls) == 0?"} + HasTool -->|是| DoneCheck{"done?"} + DoneCheck -->|是| Nil["返回 nil"] + DoneCheck -->|否| Err2["stream closed without completion"] + HasTool -->|否| Append["追加 assistant + tool 结果"] + Append --> Loop + Loop -->|否| MaxErr["超过最大迭代次数"] +``` + +> 注意:`Runner.Stream` 当前使用 `context.Background()`,所以图中的 `ctx.Done()` 分支实际上很难触发。 + +--- + +## 流式调用时序图 + +从 HTTP 到 OpenAIClient 的完整流式链路如下,包含一轮工具调用后的二次模型请求。 + +```mermaid +sequenceDiagram + participant H as HTTP Handler + participant C as ChatService + participant R as Runner.Stream + participant A as Agent.streamLLM + participant CM as ChatModel.Stream + participant O as OpenAIClient.Stream + + H->>C: POST /chat_stream + C->>R: Runner.Stream(userID, sessionID, content) + R->>R: notifyPlugins() + R->>A: Agent.stream(ctx, content, outputs) + A->>CM: Stream(ctx, messages) + CM->>O: Stream(ctx, messages, tools) + O-->>CM: ChatStreamEvent{Delta} + CM-->>A: ChatStreamEvent{Delta} + A-->>R: out <- Delta + R-->>H: outputs <- Delta + H-->>H: c.SSEvent("message", Delta) + O-->>CM: ChatStreamEvent{ToolCalls} + CM-->>A: ChatStreamEvent{ToolCalls} + A->>A: executeToolCalls() + A->>CM: Stream(ctx, messages + tool result) + O-->>CM: ChatStreamEvent{Done} + CM-->>A: ChatStreamEvent{Done} + A-->>R: return nil + R-->>H: close(outputs) +``` + +--- + +## Channel 生命周期 + +三层各自创建和关闭自己的 channel,遵循“谁创建、谁关闭”的原则。 + +| 层 | 创建的 channel | 关闭者 | 消费方 | +|---|---|---|---| +| `OpenAIClient.Stream` | `events`、`errs` | 它自己的 goroutine defer | `EinoChatModel` / `streamLLM` | +| `EinoChatModel.Stream` | 不创建,直接透传 | 不负责 | `streamLLM` | +| `streamLLM` | 不创建,使用传入的 `out` | 不负责 | `Runner.Stream` | +| `Runner.Stream` | `outputs`、`errs` | 它自己的 goroutine defer | HTTP Handler | + +数据单位会逐层“降噪”: + +```text +HTTP SSE 原始 chunk + → ChatStreamEvent(Delta / ToolCalls / Done) + → 纯文本字符串 + → SSE message 事件 +``` diff --git a/docs/mermaid/Agent执行引擎结构与策略分发.md b/docs/mermaid/Agent执行引擎结构与策略分发.md new file mode 100644 index 0000000..3031b77 --- /dev/null +++ b/docs/mermaid/Agent执行引擎结构与策略分发.md @@ -0,0 +1,141 @@ +# Agent 执行引擎结构与策略分发 + +> 源码: +`internal/infrastructure/adk/adapter.go` + + +`adk` 包内部由 `Factory`、`Agent`、`Runner` 三层组成:Factory 负责创建对象,Agent 负责按 kind 执行,Runner 负责生命周期管理。 + +## 三层结构图 + +```mermaid +flowchart TD + subgraph Factory["adk.Factory(创建层)"] + F["sessionCounter / plugins / router"] + F -->|NewLLMAgent| LA["Agent{kind:llm}"] + F -->|NewSequentialAgent| SA["Agent{kind:sequential}"] + F -->|NewParallelAgent| PA["Agent{kind:parallel}"] + F -->|NewLoopAgent| LO["Agent{kind:loop}"] + F -->|NewRunner| R["Runner"] + end + + subgraph Agent["adk.Agent(执行层)"] + LA -->|runWithVars| LLM["runLLM"] + SA -->|runWithVars| SEQ["runSequential"] + PA -->|runWithVars| FAN["runFanOut"] + LO -->|runWithVars| FAN + end + + subgraph Runner["adk.Runner(生命周期层)"] + R -->|Run| RUN["agent.run"] + R -->|Stream| STREAM["agent.stream"] + R -->|notifyPlugins| PLUGIN["RunnerPlugin"] + end +``` + + +| 层 | 核心类型 | 职责 | +|---|---|---| +| 创建层 | `Factory` | 创建 Agent / Runner,注入 ToolRouter | +| 执行层 | `Agent` | 根据 `kind` 选择 `runLLM` / `runSequential` / `runFanOut` | +| 生命周期层 | `Runner` | 插件通知、会话 ID 生成、普通/流式执行入口 | + +设计意图:创建与执行分离,执行与生命周期分离,依赖通过外部注入。 + +--- + +## 执行策略分发图 + +`runWithVars` 是 Agent 执行的分发中心。 + +```mermaid +flowchart TD + Run["Agent.run"] --> RW["Agent.runWithVars"] + RW --> Switch{"kind?"} + Switch -->|"llm"| RunLLM["runLLM"] + Switch -->|"sequential"| RunSeq["runSequential"] + Switch -->|"loop / parallel"| RunFan["runFanOut"] +``` + +### 代码对应 + +```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) + } +} +``` + +| kind | 执行方法 | 说明 | +|---|---|---| +| `llm` | `runLLM` | 普通大模型对话 + Tool-Calling Loop | +| `sequential` | `runSequential` | 按顺序执行子 Agent,并通过 outputKey 传值 | +| `loop` | `runFanOut` | 当前实现按 fan-out 聚合子 Agent 输出 | +| `parallel` | `runFanOut` | 当前实现按 fan-out 聚合子 Agent 输出 | + +> 注意:当前 `loop` 与 `parallel` 都走 `runFanOut`,并不是真正的并发执行。 + + +--- + +## 为什么 AgentFactory 和 RunnerFactory 是同一个 Factory + +`bootstrap.Build()` 中只创建了一个 `*adk.Factory`,同时把它作为 `ports.AgentFactory` 和 `ports.RunnerFactory` 传入 Armory: + +```go +agentFactory := adk.NewFactory() +agentFactory.UseToolRouter(toolRouter) +runnerFactory := agentFactory +``` + +调用方通过窄接口依赖 Factory,但底层共享同一个会话计数器、工具路由器和插件注册表。 + +```mermaid +flowchart LR + B["bootstrap.Build"] -->|"agentFactory"| F["*adk.Factory"] + B -->|"runnerFactory"| F + F -->|"实现"| AF["ports.AgentFactory"] + F -->|"实现"| RF["ports.RunnerFactory"] + AN["Armory.AgentNode / WorkflowNode"] --> AF + RN["Armory.RunnerNode"] --> RF +``` + +好处: + +1. `sessionCounter` 全局唯一,多个 Runner 不会生成重复会话 ID。 +2. `router` 只注入一次,所有 Agent 共享同一个工具路由器。 +3. Runner 可以对同一个 Factory 产出的 `*Agent` 做类型断言和编排。 +4. 外部按需依赖 `ports.AgentFactory` 或 `ports.RunnerFactory`,不依赖具体类型。 + +--- + +## Sequential 变量作用域链 + +Sequential 工作流通过 `output-key` 把上一步的完整输出写入 `scope`,后续 Agent 的 instruction 在 `applyVars` 时替换 `{key}`。 + +```mermaid +flowchart LR + R["Agent.run
vars = {}"] --> RW["runWithVars"] + RW --> S["runSequential
scope := cloneVars(vars)"] + S --> S1["sub1.runWithVars(scope)"] + S1 -->|"outputKey: analysis_result"| Scope["scope"] + Scope -->|"applyVars(instruction, scope)"| S2["sub2.runWithVars(scope)"] + S2 -->|"outputKey: draft_diagram"| Scope + Scope -->|"applyVars(instruction, scope)"| S3["sub3.runWithVars(scope)"] + S3 -->|"最终输出"| Out["返回 last"] +``` + +要点: + +- `run` 是无变量入口,内部传入 `map[string]string{}` 作为初始作用域。 +- `runWithVars` 才是带变量作用域的递归入口。 +- Sequential 每次使用 `cloneVars` 复制作用域,避免影响外部调用方。 +- `loop` / `parallel` 走 `runFanOut`,所有子 Agent 共用同一份变量,不会逐级累加 `output-key`。 diff --git a/docs/mermaid/Agent执行引擎运行时流程.md b/docs/mermaid/Agent执行引擎运行时流程.md new file mode 100644 index 0000000..4b9cfb7 --- /dev/null +++ b/docs/mermaid/Agent执行引擎运行时流程.md @@ -0,0 +1,143 @@ +# Agent 执行引擎运行时流程 + +> 源码: +`internal/trigger/http/agent_handler.go` +`internal/domain/agent/service/chat/service.go` +`internal/infrastructure/adk/adapter.go` + +运行时流程包含两部分:一是单个 LLM Agent 内部的 Tool-Calling Loop,二是一次聊天请求从 HTTP 到 Runner、Agent、模型、工具的整体时序。 + +## Tool-Calling Loop 流程图 + +`runLLM` 实现了大模型“思考 → 调用工具 → 看到结果 → 再思考”的循环,最多迭代 4 轮。 + +```mermaid +flowchart TD + Start["初始 messages: system + user"] --> Gen["ChatModel.Generate"] + Gen --> Check{"有 ToolCalls?"} + Check -->|"无"| Return["返回 reply.Content"] + Check -->|"有"| AppendAssistant["追加 assistant tool_calls"] + AppendAssistant --> Exec["executeToolCalls"] + Exec --> AppendTool["追加 tool 结果"] + AppendTool --> Loop{"iter < 4?"} + Loop -->|"是"| Gen + Loop -->|"否"| Error["超过最大迭代次数"] +``` + +### 代码对应 + +```go +func (a *Agent) runLLM(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) { + messages := initialMessages(applyVars(a.instruction, vars), firstText(content)) + for iter := 0; iter < maxToolCallIterations; iter++ { + reply, err := a.chatModel.Generate(ctx, messages) + if err != nil { + return "", err + } + if len(reply.ToolCalls) == 0 { + return reply.Content, nil + } + messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: reply.Content, ToolCalls: reply.ToolCalls}) + toolMessages, err := a.executeToolCalls(ctx, reply.ToolCalls) + if err != nil { + return "", err + } + messages = append(messages, toolMessages...) + } + return "", fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations) +} +``` + +### 关键步骤 + +1. 构建初始消息:`system` + `user`。 +2. 调用 `ChatModel.Generate`。 +3. 如果没有工具调用,直接返回文本结果。 +4. 如果有工具调用,把 assistant 消息加入历史。 +5. 执行工具调用并追加 `tool` 角色消息。 +6. 回到第 2 步,最多 4 轮。 + +--- + +## 请求执行时序图 + +一次普通聊天请求从 HTTP 进入,经过 ChatService 找到 Runner,再由 Agent 调用大模型和工具,最终返回结果。 + +```mermaid +sequenceDiagram + participant H as HTTP Handler + participant C as ChatService + participant R as adk.Runner + participant A as adk.Agent + participant CM as EinoChatModel/OpenAIClient + participant TR as MCPToolRouter/MCPSSEClient + + H->>C: HandleMessage() + C->>R: Runner.Run() + R->>R: notifyPlugins() + R->>A: agent.run() + A->>A: runWithVars() + A->>CM: ChatModel.Generate() + CM-->>A: ChatReply{ToolCalls} + A->>TR: ToolRouter.CallTool() + TR-->>A: tool result + A->>CM: Generate(messages + tool result) + CM-->>A: final content + A-->>R: output + R-->>C: []string{output} + C-->>H: JSON response +``` + +| 参与者 | 实际类型 | 说明 | +|---|---|---| +| `HTTP Handler` | `internal/trigger/http/agent_handler.go` | 接收 `/chat` 请求 | +| `ChatService` | `internal/domain/agent/service/chat/service.go` | 会话路由 | +| `adk.Runner` | `internal/infrastructure/adk/adapter.go` | 生命周期管理、插件通知 | +| `adk.Agent` | `internal/infrastructure/adk/adapter.go` | 执行核心 | +| `EinoChatModel/OpenAIClient` | `internal/infrastructure/ai/*` | 大模型调用 | +| `MCPToolRouter/MCPSSEClient` | `internal/infrastructure/ai/*` | 工具调用 | + +> 图中展示的是包含一轮工具调用的场景。实际运行时可能根据 Tool-Calling Loop 进行多轮工具调用,直到模型返回最终文本。 + + +--- + +## Runner 视角的完整链路(含 Registry) + +前面的时序图侧重“Agent 内部如何调模型和工具”。下面这张图把 `AgentRegistry` 的查找过程显式画出来,更侧重 Runner 在会话链路中的位置。 + +```mermaid +sequenceDiagram + participant Client + participant Handler as HTTP Handler + participant Chat as ChatService + participant Registry as AgentRegistry + participant Runner as adk.Runner + participant Agent as adk.Agent + participant Model as ChatModel + participant Tool as ToolRouter + + Client->>Handler: POST /api/v1/chat + Handler->>Chat: HandleMessage(agentID, userID, sessionID, message) + Chat->>Registry: Get(agentID) + Registry-->>Chat: RegisteredAgent{Runner} + Chat->>Runner: Run(userID, sessionID, content) + Runner->>Runner: notifyPlugins() + Runner->>Agent: run(content) + Agent->>Model: Generate(messages) + Model-->>Agent: ToolCalls + Agent->>Tool: CallTool(...) + Tool-->>Agent: result + Agent->>Model: Generate(messages + tool result) + Model-->>Agent: final content + Agent-->>Runner: output + Runner-->>Chat: []string{output} + Chat-->>Handler: outputs + Handler-->>Client: JSON response +``` + +关键点: + +- `ChatService` 不直接依赖 `adk.Runner`,只依赖 `model.Runner` 接口。 +- `Runner` 不关心模型和工具的协议细节,只负责会话与生命周期。 +- 入口 Agent 通常是一个 workflow Agent,内部再编排多个子 Agent。 diff --git a/docs/mermaid/README.md b/docs/mermaid/README.md new file mode 100644 index 0000000..6ce02fc --- /dev/null +++ b/docs/mermaid/README.md @@ -0,0 +1,23 @@ +# Mermaid 图表阅读索引 + +本目录下的文档用于配合阅读 Agent 执行引擎源码: + +- 源码文件:`../../internal/infrastructure/adk/adapter.go` +- 相关端口:`../../internal/domain/agent/ports/ports.go` +- 相关入口:`../../internal/app/bootstrap/bootstrap.go` +- 流式协议:`../../internal/infrastructure/ai/openai_client.go` +- HTTP / 会话入口:`../../internal/trigger/http/agent_handler.go`、`../../internal/domain/agent/service/chat/service.go` + +| 文件 | 主要内容 | +|---|---| +| [Agent执行引擎位置与启动装配.md](Agent执行引擎位置与启动装配.md) | 执行引擎在项目中的位置、启动装配时序 | +| [Agent执行引擎结构与策略分发.md](Agent执行引擎结构与策略分发.md) | Factory / Agent / Runner 三层结构、策略分发、Factory 双接口、Sequential 变量作用域 | +| [Agent执行引擎运行时流程.md](Agent执行引擎运行时流程.md) | Tool-Calling Loop、一次请求的完整执行时序、Runner 视角的 Registry 链路 | +| [Agent执行引擎流式执行.md](Agent执行引擎流式执行.md) | Runner.Stream / streamLLM / OpenAIClient.Stream 的分层关系、流程图与时序图 | + +建议阅读顺序: + +1. 先看 `Agent执行引擎位置与启动装配.md` +2. 再看 `Agent执行引擎结构与策略分发.md` +3. 接着看 `Agent执行引擎运行时流程.md` +4. 最后看 `Agent执行引擎流式执行.md` diff --git a/docs/项目完善报告.md b/docs/项目完善报告.md new file mode 100644 index 0000000..bd7ca5c --- /dev/null +++ b/docs/项目完善报告.md @@ -0,0 +1,1262 @@ +# AI Agent Scaffold Go 项目完善报告 + +> 生成时间:基于当前工作区代码(commit `adf5fdb`)通读全项目后整理。 +> 范围:后端为主;前端仅在影响后端接口契约时提及。 +> 参考:`docs/something-to-be-implemented.md`。 + +--- + +## 目录 + +- [阅读说明](#阅读说明) +- [严重程度总览](#严重程度总览) +- [P0 严重问题(安全 / 正确性 / 资源泄漏)](#p0-严重问题) +- [P1 高优先级问题](#p1-高优先级问题) +- [P2 中优先级问题](#p2-中优先级问题) +- [P3 优化点](#p3-优化点) +- [第二轮复核补充](#第二轮复核补充) +- [附录:全局死代码与冗余清单](#附录全局死代码与冗余清单) +- [附录:建议的落地顺序](#附录建议的落地顺序) + +--- + +## 阅读说明 + +本报告区分两类内容: + +- **问题(Bug / 风险)**:当前实现会导致错误行为、安全风险或资源泄漏,需要修复。 +- **优化点(Improvement)**:当前能工作,但存在更好的设计;对这类点会额外说明「为什么优化 / 方案 / 改动量 / 影响」。 + +严重程度定义: + +| 等级 | 含义 | +|---|---| +| P0 | 安全漏洞、导致服务不可用、数据/资源泄漏、明显错误行为 | +| P1 | 功能缺失或错误,影响核心链路,但暂不致命 | +| P2 | 设计缺陷,运行时可感知,但短期内不影响主流程 | +| P3 | 代码质量、可维护性、可扩展性优化 | + +--- + +## 严重程度总览 + +| 编号 | 等级 | 问题 | 位置 | +|---|---|---|---| +| P0-1 | P0 | CORS 反射任意 Origin + `Allow-Credentials: true`,等于开放跨源凭证读取 | `internal/app/bootstrap/bootstrap.go` `corsMiddleware` | +| P0-2 | P0 | `.env.example` 被 git 跟踪且包含疑似真实 Key、百度 api_key 与推广链接 | `.env.example` | +| P0-3 | P0 | 所有工具描述都丢失,模型只能看到兜底描述,工具选择质量下降 | `internal/infrastructure/ai/eino_adapter.go` + `ports.ToolDescriptor` | +| P0-4 | P0 | MCP `pending` map 在超时/提前返回路径泄漏,长期运行内存持续增长 | `internal/infrastructure/ai/mcp_sse_client.go` `callRPC` | +| P0-5 | P0 | `MCPSSEClient.ensureStarted` 并发首次调用会返回 `post url is not set` | `internal/infrastructure/ai/mcp_sse_client.go` `ensureStarted` | +| P0-6 | P0 | 流式取消时 `OpenAIClient.Stream` 可能永久阻塞在 `events <- ...`,goroutine 泄漏 | `internal/infrastructure/ai/openai_client.go` `Stream` | +| P0-7 | P0 | `writeError(c, nil)` 会 panic | `internal/trigger/http/agent_handler.go` `writeError` | +| P0-8 | P0 | 没有优雅停机,进程收到 SIGTERM 直接中断在途请求 | `cmd/server/main.go` / `bootstrap.Engine` | +| P0-9 | P0 | 同一 MCP SSE 工具被第二张表重复注册时返回 nil,该表拿到不可调用的占位工具 | `mcp_sse_client.go` `RegisterAndExpand` + `tools.go` `BuildTools` | +| P1-1 | P1 | Skill 工具只暴露不可执行,模型调用必然失败 | `internal/infrastructure/ai/tools.go` + `mcp_sse_client.go` `CallTool` | +| P1-2 | P1 | `max-iterations` 配置完全无效,`loop` 与 `parallel` 都退化为 fan-out | `internal/infrastructure/adk/adapter.go` | +| P1-3 | P1 | `parallel` 不是真正并发,串行执行 | `internal/infrastructure/adk/adapter.go` `runFanOut` | +| P1-4 | P1 | HTTP 请求 context 未传递到 Agent,取消/超时失效 | `adapter.go` `Runner.Run/Stream/notifyPlugins` | +| P1-5 | P1 | 调用方可传任意 `sessionId`,不校验归属 | `internal/domain/agent/service/chat/service.go` `resolveRunnerSession` | +| P1-6 | P1 | Session 只存 ID 不存消息,实际无多轮上下文 | `ports.SessionStore` + `adapter.go` `initialMessages` | +| P1-7 | P1 | 并发 `CreateSession` 存在竞态,可能创建多个会话互相覆盖 | `chat/service.go` `CreateSession` | +| P1-8 | P1 | 配置校验缺失:子 Agent 不存在/重名、`runner.agent-name`、skill 路径等 | `internal/app/config/loader.go` `validateTable` | +| P1-9 | P1 | 工具参数 schema 被硬编码为 `query`,与真实 MCP 工具入参不匹配 | `openai_client.go` `encodeTools` | +| P1-10 | P1 | `stdio` / `local` 传输运行时不可执行,配置了也只能报错 | `mcp_sse_client.go` `CallTool` | +| P2-1 | P2 | `AgentWorkflowNode.Apply` 递归实现,可读性差 | `armory/workflow/agent_workflow_node.go` | +| P2-2 | P2 | `DynamicContext.agentGroup` 以名称为 key,重名覆盖、缺失静默跳过 | `armory/context.go` | +| P2-3 | P2 | `map` 遍历装配顺序不确定 | `armory/service.go`、`loader.go`、`bootstrap.loadAgentTables` | +| P2-4 | P2 | 跨文件同名 table 静默覆盖 | `internal/app/bootstrap/bootstrap.go` `loadAgentTables` | +| P2-5 | P2 | 环境变量在 YAML 解析前展开,值含 YAML 特殊字符会破坏结构 | `internal/app/config/loader.go` `expandEnvPlaceholders` | +| P2-6 | P2 | `yaml.Unmarshal` 非严格模式,字段拼写错误静默忽略 | `loader.go` / `application.go` | +| P2-7 | P2 | `application.yaml` 不做环境变量替换,DB/Redis 配置无法通过 env 注入 | `internal/app/config/application.go` `LoadApplication` | +| P2-8 | P2 | MySQL / Redis 适配器完全未接入 | `bootstrap.Build` | +| P2-9 | P2 | 应用配置校验偏弱(app.name / server.addr / config-paths / required 资源) | `application.go` | +| P2-10 | P2 | `MCPToolRouter` 无锁,运行期读写潜在数据竞争 | `mcp_sse_client.go` `MCPToolRouter` | +| P2-11 | P2 | 内容为空时报 `0001` 且先建 Session 后校验内容 | `chat/service.go` `resolveRunnerSession` | +| P2-12 | P2 | DTO 无 `binding` 校验,`GET /create_session` 无参数校验 | `internal/api/dto/agent.go`、`agent_handler.go` | +| P2-13 | P2 | SSE 无心跳、未处理客户端断连 | `agent_handler.go` `chatStream` | +| P2-14 | P2 | 未知错误直接回显内部信息(上游 URL、片段) | `agent_handler.go` `writeError` | +| P2-15 | P2 | 日志不可配置,Gin 访问日志未接 zap,插件用 `fmt.Printf`,`logger.Fatal` 跳过 `Sync` | `logging/logger.go`、`bootstrap.newRouter`、`adapter.go` 插件 | +| P2-16 | P2 | `CreateSession` 不校验 Agent 是否仍存在 | `chat/service.go` `CreateSession` | +| P2-17 | P2 | Service 层方法无 `context.Context` | `chat/service.go` 方法签名 | +| P2-18 | P2 | `http.Server` 缺少读写/空闲超时,`Engine` 无 `Close` | `bootstrap.go` `Engine.Run` | +| P3-1 | P3 | `internal/infrastructure/dependencies` 从未被 import,blank import 不生效 | 该目录 | +| P3-2 | P3 | 全局死代码与未使用接口(详见附录) | 多处 | +| P3-3 | P3 | `EmbeddingsPath` 定义但未使用 | `model/config.go` / `eino_adapter.go` | +| P3-4 | P3 | `AgentFactory` 为三种 workflow 各定义一个方法,接口冗余 | `ports/ports.go` | +| P3-5 | P3 | 错误码体系过少,`Code` 为 `string` 无编译期约束 | `pkg/types` | +| P3-6 | P3 | `AppError` 不含上下文(agentId 等)与错误链 | `pkg/types/errors.go` | +| P3-7 | P3 | `ports.SessionStore` 无 `context.Context`,限制 Redis 接入 | `ports/ports.go` | +| P3-8 | P3 | 项目零测试 | 全仓库 | +| P3-9 | P3 | `gofmt -l .` 报告所有文件(CRLF 行尾) | 全仓库 | +| P3-10 | P3 | CORS 缺少 `Expose-Headers` / `Max-Age`,`Vary` 处理不完整 | `corsMiddleware` | +| P3-11 | P3 | `ChatContent` 的 Files / InlineDatas 被静默忽略 | `adapter.go` `firstText` | +| P3-12 | P3 | `InMemoryAgentRegistry.Register` 无任何校验且恒返回 nil | `ports/ports.go` | +| P3-13 | P3 | Session key 用 `:` 拼接存在歧义 | `ports/ports.go` `sessionKey` | +| P3-14 | P3 | `Agent.Description()` / `ChatModel.Tools()` 等接口方法未被使用 | 多处 | + +> 注:第二轮复核还补充了 P1-11 ~ P1-14、P2-19 ~ P2-25、P3-15 ~ P3-23,见文末 [第二轮复核补充](#第二轮复核补充) 章节;其中包含对 P0-9 描述的修正。 + + +--- + +## P0 严重问题 + +### P0-1 CORS 允许任意 Origin 携带凭证 + +**位置**:`internal/app/bootstrap/bootstrap.go:120-138` `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") +``` + +### P0-2 `.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=` 等模式。 + +### P0-3 工具描述全部丢失,模型只能看到兜底描述 + +**位置**: + +- 接口定义:`internal/domain/agent/ports/ports.go:61-63` `ToolDescriptor` +- 消费方:`internal/infrastructure/ai/eino_adapter.go:91-104` `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` 的类型断言,同时提供统一的描述访问方式,避免以后再漏。 + +### P0-4 MCP `pending` map 在超时/提前返回路径泄漏 + +**位置**:`internal/infrastructure/ai/mcp_sse_client.go:402-453` `callRPC` + +```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`。 + +### P0-5 `ensureStarted` 并发首次调用会失败 + +**位置**:`internal/infrastructure/ai/mcp_sse_client.go:63-102` `ensureStarted` + +```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`,让并发调用者等待初始化完成或拿到同一个初始化错误。 + +### P0-6 流式取消时 `OpenAIClient.Stream` goroutine 泄漏 + +**位置**:`internal/infrastructure/ai/openai_client.go:89-174` `Stream`,尤其: + +```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-7 `writeError(c, nil)` 会 panic + +**位置**:`internal/trigger/http/agent_handler.go:102-109` `writeError` + +```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 +} +``` + +### P0-8 没有优雅停机 + +**位置**:`cmd/server/main.go:44-51`、`internal/app/bootstrap/bootstrap.go:93-102` `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) +``` + +这同时解决 P2-18(`http.Server` 无超时)。 + +### P0-9 重复注册 MCP SSE 工具导致第二张表拿到不可调用占位工具 + +**位置**:`internal/infrastructure/ai/mcp_sse_client.go:518-554` `RegisterAndExpand` 与 `internal/infrastructure/ai/tools.go:91-106` `BuildTools` + +```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 一调工具就报错」。注意:这与 P1-10 的 stdio/local「transport not supported」是两条不同的错误路径。 + +**修复方案**(任一): + +1. `RegisterAndExpand` 命中已存在时,返回该 client 已展开的真实工具列表(需要缓存 `expandedByServer`)。 +2. `BuildTools` 在 `len(ts) == 0` 时不要静默跳过,而是报错提示「工具已被注册」。 +3. 更彻底:把 MCP client 的复用键改为 `baseURI+endpoint`,工具名到 client 的映射独立维护。 + +推荐方案 1 或 3,并为「多表共享同名 MCP」补测试。 + +--- + +## P1 高优先级问题 + +### P1-1 Skill 工具只暴露、不可执行 + +**位置**:`internal/infrastructure/ai/tools.go`(`SkillFactory`)、`internal/infrastructure/ai/mcp_sse_client.go:564-579` `CallTool` + +**问题概述**: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-2 `max-iterations` 配置无效 + +**位置**:`internal/app/config/loader.go:86-90`(补默认值)、`internal/infrastructure/adk/adapter.go:70-72,96-107,136-137`(构建与分发) + +**问题概述**: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。 + +### P1-3 `parallel` 并非真正并发 + +**位置**:`internal/infrastructure/adk/adapter.go:330-348` `runFanOut` + +**问题概述**:`runFanOut` 是普通 for 循环,子 Agent 串行执行;`parallel` 命名与实际行为不符。 + +**影响**:并行工作流没有加速效果,多子 Agent 场景延迟线性叠加。 + +**修复方案**:`runFanOut` 改为 `goroutine + sync.WaitGroup + 有序结果切片`,并考虑子 Agent 的失败策略(快速失败 or 全部收集)。注意 `router`/`chatModel` 的并发安全性——当前 `OpenAIClient` 并发安全(只读字段),`MCPToolRouter` 需加锁(见 P2-10)。 + +### P1-4 HTTP 请求 context 未传递到 Agent + +**位置**:`internal/infrastructure/adk/adapter.go:403-415` `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`。 + +### P1-5 `sessionId` 不校验归属 + +**位置**:`internal/domain/agent/service/chat/service.go:97-116` `resolveRunnerSession` + +**问题概述**:只要 `command.SessionID != ""` 就直接使用,不校验它是否属于该 `userId` / `agentId`,也不校验是否存在。 + +**影响**:任意调用方可传入他人 sessionId;虽然当前 session 无状态、危害有限,但一旦引入对话历史(P1-6)或计费,就是越权访问。 + +**修复方案**:`SessionStore` 增加 `Validate(userID, agentID, sessionID) bool` 或让 `Get` 返回后比对;`resolveRunnerSession` 中先校验再使用,不匹配返回 `CodeIllegalParameter`。 + +### P1-6 Session 无对话历史(Agent 实际无状态) + +**位置**:`internal/domain/agent/ports/ports.go:142-167` `InMemorySessionStore`、`internal/infrastructure/adk/adapter.go:375-386` `initialMessages` + +**问题概述**:`SessionStore` 只保存 `userID:agentID -> sessionID` 字符串,不保存消息历史;`runLLM` 每次都从 `[system, user]` 重建消息。 + +**影响**:看似支持多轮对话,实则每轮独立;前端「上下文」只能靠把上一轮 XML 拼进 message 来绕过。这是产品能力的核心缺口。 + +**修复方案**: + +- 新增 `ConversationStore` 端口,保存 `sessionID -> []ChatMessage`。 +- `Runner.Run` 前加载历史并追加到 `initialMessages` 之后;执行完成后把 user + assistant 消息写回。 +- 内存实现先用带锁 map,后续可替换 Redis/MySQL。 +- 注意消息裁剪(token 预算)与并发写同一 session 的顺序问题。 + +### P1-7 `CreateSession` 并发竞态 + +**位置**:`internal/domain/agent/service/chat/service.go:37-53` `CreateSession` + +**问题概述**:`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`。 + +### P1-8 配置校验缺失 + +**位置**:`internal/app/config/loader.go:93-135` `validateTable` + +**问题概述**:只校验了必填字段、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 字段。 + +### P1-9 工具参数 schema 硬编码为 `query` + +**位置**:`internal/infrastructure/ai/openai_client.go:278-299` `encodeTools` + +**问题概述**:所有工具的参数 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-10 `stdio` / `local` 传输运行时不可执行 + +**位置**:`internal/infrastructure/ai/tools.go:368-434`(构建)、`mcp_sse_client.go:564-579` `CallTool` + +**问题概述**:配置层支持 stdio/local,`buildStdioMCPTools` 会构建 `MCPTool`,但运行时 `CallTool` 只处理 `clients` 里的 SSE 客户端,stdio/local 一律报「transport not supported in runtime」/「not callable」。此外 local 传输是更彻底的桩:`buildLocalMCPTools`(`tools.go:368-381`)只认识硬编码的 `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,并同步修正文档,避免用户踩坑。 + +--- + +## P2 中优先级问题 + +### P2-1 `AgentWorkflowNode.Apply` 递归实现 + +**位置**:`internal/domain/agent/service/armory/workflow/agent_workflow_node.go:40-57` + +**问题概述**:用尾递归遍历 workflows,逻辑隐晦;虽然当前 `NewDynamicContext()` 每次全新、递归深度可控,但可读性差。 + +**影响**:维护成本,且未来若支持复用 context 会引入「从中间继续」的隐式语义。 + +**修复方案**:按参考文档改为 for 循环版本,并同步清理 `currentStepIndex`(若采用「循环版本一」)。改动量很小(单文件),行为等价。 + +### P2-2 `DynamicContext.agentGroup` 名称覆盖与静默跳过 + +**位置**:`internal/domain/agent/service/armory/context.go:27-50` + +**问题概述**: + +- `agentGroup[agent.Name()]` 同名覆盖,后注册的赢; +- `QueryAgentList` 对不存在的名字静默跳过,可能构造出缺子 Agent 甚至空 workflow。 + +**影响**:配置错误被掩盖,运行时行为与预期不符。 + +**修复方案**:`AddAgent` 检测重名并报错(或在 loader 校验 Agent 唯一性);`QueryAgentList` 返回缺失的名称列表,由调用方决定是否报错。 + +### P2-3 装配与加载顺序不确定 + +**位置**:`internal/domain/agent/service/armory/service.go:17-24`、`internal/app/config/loader.go:35-41`、`internal/app/bootstrap/bootstrap.go:152-154` + +**问题概述**:多处 `for name, table := range tables`,Go map 遍历顺序随机。 + +**影响**:多表装配顺序、注册顺序不稳定;对依赖注册顺序的扩展(如后注册覆盖前注册)会不确定。 + +**修复方案**:把 `tables` 改为按 name 排序后的切片再遍历,保证确定性。 + +### P2-4 跨文件同名 table 静默覆盖 + +**位置**:`internal/app/bootstrap/bootstrap.go:140-156` `loadAgentTables` + +```go +for name, table := range tables { + merged[name] = table // 后加载文件覆盖先加载 +} +``` + +**影响**:两个 YAML 文件里写了同名 table 时,前者被静默丢弃,排查困难。 + +**修复方案**:合并时检测重复并报错,或明确「后者覆盖前者」并打警告日志。 + +### P2-5 环境变量在 YAML 解析前展开 + +**位置**:`internal/app/config/loader.go:23-24,60-72` + +**问题概述**:`expandEnvPlaceholders(string(data))` 先做字符串替换,再 `yaml.Unmarshal`。 + +**影响**:环境变量值包含 YAML 特殊字符(`:`、`#`、换行、引号)时会破坏 YAML 结构,报错信息指向解析失败而非环境变量。 + +**修复方案**:给 `.env` 值加引号的约定(文档化);或改为「先解析,再对字符串字段做展开」,从根上避免注入破坏结构。 + +### P2-6 YAML 非严格解析 + +**位置**:`internal/app/config/loader.go:26`、`internal/app/config/application.go:75` + +**问题概述**:`yaml.Unmarshal` 忽略未知字段,字段名拼错不会报错。 + +**影响**:如 `base-url` 写成 `base_url` 会静默取零值,最终表现为「必填校验失败」或运行异常,定位成本高。 + +**修复方案**:使用 `yaml.NewDecoder(bytes.NewReader(...))` + `dec.KnownFields(true)` 开启严格模式。 + +### P2-7 `application.yaml` 不做环境变量替换 + +**位置**:`internal/app/config/application.go:69-87` `LoadApplication` + +**问题概述**:直接 `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}` 等占位符。 + +### P2-8 MySQL / Redis 适配器未接入 + +**位置**:`internal/app/bootstrap/bootstrap.go:49-50` + +**问题概述**:始终使用 `NewInMemoryAgentRegistry()` / `NewInMemorySessionStore()`,`persistence.OpenMySQL` 与 `cache.OpenRedis` 无人调用。 + +**影响**: + +- 重启丢会话; +- 多实例无法共享; +- 适配器代码长期未被验证,可能已腐化。 + +**修复方案**:在 `bootstrap.Build` 中根据 `appCfg.Database.Required/DSN`、`appCfg.Redis.Required/Addr` 决定是否打开,并让 `SessionStore` 走 Redis 实现(需先解决 P3-7 的 context 问题)。`Required=false` 时保持内存实现并打日志说明。 + +### P2-9 应用配置校验偏弱 + +**位置**:`internal/app/config/application.go:69-87` + +**问题概述**:只校验 `llm.request-timeout`,未校验 `app.name`、`server.addr` 合法性、`agent.config-paths` 非空、`required=true` 时 DSN/Addr 非空。 + +**影响**:错误配置延迟到 bootstrap 或运行时,报错不明确。 + +**修复方案**:在 `LoadApplication` 末尾统一做一次语义校验,返回聚合错误(含字段名),让启动即失败、失败信息可操作。 + +### P2-10 `MCPToolRouter` 无锁 + +**位置**:`internal/infrastructure/ai/mcp_sse_client.go:487-579` `MCPToolRouter` + +**问题概述**:`clients` / `tools` / `registered` / `listFailures` 都是普通 map,没有任何互斥保护。当前写入只发生在启动阶段(单 goroutine),运行时只读,勉强安全;但一旦支持热更新、延迟注册或并发 `BuildTools`,就是数据竞争。 + +**影响**:潜在 `fatal error: concurrent map read and map write`,进程直接崩溃。 + +**修复方案**:给 `MCPToolRouter` 加 `sync.RWMutex`,所有读写走锁;`CallTool` 读路径用 RLock。 + +### P2-11 空内容错误码不准确 + 先建 Session 后校验内容 + +**位置**:`internal/domain/agent/service/chat/service.go:102-115` + +```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-12 DTO 缺少 binding 校验 / GET 接口无校验 + +**位置**:`internal/api/dto/agent.go`、`internal/trigger/http/agent_handler.go:39-64` + +**问题概述**: + +- `CreateSessionRequest`、`ChatRequest` 都没有 `binding:"required"`; +- `GET /create_session` 直接取 query 参数,为空要到下游才报错; +- `message` 无长度限制。 + +**影响**:无效请求返回 `0001` 而不是 `0002`;超长 message 直接送入模型,浪费 token 并可能触发上游 400。 + +**修复方案**:给必填字段加 `binding:"required"`;给 `Message` 加 `binding:"max=..."`;GET 接口显式校验或改为 POST 单一入口。 + +### P2-13 SSE 无心跳、未处理客户端断连 + +**位置**:`internal/trigger/http/agent_handler.go:82-100` `chatStream` + +**问题概述**:`chatStream` 只是 range outputs 并 flush,未发送心跳注释行,也未监听 `c.Request.Context().Done()`。 + +**影响**: + +- 反向代理(Nginx/网关)可能因长时间无数据断开连接; +- 客户端断开后后端仍继续生成,浪费模型调用。 + +**修复方案**:启动 `time.Ticker` 定期写 `: ping\n\n`;监听 `c.Request.Context().Done()` 并取消下游(依赖 P1-4)。 + +### P2-14 未知错误直接回显内部信息 + +**位置**:`internal/trigger/http/agent_handler.go:108` + +```go +c.JSON(http.StatusOK, response.Failure(types.CodeUnknownError, err.Error())) +``` + +**问题概述**:把内部错误原文返回给客户端,可能包含上游 URL、响应片段(`openai upstream 500: {...}`)、文件路径等。 + +**影响**:信息泄露,攻击者可据此探测上游服务。 + +**修复方案**:对外返回 `types.InfoUnknownError` 之类的通用文案,详细错误只写日志(配合 request id)。 + +### P2-15 日志体系不完善 + +**位置**:`internal/infrastructure/logging/logger.go`、`bootstrap.newRouter`、`adapter.go:525-571`、`main.go:33-51` + +**问题概述**: + +- 日志级别/格式/输出目标不可配; +- 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`。 + +### P2-16 `CreateSession` 不校验 Agent 是否仍存在 + +**位置**:`chat/service.go:37-40` + +**问题概述**:命中缓存直接返回旧 session,不检查 `registry` 中 Agent 是否还在。 + +**影响**:当前 registry 只增不删,问题不显现;支持热更新/下线后会出现「Agent 已下线仍可用」的不一致。 + +**修复方案**:命中缓存后仍做一次 `registry.Get(agentID)` 校验。 + +### P2-17 Service 层方法无 context + +**位置**:`internal/domain/agent/service/chat/service.go` 全部方法 + +**问题概述**:`CreateSession`、`HandleMessage`、`HandleCommand`、`HandleMessageStream`、`HandleCommandStream` 都不接收 context。 + +**影响**:无法实现超时/取消,与 P1-4 同源。 + +**修复方案**:统一加 `ctx context.Context` 作为首参,并透传。 + +### P2-18 `http.Server` 缺少超时、`Engine` 无 Close + +**位置**:`bootstrap.go:93-102` `Engine.Run` + +**问题概述**:`gin.Engine.Run` 内部创建默认 `http.Server`,无 `ReadHeaderTimeout`/`ReadTimeout`/`WriteTimeout`/`IdleTimeout`,存在慢速攻击与连接堆积风险;同时没有 `Close`/`Shutdown` 句柄。 + +**修复方案**:与 P0-8 一并改为显式 `http.Server` 并设置合理超时;为 `Engine` 增加 `Close(ctx)`。 + +--- + +## P3 优化点 + +> 本节按「为什么优化 / 方案 / 改动量 / 影响」描述。 + +### P3-1 `internal/infrastructure/dependencies` 从未被 import + +**为什么优化**:该包用 blank import 锚定 Eino / Google ADK / GORM 等依赖,但全仓库没有任何地方 import 它。包不被引用时,blank import 不会进入任何构建产物(只会在 `go build ./...` 时单独编译),因此「锚定依赖」的目的没有达到;而且 Eino 实际上完全没被业务代码使用。 + +**方案**: + +- 若确实需要保留依赖,在 `main` 或 bootstrap 中显式 import; +- 若不需要,删除该包,并 `go mod tidy` 清掉 `github.com/cloudwego/eino` 等未被真正引用的直接依赖; +- 注意 `google.golang.org/adk` 的 `plugin`/`loggingplugin` 被 `adk/adapter.go` 真实使用,需保留。 + +**改动量**:小(删包 + `go mod tidy`),可能引发 `go.sum` 变化。 + +**影响**:依赖图更真实,构建更快、更小的模块下载面;避免「以为在用 Eino」的误解。 + +### P3-2 全局死代码与未使用接口 + +**为什么优化**:死代码增加阅读与维护成本,也让「接口即契约」的意图失真。 + +**方案**:清理附录清单中的项,或明确保留并加注释说明预留原因。 + +**改动量**:小。 + +**影响**:代码可读性提升,减少误导。 + +### P3-3 `EmbeddingsPath` 定义但未使用 + +**为什么优化**:配置项存在但不生效会让使用者误以为支持 embedding。 + +**方案**:实现 embedding 客户端并在 Armory 中新增节点,或暂时从配置与文档中移除。 + +**改动量**:移除很小;实现则中等(新客户端 + 新节点 + 端口)。 + +**影响**:配置语义变清晰,或新增 RAG 能力。 + +### P3-4 `AgentFactory` 为三种 workflow 各定义一个方法 + +**为什么优化**:新增 workflow 类型要同时改端口、实现、Armory 节点,扩展成本高。 + +**方案**:统一为 `NewWorkflowAgent(ctx, workflowType, config, subAgents)`,由实现内部按 type 分派;或让 `AgentFactory` 只保留 `NewLLMAgent` + `NewWorkflowAgent`。 + +**改动量**:小-中(端口 + factory + 三个 node 文件)。 + +**影响**:扩展新 workflow 只需改一处;接口更内聚。 + +### P3-5 错误码体系过少、`Code` 为裸 string + +**为什么优化**:除 `0002`/`0003` 外全部落到 `0001`,前端无法区分错误类型;裸 string 让编译器无法约束。 + +**方案**: + +```go +type Code string +const ( + CodeSuccess Code = "0000" + ... +) +type AppError struct { + Code Code + Info string +} +``` + +并补充上游错误、工具错误、超时、未授权等码。 + +**改动量**:中(触及 `types`、`response`、handler、service)。 + +**影响**:前端可做差异化处理;错误码生成受编译期约束。 + +### P3-6 `AppError` 不含上下文与错误链 + +**为什么优化**:`AppError` 只有 `Code`/`Info`,无法携带 `agentId`、`sessionId`、`cause`,排障依赖日志拼凑。 + +**方案**:增加 `Cause error`、`Meta map[string]string`,实现 `Unwrap()`;在关键路径包装错误。 + +**改动量**:中。 + +**影响**:`errors.Is/As` 可用,错误可携带上下文,排障更快。 + +### P3-7 `ports.SessionStore` 无 context + +**为什么优化**:接口无 context,Redis/MySQL 实现只能内部用 `context.Background()`,无法随请求取消/超时。 + +**方案**:`Get(ctx, ...)` / `Set(ctx, ...)`,同步改内存实现与调用方。 + +**改动量**:小-中。 + +**影响**:为 P2-8 的 Redis 接入铺路。 + +### P3-8 项目零测试 + +**为什么优化**:核心模块(MCP 解析、SSE 累积、Tool-Calling Loop、Armory)都是易回归逻辑,没有测试无法安全重构(本报告的多数修复都缺回归保障)。 + +**方案**: + +- 优先 `openai_client.go` 的流式 tool call 累积(用 httptest 模拟 SSE); +- 优先 `mcp_sse_client.go` 的 JSON-RPC 匹配与超时清理(httptest 模拟 SSE + POST); +- `adapter.go` 的 sequential/loop/fan-out 用 fake ChatModel/ToolRouter; +- `loader.go` 的校验用例。 + +**改动量**:中-大(但收益最高)。 + +**影响**:重构可控,回归成本下降;也是「面试能讲」的加分项。 + +### P3-9 `gofmt -l .` 报告所有文件(CRLF) + +**为什么优化**:仓库设置 `core.autocrlf=true`,工作区文件是 CRLF,`gofmt` 认为所有文件格式不一致。若 CI 跑 `gofmt -l` 会全部误报。 + +**方案**:添加 `.gitattributes`(`* text=auto`、`*.go text eol=lf`)并在 CI 中固定 `gofmt` 校验。 + +**改动量**:很小。 + +**影响**:格式化校验可用,避免无关 diff 噪音。 + +### P3-10 CORS 缺少 `Expose-Headers` / `Max-Age` + +**为什么优化**:预检结果无法缓存,增加 OPTIONS 请求;若未来返回自定义头前端读不到。 + +**方案**:与 P0-1 一起补 `Access-Control-Max-Age` 和必要的 `Access-Control-Expose-Headers`。 + +**改动量**:很小。 + +**影响**:减少预检开销,前端可用性更完整。 + +### P3-11 `ChatContent` 的 Files / InlineDatas 被静默忽略 + +**为什么优化**:领域模型声明支持文件与内联数据,但 `firstText` 只取第一段文本,OpenAI 请求里也没有多模态内容编码,属于「声明支持但实际丢弃」。 + +**方案**:实现多模态 message 编码(image_url / input_file),或明确不支持并在 DTO 层拒绝。 + +**改动量**:中。 + +**影响**:消除静默丢弃;若实现则打开多模态能力。 + +### P3-12 `InMemoryAgentRegistry.Register` 无校验且恒返回 nil + +**为什么优化**:`Register` 声明返回 error 但永远 nil;空 `AgentID` 会互相覆盖到 `""`。 + +**方案**:校验 `AgentID` 非空、重复注册报错(或显式允许覆盖)。 + +**改动量**:很小。 + +**影响**:装配期即可发现 Agent 配置问题。 + +### P3-13 Session key 用 `:` 拼接存在歧义 + +**为什么优化**:`userID + ":" + agentID`,当 ID 自身含 `:` 时可能碰撞(如 `a:b` + `c` 与 `a` + `b:c`)。 + +**方案**:改用长度前缀编码、`\x00` 分隔或 `struct{userID, agentID string}` 作为 map key。 + +**改动量**:很小。 + +**影响**:消除边界情况。 + +### P3-14 未使用的接口方法 + +**为什么优化**:`ChatModel.Tools()`、`MCPToolRouter.Tools()`/`Register()`、`Agent.Description()`、`DynamicContext.values`/`SetValue`/`Value`、`currentWorkflow`、`types.InfoIllegalParameter`、`types.InfoUnknownError` 等要么未使用、要么只写不读。 + +**方案**:按附录清理或明确预留并注释。 + +**改动量**:小。 + +**影响**:减少「看起来有用其实没用」的误导。 + +--- + +## 第二轮复核补充 + +> 本节是对全文二次通读的结果,补充第一版报告遗漏的问题与优化点。 +> 编号沿用主报告体系(P1-11 / P2-19 / P3-15 ...),严重程度定义与主报告一致。 + +### 对 P0-9 描述的修正 + +第一版把重复注册的运行时错误描述为走 `case MCPTool:` 返回 "transport not supported"。二次核对 `MCPToolRouter.CallTool` 后确认该描述不准确: +`CallTool` 先查 `r.clients[name]`(`mcp_sse_client.go:565`),而配置名 `baidu-search` 在第一张表注册时已写入 `clients`,因此实际会转发 `tools/call {name:"baidu-search"}` 到 MCP Server,由服务端报「工具不存在」。 +结论不变(第二张表拿到不可用工具),但错误来源不同,已同步修正 P0-9 正文。 + +### P1-11 `docker-compose.yml` 中 redis 引用了未声明的网络,compose 无法启动 + +**位置**:`deployments/docker-compose.yml:38-43` + +```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`。 + + +### P1-12 全项目没有鉴权,`userId` 完全由客户端控制 + +**位置**:`internal/trigger/http/agent_handler.go`(无认证中间件)、`internal/api/dto/agent.go:9-23` + +**问题概述**:所有 `/api/v1/*` 接口完全开放;`userId` 直接取自请求体/query,服务端不校验其真实性,也不与任何凭证绑定。前端登录页只是把 `user` 写进 Cookie,后端完全不感知(`grep "Auth|middleware" internal/trigger internal/app` 只命中 CORS 里的 `Authorization` 头名)。 + +**影响**: + +- 任何调用方可伪造任意 `userId`,以他人身份创建会话、发消息、读同一 Session 上下文(P1-5 的 sessionId 不校验会进一步放大); +- 一旦引入对话历史/计费/审计,就是越权与数据泄露; +- `createSessionQuery` 允许 GET 传 `userId`,更易被日志/Referer 泄露。 + +**修复方案**:接入认证中间件(JWT / API Key / 网关透传身份),从凭证解析 `userId` 而非信任入参;至少在 `chat.Service` 层校验 `userId` 与凭证一致。CORS 已允许 `Authorization` 头,具备接入条件。 + +### P1-13 `adkRunnerPlugin` 是空壳,`myLogPlugin` 实际没有任何 ADK 日志能力 + +**位置**:`internal/infrastructure/adk/adapter.go:558-572` + +```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`(与 P2-15 合并处理)。 + + +### P1-14 MCP 启动期工具发现失败时,会把「服务端标签」当工具暴露给模型且不告警 + +**位置**:`internal/infrastructure/ai/mcp_sse_client.go:518-554`、`internal/infrastructure/ai/tools.go:91-106` + +```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 启动时不可达/超时(或如 P0-9 的重复注册)时,`BuildTools` 会把 `MCPTool{ToolName:"baidu-search"}` 作为「工具」返回给 ChatModel。模型看到一个名为 `baidu-search` 的 function,但该名字不是服务端真实工具,运行时 `tools/call` 必然失败;`listFailures` 只写不读,启动既不失败也不打日志。 + +**影响**:把不可用工具暴露给模型导致运行期报错;「降级保留占位工具」的初衷(启动不中断 + 错误清晰)没有达成,属于静默劣化。 + +**修复方案**:启动期区分「连接失败」与「无工具」,失败时记 `listFailures` 并打警告日志,或按 `required` 语义 fail fast;不要把配置名当可调用工具暴露;若保留占位,运行时应给出「MCP Server 未就绪」的明确错误。 + +### P2-19 MySQL 库名与端口在三个文件里互不一致 + +**位置**:`deployments/docker-compose.yml:10`、`configs/application.yaml:8`、`.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 目前未接入,问题被掩盖;一旦按 P2-8 启用 MySQL,连接会直接失败(库不存在)。 + +**影响**:启用持久化时立刻踩坑;三处配置让排查成本变高。 + +**修复方案**:统一为一个库名(建议 `ai_agent_scaffold_go`)与一个端口(compose `13306`),并让 `application.yaml` 用 `${MYSQL_DSN}` 占位符(依赖 P2-7),使 `.env` 成为唯一事实来源。 + +### P2-20 `.env` 里的 `APP_ENV` 与 `SERVER_ADDR` 根本不生效 + +**位置**:`cmd/server/main.go:24-32`、`internal/app/config/application.go:78-83` + +**问题概述**:`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` 不会改端口。属于典型的「看似可配实际无效」,与 P2-7 同源但影响面更直接。 + +**修复方案**:让 `LoadApplication` 展开 `${APP_ENV}` / `${SERVER_ADDR}` 占位符(P2-7 的统一解法),或在文档中明确这两个变量无需配置并从 `.env.example` 删除以免误导。 + + +### P2-21 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。 + +### P2-22 `io.ReadAll` 无上限读取上游响应体 + +**位置**:`internal/infrastructure/ai/openai_client.go:57,108`、`internal/infrastructure/ai/mcp_sse_client.go:119` + +**问题概述**:三处都用 `io.ReadAll` 把响应体一次性读入内存,没有任何大小限制。`truncate(...,400)` 只截断错误文案,读入本身仍是全量。 + +**影响**:异常/恶意上游返回超大响应(或错误页)时可导致内存快速膨胀,属于 DoS 面;对非流式 `Generate` 尤其明显。 + +**修复方案**:用 `io.LimitReader`(如 4~8 MiB)限制读取并在超限时返回明确错误;错误体只需读几百字节。 + +### P2-23 流式请求没有发送 `Accept: text/event-stream` + +**位置**:`internal/infrastructure/ai/openai_client.go:199-208` `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` 并给出明确错误。 + + +### P2-24 无法配置任何生成参数 + +**位置**:`internal/domain/agent/model/config.go:38-42` `ChatModelConfig`、`internal/infrastructure/ai/openai_client.go:220-234` `buildRequestBody` + +**问题概述**:`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 三处,向后兼容。 + +### P2-25 本地路径解析依赖进程 CWD,从其他目录启动会失败 + +**位置**:`internal/infrastructure/ai/tools.go:166-185` `resolveSkillRoot`(`os.Getwd()`)、`internal/app/bootstrap/bootstrap.go:147`(`os.ExpandEnv(path)` 后直接 `os.ReadFile`) + +**问题概述**:技能路径通过「从当前工作目录逐级向上找候选」解析;`agent.config-paths` 与 `.env` 路径也相对 CWD。代码没有以可执行文件位置或配置目录为基准。 + +**影响**:用 systemd / 容器 / IDE 以不同 `WORKDIR` 启动时可能找不到技能或 Agent 配置;`skillPathCandidates` 里硬编码的 `ai-agent-scaffold-go` 目录名让解析逻辑对仓库名敏感。 + +**修复方案**:以「配置文件所在目录」或显式 `APP_BASE_DIR` 环境变量为基准解析相对路径;技能路径优先支持绝对路径并给出清晰错误;去掉硬编码的仓库目录名候选。 + +### P3-15 `MCPToolRouter` 的 `registered` / `listFailures` 是死字段,`notify` 不校验状态码 + +**位置**:`internal/infrastructure/ai/mcp_sse_client.go:490-492,540,548`、`notify` 在 `:458-485` + +**问题概述**: + +- `registered map[string]struct{}` 只写不读(第 548 行写、无任何读取); +- `listFailures map[string]error` 只写不读(第 540 行写、无任何读取); +- `notify()` 丢弃响应体后不检查 `StatusCode`。 + +**影响**:死字段误导读者;`notifications/initialized` 若被服务端拒绝(4xx/5xx),客户端仍认为握手成功,后续调用才报莫名的错。 + +**修复方案**:删除死字段(或让 `listFailures` 真正参与启动告警);`notify` 增加状态码校验。 + +### P3-16 空列表响应会缺少 `data` 字段,与前端约定的响应契约不一致 + +**位置**:`internal/api/response/response.go:5-9` + +```go +type Envelope[T any] struct { + Code string `json:"code"` + Info string `json:"info"` + Data T `json:"data,omitempty"` +} +``` + +**问题概述**:`omitempty` 对切片在 `len == 0` 时同样生效。`queryAgentConfigList` 返回的 `responses` 是 `make(..., 0, len)` 的空切片,序列化后 `data` 字段直接消失,响应变成 `{"code":"0000","info":"success"}`。 + +**影响**:与「统一 `{code, info, data}`」的约定不符;弱类型/严格反序列化的客户端会意外。当前前端用 `res.data || []` 兜底所以没暴露,但契约已经不一致。 + +**修复方案**:去掉 `Data` 的 `omitempty`(失败时输出 `"data":null`,需确认可接受),或让 handler 对空结果也返回非 nil 空切片,并在文档中明确空结果行为。 + + +### P3-17 `prod` 环境判断在多处重复 + +**位置**:`internal/app/bootstrap/bootstrap.go:105,110`、`internal/infrastructure/logging/logger.go:6` + +**问题概述**:`env == "prod" || env == "production"` 出现了三次,且 `bootstrap` 还要正反各判断一遍。 + +**影响**:新增环境名(如 `staging`/`release`)需要改多处,易漏。 + +**修复方案**:抽 `func isProduction(env string) bool`(放在 `app/config` 或 `pkg`),三处复用。 + +### P3-18 `.gitignore` 忽略了 `docs/`,`CLAUDE.md` 也被忽略 + +**位置**:`.gitignore:16-20` + +```text +# Learning docs (personal study materials) +docs/ +# Claude Code (personal AI assistant config) +CLAUDE.md +``` + +**问题概述**:本次生成的 `docs/项目完善报告.md` 以及项目讲解文档都在被忽略的 `docs/` 下;`CLAUDE.md` 同样不入库。 + +**影响**:如果这批文档要随项目交付/评审/招聘展示,当前不会进版本库,也不会出现在远端。 + +**修复方案**:若需要交付,改为只忽略 `docs/` 下的个人子目录(如 `docs/personal/`),把项目文档纳入版本控制;否则在 README 中说明文档不随仓库分发。 + +### P3-19 工作区 `.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`。 + +### P3-20 `validateTable` 错误顺序随机,timeout 校验文案与行为不符 + +**位置**:`internal/app/config/loader.go:95-107`、`loader.go:170,181` + +**问题概述**: + +- 必填字段放在 `map[string]string` 里遍历,Go map 顺序随机,同一份错误配置每次报错字段可能不同; +- `request-timeout < 0` 才报错,文案却是 "must be positive",即 `0` 被允许(随后被 `normalizeTimeout` 改成 300000)。 + +**影响**:错误信息不稳定,测试/排障时对不上;文案误导用户以为 0 非法。 + +**修复方案**:必填校验改为有序 `[]struct{name, value string}`;明确 `0` 的语义(「使用默认值」)并把文案改为 `must not be negative`。 + + +### P3-21 缺少就绪探针/指标,SSE 响应头不完整 + +**位置**:`internal/app/bootstrap/bootstrap.go:114-116`(`/healthz`)、`internal/trigger/http/agent_handler.go:90` + +**问题概述**: + +- 只有 `/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 标准响应头。 + +### P3-22 本地基础设施配置存在遗留项与弱口令 + +**位置**:`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 标注「仅本地示例」。 + +### P3-23 其他值得顺手处理的小问题 + +**位置**:多处 + +| 问题 | 位置 | 说明 / 建议 | +|---|---|---| +| 入站请求体无大小限制 | `internal/trigger/http/agent_handler.go` 的 `ShouldBindJSON` | 未使用 `http.MaxBytesReader` 或 Gin body limit,超大 JSON 可导致内存膨胀;与 P2-22 对称,建议加统一上限 | +| 没有编译期接口断言 | `ports/ports.go` 及各 adapter | 建议加 `var _ ports.ChatModel = (*EinoChatModel)(nil)` 之类的断言,避免接口漂移在运行期才暴露 | +| `Eino*` 命名与实际实现不符 | `internal/infrastructure/ai/eino_adapter.go` | 类型叫 `EinoProvider`/`EinoChatModel`/`EinoTool`,但实现完全基于自研 `OpenAIClient`,Eino 未被使用(见 P3-1);建议改名为 `OpenAIProvider` 等,减少误导 | +| `AgentWorkflowNode.build` 的 `buildOrder` 冗余 | `armory/workflow/agent_workflow_node.go:59-67` | 已有 `builders map[WorkflowType]workflowBuilder`,可直接 `n.builders[workflow.Type]` 查表,无需再维护 `buildOrder` 列表并循环匹配 | +| `DynamicContext` 封装风格不一致 | `armory/context.go:11-17` | `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` 存在不可达分支 | `internal/infrastructure/ai/tools.go:74-87` | `validateMCPConfig` 已保证 `kind` 是 local/sse/stdio 之一,后面 `case config.SSE != nil` / `case config.Stdio != nil` 是永远走不到的历史兼容分支,建议删除 | +| `LoadApplication` 忽略 `app/llm` 以外的语义校验 | `internal/app/config/application.go:69-87` | 与 P2-9 同源,建议一次性补齐并集中 | + +**影响**:均为小问题,不阻塞运行,但会累积成维护噪音。 + +**修复方案**:按上表逐项小改;建议与 P3-1、P3-17 一起作为一个「代码整洁」批次处理。 + + + +## 附录:全局死代码与冗余清单 + +| 项 | 位置 | 状态 | +|---|---|---| +| `maskSecretPath` | `internal/infrastructure/ai/tools.go:556` | 未被调用 | +| `mcpTimeoutString` | `internal/infrastructure/ai/tools.go:582` | 未被调用(唯一使用 `strconv` 的地方) | +| `ChatModel.Tools()` | `internal/domain/agent/ports/ports.go:54` | 未见调用 | +| `MCPToolRouter.Tools()` | `mcp_sse_client.go:557` | 未见调用 | +| `MCPToolRouter.Register()` | `mcp_sse_client.go:510` | 未见调用 | +| `Agent.Description()` | `adk/adapter.go:115` | 未见调用 | +| `DynamicContext.values` / `SetValue` / `Value` | `armory/context.go:17,76,82` | 只写不读(甚至没写) | +| `DynamicContext.currentWorkflow` | `armory/context.go:16,64,70` | 只写不读 | +| `types.InfoIllegalParameter` | `pkg/types/codes.go:9` | 未被引用 | +| `types.InfoUnknownError` | `pkg/types/codes.go:7` | 未被引用 | +| `EinoAPIConfig.EmbeddingsPath` | `eino_adapter.go:21` | 仅复制,未使用 | +| `internal/infrastructure/dependencies` 整个包 | 该目录 | 未被任何包 import | +| `github.com/cloudwego/eino` 直接依赖 | `go.mod` | 业务代码未使用 | + +--- + +## 附录:建议的落地顺序 + +1. **P0-1 / P0-2 / P0-7**:安全与崩溃类,改动小、收益大,先做。 +2. **P0-4 / P0-5 / P0-6**:MCP 与流式的资源泄漏/并发,属于核心链路稳定性。 +3. **P0-3 / P0-9 / P1-1**:工具系统的一致性问题,直接影响 demo 可用性。 +4. **P0-8 / P2-18**:优雅停机与 Server 超时,一起改。 +5. **P1-4 / P2-17 / P1-5 / P1-6 / P1-7**:context 透传 -> session 校验 -> 会话历史 -> 并发创建,按依赖顺序推进。 +6. **P1-2 / P1-3 / P2-1**:Agent 执行引擎能力补齐(loop、真并发、循环化)。 +7. **P1-8 / P2-5 / P2-6 / P2-7 / P2-9 / P3-1**:配置体系与依赖整理。 +8. **P2-8 / P3-7 / P3-8**:Redis/MySQL 接入与测试体系,属于中长期工程化。 +9. **其余 P2/P3**:按需排期。 + +> 说明:P3-8(补测试)建议穿插在 2~6 步之间进行,为每次修复提供回归保护,而不是放到最后。