memoryrouter-claude 1.0.1 → 2.1.0
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/CHANGELOG.md +50 -0
- package/README.md +189 -64
- package/bin/cli.js +242 -157
- package/lib/api.js +17 -17
- package/lib/config.js +105 -20
- package/lib/hook-runner.js +456 -135
- package/lib/project.js +153 -0
- package/lib/settings.js +56 -58
- package/lib/transcript.js +287 -42
- package/package.json +9 -4
package/lib/transcript.js
CHANGED
|
@@ -1,63 +1,308 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
// Claude Code
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// We extract plain-text user/assistant messages above a high-water mark (line index).
|
|
2
|
+
// Lossless-at-the-cursor Claude Code JSONL parsing. The parser works in bytes,
|
|
3
|
+
// never advances over malformed/incomplete data, and converts noisy transcript
|
|
4
|
+
// records into compact, deterministic memory events.
|
|
6
5
|
|
|
7
6
|
const fs = require('fs');
|
|
7
|
+
const crypto = require('crypto');
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
const MAX_TEXT_CHARS = 12000;
|
|
10
|
+
const MAX_TOOL_INPUT_CHARS = 8000;
|
|
11
|
+
const MAX_TOOL_RESULT_CHARS = 6000;
|
|
12
|
+
|
|
13
|
+
function hash(value) {
|
|
14
|
+
return crypto.createHash('sha256').update(String(value)).digest('hex');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function cleanText(value) {
|
|
18
|
+
return String(value || '')
|
|
19
|
+
.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, '')
|
|
20
|
+
.replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>/gi, '')
|
|
21
|
+
.replace(/\u0000/g, '')
|
|
22
|
+
.trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function compactText(value, maxChars) {
|
|
26
|
+
const text = cleanText(value);
|
|
27
|
+
if (text.length <= maxChars) return text;
|
|
28
|
+
const head = Math.max(1, Math.floor(maxChars * 0.7));
|
|
29
|
+
const tail = Math.max(1, maxChars - head - 80);
|
|
30
|
+
return `${text.slice(0, head)}\n… [${text.length - head - tail} chars omitted] …\n${text.slice(-tail)}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function stableJson(value) {
|
|
34
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
35
|
+
if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
|
|
36
|
+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableJson(value[k])}`).join(',')}}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function event(kind, role, content, extra = {}) {
|
|
40
|
+
const normalized = cleanText(content);
|
|
41
|
+
if (!normalized) return null;
|
|
42
|
+
const tool = extra.tool || '';
|
|
43
|
+
return {
|
|
44
|
+
kind,
|
|
45
|
+
role,
|
|
46
|
+
content: normalized,
|
|
47
|
+
...extra,
|
|
48
|
+
contentKey: hash(`${kind}\n${role}\n${tool}\n${normalized}`).slice(0, 32),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function summarizeToolUse(block) {
|
|
53
|
+
const name = String(block.name || 'unknown');
|
|
54
|
+
const input = block.input && typeof block.input === 'object' ? block.input : {};
|
|
55
|
+
const file = input.file_path || input.path || input.notebook_path;
|
|
56
|
+
const lines = [`Tool call: ${name}`];
|
|
57
|
+
if (file) lines.push(`File: ${file}`);
|
|
58
|
+
if (typeof input.command === 'string') lines.push(`Command: ${compactText(input.command, MAX_TOOL_INPUT_CHARS)}`);
|
|
59
|
+
else if (name === 'Edit' || name === 'MultiEdit') {
|
|
60
|
+
if (input.old_string) lines.push(`Replaced: ${compactText(input.old_string, 2500)}`);
|
|
61
|
+
if (input.new_string) lines.push(`With: ${compactText(input.new_string, 2500)}`);
|
|
62
|
+
if (Array.isArray(input.edits)) lines.push(`Edits: ${compactText(stableJson(input.edits), 5000)}`);
|
|
63
|
+
} else if (name === 'Write' && typeof input.content === 'string') {
|
|
64
|
+
lines.push(`Content: ${compactText(input.content, 3500)}`);
|
|
65
|
+
} else {
|
|
66
|
+
const useful = { ...input };
|
|
67
|
+
delete useful.content;
|
|
68
|
+
const serialized = stableJson(useful);
|
|
69
|
+
if (serialized && serialized !== '{}') lines.push(`Input: ${compactText(serialized, MAX_TOOL_INPUT_CHARS)}`);
|
|
70
|
+
}
|
|
71
|
+
return event('tool_use', 'assistant', lines.join('\n'), {
|
|
72
|
+
tool: name,
|
|
73
|
+
toolUseId: block.id || undefined,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function toolResultText(content) {
|
|
11
78
|
if (typeof content === 'string') return content;
|
|
12
|
-
if (Array.isArray(content))
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
79
|
+
if (!Array.isArray(content)) return stableJson(content);
|
|
80
|
+
return content.map((part) => {
|
|
81
|
+
if (!part) return '';
|
|
82
|
+
if (typeof part === 'string') return part;
|
|
83
|
+
if (part.type === 'text') return part.text || '';
|
|
84
|
+
if (part.type === 'image') return '[image result]';
|
|
85
|
+
return stableJson(part);
|
|
86
|
+
}).filter(Boolean).join('\n');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function summarizeToolResult(block, obj) {
|
|
90
|
+
const detail = toolResultText(block.content);
|
|
91
|
+
const extraResult = obj && obj.toolUseResult && typeof obj.toolUseResult === 'object'
|
|
92
|
+
? obj.toolUseResult
|
|
93
|
+
: null;
|
|
94
|
+
let resultText = detail;
|
|
95
|
+
if (!resultText && extraResult) resultText = stableJson(extraResult);
|
|
96
|
+
const status = block.is_error ? 'failed' : 'completed';
|
|
97
|
+
return event('tool_result', 'user', `Tool ${status}${block.tool_use_id ? ` (${block.tool_use_id})` : ''}:\n${compactText(resultText || '[no textual output]', MAX_TOOL_RESULT_CHARS)}`, {
|
|
98
|
+
toolUseId: block.tool_use_id || undefined,
|
|
99
|
+
isError: block.is_error === true,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function normalizeMessage(obj) {
|
|
104
|
+
const msg = obj && obj.message;
|
|
105
|
+
if (!msg || (msg.role !== 'user' && msg.role !== 'assistant')) return [];
|
|
106
|
+
const role = msg.role;
|
|
107
|
+
const content = msg.content;
|
|
108
|
+
const out = [];
|
|
109
|
+
if (typeof content === 'string') {
|
|
110
|
+
const text = compactText(content, MAX_TEXT_CHARS);
|
|
111
|
+
const ev = event('text', role, text);
|
|
112
|
+
if (ev) out.push(ev);
|
|
113
|
+
return out;
|
|
17
114
|
}
|
|
18
|
-
return
|
|
115
|
+
if (!Array.isArray(content)) return out;
|
|
116
|
+
for (const block of content) {
|
|
117
|
+
if (!block || typeof block !== 'object') continue;
|
|
118
|
+
if (block.type === 'text') {
|
|
119
|
+
const ev = event('text', role, compactText(block.text, MAX_TEXT_CHARS));
|
|
120
|
+
if (ev) out.push(ev);
|
|
121
|
+
} else if (block.type === 'tool_use') {
|
|
122
|
+
const ev = summarizeToolUse(block);
|
|
123
|
+
if (ev) out.push(ev);
|
|
124
|
+
} else if (block.type === 'tool_result') {
|
|
125
|
+
const ev = summarizeToolResult(block, obj);
|
|
126
|
+
if (ev) out.push(ev);
|
|
127
|
+
}
|
|
128
|
+
// Deliberately exclude thinking/signature blocks and binary payloads.
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
19
131
|
}
|
|
20
132
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
133
|
+
function normalizeRecord(obj) {
|
|
134
|
+
if (!obj || typeof obj !== 'object') return [];
|
|
135
|
+
if (obj.isSidechain) return [];
|
|
136
|
+
return normalizeMessage(obj).map((ev, index) => ({
|
|
137
|
+
...ev,
|
|
138
|
+
// Claude transcript UUID + block index distinguishes legitimate repeated
|
|
139
|
+
// content in later turns. Content keys remain available solely to match a
|
|
140
|
+
// Stop fallback with the same message once JSONL catches up.
|
|
141
|
+
eventKey: obj.uuid
|
|
142
|
+
? hash(`record\n${obj.uuid}\n${index}\n${ev.contentKey}`).slice(0, 32)
|
|
143
|
+
: ev.contentKey,
|
|
144
|
+
}));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function parseBuffer(buffer, baseOffset = 0) {
|
|
148
|
+
const records = [];
|
|
149
|
+
let position = 0;
|
|
150
|
+
let blockedOffset = null;
|
|
151
|
+
|
|
152
|
+
while (position < buffer.length) {
|
|
153
|
+
const newline = buffer.indexOf(0x0a, position);
|
|
154
|
+
const end = newline === -1 ? buffer.length : newline + 1;
|
|
155
|
+
const raw = buffer.subarray(position, newline === -1 ? end : newline);
|
|
156
|
+
const text = raw.toString('utf8').replace(/\r$/, '').trim();
|
|
157
|
+
const startOffset = baseOffset + position;
|
|
158
|
+
const endOffset = baseOffset + end;
|
|
159
|
+
position = end;
|
|
160
|
+
|
|
161
|
+
if (!text) {
|
|
162
|
+
records.push({ startOffset, endOffset, events: [], ignored: true });
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
33
165
|
let obj;
|
|
34
166
|
try {
|
|
35
|
-
obj = JSON.parse(
|
|
167
|
+
obj = JSON.parse(text);
|
|
36
168
|
} catch {
|
|
37
|
-
|
|
169
|
+
blockedOffset = startOffset;
|
|
170
|
+
break;
|
|
38
171
|
}
|
|
39
|
-
|
|
40
|
-
|
|
172
|
+
records.push({ startOffset, endOffset, events: normalizeRecord(obj), ignored: false });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
records,
|
|
177
|
+
blockedOffset,
|
|
178
|
+
nextOffset: records.length ? records[records.length - 1].endOffset : baseOffset,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function readTranscriptDelta(transcriptPath, afterOffset = 0) {
|
|
183
|
+
let data;
|
|
184
|
+
try { data = fs.readFileSync(transcriptPath); } catch {
|
|
185
|
+
return { records: [], nextOffset: afterOffset, blockedOffset: null, fileSize: null, reset: false };
|
|
186
|
+
}
|
|
187
|
+
let cursor = Number.isInteger(afterOffset) && afterOffset >= 0 ? afterOffset : 0;
|
|
188
|
+
let reset = false;
|
|
189
|
+
if (cursor > data.length) {
|
|
190
|
+
cursor = 0;
|
|
191
|
+
reset = true;
|
|
192
|
+
}
|
|
193
|
+
const parsed = parseBuffer(data.subarray(cursor), cursor);
|
|
194
|
+
return { ...parsed, fileSize: data.length, reset };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function lineIndexToOffset(transcriptPath, lineIndex) {
|
|
198
|
+
if (!Number.isInteger(lineIndex) || lineIndex < 0) return 0;
|
|
199
|
+
let data;
|
|
200
|
+
try { data = fs.readFileSync(transcriptPath); } catch { return 0; }
|
|
201
|
+
let lines = 0;
|
|
202
|
+
for (let i = 0; i < data.length; i++) {
|
|
203
|
+
if (data[i] === 0x0a) {
|
|
204
|
+
if (lines === lineIndex) return i + 1;
|
|
205
|
+
lines++;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return lines === lineIndex ? data.length : 0;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function contentToText(content) {
|
|
212
|
+
if (typeof content === 'string') return cleanText(content);
|
|
213
|
+
if (!Array.isArray(content)) return '';
|
|
214
|
+
return content.filter((b) => b && b.type === 'text').map((b) => cleanText(b.text)).filter(Boolean).join('\n');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Return only a completed, main-chain, user-visible final assistant message.
|
|
219
|
+
*
|
|
220
|
+
* A transcript fallback is intentionally conservative:
|
|
221
|
+
* - malformed/partially-written JSON blocks fallback entirely;
|
|
222
|
+
* - sidechains, tool results, thinking, and binary blocks are ignored;
|
|
223
|
+
* - an assistant record containing tool_use is intermediate and cannot be final;
|
|
224
|
+
* - the last assistant record after the turn boundary must be text-only;
|
|
225
|
+
* - when no reliable byte boundary exists, the matching user prompt establishes
|
|
226
|
+
* the boundary. If that prompt cannot be found, no old answer is guessed.
|
|
227
|
+
*/
|
|
228
|
+
function finalAssistantFromTranscript(transcriptPath, options = {}) {
|
|
229
|
+
let data;
|
|
230
|
+
try { data = fs.readFileSync(transcriptPath); } catch { return null; }
|
|
231
|
+
|
|
232
|
+
const requestedOffset = Number.isInteger(options.afterOffset) && options.afterOffset >= 0
|
|
233
|
+
? options.afterOffset
|
|
234
|
+
: null;
|
|
235
|
+
const canUseOffset = requestedOffset !== null && requestedOffset <= data.length;
|
|
236
|
+
const parsed = parseBuffer(canUseOffset ? data.subarray(requestedOffset) : data, canUseOffset ? requestedOffset : 0);
|
|
237
|
+
if (parsed.blockedOffset !== null) return null;
|
|
238
|
+
|
|
239
|
+
const prompt = cleanText(options.prompt);
|
|
240
|
+
let boundaryEstablished = canUseOffset;
|
|
241
|
+
let lastAssistant = null;
|
|
242
|
+
|
|
243
|
+
for (const record of parsed.records) {
|
|
244
|
+
if (record.ignored) continue;
|
|
245
|
+
const raw = data.subarray(record.startOffset, record.endOffset).toString('utf8').trim();
|
|
246
|
+
let obj;
|
|
247
|
+
try { obj = JSON.parse(raw); } catch { return null; }
|
|
248
|
+
if (!obj || obj.isSidechain || !obj.message) continue;
|
|
41
249
|
const msg = obj.message;
|
|
42
|
-
|
|
43
|
-
if (
|
|
250
|
+
|
|
251
|
+
if (!boundaryEstablished) {
|
|
252
|
+
if (msg.role === 'user' && prompt && contentToText(msg.content) === prompt) {
|
|
253
|
+
boundaryEstablished = true;
|
|
254
|
+
}
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (msg.role !== 'assistant') continue;
|
|
259
|
+
const blocks = Array.isArray(msg.content) ? msg.content : null;
|
|
260
|
+
const hasToolUse = Boolean(blocks && blocks.some((block) => block && block.type === 'tool_use'));
|
|
44
261
|
const text = contentToText(msg.content);
|
|
45
|
-
|
|
46
|
-
//
|
|
47
|
-
|
|
48
|
-
|
|
262
|
+
// Track every assistant record. If the final record is a tool call, there is
|
|
263
|
+
// no proven final user-visible response yet, even if an earlier text exists.
|
|
264
|
+
lastAssistant = !hasToolUse && text ? text : null;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (!boundaryEstablished || !lastAssistant) return null;
|
|
268
|
+
return { content: lastAssistant, blockedOffset: null };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Legacy compatibility for callers/tests. Unlike the old parser, lastLine only
|
|
272
|
+
// advances across valid records; tool activity is represented in compact text.
|
|
273
|
+
function parseTranscript(jsonlText, afterLine = -1) {
|
|
274
|
+
const lines = String(jsonlText).split('\n');
|
|
275
|
+
const messages = [];
|
|
276
|
+
let lastLine = afterLine;
|
|
277
|
+
for (let i = 0; i < lines.length; i++) {
|
|
278
|
+
if (i <= afterLine || !lines[i].trim()) continue;
|
|
279
|
+
let obj;
|
|
280
|
+
try { obj = JSON.parse(lines[i]); } catch { break; }
|
|
281
|
+
lastLine = i;
|
|
282
|
+
for (const ev of normalizeRecord(obj)) messages.push({ role: ev.role, content: ev.content });
|
|
49
283
|
}
|
|
50
284
|
return { messages, lastLine };
|
|
51
285
|
}
|
|
52
286
|
|
|
53
287
|
function readTranscript(transcriptPath, afterLine = -1) {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
text = fs.readFileSync(transcriptPath, 'utf8');
|
|
57
|
-
} catch {
|
|
58
|
-
return { messages: [], lastLine: afterLine };
|
|
59
|
-
}
|
|
60
|
-
return parseTranscript(text, afterLine);
|
|
288
|
+
try { return parseTranscript(fs.readFileSync(transcriptPath, 'utf8'), afterLine); }
|
|
289
|
+
catch { return { messages: [], lastLine: afterLine }; }
|
|
61
290
|
}
|
|
62
291
|
|
|
63
|
-
module.exports = {
|
|
292
|
+
module.exports = {
|
|
293
|
+
MAX_TEXT_CHARS,
|
|
294
|
+
MAX_TOOL_INPUT_CHARS,
|
|
295
|
+
MAX_TOOL_RESULT_CHARS,
|
|
296
|
+
hash,
|
|
297
|
+
cleanText,
|
|
298
|
+
compactText,
|
|
299
|
+
stableJson,
|
|
300
|
+
contentToText,
|
|
301
|
+
finalAssistantFromTranscript,
|
|
302
|
+
normalizeRecord,
|
|
303
|
+
parseBuffer,
|
|
304
|
+
readTranscriptDelta,
|
|
305
|
+
lineIndexToOffset,
|
|
306
|
+
parseTranscript,
|
|
307
|
+
readTranscript,
|
|
308
|
+
};
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memoryrouter-claude",
|
|
3
|
-
"version": "1.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "Deterministic, project-scoped persistent memory for Claude Code: automatic hook retrieval/capture plus an optional OAuth MCP control surface.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "John Rood <john@memoryrouter.ai>",
|
|
7
|
-
"homepage": "https://memoryrouter.ai",
|
|
7
|
+
"homepage": "https://memoryrouter.ai/claude-code",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
10
10
|
"url": "git+https://github.com/John-Rood/MemoryRouter.git",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"claude",
|
|
18
18
|
"claude-code",
|
|
19
19
|
"memory",
|
|
20
|
+
"mcp",
|
|
20
21
|
"ai",
|
|
21
22
|
"hooks",
|
|
22
23
|
"persistent-memory",
|
|
@@ -32,12 +33,16 @@
|
|
|
32
33
|
"bin/",
|
|
33
34
|
"lib/",
|
|
34
35
|
"README.md",
|
|
36
|
+
"CHANGELOG.md",
|
|
35
37
|
"LICENSE"
|
|
36
38
|
],
|
|
37
39
|
"engines": {
|
|
38
40
|
"node": ">=18.0.0"
|
|
39
41
|
},
|
|
40
42
|
"scripts": {
|
|
41
|
-
"
|
|
43
|
+
"check": "node --check bin/cli.js && for f in lib/*.js; do node --check \"$f\"; done",
|
|
44
|
+
"test": "node --test 'test/*.test.js'",
|
|
45
|
+
"test:all": "npm run check && npm test",
|
|
46
|
+
"pack:check": "npm pack --dry-run"
|
|
42
47
|
}
|
|
43
48
|
}
|