memoryrouter-claude 2.1.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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ### Added
6
+
7
+ - `reflect` CLI verb: headless consolidation loop (checkout, run local `claude -p` with the server-provided contract, commit entries). Flags: `--tier 1|2`, `--batches N|all`, `--max-tokens N` (default 50000, no cap), `--dry-run`. No local state; server-side lease expiry is the recovery mechanism. Refuses to run when the checkout carries no server contract; never authors reflection instructions locally. The model never sees memory row IDs, and commit entries are text plus importance only (extra fields are rejected client-side).
8
+ - `lib/api.js` wrappers for the Reflection Hierarchy endpoints: `reflectCheckout`, `reflectCommit`, `inspect`, `deleteIds`, `dateSearch`, and the zero-billing `debtProbe`.
9
+ - Debt nudge: when `/prepare` responses report consolidation is available, one nudge line is appended to the injected recall context, at most once per 24 hours per session, only on already-emitted contexts, and always inside the existing context character cap.
10
+ - `status` now shows consolidation debt via the date-search debt probe.
11
+ - `prepare` passes optional `tiers` and `importance` retrieval filters through when a caller supplies them; hooks never set them by default.
12
+
3
13
  ## 2.1.0 (2026-08-05)
4
14
 
5
15
  ### Fixed
package/README.md CHANGED
@@ -171,13 +171,35 @@ The key is stored only at `~/.memoryrouter/config.json` with mode `0600` in a mo
171
171
  |---|---|
172
172
  | `npx memoryrouter-claude init` | Install or upgrade automatic hooks |
173
173
  | `npx memoryrouter-claude doctor` | Diagnose config, permissions, hooks, project ID, pending capture, API, and MCP |
174
- | `npx memoryrouter-claude status` | Show key, vault stats, and active project scope |
174
+ | `npx memoryrouter-claude status` | Show key, vault stats, consolidation debt, and active project scope |
175
+ | `npx memoryrouter-claude reflect` | Consolidate memories into reflections using your local `claude` CLI |
175
176
  | `npx memoryrouter-claude mcp install` | Add the OAuth MCP manual surface with current Claude CLI syntax |
176
177
  | `npx memoryrouter-claude mcp status` | Inspect MCP configuration |
177
178
  | `npx memoryrouter-claude mcp remove` | Remove MCP only; hooks stay installed |
178
179
  | `npx memoryrouter-claude off` | Remove MemoryRouter hooks from local/project/user settings |
179
180
  | `npx memoryrouter-claude off --purge` | Also delete private key/config/checkpoint state |
180
181
 
182
+ ## Reflections (memory consolidation)
183
+
184
+ MemoryRouter's [Reflection Hierarchy](https://docs.memoryrouter.ai/reflections) consolidates raw memories into higher-level reflections. This package runs the loop headless with YOUR local Claude Code as the reflecting model (you pay your own inference; MemoryRouter never calls a provider):
185
+
186
+ ```bash
187
+ npx memoryrouter-claude reflect # one batch, raw -> reflections
188
+ npx memoryrouter-claude reflect --tier 2 # reflections -> high-level reflections
189
+ npx memoryrouter-claude reflect --batches all # run until the pool is empty
190
+ npx memoryrouter-claude reflect --max-tokens 20000 # smaller batches for faster model turns
191
+ npx memoryrouter-claude reflect --dry-run # print the prompt; commit nothing
192
+ ```
193
+
194
+ How it works, and the guarantees it keeps:
195
+
196
+ - **The server authors the reflection instructions.** Each checkout carries the contract; this package passes it to `claude -p` verbatim and never adds its own reflection guidance. If a checkout carries no contract, `reflect` refuses rather than inventing a prompt.
197
+ - **The model never sees memory IDs.** The prompt contains only instructions and dated memory texts; the commit is `{batch_id, entries[]}` only, and entries are text plus importance, nothing else.
198
+ - **No local state.** Each batch is protected by a 15 minute server-side lease. If a run crashes or is interrupted, the lease expires and the memories return to the pool; re-running simply continues. `--dry-run` deliberately lets its lease expire.
199
+ - **Idempotent commits.** Re-committing a completed batch is success, never a duplicate.
200
+
201
+ When your unconsolidated memory crosses the server threshold, injected recall context includes a one-line nudge (at most once per 24 hours per session), and `status` shows the current debt. The MCP surface (`mcp install`) exposes the same capability as in-session tools once the server-side reflect tools ship there.
202
+
181
203
  ## Configuration
182
204
 
183
205
  `~/.memoryrouter/config.json` is versioned and migrated non-destructively:
package/bin/cli.js CHANGED
@@ -21,6 +21,7 @@ const api = require('../lib/api');
21
21
  const settingsLib = require('../lib/settings');
22
22
  const { deriveProjectIdentity } = require('../lib/project');
23
23
  const { runHook } = require('../lib/hook-runner');
24
+ const { runReflect } = require('../lib/reflect');
24
25
 
25
26
  const PKG = require('../package.json');
26
27
  const VERSION = PKG.version;
@@ -43,7 +44,19 @@ Usage:
43
44
  API reachability, and optional MCP configuration.
44
45
 
45
46
  npx memoryrouter-claude status
46
- Show key validity, vault stats, and deterministic project identity.
47
+ Show key validity, vault stats, consolidation debt, and deterministic
48
+ project identity.
49
+
50
+ npx memoryrouter-claude reflect [--tier 1|2] [--batches N|all] [--max-tokens N] [--dry-run]
51
+ Consolidate unconsolidated memories into reflections. Checks out a batch
52
+ under a 15 minute lease, runs YOUR local Claude Code (claude -p) with the
53
+ server-provided instructions, and commits the entries it writes. No local
54
+ state: interrupted runs recover via server-side lease expiry.
55
+ --tier 1 consolidate raw memories into reflections (default)
56
+ --tier 2 consolidate reflections into high-level reflections
57
+ --batches N number of batches to commit (default 1; "all" runs to empty)
58
+ --max-tokens Token budget per checkout (default 50000)
59
+ --dry-run checkout and print the prompt, never call the model or commit
47
60
 
48
61
  npx memoryrouter-claude off [--local|--project|--user] [--purge]
49
62
  Remove only MemoryRouter hooks. --purge also deletes private local config/state.
@@ -75,6 +88,10 @@ function parseArgs(argv) {
75
88
  else if (value === '--include-global') args.includeGlobal = true;
76
89
  else if (value === '--yes' || value === '-y') args.yes = true;
77
90
  else if (value === '--purge') args.purge = true;
91
+ else if (value === '--tier') args.tier = parseInt(argv[++i], 10);
92
+ else if (value === '--batches') args.batches = argv[++i];
93
+ else if (value === '--max-tokens') args.maxTokens = parseInt(argv[++i], 10);
94
+ else if (value === '--dry-run') args.dryRun = true;
78
95
  else if (value === '--final') args.final = true;
79
96
  else if (value === '--help' || value === '-h') args.help = true;
80
97
  else if (value === '--version' || value === '-v') args.version = true;
@@ -168,12 +185,30 @@ async function cmdInit(args) {
168
185
  `);
169
186
  }
170
187
 
188
+ function describeDebt(debt) {
189
+ if (!debt) return 'unknown (debt probe unavailable)';
190
+ const raw = debt.unconsolidated && debt.unconsolidated.raw;
191
+ const tier2 = debt.unconsolidated && debt.unconsolidated.tier2;
192
+ const parts = [];
193
+ if (raw && Number.isFinite(Number(raw.est_tokens))) parts.push(`raw ~${Math.round(Number(raw.est_tokens) / 1000)}k tokens`);
194
+ if (tier2 && Number.isFinite(Number(tier2.est_tokens))) parts.push(`tier 2 ~${Math.round(Number(tier2.est_tokens) / 1000)}k tokens`);
195
+ const detail = parts.length ? parts.join(', ') : 'none reported';
196
+ return debt.suggestion
197
+ ? `${detail} (${debt.suggestion}; run \`npx memoryrouter-claude reflect\`)`
198
+ : `${detail} (below threshold)`;
199
+ }
200
+
171
201
  async function cmdStatus() {
172
202
  const key = getApiKey();
173
203
  if (!key) throw new Error('No Memory Key configured. Run: npx memoryrouter-claude init');
174
204
  const stats = await validateKey(key);
175
205
  const cfg = loadConfig();
176
206
  const project = deriveProjectIdentity({ cwd: process.cwd() }, cfg);
207
+ let debt = null;
208
+ try {
209
+ const probe = await api.debtProbe(key);
210
+ if (probe.ok && probe.data) debt = probe.data.reflection || null;
211
+ } catch { /* status never fails because of the probe */ }
177
212
  console.log(`
178
213
  MemoryRouter status
179
214
  ───────────────────
@@ -185,9 +220,35 @@ async function cmdStatus() {
185
220
  Memories: ${stats.totalVectors ?? stats.total_vectors ?? '?'} vectors
186
221
  Tokens: ${stats.totalTokens ?? stats.total_tokens ?? '?'}
187
222
  Storage: ${stats.storage ?? '?'}
223
+ Debt: ${describeDebt(debt)}
188
224
  `);
189
225
  }
190
226
 
227
+ async function cmdReflect(args) {
228
+ const key = getApiKey();
229
+ if (!key) throw new Error('No Memory Key configured. Run: npx memoryrouter-claude init');
230
+ if (args.tier !== undefined && args.tier !== 1 && args.tier !== 2) {
231
+ throw new Error('--tier must be 1 or 2');
232
+ }
233
+ if (args.maxTokens !== undefined && (!Number.isInteger(args.maxTokens) || args.maxTokens < 1)) {
234
+ throw new Error('--max-tokens must be a positive integer');
235
+ }
236
+ if (args.batches !== undefined && args.batches !== 'all'
237
+ && (!/^\d+$/.test(args.batches) || parseInt(args.batches, 10) < 1)) {
238
+ throw new Error('--batches must be a positive integer or "all"');
239
+ }
240
+ const summary = await runReflect({
241
+ key,
242
+ tier: args.tier,
243
+ batches: args.batches,
244
+ maxTokens: args.maxTokens,
245
+ dryRun: args.dryRun,
246
+ });
247
+ if (!summary.dry_run && !summary.empty_pool) {
248
+ console.log(`\n Done: ${summary.batches_committed} batch(es) committed, ${summary.entries_created} reflections created, ${summary.sources_consolidated} memories consolidated.`);
249
+ }
250
+ }
251
+
191
252
  function inspectState() {
192
253
  const report = { files: 0, pending: 0, blocked: 0 };
193
254
  try {
@@ -313,6 +374,7 @@ async function main() {
313
374
  switch (cmd) {
314
375
  case 'init': return cmdInit(args);
315
376
  case 'status': return cmdStatus();
377
+ case 'reflect': return cmdReflect(args);
316
378
  case 'doctor': return cmdDoctor();
317
379
  case 'off':
318
380
  case 'uninstall': return cmdOff(args);
package/lib/api.js CHANGED
@@ -39,6 +39,11 @@ function prepare(key, prompt, sessionId, opts = {}) {
39
39
  if (sessionId) body.session_id = sessionId;
40
40
  if (opts.contextLimit) body.context_limit = opts.contextLimit;
41
41
  if (opts.density) body.density = opts.density;
42
+ // Optional retrieval filters ride through unchanged when the caller sets
43
+ // them. Hooks never set these by default; they exist for user config and
44
+ // future recall profiles (importance-tier-query-spec section 7.3).
45
+ if (Array.isArray(opts.tiers) && opts.tiers.length) body.tiers = opts.tiers;
46
+ if (opts.importance !== undefined) body.importance = opts.importance;
42
47
  return request('POST', '/v1/memory/prepare', { key, body, timeoutMs: opts.timeoutMs || 6000 });
43
48
  }
44
49
 
@@ -61,4 +66,62 @@ function warmup(key, sessionId, opts = {}) {
61
66
  return request('POST', '/v1/memory/warmup', { key, body: {}, headers, timeoutMs: opts.timeoutMs || 10000 });
62
67
  }
63
68
 
64
- module.exports = { request, stats, prepare, ingest, ingestEvent, warmup, debug };
69
+ // Reflection Hierarchy wrappers. Shapes per the shipped API
70
+ // (POST /v1/memory/consolidate/checkout|commit, /inspect, /delete-ids,
71
+ // /date-search). Empty pool on checkout is HTTP 200 {batch_id: null};
72
+ // commit is idempotent (already_committed: true is success) and returns
73
+ // HTTP 409 when the lease expired (caller re-checkouts).
74
+
75
+ function reflectCheckout(key, tier = 1, maxTokens = 50000, opts = {}) {
76
+ const body = { tier };
77
+ if (maxTokens !== undefined && maxTokens !== null) body.max_tokens = maxTokens;
78
+ return request('POST', '/v1/memory/consolidate/checkout', { key, body, timeoutMs: opts.timeoutMs || 20000 });
79
+ }
80
+
81
+ function reflectCommit(key, batchId, entries, opts = {}) {
82
+ const body = { batch_id: batchId, entries };
83
+ return request('POST', '/v1/memory/consolidate/commit', { key, body, timeoutMs: opts.timeoutMs || 30000 });
84
+ }
85
+
86
+ function inspect(key, memoryId, opts = {}) {
87
+ return request('POST', '/v1/memory/inspect', { key, body: { memory_id: memoryId }, timeoutMs: opts.timeoutMs || 10000 });
88
+ }
89
+
90
+ function deleteIds(key, ids, opts = {}) {
91
+ return request('POST', '/v1/memory/delete-ids', { key, body: { ids }, timeoutMs: opts.timeoutMs || 15000 });
92
+ }
93
+
94
+ function dateSearch(key, params = {}, opts = {}) {
95
+ const body = {};
96
+ if (params.from !== undefined) body.from = params.from;
97
+ if (params.to !== undefined) body.to = params.to;
98
+ if (params.query !== undefined) body.query = params.query;
99
+ if (params.max_tokens !== undefined) body.max_tokens = params.max_tokens;
100
+ if (Array.isArray(params.tiers) && params.tiers.length) body.tiers = params.tiers;
101
+ if (params.importance !== undefined) body.importance = params.importance;
102
+ return request('POST', '/v1/memory/date-search', { key, body, timeoutMs: opts.timeoutMs || 10000 });
103
+ }
104
+
105
+ // Zero-result debt read: an empty-window date-search returns the reflection
106
+ // debt block without billing retrieval tokens. Sanctioned probe per the
107
+ // connectors spec (stats does not carry the debt block).
108
+ function debtProbe(key, opts = {}) {
109
+ const from = new Date(Date.now() - 1000).toISOString();
110
+ return dateSearch(key, { from, max_tokens: 1000 }, { timeoutMs: opts.timeoutMs || 8000 });
111
+ }
112
+
113
+ module.exports = {
114
+ request,
115
+ stats,
116
+ prepare,
117
+ ingest,
118
+ ingestEvent,
119
+ warmup,
120
+ reflectCheckout,
121
+ reflectCommit,
122
+ inspect,
123
+ deleteIds,
124
+ dateSearch,
125
+ debtProbe,
126
+ debug,
127
+ };
@@ -20,6 +20,7 @@ const { deriveProjectIdentity, sessionIdFor } = require('./project');
20
20
  const MAX_CONTEXT_CHARS = 9500;
21
21
  const MAX_EVENT_CHARS = 100000;
22
22
  const RECENT_TURN_LIMIT = 50;
23
+ const NUDGE_WINDOW_MS = 24 * 60 * 60 * 1000;
23
24
 
24
25
  function debug(...args) {
25
26
  if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
@@ -97,6 +98,51 @@ function mergeContexts(results, identity, maxChars) {
97
98
  return compactText(`${header}\n${sections.join('\n\n')}`, maxChars);
98
99
  }
99
100
 
101
+ function reflectionNudgeLine(results) {
102
+ // The server owns the threshold decision: a non-null reflection.suggestion
103
+ // on any /prepare result means consolidation is available. Connectors only
104
+ // render one line; they never recompute debt.
105
+ for (const item of results) {
106
+ const debt = item && item.reflection;
107
+ if (!debt || !debt.suggestion) continue;
108
+ const rawTokens = debt.unconsolidated && debt.unconsolidated.raw
109
+ ? Number(debt.unconsolidated.raw.est_tokens) : NaN;
110
+ const tier2Tokens = debt.unconsolidated && debt.unconsolidated.tier2
111
+ ? Number(debt.unconsolidated.tier2.est_tokens) : NaN;
112
+ const total = (Number.isFinite(rawTokens) ? rawTokens : 0)
113
+ + (Number.isFinite(tier2Tokens) ? tier2Tokens : 0);
114
+ const amount = total > 0 ? `${Math.round(total / 1000)}k` : 'significant';
115
+ return `[MemoryRouter] Consolidation available: ${amount} unconsolidated memory tokens. Run: npx memoryrouter-claude reflect`;
116
+ }
117
+ return null;
118
+ }
119
+
120
+ async function maybeAppendNudge(input, context, results, maxChars) {
121
+ // Rules (connectors spec section c): only on an already-emitted context,
122
+ // never a context solely for the nudge, at most once per 24h per session
123
+ // state, and always inside the existing char cap so memory content wins.
124
+ if (!context) return context;
125
+ const line = reflectionNudgeLine(results);
126
+ if (!line) return context;
127
+ const cap = Math.max(1000, Math.min(MAX_CONTEXT_CHARS, Number(maxChars) || MAX_CONTEXT_CHARS));
128
+ if (context.length + line.length + 1 > cap) return context;
129
+ let allowed = false;
130
+ try {
131
+ await withStateLock(stateKeyFor(input), async (state) => {
132
+ const last = Number(state.lastNudgeAt) || 0;
133
+ if (Date.now() - last >= NUDGE_WINDOW_MS) {
134
+ state.lastNudgeAt = Date.now();
135
+ saveState(stateKeyFor(input), state);
136
+ allowed = true;
137
+ }
138
+ }, { timeoutMs: 1500 });
139
+ } catch (error) {
140
+ debug('nudge state failed open:', error.message);
141
+ return context;
142
+ }
143
+ return allowed ? `${context}\n${line}` : context;
144
+ }
145
+
100
146
  async function retrieveContext(input, key, prompt, eventName) {
101
147
  const cfg = loadConfig();
102
148
  const identity = deriveProjectIdentity(input, cfg);
@@ -107,19 +153,22 @@ async function retrieveContext(input, key, prompt, eventName) {
107
153
 
108
154
  if (identity.memoryScope === 'global') {
109
155
  requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
110
- .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context })));
156
+ .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
111
157
  } else {
112
158
  requests.push(api.prepare(key, prompt, identity.id, { timeoutMs: 5500, contextLimit, density })
113
- .then((res) => ({ label: 'Project', context: res.ok && res.data && res.data.context })));
159
+ .then((res) => ({ label: 'Project', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
114
160
  if (identity.includeGlobal) {
115
161
  requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
116
- .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context })));
162
+ .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
117
163
  }
118
164
  }
119
165
 
120
166
  const settled = await Promise.allSettled(requests);
121
167
  const results = settled.filter((r) => r.status === 'fulfilled').map((r) => r.value);
122
- const context = mergeContexts(results, identity, cfg.maxContextChars || MAX_CONTEXT_CHARS);
168
+ let context = mergeContexts(results, identity, cfg.maxContextChars || MAX_CONTEXT_CHARS);
169
+ if (context && input.session_id) {
170
+ context = await maybeAppendNudge(input, context, results, cfg.maxContextChars || MAX_CONTEXT_CHARS);
171
+ }
123
172
  emitContext(eventName, context, cfg.maxContextChars);
124
173
  }
125
174
 
@@ -532,5 +581,6 @@ module.exports = {
532
581
  mergeContexts,
533
582
  emitContext,
534
583
  stateKeyFor,
584
+ reflectionNudgeLine,
535
585
  MAX_CONTEXT_CHARS,
536
586
  };
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memoryrouter-claude",
3
- "version": "2.1.0",
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>",