memoryrouter-claude 1.0.0 → 2.0.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.
@@ -1,206 +1,429 @@
1
1
  'use strict';
2
- // Hook runtime invoked by Claude Code: `memoryrouter hook <inject|capture|flush|session-start>`
3
- // Contract: ALWAYS exit 0 (fail open). Never block the user. Errors go to stderr
4
- // only when MEMORYROUTER_DEBUG=1.
2
+ // Deterministic Claude Code hook runtime. Every path fails open to Claude Code,
3
+ // while capture checkpoints fail closed: an offset is never committed until the
4
+ // corresponding deterministic batch has been accepted by MemoryRouter.
5
5
 
6
- const { getApiKey, loadState, saveState, loadConfig } = require('./config');
6
+ const {
7
+ getApiKey,
8
+ loadState,
9
+ saveState,
10
+ loadConfig,
11
+ withStateLock,
12
+ pruneState,
13
+ } = require('./config');
7
14
  const api = require('./api');
8
- const { readTranscript } = require('./transcript');
15
+ const {
16
+ hash,
17
+ compactText,
18
+ normalizeRecord,
19
+ readTranscriptDelta,
20
+ lineIndexToOffset,
21
+ } = require('./transcript');
22
+ const { deriveProjectIdentity, sessionIdFor } = require('./project');
9
23
 
10
- const MAX_CONTEXT_CHARS = 9500; // stay under Claude Code's 10k additionalContext cap
24
+ const MAX_CONTEXT_CHARS = 9500;
25
+ const DEFAULT_CAPTURE_BATCH_CHARS = 32000;
26
+ const DEFAULT_CAPTURE_BATCHES = 8;
27
+ const RECENT_KEY_LIMIT = 1500;
11
28
 
12
29
  function debug(...args) {
13
30
  if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
14
31
  }
15
32
 
33
+ function disabled(config, identity) {
34
+ return process.env.MEMORYROUTER_DISABLE === '1'
35
+ || config.enabled === false
36
+ || Boolean(identity && identity.ignored);
37
+ }
38
+
16
39
  function readStdin(timeoutMs = 2000) {
17
40
  return new Promise((resolve) => {
18
41
  let data = '';
19
- const timer = setTimeout(() => resolve(data), timeoutMs);
20
- process.stdin.setEncoding('utf8');
21
- process.stdin.on('data', (chunk) => (data += chunk));
22
- process.stdin.on('end', () => {
23
- clearTimeout(timer);
24
- resolve(data);
25
- });
26
- process.stdin.on('error', () => {
42
+ let settled = false;
43
+ const done = () => {
44
+ if (settled) return;
45
+ settled = true;
27
46
  clearTimeout(timer);
28
47
  resolve(data);
29
- });
48
+ };
49
+ const timer = setTimeout(done, timeoutMs);
50
+ process.stdin.setEncoding('utf8');
51
+ process.stdin.on('data', (chunk) => (data += chunk));
52
+ process.stdin.on('end', done);
53
+ process.stdin.on('error', done);
30
54
  });
31
55
  }
32
56
 
33
- function emitContext(eventName, context) {
57
+ function emitContext(eventName, context, maxChars = MAX_CONTEXT_CHARS) {
34
58
  if (!context || typeof context !== 'string' || !context.trim()) return;
59
+ const cap = Math.max(1000, Math.min(MAX_CONTEXT_CHARS, Number(maxChars) || MAX_CONTEXT_CHARS));
35
60
  let text = context;
36
- if (text.length > MAX_CONTEXT_CHARS) {
37
- text = text.slice(0, MAX_CONTEXT_CHARS) + '\n[memory context truncated]';
61
+ if (text.length > cap) text = text.slice(0, cap) + '\n[memory context truncated]';
62
+ process.stdout.write(JSON.stringify({
63
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
64
+ }));
65
+ }
66
+
67
+ function stateKeyFor(input) {
68
+ const session = input.session_id || 'unknown';
69
+ return input.agent_id ? `${session}--agent-${input.agent_id}` : session;
70
+ }
71
+
72
+ function transcriptPathFor(input) {
73
+ return input.agent_transcript_path || input.transcript_path || null;
74
+ }
75
+
76
+ function scopeSession(identity) {
77
+ return sessionIdFor(identity);
78
+ }
79
+
80
+ function mergeContexts(results, identity, maxChars) {
81
+ const sections = [];
82
+ const seenLines = new Set();
83
+ for (const item of results) {
84
+ if (!item || !item.context) continue;
85
+ const unique = [];
86
+ for (const line of String(item.context).split('\n')) {
87
+ const normalized = line.trim();
88
+ if (!normalized || seenLines.has(normalized)) continue;
89
+ seenLines.add(normalized);
90
+ unique.push(line);
91
+ }
92
+ if (unique.length) sections.push(`${item.label} memory:\n${unique.join('\n')}`);
38
93
  }
39
- process.stdout.write(
40
- JSON.stringify({
41
- hookSpecificOutput: {
42
- hookEventName: eventName,
43
- additionalContext: text,
44
- },
45
- }),
46
- );
94
+ if (!sections.length) return '';
95
+ const header = identity.memoryScope === 'global'
96
+ ? 'MemoryRouter recall (personal/global scope)'
97
+ : `MemoryRouter recall (project scope ${identity.id})`;
98
+ return compactText(`${header}\n${sections.join('\n\n')}`, maxChars);
47
99
  }
48
100
 
49
- // --- handlers ---
101
+ async function retrieveContext(input, key, prompt, eventName) {
102
+ const cfg = loadConfig();
103
+ const identity = deriveProjectIdentity(input, cfg);
104
+ if (disabled(cfg, identity)) return;
105
+ const contextLimit = cfg.contextLimit;
106
+ const density = cfg.density;
107
+ const requests = [];
108
+
109
+ if (identity.memoryScope === 'global') {
110
+ requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
111
+ .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context })));
112
+ } else {
113
+ requests.push(api.prepare(key, prompt, identity.id, { timeoutMs: 5500, contextLimit, density })
114
+ .then((res) => ({ label: 'Project', context: res.ok && res.data && res.data.context })));
115
+ if (identity.includeGlobal) {
116
+ requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
117
+ .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context })));
118
+ }
119
+ }
120
+
121
+ const settled = await Promise.allSettled(requests);
122
+ const results = settled.filter((r) => r.status === 'fulfilled').map((r) => r.value);
123
+ const context = mergeContexts(results, identity, cfg.maxContextChars || MAX_CONTEXT_CHARS);
124
+ emitContext(eventName, context, cfg.maxContextChars);
125
+ }
50
126
 
51
127
  async function handleInject(input, key) {
52
128
  const prompt = input.prompt;
53
129
  if (!prompt || typeof prompt !== 'string' || !prompt.trim()) return;
54
- const sessionId = input.session_id;
130
+ const cfg = loadConfig();
131
+ const identity = deriveProjectIdentity(input, cfg);
132
+ if (disabled(cfg, identity)) return;
55
133
 
56
- // Cache the prompt so the Stop hook can pair it with the assistant reply.
57
134
  try {
58
- const state = loadState(sessionId);
135
+ const stateKey = stateKeyFor(input);
136
+ const state = loadState(stateKey);
59
137
  state.lastPrompt = prompt.slice(0, 100000);
60
138
  state.lastPromptAt = Date.now();
61
- saveState(sessionId, state);
62
- } catch (e) {
63
- debug('state cache failed:', e.message);
139
+ state.projectId = identity.id;
140
+ saveState(stateKey, state);
141
+ } catch (e) { debug('prompt cache failed:', e.message); }
142
+
143
+ await retrieveContext(input, key, prompt, 'UserPromptSubmit');
144
+ }
145
+
146
+ function eventText(ev) {
147
+ if (ev.kind === 'tool_use' || ev.kind === 'tool_result') return ev.content;
148
+ return `${ev.role === 'user' ? 'User' : 'Assistant'}: ${ev.content}`;
149
+ }
150
+
151
+ function buildDigest(events, input, identity) {
152
+ const keys = events.map((ev) => ev.eventKey || ev.contentKey);
153
+ const batchId = hash(`${identity.id}\n${keys.join('\n')}`).slice(0, 24);
154
+ const agent = input.agent_id ? `\nSubagent: ${input.agent_type || 'unknown'} (${input.agent_id})` : '';
155
+ const body = events.map(eventText).join('\n\n');
156
+ return {
157
+ batchId,
158
+ digest: `[Claude Code memory batch ${batchId}]\nProject: ${identity.id}\nThread: ${input.session_id || 'unknown'}${agent}\n\n${body}`,
159
+ eventKeys: keys,
160
+ };
161
+ }
162
+
163
+ function selectBatch(records, seenKeys, startOffset, maxChars) {
164
+ const events = [];
165
+ let endOffset = startOffset;
166
+ let estimated = 0;
167
+ for (const record of records) {
168
+ const unseen = record.events.filter((ev) => !seenKeys.has(ev.eventKey || ev.contentKey));
169
+ const size = unseen.reduce((sum, ev) => sum + ev.content.length + 64, 0);
170
+ if (events.length && estimated + size > maxChars) break;
171
+ events.push(...unseen);
172
+ estimated += size;
173
+ endOffset = record.endOffset;
174
+ if (estimated >= maxChars) break;
64
175
  }
176
+ return { events, endOffset };
177
+ }
65
178
 
66
- const cfg = loadConfig();
67
- const res = await api.prepare(key, prompt, sessionId, {
68
- timeoutMs: 6000,
69
- contextLimit: cfg.contextLimit,
70
- density: cfg.density,
179
+ function addRecentKeys(state, keys) {
180
+ const merged = [...(Array.isArray(state.recentEventKeys) ? state.recentEventKeys : []), ...keys];
181
+ state.recentEventKeys = [...new Set(merged)].slice(-RECENT_KEY_LIMIT);
182
+ }
183
+
184
+ function consumeFallbackDuplicates(records, state, seenKeys) {
185
+ const pending = Array.isArray(state.pendingFallbackContentKeys)
186
+ ? [...state.pendingFallbackContentKeys]
187
+ : [];
188
+ if (!pending.length) return false;
189
+ let changed = false;
190
+ for (const record of records) {
191
+ for (const ev of record.events) {
192
+ const index = pending.indexOf(ev.contentKey);
193
+ if (index === -1) continue;
194
+ seenKeys.add(ev.eventKey || ev.contentKey);
195
+ pending.splice(index, 1);
196
+ changed = true;
197
+ }
198
+ }
199
+ if (changed) state.pendingFallbackContentKeys = pending;
200
+ return changed;
201
+ }
202
+
203
+ async function sendPending(key, stateKey, state) {
204
+ const pending = state.pendingCapture;
205
+ if (!pending) return true;
206
+ const res = await api.ingest(key, [{ role: 'assistant', content: pending.digest }], pending.scopeSessionId, {
207
+ timeoutMs: 10000,
208
+ model: 'claude-code-hook',
71
209
  });
72
- if (!res.ok || !res.data) {
73
- debug('prepare failed:', res.status);
210
+ if (!res.ok) {
211
+ debug('capture not accepted:', res.status, pending.batchId);
212
+ return false;
213
+ }
214
+ state.transcriptOffset = pending.endOffset;
215
+ state.transcriptPathHash = pending.transcriptPathHash;
216
+ addRecentKeys(state, pending.eventKeys || []);
217
+ if (pending.fallbackContentKeys && pending.fallbackContentKeys.length) {
218
+ state.pendingFallbackContentKeys = [
219
+ ...(Array.isArray(state.pendingFallbackContentKeys) ? state.pendingFallbackContentKeys : []),
220
+ ...pending.fallbackContentKeys,
221
+ ].slice(-100);
222
+ }
223
+ state.lastCaptureAt = Date.now();
224
+ state.lastAcceptedBatch = pending.batchId;
225
+ delete state.pendingCapture;
226
+ saveState(stateKey, state);
227
+ return true;
228
+ }
229
+
230
+ function fallbackAssistantEvent(input) {
231
+ const text = input.last_assistant_message;
232
+ if (!text || typeof text !== 'string' || !text.trim()) return null;
233
+ const fake = { message: { role: 'assistant', content: [{ type: 'text', text }] } };
234
+ const normalized = normalizeRecord(fake)[0] || null;
235
+ return normalized ? { ...normalized, fallback: true } : null;
236
+ }
237
+
238
+ async function captureTranscript(input, key, options = {}) {
239
+ const cfg = loadConfig();
240
+ const identity = deriveProjectIdentity(input, cfg);
241
+ const captureEnabled = identity.projectConfig.captureEnabled ?? cfg.captureEnabled;
242
+ const captureSubagents = identity.projectConfig.captureSubagents ?? cfg.captureSubagents;
243
+ if (disabled(cfg, identity) || captureEnabled === false) return;
244
+ if (input.agent_id && captureSubagents !== true && !options.forceSubagent) {
245
+ debug('subagent capture disabled');
74
246
  return;
75
247
  }
76
- emitContext('UserPromptSubmit', res.data.context);
248
+ const transcriptPath = transcriptPathFor(input);
249
+ if (!transcriptPath && !input.last_assistant_message) return;
250
+ const stateKey = stateKeyFor(input);
251
+ const maxChars = Math.max(4000, Number(cfg.captureBatchChars) || DEFAULT_CAPTURE_BATCH_CHARS);
252
+ const maxBatches = Math.max(1, Math.min(20, Number(cfg.captureMaxBatches) || DEFAULT_CAPTURE_BATCHES));
253
+
254
+ await withStateLock(stateKey, async (state) => {
255
+ if (!(await sendPending(key, stateKey, state))) return;
256
+
257
+ const pathHash = transcriptPath ? hash(transcriptPath).slice(0, 24) : null;
258
+ if (state.transcriptPathHash && pathHash && state.transcriptPathHash !== pathHash) {
259
+ state.transcriptOffset = 0;
260
+ delete state.highWaterLine;
261
+ }
262
+ if (!Number.isInteger(state.transcriptOffset)) {
263
+ state.transcriptOffset = transcriptPath && Number.isInteger(state.highWaterLine)
264
+ ? lineIndexToOffset(transcriptPath, state.highWaterLine)
265
+ : 0;
266
+ delete state.highWaterLine;
267
+ }
268
+
269
+ let batches = 0;
270
+ while (batches < maxBatches) {
271
+ const seen = new Set(Array.isArray(state.recentEventKeys) ? state.recentEventKeys : []);
272
+ const delta = transcriptPath
273
+ ? readTranscriptDelta(transcriptPath, state.transcriptOffset)
274
+ : { records: [], nextOffset: state.transcriptOffset, blockedOffset: null, reset: false };
275
+ if (delta.reset) state.transcriptOffset = 0;
276
+ if (delta.blockedOffset === null && state.blockedOffset !== undefined && delta.nextOffset >= state.blockedOffset) {
277
+ delete state.blockedOffset;
278
+ delete state.blockedAt;
279
+ }
280
+ consumeFallbackDuplicates(delta.records, state, seen);
281
+
282
+ const chosen = selectBatch(delta.records, seen, state.transcriptOffset, maxChars);
283
+ let events = chosen.events;
284
+ let endOffset = chosen.endOffset;
285
+
286
+ // Stop transcripts can lag the final assistant message. Capture that text
287
+ // now without advancing past unread bytes; its content key deduplicates it
288
+ // when the transcript catches up on the next hook.
289
+ if (!events.length) {
290
+ const fallback = fallbackAssistantEvent(input);
291
+ if (fallback && !seen.has(fallback.contentKey)) events = [fallback];
292
+ }
293
+
294
+ if (!events.length) {
295
+ if (endOffset > state.transcriptOffset) {
296
+ state.transcriptOffset = endOffset;
297
+ state.transcriptPathHash = pathHash;
298
+ state.lastCaptureAt = Date.now();
299
+ saveState(stateKey, state);
300
+ }
301
+ if (delta.blockedOffset !== null) {
302
+ state.blockedOffset = delta.blockedOffset;
303
+ state.blockedAt = Date.now();
304
+ saveState(stateKey, state);
305
+ debug('transcript blocked at malformed/partial byte:', delta.blockedOffset);
306
+ }
307
+ break;
308
+ }
309
+
310
+ const batchStartOffset = state.transcriptOffset;
311
+ const built = buildDigest(events, input, identity);
312
+ state.pendingCapture = {
313
+ batchId: built.batchId,
314
+ digest: built.digest,
315
+ eventKeys: built.eventKeys,
316
+ fallbackContentKeys: events.filter((ev) => ev.fallback).map((ev) => ev.contentKey),
317
+ startOffset: state.transcriptOffset,
318
+ endOffset,
319
+ transcriptPathHash: pathHash,
320
+ scopeSessionId: scopeSession(identity),
321
+ createdAt: Date.now(),
322
+ };
323
+ saveState(stateKey, state); // write-ahead record before network I/O
324
+ if (!(await sendPending(key, stateKey, state))) return;
325
+ batches++;
326
+
327
+ // A fallback final message has no transcript bytes to checkpoint. Stop
328
+ // after accepting it; a later hook will process newly flushed JSONL.
329
+ if (endOffset <= batchStartOffset) break;
330
+ }
331
+ }, { timeoutMs: 2000 });
77
332
  }
78
333
 
79
334
  async function handleCapture(input, key) {
80
- // Loop guard: when Claude continues due to a stop hook, don't re-ingest.
81
335
  if (input.stop_hook_active) {
82
336
  debug('stop_hook_active — skipping capture');
83
337
  return;
84
338
  }
85
- const sessionId = input.session_id;
86
- const assistant = input.last_assistant_message;
87
- if (!assistant || typeof assistant !== 'string' || !assistant.trim()) {
88
- debug('no last_assistant_message — skipping');
89
- return;
90
- }
339
+ await captureTranscript(input, key);
340
+ }
91
341
 
92
- const messages = [];
93
- let state = {};
94
- try {
95
- state = loadState(sessionId);
96
- } catch {
97
- /* ignore */
98
- }
99
- if (state.lastPrompt) {
100
- messages.push({ role: 'user', content: state.lastPrompt });
101
- }
102
- messages.push({ role: 'assistant', content: assistant });
342
+ async function handleFlush(input, key) {
343
+ await captureTranscript(input, key, { flush: true });
344
+ }
103
345
 
104
- const res = await api.ingest(key, messages, sessionId, { timeoutMs: 10000 });
105
- debug('ingest status:', res.status);
346
+ async function handleSubagentCapture(input, key) {
347
+ if (input.stop_hook_active) return;
348
+ await captureTranscript(input, key);
349
+ }
106
350
 
107
- // Advance the transcript high-water mark so PreCompact/SessionEnd flushes
108
- // don't re-send what per-turn capture already stored.
109
- try {
110
- if (input.transcript_path) {
111
- const { lastLine } = readTranscript(input.transcript_path, -1);
112
- state.highWaterLine = lastLine;
113
- }
114
- delete state.lastPrompt;
115
- state.lastCaptureAt = Date.now();
116
- saveState(sessionId, state);
117
- } catch (e) {
118
- debug('state update failed:', e.message);
119
- }
351
+ async function handleCompact(input, key) {
352
+ await captureTranscript(input, key, { flush: true });
353
+ const summary = input.compact_summary;
354
+ if (!summary || typeof summary !== 'string' || !summary.trim()) return;
355
+ const cfg = loadConfig();
356
+ const identity = deriveProjectIdentity(input, cfg);
357
+ const captureEnabled = identity.projectConfig.captureEnabled ?? cfg.captureEnabled;
358
+ if (disabled(cfg, identity) || captureEnabled === false) return;
359
+ const stateKey = stateKeyFor(input);
360
+ const syntheticKey = hash(`compact\n${summary}`).slice(0, 32);
361
+ await withStateLock(stateKey, async (state) => {
362
+ if ((state.syntheticKeys || []).includes(syntheticKey)) return;
363
+ const content = `[Claude Code compaction summary]\nProject: ${identity.id}\nThread: ${input.session_id || 'unknown'}\n\n${compactText(summary, 30000)}`;
364
+ const res = await api.ingest(key, [{ role: 'assistant', content }], scopeSession(identity), {
365
+ timeoutMs: 10000,
366
+ model: 'claude-code-compaction',
367
+ });
368
+ if (!res.ok) return;
369
+ state.syntheticKeys = [...(state.syntheticKeys || []), syntheticKey].slice(-100);
370
+ state.lastCompactAt = Date.now();
371
+ saveState(stateKey, state);
372
+ });
120
373
  }
121
374
 
122
- async function handleFlush(input, key) {
123
- const sessionId = input.session_id;
124
- if (!input.transcript_path) return;
125
- let state = {};
126
- try {
127
- state = loadState(sessionId);
128
- } catch {
129
- /* ignore */
130
- }
131
- const after = Number.isInteger(state.highWaterLine) ? state.highWaterLine : -1;
132
- const { messages, lastLine } = readTranscript(input.transcript_path, after);
133
- if (messages.length === 0) {
134
- debug('flush: nothing new to ingest');
135
- return;
136
- }
137
- // Cap batch size defensively (server chunks in background anyway)
138
- const batch = messages.slice(-200);
139
- const res = await api.ingest(key, batch, sessionId, { timeoutMs: 20000 });
140
- debug('flush ingest status:', res.status, 'messages:', batch.length);
141
- try {
142
- state.highWaterLine = lastLine;
143
- state.lastFlushAt = Date.now();
144
- saveState(sessionId, state);
145
- } catch (e) {
146
- debug('state update failed:', e.message);
147
- }
375
+ async function handleReinject(input, key) {
376
+ const state = loadState(stateKeyFor(input));
377
+ const prompt = state.lastPrompt
378
+ || 'Recall the most relevant recent project decisions, changed files, commands, failures, and unresolved work.';
379
+ await retrieveContext(input, key, prompt, 'SessionStart');
148
380
  }
149
381
 
150
382
  async function handleSessionStart(input, key) {
151
- // Fire-and-forget warmup so the first search/prepare is fast.
383
+ const cfg = loadConfig();
384
+ const identity = deriveProjectIdentity(input, cfg);
385
+ if (disabled(cfg, identity)) return;
386
+ pruneState(cfg.stateTtlDays);
152
387
  try {
153
- await api.warmup(key, { timeoutMs: 8000 });
154
- } catch (e) {
155
- debug('warmup failed:', e.message);
156
- }
388
+ const stateKey = stateKeyFor(input);
389
+ const state = loadState(stateKey);
390
+ state.projectId = identity.id;
391
+ state.sessionSource = input.source || 'unknown';
392
+ state.sessionStartedAt = Date.now();
393
+ saveState(stateKey, state);
394
+ } catch (e) { debug('session state failed:', e.message); }
395
+ try {
396
+ await api.warmup(key, scopeSession(identity), { timeoutMs: 8000 });
397
+ } catch (e) { debug('warmup failed:', e.message); }
157
398
  }
158
399
 
159
- // --- entry ---
160
-
161
400
  async function runHook(kind) {
162
- // Absolute wall-clock kill switch: never hang past our settings timeout.
163
401
  const wallClock = setTimeout(() => {
164
402
  debug('wall-clock timeout — exiting 0');
165
403
  process.exit(0);
166
- }, kind === 'inject' ? 8000 : 25000);
404
+ }, kind === 'inject' || kind === 'reinject' ? 8000 : 27000);
167
405
  wallClock.unref();
168
406
 
169
407
  try {
170
408
  const key = getApiKey();
171
- if (!key) {
172
- debug('no API key configured — run `npx memoryrouter-claude init`');
173
- return;
174
- }
409
+ if (!key) return;
175
410
  const raw = await readStdin();
176
411
  let input = {};
177
- try {
178
- input = JSON.parse(raw || '{}');
179
- } catch {
180
- debug('bad stdin JSON');
181
- return;
182
- }
412
+ try { input = JSON.parse(raw || '{}'); } catch { return; }
183
413
 
184
414
  switch (kind) {
185
- case 'inject':
186
- await handleInject(input, key);
187
- break;
188
- case 'capture':
189
- await handleCapture(input, key);
190
- break;
191
- case 'flush':
192
- await handleFlush(input, key);
193
- break;
194
- case 'session-start':
195
- await handleSessionStart(input, key);
196
- break;
197
- default:
198
- debug('unknown hook kind:', kind);
415
+ case 'inject': await handleInject(input, key); break;
416
+ case 'capture': await handleCapture(input, key); break;
417
+ case 'capture-subagent': await handleSubagentCapture(input, key); break;
418
+ case 'flush': await handleFlush(input, key); break;
419
+ case 'compact': await handleCompact(input, key); break;
420
+ case 'reinject': await handleReinject(input, key); break;
421
+ case 'session-start': await handleSessionStart(input, key); break;
422
+ default: debug('unknown hook kind:', kind);
199
423
  }
200
424
  } catch (err) {
201
425
  debug('hook error:', err && err.message);
202
426
  }
203
- // Always success — fail open.
204
427
  process.exitCode = 0;
205
428
  }
206
429
 
@@ -209,7 +432,15 @@ module.exports = {
209
432
  handleInject,
210
433
  handleCapture,
211
434
  handleFlush,
435
+ handleSubagentCapture,
436
+ handleCompact,
437
+ handleReinject,
212
438
  handleSessionStart,
439
+ captureTranscript,
440
+ buildDigest,
441
+ selectBatch,
442
+ mergeContexts,
213
443
  emitContext,
444
+ stateKeyFor,
214
445
  MAX_CONTEXT_CHARS,
215
446
  };