memoryrouter-claude 2.3.0 → 2.5.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 +7 -0
- package/README.md +26 -0
- package/bin/cli.js +96 -0
- package/lib/auto.js +237 -0
- package/lib/hook-runner.js +9 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.5.0 (2026-08-17)
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `date-search` CLI verb: time-window retrieval with `--from` (required ISO 8601), `--to`, `--query`, `--tiers 1,2,3`, `--importance N` (minimum threshold; only reflections carry ratings), `--max-tokens N`, and `--json`. Prints continuation cursors when the window is truncated.
|
|
8
|
+
- Injected recall context now carries a one-line hint teaching the model to use `date-search` with `--tiers 2,3 --importance 7` for questions like "most important things lately".
|
|
9
|
+
|
|
3
10
|
## Unreleased
|
|
4
11
|
|
|
5
12
|
### Added
|
package/README.md
CHANGED
|
@@ -172,6 +172,7 @@ The key is stored only at `~/.memoryrouter/config.json` with mode `0600` in a mo
|
|
|
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
174
|
| `npx memoryrouter-claude status` | Show key, vault stats, consolidation debt, and active project scope |
|
|
175
|
+
| `npx memoryrouter-claude date-search` | Retrieve memories from a specific time window with tier and importance filters |
|
|
175
176
|
| `npx memoryrouter-claude reflect` | Consolidate memories into reflections using your local `claude` CLI |
|
|
176
177
|
| `npx memoryrouter-claude mcp install` | Add the OAuth MCP manual surface with current Claude CLI syntax |
|
|
177
178
|
| `npx memoryrouter-claude mcp status` | Inspect MCP configuration |
|
|
@@ -179,6 +180,19 @@ The key is stored only at `~/.memoryrouter/config.json` with mode `0600` in a mo
|
|
|
179
180
|
| `npx memoryrouter-claude off` | Remove MemoryRouter hooks from local/project/user settings |
|
|
180
181
|
| `npx memoryrouter-claude off --purge` | Also delete private key/config/checkpoint state |
|
|
181
182
|
|
|
183
|
+
## Date search (time-window retrieval)
|
|
184
|
+
|
|
185
|
+
Retrieve memories from a specific time window. Use for questions like 'what happened last week' or 'most important things this month or lately'. For importance questions set importance to 7 or higher with tiers 2,3, since only reflections carry importance ratings. Omit `--query` for a chronological review; include `--query` to rank by relevance within the window. Resolve relative phrases like 'lately' to concrete ISO dates before calling.
|
|
186
|
+
|
|
187
|
+
```bash
|
|
188
|
+
npx memoryrouter-claude date-search --from 2026-08-10 # chronological review
|
|
189
|
+
npx memoryrouter-claude date-search --from 2026-08-01 --to 2026-08-15 --query "launches"
|
|
190
|
+
npx memoryrouter-claude date-search --from 2026-08-10 --tiers 2,3 --importance 7 # most important lately
|
|
191
|
+
npx memoryrouter-claude date-search --from 2026-08-10 --json # raw server response
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Flags: `--from` (required, ISO 8601), `--to` (default now), `--query`, `--tiers 1,2,3` (only tiers 2 and 3 carry importance ratings), `--importance N` (minimum threshold 1 to 10; raw memories are excluded whenever this is set), `--max-tokens N` (1000 to 200000), `--json`. Truncated windows print a continuation cursor. The injected recall context also carries a one-line hint teaching Claude this exact pattern, so the agent can answer "what are the most important things we've done lately?" by itself.
|
|
195
|
+
|
|
182
196
|
## Reflections (memory consolidation)
|
|
183
197
|
|
|
184
198
|
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):
|
|
@@ -200,6 +214,18 @@ How it works, and the guarantees it keeps:
|
|
|
200
214
|
|
|
201
215
|
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
216
|
|
|
217
|
+
### Automatic consolidation (default on)
|
|
218
|
+
|
|
219
|
+
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:
|
|
220
|
+
|
|
221
|
+
- Your session is never blocked and never sees the run; output goes to `~/.memoryrouter/consolidate.log`.
|
|
222
|
+
- At most 3 batches per trigger, with a fresh debt check between batches; the run stops as soon as debt drops below the threshold.
|
|
223
|
+
- 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.
|
|
224
|
+
- The threshold always comes from the server response; nothing is hardcoded locally.
|
|
225
|
+
- 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.
|
|
226
|
+
|
|
227
|
+
Opt out with `"autoConsolidate": false` in `~/.memoryrouter/config.json`. The suggestion line and manual `reflect` keep working; only the automatic background trigger is disabled.
|
|
228
|
+
|
|
203
229
|
## Historical import (agent-driven)
|
|
204
230
|
|
|
205
231
|
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.
|
package/bin/cli.js
CHANGED
|
@@ -22,6 +22,7 @@ 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');
|
|
25
26
|
const { runInstructions, runDismiss, runImportFile } = require('../lib/import');
|
|
26
27
|
|
|
27
28
|
const PKG = require('../package.json');
|
|
@@ -48,6 +49,24 @@ Usage:
|
|
|
48
49
|
Show key validity, vault stats, consolidation debt, and deterministic
|
|
49
50
|
project identity.
|
|
50
51
|
|
|
52
|
+
npx memoryrouter-claude date-search --from <ISO> [--to <ISO>] [--query <text>] [--tiers 1,2,3] [--importance N] [--max-tokens N] [--json]
|
|
53
|
+
Retrieve memories from a specific time window. Use for questions like
|
|
54
|
+
'what happened last week' or 'most important things this month or lately'.
|
|
55
|
+
For importance questions set --importance 7 or higher with --tiers 2,3,
|
|
56
|
+
since only reflections carry importance ratings. Omit --query for a
|
|
57
|
+
chronological review; include --query to rank by relevance within the
|
|
58
|
+
window. Resolve relative phrases like 'lately' to concrete ISO dates
|
|
59
|
+
before calling.
|
|
60
|
+
--from Window start, ISO 8601 date or datetime (required)
|
|
61
|
+
--to Window end, ISO 8601 date or datetime (default: now)
|
|
62
|
+
--query Optional relevance query (omit for chronological browse)
|
|
63
|
+
--tiers Comma-separated subset of 1,2,3 (only tiers 2 and 3 carry ratings)
|
|
64
|
+
--importance Minimum importance threshold, 1 to 10. Only reflections
|
|
65
|
+
(tiers 2 and 3) carry ratings, so raw memories are excluded
|
|
66
|
+
whenever this is set.
|
|
67
|
+
--max-tokens Token budget 1000 to 200000 (server default 50000)
|
|
68
|
+
--json Print the raw server response
|
|
69
|
+
|
|
51
70
|
npx memoryrouter-claude reflect [--tier 1|2] [--batches N|all] [--max-tokens N] [--dry-run]
|
|
52
71
|
Consolidate unconsolidated memories into reflections. Checks out a batch
|
|
53
72
|
under a 15 minute lease, runs YOUR local Claude Code (claude -p) with the
|
|
@@ -58,6 +77,11 @@ Usage:
|
|
|
58
77
|
--batches N number of batches to commit (default 1; "all" runs to empty)
|
|
59
78
|
--max-tokens Token budget per checkout (default 50000)
|
|
60
79
|
--dry-run checkout and print the prompt, never call the model or commit
|
|
80
|
+
Automatic mode: when the server reports consolidation debt above its
|
|
81
|
+
threshold, the hooks spawn this same loop in the background (max 3
|
|
82
|
+
batches per trigger, 30 minute cooldown, machine-wide lockfile). Opt
|
|
83
|
+
out with "autoConsolidate": false in ~/.memoryrouter/config.json.
|
|
84
|
+
Logs: ~/.memoryrouter/consolidate.log
|
|
61
85
|
|
|
62
86
|
npx memoryrouter-claude import [--instructions [--run]] [--file <path>] [--dismiss] [--yes]
|
|
63
87
|
Import historical Claude Code conversations into your vault.
|
|
@@ -110,6 +134,12 @@ function parseArgs(argv) {
|
|
|
110
134
|
else if (value === '--file') args.file = argv[++i];
|
|
111
135
|
else if (value === '--dismiss') args.dismiss = true;
|
|
112
136
|
else if (value === '--final') args.final = true;
|
|
137
|
+
else if (value === '--from') args.from = argv[++i];
|
|
138
|
+
else if (value === '--to') args.to = argv[++i];
|
|
139
|
+
else if (value === '--query') args.query = argv[++i];
|
|
140
|
+
else if (value === '--tiers') args.tiers = argv[++i];
|
|
141
|
+
else if (value === '--importance') args.importance = parseInt(argv[++i], 10);
|
|
142
|
+
else if (value === '--json') args.json = true;
|
|
113
143
|
else if (value === '--help' || value === '-h') args.help = true;
|
|
114
144
|
else if (value === '--version' || value === '-v') args.version = true;
|
|
115
145
|
else args._.push(value);
|
|
@@ -241,6 +271,64 @@ async function cmdStatus() {
|
|
|
241
271
|
`);
|
|
242
272
|
}
|
|
243
273
|
|
|
274
|
+
async function cmdDateSearch(args) {
|
|
275
|
+
// Time-window retrieval. Use for questions like 'what happened last week'
|
|
276
|
+
// or 'most important things this month or lately'. For importance questions
|
|
277
|
+
// set --importance 7 or higher with --tiers 2,3, since only reflections
|
|
278
|
+
// carry importance ratings. Omit --query for a chronological review;
|
|
279
|
+
// include --query to rank by relevance within the window. Resolve relative
|
|
280
|
+
// phrases like 'lately' to concrete ISO dates before calling.
|
|
281
|
+
const key = getApiKey();
|
|
282
|
+
if (!key) throw new Error('No Memory Key configured. Run: npx memoryrouter-claude init');
|
|
283
|
+
if (!args.from) throw new Error('--from <ISO date or datetime> is required (e.g. --from 2026-08-10)');
|
|
284
|
+
let tiers;
|
|
285
|
+
if (args.tiers !== undefined) {
|
|
286
|
+
tiers = String(args.tiers).split(',').map((value) => parseInt(value.trim(), 10));
|
|
287
|
+
if (!tiers.length || tiers.some((tier) => ![1, 2, 3].includes(tier))) {
|
|
288
|
+
throw new Error('--tiers must be a comma-separated subset of 1,2,3 (e.g. --tiers 2,3)');
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
if (args.importance !== undefined && (!Number.isInteger(args.importance) || args.importance < 1 || args.importance > 10)) {
|
|
292
|
+
throw new Error('--importance must be an integer 1 to 10');
|
|
293
|
+
}
|
|
294
|
+
if (args.maxTokens !== undefined && (!Number.isInteger(args.maxTokens) || args.maxTokens < 1000 || args.maxTokens > 200000)) {
|
|
295
|
+
throw new Error('--max-tokens must be an integer between 1000 and 200000');
|
|
296
|
+
}
|
|
297
|
+
const params = { from: args.from };
|
|
298
|
+
if (args.to !== undefined) params.to = args.to;
|
|
299
|
+
if (args.query !== undefined) params.query = args.query;
|
|
300
|
+
if (tiers !== undefined) params.tiers = tiers;
|
|
301
|
+
if (args.importance !== undefined) params.importance = args.importance;
|
|
302
|
+
if (args.maxTokens !== undefined) params.max_tokens = args.maxTokens;
|
|
303
|
+
const res = await api.dateSearch(key, params, { timeoutMs: 20000 });
|
|
304
|
+
if (!res.ok) {
|
|
305
|
+
const detail = res.data && res.data.error ? `: ${res.data.error}` : '';
|
|
306
|
+
throw new Error(`date-search failed (HTTP ${res.status})${detail}`);
|
|
307
|
+
}
|
|
308
|
+
const data = res.data || {};
|
|
309
|
+
if (args.json) {
|
|
310
|
+
console.log(JSON.stringify(data, null, 2));
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const rows = Array.isArray(data.results) ? data.results : [];
|
|
314
|
+
if (!rows.length) {
|
|
315
|
+
console.log(' No memories in that window matched the filters.');
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
const windowLine = data.window ? `${data.window.from || params.from} to ${data.window.to || 'now'}` : `${params.from} to ${params.to || 'now'}`;
|
|
319
|
+
console.log(`\n ${rows.length} memories, window ${windowLine}${data.truncated ? ' (truncated)' : ''}\n`);
|
|
320
|
+
for (const row of rows) {
|
|
321
|
+
const tierTag = row.tier != null ? ` | tier ${row.tier}` : '';
|
|
322
|
+
const importanceTag = row.importance != null ? ` | importance ${row.importance}` : '';
|
|
323
|
+
console.log(` [${row.date || 'unknown date'}${tierTag}${importanceTag}]`);
|
|
324
|
+
console.log(` ${String(row.content || '').split('\n').join('\n ')}\n`);
|
|
325
|
+
}
|
|
326
|
+
if (data.truncated) {
|
|
327
|
+
const cursor = data.next_to ? `--to ${data.next_to}` : data.next_from ? `--from ${data.next_from}` : 'a narrower window';
|
|
328
|
+
console.log(` Truncated. Continue with ${cursor}.`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
244
332
|
async function cmdReflect(args) {
|
|
245
333
|
const key = getApiKey();
|
|
246
334
|
if (!key) throw new Error('No Memory Key configured. Run: npx memoryrouter-claude init');
|
|
@@ -407,7 +495,15 @@ async function main() {
|
|
|
407
495
|
switch (cmd) {
|
|
408
496
|
case 'init': return cmdInit(args);
|
|
409
497
|
case 'status': return cmdStatus();
|
|
498
|
+
case 'date-search': return cmdDateSearch(args);
|
|
410
499
|
case 'reflect': return cmdReflect(args);
|
|
500
|
+
case 'reflect-auto': {
|
|
501
|
+
// Internal entrypoint for the detached automatic consolidation run
|
|
502
|
+
// spawned by the hooks. Silent to the user's session; logs to
|
|
503
|
+
// ~/.memoryrouter/consolidate.log. Always exits 0.
|
|
504
|
+
try { await runAutoConsolidate({ key: getApiKey() }); } catch { /* logged */ }
|
|
505
|
+
return void (process.exitCode = 0);
|
|
506
|
+
}
|
|
411
507
|
case 'import': return cmdImport(args);
|
|
412
508
|
case 'doctor': return cmdDoctor();
|
|
413
509
|
case 'off':
|
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
|
+
};
|
package/lib/hook-runner.js
CHANGED
|
@@ -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
|
|
|
@@ -94,7 +95,10 @@ function mergeContexts(results, identity, maxChars) {
|
|
|
94
95
|
const header = identity.memoryScope === 'global'
|
|
95
96
|
? 'MemoryRouter recall (personal/global scope)'
|
|
96
97
|
: `MemoryRouter recall (project scope ${identity.id})`;
|
|
97
|
-
|
|
98
|
+
// One-line teaching hint: time-window and importance questions have a
|
|
99
|
+
// dedicated retrieval path the model cannot reach through /prepare.
|
|
100
|
+
const hint = "For time-window questions like 'what happened last week' or 'most important things lately', run: npx memoryrouter-claude date-search --from <ISO> (add --tiers 2,3 --importance 7 for importance questions; only reflections carry ratings). Resolve relative phrases to concrete ISO dates first.";
|
|
101
|
+
return compactText(`${header}\n${hint}\n${sections.join('\n\n')}`, maxChars);
|
|
98
102
|
}
|
|
99
103
|
|
|
100
104
|
function reflectionNudgeLine(results) {
|
|
@@ -169,6 +173,10 @@ async function retrieveContext(input, key, prompt, eventName) {
|
|
|
169
173
|
|
|
170
174
|
const settled = await Promise.allSettled(requests);
|
|
171
175
|
const results = settled.filter((r) => r.status === 'fulfilled').map((r) => r.value);
|
|
176
|
+
// Automatic consolidation (default on, cfg.autoConsolidate: false opts out):
|
|
177
|
+
// fire-and-forget detached background run when the server says
|
|
178
|
+
// should-consolidate. Never blocks recall, never throws into the hook.
|
|
179
|
+
maybeSpawnAutoConsolidate(results, cfg);
|
|
172
180
|
let context = mergeContexts(results, identity, cfg.maxContextChars || MAX_CONTEXT_CHARS);
|
|
173
181
|
if (context && input.session_id) {
|
|
174
182
|
context = await maybeAppendNudge(input, context, results, cfg.maxContextChars || MAX_CONTEXT_CHARS);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memoryrouter-claude",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.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>",
|