autosnippet 3.3.2 → 3.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +8 -4
  2. package/dist/bin/cli.js +27 -1
  3. package/dist/lib/cli/KnowledgeSyncService.d.ts +26 -0
  4. package/dist/lib/cli/KnowledgeSyncService.js +33 -1
  5. package/dist/lib/external/mcp/handlers/browse.d.ts +1 -0
  6. package/dist/lib/external/mcp/handlers/browse.js +2 -1
  7. package/dist/lib/external/mcp/handlers/consolidated.d.ts +1 -0
  8. package/dist/lib/external/mcp/handlers/panorama.d.ts +11 -11
  9. package/dist/lib/external/mcp/handlers/panorama.js +20 -20
  10. package/dist/lib/external/mcp/handlers/system.d.ts +1 -1
  11. package/dist/lib/external/mcp/handlers/task.js +38 -15
  12. package/dist/lib/external/mcp/tools.d.ts +12 -12
  13. package/dist/lib/external/mcp/tools.js +120 -118
  14. package/dist/lib/http/middleware/validate.js +7 -3
  15. package/dist/lib/infrastructure/database/drizzle/schema.d.ts +100 -0
  16. package/dist/lib/infrastructure/database/drizzle/schema.js +10 -0
  17. package/dist/lib/infrastructure/database/migrations/005_recipe_source_refs.d.ts +9 -0
  18. package/dist/lib/infrastructure/database/migrations/005_recipe_source_refs.js +24 -0
  19. package/dist/lib/infrastructure/vector/HnswVectorAdapter.js +18 -2
  20. package/dist/lib/injection/ServiceContainer.js +2 -0
  21. package/dist/lib/injection/modules/KnowledgeModule.d.ts +5 -0
  22. package/dist/lib/injection/modules/KnowledgeModule.js +80 -0
  23. package/dist/lib/service/bootstrap/UiStartupTasks.d.ts +45 -0
  24. package/dist/lib/service/bootstrap/UiStartupTasks.js +101 -0
  25. package/dist/lib/service/evolution/ConsolidationAdvisor.js +9 -9
  26. package/dist/lib/service/evolution/ContradictionDetector.js +2 -2
  27. package/dist/lib/service/evolution/RedundancyAnalyzer.js +2 -2
  28. package/dist/lib/service/knowledge/SourceRefReconciler.d.ts +68 -0
  29. package/dist/lib/service/knowledge/SourceRefReconciler.js +309 -0
  30. package/dist/lib/service/panorama/PanoramaService.d.ts +18 -1
  31. package/dist/lib/service/panorama/PanoramaService.js +148 -5
  32. package/dist/lib/service/search/BM25Scorer.d.ts +2 -2
  33. package/dist/lib/service/search/CoarseRanker.d.ts +7 -6
  34. package/dist/lib/service/search/CoarseRanker.js +11 -10
  35. package/dist/lib/service/search/FieldWeightedScorer.d.ts +81 -0
  36. package/dist/lib/service/search/FieldWeightedScorer.js +318 -0
  37. package/dist/lib/service/search/MultiSignalRanker.d.ts +2 -2
  38. package/dist/lib/service/search/MultiSignalRanker.js +1 -1
  39. package/dist/lib/service/search/SearchEngine.d.ts +8 -7
  40. package/dist/lib/service/search/SearchEngine.js +59 -10
  41. package/dist/lib/service/search/SearchTypes.d.ts +23 -3
  42. package/dist/lib/service/search/SearchTypes.js +6 -1
  43. package/dist/lib/service/task/IntentExtractor.d.ts +11 -1
  44. package/dist/lib/service/task/IntentExtractor.js +137 -3
  45. package/dist/lib/service/task/PrimeSearchPipeline.js +95 -25
  46. package/dist/lib/service/vector/VectorService.d.ts +3 -0
  47. package/dist/lib/service/vector/VectorService.js +38 -4
  48. package/dist/lib/shared/schemas/mcp-tools.d.ts +1 -0
  49. package/dist/lib/shared/schemas/mcp-tools.js +5 -1
  50. package/package.json +1 -1
  51. package/skills/autosnippet-create/SKILL.md +98 -89
  52. package/skills/autosnippet-devdocs/SKILL.md +55 -60
  53. package/templates/guard-ci.yml +2 -2
  54. package/templates/instructions/conventions.md +4 -2
  55. package/templates/recipes-setup/_template.md +39 -39
@@ -1,239 +1,241 @@
1
1
  /**
2
- * MCP 工具定义 — V3 整合版 (14 agent + 2 admin = 16 工具)
2
+ * MCP Tool Definitions — V3 Consolidated (14 agent + 2 admin = 16 tools)
3
3
  *
4
- * 每个工具声明包含 nametieragent/admin)、description inputSchema
5
- * description Agent 选择工具的关键使用 bullet list 列出所有 operation 及其用途。
6
- * inputSchema Zod Schema 自动生成(zodToMcpSchema),参数的 .describe() 会转为 JSON Schema description
4
+ * Each tool declaration contains name, tier (agent/admin), description, and inputSchema.
5
+ * description is the key for Agent tool selection use bullet list to enumerate all operations and their purposes.
6
+ * inputSchema is auto-generated from Zod Schema (zodToMcpSchema); parameter .describe() translates to JSON Schema description.
7
7
  *
8
- * Agent 工具 (14):
9
- * 1-7: 查询工具 (health/search/knowledge/structure/graph/call_context/guard)
10
- * 8: 写入工具 (submit_knowledge — unified pipeline,单条/批量统一处理)
11
- * 9: Skill 管理 (skill)
12
- * 10-12: 冷启动 (bootstrap/dimension_complete/wiki)
13
- * 13: 项目全景 (panorama)
14
- * 14: 任务管理 (task — 5 ops: prime/create/close/fail/record_decision)
8
+ * Agent tools (14):
9
+ * 1-7: Query tools (health/search/knowledge/structure/graph/call_context/guard)
10
+ * 8: Write tool (submit_knowledge — unified pipeline, single/batch)
11
+ * 9: Skill management (skill)
12
+ * 10-12: Cold-start (bootstrap/dimension_complete/wiki)
13
+ * 13: Project panorama (panorama)
14
+ * 14: Task management (task — 5 ops: prime/create/close/fail/record_decision)
15
15
  *
16
- * Admin 工具 (2):
16
+ * Admin tools (2):
17
17
  * 15-16: enrich_candidates/knowledge_lifecycle
18
18
  */
19
19
  import { BootstrapInput, CallContextInput, DimensionCompleteInput, EnrichCandidatesInput, GraphInput, GuardInput, HealthInput, KnowledgeInput, KnowledgeLifecycleInput, PanoramaInput, SearchInput, SkillInput, StructureInput, SubmitKnowledgeInput, TaskInput, WikiInput, } from '#shared/schemas/mcp-tools.js';
20
20
  import { zodToMcpSchema } from './zodToMcpSchema.js';
21
- // ─── Tier 定义 ──────────────────────────────────────────────
21
+ // ─── Tier Definitions ────────────────────────────────────────
22
22
  export const TIER_ORDER = { agent: 0, admin: 1 };
23
- // ─── Gateway 映射(仅写操作需要 gating ────────────────────
23
+ // ─── Gateway Mapping (only write operations require gating)
24
24
  export const TOOL_GATEWAY_MAP = {
25
- // bootstrap — 无参数化 Mission Briefing(只读分析,无需 gating
25
+ // bootstrap — parameterless Mission Briefing (read-only analysis, no gating needed)
26
26
  // autosnippet_bootstrap: null,
27
- // dimension_complete — 写操作(recipe tagging + skill creation + checkpoint
27
+ // dimension_complete — write operation (recipe tagging + skill creation + checkpoint)
28
28
  autosnippet_dimension_complete: { action: 'knowledge:bootstrap', resource: 'knowledge' },
29
- // wiki — finalize 操作是写操作(meta.json
29
+ // wiki — finalize is a write operation (meta.json)
30
30
  autosnippet_wiki: {
31
- resolver: (args) => args?.operation === 'finalize' ? { action: 'knowledge:create', resource: 'knowledge' } : null, // plan 只读
31
+ resolver: (args) => args?.operation === 'finalize' ? { action: 'knowledge:create', resource: 'knowledge' } : null, // plan is read-only
32
32
  },
33
- // guard 写操作(仅 files 模式)
33
+ // guard write operation (files mode only)
34
34
  autosnippet_guard: {
35
35
  resolver: (args) => args?.files && Array.isArray(args.files)
36
36
  ? { action: 'guard_rule:check_code', resource: 'guard_rules' }
37
- : null, // code 模式只读,跳过 Gateway
37
+ : null, // code mode is read-only, skip Gateway
38
38
  },
39
- // skill 写操作(create/update/delete
39
+ // skill write operations (create/update/delete)
40
40
  autosnippet_skill: {
41
41
  resolver: (args) => ({
42
42
  create: { action: 'create:skills', resource: 'skills' },
43
43
  update: { action: 'update:skills', resource: 'skills' },
44
44
  delete: { action: 'delete:skills', resource: 'skills' },
45
- })[args?.operation] || null, // list/load/suggest 只读
45
+ })[args?.operation] || null, // list/load/suggest are read-only
46
46
  },
47
- // 知识提交(unified pipeline
47
+ // knowledge submission (unified pipeline)
48
48
  autosnippet_submit_knowledge: { action: 'knowledge:create', resource: 'knowledge' },
49
- // task 写操作(create/close/fail + record_decision
49
+ // task write operations (create/close/fail + record_decision)
50
50
  autosnippet_task: {
51
51
  resolver: (args) => ({
52
52
  create: { action: 'task:create', resource: 'intent' },
53
53
  close: { action: 'task:update', resource: 'intent' },
54
54
  fail: { action: 'task:update', resource: 'intent' },
55
55
  record_decision: { action: 'task:create', resource: 'intent' },
56
- })[args?.operation] || null, // prime 只读
56
+ })[args?.operation] || null, // prime is read-only
57
57
  },
58
- // admin 工具
58
+ // admin tools
59
59
  autosnippet_enrich_candidates: { action: 'knowledge:update', resource: 'knowledge' },
60
60
  autosnippet_knowledge_lifecycle: { action: 'knowledge:update', resource: 'knowledge' },
61
61
  };
62
- // ─── 工具声明 ────────────────────────────────────────────────
62
+ // ─── Tool Declarations ───────────────────────────────────────
63
63
  export const TOOLS = [
64
64
  // ══════════════════════════════════════════════════════
65
- // Tier: agent — Agent 核心工具集 (14)
65
+ // Tier: agent — Core Agent Toolset (14)
66
66
  // ══════════════════════════════════════════════════════
67
- // 1. 健康检查
67
+ // 1. Health Check
68
68
  {
69
69
  name: 'autosnippet_health',
70
70
  tier: 'agent',
71
- description: '检查服务状态与知识库统计。返回 total(知识总数)和各 kind/lifecycle 分布。total=0 时需要冷启动(调用 autosnippet_bootstrap)。',
71
+ description: 'Check service status and knowledge base stats. Returns total (entry count) and kind/lifecycle distribution. When total=0, cold-start is needed (call autosnippet_bootstrap).',
72
72
  inputSchema: zodToMcpSchema(HealthInput),
73
73
  },
74
- // 2. 统合搜索
74
+ // 2. Unified Search
75
75
  {
76
76
  name: 'autosnippet_search',
77
77
  tier: 'agent',
78
- description: '搜索知识库。5 种模式:\n' +
79
- '• auto(默认)— 自动选最优策略\n' +
80
- '• keyword — 精确关键词匹配,适合 trigger/title 查找\n' +
81
- '• bm25 — 全文检索,适合自然语言描述\n' +
82
- '• semantic — 向量语义搜索,适合模糊概念匹配\n' +
83
- '• context — 综合搜索 + 上下文关联,适合编码辅助\n' +
84
- '返回按 kindrule/pattern/fact)分组的结果。',
78
+ description: 'Search the knowledge base. 5 modes:\n' +
79
+ '• auto (default) — automatically selects optimal strategy\n' +
80
+ '• keyword — exact keyword matching, best for trigger/title lookup\n' +
81
+ '• bm25 — full-text search, best for natural language descriptions\n' +
82
+ '• semantic — vector semantic search, best for fuzzy concept matching\n' +
83
+ '• context — combined search + context association, best for coding assistance\n' +
84
+ 'Returns results grouped by kind (rule/pattern/fact).',
85
85
  inputSchema: zodToMcpSchema(SearchInput),
86
86
  },
87
- // 3. 知识浏览
87
+ // 3. Knowledge Browser
88
88
  {
89
89
  name: 'autosnippet_knowledge',
90
90
  tier: 'agent',
91
- description: '知识条目管理。\n' +
92
- '• list — kind/category/status 过滤列表\n' +
93
- '• get — 获取单条完整内容(需 id)\n' +
94
- '• insights — 条目质量分析与改进建议(需 id)\n' +
95
- '• confirm_usage — 记录知识被实际采纳(需 id',
91
+ description: 'Knowledge entry management.\n' +
92
+ '• list — filter entries by kind/category/status\n' +
93
+ '• get — retrieve full content of a single entry (requires id)\n' +
94
+ '• insights — quality analysis and improvement suggestions (requires id)\n' +
95
+ '• confirm_usage — record that knowledge was actually adopted (requires id)',
96
96
  inputSchema: zodToMcpSchema(KnowledgeInput),
97
97
  },
98
- // 4. 项目结构
98
+ // 4. Project Structure
99
99
  {
100
100
  name: 'autosnippet_structure',
101
101
  tier: 'agent',
102
- description: '探查项目结构。\n' +
103
- '• targets — 构建目标列表(模块/Target/Package)\n' +
104
- '• files — 指定 Target 的文件列表\n' +
105
- '• metadata — 项目元数据(语言、依赖、配置)',
102
+ description: 'Explore project structure.\n' +
103
+ '• targets — list build targets (modules/Targets/Packages)\n' +
104
+ '• files — list files for a specific Target\n' +
105
+ '• metadata — project metadata (language, dependencies, configuration)',
106
106
  inputSchema: zodToMcpSchema(StructureInput),
107
107
  },
108
- // 5. 知识图谱
108
+ // 5. Knowledge Graph
109
109
  {
110
110
  name: 'autosnippet_graph',
111
111
  tier: 'agent',
112
- description: '知识关系图谱查询。\n' +
113
- '• query — 查询节点的关联关系\n' +
114
- '• impact — 修改某知识的影响范围分析\n' +
115
- '• path — 两个知识节点间的关联路径\n' +
116
- '• stats — 图谱全局统计(节点/边/密度)',
112
+ description: 'Knowledge relationship graph queries.\n' +
113
+ '• query — query relationships of a node\n' +
114
+ '• impact — analyze impact scope of modifying a knowledge entry\n' +
115
+ '• path — find relationship path between two knowledge nodes\n' +
116
+ '• stats — global graph statistics (nodes/edges/density)',
117
117
  inputSchema: zodToMcpSchema(GraphInput),
118
118
  },
119
- // 6. 调用链上下文
119
+ // 6. Call Context
120
120
  {
121
121
  name: 'autosnippet_call_context',
122
122
  tier: 'agent',
123
- description: '查询函数/方法的调用链。\n' +
124
- '• callers — 谁调用了它(上游调用链)\n' +
125
- '• callees — 它调用了谁(下游依赖链)\n' +
126
- '• impact — 修改它的影响半径(上+下游+受影响文件数)\n' +
127
- '• both — 同时获取 callers + callees',
123
+ description: 'Query function/method call chains.\n' +
124
+ '• callers — who calls it (upstream call chain)\n' +
125
+ '• callees — what it calls (downstream dependency chain)\n' +
126
+ '• impact — modification impact radius (upstream + downstream + affected file count)\n' +
127
+ '• both — retrieve callers + callees simultaneously',
128
128
  inputSchema: zodToMcpSchema(CallContextInput),
129
129
  },
130
- // 7. Guard 代码检查
130
+ // 7. Guard Code Check
131
131
  {
132
132
  name: 'autosnippet_guard',
133
133
  tier: 'agent',
134
- description: '代码规范检查与 Guard 免疫系统。\n' +
135
- '• 无参数自动检查 git diff 增量文件(编码后首选用法)\n' +
136
- '• files → 检查指定文件列表\n' +
137
- '• code → 内联检查代码片段\n' +
138
- '• operation: "reverse_audit" → Recipe→Code 反向验证(检查知识是否过时)\n' +
139
- '• operation: "coverage_matrix" → 模块级 Guard 规则覆盖率矩阵\n' +
140
- '每个 violation 附带修复指南(doClause + coreCode),按指示修复后可再次检查。',
134
+ description: 'Code compliance check and Guard immune system.\n' +
135
+ '• no params auto-check git diff incremental files (preferred after coding)\n' +
136
+ '• files → check specified file list\n' +
137
+ '• code → inline check code snippet\n' +
138
+ '• operation: "reverse_audit" → Recipe→Code reverse validation (check if knowledge is outdated)\n' +
139
+ '• operation: "coverage_matrix" → module-level Guard rule coverage matrix\n' +
140
+ 'Each violation includes a fix guide (doClause + coreCode). Fix accordingly and re-check.',
141
141
  inputSchema: zodToMcpSchema(GuardInput),
142
142
  },
143
- // 8. 提交知识(统一管线)
143
+ // 8. Submit Knowledge (Unified Pipeline)
144
144
  {
145
145
  name: 'autosnippet_submit_knowledge',
146
146
  tier: 'agent',
147
- description: '提交知识条目(单条/批量统一管线)。通过 items 数组传入 1~N 条。\n' +
148
- '• 所有条目统一严格校验,所有 V3 字段须一次性提供\n' +
149
- '• 统一融合分析:检测与已有 Recipe 和批次内候选的重叠\n' +
150
- '• 返回 CONSOLIDATION_MERGE / CONSOLIDATION_REORGANIZE / CONSOLIDATION_INSUFFICIENT 时需处理\n' +
151
- '• skipConsolidation: true 跳过融合检查。content reasoning 必须是对象。',
147
+ description: 'Submit knowledge entries (single/batch unified pipeline). Pass 1~N items via the items array.\n' +
148
+ '• All entries undergo strict validation; all V3 fields must be provided at once\n' +
149
+ '• Unified consolidation analysis: detects overlap with existing Recipes and batch candidates\n' +
150
+ '• Handle CONSOLIDATION_MERGE / CONSOLIDATION_REORGANIZE / CONSOLIDATION_INSUFFICIENT responses\n' +
151
+ '• Set skipConsolidation: true to skip consolidation check. content and reasoning must be objects.\n' +
152
+ '⚠️ Batch rule: items in the array must NOT be cross-redundant — no highly overlapping doClause/coreCode/trigger within the same batch. ' +
153
+ 'If two entries share 80%+ content, merge into one or split into primary + extends supplementary entries.',
152
154
  inputSchema: zodToMcpSchema(SubmitKnowledgeInput),
153
155
  },
154
- // 9. Skill 管理
156
+ // 9. Skill Management
155
157
  {
156
158
  name: 'autosnippet_skill',
157
159
  tier: 'agent',
158
- description: 'Skill 管理。\n' +
159
- '• list — 列出所有可用 Skill(内置 + 项目级)\n' +
160
- '• load — 加载 Skill 完整内容,获取详细指引(需 name)\n' +
161
- '• create — 创建项目级 Skill(需 name + description + content)\n' +
162
- '• update — 更新项目级 Skill 内容\n' +
163
- '• delete — 删除项目级 Skill(内置不可删)\n' +
164
- '• suggest — 基于项目分析推荐应创建的 Skill',
160
+ description: 'Skill management.\n' +
161
+ '• list — list all available Skills (built-in + project-level)\n' +
162
+ '• load — load full Skill content for detailed guidance (requires name)\n' +
163
+ '• create — create project-level Skill (requires name + description + content)\n' +
164
+ '• update — update project-level Skill content\n' +
165
+ '• delete — delete project-level Skill (built-in cannot be deleted)\n' +
166
+ '• suggest — recommend Skills to create based on project analysis',
165
167
  inputSchema: zodToMcpSchema(SkillInput),
166
168
  },
167
- // 10. 冷启动
169
+ // 10. Cold-Start Bootstrap
168
170
  {
169
171
  name: 'autosnippet_bootstrap',
170
172
  tier: 'agent',
171
- description: '冷启动无需参数,自动分析项目(AST、依赖图、Guard 审计),返回 Mission Briefing:\n' +
172
- '• 项目元数据与语言统计\n' +
173
- '• 维度任务清单(8 维度 × 3 Tier)\n' +
174
- '• 执行计划与提交示例\n' +
175
- '收到 Briefing 后按 executionPlan 完成所有维度分析。',
173
+ description: 'Cold-startno parameters needed. Auto-analyzes the project (AST, dependency graph, Guard audit) and returns a Mission Briefing:\n' +
174
+ '• Project metadata and language statistics\n' +
175
+ '• Dimension task list (8 dimensions × 3 Tiers)\n' +
176
+ '• Execution plan and submission examples\n' +
177
+ 'After receiving the Briefing, complete all dimension analyses per the executionPlan.',
176
178
  inputSchema: zodToMcpSchema(BootstrapInput),
177
179
  },
178
- // 11. 维度完成通知
180
+ // 11. Dimension Complete Notification
179
181
  {
180
182
  name: 'autosnippet_dimension_complete',
181
183
  tier: 'agent',
182
- description: '维度分析完成通知。负责:Recipe 关联、Skill 生成(从已提交候选自动合成)、Checkpoint 保存、跨维度 Hints 分发。\n' +
183
- 'analysisText 可简写,系统会自动从已提交的候选知识中合成详细内容用于 Skill 生成。',
184
+ description: 'Dimension analysis completion notification. Handles: Recipe linking, Skill generation (auto-synthesized from submitted candidates), Checkpoint saving, cross-dimension Hints distribution.\n' +
185
+ 'analysisText can be brief — the system auto-synthesizes detailed content from submitted candidates for Skill generation.',
184
186
  inputSchema: zodToMcpSchema(DimensionCompleteInput),
185
187
  },
186
- // 12. Wiki 文档生成
188
+ // 12. Wiki Documentation Generation
187
189
  {
188
190
  name: 'autosnippet_wiki',
189
191
  tier: 'agent',
190
- description: 'Wiki 文档生成。\n' +
191
- '• plan — 规划主题 + 数据包(整合项目结构与知识库,返回主题列表 + 每个主题的数据包,Agent 据此撰写)\n' +
192
- '• finalize — 完成生成(写入 meta.json、去重检查、验证完整性,所有文章写入后调用)',
192
+ description: 'Wiki documentation generation.\n' +
193
+ '• plan — plan topics + data packages (integrates project structure and knowledge base; returns topic list + per-topic data package for Agent to write)\n' +
194
+ '• finalize — complete generation (write meta.json, dedup check, validate completeness; call after all articles are written)',
193
195
  inputSchema: zodToMcpSchema(WikiInput),
194
196
  },
195
- // 13. 项目全景
197
+ // 13. Project Panorama
196
198
  {
197
199
  name: 'autosnippet_panorama',
198
200
  tier: 'agent',
199
- description: '项目全景查询。无数据时自动触发结构扫描,无需手动冷启动。\n' +
200
- '• overview(默认)— 项目骨架 + 架构层级 + 模块角色 + 知识覆盖率\n' +
201
- '• module — 单模块详情 + 邻居关系(需 module 参数)\n' +
202
- '• gaps — 知识空白区(有代码无 Recipe 的模块)\n' +
203
- '• health — 全景健康度(覆盖率 + 耦合度 + 循环依赖 + 健康评分)\n' +
204
- '• governance_cycle — 知识新陈代谢完整周期(矛盾检测 + 冗余分析 + 衰退评估)\n' +
205
- '• decay_report — 衰退评估报告(5 策略检测 + decayScore 评分)\n' +
206
- '• staging_check — staging 条目检查 + 到期自动发布\n' +
207
- '• enhancement_suggestions — 基于使用数据的 Recipe 增强建议',
201
+ description: 'Project panorama queries. Auto-triggers structure scan when no data exists — no manual cold-start needed.\n' +
202
+ '• overview (default) — project skeleton + architecture layers + module roles + knowledge coverage\n' +
203
+ '• module — single module details + neighbor relationships (requires module param)\n' +
204
+ '• gaps — knowledge gaps (modules with code but no Recipes)\n' +
205
+ '• health — panorama health score (coverage + coupling + circular deps + health score)\n' +
206
+ '• governance_cycle — full knowledge metabolism cycle (contradiction detection + redundancy analysis + decay assessment)\n' +
207
+ '• decay_report — decay assessment report (5 strategy detection + decayScore)\n' +
208
+ '• staging_check — staging entry check + auto-publish on expiry\n' +
209
+ '• enhancement_suggestions — Recipe enhancement suggestions based on usage data',
208
210
  inputSchema: zodToMcpSchema(PanoramaInput),
209
211
  },
210
- // 14. 任务与决策管理
212
+ // 14. Task & Decision Management
211
213
  {
212
214
  name: 'autosnippet_task',
213
215
  tier: 'agent',
214
- description: '任务与决策管理(5 operations)。每次对话开始时先调用 prime 加载知识上下文。\n' +
215
- '• prime — 加载知识上下文 + 初始化意图生命周期\n' +
216
- '• create — 创建任务锚点(≥2 files ≥10 lines 的非轻量工作)\n' +
217
- '• close — 完成任务 + 触发 Guard 合规审查\n' +
218
- '• fail — 放弃任务\n' +
219
- '• record_decision — 记录用户偏好决策',
216
+ description: 'Task and decision management (5 operations). Call prime first at the start of each conversation to load knowledge context.\n' +
217
+ '• prime — load knowledge context + initialize intent lifecycle\n' +
218
+ '• create — create task anchor (for non-trivial work: ≥2 files or ≥10 lines)\n' +
219
+ '• close — complete task + trigger Guard compliance review\n' +
220
+ '• fail — abandon task\n' +
221
+ '• record_decision — record user preference decision',
220
222
  inputSchema: zodToMcpSchema(TaskInput),
221
223
  },
222
224
  // ══════════════════════════════════════════════════════
223
- // Tier: admin — 管理员/CI 工具 (+2)
225
+ // Tier: admin — Admin/CI Tools (+2)
224
226
  // ══════════════════════════════════════════════════════
225
- // 15. 候选字段诊断
227
+ // 15. Candidate Field Diagnosis
226
228
  {
227
229
  name: 'autosnippet_enrich_candidates',
228
230
  tier: 'admin',
229
- description: '诊断候选条目的字段完整性(无 AI)。返回每条候选的 missingFields 列表,Agent 据此补全后重新提交。',
231
+ description: 'Diagnose field completeness of candidate entries (no AI). Returns missingFields list per candidate for Agent to fill in and resubmit.',
230
232
  inputSchema: zodToMcpSchema(EnrichCandidatesInput),
231
233
  },
232
- // 16. 知识生命周期
234
+ // 16. Knowledge Lifecycle
233
235
  {
234
236
  name: 'autosnippet_knowledge_lifecycle',
235
237
  tier: 'admin',
236
- description: '知识条目生命周期操作。approve/fast_track → 发布知识;reject → 拒绝;deprecate → 废弃;reactivate → 恢复。',
238
+ description: 'Knowledge entry lifecycle operations. approve/fast_track → publish; reject → reject; deprecate → deprecate; reactivate → restore.',
237
239
  inputSchema: zodToMcpSchema(KnowledgeLifecycleInput),
238
240
  },
239
241
  ];
@@ -60,8 +60,8 @@ export function validateQuery(schema) {
60
60
  });
61
61
  return;
62
62
  }
63
- // 替换为 parsed + defaulted + coerced 数据
64
- req.query = result.data;
63
+ // Express 5: req.query is a read-only getter, use defineProperty to override
64
+ Object.defineProperty(req, 'query', { value: result.data, writable: true, configurable: true });
65
65
  next();
66
66
  };
67
67
  }
@@ -85,7 +85,11 @@ export function validateParams(schema) {
85
85
  });
86
86
  return;
87
87
  }
88
- req.params = result.data;
88
+ Object.defineProperty(req, 'params', {
89
+ value: result.data,
90
+ writable: true,
91
+ configurable: true,
92
+ });
89
93
  next();
90
94
  };
91
95
  }
@@ -3311,3 +3311,103 @@ export declare const evolutionProposals: import("drizzle-orm/sqlite-core").SQLit
3311
3311
  };
3312
3312
  dialect: "sqlite";
3313
3313
  }>;
3314
+ export declare const recipeSourceRefs: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
3315
+ name: "recipe_source_refs";
3316
+ schema: undefined;
3317
+ columns: {
3318
+ recipeId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3319
+ name: "recipe_id";
3320
+ tableName: "recipe_source_refs";
3321
+ dataType: "string";
3322
+ columnType: "SQLiteText";
3323
+ data: string;
3324
+ driverParam: string;
3325
+ notNull: true;
3326
+ hasDefault: false;
3327
+ isPrimaryKey: false;
3328
+ isAutoincrement: false;
3329
+ hasRuntimeDefault: false;
3330
+ enumValues: [string, ...string[]];
3331
+ baseColumn: never;
3332
+ identity: undefined;
3333
+ generated: undefined;
3334
+ }, {}, {
3335
+ length: number | undefined;
3336
+ }>;
3337
+ sourcePath: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3338
+ name: "source_path";
3339
+ tableName: "recipe_source_refs";
3340
+ dataType: "string";
3341
+ columnType: "SQLiteText";
3342
+ data: string;
3343
+ driverParam: string;
3344
+ notNull: true;
3345
+ hasDefault: false;
3346
+ isPrimaryKey: false;
3347
+ isAutoincrement: false;
3348
+ hasRuntimeDefault: false;
3349
+ enumValues: [string, ...string[]];
3350
+ baseColumn: never;
3351
+ identity: undefined;
3352
+ generated: undefined;
3353
+ }, {}, {
3354
+ length: number | undefined;
3355
+ }>;
3356
+ status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3357
+ name: "status";
3358
+ tableName: "recipe_source_refs";
3359
+ dataType: "string";
3360
+ columnType: "SQLiteText";
3361
+ data: string;
3362
+ driverParam: string;
3363
+ notNull: true;
3364
+ hasDefault: true;
3365
+ isPrimaryKey: false;
3366
+ isAutoincrement: false;
3367
+ hasRuntimeDefault: false;
3368
+ enumValues: [string, ...string[]];
3369
+ baseColumn: never;
3370
+ identity: undefined;
3371
+ generated: undefined;
3372
+ }, {}, {
3373
+ length: number | undefined;
3374
+ }>;
3375
+ newPath: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3376
+ name: "new_path";
3377
+ tableName: "recipe_source_refs";
3378
+ dataType: "string";
3379
+ columnType: "SQLiteText";
3380
+ data: string;
3381
+ driverParam: string;
3382
+ notNull: false;
3383
+ hasDefault: false;
3384
+ isPrimaryKey: false;
3385
+ isAutoincrement: false;
3386
+ hasRuntimeDefault: false;
3387
+ enumValues: [string, ...string[]];
3388
+ baseColumn: never;
3389
+ identity: undefined;
3390
+ generated: undefined;
3391
+ }, {}, {
3392
+ length: number | undefined;
3393
+ }>;
3394
+ verifiedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3395
+ name: "verified_at";
3396
+ tableName: "recipe_source_refs";
3397
+ dataType: "number";
3398
+ columnType: "SQLiteInteger";
3399
+ data: number;
3400
+ driverParam: number;
3401
+ notNull: true;
3402
+ hasDefault: false;
3403
+ isPrimaryKey: false;
3404
+ isAutoincrement: false;
3405
+ hasRuntimeDefault: false;
3406
+ enumValues: undefined;
3407
+ baseColumn: never;
3408
+ identity: undefined;
3409
+ generated: undefined;
3410
+ }, {}, {}>;
3411
+ };
3412
+ dialect: "sqlite";
3413
+ }>;
@@ -329,3 +329,13 @@ export const evolutionProposals = sqliteTable('evolution_proposals', {
329
329
  index('idx_ep_expires').on(table.expiresAt),
330
330
  index('idx_ep_source').on(table.source),
331
331
  ]);
332
+ // ═══════════════════════════════════════════════════════════════
333
+ // 17. recipe_source_refs — Recipe 来源引用桥接表 (可信度证据链)
334
+ // ═══════════════════════════════════════════════════════════════
335
+ export const recipeSourceRefs = sqliteTable('recipe_source_refs', {
336
+ recipeId: text('recipe_id').notNull(),
337
+ sourcePath: text('source_path').notNull(),
338
+ status: text('status').notNull().default('active'),
339
+ newPath: text('new_path'),
340
+ verifiedAt: integer('verified_at').notNull(),
341
+ }, (table) => [index('idx_rsr_path').on(table.sourcePath), index('idx_rsr_status').on(table.status)]);
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Migration 005 — Recipe Source References 桥接表
3
+ *
4
+ * 存储 Recipe 的 reasoning.sources 路径引用及其健康状态:
5
+ * - active: 文件存在,路径有效
6
+ * - renamed: 文件已移动到 new_path,等待修复
7
+ * - stale: 路径失效,无法自动修复
8
+ */
9
+ export default function migrate(db: import('better-sqlite3').Database): void;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Migration 005 — Recipe Source References 桥接表
3
+ *
4
+ * 存储 Recipe 的 reasoning.sources 路径引用及其健康状态:
5
+ * - active: 文件存在,路径有效
6
+ * - renamed: 文件已移动到 new_path,等待修复
7
+ * - stale: 路径失效,无法自动修复
8
+ */
9
+ export default function migrate(db) {
10
+ db.exec(`
11
+ CREATE TABLE IF NOT EXISTS recipe_source_refs (
12
+ recipe_id TEXT NOT NULL,
13
+ source_path TEXT NOT NULL,
14
+ status TEXT NOT NULL DEFAULT 'active',
15
+ new_path TEXT,
16
+ verified_at INTEGER NOT NULL,
17
+ PRIMARY KEY (recipe_id, source_path),
18
+ FOREIGN KEY (recipe_id) REFERENCES knowledge_entries(id) ON DELETE CASCADE
19
+ );
20
+
21
+ CREATE INDEX IF NOT EXISTS idx_rsr_path ON recipe_source_refs(source_path);
22
+ CREATE INDEX IF NOT EXISTS idx_rsr_status ON recipe_source_refs(status);
23
+ `);
24
+ }
@@ -121,8 +121,13 @@ export class HnswVectorAdapter extends VectorStore {
121
121
  // 迁移完成, 数据已加载到内存
122
122
  await this.#persist();
123
123
  }
124
- // 初始化 WAL (即使是空索引也创建, 以便后续操作写 WAL)
124
+ // 初始化 WAL + replay 未刷盘操作 (即使是空索引也创建, 以便后续操作写 WAL)
125
125
  this.#initWal();
126
+ const { replayed } = this.#wal?.recover() || { replayed: 0 };
127
+ if (replayed > 0) {
128
+ this.#dirty = true;
129
+ await this.#persist();
130
+ }
126
131
  }
127
132
  /**
128
133
  * 同步初始化 (兼容 JsonVectorAdapter)
@@ -171,8 +176,19 @@ export class HnswVectorAdapter extends VectorStore {
171
176
  }
172
177
  // 同步迁移: 读取 JSON 索引并加载到内存
173
178
  this.#syncMigrateFromJson();
174
- // 初始化 WAL
179
+ // 初始化 WAL + replay 未刷盘操作
175
180
  this.#initWal();
181
+ const { replayed } = this.#wal?.recover() || { replayed: 0 };
182
+ if (replayed > 0) {
183
+ this.#dirty = true;
184
+ BinaryPersistence.save(this.#indexPath, {
185
+ index: this.#index,
186
+ quantizer: this.#quantizer,
187
+ metadata: this.#metadata,
188
+ contents: this.#contents,
189
+ });
190
+ this.#dirty = false;
191
+ }
176
192
  }
177
193
  /** 同步从 JSON 索引迁移 (用于 initSync 路径) */
178
194
  #syncMigrateFromJson() {
@@ -130,6 +130,8 @@ export class ServiceContainer {
130
130
  }
131
131
  // v3.3: 初始化 VectorService(绑定 EventBus 事件监听)
132
132
  await VectorModule.initializeVectorService(this);
133
+ // v3.4: 初始化 Knowledge 服务(绑定 EventBus → SearchEngine.refreshIndex + sourceRefs)
134
+ KnowledgeModule.initializeKnowledgeServices(this);
133
135
  this.logger.info('Service container initialized successfully');
134
136
  }
135
137
  catch (error) {
@@ -9,3 +9,8 @@
9
9
  */
10
10
  import type { ServiceContainer } from '../ServiceContainer.js';
11
11
  export declare function register(c: ServiceContainer): void;
12
+ /**
13
+ * 初始化知识服务(在容器初始化后调用)
14
+ * 绑定 EventBus → SearchEngine.refreshIndex() + recipe_source_refs 填充
15
+ */
16
+ export declare function initializeKnowledgeServices(c: ServiceContainer): void;