agentic-qe 3.6.6 → 3.6.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 (147) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/package.json +3 -1
  3. package/scripts/benchmark-aqe-baseline.ts +614 -0
  4. package/v3/CHANGELOG.md +41 -0
  5. package/v3/dist/cli/bundle.js +970 -350
  6. package/v3/dist/cli/commands/hooks.d.ts.map +1 -1
  7. package/v3/dist/cli/commands/hooks.js +172 -31
  8. package/v3/dist/cli/commands/hooks.js.map +1 -1
  9. package/v3/dist/coordination/dynamic-scaling/dynamic-scaler.d.ts +21 -0
  10. package/v3/dist/coordination/dynamic-scaling/dynamic-scaler.d.ts.map +1 -1
  11. package/v3/dist/coordination/dynamic-scaling/dynamic-scaler.js +76 -0
  12. package/v3/dist/coordination/dynamic-scaling/dynamic-scaler.js.map +1 -1
  13. package/v3/dist/coordination/mincut/mincut-persistence.d.ts +4 -0
  14. package/v3/dist/coordination/mincut/mincut-persistence.d.ts.map +1 -1
  15. package/v3/dist/coordination/mincut/mincut-persistence.js +30 -0
  16. package/v3/dist/coordination/mincut/mincut-persistence.js.map +1 -1
  17. package/v3/dist/coordination/mincut/queen-integration.d.ts.map +1 -1
  18. package/v3/dist/coordination/mincut/queen-integration.js +7 -2
  19. package/v3/dist/coordination/mincut/queen-integration.js.map +1 -1
  20. package/v3/dist/coordination/mincut/time-crystal.d.ts +22 -0
  21. package/v3/dist/coordination/mincut/time-crystal.d.ts.map +1 -1
  22. package/v3/dist/coordination/mincut/time-crystal.js +95 -0
  23. package/v3/dist/coordination/mincut/time-crystal.js.map +1 -1
  24. package/v3/dist/domains/code-intelligence/coordinator.d.ts.map +1 -1
  25. package/v3/dist/domains/code-intelligence/coordinator.js +6 -3
  26. package/v3/dist/domains/code-intelligence/coordinator.js.map +1 -1
  27. package/v3/dist/domains/code-intelligence/services/knowledge-graph.d.ts.map +1 -1
  28. package/v3/dist/domains/code-intelligence/services/knowledge-graph.js +19 -34
  29. package/v3/dist/domains/code-intelligence/services/knowledge-graph.js.map +1 -1
  30. package/v3/dist/domains/coverage-analysis/services/hnsw-index.d.ts.map +1 -1
  31. package/v3/dist/domains/coverage-analysis/services/hnsw-index.js +5 -3
  32. package/v3/dist/domains/coverage-analysis/services/hnsw-index.js.map +1 -1
  33. package/v3/dist/domains/security-compliance/services/scanners/sast-scanner.d.ts.map +1 -1
  34. package/v3/dist/domains/security-compliance/services/scanners/sast-scanner.js +7 -3
  35. package/v3/dist/domains/security-compliance/services/scanners/sast-scanner.js.map +1 -1
  36. package/v3/dist/early-exit/early-exit-controller.d.ts +20 -0
  37. package/v3/dist/early-exit/early-exit-controller.d.ts.map +1 -1
  38. package/v3/dist/early-exit/early-exit-controller.js +72 -0
  39. package/v3/dist/early-exit/early-exit-controller.js.map +1 -1
  40. package/v3/dist/feedback/coverage-learner.d.ts +19 -0
  41. package/v3/dist/feedback/coverage-learner.d.ts.map +1 -1
  42. package/v3/dist/feedback/coverage-learner.js +134 -0
  43. package/v3/dist/feedback/coverage-learner.js.map +1 -1
  44. package/v3/dist/feedback/feedback-loop.d.ts +10 -1
  45. package/v3/dist/feedback/feedback-loop.d.ts.map +1 -1
  46. package/v3/dist/feedback/feedback-loop.js +20 -1
  47. package/v3/dist/feedback/feedback-loop.js.map +1 -1
  48. package/v3/dist/feedback/index.d.ts +1 -1
  49. package/v3/dist/feedback/index.d.ts.map +1 -1
  50. package/v3/dist/feedback/index.js +1 -1
  51. package/v3/dist/feedback/index.js.map +1 -1
  52. package/v3/dist/feedback/test-outcome-tracker.d.ts +19 -0
  53. package/v3/dist/feedback/test-outcome-tracker.d.ts.map +1 -1
  54. package/v3/dist/feedback/test-outcome-tracker.js +114 -0
  55. package/v3/dist/feedback/test-outcome-tracker.js.map +1 -1
  56. package/v3/dist/governance/compliance-reporter.d.ts +13 -0
  57. package/v3/dist/governance/compliance-reporter.d.ts.map +1 -1
  58. package/v3/dist/governance/compliance-reporter.js +63 -0
  59. package/v3/dist/governance/compliance-reporter.js.map +1 -1
  60. package/v3/dist/governance/continue-gate-integration.d.ts +8 -0
  61. package/v3/dist/governance/continue-gate-integration.d.ts.map +1 -1
  62. package/v3/dist/governance/continue-gate-integration.js +50 -2
  63. package/v3/dist/governance/continue-gate-integration.js.map +1 -1
  64. package/v3/dist/governance/evolution-pipeline-integration.d.ts +13 -0
  65. package/v3/dist/governance/evolution-pipeline-integration.d.ts.map +1 -1
  66. package/v3/dist/governance/evolution-pipeline-integration.js +53 -0
  67. package/v3/dist/governance/evolution-pipeline-integration.js.map +1 -1
  68. package/v3/dist/index.d.ts +1 -1
  69. package/v3/dist/index.d.ts.map +1 -1
  70. package/v3/dist/index.js +1 -1
  71. package/v3/dist/index.js.map +1 -1
  72. package/v3/dist/init/migration/data-migrator.d.ts.map +1 -1
  73. package/v3/dist/init/migration/data-migrator.js +5 -6
  74. package/v3/dist/init/migration/data-migrator.js.map +1 -1
  75. package/v3/dist/init/phases/07-hooks.d.ts.map +1 -1
  76. package/v3/dist/init/phases/07-hooks.js +26 -5
  77. package/v3/dist/init/phases/07-hooks.js.map +1 -1
  78. package/v3/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +4 -2
  79. package/v3/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts.map +1 -1
  80. package/v3/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +68 -42
  81. package/v3/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js.map +1 -1
  82. package/v3/dist/integrations/ruvector/ast-complexity.d.ts +8 -0
  83. package/v3/dist/integrations/ruvector/ast-complexity.d.ts.map +1 -1
  84. package/v3/dist/integrations/ruvector/ast-complexity.js +45 -0
  85. package/v3/dist/integrations/ruvector/ast-complexity.js.map +1 -1
  86. package/v3/dist/integrations/ruvector/attention-wrapper.d.ts +18 -1
  87. package/v3/dist/integrations/ruvector/attention-wrapper.d.ts.map +1 -1
  88. package/v3/dist/integrations/ruvector/attention-wrapper.js +60 -2
  89. package/v3/dist/integrations/ruvector/attention-wrapper.js.map +1 -1
  90. package/v3/dist/integrations/ruvector/coverage-router.d.ts +8 -0
  91. package/v3/dist/integrations/ruvector/coverage-router.d.ts.map +1 -1
  92. package/v3/dist/integrations/ruvector/coverage-router.js +45 -0
  93. package/v3/dist/integrations/ruvector/coverage-router.js.map +1 -1
  94. package/v3/dist/integrations/ruvector/diff-risk-classifier.d.ts +8 -0
  95. package/v3/dist/integrations/ruvector/diff-risk-classifier.d.ts.map +1 -1
  96. package/v3/dist/integrations/ruvector/diff-risk-classifier.js +45 -0
  97. package/v3/dist/integrations/ruvector/diff-risk-classifier.js.map +1 -1
  98. package/v3/dist/integrations/ruvector/graph-boundaries.d.ts +8 -0
  99. package/v3/dist/integrations/ruvector/graph-boundaries.d.ts.map +1 -1
  100. package/v3/dist/integrations/ruvector/graph-boundaries.js +45 -0
  101. package/v3/dist/integrations/ruvector/graph-boundaries.js.map +1 -1
  102. package/v3/dist/integrations/ruvector/index.d.ts.map +1 -1
  103. package/v3/dist/integrations/ruvector/index.js +5 -20
  104. package/v3/dist/integrations/ruvector/index.js.map +1 -1
  105. package/v3/dist/integrations/ruvector/persistent-q-router.d.ts +7 -3
  106. package/v3/dist/integrations/ruvector/persistent-q-router.d.ts.map +1 -1
  107. package/v3/dist/integrations/ruvector/persistent-q-router.js +7 -3
  108. package/v3/dist/integrations/ruvector/persistent-q-router.js.map +1 -1
  109. package/v3/dist/integrations/ruvector/q-learning-router.d.ts +13 -0
  110. package/v3/dist/integrations/ruvector/q-learning-router.d.ts.map +1 -1
  111. package/v3/dist/integrations/ruvector/q-learning-router.js +67 -0
  112. package/v3/dist/integrations/ruvector/q-learning-router.js.map +1 -1
  113. package/v3/dist/kernel/hybrid-backend.d.ts +1 -0
  114. package/v3/dist/kernel/hybrid-backend.d.ts.map +1 -1
  115. package/v3/dist/kernel/hybrid-backend.js +39 -0
  116. package/v3/dist/kernel/hybrid-backend.js.map +1 -1
  117. package/v3/dist/kernel/kernel.d.ts.map +1 -1
  118. package/v3/dist/kernel/kernel.js +8 -0
  119. package/v3/dist/kernel/kernel.js.map +1 -1
  120. package/v3/dist/kernel/unified-memory.d.ts +1 -0
  121. package/v3/dist/kernel/unified-memory.d.ts.map +1 -1
  122. package/v3/dist/kernel/unified-memory.js +123 -4
  123. package/v3/dist/kernel/unified-memory.js.map +1 -1
  124. package/v3/dist/learning/experience-capture-middleware.d.ts.map +1 -1
  125. package/v3/dist/learning/experience-capture-middleware.js +45 -18
  126. package/v3/dist/learning/experience-capture-middleware.js.map +1 -1
  127. package/v3/dist/learning/pattern-store.d.ts.map +1 -1
  128. package/v3/dist/learning/pattern-store.js +12 -61
  129. package/v3/dist/learning/pattern-store.js.map +1 -1
  130. package/v3/dist/learning/qe-reasoning-bank.d.ts.map +1 -1
  131. package/v3/dist/learning/qe-reasoning-bank.js +15 -2
  132. package/v3/dist/learning/qe-reasoning-bank.js.map +1 -1
  133. package/v3/dist/learning/token-tracker.d.ts +23 -0
  134. package/v3/dist/learning/token-tracker.d.ts.map +1 -1
  135. package/v3/dist/learning/token-tracker.js +91 -0
  136. package/v3/dist/learning/token-tracker.js.map +1 -1
  137. package/v3/dist/mcp/bundle.js +945 -375
  138. package/v3/dist/mcp/entry.js +21 -1
  139. package/v3/dist/mcp/entry.js.map +1 -1
  140. package/v3/dist/routing/routing-feedback.d.ts +21 -0
  141. package/v3/dist/routing/routing-feedback.d.ts.map +1 -1
  142. package/v3/dist/routing/routing-feedback.js +95 -0
  143. package/v3/dist/routing/routing-feedback.js.map +1 -1
  144. package/v3/dist/shared/sql-safety.d.ts.map +1 -1
  145. package/v3/dist/shared/sql-safety.js +2 -0
  146. package/v3/dist/shared/sql-safety.js.map +1 -1
  147. package/v3/package.json +1 -1
@@ -4179,6 +4179,10 @@ var init_sql_safety = __esm({
4179
4179
  "mincut_observations",
4180
4180
  // SONA tables
4181
4181
  "sona_patterns",
4182
+ // Feedback loop tables
4183
+ "test_outcomes",
4184
+ "routing_outcomes",
4185
+ "coverage_sessions",
4182
4186
  // Sync tables
4183
4187
  "patterns",
4184
4188
  // Hypergraph tables
@@ -5123,12 +5127,16 @@ function findProjectRoot(startDir = process.cwd()) {
5123
5127
  let dir = startDir;
5124
5128
  const root = path.parse(dir).root;
5125
5129
  let checkDir = dir;
5130
+ let topmostAqeDir = null;
5126
5131
  while (checkDir !== root) {
5127
5132
  if (fs.existsSync(path.join(checkDir, ".agentic-qe"))) {
5128
- return checkDir;
5133
+ topmostAqeDir = checkDir;
5129
5134
  }
5130
5135
  checkDir = path.dirname(checkDir);
5131
5136
  }
5137
+ if (topmostAqeDir) {
5138
+ return topmostAqeDir;
5139
+ }
5132
5140
  checkDir = dir;
5133
5141
  while (checkDir !== root) {
5134
5142
  if (fs.existsSync(path.join(checkDir, ".git"))) {
@@ -5193,7 +5201,7 @@ function registerExitHandlers() {
5193
5201
  process.exit(0);
5194
5202
  });
5195
5203
  }
5196
- var DEFAULT_UNIFIED_MEMORY_CONFIG, SCHEMA_VERSION, SCHEMA_VERSION_TABLE, KV_STORE_SCHEMA, VECTORS_SCHEMA, RL_QVALUES_SCHEMA, GOAP_SCHEMA, DREAM_SCHEMA, QE_PATTERNS_SCHEMA, MINCUT_SCHEMA, SONA_PATTERNS_SCHEMA, BinaryHeap, InMemoryHNSWIndex, UnifiedMemoryManager, exitHandlersRegistered;
5204
+ var DEFAULT_UNIFIED_MEMORY_CONFIG, SCHEMA_VERSION, SCHEMA_VERSION_TABLE, KV_STORE_SCHEMA, VECTORS_SCHEMA, RL_QVALUES_SCHEMA, GOAP_SCHEMA, DREAM_SCHEMA, QE_PATTERNS_SCHEMA, MINCUT_SCHEMA, SONA_PATTERNS_SCHEMA, FEEDBACK_SCHEMA, BinaryHeap, InMemoryHNSWIndex, UnifiedMemoryManager, exitHandlersRegistered;
5197
5205
  var init_unified_memory = __esm({
5198
5206
  "src/kernel/unified-memory.ts"() {
5199
5207
  "use strict";
@@ -5213,7 +5221,7 @@ var init_unified_memory = __esm({
5213
5221
  busyTimeout: MEMORY_CONSTANTS.BUSY_TIMEOUT_MS,
5214
5222
  vectorDimensions: MEMORY_CONSTANTS.DEFAULT_VECTOR_DIMENSIONS
5215
5223
  };
5216
- SCHEMA_VERSION = 7;
5224
+ SCHEMA_VERSION = 8;
5217
5225
  SCHEMA_VERSION_TABLE = `
5218
5226
  CREATE TABLE IF NOT EXISTS schema_version (
5219
5227
  id INTEGER PRIMARY KEY CHECK (id = 1),
@@ -5684,6 +5692,81 @@ var init_unified_memory = __esm({
5684
5692
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_domain ON sona_patterns(domain);
5685
5693
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_confidence ON sona_patterns(confidence DESC);
5686
5694
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_updated ON sona_patterns(updated_at DESC);
5695
+ `;
5696
+ FEEDBACK_SCHEMA = `
5697
+ -- Test outcomes (ADR-023: Quality Feedback Loop)
5698
+ CREATE TABLE IF NOT EXISTS test_outcomes (
5699
+ id TEXT PRIMARY KEY,
5700
+ test_id TEXT NOT NULL,
5701
+ test_name TEXT NOT NULL,
5702
+ generated_by TEXT NOT NULL,
5703
+ pattern_id TEXT,
5704
+ framework TEXT NOT NULL,
5705
+ language TEXT NOT NULL,
5706
+ domain TEXT NOT NULL,
5707
+ passed INTEGER NOT NULL,
5708
+ error_message TEXT,
5709
+ coverage_lines REAL DEFAULT 0,
5710
+ coverage_branches REAL DEFAULT 0,
5711
+ coverage_functions REAL DEFAULT 0,
5712
+ mutation_score REAL,
5713
+ execution_time_ms REAL NOT NULL,
5714
+ flaky INTEGER DEFAULT 0,
5715
+ flakiness_score REAL,
5716
+ maintainability_score REAL NOT NULL,
5717
+ complexity REAL,
5718
+ lines_of_code INTEGER,
5719
+ assertion_count INTEGER,
5720
+ file_path TEXT,
5721
+ source_file_path TEXT,
5722
+ metadata_json TEXT,
5723
+ created_at TEXT DEFAULT (datetime('now'))
5724
+ );
5725
+ CREATE INDEX IF NOT EXISTS idx_test_outcomes_pattern ON test_outcomes(pattern_id);
5726
+ CREATE INDEX IF NOT EXISTS idx_test_outcomes_agent ON test_outcomes(generated_by);
5727
+ CREATE INDEX IF NOT EXISTS idx_test_outcomes_domain ON test_outcomes(domain);
5728
+ CREATE INDEX IF NOT EXISTS idx_test_outcomes_created ON test_outcomes(created_at);
5729
+
5730
+ -- Routing outcomes (ADR-022: Adaptive QE Agent Routing)
5731
+ CREATE TABLE IF NOT EXISTS routing_outcomes (
5732
+ id TEXT PRIMARY KEY,
5733
+ task_json TEXT NOT NULL,
5734
+ decision_json TEXT NOT NULL,
5735
+ used_agent TEXT NOT NULL,
5736
+ followed_recommendation INTEGER NOT NULL,
5737
+ success INTEGER NOT NULL,
5738
+ quality_score REAL NOT NULL,
5739
+ duration_ms REAL NOT NULL,
5740
+ error TEXT,
5741
+ created_at TEXT DEFAULT (datetime('now'))
5742
+ );
5743
+ CREATE INDEX IF NOT EXISTS idx_routing_outcomes_agent ON routing_outcomes(used_agent);
5744
+ CREATE INDEX IF NOT EXISTS idx_routing_outcomes_created ON routing_outcomes(created_at);
5745
+
5746
+ -- Coverage sessions (ADR-023: Coverage Learning)
5747
+ CREATE TABLE IF NOT EXISTS coverage_sessions (
5748
+ id TEXT PRIMARY KEY,
5749
+ target_path TEXT NOT NULL,
5750
+ agent_id TEXT NOT NULL,
5751
+ technique TEXT NOT NULL,
5752
+ before_lines REAL DEFAULT 0,
5753
+ before_branches REAL DEFAULT 0,
5754
+ before_functions REAL DEFAULT 0,
5755
+ after_lines REAL DEFAULT 0,
5756
+ after_branches REAL DEFAULT 0,
5757
+ after_functions REAL DEFAULT 0,
5758
+ tests_generated INTEGER DEFAULT 0,
5759
+ tests_passed INTEGER DEFAULT 0,
5760
+ gaps_json TEXT,
5761
+ duration_ms REAL NOT NULL,
5762
+ started_at TEXT NOT NULL,
5763
+ completed_at TEXT NOT NULL,
5764
+ context_json TEXT,
5765
+ created_at TEXT DEFAULT (datetime('now'))
5766
+ );
5767
+ CREATE INDEX IF NOT EXISTS idx_coverage_sessions_technique ON coverage_sessions(technique);
5768
+ CREATE INDEX IF NOT EXISTS idx_coverage_sessions_agent ON coverage_sessions(agent_id);
5769
+ CREATE INDEX IF NOT EXISTS idx_coverage_sessions_created ON coverage_sessions(created_at);
5687
5770
  `;
5688
5771
  BinaryHeap = class {
5689
5772
  data = [];
@@ -6023,6 +6106,7 @@ var init_unified_memory = __esm({
6023
6106
  db = null;
6024
6107
  config;
6025
6108
  initialized = false;
6109
+ vectorsLoaded = false;
6026
6110
  initPromise = null;
6027
6111
  preparedStatements = /* @__PURE__ */ new Map();
6028
6112
  vectorIndex = new InMemoryHNSWIndex();
@@ -6031,6 +6115,10 @@ var init_unified_memory = __esm({
6031
6115
  constructor(config) {
6032
6116
  const resolvedDefaults = getResolvedDefaultConfig();
6033
6117
  this.config = { ...resolvedDefaults, ...config };
6118
+ if (!path.isAbsolute(this.config.dbPath)) {
6119
+ const projectRoot = findProjectRoot();
6120
+ this.config.dbPath = path.join(projectRoot, this.config.dbPath);
6121
+ }
6034
6122
  }
6035
6123
  /**
6036
6124
  * Get or create the singleton instance (synchronous).
@@ -6100,7 +6188,7 @@ var init_unified_memory = __esm({
6100
6188
  this.db.pragma(`busy_timeout = ${this.config.busyTimeout}`);
6101
6189
  this.db.pragma("foreign_keys = ON");
6102
6190
  await this.runMigrations();
6103
- await this.loadVectorIndex();
6191
+ this.vectorsLoaded = false;
6104
6192
  this.initialized = true;
6105
6193
  console.log(`[UnifiedMemory] Initialized: ${this.config.dbPath}`);
6106
6194
  this.warnIfDuplicateDatabases();
@@ -6221,6 +6309,9 @@ var init_unified_memory = __esm({
6221
6309
  if (currentVersion < 7) {
6222
6310
  this.db.exec(SONA_PATTERNS_SCHEMA);
6223
6311
  }
6312
+ if (currentVersion < 8) {
6313
+ this.db.exec(FEEDBACK_SCHEMA);
6314
+ }
6224
6315
  this.db.prepare(`
6225
6316
  INSERT OR REPLACE INTO schema_version (id, version, migrated_at)
6226
6317
  VALUES (1, ?, datetime('now'))
@@ -6234,6 +6325,7 @@ var init_unified_memory = __esm({
6234
6325
  * Load all vectors from SQLite into HNSW index
6235
6326
  */
6236
6327
  async loadVectorIndex() {
6328
+ if (this.vectorsLoaded) return;
6237
6329
  if (!this.db) throw new Error("Database not initialized");
6238
6330
  this.vectorIndex.clear();
6239
6331
  const rows = this.db.prepare(
@@ -6243,6 +6335,7 @@ var init_unified_memory = __esm({
6243
6335
  const embedding = this.bufferToFloatArray(row2.embedding, row2.dimensions);
6244
6336
  this.vectorIndex.add(row2.id, embedding);
6245
6337
  }
6338
+ this.vectorsLoaded = true;
6246
6339
  console.log(`[UnifiedMemory] Loaded ${rows.length} vectors into HNSW index`);
6247
6340
  }
6248
6341
  // ============================================================================
@@ -6366,6 +6459,9 @@ var init_unified_memory = __esm({
6366
6459
  */
6367
6460
  async vectorSearch(query, k68 = 10, namespace) {
6368
6461
  this.ensureInitialized();
6462
+ if (!this.vectorsLoaded) {
6463
+ await this.loadVectorIndex();
6464
+ }
6369
6465
  const results = this.vectorIndex.search(query, k68 * 2);
6370
6466
  if (results.length === 0) return [];
6371
6467
  const ids = results.map((r54) => r54.id);
@@ -6988,6 +7084,211 @@ var init_real_embeddings = __esm({
6988
7084
  }
6989
7085
  });
6990
7086
 
7087
+ // src/kernel/unified-persistence.ts
7088
+ function getUnifiedPersistence(config) {
7089
+ return UnifiedPersistenceManager.getInstance(config);
7090
+ }
7091
+ async function initializeUnifiedPersistence(config) {
7092
+ const manager = getUnifiedPersistence(config);
7093
+ await manager.initialize();
7094
+ return manager;
7095
+ }
7096
+ function registerExitHandlers2() {
7097
+ if (exitHandlersRegistered2) return;
7098
+ exitHandlersRegistered2 = true;
7099
+ const cleanup = () => {
7100
+ try {
7101
+ const instance3 = UnifiedPersistenceManager["instance"];
7102
+ if (instance3) {
7103
+ instance3.close();
7104
+ }
7105
+ } catch (error) {
7106
+ console.debug("[UnifiedPersistence] Cleanup error:", error instanceof Error ? error.message : error);
7107
+ }
7108
+ };
7109
+ process.on("beforeExit", cleanup);
7110
+ process.on("SIGINT", () => {
7111
+ cleanup();
7112
+ process.exit(0);
7113
+ });
7114
+ process.on("SIGTERM", () => {
7115
+ cleanup();
7116
+ process.exit(0);
7117
+ });
7118
+ }
7119
+ var DEFAULT_UNIFIED_CONFIG, UnifiedPersistenceManager, exitHandlersRegistered2;
7120
+ var init_unified_persistence = __esm({
7121
+ "src/kernel/unified-persistence.ts"() {
7122
+ "use strict";
7123
+ init_unified_memory();
7124
+ DEFAULT_UNIFIED_CONFIG = {
7125
+ dbPath: DEFAULT_UNIFIED_MEMORY_CONFIG.dbPath,
7126
+ // '.agentic-qe/memory.db'
7127
+ walMode: true,
7128
+ mmapSize: 64 * 1024 * 1024,
7129
+ // 64MB
7130
+ cacheSize: -32e3,
7131
+ // 32MB
7132
+ busyTimeout: 5e3
7133
+ };
7134
+ UnifiedPersistenceManager = class _UnifiedPersistenceManager {
7135
+ static instance = null;
7136
+ static instancePromise = null;
7137
+ unifiedMemory = null;
7138
+ config;
7139
+ initialized = false;
7140
+ initPromise = null;
7141
+ constructor(config) {
7142
+ this.config = { ...DEFAULT_UNIFIED_CONFIG, ...config };
7143
+ }
7144
+ /**
7145
+ * Get or create the singleton instance (synchronous).
7146
+ * Thread-safe: JS is single-threaded for synchronous code.
7147
+ */
7148
+ static getInstance(config) {
7149
+ if (_UnifiedPersistenceManager.instance) {
7150
+ return _UnifiedPersistenceManager.instance;
7151
+ }
7152
+ _UnifiedPersistenceManager.instance = new _UnifiedPersistenceManager(config);
7153
+ return _UnifiedPersistenceManager.instance;
7154
+ }
7155
+ /**
7156
+ * Get or create the singleton instance with async initialization.
7157
+ * Thread-safe: Uses Promise lock to prevent concurrent initialization races.
7158
+ */
7159
+ static async getInstanceAsync(config) {
7160
+ if (_UnifiedPersistenceManager.instance?.initialized) {
7161
+ return _UnifiedPersistenceManager.instance;
7162
+ }
7163
+ if (!_UnifiedPersistenceManager.instancePromise) {
7164
+ _UnifiedPersistenceManager.instancePromise = (async () => {
7165
+ const instance3 = _UnifiedPersistenceManager.getInstance(config);
7166
+ await instance3.initialize();
7167
+ return instance3;
7168
+ })();
7169
+ }
7170
+ return _UnifiedPersistenceManager.instancePromise;
7171
+ }
7172
+ /**
7173
+ * Reset the singleton (for testing)
7174
+ */
7175
+ static resetInstance() {
7176
+ if (_UnifiedPersistenceManager.instance) {
7177
+ _UnifiedPersistenceManager.instance.close();
7178
+ _UnifiedPersistenceManager.instance = null;
7179
+ }
7180
+ _UnifiedPersistenceManager.instancePromise = null;
7181
+ resetUnifiedMemory();
7182
+ }
7183
+ /**
7184
+ * Initialize the database and create all schemas.
7185
+ * Thread-safe: Uses Promise lock to prevent concurrent initialization races.
7186
+ */
7187
+ async initialize() {
7188
+ if (this.initialized) return;
7189
+ if (!this.initPromise) {
7190
+ this.initPromise = this._doInitialize();
7191
+ }
7192
+ return this.initPromise;
7193
+ }
7194
+ /**
7195
+ * Internal initialization implementation
7196
+ */
7197
+ async _doInitialize() {
7198
+ if (this.initialized) return;
7199
+ try {
7200
+ const memoryConfig = {
7201
+ dbPath: this.config.dbPath,
7202
+ walMode: this.config.walMode,
7203
+ busyTimeout: this.config.busyTimeout,
7204
+ mmapSize: this.config.mmapSize,
7205
+ cacheSize: this.config.cacheSize
7206
+ };
7207
+ this.unifiedMemory = getUnifiedMemory(memoryConfig);
7208
+ await this.unifiedMemory.initialize();
7209
+ this.initialized = true;
7210
+ console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`);
7211
+ } catch (error) {
7212
+ this.initPromise = null;
7213
+ throw new Error(
7214
+ `Failed to initialize UnifiedPersistenceManager: ${error instanceof Error ? error.message : String(error)}`
7215
+ );
7216
+ }
7217
+ }
7218
+ /**
7219
+ * Get the raw database connection for advanced operations
7220
+ */
7221
+ getDatabase() {
7222
+ if (!this.unifiedMemory || !this.initialized) {
7223
+ throw new Error("UnifiedPersistenceManager not initialized");
7224
+ }
7225
+ return this.unifiedMemory.getDatabase();
7226
+ }
7227
+ /**
7228
+ * Check if initialized
7229
+ */
7230
+ isInitialized() {
7231
+ return this.initialized;
7232
+ }
7233
+ /**
7234
+ * Get the database path
7235
+ */
7236
+ getDbPath() {
7237
+ return this.config.dbPath;
7238
+ }
7239
+ /**
7240
+ * Prepare and cache a statement
7241
+ */
7242
+ prepare(name, sql) {
7243
+ if (!this.unifiedMemory) throw new Error("Database not initialized");
7244
+ return this.unifiedMemory.prepare(name, sql);
7245
+ }
7246
+ /**
7247
+ * Execute a transaction
7248
+ */
7249
+ transaction(fn) {
7250
+ if (!this.unifiedMemory) throw new Error("Database not initialized");
7251
+ return this.unifiedMemory.transaction(fn);
7252
+ }
7253
+ /**
7254
+ * Get database statistics
7255
+ */
7256
+ getStats() {
7257
+ if (!this.unifiedMemory) throw new Error("Database not initialized");
7258
+ const memStats = this.unifiedMemory.getStats();
7259
+ return {
7260
+ tables: memStats.tables,
7261
+ fileSize: memStats.fileSize,
7262
+ walSize: memStats.walSize
7263
+ };
7264
+ }
7265
+ /**
7266
+ * Vacuum the database to reclaim space
7267
+ */
7268
+ vacuum() {
7269
+ const db = this.getDatabase();
7270
+ db.exec("VACUUM");
7271
+ }
7272
+ /**
7273
+ * Checkpoint WAL to main database
7274
+ */
7275
+ checkpoint() {
7276
+ const db = this.getDatabase();
7277
+ db.pragma("wal_checkpoint(TRUNCATE)");
7278
+ }
7279
+ /**
7280
+ * Close the database connection
7281
+ */
7282
+ close() {
7283
+ this.initialized = false;
7284
+ console.log("[UnifiedPersistence] Facade closed");
7285
+ }
7286
+ };
7287
+ exitHandlersRegistered2 = false;
7288
+ registerExitHandlers2();
7289
+ }
7290
+ });
7291
+
6991
7292
  // src/coordination/consensus/model-provider.ts
6992
7293
  function buildVerificationPrompt(finding, options = {}) {
6993
7294
  const {
@@ -9416,206 +9717,6 @@ var init_sona_wrapper = __esm({
9416
9717
  }
9417
9718
  });
9418
9719
 
9419
- // src/kernel/unified-persistence.ts
9420
- function getUnifiedPersistence(config) {
9421
- return UnifiedPersistenceManager.getInstance(config);
9422
- }
9423
- function registerExitHandlers2() {
9424
- if (exitHandlersRegistered2) return;
9425
- exitHandlersRegistered2 = true;
9426
- const cleanup = () => {
9427
- try {
9428
- const instance3 = UnifiedPersistenceManager["instance"];
9429
- if (instance3) {
9430
- instance3.close();
9431
- }
9432
- } catch (error) {
9433
- console.debug("[UnifiedPersistence] Cleanup error:", error instanceof Error ? error.message : error);
9434
- }
9435
- };
9436
- process.on("beforeExit", cleanup);
9437
- process.on("SIGINT", () => {
9438
- cleanup();
9439
- process.exit(0);
9440
- });
9441
- process.on("SIGTERM", () => {
9442
- cleanup();
9443
- process.exit(0);
9444
- });
9445
- }
9446
- var DEFAULT_UNIFIED_CONFIG, UnifiedPersistenceManager, exitHandlersRegistered2;
9447
- var init_unified_persistence = __esm({
9448
- "src/kernel/unified-persistence.ts"() {
9449
- "use strict";
9450
- init_unified_memory();
9451
- DEFAULT_UNIFIED_CONFIG = {
9452
- dbPath: DEFAULT_UNIFIED_MEMORY_CONFIG.dbPath,
9453
- // '.agentic-qe/memory.db'
9454
- walMode: true,
9455
- mmapSize: 64 * 1024 * 1024,
9456
- // 64MB
9457
- cacheSize: -32e3,
9458
- // 32MB
9459
- busyTimeout: 5e3
9460
- };
9461
- UnifiedPersistenceManager = class _UnifiedPersistenceManager {
9462
- static instance = null;
9463
- static instancePromise = null;
9464
- unifiedMemory = null;
9465
- config;
9466
- initialized = false;
9467
- initPromise = null;
9468
- constructor(config) {
9469
- this.config = { ...DEFAULT_UNIFIED_CONFIG, ...config };
9470
- }
9471
- /**
9472
- * Get or create the singleton instance (synchronous).
9473
- * Thread-safe: JS is single-threaded for synchronous code.
9474
- */
9475
- static getInstance(config) {
9476
- if (_UnifiedPersistenceManager.instance) {
9477
- return _UnifiedPersistenceManager.instance;
9478
- }
9479
- _UnifiedPersistenceManager.instance = new _UnifiedPersistenceManager(config);
9480
- return _UnifiedPersistenceManager.instance;
9481
- }
9482
- /**
9483
- * Get or create the singleton instance with async initialization.
9484
- * Thread-safe: Uses Promise lock to prevent concurrent initialization races.
9485
- */
9486
- static async getInstanceAsync(config) {
9487
- if (_UnifiedPersistenceManager.instance?.initialized) {
9488
- return _UnifiedPersistenceManager.instance;
9489
- }
9490
- if (!_UnifiedPersistenceManager.instancePromise) {
9491
- _UnifiedPersistenceManager.instancePromise = (async () => {
9492
- const instance3 = _UnifiedPersistenceManager.getInstance(config);
9493
- await instance3.initialize();
9494
- return instance3;
9495
- })();
9496
- }
9497
- return _UnifiedPersistenceManager.instancePromise;
9498
- }
9499
- /**
9500
- * Reset the singleton (for testing)
9501
- */
9502
- static resetInstance() {
9503
- if (_UnifiedPersistenceManager.instance) {
9504
- _UnifiedPersistenceManager.instance.close();
9505
- _UnifiedPersistenceManager.instance = null;
9506
- }
9507
- _UnifiedPersistenceManager.instancePromise = null;
9508
- resetUnifiedMemory();
9509
- }
9510
- /**
9511
- * Initialize the database and create all schemas.
9512
- * Thread-safe: Uses Promise lock to prevent concurrent initialization races.
9513
- */
9514
- async initialize() {
9515
- if (this.initialized) return;
9516
- if (!this.initPromise) {
9517
- this.initPromise = this._doInitialize();
9518
- }
9519
- return this.initPromise;
9520
- }
9521
- /**
9522
- * Internal initialization implementation
9523
- */
9524
- async _doInitialize() {
9525
- if (this.initialized) return;
9526
- try {
9527
- const memoryConfig = {
9528
- dbPath: this.config.dbPath,
9529
- walMode: this.config.walMode,
9530
- busyTimeout: this.config.busyTimeout,
9531
- mmapSize: this.config.mmapSize,
9532
- cacheSize: this.config.cacheSize
9533
- };
9534
- this.unifiedMemory = getUnifiedMemory(memoryConfig);
9535
- await this.unifiedMemory.initialize();
9536
- this.initialized = true;
9537
- console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`);
9538
- } catch (error) {
9539
- this.initPromise = null;
9540
- throw new Error(
9541
- `Failed to initialize UnifiedPersistenceManager: ${error instanceof Error ? error.message : String(error)}`
9542
- );
9543
- }
9544
- }
9545
- /**
9546
- * Get the raw database connection for advanced operations
9547
- */
9548
- getDatabase() {
9549
- if (!this.unifiedMemory || !this.initialized) {
9550
- throw new Error("UnifiedPersistenceManager not initialized");
9551
- }
9552
- return this.unifiedMemory.getDatabase();
9553
- }
9554
- /**
9555
- * Check if initialized
9556
- */
9557
- isInitialized() {
9558
- return this.initialized;
9559
- }
9560
- /**
9561
- * Get the database path
9562
- */
9563
- getDbPath() {
9564
- return this.config.dbPath;
9565
- }
9566
- /**
9567
- * Prepare and cache a statement
9568
- */
9569
- prepare(name, sql) {
9570
- if (!this.unifiedMemory) throw new Error("Database not initialized");
9571
- return this.unifiedMemory.prepare(name, sql);
9572
- }
9573
- /**
9574
- * Execute a transaction
9575
- */
9576
- transaction(fn) {
9577
- if (!this.unifiedMemory) throw new Error("Database not initialized");
9578
- return this.unifiedMemory.transaction(fn);
9579
- }
9580
- /**
9581
- * Get database statistics
9582
- */
9583
- getStats() {
9584
- if (!this.unifiedMemory) throw new Error("Database not initialized");
9585
- const memStats = this.unifiedMemory.getStats();
9586
- return {
9587
- tables: memStats.tables,
9588
- fileSize: memStats.fileSize,
9589
- walSize: memStats.walSize
9590
- };
9591
- }
9592
- /**
9593
- * Vacuum the database to reclaim space
9594
- */
9595
- vacuum() {
9596
- const db = this.getDatabase();
9597
- db.exec("VACUUM");
9598
- }
9599
- /**
9600
- * Checkpoint WAL to main database
9601
- */
9602
- checkpoint() {
9603
- const db = this.getDatabase();
9604
- db.pragma("wal_checkpoint(TRUNCATE)");
9605
- }
9606
- /**
9607
- * Close the database connection
9608
- */
9609
- close() {
9610
- this.initialized = false;
9611
- console.log("[UnifiedPersistence] Facade closed");
9612
- }
9613
- };
9614
- exitHandlersRegistered2 = false;
9615
- registerExitHandlers2();
9616
- }
9617
- });
9618
-
9619
9720
  // native-require:@ruvector/attention
9620
9721
  var attention_exports = {};
9621
9722
  __export(attention_exports, {
@@ -9720,6 +9821,7 @@ var init_attention_wrapper = __esm({
9720
9821
  "src/integrations/ruvector/attention-wrapper.ts"() {
9721
9822
  "use strict";
9722
9823
  init_attention();
9824
+ init_unified_memory();
9723
9825
  QE_FLASH_ATTENTION_CONFIG = {
9724
9826
  "test-similarity": {
9725
9827
  dim: 384,
@@ -9833,11 +9935,19 @@ var init_attention_wrapper = __esm({
9833
9935
  }
9834
9936
  }
9835
9937
  };
9836
- QEFlashAttention = class {
9938
+ QEFlashAttention = class _QEFlashAttention {
9837
9939
  attention;
9838
9940
  config;
9839
9941
  workload;
9840
9942
  metrics = [];
9943
+ // kv_store persistence
9944
+ db = null;
9945
+ persistCount = 0;
9946
+ static KV_NAMESPACE = "attention-metrics";
9947
+ static KV_TTL = 3600;
9948
+ // 1 hour
9949
+ static PERSIST_INTERVAL = 10;
9950
+ // every 10 operations
9841
9951
  constructor(workload, customConfig) {
9842
9952
  this.workload = workload;
9843
9953
  const baseConfig = QE_FLASH_ATTENTION_CONFIG[workload];
@@ -9848,10 +9958,18 @@ var init_attention_wrapper = __esm({
9848
9958
  this.attention = AttentionFactory.create(this.config);
9849
9959
  }
9850
9960
  /**
9851
- * Initialize Flash Attention
9961
+ * Initialize Flash Attention and kv_store persistence
9852
9962
  * Note: @ruvector/attention doesn't require async initialization
9853
9963
  */
9854
9964
  async initialize() {
9965
+ try {
9966
+ this.db = getUnifiedMemory();
9967
+ if (!this.db.isInitialized()) await this.db.initialize();
9968
+ await this.loadFromKv();
9969
+ } catch (error) {
9970
+ console.warn("[QEFlashAttention] DB init failed, using memory-only:", error instanceof Error ? error.message : String(error));
9971
+ this.db = null;
9972
+ }
9855
9973
  }
9856
9974
  /**
9857
9975
  * Compute Flash Attention using @ruvector/attention
@@ -9896,6 +10014,7 @@ var init_attention_wrapper = __esm({
9896
10014
  throughput: seqLen * seqLen / ((endTime - startTime) / 1e3),
9897
10015
  peakMemoryMB: endMemory
9898
10016
  });
10017
+ this.maybePersistToKv();
9899
10018
  return output;
9900
10019
  }
9901
10020
  /**
@@ -10062,6 +10181,49 @@ var init_attention_wrapper = __esm({
10062
10181
  this.metrics = [];
10063
10182
  }
10064
10183
  // ========================================================================
10184
+ // kv_store Persistence
10185
+ // ========================================================================
10186
+ /**
10187
+ * Persist metrics snapshot to kv_store
10188
+ */
10189
+ async persistToKv() {
10190
+ if (!this.db) return;
10191
+ const kvKey = `attention-metrics-${this.workload}`;
10192
+ const snapshot = {
10193
+ workload: this.workload,
10194
+ metrics: this.metrics.slice(-50),
10195
+ savedAt: Date.now()
10196
+ };
10197
+ await this.db.kvSet(
10198
+ kvKey,
10199
+ snapshot,
10200
+ _QEFlashAttention.KV_NAMESPACE,
10201
+ _QEFlashAttention.KV_TTL
10202
+ );
10203
+ }
10204
+ /**
10205
+ * Load metrics snapshot from kv_store
10206
+ */
10207
+ async loadFromKv() {
10208
+ if (!this.db) return;
10209
+ const kvKey = `attention-metrics-${this.workload}`;
10210
+ const snapshot = await this.db.kvGet(kvKey, _QEFlashAttention.KV_NAMESPACE);
10211
+ if (snapshot?.metrics?.length) {
10212
+ this.metrics = snapshot.metrics;
10213
+ }
10214
+ }
10215
+ /**
10216
+ * Track operations and persist periodically
10217
+ */
10218
+ maybePersistToKv() {
10219
+ this.persistCount++;
10220
+ if (this.persistCount >= _QEFlashAttention.PERSIST_INTERVAL) {
10221
+ this.persistCount = 0;
10222
+ this.persistToKv().catch(() => {
10223
+ });
10224
+ }
10225
+ }
10226
+ // ========================================================================
10065
10227
  // Private Helper Methods
10066
10228
  // ========================================================================
10067
10229
  /**
@@ -10860,8 +11022,6 @@ var init_hnsw_index = __esm({
10860
11022
  const embedding = this.vectorToEmbedding(vector, key, metadata);
10861
11023
  this.ruvectorIndex.addEmbedding(embedding, label);
10862
11024
  this.vectorStore.set(key, vector);
10863
- const fullKey = this.buildKey(key);
10864
- await this.memory.storeVector(fullKey, vector, metadata);
10865
11025
  this.stats.insertOperations++;
10866
11026
  this.stats.vectorCount++;
10867
11027
  }
@@ -18305,31 +18465,6 @@ var init_pattern_store = __esm({
18305
18465
  * Load existing patterns from memory with timeout protection
18306
18466
  */
18307
18467
  async loadPatterns() {
18308
- try {
18309
- const timeoutMs = 5e3;
18310
- const searchPromise = this.memory.search(`${this.config.namespace}:pattern:*`, 1e4);
18311
- const timeoutPromise = new Promise(
18312
- (_56, reject) => setTimeout(() => reject(new Error("Pattern load timeout")), timeoutMs)
18313
- );
18314
- const keys = await Promise.race([searchPromise, timeoutPromise]);
18315
- const BATCH_SIZE = 50;
18316
- for (let i58 = 0; i58 < keys.length; i58 += BATCH_SIZE) {
18317
- const batch = keys.slice(i58, i58 + BATCH_SIZE);
18318
- const patterns = await Promise.all(
18319
- batch.map((key) => this.memory.get(key).catch(() => null))
18320
- );
18321
- for (const pattern of patterns) {
18322
- if (pattern) {
18323
- this.indexPattern(pattern);
18324
- }
18325
- }
18326
- }
18327
- if (this.patternCache.size > 0) {
18328
- console.log(`[PatternStore] Loaded ${this.patternCache.size} patterns`);
18329
- }
18330
- } catch (error) {
18331
- console.log(`[PatternStore] Starting fresh (no existing patterns loaded): ${error instanceof Error ? error.message : "unknown error"}`);
18332
- }
18333
18468
  }
18334
18469
  /**
18335
18470
  * Index a pattern in local caches
@@ -18377,10 +18512,6 @@ var init_pattern_store = __esm({
18377
18512
  if (domainCount >= this.config.maxPatternsPerDomain) {
18378
18513
  await this.cleanupDomain(pattern.qeDomain);
18379
18514
  }
18380
- const key = `${this.config.namespace}:pattern:${pattern.id}`;
18381
- await this.memory.set(key, pattern, {
18382
- persist: true
18383
- });
18384
18515
  this.indexPattern(pattern);
18385
18516
  if (pattern.embedding) {
18386
18517
  const hnsw = await this.ensureHNSW();
@@ -18477,15 +18608,7 @@ var init_pattern_store = __esm({
18477
18608
  if (!this.initialized) {
18478
18609
  await this.initialize();
18479
18610
  }
18480
- const cached = this.patternCache.get(id);
18481
- if (cached) return cached;
18482
- const key = `${this.config.namespace}:pattern:${id}`;
18483
- const pattern = await this.memory.get(key);
18484
- if (pattern) {
18485
- this.indexPattern(pattern);
18486
- return pattern;
18487
- }
18488
- return null;
18611
+ return this.patternCache.get(id) ?? null;
18489
18612
  }
18490
18613
  /**
18491
18614
  * Search for patterns
@@ -18682,10 +18805,6 @@ var init_pattern_store = __esm({
18682
18805
  if (shouldPromote && updated.tier === "short-term") {
18683
18806
  await this.promote(id);
18684
18807
  } else {
18685
- const key = `${this.config.namespace}:pattern:${id}`;
18686
- await this.memory.set(key, updated, {
18687
- persist: true
18688
- });
18689
18808
  this.patternCache.set(id, updated);
18690
18809
  }
18691
18810
  return ok(void 0);
@@ -18709,10 +18828,6 @@ var init_pattern_store = __esm({
18709
18828
  };
18710
18829
  this.tierIndex.get("short-term")?.delete(id);
18711
18830
  this.tierIndex.get("long-term")?.add(id);
18712
- const key = `${this.config.namespace}:pattern:${id}`;
18713
- await this.memory.set(key, promoted, {
18714
- persist: true
18715
- });
18716
18831
  this.patternCache.set(id, promoted);
18717
18832
  console.log(
18718
18833
  `[PatternStore] Promoted pattern ${id} (${pattern.name}) to long-term storage`
@@ -18728,8 +18843,6 @@ var init_pattern_store = __esm({
18728
18843
  return err(new Error(`Pattern not found: ${id}`));
18729
18844
  }
18730
18845
  this.unindexPattern(pattern);
18731
- const key = `${this.config.namespace}:pattern:${id}`;
18732
- await this.memory.delete(key);
18733
18846
  if (this.hnswIndex !== null) {
18734
18847
  try {
18735
18848
  await this.hnswIndex.delete(id);
@@ -18996,7 +19109,15 @@ var init_qe_reasoning_bank = __esm({
18996
19109
  await this.loadPretrainedPatterns();
18997
19110
  this.initialized = true;
18998
19111
  try {
18999
- await this.seedCrossDomainPatterns();
19112
+ const SEED_FLAG_KEY = "reasoning-bank:cross-domain-seeded";
19113
+ const alreadySeeded = await this.memory.get(SEED_FLAG_KEY);
19114
+ if (!alreadySeeded) {
19115
+ await this.memory.set(SEED_FLAG_KEY, true);
19116
+ await this.seedCrossDomainPatterns();
19117
+ } else {
19118
+ const stats = await this.patternStore.getStats();
19119
+ console.log(`[QEReasoningBank] Cross-domain transfer already complete (${stats.totalPatterns} patterns)`);
19120
+ }
19000
19121
  } catch (error) {
19001
19122
  console.warn("[QEReasoningBank] Cross-domain seeding failed (non-fatal):", error);
19002
19123
  }
@@ -27914,13 +28035,13 @@ var PathTraversalValidator = class {
27914
28035
  */
27915
28036
  joinPathsAbsolute(...paths) {
27916
28037
  if (paths.length === 0) return "";
27917
- const isAbsolute5 = paths[0].startsWith("/");
28038
+ const isAbsolute6 = paths[0].startsWith("/");
27918
28039
  const result = paths.map((p74) => {
27919
28040
  while (p74.startsWith("/")) p74 = p74.slice(1);
27920
28041
  while (p74.endsWith("/")) p74 = p74.slice(0, -1);
27921
28042
  return p74;
27922
28043
  }).filter(Boolean).join("/");
27923
- return isAbsolute5 ? `/${result}` : result;
28044
+ return isAbsolute6 ? `/${result}` : result;
27924
28045
  }
27925
28046
  /**
27926
28047
  * Get file extension from path
@@ -30866,6 +30987,7 @@ var HybridMemoryBackend = class {
30866
30987
  unifiedMemory = null;
30867
30988
  config;
30868
30989
  cleanupInterval;
30990
+ cleanupCount = 0;
30869
30991
  initialized = false;
30870
30992
  constructor(config) {
30871
30993
  this.config = {
@@ -31082,6 +31204,31 @@ var HybridMemoryBackend = class {
31082
31204
  if (this.unifiedMemory?.isInitialized()) {
31083
31205
  try {
31084
31206
  await this.unifiedMemory.kvCleanupExpired();
31207
+ const db = this.unifiedMemory.getDatabase();
31208
+ try {
31209
+ const expired = db.prepare("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?").run(Date.now());
31210
+ if (expired.changes > 0) {
31211
+ console.log(`[HybridBackend] Expired ${expired.changes} kv_store entries`);
31212
+ }
31213
+ } catch (e20) {
31214
+ }
31215
+ this.cleanupCount++;
31216
+ if (this.cleanupCount % 10 === 0) {
31217
+ try {
31218
+ const kvCount = db.prepare("SELECT COUNT(*) as cnt FROM kv_store").get();
31219
+ if (kvCount.cnt > 5e3) {
31220
+ const deleted = db.prepare(`
31221
+ DELETE FROM kv_store WHERE rowid NOT IN (
31222
+ SELECT rowid FROM kv_store ORDER BY rowid DESC LIMIT 5000
31223
+ )
31224
+ `).run();
31225
+ if (deleted.changes > 0) {
31226
+ console.log(`[HybridBackend] kv_store retention: pruned ${deleted.changes} rows (kept 5000)`);
31227
+ }
31228
+ }
31229
+ } catch (e20) {
31230
+ }
31231
+ }
31085
31232
  } catch (error) {
31086
31233
  console.warn("[HybridBackend] Cleanup failed:", error);
31087
31234
  }
@@ -31293,6 +31440,7 @@ var SemanticAntiDriftMiddleware = class {
31293
31440
  // src/kernel/kernel.ts
31294
31441
  init_constants();
31295
31442
  init_unified_memory();
31443
+ init_unified_persistence();
31296
31444
  import * as path12 from "path";
31297
31445
  import * as fs11 from "fs";
31298
31446
 
@@ -43320,11 +43468,19 @@ var isConstitutionalEnforcerEnabled = () => governanceFlags.isGateEnabled("const
43320
43468
  var isStrictMode = () => governanceFlags.getFlags().global.strictMode;
43321
43469
 
43322
43470
  // src/governance/continue-gate-integration.ts
43323
- var ContinueGateIntegration = class {
43471
+ init_unified_memory();
43472
+ var ContinueGateIntegration = class _ContinueGateIntegration {
43324
43473
  actionHistory = /* @__PURE__ */ new Map();
43325
43474
  throttledAgents = /* @__PURE__ */ new Map();
43326
43475
  guidanceContinueGate = null;
43327
43476
  initialized = false;
43477
+ db = null;
43478
+ persistCount = 0;
43479
+ static KV_NAMESPACE = "continue-gate-actions";
43480
+ static KV_KEY = "snapshot";
43481
+ static PERSIST_INTERVAL = 20;
43482
+ static KV_TTL = 3600;
43483
+ // 1 hour
43328
43484
  /**
43329
43485
  * Initialize the ContinueGate integration
43330
43486
  *
@@ -43335,8 +43491,48 @@ var ContinueGateIntegration = class {
43335
43491
  */
43336
43492
  async initialize() {
43337
43493
  if (this.initialized) return;
43494
+ try {
43495
+ this.db = getUnifiedMemory();
43496
+ if (!this.db.isInitialized()) await this.db.initialize();
43497
+ await this.loadFromKv();
43498
+ } catch (error) {
43499
+ console.warn("[ContinueGateIntegration] DB init failed, using memory-only:", error instanceof Error ? error.message : String(error));
43500
+ this.db = null;
43501
+ }
43338
43502
  this.initialized = true;
43339
43503
  }
43504
+ async loadFromKv() {
43505
+ if (!this.db) return;
43506
+ const data = await this.db.kvGet(_ContinueGateIntegration.KV_KEY, _ContinueGateIntegration.KV_NAMESPACE);
43507
+ if (data) {
43508
+ for (const [agentId, actions] of data.actionHistory) {
43509
+ this.actionHistory.set(agentId, actions);
43510
+ }
43511
+ const now = Date.now();
43512
+ for (const [agentId, until] of data.throttledAgents) {
43513
+ if (until > now) this.throttledAgents.set(agentId, until);
43514
+ }
43515
+ console.log("[ContinueGateIntegration] Loaded state from DB");
43516
+ }
43517
+ }
43518
+ async persistSnapshot() {
43519
+ if (!this.db) return;
43520
+ try {
43521
+ await this.db.kvSet(
43522
+ _ContinueGateIntegration.KV_KEY,
43523
+ {
43524
+ actionHistory: Array.from(this.actionHistory.entries()).map(
43525
+ ([agentId, actions]) => [agentId, actions.slice(-50)]
43526
+ ),
43527
+ throttledAgents: Array.from(this.throttledAgents.entries())
43528
+ },
43529
+ _ContinueGateIntegration.KV_NAMESPACE,
43530
+ _ContinueGateIntegration.KV_TTL
43531
+ );
43532
+ } catch (error) {
43533
+ console.warn("[ContinueGateIntegration] Persist failed:", error instanceof Error ? error.message : String(error));
43534
+ }
43535
+ }
43340
43536
  /**
43341
43537
  * Record an agent action for loop detection
43342
43538
  */
@@ -43348,6 +43544,11 @@ var ContinueGateIntegration = class {
43348
43544
  history.shift();
43349
43545
  }
43350
43546
  this.actionHistory.set(action.agentId, history);
43547
+ this.persistCount++;
43548
+ if (this.persistCount % _ContinueGateIntegration.PERSIST_INTERVAL === 0) {
43549
+ this.persistSnapshot().catch(() => {
43550
+ });
43551
+ }
43351
43552
  }
43352
43553
  /**
43353
43554
  * Evaluate whether an agent should continue
@@ -44626,6 +44827,7 @@ var DeterministicGatewayIntegration = class {
44626
44827
  var deterministicGatewayIntegration = new DeterministicGatewayIntegration();
44627
44828
 
44628
44829
  // src/governance/evolution-pipeline-integration.ts
44830
+ init_unified_memory();
44629
44831
  function isEvolutionPipelineEnabled() {
44630
44832
  const flags = governanceFlags.getFlags();
44631
44833
  if (!flags.global.enableAllGates) return false;
@@ -44641,11 +44843,18 @@ function getEvolutionFlags() {
44641
44843
  learningRate: 0.1
44642
44844
  };
44643
44845
  }
44644
- var EvolutionPipelineIntegration = class {
44846
+ var EvolutionPipelineIntegration = class _EvolutionPipelineIntegration {
44645
44847
  rules = /* @__PURE__ */ new Map();
44646
44848
  variantTests = /* @__PURE__ */ new Map();
44647
44849
  taskOutcomes = /* @__PURE__ */ new Map();
44648
44850
  initialized = false;
44851
+ // KV persistence
44852
+ db = null;
44853
+ persistCount = 0;
44854
+ static NAMESPACE = "rule-evolution";
44855
+ static TTL_SECONDS = 604800;
44856
+ // 7 days
44857
+ static PERSIST_INTERVAL = 10;
44649
44858
  // Statistics
44650
44859
  stats = {
44651
44860
  autoPromotions: 0,
@@ -44663,6 +44872,14 @@ var EvolutionPipelineIntegration = class {
44663
44872
  */
44664
44873
  async initialize() {
44665
44874
  if (this.initialized) return;
44875
+ try {
44876
+ this.db = getUnifiedMemory();
44877
+ if (!this.db.isInitialized()) await this.db.initialize();
44878
+ await this.loadFromKv();
44879
+ } catch (error) {
44880
+ console.warn("[EvolutionPipeline] DB init failed, using memory-only:", error instanceof Error ? error.message : String(error));
44881
+ this.db = null;
44882
+ }
44666
44883
  this.initialized = true;
44667
44884
  this.logEvent("initialize", "Evolution Pipeline initialized");
44668
44885
  }
@@ -44684,6 +44901,7 @@ var EvolutionPipelineIntegration = class {
44684
44901
  record.applications.push(application);
44685
44902
  this.pruneApplicationHistory(record);
44686
44903
  this.checkAutoPromotionDemotion(ruleId);
44904
+ this.persistSnapshot();
44687
44905
  this.logEvent("rule_application", `Rule ${ruleId} applied: ${success ? "success" : "failure"}`);
44688
44906
  }
44689
44907
  /**
@@ -45108,6 +45326,36 @@ var EvolutionPipelineIntegration = class {
45108
45326
  this.rules.delete(ruleId);
45109
45327
  }
45110
45328
  // ============================================================================
45329
+ // KV Persistence
45330
+ // ============================================================================
45331
+ /**
45332
+ * Load rules snapshot from KV store
45333
+ */
45334
+ async loadFromKv() {
45335
+ if (!this.db) return;
45336
+ const data = await this.db.kvGet("snapshot", _EvolutionPipelineIntegration.NAMESPACE);
45337
+ if (data) {
45338
+ for (const [key, record] of Object.entries(data)) {
45339
+ this.rules.set(key, record);
45340
+ }
45341
+ }
45342
+ }
45343
+ /**
45344
+ * Persist rules snapshot to KV store on interval
45345
+ */
45346
+ persistSnapshot() {
45347
+ if (!this.db) return;
45348
+ this.persistCount++;
45349
+ if (this.persistCount % _EvolutionPipelineIntegration.PERSIST_INTERVAL !== 0) return;
45350
+ try {
45351
+ const snapshot = Object.fromEntries(this.rules);
45352
+ this.db.kvSet("snapshot", snapshot, _EvolutionPipelineIntegration.NAMESPACE, _EvolutionPipelineIntegration.TTL_SECONDS).catch(() => {
45353
+ });
45354
+ } catch (error) {
45355
+ console.warn("[EvolutionPipeline] Persist failed:", error instanceof Error ? error.message : String(error));
45356
+ }
45357
+ }
45358
+ // ============================================================================
45111
45359
  // Private Helpers
45112
45360
  // ============================================================================
45113
45361
  /**
@@ -47452,6 +47700,7 @@ var ProofEnvelopeIntegration = class {
47452
47700
  var proofEnvelopeIntegration = new ProofEnvelopeIntegration();
47453
47701
 
47454
47702
  // src/governance/compliance-reporter.ts
47703
+ init_unified_memory();
47455
47704
  var DEFAULT_COMPLIANCE_REPORTER_FLAGS = {
47456
47705
  enabled: true,
47457
47706
  autoRecordViolations: true,
@@ -47468,7 +47717,7 @@ var SEVERITY_WEIGHTS = {
47468
47717
  var DEFAULT_SCORE = 100;
47469
47718
  var SCORE_DECAY_RATE = 0.5;
47470
47719
  var TREND_THRESHOLD = 5;
47471
- var ComplianceReporter = class {
47720
+ var ComplianceReporter = class _ComplianceReporter {
47472
47721
  violations = /* @__PURE__ */ new Map();
47473
47722
  alertThresholds = /* @__PURE__ */ new Map();
47474
47723
  proofIntegration;
@@ -47476,6 +47725,13 @@ var ComplianceReporter = class {
47476
47725
  initialized = false;
47477
47726
  scoreHistory = [];
47478
47727
  alertListeners = /* @__PURE__ */ new Set();
47728
+ // KV persistence
47729
+ db = null;
47730
+ persistCount = 0;
47731
+ static NAMESPACE = "compliance-audit";
47732
+ static TTL_SECONDS = 2592e3;
47733
+ // 30 days
47734
+ static PERSIST_INTERVAL = 10;
47479
47735
  /**
47480
47736
  * Create a new ComplianceReporter instance
47481
47737
  *
@@ -47491,6 +47747,14 @@ var ComplianceReporter = class {
47491
47747
  */
47492
47748
  async initialize() {
47493
47749
  if (this.initialized) return;
47750
+ try {
47751
+ this.db = getUnifiedMemory();
47752
+ if (!this.db.isInitialized()) await this.db.initialize();
47753
+ await this.loadFromKv();
47754
+ } catch (error) {
47755
+ console.warn("[ComplianceReporter] DB init failed, using memory-only:", error instanceof Error ? error.message : String(error));
47756
+ this.db = null;
47757
+ }
47494
47758
  if (!this.proofIntegration.isInitialized()) {
47495
47759
  await this.proofIntegration.initialize();
47496
47760
  }
@@ -47559,6 +47823,7 @@ var ComplianceReporter = class {
47559
47823
  if (this.flags.alertOnCritical && violation.severity === "critical") {
47560
47824
  this.triggerAlert(violation.gate, "Critical violation detected", "critical");
47561
47825
  }
47826
+ this.persistSnapshot();
47562
47827
  this.cleanupOldViolations();
47563
47828
  return id;
47564
47829
  }
@@ -47988,6 +48253,45 @@ var ComplianceReporter = class {
47988
48253
  this.initialized = false;
47989
48254
  }
47990
48255
  // ============================================================================
48256
+ // KV Persistence
48257
+ // ============================================================================
48258
+ /**
48259
+ * Load violations and score history from KV store
48260
+ */
48261
+ async loadFromKv() {
48262
+ if (!this.db) return;
48263
+ const data = await this.db.kvGet("snapshot", _ComplianceReporter.NAMESPACE);
48264
+ if (data) {
48265
+ if (data.violations) {
48266
+ for (const [key, violation] of Object.entries(data.violations)) {
48267
+ this.violations.set(key, violation);
48268
+ }
48269
+ }
48270
+ if (data.scoreHistory) {
48271
+ this.scoreHistory = data.scoreHistory;
48272
+ }
48273
+ }
48274
+ }
48275
+ /**
48276
+ * Persist violations and score history to KV store on interval
48277
+ */
48278
+ persistSnapshot() {
48279
+ if (!this.db) return;
48280
+ this.persistCount++;
48281
+ if (this.persistCount % _ComplianceReporter.PERSIST_INTERVAL !== 0) return;
48282
+ try {
48283
+ const violationEntries = Array.from(this.violations.entries()).slice(-500);
48284
+ const snapshot = {
48285
+ violations: Object.fromEntries(violationEntries),
48286
+ scoreHistory: this.scoreHistory.slice(-100)
48287
+ };
48288
+ this.db.kvSet("snapshot", snapshot, _ComplianceReporter.NAMESPACE, _ComplianceReporter.TTL_SECONDS).catch(() => {
48289
+ });
48290
+ } catch (error) {
48291
+ console.warn("[ComplianceReporter] Persist failed:", error instanceof Error ? error.message : String(error));
48292
+ }
48293
+ }
48294
+ // ============================================================================
47991
48295
  // Private Methods
47992
48296
  // ============================================================================
47993
48297
  /**
@@ -82890,13 +83194,6 @@ var KnowledgeGraphService = class {
82890
83194
  async clear() {
82891
83195
  this.nodeCache.clear();
82892
83196
  this.edgeIndex.clear();
82893
- const nodePattern = `${this.config.namespace}:node:*`;
82894
- const edgePattern = `${this.config.namespace}:edge:*`;
82895
- const nodeKeys = await this.memory.search(nodePattern, this.config.maxNodes);
82896
- const edgeKeys = await this.memory.search(edgePattern, this.config.maxNodes * 10);
82897
- for (const key of [...nodeKeys, ...edgeKeys]) {
82898
- await this.memory.delete(key);
82899
- }
82900
83197
  }
82901
83198
  // ============================================================================
82902
83199
  // ADR-051: LLM Enhancement Methods
@@ -83131,26 +83428,18 @@ ${JSON.stringify(results.map((n61) => ({ id: n61.id, label: n61.label, propertie
83131
83428
  await this.createEdge(sourceId, targetId, rel.type);
83132
83429
  edgesCreated++;
83133
83430
  }
83134
- if (relationships.designPatterns.length > 0) {
83135
- await this.memory.set(
83136
- `${this.config.namespace}:patterns:${fileNodeId}`,
83137
- relationships.designPatterns,
83138
- { namespace: this.config.namespace }
83139
- );
83140
- }
83141
- if (relationships.architecturalBoundaries.length > 0) {
83142
- await this.memory.set(
83143
- `${this.config.namespace}:boundaries:${fileNodeId}`,
83144
- relationships.architecturalBoundaries,
83145
- { namespace: this.config.namespace }
83146
- );
83147
- }
83148
- if (relationships.dependencyImpacts.length > 0) {
83149
- await this.memory.set(
83150
- `${this.config.namespace}:impacts:${fileNodeId}`,
83151
- relationships.dependencyImpacts,
83152
- { namespace: this.config.namespace }
83153
- );
83431
+ const node = this.nodeCache.get(fileNodeId);
83432
+ if (node) {
83433
+ if (relationships.designPatterns.length > 0) {
83434
+ node.properties.designPatterns = relationships.designPatterns;
83435
+ }
83436
+ if (relationships.architecturalBoundaries.length > 0) {
83437
+ node.properties.architecturalBoundaries = relationships.architecturalBoundaries;
83438
+ }
83439
+ if (relationships.dependencyImpacts.length > 0) {
83440
+ node.properties.dependencyImpacts = relationships.dependencyImpacts;
83441
+ }
83442
+ this.nodeCache.set(fileNodeId, node);
83154
83443
  }
83155
83444
  return edgesCreated;
83156
83445
  }
@@ -83200,9 +83489,6 @@ ${JSON.stringify(results.map((n61) => ({ id: n61.id, label: n61.label, propertie
83200
83489
  target: targetId,
83201
83490
  type
83202
83491
  };
83203
- await this.memory.set(`${this.config.namespace}:edge:${edgeId}`, edge, {
83204
- namespace: this.config.namespace
83205
- });
83206
83492
  const sourceEdges = this.edgeIndex.get(sourceId) || [];
83207
83493
  sourceEdges.push(edge);
83208
83494
  this.edgeIndex.set(sourceId, sourceEdges);
@@ -83214,12 +83500,8 @@ ${JSON.stringify(results.map((n61) => ({ id: n61.id, label: n61.label, propertie
83214
83500
  if (firstKey) {
83215
83501
  this.nodeCache.delete(firstKey);
83216
83502
  this.edgeIndex.delete(firstKey);
83217
- await this.memory.delete(`${this.config.namespace}:node:${firstKey}`);
83218
83503
  }
83219
83504
  }
83220
- await this.memory.set(`${this.config.namespace}:node:${node.id}`, node, {
83221
- namespace: this.config.namespace
83222
- });
83223
83505
  this.nodeCache.set(node.id, node);
83224
83506
  }
83225
83507
  async extractEntities(filePath) {
@@ -83610,11 +83892,7 @@ ${JSON.stringify(results.map((n61) => ({ id: n61.id, label: n61.label, propertie
83610
83892
  return true;
83611
83893
  });
83612
83894
  }
83613
- async storeIndexMetadata(metadata) {
83614
- await this.memory.set(`${this.config.namespace}:metadata:index`, metadata, {
83615
- namespace: this.config.namespace,
83616
- persist: true
83617
- });
83895
+ async storeIndexMetadata(_metadata) {
83618
83896
  }
83619
83897
  async generateEmbedding(entity) {
83620
83898
  const text2 = `${entity.type} ${entity.name} ${entity.visibility}${entity.isAsync ? " async" : ""}`;
@@ -86713,9 +86991,11 @@ var CodeIntelligenceCoordinator = class {
86713
86991
  async initializeHypergraph() {
86714
86992
  try {
86715
86993
  const Database = (await Promise.resolve().then(() => (init_better_sqlite3(), better_sqlite3_exports))).default;
86716
- const dbPath = this.config.hypergraphDbPath || ".agentic-qe/hypergraph.db";
86717
86994
  const fs19 = await import("fs");
86718
86995
  const path21 = await import("path");
86996
+ const { findProjectRoot: findProjectRoot2 } = await Promise.resolve().then(() => (init_unified_memory(), unified_memory_exports));
86997
+ const projectRoot = findProjectRoot2();
86998
+ const dbPath = this.config.hypergraphDbPath || path21.join(projectRoot, ".agentic-qe", "hypergraph.db");
86719
86999
  const dir = path21.dirname(dbPath);
86720
87000
  if (!fs19.existsSync(dir)) {
86721
87001
  fs19.mkdirSync(dir, { recursive: true });
@@ -89345,17 +89625,22 @@ var SASTScanner = class {
89345
89625
  * Store scan results in memory
89346
89626
  */
89347
89627
  async storeScanResults(scanId, scanType, vulnerabilities, summary) {
89628
+ const scanSummary = {
89629
+ scanId,
89630
+ scanType,
89631
+ summary,
89632
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
89633
+ vulnerabilityCount: vulnerabilities.length,
89634
+ // Keep only critical/high vulnerabilities in stored result
89635
+ criticalVulnerabilities: vulnerabilities.filter(
89636
+ (v62) => v62.severity === "critical" || v62.severity === "high"
89637
+ )
89638
+ };
89348
89639
  await this.memory.set(
89349
89640
  `security:scan:${scanId}`,
89350
- {
89351
- scanId,
89352
- scanType,
89353
- vulnerabilities,
89354
- summary,
89355
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
89356
- },
89357
- { namespace: "security-compliance", ttl: 86400 * 7 }
89358
- // 7 days
89641
+ scanSummary,
89642
+ { namespace: "security-compliance", ttl: 86400 * 2 }
89643
+ // 2 days (reduced from 7)
89359
89644
  );
89360
89645
  }
89361
89646
  // ==========================================================================
@@ -117683,6 +117968,13 @@ var QEKernelImpl = class {
117683
117968
  if (this._initialized) {
117684
117969
  return;
117685
117970
  }
117971
+ if (this._config.memoryBackend === "memory") {
117972
+ const tmpDbPath = path12.join(
117973
+ __require("os").tmpdir(),
117974
+ `aqe-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`
117975
+ );
117976
+ await initializeUnifiedPersistence({ dbPath: tmpDbPath });
117977
+ }
117686
117978
  await this._memory.initialize();
117687
117979
  const antiDriftMiddleware = new SemanticAntiDriftMiddleware({
117688
117980
  agentId: "qe-kernel"
@@ -119135,8 +119427,34 @@ var MinCutPersistence = class {
119135
119427
  JSON.stringify(snapshot.vertices),
119136
119428
  JSON.stringify(snapshot.edges)
119137
119429
  );
119430
+ await this.enforceRetention();
119138
119431
  return id;
119139
119432
  }
119433
+ /**
119434
+ * Enforce retention limits on snapshots and history to prevent DB bloat (Issue #258)
119435
+ */
119436
+ async enforceRetention(maxSnapshots = 200) {
119437
+ const db = this.memory.getDatabase();
119438
+ if (!db) return 0;
119439
+ const countRow = db.prepare("SELECT COUNT(*) as count FROM mincut_snapshots").get();
119440
+ if (!countRow || countRow.count <= maxSnapshots) return 0;
119441
+ const deleteCount = countRow.count - maxSnapshots;
119442
+ db.prepare(`
119443
+ DELETE FROM mincut_snapshots WHERE id IN (
119444
+ SELECT id FROM mincut_snapshots ORDER BY created_at ASC LIMIT ?
119445
+ )
119446
+ `).run(deleteCount);
119447
+ const historyCount = db.prepare("SELECT COUNT(*) as count FROM mincut_history").get();
119448
+ if (historyCount.count > 500) {
119449
+ const historyDelete = historyCount.count - 500;
119450
+ db.prepare(`
119451
+ DELETE FROM mincut_history WHERE id IN (
119452
+ SELECT id FROM mincut_history ORDER BY created_at ASC LIMIT ?
119453
+ )
119454
+ `).run(historyDelete);
119455
+ }
119456
+ return deleteCount;
119457
+ }
119140
119458
  /**
119141
119459
  * Get a snapshot by ID
119142
119460
  */
@@ -119688,7 +120006,10 @@ var QueenMinCutBridge = class {
119688
120006
  }
119689
120007
  this.eventSubscriptions = [];
119690
120008
  if (this.config.persistData) {
119691
- await this.saveSnapshot();
120009
+ try {
120010
+ await this.saveSnapshot();
120011
+ } catch {
120012
+ }
119692
120013
  }
119693
120014
  this.initialized = false;
119694
120015
  }
@@ -125120,7 +125441,8 @@ var DEFAULT_DYNAMIC_SCALING_CONFIG = {
125120
125441
 
125121
125442
  // src/coordination/dynamic-scaling/dynamic-scaler.ts
125122
125443
  import { randomUUID as randomUUID5 } from "node:crypto";
125123
- var DynamicScaler = class {
125444
+ init_unified_memory();
125445
+ var DynamicScaler = class _DynamicScaler {
125124
125446
  config;
125125
125447
  policy;
125126
125448
  metricsHistory = [];
@@ -125131,6 +125453,13 @@ var DynamicScaler = class {
125131
125453
  totalDecisions = 0;
125132
125454
  currentAgents;
125133
125455
  lastDecision;
125456
+ // KV store persistence (Tier 2)
125457
+ db = null;
125458
+ persistCount = 0;
125459
+ static KV_NAMESPACE = "scaling-metrics";
125460
+ static KV_KEY = "dynamic-scaler-snapshot";
125461
+ static PERSIST_INTERVAL = 10;
125462
+ static KV_TTL = 7200;
125134
125463
  /**
125135
125464
  * Create a new DynamicScaler.
125136
125465
  *
@@ -125156,6 +125485,11 @@ var DynamicScaler = class {
125156
125485
  if (this.metricsHistory.length > this.config.metricsHistorySize) {
125157
125486
  this.metricsHistory.shift();
125158
125487
  }
125488
+ this.persistCount++;
125489
+ if (this.persistCount % _DynamicScaler.PERSIST_INTERVAL === 0) {
125490
+ this.persistSnapshot().catch(() => {
125491
+ });
125492
+ }
125159
125493
  }
125160
125494
  // --------------------------------------------------------------------------
125161
125495
  // Evaluation
@@ -125353,6 +125687,23 @@ var DynamicScaler = class {
125353
125687
  // --------------------------------------------------------------------------
125354
125688
  // Lifecycle
125355
125689
  // --------------------------------------------------------------------------
125690
+ /**
125691
+ * Initialize persistence layer and load last snapshot from KV store.
125692
+ * Safe to call multiple times; will not throw on DB failure.
125693
+ */
125694
+ async initialize() {
125695
+ try {
125696
+ this.db = getUnifiedMemory();
125697
+ if (!this.db.isInitialized()) await this.db.initialize();
125698
+ await this.loadFromKv();
125699
+ } catch (error) {
125700
+ console.warn(
125701
+ "[DynamicScaler] DB init failed, using memory-only:",
125702
+ error instanceof Error ? error.message : String(error)
125703
+ );
125704
+ this.db = null;
125705
+ }
125706
+ }
125356
125707
  /**
125357
125708
  * Release internal buffers. The scaler should not be used after disposal.
125358
125709
  */
@@ -125393,12 +125744,68 @@ var DynamicScaler = class {
125393
125744
  }
125394
125745
  /**
125395
125746
  * Record a scaling event, evicting the oldest when the history cap is hit.
125747
+ * Triggers periodic persistence to KV store.
125396
125748
  */
125397
125749
  recordEvent(event) {
125398
125750
  this.events.push(event);
125399
125751
  if (this.events.length > this.config.decisionHistorySize) {
125400
125752
  this.events.shift();
125401
125753
  }
125754
+ this.persistCount++;
125755
+ if (this.persistCount % _DynamicScaler.PERSIST_INTERVAL === 0) {
125756
+ this.persistSnapshot().catch(() => {
125757
+ });
125758
+ }
125759
+ }
125760
+ /**
125761
+ * Load last persisted snapshot from KV store into in-memory state.
125762
+ */
125763
+ async loadFromKv() {
125764
+ if (!this.db) return;
125765
+ try {
125766
+ const snapshot = await this.db.kvGet(_DynamicScaler.KV_KEY, _DynamicScaler.KV_NAMESPACE);
125767
+ if (snapshot) {
125768
+ if (Array.isArray(snapshot.metricsHistory)) {
125769
+ for (const m74 of snapshot.metricsHistory) {
125770
+ this.metricsHistory.push(m74);
125771
+ }
125772
+ }
125773
+ if (Array.isArray(snapshot.events)) {
125774
+ for (const e20 of snapshot.events) {
125775
+ this.events.push(e20);
125776
+ }
125777
+ }
125778
+ }
125779
+ } catch (error) {
125780
+ console.warn(
125781
+ "[DynamicScaler] Failed to load KV snapshot:",
125782
+ error instanceof Error ? error.message : String(error)
125783
+ );
125784
+ }
125785
+ }
125786
+ /**
125787
+ * Persist a trimmed snapshot of metricsHistory and events to KV store.
125788
+ * Keeps only the last 50 entries of each to limit storage size.
125789
+ */
125790
+ async persistSnapshot() {
125791
+ if (!this.db) return;
125792
+ try {
125793
+ const snapshot = {
125794
+ metricsHistory: this.metricsHistory.slice(-50),
125795
+ events: this.events.slice(-50)
125796
+ };
125797
+ await this.db.kvSet(
125798
+ _DynamicScaler.KV_KEY,
125799
+ snapshot,
125800
+ _DynamicScaler.KV_NAMESPACE,
125801
+ _DynamicScaler.KV_TTL
125802
+ );
125803
+ } catch (error) {
125804
+ console.warn(
125805
+ "[DynamicScaler] Failed to persist KV snapshot:",
125806
+ error instanceof Error ? error.message : String(error)
125807
+ );
125808
+ }
125402
125809
  }
125403
125810
  };
125404
125811
  function createDynamicScaler(initialAgents, config) {
@@ -130038,34 +130445,55 @@ var ExperienceReplay = class {
130038
130445
  console.log("[ExperienceReplay] Initialized");
130039
130446
  }
130040
130447
  /**
130041
- * Ensure required schema exists
130448
+ * Ensure required schema exists.
130449
+ * Uses captured_experiences as the canonical table (written by experience-capture-middleware).
130450
+ * Adds ExperienceReplay-specific columns if missing.
130042
130451
  */
130043
130452
  ensureSchema() {
130044
130453
  if (!this.db) throw new Error("Database not initialized");
130045
130454
  this.db.exec(`
130046
- CREATE TABLE IF NOT EXISTS experiences (
130455
+ CREATE TABLE IF NOT EXISTS captured_experiences (
130047
130456
  id TEXT PRIMARY KEY,
130048
- trajectory_id TEXT NOT NULL,
130049
130457
  task TEXT NOT NULL,
130050
- domain TEXT NOT NULL,
130051
- strategy TEXT NOT NULL,
130052
- key_actions TEXT NOT NULL,
130053
- quality_score REAL NOT NULL DEFAULT 0.5,
130458
+ agent TEXT NOT NULL,
130459
+ domain TEXT NOT NULL DEFAULT '',
130460
+ success INTEGER NOT NULL DEFAULT 0,
130461
+ quality REAL NOT NULL DEFAULT 0.5,
130462
+ duration_ms INTEGER NOT NULL DEFAULT 0,
130463
+ model_tier INTEGER,
130464
+ routing_json TEXT,
130465
+ steps_json TEXT,
130466
+ result_json TEXT,
130467
+ error TEXT,
130468
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
130469
+ completed_at TEXT NOT NULL DEFAULT (datetime('now')),
130470
+ source TEXT DEFAULT 'middleware',
130054
130471
  application_count INTEGER DEFAULT 0,
130055
- success_rate REAL DEFAULT 1.0,
130056
130472
  avg_token_savings REAL DEFAULT 0,
130057
130473
  embedding BLOB,
130058
130474
  embedding_dimension INTEGER,
130059
- original_metrics TEXT,
130060
130475
  tags TEXT,
130061
- created_at TEXT DEFAULT (datetime('now')),
130062
- last_applied_at TEXT,
130063
- FOREIGN KEY (trajectory_id) REFERENCES qe_trajectories(id) ON DELETE SET NULL
130476
+ last_applied_at TEXT
130064
130477
  );
130065
- CREATE INDEX IF NOT EXISTS idx_experiences_domain ON experiences(domain);
130066
- CREATE INDEX IF NOT EXISTS idx_experiences_quality ON experiences(quality_score DESC);
130067
- CREATE INDEX IF NOT EXISTS idx_experiences_task ON experiences(task);
130478
+ CREATE INDEX IF NOT EXISTS idx_captured_exp_domain ON captured_experiences(domain);
130479
+ CREATE INDEX IF NOT EXISTS idx_captured_exp_quality ON captured_experiences(quality DESC);
130480
+ CREATE INDEX IF NOT EXISTS idx_captured_exp_task ON captured_experiences(task);
130068
130481
  `);
130482
+ const columns = this.db.prepare("PRAGMA table_info(captured_experiences)").all();
130483
+ const colNames = new Set(columns.map((c70) => c70.name));
130484
+ const additions = [
130485
+ ["application_count", "INTEGER DEFAULT 0"],
130486
+ ["avg_token_savings", "REAL DEFAULT 0"],
130487
+ ["embedding", "BLOB"],
130488
+ ["embedding_dimension", "INTEGER"],
130489
+ ["tags", "TEXT"],
130490
+ ["last_applied_at", "TEXT"]
130491
+ ];
130492
+ for (const [col, def] of additions) {
130493
+ if (!colNames.has(col)) {
130494
+ this.db.exec(`ALTER TABLE captured_experiences ADD COLUMN ${col} ${def}`);
130495
+ }
130496
+ }
130069
130497
  this.db.exec(`
130070
130498
  CREATE TABLE IF NOT EXISTS experience_applications (
130071
130499
  id TEXT PRIMARY KEY,
@@ -130075,38 +130503,37 @@ var ExperienceReplay = class {
130075
130503
  tokens_saved INTEGER DEFAULT 0,
130076
130504
  feedback TEXT,
130077
130505
  applied_at TEXT DEFAULT (datetime('now')),
130078
- FOREIGN KEY (experience_id) REFERENCES experiences(id) ON DELETE CASCADE
130506
+ FOREIGN KEY (experience_id) REFERENCES captured_experiences(id) ON DELETE CASCADE
130079
130507
  );
130080
130508
  CREATE INDEX IF NOT EXISTS idx_exp_apps_experience ON experience_applications(experience_id);
130081
130509
  `);
130082
130510
  }
130083
130511
  /**
130084
- * Prepare commonly used statements
130512
+ * Prepare commonly used statements against captured_experiences table
130085
130513
  */
130086
130514
  prepareStatements() {
130087
130515
  if (!this.db) throw new Error("Database not initialized");
130088
130516
  this.prepared.set("insertExperience", this.db.prepare(`
130089
- INSERT INTO experiences (
130090
- id, trajectory_id, task, domain, strategy, key_actions, quality_score,
130091
- embedding, embedding_dimension, original_metrics, tags
130092
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
130517
+ INSERT INTO captured_experiences (
130518
+ id, task, agent, domain, success, quality, duration_ms,
130519
+ steps_json, routing_json, embedding, embedding_dimension, tags, source
130520
+ ) VALUES (?, ?, ?, ?, 1, ?, 0, ?, ?, ?, ?, ?, 'experience-replay')
130093
130521
  `));
130094
130522
  this.prepared.set("getExperience", this.db.prepare(`
130095
- SELECT * FROM experiences WHERE id = ?
130523
+ SELECT * FROM captured_experiences WHERE id = ?
130096
130524
  `));
130097
130525
  this.prepared.set("getExperiencesByDomain", this.db.prepare(`
130098
- SELECT * FROM experiences WHERE domain = ? ORDER BY quality_score DESC LIMIT ?
130526
+ SELECT * FROM captured_experiences WHERE domain = ? ORDER BY quality DESC LIMIT ?
130099
130527
  `));
130100
130528
  this.prepared.set("getAllExperiences", this.db.prepare(`
130101
- SELECT * FROM experiences ORDER BY quality_score DESC LIMIT ?
130529
+ SELECT * FROM captured_experiences ORDER BY quality DESC LIMIT ?
130102
130530
  `));
130103
130531
  this.prepared.set("getAllEmbeddings", this.db.prepare(`
130104
- SELECT id, embedding, embedding_dimension FROM experiences WHERE embedding IS NOT NULL
130532
+ SELECT id, embedding, embedding_dimension FROM captured_experiences WHERE embedding IS NOT NULL
130105
130533
  `));
130106
130534
  this.prepared.set("updateApplication", this.db.prepare(`
130107
- UPDATE experiences SET
130535
+ UPDATE captured_experiences SET
130108
130536
  application_count = application_count + 1,
130109
- success_rate = (success_rate * application_count + ?) / (application_count + 1),
130110
130537
  avg_token_savings = (avg_token_savings * application_count + ?) / (application_count + 1),
130111
130538
  last_applied_at = datetime('now')
130112
130539
  WHERE id = ?
@@ -130116,13 +130543,13 @@ var ExperienceReplay = class {
130116
130543
  VALUES (?, ?, ?, ?, ?, ?)
130117
130544
  `));
130118
130545
  this.prepared.set("deleteExperience", this.db.prepare(`
130119
- DELETE FROM experiences WHERE id = ?
130546
+ DELETE FROM captured_experiences WHERE id = ?
130120
130547
  `));
130121
130548
  this.prepared.set("getLowQualityExperiences", this.db.prepare(`
130122
- SELECT id FROM experiences WHERE quality_score < ? AND application_count < 3
130549
+ SELECT id FROM captured_experiences WHERE quality < ? AND application_count < 3
130123
130550
  `));
130124
130551
  this.prepared.set("countByDomain", this.db.prepare(`
130125
- SELECT domain, COUNT(*) as count FROM experiences GROUP BY domain
130552
+ SELECT domain, COUNT(*) as count FROM captured_experiences GROUP BY domain
130126
130553
  `));
130127
130554
  }
130128
130555
  /**
@@ -130198,15 +130625,17 @@ var ExperienceReplay = class {
130198
130625
  const embeddingBuffer = embedding ? this.floatArrayToBuffer(embedding) : null;
130199
130626
  insertStmt.run(
130200
130627
  id,
130201
- trajectory.id,
130202
130628
  trajectory.task,
130203
- domain,
130204
130629
  strategy,
130205
- JSON.stringify(keyActions),
130630
+ // agent column stores strategy
130631
+ domain,
130206
130632
  trajectory.metrics.efficiencyScore,
130633
+ JSON.stringify(keyActions),
130634
+ // steps_json stores key actions
130635
+ JSON.stringify(trajectory.metrics),
130636
+ // routing_json stores original metrics
130207
130637
  embeddingBuffer,
130208
130638
  embedding?.length ?? null,
130209
- JSON.stringify(trajectory.metrics),
130210
130639
  JSON.stringify(tags)
130211
130640
  );
130212
130641
  }
@@ -130338,7 +130767,7 @@ var ExperienceReplay = class {
130338
130767
  this.ensureInitialized();
130339
130768
  const updateStmt = this.prepared.get("updateApplication");
130340
130769
  if (updateStmt) {
130341
- updateStmt.run(success ? 1 : 0, tokensSaved, experienceId);
130770
+ updateStmt.run(tokensSaved, experienceId);
130342
130771
  }
130343
130772
  const insertStmt = this.prepared.get("insertApplication");
130344
130773
  if (insertStmt) {
@@ -130445,19 +130874,21 @@ var ExperienceReplay = class {
130445
130874
  if (!row2) return null;
130446
130875
  return {
130447
130876
  id: row2.id,
130448
- trajectoryId: row2.trajectory_id,
130877
+ trajectoryId: row2.id,
130878
+ // captured_experiences doesn't have trajectory_id
130449
130879
  task: row2.task,
130450
130880
  domain: row2.domain,
130451
- strategy: row2.strategy,
130452
- keyActions: JSON.parse(row2.key_actions || "[]"),
130453
- qualityScore: row2.quality_score,
130454
- applicationCount: row2.application_count,
130455
- successRate: row2.success_rate,
130456
- avgTokenSavings: row2.avg_token_savings,
130881
+ strategy: row2.agent,
130882
+ // agent column stores strategy/agent name
130883
+ keyActions: JSON.parse(row2.steps_json || "[]"),
130884
+ qualityScore: row2.quality,
130885
+ applicationCount: row2.application_count ?? 0,
130886
+ successRate: row2.success ? 1 : 0,
130887
+ avgTokenSavings: row2.avg_token_savings ?? 0,
130457
130888
  embedding: row2.embedding && row2.embedding_dimension ? this.bufferToFloatArray(row2.embedding, row2.embedding_dimension) : void 0,
130458
- createdAt: new Date(row2.created_at),
130889
+ createdAt: new Date(row2.started_at),
130459
130890
  lastAppliedAt: row2.last_applied_at ? new Date(row2.last_applied_at) : void 0,
130460
- originalMetrics: JSON.parse(row2.original_metrics || "{}"),
130891
+ originalMetrics: JSON.parse(row2.routing_json || "{}"),
130461
130892
  tags: JSON.parse(row2.tags || "[]")
130462
130893
  };
130463
130894
  }
@@ -135671,6 +136102,7 @@ var EarlyExitTokenOptimizer = class {
135671
136102
  init_pattern_store();
135672
136103
 
135673
136104
  // src/learning/token-tracker.ts
136105
+ init_unified_memory();
135674
136106
  import { randomUUID as randomUUID7 } from "crypto";
135675
136107
  var DEFAULT_COST_CONFIG = {
135676
136108
  costPerInputToken: 3e-3 / 1e3,
@@ -135684,7 +136116,7 @@ var DEFAULT_PERSISTENCE_CONFIG2 = {
135684
136116
  // Auto-save every minute
135685
136117
  maxMetricsInMemory: 1e4
135686
136118
  };
135687
- var TokenMetricsCollectorImpl = class {
136119
+ var TokenMetricsCollectorImpl = class _TokenMetricsCollectorImpl {
135688
136120
  taskMetrics = [];
135689
136121
  agentMetrics = /* @__PURE__ */ new Map();
135690
136122
  domainMetrics = /* @__PURE__ */ new Map();
@@ -135700,6 +136132,15 @@ var TokenMetricsCollectorImpl = class {
135700
136132
  persistenceConfig = DEFAULT_PERSISTENCE_CONFIG2;
135701
136133
  autoSaveTimer = null;
135702
136134
  isDirty = false;
136135
+ // kv_store persistence
136136
+ db = null;
136137
+ kvPersistCount = 0;
136138
+ static KV_NAMESPACE = "token-usage-metrics";
136139
+ static KV_KEY = "token-tracker-snapshot";
136140
+ static KV_TTL = 604800;
136141
+ // 7 days
136142
+ static KV_PERSIST_INTERVAL = 10;
136143
+ // every 10 operations
135703
136144
  constructor() {
135704
136145
  this.sessionId = `session-${Date.now()}-${randomUUID7().substring(0, 8)}`;
135705
136146
  this.sessionStartTime = Date.now();
@@ -136114,6 +136555,88 @@ var TokenMetricsCollectorImpl = class {
136114
136555
  return this.isDirty;
136115
136556
  }
136116
136557
  // ============================================================================
136558
+ // kv_store Persistence
136559
+ // ============================================================================
136560
+ /**
136561
+ * Initialize kv_store persistence and restore snapshot if available.
136562
+ * This supplements the existing file-based persistence.
136563
+ */
136564
+ async initializeDb() {
136565
+ try {
136566
+ this.db = getUnifiedMemory();
136567
+ if (!this.db.isInitialized()) await this.db.initialize();
136568
+ await this.loadFromKv();
136569
+ } catch (error) {
136570
+ console.warn("[TokenMetricsCollector] DB init failed, using memory-only:", error instanceof Error ? error.message : String(error));
136571
+ this.db = null;
136572
+ }
136573
+ }
136574
+ /**
136575
+ * Persist current state snapshot to kv_store
136576
+ */
136577
+ async persistToKv() {
136578
+ if (!this.db) return;
136579
+ const snapshot = {
136580
+ version: "1.0.0",
136581
+ sessionId: this.sessionId,
136582
+ sessionStartTime: this.sessionStartTime,
136583
+ taskMetrics: this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),
136584
+ optimizationStats: {
136585
+ cacheHits: this.cacheHits,
136586
+ earlyExits: this.earlyExits,
136587
+ totalTokensSaved: this.totalTokensSaved,
136588
+ totalPatternsReused: this.totalPatternsReused
136589
+ },
136590
+ lastSavedAt: Date.now()
136591
+ };
136592
+ await this.db.kvSet(
136593
+ _TokenMetricsCollectorImpl.KV_KEY,
136594
+ snapshot,
136595
+ _TokenMetricsCollectorImpl.KV_NAMESPACE,
136596
+ _TokenMetricsCollectorImpl.KV_TTL
136597
+ );
136598
+ }
136599
+ /**
136600
+ * Load state snapshot from kv_store
136601
+ */
136602
+ async loadFromKv() {
136603
+ if (!this.db) return false;
136604
+ const snapshot = await this.db.kvGet(
136605
+ _TokenMetricsCollectorImpl.KV_KEY,
136606
+ _TokenMetricsCollectorImpl.KV_NAMESPACE
136607
+ );
136608
+ if (!snapshot) return false;
136609
+ if (!snapshot.version || !snapshot.version.startsWith("1.")) {
136610
+ console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load");
136611
+ return false;
136612
+ }
136613
+ const historicalMetrics = snapshot.taskMetrics || [];
136614
+ this.taskMetrics = [...historicalMetrics, ...this.taskMetrics];
136615
+ this.cacheHits += snapshot.optimizationStats?.cacheHits || 0;
136616
+ this.earlyExits += snapshot.optimizationStats?.earlyExits || 0;
136617
+ this.totalTokensSaved += snapshot.optimizationStats?.totalTokensSaved || 0;
136618
+ this.totalPatternsReused += snapshot.optimizationStats?.totalPatternsReused || 0;
136619
+ for (const metric of historicalMetrics) {
136620
+ this.updateAgentMetrics(metric.agentId, metric.usage, metric.patternReused, metric.tokensSaved || 0);
136621
+ this.updateDomainMetrics(metric.domain, metric.usage);
136622
+ }
136623
+ if (this.taskMetrics.length > this.persistenceConfig.maxMetricsInMemory) {
136624
+ this.taskMetrics = this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory);
136625
+ }
136626
+ return true;
136627
+ }
136628
+ /**
136629
+ * Track state changes and persist to kv_store periodically
136630
+ */
136631
+ maybePersistToKv() {
136632
+ this.kvPersistCount++;
136633
+ if (this.kvPersistCount >= _TokenMetricsCollectorImpl.KV_PERSIST_INTERVAL) {
136634
+ this.kvPersistCount = 0;
136635
+ this.persistToKv().catch(() => {
136636
+ });
136637
+ }
136638
+ }
136639
+ // ============================================================================
136117
136640
  // Private Helper Methods
136118
136641
  // ============================================================================
136119
136642
  ensureInitialized() {
@@ -145484,6 +146007,9 @@ var GOAPStatusTool = class extends MCPToolBase {
145484
146007
  }
145485
146008
  };
145486
146009
 
146010
+ // src/coordination/mincut/time-crystal.ts
146011
+ init_unified_memory();
146012
+
145487
146013
  // src/mcp/tools/mincut/index.ts
145488
146014
  var MINCUT_TOOL_NAMES = {
145489
146015
  HEALTH: "qe/mincut/health",
@@ -151844,24 +152370,49 @@ async function doInitialize() {
151844
152370
  await memoryManager.initialize();
151845
152371
  const db = memoryManager.getDatabase();
151846
152372
  if (db) {
152373
+ let needsCreate = false;
152374
+ const tableExists = db.prepare(
152375
+ "SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name='captured_experiences'"
152376
+ ).get().cnt > 0;
152377
+ if (tableExists) {
152378
+ const columns = db.prepare("PRAGMA table_info(captured_experiences)").all();
152379
+ const colNames = new Set(columns.map((c70) => c70.name));
152380
+ if (!colNames.has("success") || !colNames.has("task")) {
152381
+ db.exec("ALTER TABLE captured_experiences RENAME TO captured_experiences_v2_backup");
152382
+ needsCreate = true;
152383
+ } else {
152384
+ if (!colNames.has("domain")) {
152385
+ db.exec("ALTER TABLE captured_experiences ADD COLUMN domain TEXT NOT NULL DEFAULT ''");
152386
+ }
152387
+ if (!colNames.has("source")) {
152388
+ db.exec("ALTER TABLE captured_experiences ADD COLUMN source TEXT DEFAULT 'middleware'");
152389
+ }
152390
+ }
152391
+ } else {
152392
+ needsCreate = true;
152393
+ }
152394
+ if (needsCreate) {
152395
+ db.exec(`
152396
+ CREATE TABLE IF NOT EXISTS captured_experiences (
152397
+ id TEXT PRIMARY KEY,
152398
+ task TEXT NOT NULL,
152399
+ agent TEXT NOT NULL,
152400
+ domain TEXT NOT NULL DEFAULT '',
152401
+ success INTEGER NOT NULL DEFAULT 0,
152402
+ quality REAL NOT NULL DEFAULT 0.5,
152403
+ duration_ms INTEGER NOT NULL DEFAULT 0,
152404
+ model_tier INTEGER,
152405
+ routing_json TEXT,
152406
+ steps_json TEXT,
152407
+ result_json TEXT,
152408
+ error TEXT,
152409
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
152410
+ completed_at TEXT NOT NULL DEFAULT (datetime('now')),
152411
+ source TEXT DEFAULT 'middleware'
152412
+ );
152413
+ `);
152414
+ }
151847
152415
  db.exec(`
151848
- CREATE TABLE IF NOT EXISTS captured_experiences (
151849
- id TEXT PRIMARY KEY,
151850
- task TEXT NOT NULL,
151851
- agent TEXT NOT NULL,
151852
- domain TEXT NOT NULL,
151853
- success INTEGER NOT NULL DEFAULT 0,
151854
- quality REAL NOT NULL DEFAULT 0.5,
151855
- duration_ms INTEGER NOT NULL DEFAULT 0,
151856
- model_tier INTEGER,
151857
- routing_json TEXT,
151858
- steps_json TEXT,
151859
- result_json TEXT,
151860
- error TEXT,
151861
- started_at TEXT NOT NULL,
151862
- completed_at TEXT NOT NULL DEFAULT (datetime('now')),
151863
- source TEXT DEFAULT 'middleware'
151864
- );
151865
152416
  CREATE INDEX IF NOT EXISTS idx_captured_exp_domain ON captured_experiences(domain);
151866
152417
  CREATE INDEX IF NOT EXISTS idx_captured_exp_success ON captured_experiences(success);
151867
152418
  CREATE INDEX IF NOT EXISTS idx_captured_exp_agent ON captured_experiences(agent);
@@ -160536,6 +161087,25 @@ async function main() {
160536
161087
  }
160537
161088
  } catch (infraError) {
160538
161089
  originalStderrWrite(`[MCP] WARNING: Infra-healing init failed: ${infraError}
161090
+ `);
161091
+ }
161092
+ originalStderrWrite("[MCP] Auto-initializing fleet...\n");
161093
+ try {
161094
+ const fleetResult = await handleFleetInit({
161095
+ topology: "hierarchical",
161096
+ maxAgents: 15,
161097
+ memoryBackend: "hybrid",
161098
+ lazyLoading: true
161099
+ });
161100
+ if (fleetResult.success) {
161101
+ originalStderrWrite(`[MCP] Fleet ready: ${fleetResult.data?.fleetId}
161102
+ `);
161103
+ } else {
161104
+ originalStderrWrite(`[MCP] WARNING: Fleet auto-init failed: ${fleetResult.error}
161105
+ `);
161106
+ }
161107
+ } catch (fleetError) {
161108
+ originalStderrWrite(`[MCP] WARNING: Fleet auto-init error: ${fleetError}
160539
161109
  `);
160540
161110
  }
160541
161111
  originalStderrWrite("[MCP] Starting server...\n");