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
@@ -9,7 +9,7 @@ const __dirname = dirname(__filename);
9
9
  // src/services/memory-service.ts
10
10
  import * as path from "path";
11
11
  import * as os from "os";
12
- import * as fs from "fs";
12
+ import * as fs2 from "fs";
13
13
  import * as crypto2 from "crypto";
14
14
 
15
15
  // src/core/event-store.ts
@@ -741,7 +741,13 @@ import { randomUUID as randomUUID2 } from "crypto";
741
741
 
742
742
  // src/core/sqlite-wrapper.ts
743
743
  import Database from "better-sqlite3";
744
+ import * as fs from "fs";
745
+ import * as nodePath from "path";
744
746
  function createSQLiteDatabase(path2, options) {
747
+ const dir = nodePath.dirname(path2);
748
+ if (!fs.existsSync(dir)) {
749
+ fs.mkdirSync(dir, { recursive: true });
750
+ }
745
751
  const db = new Database(path2, {
746
752
  readonly: options?.readonly ?? false
747
753
  });
@@ -1009,6 +1015,23 @@ var SQLiteEventStore = class {
1009
1015
  updated_at TEXT DEFAULT (datetime('now'))
1010
1016
  );
1011
1017
 
1018
+ -- Memory Helpfulness tracking
1019
+ CREATE TABLE IF NOT EXISTS memory_helpfulness (
1020
+ id TEXT PRIMARY KEY,
1021
+ event_id TEXT NOT NULL,
1022
+ session_id TEXT NOT NULL,
1023
+ retrieval_score REAL DEFAULT 0,
1024
+ query_preview TEXT,
1025
+ session_continued INTEGER DEFAULT 0,
1026
+ prompt_count_after INTEGER DEFAULT 0,
1027
+ tool_success_count INTEGER DEFAULT 0,
1028
+ tool_total_count INTEGER DEFAULT 0,
1029
+ was_reasked INTEGER DEFAULT 0,
1030
+ helpfulness_score REAL DEFAULT 0.5,
1031
+ created_at TEXT DEFAULT (datetime('now')),
1032
+ measured_at TEXT
1033
+ );
1034
+
1012
1035
  -- Sync position tracking (for SQLite -> DuckDB sync)
1013
1036
  CREATE TABLE IF NOT EXISTS sync_positions (
1014
1037
  target_name TEXT PRIMARY KEY,
@@ -1034,6 +1057,31 @@ var SQLiteEventStore = class {
1034
1057
  CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence);
1035
1058
  CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at);
1036
1059
  CREATE INDEX IF NOT EXISTS idx_embedding_outbox_status ON embedding_outbox(status);
1060
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_event ON memory_helpfulness(event_id);
1061
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_session ON memory_helpfulness(session_id);
1062
+ CREATE INDEX IF NOT EXISTS idx_helpfulness_score ON memory_helpfulness(helpfulness_score DESC);
1063
+
1064
+ -- FTS5 Full-Text Search for fast keyword search
1065
+ CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
1066
+ content,
1067
+ event_id UNINDEXED,
1068
+ content='events',
1069
+ content_rowid='rowid'
1070
+ );
1071
+
1072
+ -- Triggers to keep FTS in sync with events table
1073
+ CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
1074
+ INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
1075
+ END;
1076
+
1077
+ CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
1078
+ INSERT INTO events_fts(events_fts, rowid, content, event_id) VALUES('delete', OLD.rowid, OLD.content, OLD.id);
1079
+ END;
1080
+
1081
+ CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
1082
+ INSERT INTO events_fts(events_fts, rowid, content, event_id) VALUES('delete', OLD.rowid, OLD.content, OLD.id);
1083
+ INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
1084
+ END;
1037
1085
  `);
1038
1086
  const tableInfo = sqliteAll(this.db, "PRAGMA table_info(events)", []);
1039
1087
  const columnNames = tableInfo.map((col) => col.name);
@@ -1055,6 +1103,15 @@ var SQLiteEventStore = class {
1055
1103
  console.error("Error adding last_accessed_at column:", err);
1056
1104
  }
1057
1105
  }
1106
+ if (!columnNames.includes("turn_id")) {
1107
+ try {
1108
+ sqliteExec(this.db, `
1109
+ ALTER TABLE events ADD COLUMN turn_id TEXT;
1110
+ `);
1111
+ } catch (err) {
1112
+ console.error("Error adding turn_id column:", err);
1113
+ }
1114
+ }
1058
1115
  try {
1059
1116
  sqliteExec(this.db, `
1060
1117
  CREATE INDEX IF NOT EXISTS idx_events_access_count ON events(access_count DESC);
@@ -1067,6 +1124,12 @@ var SQLiteEventStore = class {
1067
1124
  `);
1068
1125
  } catch (err) {
1069
1126
  }
1127
+ try {
1128
+ sqliteExec(this.db, `
1129
+ CREATE INDEX IF NOT EXISTS idx_events_turn_id ON events(turn_id);
1130
+ `);
1131
+ } catch (err) {
1132
+ }
1070
1133
  this.initialized = true;
1071
1134
  }
1072
1135
  /**
@@ -1091,9 +1154,11 @@ var SQLiteEventStore = class {
1091
1154
  const id = randomUUID2();
1092
1155
  const timestamp = toSQLiteTimestamp(input.timestamp);
1093
1156
  try {
1157
+ const metadata = input.metadata || {};
1158
+ const turnId = metadata.turnId || null;
1094
1159
  const insertEvent = this.db.prepare(`
1095
- INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
1096
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1160
+ INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata, turn_id)
1161
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1097
1162
  `);
1098
1163
  const insertDedup = this.db.prepare(`
1099
1164
  INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)
@@ -1110,7 +1175,8 @@ var SQLiteEventStore = class {
1110
1175
  input.content,
1111
1176
  canonicalKey,
1112
1177
  dedupeKey,
1113
- JSON.stringify(input.metadata || {})
1178
+ JSON.stringify(metadata),
1179
+ turnId
1114
1180
  );
1115
1181
  insertDedup.run(dedupeKey, id);
1116
1182
  insertLevel.run(id);
@@ -1460,11 +1526,11 @@ var SQLiteEventStore = class {
1460
1526
  );
1461
1527
  }
1462
1528
  /**
1463
- * Get most accessed memories
1529
+ * Get most accessed memories (falls back to recent events if none accessed)
1464
1530
  */
1465
1531
  async getMostAccessed(limit = 10) {
1466
1532
  await this.initialize();
1467
- const rows = sqliteAll(
1533
+ let rows = sqliteAll(
1468
1534
  this.db,
1469
1535
  `SELECT * FROM events
1470
1536
  WHERE access_count > 0
@@ -1472,8 +1538,222 @@ var SQLiteEventStore = class {
1472
1538
  LIMIT ?`,
1473
1539
  [limit]
1474
1540
  );
1541
+ if (rows.length === 0) {
1542
+ rows = sqliteAll(
1543
+ this.db,
1544
+ `SELECT * FROM events
1545
+ ORDER BY timestamp DESC
1546
+ LIMIT ?`,
1547
+ [limit]
1548
+ );
1549
+ }
1475
1550
  return rows.map((row) => this.rowToEvent(row));
1476
1551
  }
1552
+ /**
1553
+ * Record a memory retrieval for helpfulness tracking
1554
+ */
1555
+ async recordRetrieval(eventId, sessionId, score, query) {
1556
+ if (this.readOnly)
1557
+ return;
1558
+ await this.initialize();
1559
+ const id = randomUUID2();
1560
+ sqliteRun(
1561
+ this.db,
1562
+ `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
1563
+ VALUES (?, ?, ?, ?, ?, datetime('now'))`,
1564
+ [id, eventId, sessionId, score, query.slice(0, 100)]
1565
+ );
1566
+ }
1567
+ /**
1568
+ * Evaluate helpfulness for all retrievals in a session
1569
+ * Called at session end - uses behavioral signals to compute score
1570
+ */
1571
+ async evaluateSessionHelpfulness(sessionId) {
1572
+ if (this.readOnly)
1573
+ return;
1574
+ await this.initialize();
1575
+ const retrievals = sqliteAll(
1576
+ this.db,
1577
+ `SELECT * FROM memory_helpfulness WHERE session_id = ? AND measured_at IS NULL`,
1578
+ [sessionId]
1579
+ );
1580
+ if (retrievals.length === 0)
1581
+ return;
1582
+ const sessionEvents = sqliteAll(
1583
+ this.db,
1584
+ `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
1585
+ [sessionId]
1586
+ );
1587
+ const promptEvents = sessionEvents.filter((e) => e.event_type === "user_prompt");
1588
+ const toolEvents = sessionEvents.filter((e) => e.event_type === "tool_observation");
1589
+ let toolSuccessCount = 0;
1590
+ let toolTotalCount = toolEvents.length;
1591
+ for (const t of toolEvents) {
1592
+ try {
1593
+ const content = JSON.parse(t.content);
1594
+ if (content.success !== false)
1595
+ toolSuccessCount++;
1596
+ } catch {
1597
+ toolSuccessCount++;
1598
+ }
1599
+ }
1600
+ const toolSuccessRatio = toolTotalCount > 0 ? toolSuccessCount / toolTotalCount : 0.5;
1601
+ for (const retrieval of retrievals) {
1602
+ const retrievalTime = retrieval.created_at;
1603
+ const eventsAfter = sessionEvents.filter((e) => e.timestamp > retrievalTime);
1604
+ const sessionContinued = eventsAfter.length > 0 ? 1 : 0;
1605
+ const promptsAfter = promptEvents.filter((e) => e.timestamp > retrievalTime);
1606
+ const promptCountAfter = promptsAfter.length;
1607
+ const queryWords = new Set((retrieval.query_preview || "").toLowerCase().split(/\s+/).filter((w) => w.length > 2));
1608
+ let wasReasked = 0;
1609
+ for (const p of promptsAfter) {
1610
+ const pWords = new Set(p.content.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
1611
+ let overlap = 0;
1612
+ for (const w of queryWords) {
1613
+ if (pWords.has(w))
1614
+ overlap++;
1615
+ }
1616
+ if (queryWords.size > 0 && overlap / queryWords.size > 0.5) {
1617
+ wasReasked = 1;
1618
+ break;
1619
+ }
1620
+ }
1621
+ const retrievalScore = retrieval.retrieval_score || 0;
1622
+ const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
1623
+ sqliteRun(
1624
+ this.db,
1625
+ `UPDATE memory_helpfulness
1626
+ SET session_continued = ?, prompt_count_after = ?,
1627
+ tool_success_count = ?, tool_total_count = ?,
1628
+ was_reasked = ?, helpfulness_score = ?,
1629
+ measured_at = datetime('now')
1630
+ WHERE id = ?`,
1631
+ [
1632
+ sessionContinued,
1633
+ promptCountAfter,
1634
+ toolSuccessCount,
1635
+ toolTotalCount,
1636
+ wasReasked,
1637
+ helpfulnessScore,
1638
+ retrieval.id
1639
+ ]
1640
+ );
1641
+ }
1642
+ }
1643
+ /**
1644
+ * Get most helpful memories ranked by helpfulness score
1645
+ */
1646
+ async getHelpfulMemories(limit = 10) {
1647
+ await this.initialize();
1648
+ const rows = sqliteAll(
1649
+ this.db,
1650
+ `SELECT
1651
+ mh.event_id,
1652
+ AVG(mh.helpfulness_score) as avg_score,
1653
+ COUNT(*) as eval_count,
1654
+ e.content,
1655
+ e.access_count
1656
+ FROM memory_helpfulness mh
1657
+ JOIN events e ON e.id = mh.event_id
1658
+ WHERE mh.measured_at IS NOT NULL
1659
+ GROUP BY mh.event_id
1660
+ ORDER BY avg_score DESC
1661
+ LIMIT ?`,
1662
+ [limit]
1663
+ );
1664
+ return rows.map((r) => ({
1665
+ eventId: r.event_id,
1666
+ summary: r.content.substring(0, 200) + (r.content.length > 200 ? "..." : ""),
1667
+ helpfulnessScore: Math.round(r.avg_score * 100) / 100,
1668
+ accessCount: r.access_count || 0,
1669
+ evaluationCount: r.eval_count
1670
+ }));
1671
+ }
1672
+ /**
1673
+ * Get helpfulness statistics for dashboard
1674
+ */
1675
+ async getHelpfulnessStats() {
1676
+ await this.initialize();
1677
+ const stats = sqliteGet(
1678
+ this.db,
1679
+ `SELECT
1680
+ AVG(helpfulness_score) as avg_score,
1681
+ COUNT(*) as total_evaluated,
1682
+ SUM(CASE WHEN helpfulness_score >= 0.7 THEN 1 ELSE 0 END) as helpful,
1683
+ SUM(CASE WHEN helpfulness_score >= 0.4 AND helpfulness_score < 0.7 THEN 1 ELSE 0 END) as neutral,
1684
+ SUM(CASE WHEN helpfulness_score < 0.4 THEN 1 ELSE 0 END) as unhelpful
1685
+ FROM memory_helpfulness
1686
+ WHERE measured_at IS NOT NULL`
1687
+ );
1688
+ const totalRow = sqliteGet(
1689
+ this.db,
1690
+ `SELECT COUNT(*) as total FROM memory_helpfulness`
1691
+ );
1692
+ return {
1693
+ avgScore: Math.round((stats?.avg_score || 0) * 100) / 100,
1694
+ totalEvaluated: stats?.total_evaluated || 0,
1695
+ totalRetrievals: totalRow?.total || 0,
1696
+ helpful: stats?.helpful || 0,
1697
+ neutral: stats?.neutral || 0,
1698
+ unhelpful: stats?.unhelpful || 0
1699
+ };
1700
+ }
1701
+ /**
1702
+ * Fast keyword search using FTS5
1703
+ * Returns events matching the search query, ranked by relevance
1704
+ */
1705
+ async keywordSearch(query, limit = 10) {
1706
+ await this.initialize();
1707
+ const searchTerms = query.replace(/['"(){}[\]^~*?:\\/-]/g, " ").split(/\s+/).filter((term) => term.length > 1).map((term) => `"${term}"*`).join(" OR ");
1708
+ if (!searchTerms) {
1709
+ return [];
1710
+ }
1711
+ try {
1712
+ const rows = sqliteAll(
1713
+ this.db,
1714
+ `SELECT e.*, fts.rank
1715
+ FROM events_fts fts
1716
+ JOIN events e ON e.id = fts.event_id
1717
+ WHERE events_fts MATCH ?
1718
+ ORDER BY fts.rank
1719
+ LIMIT ?`,
1720
+ [searchTerms, limit]
1721
+ );
1722
+ return rows.map((row) => ({
1723
+ event: this.rowToEvent(row),
1724
+ rank: row.rank
1725
+ }));
1726
+ } catch (error) {
1727
+ const likePattern = `%${query}%`;
1728
+ const rows = sqliteAll(
1729
+ this.db,
1730
+ `SELECT *, 0 as rank FROM events
1731
+ WHERE content LIKE ?
1732
+ ORDER BY timestamp DESC
1733
+ LIMIT ?`,
1734
+ [likePattern, limit]
1735
+ );
1736
+ return rows.map((row) => ({
1737
+ event: this.rowToEvent(row),
1738
+ rank: 0
1739
+ }));
1740
+ }
1741
+ }
1742
+ /**
1743
+ * Rebuild FTS index from existing events
1744
+ * Call this once after upgrading to FTS5
1745
+ */
1746
+ async rebuildFtsIndex() {
1747
+ await this.initialize();
1748
+ const countRow = sqliteGet(this.db, "SELECT COUNT(*) as count FROM events", []);
1749
+ const totalEvents = countRow?.count ?? 0;
1750
+ sqliteExec(this.db, `
1751
+ DELETE FROM events_fts;
1752
+ INSERT INTO events_fts(rowid, content, event_id)
1753
+ SELECT rowid, content, id FROM events;
1754
+ `);
1755
+ return totalEvents;
1756
+ }
1477
1757
  /**
1478
1758
  * Get database instance for direct access
1479
1759
  */
@@ -1486,6 +1766,143 @@ var SQLiteEventStore = class {
1486
1766
  async close() {
1487
1767
  sqliteClose(this.db);
1488
1768
  }
1769
+ /**
1770
+ * Get events grouped by turn_id for a session
1771
+ * Returns turns ordered by first event timestamp (newest first)
1772
+ */
1773
+ async getSessionTurns(sessionId, options) {
1774
+ await this.initialize();
1775
+ const limit = options?.limit || 20;
1776
+ const offset = options?.offset || 0;
1777
+ const turnRows = sqliteAll(
1778
+ this.db,
1779
+ `SELECT turn_id, MIN(timestamp) as min_ts
1780
+ FROM events
1781
+ WHERE session_id = ? AND turn_id IS NOT NULL
1782
+ GROUP BY turn_id
1783
+ ORDER BY min_ts DESC
1784
+ LIMIT ? OFFSET ?`,
1785
+ [sessionId, limit, offset]
1786
+ );
1787
+ const turns = [];
1788
+ for (const turnRow of turnRows) {
1789
+ const events = await this.getEventsByTurn(turnRow.turn_id);
1790
+ const promptEvent = events.find((e) => e.eventType === "user_prompt");
1791
+ const toolEvents = events.filter((e) => e.eventType === "tool_observation");
1792
+ const hasResponse = events.some((e) => e.eventType === "agent_response");
1793
+ turns.push({
1794
+ turnId: turnRow.turn_id,
1795
+ events,
1796
+ startedAt: toDateFromSQLite(turnRow.min_ts),
1797
+ promptPreview: promptEvent ? promptEvent.content.slice(0, 200) + (promptEvent.content.length > 200 ? "..." : "") : "(no prompt)",
1798
+ eventCount: events.length,
1799
+ toolCount: toolEvents.length,
1800
+ hasResponse
1801
+ });
1802
+ }
1803
+ return turns;
1804
+ }
1805
+ /**
1806
+ * Get all events for a specific turn_id
1807
+ */
1808
+ async getEventsByTurn(turnId) {
1809
+ await this.initialize();
1810
+ const rows = sqliteAll(
1811
+ this.db,
1812
+ `SELECT * FROM events WHERE turn_id = ? ORDER BY timestamp ASC`,
1813
+ [turnId]
1814
+ );
1815
+ return rows.map(this.rowToEvent);
1816
+ }
1817
+ /**
1818
+ * Count total turns for a session
1819
+ */
1820
+ async countSessionTurns(sessionId) {
1821
+ await this.initialize();
1822
+ const row = sqliteGet(
1823
+ this.db,
1824
+ `SELECT COUNT(DISTINCT turn_id) as count
1825
+ FROM events
1826
+ WHERE session_id = ? AND turn_id IS NOT NULL`,
1827
+ [sessionId]
1828
+ );
1829
+ return row?.count || 0;
1830
+ }
1831
+ /**
1832
+ * Migrate existing events: backfill turn_id for events that have turnId in metadata
1833
+ * but no turn_id column value (for events stored before this migration)
1834
+ */
1835
+ async backfillTurnIds() {
1836
+ await this.initialize();
1837
+ const rows = sqliteAll(
1838
+ this.db,
1839
+ `SELECT id, metadata FROM events
1840
+ WHERE turn_id IS NULL AND metadata IS NOT NULL AND metadata LIKE '%turnId%'`
1841
+ );
1842
+ let updated = 0;
1843
+ for (const row of rows) {
1844
+ try {
1845
+ const metadata = JSON.parse(row.metadata);
1846
+ if (metadata.turnId) {
1847
+ sqliteRun(
1848
+ this.db,
1849
+ `UPDATE events SET turn_id = ? WHERE id = ?`,
1850
+ [metadata.turnId, row.id]
1851
+ );
1852
+ updated++;
1853
+ }
1854
+ } catch {
1855
+ }
1856
+ }
1857
+ return updated;
1858
+ }
1859
+ /**
1860
+ * Delete all events for a session (for force reimport)
1861
+ */
1862
+ async deleteSessionEvents(sessionId) {
1863
+ await this.initialize();
1864
+ const events = sqliteAll(
1865
+ this.db,
1866
+ `SELECT id FROM events WHERE session_id = ?`,
1867
+ [sessionId]
1868
+ );
1869
+ if (events.length === 0)
1870
+ return 0;
1871
+ const eventIds = events.map((e) => e.id);
1872
+ const placeholders = eventIds.map(() => "?").join(",");
1873
+ const ftsTriggersDropped = [];
1874
+ for (const triggerName of ["events_fts_delete", "events_fts_update", "events_fts_insert"]) {
1875
+ try {
1876
+ sqliteRun(this.db, `DROP TRIGGER IF EXISTS ${triggerName}`);
1877
+ ftsTriggersDropped.push(triggerName);
1878
+ } catch {
1879
+ }
1880
+ }
1881
+ for (const table of ["event_dedup", "memory_levels", "embedding_queue", "embedding_outbox", "vector_outbox"]) {
1882
+ try {
1883
+ sqliteRun(this.db, `DELETE FROM ${table} WHERE event_id IN (${placeholders})`, eventIds);
1884
+ } catch {
1885
+ }
1886
+ }
1887
+ const result = sqliteRun(this.db, `DELETE FROM events WHERE session_id = ?`, [sessionId]);
1888
+ if (ftsTriggersDropped.length > 0) {
1889
+ try {
1890
+ sqliteRun(this.db, `INSERT INTO events_fts(events_fts) VALUES('rebuild')`);
1891
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
1892
+ INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
1893
+ END`);
1894
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
1895
+ INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
1896
+ END`);
1897
+ sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
1898
+ INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
1899
+ INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
1900
+ END`);
1901
+ } catch {
1902
+ }
1903
+ }
1904
+ return result.changes || 0;
1905
+ }
1489
1906
  /**
1490
1907
  * Convert database row to MemoryEvent
1491
1908
  */
@@ -1506,6 +1923,9 @@ var SQLiteEventStore = class {
1506
1923
  if (row.last_accessed_at !== void 0) {
1507
1924
  event.last_accessed_at = row.last_accessed_at;
1508
1925
  }
1926
+ if (row.turn_id !== void 0 && row.turn_id !== null) {
1927
+ event.turn_id = row.turn_id;
1928
+ }
1509
1929
  return event;
1510
1930
  }
1511
1931
  };
@@ -1717,7 +2137,16 @@ var VectorStore = class {
1717
2137
  metadata: JSON.stringify(record.metadata || {})
1718
2138
  };
1719
2139
  if (!this.table) {
1720
- this.table = await this.db.createTable(this.tableName, [data]);
2140
+ try {
2141
+ this.table = await this.db.createTable(this.tableName, [data]);
2142
+ } catch (e) {
2143
+ if (e?.message?.includes("already exists")) {
2144
+ this.table = await this.db.openTable(this.tableName);
2145
+ await this.table.add([data]);
2146
+ } else {
2147
+ throw e;
2148
+ }
2149
+ }
1721
2150
  } else {
1722
2151
  await this.table.add([data]);
1723
2152
  }
@@ -1743,7 +2172,16 @@ var VectorStore = class {
1743
2172
  metadata: JSON.stringify(record.metadata || {})
1744
2173
  }));
1745
2174
  if (!this.table) {
1746
- this.table = await this.db.createTable(this.tableName, data);
2175
+ try {
2176
+ this.table = await this.db.createTable(this.tableName, data);
2177
+ } catch (e) {
2178
+ if (e?.message?.includes("already exists")) {
2179
+ this.table = await this.db.openTable(this.tableName);
2180
+ await this.table.add(data);
2181
+ } else {
2182
+ throw e;
2183
+ }
2184
+ }
1747
2185
  } else {
1748
2186
  await this.table.add(data);
1749
2187
  }
@@ -4489,7 +4927,7 @@ function createGraduationWorker(eventStore, graduation, config) {
4489
4927
  function normalizePath(projectPath) {
4490
4928
  const expanded = projectPath.startsWith("~") ? path.join(os.homedir(), projectPath.slice(1)) : projectPath;
4491
4929
  try {
4492
- return fs.realpathSync(expanded);
4930
+ return fs2.realpathSync(expanded);
4493
4931
  } catch {
4494
4932
  return path.resolve(expanded);
4495
4933
  }
@@ -4506,8 +4944,8 @@ var REGISTRY_PATH = path.join(os.homedir(), ".claude-code", "memory", "session-r
4506
4944
  var SHARED_STORAGE_PATH = path.join(os.homedir(), ".claude-code", "memory", "shared");
4507
4945
  function loadSessionRegistry() {
4508
4946
  try {
4509
- if (fs.existsSync(REGISTRY_PATH)) {
4510
- const data = fs.readFileSync(REGISTRY_PATH, "utf-8");
4947
+ if (fs2.existsSync(REGISTRY_PATH)) {
4948
+ const data = fs2.readFileSync(REGISTRY_PATH, "utf-8");
4511
4949
  return JSON.parse(data);
4512
4950
  }
4513
4951
  } catch (error) {
@@ -4547,11 +4985,13 @@ var MemoryService = class {
4547
4985
  sharedStoreConfig = null;
4548
4986
  projectHash = null;
4549
4987
  readOnly;
4988
+ lightweightMode;
4550
4989
  constructor(config) {
4551
4990
  const storagePath = this.expandPath(config.storagePath);
4552
4991
  this.readOnly = config.readOnly ?? false;
4553
- if (!this.readOnly && !fs.existsSync(storagePath)) {
4554
- fs.mkdirSync(storagePath, { recursive: true });
4992
+ this.lightweightMode = config.lightweightMode ?? false;
4993
+ if (!this.readOnly && !fs2.existsSync(storagePath)) {
4994
+ fs2.mkdirSync(storagePath, { recursive: true });
4555
4995
  }
4556
4996
  this.projectHash = config.projectHash || null;
4557
4997
  this.sharedStoreConfig = config.sharedStoreConfig ?? { enabled: true };
@@ -4596,6 +5036,10 @@ var MemoryService = class {
4596
5036
  if (this.initialized)
4597
5037
  return;
4598
5038
  await this.sqliteStore.initialize();
5039
+ if (this.lightweightMode) {
5040
+ this.initialized = true;
5041
+ return;
5042
+ }
4599
5043
  if (this.analyticsStore) {
4600
5044
  try {
4601
5045
  await this.analyticsStore.initialize();
@@ -4642,8 +5086,8 @@ var MemoryService = class {
4642
5086
  */
4643
5087
  async initializeSharedStore() {
4644
5088
  const sharedPath = this.sharedStoreConfig?.sharedStoragePath ? this.expandPath(this.sharedStoreConfig.sharedStoragePath) : SHARED_STORAGE_PATH;
4645
- if (!fs.existsSync(sharedPath)) {
4646
- fs.mkdirSync(sharedPath, { recursive: true });
5089
+ if (!fs2.existsSync(sharedPath)) {
5090
+ fs2.mkdirSync(sharedPath, { recursive: true });
4647
5091
  }
4648
5092
  this.sharedEventStore = createSharedEventStore(
4649
5093
  path.join(sharedPath, "shared.duckdb")
@@ -4740,6 +5184,7 @@ var MemoryService = class {
4740
5184
  async storeToolObservation(sessionId, payload) {
4741
5185
  await this.initialize();
4742
5186
  const content = JSON.stringify(payload);
5187
+ const turnId = payload.metadata?.turnId;
4743
5188
  const result = await this.sqliteStore.append({
4744
5189
  eventType: "tool_observation",
4745
5190
  sessionId,
@@ -4747,7 +5192,8 @@ var MemoryService = class {
4747
5192
  content,
4748
5193
  metadata: {
4749
5194
  toolName: payload.toolName,
4750
- success: payload.success
5195
+ success: payload.success,
5196
+ ...turnId ? { turnId } : {}
4751
5197
  }
4752
5198
  });
4753
5199
  if (result.success && !result.isDuplicate) {
@@ -4765,9 +5211,6 @@ var MemoryService = class {
4765
5211
  */
4766
5212
  async retrieveMemories(query, options) {
4767
5213
  await this.initialize();
4768
- if (this.vectorWorker) {
4769
- await this.vectorWorker.processAll();
4770
- }
4771
5214
  if (options?.includeShared && this.sharedStore) {
4772
5215
  return this.retriever.retrieveUnified(query, {
4773
5216
  ...options,
@@ -4777,6 +5220,29 @@ var MemoryService = class {
4777
5220
  }
4778
5221
  return this.retriever.retrieve(query, options);
4779
5222
  }
5223
+ /**
5224
+ * Fast keyword search using SQLite FTS5
5225
+ * Much faster than vector search - no embedding model needed
5226
+ */
5227
+ async keywordSearch(query, options) {
5228
+ await this.initialize();
5229
+ const results = await this.sqliteStore.keywordSearch(query, options?.topK ?? 10);
5230
+ const maxRank = Math.min(...results.map((r) => r.rank), -1e-3);
5231
+ const minRank = Math.max(...results.map((r) => r.rank), -1e3);
5232
+ const rankRange = maxRank - minRank || 1;
5233
+ return results.map((r) => ({
5234
+ event: r.event,
5235
+ score: 1 - (r.rank - minRank) / rankRange
5236
+ // Normalize to 0-1
5237
+ })).filter((r) => !options?.minScore || r.score >= options.minScore);
5238
+ }
5239
+ /**
5240
+ * Rebuild FTS index (call after database upgrade)
5241
+ */
5242
+ async rebuildFtsIndex() {
5243
+ await this.initialize();
5244
+ return this.sqliteStore.rebuildFtsIndex();
5245
+ }
4780
5246
  /**
4781
5247
  * Get session history
4782
5248
  */
@@ -5010,6 +5476,31 @@ var MemoryService = class {
5010
5476
  return [];
5011
5477
  return this.consolidatedStore.getAll({ limit });
5012
5478
  }
5479
+ /**
5480
+ * Extract topic keywords from event content (markdown headings and key terms)
5481
+ */
5482
+ extractTopicsFromContent(content) {
5483
+ const topics = /* @__PURE__ */ new Set();
5484
+ const headings = content.match(/^#{1,3}\s+(.+)$/gm);
5485
+ if (headings) {
5486
+ for (const h of headings.slice(0, 5)) {
5487
+ const text = h.replace(/^#+\s+/, "").replace(/[*_`#]/g, "").trim();
5488
+ if (text.length > 2 && text.length < 50) {
5489
+ topics.add(text);
5490
+ }
5491
+ }
5492
+ }
5493
+ const boldTerms = content.match(/\*\*([^*]+)\*\*/g);
5494
+ if (boldTerms) {
5495
+ for (const b of boldTerms.slice(0, 5)) {
5496
+ const text = b.replace(/\*\*/g, "").trim();
5497
+ if (text.length > 2 && text.length < 30) {
5498
+ topics.add(text);
5499
+ }
5500
+ }
5501
+ }
5502
+ return Array.from(topics).slice(0, 5);
5503
+ }
5013
5504
  /**
5014
5505
  * Increment access count for memories that were used in prompts
5015
5506
  */
@@ -5033,8 +5524,7 @@ var MemoryService = class {
5033
5524
  return events.map((event) => ({
5034
5525
  memoryId: event.id,
5035
5526
  summary: event.content.substring(0, 200) + (event.content.length > 200 ? "..." : ""),
5036
- topics: [],
5037
- // Could extract topics from content if needed
5527
+ topics: this.extractTopicsFromContent(event.content),
5038
5528
  accessCount: event.access_count || 0,
5039
5529
  lastAccessed: event.last_accessed_at || null,
5040
5530
  confidence: 1,
@@ -5055,6 +5545,34 @@ var MemoryService = class {
5055
5545
  }
5056
5546
  return [];
5057
5547
  }
5548
+ /**
5549
+ * Record a memory retrieval for helpfulness tracking
5550
+ */
5551
+ async recordRetrieval(eventId, sessionId, score, query) {
5552
+ await this.initialize();
5553
+ await this.sqliteStore.recordRetrieval(eventId, sessionId, score, query);
5554
+ }
5555
+ /**
5556
+ * Evaluate helpfulness of retrievals in a session (called at session end)
5557
+ */
5558
+ async evaluateSessionHelpfulness(sessionId) {
5559
+ await this.initialize();
5560
+ await this.sqliteStore.evaluateSessionHelpfulness(sessionId);
5561
+ }
5562
+ /**
5563
+ * Get most helpful memories ranked by helpfulness score
5564
+ */
5565
+ async getHelpfulMemories(limit = 10) {
5566
+ await this.initialize();
5567
+ return this.sqliteStore.getHelpfulMemories(limit);
5568
+ }
5569
+ /**
5570
+ * Get helpfulness statistics for dashboard
5571
+ */
5572
+ async getHelpfulnessStats() {
5573
+ await this.initialize();
5574
+ return this.sqliteStore.getHelpfulnessStats();
5575
+ }
5058
5576
  /**
5059
5577
  * Mark a consolidated memory as accessed
5060
5578
  */
@@ -5118,6 +5636,44 @@ var MemoryService = class {
5118
5636
  lastConsolidation
5119
5637
  };
5120
5638
  }
5639
+ // ============================================================
5640
+ // Turn Grouping Methods
5641
+ // ============================================================
5642
+ /**
5643
+ * Get events grouped by turn for a session
5644
+ */
5645
+ async getSessionTurns(sessionId, options) {
5646
+ await this.initialize();
5647
+ return this.sqliteStore.getSessionTurns(sessionId, options);
5648
+ }
5649
+ /**
5650
+ * Get all events for a specific turn
5651
+ */
5652
+ async getEventsByTurn(turnId) {
5653
+ await this.initialize();
5654
+ return this.sqliteStore.getEventsByTurn(turnId);
5655
+ }
5656
+ /**
5657
+ * Count total turns for a session
5658
+ */
5659
+ async countSessionTurns(sessionId) {
5660
+ await this.initialize();
5661
+ return this.sqliteStore.countSessionTurns(sessionId);
5662
+ }
5663
+ /**
5664
+ * Backfill turn_ids from metadata for events stored before the migration
5665
+ */
5666
+ async backfillTurnIds() {
5667
+ await this.initialize();
5668
+ return this.sqliteStore.backfillTurnIds();
5669
+ }
5670
+ /**
5671
+ * Delete all events for a session (for force reimport)
5672
+ */
5673
+ async deleteSessionEvents(sessionId) {
5674
+ await this.initialize();
5675
+ return this.sqliteStore.deleteSessionEvents(sessionId);
5676
+ }
5121
5677
  /**
5122
5678
  * Format Endless Mode context for Claude
5123
5679
  */
@@ -5200,53 +5756,38 @@ var MemoryService = class {
5200
5756
  }
5201
5757
  };
5202
5758
  var serviceCache = /* @__PURE__ */ new Map();
5203
- var GLOBAL_KEY = "__global__";
5204
- function getDefaultMemoryService() {
5205
- if (!serviceCache.has(GLOBAL_KEY)) {
5206
- serviceCache.set(GLOBAL_KEY, new MemoryService({
5207
- storagePath: "~/.claude-code/memory",
5759
+ function getLightweightMemoryService(sessionId) {
5760
+ const projectInfo = getSessionProject(sessionId);
5761
+ const key = projectInfo ? `lightweight_${projectInfo.projectHash}` : "lightweight_global";
5762
+ if (!serviceCache.has(key)) {
5763
+ const storagePath = projectInfo ? getProjectStoragePath(projectInfo.projectPath) : path.join(os.homedir(), ".claude-code", "memory");
5764
+ serviceCache.set(key, new MemoryService({
5765
+ storagePath,
5766
+ projectHash: projectInfo?.projectHash,
5767
+ lightweightMode: true,
5768
+ // Skip embedder/vector/workers
5208
5769
  analyticsEnabled: false,
5209
- // Hooks don't need DuckDB
5210
5770
  sharedStoreConfig: { enabled: false }
5211
- // Shared store uses DuckDB too
5212
5771
  }));
5213
5772
  }
5214
- return serviceCache.get(GLOBAL_KEY);
5215
- }
5216
- function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
5217
- const hash = hashProjectPath(projectPath);
5218
- if (!serviceCache.has(hash)) {
5219
- const storagePath = getProjectStoragePath(projectPath);
5220
- serviceCache.set(hash, new MemoryService({
5221
- storagePath,
5222
- projectHash: hash,
5223
- // Override shared store config - hooks don't need DuckDB
5224
- sharedStoreConfig: sharedStoreConfig ?? { enabled: false },
5225
- analyticsEnabled: false
5226
- // Hooks don't need DuckDB
5227
- }));
5228
- }
5229
- return serviceCache.get(hash);
5230
- }
5231
- function getMemoryServiceForSession(sessionId) {
5232
- const projectInfo = getSessionProject(sessionId);
5233
- if (projectInfo) {
5234
- return getMemoryServiceForProject(projectInfo.projectPath);
5235
- }
5236
- return getDefaultMemoryService();
5773
+ return serviceCache.get(key);
5237
5774
  }
5238
5775
 
5239
5776
  // src/hooks/session-end.ts
5240
5777
  async function main() {
5241
5778
  const inputData = await readStdin();
5242
5779
  const input = JSON.parse(inputData);
5243
- const memoryService = getMemoryServiceForSession(input.session_id);
5780
+ const memoryService = getLightweightMemoryService(input.session_id);
5244
5781
  try {
5245
5782
  const sessionEvents = await memoryService.getSessionHistory(input.session_id);
5246
5783
  if (sessionEvents.length > 0) {
5247
5784
  const summary = generateSummary(sessionEvents);
5248
5785
  await memoryService.storeSessionSummary(input.session_id, summary);
5249
5786
  await memoryService.endSession(input.session_id, summary);
5787
+ try {
5788
+ await memoryService.evaluateSessionHelpfulness(input.session_id);
5789
+ } catch {
5790
+ }
5250
5791
  await memoryService.processPendingEmbeddings();
5251
5792
  }
5252
5793
  console.log(JSON.stringify({}));