reference · labs

Labs

51 hands-on Python labs, two or three per session. Every lab runs offline from recorded fixtures, with Python 3.9+ and the standard library. Real runs against your own Claude Code are opt-in, capped and read-only by default.

sessions
20
labs
51
needs
python 3.9+ · stdlib
run from
labs/

How to run them

Each lab page walks through its labs: the command, real output with callouts on the lines that matter, things to try and break, and what to look for. In a terminal, the same commands work from the labs folder:

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
README.md for terminal users start with core-1 course hub

Core

Understand how Claude Code works deeply enough to reason beyond its defaults.

core-1 How Claude Code WorksREADME.md

  • session_anatomy.pyTake 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.
  • cost_model.pyPrice 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.
  • mode_simulator.pyRun 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.

core-2 Context Engineering in Claude CodeREADME.md

  • settings_resolver.pyMerge five sample settings files (managed, --settings, local, project and user) the way Claude Code does, with the source of every value, the documented exceptions, and a verdict for sample tool calls under the merged rules.
  • claudemd_lint.pyLint an instruction stack the way the docs describe it: resolve @ imports (relative to the importing file, four hops at most, never inside quotes or code), total what loads, and flag files over 200 lines, vague rules, emphasis on too many lines, content Claude can derive, procedures that want to be skills, and must-rules, each with the hook or deny rule that would enforce it.
  • rules_match.pyResolve a sample project's .claude/rules/ and a sample home's ~/.claude/rules/: what loads at launch, in context order, and which path-scoped rules each file Claude touches pulls in.

core-3 Knowledge Systems for Claude CodeREADME.md

  • codebase_map.pyMap a repository into a budgeted block you can paste into CLAUDE.md (commands, entry points, one line per module), fit it to a line budget by dropping detail before modules, and fail CI when a committed map goes stale.
  • skill_scaffold.pyThree tools in one script: new scaffolds a skill folder, validate checks SKILL.md files against the documented frontmatter and 20 rules (S001–S020), and budget sizes the skill listing against 1% of the context window.
  • spec_tasks.pyTurn a staged spec's checkboxes into TASKS.md and tasks.json, where an item counts as done only when its evidence holds: the named test passed in the log, a file contains the expected text, or a recorded output contains it.

core-4 Daily Work with Claude CodeREADME.md

  • headless_runner.pyDrive claude -p from a script in each output format (text, json, stream-json), with --json-schema and both caps, then give the CI verdict: stop_reason first, then terminal_reason, then subtype, and with a schema, no structured_output means failure.
  • worktree_fanout.pyPlan a fan-out of four parallel sessions, one git worktree each: check names, footprint overlaps, .gitignore, .worktreeinclude and the total budget, then print one claude -p --worktree command per task.
  • gha_check.pyValidate GitHub Actions workflows that run anthropics/claude-code-action against checks G001–G013: the v1 pin and removed beta inputs, unknown inputs, secrets, permissions, claude_args, PR-head checkouts under pull_request_target, who can trigger, full output in logs, and cost controls.

core-5 Building Workflows with Claude CodeREADME.md

  • workflow_skill.pyValidate and render the kit's /release-notes [since-ref] [audience] skill: named arguments, an inline and a fenced ! injection, a bundled script reached through ${CLAUDE_SKILL_DIR}, and disable-model-invocation: true.
  • format_hook.pyExercise the kit's formatter hook (matcher Edit|Write, exec form with ${CLAUDE_PROJECT_DIR}) the way Claude Code runs it: validate the settings entry, show how each matcher is read, and feed the real script 10 payloads through common/hooks.py.
  • security_review.pyRun a PASS/WARN/FAIL/MANUAL checklist over a repository before you let Claude Code work in it: credential-shaped strings (redacted), key and .env files, unpinned dependencies and install scripts, and the Claude Code config the repository ships.

Agents

Design and build specialized agents with Claude Code and the Claude Agent SDK, with tools, skills, and boundaries tailored to the job.

agents-1 Inside the Agent LoopREADME.md

  • loop_trace.pyRebuild 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.
  • cache_sim.pyReplay 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.

agents-2 Building Agents with the Claude Agent SDKREADME.md

  • sdk_agent.pyGive Claude one tool, a Python function, and nothing else.
  • sdk_permissions.pyWrite a PreToolUse hook callback and a can_use_tool callback, unit-test them as plain async functions, then run them through a simulator of the order the SDK documents: hooks, deny rules, ask rules, permission mode, allow rules, can_use_tool.
  • sdk_structured.pyAsk for output_format={"type": "json_schema", "schema": …}, accept a result only by the documented rule, and validate it again on your side.

agents-3 Extending Claude Code: MCP, Skills, PluginsREADME.md

  • test_client.pyDrive lab-docs, a read-only stdio MCP server written with the standard library, the way Claude Code does at connect time: probe, initialize, list and call tools, read resources, get a prompt.
  • skill_lint.pyLint SKILL.md and .claude/commands/*.md files against the documented rules: frontmatter off line 1, YAML that doesn't parse, misspelled fields, descriptions cut in the listing, and ! commands with no allow rule.
  • plugin_validate.pyCheck the lab-review plugin kit (a skill, a subagent and a PostToolUse hook) against the documented manifest and component rules, lint its skills, flag agent fields plugins ignore, and run its hook on documented payloads.

agents-4 Multi-Agent Work in Claude CodeREADME.md

  • validate_agents.pyFour subagents for the tiny-app sample (code-explorer, test-runner, reviewer, implementer) plus the test-runner's PreToolUse hook, and a validator that checks any agents folder against the documented frontmatter.
  • fanout_orchestrator.pyPlan four tasks as branches, git worktrees and capped claude -p --output-format json --json-schema runs, then answer the question that matters afterwards: what can be merged, in which order, and where it conflicts.
  • delegation_brief.pyUse a brief template (Goal, Context, Constraints, Out of scope, Deliverable, Done when, Budget, Escalate when) and a linter that catches what a subagent's one-string brief usually lacks: context leaks, vague words, unverifiable checks, missing paths and no write scope.

agents-5 Reliability: Guardrails, Evals, ObservabilityREADME.md

  • test_guard.pyTest a PreToolUse guard the way Claude Code runs it: a documented payload on stdin, then the exit code, stdout and stderr read with Claude Code's rules.
  • eval_harness.pyAn eval here is a prompt, a capped headless run, and code graders that read the run's transcript: how it ended, what the answer says, which tools it called, its turns and cost, any denials, and what the structured output holds.
  • otel_reader.pyTurn an OTLP/JSON export of Claude Code metrics and events into the questions people ask: what did it cost, which tools ran and failed, what did hooks block, what happened for one prompt, and what personal data is in the stream.

Delivery

Direct Claude Code toward meaningful system changes and verify what ships.

delivery-1 Product Engineering with Claude CodeREADME.md

  • explore_report.pyUse a read-only prompt pack for exploring an unfamiliar repo, then grade the answers: each claim against what the transcript shows Claude actually read, grepped or only saw in a listing, and each file:line citation against the repo.
  • variants.pyPlan three competing prototypes for one product question, each in its own claude --worktree session with the same acceptance check and its own cap.

delivery-2 Turning Intent into Claude Code WorkREADME.md

  • brief_lint.pyLint a Markdown brief the way Claude Code will meet it.
  • plan_review.pyCheck a plan-mode plan against the brief it implements before you pick an option at plan mode's approval prompt.
  • test_brief_lint.pyPin every rule in brief_lint.py and plan_review.py with a passing and a failing example, the way you'd pin a hook.

delivery-3 AI-Native Development with Claude CodeREADME.md

  • risk_map.pyMap the risk in a diff, or in a plan before any code exists.
  • parallel_plan.pyPlan parallel Claude Code sessions from what each task writes and reads.

delivery-4 Verifying What Claude Code ShipsREADME.md

  • acceptance_gate.pyGrade each acceptance criterion against what the tool calls in a stream-json transcript prove.
  • review_matrix.pyCross a change's concerns with what each Claude Code reviewer is documented to look at, and pick the fewest reviewers that cover every high and medium concern.
  • ci_gate.pyValidate a kit you copy into a repo, then run it.

delivery-5 Products That Learn After ReleaseREADME.md

  • signals_to_context.pyCluster post-release signals from support, incidents, logs, PR reviews and agent sessions, and give each theme a confidence.
  • decision_log.pyKeep product decisions (expand, revise, simplify, revert, investigate, stop) as JSONL, check the log, compare it with release outcomes, and render it where Claude Code will see it before it undoes a decision: one record per decision, a CLAUDE.md pointer, and a path-scoped rule.

Autonomy

Run Claude Code autonomously at scale, so it operates, recovers, and improves over time.

autonomy-1 Autonomous Claude CodeREADME.md

  • autonomy_ladder.pyMap nine task profiles to a rung of the permission ladder and read the run card each one gets: the cap that binds, the exact command line, the settings rules, the turn and dollar caps and the checkpoints.
  • goal_loop.pyDrive a real Stop hook, goal_gate.py, through nine scripted scenarios against a temp copy of the sample repo, where the tests really run.

autonomy-2 Control Planes for Claude CodeREADME.md

  • managed_settings.pyCompile a human-readable org policy into managed-settings.json, merge another team's drop-in by the documented rules, and check every key against the 247 documented settings keys.
  • validate_marketplace.pyValidate kit/, a marketplace called team-tools with two plugins, against the messages claude plugin validate uses.

autonomy-3 Orchestrating Claude Code TeamsREADME.md

  • team_board.pyRead a task board and the hook-logged activity of four parallel claude --worktree sessions.
  • routing.pyRoute eight work items by role, risk and complexity to a model alias and an effort level, clamp them with the org caps, estimate each route's cost against an all-Opus baseline, price a mid-session /model switch against a subagent, and write one subagent file per role.

autonomy-4 Automating Work Beyond CodeREADME.md

  • test_hooks.pyRun a kit of eight hook scripts the way Claude Code would: documented payloads, real subprocesses, and Claude Code's rules for reading exit codes and JSON.
  • validate_pipeline.pyValidate an issue-to-PR workflow built on anthropics/claude-code-action@v1: the token Claude really holds, the sandbox, and GitHub's hardening rules.

autonomy-5 Self-Improving Claude Code SystemsREADME.md

  • transcript_miner.pyRead seven sessions, find the human corrections, and group them by what they ask for.
  • config_eval.pyCompare three versions of a project's config (CLAUDE.md, rules, skills) on five tasks with outcome graders.