# Autonomy 4: Automating Work Beyond Code

Two kits for pushing Claude Code into automation. The first is a set of hooks that react to session events. The second is a CI pipeline that turns a labeled issue into a draft pull request.

| Lab | What it does | Session topics |
|---|---|---|
| `hooks_pipeline/` | `kit/.claude/` has eight hook scripts on nine events. They add context at session start, block credentials in prompts, deny destructive commands, ask before a push, add `--ignore-scripts` to every npm install (`npm ci`, `npm install-test`, ...), protect secrets and lockfiles, give feedback after edits, add hints after a failed test run, refuse the first stop that no passing test run covers (a one-time nudge, not a gate), and keep an audit log. `test_hooks.py` validates `settings.json`, runs 49 cases with documented payloads through `common/hooks.run_hook`, proves the failure modes (fail closed vs fail open, a hook that hangs), and traces a scripted session through every hook. | Hooks (events, inspecting and blocking, rewriting inputs, adding context, failure behavior), Push systems (context at session start, prompt-time context) |
| `gha_pipeline/` | `kit/.github/` is an issue-to-PR workflow on `anthropics/claude-code-action@v1`. A router with no AI classifies the issue. Claude implements it on the job's read-only `GITHUB_TOKEN`, inside the sandbox, with credentials scrubbed from its subprocesses. A job with no secrets reruns the tests on the patch, and only then does a third job push it and open a draft PR. Escalation and needs-info paths comment on the issue. `validate_pipeline.py` checks the workflow with documented action inputs, the token Claude really holds, sandbox settings and GitHub hardening rules. It takes apart an unsafe example and dry-runs six recorded `issues` events through the real router and the jobs' `if:` conditions. | Pipelines (headless in CI, GitHub Actions, classify / route / execute / verify), Events (issues and pull requests), Boundaries (budgets, permissions, failure containment, human checkpoints) |

## Run

```bash
cd labs
python3 autonomy-4/hooks_pipeline/test_hooks.py          # 56 checks, exit 1 on any failure
python3 autonomy-4/hooks_pipeline/test_hooks.py --only bash -v
python3 autonomy-4/gha_pipeline/validate_pipeline.py     # validate the kit, the unsafe example, and the dry run
python3 autonomy-4/gha_pipeline/validate_pipeline.py --workflow path/to/your.yml --repo-root path/to/repo
```

Both labs run offline. The hook scripts and the router script really execute, in temp directories. Results go to `autonomy-4/out/`.

## Install

- **Hooks:** `cp -r autonomy-4/hooks_pipeline/kit/.claude <repo>/`. Merge `settings.json` by hand if you already have one. Then run `/hooks` in a session to see them listed. Rerun `test_hooks.py` after every change.
- **Workflow:** `cp -r autonomy-4/gha_pipeline/kit/.github <repo>/`.
  1. Add the `ANTHROPIC_API_KEY` secret. The kit doesn't need the Claude GitHub App, because the implement job passes its own read-only `github_token`. (`/install-github-app` installs the App and adds the secret.)
  2. Create the labels `claude:implement`, `size:S`, `size:M`, `size:L` and `claude:needs-human`.
  3. Let GitHub Actions create pull requests: Settings > Actions > General.
  4. Label an issue that has an "## Acceptance criteria" section with `- [ ]` checkboxes.

  PRs that `GITHUB_TOKEN` opens don't start other workflows. If CI must run on them, use a GitHub App token in `open_pr`. Each run costs Actions minutes and tokens.

  How the workflow keeps Claude's job read-only:
  - `github_token: ${{ github.token }}` with `contents: read`. Without that input the action uses the Claude GitHub App's token, which can write regardless of the job's `permissions:`. That job has no `id-token: write`, because it's needed only for App or cloud-federation auth.
  - `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1` removes the Anthropic and cloud credentials from Claude's subprocesses. It keeps `GITHUB_TOKEN`, so `.github/claude/ci-settings.json` also denies `GITHUB_TOKEN` and `GH_TOKEN` to sandboxed commands.
  - The sandbox setting (`sandbox.enabled`, `failIfUnavailable`, `allowUnsandboxedCommands: false`, `autoAllowBashIfSandboxed: false`, no allowed domains). A step before it installs bubblewrap and socat, plus the AppArmor profile Ubuntu 24.04 needs. If the sandbox can't start, the run fails instead of going on unsandboxed.
  - `persist-credentials: false` on checkout, so the token isn't left in `.git/config`.
  - Concurrency is set on the implement, verify and open_pr jobs, one group per issue and job, with `cancel-in-progress: false`. A workflow-level group would let any later label event on the issue cancel a pending implement run.
  - `PYTHONDONTWRITEBYTECODE=1` on the implement and verify jobs, and the patch excludes `__pycache__` and `*.pyc`, so test runs don't leak bytecode into the PR.
  - The `verify` job has `contents: read` and no secrets. It applies the uploaded patch and runs the tests, so Claude can't fake a pass. `open_pr` runs no repository code, and commits with `--no-verify`.
  - When a job after routing fails, `escalate` labels the issue `claude:needs-human` and its comment names the job (implement, verify or open_pr) with a link to the run.

These hooks run with your user permissions. They are defense in depth: a deny holds in every permission mode, but a hook only sees the command text Claude wrote. The boundary is permission deny rules plus the sandbox. Gates fail closed: they deny on bad input, and `settings.json` sets `"onFailure": "block"` (Claude Code v2.1.295+). Observers fail open.

## What you'll see

`test_hooks.py`, a few of the 49 cases:

```text
  ok   prompt: credential is blocked                  BLOCKED; decision=block; user sees: This prompt contains what looks like an AWS access key id, so it wasn't sent. Re
  ok   bash: force push denied                        BLOCKED; decision=deny; Claude reads: bash_guard: force-pushing rewrites shared history. If it's really needed, ask
  ok   bash: lease + if-includes asks, not denied     proceeds; decision=ask; user sees: bash_guard: pushing publishes this branch; confirm the remote and branch
  ok   bash: -fu flag cluster denied                  BLOCKED; decision=deny; Claude reads: bash_guard: force-pushing rewrites shared history. If it's really needed, ask
  ok   bash: +refspec force push denied               BLOCKED; decision=deny; Claude reads: bash_guard: force-pushing rewrites shared history. If it's really needed, ask
  ok   bash: git -C dir push --force denied           BLOCKED; decision=deny; Claude reads: bash_guard: force-pushing rewrites shared history. If it's
  ok   bash: download piped to python3                BLOCKED; decision=deny; Claude reads: bash_guard: piping a download straight into a shell or an
  ok   bash: no command string                        BLOCKED; decision=deny; Claude reads: bash_guard couldn't check this command (ValueError), so it
  ok   bash: npm ci rewritten                         proceeds; decision=ask; updatedInput={"command": "npm ci --ignore-scripts", "description": "Insta; user sees: bash_g
  ok   bash: every npm install rewritten              proceeds; decision=ask; updatedInput={"command": "npm ci --ignore-scripts && npm install --ignor
  ok   bash: npm install-test rewritten               proceeds; decision=ask; updatedInput={"command": "npm install-test --ignore-scripts", "descriptio; user sees: bash_guard
  ok   file: traversal to .env                        BLOCKED; decision=deny; Claude reads: protect_files: .env looks like a secret; edit it yourself, outside Claude Code
  ok   file: .ENV in capitals                         BLOCKED; decision=deny; Claude reads: protect_files: config/.ENV looks like a secret; edit it yourself, outside Clau
  ok   file: .env.example is fine                     proceeds
  ok   file: .aws/credentials                         BLOCKED; decision=deny; Claude reads: protect_files: deploy/.aws/credentials looks like a secret
  ok   file: symlink to .env                          BLOCKED; decision=deny; Claude reads: protect_files: .env looks like a secret; edit it yourself,
  ok   post-edit: float in an indented Edit fragment  proceeds; context: tinyapp/cart.py: this edit adds float literal(s) 0.1. tinyapp keeps money in integer cents
  ok   post-edit in a worktree: float check fires     proceeds; context: tinyapp/pricing.py: this edit adds float literal(s) 1.0. tinyapp keeps money in integer ce
  ok   post-edit: syntax error fed back               proceeds; decision=block; Claude reads: tinyapp/broken.py no longer compiles: invalid syntax (line 1). Fix it before
  ok   stop: edit not covered by a passing run        BLOCKED; decision=block; Claude reads: You changed tinyapp/cart.py after the last passing test run. Run `python3 -m
  ok   stop: already continuing (stop_hook_active)    proceeds; user sees: stop_check: tinyapp/cart.py changed after the last passing test run, and Claude stopped an
```

A push with `--force-with-lease --force-if-includes` only asks; `--force`, `-f` in a flag cluster and a `+refspec` are denied, also behind git's global options (`git -C dir`, `git -c key=value`). A Bash payload without a command string is denied, because a gate fails closed. `protect_files` ignores case, lets env templates such as `.env.example` through, and judges a symlink by the file it points to. The float check reads the edited region from the file on disk, because an Edit's `new_string` is usually an indented fragment that won't tokenize on its own.

The worktree cases set `CLAUDE_PROJECT_DIR` to the main checkout and the input's `cwd` to `.claude/worktrees/wt`, which is how a session looks after Claude enters a worktree. The hooks that look at Claude's files (`post_edit_check`, `protect_files`, `session_context`) use the git toplevel of `cwd`, so the float check still fires and the branch is the worktree's. `CLAUDE_PROJECT_DIR` only locates the kit's own files, such as the audit log. A test run counts when it's `python3 -B -m unittest` too, but `pip install pytest` isn't one.

The failure modes, side by side. The hang cases use a real subprocess with a 0.5-second timeout:

```text
[3] Failure modes
ok  bash_guard gets malformed stdin                  in-script fail closed  blocked
ok  gate crashes, onFailure=block                    exit 1 is a failure    blocked
ok  gate crashes, onFailure=continue                 exit 1 is a failure    proceeds
ok  gate hangs past its timeout, onFailure=block     timed out              blocked
ok  gate hangs past its timeout, onFailure=continue  timed out              proceeds
ok  Stop hook crashes, onFailure=block               no effect on Stop      stops
ok  additionalContext at the top level               ignored + warning      no context
```

The pipeline trace is one session from start to end. The first Stop is refused because the last test run failed after the edit. The second Stop has `stop_hook_active: true`, and `stop_check.py` lets that one through whatever the tests say (it only tells the user if they still don't cover the edit). That's why it's a one-time nudge and not a gate; for a gate, see `autonomy-1/goal_gate`, and keep CI as the real check:

```text
  PreToolUse Write .env              BLOCKED  [protect_files.py]
      BLOCKED; decision=deny; Claude reads: protect_files: .env looks like a secret; edit it yourself, outside Claude Code
  PostToolUseFailure Bash tests      ok       [failure_hint.py]
      proceeds; context: The test run failed. Read the first failure, fix the code (not the test) unless the test i
  Stop                               BLOCKED  [stop_check.py]
      BLOCKED; decision=block; Claude reads: You changed tinyapp/pricing.py after the last passing test run. Run `python3 -m unittest`,
  PostToolUse Edit test_pricing.py   ok       [post_edit_check.py]
  PostToolUse Bash tests             ok       [audit_log.py]
  Stop (continuing after the block)  ok       [stop_check.py]
  SessionEnd                         ok       [audit_log.py]

56/56 checks passed, 0 settings error(s); wrote autonomy-4/out/hooks_pipeline/results.json
```

`validate_pipeline.py`. The kit has no errors. The unsafe example trips most of the checks:

```text
[1] Validate autonomy-4/gha_pipeline/kit/.github/workflows/claude-issue-to-pr.yml
  NOTE    jobs.implement: Claude runs on the job's read-only GITHUB_TOKEN; open_pr pushes the verified patch; commits and PRs made with GITHUB_TOKEN don't start other workflows, so use an app token there if CI must run on them
[2] The same checks on a deliberately unsafe workflow (bad/claude-unsafe.yml)
  ERROR   on.pull_request_target: runs with secrets and a write token on fork PRs; checking out and running PR code there is the classic Actions takeover
  ERROR   jobs.claude.steps[1] (Echo the request): `${{ github.event.comment.body }}` inside run: is script injection; pass it through env: and quote the variable
  ERROR   jobs.claude.steps[2]: @beta: upgrade to @v1 (drop mode, direct_prompt -> prompt, options into claude_args)
  ERROR   jobs.claude.steps[2].with.max_turns: a beta-era input: move it into claude_args as --max-turns
  ERROR   jobs.claude.steps[2].with.anthropic_api_key: pass credentials only as ${{ secrets.NAME }}; never commit a key or token
  ERROR   jobs.claude.steps[2].with.claude_args: --dangerously-skip-permissions removes every permission check; never in CI
  ERROR   jobs.claude.steps[2].with.claude_args: --allowedTools 'Bash' pre-approves every shell command
  WARNING jobs.claude: issue_comment runs on every comment: gate the first job with if: contains(github.event.comment.body, '@claude')
  WARNING jobs.claude.steps[2].with.allowed_bots: '*' lets any bot trigger Claude (bot loops)
  WARNING jobs.claude: actions/checkout leaves the job token in .git/config, where Claude's Bash can read it; set persist-credentials: false
```

Delete the `github_token` line from the kit (exercise 2), and the validator reports two problems. It warns that Claude now holds the App's token, which can write whatever `permissions:` says. It also raises an error because App authentication needs `id-token: write`.

In the dry run, only the ready issue reaches Claude. The injection attempt goes to a human before any model sees it:

```text
[3] Dry run: recorded `issues` events through the router and the jobs' if: conditions
    event           route                turns  jobs that run                            reason
ok  01_ready        implement            15     route -> implement -> verify -> open_pr  ready
ok  02_no_criteria  needs-info           0      route -> ask_for_info                    the issue has no acceptance criteria written as - [ ] checkb
ok  03_injection    needs-human          0      route -> escalate                        the issue text contains instruction-like or secret-seeking p
ok  04_too_big      needs-human          0      route -> escalate                        size:L is too big for one unattended run; split it into smal
ok  05_bot_label    skip                 0      route                                    a bot applied the label
ok  06_other_label  (route job skipped)  -      nothing runs
  if: evaluator self-checks: 9/9 as GitHub evaluates them
  01_ready if implement fails: route -> implement (failure) -> escalate
  01_ready if verify fails: route -> implement -> verify (failure) -> escalate
  Jobs after route are assumed to succeed offline unless shown failing: no model runs here.
```

## Formats and where they come from

| Encoded format | Source (fetched 2026-10-20) |
|---|---|
| Hook events, matcher rules, input fields per event, decision control (`permissionDecision`, `updatedInput`, `decision: "block"`, `additionalContext`, `systemMessage`), exit codes, `onFailure`, timeouts, `stop_hook_active` | https://code.claude.com/docs/en/hooks , https://code.claude.com/docs/en/hooks-guide |
| PostToolUse `tool_response` for Bash (`stdout` holds stdout and stderr merged, `stderr` the tool's own notices, `interrupted`) and Edit/Write | https://code.claude.com/docs/en/agent-sdk/typescript#tool-output-types |
| `CLAUDE_PROJECT_DIR` stays at the main checkout; the input `cwd` follows Claude into a worktree | https://code.claude.com/docs/en/worktrees , https://code.claude.com/docs/en/hooks |
| `anthropics/claude-code-action@v1` inputs (`prompt`, `claude_args`, `settings`, `github_token`, auth inputs, `allowed_bots`, `allowed_non_write_users`), the App token used when `github_token` is omitted, automation vs interactive mode, `id-token: write`, upgrade from beta | https://code.claude.com/docs/en/github-actions |
| `--allowedTools` and settings rule syntax | https://code.claude.com/docs/en/permissions |
| `sandbox.*` keys (`enabled`, `failIfUnavailable`, `allowUnsandboxedCommands`, `autoAllowBashIfSandboxed`, `network.allowedDomains`, `credentials`), Linux dependencies | https://code.claude.com/docs/en/sandboxing , https://code.claude.com/docs/en/settings-reference |
| `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` (what it removes and what it keeps) | https://code.claude.com/docs/en/env-vars |
| Workflow syntax (`on`, `jobs`, `needs`, `if`, `outputs`, `permissions`, `concurrency` and how a queued run cancels the pending one, `timeout-minutes`), `GITHUB_OUTPUT`, case-insensitive `==` in expressions | https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions |
| Script injection and `pull_request_target` | https://docs.github.com/en/actions/security-for-github-actions/security-guides/security-hardening-for-github-actions |
| The fixture events (`action`, `issue`, `label`, `repository`, `sender`) | https://docs.github.com/en/webhooks/webhook-events-and-payloads#issues |

`events/expected.json`, the audit log format and `reminders.md` are lab files. The YAML reader in `gha_pipeline/_yaml_subset.py` covers the subset that workflows use, and it refuses anything else rather than guess: anchors, multi-line plain scalars, tab indentation, and a plain value that contains `: ` (real parsers reject that one too, so the kit's comment steps use `run: |`). The dry run assumes the jobs after route succeed, apart from the ones it shows failing, because no model runs offline.
