memoryrouter-claude 2.2.1 → 2.4.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/README.md CHANGED
@@ -200,6 +200,40 @@ How it works, and the guarantees it keeps:
200
200
 
201
201
  When your unconsolidated memory crosses the server threshold, injected recall context includes a one-line consolidation suggestion on every injection, 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
202
 
203
+ ### Automatic consolidation (default on)
204
+
205
+ You do not have to run `reflect` yourself. When a retrieval response reports debt above the server's threshold, the hooks spawn the same reflect loop as a detached background process:
206
+
207
+ - Your session is never blocked and never sees the run; output goes to `~/.memoryrouter/consolidate.log`.
208
+ - At most 3 batches per trigger, with a fresh debt check between batches; the run stops as soon as debt drops below the threshold.
209
+ - A machine-wide lockfile (`~/.memoryrouter/consolidate.lock`, stale after 20 minutes) prevents concurrent sessions from double-firing, and a 30 minute cooldown follows each completed run.
210
+ - The threshold always comes from the server response; nothing is hardcoded locally.
211
+ - The reflecting model is your own local `claude` (you pay your own inference). MemoryRouter bills the checkout/commit tokens at the normal 1x raw rate.
212
+
213
+ Opt out with `"autoConsolidate": false` in `~/.memoryrouter/config.json`. The suggestion line and manual `reflect` keep working; only the automatic background trigger is disabled.
214
+
215
+ ## Historical import (agent-driven)
216
+
217
+ New vaults usually sit next to months of existing Claude Code history on disk. The import flow brings it in with a strict division of labor: the server owns the extraction prompt, your local agent owns discovery/parsing, and this package owns transport. The agent never uploads; this CLI never parses history.
218
+
219
+ ```bash
220
+ npx memoryrouter-claude import --instructions # print the server's extraction prompt
221
+ npx memoryrouter-claude import --instructions --run # or run it headless via claude -p
222
+ npx memoryrouter-claude import --file extract.jsonl # validate, preview, quote, approve, upload
223
+ npx memoryrouter-claude import --file extract.jsonl --yes # non-interactive approval
224
+ npx memoryrouter-claude import --dismiss # permanently silence the import nudge
225
+ ```
226
+
227
+ How it works, and the guarantees it keeps:
228
+
229
+ - **The server owns the prompt** (`GET /v1/memory/imports/instructions`, versioned like the reflection contract). Prompt improvements reach every user instantly, with no package update, and the extraction adapts to whatever transcript format is actually on disk.
230
+ - **The agent only reads local files and writes one JSONL extract** (four fields per record: `external_id`, `content`, `timestamp`, `role`). No network calls, no credentials in the extract.
231
+ - **`--file` is the only upload path.** It validates the extract locally, computes the same deterministic identity math as the server (record hashes, archive id, vault fingerprint), shows the record count, date range, estimated tokens, and the server's price quote, and requires explicit approval before any write.
232
+ - **Fully idempotent.** The import id is derived from content + destination, batches carry `Idempotency-Keys`, and the server dedupes by `external_id`. Re-running after any interruption replays committed batches for free and resumes where it left off. Duplicates are never re-billed.
233
+ - **The Memory Key never appears in the prompt or the extract file.** It rides only in the Authorization header.
234
+
235
+ When a vault is new (small, no completed import, not dismissed), injected recall context includes a one-line import suggestion on every injection until an import completes or you `--dismiss`.
236
+
203
237
  ## Configuration
204
238
 
205
239
  `~/.memoryrouter/config.json` is versioned and migrated non-destructively:
package/bin/cli.js CHANGED
@@ -22,6 +22,8 @@ const settingsLib = require('../lib/settings');
22
22
  const { deriveProjectIdentity } = require('../lib/project');
23
23
  const { runHook } = require('../lib/hook-runner');
24
24
  const { runReflect } = require('../lib/reflect');
25
+ const { runAutoConsolidate } = require('../lib/auto');
26
+ const { runInstructions, runDismiss, runImportFile } = require('../lib/import');
25
27
 
26
28
  const PKG = require('../package.json');
27
29
  const VERSION = PKG.version;
@@ -57,6 +59,23 @@ Usage:
57
59
  --batches N number of batches to commit (default 1; "all" runs to empty)
58
60
  --max-tokens Token budget per checkout (default 50000)
59
61
  --dry-run checkout and print the prompt, never call the model or commit
62
+ Automatic mode: when the server reports consolidation debt above its
63
+ threshold, the hooks spawn this same loop in the background (max 3
64
+ batches per trigger, 30 minute cooldown, machine-wide lockfile). Opt
65
+ out with "autoConsolidate": false in ~/.memoryrouter/config.json.
66
+ Logs: ~/.memoryrouter/consolidate.log
67
+
68
+ npx memoryrouter-claude import [--instructions [--run]] [--file <path>] [--dismiss] [--yes]
69
+ Import historical Claude Code conversations into your vault.
70
+ --instructions fetch the server's extraction prompt and print it for the
71
+ host agent to execute (add --run to spawn it via claude -p)
72
+ --file <path> upload a JSONL extract: validates locally, shows record
73
+ count, date range, and the server price quote, requires
74
+ explicit approval (interactive yes or --yes), uploads
75
+ idempotent batches with resume, prints the receipt
76
+ --dismiss permanently silence the import suggestion for this vault
77
+ Re-running --file is always safe: committed batches replay for free and
78
+ duplicates are never re-billed.
60
79
 
61
80
  npx memoryrouter-claude off [--local|--project|--user] [--purge]
62
81
  Remove only MemoryRouter hooks. --purge also deletes private local config/state.
@@ -92,6 +111,10 @@ function parseArgs(argv) {
92
111
  else if (value === '--batches') args.batches = argv[++i];
93
112
  else if (value === '--max-tokens') args.maxTokens = parseInt(argv[++i], 10);
94
113
  else if (value === '--dry-run') args.dryRun = true;
114
+ else if (value === '--instructions') args.instructions = true;
115
+ else if (value === '--run') args.run = true;
116
+ else if (value === '--file') args.file = argv[++i];
117
+ else if (value === '--dismiss') args.dismiss = true;
95
118
  else if (value === '--final') args.final = true;
96
119
  else if (value === '--help' || value === '-h') args.help = true;
97
120
  else if (value === '--version' || value === '-v') args.version = true;
@@ -249,6 +272,22 @@ async function cmdReflect(args) {
249
272
  }
250
273
  }
251
274
 
275
+ async function cmdImport(args) {
276
+ const key = getApiKey();
277
+ if (!key) throw new Error('No Memory Key configured. Run: npx memoryrouter-claude init');
278
+ const modes = [args.instructions, args.file !== undefined, args.dismiss].filter(Boolean).length;
279
+ if (modes > 1) throw new Error('Choose one of --instructions, --file <path>, or --dismiss');
280
+ if (args.dismiss) return void (await runDismiss({ key }));
281
+ if (args.file) return void (await runImportFile({ key, file: args.file, yes: args.yes }));
282
+ // Default (and --instructions): fetch + print the extraction prompt.
283
+ await runInstructions({ key, spawn: Boolean(args.run) });
284
+ if (!args.run) {
285
+ console.log('');
286
+ console.log(' Execute the prompt above with your agent (or re-run with --instructions --run to spawn claude -p).');
287
+ console.log(' Then upload the extract: npx memoryrouter-claude import --file <path>');
288
+ }
289
+ }
290
+
252
291
  function inspectState() {
253
292
  const report = { files: 0, pending: 0, blocked: 0 };
254
293
  try {
@@ -375,6 +414,14 @@ async function main() {
375
414
  case 'init': return cmdInit(args);
376
415
  case 'status': return cmdStatus();
377
416
  case 'reflect': return cmdReflect(args);
417
+ case 'reflect-auto': {
418
+ // Internal entrypoint for the detached automatic consolidation run
419
+ // spawned by the hooks. Silent to the user's session; logs to
420
+ // ~/.memoryrouter/consolidate.log. Always exits 0.
421
+ try { await runAutoConsolidate({ key: getApiKey() }); } catch { /* logged */ }
422
+ return void (process.exitCode = 0);
423
+ }
424
+ case 'import': return cmdImport(args);
378
425
  case 'doctor': return cmdDoctor();
379
426
  case 'off':
380
427
  case 'uninstall': return cmdOff(args);
package/lib/api.js CHANGED
@@ -7,7 +7,7 @@ function debug(...args) {
7
7
  if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
8
8
  }
9
9
 
10
- async function request(method, endpoint, { key, body, timeoutMs = 8000, headers = {} } = {}) {
10
+ async function request(method, endpoint, { key, body, rawBody, timeoutMs = 8000, headers = {} } = {}) {
11
11
  const ctrl = new AbortController();
12
12
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
13
13
  try {
@@ -19,7 +19,7 @@ async function request(method, endpoint, { key, body, timeoutMs = 8000, headers
19
19
  'User-Agent': 'memoryrouter-claude/' + require('./../package.json').version,
20
20
  ...headers,
21
21
  },
22
- body: body === undefined ? undefined : JSON.stringify(body),
22
+ body: rawBody !== undefined ? rawBody : body === undefined ? undefined : JSON.stringify(body),
23
23
  signal: ctrl.signal,
24
24
  });
25
25
  let data = null;
@@ -110,6 +110,54 @@ function debtProbe(key, opts = {}) {
110
110
  return dateSearch(key, { from, max_tokens: 1000 }, { timeoutMs: opts.timeoutMs || 8000 });
111
111
  }
112
112
 
113
+ // Historical import wrappers. The server owns the extraction prompt
114
+ // (GET /imports/instructions); the CLI owns transport (create, approve,
115
+ // idempotent batches, receipt). The imports API is fully idempotent:
116
+ // re-running create/approve/batches after an interruption is always safe.
117
+
118
+ function importInstructions(key, platform, opts = {}) {
119
+ const query = `platform=${encodeURIComponent(platform)}`
120
+ + (opts.outputPath ? `&output_path=${encodeURIComponent(opts.outputPath)}` : '');
121
+ return request('GET', `/v1/memory/imports/instructions?${query}`, { key, timeoutMs: opts.timeoutMs || 15000 });
122
+ }
123
+
124
+ function importCreate(key, body, opts = {}) {
125
+ return request('POST', '/v1/memory/imports', { key, body, timeoutMs: opts.timeoutMs || 20000 });
126
+ }
127
+
128
+ function importApprove(key, importId, approvalDigest, opts = {}) {
129
+ return request('POST', `/v1/memory/imports/${encodeURIComponent(importId)}/approve`, {
130
+ key,
131
+ body: { approval_digest: approvalDigest },
132
+ timeoutMs: opts.timeoutMs || 20000,
133
+ });
134
+ }
135
+
136
+ function importBatch(key, importId, batchIndex, jsonl, idempotencyKey, opts = {}) {
137
+ return request('POST', `/v1/memory/imports/${encodeURIComponent(importId)}/batches/${batchIndex}`, {
138
+ key,
139
+ rawBody: jsonl,
140
+ headers: { 'Content-Type': 'application/x-ndjson', 'Idempotency-Key': idempotencyKey },
141
+ timeoutMs: opts.timeoutMs || 120000,
142
+ });
143
+ }
144
+
145
+ function importStatus(key, importId, opts = {}) {
146
+ return request('GET', `/v1/memory/imports/${encodeURIComponent(importId)}`, { key, timeoutMs: opts.timeoutMs || 15000 });
147
+ }
148
+
149
+ function importReceipt(key, importId, opts = {}) {
150
+ return request('GET', `/v1/memory/imports/${encodeURIComponent(importId)}/receipt`, { key, timeoutMs: opts.timeoutMs || 15000 });
151
+ }
152
+
153
+ function importDismiss(key, platform, opts = {}) {
154
+ return request('POST', '/v1/memory/imports/dismiss-suggestion', {
155
+ key,
156
+ body: { platform },
157
+ timeoutMs: opts.timeoutMs || 10000,
158
+ });
159
+ }
160
+
113
161
  module.exports = {
114
162
  request,
115
163
  stats,
@@ -123,5 +171,12 @@ module.exports = {
123
171
  deleteIds,
124
172
  dateSearch,
125
173
  debtProbe,
174
+ importInstructions,
175
+ importCreate,
176
+ importApprove,
177
+ importBatch,
178
+ importStatus,
179
+ importReceipt,
180
+ importDismiss,
126
181
  debug,
127
182
  };
package/lib/auto.js ADDED
@@ -0,0 +1,237 @@
1
+ 'use strict';
2
+ // Automatic threshold-activated consolidation.
3
+ //
4
+ // When a /prepare response carries a non-null reflection.suggestion (the
5
+ // server's own threshold decision; the threshold number is never hardcoded
6
+ // client-side), the hook spawns the existing reflect loop as a detached
7
+ // background process. The user's session is never blocked and never sees
8
+ // failures; everything is logged to ~/.memoryrouter/consolidate.log.
9
+ //
10
+ // Reliability rails:
11
+ // - Lockfile ~/.memoryrouter/consolidate.lock (pid + timestamp, stale after
12
+ // 20 minutes) so concurrent sessions and other MemoryRouter connectors on
13
+ // the same machine do not fire duplicate runs. Server leases + idempotent
14
+ // commits make overlap harmless anyway; the lock avoids wasted inference.
15
+ // - Bounded: at most 3 batches per trigger, re-checking debt via the API
16
+ // between batches and stopping as soon as the server reports no suggestion.
17
+ // - Cooldown: no re-trigger within 30 minutes of the last completed run, and
18
+ // within 10 minutes of the last attempt (so persistent failures cannot
19
+ // spam the host model).
20
+ // - Opt-out: config autoConsolidate: false (default true). When opted out the
21
+ // existing suggestion nudge remains as-is.
22
+
23
+ const fs = require('fs');
24
+ const os = require('os');
25
+ const path = require('path');
26
+ const childProcess = require('child_process');
27
+
28
+ const LOCK_STALE_MS = 20 * 60 * 1000;
29
+ const COOLDOWN_MS = 30 * 60 * 1000;
30
+ const ATTEMPT_COOLDOWN_MS = 10 * 60 * 1000;
31
+ const MAX_BATCHES_PER_TRIGGER = 3;
32
+
33
+ function autoDir(env = process.env) {
34
+ return env.MEMORYROUTER_CONFIG_DIR || path.join(os.homedir(), '.memoryrouter');
35
+ }
36
+
37
+ function lockPath(env) { return path.join(autoDir(env), 'consolidate.lock'); }
38
+ function statePath(env) { return path.join(autoDir(env), 'consolidate-state.json'); }
39
+ function logPath(env) { return path.join(autoDir(env), 'consolidate.log'); }
40
+
41
+ function ensureDir(dir) {
42
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
43
+ }
44
+
45
+ function appendLog(line, env = process.env) {
46
+ try {
47
+ ensureDir(autoDir(env));
48
+ const file = logPath(env);
49
+ try {
50
+ if (fs.statSync(file).size > 1024 * 1024) fs.renameSync(file, `${file}.1`);
51
+ } catch { /* new file */ }
52
+ fs.appendFileSync(file, `[${new Date().toISOString()}] ${line}\n`, { mode: 0o600 });
53
+ } catch { /* logging never throws */ }
54
+ }
55
+
56
+ function readState(env = process.env) {
57
+ try { return JSON.parse(fs.readFileSync(statePath(env), 'utf8')) || {}; } catch { return {}; }
58
+ }
59
+
60
+ function writeState(patch, env = process.env) {
61
+ try {
62
+ ensureDir(autoDir(env));
63
+ const next = { ...readState(env), ...patch };
64
+ fs.writeFileSync(statePath(env), JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
65
+ } catch { /* state is best-effort */ }
66
+ }
67
+
68
+ function lockFresh(env = process.env, now = Date.now()) {
69
+ try {
70
+ const info = JSON.parse(fs.readFileSync(lockPath(env), 'utf8'));
71
+ return now - Number(info.at) <= LOCK_STALE_MS;
72
+ } catch (err) {
73
+ if (err && err.code === 'ENOENT') return false;
74
+ // Unreadable lock: check the file mtime instead of treating it as free.
75
+ try { return now - fs.statSync(lockPath(env)).mtimeMs <= LOCK_STALE_MS; } catch { return false; }
76
+ }
77
+ }
78
+
79
+ function acquireLock(env = process.env, now = Date.now()) {
80
+ ensureDir(autoDir(env));
81
+ for (let attempt = 0; attempt < 2; attempt++) {
82
+ try {
83
+ const fd = fs.openSync(lockPath(env), 'wx', 0o600);
84
+ fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, at: now }) + '\n');
85
+ fs.closeSync(fd);
86
+ return true;
87
+ } catch (err) {
88
+ if (!err || err.code !== 'EEXIST') return false;
89
+ if (lockFresh(env, now)) return false;
90
+ try { fs.unlinkSync(lockPath(env)); } catch { return false; }
91
+ }
92
+ }
93
+ return false;
94
+ }
95
+
96
+ function releaseLock(env = process.env) {
97
+ try { fs.unlinkSync(lockPath(env)); } catch { /* already gone */ }
98
+ }
99
+
100
+ function cooldownActive(env = process.env, now = Date.now()) {
101
+ const state = readState(env);
102
+ const completed = Number(state.lastCompletedAt);
103
+ if (Number.isFinite(completed) && now - completed < COOLDOWN_MS) return true;
104
+ const attempted = Number(state.lastAttemptAt);
105
+ if (Number.isFinite(attempted) && now - attempted < ATTEMPT_COOLDOWN_MS) return true;
106
+ return false;
107
+ }
108
+
109
+ // The tier choice is derived entirely from the server's debt block: both the
110
+ // per-tier debt numbers and the threshold come from the response.
111
+ function pickTier(debt) {
112
+ const threshold = Number(debt && debt.threshold_importance);
113
+ const rawEquiv = Number(debt && debt.unconsolidated && debt.unconsolidated.raw
114
+ && debt.unconsolidated.raw.importance_equiv);
115
+ const tier2 = Number(debt && debt.unconsolidated && debt.unconsolidated.tier2
116
+ && debt.unconsolidated.tier2.importance);
117
+ if (Number.isFinite(threshold) && threshold > 0) {
118
+ if (Number.isFinite(rawEquiv) && rawEquiv >= threshold) return 1;
119
+ if (Number.isFinite(tier2) && tier2 >= threshold) return 2;
120
+ }
121
+ return /tier 2/i.test(String(debt && debt.suggestion || '')) ? 2 : 1;
122
+ }
123
+
124
+ function maxBatches(env = process.env) {
125
+ const raw = parseInt(env.MEMORYROUTER_AUTO_MAX_BATCHES, 10);
126
+ if (Number.isInteger(raw) && raw >= 1) return Math.min(raw, MAX_BATCHES_PER_TRIGGER);
127
+ return MAX_BATCHES_PER_TRIGGER;
128
+ }
129
+
130
+ /**
131
+ * Trigger check + detached spawn. Called from the hook path with the results
132
+ * of the /prepare requests it already made; never blocks and never throws.
133
+ */
134
+ function maybeSpawnAutoConsolidate(results, cfg = {}, options = {}) {
135
+ const env = options.env || process.env;
136
+ try {
137
+ if (env.MEMORYROUTER_DISABLE === '1') return false;
138
+ if (cfg.autoConsolidate === false) return false;
139
+ const debt = (results || []).map((item) => item && item.reflection)
140
+ .find((reflection) => reflection && reflection.suggestion);
141
+ if (!debt) return false;
142
+ const now = options.now || Date.now();
143
+ if (cooldownActive(env, now)) return false;
144
+ if (lockFresh(env, now)) return false;
145
+
146
+ const spawner = options.spawn || childProcess.spawn;
147
+ const cliPath = options.cliPath || path.resolve(__dirname, '..', 'bin', 'cli.js');
148
+ ensureDir(autoDir(env));
149
+ const out = fs.openSync(logPath(env), 'a');
150
+ try {
151
+ const child = spawner(process.execPath, [cliPath, 'reflect-auto'], {
152
+ detached: true,
153
+ stdio: ['ignore', out, out],
154
+ env: { ...env },
155
+ });
156
+ if (child && child.unref) child.unref();
157
+ } finally {
158
+ try { fs.closeSync(out); } catch { /* fd handed to child */ }
159
+ }
160
+ appendLog(`trigger: spawned reflect-auto (suggestion: ${debt.suggestion})`, env);
161
+ return true;
162
+ } catch (err) {
163
+ appendLog(`trigger error: ${err && err.message}`, env);
164
+ return false;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * The detached background run: acquire the lock, consolidate up to 3 batches
170
+ * re-checking debt between each, record the completion timestamp, release.
171
+ * Runs the EXISTING reflect loop (lib/reflect.js); nothing is duplicated.
172
+ */
173
+ async function runAutoConsolidate(options = {}) {
174
+ const env = options.env || process.env;
175
+ const now = options.now || (() => Date.now());
176
+ const api = options.api || require('./api');
177
+ const runReflect = options.runReflect || require('./reflect').runReflect;
178
+ const log = (line) => appendLog(line, env);
179
+ const key = options.key;
180
+ if (!key) { log('auto: no API key available; skipping'); return { committed: 0, reason: 'no-key' }; }
181
+
182
+ if (cooldownActive(env, now())) { log('auto: cooldown active; skipping'); return { committed: 0, reason: 'cooldown' }; }
183
+ if (!acquireLock(env, now())) { log('auto: another consolidation run holds the lock; skipping'); return { committed: 0, reason: 'locked' }; }
184
+
185
+ writeState({ lastAttemptAt: now() }, env);
186
+ let committed = 0;
187
+ try {
188
+ const bound = maxBatches(env);
189
+ for (let batch = 0; batch < bound; batch++) {
190
+ const probe = await api.debtProbe(key);
191
+ const debt = probe && probe.ok && probe.data && probe.data.reflection;
192
+ if (!debt || !debt.suggestion) {
193
+ log(`auto: debt below threshold after ${committed} batch(es); stopping`);
194
+ break;
195
+ }
196
+ const tier = pickTier(debt);
197
+ log(`auto: batch ${batch + 1}/${bound} starting (tier ${tier}; ${debt.suggestion})`);
198
+ let summary;
199
+ try {
200
+ summary = await runReflect({ key, tier, batches: '1', log });
201
+ } catch (err) {
202
+ log(`auto: reflect failed: ${err && err.message}`);
203
+ break;
204
+ }
205
+ if (!summary || !summary.batches_committed) {
206
+ log('auto: no batch committed; stopping');
207
+ break;
208
+ }
209
+ committed += summary.batches_committed;
210
+ }
211
+ if (committed > 0) {
212
+ writeState({ lastCompletedAt: now() }, env);
213
+ log(`auto: run complete, ${committed} batch(es) committed`);
214
+ }
215
+ } finally {
216
+ releaseLock(env);
217
+ }
218
+ return { committed };
219
+ }
220
+
221
+ module.exports = {
222
+ maybeSpawnAutoConsolidate,
223
+ runAutoConsolidate,
224
+ acquireLock,
225
+ releaseLock,
226
+ lockFresh,
227
+ cooldownActive,
228
+ pickTier,
229
+ appendLog,
230
+ readState,
231
+ writeState,
232
+ autoDir,
233
+ LOCK_STALE_MS,
234
+ COOLDOWN_MS,
235
+ ATTEMPT_COOLDOWN_MS,
236
+ MAX_BATCHES_PER_TRIGGER,
237
+ };
@@ -14,6 +14,7 @@ const {
14
14
  pruneState,
15
15
  } = require('./config');
16
16
  const api = require('./api');
17
+ const { maybeSpawnAutoConsolidate } = require('./auto');
17
18
  const { hash, compactText, cleanText, finalAssistantFromTranscript } = require('./transcript');
18
19
  const { deriveProjectIdentity, sessionIdFor } = require('./project');
19
20
 
@@ -116,16 +117,31 @@ function reflectionNudgeLine(results) {
116
117
  return null;
117
118
  }
118
119
 
120
+ function importNudgeLine(results) {
121
+ // Same contract as the consolidation nudge: the server owns the decision
122
+ // (import.suggested on any /prepare result) and this only renders one line.
123
+ // No rate limit; the state clears server-side on import/dismiss.
124
+ for (const item of results) {
125
+ const imp = item && item.importState;
126
+ if (imp && imp.suggested) {
127
+ return '[MemoryRouter] Historical import suggested: this machine has local conversation history not yet in your vault. Run: npx memoryrouter-claude import --instructions';
128
+ }
129
+ }
130
+ return null;
131
+ }
132
+
119
133
  async function maybeAppendNudge(input, context, results, maxChars) {
120
134
  // Rules (connectors spec section c): only on an already-emitted context,
121
135
  // never a context solely for the nudge, and always inside the existing
122
136
  // char cap so memory content wins. Fires on every run with a suggestion.
123
137
  if (!context) return context;
124
- const line = reflectionNudgeLine(results);
125
- if (!line) return context;
126
138
  const cap = Math.max(1000, Math.min(MAX_CONTEXT_CHARS, Number(maxChars) || MAX_CONTEXT_CHARS));
127
- if (context.length + line.length + 1 > cap) return context;
128
- return `${context}\n${line}`;
139
+ for (const line of [reflectionNudgeLine(results), importNudgeLine(results)]) {
140
+ if (!line) continue;
141
+ if (context.length + line.length + 1 > cap) continue;
142
+ context = `${context}\n${line}`;
143
+ }
144
+ return context;
129
145
  }
130
146
 
131
147
  async function retrieveContext(input, key, prompt, eventName) {
@@ -136,20 +152,28 @@ async function retrieveContext(input, key, prompt, eventName) {
136
152
  const density = cfg.density;
137
153
  const requests = [];
138
154
 
155
+ const toResult = (label) => (res) => ({
156
+ label,
157
+ context: res.ok && res.data && res.data.context,
158
+ reflection: res.ok && res.data && res.data.reflection,
159
+ importState: res.ok && res.data && res.data.import,
160
+ });
161
+
139
162
  if (identity.memoryScope === 'global') {
140
- requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
141
- .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
163
+ requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density }).then(toResult('Global')));
142
164
  } else {
143
- requests.push(api.prepare(key, prompt, identity.id, { timeoutMs: 5500, contextLimit, density })
144
- .then((res) => ({ label: 'Project', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
165
+ requests.push(api.prepare(key, prompt, identity.id, { timeoutMs: 5500, contextLimit, density }).then(toResult('Project')));
145
166
  if (identity.includeGlobal) {
146
- requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
147
- .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
167
+ requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density }).then(toResult('Global')));
148
168
  }
149
169
  }
150
170
 
151
171
  const settled = await Promise.allSettled(requests);
152
172
  const results = settled.filter((r) => r.status === 'fulfilled').map((r) => r.value);
173
+ // Automatic consolidation (default on, cfg.autoConsolidate: false opts out):
174
+ // fire-and-forget detached background run when the server says
175
+ // should-consolidate. Never blocks recall, never throws into the hook.
176
+ maybeSpawnAutoConsolidate(results, cfg);
153
177
  let context = mergeContexts(results, identity, cfg.maxContextChars || MAX_CONTEXT_CHARS);
154
178
  if (context && input.session_id) {
155
179
  context = await maybeAppendNudge(input, context, results, cfg.maxContextChars || MAX_CONTEXT_CHARS);
@@ -567,5 +591,7 @@ module.exports = {
567
591
  emitContext,
568
592
  stateKeyFor,
569
593
  reflectionNudgeLine,
594
+ importNudgeLine,
595
+ maybeAppendNudge,
570
596
  MAX_CONTEXT_CHARS,
571
597
  };
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+ // Client-side mirror of the server import identity math
3
+ // (workers/src/services/import-identity.ts). Byte-for-byte: the server
4
+ // recomputes every hash from the wire fields and rejects any mismatch, so
5
+ // these formulas MUST stay in lockstep with the server. If either side
6
+ // changes, change the other and bump PARSER_VERSION.
7
+ //
8
+ // IMPORTANT: none of these functions ever incorporate the raw Memory Key.
9
+ // The destination is represented only by an opaque fingerprint.
10
+
11
+ const { createHash } = require('crypto');
12
+
13
+ const PARSER_VERSION = 1;
14
+ const CHUNK_VERSION = 1;
15
+ const SOURCE_PLATFORM = 'claude-code';
16
+
17
+ function sha256hex(input) {
18
+ return createHash('sha256').update(input, 'utf8').digest('hex');
19
+ }
20
+
21
+ function sortKeys(value) {
22
+ if (Array.isArray(value)) return value.map(sortKeys);
23
+ if (value && typeof value === 'object') {
24
+ const out = {};
25
+ for (const key of Object.keys(value).sort()) out[key] = sortKeys(value[key]);
26
+ return out;
27
+ }
28
+ return value;
29
+ }
30
+
31
+ /** Canonical JSON: recursively key-sorted. Identical to the server. */
32
+ function canonicalJson(value) {
33
+ return JSON.stringify(sortKeys(value));
34
+ }
35
+
36
+ /** Deterministic text normalization. Identical to the server normalizeText. */
37
+ function normalizeText(input) {
38
+ return input.normalize('NFC').replace(/\r\n?/g, '\n').trim();
39
+ }
40
+
41
+ /** Opaque, non-reversible destination fingerprint. */
42
+ function vaultFingerprint(memoryKey) {
43
+ return `mrvault_${sha256hex(memoryKey).slice(0, 16)}`;
44
+ }
45
+
46
+ function unescapeIdPart(s) {
47
+ return s.replace(/%3A/g, ':').replace(/%25/g, '%');
48
+ }
49
+
50
+ /** Recover (platform, conversationId, messageId, parserVersion) or null. */
51
+ function parseExternalId(id) {
52
+ const parts = id.split(':');
53
+ if (parts.length !== 4) return null;
54
+ const [platform, conv, msg, ver] = parts;
55
+ if (!/^v\d+$/.test(ver)) return null;
56
+ return {
57
+ platform,
58
+ conversationId: unescapeIdPart(conv),
59
+ messageId: unescapeIdPart(msg),
60
+ parserVersion: parseInt(ver.slice(1), 10),
61
+ };
62
+ }
63
+
64
+ /** Content-bound record hash. Mirrors the server computeRecordHash exactly. */
65
+ function recordHash(fields) {
66
+ return sha256hex(
67
+ canonicalJson({
68
+ conversationId: fields.conversationId,
69
+ messageId: fields.messageId,
70
+ role: fields.role,
71
+ text: normalizeText(fields.text),
72
+ timestamp: fields.timestamp,
73
+ v: PARSER_VERSION,
74
+ }),
75
+ ).slice(0, 32);
76
+ }
77
+
78
+ /** Per-conversation content hash. Mirrors the chatgpt CLI conversationContentHash. */
79
+ function conversationContentHash(fields) {
80
+ return sha256hex(canonicalJson(fields)).slice(0, 32);
81
+ }
82
+
83
+ /** Content identity of the whole extract, independent of read order. */
84
+ function archiveContentId(conversationContentHashes) {
85
+ const canonical = [...conversationContentHashes].sort().join('\n');
86
+ return `arc_${sha256hex(`v${PARSER_VERSION}\n${canonical}`).slice(0, 24)}`;
87
+ }
88
+
89
+ /** Deterministic import id: same extract to the same vault = same import. */
90
+ function deriveImportId(archiveId, fingerprint) {
91
+ return `imp_${sha256hex(`${archiveId}|${fingerprint}|p${PARSER_VERSION}|c${CHUNK_VERSION}`).slice(0, 24)}`;
92
+ }
93
+
94
+ /** Client-computed preview digest; the server recomputes and must agree. */
95
+ function previewDigest(preview) {
96
+ return `pvd_${sha256hex(canonicalJson(preview)).slice(0, 32)}`;
97
+ }
98
+
99
+ module.exports = {
100
+ PARSER_VERSION,
101
+ CHUNK_VERSION,
102
+ SOURCE_PLATFORM,
103
+ sha256hex,
104
+ canonicalJson,
105
+ normalizeText,
106
+ vaultFingerprint,
107
+ parseExternalId,
108
+ recordHash,
109
+ conversationContentHash,
110
+ archiveContentId,
111
+ deriveImportId,
112
+ previewDigest,
113
+ };
package/lib/import.js ADDED
@@ -0,0 +1,421 @@
1
+ 'use strict';
2
+ // Agent-driven historical import: the transport half.
3
+ //
4
+ // Division of labor (locked): the SERVER owns the extraction prompt
5
+ // (GET /v1/memory/imports/instructions, versioned like reflection_contract);
6
+ // the HOST AGENT executes that prompt locally and writes a JSONL extract; THIS
7
+ // MODULE owns transport only: local validation, deterministic identity math
8
+ // (byte-for-byte with the server), create/approve, idempotent batch upload
9
+ // with resume, and the receipt. The agent never touches HTTP for upload and
10
+ // this module never parses conversation history.
11
+ //
12
+ // The Memory Key never appears in the prompt or the extract file; it rides
13
+ // only in the Authorization header via lib/api.js.
14
+
15
+ const fs = require('fs');
16
+ const { spawnSync } = require('child_process');
17
+ const readline = require('readline');
18
+ const defaultApi = require('./api');
19
+ const ids = require('./import-identity');
20
+
21
+ const PLATFORM = 'claude-code';
22
+ const BATCH_SIZE = 2000; // server maximum per batch
23
+ const MAX_CONTENT_CHARS = 1000000;
24
+ const MAX_UPLOAD_ATTEMPTS = 5;
25
+ const INITIAL_BACKOFF_MS = 2000;
26
+ const MAX_BACKOFF_MS = 30000;
27
+
28
+ function sleep(ms) {
29
+ return new Promise((resolve) => setTimeout(resolve, ms));
30
+ }
31
+
32
+ function fmtDate(ms) {
33
+ if (!Number.isFinite(ms) || ms <= 0) return 'unknown';
34
+ return new Date(ms).toISOString().slice(0, 10);
35
+ }
36
+
37
+ function fmtTokens(n) {
38
+ if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
39
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
40
+ return String(n);
41
+ }
42
+
43
+ function apiErrorDetail(res) {
44
+ const data = res && res.data;
45
+ if (data && typeof data === 'object') {
46
+ const parts = [data.error, data.message].filter(Boolean);
47
+ if (parts.length) return parts.join(': ');
48
+ }
49
+ return `HTTP ${res && res.status}`;
50
+ }
51
+
52
+ /**
53
+ * Read + validate the JSONL extract. Four fields per record, platform-prefixed
54
+ * external_id, numeric epoch-ms timestamps, role user/assistant, non-empty
55
+ * content. Returns { records } or { error } (first offending line reported).
56
+ */
57
+ function readExtract(filePath, platform = PLATFORM) {
58
+ let raw;
59
+ try {
60
+ raw = fs.readFileSync(filePath, 'utf8');
61
+ } catch (err) {
62
+ return { error: `could not read ${filePath}: ${err.message}` };
63
+ }
64
+ const records = [];
65
+ const seen = new Set();
66
+ const lines = raw.split('\n');
67
+ for (let i = 0; i < lines.length; i++) {
68
+ const line = lines[i].trim();
69
+ if (!line) continue;
70
+ const lineNo = i + 1;
71
+ let p;
72
+ try {
73
+ p = JSON.parse(line);
74
+ } catch {
75
+ return { error: `line ${lineNo}: not valid JSON` };
76
+ }
77
+ if (!p || typeof p !== 'object' || Array.isArray(p)) return { error: `line ${lineNo}: record is not an object` };
78
+ const extras = Object.keys(p).filter((k) => !['external_id', 'content', 'timestamp', 'role'].includes(k));
79
+ if (extras.length) return { error: `line ${lineNo}: unexpected fields: ${extras.join(', ')}` };
80
+ if (typeof p.external_id !== 'string' || !p.external_id) return { error: `line ${lineNo}: external_id must be a string` };
81
+ const parsed = ids.parseExternalId(p.external_id);
82
+ if (!parsed) return { error: `line ${lineNo}: malformed external_id (expected ${platform}:<conversation>:<message>:v${ids.PARSER_VERSION})` };
83
+ if (parsed.platform !== platform) return { error: `line ${lineNo}: external_id platform must be ${platform}, got ${parsed.platform}` };
84
+ if (parsed.parserVersion !== ids.PARSER_VERSION) return { error: `line ${lineNo}: external_id version must be v${ids.PARSER_VERSION}` };
85
+ if (typeof p.content !== 'string' || p.content.length === 0) return { error: `line ${lineNo}: content must be a non-empty string` };
86
+ if (p.content.length > MAX_CONTENT_CHARS) return { error: `line ${lineNo}: content exceeds ${MAX_CONTENT_CHARS} chars` };
87
+ if (typeof p.timestamp !== 'number' || !Number.isFinite(p.timestamp) || p.timestamp <= 0) {
88
+ return { error: `line ${lineNo}: timestamp must be a positive epoch-milliseconds number` };
89
+ }
90
+ if (p.timestamp < 1000000000000) return { error: `line ${lineNo}: timestamp looks like seconds, not milliseconds (${p.timestamp})` };
91
+ if (p.role !== 'user' && p.role !== 'assistant') return { error: `line ${lineNo}: role must be "user" or "assistant"` };
92
+ if (seen.has(p.external_id)) return { error: `line ${lineNo}: duplicate external_id ${p.external_id}` };
93
+ seen.add(p.external_id);
94
+ records.push({
95
+ externalId: p.external_id,
96
+ conversationId: parsed.conversationId,
97
+ messageId: parsed.messageId,
98
+ content: p.content,
99
+ role: p.role,
100
+ timestamp: p.timestamp,
101
+ });
102
+ }
103
+ if (records.length === 0) return { error: 'the extract file contains no records' };
104
+ return { records };
105
+ }
106
+
107
+ /**
108
+ * Deterministic identity for the whole extract: per-record hashes, sorted
109
+ * per-conversation content hashes, archive id, and the vault-bound import id.
110
+ * Same math as the chatgpt CLI (cli/src/chatgpt/ids.ts), so re-running the
111
+ * command replays the same import and committed batches return for free.
112
+ */
113
+ function computeIdentity(records, memoryKey, platform = PLATFORM) {
114
+ const byConversation = new Map();
115
+ for (const r of records) {
116
+ r.recordSha256 = ids.recordHash({
117
+ conversationId: r.conversationId,
118
+ messageId: r.messageId,
119
+ role: r.role,
120
+ text: r.content,
121
+ timestamp: r.timestamp,
122
+ });
123
+ if (!byConversation.has(r.conversationId)) byConversation.set(r.conversationId, []);
124
+ byConversation.get(r.conversationId).push(r);
125
+ }
126
+ const convHashes = [];
127
+ for (const [conversationId, convRecords] of byConversation) {
128
+ convHashes.push(ids.conversationContentHash({
129
+ conversationId,
130
+ canonicalPolicy: `agent-extract-${platform}`,
131
+ canonicalLeaf: null,
132
+ records: convRecords.map((r) => ({
133
+ externalId: r.externalId,
134
+ recordHash: r.recordSha256,
135
+ role: r.role,
136
+ timestamp: r.timestamp,
137
+ })),
138
+ }));
139
+ }
140
+ const archiveId = ids.archiveContentId(convHashes);
141
+ const fingerprint = ids.vaultFingerprint(memoryKey);
142
+ const importId = ids.deriveImportId(archiveId, fingerprint);
143
+ return { archiveId, fingerprint, importId, conversations: byConversation.size };
144
+ }
145
+
146
+ function estimateTokens(records) {
147
+ let total = 0;
148
+ for (const r of records) total += Math.ceil(r.content.length / 4);
149
+ return total;
150
+ }
151
+
152
+ function buildPreviewSummary(records) {
153
+ let earliest = Number.POSITIVE_INFINITY;
154
+ let latest = 0;
155
+ let user = 0;
156
+ for (const r of records) {
157
+ if (r.role === 'user') user++;
158
+ if (r.timestamp < earliest) earliest = r.timestamp;
159
+ if (r.timestamp > latest) latest = r.timestamp;
160
+ }
161
+ return {
162
+ records: records.length,
163
+ userRecords: user,
164
+ assistantRecords: records.length - user,
165
+ earliestMs: Number.isFinite(earliest) ? earliest : 0,
166
+ latestMs: latest,
167
+ estimatedTokens: estimateTokens(records),
168
+ };
169
+ }
170
+
171
+ function toWireRecord(r, platform = PLATFORM) {
172
+ return JSON.stringify({
173
+ external_id: r.externalId,
174
+ record_sha256: r.recordSha256,
175
+ content: r.content,
176
+ role: r.role,
177
+ timestamp: r.timestamp,
178
+ source_platform: platform,
179
+ parser_version: ids.PARSER_VERSION,
180
+ chunk_version: ids.CHUNK_VERSION,
181
+ });
182
+ }
183
+
184
+ function chunkArray(arr, size) {
185
+ const out = [];
186
+ for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
187
+ return out;
188
+ }
189
+
190
+ function ask(question) {
191
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
192
+ return new Promise((resolve) => rl.question(question, (answer) => {
193
+ rl.close();
194
+ resolve(answer.trim().toLowerCase());
195
+ }));
196
+ }
197
+
198
+ /**
199
+ * Fetch and print (or execute) the server-side extraction prompt. With
200
+ * spawn=true the prompt runs through the local Claude Code CLI (claude -p),
201
+ * following the reflect verb's spawn pattern; the model does the extraction
202
+ * work and the user then runs `import --file <path>`.
203
+ */
204
+ async function runInstructions(options = {}) {
205
+ const key = options.key;
206
+ if (!key) throw new Error('a Memory Key is required');
207
+ const api = options.api || defaultApi;
208
+ const log = options.log || ((...args) => console.log(...args));
209
+ const res = await api.importInstructions(key, options.platform || PLATFORM, { outputPath: options.outputPath });
210
+ if (!res.ok) throw new Error(`could not fetch import instructions (${apiErrorDetail(res)})`);
211
+ const data = res.data || {};
212
+ if (!data.prompt) throw new Error('instructions response carried no prompt');
213
+
214
+ if (options.spawn) {
215
+ const spawn = options.spawnSync || spawnSync;
216
+ log(`Running the extraction prompt through claude -p (import prompt v${data.import_prompt_version})...`);
217
+ const result = spawn('claude', ['-p', data.prompt], {
218
+ encoding: 'utf8',
219
+ maxBuffer: 64 * 1024 * 1024,
220
+ timeout: 30 * 60 * 1000,
221
+ });
222
+ if (result.error) throw new Error(`could not run the claude CLI: ${result.error.message}`);
223
+ log(String(result.stdout || ''));
224
+ if (result.status !== 0) {
225
+ throw new Error(`claude CLI exited ${result.status}: ${String(result.stderr || '').slice(0, 400)}`);
226
+ }
227
+ log('');
228
+ log(`Extraction finished. Next: ${data.next_command}`);
229
+ return { spawned: true, version: data.import_prompt_version };
230
+ }
231
+
232
+ log(data.prompt);
233
+ return { spawned: false, version: data.import_prompt_version };
234
+ }
235
+
236
+ /** Call the dismiss endpoint so the server-side nudge stops permanently. */
237
+ async function runDismiss(options = {}) {
238
+ const key = options.key;
239
+ if (!key) throw new Error('a Memory Key is required');
240
+ const api = options.api || defaultApi;
241
+ const log = options.log || ((...args) => console.log(...args));
242
+ const res = await api.importDismiss(key, options.platform || PLATFORM);
243
+ if (!res.ok) throw new Error(`dismiss failed (${apiErrorDetail(res)})`);
244
+ log('Import suggestion dismissed permanently for this vault.');
245
+ return res.data;
246
+ }
247
+
248
+ /**
249
+ * The transport: validate the extract, compute identity, create the import
250
+ * (deterministic import_id -> re-runs resume for free), show the preview +
251
+ * server price quote, require approval, upload batches with Idempotency-Keys
252
+ * and bounded backoff, then print the receipt.
253
+ */
254
+ async function runImportFile(options = {}) {
255
+ const key = options.key;
256
+ if (!key) throw new Error('a Memory Key is required');
257
+ if (!options.file) throw new Error('--file <path> is required');
258
+ const api = options.api || defaultApi;
259
+ const log = options.log || ((...args) => console.log(...args));
260
+ const platform = options.platform || PLATFORM;
261
+
262
+ // 1. Validate locally (fail fast, never partially upload a malformed file).
263
+ const parsed = readExtract(options.file, platform);
264
+ if (parsed.error) throw new Error(`invalid extract: ${parsed.error}`);
265
+ const records = parsed.records;
266
+ const identity = computeIdentity(records, key, platform);
267
+ const preview = buildPreviewSummary(records);
268
+
269
+ // 2. Create / preflight (idempotent: same content + vault = same import).
270
+ const previewDigest = ids.previewDigest({
271
+ importId: identity.importId,
272
+ archiveId: identity.archiveId,
273
+ fingerprint: identity.fingerprint,
274
+ parserVersion: ids.PARSER_VERSION,
275
+ chunkVersion: ids.CHUNK_VERSION,
276
+ expectedRecords: preview.records,
277
+ expectedChunks: preview.records,
278
+ estimatedTokens: preview.estimatedTokens,
279
+ selection: null,
280
+ categories: [],
281
+ });
282
+ const createRes = await api.importCreate(key, {
283
+ import_id: identity.importId,
284
+ archive_content_id: identity.archiveId,
285
+ archive_sha256: null,
286
+ parser_version: ids.PARSER_VERSION,
287
+ chunk_version: ids.CHUNK_VERSION,
288
+ source_platform: platform,
289
+ vault_fingerprint: identity.fingerprint,
290
+ preview_digest: previewDigest,
291
+ expected_records: preview.records,
292
+ expected_chunks: preview.records,
293
+ estimated_tokens: preview.estimatedTokens,
294
+ selection: null,
295
+ categories: [],
296
+ });
297
+ if (!createRes.ok) throw new Error(`import preflight failed (${apiErrorDetail(createRes)})`);
298
+ const created = createRes.data || {};
299
+ if (created.preview_digest && created.preview_digest !== previewDigest) {
300
+ throw new Error('client/server preview digest mismatch (fail closed)');
301
+ }
302
+ const quote = created.cost_quote || {};
303
+
304
+ // 3. Preview + quote for the user.
305
+ log('');
306
+ log('Import preview');
307
+ log('----------------------------');
308
+ log(`Platform: ${platform}`);
309
+ log(`Destination vault: ${identity.fingerprint} (opaque fingerprint)`);
310
+ log(`Conversations: ${identity.conversations}`);
311
+ log(`Records: ${preview.records} (user ${preview.userRecords}, assistant ${preview.assistantRecords})`);
312
+ log(`Date range: ${fmtDate(preview.earliestMs)} to ${fmtDate(preview.latestMs)}`);
313
+ log(`Estimated tokens: ${fmtTokens(preview.estimatedTokens)}`);
314
+ if (quote.available) {
315
+ log(`Estimated cost: $${((quote.estimated_cost_cents || 0) / 100).toFixed(2)} (rate $${quote.rate_per_million_usd}/1M paid tokens, free remaining ${fmtTokens(quote.free_tokens_remaining || 0)})`);
316
+ } else {
317
+ log(`Estimated cost: unavailable (${quote.reason || 'unknown'}); the server will refuse approval (fail closed)`);
318
+ }
319
+ log(`Import id: ${identity.importId}`);
320
+ log('');
321
+ log('Re-running this command is always safe: committed batches replay for free and duplicates are never re-billed.');
322
+ log('');
323
+
324
+ // 4. Explicit approval.
325
+ if (!options.yes) {
326
+ if (options.nonInteractive || !process.stdin.isTTY) {
327
+ throw new Error('approval required: re-run with --yes to confirm the upload');
328
+ }
329
+ const answer = await ask('Proceed with the upload? [y/N]: ');
330
+ if (answer !== 'y' && answer !== 'yes') {
331
+ log('Aborted. Nothing was uploaded.');
332
+ return { aborted: true };
333
+ }
334
+ }
335
+
336
+ const approveRes = await api.importApprove(key, identity.importId, created.approval_digest);
337
+ if (!approveRes.ok) {
338
+ // A completed import cannot be re-approved; that is the fully-settled
339
+ // resume case. Print the receipt instead of failing.
340
+ const reason = approveRes.data && approveRes.data.error;
341
+ if (reason === 'import_completed') {
342
+ const receiptRes = await api.importReceipt(key, identity.importId);
343
+ const receipt = receiptRes.ok && receiptRes.data ? receiptRes.data.receipt || null : null;
344
+ log('This exact extract was already fully imported into this vault. Nothing to upload.');
345
+ if (receipt) {
346
+ log('Receipt:');
347
+ log(JSON.stringify(receipt, null, 2));
348
+ }
349
+ return { importId: identity.importId, alreadyComplete: true, complete: true, receipt };
350
+ }
351
+ throw new Error(`approval refused (${apiErrorDetail(approveRes)})`);
352
+ }
353
+
354
+ // 5. Idempotent batch upload with bounded backoff. Resume is free: a batch
355
+ // index that was already durably committed replays its stored response.
356
+ const batches = chunkArray(records, options.batchSize || BATCH_SIZE);
357
+ const totals = { stored: 0, duplicate: 0, skipped: 0, failed: 0, conflict: 0 };
358
+ log(`Uploading ${records.length} record(s) in ${batches.length} batch(es)...`);
359
+ for (let i = 0; i < batches.length; i++) {
360
+ const jsonl = batches[i].map((r) => toWireRecord(r, platform)).join('\n');
361
+ const idempotencyKey = `${identity.importId}:b${i}`;
362
+ let res = null;
363
+ let backoff = INITIAL_BACKOFF_MS;
364
+ for (let attempt = 1; attempt <= MAX_UPLOAD_ATTEMPTS; attempt++) {
365
+ try {
366
+ res = await api.importBatch(key, identity.importId, i, jsonl, idempotencyKey);
367
+ } catch (err) {
368
+ res = null;
369
+ if (attempt === MAX_UPLOAD_ATTEMPTS) throw new Error(`batch ${i} failed after ${MAX_UPLOAD_ATTEMPTS} attempts: ${err.message}`);
370
+ }
371
+ if (res && (res.ok || (res.status < 500 && res.status !== 429))) break;
372
+ if (attempt === MAX_UPLOAD_ATTEMPTS) break;
373
+ await sleep(backoff);
374
+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
375
+ }
376
+ if (!res) throw new Error(`batch ${i} received no response`);
377
+ if (res.status === 402) {
378
+ throw new Error('payment required: out of tokens/credits. Add credits at https://app.memoryrouter.ai and re-run to resume.');
379
+ }
380
+ if (!res.ok) throw new Error(`batch ${i} failed (${apiErrorDetail(res)}). Re-run to resume; committed batches replay for free.`);
381
+ const body = res.data || {};
382
+ const s = body.summary || {};
383
+ totals.stored += s.stored || 0;
384
+ totals.duplicate += s.duplicate || 0;
385
+ totals.skipped += s.skipped || 0;
386
+ totals.failed += s.failed || 0;
387
+ totals.conflict += s.conflict || 0;
388
+ log(` batch ${i + 1}/${batches.length}${body.replayed ? ' (replayed, free)' : ''}: stored ${s.stored || 0}, duplicate ${s.duplicate || 0}, failed ${s.failed || 0}`);
389
+ }
390
+
391
+ // 6. Receipt.
392
+ const statusRes = await api.importStatus(key, identity.importId);
393
+ const complete = Boolean(statusRes.ok && statusRes.data && statusRes.data.complete);
394
+ let receipt = null;
395
+ if (complete) {
396
+ const receiptRes = await api.importReceipt(key, identity.importId);
397
+ if (receiptRes.ok && receiptRes.data) receipt = receiptRes.data.receipt || null;
398
+ }
399
+ log('');
400
+ log(`Done. stored=${totals.stored} duplicate=${totals.duplicate} skipped=${totals.skipped} failed=${totals.failed} conflict=${totals.conflict}`);
401
+ if (receipt) {
402
+ log('Receipt:');
403
+ log(JSON.stringify(receipt, null, 2));
404
+ } else if (!complete) {
405
+ log('The import is not fully settled yet; re-run this command to resume/reconcile.');
406
+ }
407
+ return { importId: identity.importId, totals, complete, receipt };
408
+ }
409
+
410
+ module.exports = {
411
+ PLATFORM,
412
+ BATCH_SIZE,
413
+ readExtract,
414
+ computeIdentity,
415
+ buildPreviewSummary,
416
+ estimateTokens,
417
+ toWireRecord,
418
+ runInstructions,
419
+ runDismiss,
420
+ runImportFile,
421
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memoryrouter-claude",
3
- "version": "2.2.1",
3
+ "version": "2.4.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>",