memoryrouter-claude 2.0.0 → 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.
- package/CHANGELOG.md +21 -1
- package/README.md +52 -27
- package/bin/cli.js +17 -13
- package/lib/api.js +8 -1
- package/lib/hook-runner.js +318 -228
- package/lib/settings.js +3 -3
- package/lib/transcript.js +55 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## 2.
|
|
3
|
+
## 2.1.0 (2026-08-05)
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- Replaced full transcript-delta ingestion with one typed `user_prompt` and one typed `assistant_final` per Claude Code turn.
|
|
8
|
+
- Made `/prepare` recall a separate read-only operation after local prompt-event creation.
|
|
9
|
+
- 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.
|
|
10
|
+
- Added lost-`202` recovery. Repeated delivery returns durable `duplicate` success without a second buffer append.
|
|
11
|
+
- Made `last_assistant_message` authoritative and added a conservative transcript fallback that rejects partial JSON, tool-last records, and sidechains.
|
|
12
|
+
- Removed automatic tool, intermediate assistant, tool result/failure, compaction summary, `StopFailure`, and subagent transcript capture.
|
|
13
|
+
|
|
14
|
+
### Compatibility and operations
|
|
15
|
+
|
|
16
|
+
- Untyped legacy `messages[]` ingest requests retain their existing behavior.
|
|
17
|
+
- Typed capture requires additive D1 migration `0029_capture_event_receipts.sql` before Worker deployment.
|
|
18
|
+
- Completed D1 receipts are retained for 90 days; local turn state remains 30 days by default.
|
|
19
|
+
- Added durable pending-chunk leases so background embedding/mirroring can resume after a crash without losing accepted buffer content.
|
|
20
|
+
|
|
21
|
+
## 2.0.0 (2026-07-31)
|
|
22
|
+
|
|
23
|
+
> 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
24
|
|
|
5
25
|
### Fixed
|
|
6
26
|
|
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
|
|
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` |
|
|
53
|
-
| `Stop` |
|
|
54
|
-
| `StopFailure` |
|
|
55
|
-
| `PreCompact`
|
|
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` |
|
|
60
|
-
| `SessionEnd` |
|
|
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
|
-
|
|
61
|
+
## Deterministic capture and durable retry safety
|
|
63
62
|
|
|
64
|
-
|
|
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
|
-
|
|
65
|
+
The typed request is opt-in through `capture_event` on `POST /v1/memory/ingest`:
|
|
67
66
|
|
|
68
|
-
|
|
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
|
|
95
|
+
|
|
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.
|
|
69
97
|
|
|
70
|
-
|
|
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.
|
|
98
|
+
### Retry, interruption, and retention behavior
|
|
77
99
|
|
|
78
|
-
|
|
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
|
```
|
|
@@ -161,12 +189,9 @@ The key is stored only at `~/.memoryrouter/config.json` with mode `0600` in a mo
|
|
|
161
189
|
"memoryScope": "project",
|
|
162
190
|
"includeGlobal": false,
|
|
163
191
|
"captureEnabled": true,
|
|
164
|
-
"captureSubagents": false,
|
|
165
192
|
"contextLimit": 2000,
|
|
166
193
|
"density": "balanced",
|
|
167
194
|
"maxContextChars": 9500,
|
|
168
|
-
"captureBatchChars": 32000,
|
|
169
|
-
"captureMaxBatches": 8,
|
|
170
195
|
"stateTtlDays": 30
|
|
171
196
|
}
|
|
172
197
|
```
|
|
@@ -186,10 +211,10 @@ Read-only mode uses the canonical `:read` suffix, for example `mk_xxx:read`. The
|
|
|
186
211
|
|
|
187
212
|
## Local retention and failure behavior
|
|
188
213
|
|
|
189
|
-
-
|
|
214
|
+
- 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
215
|
- State files are pruned after 30 days by default.
|
|
191
|
-
-
|
|
192
|
-
- Every hook exits successfully from Claude Code's perspective. Retrieval failures produce no injected context; write failures retain
|
|
216
|
+
- 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.
|
|
217
|
+
- Every hook exits successfully from Claude Code's perspective. Retrieval failures produce no injected context; write failures retain pending typed events for retry.
|
|
193
218
|
- Hook wall clocks are 8 seconds for retrieval and 27 seconds for capture paths, below their configured Claude Code timeouts.
|
|
194
219
|
|
|
195
220
|
## Development
|
package/bin/cli.js
CHANGED
|
@@ -27,7 +27,7 @@ const VERSION = PKG.version;
|
|
|
27
27
|
const MCP_URL = 'https://mcp.memoryrouter.ai/mcp';
|
|
28
28
|
|
|
29
29
|
const HELP = `
|
|
30
|
-
${PKG.name} v${VERSION}
|
|
30
|
+
${PKG.name} v${VERSION}: deterministic memory for Claude Code
|
|
31
31
|
|
|
32
32
|
Usage:
|
|
33
33
|
npx memoryrouter-claude init [--key mk_xxx] [--local|--project|--user] [--yes]
|
|
@@ -37,7 +37,6 @@ Usage:
|
|
|
37
37
|
--user ~/.claude/settings.json (all projects)
|
|
38
38
|
--global Explicitly use personal/global memory instead of project memory
|
|
39
39
|
--include-global Recall project memory plus personal/global memory
|
|
40
|
-
--capture-subagents Capture subagent transcripts (off by default)
|
|
41
40
|
|
|
42
41
|
npx memoryrouter-claude doctor
|
|
43
42
|
Diagnose config migration, permissions, hooks, project scope, pending capture,
|
|
@@ -74,7 +73,6 @@ function parseArgs(argv) {
|
|
|
74
73
|
else if (value === '--local') args.scope = 'local';
|
|
75
74
|
else if (value === '--global') args.global = true;
|
|
76
75
|
else if (value === '--include-global') args.includeGlobal = true;
|
|
77
|
-
else if (value === '--capture-subagents') args.captureSubagents = true;
|
|
78
76
|
else if (value === '--yes' || value === '-y') args.yes = true;
|
|
79
77
|
else if (value === '--purge') args.purge = true;
|
|
80
78
|
else if (value === '--final') args.final = true;
|
|
@@ -137,7 +135,9 @@ async function cmdInit(args) {
|
|
|
137
135
|
cfg.apiKey = key;
|
|
138
136
|
if (args.global) cfg.memoryScope = 'global';
|
|
139
137
|
if (args.includeGlobal) cfg.includeGlobal = true;
|
|
140
|
-
|
|
138
|
+
// Automatic subagent transcript capture was removed in v2.1: delegated and
|
|
139
|
+
// intermediate chatter is never part of the deterministic turn contract.
|
|
140
|
+
cfg.captureSubagents = false;
|
|
141
141
|
cfg.lastInstalledVersion = VERSION;
|
|
142
142
|
cfg.lastInstalledAt = new Date().toISOString();
|
|
143
143
|
const file = settingsLib.settingsPathFor(scope, process.cwd());
|
|
@@ -152,14 +152,14 @@ async function cmdInit(args) {
|
|
|
152
152
|
console.log(`
|
|
153
153
|
Automatic engine:
|
|
154
154
|
SessionStart asynchronous project-vault warmup
|
|
155
|
-
UserPromptSubmit
|
|
156
|
-
Stop
|
|
157
|
-
StopFailure
|
|
158
|
-
PreCompact
|
|
159
|
-
PostCompact
|
|
155
|
+
UserPromptSubmit one durable typed prompt, then separate semantic recall
|
|
156
|
+
Stop one durable final user-visible assistant response
|
|
157
|
+
StopFailure retry pending prompt only; no synthetic final
|
|
158
|
+
PreCompact retry already-created pending events
|
|
159
|
+
PostCompact no summary capture; retry pending events only
|
|
160
160
|
SessionStart re-injection after compact/resume/fork
|
|
161
|
-
SubagentStop
|
|
162
|
-
SessionEnd
|
|
161
|
+
SubagentStop never captured
|
|
162
|
+
SessionEnd retry pending typed events
|
|
163
163
|
|
|
164
164
|
✓ Installed. Restart Claude Code or start a new session.
|
|
165
165
|
Run \`npx memoryrouter-claude doctor\` to verify the complete setup.
|
|
@@ -196,8 +196,12 @@ function inspectState() {
|
|
|
196
196
|
report.files++;
|
|
197
197
|
try {
|
|
198
198
|
const state = JSON.parse(fs.readFileSync(path.join(STATE_DIR, name), 'utf8'));
|
|
199
|
-
|
|
200
|
-
|
|
199
|
+
const turns = Array.isArray(state.turns) ? state.turns : [];
|
|
200
|
+
report.pending += turns.reduce((count, turn) => count
|
|
201
|
+
+ (turn.promptEvent && turn.promptEvent.status === 'pending' ? 1 : 0)
|
|
202
|
+
+ (turn.finalEvent && turn.finalEvent.status === 'pending' ? 1 : 0), 0);
|
|
203
|
+
if (turns.some((turn) => (turn.promptEvent && turn.promptEvent.status === 'conflict')
|
|
204
|
+
|| (turn.finalEvent && turn.finalEvent.status === 'conflict'))) report.blocked++;
|
|
201
205
|
} catch { report.blocked++; }
|
|
202
206
|
}
|
|
203
207
|
} catch { /* absent */ }
|
package/lib/api.js
CHANGED
|
@@ -49,9 +49,16 @@ function ingest(key, messages, sessionId, opts = {}) {
|
|
|
49
49
|
return request('POST', '/v1/memory/ingest', { key, body, timeoutMs: opts.timeoutMs || 15000 });
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
function ingestEvent(key, captureEvent, sessionId, opts = {}) {
|
|
53
|
+
const body = { capture_event: captureEvent };
|
|
54
|
+
if (sessionId) body.session_id = sessionId;
|
|
55
|
+
if (opts.model) body.model = opts.model;
|
|
56
|
+
return request('POST', '/v1/memory/ingest', { key, body, timeoutMs: opts.timeoutMs || 15000 });
|
|
57
|
+
}
|
|
58
|
+
|
|
52
59
|
function warmup(key, sessionId, opts = {}) {
|
|
53
60
|
const headers = sessionId ? { 'X-Session-ID': sessionId } : {};
|
|
54
61
|
return request('POST', '/v1/memory/warmup', { key, body: {}, headers, timeoutMs: opts.timeoutMs || 10000 });
|
|
55
62
|
}
|
|
56
63
|
|
|
57
|
-
module.exports = { request, stats, prepare, ingest, warmup, debug };
|
|
64
|
+
module.exports = { request, stats, prepare, ingest, ingestEvent, warmup, debug };
|
package/lib/hook-runner.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
// Deterministic Claude Code hook runtime.
|
|
3
|
-
//
|
|
4
|
-
//
|
|
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,12 @@ 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
|
|
26
|
-
const
|
|
27
|
-
const RECENT_KEY_LIMIT = 1500;
|
|
21
|
+
const MAX_EVENT_CHARS = 100000;
|
|
22
|
+
const RECENT_TURN_LIMIT = 50;
|
|
28
23
|
|
|
29
24
|
function debug(...args) {
|
|
30
25
|
if (process.env.MEMORYROUTER_DEBUG) console.error('[memoryrouter]', ...args);
|
|
@@ -65,12 +60,16 @@ function emitContext(eventName, context, maxChars = MAX_CONTEXT_CHARS) {
|
|
|
65
60
|
}
|
|
66
61
|
|
|
67
62
|
function stateKeyFor(input) {
|
|
68
|
-
|
|
69
|
-
return input.agent_id ? `${session}--agent-${input.agent_id}` : session;
|
|
63
|
+
return input.session_id || 'unknown';
|
|
70
64
|
}
|
|
71
65
|
|
|
72
66
|
function transcriptPathFor(input) {
|
|
73
|
-
return input.
|
|
67
|
+
return input.transcript_path || null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function transcriptSize(transcriptPath) {
|
|
71
|
+
if (!transcriptPath) return null;
|
|
72
|
+
try { return fs.statSync(transcriptPath).size; } catch { return null; }
|
|
74
73
|
}
|
|
75
74
|
|
|
76
75
|
function scopeSession(identity) {
|
|
@@ -124,258 +123,345 @@ async function retrieveContext(input, key, prompt, eventName) {
|
|
|
124
123
|
emitContext(eventName, context, cfg.maxContextChars);
|
|
125
124
|
}
|
|
126
125
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
const cfg = loadConfig();
|
|
131
|
-
const identity = deriveProjectIdentity(input, cfg);
|
|
132
|
-
if (disabled(cfg, identity)) return;
|
|
126
|
+
function normalizeEventContent(value) {
|
|
127
|
+
return compactText(cleanText(value), MAX_EVENT_CHARS);
|
|
128
|
+
}
|
|
133
129
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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;
|
|
155
|
+
}
|
|
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;
|
|
159
|
+
}
|
|
160
|
+
return state.turns;
|
|
161
|
+
}
|
|
162
|
+
|
|
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;
|
|
195
|
+
}
|
|
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);
|
|
203
|
+
}
|
|
204
|
+
state.turns = Array.from(retained.values()).sort((a, b) => a.sequence - b.sequence);
|
|
205
|
+
state.activeTurnId = turn.turnId;
|
|
206
|
+
return turn;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function findTurn(state, turnId) {
|
|
210
|
+
return ensureTurns(state).find((turn) => turn.turnId === turnId) || null;
|
|
211
|
+
}
|
|
142
212
|
|
|
143
|
-
|
|
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;
|
|
144
217
|
}
|
|
145
218
|
|
|
146
|
-
function
|
|
147
|
-
|
|
148
|
-
|
|
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);
|
|
149
223
|
}
|
|
150
224
|
|
|
151
|
-
function
|
|
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');
|
|
225
|
+
function captureEventPayload(turn, event) {
|
|
156
226
|
return {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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,
|
|
160
236
|
};
|
|
161
237
|
}
|
|
162
238
|
|
|
163
|
-
function
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
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;
|
|
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
|
+
);
|
|
201
244
|
}
|
|
202
245
|
|
|
203
|
-
async function
|
|
204
|
-
const
|
|
205
|
-
if (!
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
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;
|
|
250
|
+
try {
|
|
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);
|
|
212
260
|
return false;
|
|
213
261
|
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
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}`;
|
|
222
274
|
}
|
|
223
|
-
state.lastCaptureAt = Date.now();
|
|
224
|
-
state.lastAcceptedBatch = pending.batchId;
|
|
225
|
-
delete state.pendingCapture;
|
|
226
275
|
saveState(stateKey, state);
|
|
227
|
-
return
|
|
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;
|
|
276
|
+
return event.status === 'accepted';
|
|
236
277
|
}
|
|
237
278
|
|
|
238
|
-
async function
|
|
279
|
+
async function handleInject(input, key) {
|
|
280
|
+
const prompt = normalizeEventContent(input.prompt);
|
|
281
|
+
if (!prompt || !input.session_id) return;
|
|
239
282
|
const cfg = loadConfig();
|
|
240
283
|
const identity = deriveProjectIdentity(input, cfg);
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
284
|
+
if (disabled(cfg, identity)) return;
|
|
285
|
+
|
|
286
|
+
let turnId = null;
|
|
287
|
+
try {
|
|
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);
|
|
247
299
|
}
|
|
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
300
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
if (
|
|
277
|
-
|
|
278
|
-
|
|
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;
|
|
279
312
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
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];
|
|
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;
|
|
292
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
|
+
}
|
|
293
330
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
}
|
|
307
|
-
break;
|
|
308
|
-
}
|
|
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
|
+
}
|
|
309
343
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
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 });
|
|
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;
|
|
332
355
|
}
|
|
333
356
|
|
|
334
357
|
async function handleCapture(input, key) {
|
|
335
|
-
if (input.stop_hook_active) {
|
|
336
|
-
debug('stop_hook_active
|
|
358
|
+
if (input.stop_hook_active || input.agent_id) {
|
|
359
|
+
debug(input.agent_id ? 'subagent Stop ignored' : 'stop_hook_active: skipping capture');
|
|
337
360
|
return;
|
|
338
361
|
}
|
|
339
|
-
|
|
340
|
-
|
|
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;
|
|
341
366
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
367
|
+
try {
|
|
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
|
+
}
|
|
345
389
|
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
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);
|
|
399
|
+
}
|
|
349
400
|
}
|
|
350
401
|
|
|
351
|
-
async function
|
|
352
|
-
|
|
353
|
-
const summary = input.compact_summary;
|
|
354
|
-
if (!summary || typeof summary !== 'string' || !summary.trim()) return;
|
|
402
|
+
async function retryPendingEvents(input, key) {
|
|
403
|
+
if (!input.session_id || input.agent_id) return;
|
|
355
404
|
const cfg = loadConfig();
|
|
356
405
|
const identity = deriveProjectIdentity(input, cfg);
|
|
357
406
|
const captureEnabled = identity.projectConfig.captureEnabled ?? cfg.captureEnabled;
|
|
358
407
|
if (disabled(cfg, identity) || captureEnabled === false) return;
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
408
|
+
try {
|
|
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);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
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);
|
|
367
443
|
});
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
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);
|
|
373
460
|
}
|
|
374
461
|
|
|
375
462
|
async function handleReinject(input, key) {
|
|
376
463
|
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.';
|
|
464
|
+
const prompt = state.lastPrompt || 'Recall the most relevant recent project decisions and unresolved work.';
|
|
379
465
|
await retrieveContext(input, key, prompt, 'SessionStart');
|
|
380
466
|
}
|
|
381
467
|
|
|
@@ -399,7 +485,7 @@ async function handleSessionStart(input, key) {
|
|
|
399
485
|
|
|
400
486
|
async function runHook(kind) {
|
|
401
487
|
const wallClock = setTimeout(() => {
|
|
402
|
-
debug('wall-clock timeout
|
|
488
|
+
debug('wall-clock timeout: exiting 0');
|
|
403
489
|
process.exit(0);
|
|
404
490
|
}, kind === 'inject' || kind === 'reinject' ? 8000 : 27000);
|
|
405
491
|
wallClock.unref();
|
|
@@ -415,6 +501,7 @@ async function runHook(kind) {
|
|
|
415
501
|
case 'inject': await handleInject(input, key); break;
|
|
416
502
|
case 'capture': await handleCapture(input, key); break;
|
|
417
503
|
case 'capture-subagent': await handleSubagentCapture(input, key); break;
|
|
504
|
+
case 'failure': await handleFailure(input, key); break;
|
|
418
505
|
case 'flush': await handleFlush(input, key); break;
|
|
419
506
|
case 'compact': await handleCompact(input, key); break;
|
|
420
507
|
case 'reinject': await handleReinject(input, key); break;
|
|
@@ -431,14 +518,17 @@ module.exports = {
|
|
|
431
518
|
runHook,
|
|
432
519
|
handleInject,
|
|
433
520
|
handleCapture,
|
|
521
|
+
handleFailure,
|
|
434
522
|
handleFlush,
|
|
435
523
|
handleSubagentCapture,
|
|
436
524
|
handleCompact,
|
|
437
525
|
handleReinject,
|
|
438
526
|
handleSessionStart,
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
527
|
+
retryPendingEvents,
|
|
528
|
+
captureEventPayload,
|
|
529
|
+
createOrResumePromptTurn,
|
|
530
|
+
idempotencyKeyFor,
|
|
531
|
+
turnIdFor,
|
|
442
532
|
mergeContexts,
|
|
443
533
|
emitContext,
|
|
444
534
|
stateKeyFor,
|
package/lib/settings.js
CHANGED
|
@@ -6,7 +6,7 @@ const path = require('path');
|
|
|
6
6
|
const os = require('os');
|
|
7
7
|
|
|
8
8
|
const OURS_RE = /memoryrouter/i;
|
|
9
|
-
const HOOK_RE = /\bhook (inject|capture|capture-subagent|flush|compact|reinject|session-start)\b/;
|
|
9
|
+
const HOOK_RE = /\bhook (inject|capture|capture-subagent|failure|flush|compact|reinject|session-start)\b/;
|
|
10
10
|
|
|
11
11
|
function commandHook(bin, kind, timeout, extra = {}) {
|
|
12
12
|
return { type: 'command', command: `${bin} hook ${kind}`, timeout, ...extra };
|
|
@@ -26,14 +26,13 @@ function buildHookConfig(bin) {
|
|
|
26
26
|
],
|
|
27
27
|
UserPromptSubmit: [{ hooks: [commandHook(bin, 'inject', 10)] }],
|
|
28
28
|
Stop: [{ hooks: [commandHook(bin, 'capture', 30)] }],
|
|
29
|
-
StopFailure: [{ hooks: [commandHook(bin, '
|
|
29
|
+
StopFailure: [{ hooks: [commandHook(bin, 'failure', 30)] }],
|
|
30
30
|
PreCompact: [
|
|
31
31
|
{ matcher: 'auto|manual', hooks: [commandHook(bin, 'flush', 30)] },
|
|
32
32
|
],
|
|
33
33
|
PostCompact: [
|
|
34
34
|
{ matcher: 'auto|manual', hooks: [commandHook(bin, 'compact', 30)] },
|
|
35
35
|
],
|
|
36
|
-
SubagentStop: [{ hooks: [commandHook(bin, 'capture-subagent', 30)] }],
|
|
37
36
|
SessionEnd: [{ hooks: [commandHook(bin, 'flush', 30)] }],
|
|
38
37
|
};
|
|
39
38
|
}
|
|
@@ -101,6 +100,7 @@ function writeSettings(file, settings) {
|
|
|
101
100
|
const existingMode = (() => { try { return fs.statSync(file).mode & 0o777; } catch { return 0o600; } })();
|
|
102
101
|
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
103
102
|
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n', { mode: existingMode });
|
|
103
|
+
try { fs.chmodSync(tmp, existingMode); } catch { /* windows best-effort */ }
|
|
104
104
|
fs.renameSync(tmp, file);
|
|
105
105
|
try { fs.chmodSync(file, existingMode); } catch { /* windows best-effort */ }
|
|
106
106
|
}
|
package/lib/transcript.js
CHANGED
|
@@ -214,6 +214,60 @@ function contentToText(content) {
|
|
|
214
214
|
return content.filter((b) => b && b.type === 'text').map((b) => cleanText(b.text)).filter(Boolean).join('\n');
|
|
215
215
|
}
|
|
216
216
|
|
|
217
|
+
/**
|
|
218
|
+
* Return only a completed, main-chain, user-visible final assistant message.
|
|
219
|
+
*
|
|
220
|
+
* A transcript fallback is intentionally conservative:
|
|
221
|
+
* - malformed/partially-written JSON blocks fallback entirely;
|
|
222
|
+
* - sidechains, tool results, thinking, and binary blocks are ignored;
|
|
223
|
+
* - an assistant record containing tool_use is intermediate and cannot be final;
|
|
224
|
+
* - the last assistant record after the turn boundary must be text-only;
|
|
225
|
+
* - when no reliable byte boundary exists, the matching user prompt establishes
|
|
226
|
+
* the boundary. If that prompt cannot be found, no old answer is guessed.
|
|
227
|
+
*/
|
|
228
|
+
function finalAssistantFromTranscript(transcriptPath, options = {}) {
|
|
229
|
+
let data;
|
|
230
|
+
try { data = fs.readFileSync(transcriptPath); } catch { return null; }
|
|
231
|
+
|
|
232
|
+
const requestedOffset = Number.isInteger(options.afterOffset) && options.afterOffset >= 0
|
|
233
|
+
? options.afterOffset
|
|
234
|
+
: null;
|
|
235
|
+
const canUseOffset = requestedOffset !== null && requestedOffset <= data.length;
|
|
236
|
+
const parsed = parseBuffer(canUseOffset ? data.subarray(requestedOffset) : data, canUseOffset ? requestedOffset : 0);
|
|
237
|
+
if (parsed.blockedOffset !== null) return null;
|
|
238
|
+
|
|
239
|
+
const prompt = cleanText(options.prompt);
|
|
240
|
+
let boundaryEstablished = canUseOffset;
|
|
241
|
+
let lastAssistant = null;
|
|
242
|
+
|
|
243
|
+
for (const record of parsed.records) {
|
|
244
|
+
if (record.ignored) continue;
|
|
245
|
+
const raw = data.subarray(record.startOffset, record.endOffset).toString('utf8').trim();
|
|
246
|
+
let obj;
|
|
247
|
+
try { obj = JSON.parse(raw); } catch { return null; }
|
|
248
|
+
if (!obj || obj.isSidechain || !obj.message) continue;
|
|
249
|
+
const msg = obj.message;
|
|
250
|
+
|
|
251
|
+
if (!boundaryEstablished) {
|
|
252
|
+
if (msg.role === 'user' && prompt && contentToText(msg.content) === prompt) {
|
|
253
|
+
boundaryEstablished = true;
|
|
254
|
+
}
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (msg.role !== 'assistant') continue;
|
|
259
|
+
const blocks = Array.isArray(msg.content) ? msg.content : null;
|
|
260
|
+
const hasToolUse = Boolean(blocks && blocks.some((block) => block && block.type === 'tool_use'));
|
|
261
|
+
const text = contentToText(msg.content);
|
|
262
|
+
// Track every assistant record. If the final record is a tool call, there is
|
|
263
|
+
// no proven final user-visible response yet, even if an earlier text exists.
|
|
264
|
+
lastAssistant = !hasToolUse && text ? text : null;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (!boundaryEstablished || !lastAssistant) return null;
|
|
268
|
+
return { content: lastAssistant, blockedOffset: null };
|
|
269
|
+
}
|
|
270
|
+
|
|
217
271
|
// Legacy compatibility for callers/tests. Unlike the old parser, lastLine only
|
|
218
272
|
// advances across valid records; tool activity is represented in compact text.
|
|
219
273
|
function parseTranscript(jsonlText, afterLine = -1) {
|
|
@@ -244,6 +298,7 @@ module.exports = {
|
|
|
244
298
|
compactText,
|
|
245
299
|
stableJson,
|
|
246
300
|
contentToText,
|
|
301
|
+
finalAssistantFromTranscript,
|
|
247
302
|
normalizeRecord,
|
|
248
303
|
parseBuffer,
|
|
249
304
|
readTranscriptDelta,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memoryrouter-claude",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "Deterministic, project-scoped persistent memory for Claude Code: automatic hook retrieval/capture plus an optional OAuth MCP control surface.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "John Rood <john@memoryrouter.ai>",
|