claude-memory-layer 1.0.10 → 1.0.12

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 (142) hide show
  1. package/AGENTS.md +60 -0
  2. package/README.md +166 -2
  3. package/bootstrap-kb/decisions/decisions.md +244 -0
  4. package/bootstrap-kb/glossary/glossary.md +46 -0
  5. package/bootstrap-kb/modules/.claude-plugin.md +22 -0
  6. package/bootstrap-kb/modules/agents.md.md +15 -0
  7. package/bootstrap-kb/modules/claude.md.md +15 -0
  8. package/bootstrap-kb/modules/context.md.md +15 -0
  9. package/bootstrap-kb/modules/docs.md +18 -0
  10. package/bootstrap-kb/modules/handoff.md.md +15 -0
  11. package/bootstrap-kb/modules/package-lock.json.md +15 -0
  12. package/bootstrap-kb/modules/package.json.md +15 -0
  13. package/bootstrap-kb/modules/plan.md.md +15 -0
  14. package/bootstrap-kb/modules/readme.md.md +15 -0
  15. package/bootstrap-kb/modules/scripts.md +26 -0
  16. package/bootstrap-kb/modules/spec.md.md +15 -0
  17. package/bootstrap-kb/modules/specs.md +20 -0
  18. package/bootstrap-kb/modules/src.md +51 -0
  19. package/bootstrap-kb/modules/tests.md +42 -0
  20. package/bootstrap-kb/modules/tsconfig.json.md +15 -0
  21. package/bootstrap-kb/modules/vitest.config.ts.md +15 -0
  22. package/bootstrap-kb/overview/overview.md +40 -0
  23. package/bootstrap-kb/sources/manifest.json +950 -0
  24. package/bootstrap-kb/sources/manifest.md +227 -0
  25. package/bootstrap-kb/timeline/timeline.md +57 -0
  26. package/d.sh +3 -0
  27. package/deploy.sh +3 -0
  28. package/dist/cli/index.js +3577 -389
  29. package/dist/cli/index.js.map +4 -4
  30. package/dist/core/index.js +1383 -138
  31. package/dist/core/index.js.map +4 -4
  32. package/dist/hooks/post-tool-use.js +1917 -214
  33. package/dist/hooks/post-tool-use.js.map +4 -4
  34. package/dist/hooks/session-end.js +1813 -231
  35. package/dist/hooks/session-end.js.map +4 -4
  36. package/dist/hooks/session-start.js +1802 -205
  37. package/dist/hooks/session-start.js.map +4 -4
  38. package/dist/hooks/stop.js +1909 -248
  39. package/dist/hooks/stop.js.map +4 -4
  40. package/dist/hooks/user-prompt-submit.js +1861 -206
  41. package/dist/hooks/user-prompt-submit.js.map +4 -4
  42. package/dist/server/api/index.js +2341 -217
  43. package/dist/server/api/index.js.map +4 -4
  44. package/dist/server/index.js +2350 -226
  45. package/dist/server/index.js.map +4 -4
  46. package/dist/services/memory-service.js +1805 -206
  47. package/dist/services/memory-service.js.map +4 -4
  48. package/dist/ui/app.js +1447 -55
  49. package/dist/ui/index.html +318 -147
  50. package/dist/ui/style.css +892 -0
  51. package/docs/MCP_MEMORY_SERVICE_COMPARATIVE_REVIEW.md +271 -0
  52. package/docs/MEMU_ADOPTION.md +40 -0
  53. package/docs/OPERATIONS.md +18 -0
  54. package/memory/.claude-plugin/commands/2026-02-25.md +263 -0
  55. package/memory/_index.md +405 -0
  56. package/memory/default/uncategorized/2026-02-25.md +4839 -0
  57. package/memory/specs/20260207-dashboard-upgrade/2026-02-25.md +142 -0
  58. package/memory/specs/citations-system/2026-02-25.md +1121 -0
  59. package/memory/specs/endless-mode/2026-02-25.md +1392 -0
  60. package/memory/specs/entity-edge-model/2026-02-25.md +1263 -0
  61. package/memory/specs/evidence-aligner-v2/2026-02-25.md +1028 -0
  62. package/memory/specs/mcp-desktop-integration/2026-02-25.md +1334 -0
  63. package/memory/specs/post-tool-use-hook/2026-02-25.md +1164 -0
  64. package/memory/specs/private-tags/2026-02-25.md +1057 -0
  65. package/memory/specs/progressive-disclosure/2026-02-25.md +1436 -0
  66. package/memory/specs/task-entity-system/2026-02-25.md +924 -0
  67. package/memory/specs/vector-outbox-v2/2026-02-25.md +1510 -0
  68. package/memory/specs/web-viewer-ui/2026-02-25.md +1709 -0
  69. package/package.json +9 -2
  70. package/scripts/build.ts +6 -0
  71. package/scripts/fix-sync-gap.js +32 -0
  72. package/scripts/heartbeat-memory-orchestrator.sh +28 -0
  73. package/scripts/report-sync-gap.js +26 -0
  74. package/scripts/review-queue-auto-resolve.js +21 -0
  75. package/scripts/sync-gap-auto-heal.sh +17 -0
  76. package/specs/20260207-dashboard-upgrade/context.md +38 -0
  77. package/specs/20260207-dashboard-upgrade/spec.md +96 -0
  78. package/src/cli/index.ts +391 -60
  79. package/src/core/consolidated-store.ts +63 -1
  80. package/src/core/consolidation-worker.ts +115 -6
  81. package/src/core/event-store.ts +14 -0
  82. package/src/core/index.ts +1 -0
  83. package/src/core/ingest-interceptor.ts +80 -0
  84. package/src/core/markdown-mirror.ts +70 -0
  85. package/src/core/md-mirror.ts +92 -0
  86. package/src/core/mongo-sync-config.ts +165 -0
  87. package/src/core/mongo-sync-worker.ts +381 -0
  88. package/src/core/retriever.ts +540 -150
  89. package/src/core/sqlite-event-store.ts +794 -7
  90. package/src/core/sqlite-wrapper.ts +8 -0
  91. package/src/core/tag-taxonomy.ts +51 -0
  92. package/src/core/turn-state.ts +159 -0
  93. package/src/core/types.ts +51 -8
  94. package/src/core/vector-store.ts +21 -3
  95. package/src/hooks/post-tool-use.ts +68 -23
  96. package/src/hooks/session-end.ts +8 -3
  97. package/src/hooks/stop.ts +96 -25
  98. package/src/hooks/user-prompt-submit.ts +44 -5
  99. package/src/server/api/chat.ts +244 -0
  100. package/src/server/api/citations.ts +3 -3
  101. package/src/server/api/events.ts +30 -5
  102. package/src/server/api/health.ts +53 -0
  103. package/src/server/api/index.ts +9 -1
  104. package/src/server/api/projects.ts +74 -0
  105. package/src/server/api/search.ts +3 -3
  106. package/src/server/api/sessions.ts +3 -3
  107. package/src/server/api/stats.ts +89 -8
  108. package/src/server/api/turns.ts +143 -0
  109. package/src/server/api/utils.ts +46 -0
  110. package/src/services/bootstrap-organizer.ts +443 -0
  111. package/src/services/codex-session-history-importer.ts +474 -0
  112. package/src/services/memory-service.ts +508 -71
  113. package/src/services/session-history-importer.ts +215 -51
  114. package/src/ui/app.js +1447 -55
  115. package/src/ui/index.html +318 -147
  116. package/src/ui/style.css +892 -0
  117. package/tests/bootstrap-organizer.test.ts +111 -0
  118. package/tests/consolidation-worker.test.ts +75 -0
  119. package/tests/ingest-interceptor.test.ts +38 -0
  120. package/tests/markdown-mirror.test.ts +85 -0
  121. package/tests/md-mirror.test.ts +50 -0
  122. package/tests/retriever-fallback-chain.test.ts +223 -0
  123. package/tests/retriever-strategy-scope.test.ts +97 -0
  124. package/tests/retriever.memu-adoption.test.ts +122 -0
  125. package/tests/sqlite-event-store-replication.test.ts +92 -0
  126. package/.claude/settings.local.json +0 -27
  127. package/.claude-memory/test.sqlite +0 -0
  128. package/.history/package_20260201112328.json +0 -45
  129. package/.history/package_20260201113602.json +0 -45
  130. package/.history/package_20260201113713.json +0 -45
  131. package/.history/package_20260201114110.json +0 -45
  132. package/.history/package_20260201114632.json +0 -46
  133. package/.history/package_20260201133143.json +0 -45
  134. package/.history/package_20260201134319.json +0 -45
  135. package/.history/package_20260201134326.json +0 -45
  136. package/.history/package_20260201134334.json +0 -45
  137. package/.history/package_20260201134912.json +0 -45
  138. package/.history/package_20260201142928.json +0 -46
  139. package/.history/package_20260201192048.json +0 -47
  140. package/.history/package_20260202114053.json +0 -49
  141. package/.history/package_20260202121115.json +0 -49
  142. package/test_access.js +0 -49
@@ -7,9 +7,9 @@ const __filename = fileURLToPath(import.meta.url);
7
7
  const __dirname = dirname(__filename);
8
8
 
9
9
  // src/services/memory-service.ts
10
- import * as path from "path";
10
+ import * as path3 from "path";
11
11
  import * as os from "os";
12
- import * as fs from "fs";
12
+ import * as fs4 from "fs";
13
13
  import * as crypto2 from "crypto";
14
14
 
15
15
  // src/core/event-store.ts
@@ -67,11 +67,11 @@ function toDate(value) {
67
67
  return new Date(value);
68
68
  return new Date(String(value));
69
69
  }
70
- function createDatabase(path2, options) {
70
+ function createDatabase(path4, options) {
71
71
  if (options?.readOnly) {
72
- return new duckdb.Database(path2, { access_mode: "READ_ONLY" });
72
+ return new duckdb.Database(path4, { access_mode: "READ_ONLY" });
73
73
  }
74
- return new duckdb.Database(path2);
74
+ return new duckdb.Database(path4);
75
75
  }
76
76
  function dbRun(db, sql, params = []) {
77
77
  return new Promise((resolve2, reject) => {
@@ -335,6 +335,17 @@ var EventStore = class {
335
335
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
336
336
  )
337
337
  `);
338
+ await dbRun(this.db, `
339
+ CREATE TABLE IF NOT EXISTS consolidated_rules (
340
+ rule_id VARCHAR PRIMARY KEY,
341
+ rule TEXT NOT NULL,
342
+ topics JSON,
343
+ source_memory_ids JSON,
344
+ source_events JSON,
345
+ confidence FLOAT DEFAULT 0.5,
346
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
347
+ )
348
+ `);
338
349
  await dbRun(this.db, `
339
350
  CREATE TABLE IF NOT EXISTS endless_config (
340
351
  key VARCHAR PRIMARY KEY,
@@ -354,6 +365,7 @@ var EventStore = class {
354
365
  await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
355
366
  await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
356
367
  await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
368
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
357
369
  await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
358
370
  this.initialized = true;
359
371
  }
@@ -741,8 +753,14 @@ import { randomUUID as randomUUID2 } from "crypto";
741
753
 
742
754
  // src/core/sqlite-wrapper.ts
743
755
  import Database from "better-sqlite3";
744
- function createSQLiteDatabase(path2, options) {
745
- const db = new Database(path2, {
756
+ import * as fs from "fs";
757
+ import * as nodePath from "path";
758
+ function createSQLiteDatabase(path4, options) {
759
+ const dir = nodePath.dirname(path4);
760
+ if (!fs.existsSync(dir)) {
761
+ fs.mkdirSync(dir, { recursive: true });
762
+ }
763
+ const db = new Database(path4, {
746
764
  readonly: options?.readonly ?? false
747
765
  });
748
766
  if (!options?.readonly && (options?.walMode ?? true)) {
@@ -783,6 +801,64 @@ function toSQLiteTimestamp(date) {
783
801
  return date.toISOString();
784
802
  }
785
803
 
804
+ // src/core/markdown-mirror.ts
805
+ import * as fs2 from "fs/promises";
806
+ import * as path from "path";
807
+ var DEFAULT_NAMESPACE = "default";
808
+ var DEFAULT_CATEGORY = "uncategorized";
809
+ function sanitizeSegment(input, fallback) {
810
+ const raw = String(input ?? "").trim().toLowerCase();
811
+ const safe = raw.normalize("NFKD").replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
812
+ if (!safe || safe === "." || safe === "..")
813
+ return fallback;
814
+ return safe;
815
+ }
816
+ function getCategorySegments(metadata, eventType) {
817
+ const raw = metadata?.categoryPath;
818
+ if (Array.isArray(raw) && raw.length > 0) {
819
+ return raw.map((s) => sanitizeSegment(s, DEFAULT_CATEGORY));
820
+ }
821
+ const single = metadata?.category;
822
+ if (typeof single === "string" && single.trim()) {
823
+ return [sanitizeSegment(single, DEFAULT_CATEGORY)];
824
+ }
825
+ return [sanitizeSegment(eventType, DEFAULT_CATEGORY)];
826
+ }
827
+ function buildMirrorPath(rootDir, event) {
828
+ const metadata = event.metadata;
829
+ const namespace = sanitizeSegment(metadata?.namespace, DEFAULT_NAMESPACE);
830
+ const categories = getCategorySegments(metadata, event.eventType);
831
+ const d = event.timestamp;
832
+ const yyyy = d.getFullYear();
833
+ const mm = String(d.getMonth() + 1).padStart(2, "0");
834
+ const dd = String(d.getDate()).padStart(2, "0");
835
+ return path.join(rootDir, "memory", namespace, ...categories, `${yyyy}-${mm}-${dd}.md`);
836
+ }
837
+ function formatMirrorEntry(event) {
838
+ const category = Array.isArray(event.metadata?.categoryPath) ? event.metadata.categoryPath.join("/") : String(event.metadata?.category ?? event.eventType);
839
+ return [
840
+ "",
841
+ `- ts: ${event.timestamp.toISOString()}`,
842
+ ` id: ${event.id}`,
843
+ ` type: ${event.eventType}`,
844
+ ` session: ${event.sessionId}`,
845
+ ` category: ${category}`,
846
+ " content: |",
847
+ ...event.content.split("\n").map((line) => ` ${line}`)
848
+ ].join("\n") + "\n";
849
+ }
850
+ var MarkdownMirror = class {
851
+ constructor(rootDir) {
852
+ this.rootDir = rootDir;
853
+ }
854
+ async append(event) {
855
+ const outPath = buildMirrorPath(this.rootDir, event);
856
+ await fs2.mkdir(path.dirname(outPath), { recursive: true });
857
+ await fs2.appendFile(outPath, formatMirrorEntry(event), "utf8");
858
+ return outPath;
859
+ }
860
+ };
861
+
786
862
  // src/core/sqlite-event-store.ts
787
863
  var SQLiteEventStore = class {
788
864
  constructor(dbPath, options) {
@@ -792,10 +868,12 @@ var SQLiteEventStore = class {
792
868
  readonly: this.readOnly,
793
869
  walMode: !this.readOnly
794
870
  });
871
+ this.markdownMirror = this.readOnly || !options?.markdownMirrorRoot ? null : new MarkdownMirror(options.markdownMirrorRoot);
795
872
  }
796
873
  db;
797
874
  initialized = false;
798
875
  readOnly;
876
+ markdownMirror;
799
877
  /**
800
878
  * Initialize database schema
801
879
  */
@@ -1002,6 +1080,17 @@ var SQLiteEventStore = class {
1002
1080
  created_at TEXT DEFAULT (datetime('now'))
1003
1081
  );
1004
1082
 
1083
+ -- Consolidated Rules table (long-term stable memory)
1084
+ CREATE TABLE IF NOT EXISTS consolidated_rules (
1085
+ rule_id TEXT PRIMARY KEY,
1086
+ rule TEXT NOT NULL,
1087
+ topics TEXT,
1088
+ source_memory_ids TEXT,
1089
+ source_events TEXT,
1090
+ confidence REAL DEFAULT 0.5,
1091
+ created_at TEXT DEFAULT (datetime('now'))
1092
+ );
1093
+
1005
1094
  -- Endless Mode Config table
1006
1095
  CREATE TABLE IF NOT EXISTS endless_config (
1007
1096
  key TEXT PRIMARY KEY,
@@ -1009,6 +1098,41 @@ var SQLiteEventStore = class {
1009
1098
  updated_at TEXT DEFAULT (datetime('now'))
1010
1099
  );
1011
1100
 
1101
+ -- Memory Helpfulness tracking
1102
+ CREATE TABLE IF NOT EXISTS memory_helpfulness (
1103
+ id TEXT PRIMARY KEY,
1104
+ event_id TEXT NOT NULL,
1105
+ session_id TEXT NOT NULL,
1106
+ retrieval_score REAL DEFAULT 0,
1107
+ query_preview TEXT,
1108
+ session_continued INTEGER DEFAULT 0,
1109
+ prompt_count_after INTEGER DEFAULT 0,
1110
+ tool_success_count INTEGER DEFAULT 0,
1111
+ tool_total_count INTEGER DEFAULT 0,
1112
+ was_reasked INTEGER DEFAULT 0,
1113
+ helpfulness_score REAL DEFAULT 0.5,
1114
+ created_at TEXT DEFAULT (datetime('now')),
1115
+ measured_at TEXT
1116
+ );
1117
+
1118
+ -- Retrieval trace log (query -> candidates -> selected for context)
1119
+ CREATE TABLE IF NOT EXISTS retrieval_traces (
1120
+ trace_id TEXT PRIMARY KEY,
1121
+ session_id TEXT,
1122
+ project_hash TEXT,
1123
+ query_text TEXT NOT NULL,
1124
+ strategy TEXT,
1125
+ candidate_event_ids TEXT,
1126
+ selected_event_ids TEXT,
1127
+ candidate_details_json TEXT,
1128
+ selected_details_json TEXT,
1129
+ candidate_count INTEGER DEFAULT 0,
1130
+ selected_count INTEGER DEFAULT 0,
1131
+ confidence TEXT,
1132
+ fallback_trace TEXT,
1133
+ created_at TEXT DEFAULT (datetime('now'))
1134
+ );
1135
+
1012
1136
  -- Sync position tracking (for SQLite -> DuckDB sync)
1013
1137
  CREATE TABLE IF NOT EXISTS sync_positions (
1014
1138
  target_name TEXT PRIMARY KEY,
@@ -1033,7 +1157,14 @@ var SQLiteEventStore = class {
1033
1157
  CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score);
1034
1158
  CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence);
1035
1159
  CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at);
1160
+ CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence);
1036
1161
  CREATE INDEX IF NOT EXISTS idx_embedding_outbox_status ON embedding_outbox(status);
1162
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_event ON memory_helpfulness(event_id);
1163
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_session ON memory_helpfulness(session_id);
1164
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_score ON memory_helpfulness(helpfulness_score DESC);
1165
+ CREATE INDEX IF NOT EXISTS idx_retrieval_traces_created_at ON retrieval_traces(created_at DESC);
1166
+ CREATE INDEX IF NOT EXISTS idx_retrieval_traces_project_hash ON retrieval_traces(project_hash);
1167
+ CREATE INDEX IF NOT EXISTS idx_retrieval_traces_session_id ON retrieval_traces(session_id);
1037
1168
 
1038
1169
  -- FTS5 Full-Text Search for fast keyword search
1039
1170
  CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
@@ -1057,6 +1188,14 @@ var SQLiteEventStore = class {
1057
1188
  INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
1058
1189
  END;
1059
1190
  `);
1191
+ try {
1192
+ sqliteExec(this.db, `ALTER TABLE retrieval_traces ADD COLUMN selected_details_json TEXT;`);
1193
+ } catch {
1194
+ }
1195
+ try {
1196
+ sqliteExec(this.db, `ALTER TABLE retrieval_traces ADD COLUMN candidate_details_json TEXT;`);
1197
+ } catch {
1198
+ }
1060
1199
  const tableInfo = sqliteAll(this.db, "PRAGMA table_info(events)", []);
1061
1200
  const columnNames = tableInfo.map((col) => col.name);
1062
1201
  if (!columnNames.includes("access_count")) {
@@ -1077,6 +1216,15 @@ var SQLiteEventStore = class {
1077
1216
  console.error("Error adding last_accessed_at column:", err);
1078
1217
  }
1079
1218
  }
1219
+ if (!columnNames.includes("turn_id")) {
1220
+ try {
1221
+ sqliteExec(this.db, `
1222
+ ALTER TABLE events ADD COLUMN turn_id TEXT;
1223
+ `);
1224
+ } catch (err) {
1225
+ console.error("Error adding turn_id column:", err);
1226
+ }
1227
+ }
1080
1228
  try {
1081
1229
  sqliteExec(this.db, `
1082
1230
  CREATE INDEX IF NOT EXISTS idx_events_access_count ON events(access_count DESC);
@@ -1089,6 +1237,12 @@ var SQLiteEventStore = class {
1089
1237
  `);
1090
1238
  } catch (err) {
1091
1239
  }
1240
+ try {
1241
+ sqliteExec(this.db, `
1242
+ CREATE INDEX IF NOT EXISTS idx_events_turn_id ON events(turn_id);
1243
+ `);
1244
+ } catch (err) {
1245
+ }
1092
1246
  this.initialized = true;
1093
1247
  }
1094
1248
  /**
@@ -1113,9 +1267,11 @@ var SQLiteEventStore = class {
1113
1267
  const id = randomUUID2();
1114
1268
  const timestamp = toSQLiteTimestamp(input.timestamp);
1115
1269
  try {
1270
+ const metadata = input.metadata || {};
1271
+ const turnId = metadata.turnId || null;
1116
1272
  const insertEvent = this.db.prepare(`
1117
- INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
1118
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1273
+ INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata, turn_id)
1274
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1119
1275
  `);
1120
1276
  const insertDedup = this.db.prepare(`
1121
1277
  INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)
@@ -1132,12 +1288,28 @@ var SQLiteEventStore = class {
1132
1288
  input.content,
1133
1289
  canonicalKey,
1134
1290
  dedupeKey,
1135
- JSON.stringify(input.metadata || {})
1291
+ JSON.stringify(metadata),
1292
+ turnId
1136
1293
  );
1137
1294
  insertDedup.run(dedupeKey, id);
1138
1295
  insertLevel.run(id);
1139
1296
  });
1140
1297
  transaction();
1298
+ if (this.markdownMirror) {
1299
+ const event = {
1300
+ id,
1301
+ eventType: input.eventType,
1302
+ sessionId: input.sessionId,
1303
+ timestamp: input.timestamp,
1304
+ content: input.content,
1305
+ canonicalKey,
1306
+ dedupeKey,
1307
+ metadata
1308
+ };
1309
+ this.markdownMirror.append(event).catch((err) => {
1310
+ console.warn("[SQLiteEventStore] markdown mirror append failed:", err);
1311
+ });
1312
+ }
1141
1313
  return { success: true, eventId: id, isDuplicate: false };
1142
1314
  } catch (error) {
1143
1315
  return {
@@ -1196,6 +1368,92 @@ var SQLiteEventStore = class {
1196
1368
  );
1197
1369
  return rows.map(this.rowToEvent);
1198
1370
  }
1371
+ /**
1372
+ * Get events since a SQLite rowid (for robust incremental replication).
1373
+ * Rowid is monotonic for append-only tables, independent of client timestamps.
1374
+ */
1375
+ async getEventsSinceRowid(lastRowid, limit = 1e3) {
1376
+ await this.initialize();
1377
+ const rows = sqliteAll(
1378
+ this.db,
1379
+ `SELECT rowid as _rowid, * FROM events WHERE rowid > ? ORDER BY rowid ASC LIMIT ?`,
1380
+ [lastRowid, limit]
1381
+ );
1382
+ return rows.map((row) => ({
1383
+ rowid: row._rowid,
1384
+ event: this.rowToEvent(row)
1385
+ }));
1386
+ }
1387
+ /**
1388
+ * Import events with fixed IDs (used for cross-machine replication).
1389
+ * Idempotent: skips if event id or dedupeKey already exists.
1390
+ *
1391
+ * NOTE: This bypasses the append() id generation to preserve stable IDs.
1392
+ */
1393
+ async importEvents(events) {
1394
+ if (events.length === 0)
1395
+ return { inserted: 0, skipped: 0 };
1396
+ if (this.readOnly)
1397
+ return { inserted: 0, skipped: events.length };
1398
+ await this.initialize();
1399
+ const getById = this.db.prepare(`SELECT id FROM events WHERE id = ?`);
1400
+ const getByDedupe = this.db.prepare(`SELECT event_id FROM event_dedup WHERE dedupe_key = ?`);
1401
+ const insertEvent = this.db.prepare(`
1402
+ INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata, turn_id)
1403
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1404
+ `);
1405
+ const insertDedup = this.db.prepare(`
1406
+ INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)
1407
+ `);
1408
+ const insertLevel = this.db.prepare(`
1409
+ INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')
1410
+ `);
1411
+ let inserted = 0;
1412
+ let skipped = 0;
1413
+ const insertedEvents = [];
1414
+ const tx = this.db.transaction((batch) => {
1415
+ for (const ev of batch) {
1416
+ const existingById = getById.get(ev.id);
1417
+ if (existingById) {
1418
+ skipped++;
1419
+ continue;
1420
+ }
1421
+ const canonicalKey = ev.canonicalKey || makeCanonicalKey(ev.content);
1422
+ const dedupeKey = ev.dedupeKey || makeDedupeKey(ev.content, ev.sessionId);
1423
+ const existingByDedupe = getByDedupe.get(dedupeKey);
1424
+ if (existingByDedupe) {
1425
+ skipped++;
1426
+ continue;
1427
+ }
1428
+ const metadata = ev.metadata || {};
1429
+ const turnId = metadata.turnId;
1430
+ insertEvent.run(
1431
+ ev.id,
1432
+ ev.eventType,
1433
+ ev.sessionId,
1434
+ toSQLiteTimestamp(ev.timestamp),
1435
+ ev.content,
1436
+ canonicalKey,
1437
+ dedupeKey,
1438
+ JSON.stringify(metadata),
1439
+ turnId ?? null
1440
+ );
1441
+ insertDedup.run(dedupeKey, ev.id);
1442
+ insertLevel.run(ev.id);
1443
+ inserted++;
1444
+ insertedEvents.push(ev);
1445
+ }
1446
+ });
1447
+ tx(events);
1448
+ if (this.markdownMirror && insertedEvents.length > 0) {
1449
+ for (const ev of insertedEvents) {
1450
+ this.markdownMirror.append(ev).catch((err) => {
1451
+ console.warn("[SQLiteEventStore] markdown mirror append failed:", err);
1452
+ });
1453
+ }
1454
+ }
1455
+ return { inserted, skipped };
1456
+ }
1199
1457
  /**
1200
1458
  * Create or update session
1201
1459
  */
@@ -1358,6 +1616,35 @@ var SQLiteEventStore = class {
1358
1616
  [error, ...ids]
1359
1617
  );
1360
1618
  }
1619
+ /**
1620
+ * Get embedding/vector outbox health statistics
1621
+ */
1622
+ async getOutboxStats() {
1623
+ await this.initialize();
1624
+ const embeddingRows = sqliteAll(
1625
+ this.db,
1626
+ `SELECT status, COUNT(*) as count FROM embedding_outbox GROUP BY status`
1627
+ );
1628
+ const vectorRows = sqliteAll(
1629
+ this.db,
1630
+ `SELECT status, COUNT(*) as count FROM vector_outbox GROUP BY status`
1631
+ );
1632
+ const fromRows = (rows) => {
1633
+ const out = { pending: 0, processing: 0, failed: 0, total: 0 };
1634
+ for (const row of rows) {
1635
+ const key = row.status;
1636
+ if (key === "pending" || key === "processing" || key === "failed") {
1637
+ out[key] += row.count;
1638
+ }
1639
+ out.total += row.count;
1640
+ }
1641
+ return out;
1642
+ };
1643
+ return {
1644
+ embedding: fromRows(embeddingRows),
1645
+ vector: fromRows(vectorRows)
1646
+ };
1647
+ }
1361
1648
  /**
1362
1649
  * Update memory level
1363
1650
  */
@@ -1482,11 +1769,11 @@ var SQLiteEventStore = class {
1482
1769
  );
1483
1770
  }
1484
1771
  /**
1485
- * Get most accessed memories
1772
+ * Get most accessed memories (falls back to recent events if none accessed)
1486
1773
  */
1487
1774
  async getMostAccessed(limit = 10) {
1488
1775
  await this.initialize();
1489
- const rows = sqliteAll(
1776
+ let rows = sqliteAll(
1490
1777
  this.db,
1491
1778
  `SELECT * FROM events
1492
1779
  WHERE access_count > 0
@@ -1494,8 +1781,166 @@ var SQLiteEventStore = class {
1494
1781
  LIMIT ?`,
1495
1782
  [limit]
1496
1783
  );
1784
+ if (rows.length === 0) {
1785
+ rows = sqliteAll(
1786
+ this.db,
1787
+ `SELECT * FROM events
1788
+ ORDER BY timestamp DESC
1789
+ LIMIT ?`,
1790
+ [limit]
1791
+ );
1792
+ }
1497
1793
  return rows.map((row) => this.rowToEvent(row));
1498
1794
  }
1795
+ /**
1796
+ * Record a memory retrieval for helpfulness tracking
1797
+ */
1798
+ async recordRetrieval(eventId, sessionId, score, query) {
1799
+ if (this.readOnly)
1800
+ return;
1801
+ await this.initialize();
1802
+ const id = randomUUID2();
1803
+ sqliteRun(
1804
+ this.db,
1805
+ `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
1806
+ VALUES (?, ?, ?, ?, ?, datetime('now'))`,
1807
+ [id, eventId, sessionId, score, query.slice(0, 100)]
1808
+ );
1809
+ }
1810
+ /**
1811
+ * Evaluate helpfulness for all retrievals in a session
1812
+ * Called at session end - uses behavioral signals to compute score
1813
+ */
1814
+ async evaluateSessionHelpfulness(sessionId) {
1815
+ if (this.readOnly)
1816
+ return;
1817
+ await this.initialize();
1818
+ const retrievals = sqliteAll(
1819
+ this.db,
1820
+ `SELECT * FROM memory_helpfulness WHERE session_id = ? AND measured_at IS NULL`,
1821
+ [sessionId]
1822
+ );
1823
+ if (retrievals.length === 0)
1824
+ return;
1825
+ const sessionEvents = sqliteAll(
1826
+ this.db,
1827
+ `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
1828
+ [sessionId]
1829
+ );
1830
+ const promptEvents = sessionEvents.filter((e) => e.event_type === "user_prompt");
1831
+ const toolEvents = sessionEvents.filter((e) => e.event_type === "tool_observation");
1832
+ let toolSuccessCount = 0;
1833
+ let toolTotalCount = toolEvents.length;
1834
+ for (const t of toolEvents) {
1835
+ try {
1836
+ const content = JSON.parse(t.content);
1837
+ if (content.success !== false)
1838
+ toolSuccessCount++;
1839
+ } catch {
1840
+ toolSuccessCount++;
1841
+ }
1842
+ }
1843
+ const toolSuccessRatio = toolTotalCount > 0 ? toolSuccessCount / toolTotalCount : 0.5;
1844
+ for (const retrieval of retrievals) {
1845
+ const retrievalTime = retrieval.created_at;
1846
+ const eventsAfter = sessionEvents.filter((e) => e.timestamp > retrievalTime);
1847
+ const sessionContinued = eventsAfter.length > 0 ? 1 : 0;
1848
+ const promptsAfter = promptEvents.filter((e) => e.timestamp > retrievalTime);
1849
+ const promptCountAfter = promptsAfter.length;
1850
+ const queryWords = new Set((retrieval.query_preview || "").toLowerCase().split(/\s+/).filter((w) => w.length > 2));
1851
+ let wasReasked = 0;
1852
+ for (const p of promptsAfter) {
1853
+ const pWords = new Set(p.content.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
1854
+ let overlap = 0;
1855
+ for (const w of queryWords) {
1856
+ if (pWords.has(w))
1857
+ overlap++;
1858
+ }
1859
+ if (queryWords.size > 0 && overlap / queryWords.size > 0.5) {
1860
+ wasReasked = 1;
1861
+ break;
1862
+ }
1863
+ }
1864
+ const retrievalScore = retrieval.retrieval_score || 0;
1865
+ const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
1866
+ sqliteRun(
1867
+ this.db,
1868
+ `UPDATE memory_helpfulness
1869
+ SET session_continued = ?, prompt_count_after = ?,
1870
+ tool_success_count = ?, tool_total_count = ?,
1871
+ was_reasked = ?, helpfulness_score = ?,
1872
+ measured_at = datetime('now')
1873
+ WHERE id = ?`,
1874
+ [
1875
+ sessionContinued,
1876
+ promptCountAfter,
1877
+ toolSuccessCount,
1878
+ toolTotalCount,
1879
+ wasReasked,
1880
+ helpfulnessScore,
1881
+ retrieval.id
1882
+ ]
1883
+ );
1884
+ }
1885
+ }
1886
+ /**
1887
+ * Get most helpful memories ranked by helpfulness score
1888
+ */
1889
+ async getHelpfulMemories(limit = 10) {
1890
+ await this.initialize();
1891
+ const rows = sqliteAll(
1892
+ this.db,
1893
+ `SELECT
1894
+ mh.event_id,
1895
+ AVG(mh.helpfulness_score) as avg_score,
1896
+ COUNT(*) as eval_count,
1897
+ e.content,
1898
+ e.access_count
1899
+ FROM memory_helpfulness mh
1900
+ JOIN events e ON e.id = mh.event_id
1901
+ WHERE mh.measured_at IS NOT NULL
1902
+ GROUP BY mh.event_id
1903
+ ORDER BY avg_score DESC
1904
+ LIMIT ?`,
1905
+ [limit]
1906
+ );
1907
+ return rows.map((r) => ({
1908
+ eventId: r.event_id,
1909
+ summary: r.content.substring(0, 200) + (r.content.length > 200 ? "..." : ""),
1910
+ helpfulnessScore: Math.round(r.avg_score * 100) / 100,
1911
+ accessCount: r.access_count || 0,
1912
+ evaluationCount: r.eval_count
1913
+ }));
1914
+ }
1915
+ /**
1916
+ * Get helpfulness statistics for dashboard
1917
+ */
1918
+ async getHelpfulnessStats() {
1919
+ await this.initialize();
1920
+ const stats = sqliteGet(
1921
+ this.db,
1922
+ `SELECT
1923
+ AVG(helpfulness_score) as avg_score,
1924
+ COUNT(*) as total_evaluated,
1925
+ SUM(CASE WHEN helpfulness_score >= 0.7 THEN 1 ELSE 0 END) as helpful,
1926
+ SUM(CASE WHEN helpfulness_score >= 0.4 AND helpfulness_score < 0.7 THEN 1 ELSE 0 END) as neutral,
1927
+ SUM(CASE WHEN helpfulness_score < 0.4 THEN 1 ELSE 0 END) as unhelpful
1928
+ FROM memory_helpfulness
1929
+ WHERE measured_at IS NOT NULL`
1930
+ );
1931
+ const totalRow = sqliteGet(
1932
+ this.db,
1933
+ `SELECT COUNT(*) as total FROM memory_helpfulness`
1934
+ );
1935
+ return {
1936
+ avgScore: Math.round((stats?.avg_score || 0) * 100) / 100,
1937
+ totalEvaluated: stats?.total_evaluated || 0,
1938
+ totalRetrievals: totalRow?.total || 0,
1939
+ helpful: stats?.helpful || 0,
1940
+ neutral: stats?.neutral || 0,
1941
+ unhelpful: stats?.unhelpful || 0
1942
+ };
1943
+ }
1499
1944
  /**
1500
1945
  * Fast keyword search using FTS5
1501
1946
  * Returns events matching the search query, ranked by relevance
@@ -1558,12 +2003,222 @@ var SQLiteEventStore = class {
1558
2003
  getDatabase() {
1559
2004
  return this.db;
1560
2005
  }
2006
+ async recordRetrievalTrace(input) {
2007
+ await this.initialize();
2008
+ const traceId = randomUUID2();
2009
+ sqliteRun(
2010
+ this.db,
2011
+ `INSERT INTO retrieval_traces (
2012
+ trace_id, session_id, project_hash, query_text, strategy,
2013
+ candidate_event_ids, selected_event_ids, candidate_details_json, selected_details_json,
2014
+ candidate_count, selected_count, confidence, fallback_trace
2015
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2016
+ [
2017
+ traceId,
2018
+ input.sessionId || null,
2019
+ input.projectHash || null,
2020
+ input.queryText,
2021
+ input.strategy || null,
2022
+ JSON.stringify(input.candidateEventIds || []),
2023
+ JSON.stringify(input.selectedEventIds || []),
2024
+ JSON.stringify(input.candidateDetails || []),
2025
+ JSON.stringify(input.selectedDetails || []),
2026
+ (input.candidateEventIds || []).length,
2027
+ (input.selectedEventIds || []).length,
2028
+ input.confidence || null,
2029
+ JSON.stringify(input.fallbackTrace || [])
2030
+ ]
2031
+ );
2032
+ }
2033
+ async getRecentRetrievalTraces(limit = 50) {
2034
+ await this.initialize();
2035
+ const rows = sqliteAll(
2036
+ this.db,
2037
+ `SELECT * FROM retrieval_traces ORDER BY created_at DESC LIMIT ?`,
2038
+ [limit]
2039
+ );
2040
+ return rows.map((row) => ({
2041
+ traceId: row.trace_id,
2042
+ sessionId: row.session_id || void 0,
2043
+ projectHash: row.project_hash || void 0,
2044
+ queryText: row.query_text,
2045
+ strategy: row.strategy || void 0,
2046
+ candidateEventIds: row.candidate_event_ids ? JSON.parse(row.candidate_event_ids) : [],
2047
+ selectedEventIds: row.selected_event_ids ? JSON.parse(row.selected_event_ids) : [],
2048
+ candidateDetails: row.candidate_details_json ? JSON.parse(row.candidate_details_json) : [],
2049
+ selectedDetails: row.selected_details_json ? JSON.parse(row.selected_details_json) : [],
2050
+ candidateCount: Number(row.candidate_count || 0),
2051
+ selectedCount: Number(row.selected_count || 0),
2052
+ confidence: row.confidence || void 0,
2053
+ fallbackTrace: row.fallback_trace ? JSON.parse(row.fallback_trace) : [],
2054
+ createdAt: toDateFromSQLite(row.created_at)
2055
+ }));
2056
+ }
2057
+ async getRetrievalTraceStats() {
2058
+ await this.initialize();
2059
+ const row = sqliteGet(
2060
+ this.db,
2061
+ `SELECT
2062
+ COUNT(*) as total_queries,
2063
+ AVG(candidate_count) as avg_candidate_count,
2064
+ AVG(selected_count) as avg_selected_count,
2065
+ CASE
2066
+ WHEN SUM(candidate_count) > 0 THEN (SUM(selected_count) * 1.0 / SUM(candidate_count))
2067
+ ELSE 0
2068
+ END as selection_rate
2069
+ FROM retrieval_traces`,
2070
+ []
2071
+ );
2072
+ return {
2073
+ totalQueries: Number(row?.total_queries || 0),
2074
+ avgCandidateCount: Number(row?.avg_candidate_count || 0),
2075
+ avgSelectedCount: Number(row?.avg_selected_count || 0),
2076
+ selectionRate: Number(row?.selection_rate || 0)
2077
+ };
2078
+ }
1561
2079
  /**
1562
2080
  * Close database connection
1563
2081
  */
1564
2082
  async close() {
1565
2083
  sqliteClose(this.db);
1566
2084
  }
2085
+ /**
2086
+ * Get events grouped by turn_id for a session
2087
+ * Returns turns ordered by first event timestamp (newest first)
2088
+ */
2089
+ async getSessionTurns(sessionId, options) {
2090
+ await this.initialize();
2091
+ const limit = options?.limit || 20;
2092
+ const offset = options?.offset || 0;
2093
+ const turnRows = sqliteAll(
2094
+ this.db,
2095
+ `SELECT turn_id, MIN(timestamp) as min_ts
2096
+ FROM events
2097
+ WHERE session_id = ? AND turn_id IS NOT NULL
2098
+ GROUP BY turn_id
2099
+ ORDER BY min_ts DESC
2100
+ LIMIT ? OFFSET ?`,
2101
+ [sessionId, limit, offset]
2102
+ );
2103
+ const turns = [];
2104
+ for (const turnRow of turnRows) {
2105
+ const events = await this.getEventsByTurn(turnRow.turn_id);
2106
+ const promptEvent = events.find((e) => e.eventType === "user_prompt");
2107
+ const toolEvents = events.filter((e) => e.eventType === "tool_observation");
2108
+ const hasResponse = events.some((e) => e.eventType === "agent_response");
2109
+ turns.push({
2110
+ turnId: turnRow.turn_id,
2111
+ events,
2112
+ startedAt: toDateFromSQLite(turnRow.min_ts),
2113
+ promptPreview: promptEvent ? promptEvent.content.slice(0, 200) + (promptEvent.content.length > 200 ? "..." : "") : "(no prompt)",
2114
+ eventCount: events.length,
2115
+ toolCount: toolEvents.length,
2116
+ hasResponse
2117
+ });
2118
+ }
2119
+ return turns;
2120
+ }
2121
+ /**
2122
+ * Get all events for a specific turn_id
2123
+ */
2124
+ async getEventsByTurn(turnId) {
2125
+ await this.initialize();
2126
+ const rows = sqliteAll(
2127
+ this.db,
2128
+ `SELECT * FROM events WHERE turn_id = ? ORDER BY timestamp ASC`,
2129
+ [turnId]
2130
+ );
2131
+ return rows.map(this.rowToEvent);
2132
+ }
2133
+ /**
2134
+ * Count total turns for a session
2135
+ */
2136
+ async countSessionTurns(sessionId) {
2137
+ await this.initialize();
2138
+ const row = sqliteGet(
2139
+ this.db,
2140
+ `SELECT COUNT(DISTINCT turn_id) as count
2141
+ FROM events
2142
+ WHERE session_id = ? AND turn_id IS NOT NULL`,
2143
+ [sessionId]
2144
+ );
2145
+ return row?.count || 0;
2146
+ }
2147
+ /**
2148
+ * Migrate existing events: backfill turn_id for events that have turnId in metadata
2149
+ * but no turn_id column value (for events stored before this migration)
2150
+ */
2151
+ async backfillTurnIds() {
2152
+ await this.initialize();
2153
+ const rows = sqliteAll(
2154
+ this.db,
2155
+ `SELECT id, metadata FROM events
2156
+ WHERE turn_id IS NULL AND metadata IS NOT NULL AND metadata LIKE '%turnId%'`
2157
+ );
2158
+ let updated = 0;
2159
+ for (const row of rows) {
2160
+ try {
2161
+ const metadata = JSON.parse(row.metadata);
2162
+ if (metadata.turnId) {
2163
+ sqliteRun(
2164
+ this.db,
2165
+ `UPDATE events SET turn_id = ? WHERE id = ?`,
2166
+ [metadata.turnId, row.id]
2167
+ );
2168
+ updated++;
2169
+ }
2170
+ } catch {
2171
+ }
2172
+ }
2173
+ return updated;
2174
+ }
2175
+ /**
2176
+ * Delete all events for a session (for force reimport)
2177
+ */
2178
+ async deleteSessionEvents(sessionId) {
2179
+ await this.initialize();
2180
+ const events = sqliteAll(
2181
+ this.db,
2182
+ `SELECT id FROM events WHERE session_id = ?`,
2183
+ [sessionId]
2184
+ );
2185
+ if (events.length === 0)
2186
+ return 0;
2187
+ const eventIds = events.map((e) => e.id);
2188
+ const placeholders = eventIds.map(() => "?").join(",");
2189
+ const ftsTriggersDropped = [];
2190
+ for (const triggerName of ["events_fts_delete", "events_fts_update", "events_fts_insert"]) {
2191
+ try {
2192
+ sqliteRun(this.db, `DROP TRIGGER IF EXISTS ${triggerName}`);
2193
+ ftsTriggersDropped.push(triggerName);
2194
+ } catch {
2195
+ }
2196
+ }
2197
+ for (const table of ["event_dedup", "memory_levels", "embedding_queue", "embedding_outbox", "vector_outbox"]) {
2198
+ try {
2199
+ sqliteRun(this.db, `DELETE FROM ${table} WHERE event_id IN (${placeholders})`, eventIds);
2200
+ } catch {
2201
+ }
2202
+ }
2203
+ const result = sqliteRun(this.db, `DELETE FROM events WHERE session_id = ?`, [sessionId]);
2204
+ if (ftsTriggersDropped.length > 0) {
2205
+ try {
2206
+ sqliteRun(this.db, `INSERT INTO events_fts(events_fts) VALUES('rebuild')`);
2207
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
2208
+ INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
2209
+ END`);
2210
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
2211
+ INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
2212
+ END`);
2213
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
2214
+ INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
2215
+ INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
2216
+ END`);
2217
+ } catch {
2218
+ }
2219
+ }
2220
+ return result.changes || 0;
2221
+ }
1567
2222
  /**
1568
2223
  * Convert database row to MemoryEvent
1569
2224
  */
@@ -1584,6 +2239,9 @@ var SQLiteEventStore = class {
1584
2239
  if (row.last_accessed_at !== void 0) {
1585
2240
  event.last_accessed_at = row.last_accessed_at;
1586
2241
  }
2242
+ if (row.turn_id !== void 0 && row.turn_id !== null) {
2243
+ event.turn_id = row.turn_id;
2244
+ }
1587
2245
  return event;
1588
2246
  }
1589
2247
  };
@@ -1795,7 +2453,16 @@ var VectorStore = class {
1795
2453
  metadata: JSON.stringify(record.metadata || {})
1796
2454
  };
1797
2455
  if (!this.table) {
1798
- this.table = await this.db.createTable(this.tableName, [data]);
2456
+ try {
2457
+ this.table = await this.db.createTable(this.tableName, [data]);
2458
+ } catch (e) {
2459
+ if (e?.message?.includes("already exists")) {
2460
+ this.table = await this.db.openTable(this.tableName);
2461
+ await this.table.add([data]);
2462
+ } else {
2463
+ throw e;
2464
+ }
2465
+ }
1799
2466
  } else {
1800
2467
  await this.table.add([data]);
1801
2468
  }
@@ -1821,7 +2488,16 @@ var VectorStore = class {
1821
2488
  metadata: JSON.stringify(record.metadata || {})
1822
2489
  }));
1823
2490
  if (!this.table) {
1824
- this.table = await this.db.createTable(this.tableName, data);
2491
+ try {
2492
+ this.table = await this.db.createTable(this.tableName, data);
2493
+ } catch (e) {
2494
+ if (e?.message?.includes("already exists")) {
2495
+ this.table = await this.db.openTable(this.tableName);
2496
+ await this.table.add(data);
2497
+ } else {
2498
+ throw e;
2499
+ }
2500
+ }
1825
2501
  } else {
1826
2502
  await this.table.add(data);
1827
2503
  }
@@ -2261,7 +2937,20 @@ var DEFAULT_OPTIONS = {
2261
2937
  topK: 5,
2262
2938
  minScore: 0.7,
2263
2939
  maxTokens: 2e3,
2264
- includeSessionContext: true
2940
+ includeSessionContext: true,
2941
+ strategy: "auto",
2942
+ rerankWithKeyword: true,
2943
+ decayPolicy: {
2944
+ enabled: true,
2945
+ windowDays: 30,
2946
+ maxPenalty: 0.15
2947
+ },
2948
+ graphHop: {
2949
+ enabled: true,
2950
+ maxHops: 1,
2951
+ hopPenalty: 0.08
2952
+ },
2953
+ projectScopeMode: "global"
2265
2954
  };
2266
2955
  var Retriever = class {
2267
2956
  eventStore;
@@ -2271,6 +2960,7 @@ var Retriever = class {
2271
2960
  sharedStore;
2272
2961
  sharedVectorStore;
2273
2962
  graduation;
2963
+ queryRewriter;
2274
2964
  constructor(eventStore, vectorStore, embedder, matcher, sharedOptions) {
2275
2965
  this.eventStore = eventStore;
2276
2966
  this.vectorStore = vectorStore;
@@ -2279,47 +2969,105 @@ var Retriever = class {
2279
2969
  this.sharedStore = sharedOptions?.sharedStore;
2280
2970
  this.sharedVectorStore = sharedOptions?.sharedVectorStore;
2281
2971
  }
2282
- /**
2283
- * Set graduation pipeline for access tracking
2284
- */
2285
2972
  setGraduationPipeline(graduation) {
2286
2973
  this.graduation = graduation;
2287
2974
  }
2288
- /**
2289
- * Set shared stores after construction
2290
- */
2291
2975
  setSharedStores(sharedStore, sharedVectorStore) {
2292
2976
  this.sharedStore = sharedStore;
2293
2977
  this.sharedVectorStore = sharedVectorStore;
2294
2978
  }
2295
- /**
2296
- * Retrieve relevant memories for a query
2297
- */
2979
+ setQueryRewriter(rewriter) {
2980
+ this.queryRewriter = rewriter;
2981
+ }
2298
2982
  async retrieve(query, options = {}) {
2299
2983
  const opts = { ...DEFAULT_OPTIONS, ...options };
2300
- const queryEmbedding = await this.embedder.embed(query);
2301
- const searchResults = await this.vectorStore.search(queryEmbedding.vector, {
2302
- limit: opts.topK * 2,
2303
- // Get extra for filtering
2984
+ const sessionFilter = opts.scope?.sessionId ?? opts.sessionId;
2985
+ const fallbackTrace = [];
2986
+ const fallbackEnabled = (opts.strategy ?? "auto") === "auto";
2987
+ const primaryStrategy = opts.strategy === "auto" ? "fast" : opts.strategy || "fast";
2988
+ let current = await this.runStage(query, {
2989
+ strategy: primaryStrategy,
2990
+ topK: opts.topK,
2304
2991
  minScore: opts.minScore,
2305
- sessionId: opts.sessionId
2992
+ sessionId: sessionFilter,
2993
+ scope: opts.scope,
2994
+ rerankWithKeyword: opts.rerankWithKeyword !== false,
2995
+ rerankWeights: opts.rerankWeights,
2996
+ decayPolicy: opts.decayPolicy,
2997
+ intentRewrite: opts.intentRewrite === true,
2998
+ graphHop: opts.graphHop,
2999
+ projectScopeMode: opts.projectScopeMode,
3000
+ projectHash: opts.projectHash,
3001
+ allowedProjectHashes: opts.allowedProjectHashes
2306
3002
  });
2307
- const matchResult = this.matcher.matchSearchResults(
2308
- searchResults,
2309
- (eventId) => this.getEventAgeDays(eventId)
2310
- );
2311
- const memories = await this.enrichResults(searchResults.slice(0, opts.topK), opts);
3003
+ fallbackTrace.push(`stage:primary:${primaryStrategy}`);
3004
+ if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results) && primaryStrategy !== "deep") {
3005
+ current = await this.runStage(query, {
3006
+ strategy: "deep",
3007
+ topK: opts.topK,
3008
+ minScore: opts.minScore,
3009
+ sessionId: sessionFilter,
3010
+ scope: opts.scope,
3011
+ rerankWithKeyword: opts.rerankWithKeyword !== false,
3012
+ rerankWeights: opts.rerankWeights,
3013
+ decayPolicy: opts.decayPolicy,
3014
+ graphHop: opts.graphHop,
3015
+ projectScopeMode: opts.projectScopeMode,
3016
+ projectHash: opts.projectHash,
3017
+ allowedProjectHashes: opts.allowedProjectHashes
3018
+ });
3019
+ fallbackTrace.push("fallback:deep");
3020
+ }
3021
+ if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results)) {
3022
+ current = await this.runStage(query, {
3023
+ strategy: "deep",
3024
+ topK: opts.topK,
3025
+ minScore: Math.max(0.5, opts.minScore - 0.15),
3026
+ sessionId: void 0,
3027
+ scope: void 0,
3028
+ rerankWithKeyword: true,
3029
+ rerankWeights: opts.rerankWeights,
3030
+ decayPolicy: opts.decayPolicy,
3031
+ graphHop: opts.graphHop,
3032
+ projectScopeMode: opts.projectScopeMode,
3033
+ projectHash: opts.projectHash,
3034
+ allowedProjectHashes: opts.allowedProjectHashes
3035
+ });
3036
+ fallbackTrace.push("fallback:scope-expanded");
3037
+ }
3038
+ if (fallbackEnabled && this.shouldFallback(current.matchResult, current.results)) {
3039
+ const summary = await this.buildSummaryFallback(query, opts.topK);
3040
+ current = {
3041
+ results: summary,
3042
+ candidateResults: summary,
3043
+ matchResult: this.matcher.matchSearchResults(summary, () => 0)
3044
+ };
3045
+ fallbackTrace.push("fallback:summary");
3046
+ }
3047
+ const memories = await this.enrichResults(current.results.slice(0, opts.topK), opts);
2312
3048
  const context = this.buildContext(memories, opts.maxTokens);
2313
3049
  return {
2314
3050
  memories,
2315
- matchResult,
3051
+ matchResult: current.matchResult,
2316
3052
  totalTokens: this.estimateTokens(context),
2317
- context
3053
+ context,
3054
+ fallbackTrace,
3055
+ selectedDebug: current.results.slice(0, opts.topK).map((r) => ({
3056
+ eventId: r.eventId,
3057
+ score: r.score,
3058
+ semanticScore: r.semanticScore,
3059
+ lexicalScore: r.lexicalScore,
3060
+ recencyScore: r.recencyScore
3061
+ })),
3062
+ candidateDebug: (current.candidateResults || []).slice(0, Math.max(opts.topK * 3, 20)).map((r) => ({
3063
+ eventId: r.eventId,
3064
+ score: r.score,
3065
+ semanticScore: r.semanticScore,
3066
+ lexicalScore: r.lexicalScore,
3067
+ recencyScore: r.recencyScore
3068
+ }))
2318
3069
  };
2319
3070
  }
2320
- /**
2321
- * Retrieve with unified search (project + shared)
2322
- */
2323
3071
  async retrieveUnified(query, options = {}) {
2324
3072
  const projectResult = await this.retrieve(query, options);
2325
3073
  if (!options.includeShared || !this.sharedStore || !this.sharedVectorStore) {
@@ -2327,22 +3075,19 @@ var Retriever = class {
2327
3075
  }
2328
3076
  try {
2329
3077
  const queryEmbedding = await this.embedder.embed(query);
2330
- const sharedVectorResults = await this.sharedVectorStore.search(
2331
- queryEmbedding.vector,
2332
- {
2333
- limit: options.topK || 5,
2334
- minScore: options.minScore || 0.7,
2335
- excludeProjectHash: options.projectHash
2336
- }
2337
- );
3078
+ const sharedVectorResults = await this.sharedVectorStore.search(queryEmbedding.vector, {
3079
+ limit: options.topK || 5,
3080
+ minScore: options.minScore || 0.7,
3081
+ excludeProjectHash: options.projectHash
3082
+ });
2338
3083
  const sharedMemories = [];
2339
3084
  for (const result of sharedVectorResults) {
2340
3085
  const entry = await this.sharedStore.get(result.entryId);
2341
- if (entry) {
2342
- if (!options.projectHash || entry.sourceProjectHash !== options.projectHash) {
2343
- sharedMemories.push(entry);
2344
- await this.sharedStore.recordUsage(entry.entryId);
2345
- }
3086
+ if (!entry)
3087
+ continue;
3088
+ if (!options.projectHash || entry.sourceProjectHash !== options.projectHash) {
3089
+ sharedMemories.push(entry);
3090
+ await this.sharedStore.recordUsage(entry.entryId);
2346
3091
  }
2347
3092
  }
2348
3093
  const unifiedContext = this.buildUnifiedContext(projectResult, sharedMemories);
@@ -2357,50 +3102,243 @@ var Retriever = class {
2357
3102
  return projectResult;
2358
3103
  }
2359
3104
  }
2360
- /**
2361
- * Build unified context combining project and shared memories
2362
- */
2363
- buildUnifiedContext(projectResult, sharedMemories) {
2364
- let context = projectResult.context;
2365
- if (sharedMemories.length > 0) {
2366
- context += "\n\n## Cross-Project Knowledge\n\n";
2367
- for (const memory of sharedMemories.slice(0, 3)) {
2368
- context += `### ${memory.title}
2369
- `;
2370
- if (memory.symptoms.length > 0) {
2371
- context += `**Symptoms:** ${memory.symptoms.join(", ")}
2372
- `;
2373
- }
2374
- context += `**Root Cause:** ${memory.rootCause}
2375
- `;
2376
- context += `**Solution:** ${memory.solution}
2377
- `;
2378
- if (memory.technologies && memory.technologies.length > 0) {
2379
- context += `**Technologies:** ${memory.technologies.join(", ")}
2380
- `;
3105
+ async runStage(query, input) {
3106
+ let initialResults = await this.searchByStrategy(query, {
3107
+ strategy: input.strategy,
3108
+ topK: input.topK,
3109
+ minScore: input.minScore,
3110
+ sessionId: input.sessionId
3111
+ });
3112
+ if (input.intentRewrite && input.strategy === "deep" && this.queryRewriter) {
3113
+ const rewritten = (await this.queryRewriter(query))?.trim();
3114
+ if (rewritten && rewritten !== query) {
3115
+ const rewrittenResults = await this.searchByStrategy(rewritten, {
3116
+ strategy: "deep",
3117
+ topK: input.topK,
3118
+ minScore: Math.max(0.5, input.minScore - 0.1),
3119
+ sessionId: input.sessionId
3120
+ });
3121
+ initialResults = this.mergeResults(initialResults, rewrittenResults, input.topK * 3);
3122
+ }
3123
+ }
3124
+ const expandedResults = input.graphHop?.enabled === false ? initialResults : await this.expandGraphHops(initialResults, {
3125
+ maxHops: Math.max(1, input.graphHop?.maxHops ?? 1),
3126
+ hopPenalty: Math.max(0, input.graphHop?.hopPenalty ?? 0.08),
3127
+ limit: input.topK * 4
3128
+ });
3129
+ const rerankedResults = input.rerankWithKeyword ? this.rerankByKeywordOverlap(expandedResults, query, input.rerankWeights, input.decayPolicy) : expandedResults;
3130
+ const filtered = await this.applyScopeFilters(rerankedResults, {
3131
+ scope: input.scope,
3132
+ projectScopeMode: input.projectScopeMode,
3133
+ projectHash: input.projectHash,
3134
+ allowedProjectHashes: input.allowedProjectHashes
3135
+ });
3136
+ const top = filtered.slice(0, input.topK);
3137
+ const matchResult = this.matcher.matchSearchResults(top, () => 0);
3138
+ return { results: top, candidateResults: filtered, matchResult };
3139
+ }
3140
+ mergeResults(primary, secondary, limit) {
3141
+ const byId = /* @__PURE__ */ new Map();
3142
+ for (const row of primary)
3143
+ byId.set(row.eventId, row);
3144
+ for (const row of secondary) {
3145
+ const prev = byId.get(row.eventId);
3146
+ if (!prev || row.score > prev.score) {
3147
+ byId.set(row.eventId, row);
3148
+ }
3149
+ }
3150
+ return [...byId.values()].sort((a, b) => b.score - a.score).slice(0, limit);
3151
+ }
3152
+ async expandGraphHops(seeds, opts) {
3153
+ const byId = /* @__PURE__ */ new Map();
3154
+ for (const s of seeds)
3155
+ byId.set(s.eventId, s);
3156
+ let frontier = seeds.map((s) => ({ row: s, hop: 0 }));
3157
+ for (let hop = 1; hop <= opts.maxHops; hop += 1) {
3158
+ const next = [];
3159
+ for (const f of frontier) {
3160
+ const ev = await this.eventStore.getEvent(f.row.eventId);
3161
+ if (!ev)
3162
+ continue;
3163
+ const rel = ev.metadata?.relatedEventIds ?? [];
3164
+ const relatedIds = Array.isArray(rel) ? rel.filter((x) => typeof x === "string") : [];
3165
+ for (const rid of relatedIds) {
3166
+ if (byId.has(rid))
3167
+ continue;
3168
+ const target = await this.eventStore.getEvent(rid);
3169
+ if (!target)
3170
+ continue;
3171
+ const score = Math.max(0, f.row.score - opts.hopPenalty * hop);
3172
+ const row = {
3173
+ id: `hop-${hop}-${rid}`,
3174
+ eventId: target.id,
3175
+ content: target.content,
3176
+ score,
3177
+ sessionId: target.sessionId,
3178
+ eventType: target.eventType,
3179
+ timestamp: target.timestamp.toISOString()
3180
+ };
3181
+ byId.set(row.eventId, row);
3182
+ next.push({ row, hop });
3183
+ if (byId.size >= opts.limit)
3184
+ break;
2381
3185
  }
2382
- context += `_Confidence: ${(memory.confidence * 100).toFixed(0)}%_
2383
-
2384
- `;
3186
+ if (byId.size >= opts.limit)
3187
+ break;
2385
3188
  }
3189
+ frontier = next;
3190
+ if (frontier.length === 0 || byId.size >= opts.limit)
3191
+ break;
2386
3192
  }
2387
- return context;
3193
+ return [...byId.values()].sort((a, b) => b.score - a.score).slice(0, opts.limit);
3194
+ }
3195
+ shouldFallback(matchResult, results) {
3196
+ if (results.length === 0)
3197
+ return true;
3198
+ if (matchResult.confidence === "none")
3199
+ return true;
3200
+ return false;
3201
+ }
3202
+ async buildSummaryFallback(query, topK) {
3203
+ const recent = await this.eventStore.getRecentEvents(Math.max(topK * 6, 20));
3204
+ const q = this.tokenize(query);
3205
+ const ranked = recent.map((e) => ({ e, overlap: this.keywordOverlap(q, this.tokenize(e.content)) })).filter((r) => r.overlap > 0).sort((a, b) => b.overlap - a.overlap).slice(0, topK).map((row, idx) => ({
3206
+ id: `summary-${row.e.id}`,
3207
+ eventId: row.e.id,
3208
+ content: row.e.content,
3209
+ score: Math.max(0.25, 0.6 - idx * 0.05),
3210
+ sessionId: row.e.sessionId,
3211
+ eventType: row.e.eventType,
3212
+ timestamp: row.e.timestamp.toISOString()
3213
+ }));
3214
+ return ranked;
3215
+ }
3216
+ async searchByStrategy(query, input) {
3217
+ const strategy = input.strategy === "auto" ? "deep" : input.strategy;
3218
+ if (strategy === "fast") {
3219
+ const keyword = await this.searchByKeyword(query, {
3220
+ limit: Math.max(5, input.topK * 3),
3221
+ sessionId: input.sessionId
3222
+ });
3223
+ return keyword;
3224
+ }
3225
+ const queryEmbedding = await this.embedder.embed(query);
3226
+ return this.vectorStore.search(queryEmbedding.vector, {
3227
+ limit: Math.max(5, input.topK * 3),
3228
+ minScore: input.minScore,
3229
+ sessionId: input.sessionId
3230
+ });
3231
+ }
3232
+ async searchByKeyword(query, input) {
3233
+ if (this.eventStore.keywordSearch) {
3234
+ const rows = await this.eventStore.keywordSearch(query, input.limit);
3235
+ const filtered2 = input.sessionId ? rows.filter((r) => r.event.sessionId === input.sessionId) : rows;
3236
+ return filtered2.map((row, idx) => ({
3237
+ id: `kw-${row.event.id}`,
3238
+ eventId: row.event.id,
3239
+ content: row.event.content,
3240
+ score: Math.max(0.4, 1 - idx * 0.04),
3241
+ sessionId: row.event.sessionId,
3242
+ eventType: row.event.eventType,
3243
+ timestamp: row.event.timestamp.toISOString()
3244
+ }));
3245
+ }
3246
+ const recent = await this.eventStore.getRecentEvents(input.limit * 4);
3247
+ const tokens = this.tokenize(query);
3248
+ const filtered = recent.filter((e) => input.sessionId ? e.sessionId === input.sessionId : true).map((e) => ({ e, overlap: this.keywordOverlap(tokens, this.tokenize(e.content)) })).filter((r) => r.overlap > 0).sort((a, b) => b.overlap - a.overlap).slice(0, input.limit);
3249
+ return filtered.map((row, idx) => ({
3250
+ id: `kw-fallback-${row.e.id}`,
3251
+ eventId: row.e.id,
3252
+ content: row.e.content,
3253
+ score: Math.max(0.3, 0.9 - idx * 0.05),
3254
+ sessionId: row.e.sessionId,
3255
+ eventType: row.e.eventType,
3256
+ timestamp: row.e.timestamp.toISOString()
3257
+ }));
3258
+ }
3259
+ rerankByKeywordOverlap(results, query, weights, decayPolicy) {
3260
+ const q = this.tokenize(query);
3261
+ const now = Date.now();
3262
+ const sw = Math.max(0, weights?.semantic ?? 0.7);
3263
+ const lw = Math.max(0, weights?.lexical ?? 0.2);
3264
+ const rw = Math.max(0, weights?.recency ?? 0.1);
3265
+ const total = sw + lw + rw || 1;
3266
+ const decayEnabled = decayPolicy?.enabled !== false;
3267
+ const decayWindow = Math.max(1, decayPolicy?.windowDays ?? 30);
3268
+ const decayMaxPenalty = Math.max(0, decayPolicy?.maxPenalty ?? 0.15);
3269
+ return [...results].map((r) => {
3270
+ const overlap = this.keywordOverlap(q, this.tokenize(r.content));
3271
+ const recencyDays = Math.max(0, (now - new Date(r.timestamp).getTime()) / (1e3 * 60 * 60 * 24));
3272
+ const recency = Math.max(0, 1 - recencyDays / decayWindow);
3273
+ let blended = (r.score * sw + overlap * lw + recency * rw) / total;
3274
+ if (decayEnabled && recencyDays > decayWindow && overlap < 0.5) {
3275
+ const ageFactor = Math.min(1, (recencyDays - decayWindow) / decayWindow);
3276
+ blended -= decayMaxPenalty * ageFactor;
3277
+ }
3278
+ return { ...r, score: Math.max(0, blended), semanticScore: r.score, lexicalScore: overlap, recencyScore: recency };
3279
+ }).sort((a, b) => b.score - a.score);
3280
+ }
3281
+ async applyScopeFilters(results, options) {
3282
+ const scope = options?.scope;
3283
+ const projectScopeMode = options?.projectScopeMode ?? "global";
3284
+ const allowedProjectHashes = new Set(
3285
+ [options?.projectHash, ...options?.allowedProjectHashes || []].filter(
3286
+ (value) => typeof value === "string" && value.length > 0
3287
+ )
3288
+ );
3289
+ if (!scope && projectScopeMode === "global")
3290
+ return results;
3291
+ const normalizedIncludes = (scope?.contentIncludes || []).map((s) => s.toLowerCase());
3292
+ const filtered = [];
3293
+ for (const result of results) {
3294
+ if (scope?.sessionId && result.sessionId !== scope.sessionId)
3295
+ continue;
3296
+ if (scope?.sessionIdPrefix && !result.sessionId.startsWith(scope.sessionIdPrefix))
3297
+ continue;
3298
+ if (scope?.eventTypes && scope.eventTypes.length > 0 && !scope.eventTypes.includes(result.eventType))
3299
+ continue;
3300
+ const event = await this.eventStore.getEvent(result.eventId);
3301
+ if (!event)
3302
+ continue;
3303
+ if (scope?.canonicalKeyPrefix && !event.canonicalKey.startsWith(scope.canonicalKeyPrefix))
3304
+ continue;
3305
+ if (normalizedIncludes.length > 0) {
3306
+ const lc = event.content.toLowerCase();
3307
+ if (!normalizedIncludes.some((needle) => lc.includes(needle)))
3308
+ continue;
3309
+ }
3310
+ if (scope?.metadata && !this.matchesMetadataScope(event.metadata, scope.metadata))
3311
+ continue;
3312
+ const projectHash = this.extractProjectHash(event.metadata);
3313
+ filtered.push({ result, projectHash });
3314
+ }
3315
+ if (projectScopeMode === "global" || allowedProjectHashes.size === 0) {
3316
+ return filtered.map((x) => x.result);
3317
+ }
3318
+ const projectMatched = filtered.filter((x) => x.projectHash && allowedProjectHashes.has(x.projectHash));
3319
+ if (projectScopeMode === "strict") {
3320
+ return projectMatched.map((x) => x.result);
3321
+ }
3322
+ return (projectMatched.length > 0 ? projectMatched : filtered).map((x) => x.result);
3323
+ }
3324
+ extractProjectHash(metadata) {
3325
+ if (!metadata || typeof metadata !== "object")
3326
+ return void 0;
3327
+ const scope = metadata.scope;
3328
+ if (!scope || typeof scope !== "object")
3329
+ return void 0;
3330
+ const project = scope.project;
3331
+ if (!project || typeof project !== "object")
3332
+ return void 0;
3333
+ const hash = project.hash;
3334
+ return typeof hash === "string" && hash.length > 0 ? hash : void 0;
2388
3335
  }
2389
- /**
2390
- * Retrieve memories from a specific session
2391
- */
2392
3336
  async retrieveFromSession(sessionId) {
2393
3337
  return this.eventStore.getSessionEvents(sessionId);
2394
3338
  }
2395
- /**
2396
- * Get recent memories across all sessions
2397
- */
2398
3339
  async retrieveRecent(limit = 100) {
2399
3340
  return this.eventStore.getRecentEvents(limit);
2400
3341
  }
2401
- /**
2402
- * Enrich search results with full event data
2403
- */
2404
3342
  async enrichResults(results, options) {
2405
3343
  const memories = [];
2406
3344
  for (const result of results) {
@@ -2408,27 +3346,16 @@ var Retriever = class {
2408
3346
  if (!event)
2409
3347
  continue;
2410
3348
  if (this.graduation) {
2411
- this.graduation.recordAccess(
2412
- event.id,
2413
- options.sessionId || "unknown",
2414
- result.score
2415
- );
3349
+ this.graduation.recordAccess(event.id, options.sessionId || "unknown", result.score);
2416
3350
  }
2417
3351
  let sessionContext;
2418
3352
  if (options.includeSessionContext) {
2419
3353
  sessionContext = await this.getSessionContext(event.sessionId, event.id);
2420
3354
  }
2421
- memories.push({
2422
- event,
2423
- score: result.score,
2424
- sessionContext
2425
- });
3355
+ memories.push({ event, score: result.score, sessionContext });
2426
3356
  }
2427
3357
  return memories;
2428
3358
  }
2429
- /**
2430
- * Get surrounding context from the same session
2431
- */
2432
3359
  async getSessionContext(sessionId, eventId) {
2433
3360
  const sessionEvents = await this.eventStore.getSessionEvents(sessionId);
2434
3361
  const eventIndex = sessionEvents.findIndex((e) => e.id === eventId);
@@ -2441,55 +3368,86 @@ var Retriever = class {
2441
3368
  return void 0;
2442
3369
  return contextEvents.filter((e) => e.id !== eventId).map((e) => `[${e.eventType}]: ${e.content.slice(0, 200)}...`).join("\n");
2443
3370
  }
2444
- /**
2445
- * Build context string from memories (respecting token limit)
2446
- */
3371
+ buildUnifiedContext(projectResult, sharedMemories) {
3372
+ let context = projectResult.context;
3373
+ if (sharedMemories.length === 0)
3374
+ return context;
3375
+ context += "\n\n## Cross-Project Knowledge\n\n";
3376
+ for (const memory of sharedMemories.slice(0, 3)) {
3377
+ context += `### ${memory.title}
3378
+ `;
3379
+ if (memory.symptoms.length > 0)
3380
+ context += `**Symptoms:** ${memory.symptoms.join(", ")}
3381
+ `;
3382
+ context += `**Root Cause:** ${memory.rootCause}
3383
+ `;
3384
+ context += `**Solution:** ${memory.solution}
3385
+ `;
3386
+ if (memory.technologies && memory.technologies.length > 0)
3387
+ context += `**Technologies:** ${memory.technologies.join(", ")}
3388
+ `;
3389
+ context += `_Confidence: ${(memory.confidence * 100).toFixed(0)}%_
3390
+
3391
+ `;
3392
+ }
3393
+ return context;
3394
+ }
2447
3395
  buildContext(memories, maxTokens) {
2448
3396
  const parts = [];
2449
3397
  let currentTokens = 0;
2450
3398
  for (const memory of memories) {
2451
3399
  const memoryText = this.formatMemory(memory);
2452
3400
  const memoryTokens = this.estimateTokens(memoryText);
2453
- if (currentTokens + memoryTokens > maxTokens) {
3401
+ if (currentTokens + memoryTokens > maxTokens)
2454
3402
  break;
2455
- }
2456
3403
  parts.push(memoryText);
2457
3404
  currentTokens += memoryTokens;
2458
3405
  }
2459
- if (parts.length === 0) {
3406
+ if (parts.length === 0)
2460
3407
  return "";
2461
- }
2462
3408
  return `## Relevant Memories
2463
3409
 
2464
3410
  ${parts.join("\n\n---\n\n")}`;
2465
3411
  }
2466
- /**
2467
- * Format a single memory for context
2468
- */
2469
3412
  formatMemory(memory) {
2470
3413
  const { event, score, sessionContext } = memory;
2471
3414
  const date = event.timestamp.toISOString().split("T")[0];
2472
3415
  let text = `**${event.eventType}** (${date}, score: ${score.toFixed(2)})
2473
3416
  ${event.content}`;
2474
- if (sessionContext) {
3417
+ if (sessionContext)
2475
3418
  text += `
2476
3419
 
2477
3420
  _Context:_ ${sessionContext}`;
2478
- }
2479
3421
  return text;
2480
3422
  }
2481
- /**
2482
- * Estimate token count (rough approximation)
2483
- */
3423
+ matchesMetadataScope(metadata, expected) {
3424
+ if (!metadata)
3425
+ return false;
3426
+ return Object.entries(expected).every(([path4, value]) => {
3427
+ const actual = path4.split(".").reduce((acc, key) => {
3428
+ if (typeof acc !== "object" || acc === null)
3429
+ return void 0;
3430
+ return acc[key];
3431
+ }, metadata);
3432
+ return actual === value;
3433
+ });
3434
+ }
3435
+ tokenize(text) {
3436
+ return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((t) => t.length >= 2).slice(0, 64);
3437
+ }
3438
+ keywordOverlap(a, b) {
3439
+ if (a.length === 0 || b.length === 0)
3440
+ return 0;
3441
+ const bs = new Set(b);
3442
+ let hit = 0;
3443
+ for (const t of a)
3444
+ if (bs.has(t))
3445
+ hit += 1;
3446
+ return hit / a.length;
3447
+ }
2484
3448
  estimateTokens(text) {
2485
3449
  return Math.ceil(text.length / 4);
2486
3450
  }
2487
- /**
2488
- * Get event age in days (for recency scoring)
2489
- */
2490
- getEventAgeDays(eventId) {
2491
- return 0;
2492
- }
2493
3451
  };
2494
3452
  function createRetriever(eventStore, vectorStore, embedder, matcher) {
2495
3453
  return new Retriever(eventStore, vectorStore, embedder, matcher);
@@ -3779,6 +4737,59 @@ var ConsolidatedStore = class {
3779
4737
  [memoryId]
3780
4738
  );
3781
4739
  }
4740
+ /**
4741
+ * Create a long-term rule promoted from stable summaries
4742
+ */
4743
+ async createRule(input) {
4744
+ const ruleId = randomUUID6();
4745
+ await dbRun(
4746
+ this.db,
4747
+ `INSERT INTO consolidated_rules
4748
+ (rule_id, rule, topics, source_memory_ids, source_events, confidence, created_at)
4749
+ VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
4750
+ [
4751
+ ruleId,
4752
+ input.rule,
4753
+ JSON.stringify(input.topics),
4754
+ JSON.stringify(input.sourceMemoryIds),
4755
+ JSON.stringify(input.sourceEvents),
4756
+ input.confidence
4757
+ ]
4758
+ );
4759
+ return ruleId;
4760
+ }
4761
+ async getRules(options) {
4762
+ const limit = options?.limit || 100;
4763
+ const rows = await dbAll(
4764
+ this.db,
4765
+ `SELECT * FROM consolidated_rules ORDER BY confidence DESC, created_at DESC LIMIT ?`,
4766
+ [limit]
4767
+ );
4768
+ return rows.map((row) => ({
4769
+ ruleId: row.rule_id,
4770
+ rule: row.rule,
4771
+ topics: JSON.parse(row.topics || "[]"),
4772
+ sourceMemoryIds: JSON.parse(row.source_memory_ids || "[]"),
4773
+ sourceEvents: JSON.parse(row.source_events || "[]"),
4774
+ confidence: Number(row.confidence ?? 0.5),
4775
+ createdAt: toDate(row.created_at) || /* @__PURE__ */ new Date()
4776
+ }));
4777
+ }
4778
+ async countRules() {
4779
+ const result = await dbAll(
4780
+ this.db,
4781
+ `SELECT COUNT(*) as count FROM consolidated_rules`
4782
+ );
4783
+ return result[0]?.count || 0;
4784
+ }
4785
+ async hasRuleForSourceMemory(memoryId) {
4786
+ const rows = await dbAll(
4787
+ this.db,
4788
+ `SELECT COUNT(*) as count FROM consolidated_rules WHERE source_memory_ids LIKE ?`,
4789
+ [`%"${memoryId}"%`]
4790
+ );
4791
+ return (rows[0]?.count || 0) > 0;
4792
+ }
3782
4793
  /**
3783
4794
  * Get count of consolidated memories
3784
4795
  */
@@ -3928,7 +4939,14 @@ var ConsolidationWorker = class {
3928
4939
  * Force a consolidation run (manual trigger)
3929
4940
  */
3930
4941
  async forceRun() {
3931
- return await this.consolidate();
4942
+ const out = await this.consolidateWithReport();
4943
+ return out.consolidatedCount;
4944
+ }
4945
+ /**
4946
+ * Force a consolidation run and return metrics report
4947
+ */
4948
+ async forceRunWithReport() {
4949
+ return this.consolidateWithReport();
3932
4950
  }
3933
4951
  /**
3934
4952
  * Schedule the next consolidation check
@@ -3968,12 +4986,21 @@ var ConsolidationWorker = class {
3968
4986
  * Perform consolidation
3969
4987
  */
3970
4988
  async consolidate() {
4989
+ const out = await this.consolidateWithReport();
4990
+ return out.consolidatedCount;
4991
+ }
4992
+ async consolidateWithReport() {
3971
4993
  const workingSet = await this.workingSetStore.get();
3972
4994
  if (workingSet.recentEvents.length < 3) {
3973
- return 0;
4995
+ return {
4996
+ consolidatedCount: 0,
4997
+ promotedRuleCount: 0,
4998
+ report: this.buildCostQualityReport(workingSet.recentEvents, [], 0)
4999
+ };
3974
5000
  }
3975
5001
  const groups = this.groupByTopic(workingSet.recentEvents);
3976
5002
  let consolidatedCount = 0;
5003
+ const createdMemoryIds = [];
3977
5004
  for (const group of groups) {
3978
5005
  if (group.events.length < 3)
3979
5006
  continue;
@@ -3982,14 +5009,16 @@ var ConsolidationWorker = class {
3982
5009
  if (alreadyConsolidated)
3983
5010
  continue;
3984
5011
  const summary = await this.summarize(group);
3985
- await this.consolidatedStore.create({
5012
+ const memoryId = await this.consolidatedStore.create({
3986
5013
  summary,
3987
5014
  topics: group.topics,
3988
5015
  sourceEvents: eventIds,
3989
5016
  confidence: this.calculateConfidence(group)
3990
5017
  });
5018
+ createdMemoryIds.push(memoryId);
3991
5019
  consolidatedCount++;
3992
5020
  }
5021
+ const promotedRuleCount = await this.promoteStableSummariesToRules(createdMemoryIds);
3993
5022
  if (consolidatedCount > 0) {
3994
5023
  const consolidatedEventIds = groups.filter((g) => g.events.length >= 3).flatMap((g) => g.events.map((e) => e.id));
3995
5024
  const oldEventIds = consolidatedEventIds.filter((id) => {
@@ -4003,7 +5032,61 @@ var ConsolidationWorker = class {
4003
5032
  await this.workingSetStore.prune(oldEventIds);
4004
5033
  }
4005
5034
  }
4006
- return consolidatedCount;
5035
+ const report = this.buildCostQualityReport(workingSet.recentEvents, groups, consolidatedCount);
5036
+ return { consolidatedCount, promotedRuleCount, report };
5037
+ }
5038
+ async promoteStableSummariesToRules(memoryIds) {
5039
+ let promoted = 0;
5040
+ for (const memoryId of memoryIds) {
5041
+ const memory = await this.consolidatedStore.get(memoryId);
5042
+ if (!memory)
5043
+ continue;
5044
+ if (memory.confidence < 0.55)
5045
+ continue;
5046
+ if (memory.sourceEvents.length < 4)
5047
+ continue;
5048
+ const exists = await this.consolidatedStore.hasRuleForSourceMemory(memoryId);
5049
+ if (exists)
5050
+ continue;
5051
+ const rule = this.buildRuleFromSummary(memory.summary, memory.topics);
5052
+ if (!rule)
5053
+ continue;
5054
+ await this.consolidatedStore.createRule({
5055
+ rule,
5056
+ topics: memory.topics,
5057
+ sourceMemoryIds: [memory.memoryId],
5058
+ sourceEvents: memory.sourceEvents,
5059
+ confidence: Math.min(1, memory.confidence + 0.08)
5060
+ });
5061
+ promoted++;
5062
+ }
5063
+ return promoted;
5064
+ }
5065
+ buildRuleFromSummary(summary, topics) {
5066
+ const lines = summary.split(/\r?\n/).map((l) => l.trim()).filter(Boolean).filter((l) => !l.toLowerCase().startsWith("topics:"));
5067
+ const bullet = lines.find((l) => l.startsWith("- "))?.replace(/^-\s*/, "");
5068
+ const seed = bullet || lines[0];
5069
+ if (!seed || seed.length < 8)
5070
+ return null;
5071
+ const topicPrefix = topics.length > 0 ? `[${topics.slice(0, 2).join(", ")}] ` : "";
5072
+ return `${topicPrefix}${seed}`;
5073
+ }
5074
+ buildCostQualityReport(events, groups, consolidatedCount) {
5075
+ const beforeTokenEstimate = events.reduce((acc, e) => acc + this.estimateTokens(e.content), 0);
5076
+ const afterSummaries = groups.filter((g) => g.events.length >= 3).slice(0, Math.max(consolidatedCount, 1));
5077
+ const afterTokenEstimate = afterSummaries.length > 0 ? afterSummaries.reduce((acc, g) => acc + this.estimateTokens(this.ruleBasedSummary(g)), 0) : beforeTokenEstimate;
5078
+ const reductionRatio = beforeTokenEstimate > 0 ? Math.max(0, (beforeTokenEstimate - afterTokenEstimate) / beforeTokenEstimate) : 0;
5079
+ const qualityGuardPassed = consolidatedCount === 0 ? true : groups.filter((g) => g.events.length >= 3).every((g) => this.calculateConfidence(g) >= 0.55);
5080
+ return {
5081
+ beforeTokenEstimate,
5082
+ afterTokenEstimate,
5083
+ reductionRatio,
5084
+ qualityGuardPassed,
5085
+ details: `groups=${groups.length}, consolidated=${consolidatedCount}`
5086
+ };
5087
+ }
5088
+ estimateTokens(text) {
5089
+ return Math.ceil((text || "").length / 4);
4007
5090
  }
4008
5091
  /**
4009
5092
  * Check if consolidation should run
@@ -4563,13 +5646,185 @@ function createGraduationWorker(eventStore, graduation, config) {
4563
5646
  );
4564
5647
  }
4565
5648
 
5649
+ // src/core/md-mirror.ts
5650
+ import * as fs3 from "node:fs";
5651
+ import * as path2 from "node:path";
5652
+ function sanitizeSegment2(input, fallback) {
5653
+ const v = (input || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
5654
+ return v || fallback;
5655
+ }
5656
+ function getAtPath(obj, dotted) {
5657
+ if (!obj)
5658
+ return void 0;
5659
+ return dotted.split(".").reduce((acc, key) => {
5660
+ if (!acc || typeof acc !== "object")
5661
+ return void 0;
5662
+ return acc[key];
5663
+ }, obj);
5664
+ }
5665
+ function buildMirrorPath2(rootDir, event) {
5666
+ const meta = event.metadata;
5667
+ const namespaceRaw = getAtPath(meta, "namespace") ?? getAtPath(meta, "scope.namespace") ?? event.eventType;
5668
+ const namespace = sanitizeSegment2(typeof namespaceRaw === "string" ? namespaceRaw : void 0, "general");
5669
+ const categoryRaw = getAtPath(meta, "categoryPath") ?? getAtPath(meta, "scope.categoryPath");
5670
+ const categoryPath = Array.isArray(categoryRaw) && categoryRaw.length > 0 ? categoryRaw.map((x) => sanitizeSegment2(typeof x === "string" ? x : void 0, "uncategorized")) : ["uncategorized"];
5671
+ const d = event.timestamp;
5672
+ const yyyy = d.getFullYear();
5673
+ const mm = String(d.getMonth() + 1).padStart(2, "0");
5674
+ const dd = String(d.getDate()).padStart(2, "0");
5675
+ return path2.join(rootDir, "memory", namespace, ...categoryPath, `${yyyy}-${mm}-${dd}.md`);
5676
+ }
5677
+ var MarkdownMirror2 = class {
5678
+ constructor(rootDir) {
5679
+ this.rootDir = rootDir;
5680
+ }
5681
+ async append(event, eventId) {
5682
+ const out = buildMirrorPath2(this.rootDir, event);
5683
+ fs3.mkdirSync(path2.dirname(out), { recursive: true });
5684
+ const lines = [
5685
+ "",
5686
+ `## ${event.timestamp.toISOString()} | ${eventId ?? "pending-id"}`,
5687
+ `- type: ${event.eventType}`,
5688
+ `- session: ${event.sessionId}`,
5689
+ event.content
5690
+ ];
5691
+ await fs3.promises.appendFile(out, lines.join("\n"), "utf8");
5692
+ await this.refreshIndex();
5693
+ }
5694
+ async refreshIndex() {
5695
+ const memoryRoot = path2.join(this.rootDir, "memory");
5696
+ await fs3.promises.mkdir(memoryRoot, { recursive: true });
5697
+ const files = [];
5698
+ await this.walk(memoryRoot, files);
5699
+ const mdFiles = files.filter((f) => f.endsWith(".md")).map((f) => path2.relative(this.rootDir, f)).filter((rel) => rel !== path2.join("memory", "_index.md")).sort();
5700
+ const index = [
5701
+ "# Memory Index",
5702
+ "",
5703
+ "Generated automatically by MarkdownMirror.",
5704
+ "",
5705
+ ...mdFiles.map((rel) => `- ${rel}`),
5706
+ ""
5707
+ ].join("\n");
5708
+ await fs3.promises.writeFile(path2.join(memoryRoot, "_index.md"), index, "utf8");
5709
+ }
5710
+ async walk(dir, out) {
5711
+ const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
5712
+ for (const e of entries) {
5713
+ const full = path2.join(dir, e.name);
5714
+ if (e.isDirectory()) {
5715
+ await this.walk(full, out);
5716
+ } else {
5717
+ out.push(full);
5718
+ }
5719
+ }
5720
+ }
5721
+ };
5722
+
5723
+ // src/core/ingest-interceptor.ts
5724
+ var IngestInterceptorRegistry = class {
5725
+ before = [];
5726
+ after = [];
5727
+ onError = [];
5728
+ registerBefore(interceptor) {
5729
+ this.before.push(interceptor);
5730
+ return () => {
5731
+ this.before = this.before.filter((i) => i !== interceptor);
5732
+ };
5733
+ }
5734
+ registerAfter(interceptor) {
5735
+ this.after.push(interceptor);
5736
+ return () => {
5737
+ this.after = this.after.filter((i) => i !== interceptor);
5738
+ };
5739
+ }
5740
+ registerOnError(interceptor) {
5741
+ this.onError.push(interceptor);
5742
+ return () => {
5743
+ this.onError = this.onError.filter((i) => i !== interceptor);
5744
+ };
5745
+ }
5746
+ async run(stage, context) {
5747
+ const interceptors = stage === "before" ? this.before : stage === "after" ? this.after : this.onError;
5748
+ for (const interceptor of interceptors) {
5749
+ await interceptor({ ...context, stage });
5750
+ }
5751
+ }
5752
+ };
5753
+ function mergeHierarchicalMetadata(base, patch) {
5754
+ if (!base && !patch)
5755
+ return void 0;
5756
+ if (!base)
5757
+ return patch;
5758
+ if (!patch)
5759
+ return base;
5760
+ const result = { ...base };
5761
+ for (const [key, value] of Object.entries(patch)) {
5762
+ const current = result[key];
5763
+ if (typeof current === "object" && current !== null && !Array.isArray(current) && typeof value === "object" && value !== null && !Array.isArray(value)) {
5764
+ result[key] = mergeHierarchicalMetadata(
5765
+ current,
5766
+ value
5767
+ );
5768
+ } else {
5769
+ result[key] = value;
5770
+ }
5771
+ }
5772
+ return result;
5773
+ }
5774
+
5775
+ // src/core/tag-taxonomy.ts
5776
+ var TAG_NAMESPACES = {
5777
+ SYSTEM: "sys:",
5778
+ QUALITY: "q:",
5779
+ PROJECT: "proj:",
5780
+ TOPIC: "topic:",
5781
+ TEMPORAL: "t:",
5782
+ USER: "user:",
5783
+ AGENT: "agent:"
5784
+ };
5785
+ var VALID_TAG_NAMESPACES = new Set(Object.values(TAG_NAMESPACES));
5786
+ function parseTag(tag) {
5787
+ const value = (tag || "").trim();
5788
+ const idx = value.indexOf(":");
5789
+ if (idx <= 0)
5790
+ return { value };
5791
+ const namespace = `${value.slice(0, idx)}:`;
5792
+ const tagValue = value.slice(idx + 1);
5793
+ if (!tagValue)
5794
+ return { value };
5795
+ return { namespace, value: tagValue };
5796
+ }
5797
+ function validateTag(tag) {
5798
+ const normalized = (tag || "").trim();
5799
+ if (!normalized)
5800
+ return false;
5801
+ const { namespace } = parseTag(normalized);
5802
+ if (!namespace)
5803
+ return true;
5804
+ return VALID_TAG_NAMESPACES.has(namespace);
5805
+ }
5806
+ function normalizeTags(tags) {
5807
+ if (!Array.isArray(tags))
5808
+ return [];
5809
+ const dedup = /* @__PURE__ */ new Set();
5810
+ for (const item of tags) {
5811
+ if (typeof item !== "string")
5812
+ continue;
5813
+ const normalized = item.trim();
5814
+ if (!validateTag(normalized))
5815
+ continue;
5816
+ dedup.add(normalized);
5817
+ }
5818
+ return [...dedup];
5819
+ }
5820
+
4566
5821
  // src/services/memory-service.ts
4567
5822
  function normalizePath(projectPath) {
4568
- const expanded = projectPath.startsWith("~") ? path.join(os.homedir(), projectPath.slice(1)) : projectPath;
5823
+ const expanded = projectPath.startsWith("~") ? path3.join(os.homedir(), projectPath.slice(1)) : projectPath;
4569
5824
  try {
4570
- return fs.realpathSync(expanded);
5825
+ return fs4.realpathSync(expanded);
4571
5826
  } catch {
4572
- return path.resolve(expanded);
5827
+ return path3.resolve(expanded);
4573
5828
  }
4574
5829
  }
4575
5830
  function hashProjectPath(projectPath) {
@@ -4578,14 +5833,14 @@ function hashProjectPath(projectPath) {
4578
5833
  }
4579
5834
  function getProjectStoragePath(projectPath) {
4580
5835
  const hash = hashProjectPath(projectPath);
4581
- return path.join(os.homedir(), ".claude-code", "memory", "projects", hash);
5836
+ return path3.join(os.homedir(), ".claude-code", "memory", "projects", hash);
4582
5837
  }
4583
- var REGISTRY_PATH = path.join(os.homedir(), ".claude-code", "memory", "session-registry.json");
4584
- var SHARED_STORAGE_PATH = path.join(os.homedir(), ".claude-code", "memory", "shared");
5838
+ var REGISTRY_PATH = path3.join(os.homedir(), ".claude-code", "memory", "session-registry.json");
5839
+ var SHARED_STORAGE_PATH = path3.join(os.homedir(), ".claude-code", "memory", "shared");
4585
5840
  function loadSessionRegistry() {
4586
5841
  try {
4587
- if (fs.existsSync(REGISTRY_PATH)) {
4588
- const data = fs.readFileSync(REGISTRY_PATH, "utf-8");
5842
+ if (fs4.existsSync(REGISTRY_PATH)) {
5843
+ const data = fs4.readFileSync(REGISTRY_PATH, "utf-8");
4589
5844
  return JSON.parse(data);
4590
5845
  }
4591
5846
  } catch (error) {
@@ -4594,13 +5849,13 @@ function loadSessionRegistry() {
4594
5849
  return { version: 1, sessions: {} };
4595
5850
  }
4596
5851
  function saveSessionRegistry(registry) {
4597
- const dir = path.dirname(REGISTRY_PATH);
4598
- if (!fs.existsSync(dir)) {
4599
- fs.mkdirSync(dir, { recursive: true });
5852
+ const dir = path3.dirname(REGISTRY_PATH);
5853
+ if (!fs4.existsSync(dir)) {
5854
+ fs4.mkdirSync(dir, { recursive: true });
4600
5855
  }
4601
5856
  const tempPath = REGISTRY_PATH + ".tmp";
4602
- fs.writeFileSync(tempPath, JSON.stringify(registry, null, 2));
4603
- fs.renameSync(tempPath, REGISTRY_PATH);
5857
+ fs4.writeFileSync(tempPath, JSON.stringify(registry, null, 2));
5858
+ fs4.renameSync(tempPath, REGISTRY_PATH);
4604
5859
  }
4605
5860
  function registerSession(sessionId, projectPath) {
4606
5861
  const registry = loadSessionRegistry();
@@ -4632,6 +5887,7 @@ var MemoryService = class {
4632
5887
  vectorWorker = null;
4633
5888
  graduationWorker = null;
4634
5889
  initialized = false;
5890
+ ingestInterceptors = new IngestInterceptorRegistry();
4635
5891
  // Endless Mode components
4636
5892
  workingSetStore = null;
4637
5893
  consolidatedStore = null;
@@ -4645,20 +5901,27 @@ var MemoryService = class {
4645
5901
  sharedPromoter = null;
4646
5902
  sharedStoreConfig = null;
4647
5903
  projectHash = null;
5904
+ projectPath = null;
4648
5905
  readOnly;
4649
5906
  lightweightMode;
5907
+ mdMirror;
4650
5908
  constructor(config) {
4651
5909
  const storagePath = this.expandPath(config.storagePath);
4652
5910
  this.readOnly = config.readOnly ?? false;
4653
5911
  this.lightweightMode = config.lightweightMode ?? false;
4654
- if (!this.readOnly && !fs.existsSync(storagePath)) {
4655
- fs.mkdirSync(storagePath, { recursive: true });
5912
+ this.mdMirror = new MarkdownMirror2(process.cwd());
5913
+ if (!this.readOnly && !fs4.existsSync(storagePath)) {
5914
+ fs4.mkdirSync(storagePath, { recursive: true });
4656
5915
  }
4657
5916
  this.projectHash = config.projectHash || null;
5917
+ this.projectPath = config.projectPath || null;
4658
5918
  this.sharedStoreConfig = config.sharedStoreConfig ?? { enabled: true };
4659
5919
  this.sqliteStore = new SQLiteEventStore(
4660
- path.join(storagePath, "events.sqlite"),
4661
- { readonly: this.readOnly }
5920
+ path3.join(storagePath, "events.sqlite"),
5921
+ {
5922
+ readonly: this.readOnly,
5923
+ markdownMirrorRoot: storagePath
5924
+ }
4662
5925
  );
4663
5926
  const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
4664
5927
  if (!analyticsEnabled) {
@@ -4666,7 +5929,7 @@ var MemoryService = class {
4666
5929
  } else if (this.readOnly) {
4667
5930
  try {
4668
5931
  this.analyticsStore = new EventStore(
4669
- path.join(storagePath, "analytics.duckdb"),
5932
+ path3.join(storagePath, "analytics.duckdb"),
4670
5933
  { readOnly: true }
4671
5934
  );
4672
5935
  } catch {
@@ -4674,11 +5937,11 @@ var MemoryService = class {
4674
5937
  }
4675
5938
  } else {
4676
5939
  this.analyticsStore = new EventStore(
4677
- path.join(storagePath, "analytics.duckdb"),
5940
+ path3.join(storagePath, "analytics.duckdb"),
4678
5941
  { readOnly: false }
4679
5942
  );
4680
5943
  }
4681
- this.vectorStore = new VectorStore(path.join(storagePath, "vectors"));
5944
+ this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
4682
5945
  this.embedder = config.embeddingModel ? new Embedder(config.embeddingModel) : getDefaultEmbedder();
4683
5946
  this.matcher = getDefaultMatcher();
4684
5947
  this.retriever = createRetriever(
@@ -4688,6 +5951,7 @@ var MemoryService = class {
4688
5951
  this.embedder,
4689
5952
  this.matcher
4690
5953
  );
5954
+ this.retriever.setQueryRewriter((q) => this.rewriteQueryIntent(q));
4691
5955
  this.graduation = createGraduationPipeline(this.sqliteStore);
4692
5956
  }
4693
5957
  /**
@@ -4747,16 +6011,16 @@ var MemoryService = class {
4747
6011
  */
4748
6012
  async initializeSharedStore() {
4749
6013
  const sharedPath = this.sharedStoreConfig?.sharedStoragePath ? this.expandPath(this.sharedStoreConfig.sharedStoragePath) : SHARED_STORAGE_PATH;
4750
- if (!fs.existsSync(sharedPath)) {
4751
- fs.mkdirSync(sharedPath, { recursive: true });
6014
+ if (!fs4.existsSync(sharedPath)) {
6015
+ fs4.mkdirSync(sharedPath, { recursive: true });
4752
6016
  }
4753
6017
  this.sharedEventStore = createSharedEventStore(
4754
- path.join(sharedPath, "shared.duckdb")
6018
+ path3.join(sharedPath, "shared.duckdb")
4755
6019
  );
4756
6020
  await this.sharedEventStore.initialize();
4757
6021
  this.sharedStore = createSharedStore(this.sharedEventStore);
4758
6022
  this.sharedVectorStore = createSharedVectorStore(
4759
- path.join(sharedPath, "vectors")
6023
+ path3.join(sharedPath, "vectors")
4760
6024
  );
4761
6025
  await this.sharedVectorStore.initialize();
4762
6026
  this.sharedPromoter = createSharedPromoter(
@@ -4767,6 +6031,86 @@ var MemoryService = class {
4767
6031
  );
4768
6032
  this.retriever.setSharedStores(this.sharedStore, this.sharedVectorStore);
4769
6033
  }
6034
+ registerIngestBefore(interceptor) {
6035
+ return this.ingestInterceptors.registerBefore(interceptor);
6036
+ }
6037
+ registerIngestAfter(interceptor) {
6038
+ return this.ingestInterceptors.registerAfter(interceptor);
6039
+ }
6040
+ registerIngestOnError(interceptor) {
6041
+ return this.ingestInterceptors.registerOnError(interceptor);
6042
+ }
6043
+ async ingestWithInterceptors(operation, input, onSuccess) {
6044
+ const normalizedInput = {
6045
+ ...input,
6046
+ metadata: mergeHierarchicalMetadata(
6047
+ {
6048
+ ingest: {
6049
+ operation,
6050
+ pipeline: "default",
6051
+ ts: (/* @__PURE__ */ new Date()).toISOString()
6052
+ },
6053
+ ...this.projectHash ? {
6054
+ scope: {
6055
+ project: {
6056
+ hash: this.projectHash,
6057
+ ...this.projectPath ? { path: this.projectPath } : {}
6058
+ }
6059
+ },
6060
+ tags: [`proj:${this.projectHash}`]
6061
+ } : {}
6062
+ },
6063
+ input.metadata
6064
+ )
6065
+ };
6066
+ if (this.projectHash && normalizedInput.metadata) {
6067
+ const meta = normalizedInput.metadata;
6068
+ const currentTags = Array.isArray(meta.tags) ? meta.tags.filter((x) => typeof x === "string") : [];
6069
+ const projectTag = `proj:${this.projectHash}`;
6070
+ if (!currentTags.includes(projectTag)) {
6071
+ meta.tags = [...currentTags, projectTag];
6072
+ }
6073
+ }
6074
+ if (normalizedInput.metadata) {
6075
+ const meta = normalizedInput.metadata;
6076
+ const normalizedTags = normalizeTags(meta.tags);
6077
+ if (normalizedTags.length > 0) {
6078
+ meta.tags = normalizedTags;
6079
+ }
6080
+ }
6081
+ await this.ingestInterceptors.run("before", {
6082
+ operation,
6083
+ sessionId: normalizedInput.sessionId,
6084
+ event: normalizedInput
6085
+ });
6086
+ try {
6087
+ const result = await this.sqliteStore.append(normalizedInput);
6088
+ if (result.success && !result.isDuplicate) {
6089
+ if (onSuccess) {
6090
+ await onSuccess(result.eventId);
6091
+ }
6092
+ try {
6093
+ await this.mdMirror.append(normalizedInput, result.eventId);
6094
+ } catch {
6095
+ }
6096
+ }
6097
+ await this.ingestInterceptors.run("after", {
6098
+ operation,
6099
+ sessionId: normalizedInput.sessionId,
6100
+ event: normalizedInput
6101
+ });
6102
+ return result;
6103
+ } catch (error) {
6104
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
6105
+ await this.ingestInterceptors.run("error", {
6106
+ operation,
6107
+ sessionId: normalizedInput.sessionId,
6108
+ event: normalizedInput,
6109
+ error: normalizedError
6110
+ });
6111
+ throw error;
6112
+ }
6113
+ }
4770
6114
  /**
4771
6115
  * Start a new session
4772
6116
  */
@@ -4794,50 +6138,57 @@ var MemoryService = class {
4794
6138
  */
4795
6139
  async storeUserPrompt(sessionId, content, metadata) {
4796
6140
  await this.initialize();
4797
- const result = await this.sqliteStore.append({
4798
- eventType: "user_prompt",
4799
- sessionId,
4800
- timestamp: /* @__PURE__ */ new Date(),
4801
- content,
4802
- metadata
4803
- });
4804
- if (result.success && !result.isDuplicate) {
4805
- await this.sqliteStore.enqueueForEmbedding(result.eventId, content);
4806
- }
4807
- return result;
6141
+ return this.ingestWithInterceptors(
6142
+ "user_prompt",
6143
+ {
6144
+ eventType: "user_prompt",
6145
+ sessionId,
6146
+ timestamp: /* @__PURE__ */ new Date(),
6147
+ content,
6148
+ metadata
6149
+ },
6150
+ async (eventId) => {
6151
+ await this.sqliteStore.enqueueForEmbedding(eventId, content);
6152
+ }
6153
+ );
4808
6154
  }
4809
6155
  /**
4810
6156
  * Store an agent response
4811
6157
  */
4812
6158
  async storeAgentResponse(sessionId, content, metadata) {
4813
6159
  await this.initialize();
4814
- const result = await this.sqliteStore.append({
4815
- eventType: "agent_response",
4816
- sessionId,
4817
- timestamp: /* @__PURE__ */ new Date(),
4818
- content,
4819
- metadata
4820
- });
4821
- if (result.success && !result.isDuplicate) {
4822
- await this.sqliteStore.enqueueForEmbedding(result.eventId, content);
4823
- }
4824
- return result;
6160
+ return this.ingestWithInterceptors(
6161
+ "agent_response",
6162
+ {
6163
+ eventType: "agent_response",
6164
+ sessionId,
6165
+ timestamp: /* @__PURE__ */ new Date(),
6166
+ content,
6167
+ metadata
6168
+ },
6169
+ async (eventId) => {
6170
+ await this.sqliteStore.enqueueForEmbedding(eventId, content);
6171
+ }
6172
+ );
4825
6173
  }
4826
6174
  /**
4827
6175
  * Store a session summary
4828
6176
  */
4829
- async storeSessionSummary(sessionId, summary) {
6177
+ async storeSessionSummary(sessionId, summary, metadata) {
4830
6178
  await this.initialize();
4831
- const result = await this.sqliteStore.append({
4832
- eventType: "session_summary",
4833
- sessionId,
4834
- timestamp: /* @__PURE__ */ new Date(),
4835
- content: summary
4836
- });
4837
- if (result.success && !result.isDuplicate) {
4838
- await this.sqliteStore.enqueueForEmbedding(result.eventId, summary);
4839
- }
4840
- return result;
6179
+ return this.ingestWithInterceptors(
6180
+ "session_summary",
6181
+ {
6182
+ eventType: "session_summary",
6183
+ sessionId,
6184
+ timestamp: /* @__PURE__ */ new Date(),
6185
+ content: summary,
6186
+ metadata
6187
+ },
6188
+ async (eventId) => {
6189
+ await this.sqliteStore.enqueueForEmbedding(eventId, summary);
6190
+ }
6191
+ );
4841
6192
  }
4842
6193
  /**
4843
6194
  * Store a tool observation
@@ -4845,39 +6196,182 @@ var MemoryService = class {
4845
6196
  async storeToolObservation(sessionId, payload) {
4846
6197
  await this.initialize();
4847
6198
  const content = JSON.stringify(payload);
4848
- const result = await this.sqliteStore.append({
4849
- eventType: "tool_observation",
4850
- sessionId,
4851
- timestamp: /* @__PURE__ */ new Date(),
4852
- content,
4853
- metadata: {
4854
- toolName: payload.toolName,
4855
- success: payload.success
6199
+ const turnId = payload.metadata?.turnId;
6200
+ return this.ingestWithInterceptors(
6201
+ "tool_observation",
6202
+ {
6203
+ eventType: "tool_observation",
6204
+ sessionId,
6205
+ timestamp: /* @__PURE__ */ new Date(),
6206
+ content,
6207
+ metadata: {
6208
+ toolName: payload.toolName,
6209
+ success: payload.success,
6210
+ ...turnId ? { turnId } : {}
6211
+ }
6212
+ },
6213
+ async (eventId) => {
6214
+ const embeddingContent = createToolObservationEmbedding(
6215
+ payload.toolName,
6216
+ payload.metadata || {},
6217
+ payload.success
6218
+ );
6219
+ await this.sqliteStore.enqueueForEmbedding(eventId, embeddingContent);
4856
6220
  }
4857
- });
4858
- if (result.success && !result.isDuplicate) {
4859
- const embeddingContent = createToolObservationEmbedding(
4860
- payload.toolName,
4861
- payload.metadata || {},
4862
- payload.success
4863
- );
4864
- await this.sqliteStore.enqueueForEmbedding(result.eventId, embeddingContent);
4865
- }
4866
- return result;
6221
+ );
4867
6222
  }
4868
6223
  /**
4869
6224
  * Retrieve relevant memories for a query
4870
6225
  */
4871
6226
  async retrieveMemories(query, options) {
4872
6227
  await this.initialize();
6228
+ const rerankWeights = await this.getRerankWeights(options?.adaptiveRerank === true);
6229
+ let result;
4873
6230
  if (options?.includeShared && this.sharedStore) {
4874
- return this.retriever.retrieveUnified(query, {
6231
+ result = await this.retriever.retrieveUnified(query, {
4875
6232
  ...options,
6233
+ intentRewrite: options?.intentRewrite === true,
6234
+ rerankWeights,
4876
6235
  includeShared: true,
4877
- projectHash: this.projectHash || void 0
6236
+ projectHash: this.projectHash || void 0,
6237
+ projectScopeMode: options?.projectScopeMode ?? (this.projectHash ? "strict" : "global"),
6238
+ allowedProjectHashes: options?.allowedProjectHashes
6239
+ });
6240
+ } else {
6241
+ result = await this.retriever.retrieve(query, {
6242
+ ...options,
6243
+ intentRewrite: options?.intentRewrite === true,
6244
+ rerankWeights,
6245
+ projectHash: this.projectHash || void 0,
6246
+ projectScopeMode: options?.projectScopeMode ?? (this.projectHash ? "strict" : "global"),
6247
+ allowedProjectHashes: options?.allowedProjectHashes
6248
+ });
6249
+ }
6250
+ try {
6251
+ const selectedEventIds = result.memories.map((m) => m.event.id);
6252
+ const selectedDetails = (result.selectedDebug || []).map((d) => ({
6253
+ eventId: d.eventId,
6254
+ score: d.score,
6255
+ semanticScore: d.semanticScore,
6256
+ lexicalScore: d.lexicalScore,
6257
+ recencyScore: d.recencyScore
6258
+ }));
6259
+ const candidateDetails = (result.candidateDebug || []).map((d) => ({
6260
+ eventId: d.eventId,
6261
+ score: d.score,
6262
+ semanticScore: d.semanticScore,
6263
+ lexicalScore: d.lexicalScore,
6264
+ recencyScore: d.recencyScore
6265
+ }));
6266
+ const candidateEventIds = candidateDetails.length > 0 ? candidateDetails.map((d) => d.eventId) : selectedEventIds;
6267
+ await this.sqliteStore.recordRetrievalTrace({
6268
+ sessionId: options?.sessionId,
6269
+ projectHash: this.projectHash || void 0,
6270
+ queryText: query,
6271
+ strategy: options?.strategy || "auto",
6272
+ candidateEventIds,
6273
+ selectedEventIds,
6274
+ candidateDetails,
6275
+ selectedDetails,
6276
+ confidence: result.matchResult.confidence,
6277
+ fallbackTrace: result.fallbackTrace || []
6278
+ });
6279
+ } catch {
6280
+ }
6281
+ return result;
6282
+ }
6283
+ getConfiguredRerankWeights() {
6284
+ const semantic = Number(process.env.MEMORY_RERANK_WEIGHT_SEMANTIC ?? "");
6285
+ const lexical = Number(process.env.MEMORY_RERANK_WEIGHT_LEXICAL ?? "");
6286
+ const recency = Number(process.env.MEMORY_RERANK_WEIGHT_RECENCY ?? "");
6287
+ const allFinite = [semantic, lexical, recency].every((v) => Number.isFinite(v));
6288
+ if (!allFinite)
6289
+ return void 0;
6290
+ const nonNegative = [semantic, lexical, recency].every((v) => v >= 0);
6291
+ const total = semantic + lexical + recency;
6292
+ if (!nonNegative || total <= 0)
6293
+ return void 0;
6294
+ return {
6295
+ semantic: semantic / total,
6296
+ lexical: lexical / total,
6297
+ recency: recency / total
6298
+ };
6299
+ }
6300
+ async getRerankWeights(adaptive) {
6301
+ const configured = this.getConfiguredRerankWeights();
6302
+ if (configured)
6303
+ return configured;
6304
+ if (adaptive)
6305
+ return this.getAdaptiveRerankWeights();
6306
+ return void 0;
6307
+ }
6308
+ async rewriteQueryIntent(query) {
6309
+ if (process.env.MEMORY_INTENT_REWRITE_ENABLED !== "1")
6310
+ return null;
6311
+ const apiUrl = process.env.COMPANY_STOCK_API_URL || process.env.COMPANY_INT_API_URL;
6312
+ if (!apiUrl)
6313
+ return null;
6314
+ const controller = new AbortController();
6315
+ const timeoutMs = Number(process.env.MEMORY_INTENT_REWRITE_TIMEOUT_MS || 5e3);
6316
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
6317
+ try {
6318
+ const prompt = [
6319
+ "Rewrite user query for memory retrieval intent expansion.",
6320
+ "Return plain text only, one line, no markdown.",
6321
+ `Query: ${query}`
6322
+ ].join("\n");
6323
+ const res = await fetch(apiUrl, {
6324
+ method: "POST",
6325
+ headers: {
6326
+ "Content-Type": "application/json",
6327
+ Accept: "*/*",
6328
+ Origin: process.env.COMPANY_INT_ORIGIN || "http://company-int.aplusai.ai",
6329
+ Referer: process.env.COMPANY_INT_REFERER || "http://company-int.aplusai.ai/"
6330
+ },
6331
+ body: JSON.stringify({
6332
+ question: prompt,
6333
+ company_name: null,
6334
+ conversation_id: null
6335
+ }),
6336
+ signal: controller.signal
4878
6337
  });
6338
+ const text = (await res.text()).trim();
6339
+ if (!text)
6340
+ return null;
6341
+ const oneLine = text.replace(/^data:\s*/gm, "").split(/\r?\n/).map((x) => x.trim()).filter(Boolean).join(" ").slice(0, 240);
6342
+ if (!oneLine || oneLine.toLowerCase() === query.toLowerCase())
6343
+ return null;
6344
+ return oneLine;
6345
+ } catch {
6346
+ return null;
6347
+ } finally {
6348
+ clearTimeout(timeout);
6349
+ }
6350
+ }
6351
+ async getAdaptiveRerankWeights() {
6352
+ try {
6353
+ const s = await this.sqliteStore.getHelpfulnessStats();
6354
+ if (s.totalEvaluated < 20)
6355
+ return void 0;
6356
+ let semantic = 0.7;
6357
+ let lexical = 0.2;
6358
+ let recency = 0.1;
6359
+ if (s.avgScore < 0.45) {
6360
+ semantic -= 0.1;
6361
+ lexical += 0.1;
6362
+ } else if (s.avgScore > 0.75) {
6363
+ semantic += 0.05;
6364
+ lexical -= 0.05;
6365
+ }
6366
+ if (s.unhelpful > s.helpful) {
6367
+ recency += 0.05;
6368
+ semantic -= 0.03;
6369
+ lexical -= 0.02;
6370
+ }
6371
+ return { semantic, lexical, recency };
6372
+ } catch {
6373
+ return void 0;
4879
6374
  }
4880
- return this.retriever.retrieve(query, options);
4881
6375
  }
4882
6376
  /**
4883
6377
  * Fast keyword search using SQLite FTS5
@@ -4919,6 +6413,18 @@ var MemoryService = class {
4919
6413
  /**
4920
6414
  * Get memory statistics
4921
6415
  */
6416
+ async getOutboxStats() {
6417
+ await this.initialize();
6418
+ return this.sqliteStore.getOutboxStats();
6419
+ }
6420
+ async getRetrievalTraceStats() {
6421
+ await this.initialize();
6422
+ return this.sqliteStore.getRetrievalTraceStats();
6423
+ }
6424
+ async getRecentRetrievalTraces(limit = 50) {
6425
+ await this.initialize();
6426
+ return this.sqliteStore.getRecentRetrievalTraces(limit);
6427
+ }
4922
6428
  async getStats() {
4923
6429
  await this.initialize();
4924
6430
  const recentEvents = await this.sqliteStore.getRecentEvents(1e4);
@@ -5135,6 +6641,31 @@ var MemoryService = class {
5135
6641
  return [];
5136
6642
  return this.consolidatedStore.getAll({ limit });
5137
6643
  }
6644
+ /**
6645
+ * Extract topic keywords from event content (markdown headings and key terms)
6646
+ */
6647
+ extractTopicsFromContent(content) {
6648
+ const topics = /* @__PURE__ */ new Set();
6649
+ const headings = content.match(/^#{1,3}\s+(.+)$/gm);
6650
+ if (headings) {
6651
+ for (const h of headings.slice(0, 5)) {
6652
+ const text = h.replace(/^#+\s+/, "").replace(/[*_`#]/g, "").trim();
6653
+ if (text.length > 2 && text.length < 50) {
6654
+ topics.add(text);
6655
+ }
6656
+ }
6657
+ }
6658
+ const boldTerms = content.match(/\*\*([^*]+)\*\*/g);
6659
+ if (boldTerms) {
6660
+ for (const b of boldTerms.slice(0, 5)) {
6661
+ const text = b.replace(/\*\*/g, "").trim();
6662
+ if (text.length > 2 && text.length < 30) {
6663
+ topics.add(text);
6664
+ }
6665
+ }
6666
+ }
6667
+ return Array.from(topics).slice(0, 5);
6668
+ }
5138
6669
  /**
5139
6670
  * Increment access count for memories that were used in prompts
5140
6671
  */
@@ -5158,8 +6689,7 @@ var MemoryService = class {
5158
6689
  return events.map((event) => ({
5159
6690
  memoryId: event.id,
5160
6691
  summary: event.content.substring(0, 200) + (event.content.length > 200 ? "..." : ""),
5161
- topics: [],
5162
- // Could extract topics from content if needed
6692
+ topics: this.extractTopicsFromContent(event.content),
5163
6693
  accessCount: event.access_count || 0,
5164
6694
  lastAccessed: event.last_accessed_at || null,
5165
6695
  confidence: 1,
@@ -5180,6 +6710,34 @@ var MemoryService = class {
5180
6710
  }
5181
6711
  return [];
5182
6712
  }
6713
+ /**
6714
+ * Record a memory retrieval for helpfulness tracking
6715
+ */
6716
+ async recordRetrieval(eventId, sessionId, score, query) {
6717
+ await this.initialize();
6718
+ await this.sqliteStore.recordRetrieval(eventId, sessionId, score, query);
6719
+ }
6720
+ /**
6721
+ * Evaluate helpfulness of retrievals in a session (called at session end)
6722
+ */
6723
+ async evaluateSessionHelpfulness(sessionId) {
6724
+ await this.initialize();
6725
+ await this.sqliteStore.evaluateSessionHelpfulness(sessionId);
6726
+ }
6727
+ /**
6728
+ * Get most helpful memories ranked by helpfulness score
6729
+ */
6730
+ async getHelpfulMemories(limit = 10) {
6731
+ await this.initialize();
6732
+ return this.sqliteStore.getHelpfulMemories(limit);
6733
+ }
6734
+ /**
6735
+ * Get helpfulness statistics for dashboard
6736
+ */
6737
+ async getHelpfulnessStats() {
6738
+ await this.initialize();
6739
+ return this.sqliteStore.getHelpfulnessStats();
6740
+ }
5183
6741
  /**
5184
6742
  * Mark a consolidated memory as accessed
5185
6743
  */
@@ -5243,6 +6801,44 @@ var MemoryService = class {
5243
6801
  lastConsolidation
5244
6802
  };
5245
6803
  }
6804
+ // ============================================================
6805
+ // Turn Grouping Methods
6806
+ // ============================================================
6807
+ /**
6808
+ * Get events grouped by turn for a session
6809
+ */
6810
+ async getSessionTurns(sessionId, options) {
6811
+ await this.initialize();
6812
+ return this.sqliteStore.getSessionTurns(sessionId, options);
6813
+ }
6814
+ /**
6815
+ * Get all events for a specific turn
6816
+ */
6817
+ async getEventsByTurn(turnId) {
6818
+ await this.initialize();
6819
+ return this.sqliteStore.getEventsByTurn(turnId);
6820
+ }
6821
+ /**
6822
+ * Count total turns for a session
6823
+ */
6824
+ async countSessionTurns(sessionId) {
6825
+ await this.initialize();
6826
+ return this.sqliteStore.countSessionTurns(sessionId);
6827
+ }
6828
+ /**
6829
+ * Backfill turn_ids from metadata for events stored before the migration
6830
+ */
6831
+ async backfillTurnIds() {
6832
+ await this.initialize();
6833
+ return this.sqliteStore.backfillTurnIds();
6834
+ }
6835
+ /**
6836
+ * Delete all events for a session (for force reimport)
6837
+ */
6838
+ async deleteSessionEvents(sessionId) {
6839
+ await this.initialize();
6840
+ return this.sqliteStore.deleteSessionEvents(sessionId);
6841
+ }
5246
6842
  /**
5247
6843
  * Format Endless Mode context for Claude
5248
6844
  */
@@ -5319,7 +6915,7 @@ var MemoryService = class {
5319
6915
  */
5320
6916
  expandPath(p) {
5321
6917
  if (p.startsWith("~")) {
5322
- return path.join(os.homedir(), p.slice(1));
6918
+ return path3.join(os.homedir(), p.slice(1));
5323
6919
  }
5324
6920
  return p;
5325
6921
  }
@@ -5332,6 +6928,7 @@ function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
5332
6928
  serviceCache.set(hash, new MemoryService({
5333
6929
  storagePath,
5334
6930
  projectHash: hash,
6931
+ projectPath,
5335
6932
  // Override shared store config - hooks don't need DuckDB
5336
6933
  sharedStoreConfig: sharedStoreConfig ?? { enabled: false },
5337
6934
  analyticsEnabled: false