autosnippet 3.3.0 → 3.3.3

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 (245) hide show
  1. package/dashboard/dist/assets/icons-BJ2mUBi8.js +1 -0
  2. package/dashboard/dist/assets/index-B659K9t5.js +128 -0
  3. package/dashboard/dist/assets/index-NCm40PMD.css +1 -0
  4. package/dashboard/dist/index.html +3 -3
  5. package/dist/bin/cli.d.ts +1 -0
  6. package/dist/bin/cli.js +284 -142
  7. package/dist/lib/agent/context/ExplorationTracker.d.ts +2 -0
  8. package/dist/lib/agent/context/ExplorationTracker.js +21 -3
  9. package/dist/lib/agent/core/ToolExecutionPipeline.d.ts +3 -1
  10. package/dist/lib/agent/core/ToolExecutionPipeline.js +8 -1
  11. package/dist/lib/agent/forge/DynamicComposer.d.ts +58 -0
  12. package/dist/lib/agent/forge/DynamicComposer.js +99 -0
  13. package/dist/lib/agent/forge/SandboxRunner.d.ts +60 -0
  14. package/dist/lib/agent/forge/SandboxRunner.js +251 -0
  15. package/dist/lib/agent/forge/TemporaryToolRegistry.d.ts +76 -0
  16. package/dist/lib/agent/forge/TemporaryToolRegistry.js +154 -0
  17. package/dist/lib/agent/forge/ToolForge.d.ts +92 -0
  18. package/dist/lib/agent/forge/ToolForge.js +239 -0
  19. package/dist/lib/agent/forge/ToolRequirementAnalyzer.d.ts +44 -0
  20. package/dist/lib/agent/forge/ToolRequirementAnalyzer.js +119 -0
  21. package/dist/lib/agent/tools/ToolRegistry.d.ts +2 -0
  22. package/dist/lib/agent/tools/ToolRegistry.js +4 -0
  23. package/dist/lib/agent/tools/composite.js +0 -1
  24. package/dist/lib/agent/tools/index.d.ts +2 -50
  25. package/dist/lib/agent/tools/index.js +2 -3
  26. package/dist/lib/agent/tools/lifecycle.d.ts +1 -58
  27. package/dist/lib/agent/tools/lifecycle.js +2 -75
  28. package/dist/lib/cli/KnowledgeSyncService.d.ts +26 -0
  29. package/dist/lib/cli/KnowledgeSyncService.js +33 -1
  30. package/dist/lib/cli/deploy/FileManifest.d.ts +0 -21
  31. package/dist/lib/cli/deploy/FileManifest.js +0 -11
  32. package/dist/lib/domain/knowledge/KnowledgeEntry.d.ts +10 -0
  33. package/dist/lib/domain/knowledge/KnowledgeEntry.js +2 -0
  34. package/dist/lib/domain/knowledge/Lifecycle.d.ts +19 -2
  35. package/dist/lib/domain/knowledge/Lifecycle.js +32 -6
  36. package/dist/lib/domain/knowledge/UnifiedValidator.d.ts +1 -5
  37. package/dist/lib/domain/knowledge/UnifiedValidator.js +7 -44
  38. package/dist/lib/domain/knowledge/values/Stats.d.ts +29 -0
  39. package/dist/lib/domain/knowledge/values/Stats.js +41 -0
  40. package/dist/lib/external/mcp/McpServer.d.ts +19 -38
  41. package/dist/lib/external/mcp/McpServer.js +145 -117
  42. package/dist/lib/external/mcp/autoApproveInjector.js +0 -2
  43. package/dist/lib/external/mcp/handlers/bootstrap/MissionBriefingBuilder.d.ts +26 -1
  44. package/dist/lib/external/mcp/handlers/bootstrap/MissionBriefingBuilder.js +41 -0
  45. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/orchestrator.js +49 -0
  46. package/dist/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.d.ts +3 -0
  47. package/dist/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.js +27 -0
  48. package/dist/lib/external/mcp/handlers/bootstrap/skills.js +1 -1
  49. package/dist/lib/external/mcp/handlers/bootstrap-external.js +1 -0
  50. package/dist/lib/external/mcp/handlers/bootstrap-internal.js +2 -0
  51. package/dist/lib/external/mcp/handlers/browse.d.ts +1 -0
  52. package/dist/lib/external/mcp/handlers/browse.js +2 -1
  53. package/dist/lib/external/mcp/handlers/consolidated.d.ts +117 -6
  54. package/dist/lib/external/mcp/handlers/consolidated.js +251 -71
  55. package/dist/lib/external/mcp/handlers/guard.d.ts +150 -0
  56. package/dist/lib/external/mcp/handlers/guard.js +239 -5
  57. package/dist/lib/external/mcp/handlers/knowledge.d.ts +0 -29
  58. package/dist/lib/external/mcp/handlers/knowledge.js +1 -76
  59. package/dist/lib/external/mcp/handlers/panorama.d.ts +36 -0
  60. package/dist/lib/external/mcp/handlers/panorama.js +156 -0
  61. package/dist/lib/external/mcp/handlers/system.d.ts +2 -54
  62. package/dist/lib/external/mcp/handlers/system.js +3 -113
  63. package/dist/lib/external/mcp/handlers/task.d.ts +13 -24
  64. package/dist/lib/external/mcp/handlers/task.js +218 -557
  65. package/dist/lib/external/mcp/handlers/types.d.ts +91 -8
  66. package/dist/lib/external/mcp/handlers/types.js +18 -1
  67. package/dist/lib/external/mcp/handlers/wiki-external.d.ts +18 -1
  68. package/dist/lib/external/mcp/handlers/wiki-external.js +16 -1
  69. package/dist/lib/external/mcp/tools.d.ts +18 -24
  70. package/dist/lib/external/mcp/tools.js +132 -159
  71. package/dist/lib/http/HttpServer.js +52 -0
  72. package/dist/lib/http/middleware/validate.js +7 -3
  73. package/dist/lib/http/routes/audit.d.ts +8 -0
  74. package/dist/lib/http/routes/audit.js +51 -0
  75. package/dist/lib/http/routes/guardReport.d.ts +10 -0
  76. package/dist/lib/http/routes/guardReport.js +143 -0
  77. package/dist/lib/http/routes/knowledge.js +32 -1
  78. package/dist/lib/http/routes/panorama.d.ts +11 -0
  79. package/dist/lib/http/routes/panorama.js +322 -0
  80. package/dist/lib/http/routes/signals.d.ts +10 -0
  81. package/dist/lib/http/routes/signals.js +104 -0
  82. package/dist/lib/http/routes/task.d.ts +2 -3
  83. package/dist/lib/http/routes/task.js +17 -347
  84. package/dist/lib/http/routes/violations.js +1 -1
  85. package/dist/lib/infrastructure/audit/AuditLogger.d.ts +6 -1
  86. package/dist/lib/infrastructure/audit/AuditLogger.js +14 -1
  87. package/dist/lib/infrastructure/database/drizzle/schema.d.ts +202 -504
  88. package/dist/lib/infrastructure/database/drizzle/schema.js +38 -69
  89. package/dist/lib/infrastructure/database/migrations/004_evolution_proposals.d.ts +8 -0
  90. package/dist/lib/infrastructure/database/migrations/004_evolution_proposals.js +43 -0
  91. package/dist/lib/infrastructure/database/migrations/005_recipe_source_refs.d.ts +9 -0
  92. package/dist/lib/infrastructure/database/migrations/005_recipe_source_refs.js +24 -0
  93. package/dist/lib/infrastructure/logging/Logger.d.ts +2 -0
  94. package/dist/lib/infrastructure/logging/Logger.js +34 -7
  95. package/dist/lib/infrastructure/monitoring/ErrorTracker.js +3 -1
  96. package/dist/lib/infrastructure/monitoring/PerformanceMonitor.d.ts +2 -2
  97. package/dist/lib/infrastructure/monitoring/PerformanceMonitor.js +12 -10
  98. package/dist/lib/infrastructure/notification/LarkNotifier.d.ts +24 -0
  99. package/dist/lib/infrastructure/notification/LarkNotifier.js +97 -0
  100. package/dist/lib/infrastructure/report/ReportStore.d.ts +45 -0
  101. package/dist/lib/infrastructure/report/ReportStore.js +133 -0
  102. package/dist/lib/infrastructure/signal/SignalAggregator.d.ts +18 -0
  103. package/dist/lib/infrastructure/signal/SignalAggregator.js +84 -0
  104. package/dist/lib/infrastructure/signal/SignalBridge.d.ts +13 -0
  105. package/dist/lib/infrastructure/signal/SignalBridge.js +20 -0
  106. package/dist/lib/infrastructure/signal/SignalBus.d.ts +63 -0
  107. package/dist/lib/infrastructure/signal/SignalBus.js +106 -0
  108. package/dist/lib/infrastructure/signal/SignalTraceWriter.d.ts +36 -0
  109. package/dist/lib/infrastructure/signal/SignalTraceWriter.js +130 -0
  110. package/dist/lib/infrastructure/vector/HnswVectorAdapter.js +18 -2
  111. package/dist/lib/injection/ServiceContainer.js +8 -0
  112. package/dist/lib/injection/ServiceMap.d.ts +16 -10
  113. package/dist/lib/injection/modules/AgentModule.d.ts +1 -1
  114. package/dist/lib/injection/modules/AgentModule.js +7 -1
  115. package/dist/lib/injection/modules/AppModule.d.ts +1 -1
  116. package/dist/lib/injection/modules/AppModule.js +4 -13
  117. package/dist/lib/injection/modules/GuardModule.js +27 -2
  118. package/dist/lib/injection/modules/InfraModule.d.ts +0 -1
  119. package/dist/lib/injection/modules/InfraModule.js +9 -7
  120. package/dist/lib/injection/modules/KnowledgeModule.d.ts +5 -0
  121. package/dist/lib/injection/modules/KnowledgeModule.js +131 -0
  122. package/dist/lib/injection/modules/PanoramaModule.d.ts +18 -0
  123. package/dist/lib/injection/modules/PanoramaModule.js +76 -0
  124. package/dist/lib/injection/modules/SignalModule.d.ts +10 -0
  125. package/dist/lib/injection/modules/SignalModule.js +84 -0
  126. package/dist/lib/repository/knowledge/KnowledgeRepository.impl.d.ts +1 -0
  127. package/dist/lib/repository/knowledge/KnowledgeRepository.impl.js +6 -0
  128. package/dist/lib/service/bootstrap/BootstrapTaskManager.d.ts +3 -1
  129. package/dist/lib/service/bootstrap/BootstrapTaskManager.js +20 -1
  130. package/dist/lib/service/bootstrap/UiStartupTasks.d.ts +45 -0
  131. package/dist/lib/service/bootstrap/UiStartupTasks.js +101 -0
  132. package/dist/lib/service/delivery/AgentInstructionsGenerator.js +4 -5
  133. package/dist/lib/service/delivery/CursorDeliveryPipeline.d.ts +3 -1
  134. package/dist/lib/service/delivery/CursorDeliveryPipeline.js +13 -10
  135. package/dist/lib/service/delivery/RulesGenerator.js +3 -2
  136. package/dist/lib/service/evolution/ConsolidationAdvisor.d.ts +114 -0
  137. package/dist/lib/service/evolution/ConsolidationAdvisor.js +542 -0
  138. package/dist/lib/service/evolution/ContradictionDetector.d.ts +54 -0
  139. package/dist/lib/service/evolution/ContradictionDetector.js +253 -0
  140. package/dist/lib/service/evolution/DecayDetector.d.ts +71 -0
  141. package/dist/lib/service/evolution/DecayDetector.js +244 -0
  142. package/dist/lib/service/evolution/EnhancementSuggester.d.ts +38 -0
  143. package/dist/lib/service/evolution/EnhancementSuggester.js +220 -0
  144. package/dist/lib/service/evolution/KnowledgeMetabolism.d.ts +82 -0
  145. package/dist/lib/service/evolution/KnowledgeMetabolism.js +167 -0
  146. package/dist/lib/service/evolution/RedundancyAnalyzer.d.ts +53 -0
  147. package/dist/lib/service/evolution/RedundancyAnalyzer.js +210 -0
  148. package/dist/lib/service/evolution/StagingManager.d.ts +57 -0
  149. package/dist/lib/service/evolution/StagingManager.js +201 -0
  150. package/dist/lib/service/guard/ComplianceReporter.d.ts +42 -2
  151. package/dist/lib/service/guard/ComplianceReporter.js +43 -5
  152. package/dist/lib/service/guard/CoverageAnalyzer.d.ts +54 -0
  153. package/dist/lib/service/guard/CoverageAnalyzer.js +149 -0
  154. package/dist/lib/service/guard/GuardCheckEngine.d.ts +42 -0
  155. package/dist/lib/service/guard/GuardCheckEngine.js +465 -14
  156. package/dist/lib/service/guard/GuardFeedbackLoop.d.ts +3 -0
  157. package/dist/lib/service/guard/GuardFeedbackLoop.js +9 -0
  158. package/dist/lib/service/guard/ReverseGuard.d.ts +73 -0
  159. package/dist/lib/service/guard/ReverseGuard.js +256 -0
  160. package/dist/lib/service/guard/RuleLearner.d.ts +12 -0
  161. package/dist/lib/service/guard/RuleLearner.js +38 -0
  162. package/dist/lib/service/guard/UncertaintyCollector.d.ts +83 -0
  163. package/dist/lib/service/guard/UncertaintyCollector.js +149 -0
  164. package/dist/lib/service/guard/ViolationsStore.d.ts +1 -0
  165. package/dist/lib/service/guard/ViolationsStore.js +33 -3
  166. package/dist/lib/service/knowledge/ConfidenceRouter.d.ts +13 -0
  167. package/dist/lib/service/knowledge/ConfidenceRouter.js +14 -0
  168. package/dist/lib/service/knowledge/KnowledgeService.js +22 -4
  169. package/dist/lib/service/knowledge/SourceRefReconciler.d.ts +68 -0
  170. package/dist/lib/service/knowledge/SourceRefReconciler.js +309 -0
  171. package/dist/lib/service/panorama/CouplingAnalyzer.d.ts +27 -0
  172. package/dist/lib/service/panorama/CouplingAnalyzer.js +192 -0
  173. package/dist/lib/service/panorama/DimensionAnalyzer.d.ts +28 -0
  174. package/dist/lib/service/panorama/DimensionAnalyzer.js +320 -0
  175. package/dist/lib/service/panorama/LayerInferrer.d.ts +19 -0
  176. package/dist/lib/service/panorama/LayerInferrer.js +182 -0
  177. package/dist/lib/service/panorama/ModuleDiscoverer.d.ts +24 -0
  178. package/dist/lib/service/panorama/ModuleDiscoverer.js +185 -0
  179. package/dist/lib/service/panorama/PanoramaAggregator.d.ts +29 -0
  180. package/dist/lib/service/panorama/PanoramaAggregator.js +228 -0
  181. package/dist/lib/service/panorama/PanoramaScanner.d.ts +52 -0
  182. package/dist/lib/service/panorama/PanoramaScanner.js +188 -0
  183. package/dist/lib/service/panorama/PanoramaService.d.ts +125 -0
  184. package/dist/lib/service/panorama/PanoramaService.js +363 -0
  185. package/dist/lib/service/panorama/PanoramaTypes.d.ts +134 -0
  186. package/dist/lib/service/panorama/PanoramaTypes.js +6 -0
  187. package/dist/lib/service/panorama/RoleRefiner.d.ts +48 -0
  188. package/dist/lib/service/panorama/RoleRefiner.js +535 -0
  189. package/dist/lib/service/search/BM25Scorer.d.ts +2 -2
  190. package/dist/lib/service/search/CoarseRanker.d.ts +7 -6
  191. package/dist/lib/service/search/CoarseRanker.js +11 -10
  192. package/dist/lib/service/search/FieldWeightedScorer.d.ts +81 -0
  193. package/dist/lib/service/search/FieldWeightedScorer.js +318 -0
  194. package/dist/lib/service/search/MultiSignalRanker.d.ts +3 -2
  195. package/dist/lib/service/search/MultiSignalRanker.js +17 -1
  196. package/dist/lib/service/search/SearchEngine.d.ts +9 -7
  197. package/dist/lib/service/search/SearchEngine.js +67 -10
  198. package/dist/lib/service/search/SearchTypes.d.ts +25 -3
  199. package/dist/lib/service/search/SearchTypes.js +6 -1
  200. package/dist/lib/service/signal/HitRecorder.d.ts +68 -0
  201. package/dist/lib/service/signal/HitRecorder.js +173 -0
  202. package/dist/lib/service/skills/SignalCollector.d.ts +3 -1
  203. package/dist/lib/service/skills/SignalCollector.js +31 -1
  204. package/dist/lib/service/task/IntentExtractor.d.ts +66 -0
  205. package/dist/lib/service/task/IntentExtractor.js +256 -0
  206. package/dist/lib/service/task/PrimeSearchPipeline.d.ts +54 -0
  207. package/dist/lib/service/task/PrimeSearchPipeline.js +113 -0
  208. package/dist/lib/service/vector/VectorService.d.ts +3 -0
  209. package/dist/lib/service/vector/VectorService.js +38 -4
  210. package/dist/lib/shared/schemas/mcp-tools.d.ts +41 -96
  211. package/dist/lib/shared/schemas/mcp-tools.js +59 -119
  212. package/dist/scripts/analyze-signals.d.ts +20 -0
  213. package/dist/scripts/analyze-signals.js +155 -0
  214. package/dist/scripts/diagnose-mcp.js +1 -1
  215. package/package.json +1 -1
  216. package/skills/autosnippet-create/SKILL.md +98 -89
  217. package/skills/autosnippet-devdocs/SKILL.md +55 -57
  218. package/templates/claude-code/hooks/autosnippet-session.sh +10 -15
  219. package/templates/cursor-hooks/hooks/session-start.sh +1 -1
  220. package/templates/guard-ci.yml +2 -2
  221. package/templates/instructions/agent-static.md +2 -1
  222. package/templates/instructions/conventions.md +5 -6
  223. package/templates/recipes-setup/README.md +1 -2
  224. package/templates/recipes-setup/_template.md +39 -39
  225. package/dashboard/dist/assets/icons-BofcEZ3f.js +0 -1
  226. package/dashboard/dist/assets/index-D0whuycy.css +0 -1
  227. package/dashboard/dist/assets/index-SiN1GChm.js +0 -128
  228. package/dist/lib/domain/task/Task.d.ts +0 -140
  229. package/dist/lib/domain/task/Task.js +0 -254
  230. package/dist/lib/domain/task/TaskDependency.d.ts +0 -23
  231. package/dist/lib/domain/task/TaskDependency.js +0 -34
  232. package/dist/lib/domain/task/TaskIdGenerator.d.ts +0 -40
  233. package/dist/lib/domain/task/TaskIdGenerator.js +0 -75
  234. package/dist/lib/domain/task/index.d.ts +0 -4
  235. package/dist/lib/domain/task/index.js +0 -4
  236. package/dist/lib/infrastructure/database/migrations/002_add_tasks.d.ts +0 -11
  237. package/dist/lib/infrastructure/database/migrations/002_add_tasks.js +0 -86
  238. package/dist/lib/repository/task/TaskRepository.impl.d.ts +0 -171
  239. package/dist/lib/repository/task/TaskRepository.impl.js +0 -347
  240. package/dist/lib/service/task/TaskGraphService.d.ts +0 -222
  241. package/dist/lib/service/task/TaskGraphService.js +0 -597
  242. package/dist/lib/service/task/TaskKnowledgeBridge.d.ts +0 -95
  243. package/dist/lib/service/task/TaskKnowledgeBridge.js +0 -298
  244. package/dist/lib/service/task/TaskReadyEngine.d.ts +0 -84
  245. package/dist/lib/service/task/TaskReadyEngine.js +0 -115
@@ -133,6 +133,18 @@ export async function guardAuditFiles(ctx, args) {
133
133
  ...(result.crossFileViolations?.length
134
134
  ? { crossFileViolations: result.crossFileViolations }
135
135
  : {}),
136
+ // uncertain 消费链路 — 结构化上抛给 Agent
137
+ ...(result.capabilityReport
138
+ ? {
139
+ capabilityReport: result.capabilityReport,
140
+ uncertainSummary: {
141
+ total: result.capabilityReport.uncertainResults.length,
142
+ byLayer: _groupBy(result.capabilityReport.uncertainResults, 'layer'),
143
+ byReason: _groupBy(result.capabilityReport.uncertainResults, 'reason'),
144
+ },
145
+ boundaries: result.capabilityReport.boundaries,
146
+ }
147
+ : {}),
136
148
  },
137
149
  meta: { tool: 'autosnippet_guard' },
138
150
  });
@@ -152,7 +164,7 @@ export async function guardAuditFiles(ctx, args) {
152
164
  * @param args { files?: string[] }
153
165
  */
154
166
  export async function guardReview(ctx, args) {
155
- const { GuardCheckEngine, detectLanguage } = await import('#service/guard/GuardCheckEngine.js');
167
+ const { GuardCheckEngine } = await import('#service/guard/GuardCheckEngine.js');
156
168
  const projectRoot = resolveProjectRoot(ctx.container);
157
169
  // 轮次追踪(基于 projectRoot,不绑定 task)
158
170
  const round = (_reviewRounds.get(projectRoot) || 0) + 1;
@@ -203,16 +215,21 @@ export async function guardReview(ctx, args) {
203
215
  // 3. 创建引擎,注入 Enhancement Pack
204
216
  const engine = _getOrCreateEngine(ctx, GuardCheckEngine);
205
217
  await _injectEnhancementGuardRules(engine, ctx);
206
- // 4. 逐文件检查
218
+ // 4. 逐文件检查(使用 auditFile 以捕获 uncertain)
207
219
  const results = [];
208
220
  let totalViolations = 0;
209
221
  let totalErrors = 0;
210
222
  let totalWarnings = 0;
223
+ const allUncertainResults = [];
211
224
  for (const fp of filePaths) {
212
225
  try {
213
226
  const code = await readFile(fp, 'utf8');
214
- const lang = detectLanguage(fp);
215
- const violations = engine.checkCode(code, lang, { filePath: fp });
227
+ const auditResult = engine.auditFile(fp, code);
228
+ const violations = auditResult.violations;
229
+ // 收集 uncertain
230
+ if (auditResult.uncertainResults?.length) {
231
+ allUncertainResults.push(...auditResult.uncertainResults);
232
+ }
216
233
  const fileSummary = {
217
234
  total: violations.length,
218
235
  errors: violations.filter((v) => v.severity === 'error').length,
@@ -242,7 +259,12 @@ export async function guardReview(ctx, args) {
242
259
  }
243
260
  return base;
244
261
  });
245
- results.push({ filePath: fp, language: lang, violations: enriched, summary: fileSummary });
262
+ results.push({
263
+ filePath: fp,
264
+ language: auditResult.language,
265
+ violations: enriched,
266
+ summary: fileSummary,
267
+ });
246
268
  }
247
269
  catch (err) {
248
270
  results.push({
@@ -312,6 +334,17 @@ export async function guardReview(ctx, args) {
312
334
  warnings: totalWarnings,
313
335
  filesChecked: filePaths.length,
314
336
  },
337
+ // uncertain 消费链路 — 结构化上抛给 Agent
338
+ ...(allUncertainResults.length > 0
339
+ ? {
340
+ uncertainSummary: {
341
+ total: allUncertainResults.length,
342
+ byLayer: _groupBy(allUncertainResults, 'layer'),
343
+ byReason: _groupBy(allUncertainResults, 'reason'),
344
+ },
345
+ uncertainResults: allUncertainResults,
346
+ }
347
+ : {}),
315
348
  },
316
349
  message,
317
350
  meta: { tool: 'autosnippet_guard', mode: 'review' },
@@ -562,6 +595,15 @@ export async function scanProject(ctx, args) {
562
595
  });
563
596
  }
564
597
  // ─── 内部辅助 ─────────────────────────────────────────────
598
+ /** 按字段值分组计数 */
599
+ function _groupBy(arr, key) {
600
+ const counts = {};
601
+ for (const item of arr) {
602
+ const k = String(item[key] ?? 'unknown');
603
+ counts[k] = (counts[k] || 0) + 1;
604
+ }
605
+ return counts;
606
+ }
565
607
  /**
566
608
  * 获取 DI 容器中的 GuardCheckEngine 单例,回退到新建实例
567
609
  * 优先复用 DI 单例以保持 externalRules / cache 的跨调用一致性
@@ -618,3 +660,195 @@ async function _injectEnhancementGuardRules(engine, ctx) {
618
660
  /* Enhancement registry not available — non-critical */
619
661
  }
620
662
  }
663
+ /**
664
+ * 对所有 active rule Recipe 执行反向验证:
665
+ * - 检查 coreCode 引用的符号是否还存在
666
+ * - 检查 guard pattern 匹配率是否骤降
667
+ */
668
+ export async function guardReverseAudit(ctx, args) {
669
+ const { ReverseGuard } = await import('#service/guard/ReverseGuard.js');
670
+ const { collectSourceFilesWithContent } = await import('#service/guard/SourceFileCollector.js');
671
+ const projectRoot = resolveProjectRoot(ctx.container);
672
+ // 尝试从 DI 获取,回退到新建
673
+ let reverseGuard;
674
+ try {
675
+ reverseGuard = ctx.container.get('reverseGuard');
676
+ }
677
+ catch {
678
+ const db = ctx.container.get('database');
679
+ reverseGuard = new ReverseGuard(db.getDb());
680
+ }
681
+ const maxFiles = args.maxFiles || 200;
682
+ const projectFiles = await collectSourceFilesWithContent(projectRoot, { maxFiles });
683
+ const results = reverseGuard.auditAllRules(projectFiles);
684
+ const drifts = reverseGuard.getDriftResults(results);
685
+ return envelope({
686
+ success: true,
687
+ data: {
688
+ totalRecipes: results.length,
689
+ healthy: results.filter((r) => r.recommendation === 'healthy').length,
690
+ investigate: results.filter((r) => r.recommendation === 'investigate').length,
691
+ decay: results.filter((r) => r.recommendation === 'decay').length,
692
+ drifts: drifts.map((d) => ({
693
+ recipeId: d.recipeId,
694
+ title: d.title,
695
+ recommendation: d.recommendation,
696
+ signals: d.signals,
697
+ })),
698
+ allResults: results.map((r) => ({
699
+ recipeId: r.recipeId,
700
+ title: r.title,
701
+ recommendation: r.recommendation,
702
+ signalCount: r.signals.length,
703
+ })),
704
+ },
705
+ meta: { tool: 'autosnippet_guard', operation: 'reverse_audit' },
706
+ });
707
+ }
708
+ /**
709
+ * 计算模块级 Guard 规则覆盖率矩阵
710
+ */
711
+ export async function guardCoverageMatrix(ctx, _args) {
712
+ const { CoverageAnalyzer } = await import('#service/guard/CoverageAnalyzer.js');
713
+ const projectRoot = resolveProjectRoot(ctx.container);
714
+ // 尝试从 DI 获取,回退到新建
715
+ let analyzer;
716
+ try {
717
+ analyzer = ctx.container.get('coverageAnalyzer');
718
+ }
719
+ catch {
720
+ const db = ctx.container.get('database');
721
+ analyzer = new CoverageAnalyzer(db.getDb());
722
+ }
723
+ // 构建 moduleFiles 映射 — 从 Panorama 或目录结构推断
724
+ const moduleFiles = await _buildModuleFiles(ctx, projectRoot);
725
+ const matrix = analyzer.analyze(moduleFiles);
726
+ return envelope({
727
+ success: true,
728
+ data: {
729
+ overallCoverage: matrix.overallCoverage,
730
+ zeroModules: matrix.zeroModules,
731
+ lowModules: matrix.lowModules,
732
+ modules: matrix.modules,
733
+ },
734
+ meta: { tool: 'autosnippet_guard', operation: 'coverage_matrix' },
735
+ });
736
+ }
737
+ /**
738
+ * 生成 3D 合规报告(compliance + coverage + confidence)
739
+ * 包含完整 uncertain 消费数据
740
+ */
741
+ export async function guardComplianceReport(ctx, _args) {
742
+ const { ComplianceReporter } = await import('#service/guard/ComplianceReporter.js');
743
+ const projectRoot = resolveProjectRoot(ctx.container);
744
+ // 尝试从 DI 获取,回退到新建
745
+ let reporter;
746
+ try {
747
+ reporter = ctx.container.get('complianceReporter');
748
+ }
749
+ catch {
750
+ const { GuardCheckEngine } = await import('#service/guard/GuardCheckEngine.js');
751
+ const engine = _getOrCreateEngine(ctx, GuardCheckEngine);
752
+ await _injectEnhancementGuardRules(engine, ctx);
753
+ // ComplianceReporter(engine, violationsStore, ruleLearner, exclusionManager, config)
754
+ let violationsStore = null;
755
+ let ruleLearner = null;
756
+ let exclusionManager = null;
757
+ try {
758
+ violationsStore = ctx.container.get('violationsStore');
759
+ }
760
+ catch {
761
+ /* optional */
762
+ }
763
+ try {
764
+ ruleLearner = ctx.container.get('ruleLearner');
765
+ }
766
+ catch {
767
+ /* optional */
768
+ }
769
+ try {
770
+ exclusionManager = ctx.container.get('exclusionManager');
771
+ }
772
+ catch {
773
+ /* optional */
774
+ }
775
+ reporter = new ComplianceReporter(engine, violationsStore, ruleLearner, exclusionManager);
776
+ }
777
+ const report = await reporter.generate(projectRoot);
778
+ return envelope({
779
+ success: true,
780
+ data: {
781
+ scores: {
782
+ compliance: report.complianceScore,
783
+ coverage: report.coverageScore,
784
+ confidence: report.confidenceScore,
785
+ },
786
+ qualityGate: report.qualityGate,
787
+ summary: report.summary,
788
+ uncertainSummary: report.uncertainSummary || null,
789
+ boundaries: report.boundaries || [],
790
+ topViolations: (report.topViolations || []).slice(0, 10),
791
+ trend: report.trend || null,
792
+ },
793
+ meta: { tool: 'autosnippet_guard', operation: 'compliance_report' },
794
+ });
795
+ }
796
+ /** 从 Panorama 或目录结构构建模块→文件映射 */
797
+ async function _buildModuleFiles(ctx, projectRoot) {
798
+ const moduleFiles = new Map();
799
+ try {
800
+ const panorama = ctx.container.get('panoramaService');
801
+ const overview = await panorama.getOverview();
802
+ if (overview?.modules) {
803
+ for (const mod of overview.modules) {
804
+ if (mod.files?.length > 0) {
805
+ moduleFiles.set(mod.name, mod.files);
806
+ }
807
+ }
808
+ }
809
+ }
810
+ catch {
811
+ /* PanoramaService not available */
812
+ }
813
+ if (moduleFiles.size === 0) {
814
+ const { readdirSync, existsSync } = await import('node:fs');
815
+ const srcDirs = ['Sources', 'BiliDili/Modules', 'src', 'lib'];
816
+ for (const dir of srcDirs) {
817
+ const fullDir = path.join(projectRoot, dir);
818
+ if (existsSync(fullDir)) {
819
+ for (const entry of readdirSync(fullDir, { withFileTypes: true })) {
820
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
821
+ const files = _walkSourceFiles(path.join(fullDir, entry.name));
822
+ if (files.length > 0) {
823
+ moduleFiles.set(entry.name, files);
824
+ }
825
+ }
826
+ }
827
+ }
828
+ }
829
+ }
830
+ return moduleFiles;
831
+ }
832
+ function _walkSourceFiles(dir) {
833
+ const files = [];
834
+ try {
835
+ const { readdirSync } = require('node:fs');
836
+ const walk = (d) => {
837
+ for (const e of readdirSync(d, { withFileTypes: true })) {
838
+ const fp = path.join(d, e.name);
839
+ if (e.isDirectory() && !e.name.startsWith('.')) {
840
+ walk(fp);
841
+ }
842
+ else if (e.isFile() &&
843
+ /\.(m|h|swift|mm|ts|js|py|java|kt|dart|rs|go|cs|rb)$/.test(e.name)) {
844
+ files.push(fp);
845
+ }
846
+ }
847
+ };
848
+ walk(dir);
849
+ }
850
+ catch {
851
+ /* directory read error */
852
+ }
853
+ return files;
854
+ }
@@ -75,33 +75,4 @@ export declare function knowledgeLifecycle(ctx: McpContext, args: {
75
75
  tool?: string | undefined;
76
76
  };
77
77
  }>;
78
- /**
79
- * 保存开发文档 (autosnippet_save_document)
80
- *
81
- * 精简入口:仅需 title + markdown。
82
- * 自动设置 knowledgeType='dev-document', kind='fact', source='agent'。
83
- * 不走 RecipeReadiness 检查(文档无需 doClause/trigger)。
84
- * 支持 autoApprove — 文档直接进入 active 状态。
85
- */
86
- export declare function saveDocument(ctx: McpContext, args: {
87
- title?: string;
88
- markdown?: string;
89
- description?: string;
90
- client_id?: string;
91
- source?: string;
92
- scope?: string;
93
- tags?: string[];
94
- [key: string]: unknown;
95
- }): Promise<{
96
- success: boolean;
97
- errorCode: string | null;
98
- message: string;
99
- data: unknown;
100
- meta: {
101
- source?: string | undefined;
102
- responseTimeMs?: number | undefined;
103
- version: string;
104
- tool?: string | undefined;
105
- };
106
- }>;
107
78
  export {};
@@ -258,80 +258,5 @@ export async function knowledgeLifecycle(ctx, args) {
258
258
  meta: { tool: 'autosnippet_knowledge_lifecycle' },
259
259
  });
260
260
  }
261
- // ─── 内部辅助 ──────────────────────────────────────────────
262
- /**
263
- * 保存开发文档 (autosnippet_save_document)
264
- *
265
- * 精简入口:仅需 title + markdown。
266
- * 自动设置 knowledgeType='dev-document', kind='fact', source='agent'。
267
- * 不走 RecipeReadiness 检查(文档无需 doClause/trigger)。
268
- * 支持 autoApprove — 文档直接进入 active 状态。
269
- */
270
- export async function saveDocument(ctx, args) {
271
- if (!args.title || !args.title.trim()) {
272
- throw new Error('title 必填');
273
- }
274
- if (!args.markdown || !args.markdown.trim()) {
275
- throw new Error('markdown 必填');
276
- }
277
- // 限流
278
- const blocked = await _checkRateLimit('autosnippet_save_document', args.client_id, ctx.container);
279
- if (blocked) {
280
- return blocked;
281
- }
282
- const service = ctx.container.get('knowledgeService');
283
- const data = {
284
- title: args.title.trim(),
285
- description: args.description || '',
286
- knowledgeType: 'dev-document',
287
- kind: 'fact',
288
- source: args.source || 'agent',
289
- scope: args.scope || 'project-specific',
290
- tags: args.tags || [],
291
- content: {
292
- markdown: args.markdown,
293
- pattern: '',
294
- },
295
- // 文档不需要 Cursor Delivery 字段
296
- trigger: '',
297
- doClause: '',
298
- dontClause: '',
299
- whenClause: '',
300
- topicHint: '',
301
- coreCode: '',
302
- // 基础推理
303
- reasoning: {
304
- whyStandard: 'Agent development document — preserved for team knowledge',
305
- sources: ['agent'],
306
- confidence: 0.8,
307
- },
308
- };
309
- // ── UnifiedValidator 校验(自动检测 document 模式)──
310
- const validator = new UnifiedValidator();
311
- const vr = validator.validate(data, { skipUniqueness: true });
312
- if (!vr.pass) {
313
- throw new Error(`文档校验失败: ${vr.errors.join('; ')}`);
314
- }
315
- const entry = await service.create(data, { userId: 'mcp' });
316
- // 自动发布(dev-document 不需要人工审核)
317
- try {
318
- await service.publish(entry.id, { userId: 'mcp' });
319
- }
320
- catch {
321
- // 发布失败保持 pending — 非阻塞
322
- }
323
- return envelope({
324
- success: true,
325
- data: {
326
- id: entry.id,
327
- lifecycle: 'active',
328
- title: entry.title,
329
- kind: 'fact',
330
- knowledgeType: 'dev-document',
331
- },
332
- message: `文档「${entry.title}」已保存到知识库。`,
333
- meta: { tool: 'autosnippet_save_document' },
334
- });
335
- }
336
- // ─── 内部辅助 ──────────────────────────────────────────────
261
+ // ─── (已删除: saveDocument — 已合并到 submit_knowledge 统一管线) ──
337
262
  // ─── (已删除: _toReadinessInput — 统一使用 UnifiedValidator) ──
@@ -0,0 +1,36 @@
1
+ /**
2
+ * MCP Handler — autosnippet_panorama
3
+ *
4
+ * Project panorama query tool with 8 operations:
5
+ * overview — project skeleton + layers + module roles
6
+ * module — single module detail + neighbors + recipes + file groups
7
+ * gaps — knowledge gaps (code without Recipes)
8
+ * health — panorama health (coverage + coupling + cycles)
9
+ * governance_cycle — full metabolism cycle (contradiction + redundancy + decay)
10
+ * decay_report — decay assessment report
11
+ * staging_check — staging entry check + auto-publish
12
+ * enhancement_suggestions — usage-data-based enhancement suggestions
13
+ *
14
+ * All read-only except governance_cycle and staging_check (which perform state transitions).
15
+ */
16
+ import type { McpContext } from './types.js';
17
+ interface PanoramaArgs {
18
+ operation?: string;
19
+ module?: string;
20
+ }
21
+ /**
22
+ * autosnippet_panorama — unified panorama query
23
+ */
24
+ export declare function panoramaHandler(ctx: McpContext, args: PanoramaArgs): Promise<{
25
+ success: boolean;
26
+ errorCode: string | null;
27
+ message: string;
28
+ data: unknown;
29
+ meta: {
30
+ source?: string | undefined;
31
+ responseTimeMs?: number | undefined;
32
+ version: string;
33
+ tool?: string | undefined;
34
+ };
35
+ }>;
36
+ export {};
@@ -0,0 +1,156 @@
1
+ /**
2
+ * MCP Handler — autosnippet_panorama
3
+ *
4
+ * Project panorama query tool with 8 operations:
5
+ * overview — project skeleton + layers + module roles
6
+ * module — single module detail + neighbors + recipes + file groups
7
+ * gaps — knowledge gaps (code without Recipes)
8
+ * health — panorama health (coverage + coupling + cycles)
9
+ * governance_cycle — full metabolism cycle (contradiction + redundancy + decay)
10
+ * decay_report — decay assessment report
11
+ * staging_check — staging entry check + auto-publish
12
+ * enhancement_suggestions — usage-data-based enhancement suggestions
13
+ *
14
+ * All read-only except governance_cycle and staging_check (which perform state transitions).
15
+ */
16
+ import { envelope } from '../envelope.js';
17
+ /**
18
+ * autosnippet_panorama — unified panorama query
19
+ */
20
+ export async function panoramaHandler(ctx, args) {
21
+ const op = args.operation || 'overview';
22
+ const panoramaService = ctx.container.get('panoramaService');
23
+ if (!panoramaService) {
24
+ return envelope({
25
+ success: false,
26
+ message: 'Panorama service not initialized',
27
+ meta: { tool: 'autosnippet_panorama' },
28
+ });
29
+ }
30
+ // Auto-ensure data is ready (triggers built-in scan when no data exists)
31
+ await panoramaService.ensureData();
32
+ switch (op) {
33
+ case 'overview': {
34
+ const overview = panoramaService.getOverview();
35
+ return envelope({
36
+ success: true,
37
+ data: overview,
38
+ meta: { tool: 'autosnippet_panorama' },
39
+ });
40
+ }
41
+ case 'module': {
42
+ const moduleName = args.module;
43
+ if (!moduleName) {
44
+ return envelope({
45
+ success: false,
46
+ message: 'operation=module requires the "module" parameter (module name)',
47
+ meta: { tool: 'autosnippet_panorama' },
48
+ });
49
+ }
50
+ const detail = panoramaService.getModule(moduleName);
51
+ if (!detail) {
52
+ return envelope({
53
+ success: false,
54
+ message: `Module not found: ${moduleName}`,
55
+ meta: { tool: 'autosnippet_panorama' },
56
+ });
57
+ }
58
+ return envelope({
59
+ success: true,
60
+ data: detail,
61
+ meta: { tool: 'autosnippet_panorama' },
62
+ });
63
+ }
64
+ case 'gaps': {
65
+ const gaps = panoramaService.getGaps();
66
+ return envelope({
67
+ success: true,
68
+ data: { gaps },
69
+ meta: { tool: 'autosnippet_panorama' },
70
+ });
71
+ }
72
+ case 'health': {
73
+ const health = panoramaService.getHealth();
74
+ return envelope({
75
+ success: true,
76
+ data: health,
77
+ meta: { tool: 'autosnippet_panorama' },
78
+ });
79
+ }
80
+ default:
81
+ // ── Governance operations (independent of panoramaService) ──
82
+ return handleGovernanceOps(ctx, op);
83
+ }
84
+ }
85
+ /* ────────────────────── Governance Handlers ────────────────────── */
86
+ async function handleGovernanceOps(ctx, op) {
87
+ switch (op) {
88
+ case 'governance_cycle': {
89
+ const metabolism = ctx.container.get('knowledgeMetabolism');
90
+ if (!metabolism) {
91
+ return envelope({
92
+ success: false,
93
+ message: 'Governance service not initialized (knowledgeMetabolism not registered)',
94
+ meta: { tool: 'autosnippet_panorama' },
95
+ });
96
+ }
97
+ const report = metabolism.runFullCycle();
98
+ return envelope({
99
+ success: true,
100
+ data: report,
101
+ meta: { tool: 'autosnippet_panorama', operation: 'governance_cycle' },
102
+ });
103
+ }
104
+ case 'decay_report': {
105
+ const decayDetector = ctx.container.get('decayDetector');
106
+ if (!decayDetector) {
107
+ return envelope({
108
+ success: false,
109
+ message: 'Decay detector not initialized (decayDetector not registered)',
110
+ meta: { tool: 'autosnippet_panorama' },
111
+ });
112
+ }
113
+ const results = decayDetector.scanAll();
114
+ return envelope({
115
+ success: true,
116
+ data: { results },
117
+ meta: { tool: 'autosnippet_panorama', operation: 'decay_report' },
118
+ });
119
+ }
120
+ case 'staging_check': {
121
+ const stagingManager = ctx.container.get('stagingManager');
122
+ if (!stagingManager) {
123
+ return envelope({
124
+ success: false,
125
+ message: 'Staging manager not initialized (stagingManager not registered)',
126
+ meta: { tool: 'autosnippet_panorama' },
127
+ });
128
+ }
129
+ const checkResult = stagingManager.checkAndPromote();
130
+ const currentStaging = stagingManager.listStaging();
131
+ return envelope({
132
+ success: true,
133
+ data: { checkResult, currentStaging },
134
+ meta: { tool: 'autosnippet_panorama', operation: 'staging_check' },
135
+ });
136
+ }
137
+ case 'enhancement_suggestions': {
138
+ const suggester = ctx.container.get('enhancementSuggester');
139
+ if (!suggester) {
140
+ return envelope({
141
+ success: false,
142
+ message: 'Enhancement suggester not initialized (enhancementSuggester not registered)',
143
+ meta: { tool: 'autosnippet_panorama' },
144
+ });
145
+ }
146
+ const suggestions = suggester.analyzeAll();
147
+ return envelope({
148
+ success: true,
149
+ data: { suggestions },
150
+ meta: { tool: 'autosnippet_panorama', operation: 'enhancement_suggestions' },
151
+ });
152
+ }
153
+ default:
154
+ throw new Error(`Unknown panorama operation: ${op}. Expected: overview, module, gaps, health, governance_cycle, decay_report, staging_check, enhancement_suggestions`);
155
+ }
156
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * MCP Handlers — 系统类
3
- * health, capabilities
3
+ * health
4
4
  */
5
5
  import type { KnowledgeBaseStats, McpContext } from './types.js';
6
6
  export declare function health(ctx: McpContext): Promise<{
@@ -12,7 +12,7 @@ export declare function health(ctx: McpContext): Promise<{
12
12
  issues?: string[] | undefined;
13
13
  session?: {
14
14
  id: string;
15
- readyCalled: boolean;
15
+ intentPhase: "active" | "idle" | "ended";
16
16
  toolCallCount: number;
17
17
  toolsUsed: string[];
18
18
  durationMs: number;
@@ -40,55 +40,3 @@ export declare function health(ctx: McpContext): Promise<{
40
40
  tool?: string | undefined;
41
41
  };
42
42
  }>;
43
- export declare function capabilities(): {
44
- success: boolean;
45
- errorCode: string | null;
46
- message: string;
47
- data: {
48
- count: number;
49
- tier: string;
50
- categoryGuide: {
51
- system: string;
52
- search: string;
53
- browse: string;
54
- graph: string;
55
- structure: string;
56
- submit: string;
57
- guard: string;
58
- skill: string;
59
- bootstrap: string;
60
- admin: string;
61
- };
62
- byCategory: Record<string, string[]>;
63
- tools: {
64
- name: string;
65
- tier: string;
66
- description: string;
67
- category: string;
68
- gatewayGated: boolean;
69
- params: {
70
- description?: {} | undefined;
71
- enum?: {} | undefined;
72
- default?: {} | null | undefined;
73
- name: string;
74
- type: {};
75
- required: boolean;
76
- }[];
77
- }[];
78
- workflows: ({
79
- name: string;
80
- steps: string[];
81
- tips: string;
82
- } | {
83
- name: string;
84
- steps: string[];
85
- tips?: undefined;
86
- })[];
87
- } | null;
88
- meta: {
89
- source?: string | undefined;
90
- responseTimeMs?: number | undefined;
91
- version: string;
92
- tool?: string | undefined;
93
- };
94
- };