# Agents 5 labs: guard hooks, evals, telemetry

Three ways to keep an agent honest after you've built it: a PreToolUse guard that fails closed, an eval harness with deterministic graders, and a reader for Claude Code's OpenTelemetry export. Everything runs offline by default with Python 3.9+ and the standard library. Only `eval_harness.py --real` calls the model, and it says so before it starts.

| Lab | What it is | Run (from `labs/`) |
|---|---|---|
| `guard_hooks/` | A kit to copy into a repo: `kit/.claude/hooks/guard.py` (PreToolUse guard) and `kit/.claude/settings.json` (registration with `"onFailure": "block"` plus matching permission deny rules). `test_guard.py` runs 44 table-driven cases through `common.hooks.run_hook`, plus 5 checks on the settings file. | `python3 agents-5/guard_hooks/test_guard.py` |
| `eval_harness.py` | Headless tasks in `evals/tasks.json` with code graders (outcome, result text and regex, tools called or not, turns, cost, tool errors, permission denials, structured output). Replay by default; `--real --trials N` for pass@k and pass^k under a total budget cap. | `python3 agents-5/eval_harness.py` |
| `otel_reader.py` | Summarizes an OTLP/JSON export of Claude Code metrics and events: cost, tokens, API latency, tool results and decisions, hooks, per-prompt timelines, a cost cross-check and a privacy check. Reads `otel_sample/` by default. | `python3 agents-5/otel_reader.py` |

`run_all.txt` lists the three entries `python3 run_all.py --only agents-5` runs.

## guard_hooks: a PreToolUse guard that fails closed

### Install

```bash
cp -r agents-5/guard_hooks/kit/.claude <your-repo>/        # overwrites an existing .claude/settings.json: check first
chmod +x <your-repo>/.claude/hooks/guard.py
```

If the repo already has a `.claude/settings.json`, copy only `hooks/guard.py` and merge the `permissions` and `hooks` blocks into that file by hand. (Hooks from different settings files merge; `cp` doesn't.) Then open `/hooks` in a session to confirm the registration. The kit registers the guard in exec form, so no shell quoting is involved:

```json
{
  "matcher": "Bash|Write|Edit|NotebookEdit",
  "hooks": [{"type": "command", "command": "python3",
             "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/guard.py"],
             "timeout": 10, "onFailure": "block"}]
}
```

`onFailure` requires Claude Code v2.1.295 or later. Older versions ignore it, so a crashed or timed-out guard lets the call through there.

### What it does

The guard reads the hook payload on stdin and answers in one of three ways:

- **Allow:** no output, exit 0. The guard has no opinion, so the normal permission flow (rules, mode, prompt) decides.
- **Deny or ask:** `hookSpecificOutput.permissionDecision` JSON on exit 0. For a deny, Claude sees the reason as the tool error.
- **Fail closed:** exit 2 with the reason on stderr, for anything it can't judge. That covers stdin that isn't JSON, a missing `tool_input`, a `command` that isn't a string, and any exception inside the guard.

It denies recursive `rm` of critical paths (`/`, `~`, `$HOME`, `.`, the project root, top-level system directories) and `--no-preserve-root`. It also denies force pushes that name main or master, or name no branch, and asks for other force pushes. Downloads piped or substituted into a shell (`curl … | bash`, `sh -c "$(curl …)"`) and recursive `chmod 777` are denied. Writes to `.env` / `.env.*`, `secrets/`, `.git/`, private keys and the guard's own files are denied, whether they come from Write, Edit or NotebookEdit or from shell redirects and `tee`.

### Limits

This is defense in depth, not the boundary:

- **It's string matching.** `bash -c '…'`, `python3 -c`, variables, `eval`, `git -C . push`, scripts written now and run later: many spellings get through. Claude Code's docs say the same about Bash permission rules, which aren't "a security boundary around the program".
- **It sees only `tool_input`.** It can't see what a command does at run time, or what MCP tools do. PowerShell isn't in the matcher.
- **The script can fail closed, but the hook around it can't.** If the interpreter is missing, the hook times out, or the process is killed, Claude Code applies `onFailure`, and the default is to let the call through. The kit sets `"onFailure": "block"`.
- **The boundary is permission deny rules plus the sandbox.** Deny rules block in every permission mode, including `bypassPermissions`, and the sandbox enforces file and network limits at the OS level for shell commands. That's why the kit ships deny rules too, and why you should turn on `/sandbox` where it's available. Two caveats from the permissions page:
  - **Mods.** Without managed settings, and without a Team or Enterprise `/login` as the session's credential (an API key or `CLAUDE_CODE_OAUTH_TOKEN` doesn't count), a mod you installed "can approve a call that a deny rule refuses or a `PreToolUse` hook blocked".
  - **What Read/Edit denies see.** They cover the Bash file commands and redirects Claude Code recognizes (`cat`, `head`, `tail`, `sed`, `tee`, `>`, `>>`, `<`), but not commands that read without naming the file (`grep -r .`) or scripts that open files themselves (`python3 x.py`). OS-level enforcement there is the sandbox.

### Output (`python3 agents-5/guard_hooks/test_guard.py`, excerpt)

```
      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  denied       deny-rm-root             deny         exit 0, deny              recursive rm of a critical path (/)
PASS  denied       deny-rm-project          deny         exit 0, deny              recursive rm of the project root (/tmp/cc-lab-demo/tiny-app)
PASS  denied       deny-force-head-master   deny         exit 0, deny              force push to main/master is not allowed
PASS  denied       deny-sh-subst            deny         exit 0, deny              piping a download straight into a shell runs code nobody revie
PASS  denied       deny-edit-guard          deny         exit 0, deny              the guard's own hook scripts are protected (a guard Claude can
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-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-nostart-continue  proceeds     couldn't start, proceeds  onFailure=continue: exec form, executable missing: can't start
PASS  onFailure    gotcha-missing-script    blocked      exit 2, BLOCKED           onFailure=continue: python3 exits 2 on a missing script: every

kit configuration
PASS  settings.json parses                   agents-5/guard_hooks/kit/.claude/settings.json
PASS  hook entry matches settings_snippet()  exec form, timeout 10, onFailure block
...
49/49 checks passed
```

The `onFailure` rows use stand-ins: a `sh -c '… exit 139'` crash, a missing executable, and the guard's test-only `GUARD_SELFTEST_FAULT=sleep`. They show what happens to the hook process, not to the guard's logic. The last row is a real gotcha: `python3 missing.py` exits 2, so a mistyped script path blocks every matching call even without `onFailure`.

## eval_harness.py: graders over headless runs

Each task in `evals/tasks.json` is a prompt, caps, a replay fixture, graders and an `expect` (pass or fail). Graders read only documented fields from the transcript, and the outcome check reads `stop_reason` first, then `terminal_reason`, then `subtype`, the order agent-sdk/python gives.

**Replay tests the harness, not the model.** The recorded transcript never changes, so a passing replay means the graders and the classification work. `--real` measures the model, and you need several trials per task because runs vary. Gate CI on pass^k (every trial passed), not pass@k (any trial passed).

```
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)

  run-tests-read-only trial 1 (replay):
    ✗ no_permission_denials  1 permission denial(s): Bash

  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`
```

Two tasks fail on purpose. A turn-limited run has no `result` text at all. The run-tests task ends `success` even though Bash was denied and no tests ran, which is why "success" isn't "passed". Its `tool_called(Bash)` grader passes, because the denied call still appears as a `tool_use` block: only `no_permission_denials` catches it.

The outcome check reads `stop_reason` first: `"refusal"` grades as `refusal` whatever `terminal_reason` and `subtype` say, because a declined response usually arrives as `subtype: "success"` and its `terminal_reason` can read `completed` or `api_error` ([ResultError](https://code.claude.com/docs/en/agent-sdk/python#resulterror)). Then `terminal_reason`: only `completed` counts as finished, so a result with `subtype: "success"` and `terminal_reason` `api_error`, `prompt_too_long`, `model_error` or `budget_exhausted` grades as `api_error`, `context_full`, `model_error` or `budget_limit`. Other documented stop reasons grade as `stopped`, and an undocumented one as `unknown`.

A bad tasks file exits 2 before any run: an unknown grader or `structured` op, a regex that doesn't compile, a missing or mistyped grader value, a bad cap, or a fixture that doesn't exist or doesn't parse. A fixture path (`.jsonl` or `.json`) is resolved against the tasks file's folder, so `--tasks` works from any directory. A `structured` grader with `op: "contains"` checks the value's type first: a number fails with a reason instead of crashing, a string can only contain a string, and an object is checked for a key.

Real runs go through `common.cc.run_headless`, the same as every other lab. Every run uses `--permission-mode dontAsk` in a temp copy of `common/samples/tiny-app`, capped by `--max-turns` and `--max-budget-usd`, with `--allowedTools Read,Grep,Glob`. Four tasks get `--tools Read,Grep,Glob` and are read-only. `run-tests-read-only` also makes Bash available (`--tools Bash,Read,Grep,Glob`), and dontAsk denies any command that would prompt, so only the built-in read-only commands could run; the notice says so before the first run. The harness also enforces `--total-budget-usd` between runs and skips the rest once the next run could pass the cap. A run whose cost isn't reported counts as its full cap.

```bash
python3 agents-5/eval_harness.py --real --trials 3 --model haiku --max-budget-usd 0.05 --total-budget-usd 0.60
```

To test the `--real` wiring without spending anything, point `LAB_CLAUDE_BIN` at a script that prints a fixture from `common/fixtures/stream/` and answers `--version`. `common.cc.find_claude()` honors that variable.

## otel_reader.py: Claude Code telemetry

Telemetry is opt-in. `python3 agents-5/otel_reader.py --env` prints the export block (`CLAUDE_CODE_ENABLE_TELEMETRY=1`, `OTEL_METRICS_EXPORTER=otlp`, `OTEL_LOGS_EXPORTER=otlp`, `OTEL_EXPORTER_OTLP_PROTOCOL=http/json`, the endpoint and intervals). `OTEL_EXPORTER_OTLP_PROTOCOL` has no default, and exporter variables in a repo's `.claude/settings.json` are ignored.

The sample in `otel_sample/` was constructed from the monitoring docs, not captured from a real session. `otel_sample/README.md` separates what is documented from what is assumed, such as where the event name sits in a log record, and the reader accepts every variant.

```
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)

events
  api_request: 6 requests, $0.002736, latency p50 1830.0 ms / p95 2480.0 ms, models {'claude-haiku-5-5': 6}
  api_error: HTTP 529 Overloaded after 3 attempt(s)

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

  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.860  15   hook_execution_complete  PreToolUse:Bash blocking=1 ok=0
10:02:01.861  16   tool_decision            Bash reject (source=hook)
10:02:09.400  18   tool_decision            Edit accept (source=user_temporary)
10:02:09.520  21   tool_result              Read success=false 3ms Error:ENOENT
...
```

One blocked Bash call shows up three ways: `hook_execution_complete` with `num_blocking` 1, a `tool_decision` with source `hook`, and no `tool_result`. Cost figures are approximations; use your provider's console for billing.

**A real capture was attempted.** During the agents-3 real run (2026-10-20, Claude Code v2.1.303), the run exported with `OTEL_*` set to `http/json` and a one-off receiver on `127.0.0.1`, but the receiver got no requests. The cause wasn't confirmed. A likely one is that managed settings controlled the OTLP destination: the monitoring page says managed settings remove conflicting endpoint variables a developer sets. So the sample stays constructed. On your own machine, follow `otel_sample/README.md` to capture one.

To read your own export, write it to files and pass `--metrics` and `--logs`. Each file can hold one export request as JSON, or many as JSONL, which is what a collector's file exporter writes. Repeated data points for the same attributes (one request per line, or delta temporality) are summed, for every metric including `code_edit_tool.decision`. Bind any local collector to `127.0.0.1`.

## Docs (fetched 2026-10-20)

- Hooks: https://code.claude.com/docs/en/hooks (PreToolUse input and decision control, exit code 2, `onFailure`, timeouts, exec form) and https://code.claude.com/docs/en/hooks-guide
- Permissions and their limits: https://code.claude.com/docs/en/permissions, https://code.claude.com/docs/en/permission-modes#critical-paths, https://code.claude.com/docs/en/sandboxing
- Headless runs and results: https://code.claude.com/docs/en/headless, https://code.claude.com/docs/en/agent-sdk/agent-loop, https://code.claude.com/docs/en/agent-sdk/structured-outputs, https://code.claude.com/docs/en/agent-sdk/cost-tracking
- Telemetry: https://code.claude.com/docs/en/monitoring-usage and the OTLP JSON encoding at https://opentelemetry.io/docs/specs/otlp/#json-protobuf-encoding
