memoryrouter-claude 2.0.0 → 2.2.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 +31 -1
- package/README.md +75 -28
- package/bin/cli.js +80 -14
- package/lib/api.js +71 -1
- package/lib/hook-runner.js +372 -232
- package/lib/reflect.js +236 -0
- package/lib/settings.js +3 -3
- package/lib/transcript.js +55 -0
- package/package.json +1 -1
package/lib/reflect.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Headless consolidation loop: checkout -> host model (claude -p) -> commit.
|
|
3
|
+
// The server is the single source of reflection prompts: the model prompt is
|
|
4
|
+
// built exclusively from the checkout contract plus the dated memory texts.
|
|
5
|
+
// This package never authors reflection guidance. There is no local state;
|
|
6
|
+
// server-side lease expiry is the recovery mechanism, so a crashed or
|
|
7
|
+
// interrupted run simply re-checkouts the same memories after the lease ends.
|
|
8
|
+
// Invariant: the model never sees memory row IDs. Checkout source_ids are
|
|
9
|
+
// never read, and commit is {batch_id, entries[]} only.
|
|
10
|
+
|
|
11
|
+
const { spawnSync } = require('child_process');
|
|
12
|
+
const defaultApi = require('./api');
|
|
13
|
+
|
|
14
|
+
const DEFAULT_MAX_TOKENS = 50000;
|
|
15
|
+
const MAX_ENTRY_CHARS = 8000;
|
|
16
|
+
const MAX_ENTRIES = 100;
|
|
17
|
+
const ALLOWED_ENTRY_KEYS = ['text', 'importance'];
|
|
18
|
+
const JSON_ENVELOPE = '{"entries": [{"text": "...", "importance": N}]}';
|
|
19
|
+
|
|
20
|
+
function contractOf(data) {
|
|
21
|
+
const contract = data && data.reflection_contract;
|
|
22
|
+
if (contract && typeof contract.instructions === 'string' && contract.instructions.trim()) {
|
|
23
|
+
return { instructions: contract.instructions, version: contract.version ?? null };
|
|
24
|
+
}
|
|
25
|
+
// Transitional fallback: the shipped checkout emits tier_definitions until
|
|
26
|
+
// reflection_contract lands (connectors spec section a). Same rule applies:
|
|
27
|
+
// server text verbatim, never local authorship.
|
|
28
|
+
const legacy = data && data.tier_definitions;
|
|
29
|
+
if (legacy && typeof legacy.instruction === 'string' && legacy.instruction.trim()) {
|
|
30
|
+
return { instructions: legacy.instruction, version: null };
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function buildPrompt(contract, memories) {
|
|
36
|
+
const dated = memories
|
|
37
|
+
.map((memory) => `[${memory.date}] ${memory.text}`)
|
|
38
|
+
.join('\n\n');
|
|
39
|
+
// The JSON-envelope instruction below is connector transport mechanics
|
|
40
|
+
// (permitted); every reflection semantic comes from contract.instructions.
|
|
41
|
+
return [
|
|
42
|
+
contract.instructions,
|
|
43
|
+
'',
|
|
44
|
+
'Memories:',
|
|
45
|
+
dated,
|
|
46
|
+
'',
|
|
47
|
+
'Respond with ONLY strict JSON in exactly this envelope, no prose before or after:',
|
|
48
|
+
JSON_ENVELOPE,
|
|
49
|
+
].join('\n');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function extractJson(text) {
|
|
53
|
+
try { return JSON.parse(text); } catch { /* not a whole-string JSON */ }
|
|
54
|
+
const start = text.indexOf('{');
|
|
55
|
+
const end = text.lastIndexOf('}');
|
|
56
|
+
if (start >= 0 && end > start) {
|
|
57
|
+
try { return JSON.parse(text.slice(start, end + 1)); } catch { /* no parsable object */ }
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function validateEntries(payload) {
|
|
63
|
+
if (!payload || typeof payload !== 'object' || !Array.isArray(payload.entries)) {
|
|
64
|
+
return { error: 'missing entries array' };
|
|
65
|
+
}
|
|
66
|
+
if (!payload.entries.length) return { error: 'entries array is empty' };
|
|
67
|
+
if (payload.entries.length > MAX_ENTRIES) return { error: `more than ${MAX_ENTRIES} entries` };
|
|
68
|
+
const entries = [];
|
|
69
|
+
for (const entry of payload.entries) {
|
|
70
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
71
|
+
return { error: 'entry is not an object' };
|
|
72
|
+
}
|
|
73
|
+
// Position references and IDs are structurally impossible: any field
|
|
74
|
+
// beyond text and importance rejects the whole batch client-side.
|
|
75
|
+
const extras = Object.keys(entry).filter((k) => !ALLOWED_ENTRY_KEYS.includes(k));
|
|
76
|
+
if (extras.length) return { error: `entry has forbidden fields: ${extras.join(', ')}` };
|
|
77
|
+
if (typeof entry.text !== 'string' || !entry.text.trim() || entry.text.length > MAX_ENTRY_CHARS) {
|
|
78
|
+
return { error: `entry text must be a 1 to ${MAX_ENTRY_CHARS} character string` };
|
|
79
|
+
}
|
|
80
|
+
if (!Number.isInteger(entry.importance) || entry.importance < 1 || entry.importance > 10) {
|
|
81
|
+
return { error: 'entry importance must be an integer 1 to 10' };
|
|
82
|
+
}
|
|
83
|
+
entries.push({ text: entry.text, importance: entry.importance });
|
|
84
|
+
}
|
|
85
|
+
return { entries };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parseEntries(stdout) {
|
|
89
|
+
const wrapper = extractJson(String(stdout || ''));
|
|
90
|
+
if (!wrapper) return { error: 'no JSON found in model output' };
|
|
91
|
+
// `claude -p --output-format json` wraps the answer in {result: "..."}.
|
|
92
|
+
const payload = typeof wrapper.result === 'string'
|
|
93
|
+
? extractJson(wrapper.result)
|
|
94
|
+
: wrapper;
|
|
95
|
+
if (!payload) return { error: 'no JSON envelope found in model result' };
|
|
96
|
+
return validateEntries(payload);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function invokeModel(prompt, spawn) {
|
|
100
|
+
const result = spawn('claude', ['-p', prompt, '--output-format', 'json'], {
|
|
101
|
+
encoding: 'utf8',
|
|
102
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
103
|
+
timeout: 10 * 60 * 1000,
|
|
104
|
+
});
|
|
105
|
+
if (result.error) throw new Error(`could not run the claude CLI: ${result.error.message}`);
|
|
106
|
+
if (result.status !== 0) {
|
|
107
|
+
throw new Error(`claude CLI exited ${result.status}: ${String(result.stderr || '').slice(0, 400)}`);
|
|
108
|
+
}
|
|
109
|
+
return String(result.stdout || '');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function apiErrorDetail(res) {
|
|
113
|
+
const message = res && res.data && (res.data.error || res.data.reason);
|
|
114
|
+
return message ? `: ${message}` : '';
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function runReflect(options = {}) {
|
|
118
|
+
const key = options.key;
|
|
119
|
+
if (!key) throw new Error('a Memory Key is required');
|
|
120
|
+
const api = options.api || defaultApi;
|
|
121
|
+
const spawn = options.spawn || spawnSync;
|
|
122
|
+
const log = options.log || ((...args) => console.log(...args));
|
|
123
|
+
const now = options.now || (() => Date.now());
|
|
124
|
+
const tier = options.tier === 2 ? 2 : 1;
|
|
125
|
+
const maxTokens = options.maxTokens === undefined ? DEFAULT_MAX_TOKENS : options.maxTokens;
|
|
126
|
+
const batchesAll = options.batches === 'all';
|
|
127
|
+
const batchLimit = batchesAll ? Infinity : Math.max(1, parseInt(options.batches, 10) || 1);
|
|
128
|
+
// Lease-recovery retries (expired lease, 409) re-checkout without counting
|
|
129
|
+
// as a committed batch; the iteration guard keeps that loop finite.
|
|
130
|
+
const maxIterations = batchesAll ? 10000 : batchLimit * 3 + 3;
|
|
131
|
+
|
|
132
|
+
const summary = {
|
|
133
|
+
batches_committed: 0,
|
|
134
|
+
entries_created: 0,
|
|
135
|
+
sources_consolidated: 0,
|
|
136
|
+
skipped: 0,
|
|
137
|
+
empty_pool: false,
|
|
138
|
+
dry_run: Boolean(options.dryRun),
|
|
139
|
+
};
|
|
140
|
+
let warnedLease = false;
|
|
141
|
+
let iterations = 0;
|
|
142
|
+
|
|
143
|
+
while (summary.batches_committed < batchLimit && iterations < maxIterations) {
|
|
144
|
+
iterations++;
|
|
145
|
+
|
|
146
|
+
const checkout = await api.reflectCheckout(key, tier, maxTokens);
|
|
147
|
+
if (!checkout.ok) {
|
|
148
|
+
throw new Error(`checkout failed (HTTP ${checkout.status}${apiErrorDetail(checkout)})`);
|
|
149
|
+
}
|
|
150
|
+
const data = checkout.data || {};
|
|
151
|
+
if (!data.batch_id || !data.count) {
|
|
152
|
+
summary.empty_pool = true;
|
|
153
|
+
log('Nothing to consolidate.');
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const contract = contractOf(data);
|
|
158
|
+
if (!contract) {
|
|
159
|
+
throw new Error('checkout response has no reflection contract (neither reflection_contract nor tier_definitions); refusing to author reflection instructions locally');
|
|
160
|
+
}
|
|
161
|
+
const memories = Array.isArray(data.memories) ? data.memories : [];
|
|
162
|
+
const prompt = buildPrompt(contract, memories);
|
|
163
|
+
|
|
164
|
+
if (options.dryRun) {
|
|
165
|
+
log(`Dry run: checked out ${data.count} memories (~${data.est_tokens ?? '?'} tokens, batch tier ${data.tier ?? tier} -> ${contract.version !== null ? `contract v${contract.version}` : 'legacy tier_definitions'}).`);
|
|
166
|
+
log('');
|
|
167
|
+
log(prompt);
|
|
168
|
+
log('');
|
|
169
|
+
log('Dry run: no model call, no commit. The lease expires naturally and the memories return to the pool.');
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
let entries = null;
|
|
174
|
+
let parseError = null;
|
|
175
|
+
for (let attempt = 0; attempt < 2 && !entries; attempt++) {
|
|
176
|
+
const corrective = attempt
|
|
177
|
+
? `\n\nYour previous response could not be used (${parseError}). Respond again with ONLY the strict JSON envelope ${JSON_ENVELOPE} and nothing else.`
|
|
178
|
+
: '';
|
|
179
|
+
const stdout = invokeModel(prompt + corrective, spawn);
|
|
180
|
+
const parsed = parseEntries(stdout);
|
|
181
|
+
if (parsed.entries) entries = parsed.entries;
|
|
182
|
+
else parseError = parsed.error;
|
|
183
|
+
}
|
|
184
|
+
if (!entries) {
|
|
185
|
+
summary.skipped++;
|
|
186
|
+
log(`Could not obtain valid reflection entries (${parseError}). Leaving this batch to lease expiry; nothing was committed. Re-run to retry.`);
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (data.lease_expires_at && Date.parse(data.lease_expires_at) <= now()) {
|
|
191
|
+
summary.skipped++;
|
|
192
|
+
if (!warnedLease) {
|
|
193
|
+
log('Warning: the model step outlasted the lease window. Skipping commit and re-checking out; consider a smaller --max-tokens.');
|
|
194
|
+
warnedLease = true;
|
|
195
|
+
}
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const commit = await api.reflectCommit(key, data.batch_id, entries);
|
|
200
|
+
if (commit.status === 409) {
|
|
201
|
+
summary.skipped++;
|
|
202
|
+
if (!warnedLease) {
|
|
203
|
+
log('Warning: the lease expired before commit. Re-checking out; consider a smaller --max-tokens.');
|
|
204
|
+
warnedLease = true;
|
|
205
|
+
}
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (!commit.ok) {
|
|
209
|
+
throw new Error(`commit failed (HTTP ${commit.status}${apiErrorDetail(commit)})`);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const committed = commit.data || {};
|
|
213
|
+
summary.batches_committed++;
|
|
214
|
+
const created = Array.isArray(committed.created) ? committed.created.length : entries.length;
|
|
215
|
+
summary.entries_created += created;
|
|
216
|
+
summary.sources_consolidated += Number(committed.sources_consolidated) || 0;
|
|
217
|
+
const covers = data.covers && data.covers.from
|
|
218
|
+
? ` covering ${data.covers.from} to ${data.covers.to}` : '';
|
|
219
|
+
log(committed.already_committed
|
|
220
|
+
? `Batch was already committed${covers}; treated as success.`
|
|
221
|
+
: `Committed ${created} reflections${covers}; ${committed.sources_consolidated ?? '?'} memories consolidated.`);
|
|
222
|
+
const debt = committed.reflection;
|
|
223
|
+
if (debt && debt.suggestion) log(`Remaining: ${debt.suggestion}.`);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return summary;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
module.exports = {
|
|
230
|
+
runReflect,
|
|
231
|
+
buildPrompt,
|
|
232
|
+
contractOf,
|
|
233
|
+
parseEntries,
|
|
234
|
+
validateEntries,
|
|
235
|
+
DEFAULT_MAX_TOKENS,
|
|
236
|
+
};
|
package/lib/settings.js
CHANGED
|
@@ -6,7 +6,7 @@ const path = require('path');
|
|
|
6
6
|
const os = require('os');
|
|
7
7
|
|
|
8
8
|
const OURS_RE = /memoryrouter/i;
|
|
9
|
-
const HOOK_RE = /\bhook (inject|capture|capture-subagent|flush|compact|reinject|session-start)\b/;
|
|
9
|
+
const HOOK_RE = /\bhook (inject|capture|capture-subagent|failure|flush|compact|reinject|session-start)\b/;
|
|
10
10
|
|
|
11
11
|
function commandHook(bin, kind, timeout, extra = {}) {
|
|
12
12
|
return { type: 'command', command: `${bin} hook ${kind}`, timeout, ...extra };
|
|
@@ -26,14 +26,13 @@ function buildHookConfig(bin) {
|
|
|
26
26
|
],
|
|
27
27
|
UserPromptSubmit: [{ hooks: [commandHook(bin, 'inject', 10)] }],
|
|
28
28
|
Stop: [{ hooks: [commandHook(bin, 'capture', 30)] }],
|
|
29
|
-
StopFailure: [{ hooks: [commandHook(bin, '
|
|
29
|
+
StopFailure: [{ hooks: [commandHook(bin, 'failure', 30)] }],
|
|
30
30
|
PreCompact: [
|
|
31
31
|
{ matcher: 'auto|manual', hooks: [commandHook(bin, 'flush', 30)] },
|
|
32
32
|
],
|
|
33
33
|
PostCompact: [
|
|
34
34
|
{ matcher: 'auto|manual', hooks: [commandHook(bin, 'compact', 30)] },
|
|
35
35
|
],
|
|
36
|
-
SubagentStop: [{ hooks: [commandHook(bin, 'capture-subagent', 30)] }],
|
|
37
36
|
SessionEnd: [{ hooks: [commandHook(bin, 'flush', 30)] }],
|
|
38
37
|
};
|
|
39
38
|
}
|
|
@@ -101,6 +100,7 @@ function writeSettings(file, settings) {
|
|
|
101
100
|
const existingMode = (() => { try { return fs.statSync(file).mode & 0o777; } catch { return 0o600; } })();
|
|
102
101
|
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
103
102
|
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n', { mode: existingMode });
|
|
103
|
+
try { fs.chmodSync(tmp, existingMode); } catch { /* windows best-effort */ }
|
|
104
104
|
fs.renameSync(tmp, file);
|
|
105
105
|
try { fs.chmodSync(file, existingMode); } catch { /* windows best-effort */ }
|
|
106
106
|
}
|
package/lib/transcript.js
CHANGED
|
@@ -214,6 +214,60 @@ function contentToText(content) {
|
|
|
214
214
|
return content.filter((b) => b && b.type === 'text').map((b) => cleanText(b.text)).filter(Boolean).join('\n');
|
|
215
215
|
}
|
|
216
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;
|
|
249
|
+
const msg = obj.message;
|
|
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'));
|
|
261
|
+
const text = contentToText(msg.content);
|
|
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
|
+
|
|
217
271
|
// Legacy compatibility for callers/tests. Unlike the old parser, lastLine only
|
|
218
272
|
// advances across valid records; tool activity is represented in compact text.
|
|
219
273
|
function parseTranscript(jsonlText, afterLine = -1) {
|
|
@@ -244,6 +298,7 @@ module.exports = {
|
|
|
244
298
|
compactText,
|
|
245
299
|
stableJson,
|
|
246
300
|
contentToText,
|
|
301
|
+
finalAssistantFromTranscript,
|
|
247
302
|
normalizeRecord,
|
|
248
303
|
parseBuffer,
|
|
249
304
|
readTranscriptDelta,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memoryrouter-claude",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
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>",
|