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
package/dist/server/index.js
CHANGED
|
@@ -4,26 +4,37 @@ import { dirname } from 'path';
|
|
|
4
4
|
const require = createRequire(import.meta.url);
|
|
5
5
|
const __filename = fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = dirname(__filename);
|
|
7
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
8
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
9
|
+
}) : x)(function(x) {
|
|
10
|
+
if (typeof require !== "undefined")
|
|
11
|
+
return require.apply(this, arguments);
|
|
12
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
13
|
+
});
|
|
7
14
|
|
|
8
15
|
// src/server/index.ts
|
|
9
|
-
import { Hono as
|
|
16
|
+
import { Hono as Hono10 } from "hono";
|
|
10
17
|
import { cors } from "hono/cors";
|
|
11
18
|
import { logger } from "hono/logger";
|
|
12
19
|
import { serve } from "@hono/node-server";
|
|
13
20
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
14
|
-
import * as
|
|
15
|
-
import * as
|
|
21
|
+
import * as path4 from "path";
|
|
22
|
+
import * as fs4 from "fs";
|
|
16
23
|
|
|
17
24
|
// src/server/api/index.ts
|
|
18
|
-
import { Hono as
|
|
25
|
+
import { Hono as Hono9 } from "hono";
|
|
19
26
|
|
|
20
27
|
// src/server/api/sessions.ts
|
|
21
28
|
import { Hono } from "hono";
|
|
22
29
|
|
|
30
|
+
// src/server/api/utils.ts
|
|
31
|
+
import * as path2 from "path";
|
|
32
|
+
import * as os2 from "os";
|
|
33
|
+
|
|
23
34
|
// src/services/memory-service.ts
|
|
24
35
|
import * as path from "path";
|
|
25
36
|
import * as os from "os";
|
|
26
|
-
import * as
|
|
37
|
+
import * as fs2 from "fs";
|
|
27
38
|
import * as crypto2 from "crypto";
|
|
28
39
|
|
|
29
40
|
// src/core/event-store.ts
|
|
@@ -81,11 +92,11 @@ function toDate(value) {
|
|
|
81
92
|
return new Date(value);
|
|
82
93
|
return new Date(String(value));
|
|
83
94
|
}
|
|
84
|
-
function createDatabase(
|
|
95
|
+
function createDatabase(path5, options) {
|
|
85
96
|
if (options?.readOnly) {
|
|
86
|
-
return new duckdb.Database(
|
|
97
|
+
return new duckdb.Database(path5, { access_mode: "READ_ONLY" });
|
|
87
98
|
}
|
|
88
|
-
return new duckdb.Database(
|
|
99
|
+
return new duckdb.Database(path5);
|
|
89
100
|
}
|
|
90
101
|
function dbRun(db, sql, params = []) {
|
|
91
102
|
return new Promise((resolve2, reject) => {
|
|
@@ -755,8 +766,14 @@ import { randomUUID as randomUUID2 } from "crypto";
|
|
|
755
766
|
|
|
756
767
|
// src/core/sqlite-wrapper.ts
|
|
757
768
|
import Database from "better-sqlite3";
|
|
758
|
-
|
|
759
|
-
|
|
769
|
+
import * as fs from "fs";
|
|
770
|
+
import * as nodePath from "path";
|
|
771
|
+
function createSQLiteDatabase(path5, options) {
|
|
772
|
+
const dir = nodePath.dirname(path5);
|
|
773
|
+
if (!fs.existsSync(dir)) {
|
|
774
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
775
|
+
}
|
|
776
|
+
const db = new Database(path5, {
|
|
760
777
|
readonly: options?.readonly ?? false
|
|
761
778
|
});
|
|
762
779
|
if (!options?.readonly && (options?.walMode ?? true)) {
|
|
@@ -1023,6 +1040,23 @@ var SQLiteEventStore = class {
|
|
|
1023
1040
|
updated_at TEXT DEFAULT (datetime('now'))
|
|
1024
1041
|
);
|
|
1025
1042
|
|
|
1043
|
+
-- Memory Helpfulness tracking
|
|
1044
|
+
CREATE TABLE IF NOT EXISTS memory_helpfulness (
|
|
1045
|
+
id TEXT PRIMARY KEY,
|
|
1046
|
+
event_id TEXT NOT NULL,
|
|
1047
|
+
session_id TEXT NOT NULL,
|
|
1048
|
+
retrieval_score REAL DEFAULT 0,
|
|
1049
|
+
query_preview TEXT,
|
|
1050
|
+
session_continued INTEGER DEFAULT 0,
|
|
1051
|
+
prompt_count_after INTEGER DEFAULT 0,
|
|
1052
|
+
tool_success_count INTEGER DEFAULT 0,
|
|
1053
|
+
tool_total_count INTEGER DEFAULT 0,
|
|
1054
|
+
was_reasked INTEGER DEFAULT 0,
|
|
1055
|
+
helpfulness_score REAL DEFAULT 0.5,
|
|
1056
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
1057
|
+
measured_at TEXT
|
|
1058
|
+
);
|
|
1059
|
+
|
|
1026
1060
|
-- Sync position tracking (for SQLite -> DuckDB sync)
|
|
1027
1061
|
CREATE TABLE IF NOT EXISTS sync_positions (
|
|
1028
1062
|
target_name TEXT PRIMARY KEY,
|
|
@@ -1048,6 +1082,9 @@ var SQLiteEventStore = class {
|
|
|
1048
1082
|
CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence);
|
|
1049
1083
|
CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at);
|
|
1050
1084
|
CREATE INDEX IF NOT EXISTS idx_embedding_outbox_status ON embedding_outbox(status);
|
|
1085
|
+
CREATE INDEX IF NOT EXISTS idx_helpfulness_event ON memory_helpfulness(event_id);
|
|
1086
|
+
CREATE INDEX IF NOT EXISTS idx_helpfulness_session ON memory_helpfulness(session_id);
|
|
1087
|
+
CREATE INDEX IF NOT EXISTS idx_helpfulness_score ON memory_helpfulness(helpfulness_score DESC);
|
|
1051
1088
|
|
|
1052
1089
|
-- FTS5 Full-Text Search for fast keyword search
|
|
1053
1090
|
CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
|
|
@@ -1091,6 +1128,15 @@ var SQLiteEventStore = class {
|
|
|
1091
1128
|
console.error("Error adding last_accessed_at column:", err);
|
|
1092
1129
|
}
|
|
1093
1130
|
}
|
|
1131
|
+
if (!columnNames.includes("turn_id")) {
|
|
1132
|
+
try {
|
|
1133
|
+
sqliteExec(this.db, `
|
|
1134
|
+
ALTER TABLE events ADD COLUMN turn_id TEXT;
|
|
1135
|
+
`);
|
|
1136
|
+
} catch (err) {
|
|
1137
|
+
console.error("Error adding turn_id column:", err);
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1094
1140
|
try {
|
|
1095
1141
|
sqliteExec(this.db, `
|
|
1096
1142
|
CREATE INDEX IF NOT EXISTS idx_events_access_count ON events(access_count DESC);
|
|
@@ -1103,6 +1149,12 @@ var SQLiteEventStore = class {
|
|
|
1103
1149
|
`);
|
|
1104
1150
|
} catch (err) {
|
|
1105
1151
|
}
|
|
1152
|
+
try {
|
|
1153
|
+
sqliteExec(this.db, `
|
|
1154
|
+
CREATE INDEX IF NOT EXISTS idx_events_turn_id ON events(turn_id);
|
|
1155
|
+
`);
|
|
1156
|
+
} catch (err) {
|
|
1157
|
+
}
|
|
1106
1158
|
this.initialized = true;
|
|
1107
1159
|
}
|
|
1108
1160
|
/**
|
|
@@ -1127,9 +1179,11 @@ var SQLiteEventStore = class {
|
|
|
1127
1179
|
const id = randomUUID2();
|
|
1128
1180
|
const timestamp = toSQLiteTimestamp(input.timestamp);
|
|
1129
1181
|
try {
|
|
1182
|
+
const metadata = input.metadata || {};
|
|
1183
|
+
const turnId = metadata.turnId || null;
|
|
1130
1184
|
const insertEvent = this.db.prepare(`
|
|
1131
|
-
INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
|
|
1132
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1185
|
+
INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata, turn_id)
|
|
1186
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1133
1187
|
`);
|
|
1134
1188
|
const insertDedup = this.db.prepare(`
|
|
1135
1189
|
INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)
|
|
@@ -1146,7 +1200,8 @@ var SQLiteEventStore = class {
|
|
|
1146
1200
|
input.content,
|
|
1147
1201
|
canonicalKey,
|
|
1148
1202
|
dedupeKey,
|
|
1149
|
-
JSON.stringify(
|
|
1203
|
+
JSON.stringify(metadata),
|
|
1204
|
+
turnId
|
|
1150
1205
|
);
|
|
1151
1206
|
insertDedup.run(dedupeKey, id);
|
|
1152
1207
|
insertLevel.run(id);
|
|
@@ -1496,11 +1551,11 @@ var SQLiteEventStore = class {
|
|
|
1496
1551
|
);
|
|
1497
1552
|
}
|
|
1498
1553
|
/**
|
|
1499
|
-
* Get most accessed memories
|
|
1554
|
+
* Get most accessed memories (falls back to recent events if none accessed)
|
|
1500
1555
|
*/
|
|
1501
1556
|
async getMostAccessed(limit = 10) {
|
|
1502
1557
|
await this.initialize();
|
|
1503
|
-
|
|
1558
|
+
let rows = sqliteAll(
|
|
1504
1559
|
this.db,
|
|
1505
1560
|
`SELECT * FROM events
|
|
1506
1561
|
WHERE access_count > 0
|
|
@@ -1508,8 +1563,166 @@ var SQLiteEventStore = class {
|
|
|
1508
1563
|
LIMIT ?`,
|
|
1509
1564
|
[limit]
|
|
1510
1565
|
);
|
|
1566
|
+
if (rows.length === 0) {
|
|
1567
|
+
rows = sqliteAll(
|
|
1568
|
+
this.db,
|
|
1569
|
+
`SELECT * FROM events
|
|
1570
|
+
ORDER BY timestamp DESC
|
|
1571
|
+
LIMIT ?`,
|
|
1572
|
+
[limit]
|
|
1573
|
+
);
|
|
1574
|
+
}
|
|
1511
1575
|
return rows.map((row) => this.rowToEvent(row));
|
|
1512
1576
|
}
|
|
1577
|
+
/**
|
|
1578
|
+
* Record a memory retrieval for helpfulness tracking
|
|
1579
|
+
*/
|
|
1580
|
+
async recordRetrieval(eventId, sessionId, score, query) {
|
|
1581
|
+
if (this.readOnly)
|
|
1582
|
+
return;
|
|
1583
|
+
await this.initialize();
|
|
1584
|
+
const id = randomUUID2();
|
|
1585
|
+
sqliteRun(
|
|
1586
|
+
this.db,
|
|
1587
|
+
`INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
|
|
1588
|
+
VALUES (?, ?, ?, ?, ?, datetime('now'))`,
|
|
1589
|
+
[id, eventId, sessionId, score, query.slice(0, 100)]
|
|
1590
|
+
);
|
|
1591
|
+
}
|
|
1592
|
+
/**
|
|
1593
|
+
* Evaluate helpfulness for all retrievals in a session
|
|
1594
|
+
* Called at session end - uses behavioral signals to compute score
|
|
1595
|
+
*/
|
|
1596
|
+
async evaluateSessionHelpfulness(sessionId) {
|
|
1597
|
+
if (this.readOnly)
|
|
1598
|
+
return;
|
|
1599
|
+
await this.initialize();
|
|
1600
|
+
const retrievals = sqliteAll(
|
|
1601
|
+
this.db,
|
|
1602
|
+
`SELECT * FROM memory_helpfulness WHERE session_id = ? AND measured_at IS NULL`,
|
|
1603
|
+
[sessionId]
|
|
1604
|
+
);
|
|
1605
|
+
if (retrievals.length === 0)
|
|
1606
|
+
return;
|
|
1607
|
+
const sessionEvents = sqliteAll(
|
|
1608
|
+
this.db,
|
|
1609
|
+
`SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
|
|
1610
|
+
[sessionId]
|
|
1611
|
+
);
|
|
1612
|
+
const promptEvents = sessionEvents.filter((e) => e.event_type === "user_prompt");
|
|
1613
|
+
const toolEvents = sessionEvents.filter((e) => e.event_type === "tool_observation");
|
|
1614
|
+
let toolSuccessCount = 0;
|
|
1615
|
+
let toolTotalCount = toolEvents.length;
|
|
1616
|
+
for (const t of toolEvents) {
|
|
1617
|
+
try {
|
|
1618
|
+
const content = JSON.parse(t.content);
|
|
1619
|
+
if (content.success !== false)
|
|
1620
|
+
toolSuccessCount++;
|
|
1621
|
+
} catch {
|
|
1622
|
+
toolSuccessCount++;
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
const toolSuccessRatio = toolTotalCount > 0 ? toolSuccessCount / toolTotalCount : 0.5;
|
|
1626
|
+
for (const retrieval of retrievals) {
|
|
1627
|
+
const retrievalTime = retrieval.created_at;
|
|
1628
|
+
const eventsAfter = sessionEvents.filter((e) => e.timestamp > retrievalTime);
|
|
1629
|
+
const sessionContinued = eventsAfter.length > 0 ? 1 : 0;
|
|
1630
|
+
const promptsAfter = promptEvents.filter((e) => e.timestamp > retrievalTime);
|
|
1631
|
+
const promptCountAfter = promptsAfter.length;
|
|
1632
|
+
const queryWords = new Set((retrieval.query_preview || "").toLowerCase().split(/\s+/).filter((w) => w.length > 2));
|
|
1633
|
+
let wasReasked = 0;
|
|
1634
|
+
for (const p of promptsAfter) {
|
|
1635
|
+
const pWords = new Set(p.content.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
|
|
1636
|
+
let overlap = 0;
|
|
1637
|
+
for (const w of queryWords) {
|
|
1638
|
+
if (pWords.has(w))
|
|
1639
|
+
overlap++;
|
|
1640
|
+
}
|
|
1641
|
+
if (queryWords.size > 0 && overlap / queryWords.size > 0.5) {
|
|
1642
|
+
wasReasked = 1;
|
|
1643
|
+
break;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
const retrievalScore = retrieval.retrieval_score || 0;
|
|
1647
|
+
const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
|
|
1648
|
+
sqliteRun(
|
|
1649
|
+
this.db,
|
|
1650
|
+
`UPDATE memory_helpfulness
|
|
1651
|
+
SET session_continued = ?, prompt_count_after = ?,
|
|
1652
|
+
tool_success_count = ?, tool_total_count = ?,
|
|
1653
|
+
was_reasked = ?, helpfulness_score = ?,
|
|
1654
|
+
measured_at = datetime('now')
|
|
1655
|
+
WHERE id = ?`,
|
|
1656
|
+
[
|
|
1657
|
+
sessionContinued,
|
|
1658
|
+
promptCountAfter,
|
|
1659
|
+
toolSuccessCount,
|
|
1660
|
+
toolTotalCount,
|
|
1661
|
+
wasReasked,
|
|
1662
|
+
helpfulnessScore,
|
|
1663
|
+
retrieval.id
|
|
1664
|
+
]
|
|
1665
|
+
);
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* Get most helpful memories ranked by helpfulness score
|
|
1670
|
+
*/
|
|
1671
|
+
async getHelpfulMemories(limit = 10) {
|
|
1672
|
+
await this.initialize();
|
|
1673
|
+
const rows = sqliteAll(
|
|
1674
|
+
this.db,
|
|
1675
|
+
`SELECT
|
|
1676
|
+
mh.event_id,
|
|
1677
|
+
AVG(mh.helpfulness_score) as avg_score,
|
|
1678
|
+
COUNT(*) as eval_count,
|
|
1679
|
+
e.content,
|
|
1680
|
+
e.access_count
|
|
1681
|
+
FROM memory_helpfulness mh
|
|
1682
|
+
JOIN events e ON e.id = mh.event_id
|
|
1683
|
+
WHERE mh.measured_at IS NOT NULL
|
|
1684
|
+
GROUP BY mh.event_id
|
|
1685
|
+
ORDER BY avg_score DESC
|
|
1686
|
+
LIMIT ?`,
|
|
1687
|
+
[limit]
|
|
1688
|
+
);
|
|
1689
|
+
return rows.map((r) => ({
|
|
1690
|
+
eventId: r.event_id,
|
|
1691
|
+
summary: r.content.substring(0, 200) + (r.content.length > 200 ? "..." : ""),
|
|
1692
|
+
helpfulnessScore: Math.round(r.avg_score * 100) / 100,
|
|
1693
|
+
accessCount: r.access_count || 0,
|
|
1694
|
+
evaluationCount: r.eval_count
|
|
1695
|
+
}));
|
|
1696
|
+
}
|
|
1697
|
+
/**
|
|
1698
|
+
* Get helpfulness statistics for dashboard
|
|
1699
|
+
*/
|
|
1700
|
+
async getHelpfulnessStats() {
|
|
1701
|
+
await this.initialize();
|
|
1702
|
+
const stats = sqliteGet(
|
|
1703
|
+
this.db,
|
|
1704
|
+
`SELECT
|
|
1705
|
+
AVG(helpfulness_score) as avg_score,
|
|
1706
|
+
COUNT(*) as total_evaluated,
|
|
1707
|
+
SUM(CASE WHEN helpfulness_score >= 0.7 THEN 1 ELSE 0 END) as helpful,
|
|
1708
|
+
SUM(CASE WHEN helpfulness_score >= 0.4 AND helpfulness_score < 0.7 THEN 1 ELSE 0 END) as neutral,
|
|
1709
|
+
SUM(CASE WHEN helpfulness_score < 0.4 THEN 1 ELSE 0 END) as unhelpful
|
|
1710
|
+
FROM memory_helpfulness
|
|
1711
|
+
WHERE measured_at IS NOT NULL`
|
|
1712
|
+
);
|
|
1713
|
+
const totalRow = sqliteGet(
|
|
1714
|
+
this.db,
|
|
1715
|
+
`SELECT COUNT(*) as total FROM memory_helpfulness`
|
|
1716
|
+
);
|
|
1717
|
+
return {
|
|
1718
|
+
avgScore: Math.round((stats?.avg_score || 0) * 100) / 100,
|
|
1719
|
+
totalEvaluated: stats?.total_evaluated || 0,
|
|
1720
|
+
totalRetrievals: totalRow?.total || 0,
|
|
1721
|
+
helpful: stats?.helpful || 0,
|
|
1722
|
+
neutral: stats?.neutral || 0,
|
|
1723
|
+
unhelpful: stats?.unhelpful || 0
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1513
1726
|
/**
|
|
1514
1727
|
* Fast keyword search using FTS5
|
|
1515
1728
|
* Returns events matching the search query, ranked by relevance
|
|
@@ -1578,6 +1791,143 @@ var SQLiteEventStore = class {
|
|
|
1578
1791
|
async close() {
|
|
1579
1792
|
sqliteClose(this.db);
|
|
1580
1793
|
}
|
|
1794
|
+
/**
|
|
1795
|
+
* Get events grouped by turn_id for a session
|
|
1796
|
+
* Returns turns ordered by first event timestamp (newest first)
|
|
1797
|
+
*/
|
|
1798
|
+
async getSessionTurns(sessionId, options) {
|
|
1799
|
+
await this.initialize();
|
|
1800
|
+
const limit = options?.limit || 20;
|
|
1801
|
+
const offset = options?.offset || 0;
|
|
1802
|
+
const turnRows = sqliteAll(
|
|
1803
|
+
this.db,
|
|
1804
|
+
`SELECT turn_id, MIN(timestamp) as min_ts
|
|
1805
|
+
FROM events
|
|
1806
|
+
WHERE session_id = ? AND turn_id IS NOT NULL
|
|
1807
|
+
GROUP BY turn_id
|
|
1808
|
+
ORDER BY min_ts DESC
|
|
1809
|
+
LIMIT ? OFFSET ?`,
|
|
1810
|
+
[sessionId, limit, offset]
|
|
1811
|
+
);
|
|
1812
|
+
const turns = [];
|
|
1813
|
+
for (const turnRow of turnRows) {
|
|
1814
|
+
const events = await this.getEventsByTurn(turnRow.turn_id);
|
|
1815
|
+
const promptEvent = events.find((e) => e.eventType === "user_prompt");
|
|
1816
|
+
const toolEvents = events.filter((e) => e.eventType === "tool_observation");
|
|
1817
|
+
const hasResponse = events.some((e) => e.eventType === "agent_response");
|
|
1818
|
+
turns.push({
|
|
1819
|
+
turnId: turnRow.turn_id,
|
|
1820
|
+
events,
|
|
1821
|
+
startedAt: toDateFromSQLite(turnRow.min_ts),
|
|
1822
|
+
promptPreview: promptEvent ? promptEvent.content.slice(0, 200) + (promptEvent.content.length > 200 ? "..." : "") : "(no prompt)",
|
|
1823
|
+
eventCount: events.length,
|
|
1824
|
+
toolCount: toolEvents.length,
|
|
1825
|
+
hasResponse
|
|
1826
|
+
});
|
|
1827
|
+
}
|
|
1828
|
+
return turns;
|
|
1829
|
+
}
|
|
1830
|
+
/**
|
|
1831
|
+
* Get all events for a specific turn_id
|
|
1832
|
+
*/
|
|
1833
|
+
async getEventsByTurn(turnId) {
|
|
1834
|
+
await this.initialize();
|
|
1835
|
+
const rows = sqliteAll(
|
|
1836
|
+
this.db,
|
|
1837
|
+
`SELECT * FROM events WHERE turn_id = ? ORDER BY timestamp ASC`,
|
|
1838
|
+
[turnId]
|
|
1839
|
+
);
|
|
1840
|
+
return rows.map(this.rowToEvent);
|
|
1841
|
+
}
|
|
1842
|
+
/**
|
|
1843
|
+
* Count total turns for a session
|
|
1844
|
+
*/
|
|
1845
|
+
async countSessionTurns(sessionId) {
|
|
1846
|
+
await this.initialize();
|
|
1847
|
+
const row = sqliteGet(
|
|
1848
|
+
this.db,
|
|
1849
|
+
`SELECT COUNT(DISTINCT turn_id) as count
|
|
1850
|
+
FROM events
|
|
1851
|
+
WHERE session_id = ? AND turn_id IS NOT NULL`,
|
|
1852
|
+
[sessionId]
|
|
1853
|
+
);
|
|
1854
|
+
return row?.count || 0;
|
|
1855
|
+
}
|
|
1856
|
+
/**
|
|
1857
|
+
* Migrate existing events: backfill turn_id for events that have turnId in metadata
|
|
1858
|
+
* but no turn_id column value (for events stored before this migration)
|
|
1859
|
+
*/
|
|
1860
|
+
async backfillTurnIds() {
|
|
1861
|
+
await this.initialize();
|
|
1862
|
+
const rows = sqliteAll(
|
|
1863
|
+
this.db,
|
|
1864
|
+
`SELECT id, metadata FROM events
|
|
1865
|
+
WHERE turn_id IS NULL AND metadata IS NOT NULL AND metadata LIKE '%turnId%'`
|
|
1866
|
+
);
|
|
1867
|
+
let updated = 0;
|
|
1868
|
+
for (const row of rows) {
|
|
1869
|
+
try {
|
|
1870
|
+
const metadata = JSON.parse(row.metadata);
|
|
1871
|
+
if (metadata.turnId) {
|
|
1872
|
+
sqliteRun(
|
|
1873
|
+
this.db,
|
|
1874
|
+
`UPDATE events SET turn_id = ? WHERE id = ?`,
|
|
1875
|
+
[metadata.turnId, row.id]
|
|
1876
|
+
);
|
|
1877
|
+
updated++;
|
|
1878
|
+
}
|
|
1879
|
+
} catch {
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
return updated;
|
|
1883
|
+
}
|
|
1884
|
+
/**
|
|
1885
|
+
* Delete all events for a session (for force reimport)
|
|
1886
|
+
*/
|
|
1887
|
+
async deleteSessionEvents(sessionId) {
|
|
1888
|
+
await this.initialize();
|
|
1889
|
+
const events = sqliteAll(
|
|
1890
|
+
this.db,
|
|
1891
|
+
`SELECT id FROM events WHERE session_id = ?`,
|
|
1892
|
+
[sessionId]
|
|
1893
|
+
);
|
|
1894
|
+
if (events.length === 0)
|
|
1895
|
+
return 0;
|
|
1896
|
+
const eventIds = events.map((e) => e.id);
|
|
1897
|
+
const placeholders = eventIds.map(() => "?").join(",");
|
|
1898
|
+
const ftsTriggersDropped = [];
|
|
1899
|
+
for (const triggerName of ["events_fts_delete", "events_fts_update", "events_fts_insert"]) {
|
|
1900
|
+
try {
|
|
1901
|
+
sqliteRun(this.db, `DROP TRIGGER IF EXISTS ${triggerName}`);
|
|
1902
|
+
ftsTriggersDropped.push(triggerName);
|
|
1903
|
+
} catch {
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
for (const table of ["event_dedup", "memory_levels", "embedding_queue", "embedding_outbox", "vector_outbox"]) {
|
|
1907
|
+
try {
|
|
1908
|
+
sqliteRun(this.db, `DELETE FROM ${table} WHERE event_id IN (${placeholders})`, eventIds);
|
|
1909
|
+
} catch {
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
const result = sqliteRun(this.db, `DELETE FROM events WHERE session_id = ?`, [sessionId]);
|
|
1913
|
+
if (ftsTriggersDropped.length > 0) {
|
|
1914
|
+
try {
|
|
1915
|
+
sqliteRun(this.db, `INSERT INTO events_fts(events_fts) VALUES('rebuild')`);
|
|
1916
|
+
sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events BEGIN
|
|
1917
|
+
INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
|
|
1918
|
+
END`);
|
|
1919
|
+
sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_delete AFTER DELETE ON events BEGIN
|
|
1920
|
+
INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
|
|
1921
|
+
END`);
|
|
1922
|
+
sqliteRun(this.db, `CREATE TRIGGER IF NOT EXISTS events_fts_update AFTER UPDATE ON events BEGIN
|
|
1923
|
+
INSERT INTO events_fts(events_fts, rowid, content) VALUES('delete', OLD.rowid, OLD.content);
|
|
1924
|
+
INSERT INTO events_fts(rowid, content) VALUES (NEW.rowid, NEW.content);
|
|
1925
|
+
END`);
|
|
1926
|
+
} catch {
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
return result.changes || 0;
|
|
1930
|
+
}
|
|
1581
1931
|
/**
|
|
1582
1932
|
* Convert database row to MemoryEvent
|
|
1583
1933
|
*/
|
|
@@ -1598,6 +1948,9 @@ var SQLiteEventStore = class {
|
|
|
1598
1948
|
if (row.last_accessed_at !== void 0) {
|
|
1599
1949
|
event.last_accessed_at = row.last_accessed_at;
|
|
1600
1950
|
}
|
|
1951
|
+
if (row.turn_id !== void 0 && row.turn_id !== null) {
|
|
1952
|
+
event.turn_id = row.turn_id;
|
|
1953
|
+
}
|
|
1601
1954
|
return event;
|
|
1602
1955
|
}
|
|
1603
1956
|
};
|
|
@@ -1809,7 +2162,16 @@ var VectorStore = class {
|
|
|
1809
2162
|
metadata: JSON.stringify(record.metadata || {})
|
|
1810
2163
|
};
|
|
1811
2164
|
if (!this.table) {
|
|
1812
|
-
|
|
2165
|
+
try {
|
|
2166
|
+
this.table = await this.db.createTable(this.tableName, [data]);
|
|
2167
|
+
} catch (e) {
|
|
2168
|
+
if (e?.message?.includes("already exists")) {
|
|
2169
|
+
this.table = await this.db.openTable(this.tableName);
|
|
2170
|
+
await this.table.add([data]);
|
|
2171
|
+
} else {
|
|
2172
|
+
throw e;
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
1813
2175
|
} else {
|
|
1814
2176
|
await this.table.add([data]);
|
|
1815
2177
|
}
|
|
@@ -1835,7 +2197,16 @@ var VectorStore = class {
|
|
|
1835
2197
|
metadata: JSON.stringify(record.metadata || {})
|
|
1836
2198
|
}));
|
|
1837
2199
|
if (!this.table) {
|
|
1838
|
-
|
|
2200
|
+
try {
|
|
2201
|
+
this.table = await this.db.createTable(this.tableName, data);
|
|
2202
|
+
} catch (e) {
|
|
2203
|
+
if (e?.message?.includes("already exists")) {
|
|
2204
|
+
this.table = await this.db.openTable(this.tableName);
|
|
2205
|
+
await this.table.add(data);
|
|
2206
|
+
} else {
|
|
2207
|
+
throw e;
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
1839
2210
|
} else {
|
|
1840
2211
|
await this.table.add(data);
|
|
1841
2212
|
}
|
|
@@ -4581,7 +4952,7 @@ function createGraduationWorker(eventStore, graduation, config) {
|
|
|
4581
4952
|
function normalizePath(projectPath) {
|
|
4582
4953
|
const expanded = projectPath.startsWith("~") ? path.join(os.homedir(), projectPath.slice(1)) : projectPath;
|
|
4583
4954
|
try {
|
|
4584
|
-
return
|
|
4955
|
+
return fs2.realpathSync(expanded);
|
|
4585
4956
|
} catch {
|
|
4586
4957
|
return path.resolve(expanded);
|
|
4587
4958
|
}
|
|
@@ -4596,6 +4967,17 @@ function getProjectStoragePath(projectPath) {
|
|
|
4596
4967
|
}
|
|
4597
4968
|
var REGISTRY_PATH = path.join(os.homedir(), ".claude-code", "memory", "session-registry.json");
|
|
4598
4969
|
var SHARED_STORAGE_PATH = path.join(os.homedir(), ".claude-code", "memory", "shared");
|
|
4970
|
+
function loadSessionRegistry() {
|
|
4971
|
+
try {
|
|
4972
|
+
if (fs2.existsSync(REGISTRY_PATH)) {
|
|
4973
|
+
const data = fs2.readFileSync(REGISTRY_PATH, "utf-8");
|
|
4974
|
+
return JSON.parse(data);
|
|
4975
|
+
}
|
|
4976
|
+
} catch (error) {
|
|
4977
|
+
console.error("Failed to load session registry:", error);
|
|
4978
|
+
}
|
|
4979
|
+
return { version: 1, sessions: {} };
|
|
4980
|
+
}
|
|
4599
4981
|
var MemoryService = class {
|
|
4600
4982
|
// Primary store: SQLite (WAL mode) - for hooks, always available
|
|
4601
4983
|
sqliteStore;
|
|
@@ -4629,8 +5011,8 @@ var MemoryService = class {
|
|
|
4629
5011
|
const storagePath = this.expandPath(config.storagePath);
|
|
4630
5012
|
this.readOnly = config.readOnly ?? false;
|
|
4631
5013
|
this.lightweightMode = config.lightweightMode ?? false;
|
|
4632
|
-
if (!this.readOnly && !
|
|
4633
|
-
|
|
5014
|
+
if (!this.readOnly && !fs2.existsSync(storagePath)) {
|
|
5015
|
+
fs2.mkdirSync(storagePath, { recursive: true });
|
|
4634
5016
|
}
|
|
4635
5017
|
this.projectHash = config.projectHash || null;
|
|
4636
5018
|
this.sharedStoreConfig = config.sharedStoreConfig ?? { enabled: true };
|
|
@@ -4725,8 +5107,8 @@ var MemoryService = class {
|
|
|
4725
5107
|
*/
|
|
4726
5108
|
async initializeSharedStore() {
|
|
4727
5109
|
const sharedPath = this.sharedStoreConfig?.sharedStoragePath ? this.expandPath(this.sharedStoreConfig.sharedStoragePath) : SHARED_STORAGE_PATH;
|
|
4728
|
-
if (!
|
|
4729
|
-
|
|
5110
|
+
if (!fs2.existsSync(sharedPath)) {
|
|
5111
|
+
fs2.mkdirSync(sharedPath, { recursive: true });
|
|
4730
5112
|
}
|
|
4731
5113
|
this.sharedEventStore = createSharedEventStore(
|
|
4732
5114
|
path.join(sharedPath, "shared.duckdb")
|
|
@@ -4823,6 +5205,7 @@ var MemoryService = class {
|
|
|
4823
5205
|
async storeToolObservation(sessionId, payload) {
|
|
4824
5206
|
await this.initialize();
|
|
4825
5207
|
const content = JSON.stringify(payload);
|
|
5208
|
+
const turnId = payload.metadata?.turnId;
|
|
4826
5209
|
const result = await this.sqliteStore.append({
|
|
4827
5210
|
eventType: "tool_observation",
|
|
4828
5211
|
sessionId,
|
|
@@ -4830,7 +5213,8 @@ var MemoryService = class {
|
|
|
4830
5213
|
content,
|
|
4831
5214
|
metadata: {
|
|
4832
5215
|
toolName: payload.toolName,
|
|
4833
|
-
success: payload.success
|
|
5216
|
+
success: payload.success,
|
|
5217
|
+
...turnId ? { turnId } : {}
|
|
4834
5218
|
}
|
|
4835
5219
|
});
|
|
4836
5220
|
if (result.success && !result.isDuplicate) {
|
|
@@ -5113,6 +5497,31 @@ var MemoryService = class {
|
|
|
5113
5497
|
return [];
|
|
5114
5498
|
return this.consolidatedStore.getAll({ limit });
|
|
5115
5499
|
}
|
|
5500
|
+
/**
|
|
5501
|
+
* Extract topic keywords from event content (markdown headings and key terms)
|
|
5502
|
+
*/
|
|
5503
|
+
extractTopicsFromContent(content) {
|
|
5504
|
+
const topics = /* @__PURE__ */ new Set();
|
|
5505
|
+
const headings = content.match(/^#{1,3}\s+(.+)$/gm);
|
|
5506
|
+
if (headings) {
|
|
5507
|
+
for (const h of headings.slice(0, 5)) {
|
|
5508
|
+
const text = h.replace(/^#+\s+/, "").replace(/[*_`#]/g, "").trim();
|
|
5509
|
+
if (text.length > 2 && text.length < 50) {
|
|
5510
|
+
topics.add(text);
|
|
5511
|
+
}
|
|
5512
|
+
}
|
|
5513
|
+
}
|
|
5514
|
+
const boldTerms = content.match(/\*\*([^*]+)\*\*/g);
|
|
5515
|
+
if (boldTerms) {
|
|
5516
|
+
for (const b of boldTerms.slice(0, 5)) {
|
|
5517
|
+
const text = b.replace(/\*\*/g, "").trim();
|
|
5518
|
+
if (text.length > 2 && text.length < 30) {
|
|
5519
|
+
topics.add(text);
|
|
5520
|
+
}
|
|
5521
|
+
}
|
|
5522
|
+
}
|
|
5523
|
+
return Array.from(topics).slice(0, 5);
|
|
5524
|
+
}
|
|
5116
5525
|
/**
|
|
5117
5526
|
* Increment access count for memories that were used in prompts
|
|
5118
5527
|
*/
|
|
@@ -5136,8 +5545,7 @@ var MemoryService = class {
|
|
|
5136
5545
|
return events.map((event) => ({
|
|
5137
5546
|
memoryId: event.id,
|
|
5138
5547
|
summary: event.content.substring(0, 200) + (event.content.length > 200 ? "..." : ""),
|
|
5139
|
-
topics:
|
|
5140
|
-
// Could extract topics from content if needed
|
|
5548
|
+
topics: this.extractTopicsFromContent(event.content),
|
|
5141
5549
|
accessCount: event.access_count || 0,
|
|
5142
5550
|
lastAccessed: event.last_accessed_at || null,
|
|
5143
5551
|
confidence: 1,
|
|
@@ -5158,6 +5566,34 @@ var MemoryService = class {
|
|
|
5158
5566
|
}
|
|
5159
5567
|
return [];
|
|
5160
5568
|
}
|
|
5569
|
+
/**
|
|
5570
|
+
* Record a memory retrieval for helpfulness tracking
|
|
5571
|
+
*/
|
|
5572
|
+
async recordRetrieval(eventId, sessionId, score, query) {
|
|
5573
|
+
await this.initialize();
|
|
5574
|
+
await this.sqliteStore.recordRetrieval(eventId, sessionId, score, query);
|
|
5575
|
+
}
|
|
5576
|
+
/**
|
|
5577
|
+
* Evaluate helpfulness of retrievals in a session (called at session end)
|
|
5578
|
+
*/
|
|
5579
|
+
async evaluateSessionHelpfulness(sessionId) {
|
|
5580
|
+
await this.initialize();
|
|
5581
|
+
await this.sqliteStore.evaluateSessionHelpfulness(sessionId);
|
|
5582
|
+
}
|
|
5583
|
+
/**
|
|
5584
|
+
* Get most helpful memories ranked by helpfulness score
|
|
5585
|
+
*/
|
|
5586
|
+
async getHelpfulMemories(limit = 10) {
|
|
5587
|
+
await this.initialize();
|
|
5588
|
+
return this.sqliteStore.getHelpfulMemories(limit);
|
|
5589
|
+
}
|
|
5590
|
+
/**
|
|
5591
|
+
* Get helpfulness statistics for dashboard
|
|
5592
|
+
*/
|
|
5593
|
+
async getHelpfulnessStats() {
|
|
5594
|
+
await this.initialize();
|
|
5595
|
+
return this.sqliteStore.getHelpfulnessStats();
|
|
5596
|
+
}
|
|
5161
5597
|
/**
|
|
5162
5598
|
* Mark a consolidated memory as accessed
|
|
5163
5599
|
*/
|
|
@@ -5221,6 +5657,44 @@ var MemoryService = class {
|
|
|
5221
5657
|
lastConsolidation
|
|
5222
5658
|
};
|
|
5223
5659
|
}
|
|
5660
|
+
// ============================================================
|
|
5661
|
+
// Turn Grouping Methods
|
|
5662
|
+
// ============================================================
|
|
5663
|
+
/**
|
|
5664
|
+
* Get events grouped by turn for a session
|
|
5665
|
+
*/
|
|
5666
|
+
async getSessionTurns(sessionId, options) {
|
|
5667
|
+
await this.initialize();
|
|
5668
|
+
return this.sqliteStore.getSessionTurns(sessionId, options);
|
|
5669
|
+
}
|
|
5670
|
+
/**
|
|
5671
|
+
* Get all events for a specific turn
|
|
5672
|
+
*/
|
|
5673
|
+
async getEventsByTurn(turnId) {
|
|
5674
|
+
await this.initialize();
|
|
5675
|
+
return this.sqliteStore.getEventsByTurn(turnId);
|
|
5676
|
+
}
|
|
5677
|
+
/**
|
|
5678
|
+
* Count total turns for a session
|
|
5679
|
+
*/
|
|
5680
|
+
async countSessionTurns(sessionId) {
|
|
5681
|
+
await this.initialize();
|
|
5682
|
+
return this.sqliteStore.countSessionTurns(sessionId);
|
|
5683
|
+
}
|
|
5684
|
+
/**
|
|
5685
|
+
* Backfill turn_ids from metadata for events stored before the migration
|
|
5686
|
+
*/
|
|
5687
|
+
async backfillTurnIds() {
|
|
5688
|
+
await this.initialize();
|
|
5689
|
+
return this.sqliteStore.backfillTurnIds();
|
|
5690
|
+
}
|
|
5691
|
+
/**
|
|
5692
|
+
* Delete all events for a session (for force reimport)
|
|
5693
|
+
*/
|
|
5694
|
+
async deleteSessionEvents(sessionId) {
|
|
5695
|
+
await this.initialize();
|
|
5696
|
+
return this.sqliteStore.deleteSessionEvents(sessionId);
|
|
5697
|
+
}
|
|
5224
5698
|
/**
|
|
5225
5699
|
* Format Endless Mode context for Claude
|
|
5226
5700
|
*/
|
|
@@ -5329,12 +5803,36 @@ function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
|
|
|
5329
5803
|
return serviceCache.get(hash);
|
|
5330
5804
|
}
|
|
5331
5805
|
|
|
5806
|
+
// src/server/api/utils.ts
|
|
5807
|
+
function getServiceFromQuery(c) {
|
|
5808
|
+
const project = c.req.query("project");
|
|
5809
|
+
if (project) {
|
|
5810
|
+
const isHash = /^[a-f0-9]{8}$/.test(project);
|
|
5811
|
+
let storagePath;
|
|
5812
|
+
if (isHash) {
|
|
5813
|
+
storagePath = path2.join(os2.homedir(), ".claude-code", "memory", "projects", project);
|
|
5814
|
+
} else {
|
|
5815
|
+
const crypto3 = __require("crypto");
|
|
5816
|
+
const normalized = project.replace(/\/+$/, "") || "/";
|
|
5817
|
+
const hash = crypto3.createHash("sha256").update(normalized).digest("hex").slice(0, 8);
|
|
5818
|
+
storagePath = path2.join(os2.homedir(), ".claude-code", "memory", "projects", hash);
|
|
5819
|
+
}
|
|
5820
|
+
return new MemoryService({
|
|
5821
|
+
storagePath,
|
|
5822
|
+
readOnly: true,
|
|
5823
|
+
analyticsEnabled: false,
|
|
5824
|
+
sharedStoreConfig: { enabled: false }
|
|
5825
|
+
});
|
|
5826
|
+
}
|
|
5827
|
+
return getReadOnlyMemoryService();
|
|
5828
|
+
}
|
|
5829
|
+
|
|
5332
5830
|
// src/server/api/sessions.ts
|
|
5333
5831
|
var sessionsRouter = new Hono();
|
|
5334
5832
|
sessionsRouter.get("/", async (c) => {
|
|
5335
5833
|
const page = parseInt(c.req.query("page") || "1", 10);
|
|
5336
5834
|
const pageSize = parseInt(c.req.query("pageSize") || "20", 10);
|
|
5337
|
-
const memoryService =
|
|
5835
|
+
const memoryService = getServiceFromQuery(c);
|
|
5338
5836
|
try {
|
|
5339
5837
|
await memoryService.initialize();
|
|
5340
5838
|
const recentEvents = await memoryService.getRecentEvents(1e3);
|
|
@@ -5378,7 +5876,7 @@ sessionsRouter.get("/", async (c) => {
|
|
|
5378
5876
|
});
|
|
5379
5877
|
sessionsRouter.get("/:id", async (c) => {
|
|
5380
5878
|
const { id } = c.req.param();
|
|
5381
|
-
const memoryService =
|
|
5879
|
+
const memoryService = getServiceFromQuery(c);
|
|
5382
5880
|
try {
|
|
5383
5881
|
await memoryService.initialize();
|
|
5384
5882
|
const events = await memoryService.getSessionHistory(id);
|
|
@@ -5419,18 +5917,36 @@ var eventsRouter = new Hono2();
|
|
|
5419
5917
|
eventsRouter.get("/", async (c) => {
|
|
5420
5918
|
const sessionId = c.req.query("sessionId");
|
|
5421
5919
|
const eventType = c.req.query("type");
|
|
5920
|
+
const level = c.req.query("level");
|
|
5921
|
+
const sort = c.req.query("sort") || "recent";
|
|
5422
5922
|
const limit = parseInt(c.req.query("limit") || "100", 10);
|
|
5423
5923
|
const offset = parseInt(c.req.query("offset") || "0", 10);
|
|
5424
|
-
const memoryService =
|
|
5924
|
+
const memoryService = getServiceFromQuery(c);
|
|
5425
5925
|
try {
|
|
5426
5926
|
await memoryService.initialize();
|
|
5427
|
-
let events
|
|
5927
|
+
let events;
|
|
5928
|
+
if (level) {
|
|
5929
|
+
events = await memoryService.getEventsByLevel(level, { limit: limit + offset + 1e3, offset: 0 });
|
|
5930
|
+
} else {
|
|
5931
|
+
events = await memoryService.getRecentEvents(limit + offset + 1e3);
|
|
5932
|
+
}
|
|
5428
5933
|
if (sessionId) {
|
|
5429
5934
|
events = events.filter((e) => e.sessionId === sessionId);
|
|
5430
5935
|
}
|
|
5431
5936
|
if (eventType) {
|
|
5432
5937
|
events = events.filter((e) => e.eventType === eventType);
|
|
5433
5938
|
}
|
|
5939
|
+
if (sort === "accessed") {
|
|
5940
|
+
events.sort((a, b) => {
|
|
5941
|
+
const aTime = a.last_accessed_at || "";
|
|
5942
|
+
const bTime = b.last_accessed_at || "";
|
|
5943
|
+
return bTime.localeCompare(aTime);
|
|
5944
|
+
});
|
|
5945
|
+
} else if (sort === "most-accessed") {
|
|
5946
|
+
events.sort((a, b) => (b.access_count || 0) - (a.access_count || 0));
|
|
5947
|
+
} else if (sort === "oldest") {
|
|
5948
|
+
events.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
|
|
5949
|
+
}
|
|
5434
5950
|
const total = events.length;
|
|
5435
5951
|
events = events.slice(offset, offset + limit);
|
|
5436
5952
|
return c.json({
|
|
@@ -5440,7 +5956,9 @@ eventsRouter.get("/", async (c) => {
|
|
|
5440
5956
|
timestamp: e.timestamp,
|
|
5441
5957
|
sessionId: e.sessionId,
|
|
5442
5958
|
preview: e.content.slice(0, 200) + (e.content.length > 200 ? "..." : ""),
|
|
5443
|
-
contentLength: e.content.length
|
|
5959
|
+
contentLength: e.content.length,
|
|
5960
|
+
accessCount: e.access_count || 0,
|
|
5961
|
+
lastAccessedAt: e.last_accessed_at || null
|
|
5444
5962
|
})),
|
|
5445
5963
|
total,
|
|
5446
5964
|
limit,
|
|
@@ -5455,7 +5973,7 @@ eventsRouter.get("/", async (c) => {
|
|
|
5455
5973
|
});
|
|
5456
5974
|
eventsRouter.get("/:id", async (c) => {
|
|
5457
5975
|
const { id } = c.req.param();
|
|
5458
|
-
const memoryService =
|
|
5976
|
+
const memoryService = getServiceFromQuery(c);
|
|
5459
5977
|
try {
|
|
5460
5978
|
await memoryService.initialize();
|
|
5461
5979
|
const recentEvents = await memoryService.getRecentEvents(1e4);
|
|
@@ -5495,7 +6013,7 @@ eventsRouter.get("/:id", async (c) => {
|
|
|
5495
6013
|
import { Hono as Hono3 } from "hono";
|
|
5496
6014
|
var searchRouter = new Hono3();
|
|
5497
6015
|
searchRouter.post("/", async (c) => {
|
|
5498
|
-
const memoryService =
|
|
6016
|
+
const memoryService = getServiceFromQuery(c);
|
|
5499
6017
|
try {
|
|
5500
6018
|
const body = await c.req.json();
|
|
5501
6019
|
if (!body.query) {
|
|
@@ -5539,7 +6057,7 @@ searchRouter.get("/", async (c) => {
|
|
|
5539
6057
|
return c.json({ error: 'Query parameter "q" is required' }, 400);
|
|
5540
6058
|
}
|
|
5541
6059
|
const topK = parseInt(c.req.query("topK") || "5", 10);
|
|
5542
|
-
const memoryService =
|
|
6060
|
+
const memoryService = getServiceFromQuery(c);
|
|
5543
6061
|
try {
|
|
5544
6062
|
await memoryService.initialize();
|
|
5545
6063
|
const result = await memoryService.retrieveMemories(query, { topK });
|
|
@@ -5567,7 +6085,7 @@ searchRouter.get("/", async (c) => {
|
|
|
5567
6085
|
import { Hono as Hono4 } from "hono";
|
|
5568
6086
|
var statsRouter = new Hono4();
|
|
5569
6087
|
statsRouter.get("/shared", async (c) => {
|
|
5570
|
-
const memoryService =
|
|
6088
|
+
const memoryService = getServiceFromQuery(c);
|
|
5571
6089
|
try {
|
|
5572
6090
|
await memoryService.initialize();
|
|
5573
6091
|
const sharedStats = await memoryService.getSharedStoreStats();
|
|
@@ -5624,7 +6142,7 @@ statsRouter.get("/levels/:level", async (c) => {
|
|
|
5624
6142
|
if (!validLevels.includes(level)) {
|
|
5625
6143
|
return c.json({ error: `Invalid level. Must be one of: ${validLevels.join(", ")}` }, 400);
|
|
5626
6144
|
}
|
|
5627
|
-
const memoryService =
|
|
6145
|
+
const memoryService = getServiceFromQuery(c);
|
|
5628
6146
|
try {
|
|
5629
6147
|
await memoryService.initialize();
|
|
5630
6148
|
let events = await memoryService.getEventsByLevel(level, { limit: limit * 2, offset });
|
|
@@ -5671,7 +6189,7 @@ statsRouter.get("/levels/:level", async (c) => {
|
|
|
5671
6189
|
}
|
|
5672
6190
|
});
|
|
5673
6191
|
statsRouter.get("/", async (c) => {
|
|
5674
|
-
const memoryService =
|
|
6192
|
+
const memoryService = getServiceFromQuery(c);
|
|
5675
6193
|
try {
|
|
5676
6194
|
await memoryService.initialize();
|
|
5677
6195
|
const stats = await memoryService.getStats();
|
|
@@ -5715,7 +6233,7 @@ statsRouter.get("/", async (c) => {
|
|
|
5715
6233
|
});
|
|
5716
6234
|
statsRouter.get("/most-accessed", async (c) => {
|
|
5717
6235
|
const limit = parseInt(c.req.query("limit") || "10", 10);
|
|
5718
|
-
const memoryService =
|
|
6236
|
+
const memoryService = getServiceFromQuery(c);
|
|
5719
6237
|
try {
|
|
5720
6238
|
await memoryService.initialize();
|
|
5721
6239
|
console.log("[most-accessed] Fetching most accessed memories, limit:", limit);
|
|
@@ -5746,7 +6264,7 @@ statsRouter.get("/most-accessed", async (c) => {
|
|
|
5746
6264
|
});
|
|
5747
6265
|
statsRouter.get("/timeline", async (c) => {
|
|
5748
6266
|
const days = parseInt(c.req.query("days") || "7", 10);
|
|
5749
|
-
const memoryService =
|
|
6267
|
+
const memoryService = getServiceFromQuery(c);
|
|
5750
6268
|
try {
|
|
5751
6269
|
await memoryService.initialize();
|
|
5752
6270
|
const recentEvents = await memoryService.getRecentEvents(1e4);
|
|
@@ -5776,8 +6294,39 @@ statsRouter.get("/timeline", async (c) => {
|
|
|
5776
6294
|
await memoryService.shutdown();
|
|
5777
6295
|
}
|
|
5778
6296
|
});
|
|
6297
|
+
statsRouter.get("/helpfulness", async (c) => {
|
|
6298
|
+
const limit = parseInt(c.req.query("limit") || "10", 10);
|
|
6299
|
+
const memoryService = getServiceFromQuery(c);
|
|
6300
|
+
try {
|
|
6301
|
+
await memoryService.initialize();
|
|
6302
|
+
const stats = await memoryService.getHelpfulnessStats();
|
|
6303
|
+
const topMemories = await memoryService.getHelpfulMemories(limit);
|
|
6304
|
+
return c.json({
|
|
6305
|
+
...stats,
|
|
6306
|
+
topMemories: topMemories.map((m) => ({
|
|
6307
|
+
eventId: m.eventId,
|
|
6308
|
+
summary: m.summary,
|
|
6309
|
+
helpfulnessScore: m.helpfulnessScore,
|
|
6310
|
+
accessCount: m.accessCount,
|
|
6311
|
+
evaluationCount: m.evaluationCount
|
|
6312
|
+
}))
|
|
6313
|
+
});
|
|
6314
|
+
} catch (error) {
|
|
6315
|
+
return c.json({
|
|
6316
|
+
avgScore: 0,
|
|
6317
|
+
totalEvaluated: 0,
|
|
6318
|
+
totalRetrievals: 0,
|
|
6319
|
+
helpful: 0,
|
|
6320
|
+
neutral: 0,
|
|
6321
|
+
unhelpful: 0,
|
|
6322
|
+
topMemories: []
|
|
6323
|
+
});
|
|
6324
|
+
} finally {
|
|
6325
|
+
await memoryService.shutdown();
|
|
6326
|
+
}
|
|
6327
|
+
});
|
|
5779
6328
|
statsRouter.post("/graduation/run", async (c) => {
|
|
5780
|
-
const memoryService =
|
|
6329
|
+
const memoryService = getServiceFromQuery(c);
|
|
5781
6330
|
try {
|
|
5782
6331
|
await memoryService.initialize();
|
|
5783
6332
|
const result = await memoryService.forceGraduation();
|
|
@@ -5838,7 +6387,7 @@ var citationsRouter = new Hono5();
|
|
|
5838
6387
|
citationsRouter.get("/:id", async (c) => {
|
|
5839
6388
|
const { id } = c.req.param();
|
|
5840
6389
|
const citationId = parseCitationId(id) || id;
|
|
5841
|
-
const memoryService =
|
|
6390
|
+
const memoryService = getServiceFromQuery(c);
|
|
5842
6391
|
try {
|
|
5843
6392
|
await memoryService.initialize();
|
|
5844
6393
|
const recentEvents = await memoryService.getRecentEvents(1e4);
|
|
@@ -5872,7 +6421,7 @@ citationsRouter.get("/:id", async (c) => {
|
|
|
5872
6421
|
citationsRouter.get("/:id/related", async (c) => {
|
|
5873
6422
|
const { id } = c.req.param();
|
|
5874
6423
|
const citationId = parseCitationId(id) || id;
|
|
5875
|
-
const memoryService =
|
|
6424
|
+
const memoryService = getServiceFromQuery(c);
|
|
5876
6425
|
try {
|
|
5877
6426
|
await memoryService.initialize();
|
|
5878
6427
|
const recentEvents = await memoryService.getRecentEvents(1e4);
|
|
@@ -5908,23 +6457,373 @@ citationsRouter.get("/:id/related", async (c) => {
|
|
|
5908
6457
|
}
|
|
5909
6458
|
});
|
|
5910
6459
|
|
|
6460
|
+
// src/server/api/turns.ts
|
|
6461
|
+
import { Hono as Hono6 } from "hono";
|
|
6462
|
+
var turnsRouter = new Hono6();
|
|
6463
|
+
turnsRouter.get("/", async (c) => {
|
|
6464
|
+
const sessionId = c.req.query("sessionId");
|
|
6465
|
+
const limit = parseInt(c.req.query("limit") || "20", 10);
|
|
6466
|
+
const offset = parseInt(c.req.query("offset") || "0", 10);
|
|
6467
|
+
if (!sessionId) {
|
|
6468
|
+
return c.json({ error: "sessionId is required" }, 400);
|
|
6469
|
+
}
|
|
6470
|
+
const memoryService = getServiceFromQuery(c);
|
|
6471
|
+
try {
|
|
6472
|
+
await memoryService.initialize();
|
|
6473
|
+
const turns = await memoryService.getSessionTurns(sessionId, { limit, offset });
|
|
6474
|
+
const totalTurns = await memoryService.countSessionTurns(sessionId);
|
|
6475
|
+
return c.json({
|
|
6476
|
+
turns: turns.map((t) => ({
|
|
6477
|
+
turnId: t.turnId,
|
|
6478
|
+
startedAt: t.startedAt.toISOString(),
|
|
6479
|
+
promptPreview: t.promptPreview,
|
|
6480
|
+
eventCount: t.eventCount,
|
|
6481
|
+
toolCount: t.toolCount,
|
|
6482
|
+
hasResponse: t.hasResponse,
|
|
6483
|
+
events: t.events.map((e) => ({
|
|
6484
|
+
id: e.id,
|
|
6485
|
+
eventType: e.eventType,
|
|
6486
|
+
timestamp: e.timestamp instanceof Date ? e.timestamp.toISOString() : e.timestamp,
|
|
6487
|
+
preview: e.content.slice(0, 300) + (e.content.length > 300 ? "..." : ""),
|
|
6488
|
+
contentLength: e.content.length
|
|
6489
|
+
}))
|
|
6490
|
+
})),
|
|
6491
|
+
total: totalTurns,
|
|
6492
|
+
limit,
|
|
6493
|
+
offset,
|
|
6494
|
+
hasMore: offset + limit < totalTurns
|
|
6495
|
+
});
|
|
6496
|
+
} catch (error) {
|
|
6497
|
+
return c.json({ error: error.message }, 500);
|
|
6498
|
+
} finally {
|
|
6499
|
+
await memoryService.shutdown();
|
|
6500
|
+
}
|
|
6501
|
+
});
|
|
6502
|
+
turnsRouter.get("/:turnId", async (c) => {
|
|
6503
|
+
const { turnId } = c.req.param();
|
|
6504
|
+
const memoryService = getServiceFromQuery(c);
|
|
6505
|
+
try {
|
|
6506
|
+
await memoryService.initialize();
|
|
6507
|
+
const events = await memoryService.getEventsByTurn(turnId);
|
|
6508
|
+
if (events.length === 0) {
|
|
6509
|
+
return c.json({ error: "Turn not found" }, 404);
|
|
6510
|
+
}
|
|
6511
|
+
const promptEvent = events.find((e) => e.eventType === "user_prompt");
|
|
6512
|
+
const toolEvents = events.filter((e) => e.eventType === "tool_observation");
|
|
6513
|
+
const responseEvents = events.filter((e) => e.eventType === "agent_response");
|
|
6514
|
+
return c.json({
|
|
6515
|
+
turnId,
|
|
6516
|
+
sessionId: events[0].sessionId,
|
|
6517
|
+
startedAt: events[0].timestamp instanceof Date ? events[0].timestamp.toISOString() : events[0].timestamp,
|
|
6518
|
+
prompt: promptEvent ? {
|
|
6519
|
+
id: promptEvent.id,
|
|
6520
|
+
content: promptEvent.content,
|
|
6521
|
+
timestamp: promptEvent.timestamp instanceof Date ? promptEvent.timestamp.toISOString() : promptEvent.timestamp
|
|
6522
|
+
} : null,
|
|
6523
|
+
tools: toolEvents.map((e) => {
|
|
6524
|
+
let toolName = "";
|
|
6525
|
+
let success = true;
|
|
6526
|
+
try {
|
|
6527
|
+
const parsed = JSON.parse(e.content);
|
|
6528
|
+
toolName = parsed.toolName || "";
|
|
6529
|
+
success = parsed.success !== false;
|
|
6530
|
+
} catch {
|
|
6531
|
+
}
|
|
6532
|
+
return {
|
|
6533
|
+
id: e.id,
|
|
6534
|
+
toolName,
|
|
6535
|
+
success,
|
|
6536
|
+
timestamp: e.timestamp instanceof Date ? e.timestamp.toISOString() : e.timestamp,
|
|
6537
|
+
preview: e.content.slice(0, 500) + (e.content.length > 500 ? "..." : "")
|
|
6538
|
+
};
|
|
6539
|
+
}),
|
|
6540
|
+
responses: responseEvents.map((e) => ({
|
|
6541
|
+
id: e.id,
|
|
6542
|
+
content: e.content,
|
|
6543
|
+
timestamp: e.timestamp instanceof Date ? e.timestamp.toISOString() : e.timestamp
|
|
6544
|
+
})),
|
|
6545
|
+
totalEvents: events.length
|
|
6546
|
+
});
|
|
6547
|
+
} catch (error) {
|
|
6548
|
+
return c.json({ error: error.message }, 500);
|
|
6549
|
+
} finally {
|
|
6550
|
+
await memoryService.shutdown();
|
|
6551
|
+
}
|
|
6552
|
+
});
|
|
6553
|
+
turnsRouter.post("/backfill", async (c) => {
|
|
6554
|
+
const memoryService = getServiceFromQuery(c);
|
|
6555
|
+
try {
|
|
6556
|
+
await memoryService.initialize();
|
|
6557
|
+
const updated = await memoryService.backfillTurnIds();
|
|
6558
|
+
return c.json({
|
|
6559
|
+
success: true,
|
|
6560
|
+
updated,
|
|
6561
|
+
message: `Backfilled turn_id for ${updated} events`
|
|
6562
|
+
});
|
|
6563
|
+
} catch (error) {
|
|
6564
|
+
return c.json({
|
|
6565
|
+
success: false,
|
|
6566
|
+
error: error.message
|
|
6567
|
+
}, 500);
|
|
6568
|
+
} finally {
|
|
6569
|
+
await memoryService.shutdown();
|
|
6570
|
+
}
|
|
6571
|
+
});
|
|
6572
|
+
|
|
6573
|
+
// src/server/api/projects.ts
|
|
6574
|
+
import { Hono as Hono7 } from "hono";
|
|
6575
|
+
import * as fs3 from "fs";
|
|
6576
|
+
import * as path3 from "path";
|
|
6577
|
+
import * as os3 from "os";
|
|
6578
|
+
var projectsRouter = new Hono7();
|
|
6579
|
+
projectsRouter.get("/", async (c) => {
|
|
6580
|
+
try {
|
|
6581
|
+
const projectsDir = path3.join(os3.homedir(), ".claude-code", "memory", "projects");
|
|
6582
|
+
if (!fs3.existsSync(projectsDir)) {
|
|
6583
|
+
return c.json({ projects: [] });
|
|
6584
|
+
}
|
|
6585
|
+
const projectHashes = fs3.readdirSync(projectsDir).filter((name) => {
|
|
6586
|
+
const fullPath = path3.join(projectsDir, name);
|
|
6587
|
+
return fs3.statSync(fullPath).isDirectory();
|
|
6588
|
+
});
|
|
6589
|
+
const registry = loadSessionRegistry();
|
|
6590
|
+
const hashToPath = /* @__PURE__ */ new Map();
|
|
6591
|
+
for (const entry of Object.values(registry.sessions)) {
|
|
6592
|
+
if (!hashToPath.has(entry.projectHash)) {
|
|
6593
|
+
hashToPath.set(entry.projectHash, entry.projectPath);
|
|
6594
|
+
}
|
|
6595
|
+
}
|
|
6596
|
+
const projects = projectHashes.map((hash) => {
|
|
6597
|
+
const dirPath = path3.join(projectsDir, hash);
|
|
6598
|
+
const dbPath = path3.join(dirPath, "events.sqlite");
|
|
6599
|
+
let dbSize = 0;
|
|
6600
|
+
if (fs3.existsSync(dbPath)) {
|
|
6601
|
+
dbSize = fs3.statSync(dbPath).size;
|
|
6602
|
+
}
|
|
6603
|
+
const projectPath = hashToPath.get(hash) || `unknown (${hash})`;
|
|
6604
|
+
return {
|
|
6605
|
+
hash,
|
|
6606
|
+
projectPath,
|
|
6607
|
+
projectName: path3.basename(projectPath),
|
|
6608
|
+
dbSize,
|
|
6609
|
+
dbSizeHuman: formatBytes(dbSize)
|
|
6610
|
+
};
|
|
6611
|
+
});
|
|
6612
|
+
projects.sort((a, b) => a.projectName.localeCompare(b.projectName));
|
|
6613
|
+
return c.json({ projects });
|
|
6614
|
+
} catch (error) {
|
|
6615
|
+
return c.json({ projects: [], error: error.message }, 500);
|
|
6616
|
+
}
|
|
6617
|
+
});
|
|
6618
|
+
function formatBytes(bytes) {
|
|
6619
|
+
if (bytes === 0)
|
|
6620
|
+
return "0 B";
|
|
6621
|
+
const k = 1024;
|
|
6622
|
+
const sizes = ["B", "KB", "MB", "GB"];
|
|
6623
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
6624
|
+
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
|
|
6625
|
+
}
|
|
6626
|
+
|
|
6627
|
+
// src/server/api/chat.ts
|
|
6628
|
+
import { Hono as Hono8 } from "hono";
|
|
6629
|
+
import { streamSSE } from "hono/streaming";
|
|
6630
|
+
import { spawn } from "child_process";
|
|
6631
|
+
var chatRouter = new Hono8();
|
|
6632
|
+
var CLAUDE_TIMEOUT_MS = 12e4;
|
|
6633
|
+
chatRouter.post("/", async (c) => {
|
|
6634
|
+
let body;
|
|
6635
|
+
try {
|
|
6636
|
+
body = await c.req.json();
|
|
6637
|
+
} catch {
|
|
6638
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
6639
|
+
}
|
|
6640
|
+
if (!body.message?.trim()) {
|
|
6641
|
+
return c.json({ error: "Message is required" }, 400);
|
|
6642
|
+
}
|
|
6643
|
+
const memoryService = getServiceFromQuery(c);
|
|
6644
|
+
try {
|
|
6645
|
+
await memoryService.initialize();
|
|
6646
|
+
let memoryContext = "";
|
|
6647
|
+
let statsContext = "";
|
|
6648
|
+
try {
|
|
6649
|
+
const result = await memoryService.retrieveMemories(body.message, {
|
|
6650
|
+
topK: 8,
|
|
6651
|
+
minScore: 0.5
|
|
6652
|
+
});
|
|
6653
|
+
if (result.memories.length > 0) {
|
|
6654
|
+
const parts = ["## Relevant Memories\n"];
|
|
6655
|
+
for (const m of result.memories) {
|
|
6656
|
+
const date = new Date(m.event.timestamp).toISOString().split("T")[0];
|
|
6657
|
+
const content = m.event.content.slice(0, 500);
|
|
6658
|
+
parts.push(`### [${m.event.eventType}] ${date} (score: ${m.score.toFixed(2)})`);
|
|
6659
|
+
parts.push(content);
|
|
6660
|
+
if (m.sessionContext) {
|
|
6661
|
+
parts.push(`_Context: ${m.sessionContext}_`);
|
|
6662
|
+
}
|
|
6663
|
+
parts.push("");
|
|
6664
|
+
}
|
|
6665
|
+
memoryContext = parts.join("\n");
|
|
6666
|
+
}
|
|
6667
|
+
} catch {
|
|
6668
|
+
}
|
|
6669
|
+
try {
|
|
6670
|
+
const stats = await memoryService.getStats();
|
|
6671
|
+
const levels = stats.levelStats.map((l) => `${l.level}: ${l.count}`).join(", ");
|
|
6672
|
+
statsContext = [
|
|
6673
|
+
"## Memory Stats",
|
|
6674
|
+
`- Total events: ${stats.totalEvents}`,
|
|
6675
|
+
`- Vector nodes: ${stats.vectorCount}`,
|
|
6676
|
+
`- By level: ${levels}`
|
|
6677
|
+
].join("\n");
|
|
6678
|
+
} catch {
|
|
6679
|
+
}
|
|
6680
|
+
const fullPrompt = buildPrompt(
|
|
6681
|
+
statsContext,
|
|
6682
|
+
memoryContext,
|
|
6683
|
+
body.history || [],
|
|
6684
|
+
body.message
|
|
6685
|
+
);
|
|
6686
|
+
return streamSSE(c, async (stream) => {
|
|
6687
|
+
try {
|
|
6688
|
+
await streamClaudeResponse(fullPrompt, stream);
|
|
6689
|
+
} catch (err) {
|
|
6690
|
+
await stream.writeSSE({
|
|
6691
|
+
event: "error",
|
|
6692
|
+
data: JSON.stringify({ error: err.message })
|
|
6693
|
+
});
|
|
6694
|
+
}
|
|
6695
|
+
});
|
|
6696
|
+
} catch (error) {
|
|
6697
|
+
return c.json({ error: error.message }, 500);
|
|
6698
|
+
} finally {
|
|
6699
|
+
await memoryService.shutdown();
|
|
6700
|
+
}
|
|
6701
|
+
});
|
|
6702
|
+
function buildPrompt(statsContext, memoryContext, history, currentMessage) {
|
|
6703
|
+
const parts = [];
|
|
6704
|
+
parts.push("You are a helpful assistant that answers questions about the user's code memory data.");
|
|
6705
|
+
parts.push("The memory system tracks coding sessions, tool usage, prompts, and responses.");
|
|
6706
|
+
parts.push("Answer concisely based on the memory context below. If you don't have enough data, say so.");
|
|
6707
|
+
parts.push("Use markdown formatting in your responses.\n");
|
|
6708
|
+
if (statsContext) {
|
|
6709
|
+
parts.push(statsContext);
|
|
6710
|
+
parts.push("");
|
|
6711
|
+
}
|
|
6712
|
+
if (memoryContext) {
|
|
6713
|
+
parts.push(memoryContext);
|
|
6714
|
+
} else {
|
|
6715
|
+
parts.push("No directly relevant memories found for this query.");
|
|
6716
|
+
parts.push("Answer based on general knowledge or suggest the user rephrase.\n");
|
|
6717
|
+
}
|
|
6718
|
+
parts.push("---\n");
|
|
6719
|
+
const recentHistory = history.slice(-10);
|
|
6720
|
+
if (recentHistory.length > 0) {
|
|
6721
|
+
parts.push("## Conversation History\n");
|
|
6722
|
+
for (const msg of recentHistory) {
|
|
6723
|
+
const prefix = msg.role === "user" ? "User" : "Assistant";
|
|
6724
|
+
parts.push(`**${prefix}:** ${msg.content}
|
|
6725
|
+
`);
|
|
6726
|
+
}
|
|
6727
|
+
}
|
|
6728
|
+
parts.push(`**User:** ${currentMessage}`);
|
|
6729
|
+
return parts.join("\n");
|
|
6730
|
+
}
|
|
6731
|
+
function streamClaudeResponse(prompt, stream) {
|
|
6732
|
+
return new Promise((resolve2, reject) => {
|
|
6733
|
+
const proc = spawn("claude", [
|
|
6734
|
+
"-p",
|
|
6735
|
+
"--output-format",
|
|
6736
|
+
"stream-json",
|
|
6737
|
+
"--verbose"
|
|
6738
|
+
], {
|
|
6739
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
6740
|
+
env: { ...process.env }
|
|
6741
|
+
});
|
|
6742
|
+
const timeout = setTimeout(() => {
|
|
6743
|
+
proc.kill("SIGTERM");
|
|
6744
|
+
reject(new Error("Chat response timed out after 2 minutes"));
|
|
6745
|
+
}, CLAUDE_TIMEOUT_MS);
|
|
6746
|
+
proc.stdin.write(prompt);
|
|
6747
|
+
proc.stdin.end();
|
|
6748
|
+
let buffer = "";
|
|
6749
|
+
let lastSentText = "";
|
|
6750
|
+
proc.stdout.on("data", async (chunk) => {
|
|
6751
|
+
buffer += chunk.toString();
|
|
6752
|
+
const lines = buffer.split("\n");
|
|
6753
|
+
buffer = lines.pop() || "";
|
|
6754
|
+
for (const line of lines) {
|
|
6755
|
+
if (!line.trim())
|
|
6756
|
+
continue;
|
|
6757
|
+
try {
|
|
6758
|
+
const parsed = JSON.parse(line);
|
|
6759
|
+
if (parsed.type === "assistant" && parsed.message?.content) {
|
|
6760
|
+
const textBlocks = parsed.message.content.filter((b) => b.type === "text").map((b) => b.text).join("");
|
|
6761
|
+
if (textBlocks.length > lastSentText.length) {
|
|
6762
|
+
const delta = textBlocks.slice(lastSentText.length);
|
|
6763
|
+
lastSentText = textBlocks;
|
|
6764
|
+
await stream.writeSSE({
|
|
6765
|
+
event: "message",
|
|
6766
|
+
data: JSON.stringify({ content: delta })
|
|
6767
|
+
});
|
|
6768
|
+
}
|
|
6769
|
+
}
|
|
6770
|
+
if (parsed.type === "result") {
|
|
6771
|
+
await stream.writeSSE({ event: "done", data: "{}" });
|
|
6772
|
+
}
|
|
6773
|
+
} catch {
|
|
6774
|
+
}
|
|
6775
|
+
}
|
|
6776
|
+
});
|
|
6777
|
+
proc.stderr.on("data", (chunk) => {
|
|
6778
|
+
if (process.env.CLAUDE_MEMORY_DEBUG) {
|
|
6779
|
+
console.error("[chat] claude stderr:", chunk.toString());
|
|
6780
|
+
}
|
|
6781
|
+
});
|
|
6782
|
+
proc.on("error", (err) => {
|
|
6783
|
+
clearTimeout(timeout);
|
|
6784
|
+
if (err.code === "ENOENT") {
|
|
6785
|
+
reject(new Error("Claude CLI not found. Install with: npm install -g @anthropic-ai/claude-code"));
|
|
6786
|
+
} else {
|
|
6787
|
+
reject(err);
|
|
6788
|
+
}
|
|
6789
|
+
});
|
|
6790
|
+
proc.on("close", async (code) => {
|
|
6791
|
+
clearTimeout(timeout);
|
|
6792
|
+
if (buffer.trim()) {
|
|
6793
|
+
try {
|
|
6794
|
+
const parsed = JSON.parse(buffer);
|
|
6795
|
+
if (parsed.type === "result") {
|
|
6796
|
+
await stream.writeSSE({ event: "done", data: "{}" });
|
|
6797
|
+
}
|
|
6798
|
+
} catch {
|
|
6799
|
+
}
|
|
6800
|
+
}
|
|
6801
|
+
if (code !== 0 && code !== null) {
|
|
6802
|
+
reject(new Error(`Claude CLI exited with code ${code}`));
|
|
6803
|
+
} else {
|
|
6804
|
+
resolve2();
|
|
6805
|
+
}
|
|
6806
|
+
});
|
|
6807
|
+
});
|
|
6808
|
+
}
|
|
6809
|
+
|
|
5911
6810
|
// src/server/api/index.ts
|
|
5912
|
-
var apiRouter = new
|
|
6811
|
+
var apiRouter = new Hono9().route("/sessions", sessionsRouter).route("/events", eventsRouter).route("/search", searchRouter).route("/stats", statsRouter).route("/citations", citationsRouter).route("/turns", turnsRouter).route("/projects", projectsRouter).route("/chat", chatRouter);
|
|
5913
6812
|
|
|
5914
6813
|
// src/server/index.ts
|
|
5915
|
-
var app = new
|
|
6814
|
+
var app = new Hono10();
|
|
5916
6815
|
app.use("/*", cors());
|
|
5917
6816
|
app.use("/*", logger());
|
|
5918
6817
|
app.route("/api", apiRouter);
|
|
5919
6818
|
app.get("/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
5920
|
-
var uiPath =
|
|
5921
|
-
if (
|
|
6819
|
+
var uiPath = path4.join(__dirname, "../../dist/ui");
|
|
6820
|
+
if (fs4.existsSync(uiPath)) {
|
|
5922
6821
|
app.use("/*", serveStatic({ root: uiPath }));
|
|
5923
6822
|
}
|
|
5924
6823
|
app.get("*", (c) => {
|
|
5925
|
-
const indexPath =
|
|
5926
|
-
if (
|
|
5927
|
-
return c.html(
|
|
6824
|
+
const indexPath = path4.join(uiPath, "index.html");
|
|
6825
|
+
if (fs4.existsSync(indexPath)) {
|
|
6826
|
+
return c.html(fs4.readFileSync(indexPath, "utf-8"));
|
|
5928
6827
|
}
|
|
5929
6828
|
return c.text('UI not built. Run "npm run build:ui" first.', 404);
|
|
5930
6829
|
});
|