A PreToolUse guard that fails closed
Test a PreToolUse guard the way Claude Code runs it: a documented payload on stdin, then the exit code, stdout and stderr read with Claude Code's rules. The 44 cases cover what the guard allows, denies and asks about, the input it can't judge, and what happens to the hook process itself when it times out, crashes or can't start.
- Python 3.9+
- standard library only
- offline:
guard_hooks/kit/.claude/(guard and settings) - 44 table-driven cases + 5 settings checks
python3 agents-5/guard_hooks/test_guard.py
Nothing in a payload is ever executed: the dangerous commands are strings inside JSON that the guard reads and refuses. The onFailure rows use stand-ins (a sh -c '… exit 139' crash, a missing executable, a test-only sleep) to show what happens to the hook process, not to the guard's logic.
┌─────────────────────────────────────────────────────────┐
│ Agents 5 · guard_hooks: the PreToolUse guard under test │
└─────────────────────────────────────────────────────────┘
guard: agents-5/guard_hooks/kit/.claude/hooks/guard.py (exec form: python3 guard.py)
registration: matcher 'Bash|Write|Edit|NotebookEdit', onFailure "block" (Claude Code v2.1.295+)
group case expect got reason / note
──── ─────────── ─────────────────────── ─────────── ──────────────────────── ──────────────────────────────────────────────────────────────
PASS allowed allow-tests allow exit 0, proceeds
PASS allowed allow-rm-build allow exit 0, proceeds recursive rm, but not a critical path
PASS allowed allow-push-feature allow exit 0, proceeds
PASS allowed allow-curl-to-file allow exit 0, proceeds downloading is fine; running it unread is the problem
PASS allowed allow-write-src allow exit 0, proceeds
PASS allowed allow-env-example allow exit 0, proceeds templates without secrets are allowed
PASS allowed allow-other-tool allow exit 0, proceeds not in the matcher; the guard passes through if it ever sees o
PASS denied deny-rm-root deny exit 0, deny recursive rm of a critical path (/)
PASS denied deny-rm-home deny exit 0, deny recursive rm of a critical path ($HOME)
PASS denied deny-rm-tilde deny exit 0, deny recursive rm of a critical path (~)
PASS denied deny-rm-no-preserve deny exit 0, deny rm --no-preserve-root is never allowed
PASS denied deny-rm-project deny exit 0, deny recursive rm of the project root (/tmp/cc-lab-demo/tiny-app)
PASS denied deny-rm-dot deny exit 0, deny recursive rm of a critical path (.)
PASS denied deny-force-main deny exit 0, deny force push to main/master is not allowed
PASS denied deny-force-head-master deny exit 0, deny force push to main/master is not allowed
PASS denied deny-force-no-branch deny exit 0, deny force push without naming a branch (the current branch may be
PASS denied deny-curl-sh deny exit 0, deny piping a download straight into a shell runs code nobody revie
PASS denied deny-wget-sudo-sh deny exit 0, deny piping a download straight into a shell runs code nobody revie
PASS denied deny-sh-subst deny exit 0, deny piping a download straight into a shell runs code nobody revie
PASS denied deny-chmod-777 deny exit 0, deny recursive chmod 777 makes everything world-writable
PASS denied deny-redirect-env deny exit 0, deny shell write to a protected path: .env holds environment secret
PASS denied deny-tee-secrets deny exit 0, deny shell write to a protected path: files under a secrets/ direct
PASS denied deny-write-env deny exit 0, deny .env holds environment secrets
PASS denied deny-write-env-local deny exit 0, deny .env.local holds environment secrets
PASS denied deny-edit-git deny exit 0, deny the .git directory is managed by git, not by edits
PASS denied deny-write-secrets deny exit 0, deny files under a secrets/ directory are protected
PASS denied deny-write-key deny exit 0, deny server.pem looks like a private key
PASS denied deny-edit-guard deny exit 0, deny the guard's own hook scripts are protected (a guard Claude can
PASS denied deny-edit-settings deny exit 0, deny the settings file that registers this guard is protected
PASS denied deny-notebook-secrets deny exit 0, deny files under a secrets/ directory are protected
PASS denied deny-unparseable deny exit 0, deny couldn't parse the command safely (No closing quotation); rewr
PASS ask ask-force-feature ask exit 0, ask force push rewrites shared history; confirm the branch
PASS fail-closed fail-not-json fail-closed exit 2, BLOCKED guard.py blocked the call: invalid hook input: stdin is not JS
PASS fail-closed fail-no-tool-input fail-closed exit 2, BLOCKED guard.py blocked the call: invalid hook input: payload has no
PASS fail-closed fail-command-not-str fail-closed exit 2, BLOCKED guard.py blocked the call: invalid hook input: Bash tool_input
PASS fail-closed fail-write-no-path fail-closed exit 2, BLOCKED guard.py blocked the call: invalid hook input: Write tool_inpu
PASS fail-closed fail-internal-error fail-closed exit 2, BLOCKED guard.py blocked the call: internal error (RuntimeError): GUAR
PASS onFailure onfail-timeout-continue proceeds timed out, proceeds onFailure=continue: timed out: the call goes ahead, even rm -r
PASS onFailure onfail-timeout-block blocked timed out, BLOCKED onFailure=block: timed out: blocked
PASS onFailure onfail-crash-continue proceeds exit 139, proceeds onFailure=continue: a hard crash (exit 139) fails open
PASS onFailure onfail-crash-block blocked exit 139, BLOCKED onFailure=block: the same crash is blocked
PASS onFailure onfail-nostart-continue proceeds couldn't start, proceeds onFailure=continue: exec form, executable missing: can't start
PASS onFailure onfail-nostart-block blocked couldn't start, BLOCKED onFailure=block: can't start
PASS onFailure gotcha-missing-script blocked exit 2, BLOCKED onFailure=continue: python3 exits 2 on a missing script: every
kit configuration
check detail
──── ───────────────────────────────────── ───────────────────────────────────────────────
PASS settings.json parses agents-5/guard_hooks/kit/.claude/settings.json
PASS hook entry matches settings_snippet() exec form, timeout 10, onFailure block
PASS hook event names are documented PreToolUse
PASS deny rules back up the guard 7 deny rules
PASS guard script exists agents-5/guard_hooks/kit/.claude/hooks/guard.py
49/49 checks passed
Defense in depth: this hook, the deny rules next to it, and the sandbox. The hook alone is not the boundary.
- Allowed calls produce no output and exit 0: the guard has no opinion, so the normal permission flow (rules, mode, prompt) decides.
- A guard Claude can edit is no guard: writes to its own script and to the settings file that registers it are denied.
- Input it can't judge, or a bug inside the guard, exits 2 with the reason on stderr. That's what fail closed means for the script.
- The hook around the script is another matter: a timed-out PreToolUse hook lets the call through unless its registration sets
"onFailure": "block"(v2.1.295+). The kit sets it. - A gotcha that works the other way:
python3 missing.pystarts, then exits 2, which Claude Code reads as a block. A mistyped script path blocks every matching call. - The kit ships matching permission deny rules, because the hook is defense in depth and the deny rules plus the sandbox are the boundary.
--only rmruns the cases whose id containsrm(seven of them) plus the settings checks;-valso prints each hook's stdout and stderr, such as the deny JSON.- Run the guard by hand. A deny is JSON on stdout with exit 0; input that isn't JSON is a reason on stderr with exit 2:
echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"rm -rf /"}}' \ | python3 agents-5/guard_hooks/kit/.claude/hooks/guard.py; echo "exit=$?" echo 'nope' | python3 agents-5/guard_hooks/kit/.claude/hooks/guard.py; echo "exit=$?" - Break it: find spellings the string matching misses.
git push --force origin mainis denied, butgit -C . push --force origin mainandd=/; rm -rf $dboth get no output and exit 0, so they'd go on to the normal permission flow. That's the limit the deny rules and the sandbox are there for:for c in 'git push --force origin main' 'git -C . push --force origin main' 'd=/; rm -rf $d'; do printf '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"%s"}}' "$c" \ | python3 agents-5/guard_hooks/kit/.claude/hooks/guard.py; echo " exit=$? ($c)" done
To install the kit, copy agents-5/guard_hooks/kit/.claude into a repo and chmod +x the guard. The copy overwrites an existing .claude/settings.json, so merge the permissions and hooks blocks by hand if the repo has one (agents-5/README.md has the steps). Then check the registration in /hooks.
- The three answers a PreToolUse hook can give: no output (no decision),
permissionDecisionJSON on exit 0 (deny or ask), or exit 2 with a reason on stderr (block). - The script can fail closed; the hook around it fails open unless
onFailuresaysblock. - String matching has bypasses. Pair a guard with deny rules, which hold in every permission mode, and with the sandbox for OS-level limits on shell commands.
Grade headless runs with deterministic graders
An eval here is a prompt, a capped headless run, and code graders that read the run's transcript: how it ended, what the answer says, which tools it called, its turns and cost, any denials, and what the structured output holds. Five tasks in evals/tasks.json replay the common transcript fixtures, two of them failing on purpose.
- Python 3.9+
- standard library only
- offline: 5 tasks in
agents-5/evals/tasks.json - the common stream and JSON fixtures
python3 agents-5/eval_harness.py
The outcome grader reads the result in the documented order: stop_reason first, so a refusal grades as refusal even with subtype: "success"; then terminal_reason, where only completed counts as finished; then subtype.
┌───────────────────────────────────────────────┐
│ Agents 5 · eval_harness: replay of tasks.json │
└───────────────────────────────────────────────┘
mode: replay: recorded transcripts from common/fixtures (tests the harness, not the model)
task graders outcome turns cost trials ok verdict expect as expected
──────────────────────── ─────── ────────── ───── ───────── ───────── ─────── ────── ───────────
map-modules 7/7 completed 4 $0.001987 1/1 PASS pass yes
find-discounts 4/4 completed 4 $0.001706 1/1 PASS pass yes
find-discounts-two-turns 1/3 turn_limit 3 $0.001407 0/1 FAIL fail yes
run-tests-read-only 2/3 completed 2 $0.001476 0/1 FAIL fail yes
public-functions-json 4/4 completed 4 $0.002192 1/1 PASS pass yes
find-discounts-two-turns trial 1 (replay):
✗ outcome outcome turn_limit (want completed)
✗ result_contains no result text (the run didn't end in success)
why: The same task with --max-turns 2: the run stops before answering, so outcome and result_contains fail.
run-tests-read-only trial 1 (replay):
✗ no_permission_denials 1 permission denial(s): Bash
why: python3 -m unittest needs approval, and dontAsk denies anything that would prompt, so the call is denied and the run 'succeeds' without running the tests.
tasks: 3/5 passed (pass^k); 3/5 pass@k
cost: $0.008768 recorded in the fixtures
as expected: 5/5 tasks match their `expect`
Replay graders are regression tests of the harness: the transcript never changes, so a pass here says the graders work, not that the model does. Use --real --trials N for that.
- Replay tests the harness, not the model: the transcript never changes, so a pass says the graders and the classification work.
- A run that hits its turn cap has no
resultfield at all, soresult_containsfails along withoutcome. - The tests never ran, yet the outcome is
completed. Onlyno_permission_denialscatches it;tool_called(Bash)passes, because a denied call still appears as atool_useblock. - This task's graders read
structured_output, never theresultstring. - pass^k counts tasks where every trial passed, pass@k tasks where any did. Gate CI on pass^k; with one replay per task they're the same.
- Every task matches its
expect, including the two meant to fail. That's the harness's own regression test.
--listprints every task with its graders;--task map-modules -vshows all seven graders for one task, not only the failures;--savealso writesagents-5/out/eval_report.json.- Write a task of your own. This one asks the
explore_readonlyanswer to namediscounts.py, which it doesn't, so the task fails, its row saysNOunder "as expected", and the harness exits 1:echo '{"tasks": [{"id": "names-discounts", "prompt": "List the modules in tinyapp/.", "fixture": "explore_readonly", "expect": "pass", "graders": [{"type": "outcome", "equals": "completed"}, {"type": "result_contains", "value": "discounts.py"}]}]}' > /tmp/lab-tasks.json python3 agents-5/eval_harness.py --tasks /tmp/lab-tasks.json - Break it: misspell a grader type, say
result_contians. The file is rejected before any run, with the list of known graders and exit code 2.
Measure the model instead of the harness. It costs money: every run is capped, in --permission-mode dontAsk, in a temp copy of tiny-app, with --allowedTools Read,Grep,Glob. Four tasks get --tools Read,Grep,Glob; run-tests-read-only also gets Bash, and dontAsk denies any command that would prompt. Several trials per task, because runs vary:
python3 agents-5/eval_harness.py --real --trials 3 --model haiku \
--max-budget-usd 0.05 --total-budget-usd 0.60
The harness enforces --total-budget-usd between runs and skips the rest once the next run could pass it; a run whose cost isn't reported counts as its full cap. Each per-run budget is checked against Claude Code's client-side estimate and can pass the cap by up to one response. The README describes a no-cost way to test the wiring with a stand-in binary (LAB_CLAUDE_BIN).
- "success" isn't "passed": check how the run ended in order, then
permission_denials, then the answer. - Graders read documented fields only:
result,structured_output,num_turns,total_cost_usd,permission_denialsand thetool_useblocks. - A replay suite guards the harness; real trials, gated on pass^k, guard the agent.
Read Claude Code's OpenTelemetry export
Turn an OTLP/JSON export of Claude Code metrics and events into the questions people ask: what did it cost, which tools ran and failed, what did hooks block, what happened for one prompt, and what personal data is in the stream.
- Python 3.9+
- standard library only
- offline:
agents-5/otel_sample/(metrics and logs) - a sample constructed from the docs
python3 agents-5/otel_reader.py
The sample was built from the monitoring docs, not captured from a real session, and its values are illustrative. otel_sample/README.md separates what's documented from what's assumed, such as where the event name sits in a log record; the reader accepts every variant.
┌────────────────────────────────────────────────────────────────────────┐
│ Agents 5 · otel_reader: Claude Code telemetry from an OTLP JSON export │
└────────────────────────────────────────────────────────────────────────┘
source: agents-5/otel_sample/metrics.json agents-5/otel_sample/logs.json
resource: service.name=claude-code, service.version=2.1.303, os.type=darwin, os.version=25.6.0, host.arch=arm64
data: 11 metric data points (6 sum); 27 events
metrics
sessions: {'fresh': 1}
cost (USD, approximate): {'claude-haiku-5-5': 0.002736}
tokens by type: {'cacheCreation': 14232, 'cacheRead': 59276, 'input': 20, 'output': 724}
GenAI input total: 73528 = input + cacheRead + cacheCreation ('input' alone excludes the cache)
lines of code: {'added': 6, 'removed': 1}
code edit decisions: {'Edit/accept/user_temporary': 1}
active time (s): {'cli': 18.2, 'user': 42.5}
events
by name: {'api_error': 1, 'api_request': 6, 'assistant_response': 2, 'hook_execution_complete': 1, 'hook_execution_start': 1, 'mcp_server_connection': 1, 'permission_mode_changed': 1, 'tool_decision': 6, 'tool_result': 5, 'user_prompt': 3}
not summarized below: permission_mode_changed
api_request: 6 requests, $0.002736, latency p50 1830.0 ms / p95 2480.0 ms, models {'claude-haiku-5-5': 6}
api tokens: {'input_tokens': 20, 'output_tokens': 724, 'cache_read_tokens': 59276, 'cache_creation_tokens': 14232}
api_error: HTTP 529 Overloaded after 3 attempt(s)
tool results
tool calls success mean ms max ms errors
──── ───── ─────── ─────── ────── ───────────────────
Edit 1 100% 27.0 27.0
Glob 1 100% 41.0 41.0
Read 3 67% 8.0 12.0 {'Error:ENOENT': 1}
tool decisions (rejections never produce a tool_result)
tool decision source count
──── ──────── ────────────── ─────
Bash reject hook 1
Edit accept user_temporary 1
Glob accept config 1
Read accept config 3
hooks
hook hooks ok blocking non-blocking err cancelled ms
─────────────── ───── ── ──────── ──────────────── ───────── ──
PreToolUse:Bash 1 0 1 0 0 38
mcp_server_connection: {'status': 'connected', 'transport_type': 'stdio', 'server_scope': 'project', 'duration_ms': 412, 'is_plugin': False}
per prompt (prompt.id)
prompt.id (tail) events API cost tool results rejected API errors
──────────────── ────── ─── ───────── ───────────────── ──────────── ──────────
00000000aa01 11 3 $0.001888 Glob Read Read - 0
00000000aa02 12 3 $0.000848 Edit Read(failed) Bash by hook 0
00000000aa03 2 0 $0.000000 - - 1
cross-check: cost metric $0.002736 vs sum of api_request.cost_usd $0.002736: match
privacy check
present user.email on 38 record(s): the signed-in user's email (always sent when available)
absent prompt text, tool input and tool parameters (their OTEL_LOG_* gates are off)
timeline for prompt.id a7c1e2d4-0002-4b6a-9f00-00000000aa02 (ordered by event.timestamp, then event.sequence)
time seq event detail
──────────── ─── ─────────────────────── ──────────────────────────────────────────────────────────────
10:02:00.000 12 user_prompt prompt_length=71
10:02:01.800 13 api_request claude-haiku-5-5 1720ms $0.000330 in=9 cacheRead=12192 out=95
10:02:01.820 14 hook_execution_start PreToolUse:Bash hooks=1
10:02:01.860 15 hook_execution_complete PreToolUse:Bash blocking=1 ok=0
10:02:01.861 16 tool_decision Bash reject (source=hook)
10:02:04.100 17 api_request claude-haiku-5-5 2290ms $0.000282 in=2 cacheRead=13472 out=210
10:02:09.400 18 tool_decision Edit accept (source=user_temporary)
10:02:09.430 19 tool_result Edit success=true 27ms
10:02:09.500 20 tool_decision Read accept (source=config)
10:02:09.520 21 tool_result Read success=false 3ms Error:ENOENT
10:02:11.900 22 api_request claude-haiku-5-5 2380ms $0.000235 in=2 cacheRead=13812 out=88
10:02:11.910 23 assistant_response response_length=233
Cost metrics are approximations, not billing data; use your provider's console for that.
- The
inputtoken type excludes cache reads and writes. Add all three for the full input, as the GenAI conventions count it. - One blocked Bash call, three ways: a
tool_decisionwith sourcehook, ahook_execution_completewith one blocking result, and notool_result, because rejections never produce one. - The cost metric and the sum of
api_request.cost_usdagree: two views of the same client-side estimate, not billing data. user.emailis on every record when available, while prompt text and tool input stay out until you turn on theirOTEL_LOG_*variables.- Correlate by
prompt.idand order byevent.timestampfirst:event.sequencerestarts per process.
--envprints the export block to paste into your shell:CLAUDE_CODE_ENABLE_TELEMETRY=1, the two OTLP exporters,OTEL_EXPORTER_OTLP_PROTOCOL=http/json(it has no default), the endpoint and the intervals.--prompt a7c1e2d4-0001-4b6a-9f00-00000000aa01shows the first prompt's timeline, where twoReaddecisions share a timestamp (10:00:08.750) andevent.sequence(6, 7) orders them.- Read your own capture with
--metrics m.json --logs l.json: each file can hold one export request as JSON or many as JSONL, the way a collector's file exporter writes them. Bind any local collector to127.0.0.1.
- Telemetry is opt-in, and exporter variables in a repo's
.claude/settings.jsonare ignored: set them in your shell,~/.claude/settings.jsonor managed settings. - A blocked call has no
tool_result, so tool-failure dashboards built on results alone never see it. - The sample predates
claude_code.safety_event(v2.1.307+), "Logged when a check refuses a tool call or requires a permission prompt" (monitoring), with the call'stool_use_idin most cases. - Run the privacy check before a stream goes to a shared collector.