# Core 1 labs: how Claude Code works

Companion labs for **Core 1: How Claude Code Works**. They take a real run apart event by event, model what each request costs and what the prompt cache saves, and simulate what every permission mode does with a tool call. All three run offline from recorded fixtures and the docs' own rules. Python 3.9+, stdlib only. Run the commands from `labs/`.

| Lab | What it does | Session topics |
|---|---|---|
| `session_anatomy.py` | Replays a stream-json transcript and breaks it into the `system/init` harness config, request 1's prompt size (how you measure the unpublished system prompt), one block per model response with cache reads and writes, tool calls and results, the `result` line, and a recompute of `total_cost_usd` from list prices. `--all` compares the four recorded runs; `--file` reads your own capture; `--real` captures a new one. | Anatomy, Costs |
| `cost_model.py` | Builds each request from the harness, project context, MCP tools (deferred or upfront) and the skill listing, then simulates a session turn by turn under the 5-minute and 1-hour cache TTLs. It resolves which TTL you get with the documented precedence, and models the events that invalidate the cache (model switch, effort change, fast mode, MCP upfront, compaction) and the ones that don't. | Costs, Models and Effort, Limits |
| `mode_simulator.py` | Evaluates tool calls against permission rules in all six modes, in the documented order: hooks, deny, critical paths, ask, protected paths, allow, then the mode's baseline. `--explain` prints each trace, `--headless` shows what `claude -p` denies, `--hook` adds PreToolUse answers (repeatable, merged deny > defer > ask > allow; `defer` only counts in `claude -p`), and `--self-test` asserts 62 rule-matching examples, 16 critical-path cases and the per-mode tables from the docs. Read/Edit deny rules also reach `cat`, `head`, `tail`, `sed` and `tee`. | First Session (permission modes, plan mode), Anatomy (harness responsibilities) |

Shared helpers for the core labs live here too: `_perms.py` (the permission-rule engine that `mode_simulator.py`, `core-2/settings_resolver.py`, `core-3/skill_scaffold.py` and `core-5/workflow_skill.py` use) and `_yamlish.py` (a YAML-subset parser for the GitHub Actions workflows `core-4/gha_check.py` reads). Frontmatter in SKILL.md and rule files goes through `common/frontmatter.py`, not `_yamlish.py`. `python3 core-1/_perms.py` and `python3 core-1/_yamlish.py` run their self-checks.

## Commands

```bash
# Anatomy of a run
python3 core-1/session_anatomy.py                                  # explore_readonly fixture
python3 core-1/session_anatomy.py --fixture tool_error_recovery    # also max_turns_stop, permission_denied
python3 core-1/session_anatomy.py --all
python3 core-1/session_anatomy.py --file my-run.jsonl              # your capture; see the docstring for the command
python3 core-1/session_anatomy.py --real --model haiku --max-budget-usd 0.05   # costs money, read-only, temp copy

# Cost and cache model
python3 core-1/cost_model.py                                       # Opus 5.5, API key, a 20-minute break every 10 turns
python3 core-1/cost_model.py --billing subscription                # main conversation gets the 1-hour TTL
python3 core-1/cost_model.py --break-every 0                       # no breaks: 5m wins
python3 core-1/cost_model.py --event 12:effort-change --billing cloud
python3 core-1/cost_model.py --mcp-tools 60 --tool-search off --skills 30

# Permission modes
python3 core-1/mode_simulator.py
python3 core-1/mode_simulator.py --explain --mode auto
python3 core-1/mode_simulator.py --call 'Bash: npm run lint && git push origin main' --mode dontAsk --headless
python3 core-1/mode_simulator.py --allow 'Bash(npm *)' --deny 'Bash(rm *)' --call 'Bash: FOO=1 rm -rf dist'
python3 core-1/mode_simulator.py --hook allow --hook defer --headless   # two hooks; defer pauses a -p run
python3 core-1/mode_simulator.py --self-test
```

## Output excerpts (real runs)

`python3 core-1/session_anatomy.py`: request 1 already carries ~9.8K tokens with three tools, and later requests mostly read it back from cache.

```text
[3] Request 1: what Claude read before doing anything
  prompt tokens: 9,815 = input 3 + cache write 9,812 + cache read 0
  That's the system prompt, tool definitions, CLAUDE.md and your message together. The stream
  never shows the system prompt itself; this count is how you see its size.
[4] Timeline: one block per model response (assistant lines grouped by message.id)
  #1 msg_lab_explore_01  (2 assistant lines, stop_reason=None)
     prompt   9,815 ████████████████████····  read      0 · write  9,812 · uncached   3
     text: "I'll list the package modules first."
     tool: Glob(tinyapp/*.py) -> ok, 69 chars to Claude, tool_use_result keys: countIsComplete,durationMs,filenames,numFiles,totalMatches,truncated
  #2 msg_lab_explore_02  (2 assistant lines, stop_reason=None)
     prompt   9,990 █████████████████████···  read  9,812 · write    176 · uncached   2  (+175 since #1)
     tool: Read(/tmp/cc-lab-demo/tiny-app/tinyapp/pricing.py) -> ok, 1,184 chars to Claude, tool_use_result keys: file,type
     tool: Read(/tmp/cc-lab-demo/tiny-app/tinyapp/cart.py) -> ok, 2,108 chars to Claude, tool_use_result keys: file,type
...
[7] Cost check: recompute total_cost_usd from usage and list prices
  claude-haiku-5-5: $0.1/$0.5 per Mtok in/out, cache write 1.25x (5m) or 2.0x (1h), cache read 0.1x
    recomputed: $0.00198721 vs reported $0.00198721  -> match
```

`python3 core-1/session_anatomy.py --all`:

```text
fixture              stop_reason  terminal_reason  subtype          num_turns  responses  tools  errors  denials  req-1 prompt  cost    
───────────────────  ───────────  ───────────────  ───────────────  ─────────  ─────────  ─────  ──────  ───────  ────────────  ────────
explore_readonly     end_turn     completed        success          4          4          4      0       0        9,815         $0.00199
max_turns_stop       tool_use     max_turns        error_max_turns  3          2          3      1       0        9,793         $0.00141
permission_denied    end_turn     completed        success          2          2          1      1       1        10,243        $0.00148
tool_error_recovery  end_turn     completed        success          4          4          3      1       0        9,793         $0.00171
```

`python3 core-1/cost_model.py`: on an API key the main conversation gets 5 minutes, so every break costs a full rewrite. Here the 1-hour TTL would be cheaper:

```text
[3] Turn by turn with the 5m TTL (one request per turn; effort medium)
turn  minute  cache    read    write   output  cost     event
────  ──────  ───────  ──────  ──────  ──────  ───────  ─────
1     0.0     cold     0       11,315  500     $0.0666       
2     2.0     warm     11,315  2,000   500     $0.0223       
…                                                            
11    40.0    expired  0       31,315  500     $0.1666       
…                                                            
21    80.0    expired  0       51,315  500     $0.2666       
…                                                            
[4] 5-minute vs 1-hour TTL for the same session
TTL  total    turns without a cache hit  write price
───  ───────  ─────────────────────────  ───────────
5m   $1.2520  3                          1.25x      
1h   $1.0825  1                          2.0x       
  1h is cheaper here by $0.1695 (14%). Prices: $4.0/$20.0 per Mtok in/out, cache read 0.05x.
  Your configuration resolves to 5m; to switch for sessions like this one, set promptCacheTtl to "1h" (v2.1.242+).
```

With `--break-every 0` (no idle gaps) the 2x write price makes 1h the loser:

```text
5m   $0.8746  1                          1.25x      
1h   $1.0825  1                          2.0x       
  5m is cheaper here by $0.2079 (19%). Prices: $4.0/$20.0 per Mtok in/out, cache read 0.05x.
```

`python3 core-1/cost_model.py --billing subscription`:

```text
[2] Which TTL your requests get
  main conversation: 1h
    -> default (Claude subscription within plan usage: main conversation gets one hour): 1h
  everything else (subagents, compaction, titles): 5m
    -> default (five minutes by default; on a subscription, server-controlled helper requests get one hour): 5m
```

`python3 core-1/mode_simulator.py` (excerpt; sample rules allow `Bash(npm run *)`, ask `Bash(git push *)`, deny `Read(./.env)` and `Bash(curl *)`):

```text
call                                          default  acceptEdits  plan        auto        dontAsk  bypass
────────────────────────────────────────────  ───────  ───────────  ──────────  ──────────  ───────  ──────
Read: .env                                    deny     deny         deny        deny        deny     deny  
Edit: tinyapp/pricing.py                      prompt   allow        deny        allow       deny     allow 
Edit: .git/config                             prompt   prompt       deny        classifier  deny     allow 
Bash: npm run build                           allow    allow        allow       classifier  allow    allow 
Bash: npm run lint && git push origin main    prompt   prompt       prompt      prompt      deny     prompt
Bash: timeout 60 python3 -m unittest          allow    allow        allow       allow       allow    allow 
Bash: mkdir build                             prompt   allow        classifier  classifier  deny     allow 
Bash: rm -rf ~                                prompt   prompt       prompt      prompt      deny     prompt
Bash: curl https://example.com                deny     deny         deny        deny        deny     deny  
Bash: /usr/bin/curl https://example.com       prompt   prompt       classifier  classifier  deny     allow 
```

`python3 core-1/mode_simulator.py --self-test`:

```text
  rule-matching rows: 62 (Wildcard patterns, Compound commands, Wrappers, Read and Edit tables)
  critical-path rows: 16 (Critical paths, Other targets, nested commands and inline scripts)
  mode-table rows: 24 calls × 6 modes, 15 hook cases, 1 headless case

all documented examples hold
```

## Formats and rules these labs encode

Each rule is cited next to the code that implements it.

- **Stream-json events, result fields, cost estimates:** https://code.claude.com/docs/en/headless, https://code.claude.com/docs/en/agent-sdk/typescript#sdkmessage, https://code.claude.com/docs/en/agent-sdk/cost-tracking. Per-step `stop_reason` is null, per-step `output_tokens` is a placeholder, and you deduplicate responses by `message.id`, as the real v2.1.303 runs recorded in `common/fixtures/README.md` show.
- **Cache layers, TTL buckets and their precedence, invalidating and cache-safe actions:** https://code.claude.com/docs/en/prompt-caching. Write prices are 1.25x (5m) and 2x (1h); read multipliers and list prices come from `common/llm.py`.
- **Context window and auto-compaction near 967K on 1M models:** https://code.claude.com/docs/en/model-config. **Skill listing budget of 1% of the context window:** https://code.claude.com/docs/en/skills. **MCP tool search:** https://code.claude.com/docs/en/mcp.
- **Rule syntax:** https://code.claude.com/docs/en/permissions. This covers Bash wildcard matching, compound commands, wrappers, env assignments, the read-only set, redirections, Read/Edit gitignore paths and anchors, `!` carve-outs, WebFetch domains, MCP and Agent rules, parameter rules, and hooks vs rules.
- **Modes:** https://code.claude.com/docs/en/permission-modes. This covers the six modes, actions no mode auto-approves, protected paths, critical paths per mode, auto mode's evaluation order, and the broad allow rules auto mode drops. **`-p` denies what would prompt:** https://code.claude.com/docs/en/headless.

## Limits of the models

- **Classifier:** auto mode's classifier isn't simulated; calls it would review show as `classifier`.
- **Inline scripts:** `bash -c '...'` is searched only for critical-path removals, as the docs describe; deny and ask rules don't look inside it. Read/Edit deny rules reach the path arguments of `cat`, `head`, `tail`, `sed` and `tee`, but not commands that read without naming the file (`grep -r x .`). The docs give those five as examples, so other readers that name a denied file (`grep KEY .env`, `wc -l .env`, `diff .env x`) aren't modeled: the lab allows them and its `--explain` trace says Claude Code may deny them too.
- **What `mode_simulator.py` leaves out:** sandboxing, mods, network paths and `blockReadsOutsideWorkingDirectories`.
- **Partial lists:** the read-only command set, the "known-safe" env variables and the dropped interpreter rules are examples from the docs, not Claude Code's full internal lists.
- **Unstated by the docs:** whether a PreToolUse `allow` in auto mode still goes to the classifier. The lab treats it as resolving the call.
- **One request per turn:** `cost_model.py` simplifies each turn to a single request. Its effort multipliers and MCP/skill token sizes are labelled assumptions, and you can replace the harness size with your own measurement (`--base`, from request 1 in `session_anatomy.py`).
- **`--real`:** it goes through `common/cc.py`, so it's read-only, capped and runs in a temp copy. The CLI may still leave an empty `~/.claude/projects/<tmp>/memory/` folder; you can delete it.
