# Claude Code labs

Hands-on kits and scripts for the course. Each lab is either a real configuration artifact (settings, CLAUDE.md, skills, subagents, hooks, MCP servers, plugins, CI workflows) or a script that drives or analyzes Claude Code. Every lab works offline, and every real run is opt-in, read-only by default, and capped.

## Quick start

```bash
cd labs
python3 run_all.py                     # smoke-test everything offline
python3 common/selftest.py -v          # check the shared library
python3 <session>/<lab>.py             # run one lab (offline replay), e.g. a core-1 script
python3 <session>/<lab>.py --real --max-budget-usd 0.10   # the same lab against your claude CLI
```

## Two modes

| | Offline (default) | `--real` (opt-in) |
|---|---|---|
| Needs | Python 3.9+, stdlib only | the `claude` CLI, installed and signed in; SDK labs also need Python 3.10+ and `pip install claude-agent-sdk` |
| Data | recorded fixtures in `common/fixtures/` that follow documented formats | live `claude -p` output, or real Agent SDK messages |
| Cost | free, no network, no API key | real model calls: every run states its cap up front |
| Output | deterministic: the same run prints the same thing | varies with the model and your setup |

An SDK lab run with `--real` exits with code 2 and prints `pip install claude-agent-sdk; Python 3.10+` when the SDK can't be imported. A CLI lab run with `--real` and no `claude` on PATH exits 2 and says how to install it.

## Prerequisites

- **Offline:** `python3` 3.9 or later. Nothing else.
- **Real CLI runs:** Claude Code (https://code.claude.com/docs/en/setup), signed in. Check with `claude --version` and `claude auth status`.
- **Real SDK runs:** Python 3.10+ in a virtual environment (system Pythons on macOS/Homebrew and Debian/Ubuntu refuse global installs), then `pip install claude-agent-sdk`. The SDK bundles its own Claude Code binary.

## Safety defaults for real runs

`common/cc.py` builds every real `claude -p` command, and its guards also run in offline replay, so a misconfigured lab fails the same way in both modes.

- **Read-only.** `--tools Read,Grep,Glob` limits which built-in tools exist. `--allowedTools Read,Grep,Glob` pre-approves only those (scoped forms such as `Read(./src/**)` are fine), and `--permission-mode dontAsk` denies anything else instead of prompting. A lab that needs edits, or a non-read allow rule such as `Bash(git diff *)`, must pass `allow_writes=True`, and it still runs in a temp copy.
- **No MCP surprises.** `--tools` doesn't affect MCP tools, so runs also pass `--disallowedTools "mcp__*"` and `--strict-mcp-config`. Turning that off (`block_mcp=False`) needs `allow_writes=True`. An MCP lab passes `mcp_config=<its own .mcp.json-shaped file>` instead (a file path, not inline JSON): only that file's servers load (`--mcp-config <abs path> --strict-mcp-config`), and their tools run only if `allowed_tools` names them. MCP servers count as write-capable, because a server can do anything (a filesystem server's `write_file` reaches the whole disk), so an `mcp_config` run needs `allow_writes=True`. The one exception is a server listed in `read_only_servers=[...]` whose entry has exactly the shape `{"command": "python3" | "python" | <exactly sys.executable>, "args": ["<absolute path to a .py file inside labs/>"]}` or `{"command": "node", "args": ["<absolute path to a .js/.mjs/.cjs file inside labs/>"]}` (`env` absent or empty, no other keys, no other arguments, no symlink or `..` out of `labs/`), and whose tools are allowed by exact `mcp__<server>__<tool>` names with no `*`. Anything else, such as another absolute interpreter path, any `env` key (even `PATH`), `sh -c`, `npx`, `uv run`, `npm exec` or extra arguments, needs `allow_writes=True`. The run notice names every server, what it runs or which URL it calls, and flags package fetchers. Use absolute paths inside the config, since the run's working dir is a temp copy. `--permission-prompt-tool` is refused.
- **No repo hooks.** A `-p` run shows no workspace-trust dialog and would run hooks committed in the repo, so runs pass `--settings '{"disableAllHooks": true}'`. Hook labs turn this off on purpose, and the run prints a warning. Under `--repo`, the repo's `.claude/settings.json` `env` and `apiKeyHelper` still apply even with hooks off, so only point `--repo` at a repo you trust.
- **Only known flags.** Labs can pass extra CLI flags only from an allowlist (`--append-system-prompt`, `--append-system-prompt-file` with an absolute path, `--include-partial-messages`, `--include-hook-events`, `--forward-subagent-text`, `--exclude-dynamic-system-prompt-sections`, `--effort`, `--fallback-model`, `--permission-prompts none`). Everything else is refused, including `--cloud`, `--remote`, `-w`/`--worktree`, `--add-dir`, `--agents`, `--plugin-dir`, `--resume` and `--setting-sources`. `--model` must be a model alias or id.
- **Always capped.** `--max-turns` (1–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.
- **Never bypass.** `--dangerously-skip-permissions` and `bypassPermissions` are refused outright.
- **Never your repo by default.** Runs happen in a temp copy of `common/samples/tiny-app`, which is deleted at exit (set `LAB_KEEP_TMP=1` to keep it). A run touches your own repo only if you pass `--repo PATH`.
- **Git stays in the temp copy.** Labs run git in a temp copy only through `common.cc.run_git(copy, *args)`. It removes every inherited `GIT_*` variable (git exports `GIT_DIR` and `GIT_INDEX_FILE` inside hooks, and an inherited `GIT_DIR` would point `git -C <tmp>` at your repo), ignores your global and system git config, stops repository discovery at the temp directory, disables signing and hooks, and refuses paths outside temp copies. `common.cc.git_env()` gives the same environment for tools that need it.
- **No clutter.** `--no-session-persistence` keeps lab runs out of `/resume`, and `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` keeps them out of auto memory.

Hooks and guard scripts in these labs are defense in depth. The security boundary is permission deny rules plus the sandbox. A hook that crashes or times out lets the action through unless it sets `"onFailure": "block"` (Claude Code v2.1.295+), and the hook labs demonstrate exactly that. `onFailure` has no effect on `Stop`, `SubagentStop`, `TaskCompleted` and `TeammateIdle` hooks, or on async hooks (https://code.claude.com/docs/en/hooks, "Block the action when a hook fails"), so a crashing Stop gate always fails open: Claude simply stops.

## Running the smoke test

```bash
python3 run_all.py                       # common/selftest.py, then every session folder
python3 run_all.py --only core-4         # one session; repeat --only for more; --only common = self-test
python3 run_all.py --hide-claude         # behave as if Claude Code weren't installed
python3 run_all.py --python python3.13   # another interpreter
python3 run_all.py -v                    # print the tail of each lab's output
```

Each entry runs from `labs/` with stdin from `/dev/null`, `NO_COLOR=1`, `LAB_PROVIDER=mock` and `PYTHONDONTWRITEBYTECODE=1`, and passes when it exits 0 within `--timeout` seconds (default 90). By default, a session folder's entries are its top-level `*.py` files, except names starting with `_`. To pick the entries or pass arguments, add `<session>/run_all.txt` with one entry per line, for example `md_runner.py --self-test` or `kit/test_hooks.sh` (`.sh` entries run with bash); `#` starts a comment. Importing `common` never writes `.pyc` files: `common/__pycache__` is a placeholder file (keep it), so Python can't create that cache directory. Lab scripts should still set `sys.dont_write_bytecode = True` before their imports, so their own modules aren't cached either; `labs/.gitignore` covers any `__pycache__/` that slips through.

## Layout and conventions

```
labs/
├── run_all.py
├── common/                  shared library (below)
│   ├── fixtures/            documented-format samples; see fixtures/FIXTURES.md
│   └── samples/tiny-app/    the sample repo real runs copy to a temp dir
└── <session>/               core-1 ... autonomy-5
    ├── <lab>.py             docstring: What you'll learn / How to run / What to observe / Exercises
    ├── <kit>/kit/           things a learner copies into a repo, e.g. kit/.claude/
    ├── out/                 the only place a lab writes (or a temp dir)
    └── README.md            real output excerpts
```

## Shared library (`common/`)

| Module | What it gives a lab |
|---|---|
| `cc.py` | `find_claude()`, `claude_version()`; `run_headless(prompt, *, cwd, tools, permission_mode, max_turns, max_budget_usd, output_format, extra_args, real, fixture, ...)` returns a `HeadlessRun` (iterate it for events; `.argv`, `.result`, `.returncode`); `parse_stream_json(lines)` returns typed events (`SystemEvent`, `AssistantEvent`, `UserEvent`, `ResultEvent`, ...); `summarize(events)` gives turns, tool calls, cost and duration from the result's documented fields; `load_fixture(name_or_path)` (a common fixture name or a lab-local `.jsonl`/`.json` path); `temp_repo(sample, git=False)`; `run_git(copy, *args)` / `git_env()` for git calls in temp copies; `add_real_args(parser)` + `run_from_args(args, prompt, fixture=...)` for the standard `--real/--repo/--max-turns/--max-budget-usd/--model` flags |
| `hooks.py` | `payload(event, **fields)` and builders (`pre_tool_use`, `post_tool_use`, `user_prompt_submit`, `session_start`, `stop`); `run_hook(cmd, payload, on_failure=...)` runs a command hook and returns a `HookResult` that says what Claude Code would do; `interpret(...)` is the same logic without a subprocess; `merge_pre_tool_use`, `settings_snippet`, and the per-event tables (`HOOK_EVENTS`, `EXIT_2`, ...) |
| `sdk_fake.py` | offline `claude-agent-sdk` stand-ins: the message and block dataclasses, `ClaudeAgentOptions`, the permission types (`PermissionResultAllow`/`Deny`, `ToolPermissionContext`, `PermissionUpdate`, `PermissionRuleValue`) and `HookMatcher`, the error classes, `tool()` / `create_sdk_mcp_server()`, and a `query()` that replays fixtures (`fixture=` a name or a lab-local `.jsonl`/`.json` path, or `use_fixture()`); `get_sdk(real)` returns the real SDK or the fake |
| `frontmatter.py` | `split(text)` for SKILL.md / `.claude/agents/*.md` / command files (frontmatter only when line 1 is `---`; YAML that doesn't parse becomes `errors`, not fields), `parse_yaml()` for the YAML subset those files use, `as_bool()` (true/false/yes/no/on/off/1/0), `as_list()` (`"Read, Grep"`, `"Bash(git diff *) Read"`, or a YAML list) and `as_paths()` for `paths` (comma string or YAML list; `{ts,tsx}` brace expansion stays one pattern) |
| `llm.py`, `pretty.py` | Claude API client with a mock provider; terminal colors, headers and tables |
| `selftest.py` | exercises all of the above offline (`python3 common/selftest.py`) |
| `fixtures/make_fixtures.py` | checks that the generated fixtures match the sample and the helpers; `--write` regenerates them after you edit `samples/tiny-app` |

The recorded fixtures were checked against real Claude Code v2.1.303 output, and the fake SDK's message conversion was checked against the real `claude-agent-sdk` 0.2.168 parser. Synthetic endings, such as the two refusal fixtures in `agents-1/loop_trace.py`, follow the documented result fields as of 2026-10-24 (v2.1.310) and are labelled illustrative in the lab. `common/fixtures/README.md` records the results, and lists what the docs leave unspecified.
