feat(776): every hook reports that it fired, and the report is measured

In this harness version only `Stop` hooks emit a structured transcript record.
`PreToolUse` and `PostToolUse` hooks leave no durable execution trace — which is
every guard this repo relies on. #773 §5.4 could therefore only count filename
mentions in settings dumps, i.e. inference, so a silently broken hook looked
identical to a working one indefinitely.

Each hook now sources one shared sink, `scripts/hook-fire-log.sh`, and records a
`fire` record on entry and an `exit` record carrying its status and decision. The
decision is parsed from the bytes the hook actually emitted rather than declared
by the author: Claude hooks always exit 0 and decide by printing JSON, so stdout
is diverted and replayed; git hooks decide by exit code and stream their output,
so theirs is left alone. That avoided ~40 edits inside pretooluse-merge-consent
and records what the harness sees rather than what the author meant.

The instrumentation sits in the stdin/stdout path of the most authoritative
guards in the repo, so transparency is the load-bearing claim, not coverage:
test_instrumentation_changes_NOTHING_the_harness_can_see drives every hook with
and without it over a payload matrix reaching each hook's deciding branch, and
demands byte-equal stdout and equal exit status. It shipped with two defects that
only that shape catches — `out=$(cat f)` stripping a trailing newline, and an
unconditional stdin slurp that hangs on a TTY and would have frozen every
interactive `git commit`. Both are now pinned, the second through a real pty.

fixes #776

Decisions-Edit: yes
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-14 18:52:20 +02:00
co-authored by Claude Opus 5
parent 84165ab755
commit 56ed794ff7
18 changed files with 1015 additions and 4 deletions
+6
View File
@@ -4,6 +4,12 @@
# body-diff, CI). This shim runs the structural validator over the working tree; the body-diff/no-
# vanish checks run in CI where a base/head is available. Fail-open on any tooling trouble.
set -uo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# git hook: decides by exit code, and its stdout is live progress text.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin decisions-guard "" stream || true
cd "$(git rev-parse --show-toplevel)" || exit 0
command -v python3 >/dev/null 2>&1 || exit 0 # no python -> fail-open
PYTHONPATH=. python3 scripts/decisions_validate.py
+6
View File
@@ -17,6 +17,12 @@
# This is a reminder, never a hard gate — `start` only injects context; `finish` is a one-shot Stop nudge.
set -euo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin design-sync-reminder "${1:-}" capture || true
UI_RE='(^|/)web/src/.*\.(tsx|css)$'
TEST_RE='\.test\.(tsx|ts)$'
@@ -4,6 +4,12 @@
# a sibling worktree another session created apart from this session's own.
# Fail-safe: any parse trouble → do nothing (the guard stays fail-open without a marker).
set -euo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin posttooluse-worktree-marker "" capture || true
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
cwd=$(printf '%s' "$input" | jq -r '.cwd // ""' 2>/dev/null || true)
@@ -15,6 +15,12 @@
# no origin/main, HEAD unresolved -> allow. Deliberate escape: ETV_ALLOW_DIRTY_PUSH=1.
set -uo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# git hook: decides by exit code, and its stdout is live progress text.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin prepush-clean-worktree-check "" stream || true
[ "${ETV_ALLOW_DIRTY_PUSH:-}" = "1" ] && exit 0
git rev-parse --git-dir >/dev/null 2>&1 || exit 0
+6
View File
@@ -12,6 +12,12 @@
# Auth (never committed): ETV_GITEA_TOKEN or ETV_GITEA_BASICAUTH; ETV_GITEA_URL overrides the base.
set -euo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# git hook: decides by exit code, and its stdout is live progress text.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin prepush-donewhen "" stream || true
# git passes "<localref> <localsha> <remoteref> <remotesha>" lines on stdin.
refs=$(cat || true)
printf '%s\n' "$refs" | grep -q 'refs/heads/main' || exit 0 # only gate pushes to main
+6
View File
@@ -9,6 +9,12 @@
# a positively-proven "behind origin/main". Deliberate exception: ETV_SKIP_REBASE_CHECK=1.
set -uo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# git hook: decides by exit code, and its stdout is live progress text.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin prepush-rebase-check "" stream || true
[ "${ETV_SKIP_REBASE_CHECK:-}" = "1" ] && exit 0
git rev-parse --git-dir >/dev/null 2>&1 || exit 0
+6
View File
@@ -40,6 +40,12 @@
# Fail-open by design: any parse trouble -> allow (exit 0, no output).
set -uo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin pretooluse-agent-model "" capture || true
input=$(cat)
tool=$(printf '%s' "$input" | jq -r '.tool_name // ""' 2>/dev/null || true)
+6
View File
@@ -3,6 +3,12 @@
# The historic 8-9-way crash was RAM starvation, not CPU load; gate on FREE RAM.
# Fail-open: if memory_pressure is unavailable/unparsable → allow.
set -euo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin pretooluse-agent-ram "" capture || true
free=$(memory_pressure -Q 2>/dev/null | grep -oE 'free percentage: [0-9]+' | grep -oE '[0-9]+' || true)
[ -z "${free:-}" ] && exit 0
+6
View File
@@ -2,6 +2,12 @@
# PreToolUse / Bash — deny commands that violate a HARD RULE.
# Fail-open: any parse trouble → allow (exit 0 with no output).
set -euo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin pretooluse-bash-guard "" capture || true
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
+6
View File
@@ -18,6 +18,12 @@
# the reason a commit can't happen; CI is still the backstop.
set -uo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin pretooluse-bom-guard "" capture || true
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
[ -n "$cmd" ] || exit 0
@@ -40,6 +40,12 @@
# Gitea auth from env (never committed): ETV_GITEA_TOKEN (a token) OR ETV_GITEA_BASICAUTH (user:pass).
# ETV_GITEA_URL overrides the base (default: the LAN instance; a LAN address, not a secret).
set -euo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin pretooluse-merge-consent "" capture || true
input=$(cat)
decide() { # $1=grant|allow|deny|ask $2=reason
+6
View File
@@ -2,6 +2,12 @@
# PreToolUse / browser-navigate — deny opening download/stream endpoints in a tab
# (they hang the MCP session; curl them instead). Fail-open on parse trouble.
set -euo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin pretooluse-nav-guard "" capture || true
input=$(cat)
url=$(printf '%s' "$input" | jq -r '.tool_input.url // ""' 2>/dev/null || true)
@@ -8,6 +8,12 @@
# So the main tree (never marked) and pre-convention worktrees (no marker) are unaffected;
# only a commit/merge into another session's marked worktree is blocked.
set -euo pipefail
# ersatztv#776 — report that this hook fired. MUST precede any stdin read.
# Claude hook: decides by printed JSON, so stdout is captured.
ETV_HOOK_FIRE_LIB="${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true
etv_hook_fire_begin pretooluse-worktree-guard "" capture || true
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
cwd=$(printf '%s' "$input" | jq -r '.cwd // ""' 2>/dev/null || true)
+1
View File
@@ -196,6 +196,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `testing.enumerating-guard-identity-not-position` | A guard that cross-checks a hand-reviewed registry against call sites discovered across the whole repo must key each entry on properties INTRINSIC to the site — file, kind, and the value source text — and never on its absolute line or column. A registry keyed on position is a function of every other file in the repo, so a branch that never touches the guard can invalidate it; and because each PR is green against its own base, that failure is structurally invisible pre-merge and lands on `main` after review and after the merge gate. Dropping the position keeps every mutation the guard exists for — a NEW site, a REMOVED site and a CHANGED value each still fail, since each changes the identity multiset — and costs exactly ONE case, which must be stated rather than implied: a SAME-IDENTITY SUBSTITUTION within one file (delete a registered site, add a different unreviewed one with the same kind and value token, net-zero count) now passes. A REPORTED failure still prints the discovered line:column, because identity and diagnostics need not share a format. Comparison stays a MULTISET count rather than set membership, so two sites in one file sharing an identity must be discovered exactly that many times and a third occurrence still fails. A SCANNER test that asserts real AST positions against FIXED inline fixtures is the opposite case and keeps its line/column identity — it has no churn, because its input does not move. | 2026-07-27 | [link](records/testing/enumerating-guard-identity-not-position.md) |
| `testing.guard-derives-population-from-source` | A guard that asserts a COMPLETENESS property enumerates its population from a machine-readable authoritative source — the enum, the generated OpenAPI document, the parsed workflow YAML, the provider list — and asserts SET EQUALITY in BOTH directions against it. It may not narrow that population with a filter, a `Where`, a `grep` or an early `continue` before the assertion, because a filter cannot see the member that is MISSING: the member whose absence is the defect is precisely the one the predicate excludes. A hand-written literal list of members is the same defect in slower motion — a filter frozen at authoring time, correct on the day it was written and unable to report the day it stopped being. Two boundaries bound the rule rather than weaken it. FIRST, filtering to select the SUBJECT of a PER-MEMBER property is legitimate and is not this defect: the excluded members satisfy the property vacuously, so the filtered walk and the whole walk assert the same thing (`ToolCatalogTests.Every_Query_Parameter_Should_Be_A_Declared_Property` filters to tools that declare query parameters, and a tool declaring none has nothing to check). The defect is filtering the population before a COMPLETENESS claim, which is what makes an absent member unrepresentable (#757 filtered on `QueryParameters is {Count: > 0}` and so could not see a tool that should have declared one and did not). SECOND, a population of VALUES always has an external authoritative source and this rule applies directly; a population of SITES IN CODE has no such list, needs find-all-references tooling, and is tracked separately in #777 — do not stretch a set-equality assertion over it. Distinguish the guard SCOPE (which subsystems it covers — a reviewed policy choice, legitimately hand-written) from the guard POPULATION (the members inside that scope — always derived). When the scope itself MIRRORS an authoritative source, the mirror needs its own equality check or a dated staleness marker, or the guard is complete within a scope that has silently gone stale. The canonical worked example in this repo is `ToolCatalogTests.Every_Tool_Should_Declare_Exactly_Its_OpenApi_Query_Parameters`; the canonical residual gap is `MARKED_JOBS` in `scripts/tests/test_ci_dropped_step_guard.py`. | 2026-08-13 | [link](records/testing/guard-derives-population-from-source.md) |
| `testing.guard-ships-with-mutation-proof` | A guard is not considered tested because a test involving it passes. It ships with a MUTATION PROOF: remove or disarm THAT GUARD'S CLAUSE ALONE, and a NAMED test must go red. ONE NAMED EXCEPTION, with its limits, because the rule degenerates without it: where the guard IS a test (a checker enforcing a repo invariant, with no separate script behind it), disarming it makes it ABSENT rather than red, so the proof is the contrapositive — INTRODUCE THE DEFECT THE GUARD EXISTS TO CATCH into an isolated copy of the guarded artifact, and the named test must go red. That is a mutation of the guarded SYSTEM rather than of the assertion, and it is admissible ONLY for checker-guards and ONLY when the mutation was executed and witnessed. It is NOT a licence to grade an ordinary script-guard MUTATION for having a bad-input test: feeding a script an input its clause rejects is BEHAVIOUR-ONLY, which is what three rows were regraded for. A file-level grade under this exception covers the clause its cited case actually mutates, not every assertion that later lands in the same file; clause-level grading is tracked in #790. Three things this excludes, each of which has already shipped here as a green suite over a dead check. FIRST, a behavioural test — one that feeds the guard a good input and a bad input and checks it passes and fails — proves the guard REACTS, never that it is LOAD-BEARING; #685 had two guards on one condition where deleting either left the whole suite green while every behavioural test passed. SECOND, mutating the WHOLE FILE does not count (#510): a whole-file revert cannot show that a test reaches a particular clause, so the mutation must target the clause. THIRD, the guard being WIRED is not the guard RUNNING — #631's suite was invoked by no CI job, #751's step was dropped by the runner and the job reported success in 6s against a normal 14-17s, and #719's new logic was never connected to stdin. Every guard also carries an ANTI-VACUITY assertion, because the characteristic failure of a completeness check is reporting that it proved everything while its population was empty. Mechanical enforcement is possible for the BOOKKEEPING and not for the JUDGEMENT, and the split is the decision: `docs/guard-inventory.md` lists every guard file with its Kind, its Proof class (`MUTATION`/`BEHAVIOUR-ONLY`/`NONE`) and a `file::function` ref, and `scripts/tests/test_guard_inventory.py` derives the guard population from the filesystem and the call sites, asserts SET EQUALITY against the rows, and resolves every claimed ref to a real `def`. So a new guard cannot ship unclassified and a renamed test cannot leave a row silently claiming coverage. What stays with review, and is stated rather than papered over: nothing checks that a row claiming `MUTATION` is telling the truth. | 2026-08-13 | [link](records/testing/guard-ships-with-mutation-proof.md) |
| `testing.hook-reports-its-own-execution` | Every script in `.claude/hooks/` sources `scripts/hook-fire-log.sh` and calls `etv_hook_fire_begin <its-own-name> <label> <capture\|stream>` as its FIRST act, before anything reads stdin. Two records are appended per invocation — a `fire` record on entry and an `exit` record carrying the exit status and the decision — to a session-scoped JSONL log. THE DECISION IS READ FROM WHAT THE HOOK ACTUALLY EMITTED, never declared by the hook author: Claude Code hooks (`capture` mode) always exit 0 and communicate by PRINTING JSON, so their stdout is diverted and replayed, and the recorded decision is parsed from those bytes; git hooks (`stream` mode) decide by EXIT CODE and their stdout is live progress text a human is watching, so it is not diverted and the decision is the status. That split is not a tuning knob — capturing a slow pre-push hook's output would hold it back until the end and read as a hang, and inferring a git hook's decision from absent JSON would put the report back into the guessing business this record exists to end. The population is DERIVED from `.claude/hooks/*.sh` by `scripts/tests/test_hook_fire_log.py`, so a new hook is uninstrumented-and-red rather than silently unobserved, and the report lists every hook that EXISTS rather than every hook that appears in the log — a report built from the log alone can only show hooks that fired, which makes the never-fired hook, the one finding worth having, invisible. THE INSTRUMENTATION MUST BE INVISIBLE TO THE HARNESS, and this is the load-bearing half: it sits in the stdin and stdout path of the most authoritative guards in the repo, so a differential test drives EVERY hook with and without it over a payload matrix and demands byte-equal stdout and equal exit status. It fails OPEN in exactly one direction — if the log cannot be written the hook behaves exactly as before — because observability that breaks a guard is worse than the blindness it replaces. Two mechanical traps are pinned by tests rather than left to care: stdout must be replayed from the FILE, since `out=$(cat f)` strips trailing newlines and delivers a guard's JSON one byte short with no parser anywhere to complain; and stdin must never be slurped when it is a TTY, because an interactive `git commit` hands its hooks a terminal and `cat` would block forever, hanging the commit the instrumentation was added to observe. | 2026-08-14 | [link](records/testing/hook-reports-its-own-execution.md) |
| `testing.live-e2e-prepush-timing` | Run live-E2E via `scripts/e2e-local.sh` before pushing a write-path or UI change, and exercise download endpoints with curl, never a browser tab. | 2026-07-21 | [link](records/testing/live-e2e-prepush-timing.md) |
| `testing.playwright-mcp-download-and-recovery` | In Playwright-MCP E2E, fetch file-download endpoints with curl — never a browser tab or `window.open` — and if browser tools stall repeatedly, `pkill -f ms-playwright-mcp` and drive a fresh session. | 2026-07-21 | [link](records/testing/playwright-mcp-download-and-recovery.md) |
| `testing.scripted-playout-golden-deferred` | The `PlayoutBuildGoldenTests` in-memory golden net covers Sequential (YAML) as of #381. Scripted's *end-to-end pipeline* is excluded — `ScriptedPlayoutBuilder` runs a user-authored external program that drives the engine over HTTP loopback, which the in-memory harness can't pin — so that full-pipeline (integration) harness is deferred to #563. But the scheduling *behavior* those scripts drive lives entirely in the in-process `SchedulingEngine` (the `ScriptedScheduleController` is a 1:1 pass-through to it), which IS directly unit/golden-testable; the earlier "Scripted is un-golden-able by construction" framing overstated the constraint by conflating transport with engine. #395 extracts that shared switch to `ContentEnumeratorBuilder` and adds a direct regression net (`ContentEnumeratorBuilderTests`) over it. | 2026-07-22 | [link](records/testing/scripted-playout-golden-deferred.md) |
@@ -0,0 +1,70 @@
---
key: testing.hook-reports-its-own-execution
title: '2026-08-14 — every hook records that it fired and what it decided, through one shared sink (#776)'
status: active
since: '2026-08-14'
supersedes: none
superseded-by: none
rule: 'Every script in `.claude/hooks/` sources `scripts/hook-fire-log.sh` and calls `etv_hook_fire_begin <its-own-name> <label> <capture|stream>` as its FIRST act, before anything reads stdin. Two records are appended per invocation — a `fire` record on entry and an `exit` record carrying the exit status and the decision — to a session-scoped JSONL log. THE DECISION IS READ FROM WHAT THE HOOK ACTUALLY EMITTED, never declared by the hook author: Claude Code hooks (`capture` mode) always exit 0 and communicate by PRINTING JSON, so their stdout is diverted and replayed, and the recorded decision is parsed from those bytes; git hooks (`stream` mode) decide by EXIT CODE and their stdout is live progress text a human is watching, so it is not diverted and the decision is the status. That split is not a tuning knob — capturing a slow pre-push hook''s output would hold it back until the end and read as a hang, and inferring a git hook''s decision from absent JSON would put the report back into the guessing business this record exists to end. The population is DERIVED from `.claude/hooks/*.sh` by `scripts/tests/test_hook_fire_log.py`, so a new hook is uninstrumented-and-red rather than silently unobserved, and the report lists every hook that EXISTS rather than every hook that appears in the log — a report built from the log alone can only show hooks that fired, which makes the never-fired hook, the one finding worth having, invisible. THE INSTRUMENTATION MUST BE INVISIBLE TO THE HARNESS, and this is the load-bearing half: it sits in the stdin and stdout path of the most authoritative guards in the repo, so a differential test drives EVERY hook with and without it over a payload matrix and demands byte-equal stdout and equal exit status. It fails OPEN in exactly one direction — if the log cannot be written the hook behaves exactly as before — because observability that breaks a guard is worse than the blindness it replaces. Two mechanical traps are pinned by tests rather than left to care: stdout must be replayed from the FILE, since `out=$(cat f)` strips trailing newlines and delivers a guard''s JSON one byte short with no parser anywhere to complain; and stdin must never be slurped when it is a TTY, because an interactive `git commit` hands its hooks a terminal and `cat` would block forever, hanging the commit the instrumentation was added to observe.'
signals: 'hook fire log · did this hook actually fire · PreToolUse leaves no transcript record · make the system report it rather than infer it · capture vs stream mode · byte-equal stdout differential · fail-open observability · never slurp a tty · derived hook population · never-fired row · paths: `scripts/hook-fire-log.sh`, `scripts/tests/test_hook_fire_log.py`, `docs/guard-inventory.md`, `docs/defect-shapes-773.md` · issues: #776, #773, #775, #774, #756, #751, #719, #685, #631'
mechanics: 'Read side: `scripts/hook-fire-log.sh report [--all|--json|--dir D|--session S]`. Logs default to `$HOME/.cache/ersatztv/hook-fire/<session-id>.jsonl`, outside the repo, overridable with `ETV_HOOK_FIRE_LOG_DIR`; `ETV_HOOK_FIRE_DISABLE=1` turns recording off without editing a hook. The session id comes from the payload''s `.session_id`, because this harness version does not export one to hooks. Records carry no tool arguments — only hook, label, event, tool name, phase, status and decision — so the log is not a second copy of the transcript.'
---
**The blind spot this closes.** In this harness version only `Stop` hooks emit a structured
transcript record. `PreToolUse` and `PostToolUse` hooks — which is *every* guard this repo actually
relies on: merge consent, worktree ownership, BOM, agent model and RAM, the golden-file ban — leave
no durable execution trace at all. When #773 tried to measure whether they fire, the only available
signal was **filename mentions in settings dumps and prior audits**, which is not evidence of
execution. So the guards carrying the most authority were the ones whose execution could only be
inferred, and a silently broken hook would have looked identical to a working one indefinitely.
That is Family B (the check never ran) applied to the hook layer itself, and this project has
already paid for it twice one layer down: #751's guard that reported success in 6 seconds having run
nothing, and #756's fail-open twin that 30 green tests could not see. #756's standing lesson is the
whole of this record — **make the system report it rather than infer it**.
**Why the decision is parsed from the emitted bytes rather than declared.** The obvious design has
each decision site announce itself. `pretooluse-merge-consent.sh` alone reaches its output through a
`decide` helper from roughly forty call sites, so that design is forty edits in the most
load-bearing guard in the repo, and it records **what the author meant** — which is the inference
being abolished, reintroduced one layer up. Capturing what the hook printed records what the
*harness* sees. It cannot drift from the decision because it **is** the decision, and it needed no
edit to any decision site.
**The risk this takes on, stated plainly.** Reading stdin before the hook and diverting its stdout
puts this code directly in the path of every guard. Get it wrong and a `deny` is swallowed while the
log cheerfully reports the guard firing — strictly worse than the blindness it replaces, and
undetectable from the outside for the same reason the original gap was. That is why the proof
obligation here is not a unit test of the sink: a wrapper can be perfect alone and lethal in
context. `test_instrumentation_changes_NOTHING_the_harness_can_see` runs every hook, in both forms,
over a payload matrix chosen to reach each hook's *deciding* branch rather than its early exit, and
compares bytes and exit status. A matrix that only ever produced silent allows would prove
transparency on the one path where there is nothing to be transparent about.
**Three defects this shipped with and the tests that now pin them**, recorded because each was
invisible to every other check and two would have degraded a guard silently:
| Defect | Why nothing else would catch it | Pinned by |
|---|---|---|
| `out=$(cat f)` strips trailing newlines, so a hook's JSON reached the harness one byte short | every JSON parser accepts it; only a byte comparison objects | `test_stdout_is_replayed_BYTE_EXACT` |
| An unconditional stdin slurp blocks forever on a TTY, hanging every interactive `git commit` | the pipe-fed tests that cover the Claude hooks cannot reach a tty; needs a real pty | `test_a_TTY_stdin_is_not_slurped` |
| A shared `TMPDIR` let the control run's one-shot throttle marker suppress the instrumented run | the differential test went red and blamed the wrapper for the hook's own correct behaviour | a separate TMPDIR per side |
The third is not a product defect but a measurement one, and it is the more instructive: a
differential test whose two halves share mutable state stops measuring the difference and starts
measuring the state. It reported a swallowed decision that never happened.
**What the first measurement immediately produced**, which is the argument for the whole thing. A
live run recorded `pretooluse-agent-model` firing on an `Agent` dispatch and deciding `no-op` where
`ask` was expected. Under the old regime that would have been an unanswerable suspicion. Instead the
question was settled by dumping the real payload: the dispatch carried `model: haiku`, so `no-op`
was correct and there was no bug. Note what did *not* happen — no argument from the hook's source
about what it "must" do, which this repo's record says has been wrong repeatedly. One printed line
settled it in one run.
**The limit, stated rather than implied.** A zero in the report means *not observed in this window*,
which is two different findings wearing one number: a hook that is broken, and a hook whose trigger
genuinely did not occur. The report says so in its own footer rather than presenting a zero as a
verdict. `pretooluse-nav-guard` and `pretooluse-merge-consent` are the standing examples — neither
can be exercised without either a browser session or a real merge, so their zeroes are expected and
distinguishing them stays a human judgement.
+12 -4
View File
@@ -101,6 +101,7 @@ all.
| `scripts/e2e-functional.sh` | the Functional E2E job, on a failed HTTP contract assertion | GUARD | NONE | — |
| `scripts/e2e-local.sh` | nothing (boots a local instance) | TOOLING | NONE | — |
| `scripts/e2e-ui.sh` | nothing (drives the Playwright flows) | TOOLING | NONE | — |
| `scripts/hook-fire-log.sh` | nothing (records that each hook fired, and reports it) | TOOLING | NONE | — |
| `scripts/jq-preflight.sh` | the `script-tests` job, on a jq version change | GUARD | BEHAVIOUR-ONLY | `test_jq_preflight.py::test_below_the_floor_is_LOUD` |
| `scripts/post-review-verdict.sh` | nothing (writes the verdict status) | GUARD | BEHAVIOUR-ONLY | `test_post_review_verdict.py::test_never_retargets_the_verdict_at_the_new_head` |
| `scripts/pr-changed-files.sh` | the verdict exemption, on an incomplete enumeration | GUARD | BEHAVIOUR-ONLY | `test_pr_changed_files.py::test_a_SHORT_page_does_not_end_the_enumeration` |
@@ -114,6 +115,7 @@ all.
| `scripts/tests/test_decisions_lib.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_decisions_validate.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_guard_inventory.py` | the `script-tests` job, on an unclassified guard or a stale proof ref | GUARD | MUTATION | `test_guard_inventory.py::test_the_inventory_covers_exactly_the_guards_that_exist` |
| `scripts/tests/test_hook_fire_log.py` | the `script-tests` job, on a hook that stops reporting that it fired, or whose reporting changes what the harness sees | GUARD | MUTATION | `test_hook_fire_log.py::test_a_hook_that_LOSES_its_instrumentation_is_DETECTED` |
| `scripts/tests/test_jq_preflight.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_merge_consent_base_change.py` | the `script-tests` job | PROOF | NONE | — |
| `scripts/tests/test_merge_consent_exemption.py` | the `script-tests` job | PROOF | NONE | — |
@@ -124,7 +126,7 @@ all.
## What the numbers say
31 guards, 4 tooling scripts, 13 proof files. **5 guards carry a mutation proof; 6 are
32 guards, 5 tooling scripts, 13 proof files. **6 guards carry a mutation proof; 6 are
behaviour-only; 20 have none.** These figures are asserted against the table by
`test_the_summary_counts_match_the_table` — they were wrong in the first draft (28/4/6/3/19 against
a table holding 27/5/6/3/18), because a hand-maintained summary of a table is a second copy of it,
@@ -176,9 +178,15 @@ the BOM guard was regraded, and `test_the_summary_counts_match_the_table` cannot
checks the formatted summary sentence and nothing else. A second hand-maintained copy of a number is
the duplication family this file argues against, so the copy is removed rather than corrected: the
set is every `PreToolUse` hook except merge-consent and the BOM guard, and the count is in the
summary above. It is also the population #776 found we
cannot even observe firing. A guard that is neither proven nor observable is an assertion about the
past.
summary above.
**They are now observable but still unproven, and the two words carry different weight.** Observable:
every hook records its own execution through `scripts/hook-fire-log.sh`, so "did this hook fire, and
what did it decide" is a measurement — run `scripts/hook-fire-log.sh report` (#776). Unproven:
nobody has demonstrated any of them is load-bearing, which is what #785 tracks. Observability tells
you a guard ran; only a mutation tells you it would have caught anything. The BOM guard is the case
that shows why the distinction matters — it was firing on every commit the whole time it was
fail-open.
The gaps are not uniform in cost, and the ranking that matters is *what a silent failure would let
through*, not test count:
+364
View File
@@ -0,0 +1,364 @@
#!/usr/bin/env bash
# Hook fire log — the WRITE side and the READ side, deliberately in ONE file (ersatztv#776).
#
# WHY THIS EXISTS. In this harness version only `Stop` hooks emit a structured transcript record
# (`stop_hook_summary`/`hookInfos`). `PreToolUse` and `PostToolUse` hooks leave no durable execution
# trace — which is every guard this repo actually relies on. #773 §5.4 could therefore only count
# *filename mentions in settings dumps*, i.e. inference. A guard that is neither proven nor
# observable is an assertion about the past, and a silently broken hook looks identical to a working
# one indefinitely. #756's standing lesson: make the system REPORT it rather than infer it.
#
# WHY ONE FILE. The reader and the writer share the record format. Two files means the format can
# drift and the report can quietly describe a shape nothing writes any more — the same argument that
# put `scripts/ci-step-ran.sh` in one script instead of an inline workflow body (#756).
#
# WHY IT CAPTURES STDOUT RATHER THAN BEING TOLD THE DECISION. Every hook here exits 0 always; the
# decision is communicated by *printing* `hookSpecificOutput.permissionDecision` (PreToolUse) or
# `decision` (Stop). `pretooluse-merge-consent.sh` alone reaches that print from ~40 call sites via
# its `decide` helper. Asking each site to also set a variable would (a) be 40 edits in the most
# load-bearing guard in the repo and (b) record what the author *meant*, which is the inference this
# issue exists to abolish. Capturing the bytes the hook actually emits records what the HARNESS
# sees. It cannot drift from the decision because it IS the decision.
#
# WHY IT CAPTURES STDIN. 8 of the 9 hooks already open with `input=$(cat)` — a full blocking slurp —
# so reading stdin once here and replaying it via `exec 0<` is not a new risk, it is the read they
# already perform, moved earlier. It buys the tool name and session id for the log, and it makes
# `pretooluse-agent-ram.sh` (which reads no stdin at all today) observable on the same terms as the
# rest instead of being a hole in the table.
#
# FAIL-OPEN, DELIBERATELY AND IN THIS DIRECTION ONLY. This file is observability, not a guard. If
# anything here fails — no temp dir, unwritable log, missing `date` — the hook must behave EXACTLY as
# it did before instrumentation. A logging bug that denies a merge, or that swallows a guard's deny
# JSON, would be far worse than the blindness it is fixing. Every function returns 0, the stdout
# replay is the first act of the exit path, and the original exit code is re-raised explicitly.
#
# USAGE (write side) — the first two lines of every hook, before anything reads stdin:
# . "${CLAUDE_PROJECT_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}/scripts/hook-fire-log.sh"
# etv_hook_fire_begin <hook-name> [label]
#
# USAGE (read side):
# scripts/hook-fire-log.sh report # this session (or every session, see below)
# scripts/hook-fire-log.sh report --all # every session in the log dir
# scripts/hook-fire-log.sh report --json
# scripts/hook-fire-log.sh path # where the current session logs
#
# `scripts/tests/test_hook_fire_log.py` is the guard: it derives the hook population from the
# filesystem (never a list — `testing.guard-derives-population-from-source`) and fails if any hook
# is uninstrumented, and it proves stdin, stdout and the exit code survive the wrapper.
# ---------------------------------------------------------------------------------------------
# Shared: where the log lives, and how a record is written
# ---------------------------------------------------------------------------------------------
etv_hook_fire_log_dir() {
printf '%s' "${ETV_HOOK_FIRE_LOG_DIR:-${HOME:-/tmp}/.cache/ersatztv/hook-fire}"
}
etv_hook_fire_session() {
# The harness does not export a session id to hooks in this version, so the payload's
# `.session_id` is the real source and the env var is only a fallback. Recorded rather than
# assumed: several hooks already read `.session_id` from stdin for exactly this reason.
printf '%s' "${ETV_HOOK_FIRE_SESSION:-${CLAUDE_SESSION_ID:-unknown-session}}"
}
etv_hook_fire_log_file() {
printf '%s/%s.jsonl' "$(etv_hook_fire_log_dir)" "$(etv_hook_fire_session)"
}
# Sanitise a value to a safe JSON scalar charset. This is why no `jq` is needed on the write side:
# with the value space restricted there is nothing to escape, so there is no escaping bug to have.
# A quote, backslash or newline in a hook name or tool name is not a case worth supporting — it is a
# case worth flattening, loudly, to `_`.
etv_hook_fire_scrub() {
printf '%s' "${1:-}" | tr -c 'A-Za-z0-9._/:+@=-' '_' | cut -c1-200
}
# Append one record. Never fails; never writes a partial line (built whole, appended once).
etv_hook_fire_record() {
[ "${ETV_HOOK_FIRE_DISABLE:-0}" = "1" ] && return 0
local file line
file="${ETV_HOOK_FIRE_LOG_FILE:-$(etv_hook_fire_log_file)}"
mkdir -p "$(dirname "$file")" 2>/dev/null || return 0
line=$(printf '{"ts":"%s","session":"%s","pid":"%s","hook":"%s","label":"%s","event":"%s","tool":"%s","phase":"%s","code":"%s","decision":"%s"}' \
"$(date -u '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || printf 'unknown')" \
"$(etv_hook_fire_scrub "$(etv_hook_fire_session)")" \
"$(etv_hook_fire_scrub "${ETV_HOOK_FIRE_PID:-$$}")" \
"$(etv_hook_fire_scrub "${1:-}")" \
"$(etv_hook_fire_scrub "${2:-}")" \
"$(etv_hook_fire_scrub "${3:-}")" \
"$(etv_hook_fire_scrub "${4:-}")" \
"$(etv_hook_fire_scrub "${5:-}")" \
"$(etv_hook_fire_scrub "${6:-}")" \
"$(etv_hook_fire_scrub "${7:-}")" 2>/dev/null) || return 0
printf '%s\n' "$line" >> "$file" 2>/dev/null || true
return 0
}
# ---------------------------------------------------------------------------------------------
# Write side: what a hook calls
# ---------------------------------------------------------------------------------------------
# Classify what the hook printed. The harness reads these two shapes and nothing else:
# PreToolUse : {"hookSpecificOutput":{"permissionDecision":"allow|deny|ask", ...}}
# Stop : {"decision":"block", "reason": ...}
# Anything else printed on stdout is surfaced to the user but decides nothing.
etv_hook_fire_classify() {
local out="${1:-}" code="${2:-0}" mode="${3:-capture}" d=""
# A `stream`-mode hook is a git hook: git reads its exit code and nothing else, so that is the
# whole of its decision. Reporting `no-op` here because no JSON was captured would be an
# inference, and inference is what this file exists to replace.
if [ "$mode" = "stream" ]; then
if [ "$code" = "0" ]; then printf 'pass'; else printf 'blocked'; fi
return 0
fi
if [ -n "$out" ]; then
d=$(printf '%s' "$out" | sed -n 's/.*"permissionDecision"[[:space:]]*:[[:space:]]*"\([a-z]*\)".*/\1/p' | head -n1)
[ -z "$d" ] && d=$(printf '%s' "$out" | sed -n 's/.*"decision"[[:space:]]*:[[:space:]]*"\([a-z]*\)".*/\1/p' | head -n1)
# `additionalContext` with no decision (design-sync-reminder's `start` path) informs, it does
# not gate. Naming it distinctly keeps it out of the allow/deny counts.
if [ -z "$d" ] && printf '%s' "$out" | grep -q 'additionalContext'; then d="context"; fi
[ -z "$d" ] && d="output"
fi
# Exit 2 is the harness's non-JSON block channel. No hook here uses it today; it is classified
# anyway so that a hook which starts using it is not silently recorded as a no-op.
if [ "$code" = "2" ] && [ -z "$d" ]; then d="deny-exit2"; fi
[ -z "$d" ] && d="no-op"
[ "$code" != "0" ] && [ "$code" != "2" ] && d="error"
printf '%s' "$d"
}
# etv_hook_fire_begin <hook-name> [label] [stdout-mode]
#
# `stdout-mode` is `capture` (default) or `stream`, and the split is not a tuning knob — the two
# kinds of hook in this repo decide by different channels:
#
# Claude Code hooks (pretooluse-*, posttooluse-*, design-sync-reminder) always exit 0 and
# communicate by PRINTING JSON. Their decision is only observable by capturing stdout, and their
# output is a single line consumed by the harness after exit, so buffering costs nothing.
#
# Git hooks (prepush-*, decisions-guard) decide by EXIT CODE, and their stdout is progress text a
# human is watching in real time. Capturing it would hold a slow pre-push hook's output back until
# the end, turning a working progress display into an apparent hang. They pass `stream`, and their
# decision is read from the exit code, which is what git reads too.
etv_hook_fire_begin() {
ETV_HOOK_FIRE_NAME="${1:-unknown-hook}"
ETV_HOOK_FIRE_LABEL="${2:-}"
ETV_HOOK_FIRE_MODE="${3:-capture}"
ETV_HOOK_FIRE_PID="$$"
ETV_HOOK_FIRE_STDIN_TMP=""
ETV_HOOK_FIRE_STDOUT_TMP=""
[ "${ETV_HOOK_FIRE_DISABLE:-0}" = "1" ] && return 0
ETV_HOOK_FIRE_LOG_FILE="$(etv_hook_fire_log_file)"
mkdir -p "$(dirname "$ETV_HOOK_FIRE_LOG_FILE")" 2>/dev/null || { ETV_HOOK_FIRE_DISABLE=1; return 0; }
# --- stdin: slurp, replay, and read the payload's identifying fields ------------------------
#
# NEVER on a terminal. A `git commit` run interactively hands its hooks a TTY on fd 0, and `cat`
# would block there forever — instrumentation hanging the commit it was added to observe. Claude
# Code always writes the JSON payload and closes the pipe, which is why the 8 hooks that already
# open with `input=$(cat)` are safe today; that guarantee does not extend to the git hooks, so the
# capture is conditioned on stdin not being a tty rather than on which hook is calling.
local sin payload="" event="" tool="" sess=""
if [ ! -t 0 ]; then
sin=$(mktemp "${TMPDIR:-/tmp}/etv-hook-stdin.XXXXXX" 2>/dev/null) || sin=""
else
sin=""
fi
if [ -n "$sin" ]; then
ETV_HOOK_FIRE_STDIN_TMP="$sin"
cat > "$sin" 2>/dev/null || true
# Replay unconditionally: even a partial capture is closer to the truth than the drained pipe
# the hook would otherwise inherit.
exec 0<"$sin" 2>/dev/null || true
payload=$(head -c 65536 "$sin" 2>/dev/null || true)
fi
if [ -n "$payload" ]; then
event=$(printf '%s' "$payload" | sed -n 's/.*"hook_event_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
tool=$(printf '%s' "$payload" | sed -n 's/.*"tool_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
sess=$(printf '%s' "$payload" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
fi
# The payload's session id is authoritative when the env var is absent, which it is in this
# harness version. Re-point the log file at it before the first record is written.
if [ -n "$sess" ] && [ -z "${CLAUDE_SESSION_ID:-}" ] && [ -z "${ETV_HOOK_FIRE_SESSION:-}" ]; then
ETV_HOOK_FIRE_SESSION="$sess"
ETV_HOOK_FIRE_LOG_FILE="$(etv_hook_fire_log_file)"
mkdir -p "$(dirname "$ETV_HOOK_FIRE_LOG_FILE")" 2>/dev/null || true
fi
ETV_HOOK_FIRE_EVENT="$event"
ETV_HOOK_FIRE_TOOL="$tool"
etv_hook_fire_record "$ETV_HOOK_FIRE_NAME" "$ETV_HOOK_FIRE_LABEL" "$event" "$tool" "fire" "" ""
# --- stdout: divert, so the exit path can read the decision the hook emitted ----------------
local sout=""
if [ "$ETV_HOOK_FIRE_MODE" = "capture" ]; then
sout=$(mktemp "${TMPDIR:-/tmp}/etv-hook-stdout.XXXXXX" 2>/dev/null) || sout=""
fi
if [ -n "$sout" ]; then
ETV_HOOK_FIRE_STDOUT_TMP="$sout"
exec 3>&1 || { ETV_HOOK_FIRE_STDOUT_TMP=""; rm -f "$sout" 2>/dev/null; return 0; }
exec 1>"$sout" || { exec 1>&3 3>&-; ETV_HOOK_FIRE_STDOUT_TMP=""; rm -f "$sout" 2>/dev/null; return 0; }
fi
trap 'etv_hook_fire_end "$?"' EXIT
return 0
}
etv_hook_fire_end() {
local code="${1:-0}" out=""
# RESTORE AND REPLAY FIRST. Everything after this point is bookkeeping; if any of it dies, the
# hook has already said what it came to say. Getting this order wrong would let an instrumentation
# bug swallow a `deny`, which is the one outcome worse than not logging at all.
if [ -n "${ETV_HOOK_FIRE_STDOUT_TMP:-}" ] && [ -f "${ETV_HOOK_FIRE_STDOUT_TMP:-}" ]; then
exec 1>&3 3>&- 2>/dev/null || true
# `cat` the FILE, not a variable. `out=$(cat f)` strips trailing newlines, so replaying from a
# variable delivers the hook's JSON one byte short of what it wrote. Caught by
# `test_stdout_is_replayed_BYTE_EXACT` — which was written because the first version of this
# function did exactly that, and the shortfall is invisible to every JSON parser that would
# otherwise have been the only reader.
cat "$ETV_HOOK_FIRE_STDOUT_TMP" 2>/dev/null || true
# A separate read for CLASSIFICATION only, where losing a trailing newline is harmless.
out=$(head -c 65536 "$ETV_HOOK_FIRE_STDOUT_TMP" 2>/dev/null || true)
fi
etv_hook_fire_record \
"${ETV_HOOK_FIRE_NAME:-unknown-hook}" "${ETV_HOOK_FIRE_LABEL:-}" \
"${ETV_HOOK_FIRE_EVENT:-}" "${ETV_HOOK_FIRE_TOOL:-}" \
"exit" "$code" "$(etv_hook_fire_classify "$out" "$code" "${ETV_HOOK_FIRE_MODE:-capture}")" || true
rm -f "${ETV_HOOK_FIRE_STDIN_TMP:-}" "${ETV_HOOK_FIRE_STDOUT_TMP:-}" 2>/dev/null || true
# Re-raise the hook's own status explicitly rather than relying on the trap preserving it. Bash
# does not re-enter an EXIT trap, so this is not recursive.
exit "$code"
}
# ---------------------------------------------------------------------------------------------
# Read side: the report
# ---------------------------------------------------------------------------------------------
# The hook population, DERIVED from the filesystem, never listed
# (`testing.guard-derives-population-from-source`). A hook added tomorrow appears in the report as
# NEVER-FIRED the moment it exists, rather than being invisible because nobody updated an array.
etv_hook_fire_population() {
local root="${1:-}" f
[ -d "$root/.claude/hooks" ] || return 0
for f in "$root"/.claude/hooks/*.sh; do
[ -f "$f" ] || continue
basename "$f" .sh
done
}
etv_hook_fire_repo_root() {
if [ -n "${CLAUDE_PROJECT_DIR:-}" ] && [ -d "$CLAUDE_PROJECT_DIR/.claude/hooks" ]; then
printf '%s' "$CLAUDE_PROJECT_DIR"
return 0
fi
( cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." >/dev/null 2>&1 && pwd )
}
etv_hook_fire_report() {
local all=0 as_json=0 dir root files hook
while [ $# -gt 0 ]; do
case "$1" in
--all) all=1 ;;
--json) as_json=1 ;;
--dir) shift; ETV_HOOK_FIRE_LOG_DIR="${1:-}" ;;
--session) shift; ETV_HOOK_FIRE_SESSION="${1:-}" ;;
*) printf 'hook-fire-log: unknown report option %s\n' "$1" >&2; return 2 ;;
esac
shift
done
dir="$(etv_hook_fire_log_dir)"
root="$(etv_hook_fire_repo_root)"
if [ "$all" = "1" ]; then
files=$(find "$dir" -name '*.jsonl' -type f 2>/dev/null | sort)
else
files="$(etv_hook_fire_log_file)"
[ -f "$files" ] || files=""
fi
if [ -z "$files" ]; then
printf 'hook-fire-log: no records under %s%s\n' "$dir" \
"$([ "$all" = "1" ] || printf ' for session %s (try --all)' "$(etv_hook_fire_session)")" >&2
fi
# ANTI-VACUITY. A report over an empty population would print a clean table of nothing and read
# as "all hooks accounted for" — the exact failure this file exists to end.
local pop
pop=$(etv_hook_fire_population "$root")
if [ -z "$pop" ]; then
printf 'hook-fire-log: found NO hook scripts under %s/.claude/hooks — refusing to report, because a report over an empty population reads as full coverage.\n' "$root" >&2
return 2
fi
local total_fires=0 rows=""
while IFS= read -r hook; do
[ -n "$hook" ] || continue
local fires decisions
fires=0
decisions=""
if [ -n "$files" ]; then
fires=$(cat $files 2>/dev/null | grep -c "\"hook\":\"$hook\",.*\"phase\":\"fire\"" || true)
decisions=$(cat $files 2>/dev/null \
| grep "\"hook\":\"$hook\",.*\"phase\":\"exit\"" \
| sed -n 's/.*"decision":"\([^"]*\)".*/\1/p' \
| sort | uniq -c | sort -rn \
| awk '{printf "%s=%s ", $2, $1}')
fi
[ -z "$fires" ] && fires=0
total_fires=$((total_fires + fires))
if [ "$as_json" = "1" ]; then
rows="${rows}{\"hook\":\"$hook\",\"fires\":$fires,\"decisions\":\"$(printf '%s' "$decisions" | tr -d '"')\"}\n"
else
rows="$(printf '%s%-34s %6s %s\n' "$rows" "$hook" "$fires" "${decisions:-—}")"$'\n'
fi
done <<EOF
$pop
EOF
if [ "$as_json" = "1" ]; then
printf '{"log_dir":"%s","total_fires":%s,"hooks":[%s]}\n' "$dir" "$total_fires" \
"$(printf '%b' "$rows" | sed '/^$/d' | paste -sd, -)"
return 0
fi
printf 'Hook fire log — %s\n' "$dir"
printf '%-34s %6s %s\n' 'HOOK' 'FIRES' 'DECISIONS'
printf '%s' "$rows"
printf '\n%s hook scripts on disk, %s recorded fires.\n' "$(printf '%s\n' "$pop" | wc -l | tr -d ' ')" "$total_fires"
printf 'A hook showing 0 has NOT been observed firing. That is a finding to investigate (broken\nwiring vs genuinely never matched in this window), not a blank to ignore.\n'
return 0
}
# ---------------------------------------------------------------------------------------------
# CLI (only when executed, never when sourced)
# ---------------------------------------------------------------------------------------------
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
set -uo pipefail
case "${1:-report}" in
report) shift 2>/dev/null || true; etv_hook_fire_report "$@" ;;
path) etv_hook_fire_log_file; printf '\n' ;;
record) shift; etv_hook_fire_record "$@" ;;
*)
printf 'usage: %s [report [--all|--json|--dir D|--session S] | path]\n' "$0" >&2
exit 2
;;
esac
fi
+490
View File
@@ -0,0 +1,490 @@
"""Every hook reports that it fired, and the reporting changes nothing else (ersatztv#776).
Two separable claims, and conflating them is how instrumentation ships as a regression:
1. COVERAGE — every hook script records its own execution. The population is DERIVED from
`.claude/hooks/*.sh`, never listed, per `testing.guard-derives-population-from-source`, so a
hook added tomorrow is uninstrumented-and-red rather than silently unobserved.
2. TRANSPARENCY — the wrapper is invisible to the harness. It slurps stdin and replays it, and it
diverts stdout and replays it, which puts it directly in the path of the most load-bearing
guards in this repo. If it drops a byte of a `deny` payload or swallows an exit code, it
disables a guard while reporting that the guard fired. That is strictly worse than the
blindness #776 set out to fix, so the differential test below drives EVERY hook, with and
without the instrumentation, over a payload matrix and demands byte-equal stdout and equal
exit status.
The mutation proof for claim 1 is the contrapositive form allowed by
`testing.guard-ships-with-mutation-proof` for a checker-guard: the defect the guard exists to catch
(an uninstrumented hook) is introduced into an isolated copy of the guarded artifact, and the named
check must go red. See `test_a_hook_that_LOSES_its_instrumentation_is_DETECTED`.
Claim 2's proof is not a mutation of an assertion but a real A/B over the real scripts, which is the
only thing that can establish it — a unit test of the wrapper in isolation would pass on a wrapper
that is fine alone and lethal in context.
"""
from __future__ import annotations
import os
import re
import subprocess
import pty
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
HOOKS_DIR = REPO_ROOT / ".claude" / "hooks"
SINK = REPO_ROOT / "scripts" / "hook-fire-log.sh"
# The three lines a hook must carry. Matched structurally rather than as one frozen blob so that a
# comment reflow does not redden the suite, but the two things that matter — sourcing the single
# shared sink, and calling begin with this hook's own name — are both pinned.
_SOURCES_SINK = re.compile(r'^\[ -r "\$ETV_HOOK_FIRE_LIB" \] && \. "\$ETV_HOOK_FIRE_LIB" \|\| true$', re.M)
_BEGINS = re.compile(r"^etv_hook_fire_begin (\S+) .*\|\| true$", re.M)
def hook_scripts() -> list[Path]:
"""THE POPULATION, from the filesystem. Never a list."""
return sorted(HOOKS_DIR.glob("*.sh"))
def instrumentation_faults(text: str, name: str) -> list[str]:
"""The check itself, factored out so a mutation can be fed to the same code the suite runs."""
faults = []
if not _SOURCES_SINK.search(text):
faults.append(f"{name}: does not source scripts/hook-fire-log.sh")
m = _BEGINS.search(text)
if not m:
faults.append(f"{name}: never calls etv_hook_fire_begin")
elif m.group(1) != name:
faults.append(f"{name}: calls etv_hook_fire_begin for {m.group(1)!r}, not for itself")
else:
# Order is the whole point: 8 of the hooks slurp stdin with `input=$(cat)`, and a begin
# placed after that read would find the pipe already drained — recording a fire with no
# tool name, and replaying nothing into a hook that has already consumed its payload.
stdin_read = text.find("$(cat)")
if 0 <= stdin_read < m.start():
faults.append(f"{name}: reads stdin before etv_hook_fire_begin")
return faults
def strip_instrumentation(text: str) -> str:
"""Reconstruct the pre-#776 script. Used BOTH as the mutation and as the A/B control."""
out, skipping = [], False
for line in text.splitlines(keepends=True):
if line.startswith("# ersatztv#776 —"):
skipping = True
continue
if skipping:
if line.startswith(("#", "ETV_HOOK_FIRE_LIB=", "[ -r ", "etv_hook_fire_begin ")):
continue
skipping = False
out.append(line)
return "".join(out)
# ------------------------------------------------------------------------------------------------
# ANTI-VACUITY FIRST — a glob that stopped matching would make every assertion below iterate over
# nothing and report full coverage. That is the characteristic failure of a completeness check, and
# this repo has shipped it (#631, #751), so it is asserted before anything depends on it.
# ------------------------------------------------------------------------------------------------
def test_the_population_is_not_empty():
hooks = hook_scripts()
assert len(hooks) >= 10, (
f"only found {len(hooks)} hook scripts under {HOOKS_DIR} — the glob has stopped matching, "
"so every coverage assertion in this file is vacuous."
)
assert SINK.exists(), "the shared sink is missing; the instrumentation cannot work"
assert os.access(SINK, os.X_OK), "the sink is not executable, so its report side cannot be run"
def test_the_stripper_actually_strips():
"""The A/B control and the mutation are the same function. If it were a no-op, the differential
test would compare each hook against itself and pass on a wrapper that breaks everything."""
for hook in hook_scripts():
text = hook.read_text()
stripped = strip_instrumentation(text)
assert stripped != text, f"{hook.name}: strip_instrumentation() removed nothing"
assert "etv_hook_fire_begin" not in stripped, f"{hook.name}: begin survived the strip"
assert not instrumentation_faults(text, hook.stem), f"{hook.name} is not instrumented"
# ------------------------------------------------------------------------------------------------
# CLAIM 1 — COVERAGE
# ------------------------------------------------------------------------------------------------
def test_every_hook_reports_that_it_fired():
faults = []
for hook in hook_scripts():
faults += instrumentation_faults(hook.read_text(), hook.stem)
assert not faults, (
"these hooks do not report their own execution:\n " + "\n ".join(faults) +
"\n\nAdd the three-line preamble after the `set -` line and BEFORE any stdin read. A hook "
"that does not report is one whose firing we can only infer, which is ersatztv#776."
)
def test_a_hook_that_LOSES_its_instrumentation_is_DETECTED():
"""THE MUTATION PROOF (contrapositive form, for a checker-guard).
Introduce the defect this guard exists to catch — an uninstrumented hook — into an isolated copy
of each hook in turn, and the check must report it. Every hook, not a sample: the interesting
loss is whichever file someone actually edits.
"""
for hook in hook_scripts():
mutated = strip_instrumentation(hook.read_text())
faults = instrumentation_faults(mutated, hook.stem)
assert faults, (
f"stripping the instrumentation from {hook.name} left the check GREEN. The check is "
"not load-bearing — it would not notice a hook silently losing its reporting."
)
def test_begin_placed_AFTER_the_stdin_read_is_DETECTED():
"""The subtler mutation: present but too late. Ordering is the property that makes it work."""
late = 'set -euo pipefail\ninput=$(cat)\nETV_HOOK_FIRE_LIB="x"\n[ -r "$ETV_HOOK_FIRE_LIB" ] && . "$ETV_HOOK_FIRE_LIB" || true\netv_hook_fire_begin demo "" capture || true\n'
faults = instrumentation_faults(late, "demo")
assert any("reads stdin before" in f for f in faults), (
"a begin call placed after `input=$(cat)` was accepted. It would record a fire with no "
f"payload and replay nothing. faults={faults}"
)
# ------------------------------------------------------------------------------------------------
# CLAIM 2 — TRANSPARENCY. The wrapper must be invisible to the harness.
# ------------------------------------------------------------------------------------------------
# Payloads chosen to reach the DECIDING branch of each hook, not merely its early-exit. A matrix
# that only ever produced silent allows would prove the wrapper transparent on the one path where
# there is nothing to be transparent about.
PAYLOADS = {
"bash-deny": '{"session_id":"s","hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"%(cwd)s","tool_input":{"command":"ETV_UPDATE_GOLDENS=1 dotnet test"}}',
"bash-allow": '{"session_id":"s","hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"%(cwd)s","tool_input":{"command":"ls -la"}}',
"git-commit": '{"session_id":"s","hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"%(cwd)s","tool_input":{"command":"git commit -m x"}}',
"nav-deny": '{"session_id":"s","hook_event_name":"PreToolUse","tool_name":"mcp__x__navigate","cwd":"%(cwd)s","tool_input":{"url":"http://h/iptv/channels.m3u"}}',
"agent-no-model": '{"session_id":"s","hook_event_name":"PreToolUse","tool_name":"Agent","cwd":"%(cwd)s","tool_input":{"description":"d","prompt":"p"}}',
"agent-model": '{"session_id":"s","hook_event_name":"PreToolUse","tool_name":"Agent","cwd":"%(cwd)s","tool_input":{"description":"d","prompt":"p","model":"sonnet"}}',
"merge": '{"session_id":"s","hook_event_name":"PreToolUse","tool_name":"mcp__gitea__pull_request_write","cwd":"%(cwd)s","tool_input":{"method":"merge","owner":"timothy","repo":"ersatztv","pull_number":1}}',
"worktree-add": '{"session_id":"s","hook_event_name":"PostToolUse","tool_name":"Bash","cwd":"%(cwd)s","tool_input":{"command":"git worktree add /tmp/nope-%(nonce)s HEAD"}}',
"ui-edit": '{"session_id":"s","hook_event_name":"PreToolUse","tool_name":"Edit","cwd":"%(cwd)s","tool_input":{"file_path":"web/src/screens/Channels.tsx"}}',
"empty": "",
"garbage": "not json at all",
}
@pytest.fixture(scope="module")
def sandbox(tmp_path_factory):
"""A controlled environment so the A/B pair cannot differ for reasons unrelated to the wrapper.
`memory_pressure` is stubbed because `pretooluse-agent-ram.sh` reads live free RAM: a real
reading that crossed the 10% or 20% threshold between the two runs would make the A and B halves
disagree for a reason that has nothing to do with instrumentation, and a differential test that
flakes is one that gets rerun until green.
"""
root = tmp_path_factory.mktemp("hookfire")
bindir = root / "bin"
bindir.mkdir()
stub = bindir / "memory_pressure"
stub.write_text("#!/bin/sh\necho 'System-wide memory free percentage: 42%'\n")
stub.chmod(0o755)
env = dict(os.environ)
env["PATH"] = f"{bindir}:{env['PATH']}"
env["ETV_HOOK_FIRE_LOG_DIR"] = str(root / "log")
env["CLAUDE_PROJECT_DIR"] = str(REPO_ROOT)
# No creds: `pretooluse-merge-consent.sh` must take its documented "cannot derive state" path
# rather than making live Gitea calls from a unit test.
for k in ("ETV_GITEA_TOKEN", "ETV_GITEA_BASICAUTH"):
env.pop(k, None)
return root, env
def _run(script: Path, payload: str, env: dict, cwd: Path, arg: str | None = None):
cmd = ["bash", str(script)] + ([arg] if arg else [])
p = subprocess.run(
cmd, input=payload.encode(), capture_output=True, cwd=str(cwd), env=env, timeout=60
)
return p.returncode, p.stdout
@pytest.mark.parametrize("hook", hook_scripts(), ids=lambda h: h.stem)
def test_instrumentation_changes_NOTHING_the_harness_can_see(hook, sandbox):
"""THE REGRESSION NET. Every hook, every payload, byte-equal stdout and equal exit status.
This is what stands between #776 and having silently disarmed the guard set while adding a log
that cheerfully reports every hook firing.
"""
root, env = sandbox
control = root / f"control-{hook.name}"
control.write_text(strip_instrumentation(hook.read_text()))
# `design-sync-reminder.sh` dispatches on argv[1], so both of its branches are exercised.
args = [None, "start", "finish"] if hook.stem == "design-sync-reminder" else [None]
for name, template in PAYLOADS.items():
for arg in args:
payload = template % {"cwd": str(root), "nonce": name}
# A SEPARATE TMPDIR PER SIDE, not per pair. `design-sync-reminder.sh` throttles itself
# with a marker file under $TMPDIR, so a shared one let the control fire and then
# silently suppress the instrumented run — the A/B reported a swallowed decision that
# was really the hook's own one-shot behaviour working correctly. Sharing state between
# the two halves of a differential test makes it measure the state, not the difference.
def side(tag: str) -> dict:
e = dict(env)
e["TMPDIR"] = str(root / f"tmp-{name}-{arg}-{tag}")
Path(e["TMPDIR"]).mkdir(parents=True, exist_ok=True)
return e
rc_a, out_a = _run(control, payload, side("control"), root, arg)
rc_b, out_b = _run(hook, payload, side("instrumented"), root, arg)
label = f"{hook.name} payload={name} arg={arg}"
assert rc_a == rc_b, f"{label}: exit status changed {rc_a} -> {rc_b}"
assert out_a == out_b, (
f"{label}: stdout changed.\n without: {out_a!r}\n with: {out_b!r}"
)
def test_stdout_is_replayed_BYTE_EXACT(sandbox):
"""Pinned separately from the A/B because the first version of the sink lost exactly one byte.
`out=$(cat file)` strips trailing newlines, so the hook's JSON reached the harness a newline
short. Every JSON parser accepts it, so nothing downstream would ever have complained — the only
thing that catches it is comparing bytes.
"""
root, env = sandbox
hook = root / "trailing.sh"
hook.write_text(
"#!/usr/bin/env bash\nset -euo pipefail\n"
f'. "{SINK}"\n'
"etv_hook_fire_begin trailing \"\" capture || true\n"
"input=$(cat)\n"
r'printf "{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\"}}\n\n"' + "\n"
)
rc, out = _run(hook, '{"tool_name":"Bash"}', env, root)
assert rc == 0
assert out == b'{"hookSpecificOutput":{"permissionDecision":"deny"}}\n\n', (
f"trailing bytes were altered: {out!r}"
)
@pytest.mark.parametrize("code", [0, 1, 2, 3])
def test_the_exit_code_is_preserved(sandbox, code):
"""Exit 2 is the harness's block channel and non-zero is git's. A wrapper that normalised the
status to 0 would turn every git hook into a rubber stamp while logging that it ran."""
root, env = sandbox
hook = root / f"exit{code}.sh"
hook.write_text(
"#!/usr/bin/env bash\nset -uo pipefail\n"
f'. "{SINK}"\n'
f'etv_hook_fire_begin exit{code} "" capture || true\n'
f"exit {code}\n"
)
rc, _ = _run(hook, "{}", env, root)
assert rc == code, f"exit {code} came back as {rc}"
def test_stdin_reaches_the_hook_intact(sandbox):
"""The wrapper reads stdin before the hook does. If it did not replay it faithfully, every
guard that parses `.tool_input` would see an empty payload and fail open, silently."""
root, env = sandbox
payload = '{"tool_name":"Bash","tool_input":{"command":"echo \\"quoted\\" && ls"},"session_id":"s"}'
hook = root / "echo-stdin.sh"
hook.write_text(
"#!/usr/bin/env bash\nset -euo pipefail\n"
f'. "{SINK}"\n'
'etv_hook_fire_begin echo-stdin "" capture || true\n'
"input=$(cat)\nprintf '%s' \"$input\"\n"
)
rc, out = _run(hook, payload, env, root)
assert rc == 0
assert out.decode() == payload, f"stdin was altered:\n sent: {payload}\n saw: {out.decode()}"
def test_a_TTY_stdin_is_not_slurped(sandbox):
"""The hang this nearly shipped with.
An interactive `git commit` hands its hooks a terminal on fd 0. `cat` on a tty blocks until the
user types EOF, so an unconditional slurp would freeze every commit — instrumentation hanging
the very thing it was added to observe. Driven through a real pty, because the `[ ! -t 0 ]`
guard is precisely what a pipe-based test cannot exercise.
"""
root, env = sandbox
hook = root / "tty.sh"
hook.write_text(
"#!/usr/bin/env bash\nset -uo pipefail\n"
f'. "{SINK}"\n'
'etv_hook_fire_begin ttyhook "" stream || true\n'
"echo ALIVE\n"
)
master, slave = pty.openpty()
try:
p = subprocess.Popen(
["bash", str(hook)], stdin=slave, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, cwd=str(root), env=env,
)
os.close(slave)
try:
out, _ = p.communicate(timeout=20)
except subprocess.TimeoutExpired:
p.kill()
pytest.fail(
"the hook hung with a tty on stdin — the instrumentation slurped a terminal, "
"which would freeze every interactive `git commit`."
)
finally:
os.close(master)
assert b"ALIVE" in out
def test_logging_failure_does_not_break_the_hook(sandbox):
"""Fail-open, in the one direction that is correct here. This file is observability; if it
cannot write, the guard must still guard. The inverse — a logging bug that swallows a `deny` —
is the failure mode the A/B test above exists to prevent."""
root, env = sandbox
bad = dict(env)
bad["ETV_HOOK_FIRE_LOG_DIR"] = "/dev/null/cannot-exist"
hook = root / "failopen.sh"
hook.write_text(
"#!/usr/bin/env bash\nset -euo pipefail\n"
f'. "{SINK}"\n'
'etv_hook_fire_begin failopen "" capture || true\n'
"input=$(cat)\n"
r'printf "{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\"}}"' + "\n"
)
rc, out = _run(hook, '{"tool_name":"Bash"}', bad, root)
assert rc == 0
assert out == b'{"hookSpecificOutput":{"permissionDecision":"deny"}}', (
f"an unwritable log dir changed the hook's decision output: {out!r}"
)
# ------------------------------------------------------------------------------------------------
# THE RECORD ITSELF, and the report over it
# ------------------------------------------------------------------------------------------------
@pytest.mark.parametrize(
"emit,mode,expected",
[
(r'{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\"}}', "capture", "deny"),
(r'{\"hookSpecificOutput\":{\"permissionDecision\":\"ask\"}}', "capture", "ask"),
(r'{\"hookSpecificOutput\":{\"permissionDecision\":\"allow\"}}', "capture", "allow"),
(r'{\"hookSpecificOutput\":{\"additionalContext\":\"hi\"}}', "capture", "context"),
(r'{\"decision\":\"block\",\"reason\":\"r\"}', "capture", "block"),
("", "capture", "no-op"),
("", "stream", "pass"),
],
)
def test_the_recorded_decision_is_the_one_the_hook_emitted(sandbox, emit, mode, expected):
"""The decision in the log is derived from the bytes the harness receives, never from something
the hook author remembered to declare. That is the whole difference between this and inference.
"""
root, env = sandbox
logdir = root / f"log-{expected}-{mode}"
runenv = dict(env)
runenv["ETV_HOOK_FIRE_LOG_DIR"] = str(logdir)
hook = root / f"decide-{expected}-{mode}.sh"
body = f'printf "{emit}"\n' if emit else ""
hook.write_text(
"#!/usr/bin/env bash\nset -uo pipefail\n"
f'. "{SINK}"\n'
f'etv_hook_fire_begin decider "" {mode} || true\n'
"input=$(cat)\n" + body
)
rc, _ = _run(hook, '{"session_id":"sess1","tool_name":"Bash"}', runenv, root)
assert rc == 0
records = (logdir / "sess1.jsonl").read_text().splitlines()
exits = [r for r in records if '"phase":"exit"' in r]
assert len(exits) == 1, f"expected one exit record, got {records}"
assert f'"decision":"{expected}"' in exits[0], f"expected {expected} in {exits[0]}"
assert any('"phase":"fire"' in r for r in records), "no fire record was written"
def test_a_stream_mode_hook_that_BLOCKS_is_recorded_as_blocked(sandbox):
"""A git hook decides by exit code; recording a non-zero exit as `pass` would put the report
back into the business of inferring, with the answer inverted on the only path that matters."""
root, env = sandbox
logdir = root / "log-blocked"
runenv = dict(env)
runenv["ETV_HOOK_FIRE_LOG_DIR"] = str(logdir)
hook = root / "blocker.sh"
hook.write_text(
"#!/usr/bin/env bash\nset -uo pipefail\n"
f'. "{SINK}"\n'
'etv_hook_fire_begin blocker "" stream || true\n'
"input=$(cat)\nexit 1\n"
)
rc, _ = _run(hook, '{"session_id":"sess1"}', runenv, root)
assert rc == 1
assert '"decision":"blocked"' in (logdir / "sess1.jsonl").read_text()
def test_the_report_names_hooks_that_NEVER_fired(sandbox):
"""The finding #776 asks for is the ZERO row, so the report must derive its rows from the hooks
that exist rather than from the hooks that happen to appear in the log. A report built from the
log alone can only ever show hooks that fired, and would print a clean table while the broken
hook is the one missing from it."""
root, env = sandbox
logdir = root / "log-report"
logdir.mkdir()
(logdir / "sessX.jsonl").write_text(
'{"ts":"t","session":"sessX","pid":"1","hook":"pretooluse-bash-guard","label":"",'
'"event":"PreToolUse","tool":"Bash","phase":"fire","code":"","decision":""}\n'
'{"ts":"t","session":"sessX","pid":"1","hook":"pretooluse-bash-guard","label":"",'
'"event":"PreToolUse","tool":"Bash","phase":"exit","code":"0","decision":"deny"}\n'
)
p = subprocess.run(
["bash", str(SINK), "report", "--all", "--dir", str(logdir)],
capture_output=True, cwd=str(REPO_ROOT), env=env, timeout=60,
)
out = p.stdout.decode()
assert p.returncode == 0, p.stderr.decode()
assert "pretooluse-bash-guard" in out and "deny=1" in out
for hook in hook_scripts():
assert hook.stem in out, (
f"{hook.stem} is absent from the report. Only hooks present in the log were listed, so "
"a hook that never fires — the finding this report exists to surface — is invisible."
)
zero_rows = [ln for ln in out.splitlines() if re.search(r"\s0\s", ln)]
assert zero_rows, "no never-fired rows shown despite only one hook appearing in the log"
def test_the_report_REFUSES_an_empty_population(tmp_path, sandbox):
"""Anti-vacuity on the read side. A report over zero hooks would print a tidy empty table and
read as 'all hooks accounted for' — the shape of #751's 6-second green.
The sink is COPIED into a hook-less tree rather than pointed at one via `CLAUDE_PROJECT_DIR`,
because the real script deliberately falls back to its own location when that variable names a
tree with no hooks. That fallback is correct — it is what makes `scripts/hook-fire-log.sh
report` work from anywhere — and the first version of this test drove the fallback straight back
into the real repo, so it was asserting against all 13 live hooks while claiming to test the
empty case.
"""
_, env = sandbox
fake_scripts = tmp_path / "scripts"
fake_scripts.mkdir()
copied = fake_scripts / "hook-fire-log.sh"
copied.write_text(SINK.read_text())
copied.chmod(0o755)
runenv = dict(env)
runenv.pop("CLAUDE_PROJECT_DIR", None)
p = subprocess.run(
["bash", str(copied), "report", "--all", "--dir", str(tmp_path / "log")],
capture_output=True, cwd=str(tmp_path), env=runenv, timeout=60,
)
assert p.returncode == 2, (
"the report exited 0 over an empty hook population. It must refuse rather than print a "
f"clean table of nothing. stdout={p.stdout.decode()!r}"
)
assert b"refusing to report" in p.stderr