Trace the loop and classify how it ended

Rebuild the agent loop from stream-json transcripts: one row per model response with its tool calls and results, then permission denials and API retries, then a verdict on how the run ended. The verdict checks the result event in the order the docs give: stop_reason, then terminal_reason, then subtype.

  • Python 3.9+
  • standard library only
  • offline: 4 common stream/*.jsonl fixtures
  • 1 real api_error run (v2.1.303)
  • 6 synthetic endings
python3 agents-1/loop_trace.py

The first five transcripts follow real v2.1.303 runs: max_turns_stop, permission_denied and api_error event for event (paths sanitized), tool_error_recovery for its first events, and explore_readonly is built from the same event shapes. The synthetic/* endings reuse the max_turns_stop transcript and change only documented result fields, so you can see endings that are expensive or awkward to provoke for real. Their errors texts and the subtypes the docs don't pair with a terminal_reason are marked as assumed or illustrative in the output.

┌─────────────────────────────────────────────────────────────────────┐
│ Agents 1 · loop_trace: responses, tool calls and how each run ended │
└─────────────────────────────────────────────────────────────────────┘

── explore_readonly  (common/fixtures/stream/explore_readonly.jsonl)
  init: model=claude-haiku-5-5 permissionMode=dontAsk tools=Glob,Grep,Read
  step 1  msg_lab_explore_01     text "I'll list the package modules first."; Glob(tinyapp/*.py) ✓
  step 2  msg_lab_explore_02     Read(tinyapp/pricing.py) ✓; Read(tinyapp/cart.py) ✓  [2 tool calls in one response]
  step 3  msg_lab_explore_03     Grep(^def ) ✓
  step 4  msg_lab_explore_04     text 'tinyapp has four modules: - `pricing.py`: `mone…'
  result: stop_reason=end_turn terminal_reason=completed subtype=success num_turns=4 cost=$0.001987
  verdict: COMPLETED - stop_reason=end_turn, terminal_reason=completed

── tool_error_recovery  (common/fixtures/stream/tool_error_recovery.jsonl)
  init: model=claude-haiku-5-5 permissionMode=dontAsk tools=Glob,Grep,Read
  step 1  msg_lab_recover_01     Read(tinyapp/discounts.py) ✗
           ↳ Read error: File does not exist. Note: your current working directory i…
  step 2  msg_lab_recover_02     text "There's no discounts.py, so I'll look at what t…"; Glob(tinyapp/*.py) ✓
  step 3  msg_lab_recover_03     Read(tinyapp/pricing.py) ✓
  step 4  msg_lab_recover_04     text '`DISCOUNTS` is defined in `tinyapp/pricing.py` …'
  result: stop_reason=end_turn terminal_reason=completed subtype=success num_turns=4 cost=$0.001706
  verdict: COMPLETED - stop_reason=end_turn, terminal_reason=completed

── max_turns_stop  (common/fixtures/stream/max_turns_stop.jsonl)
  init: model=claude-haiku-5-5 permissionMode=dontAsk tools=Glob,Grep,Read
  step 1  msg_lab_maxturns_01    Read(tinyapp/discounts.py) ✗
           ↳ Read error: File does not exist. Note: your current working directory i…
  step 2  msg_lab_maxturns_02    Glob(tinyapp/*.py) ✓; Read(tinyapp/pricing.py) ✓  [2 tool calls in one response]
  result: stop_reason=tool_use terminal_reason=max_turns subtype=error_max_turns num_turns=3 cost=$0.001407
  errors: ['Reached maximum number of turns (2)']
  verdict: TURN_LIMIT - terminal_reason=max_turns (hit --max-turns / max_turns: Reached maximum number of turns (2))

── permission_denied  (common/fixtures/stream/permission_denied.jsonl)
  init: model=claude-haiku-5-5 permissionMode=dontAsk tools=Bash,Glob,Grep,Read
  step 1  msg_lab_denied_01      Bash(python3 -m unittest) denied
           ↳ Bash error: Permission to use Bash has been denied because Claude Code …
  step 2  msg_lab_denied_02      text "I couldn't run `python3 -m unittest`: Bash was …"
  result: stop_reason=end_turn terminal_reason=completed subtype=success num_turns=2 cost=$0.001476
  permission_denials: ['Bash']
  verdict: COMPLETED - stop_reason=end_turn, terminal_reason=completed; 1 permission denial(s): it finished, but without something it tried

── api_error  (agents-1/fixtures/api_error.jsonl: a real run that never reached the model)
  init: model=claude-haiku-5-5 permissionMode=dontAsk tools=mcp__tinyapp__quote_cart
  step 1  msg_lab_apierror_01    text 'API Error: Could not load AWS credentials · Cou…'
           ↳ assistant error category: cloud_credential_error
  api_retry: attempt 1/2 error=cloud_credential_error status=None, attempt 2/2 error=cloud_credential_error status=None
  result: stop_reason=stop_sequence terminal_reason=api_error subtype=success num_turns=1 cost=$0.000000
  verdict: API_ERROR - terminal_reason=api_error (no HTTP status: the request never got a response); subtype is 'success', so a subtype-only check would call this a success

── synthetic/budget_stop  (error_max_budget_usd with terminal_reason budget_exhausted (agent-sdk/typescript enum; a real v2.1.303 budget stop gave the same); errors text illustrative)
  result: stop_reason=tool_use terminal_reason=budget_exhausted subtype=error_max_budget_usd num_turns=3 cost=$0.001407
  errors: ['Reached maximum budget ($0.001)']
  verdict: BUDGET_LIMIT - terminal_reason=budget_exhausted (hit --max-budget-usd at $0.0014, a client-side estimate that can pass the cap by up to one response)

── synthetic/context_full  (terminal_reason prompt_too_long (documented enum value) with subtype success, assumed by analogy with the real api_error run)
  result: stop_reason=None terminal_reason=prompt_too_long subtype=success num_turns=3 cost=$0.001407
  verdict: CONTEXT_FULL - terminal_reason=prompt_too_long (the request no longer fit the context window); subtype is 'success', so a subtype-only check would call this a success

── synthetic/interrupted  (terminal_reason aborted_tools; the subtype it pairs with and the errors text are assumed)
  result: stop_reason=None terminal_reason=aborted_tools subtype=error_during_execution num_turns=3 cost=$0.001407
  errors: ['Interrupted']
  verdict: INTERRUPTED - terminal_reason=aborted_tools (an interrupt() stopped the loop during tool execution)

── synthetic/refusal  (success with stop_reason refusal and terminal_reason completed)
  result: stop_reason=refusal terminal_reason=completed subtype=success num_turns=3 cost=$0.001407
  verdict: REFUSAL - stop_reason=refusal: the model declined (terminal_reason=completed, subtype=success); a subtype-only check would call it a success

── synthetic/refusal_api_error  (the same refusal with terminal_reason api_error, which the docs say a refusal can read)
  result: stop_reason=refusal terminal_reason=api_error subtype=success num_turns=3 cost=$0.001407
  verdict: REFUSAL - stop_reason=refusal: the model declined (terminal_reason=api_error, subtype=success); checking terminal_reason first would call it an API error

── synthetic/killed  (the result line is missing, as when the process is killed)
  verdict: INCOMPLETE - no result event: the process was killed, timed out or crashed; nothing below is trustworthy

transcript                   responses  tools  errors  denied  num_turns  stop_reason    terminal_reason   subtype                 verdict     
───────────────────────────  ─────────  ─────  ──────  ──────  ─────────  ─────────────  ────────────────  ──────────────────────  ────────────
explore_readonly             4          4      0       0       4          end_turn       completed         success                 COMPLETED   
tool_error_recovery          4          3      1       0       4          end_turn       completed         success                 COMPLETED   
max_turns_stop               2          3      1       0       3          tool_use       max_turns         error_max_turns         TURN_LIMIT  
permission_denied            2          1      1       1       2          end_turn       completed         success                 COMPLETED   
api_error                    1          0      0       0       1          stop_sequence  api_error         success                 API_ERROR   
synthetic/budget_stop        2          3      1       0       3          tool_use       budget_exhausted  error_max_budget_usd    BUDGET_LIMIT
synthetic/context_full       2          3      1       0       3          None           prompt_too_long   success                 CONTEXT_FULL
synthetic/interrupted        2          3      1       0       3          None           aborted_tools     error_during_execution  INTERRUPTED 
synthetic/refusal            2          3      1       0       3          refusal        completed         success                 REFUSAL     
synthetic/refusal_api_error  2          3      1       0       3          refusal        api_error         success                 REFUSAL     
synthetic/killed             2          3      1       0       None       None           None              None                    INCOMPLETE  

num_turns, stop_reason, terminal_reason and cost come from the result event only; read stop_reason,
then terminal_reason, then subtype. 'responses' counts distinct message.id values.
  1. One response, two tool calls: both Read events share message.id. Claude Code emits one assistant event per content block, so count responses by message.id, never by event.
  2. A --max-turns 2 run reports num_turns=3, ends with stop_reason=tool_use and carries the cap in errors. Read the number from the result; don't recompute it from the steps.
  3. The tests never ran, yet the run is success and completed. Only permission_denials tells you Claude finished without something it tried.
  4. A real run whose cloud credentials never loaded: subtype=success, cost $0, no HTTP status, and terminal_reason=api_error. A wrapper that trusts subtype reports an outage as a finished task.
  5. The same refusal with terminal_reason=api_error is still REFUSAL, because stop_reason is checked first. A gate that read terminal_reason first would retry it as an outage.
  6. Four rows say subtype: success and aren't successes. After the refusal check, only terminal_reason: completed counts as a finished loop.
  • Trace one transcript with its one-row summary: python3 agents-1/loop_trace.py --only max_turns_stop --no-synthetic. --only is repeatable and takes the four common fixture names.
  • Get the rows as data: --json prints only a JSON array (one object per transcript, with verdict, denials, num_turns and cost_usd). --save also writes agents-1/out/loop_trace.json.
  • Gate on it, the way a CI step would. With --only permission_denied, whose run "succeeded", it prints 1; with --only explore_readonly it prints 0:
    python3 agents-1/loop_trace.py --json --no-synthetic \
        --only permission_denied | python3 -c '
    import json, sys
    rows = json.load(sys.stdin)
    sys.exit(any(r["verdict"] != "COMPLETED" or r["denials"] for r in rows))'
    echo $?
  • Break it: kill the run. Drop the last line (the result event) and trace what's left. All four steps are still there, but the verdict is INCOMPLETE and num_turns, stop_reason and subtype read None:
    sed '$d' common/fixtures/stream/explore_readonly.jsonl \
        > /tmp/lab-killed.jsonl
    python3 agents-1/loop_trace.py --no-synthetic \
        --transcript /tmp/lab-killed.jsonl
  • Break it: forge a refusal. Change only the result's stop_reason; terminal_reason stays completed and subtype stays success, and the verdict turns to REFUSAL:
    sed 's/"stop_reason": "end_turn"/"stop_reason": "refusal"/' \
        common/fixtures/stream/explore_readonly.jsonl > /tmp/lab-refused.jsonl
    python3 agents-1/loop_trace.py --no-synthetic \
        --transcript /tmp/lab-refused.jsonl

Trace a run of your own Claude Code. It costs money, and it's one capped, read-only claude -p in a temp copy of common/samples/tiny-app: --tools Read,Grep,Glob, --permission-mode dontAsk, hooks and MCP off, then traced like the fixtures.

python3 agents-1/loop_trace.py --real \
    --max-turns 2 --max-budget-usd 0.05 --model haiku

--max-turns (1 to 30) and --max-budget-usd (above 0, at most 5) are mandatory. 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. To trace a run you saved yourself, pass --transcript run.jsonl (from claude -p … --output-format stream-json --verbose). Even with --no-session-persistence, real runs left empty ~/.claude/projects/<tmp>/memory/ folders behind.

  • Responses are distinct message.id values. Turns, stop reason and cost come from the result event only: message.stop_reason was null on every assistant event in real v2.1.303 runs.
  • The gate order: stop_reason (refusal fails whatever follows), then terminal_reason (only completed is a finished loop), then subtype, then permission_denials.
  • "To tell failures apart, check data["stop_reason"] first, then terminal_reason, then subtype" (Python SDK reference). The recorded claude -p results carry the same three fields.
  • No result event means the process was killed, timed out or crashed: treat everything else in the transcript as unconfirmed.

Prompt-cache hits and misses over a session

Replay scripted sessions against a toy model of Claude Code's prompt cache and price every request: tokens read from cache, tokens written at the 5-minute or 1-hour rate, uncached input, and the reason each miss happened. The toy's token counts and timings are illustrative; the rules it applies come from the prompt-caching page.

  • Python 3.9+
  • standard library only
  • offline: 4 built-in scenarios
  • the explore_readonly fixture for observed usage
python3 agents-1/cache_sim.py --scenario switches

Without --scenario it replays all four: steady, coffee-break, switches and subagents. The default billing is a subscription within plan usage, so the main conversation gets the 1-hour TTL and everything else 5 minutes.

┌────────────────────────────────────────────────────────────────┐
│ Agents 1 · cache_sim: prompt-cache hits and misses (toy model) │
└────────────────────────────────────────────────────────────────┘
  model: claude-opus-5-5
  TTL buckets: main 1h, others 5m (subscription)
  note: dollar figures are API list-price equivalents; on a subscription they draw on plan usage instead, and past it (usage credits) the main bucket drops to 5m
  prices: per 1M tokens: input $4.00, cache read x0.05, 5m write x1.25, 1h write x2.0

observed: per-request usage in explore_readonly (assistant events deduplicated by message.id)
req  message.id          cache read  cache write  uncached input
───  ──────────────────  ──────────  ───────────  ──────────────
1    msg_lab_explore_01  0           9812         3             
2    msg_lab_explore_02  9812        176          2             
3    msg_lab_explore_03  9988        1468         2             
4    msg_lab_explore_04  11456       158          2             
Each request reads everything already cached and writes only its new tail; per-step output_tokens is a placeholder, so it isn't shown.

switches: mid-session actions, cache-safe and not  (main TTL 1h, others 5m)
at   who      event                                         read    write   input  out   cost     cache                                              
───  ───────  ────────────────────────────────────────────  ──────  ──────  ─────  ────  ───────  ───────────────────────────────────────────────────
0m   main     first request                                 0       11,697  3      300   $0.0996  MISS (cold: nothing cached for this model and lane)
1m   main     after permission mode change                  11,700  1,097   3      300   $0.0171  HIT+tail                                           
2m   main     after editing CLAUDE.md                       12,800  1,097   3      300   $0.0173  HIT+tail                                           
3m   main     after adding an MCP server (tool search on)   13,900  1,097   3      300   $0.0176  HIT+tail                                           
4m   main     after /effort high                            15,000  1,097   3      300   $0.0178  HIT+tail                                           
5m   main     after /model sonnet                           0       17,197  3      300   $0.0718  MISS (cold: nothing cached for this model and lane)
6m   main     back to opus within its TTL                   16,100  2,197   3      300   $0.0268  HIT+tail                                           
7m   main     after adding an MCP server (tool search off)  9,000   12,797  3      300   $0.1102  PARTIAL (prefix changed at mcp:1)                  
8m   compact  /compact (summarization request)              21,800  497     3      2000  $0.0469  HIT+tail                                           
9m   main     first request after /compact                  11,400  3,997   3      300   $0.0403  PARTIAL (prefix changed at project:v2)             
10m  main     after /rewind                                 14,600  797     3      300   $0.0153  HIT+tail                                           
11m  main     after upgrading Claude Code                   0       16,497  3      300   $0.1380  MISS (prefix changed at sys:v2:e0)                 
  total: $0.6186 with caching vs $0.8542 without (28% saved); 64% of input tokens read from cache

Toy model: illustrative token counts, list prices; real totals come from usage in the result event.
  1. The only table read from a transcript fixture (explore_readonly): each request reads everything already cached (9,812, then 9,988, then 11,456) and writes only its new tail. The toy reproduces that pattern.
  2. Cache-safe: a permission-mode change, a CLAUDE.md edit, an MCP server with tool search on, and /effort on Opus 5.5 with a subscription. Each request writes only its tail.
  3. Each model has its own cache, so switching to Sonnet is a cold miss. Switching back within the TTL reads Opus's old prefix again.
  4. An MCP server whose tools load upfront (tool search off) changes the prefix at the tool definitions: everything after them is written again.
  5. The /compact request reads the conversation's cache but is in the "everything else" bucket, so it writes at the 5-minute rate. The next request misses at the project layer: the CLAUDE.md edit from 2m applies only now.
  6. An upgrade brings a new system prompt and tool definitions, so the whole prefix rebuilds.

Now the same coffee break under API-key billing, where both buckets get 5 minutes:

python3 agents-1/cache_sim.py --scenario coffee-break --billing api
┌────────────────────────────────────────────────────────────────┐
│ Agents 1 · cache_sim: prompt-cache hits and misses (toy model) │
└────────────────────────────────────────────────────────────────┘
  model: claude-opus-5-5
  TTL buckets: main 5m, others 5m (api)
  prices: per 1M tokens: input $4.00, cache read x0.05, 5m write x1.25, 1h write x2.0
…
coffee-break: a 12-minute pause in the middle  (main TTL 5m, others 5m)
at   who   event                    read    write   input  out  cost     cache                                              
───  ────  ───────────────────────  ──────  ──────  ─────  ───  ───────  ───────────────────────────────────────────────────
0m   main  request                  0       11,697  3      300  $0.0645  MISS (cold: nothing cached for this model and lane)
1m   main  request                  11,700  1,097   3      300  $0.0138  HIT+tail                                           
2m   main  request                  12,800  1,097   3      300  $0.0141  HIT+tail                                           
14m  main  after a 12-minute pause  0       14,997  3      300  $0.0810  MISS (expired: idle longer than its 5m TTL)        
15m  main  request                  15,000  1,097   3      300  $0.0145  HIT+tail                                           
  total: $0.1879 with caching vs $0.3080 without (39% saved); 57% of input tokens read from cache

TTL comparison on coffee-break
TTL                            cost     full misses
─────────────────────────────  ───────  ───────────
API key / cloud provider (5m)  $0.1879  2          
subscription main bucket (1h)  $0.1694  1          

Toy model: illustrative token counts, list prices; real totals come from usage in the result event.
  1. --billing api stands for an API key or usage credits: both buckets fall to 5 minutes.
  2. The 12-minute pause outlives the 5-minute TTL, so the first request back rewrites the whole prefix.
  3. The TTL table prices the same session both ways: on the 1-hour main bucket the pause costs no second full miss.
  • --scenario switches --billing cloud stands for Bedrock, Google Cloud's Agent Platform or a Claude apps gateway. The /effort high row at 4m turns into a MISS, because effort keeps the cache only with an API key or a subscription.
  • --scenario subagents: the Explore subagent pays its own first write while the fork's first request reads the parent's cache. Under --billing api the main conversation's 8.5-minute gap also expires.
  • Choose a bucket's TTL, as the promptCacheTtl and subagentPromptCacheTtl settings do: --scenario subagents --sub-ttl 1h turns the 12m subagent MISS into a HIT, and --scenario coffee-break --main-ttl 5m makes the pause miss even on a subscription.
  • Script your own day. Save {"name": "lunch", "steps": [{"at": 0, "do": "request", "add": 1200}, {"at": 1, "do": "request", "add": 800}, {"at": 45, "do": "request", "add": 500}]} as lunch.json and run --scenario-file lunch.json: the 45-minute row is a HIT on the default subscription and a MISS with --billing api. The docstring lists every action (switch_model, compact, add_mcp, …).
  • Break it: put a step out of time order, or give add a negative count. The file is rejected before anything is priced, with error: bad scenario … and exit code 2.
  • HIT+tail is the healthy pattern: everything up to the new tail is a cache read. A MISS or PARTIAL names the layer where the prefix changed.
  • A miss has one of three causes: something early in the prefix changed (upfront tool definitions, the system prompt after an upgrade, the conversation after /compact), the model has no cache yet, or the entry idled past its TTL.
  • TTL is per bucket, not per session: subagents and compaction stay at 5 minutes even when the main conversation gets the hour.
  • On a subscription the dollar figures are API list-price equivalents, not charges. For real numbers, read usage in a run's result event.