claude-memory-layer 1.0.10 → 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.
- package/dist/cli/index.js +1266 -181
- package/dist/cli/index.js.map +4 -4
- package/dist/core/index.js +367 -7
- package/dist/core/index.js.map +2 -2
- package/dist/hooks/post-tool-use.js +598 -40
- package/dist/hooks/post-tool-use.js.map +4 -4
- package/dist/hooks/session-end.js +486 -49
- package/dist/hooks/session-end.js.map +3 -3
- package/dist/hooks/session-start.js +474 -22
- package/dist/hooks/session-start.js.map +3 -3
- package/dist/hooks/stop.js +586 -70
- package/dist/hooks/stop.js.map +4 -4
- package/dist/hooks/user-prompt-submit.js +537 -27
- package/dist/hooks/user-prompt-submit.js.map +4 -4
- package/dist/server/api/index.js +938 -39
- package/dist/server/api/index.js.map +4 -4
- package/dist/server/index.js +947 -48
- package/dist/server/index.js.map +4 -4
- package/dist/services/memory-service.js +475 -22
- package/dist/services/memory-service.js.map +3 -3
- package/dist/ui/app.js +1380 -55
- package/dist/ui/index.html +311 -148
- package/dist/ui/style.css +892 -0
- package/docs/OPERATIONS.md +18 -0
- package/package.json +8 -2
- package/scripts/fix-sync-gap.js +32 -0
- package/scripts/heartbeat-memory-orchestrator.sh +28 -0
- package/scripts/report-sync-gap.js +26 -0
- package/scripts/review-queue-auto-resolve.js +21 -0
- package/scripts/sync-gap-auto-heal.sh +17 -0
- package/specs/20260207-dashboard-upgrade/context.md +38 -0
- package/specs/20260207-dashboard-upgrade/spec.md +96 -0
- package/src/cli/index.ts +110 -58
- package/src/core/sqlite-event-store.ts +444 -6
- package/src/core/sqlite-wrapper.ts +8 -0
- package/src/core/turn-state.ts +159 -0
- package/src/core/types.ts +23 -8
- package/src/core/vector-store.ts +21 -3
- package/src/hooks/post-tool-use.ts +68 -23
- package/src/hooks/session-end.ts +8 -3
- package/src/hooks/stop.ts +96 -25
- package/src/hooks/user-prompt-submit.ts +44 -5
- package/src/server/api/chat.ts +244 -0
- package/src/server/api/citations.ts +3 -3
- package/src/server/api/events.ts +30 -5
- package/src/server/api/index.ts +7 -1
- package/src/server/api/projects.ts +74 -0
- package/src/server/api/search.ts +3 -3
- package/src/server/api/sessions.ts +3 -3
- package/src/server/api/stats.ts +43 -7
- package/src/server/api/turns.ts +143 -0
- package/src/server/api/utils.ts +46 -0
- package/src/services/memory-service.ts +137 -5
- package/src/services/session-history-importer.ts +215 -51
- package/src/ui/app.js +1380 -55
- package/src/ui/index.html +311 -148
- package/src/ui/style.css +892 -0
- package/.claude/settings.local.json +0 -27
- package/.claude-memory/test.sqlite +0 -0
- package/.history/package_20260201112328.json +0 -45
- package/.history/package_20260201113602.json +0 -45
- package/.history/package_20260201113713.json +0 -45
- package/.history/package_20260201114110.json +0 -45
- package/.history/package_20260201114632.json +0 -46
- package/.history/package_20260201133143.json +0 -45
- package/.history/package_20260201134319.json +0 -45
- package/.history/package_20260201134326.json +0 -45
- package/.history/package_20260201134334.json +0 -45
- package/.history/package_20260201134912.json +0 -45
- package/.history/package_20260201142928.json +0 -46
- package/.history/package_20260201192048.json +0 -47
- package/.history/package_20260202114053.json +0 -49
- package/.history/package_20260202121115.json +0 -49
- 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
|
|
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,9 @@ 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);
|
|
1037
1063
|
|
|
1038
1064
|
-- FTS5 Full-Text Search for fast keyword search
|
|
1039
1065
|
CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
|
|
@@ -1077,6 +1103,15 @@ var SQLiteEventStore = class {
|
|
|
1077
1103
|
console.error("Error adding last_accessed_at column:", err);
|
|
1078
1104
|
}
|
|
1079
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
|
+
}
|
|
1080
1115
|
try {
|
|
1081
1116
|
sqliteExec(this.db, `
|
|
1082
1117
|
CREATE INDEX IF NOT EXISTS idx_events_access_count ON events(access_count DESC);
|
|
@@ -1089,6 +1124,12 @@ var SQLiteEventStore = class {
|
|
|
1089
1124
|
`);
|
|
1090
1125
|
} catch (err) {
|
|
1091
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
|
+
}
|
|
1092
1133
|
this.initialized = true;
|
|
1093
1134
|
}
|
|
1094
1135
|
/**
|
|
@@ -1113,9 +1154,11 @@ var SQLiteEventStore = class {
|
|
|
1113
1154
|
const id = randomUUID2();
|
|
1114
1155
|
const timestamp = toSQLiteTimestamp(input.timestamp);
|
|
1115
1156
|
try {
|
|
1157
|
+
const metadata = input.metadata || {};
|
|
1158
|
+
const turnId = metadata.turnId || null;
|
|
1116
1159
|
const insertEvent = this.db.prepare(`
|
|
1117
|
-
INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
|
|
1118
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1160
|
+
INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata, turn_id)
|
|
1161
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1119
1162
|
`);
|
|
1120
1163
|
const insertDedup = this.db.prepare(`
|
|
1121
1164
|
INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)
|
|
@@ -1132,7 +1175,8 @@ var SQLiteEventStore = class {
|
|
|
1132
1175
|
input.content,
|
|
1133
1176
|
canonicalKey,
|
|
1134
1177
|
dedupeKey,
|
|
1135
|
-
JSON.stringify(
|
|
1178
|
+
JSON.stringify(metadata),
|
|
1179
|
+
turnId
|
|
1136
1180
|
);
|
|
1137
1181
|
insertDedup.run(dedupeKey, id);
|
|
1138
1182
|
insertLevel.run(id);
|
|
@@ -1482,11 +1526,11 @@ var SQLiteEventStore = class {
|
|
|
1482
1526
|
);
|
|
1483
1527
|
}
|
|
1484
1528
|
/**
|
|
1485
|
-
* Get most accessed memories
|
|
1529
|
+
* Get most accessed memories (falls back to recent events if none accessed)
|
|
1486
1530
|
*/
|
|
1487
1531
|
async getMostAccessed(limit = 10) {
|
|
1488
1532
|
await this.initialize();
|
|
1489
|
-
|
|
1533
|
+
let rows = sqliteAll(
|
|
1490
1534
|
this.db,
|
|
1491
1535
|
`SELECT * FROM events
|
|
1492
1536
|
WHERE access_count > 0
|
|
@@ -1494,8 +1538,166 @@ var SQLiteEventStore = class {
|
|
|
1494
1538
|
LIMIT ?`,
|
|
1495
1539
|
[limit]
|
|
1496
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
|
+
}
|
|
1497
1550
|
return rows.map((row) => this.rowToEvent(row));
|
|
1498
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
|
+
}
|
|
1499
1701
|
/**
|
|
1500
1702
|
* Fast keyword search using FTS5
|
|
1501
1703
|
* Returns events matching the search query, ranked by relevance
|
|
@@ -1564,6 +1766,143 @@ var SQLiteEventStore = class {
|
|
|
1564
1766
|
async close() {
|
|
1565
1767
|
sqliteClose(this.db);
|
|
1566
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
|
+
}
|
|
1567
1906
|
/**
|
|
1568
1907
|
* Convert database row to MemoryEvent
|
|
1569
1908
|
*/
|
|
@@ -1584,6 +1923,9 @@ var SQLiteEventStore = class {
|
|
|
1584
1923
|
if (row.last_accessed_at !== void 0) {
|
|
1585
1924
|
event.last_accessed_at = row.last_accessed_at;
|
|
1586
1925
|
}
|
|
1926
|
+
if (row.turn_id !== void 0 && row.turn_id !== null) {
|
|
1927
|
+
event.turn_id = row.turn_id;
|
|
1928
|
+
}
|
|
1587
1929
|
return event;
|
|
1588
1930
|
}
|
|
1589
1931
|
};
|
|
@@ -1795,7 +2137,16 @@ var VectorStore = class {
|
|
|
1795
2137
|
metadata: JSON.stringify(record.metadata || {})
|
|
1796
2138
|
};
|
|
1797
2139
|
if (!this.table) {
|
|
1798
|
-
|
|
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
|
+
}
|
|
1799
2150
|
} else {
|
|
1800
2151
|
await this.table.add([data]);
|
|
1801
2152
|
}
|
|
@@ -1821,7 +2172,16 @@ var VectorStore = class {
|
|
|
1821
2172
|
metadata: JSON.stringify(record.metadata || {})
|
|
1822
2173
|
}));
|
|
1823
2174
|
if (!this.table) {
|
|
1824
|
-
|
|
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
|
+
}
|
|
1825
2185
|
} else {
|
|
1826
2186
|
await this.table.add(data);
|
|
1827
2187
|
}
|
|
@@ -4567,7 +4927,7 @@ function createGraduationWorker(eventStore, graduation, config) {
|
|
|
4567
4927
|
function normalizePath(projectPath) {
|
|
4568
4928
|
const expanded = projectPath.startsWith("~") ? path.join(os.homedir(), projectPath.slice(1)) : projectPath;
|
|
4569
4929
|
try {
|
|
4570
|
-
return
|
|
4930
|
+
return fs2.realpathSync(expanded);
|
|
4571
4931
|
} catch {
|
|
4572
4932
|
return path.resolve(expanded);
|
|
4573
4933
|
}
|
|
@@ -4584,8 +4944,8 @@ var REGISTRY_PATH = path.join(os.homedir(), ".claude-code", "memory", "session-r
|
|
|
4584
4944
|
var SHARED_STORAGE_PATH = path.join(os.homedir(), ".claude-code", "memory", "shared");
|
|
4585
4945
|
function loadSessionRegistry() {
|
|
4586
4946
|
try {
|
|
4587
|
-
if (
|
|
4588
|
-
const data =
|
|
4947
|
+
if (fs2.existsSync(REGISTRY_PATH)) {
|
|
4948
|
+
const data = fs2.readFileSync(REGISTRY_PATH, "utf-8");
|
|
4589
4949
|
return JSON.parse(data);
|
|
4590
4950
|
}
|
|
4591
4951
|
} catch (error) {
|
|
@@ -4630,8 +4990,8 @@ var MemoryService = class {
|
|
|
4630
4990
|
const storagePath = this.expandPath(config.storagePath);
|
|
4631
4991
|
this.readOnly = config.readOnly ?? false;
|
|
4632
4992
|
this.lightweightMode = config.lightweightMode ?? false;
|
|
4633
|
-
if (!this.readOnly && !
|
|
4634
|
-
|
|
4993
|
+
if (!this.readOnly && !fs2.existsSync(storagePath)) {
|
|
4994
|
+
fs2.mkdirSync(storagePath, { recursive: true });
|
|
4635
4995
|
}
|
|
4636
4996
|
this.projectHash = config.projectHash || null;
|
|
4637
4997
|
this.sharedStoreConfig = config.sharedStoreConfig ?? { enabled: true };
|
|
@@ -4726,8 +5086,8 @@ var MemoryService = class {
|
|
|
4726
5086
|
*/
|
|
4727
5087
|
async initializeSharedStore() {
|
|
4728
5088
|
const sharedPath = this.sharedStoreConfig?.sharedStoragePath ? this.expandPath(this.sharedStoreConfig.sharedStoragePath) : SHARED_STORAGE_PATH;
|
|
4729
|
-
if (!
|
|
4730
|
-
|
|
5089
|
+
if (!fs2.existsSync(sharedPath)) {
|
|
5090
|
+
fs2.mkdirSync(sharedPath, { recursive: true });
|
|
4731
5091
|
}
|
|
4732
5092
|
this.sharedEventStore = createSharedEventStore(
|
|
4733
5093
|
path.join(sharedPath, "shared.duckdb")
|
|
@@ -4824,6 +5184,7 @@ var MemoryService = class {
|
|
|
4824
5184
|
async storeToolObservation(sessionId, payload) {
|
|
4825
5185
|
await this.initialize();
|
|
4826
5186
|
const content = JSON.stringify(payload);
|
|
5187
|
+
const turnId = payload.metadata?.turnId;
|
|
4827
5188
|
const result = await this.sqliteStore.append({
|
|
4828
5189
|
eventType: "tool_observation",
|
|
4829
5190
|
sessionId,
|
|
@@ -4831,7 +5192,8 @@ var MemoryService = class {
|
|
|
4831
5192
|
content,
|
|
4832
5193
|
metadata: {
|
|
4833
5194
|
toolName: payload.toolName,
|
|
4834
|
-
success: payload.success
|
|
5195
|
+
success: payload.success,
|
|
5196
|
+
...turnId ? { turnId } : {}
|
|
4835
5197
|
}
|
|
4836
5198
|
});
|
|
4837
5199
|
if (result.success && !result.isDuplicate) {
|
|
@@ -5114,6 +5476,31 @@ var MemoryService = class {
|
|
|
5114
5476
|
return [];
|
|
5115
5477
|
return this.consolidatedStore.getAll({ limit });
|
|
5116
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
|
+
}
|
|
5117
5504
|
/**
|
|
5118
5505
|
* Increment access count for memories that were used in prompts
|
|
5119
5506
|
*/
|
|
@@ -5137,8 +5524,7 @@ var MemoryService = class {
|
|
|
5137
5524
|
return events.map((event) => ({
|
|
5138
5525
|
memoryId: event.id,
|
|
5139
5526
|
summary: event.content.substring(0, 200) + (event.content.length > 200 ? "..." : ""),
|
|
5140
|
-
topics:
|
|
5141
|
-
// Could extract topics from content if needed
|
|
5527
|
+
topics: this.extractTopicsFromContent(event.content),
|
|
5142
5528
|
accessCount: event.access_count || 0,
|
|
5143
5529
|
lastAccessed: event.last_accessed_at || null,
|
|
5144
5530
|
confidence: 1,
|
|
@@ -5159,6 +5545,34 @@ var MemoryService = class {
|
|
|
5159
5545
|
}
|
|
5160
5546
|
return [];
|
|
5161
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
|
+
}
|
|
5162
5576
|
/**
|
|
5163
5577
|
* Mark a consolidated memory as accessed
|
|
5164
5578
|
*/
|
|
@@ -5222,6 +5636,44 @@ var MemoryService = class {
|
|
|
5222
5636
|
lastConsolidation
|
|
5223
5637
|
};
|
|
5224
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
|
+
}
|
|
5225
5677
|
/**
|
|
5226
5678
|
* Format Endless Mode context for Claude
|
|
5227
5679
|
*/
|
|
@@ -5304,53 +5756,38 @@ var MemoryService = class {
|
|
|
5304
5756
|
}
|
|
5305
5757
|
};
|
|
5306
5758
|
var serviceCache = /* @__PURE__ */ new Map();
|
|
5307
|
-
|
|
5308
|
-
|
|
5309
|
-
|
|
5310
|
-
|
|
5311
|
-
|
|
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
|
|
5312
5769
|
analyticsEnabled: false,
|
|
5313
|
-
// Hooks don't need DuckDB
|
|
5314
5770
|
sharedStoreConfig: { enabled: false }
|
|
5315
|
-
// Shared store uses DuckDB too
|
|
5316
|
-
}));
|
|
5317
|
-
}
|
|
5318
|
-
return serviceCache.get(GLOBAL_KEY);
|
|
5319
|
-
}
|
|
5320
|
-
function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
|
|
5321
|
-
const hash = hashProjectPath(projectPath);
|
|
5322
|
-
if (!serviceCache.has(hash)) {
|
|
5323
|
-
const storagePath = getProjectStoragePath(projectPath);
|
|
5324
|
-
serviceCache.set(hash, new MemoryService({
|
|
5325
|
-
storagePath,
|
|
5326
|
-
projectHash: hash,
|
|
5327
|
-
// Override shared store config - hooks don't need DuckDB
|
|
5328
|
-
sharedStoreConfig: sharedStoreConfig ?? { enabled: false },
|
|
5329
|
-
analyticsEnabled: false
|
|
5330
|
-
// Hooks don't need DuckDB
|
|
5331
5771
|
}));
|
|
5332
5772
|
}
|
|
5333
|
-
return serviceCache.get(
|
|
5334
|
-
}
|
|
5335
|
-
function getMemoryServiceForSession(sessionId) {
|
|
5336
|
-
const projectInfo = getSessionProject(sessionId);
|
|
5337
|
-
if (projectInfo) {
|
|
5338
|
-
return getMemoryServiceForProject(projectInfo.projectPath);
|
|
5339
|
-
}
|
|
5340
|
-
return getDefaultMemoryService();
|
|
5773
|
+
return serviceCache.get(key);
|
|
5341
5774
|
}
|
|
5342
5775
|
|
|
5343
5776
|
// src/hooks/session-end.ts
|
|
5344
5777
|
async function main() {
|
|
5345
5778
|
const inputData = await readStdin();
|
|
5346
5779
|
const input = JSON.parse(inputData);
|
|
5347
|
-
const memoryService =
|
|
5780
|
+
const memoryService = getLightweightMemoryService(input.session_id);
|
|
5348
5781
|
try {
|
|
5349
5782
|
const sessionEvents = await memoryService.getSessionHistory(input.session_id);
|
|
5350
5783
|
if (sessionEvents.length > 0) {
|
|
5351
5784
|
const summary = generateSummary(sessionEvents);
|
|
5352
5785
|
await memoryService.storeSessionSummary(input.session_id, summary);
|
|
5353
5786
|
await memoryService.endSession(input.session_id, summary);
|
|
5787
|
+
try {
|
|
5788
|
+
await memoryService.evaluateSessionHelpfulness(input.session_id);
|
|
5789
|
+
} catch {
|
|
5790
|
+
}
|
|
5354
5791
|
await memoryService.processPendingEmbeddings();
|
|
5355
5792
|
}
|
|
5356
5793
|
console.log(JSON.stringify({}));
|