Claude Code made producing a diff cheap. It did not make it cheap to know which diff to produce, to see how a change fits a system you only half know, to integrate four branches that ran in parallel, or to stand behind what ships. In an AI-native development flow, those are where your hours go, and each one maps onto concrete Claude Code machinery: subagents and git for exploration, plan mode for planning, worktrees and background sessions for execution, Chrome and logs for feedback, rules and hooks for engineering discipline, and gh, hooks and /loop for delivery.
This session follows one feature from first question to production through six phases: explore → plan → execute → feedback → engineer → deliver. The running example is shareable report links in a fictional repo, acme-dash: a Next.js web app, a Node API, Postgres and a jobs worker. A dashboard owner creates an expiring link, anonymous viewers open it, a nightly job expires old links, and every share is audited. The feature is small enough to hold in your head, but it touches security, data, UI, email and operations, so every phase has something real to do.
Everything here is as of 2026-10-24 (Claude Code v2.1.310). Features that need a minimum version say so inline ("requires v2.1.xxx+"). Commands, settings keys and hook fields come from the docs at code.claude.com/docs. Where a widget shows numbers, it is a toy model and says so.
By the end you will be able to:
answer codebase and history questions without flooding your context: Explore and custom subagents, /btw, a /why skill over git and PR history, diagrams as code and artifacts, and synthetic user flows driven through Chrome;
set a deliberate cut line in plan mode, run a premortem that turns risks into enforced controls, and pick an implementation strategy that fits uncertainty, breadth and reversibility;
route each task to direct work, a handoff (subagent, /subtask, claude --bg, claude --cloud) or parallel worktrees, and plan file footprints and merge points before you start;
wire logs, screenshots, human comments and artifacts into Claude's own loop so it sees what you would see;
keep the codebase simple while an agent writes most of it: /simplify, conventions promoted from prose to rules to hooks, and a plan for debt that agents copy;
ship with integration gates, PRs that carry evidence, release watches that fit your machine's uptime, and an explicit list of unresolved risks.
Six phases run left to right. Above each one sits the stack of artifacts the work has produced so far, with that phase's own artifact on top, and the whole stack is the context the next phase loads. The return arcs matter as much as the forward arrows: feedback sends you back to the plan, and delivery signals start the next exploration (Delivery 5). Hover or focus a phase for its mechanisms; click it to jump to its section.
Exploration
You can't steer what you can't see. Claude Code can read a codebase, its history and its running behavior faster than you can, but every file it reads lands in some context window, and every explanation it gives without reading is a guess. The skill in this phase is choosing where a question runs, demanding evidence with every answer, and turning what you learn into artifacts the planning phase can load.
Codebase Questions
The advice is plain: ask Claude the questions you'd ask a senior engineer. How does logging work? Where do we create signed URLs? What edge cases does ReportExporter handle? Claude Code has no prebuilt index of your repo. It answers by agentic search: it runs searches (on macOS, Linux and WSL the default tool set leaves out Glob and Grep, so Claude runs find and grep through Bash, which in Claude's shell are embedded versions of bfs and ugrep), reads the files that look relevant, and reasons over what it read. With a code intelligence plugin installed, such as typescript-lsp or pyright-lsp from claude-plugins-official, it can also jump to definitions and find references by symbol instead of by text.
Where a question runs decides what it costs
Every file read is tokens in a context window. The question is which window:
Where
What happens
Use it when
Main session
Every read and search result stays in your conversation.
The answer needs a few files and you'll act on it right away.
/btw <question>
A side question with no tools. The answer never enters history. Press f to fork it into a subagent with tools.
Claude already has the answer in context ("which flag name did you use?").
Explore subagent
A built-in read-only subagent with its own context. You can ask for quick, medium or very thorough. Only its summary comes back.
The answer needs many files you won't reference again ("use a subagent to investigate how our auth system handles token refresh").
Custom scout subagent
Your own .claude/agents/*.md with a fixed report format, tools and model.
You ask the same kind of question often and want a consistent, cited report.
Toy model with illustrative numbers: a 200K-token window that already holds 40K, about 2,500 tokens per file read and a 1,200-token subagent summary. Pick a question, then say whether you'll act on the answer in this session. The bar is your context window: the three dashed placements show where each option's additions would land, the recommended one is filled in, and what's left, in the highlight, is the headroom for the implementation that follows. Total tokens processed is counted under the bar, not drawn: a subagent processes more in total but leaves your window almost untouched, and /btw only works for answers already in context.
Ask in a ladder, and demand citations
Broad questions orient you, narrow ones locate code, and trace questions show how it fits together. Ask for file:line citations at every step. A model that has to cite can't quietly explain code it never read.
# 1. orient
give me an overview of this codebase: entry points, deployables, data stores,
and the five directories I'd touch to add shareable report links
# 2. locate (keep the search out of my context)
use a subagent to find every place we create, validate or expire a signed token
or URL. cite file:line for each. don't edit anything
# 3. trace
trace GET /reports/:id from the route handler to the SQL query and back.
list each hop as file:line -> file:line
# 4. probe
what in src/api/middleware/auth.ts would surprise an engineer who joined last week?
---
name: code-scout
description: Read-only codebase investigator. Use to answer "how does X work",
"where is Y" or "trace Z end to end" when the answer needs more than a few
files. Returns a cited summary and never edits.
tools: Read, Bash
model: sonnet
---
You answer one question about this repository and report back.
Rules:
- Read before you claim. Every statement about behavior cites file:line.
- Mark anything you inferred from naming, config or dynamic dispatch as INFERRED.
- Use read-only shell commands only: grep, find, ls, cat, git log, git blame, git show.
- Stop when you can answer. Don't survey the whole repository.
Report:
1. Answer, in 3-6 sentences
2. Evidence: file:line bullets with a one-line note each
3. Open questions: what you couldn't determine, and where to look next
The built-in Explore agent is usually enough. Define a scout like the one above when you want a fixed report format, or want lookups on a cheaper model. An official cost post advises: "Move down to Sonnet or Haiku for lookups, not for writing code" (What a task costs on Opus 5.5). Invoke it with @"code-scout (agent)", or just ask Claude to use it. The tools line is deliberately Read, Bash: listing Glob or Grep only brings them back for a subagent that also leaves out Bash. To make every exploration cheaper, a user or project subagent named Explore "overrides the built-in and keeps its own model field", for example model: haiku.
Failure modesConfident explanations of unread code. If an answer has no citations, ask "which lines say that?" The infinite exploration, the docs' name for an unscoped "investigate" that reads hundreds of files into your context. Scope it, or send it to a subagent. Explore doesn't load your CLAUDE.md files or the git status, so it doesn't know your conventions unless the request names them (a subdirectory's CLAUDE.md and matching path rules do still load when it reads files there). Stale maps: a codebase map in CLAUDE.md that contradicts the code wins arguments it shouldn't. Ask Claude to check the map against the code before trusting it.
How Claude Code actually searches, and what that means for big repos
No embedding index. Context arrives just in time: CLAUDE.md files load at launch, and everything else is read when Claude decides to read it. Search quality therefore depends on vocabulary. Use the domain words the code uses ("share token", not "magic link", if the code says shareToken). Ask for a glossary of project terms early (a recipe on the common workflows page).
Search tools. On macOS, Linux and WSL, Claude Code leaves Glob and Grep out of the default tool set, and Claude "searches with find and grep through the Bash tool instead. In Claude's shell those two commands run embedded versions of bfs and ugrep, and the searches reach your hooks and permission rules as Bash calls." The two tools come back if you name them in --tools or --allowedTools, if Bash is removed from the session, or for a subagent whose tools field lists them and leaves out Bash (tools reference). Read-only commands such as ls, cat, grep, find and read-only git never prompt (permissions), so exploration rarely interrupts you.
Symbols beat strings. A code intelligence plugin connects a language server, which gives Claude go-to-definition, find-references and post-edit diagnostics. Install the binary first (for TypeScript, npm install -g typescript-language-server typescript), then /plugin install typescript-lsp@claude-plugins-official. Language servers don't start in cloud sessions (code intelligence).
Subagent economics. A subagent's reads happen in its own window. Its transcript is kept at ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl, so you can audit what it actually read. Since v2.1.198 subagents run in the background by default, so you can keep talking while one explores (subagents).
Large repos. Nested CLAUDE.md files load on demand when Claude reads or edits in that directory, so a per-package CLAUDE.md costs nothing until Claude works there. See monorepos and large codebases, and Core 3 for codebase maps.
Historical Changes
Code tells you what. History tells you why, and "why" is what keeps an agent from "simplifying" away a constraint that still matters. A codebase has three layers of history, and Claude Code can read all three:
Commits: git log, git blame, git show, and the pickaxe (git log -S, -G), which finds the commits where a string or a regex match appeared or disappeared.
Review discussions: gh pr view <n> --comments and gh pr list --search. This is where the trade-offs got argued. The best-practices guide says that if a system has a CLI, "that's usually the easiest way in", and that with gh installed "Claude will open pull requests and read review comments without any explanation from you."
Sessions: Claude Code transcripts. claude --from-pr 1234 opens the session picker filtered to sessions linked to that PR, and pasting a PR URL into the /resume picker search works too. Claude Code links a session to a PR when Claude creates it with gh pr create or glab mr create, or works on an existing one.
For a "why" question, the right source is often history: instead of asking why ExecutionFactory has such a weird API, ask Claude to read its git history and summarize how the API came to be.
An illustrative investigation on the fictional acme-dash repo, with invented hashes and PR numbers, drawn as a chain of loupes. Each loupe magnifies the boxed detail of the one before it: the line, its blame stamp, the commit, the PR thread, the older history. It opens on the finished chain; step back to the start and play it. The meter fills with what the skill's subagent reads inside its own frame, and only the thin summary card leaves for your session, with the counters above keeping score. The answer is a constraint the code alone couldn't show: SMS segment length. The transcript behind the loupes is under the stepper.
Package the pattern as a skill so it runs the same way every time and keeps the raw history out of your main context. This one runs in an isolated subagent (context: fork) using the read-only Explore agent, and pre-approves only read-only git and gh commands for that turn. "Despite the name, a skill with context: fork doesn't run in a fork of the current conversation": the subagent gets the skill content as its prompt and nothing you've discussed, and Explore also skips CLAUDE.md. So the skill has to stand on its own, and $ARGUMENTS must carry the target (skills).
---
name: why
description: Explain why code is the way it is, from git history, blame and the PR
discussions that introduced it. Use for "why does X do Y", "when did this change",
or before changing long-lived code.
argument-hint: <path[:line] or symbol>
context: fork
agent: Explore
allowed-tools: Bash(git log *) Bash(git blame *) Bash(git show *) Bash(gh pr view *) Bash(gh pr list *)
---
Target: $ARGUMENTS
1. Find the lines that implement the target. Cite file:line.
2. Run `git blame -w -C` on those lines and collect the commits that introduced
or last changed the behavior.
3. For each commit, read `git show --stat <sha>`. If the message names a PR (#123),
read it with `gh pr view 123 --comments`.
4. Use `git log -S'<literal>'` to find when a constant, flag or call first appeared.
5. Report: a dated timeline (sha, PR, one-line reason), the constraint that still
holds today, and what would break if it changed. Mark inferences as INFERRED.
# who last changed these lines, ignoring whitespace, following moved or copied code
git blame -w -C -L 38,44 src/lib/tokens.ts
# when a literal first appeared or disappeared (pickaxe)
git log -S'base62' --oneline -- src/lib
# commits whose diff touches lines matching a regex
git log -G'expires_?at' --oneline --since=1.year
# a file's history across renames
git log --follow --oneline -- src/lib/tokens.ts
# the review discussion behind a commit
gh pr view 812 --comments
# the Claude Code session that produced a PR
claude --from-pr 812
# files changed most often in the last 6 months (merges excluded)
git log --since="6 months ago" --no-merges --pretty=format: --name-only -- src \
| grep -v '^$' | sort | uniq -c | sort -rn | head -15
# prompt: hidden coupling before you plan
use a subagent to analyze the last 6 months of history under src/api and src/db:
top 10 hotspots (commits x lines), top 10 file pairs that change together in at
least 40% of commits, flagging pairs with no import between them. skip commits that
touch more than 30 files. show the commands you ran.
A hotspot is a file that is both large and frequently changed, which is where defects cluster. Co-change coupling is two files that keep changing in the same commits. When there is no import between them, the pair is a hidden contract that an agent editing one side won't see. Both belong in the planning context.
Failure modesInventing a rationale. Ask "why is this 22 characters?" without pointing at history, and you'll get a plausible story, not the real one. Bulk commits (formatting, renames, dependency bumps) create fake hotspots and fake coupling, so filter by commit size. Squash merges flatten history, so the PR discussion is often the only record of the trade-off. Agent authorship: with Claude writing most commits, "author" means whoever directed the change. The PR and session are where the reasoning lives, which is one more reason to keep sessions linked to PRs.
Architecture Visualizations
A diagram is the cheapest review artifact there is. Thirty seconds on a container diagram replaces thirty minutes reading routes and config, and a diff of two diagrams shows exactly the changes that need a human: a new data store, a new external dependency, a new public entry point. Claude Code is good at producing diagrams as code (Mermaid, PlantUML, D2, Structurizr) from routes, infrastructure files and imports. Because they're text, you can regenerate them per branch and diff them.
Pick one zoom level per question
The C4 model gives four levels: context (who uses the system and what it talks to), containers (deployables and data stores), components (building blocks inside one container) and code. Most confusing diagrams mix levels, putting a box for "Postgres" next to a box for "TokenSigner". For shareable links, the container level answers "what new public surface and dependencies does this add?", and the component level answers "where inside the API does the change live?"
Switch between branches and the diff view, and toggle model-inferred edges. In the diff, the highlighted boxes and edges are what the branch adds (+) or changes (~). A dashed edge is inferred rather than extracted, so it goes in an "unverified" list instead of the committed diagram. Hover or focus any box or edge to read the %% src: line that proves it. The Mermaid source below regenerates from the same model, with a citation on every element. This is how you want Claude to hand you a diagram.
Produce a C4 container diagram of acme-dash as Mermaid `flowchart LR` in
docs/arch/containers.md. Sources you may use: docker-compose.yml, infra/*.tf,
src/*/main.ts, next.config.js.
Rules: one node per deployable or data store; label edges with the protocol;
put a `%% src: file:line` comment on every node and edge; anything you can't
cite goes in an "Unverified" list under the diagram, not in it.
Then do the same on feat/share-links and add a table of added and removed
nodes and edges.
Make an artifact that walks through the feat/share-links architecture change:
the container diagram before and after as inline SVG, new elements highlighted,
and a side panel listing each new edge with the file that proves it.
Keep it updated as we plan.
Artifacts: diagrams you can click and share
An artifact is "a live, interactive web page that Claude Code publishes from your session to a private URL on claude.ai." It updates in place as the session continues, and each publish becomes a version. Claude may publish one on its own when the output suits a page, or you ask for it in plain words. Ctrl+] reopens the session's most recent artifact, and /artifacts (requires v2.1.208+) lists yours and the ones shared with you. The bundled /artifact-diagramming skill (requires v2.1.221+) loads guidance on "how to write inline SVG that stays legible in light and dark themes." Artifacts suit exactly this phase: a PR walk-through, an architecture before/after, or options side by side.
They have hard limits. Artifacts need a Pro, Max, Team or Enterprise plan, a session signed in with /login and the Anthropic API. They aren't available through API keys, gateways, Bedrock, Google Cloud's Agent Platform or Foundry. They're off by default in claude -p, the Agent SDK and the GitHub Action. When they're unavailable, Claude writes a local HTML file or says it can't publish (artifacts).
Failure modesPretty diagrams of an imagined system. The model draws what systems like yours usually look like, so demand citations. Mixed C4 levels.No legend: do arrows mean calls or data flow? Rot: hand-edited diagrams drift silently, while regenerated ones drift visibly. Artifact hygiene: content is stored on Anthropic infrastructure and is private until you share it. Public sharing on Team and Enterprise stays off until an Owner enables it. Don't put secrets or customer data on a page you might share.
Artifacts: when Claude Code asks before publishing, and the page constraints
A new artifact published in response to a prompt you typed goes through "without a permission prompt or classifier review". Claude Code asks first, or has the auto-mode classifier review the publish, in these cases: the session is in plan mode (it asks before the first publish of each artifact); the page declares runtime capabilities such as connector calls or file downloads; the artifact was shared publicly (it asks once per conversation before changing it); a session-scoped scheduled task started the turn; or Claude can't read the file without your approval. Even an allow rule for the Artifact tool doesn't skip that last prompt.
Pages are single, self-contained HTML or Markdown files, served under a strict CSP. The page can load fonts from Google Fonts and scripts from five public CDNs. External images are blocked, so they get embedded as data URIs. There is no backend, relative links don't resolve, and the rendered page has a 16 MiB limit. Styled pages cost more output tokens than terminal text, so the docs recommend "Prefer SVG, or HTML and CSS, for diagrams over embedded raster images."
To turn artifacts off, use any of: "enableArtifact": false in settings, CLAUDE_CODE_DISABLE_ARTIFACT=1, or Artifact in permissions.deny. Honoring the key in project settings requires v2.1.242+, and a project-level true can't turn them back on. When Claude reads an artifact someone else wrote, it gets a summary "the way it reads a web page with WebFetch", with any instructions on the page reported rather than followed. That is a prompt-injection safeguard worth knowing about before you build workflows on shared pages (artifacts).
Synthetic User Flows
A synthetic user flow is a generated journey through a feature. It has a persona (who), a goal, a path through the feature's states, the conditions around it (device, network, data), and an expected outcome, the oracle. You generate dozens on purpose to probe the feature. Before you build, flows expose undefined behavior: "what does an anonymous viewer see for a revoked link, 404 or 410?" After you build, the same flows become browser tests and the scenarios in Delivery 4.
How to generate them with Claude Code
Model the states from the code, not from memory. Ask the scout to list the routes, screens and error states for the feature, with citations. Correct the list yourself, then forbid flows that use states outside it.
Name the dimensions that change behavior: viewer ∈ {owner, teammate, anonymous}, link ∈ {active, expired, revoked}, device, report size, network.
Generate in two passes.Pairwise generation covers every pair of dimension values with a handful of flows. Adversarial probes, from asking "what would break this?", aim at edge states and at the three-way combinations pairwise doesn't guarantee.
Execute at the cheapest level that answers the question. A paper walkthrough in plan mode flags undefined behavior against the spec. A live run through Claude in Chrome (claude --chrome or /chrome, extension 1.0.36+) clicks through the real app, reads the console and saves screenshots. Desktop's Browser pane does the same against a dev server from .claude/launch.json. A Playwright test makes the flow permanent.
Five dimensions give 3·3·2·2·2 = 72 combinations. Each generated flow is one line across the five axes to an outcome. Lines that end on ? carry the highlight: those combinations aren't defined by the spec, and each one raises a spec question in the list. T1 and T2 tag two three-way target triples on their axes, and the line under the drawing says whether any flow passes through all three values. Pick a strategy and, for random generation, a budget; hover or focus a line for its flow. Pairwise reaches 100% pair coverage with nine flows and surfaces every two-way question by construction, but the three-way combinations, where the nastiest questions live, are hit only by luck. The adversarial pass targets them on purpose. Toy model.
## Synthetic flows for shareable report links
Context: @docs/specs/share-links.md, routes under src/app/s and src/api/reports.
States (use only these): Report, ShareDialog, LinkCreated, PublicView, Expired,
Revoked, NotFound, RateLimited
Dimensions: viewer{owner,teammate,anonymous} link{active,expired,revoked}
device{desktop,mobile} size{small,huge} network{good,flaky}
1. Generate the smallest set of flows that covers every PAIR of dimension values.
2. Add 6 adversarial flows aimed at edge states, each with a one-line rationale.
3. For each flow: persona, steps (state names), expected outcome, and the spec
line it tests, or "UNSPECIFIED".
4. Save them to docs/flows/*.json, then list the spec questions grouped by state.
{
"id": "F07",
"persona": {"viewer": "anonymous", "link": "revoked", "device": "mobile", "size": "small", "network": "flaky"},
"strategy": "adversarial",
"rationale": "revocation races a retry on a flaky connection",
"steps": ["PublicView", "Revoked"],
"expected": "Revoked page; no report data in the HTML; retry does not re-fetch the report",
"spec_ref": "UNSPECIFIED",
"question": "Is a revoked link 404 (indistinguishable) or 410 (explicitly revoked)?"
}
claude --chrome
# then, at the prompt:
# open localhost:3000/s/demo-revoked as a signed-out user. read the console for
# errors, save a screenshot to docs/flows/F07.png, and compare what renders with
# "expected" in docs/flows/F07.json. report differences; don't change code yet.
// generated from docs/flows/F07.json; the assertion comes from "expected"
test("F07 anonymous/mobile: revoked link leaks nothing", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const res = await page.goto("/s/demo-revoked");
expect(res.status()).toBe(410); // decided after F07 raised the question
await expect(page.getByRole("heading", { name: "This link was revoked" })).toBeVisible();
expect(await page.content()).not.toContain("Q3 revenue"); // no report data in HTML
});
Failure modesConfirmation flows that restate the spec and find nothing. Impossible flows that use a state the product doesn't have, which is why the prompt pins the list. No oracle: a flow without an expected outcome is a story, not a probe. Chrome caveats: it needs the Claude in Chrome extension 1.0.36+, a direct Anthropic plan and /login (API keys keep it off), and it isn't available on WSL or third-party providers. A recorded GIF "captures everything visible in the browser, including account details on logged-in pages", so review it before sharing (Chrome). And flows aren't users. They probe behavior, not desirability, which is Delivery 5's job.
Why pairs are the sweet spot (covering arrays in one paragraph)
With k dimensions of v values, exhaustive testing needs v^k flows, while a strength-2 covering array needs at least v₁·v₂ rows (the two largest domains) and grows only logarithmically in k. The widget's greedy picker covers all 57 value pairs of the five dimensions with nine flows instead of 72, and still misses three of its five three-way questions. NIST's fault-interaction studies (Kuhn, Wallace & Gallo, IEEE TSE 2004) found most failures triggered by one or two interacting parameters, which is why pairwise is the cheap first pass. Add strength 3 for payments and authorization. Flows add what covering arrays lack, paths: transition coverage is the path analogue of t-way coverage.
Exercise: an exploration pack for your next change
Pick a real change you'll make this week. In Claude Code, produce three artifacts under docs/explore/<change>/, each in a subagent or a skill so your main context stays clean: (1) a cited container or component diagram as Mermaid, (2) a /why report on the oldest file you'll touch, (3) twelve synthetic flows plus their spec questions. Then find one lie in each: an uncited edge, an invented rationale, an impossible flow. Record how you caught it.
Show a reference approach
Create .claude/agents/code-scout.md and .claude/skills/why/SKILL.md from this section, and run the three requests as separate subagent tasks: "use code-scout to…", "/why src/…", "use a subagent to generate flows…". Typical lies: (1) a cache container that exists only in a design doc, which the citation rule exposes because no docker-compose.yml line backs it; (2) a "security hardening" rationale for a value that the PR thread shows was about SMS length; (3) a flow where an anonymous viewer reaches the ShareDialog, which the pinned state list makes impossible. Load the three summaries, not the raw outputs, into your planning session with @docs/explore/<change>/.
Key takeaways
Decide where a question runs: the main session for a few files you'll act on, /btw for answers already in context, Explore or a custom scout for anything broad.
Require file:line citations and mark inferences. Uncited explanations of code are guesses.
History answers "why". Use blame, the pickaxe, gh pr view --comments and claude --from-pr, packaged as a context: fork skill so the raw history stays in its own subagent, out of your context.
Generate diagrams as code with citations, one C4 level per question, and diff them per branch. Artifacts make them interactive and shareable within their availability limits.
Synthetic flows earn their keep through the spec questions they raise. Use pairwise for breadth, adversarial probes for edge states, and Chrome or Playwright to run them.
Planning
When implementation is cheap, planning is mostly about choosing: what's in, what could go wrong, and how to move from today's behavior to tomorrow's without betting the system on one deploy. In Claude Code the plan is a file. Plan mode writes it, you edit it with Ctrl+G, it survives compaction, and every later session loads it. So a plan is cheap to make, cheap to correct, and expensive to skip.
Scope Expansion and Contraction
Agents change the cost curve unevenly. Adding "password-protected links" to a plan costs Claude twenty minutes, but it costs you forty minutes of review, a new attack surface, a support burden and a migration you'll own for years. Claude, asked to plan, will cheerfully expand scope: "while we're here, we could also…". Your job is to expand deliberately when a cheap addition buys real value, and contract to the smallest slice that delivers the outcome. Draw a cut line, and move everything below it to a follow-ups list.
The Claude Code mechanics
Plan in plan mode. Type /plan [description], start with claude --permission-mode plan, or press Shift+Tab until the status bar shows ⏸ plan mode on (from auto mode that's three presses, so /plan is easier). Claude researches and proposes without editing. With auto mode available, the classifier may approve shell commands during planning, so plan mode isn't strictly read-only.
Interview before you scope. For a feature this size, follow the docs: "Interview me until you could write the spec, then write it to SPEC.md." Claude asks with the AskUserQuestion tool. Then "start a fresh session to build from it".
Edit the plan directly.Ctrl+G opens it in your editor. Cut items there instead of arguing in chat. On approval you choose "Yes, and use auto mode", "Yes, manually approve edits" or "No, keep planning".
Explore an expansion without losing the plan./branch creates a branch of the conversation, so you can try "what if we add password protection?" and return to the original with /resume.
Skip the plan when the diff fits in a sentence. Planning a one-line change costs more than it saves.
Toy model with illustrative minutes and values. The box is as wide as your review budget for the week. Each in-scope item is a block whose width is its review minutes and whose height is its value. Agent build time is only the thin shadow under the floor, drawn at half scale: it barely moves the outcome. What binds is your review attention: a block past the box wall ships unreviewed, as unverified code. Click a block, or tick the list, to move an item between the box and the out-of-scope tray. "Contract to fit" fills the budget greedily by value per review minute, keeping the must-haves. "Let Claude expand" takes everything it proposed.
<!-- SPEC.md excerpt: the cut line is explicit -->
## In scope (v1)
- Create a link with expiry (1, 7 or 30 days); revoke it
- Anonymous read-only viewer at /s/:token
- Nightly expiry job; audit event on create, view and revoke
## Out of scope (follow-ups, with the reason)
- Password-protected links: new secret storage and a reset flow; revisit if requested by 3+ customers
- View analytics: raises PII questions; needs a privacy review first
- Custom slugs, iframe embeds: low value, high abuse surface
## Done means
- Every flow in docs/flows/ passes in Playwright; expired and revoked return 410
- `npm run check` green; /security-review has no open high findings
Add a line to CLAUDE.md so the cut line holds across sessions: - Implement only what SPEC.md marks in scope. Put ideas under "Follow-ups" in the PR instead of building them. After implementation, check the diff against the plan with a fresh-context reviewer. The docs' review prompt checks that "every requirement is implemented and the listed edge cases have tests"; add a scope line of your own, such as nothing outside the task's scope changed.
Failure modes"It was free to build": cheap to generate isn't cheap to own. Gold-plating by agent: extra options, configuration and abstraction nobody asked for. A scope reviewer catches them. Over-contraction: cutting the expiry job or the audit trail gives you a demo, not a feature. Must-haves are the items without which the outcome isn't delivered, and they stay above the line. Scope by chat: if the cut line lives only in conversation, compaction or a fresh session loses it. Put it in SPEC.md.
Risk Mapping
A risk map lists what could go wrong, how likely and how bad each item is, and, the part that matters, which control addresses it. In Claude Code, controls come in two kinds. Advisory controls (CLAUDE.md lines, plan notes, prompts) shape what Claude intends. Enforced controls (permission rules, hooks, tests, CI, human approval) hold whatever Claude decides. The docs are explicit that CLAUDE.md is "context, not enforced configuration", while "permission rules are enforced by Claude Code, not by the model." A good risk register pairs every high risk with at least one enforced control.
Run a premortem in plan mode
A premortem assumes the feature failed in production and asks why. Models are good at this: they enumerate failure modes tirelessly, and you judge which ones are real.
/plan Premortem for share links. Assume it shipped and caused an incident within
30 days. List the 8 most plausible causes across security, data, performance,
operations and product. For each: likelihood 1-5, impact 1-5, the earliest signal
we'd see, and the cheapest control that ENFORCES the mitigation (permission rule,
hook, test, CI check, flag, human review). Mark controls that are advisory only.
Add the table to the plan under "Risks".
The share-links premortem as tomorrow's front page. Each of the six risks is a headline: its size is the impact, its byline gives likelihood × impact, and anything scoring 9 or more stays on the front page, which is the unresolved risks list that ships with the PR. Tick controls to apply them. Each one is a real Claude Code or engineering mechanism, and it re-sets the stories it touches smaller or moves them inside, with a margin note naming it. Hover or focus a story to see which controls touch it. The CLAUDE.md line moves nothing. Scores and effects are illustrative.
## Risks
| # | Risk | L | I | Control | Kind |
|---|------|---|---|---------|------|
| R1 | Token guessable or leaked in logs | 3 | 5 | 128-bit tokens; log redaction test; /security-review | enforced (test) |
| R2 | Revoked link still served from CDN cache | 4 | 4 | `Cache-Control: private, no-store` test on /s/* | enforced (test) |
| R3 | Migration locks `reports` for minutes | 2 | 5 | expand-contract; dry run on a prod-size snapshot | enforced (CI) |
| R4 | Invite email to the wrong recipient | 2 | 4 | human review of template + recipient logic | human |
| R6 | Agent edits migrations without review | 3 | 4 | `ask` rule on Edit(/src/db/migrations/**) | enforced (permission) |
Why two ask rules? The Edit ask rule covers Claude's file tools. For Bash, Claude Code also checks the files that commands it recognizes write (sed, tee, redirect targets such as > file), but the docs describe that check against your Edit allow and deny rules and don't say ask rules get it. And no path rule sees "a Python or Node script that opens files itself", such as a migration generator. So the Bash(npm run db:migrate *) rule covers the shell path explicitly. The ask rule is anchored with a leading /, so in project settings it matches <primary working directory>/src/db/migrations/**, which in a worktree session means that worktree's own copy. Remember that a Bash deny rule "isn't a security boundary around the program": Bash(psql *prod*) doesn't stop bash -c or a script. For containment, use the sandbox: it's off by default, covers shell commands only, and you turn it on with /sandbox. The docs recommend it "for filesystem and network enforcement that doesn't depend on the command text." A PreToolUse hook adds your own checks on the command text as defense in depth. For production, the real control is not giving the agent production credentials at all (Core 5: security).
What you build: a deterministic analyzer for a diff or a plan-mode plan. It combines path tiers (money code, public API, CI, and the agent's own config: .claude/settings.json, hooks, .mcp.json), content signals in changed lines (a deleted assertion, float money math, a Bash(*) allow rule), an ast import-graph blast radius, and plan drift. It maps each mitigation to a control (ask/deny rule, hook, test, review command or human) and writes a reviewable settings.json snippet. It needs no model, network or claude binary.
cd labs && python3 delivery-3/risk_map.py # sample diff + plan
cd labs && python3 delivery-3/risk_map.py --plan delivery-3/samples/plan.md # before any code exists
cd labs && python3 delivery-3/risk_map.py --strict # exit 1 if a high risk has no gate or deterministic check
Observe: the sample suite still passes, yet the diff deletes an assertion and reintroduces float math that CLAUDE.md already forbids. A prose rule that's still violated is a rule that needs to become a check. Also look at the plan-vs-diff section (files touched outside the plan's scope), and at how --strict treats /code-review and /security-review as advisory, not gates. On the sample every high risk already has a gate, so --strict exits 0; README exercise 1 shows it failing.
Why advisory controls fail when you need them most
CLAUDE.md is a message, not a policy. "CLAUDE.md content is delivered as a user message after the system prompt", and Claude treats it as context. "To block an action regardless of what Claude decides, use a PreToolUse hook instead" (memory).
Boundaries in chat can vanish. In auto mode, "Boundaries are not stored as rules… a boundary can be lost if context compaction removes the message that stated it. For a hard guarantee, add a deny rule instead" (permission modes).
Precedence is strict. "Rules are evaluated in order: deny, then ask, then allow… An allow rule can't carve an exception out of a deny rule." A hook's exit 2 blocks before rules are evaluated, and a hook deny holds even in bypassPermissions (permissions, hooks guide). One exception: mods. "With neither managed settings nor a Team or Enterprise /login as the session's credential, the mod can approve a call that a deny rule refuses or a PreToolUse hook blocked." On personal setups, audit the mods you install.
Hooks can fail open. A timed-out PreToolUse command hook doesn't block unless you set "onFailure": "block" (requires v2.1.295+). "Don't count on a stalled hook to act as a gate." For hard allow/deny decisions, use permission rules.
The practical rule: score risks, then for every risk with L×I ≥ 9 ask "what holds if Claude ignores the plan?" If the answer is "nothing", the control is advisory, and the risk is unresolved until you add an enforced one.
Implementation Strategies
"How do we build it?" has a handful of recurring answers. Each maps onto Claude Code machinery, and each fits a different mix of uncertainty (do we know the approach?), breadth (how many files?), coupling (how many shared hot files?), repetition (is it the same change many times?) and reversibility (can we undo it after release?).
Strategy
Fits when
In Claude Code
Direct
Clear approach, a few files
One interactive session; skip the plan for one-sentence diffs
Spec → fresh session
Medium feature, real ambiguity up front
AskUserQuestion interview → SPEC.md → new session executes it
Tracer bullet, then fan out
Many layers, shared contracts
One session builds a thin path through DB, API and UI; then parallel worktrees fill in each layer
Parallel variants
High uncertainty about approach or design
/fork copies or worktree sessions per variant; an artifact "with four distinctly different layouts… as a grid with a one-line tradeoff under each"
Mechanical fan-out
Same change in many files, low coupling
/batch <instruction> (5 to 30 worktree-isolated units) or a dynamic workflow ("use a workflow to migrate every component…")
Expand-contract behind a flag
One-way doors: schema, public URLs, data formats
Plan the steps as separate PRs; ask rules on migrations; a flag plus a watched rollout
Toy scoring with illustrative weights. Move the sliders to describe the work (1 is low, 5 is high): your constraints are the filled shape on the radar. Each strategy's ideal shape is a dashed outline, the best fit's outline carries the highlight, and the list ranks the fits; hover or focus a strategy to lay its shape over yours. The recipe shows how to start the top one in Claude Code. The defaults describe share links (uncertainty 2, about 25 files, coupling 4, repetition 1, irreversibility 4): the tracer bullet wins, with expand-contract for the migration. Push uncertainty to 5, or repetition to 5 with coupling at 1, and watch the shape and the pick change. The range below reads the pick.
For share links, the plan that falls out is: a tracer bullet first (migration, one API route and a bare viewer page, end to end, in one session), then four parallel worktrees for the API details, the UI, the jobs and the email, and an expand-contract migration so the share_links table ships before any code depends on it. When the approach itself is in doubt, have several agents draft plans from different angles first. Dynamic workflows (v2.1.154+) list "a hard plan worth drafting from several independent angles before you commit to one" as a core use.
A tracer round glows, so you see where it lands while there's still time to re-aim. The range is seen from the side. The tracer slice (a migration, one API route and a bare UI behind a flag) crosses all three layers through a thin lit slit and lands on day 1, slightly off: it finds this page's own risk R2, revoked links still served from the CDN cache. Corrected, it hits on day 2, and only then do the fan-out lanes fill in. Layer by layer builds each wall in full, fires once at integration, misses on day 8 with the same R2, and pays for the rework. Pick a strategy, scrub the days or press $ fire tracer. Linked to the strategy chooser above. Days, arcs and miss sizes are illustrative.Where the plan lives, and why that matters for long work
Plan files persist. Plans are written under plansDirectory (default ~/.claude/plans). After compaction, the plan Claude wrote in plan mode is "Re-injected from disk", so an approved plan survives a long session where chat instructions might not (context window). Commit the plan you executed, for example as docs/plans/share-links.md, so cloud sessions, teammates and reviewers see it too. ~/.claude doesn't travel to cloud sessions.
Accepting a plan."showClearContextOnPlanAccept": true (default false) adds a first option to the approval menu, Yes, clear context and …, which approves the plan, clears the conversation and starts implementing from the plan alone. That's the "fresh session" pattern in one step. useAutoModeDuringPlan (default on) lets the classifier review shell commands while planning. Set it to false to get prompts instead.
Model split. The opusplan alias "uses opus during plan mode, then switches to sonnet for execution". It's an option when planning is the hard part and execution is routine. Measure on your codebase before you adopt it (model config).
Effort. One insider's loop: "getting the model to interview me then implementing on low effort, reviewing what it built, and then running verification on high effort." Effort "tends to reduce failures due to missing edgecases… but does not fix when the model has the wrong approach", which is why strategy comes first (Spending your effort, official blog).
Exercise: a one-page plan Claude can execute
For a real feature, run the interview prompt with AskUserQuestion until Claude writes SPEC.md. Then, in plan mode: (1) draw an explicit cut line with reasons; (2) run the premortem and add a Risks table where every L×I ≥ 9 risk has an enforced control; (3) name the strategy and the merge order. Press Ctrl+G and cut anything you wouldn't review this week. Approve with "Yes, manually approve edits" and check whether the first edits match the plan.
Show what a strong plan has
A strong plan fits on one screen. It has a "Done means" block with commands that prove it (npm run check, specific Playwright flows), an "Out of scope" list with a reason per item, a Risks table whose controls are mostly rules, hooks and tests rather than prose, and a sequence with explicit merge points ("schema PR merges before any API work starts"). Weak plans list steps without evidence, put every risk control in CLAUDE.md, and have no out-of-scope section, so the agent's helpful expansions creep back in.
Key takeaways
Agent minutes are cheap and your review minutes aren't. Draw an explicit cut line in SPEC.md and send expansions to follow-ups.
Plan in plan mode, edit the plan with Ctrl+G, and skip the plan when the diff fits in one sentence.
Every high risk needs at least one enforced control: a permission rule, hook, test, CI check or human approval. CLAUDE.md lines are advisory.
Choose the strategy by uncertainty, breadth, coupling, repetition and reversibility: direct, spec-then-fresh-session, tracer bullet, variants, /batch, or expand-contract.
The plan is a file that survives compaction. Commit it so other sessions and reviewers can load it.
Execution
Execution is now mostly a routing decision. For each task, who holds the context: you in an interactive session, a subagent, a background session, a cloud VM, or several worktrees at once? And where does the work merge back? Getting the routing right matters more than prompt polish. A task routed to the wrong place either eats your attention (too close) or comes back as plausible rework (too far).
Two qualitative curves cross: your attention per task falls, and the cost of transferring context and merging work rises, as work runs further from you. Their crossover falls in the handoff regime. Under each shaded regime are its Claude Code mechanisms: direct work keeps context with you; a handoff moves it into a brief for one worker; parallel work multiplies workers, so the binding costs become file footprints, merge points and your review queue. Hover or focus a regime to light it.
Direct Work
Direct work is you and Claude in one interactive session, steering turn by turn. It's still the right default for a large class of tasks: when the task needs your judgment each turn (naming, UI feel, API shape), when the definition of done is still forming, when you're debugging and you hold the hypotheses, when you need to understand the result well enough to own it on call, and for one-sentence diffs. On v2.1.283+, interactive terminal and VS Code sessions start in auto mode, so the classifier reviews most actions instead of you. Switch to Manual when you want to approve every edit.
How to do it well
Give it a check it can run, in the same prompt: "run npm test -- ShareDialog and show me the output." In the docs' words: "Once it has that, it can keep going on its own and you don't have to watch."
Point to the pattern. "Follow the toast pattern in src/ui/ExportButton.tsx" beats describing the toast. Claude copies what it reads, which Engineering turns into a debt question.
Interrupt early.Esc stops Claude mid-action and "Claude keeps the work done so far". Esc Esc on an empty prompt, or /rewind, restores code, conversation or both from a checkpoint. Checkpoints don't cover files that only Bash commands changed (once Claude has edited a file with its own tools, /rewind also undoes later Bash changes to it), so commit at every green point (checkpointing limits).
Reset after two misses. The docs: "after two failed corrections run /clear and write a better prompt instead of a third", one that includes what you learned.
the share dialog's "Copy link" button should show "Copied" for 2 seconds, then
revert. implement it in src/ui/ShareDialog.tsx using the toast pattern from
src/ui/ExportButton.tsx. add a test for the revert timing with fake timers,
run `npm test -- ShareDialog`, and paste the output.
Failure modesBabysitting: watching Claude do a well-specified, verifiable task that could have run in the background while you did the judgment-heavy one. The kitchen-sink session: unrelated tasks piled into one context. Use /clear between them. Rubber-stamping: in Manual mode, "after the tenth prompt you start approving without reading". Allowlist the safe commands and spend your attention on the diffs. Trusting rewind for side effects it doesn't cover: files only Bash changed, external services, pushed commits.
Handoffs
A handoff moves a task's context from you to another worker, and what the handoff carries is the main design question. Claude Code has several handoff mechanisms, and they differ exactly there:
Mechanism
Carries
Result comes back
Subagent ("use a subagent to…", @"name (agent)")
Its own system prompt, the task prompt Claude writes, your CLAUDE.md hierarchy and a git-status snapshot. Not your conversation. (Explore and Plan skip CLAUDE.md and git status.)
A copy of the conversation in a new background session, plus model, mode, effort and grants
Not automatically. Check it in agent view
/background (/bg)
This whole session, detached
You reattach with claude attach
Background session: claude --bg "<prompt>"
A fresh session: your project config plus the prompt, nothing from this conversation. It moves into its own worktree before editing
A final report naming where the work is: path, branch or PR
Cloud session: claude --cloud "<task>"
With the Claude GitHub App installed: your GitHub remote at the current branch (push first). Without it, or with no remote: a bundle of your local repo. Not ~/.claude or local plugins
A branch or PR. claude --teleport pulls the session down (one-way)
Because most handoffs carry only a prompt, the prompt is the context transfer. The official cloud field guide puts it in one line: "Write each task as a self-contained ticket that states what's wrong, what done looks like, and how to prove it." That's a handoff brief:
## Task: expire share links nightly
Wanted: links past `expires_at` stop working without waiting for a viewer.
Done means: src/jobs/expire-links.ts revokes expired links in batches of 500 and
writes one audit event per batch; it's registered in src/jobs/index.ts;
`npm test -- expire-links` passes.
Prove it: paste the test output and one dry-run log line.
Boundaries: don't touch src/db/migrations/ or src/api/. No new dependencies.
Context: docs/plans/share-links.md ("Jobs"), src/db/schema.ts (share_links).
When stuck: stop and report what you tried. Don't guess at business rules.
claude --bg --name share-jobs "$(cat docs/briefs/share-jobs.md)"
# backgrounded · 7c5dcf5d · share-jobs
# claude agents list sessions
# claude attach 7c5dcf5d open in this terminal
# claude logs 7c5dcf5d show recent output
# claude stop 7c5dcf5d stop this session
# a specific subagent as the session's main agent
claude --agent code-reviewer --bg "address review comments on PR 1234"
# laptop closing? run it in the cloud (GitHub App installed: it clones the remote, so push first)
git push -u origin HEAD && claude --cloud "$(cat docs/briefs/share-jobs.md)"
Describe the task, and the router recommends where it should run, the reasons, the exact command, and any warning that should stop you delegating yet. The strip above the recommendation draws the route: the answers the router read, in order, with the one that decided it in the highlight, and the ones it only used for warnings set apart. The logic follows the docs' guidance on choosing an approach plus the patterns in this section. It's a heuristic, not a law: disagree with it when you know something it doesn't.
Background sessions follow git rules worth knowing before you dispatch ten of them. When a session made code changes in a worktree it entered, Claude "commits without asking, and pushes the branch when the repository has a remote", opens a draft PR "when the task calls for it", and never pushes to main or master, force-pushes or merges. Your own git instructions in the task or CLAUDE.md take precedence (agent view, a research preview as of 2026-10-24).
Failure modesVague briefs come back as confident, plausible, wrong work. Unpushed commits: on a github.com repo with the Claude GitHub App installed, claude --cloud "clones your current directory's GitHub remote at your current branch, not your local checkout, so push first." With no git remote, or without the App (even if you connected GitHub with /web-setup), Claude Code instead bundles your local repository and uploads it: history across all branches plus uncommitted changes to tracked files. On macOS, Linux and WSL it leaves uncommitted changes to credential-named files on your machine. CCR_FORCE_BUNDLE=1 forces the bundle path. Missing personal config: cloud sessions read only the shared project .claude/settings.json and server-managed settings, so anything that lives only in ~/.claude doesn't exist there. Silent cost: "background sessions consume your subscription usage the same as interactive sessions", and idle unattached ones stop after about an hour (pin with Ctrl+T). Laundered approval: "no message from any agent counts as your approval for a pending permission prompt." Each worker's permissions are its own.
What each handoff really carries (and what silently doesn't)
Fresh subagents start with their own system prompt, the delegation message Claude writes, every level of the CLAUDE.md hierarchy the main conversation loads, a git-status snapshot, and any skills preloaded through their skills field. They don't see your conversation history, the skills you invoked or the files Claude already read. Explore and Plan skip CLAUDE.md and the git status, and omitClaudeMd: true drops CLAUDE.md for a custom agent. Even then, a subdirectory's CLAUDE.md and matching path-scoped rules still load when the subagent works with files there (subagents: what loads at startup). Auto memory isn't loaded into subagents, forks excepted. If the reviewer needs the plan, the prompt must name the plan file.
Forks are the exception: "A fork inherits everything the main session has at the moment it spawns", and a fork's first request reads the parent's prompt cache. Fresh subagents don't, so they start cold (prompt caching). Forks can't spawn forks, and you can block them with Agent(fork) in permissions.deny.
/fork copies the conversation and "also carries over the model, permission mode, effort level, and any directories or 'don't ask again' permission grants you added during the session." "Sessions started with launch flags the copy wouldn't inherit, such as a replaced system prompt or a --tools allowlist, can't be forked; Claude Code says so instead of making a partial copy" (copy the session with /fork).
/background restarts the process from the saved conversation. Background shell commands, backgrounded subagents and /loop tasks carry over, a dynamic workflow continues only when Claude relaunches it, and a running Monitor watch stops. Claude Code shows a Background this session? dialog before stopping it.
Cloud: with the Claude GitHub App the session clones your remote; without it, Claude Code uploads a bundle of your local repo (CCR_FORCE_BUNDLE=1 forces this). Session handoff is one-way: --teleport pulls a cloud session down, and nothing pushes a terminal session up (cloud sessions).
Cloud config and credentials: per the official field guide, "CLAUDE.md, rules, skills, agents, and commands travel with the repo, and your ~/.claude stays on your laptop", and "Your GitHub token never enters the VM." (field guide).
What a cloud session gets: in the docs' terms, a cloud session starts from a fresh clone and doesn't install the plugins a repository turns on in its settings (what carries over).
Delegation contracts, result formats and failure reporting get their full treatment in Agents 4: delegation.
Parallel Sessions
Parallel execution means several workers changing the same repository at once. Claude Code gives you five ways to do it (subagents, agent view, agent teams, dynamic workflows and projects), plus three tools that support them: worktrees, cross-session messaging and /batch (run agents in parallel). For a feature like share links, the practical setup is a handful of worktree sessions or background sessions, each owning a lane.
Worktree mechanics
# one terminal per lane: each gets .claude/worktrees/<name>/ on branch worktree-<name>
claude -w share-api
claude -w share-ui
# or dispatch and walk away: each moves into its own worktree before it edits
claude --bg --name share-api "$(cat docs/briefs/share-api.md)"
claude --bg --name share-ui "$(cat docs/briefs/share-ui.md)"
claude agents # one screen: Working, Needs input, Completed, Failed...
# once per repo
echo ".claude/worktrees/" >> .gitignore
printf ".env.local\nconfig/dev-secrets.json\n" > .worktreeinclude # gitignored files to copy in
A worktree "is a fresh checkout, so untracked files like .env or .env.local from your main repository are not present." The .worktreeinclude file (gitignore syntax) copies only files that match and are gitignored. New worktrees branch from the remote default branch (worktree.baseRef: "fresh"). Set "head" to carry your unpushed work. While a session is in a worktree, Claude Code blocks edits to paths in the main checkout, commands whose working directory resolves there, and git redirected into it. Worktrees share the repository's .git, project-scope plugins and "don't ask again" approvals (worktrees).
Plan the file footprints first
Worktrees isolate edits, not merges. Two lanes that both edit src/db/schema.ts will conflict at merge time however well isolated they were. Before dispatching, ask Claude in plan mode for a file footprint per task: the files it will edit and the files it will only read. Overlaps on hot files (schemas, route indexes, i18n string tables, package.json and its lockfile) are where parallel work breaks. Resolve them before starting: give one lane ownership, land the shared contract in the tracer bullet, or put the lanes in sequential waves. The field guide's version: "Split parallel tasks along file boundaries, merge the branches in a sensible order."
Each tile is a file. Each lane hatches the files it edits at its own angle, so two lanes on one file cross-hatch and three overprint into a dense patch. Files tagged hot are the shared ones (schema, routes, middleware, i18n, lockfile), and a hot file with two or more editors carries the highlight. Pick a lane as the brush and click a tile to toggle that lane's edit. The planner groups lanes into waves, printing passes in which no two hatches meet, honors the dependency "schema before anything that uses it", and prints the dispatch commands and merge order. Turn the dependency off (assume the tracer bullet already landed the schema), then press the three ownership buttons and watch six lanes collapse into one wave. The merge-order slots below read these file sets.
What you build: a planner for parallel sessions built from write and read footprints (nine tasks against the sample repo). It produces an overlap matrix, waves with the reason each delayed task waits, what-if scenarios, and merge points. Each task gets a mechanism: claude --worktree, a read-only subagent, the main checkout, /batch or agent teams.
cd labs && python3 delivery-3/parallel_plan.py # at most 3 writer sessions
cd labs && python3 delivery-3/parallel_plan.py --max-parallel 6 # more seats: does it help?
Observe: unlimited writers still take four waves, because footprints cap parallelism, not seats. The merge-point section flags stale reads that git can't see (a task built on the old version of a file another task changed), and reminds you to push the merged branch before the next wave, since new worktrees branch from the remote default branch.
Failure modesToken multiplication: "five sessions use them about five times as fast as one" (field guide). Review becomes the bottleneck. As one practitioner puts it, the limit "is how fast I can review the results" (Simon Willison, community). Don't run more lanes than you can review this week. Environment drift: missing .env, dependencies not installed in the new checkout, two dev servers fighting over port 3000. Agent teams don't isolate teammates in worktrees, so partition files yourself. Shell writes: the isolation checks read edit paths, command directories and command text, so "a command that writes into the main checkout without running git there, such as cp or a shell redirect, isn't refused by them."
Worktree isolation internals, cleanup and locks
Four checks apply to the session and every subagent it spawns: file edits targeting the main checkout; Bash, PowerShell or Monitor commands whose working directory resolves to the main checkout (or can't be verified to stay outside it); git redirected into the main checkout through git -C, --git-dir, GIT_DIR/GIT_WORK_TREE or a cd; and commands whose shape can't be verified, such as computed command names or unparseable syntax. You can't turn that last check off.
Hooks don't follow the worktree.${CLAUDE_PROJECT_DIR} keeps pointing at the project root where the session started, while the hook input's cwd field is the worktree root. A hook that runs tests must read cwd, or it tests the main checkout. This catches people in integration gates.
Cleanup. When you exit, a clean, unnamed worktree is removed with its branch. A named or dirty one prompts you. -p runs never clean up. Subagent and background-session worktrees are swept after cleanupPeriodDays, unless they still hold work. While an agent runs, Claude Code holds a git worktree lock on its worktree.
Subagent isolation.isolation: worktree in an agent's frontmatter gives every invocation its own temporary worktree. In a background session, a spawned subagent's edits land in the session's worktree unless the subagent has its own isolation.
Why more lanes stop helping. The serial share of merges and review caps the speedup (Amdahl's law), and coordination costs grow with lanes squared (the Universal Scalability Law). Core 4's throughput model shows the same ceiling for your own attention.
Merge Points
A merge point is a planned moment where a lane's branch integrates into the mainline, with a check that must pass before the remaining lanes rebase onto it. Unplanned merge points are where parallel work loses its gains: four branches that each pass their own tests and fail together, or a final merge that turns into an afternoon of conflict resolution.
Why schema first and contract last? Every merge makes the lanes behind it redo work. The rail holds five ordered slots, M1 to M5, with a ◆ integration check after each merge, and the contract step, which drops the old column, stands in the last slot for good. When a lane drops into its slot, every lane still waiting rebases the files it shares with it and gets one cross-session message, so its meter fills; a check fails when a lane lands before the schema it depends on, which sends that lane back to rebase everything. The default is the recommended order. Press $ worst order to see the pile-up, or click cards to set your own. The file sets come from the footprint planner above; the cost model is illustrative.
Mechanics in Claude Code
Order by dependency and sharing. Merge the lane the others build on (schema, shared types) first, then the most-shared one, and leave the riskiest, most isolated lane for last so it rebases onto everything.
Review each lane on its own./code-review main...worktree-share-api reviews one branch against another, and /code-review 1234 reviews a PR. claude --worktree "#1234" checks out a PR in its own worktree (.claude/worktrees/pr-1234) so you can run it without touching your checkout.
Tell the other lanes what landed. With cross-session messaging (requires v2.1.224+ on macOS and Linux, v2.1.234+ on native Windows), Claude can "tell the other sessions what landed" when they work the same repo in separate worktrees. Prompt it with: "explain what we just merged to the sessions working on share-ui and share-jobs."
Rebase with a check. In each remaining lane: "rebase on origin/main, resolve conflicts in the files this lane owns, run npm run check and paste the output. If a conflict is in a file another lane owns, stop and tell me."
Failure modesSemantic conflicts: git merges cleanly but behavior breaks. Two lanes each register /s/:token, or one changes the token format the other parses. Only an integration check after each merge catches these early. Resolution by deletion: an agent "resolves" a conflict by keeping its own side. Review conflict resolutions as their own diff. Merge-day pileups: merging everything at the end turns four small integrations into one big one. Auto-fix and conflicts: GitHub sends no webhook when the base branch advances into a conflict, so PR auto-fix "can't react to conflicts on its own". Ask for the rebase yourself.
How likely is a conflict, and what to do about hot files
If n lanes each edit k of F equally likely files, the chance that some pair shares a file is a birthday problem: roughly 1 − (1 − k/F)^(k · n(n−1)/2). With 6 lanes (15 pairs), 4 files each and 200 candidate files, that's 1 − 0.98^60 ≈ 70%, even with perfectly uniform edits. Real repos aren't uniform: edits concentrate in hotspots, so the real number is higher still. That's why the footprint planner treats schema files, route indexes and lockfiles specially. Where the lanes rejoin is Agents 4: merge points.
Three structural fixes beat luck. Ownership: exactly one lane edits each hot file, and the others request changes through it. Contract first: the tracer bullet lands shared types and the migration before the lanes start. Generated files: let lockfiles conflict and regenerate them (npm install after the rebase) instead of merging them by hand.
Exercise: run a three-lane execution
Take a feature with at least three separable parts. In plan mode, ask for a footprint table (files edited and read per lane) and fix every hot-file overlap by ownership or sequencing. Write a brief per lane in docs/briefs/. Dispatch two lanes with claude --bg --name … and run the third yourself in claude -w. Merge in the planned order, with npm run check (or your equivalent) after each merge and a cross-session message to the remaining lanes. Afterwards, note where your attention actually went.
Show a reference approach
For share links: lane A (schema plus API, owns schema.ts and routes.ts), lane B (UI, owns ShareDialog.tsx and en.json), lane C (jobs and email). Land the tracer bullet first, a single commit with the migration and type definitions, so B and C build against real types. Merge order: A, then B (rebased), then C. Typical lessons: most of your time goes to reviewing and to the one lane with an under-specified brief, not to "running agents"; a semantic conflict shows up after the second merge (both A and C formatted expiry dates); and two lanes are usually as many as one person can review deeply in a day.
Key takeaways
Route each task by where its context should live: with you (direct), in a brief for one worker (handoff), or across lanes (parallel).
Direct work wins when the task needs your judgment each turn. Give Claude a runnable check, interrupt early, and reset after two misses.
Most handoffs carry only a prompt, so the brief is the context. State what's wanted, what done means, how to prove it, the boundaries, and what to do when stuck.
Worktrees isolate edits, not merges. Plan file footprints and give each hot file one owner before dispatching.
Plan merge points: merge the shared lane first, run an integration check after each merge, and tell the remaining lanes what landed.
Feedback
"Claude stops when the work looks done." Feedback loops decide what "looks done" means. Without a signal Claude can read, you become the test suite, and every mistake "sits there until you happen to notice it." This topic is about closing loops inside Claude's turn: logs it can grep, screenshots it can see, human comments that reach the session, and artifacts that outlive the context window.
Logs
Logs are the cheapest high-signal feedback there is, if they reach Claude in the right shape. They can reach it in four ways:
Claude reads them with Bash: tail -n 200 .logs/dev.log, grep -n ERROR. Read-only commands such as tail and grep never prompt.
You pipe them in: cat error.log | claude -p "what's going on here", straight from the best-practices guide. Piped stdin "is capped at 10MB."
Claude streams them with the Monitor tool (added in 2.1.98), which "runs a command in the background and feeds each output line back to Claude, so it can react to log entries, file changes, or polled status mid-conversation." Ask it to "tail the dev server log and flag errors as they appear while I click through the share flow." Each watch has a deadline: 5 minutes by default, at most 30, and at most 10 in a -p run. When it ends, Claude gets one notice and can restart it.
Background commands: Ctrl+B backgrounds a running Bash command, and /tasks lists background work. claude --bg --exec 'npm run dev' runs a shell job as an agent-view row, for you: its output "isn't sent to any session."
Make logs agent-friendly, then put them on a diet
The C-compiler experiment's advice generalizes: "The test harness should not print thousands of useless bytes" and "write ERROR and put the reason on the same line so grep will find it" (Anthropic engineering). Use one event per line, the level and reason together, a request or job id on every line, and dev servers writing to a file Claude can grep. Then filter before Claude reads anything. The costs docs ship this PreToolUse hook, which rewrites test commands to show only failures:
#!/bin/bash
input=$(cat)
cmd=$(echo "$input" | jq -r '.tool_input.command')
# If running tests, filter to show only failures
pattern='^(npm test|pytest|go test)( [^;&|<>`$#\\[:cntrl:]]*)?$'
if [[ "$cmd" =~ $pattern ]]; then
filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:)' | head -100"
echo "$input" | jq --arg filtered "$filtered_cmd" \
'{hookSpecificOutput: {hookEventName: "PreToolUse", updatedInput: (.tool_input + {command: $filtered})}}'
else
echo "{}"
fi
Verify it with /hooks, or start claude --debug-file ./claude-debug.txt, run npm test, and look for a modified tool input keys line (costs). The pattern matches only a bare test command with plain arguments, and the hook returns no permissionDecision, so the rewritten command still goes through your permission rules and mode. And mind the pipe: the rewritten command's exit status is head's, so a failing run whose output doesn't match the regex looks clean. Prefix set -o pipefail; or append a failure count so a failed read never passes for a quiet log.
Toy model with illustrative numbers. Each square's area is proportional to tokens: first the log itself, then what reaches your main context with each strategy. Pasting puts the whole square in your context; a separate claude -p and a subagent return one small answer or summary; a filter hook passes only matched lines up to its head -100 cut; Monitor streams only matching lines (the all-signal square). Lit specks are signal lines. Under each square: tokens added to your context, then the total processed anywhere. Set the log size, the tokens per line and the share of lines that matter: pasting is the only option that's expensive on both counts.
Failure modesSecrets in logs: anything Claude reads enters model context, so redact tokens at the logger, not in the prompt. Firehose reads: cat on a 50,000-line log crowds out the instructions that matter. Watches that silently end: a Monitor watch past its deadline is gone, so ask Claude to re-arm it or use /loop for long horizons. Availability: on Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform and Foundry, and when DISABLE_TELEMETRY or CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC is set, the Monitor tool and plugin monitors need v2.1.310 or later; earlier versions don't offer them there. On Windows it needs Git Bash. A failed read isn't a quiet log: "Don't mistake a failed read for a quiet day" (official blog). Have Claude report "0 errors in 1,240 lines", never just "no errors".
Visual Feedback
UI work has a feedback channel that tests barely touch: what the screen looks like. Claude Code closes it in both directions. You show Claude: paste a screenshot with Ctrl+V (Alt+V on Windows and WSL), drag in a mockup, or give a path, and it appears as [Image #N]. Claude shows itself: through Claude in Chrome it can open your local app, click through it, read the console and DOM, take screenshots and record GIFs. Desktop's Browser pane does the same against a dev server it starts, and "by default, Claude auto-verifies changes after every edit."
The visual loop only closes when a target exists to compare against: a mockup, a baseline screenshot, or a written expected outcome from a synthetic flow. Drag the onion-skin slider between the target (dashed) and the current render. The circled numbers mark the differences, and they become the difference list Claude fixes. The thin ring around the frame is the loop itself: edit, run, look, compare, fix. Without a target, "looks good" is self-assessment. Your role sits off the hot path: you supply the target and review annotated screenshots, not every iteration. The share dialog is an illustrative mock.
[paste screenshot] implement this design, take a screenshot of the result,
compare it to the original, then list the differences and fix them
I just updated the share dialog. open localhost:3000/reports/42, open the share
dialog at 390px and 1280px widths, create a 7-day link, and check the console for
errors. save both screenshots to docs/shots/ and compare them with
docs/shots/share-dialog-target.png. list every difference, then fix them.
Three bundled skills turn "it compiles" into "it works": /verify builds and runs your app "to confirm a code change does what it should, without falling back to tests or type checks", /run launches and drives it, and /run-skill-generator records how to build and launch your project as a per-project skill at .claude/skills/run-<name>/, so later runs follow the recipe instead of rediscovering it. /verify runs only when you invoke it. When /verify has to work out a build without a recorded recipe, it writes what worked to .claude/skills/verify/SKILL.md (at the repo root, or in the touched package in a monorepo), and at the repo root that recorded skill replaces the bundled /verify. That matters because of a second rule (requires v2.1.286+): when a skill named verify or simplify is in place at session start, Claude's commit instructions tell it to run that skill right before each commit, except for changes to docs or tests. Three conditions apply. The skill must load from an enterprise, personal, project or additional-directory location (or a .claude/commands/ file with that name), not be the bundled one, a plugin skill or a claude.ai skill. Claude must be able to invoke it, so no disable-model-invocation: true. And includeGitInstructions must not be false (skills).
Failure modesSelf-graded screenshots: "agents tend to respond by confidently praising the work", and "tuning a standalone evaluator to be skeptical turns out to be far more tractable than making a generator critical of its own work" (Anthropic engineering). Give it a target, or a second reviewer. One viewport, one state: a desktop screenshot of the happy path says nothing about mobile, empty states or errors, so name the widths and states. Console blindness: ask for console errors explicitly. Generic taste: "make it look better" swaps one default for another, so name what you want and what you don't. Privacy: screenshots and GIFs of logged-in pages capture account data.
Human Feedback
Your feedback is the most expensive signal in the loop and the only one that carries taste, intent and accountability. The goal is to make it cheap to give, precise when it lands, and durable, so you don't give the same note twice. Claude Code has a route for feedback at every artifact:
On
How the feedback reaches Claude
A plan
Ctrl+G opens it in your editor. In VS Code, plans open as Markdown with inline comments.
A diff
Desktop's diff view: click any line, type a comment, then submit all comments with Cmd+Enter (Ctrl+Enter on Windows). Claude makes the changes as a new diff.
A pull request
Reviewers comment on GitHub. /autofix-pr spawns a cloud session that watches the PR and pushes fixes for CI failures and review comments. Desktop's Auto-fix does the same for a local session. @claude in a comment triggers the GitHub Action.
An artifact
Teammates comment on the page and send a thread to Claude ("Send to Claude" or @claude). Claude reads comments (v2.1.221+) and, in a mode that allows it, replies on its own (v2.1.228+).
An open question
AskUserQuestion interviews, and Remote Control from your phone to answer a prompt that's waiting.
Make each note actionable
A good note has a location, the expected versus actual behavior, and a severity. Batch notes into one round instead of trickling them. The Claude Code team's review practice caps the loop: "After three rounds, the reviewer asks the author to step back" (How the Claude Code team does code review, official blog).
review round 1 for ShareDialog (fix blockers and shoulds; list nits you skip)
- BLOCKER src/ui/ShareDialog.tsx:58 expiry dropdown defaults to "never";
spec says 7 days. expected: 7d preselected
- SHOULD :91 "Copied" toast steals focus from the dialog. keep focus on the button
- NIT copy "Share this report" -> "Share report" (matches ReportHeader)
Failure modesSaying it twice: a note you've given twice belongs in a rule, a skill or a hook (see Conventions and Delivery 5). Auto-fix side effects: replies "are posted using your GitHub account", labeled as coming from Claude Code. If PR comments trigger automation such as Atlantis or issue_comment workflows, "consider disabling auto-fix for repositories where a PR comment can deploy infrastructure." Infinite review: "A reviewer that's asked to find problems will always find something." Ask only for gaps that affect correctness, and skip style. Mid-session CLAUDE.md edits don't apply until /clear, /compact or a restart.
Artifacts
Context windows end and files don't. Every phase should leave something durable that the next session, teammate or reviewer can load: SPEC.md, the plan, docs/flows/*.json, briefs, screenshots, test output, the PR body. The long-running-agents work at Anthropic converged on the same idea: progress files, a feature list, frequent commits (effective harnesses). And the docs' rule for evidence is: "ask Claude for evidence: the command it ran and its output, or the screenshot."
Claude Code artifacts as living status
Claude Code's artifacts add a second kind: live pages that update as the session works. Two documented patterns fit execution and feedback especially well:
# track work in progress (anyone with the link follows along)
Turn this migration plan into a checklist artifact. Check items off as you
complete them and add a note for anything you skip.
# bring a decision back into the session
Make a triage board artifact with each open issue as a draggable card across Now,
Next, Later, and Cut columns. Add a "Copy as prompt" button that gives me the
final ordering to paste back here.
For the session itself, /recap generates a one-line summary on demand, and /export [filename] writes the conversation out. Transcripts are plaintext JSONL under ~/.claude/projects/, kept for cleanupPeriodDays (default 30).
Each defect is caught first and cheapest by one feedback channel. Pick a channel for each, and the explanation names the Claude Code mechanism that closes that loop. The point isn't the score. It's noticing that no single channel catches more than a few of these.
Artifact comments: the mechanics behind "Send to Claude"
Reading. Give Claude the artifact URL and ask for the comments (requires v2.1.221+). It lists each thread and marks the comments that someone who can edit the artifact sent to it. Claude can reply to or resolve only an activated thread.
Auto-replies. After publishing, Claude Code watches the artifact for comments (requires v2.1.228+). Your permission mode decides what happens: replies go out on their own if posting doesn't need approval, otherwise you see Comments are waiting on Artifact: <name>. Plan mode pauses replies. After 60 sent comments or thread activations on one artifact within an hour, Claude stops auto-replying until that hour's comments age out.
Stopping.Ctrl+C once at an idle prompt pauses replies until your next message. Stop the watch in /tasks (under System tasks) to stop replies on one artifact. Ctrl+X Ctrl+K twice within 3 seconds stops all background subagents and all artifact replies for the session.
Trust. Viewers see replies "attributed to Claude, via you." A page someone else wrote is read like a web page, summarized with any instructions reported rather than followed (artifacts).
Exercise: wire one more loop into Claude's turn
Pick the feedback you currently provide by hand most often: "the page is broken", "the log says X", "the test output is huge". Close it inside Claude's turn with one mechanism from this topic (a filter hook, a Monitor watch, a Chrome check with a target screenshot, or a /run-skill-generator recipe). Then repeat a recent task and count how many times you had to intervene compared with before.
Show a reference approach
The most common win is the dev-server log. Start the server writing to .logs/dev.log, add a CLAUDE.md line ("dev server logs: .logs/dev.log; grep it after UI changes"), and ask for a Monitor watch during manual testing. The second is visual: run /run-skill-generator once so /verify knows how to boot the app, keep a docs/shots/*-target.png per key screen, and ask for comparisons against it. People typically find that half their old interventions were relaying information Claude could have read itself.
Key takeaways
Close loops inside Claude's turn. A check it can run beats a correction you have to type.
Shape logs for grep (one line per event, level and reason together, ids), filter them with a hook, and stream them with Monitor when timing matters.
Visual feedback needs a target. Chrome, Desktop's Browser pane and /verify let Claude look, and a mockup or baseline lets it compare.
Route human feedback through the artifact it's about (plan, diff, PR, artifact page). Batch it, rate its severity, and cap the rounds.
Leave durable artifacts at every phase. Evidence beats assertion.
Engineering
When an agent writes most of the code, the codebase becomes the prompt. Claude reads neighboring code and follows it, which is exactly what the docs tell you to ask for. So simplicity, conventions and debt stop being matters of taste. They are the inputs to every future change. This topic is about keeping those inputs clean at agent speed, and about choosing the smallest Claude Code primitive that enforces what matters.
Simplification
Agents make adding code nearly free and deleting code feel optional. Left alone, an agent-written codebase drifts toward more: more options, more layers, more defensive branches, more "flexible" abstractions. Insiders describe the human role bluntly: "Very often, we found that the role of the engineers was to tell Claude 'no'", and adversarial review "can also be myopic, so skilled engineers needed to steer Claude away from over-engineering" (Redesigning source control at Anthropic, official, practitioner opinion).
The tools
/simplify [target] is a bundled skill that reviews changed code "for cleanup opportunities and apply the fixes. Four review agents run in parallel, covering reuse of existing helpers, simplification, efficiency, and whether the change is at the right level of abstraction. The review doesn't look for correctness bugs."
/code-review finds correctness bugs. Its history matters if you've scripted it: /simplify was renamed /code-review in 2.1.147, and /simplify came back as the cleanup-only review in 2.1.154. "If you scripted /simplify for bug-finding, switch to /code-review --fix."
Your own simplify skill. A project skill with the same name replaces the bundled one, so you can encode your team's idea of "simpler". And when a project or personal skill named simplify or verify exists at session start, Claude runs it before each commit (requires v2.1.286+), as long as Claude may invoke it and includeGitInstructions isn't false (see Visual Feedback).
Deletion prompts. Ask for evidence first and deletions second: "list exported functions under src/lib with no references outside tests, with the search you ran; don't delete yet." Flag cleanup is the highest-yield deletion: "share_links_v0 is at 100%. Remove the flag, the dead branch and its tests, in one commit."
✗ What an unconstrained agent ships
ShareLinkFactory, a LinkExpiryStrategy interface with one implementation, a config option for token length "for flexibility", and retry logic around a local function call. 240 lines, three new files, every one of them a pattern the next session will copy.
✓ What the plan asked for
createShareLink(reportId, days) in src/lib/share.ts: generate a 128-bit token, insert a row, return the URL. 30 lines and one test file. The prompt that got it: "prefer the smallest change that satisfies SPEC.md; no new abstraction unless this diff uses it twice."
Failure modesChasing every finding: "If you fix every finding, you end up with extra abstraction layers and tests for cases that can't happen." Tell reviewers to report gaps that affect correctness and skip style. Cleanup without a check: a simplification that changes behavior is a bug, so run the tests after every /simplify pass. Simplifying away constraints: that odd-looking branch may be the SMS-length rule from history. Run /why before deleting anything old. Confusing the two commands: /simplify won't find the bug, and /code-review won't remove your factory.
Conventions
Conventions keep a codebase legible when many writers touch it. With agents in the mix, an unwritten convention is one that gets violated at machine speed, and a convention written in the wrong place is one that gets violated anyway. Claude Code gives you a ladder of places to put a convention, from advisory to deterministic. The skill is promoting each convention to the lowest rung that actually holds.
One convention, "validate handler input with the zod schema in the same file", shown as the artifact it becomes at each promotion: a chat line, a CLAUDE.md bullet, a paths: rule, a SKILL.md, a PostToolUse hook script, and a CI lint rule. Press $ violated again to promote it one rung, or click a row; the current form is expanded and carries the highlight, earlier forms are struck through. The scale underneath runs from advisory and flexible to deterministic and costly to set up. Climb only as far as you need. File names, the hook script and the lint rule are illustrative.
---
paths:
- "src/api/**/*.ts"
---
# API route conventions
- Validate input with the zod schema declared in the same file; never read req.query directly.
- Return errors through apiError(code, message) from src/api/errors.ts.
- Every mutating route writes an audit event via audit.record() in src/lib/audit.ts.
- Canonical example to copy: src/api/reports/[id]/export.ts
- Don't copy anything under src/api/legacy/: it predates requireSession().
# acme-dash
- Commands: `npm run dev` (web :3000, api :8080), `npm run check` (types+lint+tests)
- Dev server logs: .logs/dev.log. grep it after UI changes
- Migrations are expand-contract: never drop or rename a column in the same PR that stops using it
- Implement only what SPEC.md marks in scope; list other ideas under "Follow-ups" in the PR
- API conventions load from .claude/rules/api-routes.md when you touch src/api/
The path-scoped rule loads when Claude reads, writes or edits a matching file, so it costs nothing in sessions that never touch the API. A rule without paths: loads at launch like CLAUDE.md. Keep CLAUDE.md files under the documented target of 200 lines, and run /doctor prompt-audit (requires v2.1.283+) to check your instruction files (CLAUDE.md, rules, skills, commands, subagents, output styles) for "instructions written for older models", references to files or commands that don't exist, and files that contradict each other. Plain /doctor proposes cuts for content Claude could derive from the codebase.
Failure modesLint by prose: "Never send an LLM to do a linter's job" (HumanLayer, community, consistent with the docs). If a convention is machine-checkable, the linter is the convention. Compaction drops path rules: "If a rule must persist across compaction, drop the paths: frontmatter or move it to the project-root CLAUDE.md." Shouting: on current models "piling on emphasis mostly makes Claude over-apply the rule." Write the line plainly; if it can't bend, make it a hook. Contradictions between CLAUDE.md, rules and the code itself. When the code disagrees with the rule, Claude often copies the code. Fix one of them.
Where instructions load from, in worktrees and subagents
Load order. CLAUDE.md files from the working directory and every ancestor "are concatenated into context rather than overriding each other", root first, and files in subdirectories load on demand. ~/.claude/rules/ loads before project rules. The InstructionsLoaded hook fires with a load_reason such as path_glob_match, which is handy for checking that a rule actually loaded (memory, hooks).
Worktree subagents. A subagent in its own worktree "takes the instruction files it starts with from your main conversation, not from its worktree", and in the default .claude/worktrees/ location it doesn't load the worktree-root CLAUDE.md or .claude/rules/ as it reads there, "even if those differ on the worktree's branch." A convention you changed on a branch isn't seen by isolated subagents until it reaches the main checkout (worktrees).
Hooks merge, with one dedup rule. Hooks from every settings level merge instead of replacing each other, but "If you define the same handler in more than one settings file, it runs once. A plugin's or skill's copy of the same handler stays separate." So a formatter in both user and project settings runs once, while the same formatter shipped again in a plugin's hooks/hooks.json "runs twice" (hooks).
Technical Debt
The docs' own example of a good prompt points at an existing pattern: "follow the pattern in HotDogWidget.php and build a calendar widget". It works, and that's the problem. Claude follows whatever pattern it finds nearest, including the deprecated one. If 30% of your API handlers still use withAuthLegacy(), a meaningful share of new handlers will too, so the pattern never dilutes away, and where it clusters (one directory, one module family) each copy makes the next one nearby more likely. That's pattern copying: debt that grows at agent speed, because the agent writes more code than you do and reads the codebase every time.
Interest, in agent terms
Each instance of a bad pattern costs something every sprint: review attention ("why is this one different?"), bug surface (the legacy auth path missed the new audit hook), and future migration work. The interest rate rises with the instance count, because copying is proportional to prevalence. Two levers work against it: guidance (making the right pattern the nearest and most explicit example) and paydown (migrating instances faster than new ones appear).
Toy expected-value model with illustrative numbers. The agent is a photocopier: each sprint it copies whichever handler pattern it finds on the glass, the deprecated one with probability equal to its current share, reduced by your guidance controls, which cover part of the old original. Each of the 26 piles is one sprint's new handlers, one sheet per handler; the smudged sheets at the bottom are copies of the deprecated pattern, and the dashed tick on a pile is where the smudge would reach with no controls and no cleanup. The codebase starts with 120 handlers, 30 of them deprecated. Interest, the strip under the piles, grows stronger with the review and fix time per sprint. Turn on controls, add a cleanup budget, or schedule a one-time /batch migration, a recall that reprints the smudged sheets at sprint 10. Hover a pile for its sprint. The faster the agent writes, the more guidance matters.
What actually stops the spread
Make the right pattern the nearest example. Name the canonical file in a path-scoped rule ("Canonical example to copy: …"), and say what not to copy and why.
Mark the deprecated code where Claude reads it: @deprecated use requireSession() — see src/api/reports/[id]/export.ts at the definition, plus a rule scoped to src/api/legacy/**.
Enforce with a lint rule (no-restricted-imports for withAuthLegacy), run by the formatter hook or npm run check. Enforcement is the only control that's near 100%.
Pay it down in one sweep when the change is mechanical: /batch migrate every handler under src/api from withAuthLegacy to requireSession; one unit per directory; run npm run check in each. It decomposes the change into 5 to 30 worktree-isolated units and presents a plan before it starts.
Keep a debt register (docs/debt.md: item, instances, owner, plan) and give scheduled cleanup a slot. A bare /loop runs the built-in maintenance prompt, which includes "cleanup passes such as bug hunts or simplification when nothing else is pending."
The copy-amplification model behind the simulator
Let B_t be bad instances and N_t total instances at sprint t, with share p_t = B_t / N_t. The agent writes G new instances per sprint, and each copies the bad pattern with probability p_t · (1 − g), where guidance g = 1 − ∏(1 − g_i) combines independent controls (canonical-example rule, deprecation markers, lint rule). Cleanup removes min(c, B_t) per sprint. In expectation:
At g = 0 with no cleanup, the expected share is a martingale, like a Pólya urn: p stays exactly where it started, so the codebase "remembers" the pattern forever. Meanwhile B_t grows linearly (G·p per sprint) and cumulative interest grows quadratically. With g > 0, new code dilutes the share at a rate set by (1 − g). With cleanup, there's a threshold: if c > G·p·(1 − g), the instance count falls every sprint, and below it, it grows. Interest per sprint is i · B_t minutes, so payments rise every sprint even though the share is flat. In this global-share model that's linear growth, not compounding; true compounding appears when copying is local and the share near the bad pattern rises. That's the agent-era twist: raising G without raising g raises your debt payments. Real copying isn't proportional to global prevalence. It's dominated by proximity (the files Claude happened to read), so a bad pattern concentrated in one directory spreads fastest there. That's why path-scoped rules are the right placement for the guidance.
Exercise: a debt and deletion sweep
In one session, ask Claude (with a subagent) to find the three most-copied deprecated patterns in your repo, with instance counts, the commands it used, and the canonical replacement for each. Pick one. Add (1) a path-scoped rule naming the canonical example, (2) a @deprecated marker, (3) a lint rule. Then either migrate the instances with /batch or schedule them in docs/debt.md. A week later, count new instances.
Show a reference approach
The prompt that works: "use a subagent to find patterns that exist in both an old and a new form (auth wrappers, fetch helpers, error shapes). For each: instance counts by directory, the command you ran to count, and which form newer files use. Don't change anything." Expect the top hit to be an auth or data-access wrapper. A good sign that the guidance works is that the next feature's new files all use the canonical form without being told. If they don't, the rule probably isn't loading (check with the InstructionsLoaded hook, or ask "which rules did you load for this file?") or the canonical example isn't the nearest file.
Thinking in Primitives
"Claude Code is composable and follows the Unix philosophy." It's built from a small set of primitives: tools, CLAUDE.md, rules, skills, subagents, hooks, permission rules, MCP, plugins and workflows. Each guarantees something different. Thinking in primitives means two things. In your Claude Code setup, reach for the smallest primitive that guarantees the behavior. In your product code, build small composable pieces that both people and agents can use, rather than bespoke one-offs that only one session understood.
You need
Smallest primitive
Why that one
A fact every session needs
CLAUDE.md line
Loaded at launch, advisory, cheap
A convention for some files
Path-scoped rule
Loads only when matching files are touched
A procedure, sometimes
Skill (disable-model-invocation: true if it has side effects)
Body loads on use, and it can carry scripts
Something that must happen every time
Hook
"Claude Code applies this every time, no matter what the model decided to do"
Something that must never happen
Permission deny rule, plus the sandbox
Enforced by Claude Code in every mode
Isolated investigation or fresh-eyes review
Subagent
Own context and tools, and returns a summary
An external system
A CLI first, MCP if no CLI exists
"If that system has a CLI, that's usually the easiest way in"
The same setup across many repos
Plugin
Versioned skills, agents, hooks and MCP installed as one unit
Dozens of agents with cross-checking
Dynamic workflow
The plan lives in a script, not in a context window
Eight real requirements from the share-links project. Pick the smallest primitive that reliably delivers each one. The feedback explains the trade-off, including the tempting wrong answer.
Primitives in the product
The same idea applies to the code Claude writes. A scripts/share-link CLI with create, revoke and inspect subcommands and a good --help is usable by your tests, your support team and Claude. The docs suggest exactly this pattern for unfamiliar tools: "For a CLI it hasn't seen before, pointing it at --help is enough." A one-off migration script that only one session understood is not. Primitives also make release monitoring cheaper, because a watch that calls scripts/share-link stats --since 1h reads ten lines instead of a dashboard.
Failure modesThe mega-skill that does five things, with a description too vague for Claude to match. Keep SKILL.md under 500 lines and split by trigger. MCP for things gh already does.Hooks for advice: a hook that "reminds" is a CLAUDE.md line with latency. A plugin for one person's preferences.Primitive sprawl: every enabled skill, MCP server and plugin costs context. /doctor reports unused extensions against their context cost, and /skill-doctor (v2.1.252+) shows unused skills.
Key takeaways
The codebase is the most-read prompt. Keep it simple on purpose: say "no" to unneeded abstraction, and use /simplify for cleanup and /code-review for bugs.
Put each convention on the lowest rung that holds: CLAUDE.md → path-scoped rule → skill → hook → linter or CI. Promote it when it's violated again.
Agents copy patterns, so deprecated code spreads in proportion to its prevalence. Name canonical examples, mark the deprecated code, enforce with lint, and pay down with /batch.
Choose the smallest Claude Code primitive that guarantees the behavior, and build product code from primitives that both agents and people can use.
Delivery
Delivery is where "the agent says it's done" becomes "we stand behind it". Four things have to be true: the integrated system works, not just each lane; the PR carries evidence a reviewer can check quickly; someone is watching the release with a plan for bad news; and everything still unknown is written down with an owner. Claude Code can do most of the work in each. None of it removes the human approval at the end.
Integration Checks
Each lane passed its own tests. Integration checks are the ones no single lane could run: the full build and type check on the merged code, all tests, the synthetic flows end to end, the migration on production-sized data, the running app via /verify, /security-review on the branch (it "reviews the diff between your branch and origin's default branch"), and /code-review on the merged diff.
Four ways to gate "done", from the docs
The best-practices guide lays out a ladder, from "Claude deciding for itself all the way to Claude Code enforcing it": run the check in one prompt; set it as a /goal condition, which "a separate model checks against the conversation after every turn"; make it a deterministic gate with a Stop hook that "sends Claude back to work if the script exits with code 2" (as the tabs below show, how hard it blocks depends on how you write it); or get a second opinion from someone "who didn't write the code": /code-review, a verification subagent or a dynamic workflow. Each step trades setup for attention.
/goal `npm run check` exits 0 and every flow in docs/flows passes with
`npx playwright test tests/flows`; don't modify files under tests/flows;
or stop after 20 turns
#!/bin/bash
# One-time nudge: if the integration check is red when Claude tries to stop,
# send it back once. This is NOT a gate: CI and branch protection are.
INPUT=$(cat)
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
exit 0 # second stop attempt: allowed even if the check is still red
fi
# cwd is where Claude is working (the worktree, or wherever it last cd'd);
# $CLAUDE_PROJECT_DIR stays at the main checkout. Climb to that checkout's root.
cd "$(git -C "$(echo "$INPUT" | jq -r '.cwd')" rev-parse --show-toplevel)" || exit 0
if ! OUT=$(npm run -s check 2>&1); then
echo "Integration check failed. Fix the cause; don't skip or weaken tests:" >&2
echo "$OUT" | grep -E "(FAIL|ERROR|error TS)" | head -40 >&2
exit 2 # exit 2 on Stop: Claude keeps working, stderr is the message
fi
exit 0
#!/bin/bash
# Keep sending Claude back while the check is red, up to MAX forced retries
# per session (state keyed on session_id), then let it stop. CI still gates the merge.
MAX=3
INPUT=$(cat)
SID=$(echo "$INPUT" | jq -r '.session_id')
STATE="${TMPDIR:-/tmp}/require-green-$SID"
cd "$(git -C "$(echo "$INPUT" | jq -r '.cwd')" rev-parse --show-toplevel)" || exit 0
if OUT=$(npm run -s check 2>&1); then
rm -f "$STATE"; exit 0
fi
N=$(cat "$STATE" 2>/dev/null || echo 0)
if [ "$N" -ge "$MAX" ]; then
rm -f "$STATE"; exit 0 # give up and stop; the red check stays visible in CI
fi
echo $((N + 1)) > "$STATE"
echo "Integration check failed (retry $((N + 1))/$MAX). Fix the cause; don't weaken tests:" >&2
echo "$OUT" | grep -E "(FAIL|ERROR|error TS)" | head -40 >&2
exit 2
Two details in that script are easy to get wrong. First, ${CLAUDE_PROJECT_DIR} "still points at the project root where the session started" even after Claude enters a worktree, while cwd in the hook input "is the worktree root after Claude enters a worktree, and the new directory after Claude runs cd". So the script resolves the repository root from cwd. A gate that cds to $CLAUDE_PROJECT_DIR tests the wrong checkout. Second, Claude Code "overrides a Stop hook after it blocks eight times in a row with no tool call from Claude in between", and the documented guard is to exit early when stop_hook_active is true. Be clear about what that guard means: the first script is a one-time nudge. It sends Claude back once, and the next stop attempt is allowed even if the check is still red. Dropping the guard doesn't make it a gate either, because the 8-block cap resets every time Claude calls a tool, so it doesn't bound a loop where Claude re-runs the tests between blocks. A hard gate needs its own state, like the counter keyed on session_id in the second tab, with an explicit retry limit. Even then it's a convenience, not enforcement: a Stop hook that crashes or can't start fails open, and onFailure has no effect on Stop. CI and branch protection stay the real gate. For multi-round convergence inside the session, /goal … or stop after 20 turns gives you a bounded loop with a separate evaluator.
Failure modesPassing by weakening: a check Claude can edit is a check Claude can satisfy by editing it. State "don't modify tests under…" in the goal, or protect the paths with an ask rule. Evaluator blindness: the /goal evaluator "doesn't run commands or read files independently", so write conditions that Claude's own output can demonstrate. Gates that fail open: a timed-out hook doesn't block unless you set "onFailure": "block" (requires v2.1.295+), and that setting has no effect on Stop hooks. Integration only at the end: run the check after every merge point, not once. See Delivery 4 for gates as a system.
/goal, Stop hooks and auto mode: how they compose
Different jobs. "Auto mode removes per-tool prompts, and /goal removes per-turn prompts." Auto mode alone "approves tool calls within a single turn but doesn't start a new one". Claude still stops when it judges the work done. /goal adds "a separate evaluator… so completion is decided by a fresh model rather than the one doing the work" (goal).
Mechanism. "/goal is a wrapper around a session-scoped prompt-based Stop hook": after each turn the condition and conversation go to your configured small fast model. That's why it's unavailable when disableAllHooks is true or managed settings set allowManagedHooksOnly, and why it follows the same workspace trust rule as settings hooks.
Scope. One goal per session, up to 4,000 characters, active only for that session. A Stop hook lives in settings and applies to every session in its scope. It can run a script (deterministic) or a prompt or agent hook (model-evaluated, with an {"ok": …, "reason": …} reply).
Permissions don't change. "A goal doesn't change your permission mode." In Manual mode, goal turns still prompt for tools your settings don't allow, so unattended goal runs pair with auto mode, plus deny rules for what must never happen.
Cost. Every forced continuation is another turn. Bound the goal ("or stop after 20 turns") and watch /usage. For headless runs, --max-turns and --max-budget-usd cap the run. The budget is checked "against its client-side cost estimate, which can differ from your bill."
Pull Requests
"create a pr for my changes" is a complete instruction in Claude Code (common workflows). Claude follows built-in commit and PR instructions (they live in the Bash tool's description, and "includeGitInstructions": false removes them, for example if you use your own git workflow skills), uses gh pr create, and links the session to the PR so claude --from-pr <n> finds it later. The PR is the delivery artifact that reviewers, CI and future archaeology all read, so make it carry evidence, not claims.
Scrub through one pull request's life. The card changes as Claude works: branch, commits, gh pr create, checks, review, the fix loop, the human approval, and the merge with its watch. The highlighted approval slot is the one step Claude can't fill. The label in the card's corner is agent view's pull request label, written here as its status. In agent view the number itself is coloured: yellow (waiting on checks or review, or checks failed), green (checks passed, no review blocking), purple (merged) or grey (draft or closed). "Review and merge the pull request when its number turns green." The PR number and the check results are illustrative.
## What and why
<!-- one paragraph; link SPEC.md and the plan -->
## Testing (evidence, not claims)
<!-- commands run and their output; screenshots for UI; flows that passed -->
## Risk
<!-- what could break, who is affected, which controls exist -->
## How to revert
<!-- the exact command or flag flip; whether data needs fixing after revert -->
## Unresolved risks
| Risk | Why accepted | Owner | Trigger to act | Revisit |
|------|--------------|-------|----------------|---------|
The template's Testing, Risk and How to revert sections follow the checklist the Claude Code team published for its own reviews (official blog). attribution.commit and attribution.pr are strings, and sessionUrl drops the claude.ai session link from cloud and Remote Control commits. "attribution": false hides everything but requires v2.1.281+. Earlier versions reject it and skip the whole settings file. The workflow is the docs' @claude example. /install-github-app sets it up on github.com repos.
Review and merge
Local review into the PR: /code-review --comment posts findings as inline GitHub comments, or as a single note on a GitLab merge request (v2.1.257+). /code-review ultra runs the deeper multi-agent cloud review.
Managed Code Review (Team and Enterprise) reviews every PR on GitHub with inline comments and a check run, and is tuned with REVIEW.md, which local /code-review doesn't read. "A review never approves or blocks the pull request, so the decision to merge stays with your team" (Code Review).
Fix loop: /autofix-pr from the PR's branch, or Desktop's Auto-fix, responds to CI failures and review comments. Desktop's Merge when ready turns on GitHub auto-merge, requesting a squash merge in local sessions unless the base branch uses a merge queue.
Human approval stays human. The Claude Code team's policy: "An agent's approval never counts as a person's", and "the person directing the agent counts as one of the required reviewers." Encode it in branch protection and CODEOWNERS, not in hope.
Measure outcomes, not outputWith a few parallel sessions, PR and commit counts rise almost for free, so they stop telling you whether the work mattered. More PRs isn't the goal. Track what each PR was for: the outcome named in its spec, the user-visible change, and whether the post-release check met it. Treat PR counts, commits and lines accepted as adoption and capacity signals only. If they climb while delivered outcomes stay flat, that's a warning sign, not a win. Delivery 1: outcome over output explains why Claude Code's own analytics count output, and Delivery 5: observation checks intended outcomes against production.
Failure modesClaims without evidence ("all tests pass") that nobody can check. Ask for pasted output. Giant PRs from merged lanes: reviewers "examine the intent of the change as opposed to reading every line of code" (insider practice), which only works if each PR has one intent. Auto-merge on agent review alone.Hidden attribution policy: a CLAUDE.md rule about attribution takes precedence over the settings lines, "unless the line is set in managed settings."
Release Monitoring
Before you ship, write the watch down: which signal (5xx rate on /s/*, expiry-job failures, share-email bounces), what threshold over what window, what action (flag off, revert command), and who decides. Claude can run the watch. Whether it can also take the action is a permission question, and for irreversible actions the answer should be "propose, don't do".
Pick the mechanism by how long the watch is and whether your machine stays on
Mechanism
Runs
Fits
/loop5m check …
In your open session, on a fixed interval (1-minute minimum, 7-day expiry)
The first hour after a deploy, while you're at the keyboard
/loop check … (self-paced)
Claude picks 1 minute to 1 hour per iteration
Babysitting a PR or rollout that's sometimes busy and sometimes quiet
Monitor tool
Streams output lines into the session (5 to 30-minute deadline)
Tailing logs during a canary window
Channels (research preview)
An MCP server pushes events into the open session
CI or monitoring alerts that should interrupt you
Cloud scheduled task (/schedule)
In the cloud, hourly at most often, with no machine needed
Daily or hourly checks for the week after release
Desktop scheduled task
On your machine, with no open session needed
Local checks that need local files or tools
# the first hour after the share-links deploy
/loop 5m run `scripts/share-link stats --since 10m` and `gh run list -L 3`.
report 5xx count on /s/*, expiry-job status and the latest deploy run in one line.
if 5xx > 20 in a window, say so loudly and print the revert command from the PR;
don't run it.
# .claude/loop.md (default for a bare /loop in this repo)
Check the `release/next` PR. If CI is red, pull the failing job log, diagnose, and
push a minimal fix. If new review comments have arrived, address each one and
resolve the thread. If everything is green and quiet, say so in one line.
The loop.md example is the docs' own. A bare /loop uses it instead of the built-in maintenance prompt, and edits take effect on the next iteration.
Toy model with illustrative token costs per check. Each row is 24 hours of one mechanism: polling checks as ticks, streamed events as short marks, and Monitor's watches as spans of up to 30 minutes that Claude starts again at each deadline. The highlighted line is a problem dropped at a random time, and the bracket under each lane is its wait, from the problem to that mechanism's first look. Set the /loop interval and the event rate, drop a new problem, and say whether your laptop closes overnight: mechanisms that need an open session go dark for those hours, which is the most common real-world gap. Tokens per hour sit beside each row.
Failure modesPolling burn: a 1-minute /loop for a day is 1,440 turns, so tighten the interval during the canary and relax it after. Silence mistaken for health: "Don't mistake a failed read for a quiet day." A watch that can't reach the metrics API must say so. "The last 24 hours": give scheduled watchers "a bookmark per source" instead (official blog). Over-privileged watchers: "Use read-only tokens wherever the agent only reads", and cap spend at "three to five times the cost of a normal run." Autonomous rollback: a revert is a deploy. Keep it behind human approval unless you've built and tested that automation deliberately (Autonomy 4: boundaries).
How long until a canary tells you something?
Detection delay has two parts: mechanism latency (half the polling interval on average, near zero for streamed events) and statistical latency (how much traffic you need before a real regression is distinguishable from noise). The second usually dominates. With a baseline error rate p₀ = 0.5% and a regression to p₁ = 1%, a one-sided test at α = 0.05 with 80% power needs roughly n ≈ (z_α√(p₀q₀) + z_β√(p₁q₁))² / (p₁ − p₀)² ≈ 1,600 requests on the canary. At 200 share views a minute on a 10% canary, that's 20 canary requests a minute, or about 80 minutes, however fast your /loop runs. Tighter polling buys little until traffic does. Delivery 5 picks up what to do with the signals.
Unresolved Risks
Every release ships with known unknowns. The failure isn't having them. It's not writing them down, so the next person (or the next session) rediscovers them in production. An unresolved risk is anything you chose to ship without fully resolving: a premortem item left at L×I ≥ 9 with only advisory controls, a check you skipped, a review finding you accepted, a flow whose expected outcome was decided provisionally, or a follow-up that matters for safety.
Make each one actionable
Each entry needs five fields: the risk, why it was accepted, an owner, a trigger (the signal that means act now), and a revisit date. It goes in the PR body, so reviewers approve it knowingly, and in an issue (gh issue create), so it outlives the PR. The plan's Risks table gets updated with the outcome. Claude is good at assembling the list. Ask it to reconcile the plan's risks, the review findings it skipped and any UNSPECIFIED flows. But it can't decide which risks are acceptable. That's the accountable human's job.
before we open the PR: reconcile docs/plans/share-links.md "Risks", the review
findings you marked as skipped, and any flow in docs/flows with spec_ref
"UNSPECIFIED". produce an "Unresolved risks" table (risk, why accepted, owner,
trigger, revisit) for the PR body. leave owner as TODO where you can't infer it.
then draft one `gh issue create` command per row, but don't run them.
Tick what's done, add up to three unresolved risks (risk, owner, trigger, revisit date), and the builder computes readiness, blocking items first: the lamp reads go only when none is open. It renders the PR body's evidence and risk sections as Markdown you could paste. Blocking items are the ones this session argued are non-negotiable. Everything else is a judgment call you make visibly.
Failure modesRisks without owners are wishes. "Low risk" with no trigger: say what signal would change your mind. Burying risks in prose where reviewers skim past them. Use a table. Letting the agent accept risks: a model can rank and draft, but acceptance belongs to the person whose name is on the approval. Never revisiting: put a date on it, and let Delivery 5's decisions close the loop.
Team practices that pair with these mechanics
The mechanics on this page pay off inside a few team habits. Each one below starts from the current best-practices guide and points to where this course teaches the mechanism.
Write what "correct" means first. The guide's central rule is "Give Claude something it can run that comes back pass or fail." On a team, that's acceptance criteria in the spec (Delivery 2: specifications), turned into a /goal condition that a separate evaluator checks after every turn (Integration Checks).
Review in a fresh context. "A fresh reviewer does help, because it hasn't seen your reasoning, which is a different thing from delegating" (what you can stop doing). In Claude Code that's a review subagent with its own instructions and its own model: field (Delivery 4: review), or a second session: "A second session is also the easiest independent reviewer you can get." It doesn't inherit the writer's reasoning, so it can disagree with it. The same split works for tests: one session writes them, another writes code to pass them.
Coordinate parallel lanes with the built-ins. Agent view shows every session on your machine and its state, each worktree session keeps its edits apart, and cross-session messaging (v2.1.224+, or v2.1.234+ on native Windows) tells the other lanes what landed; in an agent team, teammates claim tasks from a shared task list (Agents 4: orchestration). Nothing claims files for you, which is why this page plans file footprints before dispatching.
Cut ceremony, not the required reviewer. An agent's approval never counts as a person's (Pull Requests), and the guide's checklist for unattended runs ends the same way for every change: "a person approving the merge, the deploy, or anything else you can't take back" (let Claude run without you).
Show half-baked work early. A draft PR or a live artifact is the cheapest way to show work while it's still easy to change.
Exercise: a release handoff for your last change
For the last change you shipped with Claude Code, write the handoff you should have attached: the integration evidence (commands and outputs), the watch (signal, threshold, window, action, owner, and the mechanism you'd use from the table above), and an unresolved risks table with at least two rows. Then have Claude draft the same from the PR, plan and transcript (claude --from-pr <n> to find the session), and compare the two.
Show what usually differs
Claude's draft is usually more complete on what was written down: skipped findings, UNSPECIFIED flows, risks noted in the plan. Yours is usually better on what was known but unwritten: "the expiry job has never run on the full table", "support doesn't know revoked links return 410". The gap tells you what to capture during the work next time, typically in the plan's Risks table as you go. If Claude's draft invents risks the record doesn't support, ask for a citation per row.
Key takeaways
Run integration checks after every merge point, and gate "done" with a prompt, /goal, a Stop hook or a second-opinion reviewer, depending on how unattended the run is.
A Stop hook with the documented stop_hook_active guard is a one-time nudge, not a gate. A harder gate needs its own retry counter, and in worktrees it must resolve the repo root from the hook input's cwd. CI and branch protection remain the real gate.
PRs carry evidence, risk and a revert path. Claude opens them with gh pr create, links the session, and can review and auto-fix them. Humans approve them.
Choose the watch mechanism by horizon and uptime: /loop and Monitor while the session is open, cloud scheduled tasks when it isn't.
Ship unresolved risks as a table with owner, trigger and revisit date. Claude assembles the list, and you accept the risks.
Session wrap-up
You followed one feature through the whole flow. Exploration ran in the right context (main session, /btw, Explore or a scout) and demanded citations. It read history through /why, drew cited diagrams and artifacts, and probed behavior with synthetic flows run in Chrome. Planning drew a cut line on your attention budget, turned a premortem into enforced controls, and picked a strategy by uncertainty, breadth, coupling, repetition and reversibility. Execution routed each task to direct work, a handoff with a real brief, or parallel worktrees with planned footprints and merge points. Feedback closed loops inside Claude's turn with filtered logs, visual targets, routed human comments and durable artifacts. Engineering kept the codebase, which is now the most-read prompt, simple, conventional and free of copied debt, using the smallest primitive that holds. Delivery gated the integrated system, shipped a PR with evidence, watched the release with a mechanism that matched its horizon, and wrote down what was still unknown.
Path tiers, content signals, import-graph blast radius and plan drift, turned into a register whose mitigations are ask/deny rules, hooks, tests, review commands and humans. Run it on the plan before you approve it, and again on the final diff (--diff, --repo, --strict).
Write and read footprints, then an overlap matrix, waves with delay reasons, what-ifs and merge points with stale-read warnings, plus the Claude Code mechanism for each task. Feed it the footprint table Claude proposes in plan mode (--tasks my_tasks.json).