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
@@ -8,7 +8,7 @@ const __dirname = dirname(__filename);
8
8
  // src/services/memory-service.ts
9
9
  import * as path from "path";
10
10
  import * as os from "os";
11
- import * as fs from "fs";
11
+ import * as fs2 from "fs";
12
12
  import * as crypto2 from "crypto";
13
13
 
14
14
  // src/core/event-store.ts
@@ -740,7 +740,13 @@ import { randomUUID as randomUUID2 } from "crypto";
740
740
 
741
741
  // src/core/sqlite-wrapper.ts
742
742
  import Database from "better-sqlite3";
743
+ import * as fs from "fs";
744
+ import * as nodePath from "path";
743
745
  function createSQLiteDatabase(path2, options) {
746
+ const dir = nodePath.dirname(path2);
747
+ if (!fs.existsSync(dir)) {
748
+ fs.mkdirSync(dir, { recursive: true });
749
+ }
744
750
  const db = new Database(path2, {
745
751
  readonly: options?.readonly ?? false
746
752
  });
@@ -1008,6 +1014,23 @@ var SQLiteEventStore = class {
1008
1014
  updated_at TEXT DEFAULT (datetime('now'))
1009
1015
  );
1010
1016
 
1017
+ -- Memory Helpfulness tracking
1018
+ CREATE TABLE IF NOT EXISTS memory_helpfulness (
1019
+ id TEXT PRIMARY KEY,
1020
+ event_id TEXT NOT NULL,
1021
+ session_id TEXT NOT NULL,
1022
+ retrieval_score REAL DEFAULT 0,
1023
+ query_preview TEXT,
1024
+ session_continued INTEGER DEFAULT 0,
1025
+ prompt_count_after INTEGER DEFAULT 0,
1026
+ tool_success_count INTEGER DEFAULT 0,
1027
+ tool_total_count INTEGER DEFAULT 0,
1028
+ was_reasked INTEGER DEFAULT 0,
1029
+ helpfulness_score REAL DEFAULT 0.5,
1030
+ created_at TEXT DEFAULT (datetime('now')),
1031
+ measured_at TEXT
1032
+ );
1033
+
1011
1034
  -- Sync position tracking (for SQLite -> DuckDB sync)
1012
1035
  CREATE TABLE IF NOT EXISTS sync_positions (
1013
1036
  target_name TEXT PRIMARY KEY,
@@ -1033,6 +1056,31 @@ var SQLiteEventStore = class {
1033
1056
  CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence);
1034
1057
  CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at);
1035
1058
  CREATE INDEX IF NOT EXISTS idx_embedding_outbox_status ON embedding_outbox(status);
1059
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_event ON memory_helpfulness(event_id);
1060
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_session ON memory_helpfulness(session_id);
1061
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_score ON memory_helpfulness(helpfulness_score DESC);
1062
+
1063
+ -- FTS5 Full-Text Search for fast keyword search
1064
+ CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
1065
+ content,
1066
+ event_id UNINDEXED,
1067
+ content='events',
1068
+ content_rowid='rowid'
1069
+ );
1070
+
1071
+ -- Triggers to keep FTS in sync with events table
1072
+ CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
1073
+ INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
1074
+ END;
1075
+
1076
+ CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
1077
+ INSERT INTO events_fts(events_fts, rowid, content, event_id) VALUES('delete', OLD.rowid, OLD.content, OLD.id);
1078
+ END;
1079
+
1080
+ CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
1081
+ INSERT INTO events_fts(events_fts, rowid, content, event_id) VALUES('delete', OLD.rowid, OLD.content, OLD.id);
1082
+ INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
1083
+ END;
1036
1084
  `);
1037
1085
  const tableInfo = sqliteAll(this.db, "PRAGMA table_info(events)", []);
1038
1086
  const columnNames = tableInfo.map((col) => col.name);
@@ -1054,6 +1102,15 @@ var SQLiteEventStore = class {
1054
1102
  console.error("Error adding last_accessed_at column:", err);
1055
1103
  }
1056
1104
  }
1105
+ if (!columnNames.includes("turn_id")) {
1106
+ try {
1107
+ sqliteExec(this.db, `
1108
+ ALTER TABLE events ADD COLUMN turn_id TEXT;
1109
+ `);
1110
+ } catch (err) {
1111
+ console.error("Error adding turn_id column:", err);
1112
+ }
1113
+ }
1057
1114
  try {
1058
1115
  sqliteExec(this.db, `
1059
1116
  CREATE INDEX IF NOT EXISTS idx_events_access_count ON events(access_count DESC);
@@ -1066,6 +1123,12 @@ var SQLiteEventStore = class {
1066
1123
  `);
1067
1124
  } catch (err) {
1068
1125
  }
1126
+ try {
1127
+ sqliteExec(this.db, `
1128
+ CREATE INDEX IF NOT EXISTS idx_events_turn_id ON events(turn_id);
1129
+ `);
1130
+ } catch (err) {
1131
+ }
1069
1132
  this.initialized = true;
1070
1133
  }
1071
1134
  /**
@@ -1090,9 +1153,11 @@ var SQLiteEventStore = class {
1090
1153
  const id = randomUUID2();
1091
1154
  const timestamp = toSQLiteTimestamp(input.timestamp);
1092
1155
  try {
1156
+ const metadata = input.metadata || {};
1157
+ const turnId = metadata.turnId || null;
1093
1158
  const insertEvent = this.db.prepare(`
1094
- INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
1095
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1159
+ INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata, turn_id)
1160
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1096
1161
  `);
1097
1162
  const insertDedup = this.db.prepare(`
1098
1163
  INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)
@@ -1109,7 +1174,8 @@ var SQLiteEventStore = class {
1109
1174
  input.content,
1110
1175
  canonicalKey,
1111
1176
  dedupeKey,
1112
- JSON.stringify(input.metadata || {})
1177
+ JSON.stringify(metadata),
1178
+ turnId
1113
1179
  );
1114
1180
  insertDedup.run(dedupeKey, id);
1115
1181
  insertLevel.run(id);
@@ -1459,11 +1525,11 @@ var SQLiteEventStore = class {
1459
1525
  );
1460
1526
  }
1461
1527
  /**
1462
- * Get most accessed memories
1528
+ * Get most accessed memories (falls back to recent events if none accessed)
1463
1529
  */
1464
1530
  async getMostAccessed(limit = 10) {
1465
1531
  await this.initialize();
1466
- const rows = sqliteAll(
1532
+ let rows = sqliteAll(
1467
1533
  this.db,
1468
1534
  `SELECT * FROM events
1469
1535
  WHERE access_count > 0
@@ -1471,8 +1537,222 @@ var SQLiteEventStore = class {
1471
1537
  LIMIT ?`,
1472
1538
  [limit]
1473
1539
  );
1540
+ if (rows.length === 0) {
1541
+ rows = sqliteAll(
1542
+ this.db,
1543
+ `SELECT * FROM events
1544
+ ORDER BY timestamp DESC
1545
+ LIMIT ?`,
1546
+ [limit]
1547
+ );
1548
+ }
1474
1549
  return rows.map((row) => this.rowToEvent(row));
1475
1550
  }
1551
+ /**
1552
+ * Record a memory retrieval for helpfulness tracking
1553
+ */
1554
+ async recordRetrieval(eventId, sessionId, score, query) {
1555
+ if (this.readOnly)
1556
+ return;
1557
+ await this.initialize();
1558
+ const id = randomUUID2();
1559
+ sqliteRun(
1560
+ this.db,
1561
+ `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
1562
+ VALUES (?, ?, ?, ?, ?, datetime('now'))`,
1563
+ [id, eventId, sessionId, score, query.slice(0, 100)]
1564
+ );
1565
+ }
1566
+ /**
1567
+ * Evaluate helpfulness for all retrievals in a session
1568
+ * Called at session end - uses behavioral signals to compute score
1569
+ */
1570
+ async evaluateSessionHelpfulness(sessionId) {
1571
+ if (this.readOnly)
1572
+ return;
1573
+ await this.initialize();
1574
+ const retrievals = sqliteAll(
1575
+ this.db,
1576
+ `SELECT * FROM memory_helpfulness WHERE session_id = ? AND measured_at IS NULL`,
1577
+ [sessionId]
1578
+ );
1579
+ if (retrievals.length === 0)
1580
+ return;
1581
+ const sessionEvents = sqliteAll(
1582
+ this.db,
1583
+ `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
1584
+ [sessionId]
1585
+ );
1586
+ const promptEvents = sessionEvents.filter((e) => e.event_type === "user_prompt");
1587
+ const toolEvents = sessionEvents.filter((e) => e.event_type === "tool_observation");
1588
+ let toolSuccessCount = 0;
1589
+ let toolTotalCount = toolEvents.length;
1590
+ for (const t of toolEvents) {
1591
+ try {
1592
+ const content = JSON.parse(t.content);
1593
+ if (content.success !== false)
1594
+ toolSuccessCount++;
1595
+ } catch {
1596
+ toolSuccessCount++;
1597
+ }
1598
+ }
1599
+ const toolSuccessRatio = toolTotalCount > 0 ? toolSuccessCount / toolTotalCount : 0.5;
1600
+ for (const retrieval of retrievals) {
1601
+ const retrievalTime = retrieval.created_at;
1602
+ const eventsAfter = sessionEvents.filter((e) => e.timestamp > retrievalTime);
1603
+ const sessionContinued = eventsAfter.length > 0 ? 1 : 0;
1604
+ const promptsAfter = promptEvents.filter((e) => e.timestamp > retrievalTime);
1605
+ const promptCountAfter = promptsAfter.length;
1606
+ const queryWords = new Set((retrieval.query_preview || "").toLowerCase().split(/\s+/).filter((w) => w.length > 2));
1607
+ let wasReasked = 0;
1608
+ for (const p of promptsAfter) {
1609
+ const pWords = new Set(p.content.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
1610
+ let overlap = 0;
1611
+ for (const w of queryWords) {
1612
+ if (pWords.has(w))
1613
+ overlap++;
1614
+ }
1615
+ if (queryWords.size > 0 && overlap / queryWords.size > 0.5) {
1616
+ wasReasked = 1;
1617
+ break;
1618
+ }
1619
+ }
1620
+ const retrievalScore = retrieval.retrieval_score || 0;
1621
+ const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
1622
+ sqliteRun(
1623
+ this.db,
1624
+ `UPDATE memory_helpfulness
1625
+ SET session_continued = ?, prompt_count_after = ?,
1626
+ tool_success_count = ?, tool_total_count = ?,
1627
+ was_reasked = ?, helpfulness_score = ?,
1628
+ measured_at = datetime('now')
1629
+ WHERE id = ?`,
1630
+ [
1631
+ sessionContinued,
1632
+ promptCountAfter,
1633
+ toolSuccessCount,
1634
+ toolTotalCount,
1635
+ wasReasked,
1636
+ helpfulnessScore,
1637
+ retrieval.id
1638
+ ]
1639
+ );
1640
+ }
1641
+ }
1642
+ /**
1643
+ * Get most helpful memories ranked by helpfulness score
1644
+ */
1645
+ async getHelpfulMemories(limit = 10) {
1646
+ await this.initialize();
1647
+ const rows = sqliteAll(
1648
+ this.db,
1649
+ `SELECT
1650
+ mh.event_id,
1651
+ AVG(mh.helpfulness_score) as avg_score,
1652
+ COUNT(*) as eval_count,
1653
+ e.content,
1654
+ e.access_count
1655
+ FROM memory_helpfulness mh
1656
+ JOIN events e ON e.id = mh.event_id
1657
+ WHERE mh.measured_at IS NOT NULL
1658
+ GROUP BY mh.event_id
1659
+ ORDER BY avg_score DESC
1660
+ LIMIT ?`,
1661
+ [limit]
1662
+ );
1663
+ return rows.map((r) => ({
1664
+ eventId: r.event_id,
1665
+ summary: r.content.substring(0, 200) + (r.content.length > 200 ? "..." : ""),
1666
+ helpfulnessScore: Math.round(r.avg_score * 100) / 100,
1667
+ accessCount: r.access_count || 0,
1668
+ evaluationCount: r.eval_count
1669
+ }));
1670
+ }
1671
+ /**
1672
+ * Get helpfulness statistics for dashboard
1673
+ */
1674
+ async getHelpfulnessStats() {
1675
+ await this.initialize();
1676
+ const stats = sqliteGet(
1677
+ this.db,
1678
+ `SELECT
1679
+ AVG(helpfulness_score) as avg_score,
1680
+ COUNT(*) as total_evaluated,
1681
+ SUM(CASE WHEN helpfulness_score >= 0.7 THEN 1 ELSE 0 END) as helpful,
1682
+ SUM(CASE WHEN helpfulness_score >= 0.4 AND helpfulness_score < 0.7 THEN 1 ELSE 0 END) as neutral,
1683
+ SUM(CASE WHEN helpfulness_score < 0.4 THEN 1 ELSE 0 END) as unhelpful
1684
+ FROM memory_helpfulness
1685
+ WHERE measured_at IS NOT NULL`
1686
+ );
1687
+ const totalRow = sqliteGet(
1688
+ this.db,
1689
+ `SELECT COUNT(*) as total FROM memory_helpfulness`
1690
+ );
1691
+ return {
1692
+ avgScore: Math.round((stats?.avg_score || 0) * 100) / 100,
1693
+ totalEvaluated: stats?.total_evaluated || 0,
1694
+ totalRetrievals: totalRow?.total || 0,
1695
+ helpful: stats?.helpful || 0,
1696
+ neutral: stats?.neutral || 0,
1697
+ unhelpful: stats?.unhelpful || 0
1698
+ };
1699
+ }
1700
+ /**
1701
+ * Fast keyword search using FTS5
1702
+ * Returns events matching the search query, ranked by relevance
1703
+ */
1704
+ async keywordSearch(query, limit = 10) {
1705
+ await this.initialize();
1706
+ const searchTerms = query.replace(/['"(){}[\]^~*?:\\/-]/g, " ").split(/\s+/).filter((term) => term.length > 1).map((term) => `"${term}"*`).join(" OR ");
1707
+ if (!searchTerms) {
1708
+ return [];
1709
+ }
1710
+ try {
1711
+ const rows = sqliteAll(
1712
+ this.db,
1713
+ `SELECT e.*, fts.rank
1714
+ FROM events_fts fts
1715
+ JOIN events e ON e.id = fts.event_id
1716
+ WHERE events_fts MATCH ?
1717
+ ORDER BY fts.rank
1718
+ LIMIT ?`,
1719
+ [searchTerms, limit]
1720
+ );
1721
+ return rows.map((row) => ({
1722
+ event: this.rowToEvent(row),
1723
+ rank: row.rank
1724
+ }));
1725
+ } catch (error) {
1726
+ const likePattern = `%${query}%`;
1727
+ const rows = sqliteAll(
1728
+ this.db,
1729
+ `SELECT *, 0 as rank FROM events
1730
+ WHERE content LIKE ?
1731
+ ORDER BY timestamp DESC
1732
+ LIMIT ?`,
1733
+ [likePattern, limit]
1734
+ );
1735
+ return rows.map((row) => ({
1736
+ event: this.rowToEvent(row),
1737
+ rank: 0
1738
+ }));
1739
+ }
1740
+ }
1741
+ /**
1742
+ * Rebuild FTS index from existing events
1743
+ * Call this once after upgrading to FTS5
1744
+ */
1745
+ async rebuildFtsIndex() {
1746
+ await this.initialize();
1747
+ const countRow = sqliteGet(this.db, "SELECT COUNT(*) as count FROM events", []);
1748
+ const totalEvents = countRow?.count ?? 0;
1749
+ sqliteExec(this.db, `
1750
+ DELETE FROM events_fts;
1751
+ INSERT INTO events_fts(rowid, content, event_id)
1752
+ SELECT rowid, content, id FROM events;
1753
+ `);
1754
+ return totalEvents;
1755
+ }
1476
1756
  /**
1477
1757
  * Get database instance for direct access
1478
1758
  */
@@ -1485,6 +1765,143 @@ var SQLiteEventStore = class {
1485
1765
  async close() {
1486
1766
  sqliteClose(this.db);
1487
1767
  }
1768
+ /**
1769
+ * Get events grouped by turn_id for a session
1770
+ * Returns turns ordered by first event timestamp (newest first)
1771
+ */
1772
+ async getSessionTurns(sessionId, options) {
1773
+ await this.initialize();
1774
+ const limit = options?.limit || 20;
1775
+ const offset = options?.offset || 0;
1776
+ const turnRows = sqliteAll(
1777
+ this.db,
1778
+ `SELECT turn_id, MIN(timestamp) as min_ts
1779
+ FROM events
1780
+ WHERE session_id = ? AND turn_id IS NOT NULL
1781
+ GROUP BY turn_id
1782
+ ORDER BY min_ts DESC
1783
+ LIMIT ? OFFSET ?`,
1784
+ [sessionId, limit, offset]
1785
+ );
1786
+ const turns = [];
1787
+ for (const turnRow of turnRows) {
1788
+ const events = await this.getEventsByTurn(turnRow.turn_id);
1789
+ const promptEvent = events.find((e) => e.eventType === "user_prompt");
1790
+ const toolEvents = events.filter((e) => e.eventType === "tool_observation");
1791
+ const hasResponse = events.some((e) => e.eventType === "agent_response");
1792
+ turns.push({
1793
+ turnId: turnRow.turn_id,
1794
+ events,
1795
+ startedAt: toDateFromSQLite(turnRow.min_ts),
1796
+ promptPreview: promptEvent ? promptEvent.content.slice(0, 200) + (promptEvent.content.length > 200 ? "..." : "") : "(no prompt)",
1797
+ eventCount: events.length,
1798
+ toolCount: toolEvents.length,
1799
+ hasResponse
1800
+ });
1801
+ }
1802
+ return turns;
1803
+ }
1804
+ /**
1805
+ * Get all events for a specific turn_id
1806
+ */
1807
+ async getEventsByTurn(turnId) {
1808
+ await this.initialize();
1809
+ const rows = sqliteAll(
1810
+ this.db,
1811
+ `SELECT * FROM events WHERE turn_id = ? ORDER BY timestamp ASC`,
1812
+ [turnId]
1813
+ );
1814
+ return rows.map(this.rowToEvent);
1815
+ }
1816
+ /**
1817
+ * Count total turns for a session
1818
+ */
1819
+ async countSessionTurns(sessionId) {
1820
+ await this.initialize();
1821
+ const row = sqliteGet(
1822
+ this.db,
1823
+ `SELECT COUNT(DISTINCT turn_id) as count
1824
+ FROM events
1825
+ WHERE session_id = ? AND turn_id IS NOT NULL`,
1826
+ [sessionId]
1827
+ );
1828
+ return row?.count || 0;
1829
+ }
1830
+ /**
1831
+ * Migrate existing events: backfill turn_id for events that have turnId in metadata
1832
+ * but no turn_id column value (for events stored before this migration)
1833
+ */
1834
+ async backfillTurnIds() {
1835
+ await this.initialize();
1836
+ const rows = sqliteAll(
1837
+ this.db,
1838
+ `SELECT id, metadata FROM events
1839
+ WHERE turn_id IS NULL AND metadata IS NOT NULL AND metadata LIKE '%turnId%'`
1840
+ );
1841
+ let updated = 0;
1842
+ for (const row of rows) {
1843
+ try {
1844
+ const metadata = JSON.parse(row.metadata);
1845
+ if (metadata.turnId) {
1846
+ sqliteRun(
1847
+ this.db,
1848
+ `UPDATE events SET turn_id = ? WHERE id = ?`,
1849
+ [metadata.turnId, row.id]
1850
+ );
1851
+ updated++;
1852
+ }
1853
+ } catch {
1854
+ }
1855
+ }
1856
+ return updated;
1857
+ }
1858
+ /**
1859
+ * Delete all events for a session (for force reimport)
1860
+ */
1861
+ async deleteSessionEvents(sessionId) {
1862
+ await this.initialize();
1863
+ const events = sqliteAll(
1864
+ this.db,
1865
+ `SELECT id FROM events WHERE session_id = ?`,
1866
+ [sessionId]
1867
+ );
1868
+ if (events.length === 0)
1869
+ return 0;
1870
+ const eventIds = events.map((e) => e.id);
1871
+ const placeholders = eventIds.map(() => "?").join(",");
1872
+ const ftsTriggersDropped = [];
1873
+ for (const triggerName of ["events_fts_delete", "events_fts_update", "events_fts_insert"]) {
1874
+ try {
1875
+ sqliteRun(this.db, `DROP TRIGGER IF EXISTS ${triggerName}`);
1876
+ ftsTriggersDropped.push(triggerName);
1877
+ } catch {
1878
+ }
1879
+ }
1880
+ for (const table of ["event_dedup", "memory_levels", "embedding_queue", "embedding_outbox", "vector_outbox"]) {
1881
+ try {
1882
+ sqliteRun(this.db, `DELETE FROM ${table} WHERE event_id IN (${placeholders})`, eventIds);
1883
+ } catch {
1884
+ }
1885
+ }
1886
+ const result = sqliteRun(this.db, `DELETE FROM events WHERE session_id = ?`, [sessionId]);
1887
+ if (ftsTriggersDropped.length > 0) {
1888
+ try {
1889
+ sqliteRun(this.db, `INSERT INTO events_fts(events_fts) VALUES('rebuild')`);
1890
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
1891
+ INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
1892
+ END`);
1893
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
1894
+ INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
1895
+ END`);
1896
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
1897
+ INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
1898
+ INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
1899
+ END`);
1900
+ } catch {
1901
+ }
1902
+ }
1903
+ return result.changes || 0;
1904
+ }
1488
1905
  /**
1489
1906
  * Convert database row to MemoryEvent
1490
1907
  */
@@ -1505,6 +1922,9 @@ var SQLiteEventStore = class {
1505
1922
  if (row.last_accessed_at !== void 0) {
1506
1923
  event.last_accessed_at = row.last_accessed_at;
1507
1924
  }
1925
+ if (row.turn_id !== void 0 && row.turn_id !== null) {
1926
+ event.turn_id = row.turn_id;
1927
+ }
1508
1928
  return event;
1509
1929
  }
1510
1930
  };
@@ -1716,7 +2136,16 @@ var VectorStore = class {
1716
2136
  metadata: JSON.stringify(record.metadata || {})
1717
2137
  };
1718
2138
  if (!this.table) {
1719
- this.table = await this.db.createTable(this.tableName, [data]);
2139
+ try {
2140
+ this.table = await this.db.createTable(this.tableName, [data]);
2141
+ } catch (e) {
2142
+ if (e?.message?.includes("already exists")) {
2143
+ this.table = await this.db.openTable(this.tableName);
2144
+ await this.table.add([data]);
2145
+ } else {
2146
+ throw e;
2147
+ }
2148
+ }
1720
2149
  } else {
1721
2150
  await this.table.add([data]);
1722
2151
  }
@@ -1742,7 +2171,16 @@ var VectorStore = class {
1742
2171
  metadata: JSON.stringify(record.metadata || {})
1743
2172
  }));
1744
2173
  if (!this.table) {
1745
- this.table = await this.db.createTable(this.tableName, data);
2174
+ try {
2175
+ this.table = await this.db.createTable(this.tableName, data);
2176
+ } catch (e) {
2177
+ if (e?.message?.includes("already exists")) {
2178
+ this.table = await this.db.openTable(this.tableName);
2179
+ await this.table.add(data);
2180
+ } else {
2181
+ throw e;
2182
+ }
2183
+ }
1746
2184
  } else {
1747
2185
  await this.table.add(data);
1748
2186
  }
@@ -4488,7 +4926,7 @@ function createGraduationWorker(eventStore, graduation, config) {
4488
4926
  function normalizePath(projectPath) {
4489
4927
  const expanded = projectPath.startsWith("~") ? path.join(os.homedir(), projectPath.slice(1)) : projectPath;
4490
4928
  try {
4491
- return fs.realpathSync(expanded);
4929
+ return fs2.realpathSync(expanded);
4492
4930
  } catch {
4493
4931
  return path.resolve(expanded);
4494
4932
  }
@@ -4505,8 +4943,8 @@ var REGISTRY_PATH = path.join(os.homedir(), ".claude-code", "memory", "session-r
4505
4943
  var SHARED_STORAGE_PATH = path.join(os.homedir(), ".claude-code", "memory", "shared");
4506
4944
  function loadSessionRegistry() {
4507
4945
  try {
4508
- if (fs.existsSync(REGISTRY_PATH)) {
4509
- const data = fs.readFileSync(REGISTRY_PATH, "utf-8");
4946
+ if (fs2.existsSync(REGISTRY_PATH)) {
4947
+ const data = fs2.readFileSync(REGISTRY_PATH, "utf-8");
4510
4948
  return JSON.parse(data);
4511
4949
  }
4512
4950
  } catch (error) {
@@ -4516,12 +4954,12 @@ function loadSessionRegistry() {
4516
4954
  }
4517
4955
  function saveSessionRegistry(registry) {
4518
4956
  const dir = path.dirname(REGISTRY_PATH);
4519
- if (!fs.existsSync(dir)) {
4520
- fs.mkdirSync(dir, { recursive: true });
4957
+ if (!fs2.existsSync(dir)) {
4958
+ fs2.mkdirSync(dir, { recursive: true });
4521
4959
  }
4522
4960
  const tempPath = REGISTRY_PATH + ".tmp";
4523
- fs.writeFileSync(tempPath, JSON.stringify(registry, null, 2));
4524
- fs.renameSync(tempPath, REGISTRY_PATH);
4961
+ fs2.writeFileSync(tempPath, JSON.stringify(registry, null, 2));
4962
+ fs2.renameSync(tempPath, REGISTRY_PATH);
4525
4963
  }
4526
4964
  function registerSession(sessionId, projectPath) {
4527
4965
  const registry = loadSessionRegistry();
@@ -4571,11 +5009,13 @@ var MemoryService = class {
4571
5009
  sharedStoreConfig = null;
4572
5010
  projectHash = null;
4573
5011
  readOnly;
5012
+ lightweightMode;
4574
5013
  constructor(config) {
4575
5014
  const storagePath = this.expandPath(config.storagePath);
4576
5015
  this.readOnly = config.readOnly ?? false;
4577
- if (!this.readOnly && !fs.existsSync(storagePath)) {
4578
- fs.mkdirSync(storagePath, { recursive: true });
5016
+ this.lightweightMode = config.lightweightMode ?? false;
5017
+ if (!this.readOnly && !fs2.existsSync(storagePath)) {
5018
+ fs2.mkdirSync(storagePath, { recursive: true });
4579
5019
  }
4580
5020
  this.projectHash = config.projectHash || null;
4581
5021
  this.sharedStoreConfig = config.sharedStoreConfig ?? { enabled: true };
@@ -4620,6 +5060,10 @@ var MemoryService = class {
4620
5060
  if (this.initialized)
4621
5061
  return;
4622
5062
  await this.sqliteStore.initialize();
5063
+ if (this.lightweightMode) {
5064
+ this.initialized = true;
5065
+ return;
5066
+ }
4623
5067
  if (this.analyticsStore) {
4624
5068
  try {
4625
5069
  await this.analyticsStore.initialize();
@@ -4666,8 +5110,8 @@ var MemoryService = class {
4666
5110
  */
4667
5111
  async initializeSharedStore() {
4668
5112
  const sharedPath = this.sharedStoreConfig?.sharedStoragePath ? this.expandPath(this.sharedStoreConfig.sharedStoragePath) : SHARED_STORAGE_PATH;
4669
- if (!fs.existsSync(sharedPath)) {
4670
- fs.mkdirSync(sharedPath, { recursive: true });
5113
+ if (!fs2.existsSync(sharedPath)) {
5114
+ fs2.mkdirSync(sharedPath, { recursive: true });
4671
5115
  }
4672
5116
  this.sharedEventStore = createSharedEventStore(
4673
5117
  path.join(sharedPath, "shared.duckdb")
@@ -4764,6 +5208,7 @@ var MemoryService = class {
4764
5208
  async storeToolObservation(sessionId, payload) {
4765
5209
  await this.initialize();
4766
5210
  const content = JSON.stringify(payload);
5211
+ const turnId = payload.metadata?.turnId;
4767
5212
  const result = await this.sqliteStore.append({
4768
5213
  eventType: "tool_observation",
4769
5214
  sessionId,
@@ -4771,7 +5216,8 @@ var MemoryService = class {
4771
5216
  content,
4772
5217
  metadata: {
4773
5218
  toolName: payload.toolName,
4774
- success: payload.success
5219
+ success: payload.success,
5220
+ ...turnId ? { turnId } : {}
4775
5221
  }
4776
5222
  });
4777
5223
  if (result.success && !result.isDuplicate) {
@@ -4789,9 +5235,6 @@ var MemoryService = class {
4789
5235
  */
4790
5236
  async retrieveMemories(query, options) {
4791
5237
  await this.initialize();
4792
- if (this.vectorWorker) {
4793
- await this.vectorWorker.processAll();
4794
- }
4795
5238
  if (options?.includeShared && this.sharedStore) {
4796
5239
  return this.retriever.retrieveUnified(query, {
4797
5240
  ...options,
@@ -4801,6 +5244,29 @@ var MemoryService = class {
4801
5244
  }
4802
5245
  return this.retriever.retrieve(query, options);
4803
5246
  }
5247
+ /**
5248
+ * Fast keyword search using SQLite FTS5
5249
+ * Much faster than vector search - no embedding model needed
5250
+ */
5251
+ async keywordSearch(query, options) {
5252
+ await this.initialize();
5253
+ const results = await this.sqliteStore.keywordSearch(query, options?.topK ?? 10);
5254
+ const maxRank = Math.min(...results.map((r) => r.rank), -1e-3);
5255
+ const minRank = Math.max(...results.map((r) => r.rank), -1e3);
5256
+ const rankRange = maxRank - minRank || 1;
5257
+ return results.map((r) => ({
5258
+ event: r.event,
5259
+ score: 1 - (r.rank - minRank) / rankRange
5260
+ // Normalize to 0-1
5261
+ })).filter((r) => !options?.minScore || r.score >= options.minScore);
5262
+ }
5263
+ /**
5264
+ * Rebuild FTS index (call after database upgrade)
5265
+ */
5266
+ async rebuildFtsIndex() {
5267
+ await this.initialize();
5268
+ return this.sqliteStore.rebuildFtsIndex();
5269
+ }
4804
5270
  /**
4805
5271
  * Get session history
4806
5272
  */
@@ -5034,6 +5500,31 @@ var MemoryService = class {
5034
5500
  return [];
5035
5501
  return this.consolidatedStore.getAll({ limit });
5036
5502
  }
5503
+ /**
5504
+ * Extract topic keywords from event content (markdown headings and key terms)
5505
+ */
5506
+ extractTopicsFromContent(content) {
5507
+ const topics = /* @__PURE__ */ new Set();
5508
+ const headings = content.match(/^#{1,3}\s+(.+)$/gm);
5509
+ if (headings) {
5510
+ for (const h of headings.slice(0, 5)) {
5511
+ const text = h.replace(/^#+\s+/, "").replace(/[*_`#]/g, "").trim();
5512
+ if (text.length > 2 && text.length < 50) {
5513
+ topics.add(text);
5514
+ }
5515
+ }
5516
+ }
5517
+ const boldTerms = content.match(/\*\*([^*]+)\*\*/g);
5518
+ if (boldTerms) {
5519
+ for (const b of boldTerms.slice(0, 5)) {
5520
+ const text = b.replace(/\*\*/g, "").trim();
5521
+ if (text.length > 2 && text.length < 30) {
5522
+ topics.add(text);
5523
+ }
5524
+ }
5525
+ }
5526
+ return Array.from(topics).slice(0, 5);
5527
+ }
5037
5528
  /**
5038
5529
  * Increment access count for memories that were used in prompts
5039
5530
  */
@@ -5057,8 +5548,7 @@ var MemoryService = class {
5057
5548
  return events.map((event) => ({
5058
5549
  memoryId: event.id,
5059
5550
  summary: event.content.substring(0, 200) + (event.content.length > 200 ? "..." : ""),
5060
- topics: [],
5061
- // Could extract topics from content if needed
5551
+ topics: this.extractTopicsFromContent(event.content),
5062
5552
  accessCount: event.access_count || 0,
5063
5553
  lastAccessed: event.last_accessed_at || null,
5064
5554
  confidence: 1,
@@ -5079,6 +5569,34 @@ var MemoryService = class {
5079
5569
  }
5080
5570
  return [];
5081
5571
  }
5572
+ /**
5573
+ * Record a memory retrieval for helpfulness tracking
5574
+ */
5575
+ async recordRetrieval(eventId, sessionId, score, query) {
5576
+ await this.initialize();
5577
+ await this.sqliteStore.recordRetrieval(eventId, sessionId, score, query);
5578
+ }
5579
+ /**
5580
+ * Evaluate helpfulness of retrievals in a session (called at session end)
5581
+ */
5582
+ async evaluateSessionHelpfulness(sessionId) {
5583
+ await this.initialize();
5584
+ await this.sqliteStore.evaluateSessionHelpfulness(sessionId);
5585
+ }
5586
+ /**
5587
+ * Get most helpful memories ranked by helpfulness score
5588
+ */
5589
+ async getHelpfulMemories(limit = 10) {
5590
+ await this.initialize();
5591
+ return this.sqliteStore.getHelpfulMemories(limit);
5592
+ }
5593
+ /**
5594
+ * Get helpfulness statistics for dashboard
5595
+ */
5596
+ async getHelpfulnessStats() {
5597
+ await this.initialize();
5598
+ return this.sqliteStore.getHelpfulnessStats();
5599
+ }
5082
5600
  /**
5083
5601
  * Mark a consolidated memory as accessed
5084
5602
  */
@@ -5142,6 +5660,44 @@ var MemoryService = class {
5142
5660
  lastConsolidation
5143
5661
  };
5144
5662
  }
5663
+ // ============================================================
5664
+ // Turn Grouping Methods
5665
+ // ============================================================
5666
+ /**
5667
+ * Get events grouped by turn for a session
5668
+ */
5669
+ async getSessionTurns(sessionId, options) {
5670
+ await this.initialize();
5671
+ return this.sqliteStore.getSessionTurns(sessionId, options);
5672
+ }
5673
+ /**
5674
+ * Get all events for a specific turn
5675
+ */
5676
+ async getEventsByTurn(turnId) {
5677
+ await this.initialize();
5678
+ return this.sqliteStore.getEventsByTurn(turnId);
5679
+ }
5680
+ /**
5681
+ * Count total turns for a session
5682
+ */
5683
+ async countSessionTurns(sessionId) {
5684
+ await this.initialize();
5685
+ return this.sqliteStore.countSessionTurns(sessionId);
5686
+ }
5687
+ /**
5688
+ * Backfill turn_ids from metadata for events stored before the migration
5689
+ */
5690
+ async backfillTurnIds() {
5691
+ await this.initialize();
5692
+ return this.sqliteStore.backfillTurnIds();
5693
+ }
5694
+ /**
5695
+ * Delete all events for a session (for force reimport)
5696
+ */
5697
+ async deleteSessionEvents(sessionId) {
5698
+ await this.initialize();
5699
+ return this.sqliteStore.deleteSessionEvents(sessionId);
5700
+ }
5145
5701
  /**
5146
5702
  * Format Endless Mode context for Claude
5147
5703
  */
@@ -5269,6 +5825,22 @@ function getMemoryServiceForSession(sessionId) {
5269
5825
  }
5270
5826
  return getDefaultMemoryService();
5271
5827
  }
5828
+ function getLightweightMemoryService(sessionId) {
5829
+ const projectInfo = getSessionProject(sessionId);
5830
+ const key = projectInfo ? `lightweight_${projectInfo.projectHash}` : "lightweight_global";
5831
+ if (!serviceCache.has(key)) {
5832
+ const storagePath = projectInfo ? getProjectStoragePath(projectInfo.projectPath) : path.join(os.homedir(), ".claude-code", "memory");
5833
+ serviceCache.set(key, new MemoryService({
5834
+ storagePath,
5835
+ projectHash: projectInfo?.projectHash,
5836
+ lightweightMode: true,
5837
+ // Skip embedder/vector/workers
5838
+ analyticsEnabled: false,
5839
+ sharedStoreConfig: { enabled: false }
5840
+ }));
5841
+ }
5842
+ return serviceCache.get(key);
5843
+ }
5272
5844
  function createMemoryService(config) {
5273
5845
  return new MemoryService(config);
5274
5846
  }
@@ -5276,12 +5848,14 @@ export {
5276
5848
  MemoryService,
5277
5849
  createMemoryService,
5278
5850
  getDefaultMemoryService,
5851
+ getLightweightMemoryService,
5279
5852
  getMemoryServiceForProject,
5280
5853
  getMemoryServiceForSession,
5281
5854
  getProjectStoragePath,
5282
5855
  getReadOnlyMemoryService,
5283
5856
  getSessionProject,
5284
5857
  hashProjectPath,
5858
+ loadSessionRegistry,
5285
5859
  registerSession
5286
5860
  };
5287
5861
  //# sourceMappingURL=memory-service.js.map