Hooks and Transcripts
claude-p treats Claude Code’s hook events and session JSONL transcript as the source of truth for lifecycle state and assistant output.
Per-run hook harness (src/hook.zig)
Section titled “Per-run hook harness (src/hook.zig)”Each run creates a private directory under $TMPDIR (default /tmp) with mode 0700 and a name carrying 64 random bits:
$TMPDIR/claude-p-<pid>-<rand>/├── events.fifo (mode 0600, named pipe)└── hook.sh (mode 0700, POSIX /bin/sh relay)hook.sh embeds the FIFO path and a per-run nonce (16 lowercase hex characters) as single-quoted shell words. It reads the hook JSON payload from stdin and appends one line <nonce>\t<event>\t<json>\n to the FIFO:
#!/bin/shset -euevent="$1"fifo='/tmp/claude-p-4242-…/events.fifo'nonce='9f2c…'[ -p "$fifo" ] || exit 1payload="$(cat)"printf '%s\t%s\t%s\n' "$nonce" "$event" "$payload" >> "$fifo"exit 0The script reads no environment variable to find the FIFO, and CLAUDE_P_FIFO is not exported to the child; buildChildEnv drops an inherited one. If the embedded path is no longer a FIFO, the script exits 1. hook.parseLineWithNonce drops any line whose nonce does not match the run, so a foreign writer cannot inject events.
hook.createWithOptions() serializes an inline --settings JSON object registering hook.sh at index 0 for five events (matcher "*"):
| Event | Used for |
|---|---|
SessionStart |
Ready signal; transcript_path and session_id. |
UserPromptSubmit |
Prompt delivery confirmation and truncation check. |
Stop |
Turn complete; transcript_path, last_assistant_message, session_id. |
StopFailure |
Turn ended in an API error. Both modes parse the transcript first to keep usage, force is_error: true, and use the hook’s error text. One-shot exits 1; the daemon’s turn result carries "error":"stop_failure". |
PermissionRequest |
Claude Code is about to show a permission prompt that no one can answer. One-shot mode returns RunError.PermissionPromptBlocked (exit 2) at once. The daemon sends ESC, emits a turn-ending type:"result" frame with subtype: "error_during_execution" and error: "permission_prompt_blocked", and returns to idle. |
Any --extra-hook entries are appended after index 0. Any --setting-json top-level keys except "hooks" are merged at the root. --setting-json is rejected with InvalidExtraSettings when it is not a JSON object, nests deeper than 128 levels, or sets "disableAllHooks": true (which would silence the relay hooks). Script paths with spaces or shell metacharacters are single-quoted automatically.
HookHarness.deinit() runs via defer and deletes the FIFO, script, and temp directory. ~/.claude/ is never touched.
Why events.fifo opens before fork
Section titled “Why events.fifo opens before fork”On POSIX systems, opening a FIFO for writing blocks until a reader has opened it. Both driver.zig and daemon.zig open events.fifo with O_RDONLY | O_NONBLOCK before calling zmux.NativeSession.create(), guaranteeing a reader descriptor exists from millisecond zero.
Live pread tailing (src/stream.zig)
Section titled “Live pread tailing (src/stream.zig)”In stream-json mode and daemon mode, stream.Tailer follows Claude’s live transcript file using std.posix.pread(fd, buf, self.pos). Keeping its own cursor leaves the file offset untouched, and an internal partial buffer holds trailing fragments until \n arrives so downstream readers never see torn JSON. A partial line that grows past 16 MiB (default_max_partial_bytes) is dropped and skipped through its newline, which bounds memory on a runaway record.
The Stop-vs-flush race and resume isolation
Section titled “The Stop-vs-flush race and resume isolation”Claude Code can fire the Stop hook a few milliseconds before the final assistant JSONL line hits disk.
Stop is provisional for 150 ms. A blocking Stop hook (user-supplied through --extra-hook or settings) can make Claude continue the turn, so both modes wait this confirmation window before ending it. A later Stop, which Claude Code sends with stop_hook_active: true after the continuation, replaces the first and restarts the window. New assistant activity in the transcript after the provisional Stop discards it. The steps below run once Stop is confirmed.
driver.run() handles both the flush race and --resume isolation with one byte offset:
- Before submitting the prompt,
driver.run()recordspre_prompt_transcript_offset = stat(transcript_path).size. - If
Stopreports a differenttranscript_paththanSessionStartdid, the driver resets the offset to0and reopens the tailer. - After
Stopis confirmed (at once onstop_hook_summarywithpreventedContinuation: false, else after150 ms, or2000 mswith--extra-hook Stop=...), one pump-and-parse loop runs up to20 × 20 ms(daemon:30 × 25 ms). Each attempt streams new lines instream-jsonmode, then parses from the offset. It exits early when the parsed text matches Stop’slast_assistant_message; after the last attempt a mismatch is replaced with Stop’s text. - On
StopFailureit parses the transcript once, keepsusageandnum_turns, forcesis_error: true, and uses the hook’s error text. The daemon adds"error":"stop_failure". With no parsable transcript it synthesizes the error summary from the hook payload. - If retries still find no assistant message on disk, it synthesizes a
Summaryfrom Stop’slast_assistant_messageandsession_id; otherwise it returnsRunError.TranscriptUnavailable.
Transcript parsing rules (src/transcript.zig)
Section titled “Transcript parsing rules (src/transcript.zig)”- Accepts both
sessionId(real Claude Code transcripts) andsession_id(legacy stream-json). - Skips any record whose
uuidwas already seen in the slice, so a rewritten or replayed record never duplicates assistant text. - Concatenates all
{"type":"text"}blocks in eachassistantmessage’smessage.contentarray; the last assistant message wins forfinal_text. - Sums
input_tokens,output_tokens,cache_read_input_tokens, andcache_creation_input_tokensacross assistant entries in the parsed slice, counting eachmessage.idonce (the last usage seen for that id wins). Entries without an id each count. - Marks the result
is_error: truewithsubtype: "error_during_execution"when an assistant entry hasisApiErrorMessage: trueor the<synthetic>model. - Skips malformed lines (including a torn leading fragment when an offset lands mid-line) without aborting.
- When a
{"type":"result"}line exists in the slice, itsresult,is_error,num_turns,total_cost_usd, andduration_api_msfields override prior aggregates.