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.
@@ -1,8 +1,10 @@
1
1
  'use strict';
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.
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
 
7
+ const fs = require('fs');
6
8
  const {
7
9
  getApiKey,
8
10
  loadState,
@@ -12,19 +14,13 @@ const {
12
14
  pruneState,
13
15
  } = require('./config');
14
16
  const api = require('./api');
15
- const {
16
- hash,
17
- compactText,
18
- normalizeRecord,
19
- readTranscriptDelta,
20
- lineIndexToOffset,
21
- } = require('./transcript');
17
+ const { hash, compactText, cleanText, finalAssistantFromTranscript } = require('./transcript');
22
18
  const { deriveProjectIdentity, sessionIdFor } = require('./project');
23
19
 
24
20
  const MAX_CONTEXT_CHARS = 9500;
25
- const DEFAULT_CAPTURE_BATCH_CHARS = 32000;
26
- const DEFAULT_CAPTURE_BATCHES = 8;
27
- const RECENT_KEY_LIMIT = 1500;
21
+ const MAX_EVENT_CHARS = 100000;
22
+ const RECENT_TURN_LIMIT = 50;
23
+ const NUDGE_WINDOW_MS = 24 * 60 * 60 * 1000;
28
24
 
29
25
  function debug(...args) {
30
26
  if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
@@ -65,12 +61,16 @@ function emitContext(eventName, context, maxChars = MAX_CONTEXT_CHARS) {
65
61
  }
66
62
 
67
63
  function stateKeyFor(input) {
68
- const session = input.session_id || 'unknown';
69
- return input.agent_id ? `${session}--agent-${input.agent_id}` : session;
64
+ return input.session_id || 'unknown';
70
65
  }
71
66
 
72
67
  function transcriptPathFor(input) {
73
- return input.agent_transcript_path || input.transcript_path || null;
68
+ return input.transcript_path || null;
69
+ }
70
+
71
+ function transcriptSize(transcriptPath) {
72
+ if (!transcriptPath) return null;
73
+ try { return fs.statSync(transcriptPath).size; } catch { return null; }
74
74
  }
75
75
 
76
76
  function scopeSession(identity) {
@@ -98,6 +98,51 @@ function mergeContexts(results, identity, maxChars) {
98
98
  return compactText(`${header}\n${sections.join('\n\n')}`, maxChars);
99
99
  }
100
100
 
101
+ function reflectionNudgeLine(results) {
102
+ // The server owns the threshold decision: a non-null reflection.suggestion
103
+ // on any /prepare result means consolidation is available. Connectors only
104
+ // render one line; they never recompute debt.
105
+ for (const item of results) {
106
+ const debt = item && item.reflection;
107
+ if (!debt || !debt.suggestion) continue;
108
+ const rawTokens = debt.unconsolidated && debt.unconsolidated.raw
109
+ ? Number(debt.unconsolidated.raw.est_tokens) : NaN;
110
+ const tier2Tokens = debt.unconsolidated && debt.unconsolidated.tier2
111
+ ? Number(debt.unconsolidated.tier2.est_tokens) : NaN;
112
+ const total = (Number.isFinite(rawTokens) ? rawTokens : 0)
113
+ + (Number.isFinite(tier2Tokens) ? tier2Tokens : 0);
114
+ const amount = total > 0 ? `${Math.round(total / 1000)}k` : 'significant';
115
+ return `[MemoryRouter] Consolidation available: ${amount} unconsolidated memory tokens. Run: npx memoryrouter-claude reflect`;
116
+ }
117
+ return null;
118
+ }
119
+
120
+ async function maybeAppendNudge(input, context, results, maxChars) {
121
+ // Rules (connectors spec section c): only on an already-emitted context,
122
+ // never a context solely for the nudge, at most once per 24h per session
123
+ // state, and always inside the existing char cap so memory content wins.
124
+ if (!context) return context;
125
+ const line = reflectionNudgeLine(results);
126
+ if (!line) return context;
127
+ const cap = Math.max(1000, Math.min(MAX_CONTEXT_CHARS, Number(maxChars) || MAX_CONTEXT_CHARS));
128
+ if (context.length + line.length + 1 > cap) return context;
129
+ let allowed = false;
130
+ try {
131
+ await withStateLock(stateKeyFor(input), async (state) => {
132
+ const last = Number(state.lastNudgeAt) || 0;
133
+ if (Date.now() - last >= NUDGE_WINDOW_MS) {
134
+ state.lastNudgeAt = Date.now();
135
+ saveState(stateKeyFor(input), state);
136
+ allowed = true;
137
+ }
138
+ }, { timeoutMs: 1500 });
139
+ } catch (error) {
140
+ debug('nudge state failed open:', error.message);
141
+ return context;
142
+ }
143
+ return allowed ? `${context}\n${line}` : context;
144
+ }
145
+
101
146
  async function retrieveContext(input, key, prompt, eventName) {
102
147
  const cfg = loadConfig();
103
148
  const identity = deriveProjectIdentity(input, cfg);
@@ -108,274 +153,364 @@ async function retrieveContext(input, key, prompt, eventName) {
108
153
 
109
154
  if (identity.memoryScope === 'global') {
110
155
  requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
111
- .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context })));
156
+ .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
112
157
  } else {
113
158
  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 })));
159
+ .then((res) => ({ label: 'Project', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
115
160
  if (identity.includeGlobal) {
116
161
  requests.push(api.prepare(key, prompt, undefined, { timeoutMs: 5500, contextLimit, density })
117
- .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context })));
162
+ .then((res) => ({ label: 'Global', context: res.ok && res.data && res.data.context, reflection: res.ok && res.data && res.data.reflection })));
118
163
  }
119
164
  }
120
165
 
121
166
  const settled = await Promise.allSettled(requests);
122
167
  const results = settled.filter((r) => r.status === 'fulfilled').map((r) => r.value);
123
- const context = mergeContexts(results, identity, cfg.maxContextChars || MAX_CONTEXT_CHARS);
168
+ let context = mergeContexts(results, identity, cfg.maxContextChars || MAX_CONTEXT_CHARS);
169
+ if (context && input.session_id) {
170
+ context = await maybeAppendNudge(input, context, results, cfg.maxContextChars || MAX_CONTEXT_CHARS);
171
+ }
124
172
  emitContext(eventName, context, cfg.maxContextChars);
125
173
  }
126
174
 
127
- async function handleInject(input, key) {
128
- const prompt = input.prompt;
129
- if (!prompt || typeof prompt !== 'string' || !prompt.trim()) return;
130
- const cfg = loadConfig();
131
- const identity = deriveProjectIdentity(input, cfg);
132
- if (disabled(cfg, identity)) return;
175
+ function normalizeEventContent(value) {
176
+ return compactText(cleanText(value), MAX_EVENT_CHARS);
177
+ }
133
178
 
134
- try {
135
- const stateKey = stateKeyFor(input);
136
- const state = loadState(stateKey);
137
- state.lastPrompt = prompt.slice(0, 100000);
138
- state.lastPromptAt = Date.now();
139
- state.projectId = identity.id;
140
- saveState(stateKey, state);
141
- } catch (e) { debug('prompt cache failed:', e.message); }
179
+ function turnIdFor(sessionId, sequence) {
180
+ return `cct_${hash(`claude-code-turn\n${sessionId}\n${sequence}`).slice(0, 40)}`;
181
+ }
182
+
183
+ function idempotencyKeyFor(projectId, sessionId, turnId, eventType) {
184
+ return `cce_${hash(`claude-code-capture-v1\n${projectId}\n${sessionId}\n${turnId}\n${eventType}`)}`;
185
+ }
186
+
187
+ function ensureTurns(state) {
188
+ // v2.0 pending transcript digests are intentionally not replayed: their
189
+ // payload may contain tool/intermediate/subagent chatter. Record only that a
190
+ // legacy batch was discarded, remove its content, and start typed turns clean.
191
+ if (state.pendingCapture) {
192
+ state.legacyCaptureDiscarded = {
193
+ batchId: state.pendingCapture.batchId || null,
194
+ discardedAt: Date.now(),
195
+ reason: 'superseded-by-typed-capture-v1',
196
+ };
197
+ delete state.pendingCapture;
198
+ delete state.transcriptOffset;
199
+ delete state.transcriptPathHash;
200
+ delete state.blockedOffset;
201
+ delete state.blockedAt;
202
+ delete state.recentEventKeys;
203
+ delete state.pendingFallbackContentKeys;
204
+ }
205
+ if (!Array.isArray(state.turns)) state.turns = [];
206
+ if (!Number.isInteger(state.nextTurnSequence) || state.nextTurnSequence < 1) {
207
+ state.nextTurnSequence = state.turns.reduce((max, turn) => Math.max(max, Number(turn.sequence) || 0), 0) + 1;
208
+ }
209
+ return state.turns;
210
+ }
211
+
212
+ function newTurn(state, input, identity, prompt) {
213
+ const turns = ensureTurns(state);
214
+ const sequence = state.nextTurnSequence++;
215
+ const sessionId = String(input.session_id);
216
+ const turnId = turnIdFor(sessionId, sequence);
217
+ const now = Date.now();
218
+ const transcriptPath = transcriptPathFor(input);
219
+ const turn = {
220
+ version: 1,
221
+ sequence,
222
+ turnId,
223
+ projectId: identity.id,
224
+ clientSessionId: sessionId,
225
+ scopeSessionId: scopeSession(identity),
226
+ prompt,
227
+ promptHash: hash(prompt),
228
+ status: 'open',
229
+ createdAt: now,
230
+ transcriptPath,
231
+ transcriptOffsetAtPrompt: transcriptSize(transcriptPath),
232
+ promptEvent: {
233
+ eventType: 'user_prompt',
234
+ idempotencyKey: idempotencyKeyFor(identity.id, sessionId, turnId, 'user_prompt'),
235
+ content: prompt,
236
+ status: 'pending',
237
+ createdAt: now,
238
+ },
239
+ };
240
+ const priorOpen = [...turns].reverse().find((item) => item.status === 'open');
241
+ if (priorOpen) {
242
+ priorOpen.status = 'interrupted';
243
+ priorOpen.interruptedAt = now;
244
+ }
245
+ turns.push(turn);
246
+ const retained = new Map();
247
+ for (const item of turns.slice(-RECENT_TURN_LIMIT)) retained.set(item.turnId, item);
248
+ for (const item of turns) {
249
+ const hasPending = (item.promptEvent && item.promptEvent.status === 'pending')
250
+ || (item.finalEvent && item.finalEvent.status === 'pending');
251
+ if (hasPending) retained.set(item.turnId, item);
252
+ }
253
+ state.turns = Array.from(retained.values()).sort((a, b) => a.sequence - b.sequence);
254
+ state.activeTurnId = turn.turnId;
255
+ return turn;
256
+ }
257
+
258
+ function findTurn(state, turnId) {
259
+ return ensureTurns(state).find((turn) => turn.turnId === turnId) || null;
260
+ }
142
261
 
143
- await retrieveContext(input, key, prompt, 'UserPromptSubmit');
262
+ function activeTurn(state) {
263
+ const explicit = state.activeTurnId && findTurn(state, state.activeTurnId);
264
+ if (explicit && explicit.status === 'open') return explicit;
265
+ return [...ensureTurns(state)].reverse().find((turn) => turn.status === 'open') || null;
144
266
  }
145
267
 
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}`;
268
+ function createOrResumePromptTurn(state, input, identity, prompt) {
269
+ const current = activeTurn(state);
270
+ if (current && current.promptHash === hash(prompt)) return current;
271
+ return newTurn(state, input, identity, prompt);
149
272
  }
150
273
 
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');
274
+ function captureEventPayload(turn, event) {
156
275
  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,
276
+ version: 1,
277
+ source: 'claude-code-hooks',
278
+ event_type: event.eventType,
279
+ idempotency_key: event.idempotencyKey,
280
+ project_id: turn.projectId,
281
+ client_session_id: turn.clientSessionId,
282
+ turn_id: turn.turnId,
283
+ occurred_at: event.createdAt,
284
+ content: event.content,
160
285
  };
161
286
  }
162
287
 
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;
175
- }
176
- return { events, endOffset };
177
- }
178
-
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;
288
+ function durablyAccepted(res) {
289
+ return Boolean(
290
+ res && res.ok && res.data && res.data.durable === true
291
+ && (res.data.status === 'accepted' || res.data.status === 'duplicate'),
292
+ );
201
293
  }
202
294
 
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',
209
- });
210
- if (!res.ok) {
211
- debug('capture not accepted:', res.status, pending.batchId);
295
+ async function sendTurnEvent(key, stateKey, state, turn, field, timeoutMs = 10000) {
296
+ const event = turn && turn[field];
297
+ if (!event || event.status === 'accepted' || event.status === 'conflict') return event && event.status === 'accepted';
298
+ let res;
299
+ try {
300
+ res = await api.ingestEvent(key, captureEventPayload(turn, event), turn.scopeSessionId, {
301
+ timeoutMs,
302
+ model: 'claude-code-hook',
303
+ });
304
+ } catch (error) {
305
+ event.lastError = error && error.message ? error.message : 'network error';
306
+ event.lastAttemptAt = Date.now();
307
+ saveState(stateKey, state);
308
+ debug('capture event delivery failed:', event.eventType, event.lastError);
212
309
  return false;
213
310
  }
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);
311
+ event.lastAttemptAt = Date.now();
312
+ event.attempts = (Number(event.attempts) || 0) + 1;
313
+ if (durablyAccepted(res)) {
314
+ event.status = 'accepted';
315
+ event.acceptedAt = Date.now();
316
+ event.serverStatus = res.data.status;
317
+ delete event.lastError;
318
+ } else if (res.status === 409) {
319
+ event.status = 'conflict';
320
+ event.lastError = 'server rejected idempotency key reuse with different event data';
321
+ } else {
322
+ event.lastError = (res.data && (res.data.error || res.data.reason)) || `HTTP ${res.status}`;
222
323
  }
223
- state.lastCaptureAt = Date.now();
224
- state.lastAcceptedBatch = pending.batchId;
225
- delete state.pendingCapture;
226
324
  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;
325
+ return event.status === 'accepted';
236
326
  }
237
327
 
238
- async function captureTranscript(input, key, options = {}) {
328
+ async function handleInject(input, key) {
329
+ const prompt = normalizeEventContent(input.prompt);
330
+ if (!prompt || !input.session_id) return;
239
331
  const cfg = loadConfig();
240
332
  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');
246
- return;
333
+ if (disabled(cfg, identity)) return;
334
+
335
+ let turnId = null;
336
+ try {
337
+ turnId = await withStateLock(stateKeyFor(input), async (state) => {
338
+ const stateKey = stateKeyFor(input);
339
+ const turn = createOrResumePromptTurn(state, input, identity, prompt);
340
+ state.lastPrompt = prompt;
341
+ state.lastPromptAt = Date.now();
342
+ state.projectId = identity.id;
343
+ saveState(stateKey, state); // durable local turn before network I/O
344
+ return turn.turnId;
345
+ }, { timeoutMs: 2500 });
346
+ } catch (error) {
347
+ debug('prompt event state failed:', error.message);
247
348
  }
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
349
 
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;
350
+ const delivery = turnId ? withStateLock(stateKeyFor(input), async (state) => {
351
+ const turns = ensureTurns(state);
352
+ const turn = findTurn(state, turnId);
353
+ if (!turn) return;
354
+ // Preserve turn order after an offline/lost-response window. Older pending
355
+ // events are retried before the new prompt can append to the server buffer.
356
+ for (const prior of turns) {
357
+ if (prior.turnId === turn.turnId) break;
358
+ if (prior.promptEvent && prior.promptEvent.status === 'pending') {
359
+ const accepted = await sendTurnEvent(key, stateKeyFor(input), state, prior, 'promptEvent', 2000);
360
+ if (!accepted) return;
279
361
  }
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];
362
+ if (prior.finalEvent && prior.finalEvent.status === 'pending') {
363
+ if (!prior.promptEvent || prior.promptEvent.status !== 'accepted') return;
364
+ const accepted = await sendTurnEvent(key, stateKeyFor(input), state, prior, 'finalEvent', 2000);
365
+ if (!accepted) return;
292
366
  }
367
+ }
368
+ await sendTurnEvent(key, stateKeyFor(input), state, turn, 'promptEvent', 6000);
369
+ }, { timeoutMs: 2500 }).catch((error) => debug('prompt event delivery failed open:', error.message)) : Promise.resolve();
370
+
371
+ // Recall is intentionally a separate, read-only operation. It runs in
372
+ // parallel with durable event delivery so adding capture does not serialize
373
+ // two network round trips on Claude Code's latency-critical prompt hook.
374
+ await Promise.allSettled([
375
+ delivery,
376
+ retrieveContext(input, key, prompt, 'UserPromptSubmit'),
377
+ ]);
378
+ }
293
379
 
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
- }
380
+ function chooseFinalAssistant(input, turn) {
381
+ const direct = normalizeEventContent(input.last_assistant_message);
382
+ if (direct) return { content: direct, source: 'last_assistant_message' };
383
+ const transcriptPath = transcriptPathFor(input) || turn.transcriptPath;
384
+ if (!transcriptPath) return null;
385
+ const result = finalAssistantFromTranscript(transcriptPath, {
386
+ afterOffset: turn.transcriptOffsetAtPrompt,
387
+ prompt: turn.prompt,
388
+ });
389
+ if (!result || !result.content) return null;
390
+ return { content: normalizeEventContent(result.content), source: 'transcript' };
391
+ }
309
392
 
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 });
393
+ function ensureFinalEvent(turn, final) {
394
+ if (turn.finalEvent) return turn.finalEvent;
395
+ turn.finalEvent = {
396
+ eventType: 'assistant_final',
397
+ idempotencyKey: idempotencyKeyFor(turn.projectId, turn.clientSessionId, turn.turnId, 'assistant_final'),
398
+ content: final.content,
399
+ source: final.source,
400
+ status: 'pending',
401
+ createdAt: Date.now(),
402
+ };
403
+ return turn.finalEvent;
332
404
  }
333
405
 
334
406
  async function handleCapture(input, key) {
335
- if (input.stop_hook_active) {
336
- debug('stop_hook_active — skipping capture');
407
+ if (input.stop_hook_active || input.agent_id) {
408
+ debug(input.agent_id ? 'subagent Stop ignored' : 'stop_hook_active: skipping capture');
337
409
  return;
338
410
  }
339
- await captureTranscript(input, key);
340
- }
411
+ const cfg = loadConfig();
412
+ const identity = deriveProjectIdentity(input, cfg);
413
+ const captureEnabled = identity.projectConfig.captureEnabled ?? cfg.captureEnabled;
414
+ if (disabled(cfg, identity) || captureEnabled === false || !input.session_id) return;
341
415
 
342
- async function handleFlush(input, key) {
343
- await captureTranscript(input, key, { flush: true });
344
- }
416
+ try {
417
+ await withStateLock(stateKeyFor(input), async (state) => {
418
+ const stateKey = stateKeyFor(input);
419
+ const turn = activeTurn(state);
420
+ if (!turn) return; // never invent a turn from an uncorrelated transcript
421
+
422
+ const promptAccepted = await sendTurnEvent(key, stateKey, state, turn, 'promptEvent');
423
+ if (!promptAccepted) return;
424
+ if (turn.finalEvent) {
425
+ await sendTurnEvent(key, stateKey, state, turn, 'finalEvent');
426
+ } else {
427
+ const final = chooseFinalAssistant(input, turn);
428
+ if (!final || !final.content) {
429
+ turn.lastFinalProbeAt = Date.now();
430
+ turn.finalProbeStatus = 'empty-or-incomplete';
431
+ saveState(stateKey, state);
432
+ return;
433
+ }
434
+ ensureFinalEvent(turn, final);
435
+ saveState(stateKey, state); // write-ahead final event before network I/O
436
+ await sendTurnEvent(key, stateKey, state, turn, 'finalEvent');
437
+ }
345
438
 
346
- async function handleSubagentCapture(input, key) {
347
- if (input.stop_hook_active) return;
348
- await captureTranscript(input, key);
439
+ if (turn.promptEvent.status === 'accepted' && turn.finalEvent && turn.finalEvent.status === 'accepted') {
440
+ turn.status = 'complete';
441
+ turn.completedAt = Date.now();
442
+ if (state.activeTurnId === turn.turnId) delete state.activeTurnId;
443
+ saveState(stateKey, state);
444
+ }
445
+ }, { timeoutMs: 2500 });
446
+ } catch (error) {
447
+ debug('Stop capture failed open:', error.message);
448
+ }
349
449
  }
350
450
 
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;
451
+ async function retryPendingEvents(input, key) {
452
+ if (!input.session_id || input.agent_id) return;
355
453
  const cfg = loadConfig();
356
454
  const identity = deriveProjectIdentity(input, cfg);
357
455
  const captureEnabled = identity.projectConfig.captureEnabled ?? cfg.captureEnabled;
358
456
  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',
457
+ try {
458
+ await withStateLock(stateKeyFor(input), async (state) => {
459
+ const stateKey = stateKeyFor(input);
460
+ for (const turn of ensureTurns(state)) {
461
+ if (turn.promptEvent && turn.promptEvent.status === 'pending') {
462
+ await sendTurnEvent(key, stateKey, state, turn, 'promptEvent');
463
+ }
464
+ if (turn.finalEvent && turn.finalEvent.status === 'pending'
465
+ && turn.promptEvent && turn.promptEvent.status === 'accepted') {
466
+ await sendTurnEvent(key, stateKey, state, turn, 'finalEvent');
467
+ }
468
+ if (turn.promptEvent && turn.promptEvent.status === 'accepted'
469
+ && turn.finalEvent && turn.finalEvent.status === 'accepted') {
470
+ turn.status = 'complete';
471
+ }
472
+ }
473
+ saveState(stateKey, state);
474
+ }, { timeoutMs: 2500 });
475
+ } catch (error) {
476
+ debug('pending event retry failed open:', error.message);
477
+ }
478
+ }
479
+
480
+ async function handleFailure(input, key) {
481
+ await retryPendingEvents(input, key);
482
+ if (!input.session_id || input.agent_id) return;
483
+ try {
484
+ await withStateLock(stateKeyFor(input), async (state) => {
485
+ const turn = activeTurn(state);
486
+ if (!turn) return;
487
+ turn.status = 'failed';
488
+ turn.failedAt = Date.now();
489
+ turn.failureReason = typeof input.error === 'string' ? input.error.slice(0, 1000) : 'StopFailure';
490
+ if (state.activeTurnId === turn.turnId) delete state.activeTurnId;
491
+ saveState(stateKeyFor(input), state);
367
492
  });
368
- if (!res.ok) return;
369
- state.syntheticKeys = [...(state.syntheticKeys || []), syntheticKey].slice(-100);
370
- state.lastCompactAt = Date.now();
371
- saveState(stateKey, state);
372
- });
493
+ } catch (error) { debug('failure state failed open:', error.message); }
494
+ }
495
+
496
+ async function handleFlush(input, key) {
497
+ await retryPendingEvents(input, key);
498
+ }
499
+
500
+ async function handleSubagentCapture() {
501
+ // Explicit policy: automatic subagent capture is unsupported. SubagentStop
502
+ // never writes because its transcript contains delegated/internal chatter.
503
+ }
504
+
505
+ async function handleCompact(input, key) {
506
+ // Compaction summaries are model-generated intermediate artifacts, not a user
507
+ // prompt or final answer. Only retry already-created typed events.
508
+ await retryPendingEvents(input, key);
373
509
  }
374
510
 
375
511
  async function handleReinject(input, key) {
376
512
  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.';
513
+ const prompt = state.lastPrompt || 'Recall the most relevant recent project decisions and unresolved work.';
379
514
  await retrieveContext(input, key, prompt, 'SessionStart');
380
515
  }
381
516
 
@@ -399,7 +534,7 @@ async function handleSessionStart(input, key) {
399
534
 
400
535
  async function runHook(kind) {
401
536
  const wallClock = setTimeout(() => {
402
- debug('wall-clock timeout — exiting 0');
537
+ debug('wall-clock timeout: exiting 0');
403
538
  process.exit(0);
404
539
  }, kind === 'inject' || kind === 'reinject' ? 8000 : 27000);
405
540
  wallClock.unref();
@@ -415,6 +550,7 @@ async function runHook(kind) {
415
550
  case 'inject': await handleInject(input, key); break;
416
551
  case 'capture': await handleCapture(input, key); break;
417
552
  case 'capture-subagent': await handleSubagentCapture(input, key); break;
553
+ case 'failure': await handleFailure(input, key); break;
418
554
  case 'flush': await handleFlush(input, key); break;
419
555
  case 'compact': await handleCompact(input, key); break;
420
556
  case 'reinject': await handleReinject(input, key); break;
@@ -431,16 +567,20 @@ module.exports = {
431
567
  runHook,
432
568
  handleInject,
433
569
  handleCapture,
570
+ handleFailure,
434
571
  handleFlush,
435
572
  handleSubagentCapture,
436
573
  handleCompact,
437
574
  handleReinject,
438
575
  handleSessionStart,
439
- captureTranscript,
440
- buildDigest,
441
- selectBatch,
576
+ retryPendingEvents,
577
+ captureEventPayload,
578
+ createOrResumePromptTurn,
579
+ idempotencyKeyFor,
580
+ turnIdFor,
442
581
  mergeContexts,
443
582
  emitContext,
444
583
  stateKeyFor,
584
+ reflectionNudgeLine,
445
585
  MAX_CONTEXT_CHARS,
446
586
  };