# Core 4 labs: daily work with Claude Code

Companion labs for **Core 4: Daily Work with Claude Code**. You drive `claude -p` from a script and read its output the way CI should, plan and run a fan-out of parallel sessions in git worktrees with a merge report, and validate GitHub Actions workflows that run `anthropics/claude-code-action`, with a hardened workflow kit to copy.

Everything runs offline by default: Python 3.9+, stdlib only, no `claude` binary, no network, no API key. Run the commands from `labs/`. The only file a lab writes is `core-4/out/fanout-plan.json` (with `worktree_fanout.py --json`); `--execute` works in a temp git copy that's deleted on exit.

| Lab | What it does | Session topic |
|---|---|---|
| `headless_runner.py` | Replays (or, with `--real`, runs) `claude -p` in each `--output-format` (`text`, `json`, `stream-json`), with `--json-schema` and `--max-turns`; prints the exact command, the jq one-liners to consume it, stream-json progress lines, and a CI verdict (`stop_reason` first, then `terminal_reason`, then `subtype`; with a schema, no `structured_output` means failure). | Interfaces: headless `-p`, output formats, custom scripts |
| `worktree_fanout.py` | Plans N parallel sessions in `.claude/worktrees/<name>/` on `worktree-<name>` branches: name, footprint-overlap, `.gitignore`, `.worktreeinclude` and budget checks, then `claude -p --worktree` and manual `git worktree add` command lines. `--execute` builds the worktrees in a temp git copy, applies a deterministic edit per task, merges in task order and reports conflicts and test results. | Parallel work: worktrees, multi-session hygiene |
| `gha_check.py` + `kit/` | Validates claude-code-action workflows (checks G001–G013: v1 pin, removed beta inputs, unknown inputs, secrets, permissions, mode, `claude_args`, `pull_request_target` checkouts, who can trigger, full output, cost controls, skill prompts). The kit (`kit/.github/workflows/claude.yml` for `@claude` mentions, `claude-review.yml` for automatic PR review) must pass; `samples/workflows/bad-claude.yml` fails on purpose. | Git and GitHub: GitHub Actions, code review |

## Commands

```bash
# Headless runs (replay by default)
python3 core-4/headless_runner.py                          # stream-json, read-only exploration
python3 core-4/headless_runner.py --format json            # one result object
python3 core-4/headless_runner.py --format text            # just the answer and the exit status
python3 core-4/headless_runner.py --schema                 # --json-schema -> structured_output
python3 core-4/headless_runner.py --scenario max-turns     # also: explore, error-recovery, denied, structured
python3 core-4/headless_runner.py --scenario all           # verdict table for every scenario
python3 core-4/headless_runner.py --scenario max-turns --ci   # exit with the verdict code (1 here)
python3 core-4/headless_runner.py --real --schema --model haiku --max-budget-usd 0.05   # costs money

# Worktree fan-out
python3 core-4/worktree_fanout.py                          # dry run against common/samples/tiny-app
python3 core-4/worktree_fanout.py -n 2 --json              # first two tasks; also write out/fanout-plan.json
python3 core-4/worktree_fanout.py --tasks my-tasks.json --repo ~/code/app   # plan against your repo (read-only)
python3 core-4/worktree_fanout.py --execute                # needs git; temp copy only
python3 core-4/worktree_fanout.py --execute --real --model haiku --max-budget-usd 0.05   # + one read-only claude -p per worktree

# GitHub Actions
python3 core-4/gha_check.py                                # kit (must be clean) + bad sample
python3 core-4/gha_check.py --path ~/code/my-app/.github/workflows/claude.yml --strict   # your files; exit 1 on errors
```

Real runs go through `common/cc.py`: a temp copy of `common/samples/tiny-app`, `--tools Read,Grep,Glob` with `--permission-mode dontAsk`, hooks and MCP off, `--no-session-persistence`, and mandatory `--max-turns` / `--max-budget-usd` caps. `--max-turns 0`, `--max-budget-usd 0` or anything over the ceilings exits 2 before anything runs, and so does `--real` without `claude` on PATH. A real run can leave an empty `~/.claude/projects/<tmp-dir>/memory/` folder behind even with `--no-session-persistence`.

## Install the GitHub Actions kit

```bash
mkdir -p <repo>/.github/workflows && cp core-4/kit/.github/workflows/claude.yml <repo>/.github/workflows/
# optional: also copy claude-review.yml for automatic PR review with the code-review plugin
```

Then install the Claude GitHub App (https://github.com/apps/claude) and add the repository secret `ANTHROPIC_API_KEY`, or `CLAUDE_CODE_OAUTH_TOKEN` from `claude setup-token` (and rename the input to `claude_code_oauth_token`). `/install-github-app` in Claude Code does both on github.com. Edit `--allowedTools` in `claude_args` to the commands your project needs before you commit.

## Output excerpts (real runs of these scripts)

`python3 core-4/headless_runner.py --scenario all`:

```
scenario        fixture              stop_reason  terminal_reason  subtype          turns  denials  verdict  why
──────────────  ───────────────────  ───────────  ───────────────  ───────────────  ─────  ───────  ───────  ────────────────────────────────────────────────────────────
explore         explore_readonly     end_turn     completed        success          4      0        PASS     success
error-recovery  tool_error_recovery  end_turn     completed        success          4      0        PASS     success
max-turns       max_turns_stop       tool_use     max_turns        error_max_turns  3      0        FAIL     terminal_reason='max_turns' (subtype 'error_max_turns')
denied          permission_denied    end_turn     completed        success          2      1        WARN     success; 1 permission denial(s) (Bash): the task may be inc…
structured      structured_output    tool_use     completed        success          4      0        PASS     success with structured_output
```

`python3 core-4/headless_runner.py --scenario denied` (stream-json progress lines and the verdict):

```
  [init] model=claude-haiku-5-5 permissionMode=dontAsk tools=Bash,Glob,Grep,Read v2.1.303
  [msg 01] tool_use Bash {"command": "python3 -m unittest", "description": "Run the …
  [denied] Bash (mode)
  [result] ERROR 727 chars: Permission to use Bash has been denied because Cl…
  [msg 02] text: I couldn't run `python3 -m unittest`: Bash was denied by this session's…
  [result/success] stop_reason=end_turn terminal_reason=completed turns=2 cost=$0.001476

[3] Verdict
  a CI step would exit: 0  (success)
  warning: 1 permission denial(s) (Bash): the task may be incomplete
```

`python3 core-4/headless_runner.py --schema --scenario explore` shows why `structured_output` is the field to check:

```
[3] Verdict
  a CI step would exit: 1  (success, but --json-schema was set and structured_output is missing)
```

`python3 core-4/worktree_fanout.py` (dry run):

```
[2] Footprint overlaps (split parallel tasks along file boundaries)
  warn  case-insensitive-codes and trim-codes both touch tinyapp/pricing.py: merge one before starting the other, or narrow a footprint

[4] Budget
  per run: --max-turns 8, --max-budget-usd 0.25 (client-side estimate)
  worst case: 4 × $0.25 = $1.00 against your --max-total-usd $2.00

[5] Commands (run each in its own terminal, or background them; plan mode keeps them from editing files)
  claude -p 'Make discount codes case-insensitive in apply_discount and add a test for a lower-case code.' --worktree case-insensitive-codes --permission-mode plan --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --output-format json --max-turns 8 --max-budget-usd 0.25 > out/case-insensitive-codes.json
```

`python3 core-4/worktree_fanout.py --execute` (the predicted conflict happens; the rest merges and the tests pass):

```
<tmp>/tiny-app                                           34721b4 [main]
<tmp>/tiny-app/.claude/worktrees/cart-item-count         34721b4 [worktree-cart-item-count]
<tmp>/tiny-app/.claude/worktrees/case-insensitive-codes  34721b4 [worktree-case-insensitive-codes]
<tmp>/tiny-app/.claude/worktrees/cli-json-output         34721b4 [worktree-cli-json-output]
<tmp>/tiny-app/.claude/worktrees/trim-codes              34721b4 [worktree-trim-codes]
...
[3] Merge report: merge the branches into main in task order
branch                           result    conflicting files
───────────────────────────────  ────────  ──────────────────────────────────────────────────────────────────────
worktree-case-insensitive-codes  merged    -
worktree-cli-json-output         merged    -
worktree-cart-item-count         merged    -
worktree-trim-codes              CONFLICT  tinyapp/pricing.py (overlap with case-insensitive-codes was predicted)

  tests on main after the merges: 15 tests, OK
...
  worktrees left: 0
```

`python3 core-4/gha_check.py` (kit clean, bad sample excerpt):

```
core-4/kit/.github/workflows/claude-review.yml: 1 claude-code-action step(s), clean
core-4/kit/.github/workflows/claude.yml: 1 claude-code-action step(s), clean

core-4/samples/workflows/bad-claude.yml: 1 claude-code-action step(s), 9 error(s), 8 warning(s)
G001   error  jobs.claude.steps[1]     anthropics/claude-code-action@beta: @beta is the pre-v1 interface; use @v1
G002   error  jobs.claude.steps[1]     `direct_prompt` was removed in v1; use prompt
G003   warn   jobs.claude.steps[1]     `sticky_comment` isn't an input of the action (did you mean use_sticky_comment?)
G004   error  jobs.claude.steps[1]     `anthropic_api_key` is a literal value; store it as a GitHub secret and pass ${{ secrets.NAME }}
G008   error  jobs.claude.steps[1]     --dangerously-skip-permissions in claude_args: never skip permission checks on a runner that holds secrets and can push
G009   error  jobs.claude.steps[0]     checks out the PR head into the workspace root before the action; check out the base ref, put the head in a subdirectory, pass --add-dir
G010   warn   jobs.claude.steps[1]     allowed_bots: '*' lets any bot trigger runs; on public repos external Apps may invoke the action with prompts they control
G011   warn   jobs.claude.steps[1]     show_full_output prints every message, including tool results that may hold secrets, to the (possibly public) run log
G012   warn   jobs.claude              no timeout-minutes: set a job timeout to stop runaway runs
```

A dated observation, not a shipped sample: on 2026-10-20 the action's own [`examples/claude.yml`](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) passed every security check, and `gha_check.py` asked it only for `--max-turns`, a job `timeout-minutes` and a `concurrency` group, the cost controls the docs recommend. To repeat it (the upstream file may have changed since):

```bash
curl -sSL https://raw.githubusercontent.com/anthropics/claude-code-action/main/examples/claude.yml -o /tmp/claude.yml
python3 core-4/gha_check.py --path /tmp/claude.yml
```

## What each lab encodes, and where it comes from

- Output formats, `--json-schema` (`structured_output`; `result` holds the same JSON as a string), `--verbose` with stream-json, exit codes (0 / non-zero / 143 on SIGTERM): https://code.claude.com/docs/en/headless ; flags: https://code.claude.com/docs/en/cli-reference
- Result `subtype` and `terminal_reason` values: https://code.claude.com/docs/en/agent-sdk/typescript#sdkresultmessage and https://code.claude.com/docs/en/agent-sdk/agent-loop ; the check order, "check `data["stop_reason"]` first, then `terminal_reason`, then `subtype`" (a refusal is `stop_reason: "refusal"`, usually with `subtype: "success"`): https://code.claude.com/docs/en/agent-sdk/python#resulterror ; the recorded fixtures are described in `common/fixtures/FIXTURES.md`
- Worktree path and branch naming, `claude -p --worktree` skipping the trust check, `-p` never cleaning up, `.worktreeinclude`, `worktree.baseRef`: https://code.claude.com/docs/en/worktrees
- Action inputs (snapshot of `action.yml`, 2026-10-20), interactive vs automation mode, permissions, `claude_args`, beta → v1: https://code.claude.com/docs/en/github-actions , https://github.com/anthropics/claude-code-action/blob/main/action.yml , https://github.com/anthropics/claude-code-action/blob/main/docs/migration-guide.md , https://github.com/anthropics/claude-code-action/blob/main/docs/security.md

The workflow checker reads YAML with `core-1/_yamlish.py`, a stdlib subset parser (block and flow collections, quoted and block scalars); anchors and aliases are reported as a parse error rather than guessed.
