Stop hook receives stale transcript - race condition between file write and hook invocation
Bug Description
The stop hook is invoked before the transcript file write is fully flushed/visible to the hook process. The hook reads stale data, missing the most recent assistant message.
Reproduction
- Configure a stop hook that reads
transcript_pathand inspects the last assistant message - The hook uses synchronous file read (
fs.readFileSync) on the transcript path - The hook does not see the current/most recent assistant message - only previous messages
Observed Behavior
The hook consistently reads transcript data that is one message behind. The current assistant message that triggered the stop hook is not present in the file when the hook reads it.
Expected Behavior
The stop hook should receive a transcript file that includes the complete current assistant message. The file write should be flushed/synced before the hook process is spawned.
Likely Root Cause
The hook process is spawned before the transcript file I/O completes. Node.js file writes are buffered - spawning the hook process immediately after the write call but before flush means the hook reads stale data.
Suggested Fix
Ensure fsync/flush of the transcript file completes before invoking the stop hook process. Alternatively, pass the current message content directly to the hook via stdin rather than relying solely on file reads.
Environment
- Claude Code version: 2.0.76
- Platform: Linux
- Node.js runtime