claude-memory-layer 1.0.9 → 1.0.11

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 (73) hide show
  1. package/dist/cli/index.js +1373 -184
  2. package/dist/cli/index.js.map +4 -4
  3. package/dist/core/index.js +445 -7
  4. package/dist/core/index.js.map +2 -2
  5. package/dist/hooks/post-tool-use.js +705 -43
  6. package/dist/hooks/post-tool-use.js.map +4 -4
  7. package/dist/hooks/session-end.js +593 -52
  8. package/dist/hooks/session-end.js.map +3 -3
  9. package/dist/hooks/session-start.js +581 -25
  10. package/dist/hooks/session-start.js.map +3 -3
  11. package/dist/hooks/stop.js +693 -73
  12. package/dist/hooks/stop.js.map +4 -4
  13. package/dist/hooks/user-prompt-submit.js +674 -94
  14. package/dist/hooks/user-prompt-submit.js.map +4 -4
  15. package/dist/server/api/index.js +1045 -42
  16. package/dist/server/api/index.js.map +4 -4
  17. package/dist/server/index.js +1054 -51
  18. package/dist/server/index.js.map +4 -4
  19. package/dist/services/memory-service.js +599 -25
  20. package/dist/services/memory-service.js.map +3 -3
  21. package/dist/ui/app.js +1380 -55
  22. package/dist/ui/index.html +311 -148
  23. package/dist/ui/style.css +892 -0
  24. package/docs/OPERATIONS.md +18 -0
  25. package/package.json +8 -2
  26. package/scripts/fix-sync-gap.js +32 -0
  27. package/scripts/heartbeat-memory-orchestrator.sh +28 -0
  28. package/scripts/report-sync-gap.js +26 -0
  29. package/scripts/review-queue-auto-resolve.js +21 -0
  30. package/scripts/sync-gap-auto-heal.sh +17 -0
  31. package/specs/20260207-dashboard-upgrade/context.md +38 -0
  32. package/specs/20260207-dashboard-upgrade/spec.md +96 -0
  33. package/src/cli/index.ts +110 -58
  34. package/src/core/sqlite-event-store.ts +542 -6
  35. package/src/core/sqlite-wrapper.ts +8 -0
  36. package/src/core/turn-state.ts +159 -0
  37. package/src/core/types.ts +23 -8
  38. package/src/core/vector-store.ts +21 -3
  39. package/src/hooks/post-tool-use.ts +68 -23
  40. package/src/hooks/session-end.ts +8 -3
  41. package/src/hooks/stop.ts +96 -25
  42. package/src/hooks/user-prompt-submit.ts +78 -65
  43. package/src/server/api/chat.ts +244 -0
  44. package/src/server/api/citations.ts +3 -3
  45. package/src/server/api/events.ts +30 -5
  46. package/src/server/api/index.ts +7 -1
  47. package/src/server/api/projects.ts +74 -0
  48. package/src/server/api/search.ts +3 -3
  49. package/src/server/api/sessions.ts +3 -3
  50. package/src/server/api/stats.ts +43 -7
  51. package/src/server/api/turns.ts +143 -0
  52. package/src/server/api/utils.ts +46 -0
  53. package/src/services/memory-service.ts +208 -9
  54. package/src/services/session-history-importer.ts +215 -51
  55. package/src/ui/app.js +1380 -55
  56. package/src/ui/index.html +311 -148
  57. package/src/ui/style.css +892 -0
  58. package/.claude/settings.local.json +0 -27
  59. package/.claude-memory/test.sqlite +0 -0
  60. package/.history/package_20260201112328.json +0 -45
  61. package/.history/package_20260201113602.json +0 -45
  62. package/.history/package_20260201113713.json +0 -45
  63. package/.history/package_20260201114110.json +0 -45
  64. package/.history/package_20260201114632.json +0 -46
  65. package/.history/package_20260201133143.json +0 -45
  66. package/.history/package_20260201134319.json +0 -45
  67. package/.history/package_20260201134326.json +0 -45
  68. package/.history/package_20260201134334.json +0 -45
  69. package/.history/package_20260201134912.json +0 -45
  70. package/.history/package_20260201142928.json +0 -46
  71. package/.history/package_20260201192048.json +0 -47
  72. package/.history/package_20260202114053.json +0 -49
  73. package/test_access.js +0 -49
@@ -258,6 +258,23 @@ export class SQLiteEventStore {
258
258
  updated_at TEXT DEFAULT (datetime('now'))
259
259
  );
260
260
 
261
+ -- Memory Helpfulness tracking
262
+ CREATE TABLE IF NOT EXISTS memory_helpfulness (
263
+ id TEXT PRIMARY KEY,
264
+ event_id TEXT NOT NULL,
265
+ session_id TEXT NOT NULL,
266
+ retrieval_score REAL DEFAULT 0,
267
+ query_preview TEXT,
268
+ session_continued INTEGER DEFAULT 0,
269
+ prompt_count_after INTEGER DEFAULT 0,
270
+ tool_success_count INTEGER DEFAULT 0,
271
+ tool_total_count INTEGER DEFAULT 0,
272
+ was_reasked INTEGER DEFAULT 0,
273
+ helpfulness_score REAL DEFAULT 0.5,
274
+ created_at TEXT DEFAULT (datetime('now')),
275
+ measured_at TEXT
276
+ );
277
+
261
278
  -- Sync position tracking (for SQLite -> DuckDB sync)
262
279
  CREATE TABLE IF NOT EXISTS sync_positions (
263
280
  target_name TEXT PRIMARY KEY,
@@ -283,9 +300,34 @@ export class SQLiteEventStore {
283
300
  CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence);
284
301
  CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at);
285
302
  CREATE INDEX IF NOT EXISTS idx_embedding_outbox_status ON embedding_outbox(status);
303
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_event ON memory_helpfulness(event_id);
304
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_session ON memory_helpfulness(session_id);
305
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_score ON memory_helpfulness(helpfulness_score DESC);
306
+
307
+ -- FTS5 Full-Text Search for fast keyword search
308
+ CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
309
+ content,
310
+ event_id UNINDEXED,
311
+ content='events',
312
+ content_rowid='rowid'
313
+ );
314
+
315
+ -- Triggers to keep FTS in sync with events table
316
+ CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
317
+ INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
318
+ END;
319
+
320
+ CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
321
+ INSERT INTO events_fts(events_fts, rowid, content, event_id) VALUES('delete', OLD.rowid, OLD.content, OLD.id);
322
+ END;
323
+
324
+ CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
325
+ INSERT INTO events_fts(events_fts, rowid, content, event_id) VALUES('delete', OLD.rowid, OLD.content, OLD.id);
326
+ INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
327
+ END;
286
328
  `);
287
329
 
288
- // Migrate existing events table to add access tracking columns if they don't exist
330
+ // Migrate existing events table to add new columns if they don't exist
289
331
  // Check if columns exist before trying to add them
290
332
  const tableInfo = sqliteAll(this.db, "PRAGMA table_info(events)", []);
291
333
  const columnNames = tableInfo.map((col: any) => col.name);
@@ -310,6 +352,17 @@ export class SQLiteEventStore {
310
352
  }
311
353
  }
312
354
 
355
+ // Add turn_id column for grouping events within a conversation turn
356
+ if (!columnNames.includes('turn_id')) {
357
+ try {
358
+ sqliteExec(this.db, `
359
+ ALTER TABLE events ADD COLUMN turn_id TEXT;
360
+ `);
361
+ } catch (err: any) {
362
+ console.error('Error adding turn_id column:', err);
363
+ }
364
+ }
365
+
313
366
  // Create indexes for new columns if they don't exist
314
367
  try {
315
368
  sqliteExec(this.db, `
@@ -327,6 +380,14 @@ export class SQLiteEventStore {
327
380
  // Index may already exist, ignore
328
381
  }
329
382
 
383
+ try {
384
+ sqliteExec(this.db, `
385
+ CREATE INDEX IF NOT EXISTS idx_events_turn_id ON events(turn_id);
386
+ `);
387
+ } catch (err: any) {
388
+ // Index may already exist, ignore
389
+ }
390
+
330
391
  this.initialized = true;
331
392
  }
332
393
 
@@ -358,10 +419,14 @@ export class SQLiteEventStore {
358
419
  const timestamp = toSQLiteTimestamp(input.timestamp);
359
420
 
360
421
  try {
422
+ // Extract turnId from metadata if present
423
+ const metadata = input.metadata || {};
424
+ const turnId = (metadata.turnId as string) || null;
425
+
361
426
  // Use transaction for atomicity
362
427
  const insertEvent = this.db.prepare(`
363
- INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
364
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
428
+ INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata, turn_id)
429
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
365
430
  `);
366
431
 
367
432
  const insertDedup = this.db.prepare(`
@@ -381,7 +446,8 @@ export class SQLiteEventStore {
381
446
  input.content,
382
447
  canonicalKey,
383
448
  dedupeKey,
384
- JSON.stringify(input.metadata || {})
449
+ JSON.stringify(metadata),
450
+ turnId
385
451
  );
386
452
  insertDedup.run(dedupeKey, id);
387
453
  insertLevel.run(id);
@@ -790,12 +856,13 @@ export class SQLiteEventStore {
790
856
  }
791
857
 
792
858
  /**
793
- * Get most accessed memories
859
+ * Get most accessed memories (falls back to recent events if none accessed)
794
860
  */
795
861
  async getMostAccessed(limit: number = 10): Promise<MemoryEvent[]> {
796
862
  await this.initialize();
797
863
 
798
- const rows = sqliteAll<Record<string, unknown>>(
864
+ // First try events with access_count > 0
865
+ let rows = sqliteAll<Record<string, unknown>>(
799
866
  this.db,
800
867
  `SELECT * FROM events
801
868
  WHERE access_count > 0
@@ -804,9 +871,279 @@ export class SQLiteEventStore {
804
871
  [limit]
805
872
  );
806
873
 
874
+ // Fallback: if no accessed events, show recent events
875
+ if (rows.length === 0) {
876
+ rows = sqliteAll<Record<string, unknown>>(
877
+ this.db,
878
+ `SELECT * FROM events
879
+ ORDER BY timestamp DESC
880
+ LIMIT ?`,
881
+ [limit]
882
+ );
883
+ }
884
+
807
885
  return rows.map(row => this.rowToEvent(row));
808
886
  }
809
887
 
888
+ /**
889
+ * Record a memory retrieval for helpfulness tracking
890
+ */
891
+ async recordRetrieval(eventId: string, sessionId: string, score: number, query: string): Promise<void> {
892
+ if (this.readOnly) return;
893
+ await this.initialize();
894
+
895
+ const id = randomUUID();
896
+ sqliteRun(
897
+ this.db,
898
+ `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
899
+ VALUES (?, ?, ?, ?, ?, datetime('now'))`,
900
+ [id, eventId, sessionId, score, query.slice(0, 100)]
901
+ );
902
+ }
903
+
904
+ /**
905
+ * Evaluate helpfulness for all retrievals in a session
906
+ * Called at session end - uses behavioral signals to compute score
907
+ */
908
+ async evaluateSessionHelpfulness(sessionId: string): Promise<void> {
909
+ if (this.readOnly) return;
910
+ await this.initialize();
911
+
912
+ // Get all retrieval records for this session
913
+ const retrievals = sqliteAll<Record<string, unknown>>(
914
+ this.db,
915
+ `SELECT * FROM memory_helpfulness WHERE session_id = ? AND measured_at IS NULL`,
916
+ [sessionId]
917
+ );
918
+
919
+ if (retrievals.length === 0) return;
920
+
921
+ // Get session events to analyze behavior after retrieval
922
+ const sessionEvents = sqliteAll<Record<string, unknown>>(
923
+ this.db,
924
+ `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
925
+ [sessionId]
926
+ );
927
+
928
+ const promptEvents = sessionEvents.filter((e: any) => e.event_type === 'user_prompt');
929
+ const toolEvents = sessionEvents.filter((e: any) => e.event_type === 'tool_observation');
930
+
931
+ // Count successful vs failed tools
932
+ let toolSuccessCount = 0;
933
+ let toolTotalCount = toolEvents.length;
934
+ for (const t of toolEvents) {
935
+ try {
936
+ const content = JSON.parse(t.content as string);
937
+ if (content.success !== false) toolSuccessCount++;
938
+ } catch {
939
+ toolSuccessCount++; // Assume success if can't parse
940
+ }
941
+ }
942
+ const toolSuccessRatio = toolTotalCount > 0 ? toolSuccessCount / toolTotalCount : 0.5;
943
+
944
+ for (const retrieval of retrievals) {
945
+ const retrievalTime = retrieval.created_at as string;
946
+
947
+ // 1. Session continued after retrieval?
948
+ const eventsAfter = sessionEvents.filter((e: any) => e.timestamp > retrievalTime);
949
+ const sessionContinued = eventsAfter.length > 0 ? 1 : 0;
950
+
951
+ // 2. How many prompts came after?
952
+ const promptsAfter = promptEvents.filter((e: any) => e.timestamp > retrievalTime);
953
+ const promptCountAfter = promptsAfter.length;
954
+
955
+ // 3. Was a similar query asked again? (simple word overlap check)
956
+ const queryWords = new Set((retrieval.query_preview as string || '').toLowerCase().split(/\s+/).filter(w => w.length > 2));
957
+ let wasReasked = 0;
958
+ for (const p of promptsAfter) {
959
+ const pWords = new Set((p.content as string).toLowerCase().split(/\s+/).filter((w: string) => w.length > 2));
960
+ let overlap = 0;
961
+ for (const w of queryWords) {
962
+ if (pWords.has(w)) overlap++;
963
+ }
964
+ if (queryWords.size > 0 && overlap / queryWords.size > 0.5) {
965
+ wasReasked = 1;
966
+ break;
967
+ }
968
+ }
969
+
970
+ // Calculate helpfulness score
971
+ const retrievalScore = retrieval.retrieval_score as number || 0;
972
+ const helpfulnessScore = (
973
+ 0.30 * Math.min(retrievalScore, 1.0) +
974
+ 0.25 * (sessionContinued ? 1.0 : 0.0) +
975
+ 0.25 * toolSuccessRatio +
976
+ 0.20 * (wasReasked ? 0.0 : 1.0)
977
+ );
978
+
979
+ sqliteRun(
980
+ this.db,
981
+ `UPDATE memory_helpfulness
982
+ SET session_continued = ?, prompt_count_after = ?,
983
+ tool_success_count = ?, tool_total_count = ?,
984
+ was_reasked = ?, helpfulness_score = ?,
985
+ measured_at = datetime('now')
986
+ WHERE id = ?`,
987
+ [sessionContinued, promptCountAfter, toolSuccessCount, toolTotalCount,
988
+ wasReasked, helpfulnessScore, retrieval.id]
989
+ );
990
+ }
991
+ }
992
+
993
+ /**
994
+ * Get most helpful memories ranked by helpfulness score
995
+ */
996
+ async getHelpfulMemories(limit: number = 10): Promise<Array<{
997
+ eventId: string;
998
+ summary: string;
999
+ helpfulnessScore: number;
1000
+ accessCount: number;
1001
+ evaluationCount: number;
1002
+ }>> {
1003
+ await this.initialize();
1004
+
1005
+ const rows = sqliteAll<Record<string, unknown>>(
1006
+ this.db,
1007
+ `SELECT
1008
+ mh.event_id,
1009
+ AVG(mh.helpfulness_score) as avg_score,
1010
+ COUNT(*) as eval_count,
1011
+ e.content,
1012
+ e.access_count
1013
+ FROM memory_helpfulness mh
1014
+ JOIN events e ON e.id = mh.event_id
1015
+ WHERE mh.measured_at IS NOT NULL
1016
+ GROUP BY mh.event_id
1017
+ ORDER BY avg_score DESC
1018
+ LIMIT ?`,
1019
+ [limit]
1020
+ );
1021
+
1022
+ return rows.map(r => ({
1023
+ eventId: r.event_id as string,
1024
+ summary: (r.content as string).substring(0, 200) + ((r.content as string).length > 200 ? '...' : ''),
1025
+ helpfulnessScore: Math.round((r.avg_score as number) * 100) / 100,
1026
+ accessCount: (r.access_count as number) || 0,
1027
+ evaluationCount: r.eval_count as number
1028
+ }));
1029
+ }
1030
+
1031
+ /**
1032
+ * Get helpfulness statistics for dashboard
1033
+ */
1034
+ async getHelpfulnessStats(): Promise<{
1035
+ avgScore: number;
1036
+ totalEvaluated: number;
1037
+ totalRetrievals: number;
1038
+ helpful: number;
1039
+ neutral: number;
1040
+ unhelpful: number;
1041
+ }> {
1042
+ await this.initialize();
1043
+
1044
+ const stats = sqliteGet<Record<string, unknown>>(
1045
+ this.db,
1046
+ `SELECT
1047
+ AVG(helpfulness_score) as avg_score,
1048
+ COUNT(*) as total_evaluated,
1049
+ SUM(CASE WHEN helpfulness_score >= 0.7 THEN 1 ELSE 0 END) as helpful,
1050
+ SUM(CASE WHEN helpfulness_score >= 0.4 AND helpfulness_score < 0.7 THEN 1 ELSE 0 END) as neutral,
1051
+ SUM(CASE WHEN helpfulness_score < 0.4 THEN 1 ELSE 0 END) as unhelpful
1052
+ FROM memory_helpfulness
1053
+ WHERE measured_at IS NOT NULL`
1054
+ );
1055
+
1056
+ const totalRow = sqliteGet<Record<string, unknown>>(
1057
+ this.db,
1058
+ `SELECT COUNT(*) as total FROM memory_helpfulness`
1059
+ );
1060
+
1061
+ return {
1062
+ avgScore: Math.round(((stats?.avg_score as number) || 0) * 100) / 100,
1063
+ totalEvaluated: (stats?.total_evaluated as number) || 0,
1064
+ totalRetrievals: (totalRow?.total as number) || 0,
1065
+ helpful: (stats?.helpful as number) || 0,
1066
+ neutral: (stats?.neutral as number) || 0,
1067
+ unhelpful: (stats?.unhelpful as number) || 0
1068
+ };
1069
+ }
1070
+
1071
+ /**
1072
+ * Fast keyword search using FTS5
1073
+ * Returns events matching the search query, ranked by relevance
1074
+ */
1075
+ async keywordSearch(query: string, limit: number = 10): Promise<Array<{event: MemoryEvent; rank: number}>> {
1076
+ await this.initialize();
1077
+
1078
+ // Escape special FTS5 characters and prepare search terms
1079
+ const searchTerms = query
1080
+ .replace(/['"(){}[\]^~*?:\\/-]/g, ' ') // Remove special chars
1081
+ .split(/\s+/)
1082
+ .filter(term => term.length > 1) // Filter short terms
1083
+ .map(term => `"${term}"*`) // Prefix matching
1084
+ .join(' OR ');
1085
+
1086
+ if (!searchTerms) {
1087
+ return [];
1088
+ }
1089
+
1090
+ try {
1091
+ const rows = sqliteAll<Record<string, unknown>>(
1092
+ this.db,
1093
+ `SELECT e.*, fts.rank
1094
+ FROM events_fts fts
1095
+ JOIN events e ON e.id = fts.event_id
1096
+ WHERE events_fts MATCH ?
1097
+ ORDER BY fts.rank
1098
+ LIMIT ?`,
1099
+ [searchTerms, limit]
1100
+ );
1101
+
1102
+ return rows.map(row => ({
1103
+ event: this.rowToEvent(row),
1104
+ rank: row.rank as number
1105
+ }));
1106
+ } catch (error: any) {
1107
+ // FTS table might not exist yet (old database)
1108
+ // Fallback to LIKE search
1109
+ const likePattern = `%${query}%`;
1110
+ const rows = sqliteAll<Record<string, unknown>>(
1111
+ this.db,
1112
+ `SELECT *, 0 as rank FROM events
1113
+ WHERE content LIKE ?
1114
+ ORDER BY timestamp DESC
1115
+ LIMIT ?`,
1116
+ [likePattern, limit]
1117
+ );
1118
+
1119
+ return rows.map(row => ({
1120
+ event: this.rowToEvent(row),
1121
+ rank: 0
1122
+ }));
1123
+ }
1124
+ }
1125
+
1126
+ /**
1127
+ * Rebuild FTS index from existing events
1128
+ * Call this once after upgrading to FTS5
1129
+ */
1130
+ async rebuildFtsIndex(): Promise<number> {
1131
+ await this.initialize();
1132
+
1133
+ // Get count of events to index
1134
+ const countRow = sqliteGet<{count: number}>(this.db, 'SELECT COUNT(*) as count FROM events', []);
1135
+ const totalEvents = countRow?.count ?? 0;
1136
+
1137
+ // Clear and rebuild FTS index
1138
+ sqliteExec(this.db, `
1139
+ DELETE FROM events_fts;
1140
+ INSERT INTO events_fts(rowid, content, event_id)
1141
+ SELECT rowid, content, id FROM events;
1142
+ `);
1143
+
1144
+ return totalEvents;
1145
+ }
1146
+
810
1147
  /**
811
1148
  * Get database instance for direct access
812
1149
  */
@@ -821,6 +1158,201 @@ export class SQLiteEventStore {
821
1158
  sqliteClose(this.db);
822
1159
  }
823
1160
 
1161
+ /**
1162
+ * Get events grouped by turn_id for a session
1163
+ * Returns turns ordered by first event timestamp (newest first)
1164
+ */
1165
+ async getSessionTurns(sessionId: string, options?: { limit?: number; offset?: number }): Promise<Array<{
1166
+ turnId: string;
1167
+ events: MemoryEvent[];
1168
+ startedAt: Date;
1169
+ promptPreview: string;
1170
+ eventCount: number;
1171
+ toolCount: number;
1172
+ hasResponse: boolean;
1173
+ }>> {
1174
+ await this.initialize();
1175
+
1176
+ const limit = options?.limit || 20;
1177
+ const offset = options?.offset || 0;
1178
+
1179
+ // Get distinct turn_ids for this session, ordered by first event timestamp
1180
+ const turnRows = sqliteAll<{ turn_id: string; min_ts: string }>(
1181
+ this.db,
1182
+ `SELECT turn_id, MIN(timestamp) as min_ts
1183
+ FROM events
1184
+ WHERE session_id = ? AND turn_id IS NOT NULL
1185
+ GROUP BY turn_id
1186
+ ORDER BY min_ts DESC
1187
+ LIMIT ? OFFSET ?`,
1188
+ [sessionId, limit, offset]
1189
+ );
1190
+
1191
+ const turns: Array<{
1192
+ turnId: string;
1193
+ events: MemoryEvent[];
1194
+ startedAt: Date;
1195
+ promptPreview: string;
1196
+ eventCount: number;
1197
+ toolCount: number;
1198
+ hasResponse: boolean;
1199
+ }> = [];
1200
+
1201
+ for (const turnRow of turnRows) {
1202
+ const events = await this.getEventsByTurn(turnRow.turn_id);
1203
+
1204
+ const promptEvent = events.find(e => e.eventType === 'user_prompt');
1205
+ const toolEvents = events.filter(e => e.eventType === 'tool_observation');
1206
+ const hasResponse = events.some(e => e.eventType === 'agent_response');
1207
+
1208
+ turns.push({
1209
+ turnId: turnRow.turn_id,
1210
+ events,
1211
+ startedAt: toDateFromSQLite(turnRow.min_ts),
1212
+ promptPreview: promptEvent
1213
+ ? promptEvent.content.slice(0, 200) + (promptEvent.content.length > 200 ? '...' : '')
1214
+ : '(no prompt)',
1215
+ eventCount: events.length,
1216
+ toolCount: toolEvents.length,
1217
+ hasResponse
1218
+ });
1219
+ }
1220
+
1221
+ return turns;
1222
+ }
1223
+
1224
+ /**
1225
+ * Get all events for a specific turn_id
1226
+ */
1227
+ async getEventsByTurn(turnId: string): Promise<MemoryEvent[]> {
1228
+ await this.initialize();
1229
+
1230
+ const rows = sqliteAll<Record<string, unknown>>(
1231
+ this.db,
1232
+ `SELECT * FROM events WHERE turn_id = ? ORDER BY timestamp ASC`,
1233
+ [turnId]
1234
+ );
1235
+
1236
+ return rows.map(this.rowToEvent);
1237
+ }
1238
+
1239
+ /**
1240
+ * Count total turns for a session
1241
+ */
1242
+ async countSessionTurns(sessionId: string): Promise<number> {
1243
+ await this.initialize();
1244
+
1245
+ const row = sqliteGet<{ count: number }>(
1246
+ this.db,
1247
+ `SELECT COUNT(DISTINCT turn_id) as count
1248
+ FROM events
1249
+ WHERE session_id = ? AND turn_id IS NOT NULL`,
1250
+ [sessionId]
1251
+ );
1252
+
1253
+ return row?.count || 0;
1254
+ }
1255
+
1256
+ /**
1257
+ * Migrate existing events: backfill turn_id for events that have turnId in metadata
1258
+ * but no turn_id column value (for events stored before this migration)
1259
+ */
1260
+ async backfillTurnIds(): Promise<number> {
1261
+ await this.initialize();
1262
+
1263
+ // Find events with turnId in metadata JSON but no turn_id column value
1264
+ const rows = sqliteAll<{ id: string; metadata: string }>(
1265
+ this.db,
1266
+ `SELECT id, metadata FROM events
1267
+ WHERE turn_id IS NULL AND metadata IS NOT NULL AND metadata LIKE '%turnId%'`
1268
+ );
1269
+
1270
+ let updated = 0;
1271
+ for (const row of rows) {
1272
+ try {
1273
+ const metadata = JSON.parse(row.metadata);
1274
+ if (metadata.turnId) {
1275
+ sqliteRun(
1276
+ this.db,
1277
+ `UPDATE events SET turn_id = ? WHERE id = ?`,
1278
+ [metadata.turnId, row.id]
1279
+ );
1280
+ updated++;
1281
+ }
1282
+ } catch {
1283
+ // Skip rows with invalid JSON
1284
+ }
1285
+ }
1286
+
1287
+ return updated;
1288
+ }
1289
+
1290
+ /**
1291
+ * Delete all events for a session (for force reimport)
1292
+ */
1293
+ async deleteSessionEvents(sessionId: string): Promise<number> {
1294
+ await this.initialize();
1295
+
1296
+ // Get event IDs first for cascading deletes
1297
+ const events = sqliteAll<{ id: string }>(
1298
+ this.db,
1299
+ `SELECT id FROM events WHERE session_id = ?`,
1300
+ [sessionId]
1301
+ );
1302
+
1303
+ if (events.length === 0) return 0;
1304
+
1305
+ const eventIds = events.map(e => e.id);
1306
+ const placeholders = eventIds.map(() => '?').join(',');
1307
+
1308
+ // Drop FTS triggers to prevent SQLITE_CORRUPT_VTAB during bulk delete
1309
+ const ftsTriggersDropped: string[] = [];
1310
+ for (const triggerName of ['events_fts_delete', 'events_fts_update', 'events_fts_insert']) {
1311
+ try {
1312
+ sqliteRun(this.db, `DROP TRIGGER IF EXISTS ${triggerName}`);
1313
+ ftsTriggersDropped.push(triggerName);
1314
+ } catch {
1315
+ // Trigger may not exist
1316
+ }
1317
+ }
1318
+
1319
+ // Delete from related tables first (some may not exist depending on DB version)
1320
+ for (const table of ['event_dedup', 'memory_levels', 'embedding_queue', 'embedding_outbox', 'vector_outbox']) {
1321
+ try {
1322
+ sqliteRun(this.db, `DELETE FROM ${table} WHERE event_id IN (${placeholders})`, eventIds);
1323
+ } catch {
1324
+ // Table may not exist
1325
+ }
1326
+ }
1327
+
1328
+ // Delete events
1329
+ const result = sqliteRun(this.db, `DELETE FROM events WHERE session_id = ?`, [sessionId]);
1330
+
1331
+ // Rebuild FTS index if we dropped triggers
1332
+ if (ftsTriggersDropped.length > 0) {
1333
+ try {
1334
+ // Rebuild FTS from remaining events
1335
+ sqliteRun(this.db, `INSERT INTO events_fts(events_fts) VALUES('rebuild')`);
1336
+
1337
+ // Recreate triggers
1338
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
1339
+ INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
1340
+ END`);
1341
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
1342
+ INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
1343
+ END`);
1344
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
1345
+ INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
1346
+ INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
1347
+ END`);
1348
+ } catch {
1349
+ // FTS rebuild failed - non-critical, will be rebuilt on next initialize
1350
+ }
1351
+ }
1352
+
1353
+ return result.changes || 0;
1354
+ }
1355
+
824
1356
  /**
825
1357
  * Convert database row to MemoryEvent
826
1358
  */
@@ -843,6 +1375,10 @@ export class SQLiteEventStore {
843
1375
  if (row.last_accessed_at !== undefined) {
844
1376
  event.last_accessed_at = row.last_accessed_at;
845
1377
  }
1378
+ // Include turn_id if present
1379
+ if (row.turn_id !== undefined && row.turn_id !== null) {
1380
+ event.turn_id = row.turn_id;
1381
+ }
846
1382
 
847
1383
  return event;
848
1384
  }
@@ -4,6 +4,8 @@
4
4
  */
5
5
 
6
6
  import Database from 'better-sqlite3';
7
+ import * as fs from 'fs';
8
+ import * as nodePath from 'path';
7
9
 
8
10
  export type SQLiteDatabase = Database.Database;
9
11
 
@@ -16,6 +18,12 @@ export interface SQLiteOptions {
16
18
  * Creates a new SQLite database with WAL mode
17
19
  */
18
20
  export function createSQLiteDatabase(path: string, options?: SQLiteOptions): SQLiteDatabase {
21
+ // Ensure parent directory exists
22
+ const dir = nodePath.dirname(path);
23
+ if (!fs.existsSync(dir)) {
24
+ fs.mkdirSync(dir, { recursive: true });
25
+ }
26
+
19
27
  const db = new Database(path, {
20
28
  readonly: options?.readonly ?? false,
21
29
  });