refactor(harness): remove legacy agent architecture

This commit is contained in:
zhuyongxin
2026-07-22 18:02:01 +08:00
parent bc36248cd8
commit 8ee7cc0b70
148 changed files with 3091 additions and 13889 deletions
+9 -42
View File
@@ -1,48 +1,15 @@
# MVP 架构文档
**更新日期**:2026-07-10
**更新日期**:2026-07-22
**状态**:当前单 Diagnosis Agent + Harness 架构
这里是 MVP 当前架构的唯一入口。旧版设计、早期拆解和已经被新实现替代的方案已归档到:
当前文档入口:
- `mvp/architecture/archive/2026-07-05-legacy/`
归档材料只作为设计历史阅读,不再作为当前实现依据。
## 当前文档
| 文档 | 用途 |
| 文档 | 内容 |
|---|---|
| [current-mvp-architecture.md](current-mvp-architecture.md) | 当前可运行 MVP 的总体架构、链路、持久化和质量门禁 |
| [interview-one-pager.md](interview-one-pager.md) | 面试一页式架构讲解,包含总图、亮点、取舍和追问回答 |
| [agent-orchestration.md](agent-orchestration.md) | Agent 编排细节,覆盖 Chat SequentialAgent、AIOps SupervisorAgent、工具边界 |
| [executor-evidence-pipeline-refactor.md](executor-evidence-pipeline-refactor.md) | Chat 证据链路当前数据契约,覆盖 Executor V2、Gatekeeper、Verifier、Composer、`evidence_refs` |
| [harness-quality-gates.md](harness-quality-gates.md) | Prompt、Hook、Trace、Gatekeeper、Verifier、Composer、评测基线组成的质量门禁 |
| [rag-architecture.md](rag-architecture.md) | RAG/知识检索新架构,覆盖 L0 hint、VectorStore 主路径、SDK fallback、证据追踪 |
| [modular-rag-pipeline.md](modular-rag-pipeline.md) | `lookup_knowledge` 模块化 RAG 落地架构,覆盖 pipeline、fallback、evidence-first contract、trace |
| [rag-eval-closure.md](rag-eval-closure.md) | RAG 评测闭环,覆盖 offline baseline、baseline diff、diagnosis eval 和 live acceptance |
| [retrieval-observability.md](retrieval-observability.md) | 检索运行细节和可观测性,覆盖 L0/L1、去重、分数归一、评测 |
| [feedback-architecture.md](feedback-architecture.md) | 反馈与自评估闭环,覆盖 rule evaluation、Verifier、AIOps rule、用户反馈和案例沉淀 |
| [session-trace-lifecycle.md](session-trace-lifecycle.md) | 会话和 Trace 生命周期,覆盖 sessionId、状态流转、agent_step、tool_invocation、Trace API |
| [knowledge-base-authoring.md](knowledge-base-authoring.md) | 知识库文档编写与维护规范,覆盖 frontmatter、category、chunk、reindex |
| [data-model.md](data-model.md) | 数据模型总览,覆盖 Trace、知识库、反馈沉淀和 Milvus metadata |
| [evolution-roadmap.md](evolution-roadmap.md) | 从旧版 Agent 蓝图继承的后续演进路线,不代表当前已实现 |
| [current-mvp-architecture.md](current-mvp-architecture.md) | 系统分层、请求主链与 API surface |
| [agent-orchestration.md](agent-orchestration.md) | 单 Diagnosis ReAct Agent 的职责和执行方式 |
| [harness-quality-gates.md](harness-quality-gates.md) | Run、Tool、Evidence、Semantic 与 Release 门禁 |
| [session-trace-lifecycle.md](session-trace-lifecycle.md) | sessionId/runId、SSE 和 durable audit 生命周期 |
## 当前架构一句话
SuperBizAgent MVP 是一个面向故障诊断的可追踪 Agent 系统:Chat 和 AIOps 入口统一进入 Agent 编排,Executor 通过显式工具收集日志、指标和知识库证据,Chat 链路由 Gatekeeper 做引用真实性校验、Verifier 做可推导性判断、Composer 生成最终表达;多轮会话元数据落到 `chat_session`,每次诊断运行落到 `diagnosis_run`,步骤和工具明细通过 `agent_step.run_id`、`tool_invocation.run_id` 关联,最终通过 Trace API 和评测脚本证明诊断链路可解释、可回放、可对比。
## 阅读顺序
1. 先读 [current-mvp-architecture.md](current-mvp-architecture.md),理解系统边界和主链路。
2. 面试前读 [interview-one-pager.md](interview-one-pager.md),准备 2-5 分钟讲解。
3. 再读 [agent-orchestration.md](agent-orchestration.md),理解当前 Agent 如何协作。
4. 接着读 [executor-evidence-pipeline-refactor.md](executor-evidence-pipeline-refactor.md),理解 Chat 证据链路的数据结构和验真边界。
5. 然后读 [harness-quality-gates.md](harness-quality-gates.md),理解为什么系统可追踪、可验证。
6. 再读 [rag-architecture.md](rag-architecture.md),理解当前 RAG 为什么保留显式 `lookup_knowledge`,以及 Spring AI VectorStore 如何接入。
7. 继续读 [modular-rag-pipeline.md](modular-rag-pipeline.md),看 `lookup_knowledge` 的模块化落地和 evidence-first contract。
8. 再读 [rag-eval-closure.md](rag-eval-closure.md),看 RAG baseline 如何形成质量闭环。
9. 然后读 [retrieval-observability.md](retrieval-observability.md),看检索细节和质量回归方式。
10. 再读 [feedback-architecture.md](feedback-architecture.md),理解 self_evaluation、用户反馈和案例沉淀。
11. 按需读 [session-trace-lifecycle.md](session-trace-lifecycle.md)、[knowledge-base-authoring.md](knowledge-base-authoring.md)、[data-model.md](data-model.md),补齐运行生命周期、知识库维护和数据关系。
12. 最后读 [evolution-roadmap.md](evolution-roadmap.md),区分后续演进和当前实现。
13. 需要追溯旧方案时,再进入 `archive/2026-07-05-legacy/`。
2026-07-22 前的多角色编排、双入口和旧证据链文档已移动到 `archive/2026-07-22-legacy/`,仅用于历史决策追溯,不代表当前运行时。
+37 -220
View File
@@ -1,237 +1,54 @@
# Agent 编排架构
# Diagnosis Agent 执行架构
**更新日期**:2026-07-08
**更新日期**:2026-07-22
**状态**:当前可运行架构
**参考历史文档**:`archive/2026-07-05-legacy/agent-architecture.md`
## 1. 设计定位
## 1. 单 Agent 原则
旧版 Agent 架构把系统描述为 Supervisor、Planner、SubAgent、Verifier 的团队协作。当前 MVP 保留这个核心思想,但实现更收敛:
当前业务诊断只有一个 `Diagnosis Agent`。它使用框架 `ReactAgent` 完成规划、行动、观察和最终 Draft,但项目不在外层复制 ReAct 状态机,也不使用业务 Graph 或多角色协作链。
- Chat 链路使用固定顺序工作流:`Planner -> Executor -> Gatekeeper -> Verifier -> Composer`。
- AIOps 链路使用 `SupervisorAgent` 调度 `Planner + Executor`,最终由规则评估器做轻量验证。
- 当前没有拆分 ExternalApiSubAgent、InternalErrorSubAgent、DatabaseSubAgent;这些作为后续演进方向保留。
- 证据工具不直接散落在各个 Agent 里,而是通过 Spring AI ToolCallback / `@Tool` 统一暴露。
## 2. 职责
## 2. 当前 Agent 全景
Diagnosis Agent:
```mermaid
flowchart TB
subgraph Chat["Chat diagnosis"]
ChatIn["POST /api/chat"] --> ChatService["ChatService"]
ChatService --> ChatPlanner["chat_planner"]
ChatPlanner --> ChatExecutor["chat_executor"]
ChatExecutor --> ChatTools["evidence tools"]
ChatTools --> ChatExecutor
ChatExecutor --> ChatGatekeeper["ExecutorGatekeeperService"]
ChatGatekeeper --> ChatVerifier["chat_verifier"]
ChatVerifier --> ChatDecision{"PASS / LOW_CONFID / REJECT"}
ChatDecision --> ChatComposer["chat_composer"]
ChatComposer --> ChatAnswer["final answer"]
end
- 接收当前 query 与可选、受限的安全 PreviousTurn。
- 自主选择只读 evidence Tool。
- 根据 Agent projection 判断是否需要继续查询。
- 输出结构化 `DiagnosisDraft`,每条 analysis 绑定 framework `tool_call_id`。
- 证据不足时明确限制,不补造事实。
subgraph AiOps["AIOps diagnosis"]
AiOpsIn["POST /api/ai_ops"] --> AiOpsService["AiOpsService"]
AiOpsService --> Supervisor["ai_ops_supervisor"]
Supervisor --> AiOpsPlanner["planner_agent"]
Supervisor --> AiOpsExecutor["executor_agent"]
AiOpsPlanner --> AiOpsExecutor
AiOpsExecutor --> AiOpsTools["Prometheus / logs / lookup_knowledge"]
AiOpsTools --> AiOpsReport["alert report"]
AiOpsReport --> AiOpsRule["AiOpsRuleEvaluationService"]
end
Diagnosis Agent 不负责:
subgraph Trace["Trace persistence"]
ChatSession["chat_session"]
Run["diagnosis_run"]
Step["agent_step"]
Invocation["tool_invocation"]
SelfEval["self_evaluation"]
end
- HTTP/SSE、Session/Run 生命周期和持久化。
- 模型/Tool/Token/timeout/cancel 预算。
- Tool 参数授权、raw response 投影或证据物理验真。
- SemanticGuard 与最终发布决定。
ChatService --> ChatSession
ChatService --> Run
ChatPlanner --> Step
ChatExecutor --> Step
ChatGatekeeper --> SelfEval
ChatVerifier --> Step
ChatTools --> Invocation
ChatDecision --> SelfEval
ChatComposer --> Step
AiOpsService --> ChatSession
AiOpsService --> Run
AiOpsPlanner --> Step
AiOpsExecutor --> Step
AiOpsTools --> Invocation
AiOpsRule --> SelfEval
```
## 3. Chat 编排
Chat 复杂诊断采用 `SequentialAgent`,顺序固定:
```text
chat_planner
-> chat_executor
-> lookup_knowledge / query_logs / query_metrics / date_time
-> outputs executor_evidence_v2
-> VerifierInputHook / ExecutorGatekeeperService
-> validates source_invocation_id / raw_path / evidence_excerpt
-> chat_verifier
-> judges whether verified evidence can derive claims
-> chat_composer
-> writes final user-facing answer
```
关键行为:
| 角色 | 当前职责 | 输出 |
|---|---|---|
| `chat_planner` | 拆解问题,注入知识域地图和对话历史,给出排查方向 | `planner_plan` |
| `chat_executor` | 按计划调用证据工具,抽取带 `source_invocation_id + raw_path + evidence_excerpt` 的微观事实 | `executor_evidence_v2` |
| `ExecutorGatekeeperService` | 在 Verifier 前做代码级引用验真,拒绝伪造 ID、错配 raw_path、错配 excerpt | `gatekeeper_result` |
| `chat_verifier` | 只判断已验真 evidence excerpt 是否能推出 claim,不做新检索 | `verifier_output` |
| `chat_composer` | 只表达 Verifier 允许输出的 claims、缺口和建议,生成最终用户答复 | `composer_output` |
Chat 链路最多支持两轮验证:
## 3. 执行序列
```mermaid
sequenceDiagram
autonumber
participant C as ChatService
participant P as chat_planner
participant E as chat_executor
participant T as tools
participant G as gatekeeper
participant V as chat_verifier
participant M as chat_composer
participant R as diagnosis_run
participant App as Chat Application
participant Core as Harness Core
participant Agent as Diagnosis Agent
participant Tool as ACI Tool Boundary
participant EG as EvidenceGuard
participant SG as SemanticGuard
participant Release as Release Policy
C->>P: 原始问题 + history + retry_context
P-->>C: planner_plan
C->>E: planner_plan + 上下文
E->>T: 调用证据工具
T-->>E: 证据结果
E-->>C: executor_evidence_v2
C->>G: executor_structured_output + tool_invocation.evidence_refs
G-->>C: gatekeeper_result
C->>V: executor_structured_output + gatekeeper_result + tool_trace_summary
V-->>C: PASS / LOW_CONFID / REJECT
C->>R: 写入 verifier_evaluation
alt LOW_CONFID 且允许补证据
C->>P: retry_context: 仅补缺失证据
else PASS 或 REJECT
C->>M: allowed_claims + missing_info + recommended_actions
M-->>C: composer_output
C->>R: 保存 Composer 最终 answer
end
App->>Core: start RunContext
App->>Agent: query + safe previous_turn
Agent->>Tool: tool name + framework tool_call_id + typed args
Tool-->>Agent: bounded agent_result
Agent-->>App: DiagnosisDraft
App->>EG: Draft + current Run canonical invocations
EG-->>App: verified snapshot or deterministic failure
App->>SG: query + full Draft + verified snapshot
SG-->>App: SUPPORTED / UNSUPPORTED
App->>Release: decide public content
Release-->>App: report or fixed fallback
```
决策语义:
## 4. PreviousTurn
| Verdict | 行为 |
|---|---|
| `PASS` | 把 Verifier 允许表达的 claims 交给 Composer 输出 |
| `LOW_CONFID` | 如果分数低于阈值且仍有轮次,构造 `retry_context` 补证据;否则输出低置信提示 |
| `REJECT` | 输出降级答复,只保留已确认信息和下一步建议 |
## 4. AIOps 编排
AIOps 使用 `SupervisorAgent` 调度两个子 Agent:
```text
ai_ops_supervisor
-> planner_agent
-> executor_agent
-> final report
-> AiOpsRuleEvaluationService
```
与 Chat 的差异:
- AIOps 的输入可能是结构化告警 payload。
- payload 模式会进入 `PAYLOAD_TARGETED`,最终报告必须聚焦输入告警。
- 无 payload 时进入 `AUTO_DISCOVERY`,先通过告警工具发现活跃告警。
- 当前 AIOps 不使用 LLM Verifier,而使用轻量规则评估器写入 `self_evaluation.aiops_rule_evaluation`。
## 5. 工具边界
当前 Executor 可用工具来自两类:
```text
methodTools
-> dateTimeTools
-> lookupKnowledgeTool
-> queryMetricsTools
-> queryLogsTools when mock enabled
ToolCallbackProvider
-> framework-discovered tools
```
工具调用必须写入 `tool_invocation`。其中 `lookup_knowledge` 额外记录:
- L0/L1 命中数量。
- 检索层。
- relevance level。
- retrieved domains。
- dedup reason。
## 6. Skill / Playbook 流程
当前 Skill 是诊断流程编排提示,不是事实证据来源。Planner 只能看到 `SkillRegistry.listAll()` 暴露的 name/description 元数据;Executor 才能通过 Spring AI Alibaba 官方 `SkillsAgentHook` 使用 `read_skill` 读取完整 `SKILL.md`。
```mermaid
flowchart LR
Registry["SkillRegistry<br/>active skill metadata"] --> PlannerHook["PlannerSkillMetadataHook"]
PlannerHook --> Planner["Planner<br/>metadata only"]
Planner --> Plan["planner_plan<br/>selected_skill + steps"]
Registry --> ExecutorHook["SkillsAgentHook"]
ExecutorHook --> ReadSkill["read_skill"]
Plan --> Executor["Executor"]
Executor --> ReadSkill
ReadSkill --> SkillBody["SKILL.md workflow"]
SkillBody --> Executor
Executor --> EvidenceTools["lookup_knowledge / logs / metrics"]
EvidenceTools --> ToolTrace["tool_invocation evidence"]
Executor --> Gatekeeper["Gatekeeper"]
Gatekeeper --> Verifier["Verifier"]
ToolTrace --> Verifier
Verifier --> Composer["Composer"]
```
| 角色 | Skill 可见性 | 工具权限 |
|---|---|---|
| Planner | 只看 skill name / description,并输出 `selected_skill` | 不暴露 `read_skill` |
| Executor | 读取 Planner 选中的 skill 正文 | 暴露官方 `read_skill` 和证据工具 |
| Gatekeeper | 不看 skill catalog,也不读 skill 正文 | 只读取 Executor 输出和 `tool_invocation.retrieval_details.evidence_refs` |
| Verifier | 不看 skill catalog,也不读 skill 正文 | 只读取 Gatekeeper 结果、结构化 claims 和 trace summary |
| Composer | 不看 skill catalog,也不读 skill 正文 | 只读取 Verifier 允许表达的内容 |
## 7. 与旧版设计的差异
| 旧版设想 | 当前实现 |
|---|---|
| Supervisor + Planner + 多个专科 SubAgent + Verifier | Chat: Planner + Executor + Gatekeeper + Verifier + Composer;AIOps: Supervisor + Planner + Executor |
| ExternalApiSubAgent / InternalErrorSubAgent / DatabaseSubAgent | 暂未拆分,能力通过通用 Executor + 工具 + Prompt 约束实现 |
| 每个 SubAgent 专属工具集 | 当前 Executor 持有统一证据工具集合 |
| Verifier 支持 PASS / REVISE / REJECT | 当前 Chat Verifier 输出 PASS / LOW_CONFID / REJECT |
| Skill 驱动不同诊断流程 | 当前以 Planner 元数据选择 + Executor 读取 playbook 的方式接入 |
## 8. 后续演进
当诊断场景和工具复杂度继续上升时,再考虑拆分:
- `ExternalApiSubAgent`:接口文档、错误码、请求参数、第三方日志。
- `DatabaseSubAgent`:连接池、慢 SQL、死锁、索引建议。
- `CacheSubAgent`:Redis 超时、连接、热点 key、内存风险。
- `GenericDiagnosisSubAgent`:专项 Agent 失败后的兜底。
拆分前提:
- 当前 Executor prompt 已难以维护。
- 不同故障类型的工具权限明显不同。
- Trace 能证明某类问题需要独立的推理策略。
- 评测集能覆盖拆分前后的行为差异。
PreviousTurn 只来自同一 Session 最近一个 `DIAGNOSIS + SUCCESS + published_result`。Fallback、失败、取消、raw evidence 和完整历史都不能进入下一轮;字段与字节上限由 Harness 配置控制。
@@ -0,0 +1,48 @@
# MVP 架构文档
**更新日期**:2026-07-10
这里是 MVP 当前架构的唯一入口。旧版设计、早期拆解和已经被新实现替代的方案已归档到:
- `mvp/architecture/archive/2026-07-05-legacy/`
归档材料只作为设计历史阅读,不再作为当前实现依据。
## 当前文档
| 文档 | 用途 |
|---|---|
| [current-mvp-architecture.md](current-mvp-architecture.md) | 当前可运行 MVP 的总体架构、链路、持久化和质量门禁 |
| [interview-one-pager.md](interview-one-pager.md) | 面试一页式架构讲解,包含总图、亮点、取舍和追问回答 |
| [agent-orchestration.md](agent-orchestration.md) | Agent 编排细节,覆盖 Chat SequentialAgent、AIOps SupervisorAgent、工具边界 |
| [executor-evidence-pipeline-refactor.md](executor-evidence-pipeline-refactor.md) | Chat 证据链路当前数据契约,覆盖 Executor V2、Gatekeeper、Verifier、Composer、`evidence_refs` |
| [harness-quality-gates.md](harness-quality-gates.md) | Prompt、Hook、Trace、Gatekeeper、Verifier、Composer、评测基线组成的质量门禁 |
| [rag-architecture.md](rag-architecture.md) | RAG/知识检索新架构,覆盖 L0 hint、VectorStore 主路径、SDK fallback、证据追踪 |
| [modular-rag-pipeline.md](modular-rag-pipeline.md) | `lookup_knowledge` 模块化 RAG 落地架构,覆盖 pipeline、fallback、evidence-first contract、trace |
| [rag-eval-closure.md](rag-eval-closure.md) | RAG 评测闭环,覆盖 offline baseline、baseline diff、diagnosis eval 和 live acceptance |
| [retrieval-observability.md](retrieval-observability.md) | 检索运行细节和可观测性,覆盖 L0/L1、去重、分数归一、评测 |
| [feedback-architecture.md](feedback-architecture.md) | 反馈与自评估闭环,覆盖 rule evaluation、Verifier、AIOps rule、用户反馈和案例沉淀 |
| [session-trace-lifecycle.md](session-trace-lifecycle.md) | 会话和 Trace 生命周期,覆盖 sessionId、状态流转、agent_step、tool_invocation、Trace API |
| [knowledge-base-authoring.md](knowledge-base-authoring.md) | 知识库文档编写与维护规范,覆盖 frontmatter、category、chunk、reindex |
| [data-model.md](data-model.md) | 数据模型总览,覆盖 Trace、知识库、反馈沉淀和 Milvus metadata |
| [evolution-roadmap.md](evolution-roadmap.md) | 从旧版 Agent 蓝图继承的后续演进路线,不代表当前已实现 |
## 当前架构一句话
SuperBizAgent MVP 是一个面向故障诊断的可追踪 Agent 系统:Chat 和 AIOps 入口统一进入 Agent 编排,Executor 通过显式工具收集日志、指标和知识库证据,Chat 链路由 Gatekeeper 做引用真实性校验、Verifier 做可推导性判断、Composer 生成最终表达;多轮会话元数据落到 `chat_session`,每次诊断运行落到 `diagnosis_run`,步骤和工具明细通过 `agent_step.run_id`、`tool_invocation.run_id` 关联,最终通过 Trace API 和评测脚本证明诊断链路可解释、可回放、可对比。
## 阅读顺序
1. 先读 [current-mvp-architecture.md](current-mvp-architecture.md),理解系统边界和主链路。
2. 面试前读 [interview-one-pager.md](interview-one-pager.md),准备 2-5 分钟讲解。
3. 再读 [agent-orchestration.md](agent-orchestration.md),理解当前 Agent 如何协作。
4. 接着读 [executor-evidence-pipeline-refactor.md](executor-evidence-pipeline-refactor.md),理解 Chat 证据链路的数据结构和验真边界。
5. 然后读 [harness-quality-gates.md](harness-quality-gates.md),理解为什么系统可追踪、可验证。
6. 再读 [rag-architecture.md](rag-architecture.md),理解当前 RAG 为什么保留显式 `lookup_knowledge`,以及 Spring AI VectorStore 如何接入。
7. 继续读 [modular-rag-pipeline.md](modular-rag-pipeline.md),看 `lookup_knowledge` 的模块化落地和 evidence-first contract。
8. 再读 [rag-eval-closure.md](rag-eval-closure.md),看 RAG baseline 如何形成质量闭环。
9. 然后读 [retrieval-observability.md](retrieval-observability.md),看检索细节和质量回归方式。
10. 再读 [feedback-architecture.md](feedback-architecture.md),理解 self_evaluation、用户反馈和案例沉淀。
11. 按需读 [session-trace-lifecycle.md](session-trace-lifecycle.md)、[knowledge-base-authoring.md](knowledge-base-authoring.md)、[data-model.md](data-model.md),补齐运行生命周期、知识库维护和数据关系。
12. 最后读 [evolution-roadmap.md](evolution-roadmap.md),区分后续演进和当前实现。
13. 需要追溯旧方案时,再进入 `archive/2026-07-05-legacy/`。
@@ -0,0 +1,3 @@
# Archive Note
本目录保存 2026-07-22 单 Diagnosis Agent + Harness 切换前的当前架构文档。内容用于历史决策追溯,不代表现行 runtime、API 或验收口径。
@@ -0,0 +1,237 @@
# Agent 编排架构
**更新日期**:2026-07-08
**状态**:当前可运行架构
**参考历史文档**:`archive/2026-07-05-legacy/agent-architecture.md`
## 1. 设计定位
旧版 Agent 架构把系统描述为 Supervisor、Planner、SubAgent、Verifier 的团队协作。当前 MVP 保留这个核心思想,但实现更收敛:
- Chat 链路使用固定顺序工作流:`Planner -> Executor -> Gatekeeper -> Verifier -> Composer`。
- AIOps 链路使用 `SupervisorAgent` 调度 `Planner + Executor`,最终由规则评估器做轻量验证。
- 当前没有拆分 ExternalApiSubAgent、InternalErrorSubAgent、DatabaseSubAgent;这些作为后续演进方向保留。
- 证据工具不直接散落在各个 Agent 里,而是通过 Spring AI ToolCallback / `@Tool` 统一暴露。
## 2. 当前 Agent 全景
```mermaid
flowchart TB
subgraph Chat["Chat diagnosis"]
ChatIn["POST /api/chat"] --> ChatService["ChatService"]
ChatService --> ChatPlanner["chat_planner"]
ChatPlanner --> ChatExecutor["chat_executor"]
ChatExecutor --> ChatTools["evidence tools"]
ChatTools --> ChatExecutor
ChatExecutor --> ChatGatekeeper["ExecutorGatekeeperService"]
ChatGatekeeper --> ChatVerifier["chat_verifier"]
ChatVerifier --> ChatDecision{"PASS / LOW_CONFID / REJECT"}
ChatDecision --> ChatComposer["chat_composer"]
ChatComposer --> ChatAnswer["final answer"]
end
subgraph AiOps["AIOps diagnosis"]
AiOpsIn["POST /api/ai_ops"] --> AiOpsService["AiOpsService"]
AiOpsService --> Supervisor["ai_ops_supervisor"]
Supervisor --> AiOpsPlanner["planner_agent"]
Supervisor --> AiOpsExecutor["executor_agent"]
AiOpsPlanner --> AiOpsExecutor
AiOpsExecutor --> AiOpsTools["Prometheus / logs / lookup_knowledge"]
AiOpsTools --> AiOpsReport["alert report"]
AiOpsReport --> AiOpsRule["AiOpsRuleEvaluationService"]
end
subgraph Trace["Trace persistence"]
ChatSession["chat_session"]
Run["diagnosis_run"]
Step["agent_step"]
Invocation["tool_invocation"]
SelfEval["self_evaluation"]
end
ChatService --> ChatSession
ChatService --> Run
ChatPlanner --> Step
ChatExecutor --> Step
ChatGatekeeper --> SelfEval
ChatVerifier --> Step
ChatTools --> Invocation
ChatDecision --> SelfEval
ChatComposer --> Step
AiOpsService --> ChatSession
AiOpsService --> Run
AiOpsPlanner --> Step
AiOpsExecutor --> Step
AiOpsTools --> Invocation
AiOpsRule --> SelfEval
```
## 3. Chat 编排
Chat 复杂诊断采用 `SequentialAgent`,顺序固定:
```text
chat_planner
-> chat_executor
-> lookup_knowledge / query_logs / query_metrics / date_time
-> outputs executor_evidence_v2
-> VerifierInputHook / ExecutorGatekeeperService
-> validates source_invocation_id / raw_path / evidence_excerpt
-> chat_verifier
-> judges whether verified evidence can derive claims
-> chat_composer
-> writes final user-facing answer
```
关键行为:
| 角色 | 当前职责 | 输出 |
|---|---|---|
| `chat_planner` | 拆解问题,注入知识域地图和对话历史,给出排查方向 | `planner_plan` |
| `chat_executor` | 按计划调用证据工具,抽取带 `source_invocation_id + raw_path + evidence_excerpt` 的微观事实 | `executor_evidence_v2` |
| `ExecutorGatekeeperService` | 在 Verifier 前做代码级引用验真,拒绝伪造 ID、错配 raw_path、错配 excerpt | `gatekeeper_result` |
| `chat_verifier` | 只判断已验真 evidence excerpt 是否能推出 claim,不做新检索 | `verifier_output` |
| `chat_composer` | 只表达 Verifier 允许输出的 claims、缺口和建议,生成最终用户答复 | `composer_output` |
Chat 链路最多支持两轮验证:
```mermaid
sequenceDiagram
autonumber
participant C as ChatService
participant P as chat_planner
participant E as chat_executor
participant T as tools
participant G as gatekeeper
participant V as chat_verifier
participant M as chat_composer
participant R as diagnosis_run
C->>P: 原始问题 + history + retry_context
P-->>C: planner_plan
C->>E: planner_plan + 上下文
E->>T: 调用证据工具
T-->>E: 证据结果
E-->>C: executor_evidence_v2
C->>G: executor_structured_output + tool_invocation.evidence_refs
G-->>C: gatekeeper_result
C->>V: executor_structured_output + gatekeeper_result + tool_trace_summary
V-->>C: PASS / LOW_CONFID / REJECT
C->>R: 写入 verifier_evaluation
alt LOW_CONFID 且允许补证据
C->>P: retry_context: 仅补缺失证据
else PASS 或 REJECT
C->>M: allowed_claims + missing_info + recommended_actions
M-->>C: composer_output
C->>R: 保存 Composer 最终 answer
end
```
决策语义:
| Verdict | 行为 |
|---|---|
| `PASS` | 把 Verifier 允许表达的 claims 交给 Composer 输出 |
| `LOW_CONFID` | 如果分数低于阈值且仍有轮次,构造 `retry_context` 补证据;否则输出低置信提示 |
| `REJECT` | 输出降级答复,只保留已确认信息和下一步建议 |
## 4. AIOps 编排
AIOps 使用 `SupervisorAgent` 调度两个子 Agent:
```text
ai_ops_supervisor
-> planner_agent
-> executor_agent
-> final report
-> AiOpsRuleEvaluationService
```
与 Chat 的差异:
- AIOps 的输入可能是结构化告警 payload。
- payload 模式会进入 `PAYLOAD_TARGETED`,最终报告必须聚焦输入告警。
- 无 payload 时进入 `AUTO_DISCOVERY`,先通过告警工具发现活跃告警。
- 当前 AIOps 不使用 LLM Verifier,而使用轻量规则评估器写入 `self_evaluation.aiops_rule_evaluation`。
## 5. 工具边界
当前 Executor 可用工具来自两类:
```text
methodTools
-> dateTimeTools
-> lookupKnowledgeTool
-> queryMetricsTools
-> queryLogsTools when mock enabled
ToolCallbackProvider
-> framework-discovered tools
```
工具调用必须写入 `tool_invocation`。其中 `lookup_knowledge` 额外记录:
- L0/L1 命中数量。
- 检索层。
- relevance level。
- retrieved domains。
- dedup reason。
## 6. Skill / Playbook 流程
当前 Skill 是诊断流程编排提示,不是事实证据来源。Planner 只能看到 `SkillRegistry.listAll()` 暴露的 name/description 元数据;Executor 才能通过 Spring AI Alibaba 官方 `SkillsAgentHook` 使用 `read_skill` 读取完整 `SKILL.md`。
```mermaid
flowchart LR
Registry["SkillRegistry<br/>active skill metadata"] --> PlannerHook["PlannerSkillMetadataHook"]
PlannerHook --> Planner["Planner<br/>metadata only"]
Planner --> Plan["planner_plan<br/>selected_skill + steps"]
Registry --> ExecutorHook["SkillsAgentHook"]
ExecutorHook --> ReadSkill["read_skill"]
Plan --> Executor["Executor"]
Executor --> ReadSkill
ReadSkill --> SkillBody["SKILL.md workflow"]
SkillBody --> Executor
Executor --> EvidenceTools["lookup_knowledge / logs / metrics"]
EvidenceTools --> ToolTrace["tool_invocation evidence"]
Executor --> Gatekeeper["Gatekeeper"]
Gatekeeper --> Verifier["Verifier"]
ToolTrace --> Verifier
Verifier --> Composer["Composer"]
```
| 角色 | Skill 可见性 | 工具权限 |
|---|---|---|
| Planner | 只看 skill name / description,并输出 `selected_skill` | 不暴露 `read_skill` |
| Executor | 读取 Planner 选中的 skill 正文 | 暴露官方 `read_skill` 和证据工具 |
| Gatekeeper | 不看 skill catalog,也不读 skill 正文 | 只读取 Executor 输出和 `tool_invocation.retrieval_details.evidence_refs` |
| Verifier | 不看 skill catalog,也不读 skill 正文 | 只读取 Gatekeeper 结果、结构化 claims 和 trace summary |
| Composer | 不看 skill catalog,也不读 skill 正文 | 只读取 Verifier 允许表达的内容 |
## 7. 与旧版设计的差异
| 旧版设想 | 当前实现 |
|---|---|
| Supervisor + Planner + 多个专科 SubAgent + Verifier | Chat: Planner + Executor + Gatekeeper + Verifier + Composer;AIOps: Supervisor + Planner + Executor |
| ExternalApiSubAgent / InternalErrorSubAgent / DatabaseSubAgent | 暂未拆分,能力通过通用 Executor + 工具 + Prompt 约束实现 |
| 每个 SubAgent 专属工具集 | 当前 Executor 持有统一证据工具集合 |
| Verifier 支持 PASS / REVISE / REJECT | 当前 Chat Verifier 输出 PASS / LOW_CONFID / REJECT |
| Skill 驱动不同诊断流程 | 当前以 Planner 元数据选择 + Executor 读取 playbook 的方式接入 |
## 8. 后续演进
当诊断场景和工具复杂度继续上升时,再考虑拆分:
- `ExternalApiSubAgent`:接口文档、错误码、请求参数、第三方日志。
- `DatabaseSubAgent`:连接池、慢 SQL、死锁、索引建议。
- `CacheSubAgent`:Redis 超时、连接、热点 key、内存风险。
- `GenericDiagnosisSubAgent`:专项 Agent 失败后的兜底。
拆分前提:
- 当前 Executor prompt 已难以维护。
- 不同故障类型的工具权限明显不同。
- Trace 能证明某类问题需要独立的推理策略。
- 评测集能覆盖拆分前后的行为差异。
@@ -0,0 +1,444 @@
# 当前 MVP 架构
**更新日期**:2026-07-08
**状态**:当前可运行架构
**适用范围**:Demo、面试讲解、后续迭代规划
## 1. 系统定位
SuperBizAgent MVP 不是通用 Chatbot,而是面向故障诊断的 Agent 工程项目。
核心目标:
- 支持用户主动发起的 Chat 诊断。
- 支持 AIOps 告警触发的自动诊断。
- 保留 Agent 的规划、执行、验证过程。
- 工具调用必须显式、可追踪、可回放。
- RAG 检索必须通过 `lookup_knowledge` 暴露证据链。
- 每次诊断都沉淀 session、step、tool invocation 和 self evaluation。
## 2. 总体分层
```mermaid
flowchart TB
subgraph API["API Layer"]
ChatController["ChatController"]
TraceController["DiagnosisTraceController"]
SearchController["SearchController"]
DocumentController["DocumentController"]
end
subgraph App["Application Service"]
ChatService["ChatService"]
AiOpsService["AiOpsService"]
TraceService["DiagnosisTraceService"]
end
subgraph Agent["Agent Orchestration"]
Supervisor["Supervisor"]
Planner["Planner"]
Executor["Executor"]
Gatekeeper["Gatekeeper"]
Verifier["Verifier"]
Composer["Composer"]
end
subgraph Tools["Evidence Tools"]
KnowledgeTool["lookup_knowledge"]
LogsTool["query_logs"]
MetricsTool["query_metrics"]
AlertsTool["queryPrometheusAlerts"]
end
subgraph Skills["Skill / Playbook"]
SkillRegistry["SkillRegistry"]
PlannerSkillHook["PlannerSkillMetadataHook"]
SkillsHook["SkillsAgentHook"]
ReadSkill["read_skill"]
end
subgraph RAG["RAG Retrieval"]
L0["KnowledgeIndexService"]
VectorSearch["VectorSearchService"]
VectorStore["Spring AI VectorStore"]
SdkFallback["Milvus SDK fallback"]
end
subgraph Store["Persistence and Trace"]
ChatSession["chat_session"]
Run["diagnosis_run"]
Step["agent_step"]
Invocation["tool_invocation"]
ApiDoc["api_document"]
Milvus["Milvus/Zilliz"]
end
API --> App
ChatService --> Agent
AiOpsService --> Agent
SkillRegistry --> PlannerSkillHook
PlannerSkillHook --> Planner
SkillRegistry --> SkillsHook
SkillsHook --> Executor
Executor --> ReadSkill
Agent --> Tools
KnowledgeTool --> RAG
RAG --> Store
Tools --> Invocation
Agent --> Step
App --> Session
TraceService --> Session
TraceService --> Step
TraceService --> Invocation
```
```text
API Layer
-> ChatController
-> DiagnosisTraceController
-> SearchController
-> DocumentController
Application Service
-> ChatService
-> AiOpsService
-> DiagnosisTraceService
Agent Orchestration
-> Supervisor
-> Planner
-> Executor
-> Gatekeeper
-> Verifier
-> Composer
Evidence Tools
-> lookup_knowledge
-> query_logs
-> query_metrics
-> queryPrometheusAlerts
Skill / Playbook
-> SkillRegistry
-> PlannerSkillMetadataHook gives Planner name/description only
-> SkillsAgentHook gives Executor read_skill
-> Verifier is isolated from skills
RAG Retrieval
-> KnowledgeIndexService
-> VectorSearchService
-> Spring AI VectorStore
-> Milvus SDK fallback
Persistence
-> chat_session
-> diagnosis_run
-> agent_step.run_id
-> tool_invocation.run_id
-> api_document
-> Milvus/Zilliz collection
Quality Gates
-> executor gatekeeper
-> chat verifier
-> AIOps rule evaluation
-> diagnosis eval baseline
-> RAG retrieval baseline
```
## 3. Chat 诊断链路
```mermaid
sequenceDiagram
autonumber
actor User as 用户
participant API as POST /api/chat
participant Chat as ChatService
participant Planner as Planner Agent
participant Executor as Executor Agent
participant Tool as Evidence Tools
participant Gatekeeper as Gatekeeper Hook
participant Verifier as Verifier Agent
participant Composer as Composer Agent
participant DB as Trace Tables
participant Trace as Trace API
User->>API: 提交诊断问题
API->>Chat: execute chat strategy
Chat->>DB: 创建 chat_session metadata + diagnosis_run(runId)
Chat->>Planner: 复杂问题进入规划
Planner->>DB: 写入 agent_step.run_id
Planner->>Executor: 下发排查方向
Executor->>Tool: lookup_knowledge / logs / metrics
Tool->>DB: 写入 tool_invocation.run_id
Tool-->>Executor: 返回证据
Executor->>Gatekeeper: 输出 executor_evidence_v2
Gatekeeper->>DB: 读取 tool_invocation.evidence_refs 并校验引用
Gatekeeper->>Verifier: 传入已验真的 claims / excerpts
Verifier->>DB: 合并 diagnosis_run.self_evaluation.verifier_evaluation
Verifier->>Composer: 传入 allowed_claims / missing_info / actions
Composer->>Chat: 生成最终用户答复
Chat->>DB: 保存 diagnosis_run.answer
User->>Trace: GET /api/diagnosis/{sessionId}/trace?runId=...
Trace->>DB: 聚合 run / step / tool
Trace-->>User: 返回可回放诊断链路
```
```text
POST /api/chat
-> ChatService
-> 简单问题:轻量回答
-> 复杂诊断:Agent 编排
-> Planner 制定排查方向
-> Executor 调用证据工具
-> lookup_knowledge
-> query_logs
-> query_metrics
-> Gatekeeper 校验 Executor 证据引用真实性
-> Verifier 判断 claim 是否能由已核验证据推出
-> Composer 生成最终用户答复
-> 保存 chat_session metadata
-> 保存 diagnosis_run
-> 保存 agent_step.run_id
-> 保存 tool_invocation.run_id
-> 合并 diagnosis_run.self_evaluation.verifier_evaluation
```
Chat 链路的质量门禁由三段组成:Gatekeeper 先做代码级引用验真,Verifier 再做 LLM 可推导性判断,Composer 最后控制对用户的表达边界。Gatekeeper、Verifier、Composer 的输出合并到当前 `diagnosis_run.self_evaluation.verifier_evaluation`,Trace API 会展示该验证结果。
Agent 编排细节见 [agent-orchestration.md](agent-orchestration.md)。
关键代码:
- `src/main/java/com/superbiz/agent/controller/ChatController.java`
- `src/main/java/com/superbiz/agent/service/ChatService.java`
- `src/main/java/com/superbiz/agent/service/SelfEvaluationMergeService.java`
- `src/main/java/com/superbiz/agent/service/DiagnosisTraceService.java`
## 4. AIOps 诊断链路
```mermaid
flowchart TD
Request["POST /api/ai_ops"] --> Payload{"包含告警 payload?"}
Payload -->|是| Targeted["PAYLOAD_TARGETED"]
Payload -->|否| Discovery["AUTO_DISCOVERY"]
Targeted --> BuildPrompt["构造聚焦 payload 的诊断 prompt"]
Targeted --> QueryAug["生成 recommended lookup_knowledge query"]
Discovery --> DiscoverAlert["通过 queryPrometheusAlerts 发现活跃告警"]
BuildPrompt --> Plan["Planner 规划排查"]
QueryAug --> Plan
DiscoverAlert --> Plan
Plan --> Execute["Executor 收集证据"]
Execute --> Knowledge["lookup_knowledge"]
Execute --> Metrics["query_metrics / Prometheus"]
Execute --> Logs["query_logs"]
Knowledge --> Report["告警分析报告"]
Metrics --> Report
Logs --> Report
Report --> RuleEval["AiOpsRuleEvaluationService"]
RuleEval --> SelfEval["self_evaluation.aiops_rule_evaluation"]
Report --> Trace["DiagnosisTraceService"]
SelfEval --> Trace
```
```text
POST /api/ai_ops
-> AiOpsService
-> 判断是否有告警 payload
-> PAYLOAD_TARGETED
-> AUTO_DISCOVERY
-> 构造 AIOps 诊断 prompt
-> payload 模式补充 recommended lookup_knowledge query
-> Agent 编排
-> Planner / Executor
-> Prometheus / logs / knowledge tools
-> 生成告警分析报告
-> AiOpsRuleEvaluationService
-> 合并 diagnosis_run.self_evaluation.aiops_rule_evaluation
-> Trace API 可查看全链路
```
AIOps 保留两种模式:
| 模式 | 触发条件 | 行为 |
|---|---|---|
| `PAYLOAD_TARGETED` | 请求包含 alertName、service、severity、description、timeRange 等字段 | 以 payload 为唯一主诊断对象,并生成推荐知识库 query |
| `AUTO_DISCOVERY` | 请求没有明确告警 payload | 先查询当前活跃告警,再选择目标排查 |
AIOps 当前使用轻量规则验证器,重点检查:
- 最终报告是否存在。
- payload 模式是否聚焦输入告警。
- 是否使用关键证据工具,例如 `lookup_knowledge`、日志、指标。
关键代码:
- `src/main/java/com/superbiz/agent/service/AiOpsService.java`
- `src/main/java/com/superbiz/agent/service/AiOpsRuleEvaluationService.java`
## 5. RAG 位置
RAG 不是隐藏在 Chat Advisor 里的隐式能力,而是 Executor 可以显式调用的工具:
```mermaid
flowchart LR
Executor["Executor Agent"] --> Tool["lookup_knowledge Tool"]
Tool --> L0["L0 domain/entity hint"]
Tool --> Search["VectorSearchService"]
L0 --> Search
Search --> VectorStore["Spring AI VectorStore"]
Search --> Fallback["Milvus SDK fallback"]
VectorStore --> Normalize["score/rawScore/scoreLabel"]
Fallback --> Normalize
Normalize --> Evidence["evidence output"]
Evidence --> Invocation["tool_invocation"]
Evidence --> Executor
```
```text
Executor
-> lookup_knowledge(query)
-> L0 domain/entity hint
-> VectorSearchService
-> Spring AI VectorStore
-> Milvus SDK fallback
-> evidence shaping
-> tool_invocation
```
保留显式工具的原因:
- Agent 何时检索、检索什么、证据是什么,必须能在 trace 中解释。
- AIOps payload 到 query 的业务映射需要项目内控制。
- `tool_invocation` 是后续评测、回放和面试讲解的核心材料。
RAG 总体设计见 [rag-architecture.md](rag-architecture.md),检索运行细节见 [retrieval-observability.md](retrieval-observability.md)。
## 6. 持久化模型
当前诊断持久化以 session/run/trace 明细为核心:
```text
chat_session
-> 多轮会话目录和元数据
-> session_id / status / message_pair_count
diagnosis_run
-> 一次诊断运行的主记录
-> run_id / session_id
-> query / status / agent_flow / answer
-> self_evaluation
-> step_count / tool_call_count / duration
agent_step
-> Agent 模型调用步骤
-> session_id / run_id
-> step_index / agent_name
-> model_input / model_output / thought
-> duration / token_count
tool_invocation
-> 工具调用事实
-> session_id / run_id
-> tool_name / input_params / output_preview
-> retrieval_layer / retrieval_details
-> retrieval_details.evidence_refs
-> relevance_level / dedup_reason
-> duration / success
```
说明:
- 旧的 `diagnosis_record` 已不是当前主模型。
- `diagnosis_session` 已降级为历史兼容和回滚表,新执行写入 `chat_session + diagnosis_run`。
- `api_document` 仍用于文档元数据管理。
- 文档向量内容存放在 Milvus/Zilliz collection 中。
会话和 Trace 生命周期见 [session-trace-lifecycle.md](session-trace-lifecycle.md),完整数据关系见 [data-model.md](data-model.md)。
## 7. Trace API
```text
GET /api/diagnosis/{sessionId}/trace
GET /api/diagnosis/{sessionId}/trace?runId=run-...
```
Trace API 聚合:
- 会话元数据、运行状态和最终报告。
- Agent step 序列。
- 工具调用和检索细节。
- Chat Gatekeeper / Verifier / Composer 结果。
- AIOps rule evaluation 结果。
Trace 是本项目区别于普通问答系统的关键:答案不是孤立文本,而是可以追溯到 Agent 决策、工具调用和证据来源。
Prompt、Hook、Gatekeeper、Verifier、Composer 和评测门禁的完整说明见 [harness-quality-gates.md](harness-quality-gates.md),用户反馈与 `self_evaluation` 闭环见 [feedback-architecture.md](feedback-architecture.md)。
## 8. 质量门禁
当前质量门禁分层如下:
| 门禁 | 位置 | 作用 |
|---|---|---|
| Executor Gatekeeper | `VerifierInputHook` / `ExecutorGatekeeperService` | 校验 Executor 引用的 invocation、`raw_path`、`evidence_excerpt` 是否真实 |
| Chat Verifier | `ChatService` | 判断已验真证据是否能推出 Executor claims |
| Chat Composer | `ChatService` | 只表达 Verifier 允许输出的内容,避免把 no-evidence 说成已排除 |
| AIOps Rule Evaluation | `AiOpsRuleEvaluationService` | 校验告警诊断是否聚焦 payload 并使用证据 |
| Diagnosis Eval Baseline | `mvp/eval/` | 固化诊断 trace 和报告行为 |
| RAG Retrieval Baseline | `eval/rag-retrieval/` | 固化检索召回行为,避免 RAG 重构回退 |
| Live RAG Acceptance | `scripts/eval_rag_live_acceptance.py` | 在运行环境中验证重建索引后的真实检索 |
## 9. 当前完成状态
已经完成:
- Chat 和 AIOps 两条入口链路。
- 显式 `lookup_knowledge` Agent Tool。
- L0 从最终决策降级为 domain/entity hint。
- `VectorSearchService` 作为稳定检索门面。
- Spring AI VectorStore 读取路径。
- Milvus SDK fallback。
- `score` / `rawScore` / `scoreLabel` 分数语义拆分。
- `title`、`breadcrumb`、`content` 参与 embedding 文本。
- `tool_invocation` 记录检索层、relevance level、dedup reason。
- Chat verifier 和 AIOps rule evaluation 合并进 `self_evaluation`。
- Chat Executor 结构化输出 `executor_evidence_v2`,不再直接承担最终用户答复。
- `tool_invocation.retrieval_details.evidence_refs` 支持 `raw_path` 精确引用和 `$.no_evidence` 负向证据。
- Gatekeeper 对 Executor 引用做代码级验真,并在审计中记录 `rule_set_version` 和规则元数据摘要。
- Verifier 只判断可推导性。
- Composer 在 Verifier 之后生成最终用户表达,并限制 negative observation 过度表述。
- RAG offline baseline 和 live acceptance 脚本。
暂不作为当前已完成能力声明:
- 完整 QueryTransformer / MultiQuery。
- BM25、RRF、cross-encoder rerank。
- 完整邻居 chunk / section context expansion。
- VectorStore 写入路径全面迁移。
- 完整 LLM-based AIOps verifier。
后续 Agent 拆分、Skill/Playbook、MCP 工具协议化和进程隔离等方向见 [evolution-roadmap.md](evolution-roadmap.md)。
## 10. 关键代码索引
| 能力 | 代码 |
|---|---|
| Chat 入口与编排 | `ChatController`, `ChatService` |
| AIOps 入口与编排 | `ChatController.aiOps`, `AiOpsService` |
| AIOps 规则验证 | `AiOpsRuleEvaluationService` |
| 知识库工具 | `LookupKnowledgeTool` |
| L0 hint | `KnowledgeIndexService` |
| 向量检索门面 | `VectorSearchService` |
| 文档切片 | `DocumentChunkService` |
| 向量写入 | `VectorIndexService` |
| Spring AI VectorStore 配置辅助 | `SpringAiVectorStoreSidecarService` |
| Trace 聚合 | `DiagnosisTraceService` |
| 工具调用记录 | `ToolInvocationRecorder` |
| Executor 引用验真 | `ExecutorGatekeeperService`, `VerifierInputHook` |
| self_evaluation 合并 | `SelfEvaluationMergeService` |
@@ -0,0 +1,258 @@
# Harness 与质量门禁架构
**更新日期**:2026-07-08
**状态**:当前可运行架构 + 后续门禁规划
**参考历史文档**:`archive/2026-07-05-legacy/agent-architecture.md`
## 1. 设计目标
Agent 系统的核心风险不是“没有答案”,而是:
- 答案引用了不存在的证据。
- 工具调用失败后仍然编造结论。
- 检索结果相关性不足但被当作强证据。
- 多轮诊断重复检索同一文档,浪费上下文。
- 最终报告无法回放执行过程。
因此当前 MVP 的 Harness 不是单个组件,而是一组约束:
```text
Prompt contract
+ Tool boundary
+ Agent hooks
+ Trace persistence
+ Gatekeeper deterministic validation
+ Verifier / rule evaluation
+ Eval baseline
```
## 2. Harness 总图
```mermaid
flowchart TB
Input["User / AIOps input"] --> Prompt["Prompt contract"]
Prompt --> Agent["Planner / Executor / Verifier / Composer"]
Agent --> Tools["Evidence tools"]
Tools --> Invocation["tool_invocation"]
Agent --> StepHook["AgentLoggingHook"]
StepHook --> Step["agent_step"]
Agent --> Run["diagnosis_run"]
Invocation --> EvidenceRefs["retrieval_details.evidence_refs"]
EvidenceRefs --> Gatekeeper["ExecutorGatekeeperService"]
Agent --> Gatekeeper
Invocation --> TraceSummary["ToolTraceSummaryService"]
Gatekeeper --> Verifier["chat_verifier"]
TraceSummary --> Verifier
Verifier --> SelfEval["self_evaluation.verifier_evaluation"]
Invocation --> AiOpsRule["AiOpsRuleEvaluationService"]
AiOpsRule --> AiOpsEval["self_evaluation.aiops_rule_evaluation"]
Run --> TraceAPI["DiagnosisTraceService"]
Step --> TraceAPI
Invocation --> TraceAPI
SelfEval --> TraceAPI
AiOpsEval --> TraceAPI
TraceAPI --> Eval["diagnosis eval / RAG eval"]
```
## 3. Prompt Contract
当前 Prompt 按角色拆分:
| Prompt | 用途 |
|---|---|
| `supervisor-prompt.md` | AIOps Supervisor 调度 Planner / Executor |
| `planner-prompt.md` | AIOps Planner 规划、再规划、输出告警报告 |
| `executor-prompt.md` | AIOps Executor 按步骤调用工具 |
| `chat-planner-prompt.md` | Chat 复杂问题规划 |
| `chat-executor-prompt.md` | Chat 执行工具并输出 `executor_evidence_v2` 微观事实 |
| `chat-verifier-prompt.md` | 基于 Gatekeeper 已验真的证据判断 claims 是否可推出 |
| `chat-composer-prompt.md` | 基于 Verifier 允许表达的内容生成最终用户答复 |
Prompt 层当前承担的门禁:
- 禁止凭记忆回答错误码、接口定义、排障步骤。
- 需要外部信息时必须调用工具。
- 工具连续失败或返回空结果时,最终报告必须诚实说明。
- Chat Executor 不允许在窄范围问题中扩展根因、风险或修复建议。
- Chat Verifier 不允许做新检索,只能判断已验真证据是否可推出 claims。
- Chat Composer 不允许补事实,尤其不能把 `$.no_evidence` 表达为“已排除/确认没有”。
- AIOps payload 模式必须聚焦输入告警。
Chat 链路还会在 `verifier_evaluation.prompt_audit` 中持久化紧凑 Prompt 审计快照:
```json
{
"version": "chat-prompts-v1",
"prompts": [
{
"name": "chat_executor",
"version": "chat-executor-v2",
"resource": "prompts/chat-executor-prompt.md"
}
]
}
```
该快照只保存版本和资源路径,不保存完整 Prompt 文本。它用于面试演示、trace 回放和离线 baseline 解释“本次诊断使用了哪套 Prompt 契约”。
## 4. Trace Hooks
`AgentLoggingHook` 是当前 Agent step 可观测性的核心。
```mermaid
sequenceDiagram
autonumber
participant A as Agent
participant H as AgentLoggingHook
participant DB as agent_step
A->>H: before_model(messages, sessionId, runId)
H->>DB: 写入 session_id / run_id / model_input / step_index / agent_name
A-->>A: LLM 推理
A->>H: after_model(messages, sessionId, runId)
H->>DB: 回填 model_output / thought / has_tool_call / duration / token_count
```
记录内容:
- 最近输入消息摘要。
- Agent 输出摘要。
- 是否包含 tool call。
- duration。
- token count。
- Verifier 的 JSON 输出摘要。
新写入必须带 `run_id`;`session_id` 仍保留用于粗粒度排查和历史兼容。
## 5. Tool Invocation 门禁
工具调用记录由 `ToolInvocationRecorder` 和具体工具共同完成。
核心记录:
```text
tool_name
input_params
output_preview
retrieval_layer
l0_match_count
l1_match_count
retrieval_details
-> evidence_refs
relevance_level
dedup_reason
duration_ms
success
error_message
```
对 `lookup_knowledge` 的质量约束:
- L0 只作为 hint,不绕过 L1。
- 检索结果归一化为 `PRECISE`、`HIGHLY_RELEVANT`、`REFERENCE`。
- 同 session 内重复文档会被 `RetrievedDocTracker` 去重。
- dedup、no evidence、failed 等状态进入 `retrieval_details.evidence_status`。
- `retrieval_details.evidence_refs` 记录可被 Executor 引用的最小证据文本,格式为 `raw_path + text`。
- no-hit / no-evidence 工具结果会生成 `raw_path=$.no_evidence` 的负向证据引用,语义仅限“本次查询未检索到匹配证据”。
## 6. Gatekeeper 与 Verifier 门禁
Chat Verifier 前置一层 Gatekeeper。Gatekeeper 不调用 LLM,只用代码检查 Executor 输出的证据引用是否真实存在。
```mermaid
flowchart LR
Invocation["tool_invocation"] --> EvidenceRefs["retrieval_details.evidence_refs"]
ExecutorOutput["executor_evidence_v2"] --> Gatekeeper["ExecutorGatekeeperService"]
EvidenceRefs --> Gatekeeper
Gatekeeper --> GateResult["gatekeeper_result"]
Invocation --> Summary["ToolTraceSummaryService"]
Summary --> EvidenceIndex["tool_trace_summary"]
GateResult --> Verifier["chat_verifier"]
ExecutorOutput --> Verifier
EvidenceIndex --> Verifier
Verifier --> Verdict{"verdict"}
Verdict -->|PASS| Composer["chat_composer"]
Composer --> Pass["输出最终答复"]
Verdict -->|LOW_CONFID| Low["补证据或低置信输出"]
Verdict -->|REJECT| Reject["降级输出"]
```
Gatekeeper 检查:
| 检查 | 失败语义 |
|---|---|
| `answer_version=executor_evidence_v2` | 非结构化或旧结构输出降为低置信 |
| `source_invocation_id` 真实存在 | 伪造 ID 直接拒绝 |
| `tool_name` 与 invocation 对齐 | 张冠李戴直接拒绝 |
| `raw_path` 存在于 `evidence_refs` | 无中生有直接拒绝 |
| `evidence_excerpt` 由 `evidence_refs[].text` 支撑 | excerpt 编造或错配直接拒绝 |
| `negative_observation` 只能引用 `$.no_evidence` | 用正向日志证明“没查到”直接拒绝 |
Gatekeeper 审计还会记录 `rule_set_version` 和已启用规则元数据摘要。当前规则元数据来自本地 `gatekeeper-rules.json`,规则执行仍是确定性 Java 代码。
Verifier 输出:
```json
{
"verdict": "PASS|LOW_CONFID|REJECT",
"groundedness_score": 0.8,
"critical_fact_count": 2,
"claim_checks": [],
"facts_checked": [],
"rationale": "..."
}
```
Verifier 不再逐字核验 excerpt 真伪;这由 Gatekeeper 完成。Verifier 只回答一个问题:`claim_text` 是否能由已经验真的 `evidence_excerpt` 推导出来。
结果写入:
```text
diagnosis_run.self_evaluation.verifier_evaluation
```
其中同时持久化 `executor_structured_output`、`gatekeeper_result`、`tool_trace_summary`、`prompt_audit` 和 `composer_output`,用于 Trace 回放。
## 7. AIOps 规则门禁
AIOps 当前不走 Chat Verifier,而是用 `AiOpsRuleEvaluationService` 做轻量检查。
检查重点:
- 最终报告是否存在。
- payload 模式是否围绕输入告警展开。
- 是否调用证据工具,尤其是 `lookup_knowledge`、日志、指标。
- 是否把无关活跃告警扩展成主诊断对象。
结果写入:
```text
diagnosis_run.self_evaluation.aiops_rule_evaluation
```
## 8. Eval Baseline
当前质量门禁还包括离线评测资产:
| 评测 | 位置 | 作用 |
|---|---|---|
| Diagnosis eval | `mvp/eval/` | 检查诊断 trace、报告和证据行为 |
| RAG retrieval eval | `eval/rag-retrieval/` | 检查固定检索 query 的召回稳定性 |
| Live RAG acceptance | `scripts/eval_rag_live_acceptance.py` | 检查运行环境中真实 `/api/search/similar` 行为 |
## 9. 后续门禁规划
从旧版设计继承但尚未完整实现的门禁:
- 工具参数 schema 校验。
- 同一工具调用次数上限。
- 工具超时的统一熔断。
- Gatekeeper 规则远程化或三层分离:索引层、元数据层、规则实现层。
- Prompt 版本回滚和更细粒度变更审计。
- Verifier 对 AIOps 报告的 LLM 级事实校验。
这些应在评测集扩大后逐步加入,避免一次性把诊断流程卡得过死。
@@ -0,0 +1,160 @@
# 会话与 Trace 生命周期
**更新日期**:2026-07-10
**状态**:当前可运行架构
**参考历史文档**:`archive/2026-07-05-legacy/session-management.md`
## 1. 定位
当前 MVP 把“会话态”和“运行态”拆开:
```text
chat_session(sessionId)
-> diagnosis_run(runId)
-> agent_step(runId)
-> tool_invocation(runId)
```
- `sessionId` 表示多轮会话目录和 Redis 上下文。
- `runId` 表示一次可回放诊断执行。
- `DiagnosisTraceService` 聚合一个 run 的主记录、步骤和工具调用,形成可回放 Trace。
- `diagnosis_session` 只保留为历史兼容和回滚表。
## 2. 生命周期总图
```mermaid
flowchart TD
Start["request: chat / ai_ops"] --> Resolve["resolve sessionId"]
Resolve --> Session["ensure chat_session metadata"]
Session --> Run["create diagnosis_run(runId)"]
Run --> Running["run.status = RUNNING"]
Running --> Agent["Agent workflow"]
Agent --> Context["execution context(sessionId, runId)"]
Context --> StepHook["AgentLoggingHook"]
StepHook --> Step["agent_step(session_id, run_id)"]
Context --> Tool["Evidence tools"]
Tool --> Invocation["tool_invocation(session_id, run_id)"]
Invocation --> Gatekeeper["Gatekeeper evidence validation"]
Agent --> Final{"workflow result"}
Final -->|success| Success["run.status = SUCCESS, answer saved"]
Final -->|failed| Failed["run.status = FAILED"]
Success --> Evaluation["diagnosis_run.self_evaluation merge"]
Failed --> Evaluation
Evaluation --> Trace["GET /api/diagnosis/{sessionId}/trace?runId=..."]
Success --> Feedback["POST /api/feedback(sessionId, runId)"]
Feedback --> Case["useful -> case_library(run_id)"]
```
## 3. ID 规则
| ID | 来源 | 含义 |
|---|---|---|
| `sessionId` | Chat request `Id`、AIOps payload `sessionId`,缺失时由服务生成 | 多轮会话目录和 Redis 上下文 |
| `runId` | 每次有效 Chat/AIOps 执行创建 | 一次诊断运行和 Trace 回放边界 |
设计含义:
- 同一个 `sessionId` 可以贯穿多轮 Chat。
- 每次有效 Chat/AIOps 执行都会创建新的 `runId`。
- Trace 和 Feedback 新客户端应传 `runId`;只传 `sessionId` 时兼容解析 latest run。
- latest run 排序使用 `diagnosis_run.created_at DESC, id DESC`,不使用 `updated_at`。
## 4. 运行状态流转
```mermaid
stateDiagram-v2
[*] --> PENDING
PENDING --> RUNNING: start diagnosis
RUNNING --> SUCCESS: workflow completed
RUNNING --> FAILED: exception / empty state
SUCCESS --> SUCCESS: feedback submitted
FAILED --> FAILED: feedback submitted
```
字段边界:
| 字段 | 所属表 | 含义 |
|---|---|---|
| `status` | `diagnosis_run` | 单次运行执行状态 |
| `answer` | `diagnosis_run` | 本次运行最终报告或答复 |
| `self_evaluation` | `diagnosis_run` | 本次运行系统自评估 JSON |
| `feedback` | `diagnosis_run` | 本次运行用户反馈 |
`feedback` 不修改 `status`。一个执行成功但用户标记 `not_useful` 的 run,仍然应该是 `SUCCESS + feedback=not_useful`。
## 5. agent_step 写入
`AgentLoggingHook` 在模型调用前后写入和回填 `agent_step`。
```mermaid
sequenceDiagram
autonumber
participant Agent as Agent
participant Hook as AgentLoggingHook
participant DB as agent_step
Agent->>Hook: before_model(messages, sessionId, runId)
Hook->>DB: insert step(session_id, run_id, model_input, step_index)
Agent->>Hook: after_model(output, sessionId, runId)
Hook->>DB: update model_output, duration, token_count, has_tool_call
```
新写入必须带 `run_id`,同时保留 `session_id` 便于粗粒度排查。
## 6. tool_invocation 写入
工具调用记录同样通过执行上下文拿到 `sessionId + runId`:
```text
ToolInvocationRecorder
-> tool_invocation.session_id
-> tool_invocation.run_id
-> retrieval_details / evidence_refs
```
Verifier、Gatekeeper 和 EvaluationService 应按 `run_id` 读取工具调用,避免同一 session 的其他 run 参与评分或证据校验。
## 7. Trace API 聚合
```text
GET /api/diagnosis/{sessionId}/trace
GET /api/diagnosis/{sessionId}/trace?runId=run-...
```
聚合逻辑:
```text
diagnosis_run by sessionId + runId
+ chat_session metadata when available
+ agent_step where run_id = runId, ordered by the Trace API
+ tool_invocation where run_id = runId order by id
-> DiagnosisTraceResponse
```
当 `runId` 缺失时,Trace API 为兼容旧客户端解析最新 run,并在响应中返回 resolved `runId`。当 `runId` 属于其他 `sessionId` 时,API 必须拒绝,不能泄漏其他会话的 Trace。
## 8. Chat 与 AIOps 差异
| 维度 | Chat | AIOps |
|---|---|---|
| `agent_flow` | `CHAT` | `AI_OPS` |
| 编排方式 | `SequentialAgent`: Planner -> Executor -> Gatekeeper -> Verifier -> Composer | `SupervisorAgent`: Planner + Executor |
| 自评估 | `rule_evaluation` + `verifier_evaluation` | `aiops_rule_evaluation` |
| 答案字段 | Chat 最终答复 | 告警分析报告 |
| runId 暴露 | `/api/chat` JSON response | `/api/ai_ops` SSE metadata message |
## 9. 清理与边界
- Redis 会话历史用于多轮上下文,不是长期审计记录。
- MySQL `diagnosis_run + agent_step + tool_invocation` 是主要可回放来源。
- `chat_session.expires_at` 只是目录元数据;Redis 消息历史可独立过期。
- `RetrievedDocTracker` 仍是 session 级运行时去重状态,诊断结束后清理。
## 10. 后续增强
1. Trace API 增加更结构化的 `self_evaluation` 展示。
2. `agent_step` 与 `tool_invocation.step_id` 建立更严格关联。
3. 旧 `diagnosis_session` 只读观察期结束后,再评估数据库层面的约束收紧或归档策略。
+56 -414
View File
@@ -1,444 +1,86 @@
# 当前 MVP 架构
**更新日期**:2026-07-08
**更新日期**:2026-07-22
**状态**:当前可运行架构
**适用范围**:Demo、面试讲解、后续迭代规划
## 1. 系统定位
SuperBizAgent MVP 不是通用 Chatbot,而是面向故障诊断的 Agent 工程项目。
SuperBizAgent 是面向故障诊断的可追踪 Agent 应用。当前系统只保留一个拥有 Tool loop 的 `Diagnosis Agent`;Harness 负责确定性的预算、取消、工具边界、证据验真、语义审查和安全发布。
核心目标:
- 支持用户主动发起的 Chat 诊断。
- 支持 AIOps 告警触发的自动诊断。
- 保留 Agent 的规划、执行、验证过程。
- 工具调用必须显式、可追踪、可回放。
- RAG 检索必须通过 `lookup_knowledge` 暴露证据链。
- 每次诊断都沉淀 session、step、tool invocation 和 self evaluation。
## 2. 总体分层
## 2. 分层
```mermaid
flowchart TB
subgraph API["API Layer"]
ChatController["ChatController"]
TraceController["DiagnosisTraceController"]
SearchController["SearchController"]
DocumentController["DocumentController"]
end
subgraph App["Application Service"]
ChatService["ChatService"]
AiOpsService["AiOpsService"]
TraceService["DiagnosisTraceService"]
end
subgraph Agent["Agent Orchestration"]
Supervisor["Supervisor"]
Planner["Planner"]
Executor["Executor"]
Gatekeeper["Gatekeeper"]
Verifier["Verifier"]
Composer["Composer"]
end
subgraph Tools["Evidence Tools"]
KnowledgeTool["lookup_knowledge"]
LogsTool["query_logs"]
MetricsTool["query_metrics"]
AlertsTool["queryPrometheusAlerts"]
end
subgraph Skills["Skill / Playbook"]
SkillRegistry["SkillRegistry"]
PlannerSkillHook["PlannerSkillMetadataHook"]
SkillsHook["SkillsAgentHook"]
ReadSkill["read_skill"]
end
subgraph RAG["RAG Retrieval"]
L0["KnowledgeIndexService"]
VectorSearch["VectorSearchService"]
VectorStore["Spring AI VectorStore"]
SdkFallback["Milvus SDK fallback"]
end
subgraph Store["Persistence and Trace"]
ChatSession["chat_session"]
Run["diagnosis_run"]
Step["agent_step"]
Invocation["tool_invocation"]
ApiDoc["api_document"]
Milvus["Milvus/Zilliz"]
end
API --> App
ChatService --> Agent
AiOpsService --> Agent
SkillRegistry --> PlannerSkillHook
PlannerSkillHook --> Planner
SkillRegistry --> SkillsHook
SkillsHook --> Executor
Executor --> ReadSkill
Agent --> Tools
KnowledgeTool --> RAG
RAG --> Store
Tools --> Invocation
Agent --> Step
App --> Session
TraceService --> Session
TraceService --> Step
TraceService --> Invocation
Browser["Browser / API client"] --> Chat["POST /api/chat named SSE"]
Chat --> App["ChatApplicationUseCase"]
App --> Router["Intent Router"]
Router --> System["System Chat"]
Router --> Knowledge["Knowledge Query"]
Router --> Diagnosis["Diagnosis Agent"]
Diagnosis --> Tools["Harness ACI Tools"]
Tools --> Canonical["Redis canonical invocation"]
Diagnosis --> Evidence["EvidenceGuard"]
Evidence --> Semantic["SemanticGuard"]
Semantic --> Release["Release Policy"]
Release --> Chat
App --> Run["diagnosis_run"]
Diagnosis --> Step["agent_step metadata audit"]
Tools --> Invocation["tool_invocation metadata audit"]
Run --> Trace["Diagnosis Trace API"]
Step --> Trace
Invocation --> Trace
```
```text
API Layer
-> ChatController
-> DiagnosisTraceController
-> SearchController
-> DocumentController
Application Service
-> ChatService
-> AiOpsService
-> DiagnosisTraceService
Agent Orchestration
-> Supervisor
-> Planner
-> Executor
-> Gatekeeper
-> Verifier
-> Composer
Evidence Tools
-> lookup_knowledge
-> query_logs
-> query_metrics
-> queryPrometheusAlerts
Skill / Playbook
-> SkillRegistry
-> PlannerSkillMetadataHook gives Planner name/description only
-> SkillsAgentHook gives Executor read_skill
-> Verifier is isolated from skills
RAG Retrieval
-> KnowledgeIndexService
-> VectorSearchService
-> Spring AI VectorStore
-> Milvus SDK fallback
Persistence
-> chat_session
-> diagnosis_run
-> agent_step.run_id
-> tool_invocation.run_id
-> api_document
-> Milvus/Zilliz collection
Quality Gates
-> executor gatekeeper
-> chat verifier
-> AIOps rule evaluation
-> diagnosis eval baseline
-> RAG retrieval baseline
```
## 3. Chat 诊断链路
```mermaid
sequenceDiagram
autonumber
actor User as 用户
participant API as POST /api/chat
participant Chat as ChatService
participant Planner as Planner Agent
participant Executor as Executor Agent
participant Tool as Evidence Tools
participant Gatekeeper as Gatekeeper Hook
participant Verifier as Verifier Agent
participant Composer as Composer Agent
participant DB as Trace Tables
participant Trace as Trace API
User->>API: 提交诊断问题
API->>Chat: execute chat strategy
Chat->>DB: 创建 chat_session metadata + diagnosis_run(runId)
Chat->>Planner: 复杂问题进入规划
Planner->>DB: 写入 agent_step.run_id
Planner->>Executor: 下发排查方向
Executor->>Tool: lookup_knowledge / logs / metrics
Tool->>DB: 写入 tool_invocation.run_id
Tool-->>Executor: 返回证据
Executor->>Gatekeeper: 输出 executor_evidence_v2
Gatekeeper->>DB: 读取 tool_invocation.evidence_refs 并校验引用
Gatekeeper->>Verifier: 传入已验真的 claims / excerpts
Verifier->>DB: 合并 diagnosis_run.self_evaluation.verifier_evaluation
Verifier->>Composer: 传入 allowed_claims / missing_info / actions
Composer->>Chat: 生成最终用户答复
Chat->>DB: 保存 diagnosis_run.answer
User->>Trace: GET /api/diagnosis/{sessionId}/trace?runId=...
Trace->>DB: 聚合 run / step / tool
Trace-->>User: 返回可回放诊断链路
```
## 3. 唯一 Chat 主链
```text
POST /api/chat
-> ChatService
-> 简单问题:轻量回答
-> 复杂诊断:Agent 编排
-> Planner 制定排查方向
-> Executor 调用证据工具
-> lookup_knowledge
-> query_logs
-> query_metrics
-> Gatekeeper 校验 Executor 证据引用真实性
-> Verifier 判断 claim 是否能由已核验证据推出
-> Composer 生成最终用户答复
-> 保存 chat_session metadata
-> 保存 diagnosis_run
-> 保存 agent_step.run_id
-> 保存 tool_invocation.run_id
-> 合并 diagnosis_run.self_evaluation.verifier_evaluation
-> metadata(session_id, run_id)
-> status*
-> ChatApplicationUseCase
-> SYSTEM_CHAT | KNOWLEDGE_QUERY | DIAGNOSIS
-> content | failure
-> done(SUCCESS | FALLBACK | FAILED)
```
Chat 链路的质量门禁由三段组成:Gatekeeper 先做代码级引用验真,Verifier 再做 LLM 可推导性判断,Composer 最后控制对用户的表达边界。Gatekeeper、Verifier、Composer 的输出合并到当前 `diagnosis_run.self_evaluation.verifier_evaluation`,Trace API 会展示该验证结果。
- Controller 只处理请求校验、bounded worker、SSE 和 disconnect。
- Application Use Case 拥有 Session/Run、路由、PreviousTurn 和终态持久化。
- Diagnosis Agent 是唯一报告作者和唯一拥有 evidence Tool loop 的业务 Agent。
- EvidenceGuard 只做确定性结构/引用验真;SemanticGuard 在隔离上下文做整份报告语义审查。
- 未通过 Release Policy 的 Draft 永不进入公开 SSE。
Agent 编排细节见 [agent-orchestration.md](agent-orchestration.md)。
## 4. Tool 与数据边界
关键代码:
Agent 只看到三个固定 Tool:
- `src/main/java/com/superbiz/agent/controller/ChatController.java`
- `src/main/java/com/superbiz/agent/service/ChatService.java`
- `src/main/java/com/superbiz/agent/service/SelfEvaluationMergeService.java`
- `src/main/java/com/superbiz/agent/service/DiagnosisTraceService.java`
- `lookup_knowledge`
- `query_logs`
- `query_mysql`
## 4. AIOps 诊断链路
每次调用由框架提供 `tool_call_id`,Harness 校验 exact run、只读、Schema、预算和容量。Redis 保存 TTL 内完整 canonical invocation;MySQL `tool_invocation` 只保存长期有界 metadata,不保存完整参数、SQL/日志正文、raw response 或 Agent projection。
```mermaid
flowchart TD
Request["POST /api/ai_ops"] --> Payload{"包含告警 payload?"}
Payload -->|是| Targeted["PAYLOAD_TARGETED"]
Payload -->|否| Discovery["AUTO_DISCOVERY"]
Targeted --> BuildPrompt["构造聚焦 payload 的诊断 prompt"]
Targeted --> QueryAug["生成 recommended lookup_knowledge query"]
Discovery --> DiscoverAlert["通过 queryPrometheusAlerts 发现活跃告警"]
BuildPrompt --> Plan["Planner 规划排查"]
QueryAug --> Plan
DiscoverAlert --> Plan
Plan --> Execute["Executor 收集证据"]
Execute --> Knowledge["lookup_knowledge"]
Execute --> Metrics["query_metrics / Prometheus"]
Execute --> Logs["query_logs"]
Knowledge --> Report["告警分析报告"]
Metrics --> Report
Logs --> Report
Report --> RuleEval["AiOpsRuleEvaluationService"]
RuleEval --> SelfEval["self_evaluation.aiops_rule_evaluation"]
Report --> Trace["DiagnosisTraceService"]
SelfEval --> Trace
```
## 5. Trace 与持久化
```text
POST /api/ai_ops
-> AiOpsService
-> 判断是否有告警 payload
-> PAYLOAD_TARGETED
-> AUTO_DISCOVERY
-> 构造 AIOps 诊断 prompt
-> payload 模式补充 recommended lookup_knowledge query
-> Agent 编排
-> Planner / Executor
-> Prometheus / logs / knowledge tools
-> 生成告警分析报告
-> AiOpsRuleEvaluationService
-> 合并 diagnosis_run.self_evaluation.aiops_rule_evaluation
-> Trace API 可查看全链路
chat_session(sessionId)
-> diagnosis_run(runId)
-> agent_step(runId)
-> tool_invocation(runId)
```
AIOps 保留两种模式:
- `chat_session` 是 JPA Run 目录与多轮 metadata,不保存完整对话历史。
- `diagnosis_run` 是 Run 状态、intent、release outcome、安全发布结果和预算汇总真理源。
- `agent_step` 只保存模型步骤 metadata,不保存 Prompt、消息正文、模型正文或 Thought。
- `tool_invocation` 只保存 Tool durable audit metadata;完整调用由 Redis canonical store 短期保存。
| 模式 | 触发条件 | 行为 |
|---|---|---|
| `PAYLOAD_TARGETED` | 请求包含 alertName、service、severity、description、timeRange 等字段 | 以 payload 为唯一主诊断对象,并生成推荐知识库 query |
| `AUTO_DISCOVERY` | 请求没有明确告警 payload | 先查询当前活跃告警,再选择目标排查 |
## 6. 公开 API
AIOps 当前使用轻量规则验证器,重点检查:
当前诊断执行入口只有 `POST /api/chat`。Trace、feedback、文档与检索 API 保持独立;已删除的旧诊断和 Redis conversation Session endpoint 不提供兼容分支。
- 最终报告是否存在。
- payload 模式是否聚焦输入告警。
- 是否使用关键证据工具,例如 `lookup_knowledge`、日志、指标。
## 7. 安全边界
关键代码:
- `src/main/java/com/superbiz/agent/service/AiOpsService.java`
- `src/main/java/com/superbiz/agent/service/AiOpsRuleEvaluationService.java`
## 5. RAG 位置
RAG 不是隐藏在 Chat Advisor 里的隐式能力,而是 Executor 可以显式调用的工具:
```mermaid
flowchart LR
Executor["Executor Agent"] --> Tool["lookup_knowledge Tool"]
Tool --> L0["L0 domain/entity hint"]
Tool --> Search["VectorSearchService"]
L0 --> Search
Search --> VectorStore["Spring AI VectorStore"]
Search --> Fallback["Milvus SDK fallback"]
VectorStore --> Normalize["score/rawScore/scoreLabel"]
Fallback --> Normalize
Normalize --> Evidence["evidence output"]
Evidence --> Invocation["tool_invocation"]
Evidence --> Executor
```
```text
Executor
-> lookup_knowledge(query)
-> L0 domain/entity hint
-> VectorSearchService
-> Spring AI VectorStore
-> Milvus SDK fallback
-> evidence shaping
-> tool_invocation
```
保留显式工具的原因:
- Agent 何时检索、检索什么、证据是什么,必须能在 trace 中解释。
- AIOps payload 到 query 的业务映射需要项目内控制。
- `tool_invocation` 是后续评测、回放和面试讲解的核心材料。
RAG 总体设计见 [rag-architecture.md](rag-architecture.md),检索运行细节见 [retrieval-observability.md](retrieval-observability.md)。
## 6. 持久化模型
当前诊断持久化以 session/run/trace 明细为核心:
```text
chat_session
-> 多轮会话目录和元数据
-> session_id / status / message_pair_count
diagnosis_run
-> 一次诊断运行的主记录
-> run_id / session_id
-> query / status / agent_flow / answer
-> self_evaluation
-> step_count / tool_call_count / duration
agent_step
-> Agent 模型调用步骤
-> session_id / run_id
-> step_index / agent_name
-> model_input / model_output / thought
-> duration / token_count
tool_invocation
-> 工具调用事实
-> session_id / run_id
-> tool_name / input_params / output_preview
-> retrieval_layer / retrieval_details
-> retrieval_details.evidence_refs
-> relevance_level / dedup_reason
-> duration / success
```
说明:
- 旧的 `diagnosis_record` 已不是当前主模型。
- `diagnosis_session` 已降级为历史兼容和回滚表,新执行写入 `chat_session + diagnosis_run`。
- `api_document` 仍用于文档元数据管理。
- 文档向量内容存放在 Milvus/Zilliz collection 中。
会话和 Trace 生命周期见 [session-trace-lifecycle.md](session-trace-lifecycle.md),完整数据关系见 [data-model.md](data-model.md)。
## 7. Trace API
```text
GET /api/diagnosis/{sessionId}/trace
GET /api/diagnosis/{sessionId}/trace?runId=run-...
```
Trace API 聚合:
- 会话元数据、运行状态和最终报告。
- Agent step 序列。
- 工具调用和检索细节。
- Chat Gatekeeper / Verifier / Composer 结果。
- AIOps rule evaluation 结果。
Trace 是本项目区别于普通问答系统的关键:答案不是孤立文本,而是可以追溯到 Agent 决策、工具调用和证据来源。
Prompt、Hook、Gatekeeper、Verifier、Composer 和评测门禁的完整说明见 [harness-quality-gates.md](harness-quality-gates.md),用户反馈与 `self_evaluation` 闭环见 [feedback-architecture.md](feedback-architecture.md)。
## 8. 质量门禁
当前质量门禁分层如下:
| 门禁 | 位置 | 作用 |
|---|---|---|
| Executor Gatekeeper | `VerifierInputHook` / `ExecutorGatekeeperService` | 校验 Executor 引用的 invocation、`raw_path`、`evidence_excerpt` 是否真实 |
| Chat Verifier | `ChatService` | 判断已验真证据是否能推出 Executor claims |
| Chat Composer | `ChatService` | 只表达 Verifier 允许输出的内容,避免把 no-evidence 说成已排除 |
| AIOps Rule Evaluation | `AiOpsRuleEvaluationService` | 校验告警诊断是否聚焦 payload 并使用证据 |
| Diagnosis Eval Baseline | `mvp/eval/` | 固化诊断 trace 和报告行为 |
| RAG Retrieval Baseline | `eval/rag-retrieval/` | 固化检索召回行为,避免 RAG 重构回退 |
| Live RAG Acceptance | `scripts/eval_rag_live_acceptance.py` | 在运行环境中验证重建索引后的真实检索 |
## 9. 当前完成状态
已经完成:
- Chat 和 AIOps 两条入口链路。
- 显式 `lookup_knowledge` Agent Tool。
- L0 从最终决策降级为 domain/entity hint。
- `VectorSearchService` 作为稳定检索门面。
- Spring AI VectorStore 读取路径。
- Milvus SDK fallback。
- `score` / `rawScore` / `scoreLabel` 分数语义拆分。
- `title`、`breadcrumb`、`content` 参与 embedding 文本。
- `tool_invocation` 记录检索层、relevance level、dedup reason。
- Chat verifier 和 AIOps rule evaluation 合并进 `self_evaluation`。
- Chat Executor 结构化输出 `executor_evidence_v2`,不再直接承担最终用户答复。
- `tool_invocation.retrieval_details.evidence_refs` 支持 `raw_path` 精确引用和 `$.no_evidence` 负向证据。
- Gatekeeper 对 Executor 引用做代码级验真,并在审计中记录 `rule_set_version` 和规则元数据摘要。
- Verifier 只判断可推导性。
- Composer 在 Verifier 之后生成最终用户表达,并限制 negative observation 过度表述。
- RAG offline baseline 和 live acceptance 脚本。
暂不作为当前已完成能力声明:
- 完整 QueryTransformer / MultiQuery。
- BM25、RRF、cross-encoder rerank。
- 完整邻居 chunk / section context expansion。
- VectorStore 写入路径全面迁移。
- 完整 LLM-based AIOps verifier。
后续 Agent 拆分、Skill/Playbook、MCP 工具协议化和进程隔离等方向见 [evolution-roadmap.md](evolution-roadmap.md)。
## 10. 关键代码索引
| 能力 | 代码 |
|---|---|
| Chat 入口与编排 | `ChatController`, `ChatService` |
| AIOps 入口与编排 | `ChatController.aiOps`, `AiOpsService` |
| AIOps 规则验证 | `AiOpsRuleEvaluationService` |
| 知识库工具 | `LookupKnowledgeTool` |
| L0 hint | `KnowledgeIndexService` |
| 向量检索门面 | `VectorSearchService` |
| 文档切片 | `DocumentChunkService` |
| 向量写入 | `VectorIndexService` |
| Spring AI VectorStore 配置辅助 | `SpringAiVectorStoreSidecarService` |
| Trace 聚合 | `DiagnosisTraceService` |
| 工具调用记录 | `ToolInvocationRecorder` |
| Executor 引用验真 | `ExecutorGatekeeperService`, `VerifierInputHook` |
| self_evaluation 合并 | `SelfEvaluationMergeService` |
- 不输出或长期持久化 Chain of Thought。
- 不向 Agent 暴露 Redis、canonical key、完整 Tool 请求/响应或数据库凭据。
- EvidenceGuard 只接受当前 Run 的 READY canonical invocation。
- SemanticGuard 无 Tool、无记忆、无回调主 Agent 能力。
- technical failure 与 guard rejection 只能产生 stable failure 或固定 safe fallback。
+31 -241
View File
@@ -1,258 +1,48 @@
# Harness 与质量门禁架构
# Harness 与质量门禁
**更新日期**:2026-07-08
**状态**:当前可运行架构 + 后续门禁规划
**参考历史文档**:`archive/2026-07-05-legacy/agent-architecture.md`
**更新日期**:2026-07-22
**状态**:当前可运行架构
## 1. 设计目标
## 1. Harness 定位
Agent 系统的核心风险不是“没有答案”,而是:
Harness 是确定性执行边界,不承担业务推理。它统一管理:
- 答案引用了不存在的证据。
- 工具调用失败后仍然编造结论。
- 检索结果相关性不足但被当作强证据。
- 多轮诊断重复检索同一文档,浪费上下文。
- 最终报告无法回放执行过程。
- RunContext、deadline、first-terminal-wins lifecycle 与客户端取消。
- 模型调用、Tool 调用、Token、字节数和单 Tool 次数预算。
- 类型化 retry policy;Diagnosis Agent 和 Tool 调用不自动重试。
- ToolBoundary、canonical invocation 与 Agent projection。
- EvidenceGuard、Evidence repair、SemanticGuard 与 Release Policy。
- metadata-only durable audit。
因此当前 MVP 的 Harness 不是单个组件,而是一组约束:
## 2. ToolBoundary
```text
Prompt contract
+ Tool boundary
+ Agent hooks
+ Trace persistence
+ Gatekeeper deterministic validation
+ Verifier / rule evaluation
+ Eval baseline
framework tool_call_id
-> exact Run / schema / authorization / read-only / budget
-> backend execution
-> raw response -> Redis canonical invocation
-> projector -> bounded agent_result
-> ToolInvocation durable metadata audit
-> Agent observation
```
## 2. Harness 总图
Redis canonical invocation 可在 TTL 内保存完整 request/raw_response/agent_result,受独立前缀、容量和 Harness-only 访问保护。Durable audit 只保存 identity、Tool 名、状态、耗时和字节数;audit 写入失败可观测但不改变 canonical Tool 结果。
```mermaid
flowchart TB
Input["User / AIOps input"] --> Prompt["Prompt contract"]
Prompt --> Agent["Planner / Executor / Verifier / Composer"]
Agent --> Tools["Evidence tools"]
Tools --> Invocation["tool_invocation"]
Agent --> StepHook["AgentLoggingHook"]
StepHook --> Step["agent_step"]
Agent --> Run["diagnosis_run"]
## 3. EvidenceGuard
Invocation --> EvidenceRefs["retrieval_details.evidence_refs"]
EvidenceRefs --> Gatekeeper["ExecutorGatekeeperService"]
Agent --> Gatekeeper
Invocation --> TraceSummary["ToolTraceSummaryService"]
Gatekeeper --> Verifier["chat_verifier"]
TraceSummary --> Verifier
Verifier --> SelfEval["self_evaluation.verifier_evaluation"]
EvidenceGuard 不调用模型。它校验 Draft schema、analysis ID、当前 Run Tool ownership、READY 状态、evidence status 和每条结论的引用闭包,并生成只包含 Agent projection 的 verified snapshot。
Invocation --> AiOpsRule["AiOpsRuleEvaluationService"]
AiOpsRule --> AiOpsEval["self_evaluation.aiops_rule_evaluation"]
## 4. SemanticGuard
Run --> TraceAPI["DiagnosisTraceService"]
Step --> TraceAPI
Invocation --> TraceAPI
SelfEval --> TraceAPI
AiOpsEval --> TraceAPI
SemanticGuard 使用隔离的单轮模型调用,只接收原始 query、完整 Draft 和 verified snapshot。它无 Tool、无记忆、不访问 Redis、不改写报告;技术失败最多按相同输入重试一次,仍失败则安全降级。
TraceAPI --> Eval["diagnosis eval / RAG eval"]
```
## 5. Release Policy
## 3. Prompt Contract
- `SUPPORTED`:发布 Diagnosis Agent 原始安全 Draft 的 typed report。
- `UNSUPPORTED` 或 evidence failure:发布固定 SAFE_FALLBACK。
- technical failure:发布 stable failure,不泄漏内部异常。
- cancel/timeout:结束 exact Run,禁止 late content。
当前 Prompt 按角色拆分:
## 6. Audit 安全
| Prompt | 用途 |
|---|---|
| `supervisor-prompt.md` | AIOps Supervisor 调度 Planner / Executor |
| `planner-prompt.md` | AIOps Planner 规划、再规划、输出告警报告 |
| `executor-prompt.md` | AIOps Executor 按步骤调用工具 |
| `chat-planner-prompt.md` | Chat 复杂问题规划 |
| `chat-executor-prompt.md` | Chat 执行工具并输出 `executor_evidence_v2` 微观事实 |
| `chat-verifier-prompt.md` | 基于 Gatekeeper 已验真的证据判断 claims 是否可推出 |
| `chat-composer-prompt.md` | 基于 Verifier 允许表达的内容生成最终用户答复 |
Prompt 层当前承担的门禁:
- 禁止凭记忆回答错误码、接口定义、排障步骤。
- 需要外部信息时必须调用工具。
- 工具连续失败或返回空结果时,最终报告必须诚实说明。
- Chat Executor 不允许在窄范围问题中扩展根因、风险或修复建议。
- Chat Verifier 不允许做新检索,只能判断已验真证据是否可推出 claims。
- Chat Composer 不允许补事实,尤其不能把 `$.no_evidence` 表达为“已排除/确认没有”。
- AIOps payload 模式必须聚焦输入告警。
Chat 链路还会在 `verifier_evaluation.prompt_audit` 中持久化紧凑 Prompt 审计快照:
```json
{
"version": "chat-prompts-v1",
"prompts": [
{
"name": "chat_executor",
"version": "chat-executor-v2",
"resource": "prompts/chat-executor-prompt.md"
}
]
}
```
该快照只保存版本和资源路径,不保存完整 Prompt 文本。它用于面试演示、trace 回放和离线 baseline 解释“本次诊断使用了哪套 Prompt 契约”。
## 4. Trace Hooks
`AgentLoggingHook` 是当前 Agent step 可观测性的核心。
```mermaid
sequenceDiagram
autonumber
participant A as Agent
participant H as AgentLoggingHook
participant DB as agent_step
A->>H: before_model(messages, sessionId, runId)
H->>DB: 写入 session_id / run_id / model_input / step_index / agent_name
A-->>A: LLM 推理
A->>H: after_model(messages, sessionId, runId)
H->>DB: 回填 model_output / thought / has_tool_call / duration / token_count
```
记录内容:
- 最近输入消息摘要。
- Agent 输出摘要。
- 是否包含 tool call。
- duration。
- token count。
- Verifier 的 JSON 输出摘要。
新写入必须带 `run_id`;`session_id` 仍保留用于粗粒度排查和历史兼容。
## 5. Tool Invocation 门禁
工具调用记录由 `ToolInvocationRecorder` 和具体工具共同完成。
核心记录:
```text
tool_name
input_params
output_preview
retrieval_layer
l0_match_count
l1_match_count
retrieval_details
-> evidence_refs
relevance_level
dedup_reason
duration_ms
success
error_message
```
对 `lookup_knowledge` 的质量约束:
- L0 只作为 hint,不绕过 L1。
- 检索结果归一化为 `PRECISE`、`HIGHLY_RELEVANT`、`REFERENCE`。
- 同 session 内重复文档会被 `RetrievedDocTracker` 去重。
- dedup、no evidence、failed 等状态进入 `retrieval_details.evidence_status`。
- `retrieval_details.evidence_refs` 记录可被 Executor 引用的最小证据文本,格式为 `raw_path + text`。
- no-hit / no-evidence 工具结果会生成 `raw_path=$.no_evidence` 的负向证据引用,语义仅限“本次查询未检索到匹配证据”。
## 6. Gatekeeper 与 Verifier 门禁
Chat Verifier 前置一层 Gatekeeper。Gatekeeper 不调用 LLM,只用代码检查 Executor 输出的证据引用是否真实存在。
```mermaid
flowchart LR
Invocation["tool_invocation"] --> EvidenceRefs["retrieval_details.evidence_refs"]
ExecutorOutput["executor_evidence_v2"] --> Gatekeeper["ExecutorGatekeeperService"]
EvidenceRefs --> Gatekeeper
Gatekeeper --> GateResult["gatekeeper_result"]
Invocation --> Summary["ToolTraceSummaryService"]
Summary --> EvidenceIndex["tool_trace_summary"]
GateResult --> Verifier["chat_verifier"]
ExecutorOutput --> Verifier
EvidenceIndex --> Verifier
Verifier --> Verdict{"verdict"}
Verdict -->|PASS| Composer["chat_composer"]
Composer --> Pass["输出最终答复"]
Verdict -->|LOW_CONFID| Low["补证据或低置信输出"]
Verdict -->|REJECT| Reject["降级输出"]
```
Gatekeeper 检查:
| 检查 | 失败语义 |
|---|---|
| `answer_version=executor_evidence_v2` | 非结构化或旧结构输出降为低置信 |
| `source_invocation_id` 真实存在 | 伪造 ID 直接拒绝 |
| `tool_name` 与 invocation 对齐 | 张冠李戴直接拒绝 |
| `raw_path` 存在于 `evidence_refs` | 无中生有直接拒绝 |
| `evidence_excerpt` 由 `evidence_refs[].text` 支撑 | excerpt 编造或错配直接拒绝 |
| `negative_observation` 只能引用 `$.no_evidence` | 用正向日志证明“没查到”直接拒绝 |
Gatekeeper 审计还会记录 `rule_set_version` 和已启用规则元数据摘要。当前规则元数据来自本地 `gatekeeper-rules.json`,规则执行仍是确定性 Java 代码。
Verifier 输出:
```json
{
"verdict": "PASS|LOW_CONFID|REJECT",
"groundedness_score": 0.8,
"critical_fact_count": 2,
"claim_checks": [],
"facts_checked": [],
"rationale": "..."
}
```
Verifier 不再逐字核验 excerpt 真伪;这由 Gatekeeper 完成。Verifier 只回答一个问题:`claim_text` 是否能由已经验真的 `evidence_excerpt` 推导出来。
结果写入:
```text
diagnosis_run.self_evaluation.verifier_evaluation
```
其中同时持久化 `executor_structured_output`、`gatekeeper_result`、`tool_trace_summary`、`prompt_audit` 和 `composer_output`,用于 Trace 回放。
## 7. AIOps 规则门禁
AIOps 当前不走 Chat Verifier,而是用 `AiOpsRuleEvaluationService` 做轻量检查。
检查重点:
- 最终报告是否存在。
- payload 模式是否围绕输入告警展开。
- 是否调用证据工具,尤其是 `lookup_knowledge`、日志、指标。
- 是否把无关活跃告警扩展成主诊断对象。
结果写入:
```text
diagnosis_run.self_evaluation.aiops_rule_evaluation
```
## 8. Eval Baseline
当前质量门禁还包括离线评测资产:
| 评测 | 位置 | 作用 |
|---|---|---|
| Diagnosis eval | `mvp/eval/` | 检查诊断 trace、报告和证据行为 |
| RAG retrieval eval | `eval/rag-retrieval/` | 检查固定检索 query 的召回稳定性 |
| Live RAG acceptance | `scripts/eval_rag_live_acceptance.py` | 检查运行环境中真实 `/api/search/similar` 行为 |
## 9. 后续门禁规划
从旧版设计继承但尚未完整实现的门禁:
- 工具参数 schema 校验。
- 同一工具调用次数上限。
- 工具超时的统一熔断。
- Gatekeeper 规则远程化或三层分离:索引层、元数据层、规则实现层。
- Prompt 版本回滚和更细粒度变更审计。
- Verifier 对 AIOps 报告的 LLM 级事实校验。
这些应在评测集扩大后逐步加入,避免一次性把诊断流程卡得过死。
AgentStep 不保存 Prompt、消息正文、模型正文、Tool arguments 或 Thought。ToolInvocation 不保存完整 request、SQL/日志 query、raw response 或 Agent projection。应用日志不得打印这些字段。
+25 -146
View File
@@ -1,160 +1,39 @@
# 会话与 Trace 生命周期
# Session、Run 与 Trace 生命周期
**更新日期**:2026-07-10
**更新日期**:2026-07-22
**状态**:当前可运行架构
**参考历史文档**:`archive/2026-07-05-legacy/session-management.md`
## 1. 定位
## 1. Identity
当前 MVP 把“会话态”和“运行态”拆开:
- `sessionId`:多轮对话目录,由客户端传入或应用生成。
- `runId`:一次 Chat 执行,由 Harness 生成并在 SSE metadata 首事件返回。
- 所有 Run、AgentStep、ToolInvocation 和 Trace 查询必须使用同一个 exact ID;禁止用“最新一条”替代。
## 2. 生命周期
```text
chat_session(sessionId)
-> diagnosis_run(runId)
-> agent_step(runId)
-> tool_invocation(runId)
request accepted
-> start RunContext
-> persist diagnosis_run RUNNING
-> metadata(session_id, run_id)
-> route / execute / guard / release
-> SUCCESS | FALLBACK | FAILED | CANCELLED
-> persist terminal state and budget usage
```
- `sessionId` 表示多轮会话目录和 Redis 上下文。
- `runId` 表示一次可回放诊断执行。
- `DiagnosisTraceService` 聚合一个 run 的主记录、步骤和工具调用,形成可回放 Trace。
- `diagnosis_session` 只保留为历史兼容和回滚表。
disconnect、timeout 与 send failure 通过同一个 `ChatRunControl` 请求取消。正常 SSE complete 在 callback 前标记 terminal,避免误取消;late content 被 state machine 拒绝。
## 2. 生命周期总图
## 3. Trace 聚合
```mermaid
flowchart TD
Start["request: chat / ai_ops"] --> Resolve["resolve sessionId"]
Resolve --> Session["ensure chat_session metadata"]
Session --> Run["create diagnosis_run(runId)"]
Run --> Running["run.status = RUNNING"]
`GET /api/diagnosis/{sessionId}/trace?runId={runId}` 聚合:
Running --> Agent["Agent workflow"]
Agent --> Context["execution context(sessionId, runId)"]
Context --> StepHook["AgentLoggingHook"]
StepHook --> Step["agent_step(session_id, run_id)"]
Context --> Tool["Evidence tools"]
Tool --> Invocation["tool_invocation(session_id, run_id)"]
Invocation --> Gatekeeper["Gatekeeper evidence validation"]
- `chat_session` metadata。
- exact `diagnosis_run` 状态、intent、release outcome、安全 answer 与预算。
- `agent_step` metadata-only 模型步骤。
- `tool_invocation` metadata-only Tool durable audit。
Agent --> Final{"workflow result"}
Final -->|success| Success["run.status = SUCCESS, answer saved"]
Final -->|failed| Failed["run.status = FAILED"]
Redis canonical invocation 不是 Trace API 的长期响应内容;它只供当前 Run EvidenceGuard 验真。
Success --> Evaluation["diagnosis_run.self_evaluation merge"]
Failed --> Evaluation
Evaluation --> Trace["GET /api/diagnosis/{sessionId}/trace?runId=..."]
Success --> Feedback["POST /api/feedback(sessionId, runId)"]
Feedback --> Case["useful -> case_library(run_id)"]
```
## 4. PreviousTurn
## 3. ID 规则
| ID | 来源 | 含义 |
|---|---|---|
| `sessionId` | Chat request `Id`、AIOps payload `sessionId`,缺失时由服务生成 | 多轮会话目录和 Redis 上下文 |
| `runId` | 每次有效 Chat/AIOps 执行创建 | 一次诊断运行和 Trace 回放边界 |
设计含义:
- 同一个 `sessionId` 可以贯穿多轮 Chat。
- 每次有效 Chat/AIOps 执行都会创建新的 `runId`。
- Trace 和 Feedback 新客户端应传 `runId`;只传 `sessionId` 时兼容解析 latest run。
- latest run 排序使用 `diagnosis_run.created_at DESC, id DESC`,不使用 `updated_at`。
## 4. 运行状态流转
```mermaid
stateDiagram-v2
[*] --> PENDING
PENDING --> RUNNING: start diagnosis
RUNNING --> SUCCESS: workflow completed
RUNNING --> FAILED: exception / empty state
SUCCESS --> SUCCESS: feedback submitted
FAILED --> FAILED: feedback submitted
```
字段边界:
| 字段 | 所属表 | 含义 |
|---|---|---|
| `status` | `diagnosis_run` | 单次运行执行状态 |
| `answer` | `diagnosis_run` | 本次运行最终报告或答复 |
| `self_evaluation` | `diagnosis_run` | 本次运行系统自评估 JSON |
| `feedback` | `diagnosis_run` | 本次运行用户反馈 |
`feedback` 不修改 `status`。一个执行成功但用户标记 `not_useful` 的 run,仍然应该是 `SUCCESS + feedback=not_useful`。
## 5. agent_step 写入
`AgentLoggingHook` 在模型调用前后写入和回填 `agent_step`。
```mermaid
sequenceDiagram
autonumber
participant Agent as Agent
participant Hook as AgentLoggingHook
participant DB as agent_step
Agent->>Hook: before_model(messages, sessionId, runId)
Hook->>DB: insert step(session_id, run_id, model_input, step_index)
Agent->>Hook: after_model(output, sessionId, runId)
Hook->>DB: update model_output, duration, token_count, has_tool_call
```
新写入必须带 `run_id`,同时保留 `session_id` 便于粗粒度排查。
## 6. tool_invocation 写入
工具调用记录同样通过执行上下文拿到 `sessionId + runId`:
```text
ToolInvocationRecorder
-> tool_invocation.session_id
-> tool_invocation.run_id
-> retrieval_details / evidence_refs
```
Verifier、Gatekeeper 和 EvaluationService 应按 `run_id` 读取工具调用,避免同一 session 的其他 run 参与评分或证据校验。
## 7. Trace API 聚合
```text
GET /api/diagnosis/{sessionId}/trace
GET /api/diagnosis/{sessionId}/trace?runId=run-...
```
聚合逻辑:
```text
diagnosis_run by sessionId + runId
+ chat_session metadata when available
+ agent_step where run_id = runId, ordered by the Trace API
+ tool_invocation where run_id = runId order by id
-> DiagnosisTraceResponse
```
当 `runId` 缺失时,Trace API 为兼容旧客户端解析最新 run,并在响应中返回 resolved `runId`。当 `runId` 属于其他 `sessionId` 时,API 必须拒绝,不能泄漏其他会话的 Trace。
## 8. Chat 与 AIOps 差异
| 维度 | Chat | AIOps |
|---|---|---|
| `agent_flow` | `CHAT` | `AI_OPS` |
| 编排方式 | `SequentialAgent`: Planner -> Executor -> Gatekeeper -> Verifier -> Composer | `SupervisorAgent`: Planner + Executor |
| 自评估 | `rule_evaluation` + `verifier_evaluation` | `aiops_rule_evaluation` |
| 答案字段 | Chat 最终答复 | 告警分析报告 |
| runId 暴露 | `/api/chat` JSON response | `/api/ai_ops` SSE metadata message |
## 9. 清理与边界
- Redis 会话历史用于多轮上下文,不是长期审计记录。
- MySQL `diagnosis_run + agent_step + tool_invocation` 是主要可回放来源。
- `chat_session.expires_at` 只是目录元数据;Redis 消息历史可独立过期。
- `RetrievedDocTracker` 仍是 session 级运行时去重状态,诊断结束后清理。
## 10. 后续增强
1. Trace API 增加更结构化的 `self_evaluation` 展示。
2. `agent_step` 与 `tool_invocation.step_id` 建立更严格关联。
3. 旧 `diagnosis_session` 只读观察期结束后,再评估数据库层面的约束收紧或归档策略。
应用在创建当前 Run 前读取同 Session 最近安全发布结果。只允许结构化 PublishedResult 的固定字段进入 PreviousTurn,且执行字节上限;完整历史、失败、Fallback、Tool raw data 和 guard reason 均排除。