# Autonomy 5: Self-Improving Claude Code Systems

Two labs that close the loop. The first mines transcripts for what people keep correcting and proposes a fix. The second proves a configuration change helps before anyone merges it.

| Lab | What it does | Session topics |
|---|---|---|
| `transcript_miner.py` | Reads seven lab-made sessions (`transcripts/*.jsonl`, in the documented stream-json message shape), finds the human corrections, splits each into directives and groups them by what they ask for. It also finds tool calls that failed the same way across sessions, and procedures people repeated. Each group gets the right kind of fix with its evidence: a hook when CLAUDE.md already says it and people still correct it, a path-scoped rule, a permission deny, a codebase-map line or a skill draft. Nothing is applied. | Feedback (transcripts, human corrections), Distillation (sessions into skills, rules), Governance (proposing) |
| `config_eval.py` | Compares three versions of the project config (`configs/A`, `B`, `C`: CLAUDE.md, rules, skills) on five tasks with outcome graders. It shows what each version loads before the first task, catches B's regression even though B's pass rate equals the baseline's, and applies a written promotion gate that also refuses incomplete or too-small evaluations. Replays recorded runs by default. `--real` runs the read-only tasks for real and saves the raw stream-json for re-grading. | Evaluation (baselines, regression checks, skill evals), Optimization (CLAUDE.md pruning, cost), Governance (testing, approving, rolling back) |

## Run

```bash
cd labs
python3 autonomy-5/transcript_miner.py
python3 autonomy-5/transcript_miner.py --transcripts DIR --claude-md ./CLAUDE.md   # DIR: your saved stream-json runs
python3 autonomy-5/config_eval.py
python3 autonomy-5/config_eval.py --real --configs A,C --tasks explain-tax --model haiku    # costs money, capped
python3 autonomy-5/config_eval.py --runs autonomy-5/out/config_eval/real-runs --configs A,C --tasks explain-tax
```

Both labs run offline by default and write only to `autonomy-5/out/`. `_build_fixtures.py` regenerates `transcripts/` and `eval/runs/` deterministically.

`--transcripts DIR` expects `*.jsonl` files in the documented stream-json message shape: saved `claude -p --output-format stream-json --verbose` runs, or Agent SDK messages serialized the same way. The sessions in `transcripts/` are lab-made fixtures in that shape. Claude Code's own session files under `~/.claude/projects/` are an internal format the docs don't specify, so the lab doesn't depend on them. The reader skips any line it doesn't recognize and redacts credential-like strings in quotes. Nothing leaves your machine.

## What you'll see

`transcript_miner.py` groups the corrections, then proposes one fix per group:

```text
[2] Corrections, grouped by what they ask for
  #1 cent-float-integer (2 session(s))
      s1-bulk-discount: "No, don't use floats for money. Integer cents only, like CLAUDE.md says."
      s6-rounding: "Stop using floats here. Cents are integers."
  #2 run-test-before (3 session(s))
      s1-bulk-discount: "You also didn't run the tests before saying done."
      s2-save5: "Please run the tests before you finish."
      s7-receipt: "run the test suite first, then tell me it's done."
  #5 pass-test-change (2 session(s))
      s6-rounding: "Don't change the tests to make them pass. Fix the code."
      s7-receipt: "Don't edit the tests so they pass"
[3] Proposals (nothing is applied)

  Enforce: run-test-before  ->  hook   [3 sessions: s1-bulk-discount, s2-save5, s7-receipt]
    why: CLAUDE.md already says "Add or update a test for every behavior change, and run the suite before finishing." and it was still corrected in 3 session(s): an adherence gap. Make it mechanical.
    proposal: a Stop gate that runs the tests itself and keeps its own budget (autonomy-1 goal_gate), with CI as the real gate; autonomy-4 stop_check is only a one-time nudge

  Rule: pass-test-change  ->  .claude/rules/tests.md   [2 sessions: s6-rounding, s7-receipt]
    why: Not in CLAUDE.md, and every edit it followed was under tests/: a path-scoped rule loads only when Claude works there.

  Map fix: tinyapp/discounts.py  ->  CLAUDE.md (Layout)   [2 sessions: s2-save5, s3-currency]
    proposal: There is no `tinyapp/discounts.py`; the code it's looking for is in `tinyapp/pricing.py`.

  Skill: /release  ->  .claude/skills/release/SKILL.md   [2 sessions: s4-release-0.3.1, s5-release-0.3.2]
    why: A multi-step procedure repeated across sessions; a skill makes it one command (user-only, because it runs `git tag`).
[4] Watching (below --min-sessions 2)
  Enforce: add-dependency-library: s3-currency: "Don't add third-party dependencies. Use the standard library."
  CLAUDE.md line: changelog-heading: s5-release-0.3.2: "Use the same changelog headings as last time."
```

A path-scoped rule needs every session's evidence in one folder. The miner looks at the files edited in the turn the correction answers, narrowed to the ones it names. "changelog" points at `CHANGELOG.md` at the repo root, so that one becomes a CLAUDE.md line. "tests" points at `tests/` in both sessions, so that one becomes `.claude/rules/tests.md`. Only a failed lookup of a path that isn't there becomes a map fix. A failing command or a rejected edit that repeats goes on the watch list, because its cause needs a person to read the transcript.

Procedures that share at least half their steps become one skill. The other runs are listed in its evidence, so the draft never claims a session ran steps it didn't. Unrelated procedures that pick the same name get numbered folders (`release`, `release-2`).

The skill draft it writes to `out/transcript_miner/drafts/.claude/skills/release/SKILL.md`:

```text
---
name: release
description: Run the release procedure recorded in 2 sessions (Run git log, Edit CHANGELOG.md, Edit tinyapp/__init__.py, Run python3 -m unittest, Run git tag). Use when the user asks for a release.
disable-model-invocation: true
argument-hint: "[version]"
---
```

`config_eval.py`. B passes as many tasks as the baseline but breaks bulk-discount, so it's rejected. C ships:

```text
[1] What each config loads before the first task
config  CLAUDE.md lines  words  skills             path-scoped rules  always-loaded tokens  on demand
A       27               162    -                  -                  ~440                  ~0
B       9                66     add-discount-code  -                  ~229                  ~0
C       9                66     add-discount-code  money.md           ~229                  ~90
[3] Results by task
task            A               B               C
add-code        FAIL 7t $0.047  pass 5t $0.040  pass 5t $0.040
explain-tax     pass 2t $0.030  pass 2t $0.030  pass 2t $0.030
add-dependency  pass 2t $0.030  pass 2t $0.030  pass 2t $0.030
bulk-discount   pass 5t $0.040  FAIL 5t $0.040  pass 5t $0.040
tax-change      pass 2t $0.030  pass 2t $0.030  pass 2t $0.030
  A/add-code: tests_after_last_edit: a passing test run after the last edit
  B/bulk-discount: no_float_literal: no float literals in tinyapp/ (found 0.1 in tinyapp/cart.py)
[4] Summary and the promotion gate
config  passed  cost    mean turns  fixed vs baseline  broke vs baseline  decision
A       4/5     $0.179  3.6         -                  -                  baseline
B       4/5     $0.168  3.2         add-code           bulk-discount      rejected: regresses bulk-discount
C       5/5     $0.168  3.2         add-code           -                  ships: no regressions, better, cheaper
  gate: every task complete for both; at least 3 tasks; no regressions vs A; pass rate >= A's; cost <= 1.10x A's unless the pass rate went up; and a gain (a fixed task or a lower cost)
  recommendation: ship C (open a PR with its diff; a person approves)
  recorded runs, one trial each: rerun real evals several times before trusting a single pass/fail flip.
```

The gate also refuses to judge from too little. With `--configs A,C --tasks explain-tax`, C passes its one task and is still rejected:

```text
C       1/1     $0.030  2.0         -                  -                  rejected: insufficient evidence (1 task(s), one trial each)
  recommendation: keep A
```

A declined run (`stop_reason: "refusal"`, checked first because a refusal usually says `subtype: "success"`) or a run that didn't finish (any `terminal_reason` other than `completed`) shows as INCOMPLETE. It isn't graded, and it blocks the gate. `--configs` always includes the baseline (it's added if you leave it out), because a candidate is only judged against it. A `--runs` folder with no runs for the chosen configs and tasks exits 2 and writes no report.

A real run, and what it taught. This is the second of the two real calls made while building these labs: Claude Code v2.1.303 on Amazon Bedrock, config C, task explain-tax, `--model haiku`, read-only tools, `--max-budget-usd 0.05`. The output below was recorded from that run, with the grader of the time and before `--configs` began adding the baseline:

```text
[2] Real runs: 1 x claude -p, read-only, each capped at --max-turns 4 and $0.05 (total cap $0.05, client-side estimate)
task         C
explain-tax  FAIL 2t $0.002
  C/explain-tax: answer_mentions: answer mentions 'basis points'
  C/explain-tax answer: Tax is the subtotal minus any discount, multiplied by the region's rate from `TAX_BPS` in `tinyapp/pricing.py` (looked up by uppercased region code, with unknown regions untaxed), and rounded half up to whole cents in `tax_for()`. `Cart.tax
```

The answer was right. The grader was too literal: it wanted the words "basis points", and the model wrote `TAX_BPS`. So the grader changed, not the config. `explain-tax` now accepts "basis points", "TAX_BPS" or "bps". Real runs now save their raw stream-json to `out/config_eval/real-runs/`, so a grader fix can be checked with `--runs` without paying for another run. That feature came out of this run, so the run itself wasn't saved and wasn't re-graded. Real runs get only Read, Grep and Glob, so there's no Skill tool: B's and C's skills can't run, and a real run measures CLAUDE.md and rules only. Real runs also load your own `~/.claude/CLAUDE.md` (the same for every config), may leave empty `~/.claude/projects/<temp dir>/memory/` folders behind, and `--repo` is refused: every config runs in its own temp copy.

## Formats and where they come from

| Encoded format | Source (fetched 2026-10-20) |
|---|---|
| Transcript lines (stream-json messages): `system/init`, `assistant` (one line per content block, shared `message.id`), `user` (`tool_result` blocks, or a string for a human message), `result` (`terminal_reason`, `num_turns`, `total_cost_usd`, `usage`, `modelUsage`, `permission_denials`) | https://code.claude.com/docs/en/headless#stream-responses , https://code.claude.com/docs/en/agent-sdk/typescript#sdkmessage |
| Tool inputs (Edit `file_path` / `old_string` / `new_string`, Write `content`, Bash `command`, Grep `pattern` / `output_mode`) and `GrepOutput` | https://code.claude.com/docs/en/agent-sdk/typescript#tool-input-types |
| Bash `tool_use_result` (`stdout` holds stdout and stderr merged; `stderr` holds the tool's own notices; `interrupted`) | https://code.claude.com/docs/en/agent-sdk/typescript#tool-output-types |
| `--tools` restricts which tools exist (so `--tools Read,Grep,Glob` leaves out `Skill`) | https://code.claude.com/docs/en/cli-reference , https://code.claude.com/docs/en/sub-agents |
| Sessions are kept locally; their on-disk format isn't documented, so the lab doesn't read it | https://code.claude.com/docs/en/how-claude-code-works |
| `.claude/rules/*.md` with `paths:` frontmatter; CLAUDE.md under 200 lines | https://code.claude.com/docs/en/memory |
| `SKILL.md` frontmatter (`name`, `description`, `disable-model-invocation`, `argument-hint`); descriptions stay in context; 1,536-character cap | https://code.claude.com/docs/en/skills |
| "Put must-happen rules in hooks or permissions, not prose" | https://code.claude.com/docs/en/best-practices |

The configs and fixture sessions are invented for the lab. `eval/tasks.json` with its grader names, and the proposals format, are lab formats. Costs in the recorded runs come from their `usage` at the list prices in `common/llm.py`. Token counts for configs are estimates (characters / 2.5, the course-wide ratio). A skill-tool call isn't a documented message shape, so the recorded B and C runs show the skill's effect (fewer lookups) without one.
