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.
- package/dist/cli/index.js +1373 -184
- package/dist/cli/index.js.map +4 -4
- package/dist/core/index.js +445 -7
- package/dist/core/index.js.map +2 -2
- package/dist/hooks/post-tool-use.js +705 -43
- package/dist/hooks/post-tool-use.js.map +4 -4
- package/dist/hooks/session-end.js +593 -52
- package/dist/hooks/session-end.js.map +3 -3
- package/dist/hooks/session-start.js +581 -25
- package/dist/hooks/session-start.js.map +3 -3
- package/dist/hooks/stop.js +693 -73
- package/dist/hooks/stop.js.map +4 -4
- package/dist/hooks/user-prompt-submit.js +674 -94
- package/dist/hooks/user-prompt-submit.js.map +4 -4
- package/dist/server/api/index.js +1045 -42
- package/dist/server/api/index.js.map +4 -4
- package/dist/server/index.js +1054 -51
- package/dist/server/index.js.map +4 -4
- package/dist/services/memory-service.js +599 -25
- 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 +542 -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 +78 -65
- 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 +208 -9
- 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/test_access.js +0 -49
|
@@ -6,10 +6,13 @@ const require = createRequire(import.meta.url);
|
|
|
6
6
|
const __filename = fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = dirname(__filename);
|
|
8
8
|
|
|
9
|
+
// src/hooks/user-prompt-submit.ts
|
|
10
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
11
|
+
|
|
9
12
|
// src/services/memory-service.ts
|
|
10
13
|
import * as path from "path";
|
|
11
14
|
import * as os from "os";
|
|
12
|
-
import * as
|
|
15
|
+
import * as fs2 from "fs";
|
|
13
16
|
import * as crypto2 from "crypto";
|
|
14
17
|
|
|
15
18
|
// src/core/event-store.ts
|
|
@@ -67,11 +70,11 @@ function toDate(value) {
|
|
|
67
70
|
return new Date(value);
|
|
68
71
|
return new Date(String(value));
|
|
69
72
|
}
|
|
70
|
-
function createDatabase(
|
|
73
|
+
function createDatabase(path3, options) {
|
|
71
74
|
if (options?.readOnly) {
|
|
72
|
-
return new duckdb.Database(
|
|
75
|
+
return new duckdb.Database(path3, { access_mode: "READ_ONLY" });
|
|
73
76
|
}
|
|
74
|
-
return new duckdb.Database(
|
|
77
|
+
return new duckdb.Database(path3);
|
|
75
78
|
}
|
|
76
79
|
function dbRun(db, sql, params = []) {
|
|
77
80
|
return new Promise((resolve2, reject) => {
|
|
@@ -741,8 +744,14 @@ import { randomUUID as randomUUID2 } from "crypto";
|
|
|
741
744
|
|
|
742
745
|
// src/core/sqlite-wrapper.ts
|
|
743
746
|
import Database from "better-sqlite3";
|
|
744
|
-
|
|
745
|
-
|
|
747
|
+
import * as fs from "fs";
|
|
748
|
+
import * as nodePath from "path";
|
|
749
|
+
function createSQLiteDatabase(path3, options) {
|
|
750
|
+
const dir = nodePath.dirname(path3);
|
|
751
|
+
if (!fs.existsSync(dir)) {
|
|
752
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
753
|
+
}
|
|
754
|
+
const db = new Database(path3, {
|
|
746
755
|
readonly: options?.readonly ?? false
|
|
747
756
|
});
|
|
748
757
|
if (!options?.readonly && (options?.walMode ?? true)) {
|
|
@@ -1009,6 +1018,23 @@ var SQLiteEventStore = class {
|
|
|
1009
1018
|
updated_at TEXT DEFAULT (datetime('now'))
|
|
1010
1019
|
);
|
|
1011
1020
|
|
|
1021
|
+
-- Memory Helpfulness tracking
|
|
1022
|
+
CREATE TABLE IF NOT EXISTS memory_helpfulness (
|
|
1023
|
+
id TEXT PRIMARY KEY,
|
|
1024
|
+
event_id TEXT NOT NULL,
|
|
1025
|
+
session_id TEXT NOT NULL,
|
|
1026
|
+
retrieval_score REAL DEFAULT 0,
|
|
1027
|
+
query_preview TEXT,
|
|
1028
|
+
session_continued INTEGER DEFAULT 0,
|
|
1029
|
+
prompt_count_after INTEGER DEFAULT 0,
|
|
1030
|
+
tool_success_count INTEGER DEFAULT 0,
|
|
1031
|
+
tool_total_count INTEGER DEFAULT 0,
|
|
1032
|
+
was_reasked INTEGER DEFAULT 0,
|
|
1033
|
+
helpfulness_score REAL DEFAULT 0.5,
|
|
1034
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
1035
|
+
measured_at TEXT
|
|
1036
|
+
);
|
|
1037
|
+
|
|
1012
1038
|
-- Sync position tracking (for SQLite -> DuckDB sync)
|
|
1013
1039
|
CREATE TABLE IF NOT EXISTS sync_positions (
|
|
1014
1040
|
target_name TEXT PRIMARY KEY,
|
|
@@ -1034,6 +1060,31 @@ var SQLiteEventStore = class {
|
|
|
1034
1060
|
CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence);
|
|
1035
1061
|
CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at);
|
|
1036
1062
|
CREATE INDEX IF NOT EXISTS idx_embedding_outbox_status ON embedding_outbox(status);
|
|
1063
|
+
CREATE INDEX IF NOT EXISTS idx_helpfulness_event ON memory_helpfulness(event_id);
|
|
1064
|
+
CREATE INDEX IF NOT EXISTS idx_helpfulness_session ON memory_helpfulness(session_id);
|
|
1065
|
+
CREATE INDEX IF NOT EXISTS idx_helpfulness_score ON memory_helpfulness(helpfulness_score DESC);
|
|
1066
|
+
|
|
1067
|
+
-- FTS5 Full-Text Search for fast keyword search
|
|
1068
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
|
|
1069
|
+
content,
|
|
1070
|
+
event_id UNINDEXED,
|
|
1071
|
+
content='events',
|
|
1072
|
+
content_rowid='rowid'
|
|
1073
|
+
);
|
|
1074
|
+
|
|
1075
|
+
-- Triggers to keep FTS in sync with events table
|
|
1076
|
+
CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
|
|
1077
|
+
INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
|
|
1078
|
+
END;
|
|
1079
|
+
|
|
1080
|
+
CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
|
|
1081
|
+
INSERT INTO events_fts(events_fts, rowid, content, event_id) VALUES('delete', OLD.rowid, OLD.content, OLD.id);
|
|
1082
|
+
END;
|
|
1083
|
+
|
|
1084
|
+
CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
|
|
1085
|
+
INSERT INTO events_fts(events_fts, rowid, content, event_id) VALUES('delete', OLD.rowid, OLD.content, OLD.id);
|
|
1086
|
+
INSERT INTO events_fts(rowid, content, event_id) VALUES (NEW.rowid, NEW.content, NEW.id);
|
|
1087
|
+
END;
|
|
1037
1088
|
`);
|
|
1038
1089
|
const tableInfo = sqliteAll(this.db, "PRAGMA table_info(events)", []);
|
|
1039
1090
|
const columnNames = tableInfo.map((col) => col.name);
|
|
@@ -1055,6 +1106,15 @@ var SQLiteEventStore = class {
|
|
|
1055
1106
|
console.error("Error adding last_accessed_at column:", err);
|
|
1056
1107
|
}
|
|
1057
1108
|
}
|
|
1109
|
+
if (!columnNames.includes("turn_id")) {
|
|
1110
|
+
try {
|
|
1111
|
+
sqliteExec(this.db, `
|
|
1112
|
+
ALTER TABLE events ADD COLUMN turn_id TEXT;
|
|
1113
|
+
`);
|
|
1114
|
+
} catch (err) {
|
|
1115
|
+
console.error("Error adding turn_id column:", err);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1058
1118
|
try {
|
|
1059
1119
|
sqliteExec(this.db, `
|
|
1060
1120
|
CREATE INDEX IF NOT EXISTS idx_events_access_count ON events(access_count DESC);
|
|
@@ -1067,6 +1127,12 @@ var SQLiteEventStore = class {
|
|
|
1067
1127
|
`);
|
|
1068
1128
|
} catch (err) {
|
|
1069
1129
|
}
|
|
1130
|
+
try {
|
|
1131
|
+
sqliteExec(this.db, `
|
|
1132
|
+
CREATE INDEX IF NOT EXISTS idx_events_turn_id ON events(turn_id);
|
|
1133
|
+
`);
|
|
1134
|
+
} catch (err) {
|
|
1135
|
+
}
|
|
1070
1136
|
this.initialized = true;
|
|
1071
1137
|
}
|
|
1072
1138
|
/**
|
|
@@ -1091,9 +1157,11 @@ var SQLiteEventStore = class {
|
|
|
1091
1157
|
const id = randomUUID2();
|
|
1092
1158
|
const timestamp = toSQLiteTimestamp(input.timestamp);
|
|
1093
1159
|
try {
|
|
1160
|
+
const metadata = input.metadata || {};
|
|
1161
|
+
const turnId = metadata.turnId || null;
|
|
1094
1162
|
const insertEvent = this.db.prepare(`
|
|
1095
|
-
INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
|
|
1096
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1163
|
+
INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata, turn_id)
|
|
1164
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1097
1165
|
`);
|
|
1098
1166
|
const insertDedup = this.db.prepare(`
|
|
1099
1167
|
INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)
|
|
@@ -1110,7 +1178,8 @@ var SQLiteEventStore = class {
|
|
|
1110
1178
|
input.content,
|
|
1111
1179
|
canonicalKey,
|
|
1112
1180
|
dedupeKey,
|
|
1113
|
-
JSON.stringify(
|
|
1181
|
+
JSON.stringify(metadata),
|
|
1182
|
+
turnId
|
|
1114
1183
|
);
|
|
1115
1184
|
insertDedup.run(dedupeKey, id);
|
|
1116
1185
|
insertLevel.run(id);
|
|
@@ -1460,11 +1529,11 @@ var SQLiteEventStore = class {
|
|
|
1460
1529
|
);
|
|
1461
1530
|
}
|
|
1462
1531
|
/**
|
|
1463
|
-
* Get most accessed memories
|
|
1532
|
+
* Get most accessed memories (falls back to recent events if none accessed)
|
|
1464
1533
|
*/
|
|
1465
1534
|
async getMostAccessed(limit = 10) {
|
|
1466
1535
|
await this.initialize();
|
|
1467
|
-
|
|
1536
|
+
let rows = sqliteAll(
|
|
1468
1537
|
this.db,
|
|
1469
1538
|
`SELECT * FROM events
|
|
1470
1539
|
WHERE access_count > 0
|
|
@@ -1472,8 +1541,222 @@ var SQLiteEventStore = class {
|
|
|
1472
1541
|
LIMIT ?`,
|
|
1473
1542
|
[limit]
|
|
1474
1543
|
);
|
|
1544
|
+
if (rows.length === 0) {
|
|
1545
|
+
rows = sqliteAll(
|
|
1546
|
+
this.db,
|
|
1547
|
+
`SELECT * FROM events
|
|
1548
|
+
ORDER BY timestamp DESC
|
|
1549
|
+
LIMIT ?`,
|
|
1550
|
+
[limit]
|
|
1551
|
+
);
|
|
1552
|
+
}
|
|
1475
1553
|
return rows.map((row) => this.rowToEvent(row));
|
|
1476
1554
|
}
|
|
1555
|
+
/**
|
|
1556
|
+
* Record a memory retrieval for helpfulness tracking
|
|
1557
|
+
*/
|
|
1558
|
+
async recordRetrieval(eventId, sessionId, score, query) {
|
|
1559
|
+
if (this.readOnly)
|
|
1560
|
+
return;
|
|
1561
|
+
await this.initialize();
|
|
1562
|
+
const id = randomUUID2();
|
|
1563
|
+
sqliteRun(
|
|
1564
|
+
this.db,
|
|
1565
|
+
`INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
|
|
1566
|
+
VALUES (?, ?, ?, ?, ?, datetime('now'))`,
|
|
1567
|
+
[id, eventId, sessionId, score, query.slice(0, 100)]
|
|
1568
|
+
);
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Evaluate helpfulness for all retrievals in a session
|
|
1572
|
+
* Called at session end - uses behavioral signals to compute score
|
|
1573
|
+
*/
|
|
1574
|
+
async evaluateSessionHelpfulness(sessionId) {
|
|
1575
|
+
if (this.readOnly)
|
|
1576
|
+
return;
|
|
1577
|
+
await this.initialize();
|
|
1578
|
+
const retrievals = sqliteAll(
|
|
1579
|
+
this.db,
|
|
1580
|
+
`SELECT * FROM memory_helpfulness WHERE session_id = ? AND measured_at IS NULL`,
|
|
1581
|
+
[sessionId]
|
|
1582
|
+
);
|
|
1583
|
+
if (retrievals.length === 0)
|
|
1584
|
+
return;
|
|
1585
|
+
const sessionEvents = sqliteAll(
|
|
1586
|
+
this.db,
|
|
1587
|
+
`SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
|
|
1588
|
+
[sessionId]
|
|
1589
|
+
);
|
|
1590
|
+
const promptEvents = sessionEvents.filter((e) => e.event_type === "user_prompt");
|
|
1591
|
+
const toolEvents = sessionEvents.filter((e) => e.event_type === "tool_observation");
|
|
1592
|
+
let toolSuccessCount = 0;
|
|
1593
|
+
let toolTotalCount = toolEvents.length;
|
|
1594
|
+
for (const t of toolEvents) {
|
|
1595
|
+
try {
|
|
1596
|
+
const content = JSON.parse(t.content);
|
|
1597
|
+
if (content.success !== false)
|
|
1598
|
+
toolSuccessCount++;
|
|
1599
|
+
} catch {
|
|
1600
|
+
toolSuccessCount++;
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
const toolSuccessRatio = toolTotalCount > 0 ? toolSuccessCount / toolTotalCount : 0.5;
|
|
1604
|
+
for (const retrieval of retrievals) {
|
|
1605
|
+
const retrievalTime = retrieval.created_at;
|
|
1606
|
+
const eventsAfter = sessionEvents.filter((e) => e.timestamp > retrievalTime);
|
|
1607
|
+
const sessionContinued = eventsAfter.length > 0 ? 1 : 0;
|
|
1608
|
+
const promptsAfter = promptEvents.filter((e) => e.timestamp > retrievalTime);
|
|
1609
|
+
const promptCountAfter = promptsAfter.length;
|
|
1610
|
+
const queryWords = new Set((retrieval.query_preview || "").toLowerCase().split(/\s+/).filter((w) => w.length > 2));
|
|
1611
|
+
let wasReasked = 0;
|
|
1612
|
+
for (const p of promptsAfter) {
|
|
1613
|
+
const pWords = new Set(p.content.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
|
|
1614
|
+
let overlap = 0;
|
|
1615
|
+
for (const w of queryWords) {
|
|
1616
|
+
if (pWords.has(w))
|
|
1617
|
+
overlap++;
|
|
1618
|
+
}
|
|
1619
|
+
if (queryWords.size > 0 && overlap / queryWords.size > 0.5) {
|
|
1620
|
+
wasReasked = 1;
|
|
1621
|
+
break;
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
const retrievalScore = retrieval.retrieval_score || 0;
|
|
1625
|
+
const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
|
|
1626
|
+
sqliteRun(
|
|
1627
|
+
this.db,
|
|
1628
|
+
`UPDATE memory_helpfulness
|
|
1629
|
+
SET session_continued = ?, prompt_count_after = ?,
|
|
1630
|
+
tool_success_count = ?, tool_total_count = ?,
|
|
1631
|
+
was_reasked = ?, helpfulness_score = ?,
|
|
1632
|
+
measured_at = datetime('now')
|
|
1633
|
+
WHERE id = ?`,
|
|
1634
|
+
[
|
|
1635
|
+
sessionContinued,
|
|
1636
|
+
promptCountAfter,
|
|
1637
|
+
toolSuccessCount,
|
|
1638
|
+
toolTotalCount,
|
|
1639
|
+
wasReasked,
|
|
1640
|
+
helpfulnessScore,
|
|
1641
|
+
retrieval.id
|
|
1642
|
+
]
|
|
1643
|
+
);
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Get most helpful memories ranked by helpfulness score
|
|
1648
|
+
*/
|
|
1649
|
+
async getHelpfulMemories(limit = 10) {
|
|
1650
|
+
await this.initialize();
|
|
1651
|
+
const rows = sqliteAll(
|
|
1652
|
+
this.db,
|
|
1653
|
+
`SELECT
|
|
1654
|
+
mh.event_id,
|
|
1655
|
+
AVG(mh.helpfulness_score) as avg_score,
|
|
1656
|
+
COUNT(*) as eval_count,
|
|
1657
|
+
e.content,
|
|
1658
|
+
e.access_count
|
|
1659
|
+
FROM memory_helpfulness mh
|
|
1660
|
+
JOIN events e ON e.id = mh.event_id
|
|
1661
|
+
WHERE mh.measured_at IS NOT NULL
|
|
1662
|
+
GROUP BY mh.event_id
|
|
1663
|
+
ORDER BY avg_score DESC
|
|
1664
|
+
LIMIT ?`,
|
|
1665
|
+
[limit]
|
|
1666
|
+
);
|
|
1667
|
+
return rows.map((r) => ({
|
|
1668
|
+
eventId: r.event_id,
|
|
1669
|
+
summary: r.content.substring(0, 200) + (r.content.length > 200 ? "..." : ""),
|
|
1670
|
+
helpfulnessScore: Math.round(r.avg_score * 100) / 100,
|
|
1671
|
+
accessCount: r.access_count || 0,
|
|
1672
|
+
evaluationCount: r.eval_count
|
|
1673
|
+
}));
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Get helpfulness statistics for dashboard
|
|
1677
|
+
*/
|
|
1678
|
+
async getHelpfulnessStats() {
|
|
1679
|
+
await this.initialize();
|
|
1680
|
+
const stats = sqliteGet(
|
|
1681
|
+
this.db,
|
|
1682
|
+
`SELECT
|
|
1683
|
+
AVG(helpfulness_score) as avg_score,
|
|
1684
|
+
COUNT(*) as total_evaluated,
|
|
1685
|
+
SUM(CASE WHEN helpfulness_score >= 0.7 THEN 1 ELSE 0 END) as helpful,
|
|
1686
|
+
SUM(CASE WHEN helpfulness_score >= 0.4 AND helpfulness_score < 0.7 THEN 1 ELSE 0 END) as neutral,
|
|
1687
|
+
SUM(CASE WHEN helpfulness_score < 0.4 THEN 1 ELSE 0 END) as unhelpful
|
|
1688
|
+
FROM memory_helpfulness
|
|
1689
|
+
WHERE measured_at IS NOT NULL`
|
|
1690
|
+
);
|
|
1691
|
+
const totalRow = sqliteGet(
|
|
1692
|
+
this.db,
|
|
1693
|
+
`SELECT COUNT(*) as total FROM memory_helpfulness`
|
|
1694
|
+
);
|
|
1695
|
+
return {
|
|
1696
|
+
avgScore: Math.round((stats?.avg_score || 0) * 100) / 100,
|
|
1697
|
+
totalEvaluated: stats?.total_evaluated || 0,
|
|
1698
|
+
totalRetrievals: totalRow?.total || 0,
|
|
1699
|
+
helpful: stats?.helpful || 0,
|
|
1700
|
+
neutral: stats?.neutral || 0,
|
|
1701
|
+
unhelpful: stats?.unhelpful || 0
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* Fast keyword search using FTS5
|
|
1706
|
+
* Returns events matching the search query, ranked by relevance
|
|
1707
|
+
*/
|
|
1708
|
+
async keywordSearch(query, limit = 10) {
|
|
1709
|
+
await this.initialize();
|
|
1710
|
+
const searchTerms = query.replace(/['"(){}[\]^~*?:\\/-]/g, " ").split(/\s+/).filter((term) => term.length > 1).map((term) => `"${term}"*`).join(" OR ");
|
|
1711
|
+
if (!searchTerms) {
|
|
1712
|
+
return [];
|
|
1713
|
+
}
|
|
1714
|
+
try {
|
|
1715
|
+
const rows = sqliteAll(
|
|
1716
|
+
this.db,
|
|
1717
|
+
`SELECT e.*, fts.rank
|
|
1718
|
+
FROM events_fts fts
|
|
1719
|
+
JOIN events e ON e.id = fts.event_id
|
|
1720
|
+
WHERE events_fts MATCH ?
|
|
1721
|
+
ORDER BY fts.rank
|
|
1722
|
+
LIMIT ?`,
|
|
1723
|
+
[searchTerms, limit]
|
|
1724
|
+
);
|
|
1725
|
+
return rows.map((row) => ({
|
|
1726
|
+
event: this.rowToEvent(row),
|
|
1727
|
+
rank: row.rank
|
|
1728
|
+
}));
|
|
1729
|
+
} catch (error) {
|
|
1730
|
+
const likePattern = `%${query}%`;
|
|
1731
|
+
const rows = sqliteAll(
|
|
1732
|
+
this.db,
|
|
1733
|
+
`SELECT *, 0 as rank FROM events
|
|
1734
|
+
WHERE content LIKE ?
|
|
1735
|
+
ORDER BY timestamp DESC
|
|
1736
|
+
LIMIT ?`,
|
|
1737
|
+
[likePattern, limit]
|
|
1738
|
+
);
|
|
1739
|
+
return rows.map((row) => ({
|
|
1740
|
+
event: this.rowToEvent(row),
|
|
1741
|
+
rank: 0
|
|
1742
|
+
}));
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
/**
|
|
1746
|
+
* Rebuild FTS index from existing events
|
|
1747
|
+
* Call this once after upgrading to FTS5
|
|
1748
|
+
*/
|
|
1749
|
+
async rebuildFtsIndex() {
|
|
1750
|
+
await this.initialize();
|
|
1751
|
+
const countRow = sqliteGet(this.db, "SELECT COUNT(*) as count FROM events", []);
|
|
1752
|
+
const totalEvents = countRow?.count ?? 0;
|
|
1753
|
+
sqliteExec(this.db, `
|
|
1754
|
+
DELETE FROM events_fts;
|
|
1755
|
+
INSERT INTO events_fts(rowid, content, event_id)
|
|
1756
|
+
SELECT rowid, content, id FROM events;
|
|
1757
|
+
`);
|
|
1758
|
+
return totalEvents;
|
|
1759
|
+
}
|
|
1477
1760
|
/**
|
|
1478
1761
|
* Get database instance for direct access
|
|
1479
1762
|
*/
|
|
@@ -1486,6 +1769,143 @@ var SQLiteEventStore = class {
|
|
|
1486
1769
|
async close() {
|
|
1487
1770
|
sqliteClose(this.db);
|
|
1488
1771
|
}
|
|
1772
|
+
/**
|
|
1773
|
+
* Get events grouped by turn_id for a session
|
|
1774
|
+
* Returns turns ordered by first event timestamp (newest first)
|
|
1775
|
+
*/
|
|
1776
|
+
async getSessionTurns(sessionId, options) {
|
|
1777
|
+
await this.initialize();
|
|
1778
|
+
const limit = options?.limit || 20;
|
|
1779
|
+
const offset = options?.offset || 0;
|
|
1780
|
+
const turnRows = sqliteAll(
|
|
1781
|
+
this.db,
|
|
1782
|
+
`SELECT turn_id, MIN(timestamp) as min_ts
|
|
1783
|
+
FROM events
|
|
1784
|
+
WHERE session_id = ? AND turn_id IS NOT NULL
|
|
1785
|
+
GROUP BY turn_id
|
|
1786
|
+
ORDER BY min_ts DESC
|
|
1787
|
+
LIMIT ? OFFSET ?`,
|
|
1788
|
+
[sessionId, limit, offset]
|
|
1789
|
+
);
|
|
1790
|
+
const turns = [];
|
|
1791
|
+
for (const turnRow of turnRows) {
|
|
1792
|
+
const events = await this.getEventsByTurn(turnRow.turn_id);
|
|
1793
|
+
const promptEvent = events.find((e) => e.eventType === "user_prompt");
|
|
1794
|
+
const toolEvents = events.filter((e) => e.eventType === "tool_observation");
|
|
1795
|
+
const hasResponse = events.some((e) => e.eventType === "agent_response");
|
|
1796
|
+
turns.push({
|
|
1797
|
+
turnId: turnRow.turn_id,
|
|
1798
|
+
events,
|
|
1799
|
+
startedAt: toDateFromSQLite(turnRow.min_ts),
|
|
1800
|
+
promptPreview: promptEvent ? promptEvent.content.slice(0, 200) + (promptEvent.content.length > 200 ? "..." : "") : "(no prompt)",
|
|
1801
|
+
eventCount: events.length,
|
|
1802
|
+
toolCount: toolEvents.length,
|
|
1803
|
+
hasResponse
|
|
1804
|
+
});
|
|
1805
|
+
}
|
|
1806
|
+
return turns;
|
|
1807
|
+
}
|
|
1808
|
+
/**
|
|
1809
|
+
* Get all events for a specific turn_id
|
|
1810
|
+
*/
|
|
1811
|
+
async getEventsByTurn(turnId) {
|
|
1812
|
+
await this.initialize();
|
|
1813
|
+
const rows = sqliteAll(
|
|
1814
|
+
this.db,
|
|
1815
|
+
`SELECT * FROM events WHERE turn_id = ? ORDER BY timestamp ASC`,
|
|
1816
|
+
[turnId]
|
|
1817
|
+
);
|
|
1818
|
+
return rows.map(this.rowToEvent);
|
|
1819
|
+
}
|
|
1820
|
+
/**
|
|
1821
|
+
* Count total turns for a session
|
|
1822
|
+
*/
|
|
1823
|
+
async countSessionTurns(sessionId) {
|
|
1824
|
+
await this.initialize();
|
|
1825
|
+
const row = sqliteGet(
|
|
1826
|
+
this.db,
|
|
1827
|
+
`SELECT COUNT(DISTINCT turn_id) as count
|
|
1828
|
+
FROM events
|
|
1829
|
+
WHERE session_id = ? AND turn_id IS NOT NULL`,
|
|
1830
|
+
[sessionId]
|
|
1831
|
+
);
|
|
1832
|
+
return row?.count || 0;
|
|
1833
|
+
}
|
|
1834
|
+
/**
|
|
1835
|
+
* Migrate existing events: backfill turn_id for events that have turnId in metadata
|
|
1836
|
+
* but no turn_id column value (for events stored before this migration)
|
|
1837
|
+
*/
|
|
1838
|
+
async backfillTurnIds() {
|
|
1839
|
+
await this.initialize();
|
|
1840
|
+
const rows = sqliteAll(
|
|
1841
|
+
this.db,
|
|
1842
|
+
`SELECT id, metadata FROM events
|
|
1843
|
+
WHERE turn_id IS NULL AND metadata IS NOT NULL AND metadata LIKE '%turnId%'`
|
|
1844
|
+
);
|
|
1845
|
+
let updated = 0;
|
|
1846
|
+
for (const row of rows) {
|
|
1847
|
+
try {
|
|
1848
|
+
const metadata = JSON.parse(row.metadata);
|
|
1849
|
+
if (metadata.turnId) {
|
|
1850
|
+
sqliteRun(
|
|
1851
|
+
this.db,
|
|
1852
|
+
`UPDATE events SET turn_id = ? WHERE id = ?`,
|
|
1853
|
+
[metadata.turnId, row.id]
|
|
1854
|
+
);
|
|
1855
|
+
updated++;
|
|
1856
|
+
}
|
|
1857
|
+
} catch {
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
return updated;
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* Delete all events for a session (for force reimport)
|
|
1864
|
+
*/
|
|
1865
|
+
async deleteSessionEvents(sessionId) {
|
|
1866
|
+
await this.initialize();
|
|
1867
|
+
const events = sqliteAll(
|
|
1868
|
+
this.db,
|
|
1869
|
+
`SELECT id FROM events WHERE session_id = ?`,
|
|
1870
|
+
[sessionId]
|
|
1871
|
+
);
|
|
1872
|
+
if (events.length === 0)
|
|
1873
|
+
return 0;
|
|
1874
|
+
const eventIds = events.map((e) => e.id);
|
|
1875
|
+
const placeholders = eventIds.map(() => "?").join(",");
|
|
1876
|
+
const ftsTriggersDropped = [];
|
|
1877
|
+
for (const triggerName of ["events_fts_delete", "events_fts_update", "events_fts_insert"]) {
|
|
1878
|
+
try {
|
|
1879
|
+
sqliteRun(this.db, `DROP TRIGGER IF EXISTS ${triggerName}`);
|
|
1880
|
+
ftsTriggersDropped.push(triggerName);
|
|
1881
|
+
} catch {
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
for (const table of ["event_dedup", "memory_levels", "embedding_queue", "embedding_outbox", "vector_outbox"]) {
|
|
1885
|
+
try {
|
|
1886
|
+
sqliteRun(this.db, `DELETE FROM ${table} WHERE event_id IN (${placeholders})`, eventIds);
|
|
1887
|
+
} catch {
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
const result = sqliteRun(this.db, `DELETE FROM events WHERE session_id = ?`, [sessionId]);
|
|
1891
|
+
if (ftsTriggersDropped.length > 0) {
|
|
1892
|
+
try {
|
|
1893
|
+
sqliteRun(this.db, `INSERT INTO events_fts(events_fts) VALUES('rebuild')`);
|
|
1894
|
+
sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
|
|
1895
|
+
INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
|
|
1896
|
+
END`);
|
|
1897
|
+
sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
|
|
1898
|
+
INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
|
|
1899
|
+
END`);
|
|
1900
|
+
sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
|
|
1901
|
+
INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
|
|
1902
|
+
INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
|
|
1903
|
+
END`);
|
|
1904
|
+
} catch {
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
return result.changes || 0;
|
|
1908
|
+
}
|
|
1489
1909
|
/**
|
|
1490
1910
|
* Convert database row to MemoryEvent
|
|
1491
1911
|
*/
|
|
@@ -1506,6 +1926,9 @@ var SQLiteEventStore = class {
|
|
|
1506
1926
|
if (row.last_accessed_at !== void 0) {
|
|
1507
1927
|
event.last_accessed_at = row.last_accessed_at;
|
|
1508
1928
|
}
|
|
1929
|
+
if (row.turn_id !== void 0 && row.turn_id !== null) {
|
|
1930
|
+
event.turn_id = row.turn_id;
|
|
1931
|
+
}
|
|
1509
1932
|
return event;
|
|
1510
1933
|
}
|
|
1511
1934
|
};
|
|
@@ -1717,7 +2140,16 @@ var VectorStore = class {
|
|
|
1717
2140
|
metadata: JSON.stringify(record.metadata || {})
|
|
1718
2141
|
};
|
|
1719
2142
|
if (!this.table) {
|
|
1720
|
-
|
|
2143
|
+
try {
|
|
2144
|
+
this.table = await this.db.createTable(this.tableName, [data]);
|
|
2145
|
+
} catch (e) {
|
|
2146
|
+
if (e?.message?.includes("already exists")) {
|
|
2147
|
+
this.table = await this.db.openTable(this.tableName);
|
|
2148
|
+
await this.table.add([data]);
|
|
2149
|
+
} else {
|
|
2150
|
+
throw e;
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
1721
2153
|
} else {
|
|
1722
2154
|
await this.table.add([data]);
|
|
1723
2155
|
}
|
|
@@ -1743,7 +2175,16 @@ var VectorStore = class {
|
|
|
1743
2175
|
metadata: JSON.stringify(record.metadata || {})
|
|
1744
2176
|
}));
|
|
1745
2177
|
if (!this.table) {
|
|
1746
|
-
|
|
2178
|
+
try {
|
|
2179
|
+
this.table = await this.db.createTable(this.tableName, data);
|
|
2180
|
+
} catch (e) {
|
|
2181
|
+
if (e?.message?.includes("already exists")) {
|
|
2182
|
+
this.table = await this.db.openTable(this.tableName);
|
|
2183
|
+
await this.table.add(data);
|
|
2184
|
+
} else {
|
|
2185
|
+
throw e;
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
1747
2188
|
} else {
|
|
1748
2189
|
await this.table.add(data);
|
|
1749
2190
|
}
|
|
@@ -4489,7 +4930,7 @@ function createGraduationWorker(eventStore, graduation, config) {
|
|
|
4489
4930
|
function normalizePath(projectPath) {
|
|
4490
4931
|
const expanded = projectPath.startsWith("~") ? path.join(os.homedir(), projectPath.slice(1)) : projectPath;
|
|
4491
4932
|
try {
|
|
4492
|
-
return
|
|
4933
|
+
return fs2.realpathSync(expanded);
|
|
4493
4934
|
} catch {
|
|
4494
4935
|
return path.resolve(expanded);
|
|
4495
4936
|
}
|
|
@@ -4506,8 +4947,8 @@ var REGISTRY_PATH = path.join(os.homedir(), ".claude-code", "memory", "session-r
|
|
|
4506
4947
|
var SHARED_STORAGE_PATH = path.join(os.homedir(), ".claude-code", "memory", "shared");
|
|
4507
4948
|
function loadSessionRegistry() {
|
|
4508
4949
|
try {
|
|
4509
|
-
if (
|
|
4510
|
-
const data =
|
|
4950
|
+
if (fs2.existsSync(REGISTRY_PATH)) {
|
|
4951
|
+
const data = fs2.readFileSync(REGISTRY_PATH, "utf-8");
|
|
4511
4952
|
return JSON.parse(data);
|
|
4512
4953
|
}
|
|
4513
4954
|
} catch (error) {
|
|
@@ -4547,11 +4988,13 @@ var MemoryService = class {
|
|
|
4547
4988
|
sharedStoreConfig = null;
|
|
4548
4989
|
projectHash = null;
|
|
4549
4990
|
readOnly;
|
|
4991
|
+
lightweightMode;
|
|
4550
4992
|
constructor(config) {
|
|
4551
4993
|
const storagePath = this.expandPath(config.storagePath);
|
|
4552
4994
|
this.readOnly = config.readOnly ?? false;
|
|
4553
|
-
|
|
4554
|
-
|
|
4995
|
+
this.lightweightMode = config.lightweightMode ?? false;
|
|
4996
|
+
if (!this.readOnly && !fs2.existsSync(storagePath)) {
|
|
4997
|
+
fs2.mkdirSync(storagePath, { recursive: true });
|
|
4555
4998
|
}
|
|
4556
4999
|
this.projectHash = config.projectHash || null;
|
|
4557
5000
|
this.sharedStoreConfig = config.sharedStoreConfig ?? { enabled: true };
|
|
@@ -4596,6 +5039,10 @@ var MemoryService = class {
|
|
|
4596
5039
|
if (this.initialized)
|
|
4597
5040
|
return;
|
|
4598
5041
|
await this.sqliteStore.initialize();
|
|
5042
|
+
if (this.lightweightMode) {
|
|
5043
|
+
this.initialized = true;
|
|
5044
|
+
return;
|
|
5045
|
+
}
|
|
4599
5046
|
if (this.analyticsStore) {
|
|
4600
5047
|
try {
|
|
4601
5048
|
await this.analyticsStore.initialize();
|
|
@@ -4642,8 +5089,8 @@ var MemoryService = class {
|
|
|
4642
5089
|
*/
|
|
4643
5090
|
async initializeSharedStore() {
|
|
4644
5091
|
const sharedPath = this.sharedStoreConfig?.sharedStoragePath ? this.expandPath(this.sharedStoreConfig.sharedStoragePath) : SHARED_STORAGE_PATH;
|
|
4645
|
-
if (!
|
|
4646
|
-
|
|
5092
|
+
if (!fs2.existsSync(sharedPath)) {
|
|
5093
|
+
fs2.mkdirSync(sharedPath, { recursive: true });
|
|
4647
5094
|
}
|
|
4648
5095
|
this.sharedEventStore = createSharedEventStore(
|
|
4649
5096
|
path.join(sharedPath, "shared.duckdb")
|
|
@@ -4740,6 +5187,7 @@ var MemoryService = class {
|
|
|
4740
5187
|
async storeToolObservation(sessionId, payload) {
|
|
4741
5188
|
await this.initialize();
|
|
4742
5189
|
const content = JSON.stringify(payload);
|
|
5190
|
+
const turnId = payload.metadata?.turnId;
|
|
4743
5191
|
const result = await this.sqliteStore.append({
|
|
4744
5192
|
eventType: "tool_observation",
|
|
4745
5193
|
sessionId,
|
|
@@ -4747,7 +5195,8 @@ var MemoryService = class {
|
|
|
4747
5195
|
content,
|
|
4748
5196
|
metadata: {
|
|
4749
5197
|
toolName: payload.toolName,
|
|
4750
|
-
success: payload.success
|
|
5198
|
+
success: payload.success,
|
|
5199
|
+
...turnId ? { turnId } : {}
|
|
4751
5200
|
}
|
|
4752
5201
|
});
|
|
4753
5202
|
if (result.success && !result.isDuplicate) {
|
|
@@ -4765,9 +5214,6 @@ var MemoryService = class {
|
|
|
4765
5214
|
*/
|
|
4766
5215
|
async retrieveMemories(query, options) {
|
|
4767
5216
|
await this.initialize();
|
|
4768
|
-
if (this.vectorWorker) {
|
|
4769
|
-
await this.vectorWorker.processAll();
|
|
4770
|
-
}
|
|
4771
5217
|
if (options?.includeShared && this.sharedStore) {
|
|
4772
5218
|
return this.retriever.retrieveUnified(query, {
|
|
4773
5219
|
...options,
|
|
@@ -4777,6 +5223,29 @@ var MemoryService = class {
|
|
|
4777
5223
|
}
|
|
4778
5224
|
return this.retriever.retrieve(query, options);
|
|
4779
5225
|
}
|
|
5226
|
+
/**
|
|
5227
|
+
* Fast keyword search using SQLite FTS5
|
|
5228
|
+
* Much faster than vector search - no embedding model needed
|
|
5229
|
+
*/
|
|
5230
|
+
async keywordSearch(query, options) {
|
|
5231
|
+
await this.initialize();
|
|
5232
|
+
const results = await this.sqliteStore.keywordSearch(query, options?.topK ?? 10);
|
|
5233
|
+
const maxRank = Math.min(...results.map((r) => r.rank), -1e-3);
|
|
5234
|
+
const minRank = Math.max(...results.map((r) => r.rank), -1e3);
|
|
5235
|
+
const rankRange = maxRank - minRank || 1;
|
|
5236
|
+
return results.map((r) => ({
|
|
5237
|
+
event: r.event,
|
|
5238
|
+
score: 1 - (r.rank - minRank) / rankRange
|
|
5239
|
+
// Normalize to 0-1
|
|
5240
|
+
})).filter((r) => !options?.minScore || r.score >= options.minScore);
|
|
5241
|
+
}
|
|
5242
|
+
/**
|
|
5243
|
+
* Rebuild FTS index (call after database upgrade)
|
|
5244
|
+
*/
|
|
5245
|
+
async rebuildFtsIndex() {
|
|
5246
|
+
await this.initialize();
|
|
5247
|
+
return this.sqliteStore.rebuildFtsIndex();
|
|
5248
|
+
}
|
|
4780
5249
|
/**
|
|
4781
5250
|
* Get session history
|
|
4782
5251
|
*/
|
|
@@ -5010,6 +5479,31 @@ var MemoryService = class {
|
|
|
5010
5479
|
return [];
|
|
5011
5480
|
return this.consolidatedStore.getAll({ limit });
|
|
5012
5481
|
}
|
|
5482
|
+
/**
|
|
5483
|
+
* Extract topic keywords from event content (markdown headings and key terms)
|
|
5484
|
+
*/
|
|
5485
|
+
extractTopicsFromContent(content) {
|
|
5486
|
+
const topics = /* @__PURE__ */ new Set();
|
|
5487
|
+
const headings = content.match(/^#{1,3}\s+(.+)$/gm);
|
|
5488
|
+
if (headings) {
|
|
5489
|
+
for (const h of headings.slice(0, 5)) {
|
|
5490
|
+
const text = h.replace(/^#+\s+/, "").replace(/[*_`#]/g, "").trim();
|
|
5491
|
+
if (text.length > 2 && text.length < 50) {
|
|
5492
|
+
topics.add(text);
|
|
5493
|
+
}
|
|
5494
|
+
}
|
|
5495
|
+
}
|
|
5496
|
+
const boldTerms = content.match(/\*\*([^*]+)\*\*/g);
|
|
5497
|
+
if (boldTerms) {
|
|
5498
|
+
for (const b of boldTerms.slice(0, 5)) {
|
|
5499
|
+
const text = b.replace(/\*\*/g, "").trim();
|
|
5500
|
+
if (text.length > 2 && text.length < 30) {
|
|
5501
|
+
topics.add(text);
|
|
5502
|
+
}
|
|
5503
|
+
}
|
|
5504
|
+
}
|
|
5505
|
+
return Array.from(topics).slice(0, 5);
|
|
5506
|
+
}
|
|
5013
5507
|
/**
|
|
5014
5508
|
* Increment access count for memories that were used in prompts
|
|
5015
5509
|
*/
|
|
@@ -5033,8 +5527,7 @@ var MemoryService = class {
|
|
|
5033
5527
|
return events.map((event) => ({
|
|
5034
5528
|
memoryId: event.id,
|
|
5035
5529
|
summary: event.content.substring(0, 200) + (event.content.length > 200 ? "..." : ""),
|
|
5036
|
-
topics:
|
|
5037
|
-
// Could extract topics from content if needed
|
|
5530
|
+
topics: this.extractTopicsFromContent(event.content),
|
|
5038
5531
|
accessCount: event.access_count || 0,
|
|
5039
5532
|
lastAccessed: event.last_accessed_at || null,
|
|
5040
5533
|
confidence: 1,
|
|
@@ -5055,6 +5548,34 @@ var MemoryService = class {
|
|
|
5055
5548
|
}
|
|
5056
5549
|
return [];
|
|
5057
5550
|
}
|
|
5551
|
+
/**
|
|
5552
|
+
* Record a memory retrieval for helpfulness tracking
|
|
5553
|
+
*/
|
|
5554
|
+
async recordRetrieval(eventId, sessionId, score, query) {
|
|
5555
|
+
await this.initialize();
|
|
5556
|
+
await this.sqliteStore.recordRetrieval(eventId, sessionId, score, query);
|
|
5557
|
+
}
|
|
5558
|
+
/**
|
|
5559
|
+
* Evaluate helpfulness of retrievals in a session (called at session end)
|
|
5560
|
+
*/
|
|
5561
|
+
async evaluateSessionHelpfulness(sessionId) {
|
|
5562
|
+
await this.initialize();
|
|
5563
|
+
await this.sqliteStore.evaluateSessionHelpfulness(sessionId);
|
|
5564
|
+
}
|
|
5565
|
+
/**
|
|
5566
|
+
* Get most helpful memories ranked by helpfulness score
|
|
5567
|
+
*/
|
|
5568
|
+
async getHelpfulMemories(limit = 10) {
|
|
5569
|
+
await this.initialize();
|
|
5570
|
+
return this.sqliteStore.getHelpfulMemories(limit);
|
|
5571
|
+
}
|
|
5572
|
+
/**
|
|
5573
|
+
* Get helpfulness statistics for dashboard
|
|
5574
|
+
*/
|
|
5575
|
+
async getHelpfulnessStats() {
|
|
5576
|
+
await this.initialize();
|
|
5577
|
+
return this.sqliteStore.getHelpfulnessStats();
|
|
5578
|
+
}
|
|
5058
5579
|
/**
|
|
5059
5580
|
* Mark a consolidated memory as accessed
|
|
5060
5581
|
*/
|
|
@@ -5118,6 +5639,44 @@ var MemoryService = class {
|
|
|
5118
5639
|
lastConsolidation
|
|
5119
5640
|
};
|
|
5120
5641
|
}
|
|
5642
|
+
// ============================================================
|
|
5643
|
+
// Turn Grouping Methods
|
|
5644
|
+
// ============================================================
|
|
5645
|
+
/**
|
|
5646
|
+
* Get events grouped by turn for a session
|
|
5647
|
+
*/
|
|
5648
|
+
async getSessionTurns(sessionId, options) {
|
|
5649
|
+
await this.initialize();
|
|
5650
|
+
return this.sqliteStore.getSessionTurns(sessionId, options);
|
|
5651
|
+
}
|
|
5652
|
+
/**
|
|
5653
|
+
* Get all events for a specific turn
|
|
5654
|
+
*/
|
|
5655
|
+
async getEventsByTurn(turnId) {
|
|
5656
|
+
await this.initialize();
|
|
5657
|
+
return this.sqliteStore.getEventsByTurn(turnId);
|
|
5658
|
+
}
|
|
5659
|
+
/**
|
|
5660
|
+
* Count total turns for a session
|
|
5661
|
+
*/
|
|
5662
|
+
async countSessionTurns(sessionId) {
|
|
5663
|
+
await this.initialize();
|
|
5664
|
+
return this.sqliteStore.countSessionTurns(sessionId);
|
|
5665
|
+
}
|
|
5666
|
+
/**
|
|
5667
|
+
* Backfill turn_ids from metadata for events stored before the migration
|
|
5668
|
+
*/
|
|
5669
|
+
async backfillTurnIds() {
|
|
5670
|
+
await this.initialize();
|
|
5671
|
+
return this.sqliteStore.backfillTurnIds();
|
|
5672
|
+
}
|
|
5673
|
+
/**
|
|
5674
|
+
* Delete all events for a session (for force reimport)
|
|
5675
|
+
*/
|
|
5676
|
+
async deleteSessionEvents(sessionId) {
|
|
5677
|
+
await this.initialize();
|
|
5678
|
+
return this.sqliteStore.deleteSessionEvents(sessionId);
|
|
5679
|
+
}
|
|
5121
5680
|
/**
|
|
5122
5681
|
* Format Endless Mode context for Claude
|
|
5123
5682
|
*/
|
|
@@ -5200,94 +5759,115 @@ var MemoryService = class {
|
|
|
5200
5759
|
}
|
|
5201
5760
|
};
|
|
5202
5761
|
var serviceCache = /* @__PURE__ */ new Map();
|
|
5203
|
-
|
|
5204
|
-
|
|
5205
|
-
|
|
5206
|
-
|
|
5207
|
-
|
|
5762
|
+
function getLightweightMemoryService(sessionId) {
|
|
5763
|
+
const projectInfo = getSessionProject(sessionId);
|
|
5764
|
+
const key = projectInfo ? `lightweight_${projectInfo.projectHash}` : "lightweight_global";
|
|
5765
|
+
if (!serviceCache.has(key)) {
|
|
5766
|
+
const storagePath = projectInfo ? getProjectStoragePath(projectInfo.projectPath) : path.join(os.homedir(), ".claude-code", "memory");
|
|
5767
|
+
serviceCache.set(key, new MemoryService({
|
|
5768
|
+
storagePath,
|
|
5769
|
+
projectHash: projectInfo?.projectHash,
|
|
5770
|
+
lightweightMode: true,
|
|
5771
|
+
// Skip embedder/vector/workers
|
|
5208
5772
|
analyticsEnabled: false,
|
|
5209
|
-
// Hooks don't need DuckDB
|
|
5210
5773
|
sharedStoreConfig: { enabled: false }
|
|
5211
|
-
// Shared store uses DuckDB too
|
|
5212
5774
|
}));
|
|
5213
5775
|
}
|
|
5214
|
-
return serviceCache.get(
|
|
5776
|
+
return serviceCache.get(key);
|
|
5215
5777
|
}
|
|
5216
|
-
|
|
5217
|
-
|
|
5218
|
-
|
|
5219
|
-
|
|
5220
|
-
|
|
5221
|
-
|
|
5222
|
-
|
|
5223
|
-
|
|
5224
|
-
sharedStoreConfig: sharedStoreConfig ?? { enabled: false },
|
|
5225
|
-
analyticsEnabled: false
|
|
5226
|
-
// Hooks don't need DuckDB
|
|
5227
|
-
}));
|
|
5228
|
-
}
|
|
5229
|
-
return serviceCache.get(hash);
|
|
5778
|
+
|
|
5779
|
+
// src/core/turn-state.ts
|
|
5780
|
+
import * as fs3 from "fs";
|
|
5781
|
+
import * as path2 from "path";
|
|
5782
|
+
import * as os2 from "os";
|
|
5783
|
+
var TURN_STATE_DIR = path2.join(os2.homedir(), ".claude-code", "memory");
|
|
5784
|
+
function getStatePath(sessionId) {
|
|
5785
|
+
return path2.join(TURN_STATE_DIR, `.turn-state-${sessionId}.json`);
|
|
5230
5786
|
}
|
|
5231
|
-
function
|
|
5232
|
-
|
|
5233
|
-
|
|
5234
|
-
|
|
5787
|
+
function writeTurnState(sessionId, turnId) {
|
|
5788
|
+
try {
|
|
5789
|
+
if (!fs3.existsSync(TURN_STATE_DIR)) {
|
|
5790
|
+
fs3.mkdirSync(TURN_STATE_DIR, { recursive: true });
|
|
5791
|
+
}
|
|
5792
|
+
const state = {
|
|
5793
|
+
turnId,
|
|
5794
|
+
sessionId,
|
|
5795
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5796
|
+
};
|
|
5797
|
+
const filePath = getStatePath(sessionId);
|
|
5798
|
+
const tempPath = filePath + ".tmp";
|
|
5799
|
+
fs3.writeFileSync(tempPath, JSON.stringify(state));
|
|
5800
|
+
fs3.renameSync(tempPath, filePath);
|
|
5801
|
+
} catch (error) {
|
|
5802
|
+
if (process.env.CLAUDE_MEMORY_DEBUG) {
|
|
5803
|
+
console.error("Failed to write turn state:", error);
|
|
5804
|
+
}
|
|
5235
5805
|
}
|
|
5236
|
-
return getDefaultMemoryService();
|
|
5237
5806
|
}
|
|
5238
5807
|
|
|
5239
5808
|
// src/hooks/user-prompt-submit.ts
|
|
5809
|
+
var MAX_MEMORIES = parseInt(process.env.CLAUDE_MEMORY_MAX_COUNT || "5");
|
|
5810
|
+
var MIN_SCORE = parseFloat(process.env.CLAUDE_MEMORY_MIN_SCORE || "0.3");
|
|
5811
|
+
var ENABLE_SEARCH = process.env.CLAUDE_MEMORY_SEARCH !== "false";
|
|
5812
|
+
function shouldStorePrompt(prompt) {
|
|
5813
|
+
const trimmed = prompt.trim();
|
|
5814
|
+
if (trimmed.startsWith("/"))
|
|
5815
|
+
return false;
|
|
5816
|
+
if (trimmed.length < 15)
|
|
5817
|
+
return false;
|
|
5818
|
+
if (!/[a-zA-Z가-힣]{2,}/.test(trimmed))
|
|
5819
|
+
return false;
|
|
5820
|
+
return true;
|
|
5821
|
+
}
|
|
5240
5822
|
async function main() {
|
|
5241
5823
|
const inputData = await readStdin();
|
|
5242
5824
|
const input = JSON.parse(inputData);
|
|
5243
|
-
const
|
|
5244
|
-
|
|
5245
|
-
|
|
5246
|
-
minScore: parseFloat(process.env.CLAUDE_MEMORY_MIN_SCORE || "0.7"),
|
|
5247
|
-
maxMemories: parseInt(process.env.CLAUDE_MEMORY_MAX_COUNT || "5"),
|
|
5248
|
-
dynamicThresholdRatio: parseFloat(process.env.CLAUDE_MEMORY_THRESHOLD_RATIO || "0.85"),
|
|
5249
|
-
strictMinScore: parseFloat(process.env.CLAUDE_MEMORY_STRICT_MIN || "0.75")
|
|
5250
|
-
};
|
|
5825
|
+
const turnId = randomUUID9();
|
|
5826
|
+
writeTurnState(input.session_id, turnId);
|
|
5827
|
+
const memoryService = getLightweightMemoryService(input.session_id);
|
|
5251
5828
|
try {
|
|
5252
|
-
|
|
5253
|
-
|
|
5254
|
-
|
|
5255
|
-
|
|
5256
|
-
|
|
5257
|
-
|
|
5258
|
-
}
|
|
5259
|
-
|
|
5260
|
-
|
|
5261
|
-
input.prompt
|
|
5262
|
-
|
|
5263
|
-
|
|
5264
|
-
|
|
5265
|
-
|
|
5266
|
-
|
|
5267
|
-
relevantMemories = retrievalResult.memories.filter((m) => m.score >= dynamicThreshold);
|
|
5268
|
-
relevantMemories = relevantMemories.slice(0, config.maxMemories);
|
|
5269
|
-
if (relevantMemories.length === 0) {
|
|
5270
|
-
const fallbackCount = Math.min(3, config.maxMemories);
|
|
5271
|
-
relevantMemories = retrievalResult.memories.filter((m) => m.score >= config.minScore).slice(0, fallbackCount);
|
|
5272
|
-
}
|
|
5273
|
-
if (process.env.CLAUDE_MEMORY_DEBUG) {
|
|
5274
|
-
console.error(`Memory filtering: ${retrievalResult.memories.length} candidates -> ${relevantMemories.length} selected`);
|
|
5275
|
-
console.error(`Threshold: ${dynamicThreshold.toFixed(3)}, Best score: ${bestScore.toFixed(3)}`);
|
|
5276
|
-
}
|
|
5277
|
-
if (relevantMemories.length > 0) {
|
|
5278
|
-
const eventIds = relevantMemories.map((m) => m.event.id);
|
|
5829
|
+
if (shouldStorePrompt(input.prompt)) {
|
|
5830
|
+
await memoryService.storeUserPrompt(
|
|
5831
|
+
input.session_id,
|
|
5832
|
+
input.prompt,
|
|
5833
|
+
{ turnId }
|
|
5834
|
+
);
|
|
5835
|
+
}
|
|
5836
|
+
let context = "";
|
|
5837
|
+
if (ENABLE_SEARCH && input.prompt.length > 10) {
|
|
5838
|
+
const results = await memoryService.keywordSearch(input.prompt, {
|
|
5839
|
+
topK: MAX_MEMORIES,
|
|
5840
|
+
minScore: MIN_SCORE
|
|
5841
|
+
});
|
|
5842
|
+
if (results.length > 0) {
|
|
5843
|
+
const eventIds = results.map((r) => r.event.id);
|
|
5279
5844
|
await memoryService.incrementMemoryAccess(eventIds);
|
|
5845
|
+
for (const r of results) {
|
|
5846
|
+
try {
|
|
5847
|
+
await memoryService.recordRetrieval(
|
|
5848
|
+
r.event.id,
|
|
5849
|
+
input.session_id,
|
|
5850
|
+
r.score,
|
|
5851
|
+
input.prompt
|
|
5852
|
+
);
|
|
5853
|
+
} catch {
|
|
5854
|
+
}
|
|
5855
|
+
}
|
|
5856
|
+
const memories = results.map((r) => {
|
|
5857
|
+
const preview = r.event.content.length > 300 ? r.event.content.substring(0, 300) + "..." : r.event.content;
|
|
5858
|
+
return `- [${r.event.eventType}] ${preview}`;
|
|
5859
|
+
});
|
|
5860
|
+
context = `\u{1F4A1} **Related memories found:**
|
|
5861
|
+
|
|
5862
|
+
${memories.join("\n\n")}`;
|
|
5280
5863
|
}
|
|
5281
5864
|
}
|
|
5282
|
-
const filteredResult = {
|
|
5283
|
-
...retrievalResult,
|
|
5284
|
-
memories: relevantMemories
|
|
5285
|
-
};
|
|
5286
|
-
const context = memoryService.formatAsContext(filteredResult);
|
|
5287
5865
|
const output = { context };
|
|
5288
5866
|
console.log(JSON.stringify(output));
|
|
5289
5867
|
} catch (error) {
|
|
5290
|
-
|
|
5868
|
+
if (process.env.CLAUDE_MEMORY_DEBUG) {
|
|
5869
|
+
console.error("Memory hook error:", error);
|
|
5870
|
+
}
|
|
5291
5871
|
console.log(JSON.stringify({ context: "" }));
|
|
5292
5872
|
}
|
|
5293
5873
|
}
|