From 9a313e3c92cfc75e5066f6186a19301566b61e42 Mon Sep 17 00:00:00 2001 From: iven Date: Thu, 23 Apr 2026 23:45:28 +0800 Subject: [PATCH] =?UTF-8?q?docs(wiki):=20=E5=9B=9E=E5=A4=8D=E6=95=88?= =?UTF-8?q?=E7=8E=87+=E5=BB=BA=E8=AE=AE=E5=B9=B6=E8=A1=8C=E5=8C=96?= =?UTF-8?q?=E4=BC=98=E5=8C=96=20wiki=20=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - middleware.md: 分波并行执行设计决策 + parallel_safe 标注 + 不变量 + 执行流 - chat.md: suggestion prefetch + 解耦 memory + prompt 重写 - log.md: 追加变更记录 - CLAUDE.md: §13 架构快照 + 最近变更 --- CLAUDE.md | 178 ++++++++++++++++++++++++++++++++++----------- wiki/chat.md | 30 ++++++-- wiki/log.md | 8 ++ wiki/middleware.md | 46 +++++++----- 4 files changed, 196 insertions(+), 66 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index cf7c6b7..a9cbb97 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -165,10 +165,25 @@ desktop/src-tauri (→ kernel, skills, hands, protocols) 2. **自动验证** — `cargo check` / `cargo test` / `tsc --noEmit` / `vitest run` 必须通过 3. **回归测试** — 跑受影响 crate 的全量测试,确认无回归 -#### 阶段 4: 提交 + 同步(立即,不积压) +#### 阶段 4: Wiki 同步 + 提交(立即,不积压) -1. **提交推送** — 按 §11 规范提交,**立即 `git push`** -2. **文档同步** — 按 §8.3 检查并更新相关文档,提交并推送 +**Wiki 同步评估(硬门槛,不可跳过)** + +代码改完后、提交前,逐条回答以下问题。任何一条为"是"→ 必须更新对应 wiki 页面: + +| 评估问题 | 为"是"时更新 | +|----------|-------------| +| 这个改动修复或引入了 bug? | 对应模块页"活跃问题+陷阱"节 + `wiki/known-issues.md` | +| 这个改动改变了某个模块的行为或设计理由? | 对应模块页"设计决策"节 | +| 这个改动增删了文件或改变了目录结构? | 对应模块页"关键文件"表 | +| 这个改动影响了跨模块接口(谁调谁、参数形状、触发时机)? | 涉及双方的"集成契约"表 | +| 这个改动涉及一个必须始终成立的约束? | 对应模块页"代码逻辑"节的 ⚡ 不变量 | +| 这个改动改变了功能链路(前端→后端的完整路径)? | `wiki/feature-map.md` 索引表 | +| 这个改动改变了关键数字(命令数/Store数/测试数等)? | `wiki/index.md` 关键数字表 + `docs/TRUTH.md` | + +全部回答完后,无论是否有更新,都追加一条到 `wiki/log.md` + 更新模块页"变更记录"节(保持 5 条)。 + +**提交推送** — 按 §11 规范提交,**立即 `git push`**。详细文档同步规则见 §8.3。 **铁律:不允许"等一下再提交"或"最后一起推送"。每个独立工作单元完成后立即推送。** @@ -374,34 +389,44 @@ docs/ 每次完成功能实现、架构变更、问题修复后,**必须立即执行以下收尾**: -#### 步骤 A:文档同步(代码提交前) +#### 步骤 A:Wiki 同步(最高优先,代码提交前) -检查以下文档是否需要更新,有变更则立即修改: +> **为什么 wiki 排第一**:wiki 是新 AI 会话的启动燃料。如果 wiki 与代码不一致,后续所有会话都会基于错误上下文工作,错误会积累放大。 + +在 §3.3 阶段 4 的评估表基础上,执行具体更新: + +| 触发事件 | 更新目标 | 更新内容 | +|----------|---------|---------| +| 修复 bug | 对应模块页"活跃问题+陷阱" | 修复→移除条目;新增→添加条目 | +| 架构/设计变更 | 对应模块页"设计决策" | WHY 变了 + 新的权衡取舍 | +| 文件增删/移动 | 对应模块页"关键文件"表 | 更新文件列表 | +| 跨模块接口变化 | **涉及双方**的"集成契约"表 | 方向/接口/触发时机 | +| 发现新的不变量 | 对应模块页"代码逻辑"节 | ⚡ 标记 + 一句话描述 | +| 功能链路变化 | `wiki/feature-map.md` | 更新索引表对应行 | +| 关键数字变化 | `wiki/index.md` + `docs/TRUTH.md` | 更新数字 + 验证命令 | +| **每次收尾** | `wiki/log.md` + 模块页"变更记录" | 追加日志条目 + 变更记录保持 5 条 | + +**wiki 更新原则**: +- 只记录代码不能告诉你的东西(WHY、跨模块关系、不变量、历史教训) +- 模块页控制在 100-200 行,超出则归档到 `wiki/archive/` +- 同一信息只出现在一个页面(单一真相源),其他页面只引用 + +#### 步骤 B:其他文档同步 1. **CLAUDE.md** — 项目结构、技术栈、工作流程、命令变化时 -2. **CLAUDE.md §13 架构快照** — 涉及子系统变更时,更新 `` 标记区域(可执行 `/sync-arch` 技能自动分析) +2. **CLAUDE.md §13 架构快照** — 涉及子系统变更时(可执行 `/sync-arch` 技能自动分析) 3. **docs/ARCHITECTURE_BRIEF.md** — 架构决策或关键组件变更时 4. **docs/features/** — 功能状态变化时 5. **docs/knowledge-base/** — 新的排查经验或配置说明 -6. **wiki/** — 编译后知识库维护(按触发规则更新对应页面,每页统一 5 节: 设计决策 / 关键文件+集成契约 / 代码逻辑 / 活跃问题+陷阱 / 变更记录): - - 修复 bug → 更新对应模块页"活跃问题"节 + `wiki/known-issues.md` 索引 - - 架构变更 → 更新对应模块页"设计决策"节 - - 文件结构变化 → 更新对应模块页"关键文件"表 - - 跨模块接口变化 → 更新对应模块页"集成契约"表 - - 新增不变量发现 → 更新对应模块页"代码逻辑"节的 ⚡ 标记项 - - 功能链路变化 → 更新 `wiki/feature-map.md` 索引表 - - 数字变化 → 更新 `wiki/index.md` 关键数字表 + `docs/TRUTH.md` - - 每次更新 → 在 `wiki/log.md` 追加一条记录 + 模块页"变更记录"节更新最近 5 条 -6. **docs/TRUTH.md** — 数字(命令数、Store 数、crates 数等)变化时 -#### 步骤 B:提交(按逻辑分组) +#### 步骤 C:提交(按逻辑分组) ``` 代码变更 → 一个或多个逻辑提交 文档变更 → 独立提交(如果和代码分开更清晰) ``` -#### 步骤 C:推送(立即) +#### 步骤 D:推送(立即) ``` git push @@ -559,7 +584,7 @@ refactor(store): 统一 Store 数据获取方式 *** - + ## 13. 当前架构快照 @@ -567,51 +592,53 @@ refactor(store): 统一 Store 数据获取方式 | 子系统 | 状态 | 最新变更 | |--------|------|----------| -| 管家模式 (Butler) | ✅ 活跃 | 04-12 行业配置4行业 + 跨会话连续性 + XML fencing | -| Hermes 管线 | ✅ 活跃 | 04-12 触发信号持久化 + 经验行业维度 + 注入格式优化 | +| 管家模式 (Butler) | ✅ 活跃 | 04-23 跨会话身份(soul.md) + 动态建议(4路并行LLM驱动) + Agent tab 移除 | +| Hermes 管线 | ✅ 活跃 | 04-23 experience_find_relevant Tauri 命令 + ExperienceBrief + OnceLock 单例 | | Intelligence Heartbeat | ✅ 活跃 | 04-15 统一健康快照 (health_snapshot.rs) + HeartbeatManager 重构 + HealthPanel 前端 | -| 聊天流 (ChatStream) | ✅ 稳定 | 04-02 ChatStore 拆分为 4 Store (stream/conversation/message/chat) | -| 记忆管道 (Memory) | ✅ 稳定 | 04-17 E2E 验证: 存储+FTS5+TF-IDF+注入闭环,去重+跨会话注入已修复 | +| 聊天流 (ChatStream) | ✅ 活跃 | 04-23 LLM 动态建议(替换硬编码) + 澄清卡片 UX 优化 | +| 记忆管道 (Memory) | ✅ 活跃 | 04-23 身份信号提取(agent_name/user_name) + ProfileSignals 增强 | | SaaS 认证 (Auth) | ✅ 稳定 | Token池 RPM/TPM 轮换 + JWT password_version 失效机制 | -| Pipeline DSL | ✅ 稳定 | 04-01 17 个 YAML 模板 + DAG 执行器 | -| Hands 系统 | ✅ 稳定 | 7 注册 (6 HAND.toml + _reminder),Whiteboard/Slideshow/Speech 开发中 | +| Pipeline DSL | ✅ 稳定 | 04-01 18 个 YAML 模板 + DAG 执行器 | +| Hands 系统 | ✅ 稳定 | 7 注册 (6 HAND.toml + _reminder),Whiteboard/Slideshow/Speech 已删除 | | 技能系统 (Skills) | ✅ 稳定 | 75 个 SKILL.md + 语义路由 | -| 中间件链 | ✅ 稳定 | 13 层 (ButlerRouter@80, Compaction@100, Memory@150, Title@180, SkillIndex@200, DanglingTool@300, ToolError@350, ToolOutputGuard@360, Guardrail@400, LoopGuard@500, SubagentLimit@550, TrajectoryRecorder@650, TokenCalibration@700) | +| 中间件链 | ✅ 稳定 | 14 层 + 分波并行 (Evolution@78✅, ButlerRouter@80✅, Compaction@100, Memory@150✅, Title@180✅, SkillIndex@200✅, DanglingTool@300, ToolError@350, ToolOutputGuard@360, Guardrail@400, LoopGuard@500, SubagentLimit@550, TrajectoryRecorder@650, TokenCalibration@700) — ✅=parallel_safe | ### 关键架构模式 - **Hermes 管线**: 4模块闭环 — ExperienceStore(FTS5经验存取) + UserProfiler(结构化用户画像) + NlScheduleParser(中文时间→cron) + TrajectoryRecorder+Compressor(轨迹记录压缩)。通过中间件链+intelligence hooks调用 -- **管家模式**: 双模式UI (默认简洁/解锁专业) + ButlerRouter 动态行业关键词(4内置+自定义) + XML fencing注入 + 跨会话连续性(痛点回访+经验检索) + 触发信号持久化(VikingStorage) + 冷启动4阶段hook -- **聊天流**: 3种实现 → GatewayClient(WebSocket) / KernelClient(Tauri Event) / SaaSRelay(SSE) + 5min超时守护。详见 [ARCHITECTURE_BRIEF.md](docs/ARCHITECTURE_BRIEF.md) +- **管家模式**: 双模式UI (默认简洁/解锁专业) + ButlerRouter 动态行业关键词(4内置+自定义) + XML fencing注入 + 跨会话连续性(痛点回访+经验检索) + 触发信号持久化(VikingStorage) + 冷启动4阶段hook + 跨会话身份(soul.md) + 动态建议(4路并行LLM驱动2续问+1关怀) +- **聊天流**: 3种实现 → GatewayClient(WebSocket) / KernelClient(Tauri Event) / SaaSRelay(SSE) + 5min超时守护。动态建议: prefetch context + generateLLMSuggestions(1追问+1行动+1关怀) 与 memory extraction 解耦。详见 [ARCHITECTURE_BRIEF.md](docs/ARCHITECTURE_BRIEF.md) - **客户端路由**: `getClient()` 4分支决策树 → Admin路由 / SaaS Relay(可降级到本地) / Local Kernel / External Gateway - **SaaS 认证**: JWT→OS keyring 存储 + HttpOnly cookie + Token池 RPM/TPM 限流轮换 + SaaS unreachable 自动降级 -- **记忆闭环**: 对话→extraction_adapter→FTS5全文+TF-IDF权重→检索→注入系统提示(E2E 04-17 验证通过,去重+跨会话注入已修复) +- **记忆闭环**: 对话→extraction_adapter→FTS5全文+TF-IDF权重→检索→注入系统提示 + 身份信号提取(agent_name/user_name)→VikingStorage→soul.md→跨会话名字记忆 - **LLM 驱动**: 4 Rust Driver (Anthropic/OpenAI/Gemini/Local) + 国内兼容 (DeepSeek/Qwen/Moonshot 通过 base_url) ### 最近变更 -1. [04-21] Embedding 接通 + 自学习自动化 A线+B线: 记忆检索Embedding(GrowthIntegration→MemoryRetriever→SemanticScorer) + Skill路由Embedding+LLM Fallback(替换new_tf_idf_only) + evolution_bridge(SkillCandidate→SkillManifest) + generate_and_register_skill()全链路 + EvolutionMiddleware双模式(auto/suggest) + QualityGate加固(长度/标题/置信度上限)。验证: 934 tests PASS -2. [04-21] Phase 0+1 突破之路 8 项基础链路修复: 经验积累覆盖修复(reuse_count累积) + Skill工具调用桥接(complete_with_tools) + Hand字段映射(runId) + Heartbeat痛点感知 + Browser委托消息 + 跨会话检索增强(IdentityRecall 26→43模式+弱身份fallback) + Twitter凭据持久化。验证: 912 tests PASS -2. [04-17] 全系统 E2E 测试 129 链路: 82 PASS / 20 PARTIAL / 1 FAIL / 26 SKIP,有效通过率 79.1%。7 项 Bug 修复 (Dashboard 404/记忆去重/记忆注入/invoice_id/Prompt版本/agent隔离/行业字段) -2. [04-16] 3 项 P0 修复 + 5 项 E2E Bug 修复 + Agent 面板刷新 + TRUTH.md 数字校准 -3. [04-15] Heartbeat 统一健康系统: health_snapshot.rs 统一收集器(LLM连接/记忆/会话/系统资源) + heartbeat.rs HeartbeatManager 重构 + HealthPanel.tsx 前端面板 + Tauri 命令 182→183 + intelligence 模块 15→16 文件 + 删除 intelligence-client/ 9 废弃文件 -4. [04-12] 行业配置+管家主动性 全栈 5 Phase: 行业数据模型+4内置配置+ButlerRouter动态关键词+触发信号+Tauri加载+Admin管理页面+跨会话连续性+XML fencing注入格式 -5. [04-09] Hermes Intelligence Pipeline 4 Chunk: ExperienceStore+Extractor, UserProfileStore+Profiler, NlScheduleParser, TrajectoryRecorder+Compressor (684 tests, 0 failed) -6. [04-09] 管家模式6交付物完成: ButlerRouter + 冷启动 + 简洁模式UI + 桥测试 + 发布文档 +1. [04-23] 回复效率+建议生成并行化: identity prompt 缓存 + pre-hook 并行(tokio::join!) + middleware 分波并行(parallel_safe, 5层✅) + suggestion context 预取 + 建议与 memory 解耦 + prompt 重写(1追问+1行动+1关怀) +2. [04-23] 动态建议智能化: fetchSuggestionContext 4路并行(用户画像/痛点/经验/技能匹配) + generateLLMSuggestions 混合型 prompt (2续问+1管家关怀) + experience_find_relevant Tauri 命令 + ExperienceBrief +3. [04-23] 跨会话身份: detectAgentNameSuggestion trigger+extract 两步法(10 trigger) + ProfileSignals agent_name/user_name + soul.md 写回 + Agent tab 移除 (~280 行 dead code 清理) +4. [04-22] Wiki 全面重构: 5节模板+集成契约+症状导航+归档压缩,净减 ~1,200 行 +4. [04-22] 跨会话记忆断裂修复 + DataMasking 中间件移除 + 搜索功能修复(多引擎+质量过滤+SSE行缓冲) +5. [04-21] Embedding 接通 + 自学习自动化 A线+B线 + Phase 0+1 突破之路 8 项链路修复。验证: 934 tests PASS +6. [04-20] 50 轮功能链路审计 7 项断链修复 (42/50 = 84% 通过率) +7. [04-17] 全系统 E2E 测试 129 链路: 82 PASS / 20 PARTIAL / 1 FAIL / 26 SKIP,有效通过率 79.1% + + - + ## 14. AI 协作注意事项 ### 反模式警告 -- ❌ **不要**建议新增 SaaS API 端点 — 已有 140 个,稳定化约束禁止新增 +- ❌ **不要**建议新增 SaaS API 端点 — 已有 137 个,稳定化约束禁止新增 - ❌ **不要**忽略管家模式 — 已上线且为默认模式,所有聊天经过 ButlerRouter - ❌ **不要**假设 Tauri 直连 LLM — 实际通过 SaaS Token 池中转,SaaS unreachable 时降级到本地 Kernel -- ❌ **不要**建议从零实现已有能力 — 先查 Hand(9个)/Skill(75个)/Pipeline(17模板) 现有库 +- ❌ **不要**建议从零实现已有能力 — 先查 Hand(7注册)/Skill(75个)/Pipeline(18模板) 现有库 - ❌ **不要**在 CLAUDE.md 以外创建项目级配置或规则文件 — 单一入口原则 ### 场景化指令 @@ -620,6 +647,75 @@ refactor(store): 统一 Store 数据获取方式 - 当遇到**认证相关** → 记住 Tauri 模式用 OS keyring 存 JWT,SaaS 模式用 HttpOnly cookie - 当遇到**新功能建议** → 先查 [TRUTH.md](docs/TRUTH.md) 确认可用能力清单,避免重复建设 - 当遇到**记忆/上下文相关** → 记住闭环已接通: FTS5+TF-IDF+embedding,不是空壳 -- 当遇到**管家/Butler** → 管家模式是默认模式,ButlerRouter 在中间件链中做关键词分类+system prompt 增强 +- 当遇到**管家/Butler** → 管家模式是默认模式,ButlerRouter 在中间件链中做关键词分类+system prompt 增强。跨会话身份走 soul.md,动态建议走 4 路并行上下文+LLM + +*** + +## 15. Karpathy 编码原则 + +> 源自 Andrej Karpathy 对 LLM 编码问题的观察。偏向谨慎而非速度,简单任务可灵活判断。 + +### 15.1 Think Before Coding + +**Don't assume. Don't hide confusion. Surface tradeoffs.** + +- State assumptions explicitly. If uncertain, ask. +- If multiple interpretations exist, present them — don't pick silently. +- If a simpler approach exists, say so. Push back when warranted. +- If something is unclear, stop. Name what's confusing. Ask. + +### 15.2 Simplicity First + +**Minimum code that solves the problem. Nothing speculative.** + +- No features beyond what was asked. +- No abstractions for single-use code. +- No "flexibility" or "configurability" that wasn't requested. +- No error handling for impossible scenarios. +- If you write 200 lines and it could be 50, rewrite it. + +Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify. + +### 15.3 Surgical Changes + +**Touch only what you must. Clean up only your own mess.** + +When editing existing code: + +- Don't "improve" adjacent code, comments, or formatting. +- Don't refactor things that aren't broken. +- Match existing style, even if you'd do it differently. +- If you notice unrelated dead code, mention it — don't delete it. + +When your changes create orphans: + +- Remove imports/variables/functions that YOUR changes made unused. +- Don't remove pre-existing dead code unless asked. + +The test: Every changed line should trace directly to the user's request. + +### 15.4 Goal-Driven Execution + +**Define success criteria. Loop until verified.** + +Transform tasks into verifiable goals: + +- "Add validation" → "Write tests for invalid inputs, then make them pass" +- "Fix the bug" → "Write a test that reproduces it, then make it pass" +- "Refactor X" → "Ensure tests pass before and after" + +For multi-step tasks, state a brief plan: + +``` +1. [Step] → verify: [check] +2. [Step] → verify: [check] +3. [Step] → verify: [check] +``` + +Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification. + +--- + +**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes. diff --git a/wiki/chat.md b/wiki/chat.md index 35e0a9c..50326b1 100644 --- a/wiki/chat.md +++ b/wiki/chat.md @@ -1,6 +1,6 @@ --- title: 聊天系统 -updated: 2026-04-22 +updated: 2026-04-23 status: active tags: [module, chat, stream] --- @@ -17,6 +17,7 @@ tags: [module, chat, stream] | 5 Store 拆分 | 原 908 行 ChatStore → stream/conversation/message/chat/artifact,单一职责 | | 5 分钟超时守护 | 防止流挂起: kernel-chat.ts:76,超时自动 cancelStream | | 统一回调接口 | 3 种实现共享 `{ onDelta, onThinkingDelta, onTool, onHand, onComplete, onError }` | +| LLM 动态建议 | 替换硬编码关键词匹配,用 LLM 生成个性化建议(1深入追问+1实用行动+1管家关怀),4路并行预取智能上下文 | ### ChatStream 实现 @@ -33,11 +34,14 @@ tags: [module, chat, stream] | 文件 | 职责 | |------|------| -| `desktop/src/store/chat/streamStore.ts` | 流式消息编排、发送、取消 | +| `desktop/src/store/chat/streamStore.ts` | 流式消息编排、发送、取消、LLM 动态建议生成 | | `desktop/src/store/chat/conversationStore.ts` | 会话管理、当前模型、sessionKey | | `desktop/src/store/chat/messageStore.ts` | 消息持久化 (IndexedDB) | | `desktop/src/lib/kernel-chat.ts` | KernelClient ChatStream (Tauri) | +| `desktop/src/lib/suggestion-context.ts` | 4路并行智能上下文拉取 (用户画像/痛点/经验/技能匹配) | +| `desktop/src/lib/cold-start-mapper.ts` | 冷启动配置映射 (行业检测/命名/个性/技能) | | `desktop/src/components/ChatArea.tsx` | 聊天区域 UI | +| `desktop/src/components/ai/SuggestionChips.tsx` | 动态建议芯片展示 | | `crates/zclaw-runtime/src/loop_runner.rs` | Rust 主聊天循环 + 中间件链 | ### 发送消息流 @@ -100,6 +104,20 @@ UI 选择模型 → conversationStore.currentModel = newModel - cancelStream 设置原子标志位,与 onDelta 回调无竞态 - 3 种 ChatStream 共享同一套回调接口,上层代码无需感知实现差异 - 消息持久化走 messageStore → IndexedDB,与流式渲染解耦 +- 动态建议 4 路并行预取 (userProfile/painPoints/experiences/skillMatch),500ms 超时降级为空串 +- 建议生成与 memory extraction 解耦 — 不等 memory LLM 调用完成即启动建议 + +### LLM 动态建议 + +``` +sendMessage → isStreaming=true + _activeSuggestionContextPrefetch = fetchSuggestionContext(...) + → 流式响应中 prefetch 在后台执行 +onComplete → createCompleteHandler + → generateLLMSuggestions(prefetchedContext) — 立即启动不等 memory + → prompt: 1 深入追问 + 1 实用行动 + 1 管家关怀 + → memory/reflection 后台独立运行 (Promise.all) + → SuggestionChips 渲染 +``` ### Tauri 命令 @@ -122,14 +140,16 @@ UI 选择模型 → conversationStore.currentModel = newModel **注意事项:** - 辅助 LLM 调用 (记忆摘要/提取、管家路由) 复用 `kernel_init` 的 model+base_url,与聊天同链路 - 课堂聊天是独立 Tauri 命令 (`classroom_chat`),不走 `agent_chat_stream` +- Agent tab 已移除 — 跨会话身份由 soul.md 接管,不再通过 RightPanel 管理 ## 5. 变更日志 | 日期 | 变更 | |------|------| +| 04-23 | 建议 prefetch: sendMessage 时启动 context 预取,流结束后立即消费,不等 memory extraction | +| 04-23 | 建议 prompt 重写: 1深入追问+1实用行动+1管家关怀,上下文窗口 6→20 条 | | 04-23 | 身份信号: detectAgentNameSuggestion 前端即时检测 + RightPanel 监听 Tauri 事件刷新名称 | +| 04-23 | Agent tab 移除: RightPanel 清理 ~280 行 dead code,身份由 soul.md 接管 | +| 04-23 | 澄清问题卡片 UX 优化: 去悬空引用 + 默认展开 | | 04-22 | Wiki 重写: 5 节模板,增加集成契约和不变量 | | 04-21 | 上一轮更新 | -| 04-17 | ChatStore 拆分为 5 Store (stream/conversation/message/chat/artifact) | -| 04-16 | Provider Key 解密修复 (b69dc61) | -| 04-16 | Tauri invoke 参数名修复 (f6c5dd2) | diff --git a/wiki/log.md b/wiki/log.md index c95e05c..a39b93a 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -9,6 +9,14 @@ tags: [log, history] > Append-only 操作记录。格式: `## [日期] 类型 | 描述` +## [2026-04-23] perf | 回复效率+建议生成并行化优化 (三部分) +- **perf(src-tauri)**: identity prompt 缓存 (`LazyLock>`) + `pre_conversation_hook` 并行化 (`tokio::join!`) +- **perf(runtime)**: middleware `before_completion` 分波并行 — `parallel_safe()` trait + wave detection + `tokio::spawn`,5 层 safe 中间件可并行 +- **perf(desktop)**: suggestion context 预取 (sendMessage 时启动) + generateLLMSuggestions 与 memory extraction 解耦 +- **feat(desktop)**: suggestion prompt 重写 (1深入追问+1实用行动+1管家关怀) + 上下文窗口 6→20 条 +- **文件**: intelligence_hooks.rs, middleware.rs, 5 个 middleware 子模块, streamStore.ts, llm-service.ts +- **验证**: cargo test --workspace --exclude zclaw-saas 0 fail, tsc --noEmit 0 error + ## [2026-04-23] fix | Agent 命名检测重构+跨会话记忆修复+Agent tab 移除 - **fix(desktop)**: `detectAgentNameSuggestion` 从 6 个固定正则改为 trigger+extract 两步法 (10 个 trigger) - **fix(desktop)**: 名字检测从 memory extraction 解耦 — 502 不再阻断面板刷新 diff --git a/wiki/middleware.md b/wiki/middleware.md index 8b66054..2d1c389 100644 --- a/wiki/middleware.md +++ b/wiki/middleware.md @@ -1,6 +1,6 @@ --- title: 中间件链 -updated: 2026-04-22 +updated: 2026-04-23 status: active tags: [module, middleware, runtime] --- @@ -17,6 +17,7 @@ tags: [module, middleware, runtime] - **WHY 注册顺序 != 执行顺序**: `kernel/mod.rs` 中 14 次 `chain.register()` 的代码顺序与运行时顺序无关,chain 按 `priority()` 升序排列后执行。 - **WHY 6 类 14 层**: 进化(70-79) -> 路由(80-99) -> 上下文(100-199) -> 能力(200-399) -> 安全(400-599) -> 遥测(600-799),优先级范围即执行阶段。 - **WHY Stop/Block/AbortLoop**: 细粒度流控 -- Stop 中断 LLM 循环,Block 阻止单次工具调用,AbortLoop 终止整个 Agent 循环。命中后跳过所有后续中间件。 +- **WHY 分波并行 (parallel_safe)**: `before_completion` 阶段,只修改 `system_prompt` 的中间件可声明 `parallel_safe() == true`,连续的 parallel-safe 中间件通过 `tokio::spawn` 并行执行,各自持有 `MiddlewareContext` clone,完成后合并 prompt 贡献。降低串行延迟 ~1-3s。 ## 2. 关键文件 + 数据流 @@ -34,8 +35,10 @@ tags: [module, middleware, runtime] ``` 用户消息 -> AgentLoop -> chain.run_before_completion(ctx) - -> [按 priority 升序] 每层 middleware.before_completion() - -> Continue: 下一层 | Stop(reason): 中断循环 + -> [分波并行] 检测连续 parallel_safe 中间件 + -> Wave 并行 (2+ safe): tokio::spawn 各自 ctx.clone() → 合并 prompt + -> 串行 (unsafe / 单个 safe): 逐个执行 + -> Continue: 下一层 | Stop(reason): 中断循环 -> LLM 调用 -> (工具调用时) chain.run_before_tool_call() -> Allow | Block(msg) | ReplaceInput | AbortLoop @@ -57,22 +60,22 @@ tags: [module, middleware, runtime] ### 14 层 Runtime 中间件 -| 优先级 | 中间件 | 文件 | 职责 | 注册条件 | -|--------|--------|------|------|----------| -| @78 | EvolutionMiddleware | `evolution.rs` | 推送进化候选项到 system prompt | 始终 | -| @80 | ButlerRouter | `butler_router.rs` | 语义技能路由 + system prompt 增强 + XML fencing | 始终 | -| @100 | Compaction | `compaction.rs` | 超阈值时压缩对话历史 | `compaction_threshold > 0` | -| @150 | Memory | `memory.rs` | 对话后自动提取记忆 + 注入检索结果 | 始终 | -| @180 | Title | `title.rs` | 自动生成会话标题 | 始终 | -| @200 | SkillIndex | `skill_index.rs` | 注入技能索引到 system prompt | `!skill_index.is_empty()` | -| @300 | DanglingTool | `dangling_tool.rs` | 修复缺失的工具调用结果 | 始终 | -| @350 | ToolError | `tool_error.rs` | 格式化工具错误供 LLM 恢复 | 始终 | -| @360 | ToolOutputGuard | `tool_output_guard.rs` | 工具输出安全检查 | 始终 | -| @400 | Guardrail | `guardrail.rs` | shell_exec/file_write/web_fetch 安全规则 | 始终 | -| @500 | LoopGuard | `loop_guard.rs` | 防止工具调用无限循环 | 始终 | -| @550 | SubagentLimit | `subagent_limit.rs` | 限制并发子 agent | 始终 | -| @650 | TrajectoryRecorder | `trajectory_recorder.rs` | 轨迹记录 + 压缩 | 始终 | -| @700 | TokenCalibration | `token_calibration.rs` | Token 用量校准 | 始终 | +| 优先级 | 中间件 | 文件 | 职责 | parallel_safe | 注册条件 | +|--------|--------|------|------|---------------|----------| +| @78 | EvolutionMiddleware | `evolution.rs` | 推送进化候选项到 system prompt | ✅ | 始终 | +| @80 | ButlerRouter | `butler_router.rs` | 语义技能路由 + system prompt 增强 + XML fencing | ✅ | 始终 | +| @100 | Compaction | `compaction.rs` | 超阈值时压缩对话历史 | ❌ | `compaction_threshold > 0` | +| @150 | Memory | `memory.rs` | 对话后自动提取记忆 + 注入检索结果 | ✅ | 始终 | +| @180 | Title | `title.rs` | 自动生成会话标题 | ✅ | 始终 | +| @200 | SkillIndex | `skill_index.rs` | 注入技能索引到 system prompt | ✅ | `!skill_index.is_empty()` | +| @300 | DanglingTool | `dangling_tool.rs` | 修复缺失的工具调用结果 | ❌ | 始终 | +| @350 | ToolError | `tool_error.rs` | 格式化工具错误供 LLM 恢复 | ❌ | 始终 | +| @360 | ToolOutputGuard | `tool_output_guard.rs` | 工具输出安全检查 | ❌ | 始终 | +| @400 | Guardrail | `guardrail.rs` | shell_exec/file_write/web_fetch 安全规则 | ❌ | 始终 | +| @500 | LoopGuard | `loop_guard.rs` | 防止工具调用无限循环 | ❌ | 始终 | +| @550 | SubagentLimit | `subagent_limit.rs` | 限制并发子 agent | ❌ | 始终 | +| @650 | TrajectoryRecorder | `trajectory_recorder.rs` | 轨迹记录 + 压缩 | ❌ | 始终 | +| @700 | TokenCalibration | `token_calibration.rs` | Token 用量校准 | ❌ | 始终 | > 注册顺序 (代码) 与执行顺序 (priority) 不同。Chain 按 priority 升序排列后执行。 @@ -96,6 +99,8 @@ tags: [module, middleware, runtime] - Priority 升序: 0-999, 数值越小越先执行 - 注册顺序 != 执行顺序; chain 按 priority 运行时排序 - Stop/Block/AbortLoop 立即中断, 不执行后续中间件 +- parallel_safe 中间件只修改 system_prompt,不修改 messages,不返回 Stop +- 分波合并: 并行 wave 中每个中间件 clone context,完成后按 base_prompt_len 截取增量合并 ### 核心接口 @@ -103,6 +108,7 @@ tags: [module, middleware, runtime] trait AgentMiddleware: Send + Sync { fn name(&self) -> &str; fn priority(&self) -> i32 { 500 } + fn parallel_safe(&self) -> bool { false } async fn before_completion(&self, ctx: &mut MiddlewareContext) -> Result; async fn before_tool_call(&self, ctx: &MiddlewareContext, tool_name: &str, tool_input: &Value) -> Result; async fn after_tool_call(&self, ctx: &mut MiddlewareContext, tool_name: &str, result: &Value) -> Result<()>; @@ -129,8 +135,8 @@ trait AgentMiddleware: Send + Sync { | 日期 | 变更 | 影响 | |------|------|------| +| 04-23 | 分波并行执行: parallel_safe() + wave detection + tokio::spawn | before_completion 阶段 5 层 safe 中间件可并行,延迟降低 ~1-3s | | 04-22 | DataMasking 中间件移除 | 14->14 层 (替换为无), 减少 1 层无收益处理 | | 04-22 | 跨会话记忆修复 | Memory 中间件去重+跨会话注入修复 | | 04-22 | Wiki 一致性校准 | 数字与代码验证对齐 | | 04-21 | Embedding 接通 | SkillIndex 路由 TF-IDF->Embedding+LLM fallback | -| 04-15 | Heartbeat 统一健康系统 | TrajectoryRecorder 痛点感知增强 |