agentic-qe 3.6.7 → 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.
@@ -6115,6 +6115,10 @@ var init_unified_memory = __esm({
6115
6115
  constructor(config) {
6116
6116
  const resolvedDefaults = getResolvedDefaultConfig();
6117
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
+ }
6118
6122
  }
6119
6123
  /**
6120
6124
  * Get or create the singleton instance (synchronous).
@@ -7080,6 +7084,211 @@ var init_real_embeddings = __esm({
7080
7084
  }
7081
7085
  });
7082
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
+
7083
7292
  // src/coordination/consensus/model-provider.ts
7084
7293
  function buildVerificationPrompt(finding, options = {}) {
7085
7294
  const {
@@ -9508,206 +9717,6 @@ var init_sona_wrapper = __esm({
9508
9717
  }
9509
9718
  });
9510
9719
 
9511
- // src/kernel/unified-persistence.ts
9512
- function getUnifiedPersistence(config) {
9513
- return UnifiedPersistenceManager.getInstance(config);
9514
- }
9515
- function registerExitHandlers2() {
9516
- if (exitHandlersRegistered2) return;
9517
- exitHandlersRegistered2 = true;
9518
- const cleanup = () => {
9519
- try {
9520
- const instance3 = UnifiedPersistenceManager["instance"];
9521
- if (instance3) {
9522
- instance3.close();
9523
- }
9524
- } catch (error) {
9525
- console.debug("[UnifiedPersistence] Cleanup error:", error instanceof Error ? error.message : error);
9526
- }
9527
- };
9528
- process.on("beforeExit", cleanup);
9529
- process.on("SIGINT", () => {
9530
- cleanup();
9531
- process.exit(0);
9532
- });
9533
- process.on("SIGTERM", () => {
9534
- cleanup();
9535
- process.exit(0);
9536
- });
9537
- }
9538
- var DEFAULT_UNIFIED_CONFIG, UnifiedPersistenceManager, exitHandlersRegistered2;
9539
- var init_unified_persistence = __esm({
9540
- "src/kernel/unified-persistence.ts"() {
9541
- "use strict";
9542
- init_unified_memory();
9543
- DEFAULT_UNIFIED_CONFIG = {
9544
- dbPath: DEFAULT_UNIFIED_MEMORY_CONFIG.dbPath,
9545
- // '.agentic-qe/memory.db'
9546
- walMode: true,
9547
- mmapSize: 64 * 1024 * 1024,
9548
- // 64MB
9549
- cacheSize: -32e3,
9550
- // 32MB
9551
- busyTimeout: 5e3
9552
- };
9553
- UnifiedPersistenceManager = class _UnifiedPersistenceManager {
9554
- static instance = null;
9555
- static instancePromise = null;
9556
- unifiedMemory = null;
9557
- config;
9558
- initialized = false;
9559
- initPromise = null;
9560
- constructor(config) {
9561
- this.config = { ...DEFAULT_UNIFIED_CONFIG, ...config };
9562
- }
9563
- /**
9564
- * Get or create the singleton instance (synchronous).
9565
- * Thread-safe: JS is single-threaded for synchronous code.
9566
- */
9567
- static getInstance(config) {
9568
- if (_UnifiedPersistenceManager.instance) {
9569
- return _UnifiedPersistenceManager.instance;
9570
- }
9571
- _UnifiedPersistenceManager.instance = new _UnifiedPersistenceManager(config);
9572
- return _UnifiedPersistenceManager.instance;
9573
- }
9574
- /**
9575
- * Get or create the singleton instance with async initialization.
9576
- * Thread-safe: Uses Promise lock to prevent concurrent initialization races.
9577
- */
9578
- static async getInstanceAsync(config) {
9579
- if (_UnifiedPersistenceManager.instance?.initialized) {
9580
- return _UnifiedPersistenceManager.instance;
9581
- }
9582
- if (!_UnifiedPersistenceManager.instancePromise) {
9583
- _UnifiedPersistenceManager.instancePromise = (async () => {
9584
- const instance3 = _UnifiedPersistenceManager.getInstance(config);
9585
- await instance3.initialize();
9586
- return instance3;
9587
- })();
9588
- }
9589
- return _UnifiedPersistenceManager.instancePromise;
9590
- }
9591
- /**
9592
- * Reset the singleton (for testing)
9593
- */
9594
- static resetInstance() {
9595
- if (_UnifiedPersistenceManager.instance) {
9596
- _UnifiedPersistenceManager.instance.close();
9597
- _UnifiedPersistenceManager.instance = null;
9598
- }
9599
- _UnifiedPersistenceManager.instancePromise = null;
9600
- resetUnifiedMemory();
9601
- }
9602
- /**
9603
- * Initialize the database and create all schemas.
9604
- * Thread-safe: Uses Promise lock to prevent concurrent initialization races.
9605
- */
9606
- async initialize() {
9607
- if (this.initialized) return;
9608
- if (!this.initPromise) {
9609
- this.initPromise = this._doInitialize();
9610
- }
9611
- return this.initPromise;
9612
- }
9613
- /**
9614
- * Internal initialization implementation
9615
- */
9616
- async _doInitialize() {
9617
- if (this.initialized) return;
9618
- try {
9619
- const memoryConfig = {
9620
- dbPath: this.config.dbPath,
9621
- walMode: this.config.walMode,
9622
- busyTimeout: this.config.busyTimeout,
9623
- mmapSize: this.config.mmapSize,
9624
- cacheSize: this.config.cacheSize
9625
- };
9626
- this.unifiedMemory = getUnifiedMemory(memoryConfig);
9627
- await this.unifiedMemory.initialize();
9628
- this.initialized = true;
9629
- console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`);
9630
- } catch (error) {
9631
- this.initPromise = null;
9632
- throw new Error(
9633
- `Failed to initialize UnifiedPersistenceManager: ${error instanceof Error ? error.message : String(error)}`
9634
- );
9635
- }
9636
- }
9637
- /**
9638
- * Get the raw database connection for advanced operations
9639
- */
9640
- getDatabase() {
9641
- if (!this.unifiedMemory || !this.initialized) {
9642
- throw new Error("UnifiedPersistenceManager not initialized");
9643
- }
9644
- return this.unifiedMemory.getDatabase();
9645
- }
9646
- /**
9647
- * Check if initialized
9648
- */
9649
- isInitialized() {
9650
- return this.initialized;
9651
- }
9652
- /**
9653
- * Get the database path
9654
- */
9655
- getDbPath() {
9656
- return this.config.dbPath;
9657
- }
9658
- /**
9659
- * Prepare and cache a statement
9660
- */
9661
- prepare(name, sql) {
9662
- if (!this.unifiedMemory) throw new Error("Database not initialized");
9663
- return this.unifiedMemory.prepare(name, sql);
9664
- }
9665
- /**
9666
- * Execute a transaction
9667
- */
9668
- transaction(fn) {
9669
- if (!this.unifiedMemory) throw new Error("Database not initialized");
9670
- return this.unifiedMemory.transaction(fn);
9671
- }
9672
- /**
9673
- * Get database statistics
9674
- */
9675
- getStats() {
9676
- if (!this.unifiedMemory) throw new Error("Database not initialized");
9677
- const memStats = this.unifiedMemory.getStats();
9678
- return {
9679
- tables: memStats.tables,
9680
- fileSize: memStats.fileSize,
9681
- walSize: memStats.walSize
9682
- };
9683
- }
9684
- /**
9685
- * Vacuum the database to reclaim space
9686
- */
9687
- vacuum() {
9688
- const db = this.getDatabase();
9689
- db.exec("VACUUM");
9690
- }
9691
- /**
9692
- * Checkpoint WAL to main database
9693
- */
9694
- checkpoint() {
9695
- const db = this.getDatabase();
9696
- db.pragma("wal_checkpoint(TRUNCATE)");
9697
- }
9698
- /**
9699
- * Close the database connection
9700
- */
9701
- close() {
9702
- this.initialized = false;
9703
- console.log("[UnifiedPersistence] Facade closed");
9704
- }
9705
- };
9706
- exitHandlersRegistered2 = false;
9707
- registerExitHandlers2();
9708
- }
9709
- });
9710
-
9711
9720
  // native-require:@ruvector/attention
9712
9721
  var attention_exports = {};
9713
9722
  __export(attention_exports, {
@@ -28026,13 +28035,13 @@ var PathTraversalValidator = class {
28026
28035
  */
28027
28036
  joinPathsAbsolute(...paths) {
28028
28037
  if (paths.length === 0) return "";
28029
- const isAbsolute5 = paths[0].startsWith("/");
28038
+ const isAbsolute6 = paths[0].startsWith("/");
28030
28039
  const result = paths.map((p74) => {
28031
28040
  while (p74.startsWith("/")) p74 = p74.slice(1);
28032
28041
  while (p74.endsWith("/")) p74 = p74.slice(0, -1);
28033
28042
  return p74;
28034
28043
  }).filter(Boolean).join("/");
28035
- return isAbsolute5 ? `/${result}` : result;
28044
+ return isAbsolute6 ? `/${result}` : result;
28036
28045
  }
28037
28046
  /**
28038
28047
  * Get file extension from path
@@ -31431,6 +31440,7 @@ var SemanticAntiDriftMiddleware = class {
31431
31440
  // src/kernel/kernel.ts
31432
31441
  init_constants();
31433
31442
  init_unified_memory();
31443
+ init_unified_persistence();
31434
31444
  import * as path12 from "path";
31435
31445
  import * as fs11 from "fs";
31436
31446
 
@@ -117958,6 +117968,13 @@ var QEKernelImpl = class {
117958
117968
  if (this._initialized) {
117959
117969
  return;
117960
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
+ }
117961
117978
  await this._memory.initialize();
117962
117979
  const antiDriftMiddleware = new SemanticAntiDriftMiddleware({
117963
117980
  agentId: "qe-kernel"
@@ -119989,7 +120006,10 @@ var QueenMinCutBridge = class {
119989
120006
  }
119990
120007
  this.eventSubscriptions = [];
119991
120008
  if (this.config.persistData) {
119992
- await this.saveSnapshot();
120009
+ try {
120010
+ await this.saveSnapshot();
120011
+ } catch {
120012
+ }
119993
120013
  }
119994
120014
  this.initialized = false;
119995
120015
  }
@@ -130425,34 +130445,55 @@ var ExperienceReplay = class {
130425
130445
  console.log("[ExperienceReplay] Initialized");
130426
130446
  }
130427
130447
  /**
130428
- * 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.
130429
130451
  */
130430
130452
  ensureSchema() {
130431
130453
  if (!this.db) throw new Error("Database not initialized");
130432
130454
  this.db.exec(`
130433
- CREATE TABLE IF NOT EXISTS experiences (
130455
+ CREATE TABLE IF NOT EXISTS captured_experiences (
130434
130456
  id TEXT PRIMARY KEY,
130435
- trajectory_id TEXT NOT NULL,
130436
130457
  task TEXT NOT NULL,
130437
- domain TEXT NOT NULL,
130438
- strategy TEXT NOT NULL,
130439
- key_actions TEXT NOT NULL,
130440
- 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',
130441
130471
  application_count INTEGER DEFAULT 0,
130442
- success_rate REAL DEFAULT 1.0,
130443
130472
  avg_token_savings REAL DEFAULT 0,
130444
130473
  embedding BLOB,
130445
130474
  embedding_dimension INTEGER,
130446
- original_metrics TEXT,
130447
130475
  tags TEXT,
130448
- created_at TEXT DEFAULT (datetime('now')),
130449
- last_applied_at TEXT,
130450
- FOREIGN KEY (trajectory_id) REFERENCES qe_trajectories(id) ON DELETE SET NULL
130476
+ last_applied_at TEXT
130451
130477
  );
130452
- CREATE INDEX IF NOT EXISTS idx_experiences_domain ON experiences(domain);
130453
- CREATE INDEX IF NOT EXISTS idx_experiences_quality ON experiences(quality_score DESC);
130454
- 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);
130455
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
+ }
130456
130497
  this.db.exec(`
130457
130498
  CREATE TABLE IF NOT EXISTS experience_applications (
130458
130499
  id TEXT PRIMARY KEY,
@@ -130462,38 +130503,37 @@ var ExperienceReplay = class {
130462
130503
  tokens_saved INTEGER DEFAULT 0,
130463
130504
  feedback TEXT,
130464
130505
  applied_at TEXT DEFAULT (datetime('now')),
130465
- FOREIGN KEY (experience_id) REFERENCES experiences(id) ON DELETE CASCADE
130506
+ FOREIGN KEY (experience_id) REFERENCES captured_experiences(id) ON DELETE CASCADE
130466
130507
  );
130467
130508
  CREATE INDEX IF NOT EXISTS idx_exp_apps_experience ON experience_applications(experience_id);
130468
130509
  `);
130469
130510
  }
130470
130511
  /**
130471
- * Prepare commonly used statements
130512
+ * Prepare commonly used statements against captured_experiences table
130472
130513
  */
130473
130514
  prepareStatements() {
130474
130515
  if (!this.db) throw new Error("Database not initialized");
130475
130516
  this.prepared.set("insertExperience", this.db.prepare(`
130476
- INSERT INTO experiences (
130477
- id, trajectory_id, task, domain, strategy, key_actions, quality_score,
130478
- embedding, embedding_dimension, original_metrics, tags
130479
- ) 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')
130480
130521
  `));
130481
130522
  this.prepared.set("getExperience", this.db.prepare(`
130482
- SELECT * FROM experiences WHERE id = ?
130523
+ SELECT * FROM captured_experiences WHERE id = ?
130483
130524
  `));
130484
130525
  this.prepared.set("getExperiencesByDomain", this.db.prepare(`
130485
- SELECT * FROM experiences WHERE domain = ? ORDER BY quality_score DESC LIMIT ?
130526
+ SELECT * FROM captured_experiences WHERE domain = ? ORDER BY quality DESC LIMIT ?
130486
130527
  `));
130487
130528
  this.prepared.set("getAllExperiences", this.db.prepare(`
130488
- SELECT * FROM experiences ORDER BY quality_score DESC LIMIT ?
130529
+ SELECT * FROM captured_experiences ORDER BY quality DESC LIMIT ?
130489
130530
  `));
130490
130531
  this.prepared.set("getAllEmbeddings", this.db.prepare(`
130491
- 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
130492
130533
  `));
130493
130534
  this.prepared.set("updateApplication", this.db.prepare(`
130494
- UPDATE experiences SET
130535
+ UPDATE captured_experiences SET
130495
130536
  application_count = application_count + 1,
130496
- success_rate = (success_rate * application_count + ?) / (application_count + 1),
130497
130537
  avg_token_savings = (avg_token_savings * application_count + ?) / (application_count + 1),
130498
130538
  last_applied_at = datetime('now')
130499
130539
  WHERE id = ?
@@ -130503,13 +130543,13 @@ var ExperienceReplay = class {
130503
130543
  VALUES (?, ?, ?, ?, ?, ?)
130504
130544
  `));
130505
130545
  this.prepared.set("deleteExperience", this.db.prepare(`
130506
- DELETE FROM experiences WHERE id = ?
130546
+ DELETE FROM captured_experiences WHERE id = ?
130507
130547
  `));
130508
130548
  this.prepared.set("getLowQualityExperiences", this.db.prepare(`
130509
- SELECT id FROM experiences WHERE quality_score < ? AND application_count < 3
130549
+ SELECT id FROM captured_experiences WHERE quality < ? AND application_count < 3
130510
130550
  `));
130511
130551
  this.prepared.set("countByDomain", this.db.prepare(`
130512
- SELECT domain, COUNT(*) as count FROM experiences GROUP BY domain
130552
+ SELECT domain, COUNT(*) as count FROM captured_experiences GROUP BY domain
130513
130553
  `));
130514
130554
  }
130515
130555
  /**
@@ -130585,15 +130625,17 @@ var ExperienceReplay = class {
130585
130625
  const embeddingBuffer = embedding ? this.floatArrayToBuffer(embedding) : null;
130586
130626
  insertStmt.run(
130587
130627
  id,
130588
- trajectory.id,
130589
130628
  trajectory.task,
130590
- domain,
130591
130629
  strategy,
130592
- JSON.stringify(keyActions),
130630
+ // agent column stores strategy
130631
+ domain,
130593
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
130594
130637
  embeddingBuffer,
130595
130638
  embedding?.length ?? null,
130596
- JSON.stringify(trajectory.metrics),
130597
130639
  JSON.stringify(tags)
130598
130640
  );
130599
130641
  }
@@ -130725,7 +130767,7 @@ var ExperienceReplay = class {
130725
130767
  this.ensureInitialized();
130726
130768
  const updateStmt = this.prepared.get("updateApplication");
130727
130769
  if (updateStmt) {
130728
- updateStmt.run(success ? 1 : 0, tokensSaved, experienceId);
130770
+ updateStmt.run(tokensSaved, experienceId);
130729
130771
  }
130730
130772
  const insertStmt = this.prepared.get("insertApplication");
130731
130773
  if (insertStmt) {
@@ -130832,19 +130874,21 @@ var ExperienceReplay = class {
130832
130874
  if (!row2) return null;
130833
130875
  return {
130834
130876
  id: row2.id,
130835
- trajectoryId: row2.trajectory_id,
130877
+ trajectoryId: row2.id,
130878
+ // captured_experiences doesn't have trajectory_id
130836
130879
  task: row2.task,
130837
130880
  domain: row2.domain,
130838
- strategy: row2.strategy,
130839
- keyActions: JSON.parse(row2.key_actions || "[]"),
130840
- qualityScore: row2.quality_score,
130841
- applicationCount: row2.application_count,
130842
- successRate: row2.success_rate,
130843
- 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,
130844
130888
  embedding: row2.embedding && row2.embedding_dimension ? this.bufferToFloatArray(row2.embedding, row2.embedding_dimension) : void 0,
130845
- createdAt: new Date(row2.created_at),
130889
+ createdAt: new Date(row2.started_at),
130846
130890
  lastAppliedAt: row2.last_applied_at ? new Date(row2.last_applied_at) : void 0,
130847
- originalMetrics: JSON.parse(row2.original_metrics || "{}"),
130891
+ originalMetrics: JSON.parse(row2.routing_json || "{}"),
130848
130892
  tags: JSON.parse(row2.tags || "[]")
130849
130893
  };
130850
130894
  }
@@ -161043,6 +161087,25 @@ async function main() {
161043
161087
  }
161044
161088
  } catch (infraError) {
161045
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}
161046
161109
  `);
161047
161110
  }
161048
161111
  originalStderrWrite("[MCP] Starting server...\n");