Skip to content

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.

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/sh
set -eu
event="$1"
fifo='/tmp/claude-p-4242-…/events.fifo'
nonce='9f2c…'
[ -p "$fifo" ] || exit 1
payload="$(cat)"
printf '%s\t%s\t%s\n' "$nonce" "$event" "$payload" >> "$fifo"
exit 0

The 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.

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.

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.

t = 0 ms +35 ms +20 ms +1000 ms (20×) Hook FIFO transcript.jsonl driver.run() Stop arrives carries last_assistant_message assistant line hits disk + usage tokens & turn count try #1: miss sleep 20 ms try #2: parsed & matched emit result → terminate fallback (if exhausted) synthesize from Stop payload
Stop can arrive before Claude flushes the last assistant JSONL line. driver.run() pumps and parses the transcript up to 20×20 ms (daemon: 30×25 ms), exiting early when the text matches Stop, before falling back to last_assistant_message.

driver.run() handles both the flush race and --resume isolation with one byte offset:

~/.claude/projects/…/<session-id>.jsonl Historical turns (skipped) bytes [0 .. pre_prompt_transcript_offset) Current turn (tailed & parsed) bytes [pre_prompt_transcript_offset .. EOF) stat(transcript_path).size Recorded before typePrompt(); Tailer starts here On Stop: pump + parse retries 20×20 ms (early exit on Stop-text match)
On --resume or --continue, claude-p snapshots the transcript byte size before typing the new prompt and parses only [offset..EOF), so historical turns can never satisfy the current turn.
  1. Before submitting the prompt, driver.run() records pre_prompt_transcript_offset = stat(transcript_path).size.
  2. If Stop reports a different transcript_path than SessionStart did, the driver resets the offset to 0 and reopens the tailer.
  3. After Stop is confirmed (at once on stop_hook_summary with preventedContinuation: false, else after 150 ms, or 2000 ms with --extra-hook Stop=...), one pump-and-parse loop runs up to 20 × 20 ms (daemon: 30 × 25 ms). Each attempt streams new lines in stream-json mode, then parses from the offset. It exits early when the parsed text matches Stop’s last_assistant_message; after the last attempt a mismatch is replaced with Stop’s text.
  4. On StopFailure it parses the transcript once, keeps usage and num_turns, forces is_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.
  5. If retries still find no assistant message on disk, it synthesizes a Summary from Stop’s last_assistant_message and session_id; otherwise it returns RunError.TranscriptUnavailable.

Transcript parsing rules (src/transcript.zig)

Section titled “Transcript parsing rules (src/transcript.zig)”
  • Accepts both sessionId (real Claude Code transcripts) and session_id (legacy stream-json).
  • Skips any record whose uuid was already seen in the slice, so a rewritten or replayed record never duplicates assistant text.
  • Concatenates all {"type":"text"} blocks in each assistant message’s message.content array; the last assistant message wins for final_text.
  • Sums input_tokens, output_tokens, cache_read_input_tokens, and cache_creation_input_tokens across assistant entries in the parsed slice, counting each message.id once (the last usage seen for that id wins). Entries without an id each count.
  • Marks the result is_error: true with subtype: "error_during_execution" when an assistant entry has isApiErrorMessage: true or 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, its result, is_error, num_turns, total_cost_usd, and duration_api_ms fields override prior aggregates.