autosnippet 3.3.7 → 3.3.8

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 (211) hide show
  1. package/README.md +1 -0
  2. package/dashboard/dist/assets/icons-BMNb0V6L.js +1 -0
  3. package/dashboard/dist/assets/index-DHJ1Dj7u.css +1 -0
  4. package/dashboard/dist/assets/index-DV8biUkH.js +112 -0
  5. package/dashboard/dist/index.html +3 -3
  6. package/dist/bin/cli.js +7 -4
  7. package/dist/lib/agent/core/ChatAgentPrompts.js +57 -21
  8. package/dist/lib/agent/core/LoopContext.d.ts +1 -0
  9. package/dist/lib/agent/core/ToolExecutionPipeline.js +13 -0
  10. package/dist/lib/agent/memory/ActiveContext.d.ts +0 -2
  11. package/dist/lib/agent/memory/ActiveContext.js +0 -2
  12. package/dist/lib/agent/memory/MemoryEmbeddingStore.d.ts +49 -0
  13. package/dist/lib/agent/memory/MemoryEmbeddingStore.js +159 -0
  14. package/dist/lib/agent/memory/MemoryRetriever.d.ts +2 -0
  15. package/dist/lib/agent/memory/MemoryRetriever.js +25 -11
  16. package/dist/lib/agent/memory/MemoryStore.d.ts +8 -41
  17. package/dist/lib/agent/memory/MemoryStore.js +196 -261
  18. package/dist/lib/agent/memory/PersistentMemory.d.ts +2 -0
  19. package/dist/lib/agent/memory/PersistentMemory.js +4 -5
  20. package/dist/lib/agent/memory/SessionStore.d.ts +0 -2
  21. package/dist/lib/agent/memory/SessionStore.js +0 -2
  22. package/dist/lib/agent/tools/ast-graph.js +21 -19
  23. package/dist/lib/agent/tools/infrastructure.js +3 -2
  24. package/dist/lib/agent/tools/project-access.d.ts +2 -2
  25. package/dist/lib/agent/tools/project-access.js +5 -4
  26. package/dist/lib/bootstrap.js +2 -1
  27. package/dist/lib/cli/AiScanService.js +4 -17
  28. package/dist/lib/cli/KnowledgeSyncService.d.ts +7 -37
  29. package/dist/lib/cli/KnowledgeSyncService.js +23 -51
  30. package/dist/lib/core/ast/ProjectGraph.js +5 -27
  31. package/dist/lib/core/discovery/CustomConfigDiscoverer.d.ts +0 -2
  32. package/dist/lib/core/discovery/CustomConfigDiscoverer.js +0 -2
  33. package/dist/lib/domain/dimension/DimensionRegistry.d.ts +0 -2
  34. package/dist/lib/domain/dimension/DimensionRegistry.js +0 -2
  35. package/dist/lib/domain/dimension/DimensionSop.js +44 -33
  36. package/dist/lib/domain/dimension/UnifiedDimension.d.ts +0 -2
  37. package/dist/lib/domain/dimension/UnifiedDimension.js +0 -2
  38. package/dist/lib/domain/knowledge/Lifecycle.d.ts +26 -0
  39. package/dist/lib/domain/knowledge/Lifecycle.js +42 -0
  40. package/dist/lib/domain/knowledge/index.d.ts +2 -1
  41. package/dist/lib/domain/knowledge/index.js +1 -1
  42. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/BootstrapSnapshot.d.ts +2 -1
  43. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/BootstrapSnapshot.js +102 -153
  44. package/dist/lib/external/mcp/handlers/bootstrap/pipeline/orchestrator.js +33 -16
  45. package/dist/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.d.ts +1 -1
  46. package/dist/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.js +41 -37
  47. package/dist/lib/external/mcp/handlers/bootstrap-external.js +1 -1
  48. package/dist/lib/external/mcp/handlers/dimension-complete-external.js +7 -3
  49. package/dist/lib/external/mcp/handlers/evolve-external.d.ts +1 -0
  50. package/dist/lib/external/mcp/handlers/evolve-external.js +13 -16
  51. package/dist/lib/external/mcp/handlers/guard.js +15 -24
  52. package/dist/lib/external/mcp/handlers/panorama.js +9 -9
  53. package/dist/lib/external/mcp/handlers/rescan-external.js +7 -6
  54. package/dist/lib/external/mcp/handlers/rescan-internal.js +9 -5
  55. package/dist/lib/external/mcp/handlers/search.js +3 -1
  56. package/dist/lib/external/mcp/handlers/skill.js +4 -4
  57. package/dist/lib/external/mcp/handlers/structure.js +8 -12
  58. package/dist/lib/external/mcp/handlers/system.js +10 -34
  59. package/dist/lib/http/routes/ai.js +11 -13
  60. package/dist/lib/http/routes/guardReport.js +3 -5
  61. package/dist/lib/http/routes/panorama.js +12 -12
  62. package/dist/lib/http/routes/recipes.js +59 -8
  63. package/dist/lib/http/routes/remote.js +3 -13
  64. package/dist/lib/http/routes/search.js +11 -8
  65. package/dist/lib/infrastructure/audit/AuditLogger.d.ts +20 -3
  66. package/dist/lib/infrastructure/audit/AuditStore.d.ts +28 -29
  67. package/dist/lib/infrastructure/audit/AuditStore.js +81 -88
  68. package/dist/lib/infrastructure/database/drizzle/schema.d.ts +180 -2
  69. package/dist/lib/infrastructure/database/drizzle/schema.js +23 -3
  70. package/dist/lib/injection/ServiceContainer.js +7 -4
  71. package/dist/lib/injection/ServiceMap.d.ts +20 -0
  72. package/dist/lib/injection/modules/AppModule.js +2 -1
  73. package/dist/lib/injection/modules/GuardModule.js +5 -5
  74. package/dist/lib/injection/modules/InfraModule.js +60 -0
  75. package/dist/lib/injection/modules/KnowledgeModule.js +86 -51
  76. package/dist/lib/injection/modules/PanoramaModule.js +16 -10
  77. package/dist/lib/injection/modules/VectorModule.js +3 -0
  78. package/dist/lib/repository/audit/AuditRepository.d.ts +107 -0
  79. package/dist/lib/repository/audit/AuditRepository.js +272 -0
  80. package/dist/lib/repository/base/RepositoryBase.d.ts +46 -0
  81. package/dist/lib/repository/base/RepositoryBase.js +32 -0
  82. package/dist/lib/repository/bootstrap/BootstrapRepository.d.ts +94 -0
  83. package/dist/lib/repository/bootstrap/BootstrapRepository.js +246 -0
  84. package/dist/lib/repository/code/CodeEntityRepository.d.ts +91 -0
  85. package/dist/lib/repository/code/CodeEntityRepository.js +361 -0
  86. package/dist/lib/repository/delivery/DeliveryRepoAdapter.d.ts +39 -0
  87. package/dist/lib/repository/delivery/DeliveryRepoAdapter.js +23 -0
  88. package/dist/lib/repository/evolution/LifecycleEventRepository.d.ts +51 -0
  89. package/dist/lib/repository/evolution/LifecycleEventRepository.js +119 -0
  90. package/dist/lib/repository/evolution/ProposalRepository.d.ts +9 -12
  91. package/dist/lib/repository/evolution/ProposalRepository.js +114 -57
  92. package/dist/lib/repository/guard/GuardViolationRepository.d.ts +104 -0
  93. package/dist/lib/repository/guard/GuardViolationRepository.js +217 -0
  94. package/dist/lib/repository/knowledge/KnowledgeEdgeRepository.d.ts +129 -0
  95. package/dist/lib/repository/knowledge/KnowledgeEdgeRepository.js +475 -0
  96. package/dist/lib/repository/knowledge/KnowledgeFileStore.d.ts +39 -0
  97. package/dist/lib/repository/knowledge/KnowledgeFileStore.js +12 -0
  98. package/dist/lib/repository/knowledge/KnowledgeRepository.impl.d.ts +295 -11
  99. package/dist/lib/repository/knowledge/KnowledgeRepository.impl.js +608 -13
  100. package/dist/lib/repository/knowledge/KnowledgeUnitOfWork.d.ts +61 -0
  101. package/dist/lib/repository/knowledge/KnowledgeUnitOfWork.js +156 -0
  102. package/dist/lib/repository/memory/MemoryRepository.d.ts +90 -0
  103. package/dist/lib/repository/memory/MemoryRepository.js +260 -0
  104. package/dist/lib/repository/search/SearchRepoAdapter.d.ts +92 -0
  105. package/dist/lib/repository/search/SearchRepoAdapter.js +124 -0
  106. package/dist/lib/repository/session/SessionRepository.d.ts +46 -0
  107. package/dist/lib/repository/session/SessionRepository.js +110 -0
  108. package/dist/lib/repository/sourceref/RecipeSourceRefRepository.d.ts +66 -0
  109. package/dist/lib/repository/sourceref/RecipeSourceRefRepository.js +182 -0
  110. package/dist/lib/repository/sync/SyncRepoAdapter.d.ts +58 -0
  111. package/dist/lib/repository/sync/SyncRepoAdapter.js +58 -0
  112. package/dist/lib/service/bootstrap/UiStartupTasks.js +5 -6
  113. package/dist/lib/service/bootstrap/bootstrap-event-types.d.ts +0 -1
  114. package/dist/lib/service/bootstrap/bootstrap-event-types.js +0 -1
  115. package/dist/lib/service/cleanup/CleanupService.js +8 -4
  116. package/dist/lib/service/delivery/CursorDeliveryPipeline.js +6 -8
  117. package/dist/lib/service/evolution/ConsolidationAdvisor.d.ts +4 -9
  118. package/dist/lib/service/evolution/ConsolidationAdvisor.js +34 -70
  119. package/dist/lib/service/evolution/ContentPatcher.d.ts +4 -12
  120. package/dist/lib/service/evolution/ContentPatcher.js +48 -19
  121. package/dist/lib/service/evolution/ContradictionDetector.d.ts +3 -7
  122. package/dist/lib/service/evolution/ContradictionDetector.js +17 -24
  123. package/dist/lib/service/evolution/DecayDetector.d.ts +10 -9
  124. package/dist/lib/service/evolution/DecayDetector.js +63 -57
  125. package/dist/lib/service/evolution/EnhancementSuggester.d.ts +3 -9
  126. package/dist/lib/service/evolution/EnhancementSuggester.js +42 -86
  127. package/dist/lib/service/evolution/KnowledgeMetabolism.d.ts +4 -4
  128. package/dist/lib/service/evolution/KnowledgeMetabolism.js +102 -71
  129. package/dist/lib/service/evolution/ProposalExecutor.d.ts +5 -12
  130. package/dist/lib/service/evolution/ProposalExecutor.js +64 -69
  131. package/dist/lib/service/evolution/RecipeLifecycleSupervisor.d.ts +9 -14
  132. package/dist/lib/service/evolution/RecipeLifecycleSupervisor.js +94 -155
  133. package/dist/lib/service/evolution/RecipeRelevanceAuditor.d.ts +4 -1
  134. package/dist/lib/service/evolution/RecipeRelevanceAuditor.js +50 -49
  135. package/dist/lib/service/evolution/RedundancyAnalyzer.d.ts +3 -7
  136. package/dist/lib/service/evolution/RedundancyAnalyzer.js +15 -22
  137. package/dist/lib/service/evolution/StagingManager.d.ts +6 -15
  138. package/dist/lib/service/evolution/StagingManager.js +37 -95
  139. package/dist/lib/service/evolution/createSupersedeProposal.d.ts +1 -1
  140. package/dist/lib/service/evolution/createSupersedeProposal.js +7 -8
  141. package/dist/lib/service/guard/CoverageAnalyzer.d.ts +3 -7
  142. package/dist/lib/service/guard/CoverageAnalyzer.js +9 -11
  143. package/dist/lib/service/guard/GuardCheckEngine.d.ts +3 -0
  144. package/dist/lib/service/guard/GuardCheckEngine.js +14 -22
  145. package/dist/lib/service/guard/ReverseGuard.d.ts +4 -7
  146. package/dist/lib/service/guard/ReverseGuard.js +21 -31
  147. package/dist/lib/service/guard/ViolationsStore.d.ts +15 -21
  148. package/dist/lib/service/guard/ViolationsStore.js +75 -69
  149. package/dist/lib/service/knowledge/CodeEntityGraph.d.ts +39 -63
  150. package/dist/lib/service/knowledge/CodeEntityGraph.js +418 -512
  151. package/dist/lib/service/knowledge/ConfidenceRouter.js +18 -9
  152. package/dist/lib/service/knowledge/KnowledgeFileWriter.d.ts +2 -1
  153. package/dist/lib/service/knowledge/KnowledgeGraphService.d.ts +18 -60
  154. package/dist/lib/service/knowledge/KnowledgeGraphService.js +58 -109
  155. package/dist/lib/service/knowledge/KnowledgeService.d.ts +15 -1
  156. package/dist/lib/service/knowledge/KnowledgeService.js +76 -38
  157. package/dist/lib/service/knowledge/RecipeProductionGateway.d.ts +0 -2
  158. package/dist/lib/service/knowledge/RecipeProductionGateway.js +0 -2
  159. package/dist/lib/service/knowledge/SourceRefReconciler.d.ts +5 -13
  160. package/dist/lib/service/knowledge/SourceRefReconciler.js +58 -78
  161. package/dist/lib/service/panorama/CouplingAnalyzer.d.ts +5 -3
  162. package/dist/lib/service/panorama/CouplingAnalyzer.js +102 -39
  163. package/dist/lib/service/panorama/DimensionAnalyzer.d.ts +7 -4
  164. package/dist/lib/service/panorama/DimensionAnalyzer.js +72 -25
  165. package/dist/lib/service/panorama/LayerInferrer.js +1 -1
  166. package/dist/lib/service/panorama/ModuleDiscoverer.d.ts +7 -6
  167. package/dist/lib/service/panorama/ModuleDiscoverer.js +174 -82
  168. package/dist/lib/service/panorama/PanoramaAggregator.d.ts +10 -3
  169. package/dist/lib/service/panorama/PanoramaAggregator.js +67 -79
  170. package/dist/lib/service/panorama/PanoramaScanner.d.ts +5 -1
  171. package/dist/lib/service/panorama/PanoramaScanner.js +32 -31
  172. package/dist/lib/service/panorama/PanoramaService.d.ts +11 -8
  173. package/dist/lib/service/panorama/PanoramaService.js +41 -66
  174. package/dist/lib/service/panorama/PanoramaTypes.d.ts +3 -0
  175. package/dist/lib/service/panorama/RoleRefiner.d.ts +8 -5
  176. package/dist/lib/service/panorama/RoleRefiner.js +52 -283
  177. package/dist/lib/service/panorama/TechStackProfiler.js +7 -119
  178. package/dist/lib/service/quality/QualityScorer.d.ts +45 -26
  179. package/dist/lib/service/quality/QualityScorer.js +157 -83
  180. package/dist/lib/service/search/SearchEngine.d.ts +1 -0
  181. package/dist/lib/service/search/SearchEngine.js +32 -37
  182. package/dist/lib/service/signal/HitRecorder.js +5 -5
  183. package/dist/lib/service/skills/RuleRecallStrategy.js +7 -3
  184. package/dist/lib/service/skills/SignalCollector.d.ts +5 -8
  185. package/dist/lib/service/skills/SignalCollector.js +28 -55
  186. package/dist/lib/service/skills/SkillAdvisor.d.ts +7 -13
  187. package/dist/lib/service/skills/SkillAdvisor.js +30 -79
  188. package/dist/lib/service/vector/SyncCoordinator.d.ts +3 -1
  189. package/dist/lib/service/vector/SyncCoordinator.js +25 -3
  190. package/dist/lib/service/vector/VectorService.d.ts +2 -0
  191. package/dist/lib/service/vector/VectorService.js +3 -0
  192. package/dist/lib/service/wiki/WikiGenerator.js +1 -1
  193. package/dist/lib/shared/LanguageProfiles.d.ts +109 -0
  194. package/dist/lib/shared/LanguageProfiles.js +939 -0
  195. package/dist/lib/shared/LanguageService.d.ts +6 -0
  196. package/dist/lib/shared/LanguageService.js +16 -0
  197. package/dist/lib/shared/constants.d.ts +19 -19
  198. package/dist/lib/shared/constants.js +10 -10
  199. package/dist/lib/shared/schemas/mcp-tools.d.ts +1 -1
  200. package/dist/lib/types/project-snapshot-builder.d.ts +0 -1
  201. package/dist/lib/types/project-snapshot-builder.js +0 -1
  202. package/dist/lib/types/project-snapshot.d.ts +0 -1
  203. package/dist/lib/types/project-snapshot.js +0 -1
  204. package/dist/lib/types/snapshot-views.d.ts +0 -2
  205. package/dist/lib/types/snapshot-views.js +0 -1
  206. package/package.json +2 -1
  207. package/dashboard/dist/assets/icons-FHns2ypa.js +0 -1
  208. package/dashboard/dist/assets/index-BRJv5Y3r.js +0 -135
  209. package/dashboard/dist/assets/index-DzoB7kxK.css +0 -1
  210. package/dist/lib/repository/base/BaseRepository.d.ts +0 -53
  211. package/dist/lib/repository/base/BaseRepository.js +0 -226
@@ -11,11 +11,7 @@
11
11
  */
12
12
  import type { ReportStore } from '../../infrastructure/report/ReportStore.js';
13
13
  import type { SignalBus } from '../../infrastructure/signal/SignalBus.js';
14
- interface DatabaseLike {
15
- prepare(sql: string): {
16
- all(...params: unknown[]): Record<string, unknown>[];
17
- };
18
- }
14
+ import type KnowledgeRepositoryImpl from '../../repository/knowledge/KnowledgeRepository.impl.js';
19
15
  export interface RedundancyResult {
20
16
  recipeA: string;
21
17
  recipeB: string;
@@ -37,14 +33,14 @@ interface RecipeForRedundancy {
37
33
  }
38
34
  export declare class RedundancyAnalyzer {
39
35
  #private;
40
- constructor(db: DatabaseLike, options?: {
36
+ constructor(knowledgeRepo: KnowledgeRepositoryImpl, options?: {
41
37
  signalBus?: SignalBus;
42
38
  reportStore?: ReportStore;
43
39
  });
44
40
  /**
45
41
  * 分析所有 active/staging 条目之间的冗余
46
42
  */
47
- analyzeAll(): RedundancyResult[];
43
+ analyzeAll(): Promise<RedundancyResult[]>;
48
44
  /**
49
45
  * 分析两条 Recipe 的冗余度
50
46
  */
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * 综合: weighted_sum(0.2*d1 + 0.3*d2 + 0.3*d3 + 0.2*d4) ≥ 0.65
11
11
  */
12
+ import { CONSUMABLE_LIFECYCLES } from '../../domain/knowledge/Lifecycle.js';
12
13
  import Logger from '../../infrastructure/logging/Logger.js';
13
14
  import { ContradictionDetector } from './ContradictionDetector.js';
14
15
  /* ────────────────────── Constants ────────────────────── */
@@ -16,20 +17,20 @@ const WEIGHTS = { title: 0.2, clause: 0.3, code: 0.3, guard: 0.2 };
16
17
  const REDUNDANCY_THRESHOLD = 0.65;
17
18
  /* ────────────────────── Class ────────────────────── */
18
19
  export class RedundancyAnalyzer {
19
- #db;
20
+ #knowledgeRepo;
20
21
  #signalBus;
21
22
  #reportStore;
22
23
  #logger = Logger.getInstance();
23
- constructor(db, options = {}) {
24
- this.#db = db;
24
+ constructor(knowledgeRepo, options = {}) {
25
+ this.#knowledgeRepo = knowledgeRepo;
25
26
  this.#signalBus = options.signalBus ?? null;
26
27
  this.#reportStore = options.reportStore ?? null;
27
28
  }
28
29
  /**
29
30
  * 分析所有 active/staging 条目之间的冗余
30
31
  */
31
- analyzeAll() {
32
- const recipes = this.#loadRecipes();
32
+ async analyzeAll() {
33
+ const recipes = await this.#loadRecipes();
33
34
  const results = [];
34
35
  for (let i = 0; i < recipes.length; i++) {
35
36
  for (let j = i + 1; j < recipes.length; j++) {
@@ -88,24 +89,16 @@ export class RedundancyAnalyzer {
88
89
  };
89
90
  }
90
91
  /* ── Internal ── */
91
- #loadRecipes() {
92
+ async #loadRecipes() {
92
93
  try {
93
- const rows = this.#db
94
- .prepare(`SELECT id, title,
95
- doClause,
96
- dontClause,
97
- json_extract(content, '$.pattern') AS guardPattern,
98
- json_extract(content, '$.coreCode') AS coreCode
99
- FROM knowledge_entries
100
- WHERE lifecycle IN ('active', 'staging', 'evolving')`)
101
- .all();
102
- return rows.map((r) => ({
103
- id: r.id,
104
- title: r.title,
105
- doClause: r.doClause ?? null,
106
- dontClause: r.dontClause ?? null,
107
- coreCode: r.coreCode ?? null,
108
- guardPattern: r.guardPattern ?? null,
94
+ const entries = await this.#knowledgeRepo.findAllByLifecycles(CONSUMABLE_LIFECYCLES);
95
+ return entries.map((e) => ({
96
+ id: e.id,
97
+ title: e.title,
98
+ doClause: e.doClause || null,
99
+ dontClause: e.dontClause || null,
100
+ coreCode: e.coreCode || null,
101
+ guardPattern: e.content?.pattern || null,
109
102
  }));
110
103
  }
111
104
  catch {
@@ -12,15 +12,7 @@
12
12
  * 0.85-0.89 → 72h
13
13
  */
14
14
  import type { SignalBus } from '../../infrastructure/signal/SignalBus.js';
15
- interface DatabaseLike {
16
- prepare(sql: string): {
17
- all(...params: unknown[]): Record<string, unknown>[];
18
- get(...params: unknown[]): Record<string, unknown> | undefined;
19
- run(...params: unknown[]): {
20
- changes: number;
21
- };
22
- };
23
- }
15
+ import type KnowledgeRepositoryImpl from '../../repository/knowledge/KnowledgeRepository.impl.js';
24
16
  export interface StagingEntry {
25
17
  id: string;
26
18
  title: string;
@@ -34,24 +26,23 @@ export interface StagingCheckResult {
34
26
  }
35
27
  export declare class StagingManager {
36
28
  #private;
37
- constructor(db: DatabaseLike, options?: {
29
+ constructor(knowledgeRepo: KnowledgeRepositoryImpl, options?: {
38
30
  signalBus?: SignalBus;
39
31
  });
40
32
  /**
41
33
  * 将条目推入 staging 状态并记录 deadline
42
34
  */
43
- enterStaging(entryId: string, gracePeriodMs: number, confidence: number): boolean;
35
+ enterStaging(entryId: string, gracePeriodMs: number, confidence: number): Promise<boolean>;
44
36
  /**
45
37
  * 检查所有 staging 条目,执行自动发布或回滚
46
38
  */
47
- checkAndPromote(): StagingCheckResult;
39
+ checkAndPromote(): Promise<StagingCheckResult>;
48
40
  /**
49
41
  * 回滚 staging 条目到 pending(Guard 检测到冲突时调用)
50
42
  */
51
- rollback(entryId: string, reason: string): boolean;
43
+ rollback(entryId: string, reason: string): Promise<boolean>;
52
44
  /**
53
45
  * 获取所有 staging 条目及其状态
54
46
  */
55
- listStaging(): StagingEntry[];
47
+ listStaging(): Promise<StagingEntry[]>;
56
48
  }
57
- export {};
@@ -15,22 +15,20 @@ import Logger from '../../infrastructure/logging/Logger.js';
15
15
  import { unixNow } from '../../shared/utils/common.js';
16
16
  /* ────────────────────── Class ────────────────────── */
17
17
  export class StagingManager {
18
- #db;
18
+ #knowledgeRepo;
19
19
  #signalBus;
20
20
  #logger = Logger.getInstance();
21
- constructor(db, options = {}) {
22
- this.#db = db;
21
+ constructor(knowledgeRepo, options = {}) {
22
+ this.#knowledgeRepo = knowledgeRepo;
23
23
  this.#signalBus = options.signalBus ?? null;
24
24
  }
25
25
  /**
26
26
  * 将条目推入 staging 状态并记录 deadline
27
27
  */
28
- enterStaging(entryId, gracePeriodMs, confidence) {
28
+ async enterStaging(entryId, gracePeriodMs, confidence) {
29
29
  const now = Date.now();
30
30
  const deadline = now + gracePeriodMs;
31
- const entry = this.#db
32
- .prepare(`SELECT id, title, lifecycle FROM knowledge_entries WHERE id = ?`)
33
- .get(entryId);
31
+ const entry = await this.#knowledgeRepo.findById(entryId);
34
32
  if (!entry) {
35
33
  this.#logger.warn(`StagingManager: entry not found: ${entryId}`);
36
34
  return false;
@@ -39,24 +37,10 @@ export class StagingManager {
39
37
  this.#logger.warn(`StagingManager: entry ${entryId} is "${entry.lifecycle}", not pending`);
40
38
  return false;
41
39
  }
42
- // 更新 lifecycle → staging,记录 deadline 到 stats JSON
43
- const statsRaw = this.#db
44
- .prepare(`SELECT stats FROM knowledge_entries WHERE id = ?`)
45
- .get(entryId);
46
- let stats = {};
47
- try {
48
- stats = JSON.parse(statsRaw?.stats || '{}');
49
- }
50
- catch {
51
- stats = {};
52
- }
53
- stats.stagingDeadline = deadline;
54
- stats.stagingConfidence = confidence;
55
- stats.stagingEnteredAt = now;
56
- this.#db
57
- .prepare(`UPDATE knowledge_entries SET lifecycle = 'staging', stats = ?, updatedAt = ? WHERE id = ?`)
58
- .run(JSON.stringify(stats), unixNow(), entryId);
59
- // 发射信号
40
+ await this.#knowledgeRepo.update(entryId, {
41
+ lifecycle: 'staging',
42
+ stagingDeadline: deadline,
43
+ });
60
44
  if (this.#signalBus) {
61
45
  this.#signalBus.send('lifecycle', 'StagingManager.enter', confidence, {
62
46
  target: entryId,
@@ -74,40 +58,27 @@ export class StagingManager {
74
58
  /**
75
59
  * 检查所有 staging 条目,执行自动发布或回滚
76
60
  */
77
- checkAndPromote() {
61
+ async checkAndPromote() {
78
62
  const now = Date.now();
79
63
  const result = { promoted: [], rolledBack: [], waiting: [] };
80
- const rows = this.#db
81
- .prepare(`SELECT id, title, stats FROM knowledge_entries WHERE lifecycle = 'staging'`)
82
- .all();
83
- for (const row of rows) {
84
- let stats = {};
85
- try {
86
- stats = JSON.parse(row.stats || '{}');
87
- }
88
- catch {
89
- stats = {};
90
- }
91
- const deadline = stats.stagingDeadline || 0;
92
- const confidence = stats.stagingConfidence || 0;
64
+ const entries = await this.#knowledgeRepo.findAllByLifecycles(['staging']);
65
+ for (const e of entries) {
66
+ const deadline = e.stagingDeadline || 0;
93
67
  const entry = {
94
- id: row.id,
95
- title: row.title,
68
+ id: e.id,
69
+ title: e.title,
96
70
  stagingDeadline: deadline,
97
- confidence,
71
+ confidence: 0,
98
72
  };
99
73
  if (deadline === 0) {
100
- // 无 deadline 数据(旧数据兼容)→ 保持 waiting
101
74
  result.waiting.push(entry);
102
75
  continue;
103
76
  }
104
77
  if (now < deadline) {
105
- // 未到期
106
78
  result.waiting.push(entry);
107
79
  continue;
108
80
  }
109
- // 到期 → 自动发布
110
- this.#promote(entry, stats, now);
81
+ await this.#promote(entry, now);
111
82
  result.promoted.push(entry);
112
83
  }
113
84
  if (result.promoted.length > 0) {
@@ -118,30 +89,15 @@ export class StagingManager {
118
89
  /**
119
90
  * 回滚 staging 条目到 pending(Guard 检测到冲突时调用)
120
91
  */
121
- rollback(entryId, reason) {
122
- const now = Date.now();
123
- const entry = this.#db
124
- .prepare(`SELECT id, title, lifecycle, stats FROM knowledge_entries WHERE id = ?`)
125
- .get(entryId);
92
+ async rollback(entryId, reason) {
93
+ const entry = await this.#knowledgeRepo.findById(entryId);
126
94
  if (!entry || entry.lifecycle !== 'staging') {
127
95
  return false;
128
96
  }
129
- let stats = {};
130
- try {
131
- stats = JSON.parse(entry.stats || '{}');
132
- }
133
- catch {
134
- stats = {};
135
- }
136
- // 清除 staging 元数据
137
- delete stats.stagingDeadline;
138
- delete stats.stagingConfidence;
139
- delete stats.stagingEnteredAt;
140
- stats.lastRollbackReason = reason;
141
- stats.lastRollbackAt = now;
142
- this.#db
143
- .prepare(`UPDATE knowledge_entries SET lifecycle = 'pending', stats = ?, updatedAt = ? WHERE id = ?`)
144
- .run(JSON.stringify(stats), unixNow(), entryId);
97
+ await this.#knowledgeRepo.update(entryId, {
98
+ lifecycle: 'pending',
99
+ stagingDeadline: null,
100
+ });
145
101
  if (this.#signalBus) {
146
102
  this.#signalBus.send('lifecycle', 'StagingManager.rollback', 0.8, {
147
103
  target: entryId,
@@ -158,37 +114,23 @@ export class StagingManager {
158
114
  /**
159
115
  * 获取所有 staging 条目及其状态
160
116
  */
161
- listStaging() {
162
- const rows = this.#db
163
- .prepare(`SELECT id, title, stats FROM knowledge_entries WHERE lifecycle = 'staging'`)
164
- .all();
165
- return rows.map((row) => {
166
- let stats = {};
167
- try {
168
- stats = JSON.parse(row.stats || '{}');
169
- }
170
- catch {
171
- stats = {};
172
- }
173
- return {
174
- id: row.id,
175
- title: row.title,
176
- stagingDeadline: stats.stagingDeadline || 0,
177
- confidence: stats.stagingConfidence || 0,
178
- };
179
- });
117
+ async listStaging() {
118
+ const entries = await this.#knowledgeRepo.findAllByLifecycles(['staging']);
119
+ return entries.map((e) => ({
120
+ id: e.id,
121
+ title: e.title,
122
+ stagingDeadline: e.stagingDeadline || 0,
123
+ confidence: 0,
124
+ }));
180
125
  }
181
126
  /* ── Private ── */
182
- #promote(entry, stats, now) {
183
- // 清除 staging 元数据,记录发布信息
184
- delete stats.stagingDeadline;
185
- delete stats.stagingConfidence;
186
- delete stats.stagingEnteredAt;
187
- stats.autoPublishedAt = now;
127
+ async #promote(entry, now) {
188
128
  const nowS = unixNow();
189
- this.#db
190
- .prepare(`UPDATE knowledge_entries SET lifecycle = 'active', publishedAt = ?, stats = ?, updatedAt = ? WHERE id = ?`)
191
- .run(nowS, JSON.stringify(stats), nowS, entry.id);
129
+ await this.#knowledgeRepo.update(entry.id, {
130
+ lifecycle: 'active',
131
+ publishedAt: nowS,
132
+ stagingDeadline: null,
133
+ });
192
134
  if (this.#signalBus) {
193
135
  this.#signalBus.send('lifecycle', 'StagingManager.promote', 1.0, {
194
136
  target: entry.id,
@@ -40,5 +40,5 @@ export interface SupersedeResult {
40
40
  *
41
41
  * @returns SupersedeResult(成功)| null(ProposalRepo 不可用 / 旧 Recipe 不存在 / 去重拒绝)
42
42
  */
43
- export declare function createSupersedeProposal(container: MinimalContainer, input: SupersedeInput): SupersedeResult | null;
43
+ export declare function createSupersedeProposal(container: MinimalContainer, input: SupersedeInput): Promise<SupersedeResult | null>;
44
44
  export {};
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * @returns SupersedeResult(成功)| null(ProposalRepo 不可用 / 旧 Recipe 不存在 / 去重拒绝)
18
18
  */
19
- export function createSupersedeProposal(container, input) {
19
+ export async function createSupersedeProposal(container, input) {
20
20
  const { oldRecipeId, newRecipeIds, source = 'ide-agent', confidence = 0.8 } = input;
21
21
  if (!oldRecipeId || newRecipeIds.length === 0) {
22
22
  return null;
@@ -33,7 +33,7 @@ export function createSupersedeProposal(container, input) {
33
33
  return null;
34
34
  }
35
35
  // 2. 验证旧 Recipe 存在
36
- if (!verifyRecipeExists(container, oldRecipeId)) {
36
+ if (!(await verifyRecipeExists(container, oldRecipeId))) {
37
37
  return null;
38
38
  }
39
39
  // 3. 创建 supersede 提案(ProposalRepository 内部做去重检查)
@@ -65,15 +65,14 @@ export function createSupersedeProposal(container, input) {
65
65
  };
66
66
  }
67
67
  /* ────────────────────── Helpers ────────────────────── */
68
- function verifyRecipeExists(container, recipeId) {
68
+ async function verifyRecipeExists(container, recipeId) {
69
69
  try {
70
- const db = container.get('database');
71
- if (!db) {
70
+ const knowledgeRepo = container.get('knowledgeRepository');
71
+ if (!knowledgeRepo) {
72
72
  return false;
73
73
  }
74
- const rawDb = db.getDb();
75
- const row = rawDb.prepare('SELECT id FROM knowledge_entries WHERE id = ?').get(recipeId);
76
- return row !== undefined;
74
+ const entry = await knowledgeRepo.findById(recipeId);
75
+ return entry !== null;
77
76
  }
78
77
  catch {
79
78
  return false;
@@ -4,12 +4,8 @@
4
4
  * 计算模块级 Rule 覆盖率,识别零覆盖和低覆盖模块。
5
5
  * 与 PanoramaService 协同:利用模块划分 + gaps 数据做精准评估。
6
6
  */
7
- interface DatabaseLike {
8
- prepare(sql: string): {
9
- all(...params: unknown[]): Record<string, unknown>[];
10
- get(...params: unknown[]): Record<string, unknown> | undefined;
11
- };
12
- }
7
+ import type { GuardViolationRepositoryImpl } from '../../repository/guard/GuardViolationRepository.js';
8
+ import type { KnowledgeRepositoryImpl } from '../../repository/knowledge/KnowledgeRepository.impl.js';
13
9
  interface RuleLearnerLike {
14
10
  getMetrics(ruleId: string): {
15
11
  precision: number;
@@ -42,7 +38,7 @@ export interface CoverageMatrix {
42
38
  }
43
39
  export declare class CoverageAnalyzer {
44
40
  #private;
45
- constructor(db: DatabaseLike, options?: {
41
+ constructor(knowledgeRepo: KnowledgeRepositoryImpl, guardViolationRepo: GuardViolationRepositoryImpl, options?: {
46
42
  ruleLearner?: RuleLearnerLike;
47
43
  });
48
44
  /**
@@ -10,11 +10,13 @@ import { LanguageService } from '../../shared/LanguageService.js';
10
10
  const LOW_COVERAGE_THRESHOLD = 50;
11
11
  /* ────────────────────── Class ────────────────────── */
12
12
  export class CoverageAnalyzer {
13
- #db;
13
+ #knowledgeRepo;
14
+ #guardViolationRepo;
14
15
  #ruleLearner;
15
16
  #logger = Logger.getInstance();
16
- constructor(db, options = {}) {
17
- this.#db = db;
17
+ constructor(knowledgeRepo, guardViolationRepo, options = {}) {
18
+ this.#knowledgeRepo = knowledgeRepo;
19
+ this.#guardViolationRepo = guardViolationRepo;
18
20
  this.#ruleLearner = options.ruleLearner ?? null;
19
21
  }
20
22
  /**
@@ -93,9 +95,7 @@ export class CoverageAnalyzer {
93
95
  /* ── 内部 ── */
94
96
  #loadActiveRules() {
95
97
  try {
96
- const rows = this.#db
97
- .prepare(`SELECT id, language FROM knowledge_entries WHERE lifecycle = 'active' AND kind = 'rule'`)
98
- .all();
98
+ const rows = this.#knowledgeRepo.findActiveRuleIdsSync();
99
99
  return rows.map((r) => ({
100
100
  id: r.id,
101
101
  languages: r.language
@@ -110,13 +110,11 @@ export class CoverageAnalyzer {
110
110
  #buildRuleFileMap() {
111
111
  const map = new Map();
112
112
  try {
113
- const rows = this.#db
114
- .prepare(`SELECT file_path, violations_json FROM guard_violations ORDER BY created_at DESC LIMIT 200`)
115
- .all();
113
+ const rows = this.#guardViolationRepo.findRecentViolationsJson(200);
116
114
  for (const row of rows) {
117
115
  try {
118
- const violations = JSON.parse(row.violations_json || '[]');
119
- const filePath = row.file_path;
116
+ const violations = JSON.parse(row.violationsJson || '[]');
117
+ const filePath = row.filePath;
120
118
  for (const v of violations) {
121
119
  if (!v.ruleId) {
122
120
  continue;
@@ -7,6 +7,7 @@
7
7
  import * as AstAnalyzerModule from '../../core/AstAnalyzer.js';
8
8
  import Logger from '../../infrastructure/logging/Logger.js';
9
9
  import type { SignalBus } from '../../infrastructure/signal/SignalBus.js';
10
+ import type { KnowledgeRepositoryImpl } from '../../repository/knowledge/KnowledgeRepository.impl.js';
10
11
  import type { GuardCapabilityReport, UncertainResult } from './UncertaintyCollector.js';
11
12
  import { UncertaintyCollector } from './UncertaintyCollector.js';
12
13
  /** Minimal DB interface for Guard engine */
@@ -80,6 +81,7 @@ interface GuardCheckEngineOptions {
80
81
  cacheTTL?: number;
81
82
  guardConfig?: GuardConfig;
82
83
  signalBus?: SignalBus;
84
+ knowledgeRepo?: KnowledgeRepositoryImpl;
83
85
  }
84
86
  interface ExternalRuleInput {
85
87
  ruleId: string;
@@ -110,6 +112,7 @@ interface AuditFilesInput {
110
112
  export { detectLanguage } from './GuardPatternUtils.js';
111
113
  /** GuardCheckEngine - 核心检查引擎 */
112
114
  export declare class GuardCheckEngine {
115
+ #private;
113
116
  _astRulesCache: GuardRule[] | null;
114
117
  _builtInRules: Record<string, BuiltInRule>;
115
118
  _cacheTTL: number;
@@ -5,7 +5,9 @@
5
5
  * 支持: 正则模式匹配 + AST 语义规则 + code-level 检查 + 多维度审计
6
6
  */
7
7
  import * as AstAnalyzerModule from '../../core/AstAnalyzer.js';
8
+ import { GUARD_LIFECYCLES } from '../../domain/knowledge/Lifecycle.js';
8
9
  import Logger from '../../infrastructure/logging/Logger.js';
10
+ import { RawDbGuardAdapter, unwrapRawDb } from '../../repository/search/SearchRepoAdapter.js';
9
11
  import { LanguageService } from '../../shared/LanguageService.js';
10
12
  import { runCodeLevelChecks } from './GuardCodeChecks.js';
11
13
  import { runCrossFileChecks } from './GuardCrossFileChecks.js';
@@ -463,10 +465,17 @@ export class GuardCheckEngine {
463
465
  _lastBlindSpotSignalKey;
464
466
  _uncertaintyCollector;
465
467
  db;
468
+ #knowledgeRepo;
466
469
  logger;
467
470
  constructor(db, options = {}) {
468
- this.db =
469
- db && 'getDb' in db && typeof db.getDb === 'function' ? db.getDb() : db;
471
+ this.db = unwrapRawDb(db);
472
+ this.#knowledgeRepo =
473
+ options.knowledgeRepo ??
474
+ (this.db
475
+ ? new RawDbGuardAdapter(this.db)
476
+ : new RawDbGuardAdapter({
477
+ prepare: () => ({ run: () => undefined, get: () => ({}), all: () => [] }),
478
+ }));
470
479
  this.logger = Logger.getInstance();
471
480
  this._builtInRules = BUILT_IN_RULES;
472
481
  this._customRulesCache = null;
@@ -543,12 +552,7 @@ export class GuardCheckEngine {
543
552
  if (!this._customRulesCache || now - this._cacheTime > this._cacheTTL) {
544
553
  let rows = [];
545
554
  try {
546
- rows = this.db
547
- .prepare(`SELECT id, title, description, language, scope, constraints, lifecycle
548
- FROM knowledge_entries
549
- WHERE (kind = 'rule' OR knowledgeType = 'boundary-constraint')
550
- AND lifecycle IN ('active', 'staging', 'evolving', 'decaying')`)
551
- .all();
555
+ rows = this.#knowledgeRepo.findGuardRulesSync(GUARD_LIFECYCLES);
552
556
  }
553
557
  catch {
554
558
  /* table may not exist */
@@ -1296,7 +1300,7 @@ export class GuardCheckEngine {
1296
1300
  * @param violations
1297
1301
  */
1298
1302
  trackGuardHits(violations) {
1299
- if (!violations?.length || !this.db) {
1303
+ if (!violations?.length || !this.#knowledgeRepo) {
1300
1304
  return;
1301
1305
  }
1302
1306
  try {
@@ -1306,21 +1310,9 @@ export class GuardCheckEngine {
1306
1310
  const count = hitMap.get(v.ruleId) || 0;
1307
1311
  hitMap.set(v.ruleId, count + 1);
1308
1312
  }
1309
- let updateStmt;
1310
- try {
1311
- updateStmt = this.db.prepare(`UPDATE knowledge_entries
1312
- SET stats = json_set(COALESCE(stats, '{}'), '$.guardHits',
1313
- COALESCE(json_extract(stats, '$.guardHits'), 0) + ?),
1314
- updatedAt = ?
1315
- WHERE id = ?`);
1316
- }
1317
- catch {
1318
- /* table may not exist */
1319
- }
1320
- const now = Math.floor(Date.now() / 1000);
1321
1313
  for (const [ruleId, count] of hitMap) {
1322
1314
  try {
1323
- updateStmt?.run(count, now, ruleId);
1315
+ this.#knowledgeRepo.incrementGuardHitsSync(ruleId, count);
1324
1316
  }
1325
1317
  catch {
1326
1318
  /* 非 Recipe 规则(内置规则)忽略 */
@@ -12,12 +12,9 @@
12
12
  * 5. 匹配率骤降 → 代码模式正在迁移
13
13
  */
14
14
  import type { SignalBus } from '../../infrastructure/signal/SignalBus.js';
15
- interface DatabaseLike {
16
- prepare(sql: string): {
17
- all(...params: unknown[]): Record<string, unknown>[];
18
- get(...params: unknown[]): Record<string, unknown> | undefined;
19
- };
20
- }
15
+ import type { CodeEntityRepositoryImpl } from '../../repository/code/CodeEntityRepository.js';
16
+ import type { KnowledgeRepositoryImpl } from '../../repository/knowledge/KnowledgeRepository.impl.js';
17
+ import type { RecipeSourceRefRepositoryImpl } from '../../repository/sourceref/RecipeSourceRefRepository.js';
21
18
  export type DriftType = 'symbol_missing' | 'match_rate_drop' | 'api_deprecated' | 'zero_match' | 'source_ref_stale';
22
19
  export type DriftSeverity = 'high' | 'medium' | 'low';
23
20
  export interface PatternDriftSignal {
@@ -48,7 +45,7 @@ interface RecipeRow {
48
45
  }
49
46
  export declare class ReverseGuard {
50
47
  #private;
51
- constructor(db: DatabaseLike, options?: {
48
+ constructor(knowledgeRepo: KnowledgeRepositoryImpl, entityRepo: CodeEntityRepositoryImpl, sourceRefRepo: RecipeSourceRefRepositoryImpl, options?: {
52
49
  signalBus?: SignalBus;
53
50
  });
54
51
  /**