memoryrouter-claude 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,36 @@
1
1
  # Changelog
2
2
 
3
- ## 2.0.0 — 2026-07-31
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
+
13
+ ## 2.1.0 (2026-08-05)
14
+
15
+ ### Fixed
16
+
17
+ - Replaced full transcript-delta ingestion with one typed `user_prompt` and one typed `assistant_final` per Claude Code turn.
18
+ - Made `/prepare` recall a separate read-only operation after local prompt-event creation.
19
+ - Added durable request-level idempotency before conversation buffering: D1 reserves and pins the event target, then the Durable Object atomically records the receipt and appends once.
20
+ - Added lost-`202` recovery. Repeated delivery returns durable `duplicate` success without a second buffer append.
21
+ - Made `last_assistant_message` authoritative and added a conservative transcript fallback that rejects partial JSON, tool-last records, and sidechains.
22
+ - Removed automatic tool, intermediate assistant, tool result/failure, compaction summary, `StopFailure`, and subagent transcript capture.
23
+
24
+ ### Compatibility and operations
25
+
26
+ - Untyped legacy `messages[]` ingest requests retain their existing behavior.
27
+ - Typed capture requires additive D1 migration `0029_capture_event_receipts.sql` before Worker deployment.
28
+ - Completed D1 receipts are retained for 90 days; local turn state remains 30 days by default.
29
+ - Added durable pending-chunk leases so background embedding/mirroring can resume after a crash without losing accepted buffer content.
30
+
31
+ ## 2.0.0 (2026-07-31)
32
+
33
+ > Superseded by 2.1.0. The transcript-delta/full-turn capture and local content-key deduplication described below were audited as semantically incorrect and are no longer used.
4
34
 
5
35
  ### Fixed
6
36
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # memoryrouter-claude
2
2
 
3
- **Deterministic, project-scoped persistent memory for Claude Code.** Automatic hooks retrieve relevant memory before every prompt, capture complete coding turns, flush before compaction, and restore memory after compaction or resume.
3
+ **Deterministic, project-scoped persistent memory for Claude Code.** Automatic hooks durably capture one user prompt and one final user-visible response per turn, retrieve relevant memory through a separate read-only request, and restore memory after compaction or resume.
4
4
 
5
5
  ```bash
6
6
  npx memoryrouter-claude init
@@ -49,33 +49,62 @@ Teams that deliberately want MemoryRouter tools loaded up front rather than defe
49
49
  | Claude Code event | Automatic action | Notes |
50
50
  |---|---|---|
51
51
  | `SessionStart` | Warm project vault | Async hook; does not block startup |
52
- | `UserPromptSubmit` | Project-scoped semantic recall | Fails open; output capped below Claude's 10K hook limit |
53
- | `Stop` | Capture the full transcript delta | Text, decisions, commands, changed files, tool outcomes; no raw thinking |
54
- | `StopFailure` | Recovery flush | Preserves completed work when the turn ends on an API failure |
55
- | `PreCompact` | Flush all accepted complete JSONL records | Cursor never advances over failed, malformed, or partial data |
56
- | `PostCompact` | Store Claude's compact summary | `PostCompact` cannot inject context by platform contract |
52
+ | `UserPromptSubmit` | Create one local typed `user_prompt`, then deliver it and run semantic recall in parallel | Capture and `/prepare` recall are separate requests; recall stays read-only |
53
+ | `Stop` | Durably accept one typed `assistant_final` | Uses `last_assistant_message`; conservative transcript fallback accepts only a complete, main-chain, text-only final record |
54
+ | `StopFailure` | Retry an unacknowledged prompt | Marks the local turn failed; never invents or stores a final response |
55
+ | `PreCompact` / `PostCompact` | Retry already-created pending events | Compaction summaries and transcript deltas are not captured |
57
56
  | `SessionStart: compact` | Re-retrieve and inject memory | Official post-compaction reinjection path |
58
57
  | `SessionStart: resume/fork` | Re-retrieve and inject memory | Restores external memory at session boundaries |
59
- | `SubagentStop` | Optional subagent capture | Off by default; enable deliberately |
60
- | `SessionEnd` | Final checkpointed flush | Session state retained for safe resume, then pruned by TTL |
58
+ | `SubagentStop` | No capture | Subagent and delegated chatter is always excluded |
59
+ | `SessionEnd` | Retry pending typed events | Does not scan or ingest the transcript |
61
60
 
62
- Claude Code writes transcripts asynchronously. At `Stop`, `last_assistant_message` is used as a deduplicated fallback if the final response is not in JSONL yet. Tool activity already present in JSONL is captured in order.
61
+ ## Deterministic capture and durable retry safety
63
62
 
64
- ## Capture correctness and crash safety
63
+ Each Claude Code turn has a crash-safe local record under `~/.memoryrouter/state/` with a stable client session ID, monotonic turn ID, and two stable idempotency keys. The client writes that record before network I/O and marks an event accepted only when the typed server contract returns `durable: true` with `status: accepted` or `duplicate`.
65
64
 
66
- Version 2 fixes the v1 data-loss bug. V1 sent only the cached prompt and final assistant message, then moved its high-water line to EOF, permanently skipping intermediate assistant messages, tool calls, and tool results.
65
+ The typed request is opt-in through `capture_event` on `POST /v1/memory/ingest`:
67
66
 
68
- V2 uses a byte cursor and a write-ahead pending batch:
67
+ ```json
68
+ {
69
+ "session_id": "ccp_project_partition",
70
+ "capture_event": {
71
+ "version": 1,
72
+ "source": "claude-code-hooks",
73
+ "event_type": "user_prompt",
74
+ "idempotency_key": "cce_stable_event_key",
75
+ "project_id": "ccp_project_partition",
76
+ "client_session_id": "claude-session-id",
77
+ "turn_id": "cct_stable_turn_id",
78
+ "occurred_at": 1785990000000,
79
+ "content": "the exact user prompt"
80
+ }
81
+ }
82
+ ```
83
+
84
+ Server acceptance is ordered for lost-response safety:
85
+
86
+ 1. D1 reserves `(memory_key, idempotency_key)` and pins the target Durable Object shard before any conversation buffer is touched.
87
+ 2. The pinned Durable Object atomically inserts its local event receipt, appends the typed content, updates the pending buffer, and persists any complete chunks to a durable embedding outbox.
88
+ 3. D1 marks the receipt buffered.
89
+ 4. Only then does the endpoint return `202` with `durable: true`.
90
+ 5. A retry after a lost response follows the pinned shard, sees the existing receipt, returns `duplicate`, and cannot append again.
91
+
92
+ The two accepted event types map server-side to `user` and `assistant`. Legacy clients that send `messages[]` without `capture_event` retain the existing fire-and-forget behavior; this release does not silently change their contract.
93
+
94
+ ### What automatic capture excludes
69
95
 
70
- 1. Read from the last **committed byte offset**.
71
- 2. Stop before malformed/partially written JSON; never leapfrog it.
72
- 3. Normalize every meaningful record into a bounded digest. Preserve decisions, commands, file paths/edits, failures, and tool outcomes; omit thinking blocks, reminders, and binary/noisy payloads.
73
- 4. Save the deterministic batch and digest ID locally **before** network I/O.
74
- 5. Send one assistant digest so the current ingest API does not discard earlier user records.
75
- 6. Advance the cursor only after MemoryRouter returns a successful acceptance response.
76
- 7. On a crash or ambiguous retry, resend the exact same digest. Server content hashing deduplicates an already-processed retry.
96
+ Automatic capture never ingests intermediate assistant text, tool calls, commands, file edits, tool results, tool failures, injected memory, thinking/signature blocks, compaction summaries, `StopFailure` error text, or subagent transcripts. For a normal `Stop`, `last_assistant_message` is authoritative. The transcript fallback refuses malformed/partial JSON, sidechains, or a tool-use record as the last assistant record. An empty or uncertain final remains locally open for a later retry rather than guessing.
77
97
 
78
- The ingest endpoint currently returns `202 Accepted` and performs durable storage in a server background task. The client can guarantee that it never marks an unaccepted batch complete; detecting a post-acceptance server background failure requires a future server acknowledgement/status API.
98
+ ### Retry, interruption, and retention behavior
99
+
100
+ - On the first 2.1 hook run, any v2.0 `pendingCapture` transcript digest is discarded rather than replayed, because it may contain tool/intermediate/subagent chatter. Only the legacy batch ID and discard reason remain locally for diagnosis.
101
+ - Repeated `UserPromptSubmit` delivery while a turn is open resumes the same prompt event. The same text submitted after a completed final creates a new turn and new idempotency keys.
102
+ - Repeated `Stop` delivery retries the same final event or becomes a no-op after acceptance.
103
+ - A lost `202` leaves the local event pending. The next applicable hook sends byte-for-byte identical typed event identity; server receipts prevent a second append.
104
+ - A different prompt arriving before the prior final marks the prior local turn interrupted and starts a new turn. Any unacknowledged event remains retryable; no synthetic final is created.
105
+ - Before a new prompt is appended, older pending prompt/final events are retried in original turn order. If an older event is still unavailable, the new prompt remains locally pending rather than reordering the server buffer.
106
+ - Local state is retained for 30 days by default. Server idempotency receipts are retained for 90 days, then bounded cleanup may remove completed receipts. Replaying an event after both retention windows is outside the retry guarantee.
107
+ - Read-only keys can recall but cannot durably accept capture. Pending local events are retained rather than falsely marked committed.
79
108
 
80
109
  ## Deterministic project isolation
81
110
 
@@ -101,7 +130,6 @@ An optional non-secret `.memoryrouter.json` at the project root can be committed
101
130
  "projectId": "acme-api",
102
131
  "memoryScope": "project",
103
132
  "includeGlobal": false,
104
- "captureSubagents": false,
105
133
  "captureEnabled": true
106
134
  }
107
135
  ```
@@ -143,13 +171,35 @@ The key is stored only at `~/.memoryrouter/config.json` with mode `0600` in a mo
143
171
  |---|---|
144
172
  | `npx memoryrouter-claude init` | Install or upgrade automatic hooks |
145
173
  | `npx memoryrouter-claude doctor` | Diagnose config, permissions, hooks, project ID, pending capture, API, and MCP |
146
- | `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 |
147
176
  | `npx memoryrouter-claude mcp install` | Add the OAuth MCP manual surface with current Claude CLI syntax |
148
177
  | `npx memoryrouter-claude mcp status` | Inspect MCP configuration |
149
178
  | `npx memoryrouter-claude mcp remove` | Remove MCP only; hooks stay installed |
150
179
  | `npx memoryrouter-claude off` | Remove MemoryRouter hooks from local/project/user settings |
151
180
  | `npx memoryrouter-claude off --purge` | Also delete private key/config/checkpoint state |
152
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
+
153
203
  ## Configuration
154
204
 
155
205
  `~/.memoryrouter/config.json` is versioned and migrated non-destructively:
@@ -161,12 +211,9 @@ The key is stored only at `~/.memoryrouter/config.json` with mode `0600` in a mo
161
211
  "memoryScope": "project",
162
212
  "includeGlobal": false,
163
213
  "captureEnabled": true,
164
- "captureSubagents": false,
165
214
  "contextLimit": 2000,
166
215
  "density": "balanced",
167
216
  "maxContextChars": 9500,
168
- "captureBatchChars": 32000,
169
- "captureMaxBatches": 8,
170
217
  "stateTtlDays": 30
171
218
  }
172
219
  ```
@@ -186,10 +233,10 @@ Read-only mode uses the canonical `:read` suffix, for example `mk_xxx:read`. The
186
233
 
187
234
  ## Local retention and failure behavior
188
235
 
189
- - Checkpoints and the latest prompt are kept at `~/.memoryrouter/state/<session>.json`, mode `0600`, for safe resume and final-message deduplication.
236
+ - Typed turn records, stable event keys, acceptance status, and the latest prompt are kept at `~/.memoryrouter/state/<session>.json`, mode `0600`, for safe retry and reinjection.
190
237
  - State files are pruned after 30 days by default.
191
- - The latest prompt cache can contain sensitive text (up to 100,000 characters). Use `.memoryrouterignore`, `enabled: false`, or `MEMORYROUTER_DISABLE=1` for sensitive projects.
192
- - Every hook exits successfully from Claude Code's perspective. Retrieval failures produce no injected context; write failures retain the pending batch and cursor for retry.
238
+ - Local typed turn records can contain prompt and final-response text (up to 100,000 characters per event). Use `.memoryrouterignore`, `enabled: false`, or `MEMORYROUTER_DISABLE=1` for sensitive projects.
239
+ - Every hook exits successfully from Claude Code's perspective. Retrieval failures produce no injected context; write failures retain pending typed events for retry.
193
240
  - Hook wall clocks are 8 seconds for retrieval and 27 seconds for capture paths, below their configured Claude Code timeouts.
194
241
 
195
242
  ## Development
package/bin/cli.js CHANGED
@@ -21,13 +21,14 @@ 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;
27
28
  const MCP_URL = 'https://mcp.memoryrouter.ai/mcp';
28
29
 
29
30
  const HELP = `
30
- ${PKG.name} v${VERSION} — deterministic memory for Claude Code
31
+ ${PKG.name} v${VERSION}: deterministic memory for Claude Code
31
32
 
32
33
  Usage:
33
34
  npx memoryrouter-claude init [--key mk_xxx] [--local|--project|--user] [--yes]
@@ -37,14 +38,25 @@ Usage:
37
38
  --user ~/.claude/settings.json (all projects)
38
39
  --global Explicitly use personal/global memory instead of project memory
39
40
  --include-global Recall project memory plus personal/global memory
40
- --capture-subagents Capture subagent transcripts (off by default)
41
41
 
42
42
  npx memoryrouter-claude doctor
43
43
  Diagnose config migration, permissions, hooks, project scope, pending capture,
44
44
  API reachability, and optional MCP configuration.
45
45
 
46
46
  npx memoryrouter-claude status
47
- 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
48
60
 
49
61
  npx memoryrouter-claude off [--local|--project|--user] [--purge]
50
62
  Remove only MemoryRouter hooks. --purge also deletes private local config/state.
@@ -74,9 +86,12 @@ function parseArgs(argv) {
74
86
  else if (value === '--local') args.scope = 'local';
75
87
  else if (value === '--global') args.global = true;
76
88
  else if (value === '--include-global') args.includeGlobal = true;
77
- else if (value === '--capture-subagents') args.captureSubagents = true;
78
89
  else if (value === '--yes' || value === '-y') args.yes = true;
79
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;
80
95
  else if (value === '--final') args.final = true;
81
96
  else if (value === '--help' || value === '-h') args.help = true;
82
97
  else if (value === '--version' || value === '-v') args.version = true;
@@ -137,7 +152,9 @@ async function cmdInit(args) {
137
152
  cfg.apiKey = key;
138
153
  if (args.global) cfg.memoryScope = 'global';
139
154
  if (args.includeGlobal) cfg.includeGlobal = true;
140
- if (args.captureSubagents) cfg.captureSubagents = true;
155
+ // Automatic subagent transcript capture was removed in v2.1: delegated and
156
+ // intermediate chatter is never part of the deterministic turn contract.
157
+ cfg.captureSubagents = false;
141
158
  cfg.lastInstalledVersion = VERSION;
142
159
  cfg.lastInstalledAt = new Date().toISOString();
143
160
  const file = settingsLib.settingsPathFor(scope, process.cwd());
@@ -152,14 +169,14 @@ async function cmdInit(args) {
152
169
  console.log(`
153
170
  Automatic engine:
154
171
  SessionStart asynchronous project-vault warmup
155
- UserPromptSubmit project-scoped semantic recall
156
- Stop crash-safe full-turn transcript capture
157
- StopFailure recovery flush after API failures
158
- PreCompact lossless flush before compaction
159
- PostCompact durable compaction-summary capture
172
+ UserPromptSubmit one durable typed prompt, then separate semantic recall
173
+ Stop one durable final user-visible assistant response
174
+ StopFailure retry pending prompt only; no synthetic final
175
+ PreCompact retry already-created pending events
176
+ PostCompact no summary capture; retry pending events only
160
177
  SessionStart re-injection after compact/resume/fork
161
- SubagentStop optional capture (disabled by default)
162
- SessionEnd final checkpointed flush
178
+ SubagentStop never captured
179
+ SessionEnd retry pending typed events
163
180
 
164
181
  ✓ Installed. Restart Claude Code or start a new session.
165
182
  Run \`npx memoryrouter-claude doctor\` to verify the complete setup.
@@ -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 {
@@ -196,8 +257,12 @@ function inspectState() {
196
257
  report.files++;
197
258
  try {
198
259
  const state = JSON.parse(fs.readFileSync(path.join(STATE_DIR, name), 'utf8'));
199
- if (state.pendingCapture) report.pending++;
200
- if (state.blockedOffset !== undefined) report.blocked++;
260
+ const turns = Array.isArray(state.turns) ? state.turns : [];
261
+ report.pending += turns.reduce((count, turn) => count
262
+ + (turn.promptEvent && turn.promptEvent.status === 'pending' ? 1 : 0)
263
+ + (turn.finalEvent && turn.finalEvent.status === 'pending' ? 1 : 0), 0);
264
+ if (turns.some((turn) => (turn.promptEvent && turn.promptEvent.status === 'conflict')
265
+ || (turn.finalEvent && turn.finalEvent.status === 'conflict'))) report.blocked++;
201
266
  } catch { report.blocked++; }
202
267
  }
203
268
  } catch { /* absent */ }
@@ -309,6 +374,7 @@ async function main() {
309
374
  switch (cmd) {
310
375
  case 'init': return cmdInit(args);
311
376
  case 'status': return cmdStatus();
377
+ case 'reflect': return cmdReflect(args);
312
378
  case 'doctor': return cmdDoctor();
313
379
  case 'off':
314
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
 
@@ -49,9 +54,74 @@ function ingest(key, messages, sessionId, opts = {}) {
49
54
  return request('POST', '/v1/memory/ingest', { key, body, timeoutMs: opts.timeoutMs || 15000 });
50
55
  }
51
56
 
57
+ function ingestEvent(key, captureEvent, sessionId, opts = {}) {
58
+ const body = { capture_event: captureEvent };
59
+ if (sessionId) body.session_id = sessionId;
60
+ if (opts.model) body.model = opts.model;
61
+ return request('POST', '/v1/memory/ingest', { key, body, timeoutMs: opts.timeoutMs || 15000 });
62
+ }
63
+
52
64
  function warmup(key, sessionId, opts = {}) {
53
65
  const headers = sessionId ? { 'X-Session-ID': sessionId } : {};
54
66
  return request('POST', '/v1/memory/warmup', { key, body: {}, headers, timeoutMs: opts.timeoutMs || 10000 });
55
67
  }
56
68
 
57
- module.exports = { request, stats, prepare, ingest, 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
+ };