memoryrouter-claude 1.0.1 → 2.1.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,516 @@
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. Automatic capture is deliberately
3
+ // narrow: one typed user_prompt plus one typed assistant_final per local turn.
4
+ // Recall is a separate read-only /prepare request. Tool, intermediate,
5
+ // compaction-summary, and subagent transcript content is never ingested.
5
6
 
6
- const { getApiKey, loadState, saveState, loadConfig } = require('./config');
7
+ const fs = require('fs');
8
+ const {
9
+ getApiKey,
10
+ loadState,
11
+ saveState,
12
+ loadConfig,
13
+ withStateLock,
14
+ pruneState,
15
+ } = require('./config');
7
16
  const api = require('./api');
8
- const { readTranscript } = require('./transcript');
17
+ const { hash, compactText, cleanText, finalAssistantFromTranscript } = require('./transcript');
18
+ const { deriveProjectIdentity, sessionIdFor } = require('./project');
9
19
 
10
- const MAX_CONTEXT_CHARS = 9500; // stay under Claude Code's 10k additionalContext cap
20
+ const MAX_CONTEXT_CHARS = 9500;
21
+ const MAX_EVENT_CHARS = 100000;
22
+ const RECENT_TURN_LIMIT = 50;
11
23
 
12
24
  function debug(...args) {
13
25
  if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
14
26
  }
15
27
 
28
+ function disabled(config, identity) {
29
+ return process.env.MEMORYROUTER_DISABLE === '1'
30
+ || config.enabled === false
31
+ || Boolean(identity && identity.ignored);
32
+ }
33
+
16
34
  function readStdin(timeoutMs = 2000) {
17
35
  return new Promise((resolve) => {
18
36
  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', () => {
37
+ let settled = false;
38
+ const done = () => {
39
+ if (settled) return;
40
+ settled = true;
27
41
  clearTimeout(timer);
28
42
  resolve(data);
29
- });
43
+ };
44
+ const timer = setTimeout(done, timeoutMs);
45
+ process.stdin.setEncoding('utf8');
46
+ process.stdin.on('data', (chunk) => (data += chunk));
47
+ process.stdin.on('end', done);
48
+ process.stdin.on('error', done);
30
49
  });
31
50
  }
32
51
 
33
- function emitContext(eventName, context) {
52
+ function emitContext(eventName, context, maxChars = MAX_CONTEXT_CHARS) {
34
53
  if (!context || typeof context !== 'string' || !context.trim()) return;
54
+ const cap = Math.max(1000, Math.min(MAX_CONTEXT_CHARS, Number(maxChars) || MAX_CONTEXT_CHARS));
35
55
  let text = context;
36
- if (text.length > MAX_CONTEXT_CHARS) {
37
- text = text.slice(0, MAX_CONTEXT_CHARS) + '\n[memory context truncated]';
38
- }
39
- process.stdout.write(
40
- JSON.stringify({
41
- hookSpecificOutput: {
42
- hookEventName: eventName,
43
- additionalContext: text,
44
- },
45
- }),
46
- );
56
+ if (text.length > cap) text = text.slice(0, cap) + '\n[memory context truncated]';
57
+ process.stdout.write(JSON.stringify({
58
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
59
+ }));
47
60
  }
48
61
 
49
- // --- handlers ---
62
+ function stateKeyFor(input) {
63
+ return input.session_id || 'unknown';
64
+ }
50
65
 
51
- async function handleInject(input, key) {
52
- const prompt = input.prompt;
53
- if (!prompt || typeof prompt !== 'string' || !prompt.trim()) return;
54
- const sessionId = input.session_id;
66
+ function transcriptPathFor(input) {
67
+ return input.transcript_path || null;
68
+ }
55
69
 
56
- // Cache the prompt so the Stop hook can pair it with the assistant reply.
57
- try {
58
- const state = loadState(sessionId);
59
- state.lastPrompt = prompt.slice(0, 100000);
60
- state.lastPromptAt = Date.now();
61
- saveState(sessionId, state);
62
- } catch (e) {
63
- debug('state cache failed:', e.message);
70
+ function transcriptSize(transcriptPath) {
71
+ if (!transcriptPath) return null;
72
+ try { return fs.statSync(transcriptPath).size; } catch { return null; }
73
+ }
74
+
75
+ function scopeSession(identity) {
76
+ return sessionIdFor(identity);
77
+ }
78
+
79
+ function mergeContexts(results, identity, maxChars) {
80
+ const sections = [];
81
+ const seenLines = new Set();
82
+ for (const item of results) {
83
+ if (!item || !item.context) continue;
84
+ const unique = [];
85
+ for (const line of String(item.context).split('\n')) {
86
+ const normalized = line.trim();
87
+ if (!normalized || seenLines.has(normalized)) continue;
88
+ seenLines.add(normalized);
89
+ unique.push(line);
90
+ }
91
+ if (unique.length) sections.push(`${item.label} memory:\n${unique.join('\n')}`);
64
92
  }
93
+ if (!sections.length) return '';
94
+ const header = identity.memoryScope === 'global'
95
+ ? 'MemoryRouter recall (personal/global scope)'
96
+ : `MemoryRouter recall (project scope ${identity.id})`;
97
+ return compactText(`${header}\n${sections.join('\n\n')}`, maxChars);
98
+ }
65
99
 
100
+ async function retrieveContext(input, key, prompt, eventName) {
66
101
  const cfg = loadConfig();
67
- const res = await api.prepare(key, prompt, sessionId, {
68
- timeoutMs: 6000,
69
- contextLimit: cfg.contextLimit,
70
- density: cfg.density,
71
- });
72
- if (!res.ok || !res.data) {
73
- debug('prepare failed:', res.status);
74
- return;
102
+ const identity = deriveProjectIdentity(input, cfg);
103
+ if (disabled(cfg, identity)) return;
104
+ const contextLimit = cfg.contextLimit;
105
+ const density = cfg.density;
106
+ const requests = [];
107
+
108
+ if (identity.memoryScope === 'global') {
109
+ requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
110
+ .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context })));
111
+ } else {
112
+ requests.push(api.prepare(key, prompt, identity.id, { timeoutMs: 5500, contextLimit, density })
113
+ .then((res) => ({ label: 'Project', context: res.ok && res.data && res.data.context })));
114
+ if (identity.includeGlobal) {
115
+ requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
116
+ .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context })));
117
+ }
75
118
  }
76
- emitContext('UserPromptSubmit', res.data.context);
119
+
120
+ const settled = await Promise.allSettled(requests);
121
+ const results = settled.filter((r) => r.status === 'fulfilled').map((r) => r.value);
122
+ const context = mergeContexts(results, identity, cfg.maxContextChars || MAX_CONTEXT_CHARS);
123
+ emitContext(eventName, context, cfg.maxContextChars);
77
124
  }
78
125
 
79
- async function handleCapture(input, key) {
80
- // Loop guard: when Claude continues due to a stop hook, don't re-ingest.
81
- if (input.stop_hook_active) {
82
- debug('stop_hook_active — skipping capture');
83
- return;
126
+ function normalizeEventContent(value) {
127
+ return compactText(cleanText(value), MAX_EVENT_CHARS);
128
+ }
129
+
130
+ function turnIdFor(sessionId, sequence) {
131
+ return `cct_${hash(`claude-code-turn\n${sessionId}\n${sequence}`).slice(0, 40)}`;
132
+ }
133
+
134
+ function idempotencyKeyFor(projectId, sessionId, turnId, eventType) {
135
+ return `cce_${hash(`claude-code-capture-v1\n${projectId}\n${sessionId}\n${turnId}\n${eventType}`)}`;
136
+ }
137
+
138
+ function ensureTurns(state) {
139
+ // v2.0 pending transcript digests are intentionally not replayed: their
140
+ // payload may contain tool/intermediate/subagent chatter. Record only that a
141
+ // legacy batch was discarded, remove its content, and start typed turns clean.
142
+ if (state.pendingCapture) {
143
+ state.legacyCaptureDiscarded = {
144
+ batchId: state.pendingCapture.batchId || null,
145
+ discardedAt: Date.now(),
146
+ reason: 'superseded-by-typed-capture-v1',
147
+ };
148
+ delete state.pendingCapture;
149
+ delete state.transcriptOffset;
150
+ delete state.transcriptPathHash;
151
+ delete state.blockedOffset;
152
+ delete state.blockedAt;
153
+ delete state.recentEventKeys;
154
+ delete state.pendingFallbackContentKeys;
84
155
  }
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;
156
+ if (!Array.isArray(state.turns)) state.turns = [];
157
+ if (!Number.isInteger(state.nextTurnSequence) || state.nextTurnSequence < 1) {
158
+ state.nextTurnSequence = state.turns.reduce((max, turn) => Math.max(max, Number(turn.sequence) || 0), 0) + 1;
90
159
  }
160
+ return state.turns;
161
+ }
91
162
 
92
- const messages = [];
93
- let state = {};
94
- try {
95
- state = loadState(sessionId);
96
- } catch {
97
- /* ignore */
163
+ function newTurn(state, input, identity, prompt) {
164
+ const turns = ensureTurns(state);
165
+ const sequence = state.nextTurnSequence++;
166
+ const sessionId = String(input.session_id);
167
+ const turnId = turnIdFor(sessionId, sequence);
168
+ const now = Date.now();
169
+ const transcriptPath = transcriptPathFor(input);
170
+ const turn = {
171
+ version: 1,
172
+ sequence,
173
+ turnId,
174
+ projectId: identity.id,
175
+ clientSessionId: sessionId,
176
+ scopeSessionId: scopeSession(identity),
177
+ prompt,
178
+ promptHash: hash(prompt),
179
+ status: 'open',
180
+ createdAt: now,
181
+ transcriptPath,
182
+ transcriptOffsetAtPrompt: transcriptSize(transcriptPath),
183
+ promptEvent: {
184
+ eventType: 'user_prompt',
185
+ idempotencyKey: idempotencyKeyFor(identity.id, sessionId, turnId, 'user_prompt'),
186
+ content: prompt,
187
+ status: 'pending',
188
+ createdAt: now,
189
+ },
190
+ };
191
+ const priorOpen = [...turns].reverse().find((item) => item.status === 'open');
192
+ if (priorOpen) {
193
+ priorOpen.status = 'interrupted';
194
+ priorOpen.interruptedAt = now;
98
195
  }
99
- if (state.lastPrompt) {
100
- messages.push({ role: 'user', content: state.lastPrompt });
196
+ turns.push(turn);
197
+ const retained = new Map();
198
+ for (const item of turns.slice(-RECENT_TURN_LIMIT)) retained.set(item.turnId, item);
199
+ for (const item of turns) {
200
+ const hasPending = (item.promptEvent && item.promptEvent.status === 'pending')
201
+ || (item.finalEvent && item.finalEvent.status === 'pending');
202
+ if (hasPending) retained.set(item.turnId, item);
101
203
  }
102
- messages.push({ role: 'assistant', content: assistant });
204
+ state.turns = Array.from(retained.values()).sort((a, b) => a.sequence - b.sequence);
205
+ state.activeTurnId = turn.turnId;
206
+ return turn;
207
+ }
103
208
 
104
- const res = await api.ingest(key, messages, sessionId, { timeoutMs: 10000 });
105
- debug('ingest status:', res.status);
209
+ function findTurn(state, turnId) {
210
+ return ensureTurns(state).find((turn) => turn.turnId === turnId) || null;
211
+ }
212
+
213
+ function activeTurn(state) {
214
+ const explicit = state.activeTurnId && findTurn(state, state.activeTurnId);
215
+ if (explicit && explicit.status === 'open') return explicit;
216
+ return [...ensureTurns(state)].reverse().find((turn) => turn.status === 'open') || null;
217
+ }
106
218
 
107
- // Advance the transcript high-water mark so PreCompact/SessionEnd flushes
108
- // don't re-send what per-turn capture already stored.
219
+ function createOrResumePromptTurn(state, input, identity, prompt) {
220
+ const current = activeTurn(state);
221
+ if (current && current.promptHash === hash(prompt)) return current;
222
+ return newTurn(state, input, identity, prompt);
223
+ }
224
+
225
+ function captureEventPayload(turn, event) {
226
+ return {
227
+ version: 1,
228
+ source: 'claude-code-hooks',
229
+ event_type: event.eventType,
230
+ idempotency_key: event.idempotencyKey,
231
+ project_id: turn.projectId,
232
+ client_session_id: turn.clientSessionId,
233
+ turn_id: turn.turnId,
234
+ occurred_at: event.createdAt,
235
+ content: event.content,
236
+ };
237
+ }
238
+
239
+ function durablyAccepted(res) {
240
+ return Boolean(
241
+ res && res.ok && res.data && res.data.durable === true
242
+ && (res.data.status === 'accepted' || res.data.status === 'duplicate'),
243
+ );
244
+ }
245
+
246
+ async function sendTurnEvent(key, stateKey, state, turn, field, timeoutMs = 10000) {
247
+ const event = turn && turn[field];
248
+ if (!event || event.status === 'accepted' || event.status === 'conflict') return event && event.status === 'accepted';
249
+ let res;
109
250
  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);
251
+ res = await api.ingestEvent(key, captureEventPayload(turn, event), turn.scopeSessionId, {
252
+ timeoutMs,
253
+ model: 'claude-code-hook',
254
+ });
255
+ } catch (error) {
256
+ event.lastError = error && error.message ? error.message : 'network error';
257
+ event.lastAttemptAt = Date.now();
258
+ saveState(stateKey, state);
259
+ debug('capture event delivery failed:', event.eventType, event.lastError);
260
+ return false;
261
+ }
262
+ event.lastAttemptAt = Date.now();
263
+ event.attempts = (Number(event.attempts) || 0) + 1;
264
+ if (durablyAccepted(res)) {
265
+ event.status = 'accepted';
266
+ event.acceptedAt = Date.now();
267
+ event.serverStatus = res.data.status;
268
+ delete event.lastError;
269
+ } else if (res.status === 409) {
270
+ event.status = 'conflict';
271
+ event.lastError = 'server rejected idempotency key reuse with different event data';
272
+ } else {
273
+ event.lastError = (res.data && (res.data.error || res.data.reason)) || `HTTP ${res.status}`;
119
274
  }
275
+ saveState(stateKey, state);
276
+ return event.status === 'accepted';
120
277
  }
121
278
 
122
- async function handleFlush(input, key) {
123
- const sessionId = input.session_id;
124
- if (!input.transcript_path) return;
125
- let state = {};
279
+ async function handleInject(input, key) {
280
+ const prompt = normalizeEventContent(input.prompt);
281
+ if (!prompt || !input.session_id) return;
282
+ const cfg = loadConfig();
283
+ const identity = deriveProjectIdentity(input, cfg);
284
+ if (disabled(cfg, identity)) return;
285
+
286
+ let turnId = null;
126
287
  try {
127
- state = loadState(sessionId);
128
- } catch {
129
- /* ignore */
288
+ turnId = await withStateLock(stateKeyFor(input), async (state) => {
289
+ const stateKey = stateKeyFor(input);
290
+ const turn = createOrResumePromptTurn(state, input, identity, prompt);
291
+ state.lastPrompt = prompt;
292
+ state.lastPromptAt = Date.now();
293
+ state.projectId = identity.id;
294
+ saveState(stateKey, state); // durable local turn before network I/O
295
+ return turn.turnId;
296
+ }, { timeoutMs: 2500 });
297
+ } catch (error) {
298
+ debug('prompt event state failed:', error.message);
130
299
  }
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');
300
+
301
+ const delivery = turnId ? withStateLock(stateKeyFor(input), async (state) => {
302
+ const turns = ensureTurns(state);
303
+ const turn = findTurn(state, turnId);
304
+ if (!turn) return;
305
+ // Preserve turn order after an offline/lost-response window. Older pending
306
+ // events are retried before the new prompt can append to the server buffer.
307
+ for (const prior of turns) {
308
+ if (prior.turnId === turn.turnId) break;
309
+ if (prior.promptEvent && prior.promptEvent.status === 'pending') {
310
+ const accepted = await sendTurnEvent(key, stateKeyFor(input), state, prior, 'promptEvent', 2000);
311
+ if (!accepted) return;
312
+ }
313
+ if (prior.finalEvent && prior.finalEvent.status === 'pending') {
314
+ if (!prior.promptEvent || prior.promptEvent.status !== 'accepted') return;
315
+ const accepted = await sendTurnEvent(key, stateKeyFor(input), state, prior, 'finalEvent', 2000);
316
+ if (!accepted) return;
317
+ }
318
+ }
319
+ await sendTurnEvent(key, stateKeyFor(input), state, turn, 'promptEvent', 6000);
320
+ }, { timeoutMs: 2500 }).catch((error) => debug('prompt event delivery failed open:', error.message)) : Promise.resolve();
321
+
322
+ // Recall is intentionally a separate, read-only operation. It runs in
323
+ // parallel with durable event delivery so adding capture does not serialize
324
+ // two network round trips on Claude Code's latency-critical prompt hook.
325
+ await Promise.allSettled([
326
+ delivery,
327
+ retrieveContext(input, key, prompt, 'UserPromptSubmit'),
328
+ ]);
329
+ }
330
+
331
+ function chooseFinalAssistant(input, turn) {
332
+ const direct = normalizeEventContent(input.last_assistant_message);
333
+ if (direct) return { content: direct, source: 'last_assistant_message' };
334
+ const transcriptPath = transcriptPathFor(input) || turn.transcriptPath;
335
+ if (!transcriptPath) return null;
336
+ const result = finalAssistantFromTranscript(transcriptPath, {
337
+ afterOffset: turn.transcriptOffsetAtPrompt,
338
+ prompt: turn.prompt,
339
+ });
340
+ if (!result || !result.content) return null;
341
+ return { content: normalizeEventContent(result.content), source: 'transcript' };
342
+ }
343
+
344
+ function ensureFinalEvent(turn, final) {
345
+ if (turn.finalEvent) return turn.finalEvent;
346
+ turn.finalEvent = {
347
+ eventType: 'assistant_final',
348
+ idempotencyKey: idempotencyKeyFor(turn.projectId, turn.clientSessionId, turn.turnId, 'assistant_final'),
349
+ content: final.content,
350
+ source: final.source,
351
+ status: 'pending',
352
+ createdAt: Date.now(),
353
+ };
354
+ return turn.finalEvent;
355
+ }
356
+
357
+ async function handleCapture(input, key) {
358
+ if (input.stop_hook_active || input.agent_id) {
359
+ debug(input.agent_id ? 'subagent Stop ignored' : 'stop_hook_active: skipping capture');
135
360
  return;
136
361
  }
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);
362
+ const cfg = loadConfig();
363
+ const identity = deriveProjectIdentity(input, cfg);
364
+ const captureEnabled = identity.projectConfig.captureEnabled ?? cfg.captureEnabled;
365
+ if (disabled(cfg, identity) || captureEnabled === false || !input.session_id) return;
366
+
141
367
  try {
142
- state.highWaterLine = lastLine;
143
- state.lastFlushAt = Date.now();
144
- saveState(sessionId, state);
145
- } catch (e) {
146
- debug('state update failed:', e.message);
368
+ await withStateLock(stateKeyFor(input), async (state) => {
369
+ const stateKey = stateKeyFor(input);
370
+ const turn = activeTurn(state);
371
+ if (!turn) return; // never invent a turn from an uncorrelated transcript
372
+
373
+ const promptAccepted = await sendTurnEvent(key, stateKey, state, turn, 'promptEvent');
374
+ if (!promptAccepted) return;
375
+ if (turn.finalEvent) {
376
+ await sendTurnEvent(key, stateKey, state, turn, 'finalEvent');
377
+ } else {
378
+ const final = chooseFinalAssistant(input, turn);
379
+ if (!final || !final.content) {
380
+ turn.lastFinalProbeAt = Date.now();
381
+ turn.finalProbeStatus = 'empty-or-incomplete';
382
+ saveState(stateKey, state);
383
+ return;
384
+ }
385
+ ensureFinalEvent(turn, final);
386
+ saveState(stateKey, state); // write-ahead final event before network I/O
387
+ await sendTurnEvent(key, stateKey, state, turn, 'finalEvent');
388
+ }
389
+
390
+ if (turn.promptEvent.status === 'accepted' && turn.finalEvent && turn.finalEvent.status === 'accepted') {
391
+ turn.status = 'complete';
392
+ turn.completedAt = Date.now();
393
+ if (state.activeTurnId === turn.turnId) delete state.activeTurnId;
394
+ saveState(stateKey, state);
395
+ }
396
+ }, { timeoutMs: 2500 });
397
+ } catch (error) {
398
+ debug('Stop capture failed open:', error.message);
147
399
  }
148
400
  }
149
401
 
150
- async function handleSessionStart(input, key) {
151
- // Fire-and-forget warmup so the first search/prepare is fast.
402
+ async function retryPendingEvents(input, key) {
403
+ if (!input.session_id || input.agent_id) return;
404
+ const cfg = loadConfig();
405
+ const identity = deriveProjectIdentity(input, cfg);
406
+ const captureEnabled = identity.projectConfig.captureEnabled ?? cfg.captureEnabled;
407
+ if (disabled(cfg, identity) || captureEnabled === false) return;
152
408
  try {
153
- await api.warmup(key, { timeoutMs: 8000 });
154
- } catch (e) {
155
- debug('warmup failed:', e.message);
409
+ await withStateLock(stateKeyFor(input), async (state) => {
410
+ const stateKey = stateKeyFor(input);
411
+ for (const turn of ensureTurns(state)) {
412
+ if (turn.promptEvent && turn.promptEvent.status === 'pending') {
413
+ await sendTurnEvent(key, stateKey, state, turn, 'promptEvent');
414
+ }
415
+ if (turn.finalEvent && turn.finalEvent.status === 'pending'
416
+ && turn.promptEvent && turn.promptEvent.status === 'accepted') {
417
+ await sendTurnEvent(key, stateKey, state, turn, 'finalEvent');
418
+ }
419
+ if (turn.promptEvent && turn.promptEvent.status === 'accepted'
420
+ && turn.finalEvent && turn.finalEvent.status === 'accepted') {
421
+ turn.status = 'complete';
422
+ }
423
+ }
424
+ saveState(stateKey, state);
425
+ }, { timeoutMs: 2500 });
426
+ } catch (error) {
427
+ debug('pending event retry failed open:', error.message);
156
428
  }
157
429
  }
158
430
 
159
- // --- entry ---
431
+ async function handleFailure(input, key) {
432
+ await retryPendingEvents(input, key);
433
+ if (!input.session_id || input.agent_id) return;
434
+ try {
435
+ await withStateLock(stateKeyFor(input), async (state) => {
436
+ const turn = activeTurn(state);
437
+ if (!turn) return;
438
+ turn.status = 'failed';
439
+ turn.failedAt = Date.now();
440
+ turn.failureReason = typeof input.error === 'string' ? input.error.slice(0, 1000) : 'StopFailure';
441
+ if (state.activeTurnId === turn.turnId) delete state.activeTurnId;
442
+ saveState(stateKeyFor(input), state);
443
+ });
444
+ } catch (error) { debug('failure state failed open:', error.message); }
445
+ }
446
+
447
+ async function handleFlush(input, key) {
448
+ await retryPendingEvents(input, key);
449
+ }
450
+
451
+ async function handleSubagentCapture() {
452
+ // Explicit policy: automatic subagent capture is unsupported. SubagentStop
453
+ // never writes because its transcript contains delegated/internal chatter.
454
+ }
455
+
456
+ async function handleCompact(input, key) {
457
+ // Compaction summaries are model-generated intermediate artifacts, not a user
458
+ // prompt or final answer. Only retry already-created typed events.
459
+ await retryPendingEvents(input, key);
460
+ }
461
+
462
+ async function handleReinject(input, key) {
463
+ const state = loadState(stateKeyFor(input));
464
+ const prompt = state.lastPrompt || 'Recall the most relevant recent project decisions and unresolved work.';
465
+ await retrieveContext(input, key, prompt, 'SessionStart');
466
+ }
467
+
468
+ async function handleSessionStart(input, key) {
469
+ const cfg = loadConfig();
470
+ const identity = deriveProjectIdentity(input, cfg);
471
+ if (disabled(cfg, identity)) return;
472
+ pruneState(cfg.stateTtlDays);
473
+ try {
474
+ const stateKey = stateKeyFor(input);
475
+ const state = loadState(stateKey);
476
+ state.projectId = identity.id;
477
+ state.sessionSource = input.source || 'unknown';
478
+ state.sessionStartedAt = Date.now();
479
+ saveState(stateKey, state);
480
+ } catch (e) { debug('session state failed:', e.message); }
481
+ try {
482
+ await api.warmup(key, scopeSession(identity), { timeoutMs: 8000 });
483
+ } catch (e) { debug('warmup failed:', e.message); }
484
+ }
160
485
 
161
486
  async function runHook(kind) {
162
- // Absolute wall-clock kill switch: never hang past our settings timeout.
163
487
  const wallClock = setTimeout(() => {
164
- debug('wall-clock timeout — exiting 0');
488
+ debug('wall-clock timeout: exiting 0');
165
489
  process.exit(0);
166
- }, kind === 'inject' ? 8000 : 25000);
490
+ }, kind === 'inject' || kind === 'reinject' ? 8000 : 27000);
167
491
  wallClock.unref();
168
492
 
169
493
  try {
170
494
  const key = getApiKey();
171
- if (!key) {
172
- debug('no API key configured — run `npx memoryrouter-claude init`');
173
- return;
174
- }
495
+ if (!key) return;
175
496
  const raw = await readStdin();
176
497
  let input = {};
177
- try {
178
- input = JSON.parse(raw || '{}');
179
- } catch {
180
- debug('bad stdin JSON');
181
- return;
182
- }
498
+ try { input = JSON.parse(raw || '{}'); } catch { return; }
183
499
 
184
500
  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);
501
+ case 'inject': await handleInject(input, key); break;
502
+ case 'capture': await handleCapture(input, key); break;
503
+ case 'capture-subagent': await handleSubagentCapture(input, key); break;
504
+ case 'failure': await handleFailure(input, key); break;
505
+ case 'flush': await handleFlush(input, key); break;
506
+ case 'compact': await handleCompact(input, key); break;
507
+ case 'reinject': await handleReinject(input, key); break;
508
+ case 'session-start': await handleSessionStart(input, key); break;
509
+ default: debug('unknown hook kind:', kind);
199
510
  }
200
511
  } catch (err) {
201
512
  debug('hook error:', err && err.message);
202
513
  }
203
- // Always success — fail open.
204
514
  process.exitCode = 0;
205
515
  }
206
516
 
@@ -208,8 +518,19 @@ module.exports = {
208
518
  runHook,
209
519
  handleInject,
210
520
  handleCapture,
521
+ handleFailure,
211
522
  handleFlush,
523
+ handleSubagentCapture,
524
+ handleCompact,
525
+ handleReinject,
212
526
  handleSessionStart,
527
+ retryPendingEvents,
528
+ captureEventPayload,
529
+ createOrResumePromptTurn,
530
+ idempotencyKeyFor,
531
+ turnIdFor,
532
+ mergeContexts,
213
533
  emitContext,
534
+ stateKeyFor,
214
535
  MAX_CONTEXT_CHARS,
215
536
  };