Anatomy of a run

Take one recorded claude -p run apart event by event: the harness configuration, what request 1 carried, each response's cache reads and writes, the tool calls, and the result line you should read your numbers from. It's the measuring tape for the Anatomy and Costs topics.

  • Python 3.9+
  • standard library only
  • offline: the explore_readonly fixture
python3 core-1/session_anatomy.py

The fixture is built from the event shapes of real v2.1.303 runs (common/fixtures/README.md says which parts were recorded and which are illustrative), so the structure is real, and request 1's size matches what a real three-tool run measured.

┌─────────────────────────────────────┐
│ Anatomy of a run · explore_readonly │
└─────────────────────────────────────┘
[1] The run
  command --real runs: claude -p 'Which file in this repo defines DISCOUNTS, and which codes does it list? Answer in two lines.' --output-format stream-json --verbose --max-turns 3 --max-budget-usd 0.1 --permission-mode dontAsk --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --disallowedTools 'mcp__*' --strict-mcp-config --settings '{"disableAllHooks":true}' --no-session-persistence
  this replay: recorded with --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --permission-mode dontAsk --max-turns 6 (composed from real event shapes)
  lines: 12 (assistant×6, result/success×1, system/init×1, user/tool_result×4)
[2] system/init: the harness configuration (no system prompt text here)
  model: claude-haiku-5-5
  permissionMode: dontAsk
  cwd: /tmp/cc-lab-demo/tiny-app
  claude_code_version: 2.1.303
  apiKeySource: none
  output_style: default
  tools: 3: Glob, Grep, Read
  mcp_servers: none
  agents: 3: general-purpose, Explore, Plan
  skills: 0
  plugins: 0
  slash_commands: 3: compact, context, init
[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
  #3 msg_lab_explore_03  (1 assistant line, stop_reason=None)
     prompt  11,458 ████████████████████████  read  9,988 · write  1,468 · uncached   2  (+1,468 since #2)
     tool: Grep(^def  in /tmp/cc-lab-demo/tiny-app/tinyapp/cli.py) -> ok, 133 chars to Claude, tool_use_result keys: content,filenames,mode,numFiles,numLines
  #4 msg_lab_explore_04  (1 assistant line, stop_reason=None)
     prompt  11,616 ████████████████████████  read 11,456 · write    158 · uncached   2  (+158 since #3)
     text: 'tinyapp has four modules:' ...
  One response can span several assistant lines (text + tool calls, parallel calls): count
  responses by message.id, not by line.
[5] Tool calls
resp  tool  input                                              result
────  ────  ─────────────────────────────────────────────────  ──────
1     Glob  tinyapp/*.py                                       ok    
2     Read  /tmp/cc-lab-demo/tiny-app/tinyapp/pricing.py       ok    
2     Read  /tmp/cc-lab-demo/tiny-app/tinyapp/cart.py          ok    
3     Grep  ^def  in /tmp/cc-lab-demo/tiny-app/tinyapp/cli.py  ok    
[6] The result line: the only place to read turns, stop reason, cost and totals
  subtype / is_error: success / False
  stop_reason: end_turn  (check first: a refusal arrives as subtype success)
  terminal_reason: completed  (check next, then subtype)
  num_turns: 4  (read it; don't recompute it from the events)
  duration: 7140 ms total, 6385 ms in the API
  usage: input_tokens=9, cache_creation_input_tokens=11614, cache_read_input_tokens=31256, output_tokens=444
  cache hit ratio: 73% of all input tokens were cache reads
  total_cost_usd: 0.00198721  (client-side estimate, not a bill)
  result: tinyapp has four modules: ...
[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
  1. Line 5 is what --real would run: an explicit permission mode, read-only --tools and --allowedTools, both caps, hooks and MCP off. Line 6 gives the flags the replayed fixture stands for.
  2. Twelve stream-json lines, six of them assistant lines, for four model responses. Lines aren't responses.
  3. Request 1's prompt size is the only way to see the system prompt, the tool definitions, CLAUDE.md and your message together: the stream never prints them. With three tools it's already about 9.8K tokens.
  4. Response #2 is two assistant lines with one message.id: two parallel Read calls, one response. Its prompt reads request 1's 9,812 tokens back from cache and writes only the 176 new ones.
  5. Gate on stop_reason first, then terminal_reason, then subtype: a refusal arrives as subtype: "success".
  6. The lab recomputes total_cost_usd from usage and list prices, and it matches. The field is a client-side estimate, not a bill.

--all puts the four recorded runs side by side. Same harness, four endings:

┌────────────────────────────────┐
│ All recorded runs side by side │
└────────────────────────────────┘
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

Same harness, four outcomes: read stop_reason, then terminal_reason, then subtype, and count responses
by message.id. Take num_turns from the result line: the recorded --max-turns 2 run reports 3.
  1. The run cut short by --max-turns 2: stop_reason: tool_use, terminal_reason: max_turns, and the only subtype that isn't success.
  2. This run ends success with one denial. A gate that reads only subtype passes a run that couldn't do its job; check permission_denials too.
  3. Take num_turns from the result line. The recorded --max-turns 2 run reports 3, so don't derive caps from your own turn arithmetic.
  • --fixture tool_error_recovery: the first Read hits a missing file, and its tool_use_result is a plain string, not an object. Claude recovers with Glob and finishes with success; your parser has to survive both shapes.
  • --fixture max_turns_stop: block [6] shows errors: ['Reached maximum number of turns (2)'] and result: absent. Only the success subtype carries result.
  • --json also writes the breakdown to core-1/out/anatomy-explore_readonly.json for your own scripts.
  • Break it: --file common/fixtures/json/structured_output.json feeds it an --output-format json result instead of a stream. You get the totals and nothing else: no system/init line (did you capture with --verbose?), no timeline, no tool calls.
  • Break it harder: --file core-1/README.md exits 2 with has no JSON object lines. To capture your own run, use the read-only, capped command in the script's docstring.

Capture a new run against your own Claude Code. It costs money, runs read-only in a temp copy of the sample repo, and is capped (--max-turns defaults to 3):

python3 core-1/session_anatomy.py --real --model haiku --max-budget-usd 0.05

The budget is checked against Claude Code's client-side estimate, and spend can pass the cap by up to one response, so leave headroom. The CLI may still leave an empty ~/.claude/projects/<tmp>/memory/ folder; you can delete it.

  • Count responses by message.id, not by line: one response with text and two tool calls is three lines.
  • Read turns, stop reason, cost and totals from the result line. Per-step stop_reason is None on every response here.
  • Request 1's prompt size is your harness baseline. Pass your own measurement to cost_model.py --base.

Context and cache cost model

Price a 30-turn session request by request: what each request re-sends, which cache TTL it gets and why, and what a 20-minute break costs under the 5-minute and 1-hour TTLs. It turns the Costs topic's caching rules into numbers you can change.

  • Python 3.9+
  • standard library only
  • offline: list prices from common/llm.py
python3 core-1/cost_model.py

The default session: Opus 5.5 on an API key, 30 turns two minutes apart, a 20-minute break after every tenth turn. Each turn is simplified to one request, and the per-turn sizes are the lab's assumptions, so read the dollar figures as illustrative and the differences between rows as the point.

┌────────────────────────────────────────────────────┐
│ Context and cost model · claude-opus-5-5 · api-key │
└────────────────────────────────────────────────────┘
[1] What every request carries before your message (re-sent each turn)
layer                                                      tokens  share
─────────────────────────────────────────────────────────  ──────  ─────
request 1 measured: harness + tiny-app CLAUDE.md + prompt  9,815   100% 
total static prefix                                        9,815        
  Layers in cache order: system prompt (tools) -> project context (CLAUDE.md, rules, memory) ->
  conversation. A change in an early layer recomputes everything after it.
[2] Which TTL your requests get
  main conversation: 5m
    -> default (api-key: every bucket defaults to five minutes): 5m
  everything else (subagents, compaction, titles): 5m
    -> default (everything outside the main conversation gets five minutes): 5m
[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       
…                                                            
29    96.0    warm     65,315  2,000   500     $0.0331       
30    98.0    warm     67,315  2,000   500     $0.0335       
[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+).
[5] Budgets and limits
  peak request size: 69,315 tokens of a 1,000,000-token window (6.9%)
  session estimate: $1.2520 over 30 turns (list prices; Claude Code's own figure is an estimate too)
  headless cap: claude -p ... --max-budget-usd 1.57 --max-turns 30  (the cap is checked against the client-side estimate and can overshoot by one response)
[6] Events you can simulate (--event TURN:KIND)
  model-switch    each model has its own cache: the next request reads nothing from cache
  effort-change   invalidates on most models; kept on the 5.5 models and Fable 5.1 with an API key or subscription
  fast-mode-on    the fast-mode header is part of the cache key: one full rewrite, once per conversation
  mcp-add         invalidates only when MCP tools load upfront; deferred tools keep the first request's tool list
  deny-tool       with tool search active (the default) the tool list doesn't change and the cache survives; with tool search off, removing the definition invalidates it
  compact         a summarization request reads the prefix, then the history is replaced by a short summary
  claude-md-edit  cache-safe, and the edit doesn't apply until /clear, /compact or a restart
  mode-change     cache-safe (except plan mode with opusplan, which switches models)
  skill           skills append their instructions as a message: cache-safe
  output-style    cache-safe on v2.1.251+ (the style arrives as a message)
  1. The static prefix is request 1 of the recorded run from session_anatomy.py. Pass your own with --base.
  2. The TTL is resolved, not assumed: on an API key every bucket defaults to five minutes. The lab walks the documented precedence and prints the step that decided.
  3. Turn 11 comes after the break. The 5-minute cache has expired, so the whole 31,315-token prefix is written again: $0.1666, against $0.0223 for a warm turn.
  4. The same session under both TTLs. One-hour writes cost 2x instead of 1.25x but survive the breaks, so 1h wins here by 14%.
  5. The setting that switches it. The prompt-caching docs give promptCacheTtl: "1h" for API-key and cloud sessions.
  6. Not every change costs a rewrite. Each of these rows is a --event TURN:KIND you can drop into the session.
  • --billing subscription: block [2] now gives the main conversation 1h by default, and block [3] is priced with the 1-hour TTL.
  • --break-every 0: with no idle gaps the 2x write price makes 1h the loser (5m is cheaper here by $0.2079 (19%)).
  • --break-min 3 against --break-min 4: a 3-minute break plus the 2-minute turn gap stays inside five minutes, so 5m wins; at 4 minutes the cache expires and 1h wins again.
  • --event 12:effort-change --billing cloud, then the same with --billing api-key: turn 12 is invalidated ($0.1766) on a cloud provider and stays warm ($0.0263) on an API key.
  • --mcp-tools 60 --tool-search off --skills 30: sixty upfront schemas add 24,000 tokens, 65% of the prefix every request re-sends. Rerun with --tool-search on and the same tools cost 720.
  • --force-5m --enable-1h: two controls disagree, and block [2] shows FORCE_PROMPT_CACHING_5M=1 winning.
  • Break it: --event 12:typo exits 2 and lists the event kinds it knows.
  • Whether your idle gaps outlast the TTL: past it, the next turn writes the whole prefix again.
  • Which events rewrite the prefix (model switch, compaction, upfront MCP tools) and which are cache-safe (CLAUDE.md edits, mode changes, skills).
  • The suggested headless cap in block [5]: a --max-budget-usd sized from the session estimate, with headroom because spend can pass it by one response.

Permission modes × rules × tool calls

Run 24 sample tool calls through all six permission modes under one set of team rules, in the documented order: PreToolUse hooks, deny rules, critical-path removals, ask rules, protected paths, then allow rules and the mode's baseline. It's the decision table behind First Session's permission modes and plan mode.

  • Python 3.9+
  • standard library only
  • offline: the engine in core-1/_perms.py
python3 core-1/mode_simulator.py

The sample rules deny Read(./.env), Read(./secrets/**) and Bash(curl *), ask for Bash(git push *), and allow tests, npm run, commits, docs edits and one WebFetch domain. Auto mode's classifier isn't simulated: those cells say classifier.

┌──────────────────────────────────┐
│ Permission modes × rules × calls │
└──────────────────────────────────┘
[1] Rules in effect
  deny: Read(./.env), Read(./secrets/**), Bash(curl *)
  ask: Bash(git push *)
  allow: Bash(python3 -m unittest *), Bash(npm run *), Bash(git commit *), Edit(docs/**), WebFetch(domain:docs.python.org)
  working dirs: /work/tiny-app
[2] Outcome per call and mode
call                                          default  acceptEdits  plan        auto        dontAsk  bypass
────────────────────────────────────────────  ───────  ───────────  ──────────  ──────────  ───────  ──────
Read: tinyapp/pricing.py                      allow    allow        allow       allow       allow    allow 
Grep: DISCOUNTS in tinyapp                    allow    allow        allow       allow       allow    allow 
Read: .env                                    deny     deny         deny        deny        deny     deny  
Bash: cat .env                                deny     deny         deny        deny        deny     deny  
Edit: tinyapp/pricing.py                      prompt   allow        deny        allow       deny     allow 
Edit: docs/usage.md                           allow    allow        deny        allow       allow    allow 
Edit: .git/config                             prompt   prompt       deny        classifier  deny     allow 
Write: /etc/hosts                             prompt   prompt       deny        classifier  deny     allow 
Bash: ls -la                                  allow    allow        allow       allow       allow    allow 
Bash: git status                              allow    allow        allow       allow       allow    allow 
Bash: python3 -m unittest -v                  allow    allow        allow       allow       allow    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 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 
Bash: python3 -c 'print(1)'                   prompt   prompt       classifier  classifier  deny     allow 
WebFetch: https://docs.python.org/3/library/  allow    allow        allow       allow       allow    allow 
WebFetch: https://example.com                 prompt   prompt       classifier  classifier  deny     allow 
AskUserQuestion                               prompt   prompt       prompt      prompt      deny     prompt
mcp__github__create_issue                     prompt   prompt       prompt      classifier  deny     allow 
  allow = runs without asking · prompt = asks you · deny = blocked · classifier = auto mode's background review decides
[3] Why some cells look the way they do (rerun with --explain for every trace)
  Read: .env  [bypassPermissions]
    -> deny at step 'deny rule': matches Read(./.env)
       · deny rules block in every mode, including bypassPermissions
  Bash: npm run lint && git push origin main  [bypassPermissions]
    -> prompt at step 'ask rule': matches Bash(git push *); no mode auto-approves an ask rule
  Bash: npm run build  [auto]
    -> classifier at step 'mode': auto mode: the classifier reviews shell commands
       · auto mode drops broad allow rules: Bash(npm run *)
       · not covered: 'npm run build'
  Edit: .git/config  [acceptEdits]
    -> prompt at step 'protected path': protected-path write in acceptEdits
       · write to protected path .git/config: allow rules don't pre-approve it
  Bash: rm -rf ~  [bypassPermissions]
    -> prompt at step 'critical path': critical-path removals always ask, with a time limit in the terminal
       · rm targets a critical path (~)
  Bash: /usr/bin/curl https://example.com  [default]
    -> prompt at step 'mode': shell commands outside the read-only set ask
       · not covered: '/usr/bin/curl https://example.com'
  Bash: timeout 60 python3 -m unittest  [dontAsk]
    -> allow at step 'allow rule / read-only': every subcommand is covered
       · covered: 'python3 -m unittest' by Bash(python3 -m unittest *)
  /usr/bin/curl isn't stopped by Bash(curl *): a Bash rule matches command text, not the program.
  For a boundary, use the sandbox or a PreToolUse hook (permissions, 'What a Bash rule doesn't match').
  1. Deny rules hold in every column, bypass included, and a Read deny also reaches cat.
  2. Allowed by Bash(npm run *) everywhere except auto, which drops broad package-manager run rules on entry and hands the call to the classifier.
  3. One subcommand matches an ask rule, so the compound command prompts in every mode, bypass included, except dontAsk, which denies it.
  4. Removing a critical path asks even in bypassPermissions; dontAsk denies it.
  5. A Bash rule matches command text, not the program: /usr/bin/curl isn't curl, so Bash(curl *) doesn't stop it and bypass runs it. For a boundary, use the sandbox or a PreToolUse hook.

Add --headless for what a claude -p run does with the same calls. There's no one to ask, so every prompt becomes deny:

┌──────────────────────────────────────────────┐
│ Permission modes × rules × calls · claude -p │
└──────────────────────────────────────────────┘
…
call                                          default  acceptEdits  plan        auto        dontAsk  bypass
────────────────────────────────────────────  ───────  ───────────  ──────────  ──────────  ───────  ──────
Read: tinyapp/pricing.py                      allow    allow        allow       allow       allow    allow 
Grep: DISCOUNTS in tinyapp                    allow    allow        allow       allow       allow    allow 
Read: .env                                    deny     deny         deny        deny        deny     deny  
Bash: cat .env                                deny     deny         deny        deny        deny     deny  
Edit: tinyapp/pricing.py                      deny     allow        deny        allow       deny     allow 
Edit: docs/usage.md                           allow    allow        deny        allow       allow    allow 
Edit: .git/config                             deny     deny         deny        classifier  deny     allow 
Write: /etc/hosts                             deny     deny         deny        classifier  deny     allow 
Bash: ls -la                                  allow    allow        allow       allow       allow    allow 
Bash: git status                              allow    allow        allow       allow       allow    allow 
Bash: python3 -m unittest -v                  allow    allow        allow       allow       allow    allow 
Bash: npm run build                           allow    allow        allow       classifier  allow    allow 
Bash: npm run lint && git push origin main    deny     deny         deny        deny        deny     deny  
Bash: timeout 60 python3 -m unittest          allow    allow        allow       allow       allow    allow 
Bash: mkdir build                             deny     allow        classifier  classifier  deny     allow 
Bash: rm -rf build                            deny     allow        classifier  classifier  deny     allow 
Bash: rm -rf ~                                deny     deny         deny        deny        deny     deny  
Bash: curl https://example.com                deny     deny         deny        deny        deny     deny  
Bash: /usr/bin/curl https://example.com       deny     deny         classifier  classifier  deny     allow 
Bash: python3 -c 'print(1)'                   deny     deny         classifier  classifier  deny     allow 
WebFetch: https://docs.python.org/3/library/  allow    allow        allow       allow       allow    allow 
WebFetch: https://example.com                 deny     deny         classifier  classifier  deny     allow 
AskUserQuestion                               deny     deny         deny        deny        deny     deny  
mcp__github__create_issue                     deny     deny         deny        classifier  deny     allow 
  allow = runs without asking · prompt = asks you · deny = blocked · classifier = auto mode's background review decides
…
  1. The edit that prompted in default is now denied. acceptEdits and auto still approve it, so pick the mode for a headless run on purpose.
  2. An ask rule turns into a denial in all six columns.
  3. Headless doesn't add protection: bypass still runs /usr/bin/curl.
  4. Claude can't ask you a question either. Put what it would ask in the prompt.
  • --explain --mode auto: one column with every trace. npm run build goes to the classifier with the note auto mode drops broad allow rules: Bash(npm run *).
  • --call 'Bash: npm run lint && git push origin main' --mode dontAsk --headless: denied at step ask rule; dontAsk denies anything that would prompt.
  • --allow 'Bash(npm *)' --deny 'Bash(rm *)' --call 'Bash: FOO=1 rm -rf dist': denied in all six modes; the FOO=1 prefix doesn't hide rm from the deny rule.
  • --hook allow --hook defer --headless: the two hook answers merge to defer, so most calls come back deferred (the tool doesn't run and -p exits with stop_reason tool_deferred). Deny rules, the ask rule and the critical path still end in deny.
  • --self-test asserts the docs' own examples: 62 rule-matching rows, 16 critical-path rows and the per-mode tables, ending all documented examples hold.
  • Break it: --call 'Bash: grep KEY .env' comes back allow in all six modes, but Claude Code denies it: the large-codebases docs list grep among the file commands a Read deny reaches, and this lab models only cat, head, tail, sed and tee. The trace note says so. For readers the docs don't name, such as wc -l .env, the note says Claude Code may deny it too.
  • Deny rules win in every mode, and no mode auto-approves an ask rule or a critical-path removal.
  • A Bash rule is a match on command text, not a security boundary around a program.
  • In claude -p, prompts become denials: pre-approve what the run needs with --allowedTools and always pass --permission-mode.

Shared helpers: _perms.py and _yamlish.py

Two modules the other core labs import. _perms.py is the permission engine behind mode_simulator.py, core-2/settings_resolver.py, core-3/skill_scaffold.py, core-5/workflow_skill.py and core-5/security_review.py. _yamlish.py is the YAML-subset parser core-4/gha_check.py reads workflows with. Both are teaching models with self-checks, not Claude Code's implementation.

  • Python 3.9+
  • standard library only
python3 core-1/_perms.py
python3 core-1/_yamlish.py

Each prints one line (_perms doctests: 8/8 passed and ok). Run the engine's doctests with -v to see its API, the same calls the labs make:

Trying:
    rules = Rules.from_lists(allow=["Bash(npm run *)"], ask=["Bash(git push *)"], deny=["Read(./.env)"])
Expecting nothing
ok
Trying:
    decide(call("Bash", command="npm run test"), rules, "default").outcome
Expecting:
    'allow'
ok
Trying:
    decide(call("Bash", command="npm run lint && git push origin main"), rules, "acceptEdits").outcome
Expecting:
    'prompt'
ok
Trying:
    decide(call("Edit", file_path=".env"), rules, "bypassPermissions").outcome
Expecting:
    'deny'
ok
Trying:
    [bash_pattern_matches("ls *", c) for c in ("ls -la", "ls", "lsof")]
Expecting:
    [True, True, False]
ok
Trying:
    bash_pattern_matches("ls*", "lsof"), bash_pattern_matches("* --help *", "npm --help")
Expecting:
    (True, False)
ok
…
_perms doctests: 8/8 passed
  1. A rule set from plain lists, written exactly as in settings.json.
  2. One call, one mode, one outcome: allow, prompt, deny, classifier or deferred.
  3. A compound command is split, and the git push part matches the ask rule, so acceptEdits prompts.
  4. A Read(./.env) deny also blocks Edit on that file, in bypassPermissions too.
  5. The docs' wildcard rules: ls * matches ls but not lsof, and a * after a space at the end matches the bare command only when it's the rule's only wildcard.
  • python3 core-1/mode_simulator.py --self-test runs the engine against the docs' tables, not just the doctests.
  • python3 core-1/_yamlish.py also checks that an anchor, a tab, a duplicate key and an unterminated string are rejected rather than guessed, which is why gha_check.py reports them as parse errors.
  • Every lab that answers a permission question goes through this one engine, so its documented limits apply everywhere: the classifier, the sandbox and readers other than the five named ones aren't modeled.
  • SKILL.md and rule frontmatter go through common/frontmatter.py, not _yamlish.py.