# Autonomy 1: Autonomous Claude Code

Two labs about giving Claude Code more autonomy without losing control: one decides how much autonomy a task gets, the other gates an unattended loop on a check that really runs.

| Lab | What it does | Session topics |
|---|---|---|
| `autonomy_ladder.py` | Maps each task profile in `ladder/tasks.json` to a rung on a six-step ladder of permission modes (`plan`, `default`, `acceptEdits`, `auto`, `dontAsk` with a pre-approved scope, `bypassPermissions`). For each task it prints the rung, the binding cap, the exact command line, the settings rules, the `--max-turns`/`--max-budget-usd` caps and the checkpoints. It then promotes or demotes task types from a run history, reading `stop_reason` first, then `terminal_reason`, then `subtype`. | Autonomy (the permission ladder, trust calibration, bounded independence), Control (turn and budget limits) |
| `goal_loop.py` + `goal_gate/kit/` | A real Stop hook, `goal_gate.py`, runs your checks every time Claude tries to stop. It blocks with the failure as the reason, escalates when its own budget runs out, and writes an evidence file. `goal_loop.py` drives it through nine scripted scenarios against a temp copy of `common/samples/tiny-app`, and the tests in those scenarios really run. | Control (`/goal` conditions, cancellation, escalation), Observation and Recovery (failures, retries) |

## Run

```bash
cd labs
python3 autonomy-1/autonomy_ladder.py                 # nine sample tasks
python3 autonomy-1/autonomy_ladder.py --quiet         # decision table only
python3 autonomy-1/autonomy_ladder.py --task "Fix flaky test" --writes repo --verification tests \
    --unattended --environment ci --track-record 3 --size S
python3 autonomy-1/goal_loop.py                       # scenarios A-I
python3 autonomy-1/goal_loop.py --scenario B --verbose
```

Both labs run offline: no model calls, no network, no `claude` binary. They write only to `autonomy-1/out/` and to temp copies of the sample repo, which are deleted at exit.

## Install the goal gate in a repo

```bash
cp -r autonomy-1/goal_gate/kit/.claude <your-repo>/   # merge settings.json by hand if you already have one
# then edit <your-repo>/.claude/goal.json
```

In `goal.json`, set the goal text, the checks (argv lists, no shell strings), `max_check_seconds`, `max_continuations`, `max_wall_minutes` and `max_deferrals`.

Then make your pipeline trust the evidence and nothing else. A run passes only if `.claude/goal-gate/status-<session_id>.json` says `"verified": true`.

How the gate behaves:
- **Fail closed.** Every stop first overwrites the evidence with `"checking"`, so a crash, a timeout or an unreadable state file can't leave an earlier `verified` record standing.
- **Checks run where Claude works.** The gate runs its checks in the git toplevel of the hook input's `cwd`, which follows Claude into a worktree. `CLAUDE_PROJECT_DIR` stays at the project root where the session started, so the gate uses it only to find `goal.json` and the evidence folder.
- **Trust.** The gate is a real hook that runs commands with your permissions, so install it only in repos you trust.
- **Defense in depth.** The gate decides when a run may stop. It doesn't limit what Claude can do while it works: permission deny rules and the sandbox do that.

## What you'll see

`autonomy_ladder.py`. The "needs" column is the rung the job asks for: who is watching, and does it write? The "may" column is the rung its risk profile allows:

```text
task                    needs  may  rung  mode         turns  budget  status     binding cap
──────────────────────  ─────  ───  ────  ───────────  ─────  ──────  ─────────  ──────────────────────────────────────────────────────────
map-discounts           0      4    0     plan         5      $0.20   ready      none: the task needs only rung 0
nightly-audit           4      4    4     dontAsk      5      $0.20   ready      none: the task needs only rung 4
case-insensitive-codes  2      3    2     acceptEdits  10     $0.40   ready      none: the task needs only rung 2
refactor-receipt        3      4    3     auto         25     $1.00   ready      none: the task needs only rung 3
dependency-bumps        4      4    4     dontAsk      25     $1.00   ready      none: the task needs only rung 4
unattended-new-feature  4      3    2     acceptEdits  40     $1.60   NOT READY  track record 0 < 3 clean runs: earn unattended runs first
copy-tweak              4      2    2     acceptEdits  10     $0.40   NOT READY  verification=manual: no check a machine can run, so a huma
rotate-tax-table        4      1    1     default      25     $1.00   NOT READY  irreversible external write: a human approves each irrever
sandbox-fuzz            4      5    4     dontAsk      25     $1.00   ready      none: the task needs only rung 4
```

The container task may go up to rung 5, but it doesn't need more than rung 4, so no card gets a bypass command. A task that isn't ready to run unattended falls back to the rung it would get with someone watching. That's why `unattended-new-feature` gets rung 2.

The production database task is capped at rung 1. Its card splits the work, puts the risky commands in `permissions.ask` (no mode auto-approves an explicit ask rule) and denies reads of the credential folders, because built-in read-only commands such as `cat` never prompt:

```text
rotate-tax-table: Apply the new tax table to the production pricing database
  rung: 1 Approve edits and commands (mode default)  status NOT READY
    - cap 1: irreversible external write: a human approves each irreversible step
  command: claude --worktree rotate-tax-table --permission-mode default
  settings: {"permissions": {"deny": ["Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)", "Read(~/.ssh/**)", "Read(~/.aws/**)", "Read(~/.config/gh/**)"], "ask": ["Bash(psql *)", "Bash(git push *)", "Bash(terraform apply *)"]}, "sandbox": {"enabled": true, ...
    split: an unattended run (rung 4, repo writes only) prepares the change as a reviewed PR with a dry-run report; a human applies it at rung 1
    note: the config value is `default`; every UI calls it Manual (CLI alias `manual`)
```

Trust calibration reads `ladder/run_history.jsonl`, whose lines wrap a result event's documented fields. It checks them in the docs' order, `stop_reason`, then `terminal_reason`, then `subtype` ([ResultError](https://code.claude.com/docs/en/agent-sdk/python#resulterror)). `weekly-digest`'s last run isn't a refusal and says `subtype: "success"`, but it ended on an API error, so it counts neither for nor against the task. A refusal (`stop_reason: "refusal"`) is never ignored that way, even when its `terminal_reason` reads `api_error`: it isn't clean, so as the last run it demotes the task type, and earlier it breaks the clean streak:

```text
task type               runs  rung  clean streak  spend  advice
docs-sync               3     4     0             $1.20  demote to rung 3 (terminal_reason=max_turns, subtype=error_max_turns, 1 permission denial(s); review the transcript before retrying)
refactor-receipt        4     2     4             $1.05  promote to rung 3 (4 clean runs in a row)
weekly-digest           2     4     1             $0.09  stay at rung 4 (1 clean in a row; rung 4 is the top outside a disposable container) [1 inconclusive run(s) ignored: an API failure says nothing about the task]
```

`goal_loop.py`, scenario A. The scripted Claude writes a test and claims it's done. The gate runs the suite, blocks, and passes Claude the failure. The second stop passes:

```text
[A] converges: "Make discount codes case-insensitive and add a test"
  turn 1  tests/test_pricing.py: + test_lowercase_code               tools=2 $0.042  says: Done: discount codes are case-insensitive and there's a tes…
          Stop -> BLOCK (gate continuation 1, in a row: 1)
          Claude reads: FAIL: test_lowercase_code (tests.test_pricing.DiscountTest); AssertionError: 0 != 200; Continuation 1 of 3
  turn 2  tinyapp/pricing.py: apply_discount upper-cases the code    tools=2 $0.051  says: Fixed apply_discount to upper-case the code; the suite pass…
          Stop -> allowed
  pipeline: naive (exit code only) PASS, evidence-based PASS (verified); tests actually pass
```

Scenarios H and I cover the two ways a gate can be fooled. In H, the work happens in a worktree. In I, earlier evidence survives a broken gate:

```text
[H] Claude works in a worktree: "Make discount codes case-insensitive and add a test"
    setup: the edits land in .claude/worktrees/feature; CLAUDE_PROJECT_DIR stays at the project root
  turn 1  tests/test_pricing.py: + test_lowercase_code               tools=2 $0.042  says: Done: discount codes are case-insensitive and there's a tes…
          Stop -> BLOCK (gate continuation 1, in a row: 1)
          Claude reads: FAIL: test_lowercase_code (tests.test_pricing.DiscountTest); AssertionError: 0 != 200; Continuation 1 of 3
  turn 2  tinyapp/pricing.py: apply_discount upper-cases the code    tools=2 $0.051  says: Fixed apply_discount to upper-case the code; the suite pass…
          Stop -> allowed
  a gate that ran the tests in CLAUDE_PROJECT_DIR would have seen them pass on every stop; this gate checks the input's cwd
  outcome: stopped
  pipeline: naive (exit code only) PASS, evidence-based PASS (verified); tests actually pass

[I] stale evidence from an earlier turn: "Check that the suite is green"
    setup: turn 1 is verified; before turn 2's stop the gate's state file gets damaged
  turn 1  no edits                                                   tools=1 $0.012  says: The suite is already green.
          Stop -> allowed
  human: "Now make discount codes case-insensitive and add a test."
          (the gate's state file is now unreadable)
  turn 2  tests/test_pricing.py: + test_lowercase_code               tools=2 $0.042  says: Done: discount codes are case-insensitive and there's a tes…
          Stop -> allowed, user sees: goal gate error: the gate's state file state-goal-lab-I.json is unreadable (JSONDecodeErr…
  outcome: stopped
  pipeline: naive (exit code only) PASS, evidence-based FAIL (state=gate_error); tests actually FAIL
```

The summary shows why the pipeline trusts evidence rather than exit status:

```text
   scenario                                    turns  blocks  spend  result subtype        gate state  escalations  naive  evidence  tests
─  ──────────────────────────────────────────  ─────  ──────  ─────  ────────────────────  ──────────  ───────────  ─────  ────────  ─────
A  converges                                   2      1       $0.09  success               verified    0            PASS   PASS      pass
B  conflicting requirement -> escalates        4      3       $0.20  success               escalated   1            PASS   FAIL      FAIL
C  typo in goal.json, naive gate (fails open)  1      0       $0.04  success               -           0            PASS   FAIL      FAIL
D  same typo, the kit's gate (fails closed)    1      0       $0.04  success               gate_error  1            PASS   FAIL      FAIL
E  dollar cap trips first                      3      2       $1.65  error_max_budget_usd  not_met     0            FAIL   FAIL      FAIL
F  background work defers the check            2      0       $0.04  success               verified    0            PASS   PASS      pass
G  a hook that always blocks                   9      8       $0.05  success               -           0            PASS   FAIL      pass
H  Claude works in a worktree                  2      1       $0.09  success               verified    0            PASS   PASS      pass
I  stale evidence from an earlier turn         2      0       $0.05  success               gate_error  1            PASS   FAIL      FAIL
  The naive pipeline passed failing code in scenario B, C, D, I; the evidence check didn't.
```

Each escalation is one JSON line in `out/goal_loop/<scenario>/gate/escalations.jsonl`, and it carries the failing assertion (`last_tail` shortened here):

```text
{"session_id": "goal-lab-B", "reason": "gate_budget_used", "detail": "3 continuation(s) used of 3", "goal": "The test suite passes: python3 -m unittest exits 0", "failed_checks": ["python3 -m unittest -q"], "last_tail": "...    self.assertEqual(tax_for(1000, \"ny\"), 40)\nAssertionError: 45 != 40\n\n...\nRan 13 tests\n\nFAILED (failures=1)", "at": "2026-10-20T09:08:00Z"}
```

Each `status-<session_id>.json` records the `workdir` the checks ran in. For scenario H that's `<tiny-app copy>/.claude/worktrees/feature`; the lab replaces the temp path so `out/` is the same on every run.

## Formats and where they come from

| Encoded format | Source (fetched 2026-10-20) |
|---|---|
| Stop hook input (`stop_hook_active`, `last_assistant_message`, `background_tasks`, `cwd`), `decision: "block"` + `reason`, `systemMessage`, the 8-continuation cap that resets on every tool call | https://code.claude.com/docs/en/hooks#stop , https://code.claude.com/docs/en/hooks-guide |
| `hooks` block in `settings.json` (`type`, `command`, `timeout`, `statusMessage`); Stop has no matcher support; `onFailure` has no effect on Stop | https://code.claude.com/docs/en/hooks |
| `CLAUDE_PROJECT_DIR` stays at the session's project root; the input `cwd` follows Claude into a worktree | https://code.claude.com/docs/en/worktrees |
| `/goal` (a session-scoped prompt-based Stop hook whose evaluator reads only the conversation) | https://code.claude.com/docs/en/goal |
| Permission modes and what each runs without asking; bypass only in isolated containers | https://code.claude.com/docs/en/permission-modes |
| Built-in read-only commands run without a prompt; Read deny rules cover the file commands Claude Code recognizes in Bash | https://code.claude.com/docs/en/permissions#read-only-commands |
| `permissions.allow/ask/deny`, `sandbox.enabled`, `sandbox.failIfUnavailable`, `sandbox.filesystem.denyRead` | https://code.claude.com/docs/en/settings-reference |
| `claude -p` flags (`--allowedTools`, `--permission-mode dontAsk`, `--max-turns`, `--max-budget-usd`, `--worktree`) | https://code.claude.com/docs/en/headless , https://code.claude.com/docs/en/cli-reference |
| Result event fields in `run_history.jsonl` (`terminal_reason`, `subtype`, `is_error`, `num_turns`, `total_cost_usd`, `permission_denials`, `errors`, `api_error_status`); calibration also reads `stop_reason` when a line has it | https://code.claude.com/docs/en/agent-sdk/typescript#sdkresultmessage ; check order: https://code.claude.com/docs/en/agent-sdk/python#resulterror |

`ladder/tasks.json`, the outer wrapper in `run_history.jsonl` (`task_type`, `rung`, `verified`, `escalated`) and `goal.json` are lab formats, not Claude Code files. The budget numbers are illustrative: they use the list prices in `common/llm.py`, and `--max-budget-usd` is checked against a client-side estimate, not your bill.

## Limits of the simulation

- The scripted Claude is a fixed list of turns. It doesn't decide anything, but the hook, its JSON output and the tests are real.
- The docs don't say whether a Stop hook fires after `--max-budget-usd` ends a run, so scenario E assumes it doesn't. The evidence file still shows the previous stop's `not_met`.
- The sample repo isn't a git repo, so in scenario H the gate falls back to the input `cwd` itself rather than its git toplevel.
- `num_turns` in a real result event doesn't match these "turns" one for one. Read it from the result event (see `labs/README.md`).
