diff --git a/docs/plans/2026-07-06-001-feat-agent-iq-boost-plan.md b/docs/plans/2026-07-06-001-feat-agent-iq-boost-plan.md new file mode 100644 index 0000000..55089ac --- /dev/null +++ b/docs/plans/2026-07-06-001-feat-agent-iq-boost-plan.md @@ -0,0 +1,502 @@ +--- +date: 2026-07-06 +topic: agent-iq-boost +type: feature +artifact_contract: ce-unified-plan/v1 +artifact_readiness: implementation-ready +product_contract_source: ce-brainstorm +execution: code +origin: "竞品对标(2026-07 Qoder 1.11/Cursor 3.2/Devin 3.0);9 缺口(G1-G9)已交付后的新维度探索" +--- + +## Goal Capsule + +**Objective**: 扩展现有 PLAN_EXEC / TEAM_COLLAB / ReflexionEngine 三个子系统,提升 agent 处理复杂任务的智商 — 独立子任务并行执行、plan 确认后自主执行(仅危险操作确认)、失败后 prompt 跨任务自调优。 + +**Product Authority**: AgentKit 横向评估 14 维度总分 42/56,9 缺口已交付但竞品在"编排+执行深度"维度持续领先(Cursor Subagents 并行、Devin Goal-driven 自主、Qoder 多模型路由)。本 plan 对标竞品补齐这一维度。 + +**Open Blockers**: None — OQ1-3 已在 Planning Contract KTD6-8 决策。 + +**Execution Profile**: Standard depth,7 个 Implementation Units,3 个维度可部分并行(维度 1 与维度 3 独立;维度 2 内部 U1→U2→U3 串行)。 + +**Stop Conditions**: 7 个 U-ID 全部完成、Verification Contract 通过、DoD 全局条件满足。 + +--- + +## Product Contract + +### Summary + +3 个维度并行推进,不新建 ExecutionMode,全部扩展现有基础设施:TeamOrchestrator 新增"无依赖子任务并行"模式解决串行排队;PLAN_EXEC 的"每阶段确认"改为"危险操作确认"解决要人盯;ReflexionEngine 反思结果持久化到 EpisodicMemory 实现跨任务 prompt 自调优。对标 Cursor Agent Mode / Devin Quest Mode / Qoder Goal-driven 的智商能力,保持 AgentKit 现有架构不变。 + +### Problem Frame + +2026-06-29 识别的 9 个智商短板(G1-G9)已全部交付(wave1-4),覆盖反馈稳定性、响应效率、执行能力三个维度。但 2026-07 最新竞品动态显示,竞品在"编排+执行深度"维度持续领先: + +- **Cursor 3.2 Subagents**(2026-04):并行专业化 worker,多 agent 同时工作不同部分 +- **Devin 3.0 Goal-driven**(2026-05):设定目标后自主执行数小时,仅失败时介入 +- **Qoder 1.11 Goal-driven + Scheduling**(2026-06):Goal 设定后工作到完成,可定时启动 + +AgentKit 当前痛点: +- 5 个独立子任务必须串行排队(TeamOrchestrator 同层并行已存在,但"无依赖子任务并行"未实现) +- plan 生成后每阶段需人工确认(PLAN_EXEC 阶段确认机制太保守) +- ReflexionEngine 仅在单次任务内反思,同类错误跨任务重复犯(反思结果未持久化) + +### Key Decisions + +**KTD1: 方案 A — 扩展现有模式,不新建 ExecutionMode** + +3 个维度全部扩展现有 PLAN_EXEC / TEAM_COLLAB / ReflexionEngine,不新建 GOAL_DRIVEN 模式。理由:复用现有基础设施,路由/前端/配置不动,风险低;KTD7(06-29 G6 阶段约束)已验证扩展现有模式可行。 + +**KTD2: 危险操作保守白名单,不引入 LLM 辅助分类** + +自主执行时仅危险操作触发 confirmation_request,白名单包括:文件删除(rm/rmdir)、部署操作(deploy/kubectl/helm)、支付相关、git push --force、数据库迁移(alembic/migrate)。白名单外的操作自主执行。ponytail: ceiling = 漏判风险(未列入白名单的危险操作),升级路径 = LLM 辅助分类。 + +**KTD3: 复用 topological_sort 的同层并行,新增"无依赖子任务并行"模式** + +TeamOrchestrator 已有 topological_sort 返回执行层(Kahn 算法),同层并行已实现。新增"无依赖子任务并行"模式:Lead 分解任务时,若识别到多个无 depends_on 的子任务,自动派发给隔离 agent 并行执行,而非串行排队。不新建 SubAgentOrchestrator 模块(方案 C 排除)。 + +**KTD4: ReflexionEngine 反思结果持久化到 EpisodicMemory** + +失败后 ReflexionEngine 生成反思(已有),新增:反思结果写入 EpisodicMemory(task_input + reflection + improved_prompt),下次类似任务规划时 Lead 检索历史反思,用 improved_prompt 替换默认 prompt。不引入强化学习/元学习(Devin 风格太重),仅做跨任务持久化。 + +**KTD5: Prompt 自调优仅对特定错误类型触发** + +不是每次失败都触发 prompt 调优(避免无意义反思浪费 token)。触发条件:verify 失败(G1 回灌后二次失败)、工具 schema 校验失败(G3)、循环检测触发(U1)。调优后的 prompt 带 version 存入 EpisodicMemory,ABTester 可对比版本效果(离线验证,不在线 bandit)。 + +### Requirements + +**维度 1: 并行 Sub-agent 编排** + +- R1. TeamOrchestrator 的 Lead 分解任务时,识别无 depends_on 的子任务,自动派发给隔离 ConfigDrivenAgent 并行执行。 +- R2. 并行子任务的 SharedWorkspace 输出路径必须不重叠(plan 阶段强制约束:`{plan_id}/phase/{phase_id}/output` 已唯一,并行子任务用不同 phase_id)。 +- R3. 并行子任务全部完成后,Lead 才进入综合阶段(synthesis),与现有 topological_sort 的层间串行一致。 +- R4. 并行子任务数受 MAX_EXPERTS=10 约束(已有),超出时 Lead 重新分解或串行排队。 +- R5. 并行子任务的 expert_step / expert_result 事件携带 expert_id,前端已支持多 expert 同时 streaming(已验证)。 + +**维度 2: Goal-driven 自主执行** + +- R6. PLAN_EXEC 模式下,plan 确认后进入自主执行,不再每阶段 confirmation_request。 +- R7. 自主执行期间,仅危险操作(KTD2 白名单)触发 confirmation_request,其他操作自主执行。 +- R8. 危险操作白名单配置化(`agentkit.yaml` 新增 `dangerous_tools` 配置节,遵循 ServerConfig.from_dict 模式)。 +- R9. 自主执行期间,用户可随时发送 `cancel` 中断(已有 CancellationToken 机制)。 +- R10. 自主执行超时(默认 30 分钟,可配置)或连续失败 3 次时,自动暂停并通知用户。 + +**维度 3: Prompt 跨任务自调优** + +- R11. ReflexionEngine 反思结果写入 EpisodicMemory(task_input + reflection + improved_prompt + version)。 +- R12. PLAN_EXEC / TEAM_COLLAB 的 Lead 规划时,检索 EpisodicMemory 中相似 task_input 的历史反思,用 improved_prompt 替换默认 prompt。 +- R13. Prompt 自调优仅对特定错误类型触发(KTD5):verify 二次失败、工具 schema 校验失败、循环检测触发。 +- R14. 调优后的 prompt 带 version 存入,ABTester 可对比版本效果(离线验证)。 +- R15. EpisodicMemory 中 prompt 反思记录有 TTL(默认 30 天),过期自动清理避免噪声。 + +### Scope Boundaries + +**In scope**: +- 扩展 PLAN_EXEC / TEAM_COLLAB / ReflexionEngine +- 危险操作白名单配置 +- EpisodicMemory prompt 反思持久化 + +**Out of scope**: +- 新建 ExecutionMode.GOAL_DRIVEN(方案 B 排除) +- 独立可组合模块 SubAgentOrchestrator / DangerGate / OnlinePromptOptimizer(方案 C 排除) +- 多模态输入(维度 6,不在"编排+执行深度"范围) +- Cloud Agent 远程执行(维度 8,不在本次范围) +- Repo 深度索引 + Wiki 自动生成(维度 4,不在本次范围) +- 主动澄清意图(维度 1,不在本次范围) +- 强化学习 / 元学习 / bandit 探索(Devin 风格在线学习太重,仅做 ReflexionEngine 跨任务持久化) +- 项目级 Memory Files(CLAUDE.md/AGENTS.md 风格,维度 2,不在本次范围) + +### Outstanding Questions + +All OQ1-3 resolved in Planning Contract (KTD6-KTD8). No outstanding questions remain. + +--- + +## Planning Contract + +### Key Technical Decisions (Planning-Time) + +**KTD6: 并行子任务 depends_on 完全独立约束(解 OQ1)** + +并行子任务的 depends_on 必须完全独立 — 不能共享上游依赖。若 Lead 识别到共享上游依赖,降级为同层并行(topological_sort 已有机制)。此外,关键写入操作用 `SharedWorkspace.lock(key, agent_id, timeout)` 防护(已有 API,`core/shared_workspace.py:96`)。决策依据:phase_id 唯一性已保证输出路径不重叠,但读上游输出时存在 TOCTOU 风险,lock 是最小成本防护。 + +**KTD7: Prompt 版本管理 — 保留所有版本 + score 排序(解 OQ2)** + +EpisodicMemory 保留所有反思版本(key = `prompt_reflection:{task_hash}:{version}`),每条记录携带 `score`(verify 通过=1.0,失败=0.0)+ `timestamp` + `task_input`。Lead 检索时用 `EpisodicMemory.search(task_input, top_k=3)` 语义搜索,按 score 降序取最高版本。TTL 30 天(R15)由 EpisodicMemory 现有清理机制处理。ABTester 离线对比版本效果,不在线 bandit。决策依据:保留所有版本成本低(Redis/PG 存储廉价),且支持回溯;score 排序避免噪声版本干扰。 + +**KTD8: autonomy_paused 事件类型(解 OQ3)** + +新增 `autonomy_paused` WebSocket 事件类型(区别于 `confirmation_request`),前端通过事件类型区分"等待确认"和"自主暂停"。payload 包含 `reason`(timeout | consecutive_failures | manual)+ `progress`(已完成阶段)+ `resume_token`。用户可发送 `resume` 消息继续执行(带 resume_token)。决策依据:复用现有 WebSocket 协议,前端只需新增一个事件分支,不破坏现有 confirmation 流程。 + +### High-Level Technical Design + +```mermaid +flowchart TB + User[User Input] --> Router{RequestPreprocessor} + Router -->|@team| TeamOrchestrator + Router -->|plan_exec| PLAN_EXEC[PLAN_EXEC Handler] + Router -->|react| ReActEngine + + subgraph "维度 1: 并行 Sub-agent" + TeamOrchestrator --> Lead[Lead Expert] + Lead --> Decompose[_decompose_task] + Decompose --> Plan[TeamPlan] + Plan --> TopoSort[topological_sort] + TopoSort -->|同层并行| ParallelExec[_run_pipeline parallel] + ParallelExec --> Agent1[ConfigDrivenAgent 1] + ParallelExec --> Agent2[ConfigDrivenAgent 2] + Agent1 --> SharedWorkspace[(SharedWorkspace)] + Agent2 --> SharedWorkspace + SharedWorkspace -.->|lock 防护| LockMech[lock/unlock] + end + + subgraph "维度 2: Goal-driven 自主" + PLAN_EXEC --> PlanConfirm[Plan Confirmation] + PlanConfirm -->|确认后| AutonomyMode[Autonomy Mode] + AutonomyMode --> ToolExec[Tool Execution] + ToolExec --> DangerCheck{Dangerous?} + DangerCheck -->|是| ConfirmReq[confirmation_request] + DangerCheck -->|否| Continue[Continue] + ConfirmReq --> AutonomyResume[Autonomy Resume] + AutonomyMode -.->|超时/失败| Paused[autonomy_paused] + end + + subgraph "维度 3: Prompt 自调优" + ReActEngine -->|失败| ReflexionEngine + ReflexionEngine --> Reflect[_reflect] + Reflect --> EpisodicMem[(EpisodicMemory)] + EpisodicMem -.->|下次任务| LeadRetrieval[Lead 检索历史反思] + LeadRetrieval --> PromptReplace[替换默认 prompt] + end +``` + +### Assumptions + +- SharedWorkspace.lock() 在 Redis 后端下可靠(已有 SETNX + EXPIRE 实现);InProcess 后端下用 asyncio.Lock 兜底。 +- EpisodicMemory.search() 的语义搜索精度足够检索相似 task_input(pgvector 已有)。 +- 危险操作白名单覆盖 95%+ 真实危险场景;漏判由 KTD2 ponytail ceiling 标注。 +- 前端 WebSocket 已支持自定义事件类型(已验证:`team_synthesis_chunk` 等自定义事件已工作)。 + +### Sequencing + +3 个维度可部分并行: +- **维度 1(U4)** 与 **维度 3(U5-U7)** 完全独立,可并行开发。 +- **维度 2(U1→U2→U3)** 内部串行:配置 → 自主模式 → 超时暂停。 +- **跨维度依赖**:无。维度 1 的并行子任务和维度 2 的自主执行是正交的。 + +--- + +## Implementation Units + +### U1. 危险操作白名单配置 + +**Goal**: 在 `agentkit.yaml` 新增 `dangerous_tools` 配置节,遵循 ServerConfig.from_dict 模式,支持工具名正则匹配。 + +**Requirements**: R8 + +**Dependencies**: None + +**Files**: +- `src/agentkit/server/config.py` — 新增 `DangerousToolsConfig` 类,挂载到 `ServerConfig` +- `configs/agentkit.yaml.example` — 新增 `dangerous_tools` 配置示例 +- `tests/unit/test_server_config.py` — 新增配置解析测试 + +**Approach**: +- 新增 `DangerousToolsConfig` 类(继承 Pydantic BaseModel),字段:`tool_patterns: list[str]`(正则列表)+ `enabled: bool`(默认 true) +- 默认白名单:`rm`, `rmdir`, `deploy`, `kubectl`, `helm`, `git_push_force`, `alembic`, `migrate`, `payment_*` +- `ServerConfig.from_dict` 解析 `dangerous_tools` 段,缺失时用默认白名单 +- 提供 `is_dangerous(tool_name: str) -> bool` 方法,用 `re.match` 检查 + +**Patterns to follow**: `MCPServerConfig` (`server/config.py:23`) 的 from_dict 模式;`CacheConfig` 的嵌套配置模式。 + +**Test scenarios**: +- 配置解析:`dangerous_tools` 段存在时正确解析为 `DangerousToolsConfig` +- 默认值:`dangerous_tools` 段缺失时使用默认白名单 +- 工具匹配:`is_dangerous("rm")` 返回 True,`is_dangerous("read_file")` 返回 False +- 正则匹配:`is_dangerous("payment_charge")` 匹配 `payment_*` 返回 True +- enabled=false 时:`is_dangerous` 始终返回 False(禁用白名单) + +**Verification**: `python3 -m pytest tests/unit/test_server_config.py -x -q` 通过;`ruff check src/agentkit/server/config.py` 无 lint 错误。 + +### U2. PLAN_EXEC 自主执行模式 + 危险操作确认 + +**Goal**: PLAN_EXEC 模式下,plan 确认后进入自主执行,仅危险操作触发 confirmation_request,其他操作自主执行。 + +**Requirements**: R6, R7, R9 + +**Dependencies**: U1 + +**Files**: +- `src/agentkit/core/react.py` — 修改 `confirmation_request` 触发逻辑(行 1255, 2199),增加危险操作检查 +- `src/agentkit/server/routes/chat.py` — PLAN_EXEC 路由处理,注入 `DangerousToolsConfig` +- `tests/unit/test_react_autonomy.py` — 新增自主执行测试 +- `tests/unit/test_plan_exec_autonomy.py` — 新增 PLAN_EXEC 集成测试 + +**Approach**: +- ReActEngine 构造时接收 `dangerous_tools_config: DangerousToolsConfig | None` +- 工具执行前检查:若 `dangerous_tools_config.is_dangerous(tool_name)` 且在 PLAN_EXEC 自主模式 → 触发 `confirmation_request`(已有事件类型) +- 非危险操作 → 直接执行,不触发 confirmation +- PLAN_EXEC 的 plan 确认后,设置 `autonomy_mode: true` 标志(区别于现有"每阶段确认"模式) +- `cancel` 消息已有 CancellationToken 机制(`core/protocol.py`),无需修改 + +**Patterns to follow**: 现有 `confirmation_request` 事件触发模式(`react.py:1255`);`phase_violation` 检测模式(`react.py:272`)。 + +**Test scenarios**: +- 危险操作触发 confirmation:自主模式下执行 `rm` 触发 `confirmation_request` 事件 +- 非危险操作自主执行:自主模式下执行 `read_file` 不触发 confirmation +- 非自主模式行为不变:非 PLAN_EXEC 模式下,confirmation 行为与现有逻辑一致 +- cancel 中断:自主执行中发送 `cancel` 中断任务,CancellationToken 正确取消 +- 危险操作白名单禁用:`enabled=false` 时所有操作自主执行 + +**Verification**: `python3 -m pytest tests/unit/test_react_autonomy.py tests/unit/test_plan_exec_autonomy.py -x -q` 通过;现有 PLAN_EXEC 测试不回归。 + +### U3. 自主执行超时 + autonomy_paused 事件 + +**Goal**: 自主执行超时(默认 30 分钟)或连续失败 3 次时,自动暂停并发送 `autonomy_paused` 事件,用户可 `resume` 继续。 + +**Requirements**: R10 + +**Dependencies**: U2 + +**Files**: +- `src/agentkit/core/react.py` — 新增 `autonomy_paused` 事件类型 + 超时/失败计数逻辑 +- `src/agentkit/server/routes/chat.py` — 处理 `autonomy_paused` 事件 + `resume` 消息 +- `src/agentkit/server/config.py` — 新增 `autonomy_timeout_minutes: int = 30` + `max_consecutive_failures: int = 3` 配置 +- `tests/unit/test_autonomy_paused.py` — 新增暂停/恢复测试 + +**Approach**: +- ReActEngine 新增 `autonomy_started_at: float` + `consecutive_failures: int` 状态 +- 每次工具执行前检查:`time.time() - autonomy_started_at > timeout` 或 `consecutive_failures >= 3` → 触发 `autonomy_paused` +- `autonomy_paused` 事件 payload:`{reason: "timeout"|"consecutive_failures"|"manual", progress: {...}, resume_token: "..."}` +- WebSocket 路由处理 `resume` 消息:重置 `autonomy_started_at` + `consecutive_failures`,继续执行 +- 前端区分:`confirmation_request` = 等待单次确认;`autonomy_paused` = 整体自主执行暂停 + +**Patterns to follow**: 现有 `phase_changed` 事件模式(`chat.py:1694`);`confirmation_result` 处理模式。 + +**Test scenarios**: +- 超时触发暂停:自主执行超过 30 分钟触发 `autonomy_paused`,reason="timeout" +- 连续失败触发暂停:连续 3 次工具失败触发 `autonomy_paused`,reason="consecutive_failures" +- resume 恢复执行:发送 `resume` 消息后,自主执行继续,计数器重置 +- 超时配置化:`autonomy_timeout_minutes=60` 时,30 分钟不触发暂停 +- 非自主模式不触发:非 PLAN_EXEC 模式下,超时/失败不触发 `autonomy_paused` + +**Verification**: `python3 -m pytest tests/unit/test_autonomy_paused.py -x -q` 通过;`autonomy_paused` 事件 payload 符合契约。 + +### U4. TeamOrchestrator 无依赖子任务并行模式 + +**Goal**: TeamOrchestrator 的 Lead 分解任务时,识别无 depends_on 的子任务,自动派发给隔离 ConfigDrivenAgent 并行执行(而非串行排队)。 + +**Requirements**: R1, R2, R3, R4, R5 + +**Dependencies**: None(与 U1-U3 正交) + +**Files**: +- `src/agentkit/experts/orchestrator.py` — 修改 `_run_pipeline`(行 234)支持并行子任务派发 +- `src/agentkit/experts/plan.py` — `TeamPlan` 新增 `get_independent_subtasks()` 方法 +- `tests/unit/test_team_parallel.py` — 新增并行子任务测试 + +**Approach**: +- `TeamPlan.get_independent_subtasks()`: 返回 `depends_on == []` 的 PlanPhase 列表(已有 `depends_on` 字段,`plan.py:176`) +- `_run_pipeline` 修改: + 1. 调用 `topological_sort()` 得到执行层(已有) + 2. 同层内的 phases 已并行执行(已有)— 无需修改 + 3. **新增**:Lead 分解时,若识别到多个无 depends_on 的子任务,显式派发到同层(而非分散到不同层) +- KTD6 约束:若子任务共享上游依赖,降级为同层并行(topological_sort 已处理) +- SharedWorkspace 写入防护:关键写入用 `SharedWorkspace.lock()`(已有,`shared_workspace.py:96`) +- MAX_EXPERTS=10 约束已有(`experts/router.py`),超出时 Lead 重新分解 + +**Patterns to follow**: 现有 `_run_pipeline` 的同层并行模式(`orchestrator.py:234`);`_get_isolated_agent` 的 agent 创建模式(`orchestrator.py:113`)。 + +**Test scenarios**: +- 无依赖子任务并行:3 个无 depends_on 的子任务,同时派发到 3 个隔离 agent +- 共享依赖降级:2 个子任务共享上游依赖,降级为同层并行(不并行派发) +- MAX_EXPERTS 约束:11 个无依赖子任务时,Lead 重新分解为 10 个以内 +- SharedWorkspace 路径不重叠:并行子任务的输出路径 `{plan_id}/phase/{phase_id}/output` 唯一 +- expert_step 事件携带 expert_id:并行执行时事件正确区分不同 expert +- 综合阶段等待:所有并行子任务完成后才进入 synthesis + +**Verification**: `python3 -m pytest tests/unit/test_team_parallel.py -x -q` 通过;现有 TeamOrchestrator 测试不回归。 + +### U5. ReflexionEngine 反思持久化到 EpisodicMemory + +**Goal**: ReflexionEngine 的 `_reflect` 方法生成反思后,将结果写入 EpisodicMemory,支持跨任务检索。 + +**Requirements**: R11, R15 + +**Dependencies**: None(与 U1-U4 正交) + +**Files**: +- `src/agentkit/core/reflexion.py` — 修改 `_reflect`(行 648),新增持久化逻辑 +- `src/agentkit/memory/episodic.py` — 新增 `store_prompt_reflection()` + `search_prompt_reflections()` 方法 +- `tests/unit/test_reflexion_persist.py` — 新增持久化测试 + +**Approach**: +- `_reflect` 返回前,调用 `EpisodicMemory.store_prompt_reflection(task_input, reflection, improved_prompt, version, score)` +- 存储格式:`key = "prompt_reflection:{task_hash}:{version}"`,`value = {task_input, reflection, improved_prompt, score, timestamp}` +- KTD7 决策:保留所有版本,score 字段记录效果(verify 通过=1.0,失败=0.0) +- R15 TTL:复用 EpisodicMemory 现有清理机制(若无可加 `cleanup_expired()` 方法,30 天阈值) +- `_build_reflection_prompt`(行 693)已生成 improved_prompt,直接存储 + +**Patterns to follow**: `EpisodicMemory.store()` 现有模式(`episodic.py:66`);`EpisodicMemory.search()` 语义搜索模式(`episodic.py:206`)。 + +**Test scenarios**: +- 反思持久化:`_reflect` 返回后,EpisodicMemory 中存在对应记录 +- 存储字段完整:记录包含 task_input + reflection + improved_prompt + version + score + timestamp +- TTL 清理:30 天前的记录被 `cleanup_expired()` 清理 +- 多版本共存:同一 task_hash 的多个版本都保留,version 递增 +- 持久化失败不阻塞:EpisodicMemory 写入失败时,`_reflect` 仍返回反思文本(降级处理) + +**Verification**: `python3 -m pytest tests/unit/test_reflexion_persist.py -x -q` 通过;现有 ReflexionEngine 测试不回归。 + +### U6. Lead 规划时检索历史反思 + prompt 替换 + +**Goal**: PLAN_EXEC / TEAM_COLLAB 的 Lead 规划时,检索 EpisodicMemory 中相似 task_input 的历史反思,用 improved_prompt 替换默认 prompt。 + +**Requirements**: R12, R13 + +**Dependencies**: U5 + +**Files**: +- `src/agentkit/experts/orchestrator.py` — `_decompose_task`(行 534)前新增反思检索 +- `src/agentkit/core/reflexion.py` — 新增 `retrieve_prompt_reflection(task_input) -> dict | None` +- `tests/unit/test_lead_reflection_retrieval.py` — 新增检索 + 替换测试 + +**Approach**: +- `_decompose_task` 前,调用 `ReflexionEngine.retrieve_prompt_reflection(task_input)` +- 检索逻辑:`EpisodicMemory.search_prompt_reflections(task_input, top_k=3)` → 按 score 降序取最高 +- 若找到 improved_prompt(score > 0.5),替换 Lead 的默认 system prompt +- KTD5 触发条件:仅在 verify 二次失败 / schema 校验失败 / 循环检测时才触发反思(避免无意义检索) +- 无历史反思时:用默认 prompt(现有行为不变) + +**Patterns to follow**: `_decompose_task` 现有模式(`orchestrator.py:534`);`_build_reflection_prompt` 的 prompt 拼接模式(`reflexion.py:693`)。 + +**Test scenarios**: +- 历史反思命中:EpisodicMemory 有相似 task_input 记录,Lead 用 improved_prompt +- 历史反思未命中:无相似记录,Lead 用默认 prompt(行为不变) +- score 过滤:score <= 0.5 的反思不替换(避免低质量反思污染) +- KTD5 触发条件:非触发错误类型(如普通 timeout)不检索历史反思 +- 检索失败降级:EpisodicMemory 检索失败时,Lead 用默认 prompt + +**Verification**: `python3 -m pytest tests/unit/test_lead_reflection_retrieval.py -x -q` 通过;现有 TeamOrchestrator 测试不回归。 + +### U7. ABTester 离线对比 prompt 版本 + +**Goal**: ABTester 支持对比 EpisodicMemory 中同一 task_hash 的多个 prompt 版本效果,离线验证(不在线 bandit)。 + +**Requirements**: R14 + +**Dependencies**: U5 + +**Files**: +- `src/agentkit/evolution/ab_tester.py` — 新增 `compare_prompt_versions(task_hash) -> dict` 方法 +- `tests/unit/test_ab_tester_prompt.py` — 新增版本对比测试 + +**Approach**: +- `compare_prompt_versions(task_hash)`: 检索 EpisodicMemory 中该 task_hash 的所有版本 +- 输出:`{versions: [{version, score, timestamp, reflection_summary}], best_version, recommendation}` +- 离线验证:不在线 bandit,仅基于历史 score 对比 +- `recommendation` 字段:建议保留 score 最高的版本,清理低分版本(可选) + +**Patterns to follow**: 现有 ABTester 的对比模式(`evolution/ab_tester.py`)。 + +**Test scenarios**: +- 多版本对比:3 个版本(score: 0.8, 0.6, 0.4),recommendation 选 0.8 版本 +- 无版本时:返回空结果,不报错 +- 单版本时:直接返回该版本为 best_version +- 低分版本清理:可选清理 score < 0.3 的版本(保留 top-K) + +**Verification**: `python3 -m pytest tests/unit/test_ab_tester_prompt.py -x -q` 通过。 + +--- + +## Verification Contract + +### Unit Tests + +```bash +# 全量单元测试(必须通过) +python3 -m pytest tests/unit/ -x -q + +# 本次新增测试(逐个验证) +python3 -m pytest tests/unit/test_server_config.py tests/unit/test_react_autonomy.py tests/unit/test_plan_exec_autonomy.py tests/unit/test_autonomy_paused.py tests/unit/test_team_parallel.py tests/unit/test_reflexion_persist.py tests/unit/test_lead_reflection_retrieval.py tests/unit/test_ab_tester_prompt.py -x -q +``` + +### Lint + Format + +```bash +# Ruff lint + format(必须通过) +ruff check src/ && ruff format src/ +``` + +### Integration Tests (Optional) + +```bash +# 集成测试(需 Docker Redis + PostgreSQL,可选) +python3 -m pytest -m "integration" -x -q +``` + +### Quality Gates + +- 无 `any` 类型(AGENTS.md 约束) +- 所有 Pydantic 模型用 `model_config = ConfigDict(...)`(AGENTS.md 约束) +- API Key 比较用 `hmac.compare_digest`(若涉及) +- 异步生成器安全(`.trae/rules/project_rules.md`) +- 无 `return` 在第一个 `yield` 之前(若新增 async generator) + +--- + +## Definition of Done + +### Global Criteria + +- 7 个 Implementation Units (U1-U7) 全部完成 +- 所有新增测试通过(8 个测试文件) +- 现有测试不回归(`tests/unit/` 全量通过) +- `ruff check src/ && ruff format src/` 无错误 +- 无 `any` 类型,Pydantic 模型用 `ConfigDict` +- 异步生成器安全(无 early return before yield) + +### Per-Unit Criteria + +| Unit | Done Signal | +|------|-------------| +| U1 | `DangerousToolsConfig` 解析正确,`is_dangerous()` 工作正常 | +| U2 | PLAN_EXEC 自主模式下危险操作触发 confirmation,非危险操作自主执行 | +| U3 | 超时/连续失败触发 `autonomy_paused`,`resume` 恢复执行 | +| U4 | 无依赖子任务并行派发,SharedWorkspace 路径不重叠 | +| U5 | `_reflect` 后 EpisodicMemory 有记录,TTL 清理工作 | +| U6 | Lead 检索历史反思并替换 prompt(score > 0.5 时) | +| U7 | ABTester 对比多版本 prompt,返回 best_version | + +### Cleanup Criteria + +- 移除调试代码(print、TODO 注释、临时 hack) +- 移除未使用的 import +- 移除实验性死代码(尝试过但未采用的方案) +- 所有新增配置项有文档(`agentkit.yaml.example` 示例) + +--- + +## Appendix: 竞品对标参考 + +| 维度 | 竞品代表 | AgentKit 本次目标 | +|------|----------|-------------------| +| 并行 Sub-agent | Cursor 3.2 Subagents(并行专业化 worker)| R1-R5: TeamOrchestrator 无依赖子任务并行 | +| Goal-driven 自主 | Devin 3.0 Goal-driven(数小时自主)、Qoder 1.11 Goal + Scheduling | R6-R10: PLAN_EXEC 危险操作确认式自主 | +| Prompt 自调优 | Devin 强化学习+元学习、ReflexionEngine 跨任务 | R11-R15: ReflexionEngine 反思持久化到 EpisodicMemory | + +## Appendix: 关键代码位置参考 + +| 子系统 | 文件 | 关键位置 | +|--------|------|----------| +| TeamOrchestrator | `src/agentkit/experts/orchestrator.py` | `execute()` 行 143, `_run_pipeline` 行 234, `_decompose_task` 行 534 | +| TeamPlan | `src/agentkit/experts/plan.py` | `topological_sort()` 行 385, `SubTask` 行 69, `PlanPhase.depends_on` 行 176 | +| ReflexionEngine | `src/agentkit/core/reflexion.py` | `_reflect()` 行 648, `_build_reflection_prompt` 行 693 | +| EpisodicMemory | `src/agentkit/memory/episodic.py` | `store()` 行 66, `search()` 行 206 | +| SharedWorkspace | `src/agentkit/core/shared_workspace.py` | `lock()` 行 96, `write()` 行 39 | +| ReActEngine | `src/agentkit/core/react.py` | `confirmation_request` 行 1255/2199, `phase_violation` 行 272 | +| PLAN_EXEC 路由 | `src/agentkit/chat/skill_routing.py` | `ExecutionMode.PLAN_EXEC` 行 33 | +| WebSocket 事件 | `src/agentkit/server/routes/chat.py` | `confirmation_request` 行 1646, `phase_changed` 行 1701 | +| ServerConfig | `src/agentkit/server/config.py` | `from_dict` 行 200, `MCPServerConfig` 行 23 | +| CancellationToken | `src/agentkit/core/protocol.py` | 类定义 |