Claude Code is very good at doing what it was asked. Most failed agent work fails earlier, when a fuzzy request ("make CSV export work for big customers") becomes a prompt with no definition of done, no record of what the system does today, and no way for Claude to tell when it has finished. The docs put it bluntly: "Claude stops when the work looks done. If it has nothing to run that tells it whether the work actually is done, 'looks done' is all it has to go on. In practice that makes you the test suite, and every mistake sits there until you happen to notice it." This session is about the translation step. You take intent and turn it into artifacts Claude Code can act on and check: a /goal condition, a context pack in CLAUDE.md and rules, an AskUserQuestion interview, a SPEC.md, a reviewed plan from plan mode, and evidence requirements that tests and hooks enforce.

What you'll be able to do afterwards:

How it connects. Delivery-1 covered judgment: assumptions, tradeoffs and taste. This session turns that judgment into Claude Code inputs. Delivery-3 runs the development flow that consumes them, and delivery-4 verifies what ships against the acceptance criteria you write here. Where Core already taught a mechanism, this page links back instead of re-teaching it: knowledge files in core-3, the explore-plan-implement loop and /goal basics in core-4, and delegation briefs in agents-4.

Facts on this page are as of 2026-10-24 (checked against Claude Code v2.1.310). Version-gated features say "requires v2.1.x+" where they appear. Simulations are toy models with illustrative numbers.

Running example: Tally's CSV export

Tally is an invoicing web app (TypeScript, Node, Postgres). A product manager files: "CSV export is broken for big customers. Make it work." What's actually going on: GET /api/exports/invoices.csv streams rows synchronously from src/exports/invoiceCsv.ts. The load balancer cuts every connection at 30 seconds, so a workspace with tens of thousands of invoices gets a silently truncated file: HTTP 200 was already sent, and the browser saves whatever arrived. Finance admins notice at month-end close, when the totals don't match. Every widget on this page uses this change, and the wrap-up assembles the complete brief.

Each topic in this session produces one Claude Code artifact. Read it left to right: the request starts as a rough block that holds every possible implementation, and each artifact is a chisel pass that cuts away a class of wrong builds before Claude writes code, until what's left is what you meant. The label under each pass is the artifact, and where it lives decides when Claude sees it. Hover or focus a pass to see the failures it removes.

Intent

Intent is the part of a request that lives only in someone's head: when the work counts as finished, who it's for, what the system does today, and what should be true afterwards. Claude Code can read your code but not that head. Each of the four items below turns one piece of it into text Claude can act on, and the first one, the definition of done, becomes the stop condition for the whole session.

Definition of Done

A definition of done (DoD) is a list of statements that are all true when the work is finished, each phrased so that something observable can confirm it. For a human team it's a shared agreement. In Claude Code it's also mechanical: it's the only thing that can end the agent loop for the right reason. The loop runs "gather context, take action, and verify results", and it stops when Claude judges the task complete. If the DoD says "export works for big customers", Claude's judgment is all there is. If it says "npm test -- test/exports exits 0, including the 120,000-row fixture", Claude can run the check, read the result and keep going until it passes.

Where a definition of done lives in Claude Code

The same DoD can be enforced at three strengths. The best-practices guide leaves "How strict you make the check" up to you, from "Claude deciding for itself all the way to Claude Code enforcing it":

WhereWhat enforces itScopeUse when
In the prompt ("run the auth tests after, and keep going until they pass")Claude's own judgment within the turnOne requestSmall, watched work
/goal <condition>A separate evaluator model checks the condition after every turn and starts another turn if it isn't metThe current sessionMulti-turn work with a verifiable end state, attended or not
A Stop hook in settingsYour script (or a prompt hook) decides whether the turn may endEvery session in that settings file's scopeA bar that must hold on every task in the repo, such as "tests pass before stopping"

/goal (added in v2.1.139) is the natural home for a task-specific DoD. You type the condition, and setting it starts a turn immediately, with the condition as the directive. After each turn a small fast model reads the condition and the conversation and returns one of three verdicts: not yet met (Claude keeps working, using the evaluator's reason as guidance), met (the goal clears), or impossible (the goal clears as failed). A goal doesn't change the permission mode. In Manual mode Claude still asks before tool calls your settings don't allow, so unattended goal runs belong in auto mode.

Writing a condition the evaluator can judge

The single most important fact about the evaluator: it doesn't run commands or read files. It judges only what Claude has surfaced in the conversation. The goal docs list three properties of a condition that holds up across many turns:

  • One measurable end state: a test result, a build exit code, a file count, an empty queue.
  • A stated check: how Claude should prove it, such as "npm test exits 0" or "git status is clean".
  • Constraints that matter: what must not change on the way, such as "no other test file is modified".

Add a bound, such as "or stop after 25 turns". Claude reports progress against the clause and the evaluator judges it from the conversation. The condition can be up to 4,000 characters, which is plenty for a real DoD. Here is Tally's:

/goal npm test -- test/exports exits 0 and the output shows the 120k-row fixture
test passing; npm run lint and npm run typecheck both exit 0; git diff --name-only
lists only files under src/exports/, src/jobs/, src/api/exports.ts, src/notifications/
and test/exports/; no existing test is deleted or skipped; the CSV header golden test
passes unchanged. Print each command's exit code. Or stop after 25 turns and report
what is still failing.

Notice what isn't in it. "The code is clean" goes to the review step (see quality bars), because no transcript line can prove it. "Finance admins stop filing tickets" is a real outcome, but it's only observable after release, so it goes into the brief as a post-release signal for delivery-5.

Tick the DoD lines you want to keep, or add your own (custom lines are classified by a simple keyword heuristic). Each line is tagged by what the evaluator could see in the transcript. The widget assembles the checkable lines into a /goal condition, with a gauge against the 4,000-character limit, and routes the rest to where they belong.
Pitfall: a condition Claude can satisfy by cheating"All tests pass" is met by deleting the failing test, or by marking it as skipped. Claude isn't malicious, but an agent rewarded on one signal will sometimes find the cheapest route to it. Constraints close the loopholes: "no existing test is deleted or skipped", "the golden file is unchanged", and a git diff --name-only scope check. In boundaries you'll also turn the important ones into deny rules.
How the /goal evaluator judges a condition, and what that means for writing one

Mechanism. /goal is a wrapper around a session-scoped prompt-based Stop hook. When Claude finishes a turn, Claude Code sends the condition and the conversation so far to your configured small fast model. To evaluate on a different model, set ANTHROPIC_DEFAULT_HAIKU_MODEL. That variable also changes every other use of the small fast model, including the haiku alias and background summarization. Evaluation tokens are "typically negligible compared to main-turn spend".

Stalls. If Claude keeps answering the evaluator without making progress (no tool use for several turns in a row), Claude Code stops the loop, prints a warning and hands control back with the goal still set. This is the same mechanism as the Stop hook's 8-consecutive-continuation cap, whose count resets every time Claude calls a tool.

Background work defers evaluation. If a subagent or background shell is still running when a turn ends, evaluation is skipped for that turn and happens at the end of the next turn with nothing running. A condition that depends on a background verifier is judged only once the verifier's result is in the transcript.

Running goals, not writing them. Errors that clear or pause a goal, retries, idle check-ins (CLAUDE_CODE_GOAL_CHECKIN_MINUTES), resume behavior and /goal clear are operational details covered in core-4, Feedback Loops and autonomy-1, Control. Two facts matter here: one goal per session (a new /goal replaces it, and /clear removes it), and in -p, claude -p "/goal …" runs the loop to completion in one invocation. Add --output-format stream-json --verbose, or a long goal looks stuck.

Availability. Because the evaluator is part of the hooks system, /goal follows the workspace-trust rule for settings hooks. It's unavailable when disableAllHooks resolves to true or managed settings set allowManagedHooksOnly, and the command says why. Source: code.claude.com/docs/en/goal.

Design consequence. Since the evaluator reads only the transcript, a step like npm test > /dev/null; echo done destroys the evidence it needs. Put "print each command's exit code" in the condition, or a summary line such as Tests: 41 passed will be the only proof and the evaluator has to trust it.

User Impact

User impact answers four questions: who is affected, what they experience today, what they'll experience afterwards, and how much it matters (how often, how badly, how many people). None of it is in the code. Claude can infer from invoiceCsv.ts that large exports are slow. It can't infer that the people hurt are finance admins closing the books, that a truncated file is far worse than a slow one (they reconcile against it), or that month-end is when it happens.

Why it changes the work. Impact decides the tradeoffs Claude would otherwise make silently. Should a 40,000-row export block for 25 seconds or go async? Is an email link acceptable, or does policy forbid it? Should the async path show progress? For a finance admin, a correct file matters more than a fast one, so "never deliver a partial file" outranks "keep it under 5 seconds". If the brief doesn't say this, Claude picks a reasonable engineering answer, and it may be the wrong product answer.

How to write it. Keep it to a few lines in the brief, not in CLAUDE.md (it's specific to this task):

docs/specs/export-async.md (excerpt: the impact section)

## User impact
- Who: finance admins in workspaces with more than ~10k invoices in the export range
  (support estimate: ~40 workspaces; see tickets labeled `export-timeout`).
- Today: exports over ~30 s are cut off by the load balancer and the browser saves a
  truncated CSV with no error. Admins find out when totals don't reconcile.
- After: every export is complete or clearly fails; large ones arrive as a download link.
- Priority: correctness over speed. A slower complete file beats a fast partial one.

Getting the evidence with Claude. Let Claude gather impact data with the tools it has, and require sources. With the gh CLI: "Use gh issue list --label export-timeout --state all --json title,createdAt,body to summarize who reports this and when. Cite issue numbers. Mark anything you couldn't confirm, and say where you looked." (That last sentence is a recommended habit from Anthropic's Opus 5.5 prompting guide.) An analytics or support-tool MCP server works the same way.

Pitfall: invented impactAsk "how many users are affected?" without data and you'll get a confident number. Impact figures in a brief must come with a source (a ticket query, a dashboard, a person), or be marked as an estimate. A wrong impact number skews every tradeoff downstream.

Existing Behavior

Existing behavior is what the system observably does today, including the parts nobody intended. It matters for two reasons. First, the change is defined relative to it: you can't say what should be different without saying what is. Second, users depend on behavior, not on intent. Tally's customers have spreadsheets that read CSV columns by position, so the column order is part of the contract even though no spec ever said so. This is Hyrum's Law: with enough users, every observable behavior will be depended on by somebody.

How to get it in Claude Code. Make discovery a separate, read-only step before any change:

  1. Explore in plan mode. Run /plan trace what happens when a user clicks Export on the invoices page, from the route handler to the database and back. Note timeouts, buffering and error handling. In plan mode Claude reads and explores but doesn't edit source.
  2. Pin it with characterization tests. These assert what the code does now, right or wrong, so the change can't alter it by accident. "Write characterization tests in test/exports/characterization.spec.ts for the current CSV header row and column order, and a test that reproduces the truncation: an export that exceeds a simulated 30 s limit must not return a 200 with a partial body. That last test should fail today." A failing reproduction test is the best-practices pattern for bugs: "write a failing test that reproduces it, then fix it".
  3. Ask for the history. "Look through src/exports/'s git history and summarize why streaming was chosen" often uncovers a prior decision (see prior decisions).
Step down the timeline: the playhead moves through the export. Illustrative timings. The point is the gap between what the user sees and what the logs show: at 30 s the load balancer cuts the browser's connection while the handler keeps streaming, and nothing reports an error. A characterization test has to assert the failure the user experiences, not the one the code reports.
Pitfall: behavior inferred from namesGiven exportInvoicesCsv(), Claude will assume it exports invoices to CSV and move on. The truncation lives in the interaction between streaming, the load balancer timeout and the browser, so no single file shows it. Require a reproduction (a test, a curl transcript, a log excerpt) before Claude describes current behavior as fact.
Characterization tests: keeping the ones that pin bugs from becoming permanent

Characterization tests come from Michael Feathers' Working Effectively with Legacy Code (2004): write tests that capture what the code actually does, then change it with a safety net. With an agent, they do a second job. They turn "don't change unrelated behavior" from an instruction Claude might forget into a check that fails.

The trap is that some of them pin the bug. Tally's truncation reproduction must flip from "fails today" to "passes after the change", while the column-order test must stay green. Name the two groups differently (for example describe("current behavior: keep") and describe("current behavior: bug, must change")) and say in the brief which group Claude may update. Otherwise "make the tests pass" gives Claude licence to edit the test that encodes the contract.

For behavior you can't pin with unit tests (an HTTP timeout, a browser download), record a transcript instead: ask Claude to run the app locally and capture curl -sS -o /tmp/out.csv -w '%{http_code} %{size_download}\n' … output with the fixture. The bundled /verify skill builds and runs the app and observes the result, which is useful for confirming the "after" state too. Hyrum's Law reference: hyrumslaw.com.

Desired Outcome

The desired outcome is the end state in terms a user would recognize, stated as a difference from existing behavior. It's not the implementation. "Add a background job for exports" is an output: it can ship and still leave files truncated. "Every export is either complete or fails visibly, and exports above 10,000 rows arrive as a download link within five minutes" is an outcome: you can check it, and many implementations could satisfy it.

Why the distinction matters with an agent. If you specify the output, Claude builds the output. It won't question whether a job queue solves the problem, because you've already decided it does. If you specify the outcome, Claude can find a simpler route (perhaps streaming with a keep-alive avoids the timeout for 95% of cases), and you review that choice in the plan. When the implementation is a decision you've already made for good reasons, say so explicitly as a constraint or prior decision, and say why.

A before/after table is the most compact way to state an outcome, and it doubles as a test plan:

SituationTodayAfter
Export of ≤ 10,000 rowsDownloads directlyUnchanged: downloads directly, same columns and order
Export of > 10,000 rowsTruncated after 30 s, HTTP 200, no errorReturns 202; a job builds the file; an in-app notification links to a download valid for 24 h
Export job fails(not applicable)Notification says it failed, with a retry button; no partial file is ever offered
Empty date rangeHeader-only CSVUnchanged
User without the finance-admin role403Unchanged: 403, for both paths

Add non-goals right after the table: "Not in this change: XLSX export, scheduled exports, changing the columns." Non-goals are the cheapest scope control you have. Current models are proactive (a community post about Fable is titled "Claude Fable is relentlessly proactive"), and an unstated non-goal is an invitation.

✗ Output-shaped request

Add a background job queue for CSV exports so big customers can export. Use best practices.

No existing behavior, no threshold, no failure behavior, no statement of done. "Best practices" invites Claude to add a new queue library even though Tally already has one.

✓ Outcome-shaped request

Large invoice exports are silently truncated at the 30 s load-balancer timeout (see test/exports/characterization.spec.ts). Outcome: no partial file is ever delivered; ≤10k rows still download directly; larger exports arrive as a 24 h link via in-app notification. Non-goals: XLSX, column changes. Done = the /goal condition in SPEC.md.

Exercise: decompress one request from your backlog

Pick a real ticket that's one or two sentences long. In your repo, start claude and run /plan with: "Read this ticket: [paste]. Trace the existing behavior in the code. Then draft, without editing anything: (1) a user-impact block with sources, (2) a before/after table, (3) non-goals, (4) a /goal condition with a measurable end state, a stated check and constraints. Mark anything you couldn't confirm." Then edit what it produces. Count the decisions you had to make that weren't in the ticket.

Show a reference solution

A good result has at least three "today" rows that cite a file or test, a "Priority" line that resolves a tradeoff (for example correctness over latency), and a /goal condition in which every clause names a command or a file-level fact. Expect to make three to six decisions yourself: thresholds, failure behavior, who is allowed to do what, and what's out of scope. Those decisions are the real content of the ticket. If Claude's draft has a clause like "the feature works well", rewrite it as a command and an expected result, or move it to the review checklist. If a "today" row has no citation, ask Claude to reproduce it before you accept it.

Key takeaways

  • Claude stops when the work looks done. A definition of done made of checkable statements is what lets the loop stop for the right reason.
  • Put a task's DoD in a /goal condition: one measurable end state, a stated check, the constraints that matter, and a turn bound. The evaluator reads only the transcript, so Claude must print the evidence.
  • User impact sets the tradeoffs Claude would otherwise make silently. Source every impact number.
  • Discover existing behavior before changing it: plan-mode tracing, characterization tests, a failing reproduction, and git history.
  • State the outcome (the observable end state, as a before/after table) and the non-goals. Specify the implementation only when it's a deliberate decision, and say why.

Context

Intent says what to do. Context says what Claude must know to do it the way your product and codebase need: the domain, where things live, what's forbidden, how things are done here, and what was already decided. In Claude Code each kind of knowledge has a natural home, and the home decides when Claude sees it, whether it survives compaction, and whether it's advice or enforcement. Getting the placement right matters as much as writing it.

Three kinds of fixture. Always loaded is the hard-wired lamps, on from the entrance: it costs context in every request but is there from the first turn. On demand is the motion lamps, dark until a trigger fires (Claude walks into a room where it touches a matching file, pulls the cord to invoke a skill, or reads a doc). Enforced outside the context is the locks, sprinklers and cage, drawn in black line work: it costs no tokens and doesn't depend on Claude remembering, because Claude Code or the OS applies it. The pairs sit in neighbouring rooms: root and nested CLAUDE.md, unscoped and path-scoped rules, the memory index and its topic files, skill descriptions (the door sign) and skill bodies. Walk Claude down the corridor, then compact: the hard-wired lamps relight at once, the motion lamps wait until Claude goes back in. Hovering an item in the context pack builder below lights the fixture it would hang on. For when each artifact loads over one session, see delivery-5 · Feedback Loops. Sources: memory, skills, permissions.

Product Knowledge

Product knowledge is what a new engineer learns in their first month and never finds in the code: what a "workspace" is and how it's billed, which roles exist and what they may do, which customers matter for which flows, the vocabulary support uses. Without it, Claude writes code that compiles and misunderstands the product, for example by letting any member run a finance export because nothing in the route says otherwise.

Where it goes. The best-practices guide says CLAUDE.md "works best when it only holds what Claude couldn't work out from the code itself", and gives a test for each line: "Could it find this by reading the code?" and "Would it actually go and look?" "If both are yes, leave it out." The memory docs set a target of under 200 lines per file. That leaves room for only a handful of product facts. The rest goes somewhere that loads on demand:

  • The few facts every task needs go in CLAUDE.md: the core nouns and the one or two business rules that are easy to violate.
  • Reference material (personas, plan tiers, the domain glossary) goes in docs/product/*.md, which CLAUDE.md points to by path. Claude reads it when a task needs it. Don't @-import it: the memory docs warn that imports "don't reduce its context cost, because imported files load together with the CLAUDE.md that imports them". For the project CLAUDE.md, that's at launch.
  • Knowledge that matters only sometimes but must be applied consistently becomes a skill. Only its description is in context until Claude invokes it, and then the body loads.
  • Live product specs in Notion, Linear or Jira come in through MCP servers or CLIs when the task starts, not as copies that go stale.

CLAUDE.md (excerpt: product section)

## Product
- Tally bills per **workspace**; a workspace has members with roles `owner`,
  `finance_admin`, `member`. Only `owner` and `finance_admin` may export financial data.
- Invoice amounts are integer cents everywhere. Never use floats for money.
- Domain terms, personas and plan tiers: docs/product/glossary.md and docs/product/personas.md
  (read them when a task touches billing, exports or permissions).

.claude/skills/domain-glossary/SKILL.md

---
name: domain-glossary
description: Tally domain vocabulary (workspace, finance admin, invoice states, dunning,
  credit notes). Use when naming things, writing user-facing copy, or interpreting a
  ticket that uses billing terms.
---
Read docs/product/glossary.md and use its terms exactly in code, copy and tests.
If a ticket uses a term that isn't in the glossary, ask before inventing one.
Pitfall: the pasted PRDPasting a product requirements doc into CLAUDE.md feels thorough. It costs context on every request in every session, it goes stale, and it buries the rules that matter. The best-practices guide explains the cost: every line "takes a little of Claude's attention on every task, whether it's relevant or not." Keep the PRD as a doc, and put the two or three rules from it that Claude must never break into CLAUDE.md.

Codebase Maps

A codebase map is a short orientation: entry points, module boundaries, where tests live, what's generated and must not be edited, and which directory owns which concern. It saves Claude the first ten minutes of every session (and the tokens that go with them). It's not a file-by-file description. The best-practices guide lists "Describe your architecture and file layout in CLAUDE.md" among the advice you can stop following: "Claude reads the repo itself. Only write down what isn't in there." Claude can run ls. What it can't see is intent: why src/legacy/ exists and that new code must not import from it.

CLAUDE.md (excerpt: map section)

## Map (where things live)
- HTTP routes: src/api/*.ts (thin; call into src/<domain>/). Exports route: src/api/exports.ts
- Domain logic: src/exports/, src/invoices/, src/billing/
- Background jobs: src/jobs/<name>.job.ts, registered in src/jobs/registry.ts (Postgres-backed queue)
- File storage: src/storage/ (S3 helper; signed URLs via signedUrl.ts)
- Tests mirror src/ under test/; fixtures in test/**/fixtures/
- Generated: src/db/schema.gen.ts (run `npm run db:gen`; never edit by hand)
- src/legacy/: frozen. Don't import from it in new code.

Maps at three zoom levels. Claude Code gives you layered maps without one big file:

  • Root map in the project CLAUDE.md: the dozen lines above.
  • Area maps in nested src/exports/CLAUDE.md files. The memory docs say "Files in subdirectories load on demand" when Claude reads or edits there, so area detail costs nothing until Claude works in that area.
  • Task maps built fresh by a subagent. "Use a subagent to map every code path that produces a CSV, with file:line references, and report back a list." The Explore subagent reads files in its own context window and returns a summary (it supports quick, medium and very thorough), so the main context keeps only the map, not the hundred files behind it.

Building and maintaining maps is covered in depth in core-3, Repository Knowledge, including the codebase_map.py lab.

Pitfall: a stale map is worse than noneA map that says jobs live in src/workers/ after a rename sends Claude to the wrong place with confidence. Keep maps to stable boundaries, and ask Claude to update the map line in the same change whenever it moves a boundary. /doctor prompt-audit (v2.1.283+) looks for "references to files or commands that don't exist" in your instruction files.

Constraints

A constraint is a limit on acceptable solutions: no new runtime dependencies, no schema changes in this PR, CSV columns unchanged, no PII in email. Constraints come in two strengths, and the strength decides where they live:

  • Hard constraints ("must never") should be enforced, not just stated. The memory docs are explicit: Claude treats CLAUDE.md "as context, not enforced configuration. To block an action regardless of what Claude decides, use a PreToolUse hook instead." Permission rules do the same job for file paths and commands, and "Deny rules block in every mode, including bypassPermissions."
  • Soft constraints ("prefer", "avoid unless") are judgment calls. Write them in prose with the reason, so Claude can weigh them.

.claude/settings.json

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "deny": [
      "Edit(/db/migrations/**)",
      "Edit(/src/db/schema.gen.ts)",
      "Bash(git push *)"
    ],
    "ask": [
      "Bash(npm install *)"
    ]
  }
}

This is Tally's .claude/settings.json. A leading / in a path rule anchors at the primary working directory when the rule lives in project settings, and an Edit(...) rule covers every file-writing tool. The ask rule makes a new dependency a conversation instead of a surprise: explicit ask rules force a prompt even in auto mode. Note the docs' warning that a Bash deny rule "isn't a security boundary around the program", since Bash(git push *) doesn't stop bash -c "git push". Containment comes from deny rules plus the sandbox (off by default). A PreToolUse hook can catch more variants than a pattern, but it's defense in depth, not the boundary (see agents-5). Edit deny rules have a similar edge: they cover Claude's file tools, Bash file commands Claude Code recognizes (such as sed and tee) and redirect targets, but not "arbitrary subprocesses that read or write files indirectly". Edit(/src/db/schema.gen.ts) stops Claude from editing the generated file, yet npm run db:gen still rewrites it. For OS-level enforcement on every process, the docs point to the sandbox.

Task-specific constraints go in the brief, with the reason: "Don't change src/api/exports.ts's response for ≤10k rows: three customers' scripts parse it." The reason matters. It lets Claude recognize a variant of the forbidden change that the rule's wording doesn't cover.

Pitfall: constraints stated only in conversation"Don't touch migrations" typed in turn 3 is just a message. The auto mode docs warn that "a boundary can be lost if context compaction removes the message that stated it. For a hard guarantee, add a deny rule instead." The same applies to any prose constraint. If it must survive a long session, put it in the project-root CLAUDE.md (re-injected from disk after compaction) or in a rule that Claude Code enforces.

Conventions

Conventions are the local way of doing things: where jobs go and how they're registered, how errors are shaped, how tests are named, which helper to use for money. They're cheaper to show than to describe, and most of them only matter in one area of the code, so they belong in path-scoped rules: Markdown files in .claude/rules/ with a paths: frontmatter field. A path-scoped rule "loads when Claude uses the Read, Write, or Edit tool on a matching file", so the jobs convention costs nothing until Claude opens a job file.

.claude/rules/jobs.md

---
paths:
  - "src/jobs/**/*.ts"
  - "test/jobs/**/*.ts"
---
# Background job conventions
- One job per file: src/jobs/<name>.job.ts exporting `define<Name>Job()`.
- Register every job in src/jobs/registry.ts (alphabetical). Unregistered jobs never run.
- Jobs must be idempotent: the queue retries on failure (ADR-014).
- Follow src/jobs/sendDunningEmails.job.ts as the reference implementation.
- Tests: test/jobs/<name>.job.spec.ts using the `runJobOnce()` helper.

Two habits make conventions stick. Point to an exemplar: the best-practices guide's example prompt starts "follow the pattern in HotDogWidget.php". One good reference file teaches more than ten bullet points. Automate the mechanical ones: formatting and import order belong in a PostToolUse hook that runs your formatter, not in prose. Leave out conventions Claude already follows (the best-practices test: "Could it find this by reading the code?").

Pitfall: the rule that isn't loaded yetA path-scoped rule appears only after Claude touches a matching file. During planning, before Claude has opened src/jobs/, the jobs convention isn't in context, so the plan may put the job in the wrong place. Either have the plan step read the reference job first, or drop the paths: field for rules that must shape planning. After compaction, path-scoped rules "reload on demand" rather than being re-injected. The context-window docs advise: "If a rule must persist across compaction, drop the paths: frontmatter or move it to the project-root CLAUDE.md."

Prior Decisions

Prior decisions are choices the team already made, with reasons Claude can't see in the code: "We use a Postgres-backed job queue, not Redis, because we run one datastore" (ADR-014). "Exports are never emailed as attachments, because of PII retention policy" (ADR-021). Without them, Claude re-litigates settled questions. It's not being stubborn: from inside the code, adding Redis for the export queue looks perfectly reasonable, and emailing the file looks like the obvious UX.

How to give Claude the history.

  • Keep architecture decision records (ADRs) in the repo, for example docs/decisions/ADR-014-postgres-job-queue.md, each with context, decision, consequences and status.
  • Add a decisions index to CLAUDE.md: one line per load-bearing decision with its path. That's a dozen lines that prevent the expensive mistakes.
  • Reference the relevant ADR from the path-scoped rule for that area (as the jobs rule above does), so the decision arrives exactly when Claude works there.
  • For decisions nobody wrote down, have Claude dig: "Before changing invoiceCsv.ts, use git log -p --follow and the linked PRs to find why it streams rows instead of building the file. Summarize any decision you find, with commit hashes."
  • When the session makes a new decision (say, the 10,000-row threshold), have Claude draft the ADR in the same PR.

CLAUDE.md (excerpt: decisions index)

## Decisions (read the ADR before working against one)
- ADR-014 Postgres-backed job queue (src/jobs). No Redis or new queue libraries.
- ADR-021 Never email exports or attachments containing invoice data. Send links.
- ADR-030 Money is integer cents; formatting only at the edge (src/format/money.ts).

Auto memory also records decisions (its project type covers "ongoing work, deadlines, and decisions that Claude can't derive from the code or git history"). But auto memory is machine-local: your teammate's session and a cloud session never see it. Team decisions belong in the repo.

Assembling the context pack

Here are the five kinds of knowledge together for Tally's change. Place each item, and the simulation shows what it costs, when Claude sees it, whether it survives compaction, and which failure it prevents.

For each item, choose where it lives; the meter on each row is its protection, from missing through fragile and advice to enforced. Token costs are illustrative. The load rules follow the Claude Code docs: what's always loaded, what loads on demand, what survives compaction, and which placements the built-in Explore and Plan subagents miss. Hovering a row lights its fixture in the corridor above.
Who sees what: main session, Explore and Plan, custom subagents, and after compaction

Main session at launch. Claude Code walks from the working directory up and concatenates every CLAUDE.md it finds ("concatenated into context rather than overriding each other"), along with unscoped rules, the first 200 lines or 25 KB of auto memory's MEMORY.md, skill descriptions, and MCP tool names. CLAUDE.md content "is delivered as a user message after the system prompt, not as part of the system prompt itself". To confirm what loaded, run /context and check the Memory files list. To trace loading as it happens, an InstructionsLoaded hook fires per file with a load_reason (session_start, nested_traversal, path_glob_match, include, compact).

Explore and Plan subagents. These "start without your CLAUDE.md files and the git status snapshot to keep research fast and inexpensive". Your decisions index doesn't reach them, although a subdirectory's CLAUDE.md and matching path-scoped rules still load when they work with files there. The sub-agents docs give the fix: "If a rule must, such as 'ignore the vendor/ directory,' restate it in the prompt you give Claude when delegating." Custom subagents load the full CLAUDE.md hierarchy unless their definition sets omitClaudeMd: true (v2.1.271+).

After compaction. The project-root CLAUDE.md and unscoped rules are re-injected from disk, auto memory is re-injected, the plan from plan mode is re-injected, and path-scoped rules and nested CLAUDE.md files reload on demand. Invoked skill bodies are re-injected up to 5,000 tokens per skill and 25,000 total. Instructions that existed only in the conversation survive only if the summary keeps them. Add a "Compact Instructions" section to CLAUDE.md, or run /compact with a focus, to steer what the summary keeps (how Claude Code works). Source: context-window.

Edits mid-session. Editing CLAUDE.md during a session is cache-safe, but the edit "doesn't apply" until /clear, /compact or a restart. If you add a decision mid-task, tell Claude in the conversation as well.

Contradictions. "If two instructions contradict each other, Claude may pick one arbitrarily." A rule saying "use the shared queue" and a stale skill saying "use BullMQ" is a coin flip. /doctor prompt-audit reports conflicting and outdated instructions and proposes edits without applying them until you ask.

Exercise: an A/B test of your context pack

Pick a change in your repo that touches a convention and a prior decision. Run it twice in separate worktrees (claude --worktree ctx-a and claude --worktree ctx-b) with the same prompt. In run A, use your current setup. In run B, first add one decisions-index line to CLAUDE.md and one path-scoped rule pointing at an exemplar file. Commit both so the worktree sees them. Compare the plans: which run respected the decision without being told in the prompt?

Show a reference solution

In run A, expect Claude to either rediscover the decision (it spent tokens reading history) or miss it (it proposed the "obvious" design). In run B, the plan should cite the ADR by name and follow the exemplar's structure. If run B still misses it, check three things. Was the rule loaded? (It's path-scoped, so did Claude touch a matching file before planning? Look for it in /context.) Is the decision line concrete ("No Redis or new queue libraries") rather than vague ("prefer existing infrastructure")? Did the plan come from the Plan subagent, which skips CLAUDE.md? If so, the planning prompt must restate the decision.

Key takeaways

  • Placement decides when Claude sees knowledge, what it costs, whether it survives compaction, and whether it's advice or enforcement.
  • CLAUDE.md holds only what every task needs (under 200 lines). Reference docs by path rather than @-importing them, and use skills for knowledge that matters only sometimes.
  • A codebase map gives intent and boundaries, not a file listing. Layer it: root map, nested CLAUDE.md files, and task maps from an Explore subagent.
  • Hard constraints become deny rules or hooks. Soft ones are prose with reasons. A constraint typed only in conversation can disappear at compaction.
  • Conventions go in path-scoped rules that point at an exemplar file. Prior decisions go in ADRs plus a one-line index, because auto memory is machine-local.
  • Explore and Plan skip CLAUDE.md, so restate must-follow rules when delegating to them.

Requirements

Every request has gaps. The question is who fills them and when. If nobody asks, Claude fills them silently with plausible defaults while it codes, and you find out in review, or after release. This topic moves gap-filling to the cheapest moment: before code. You'll make Claude state its assumptions, find the ambiguities in a request, interview you with AskUserQuestion, and keep the questions focused on decisions that change the work.

Assumptions

An assumption is a gap Claude filled without asking. Some are harmless (naming), and some decide the design: "large" means over 50,000 rows; notification means email; any member may export. Current models are tuned to keep working rather than stall. The permission-modes docs note that auto mode in particular "nudges Claude to keep working without stopping for clarifying questions, though Claude still asks when your prompt or a skill explicitly relies on it". Since auto mode is the default starting mode for interactive sessions on v2.1.283+, the default is to assume. If you want assumptions surfaced, you have to ask for them.

Make assumptions explicit. Ask for an assumption ledger before any plan or code:

Before planning, list every assumption you are making about this change as a table:
assumption | evidence (file:line, ticket, or "none") | would the plan change if it's wrong? |
cheapest way to verify. Don't verify anything yet. Mark anything you couldn't confirm,
and say where you looked.
AssumptionEvidenceChanges the plan?Cheapest check
The 30 s cutoff is the load balancer, not the appinfra/lb.tf:41 idle_timeout = 30Yes: if it's the app, raise the app limit insteadAlready confirmed by the file
"Big" means more than 10,000 rowsNoneYes: decides which path most exports takeAsk: it's a product decision
Notifications can go in-appsrc/notifications/inApp.ts existsYes: email is forbidden by ADR-021Confirmed by ADR-021
Only finance admins exportsrc/api/exports.ts:12 role checkNo: same check reusedAlready confirmed

The ledger sorts itself. Assumptions with evidence are facts. Assumptions without evidence that don't change the plan can stay as stated defaults. The rest are questions, and only those deserve your attention. In plan mode, require the plan to carry an "Assumptions" section so you review them with the plan (see plan review).

Pitfall: assumptions written as facts"The export endpoint is only used by the web app" reads like a finding. Ask for the evidence column, and every unverified claim becomes visible as "none". A plan built on an unlabelled assumption is the most common source of a correct-looking, wrong PR.

Ambiguities

An ambiguity is a phrase in the request that has more than one reasonable reading. Ambiguities recur in a small number of shapes, and each has a standard question that resolves it:

ShapeExampleResolving question
Vague quality"fast", "properly", "robust"What number or behavior counts as meeting it?
Unbounded quantity"big customers", "large files"What's the threshold, and what happens on each side of it?
Unnamed actor"users should get notified"Which role, through which channel?
Open verb"handle", "support", "fix"What exactly happens in the failure case?
Hidden alternative"notify somehow", "etc."Which of these options, or which combination?

Claude is good at finding these when you ask it to: "Read this request and list every phrase with more than one reasonable interpretation. For each one, give the two most likely readings and how the implementation would differ." The difference in implementation is the key part. An ambiguity that doesn't change the code isn't worth a question.

Pitfall: the reading Claude picked silentlyAn ambiguity that nobody resolves doesn't stay open. Claude picks one reading, usually the most conventional one, and the code embeds it without comment. "Notify the user" becomes an email because most apps send email, which here violates ADR-021. The dangerous ambiguities are the ones that don't look ambiguous to you, because you already know the answer. Ask Claude to list readings before you decide the request is clear, and check the plan for words like "notify", "large" and "handle" turned into a specific choice you never made.
Edit the request. The widget underlines ambiguity shapes with a simple lexicon, one underline style per shape and a label in the margin, which is far cruder than Claude's reading but shows the categories. It then drafts focused questions in the real AskUserQuestion input shape and validates them against the tool's documented limits; open the draft to see them.

Interviews with AskUserQuestion

AskUserQuestion is the built-in tool Claude uses to ask you multiple-choice questions "when it needs a decision or a clarification". Claude Code renders it as a dialog: you pick an option, or type your own answer through the Other row or the notes field. Typed answers are relayed "with neutral wording so Claude follows what you wrote, including a request to wait or explain first". Each call carries 1–4 questions with 2–4 options each, and each question has a header of at most 12 characters and a multiSelect flag.

The interview pattern. For anything bigger than a small fix, the best-practices guide recommends reversing the roles: start with a minimal prompt and let Claude interview you (brainstorm with Claude first).

I want to make invoice CSV exports reliable for large workspaces (see the
truncation test in test/exports/characterization.spec.ts) but haven't thought it
through yet. Interview me until you could write the spec, then write it to
docs/specs/export-async.md.

The parenthesis and the file name are the only parts you add. The rest is the docs' prompt almost word for word. Here's what one round looks like as a tool call:

userI want to make invoice CSV exports reliable for large workspaces … Interview me until you could write the spec, then write it to docs/specs/export-async.md.
assistantI read src/exports/invoiceCsv.ts, src/api/exports.ts and ADR-014/021. Before I write the spec, three decisions that change the design:
tool_use · AskUserQuestion{"questions": [ {"question": "Above how many rows should an export switch from direct download to a background job?", "header": "Threshold", "multiSelect": false, "options": [{"label": "10,000 rows", "description": "Direct path stays well under the 30 s limit on the fixture"}, {"label": "50,000 rows", "description": "Fewer jobs, but the direct path risks the timeout on slow queries"}, {"label": "Always async", "description": "One code path; every export waits for a link"}]}, {"question": "If the export job fails after retries, what should the user see?", "header": "On failure", "multiSelect": false, "options": [{"label": "Notify + retry", "description": "In-app notice with a retry button"}, {"label": "Silent retry", "description": "Keep retrying; no notice until success"}]}, {"question": "How long should the download link stay valid?", "header": "Link TTL", "multiSelect": false, "options": [{"label": "24 hours", "description": "Matches the storage bucket's lifecycle rule"}, {"label": "7 days", "description": "Needs a lifecycle change (infra ticket)"}]} ]}
tool_resultThreshold: 10,000 rows · On failure: Notify + retry · Link TTL: 24 hours

Then start fresh. "Once SPEC.md exists, start a fresh session to build from it, so the build begins with a clean context and a written definition of done." The interview's exploration and dead ends stay behind. The spec carries the decisions forward, and you can review and commit it.

Decisions move from the conversation into a file when the interview writes the spec. When the session ends (/clear or a new session), the answers that were never written down fade, and everything on the right reads the file, not the interview. That's why the spec must be self-contained. Click an answer to write it to the spec or take it out, then end the session again. The decisions are the page's illustrative Tally example.

Mechanics and settings worth knowing

  • Unanswered questions wait. By default a question stays open until you answer it. askUserQuestionTimeout (user or managed settings: "60s", "5m", "10m" or the default "never") lets a dialog auto-continue after idle time, submitting what you'd selected and telling Claude you may be away. The timer never starts in background sessions, in screen reader mode, or while Remote Control is connected. Plan approval and other permission prompts "never auto-resolve on idle".
  • Not everywhere. AskUserQuestion isn't available inside subagents, and dontAsk mode denies it. In the Agent SDK it arrives at your canUseTool callback with tool_name == "AskUserQuestion", and you render it yourself. If you restrict tools, include it.
  • Unattended runs can't interview. For scheduled tasks the docs say: "The task runs autonomously, so it can't ask clarifying questions." Run the interview interactively first, and give the unattended run the spec.
Interview design: one question per decision, and when multiple choice beats open text

Why multiple choice. An open question ("how should failures work?") makes you design on the spot. A multiple-choice question with consequences in each option's description makes Claude do the design work (enumerate the viable options and their costs) and leaves you the decision. That's the right split of labour. The description field is where the quality is: "Notify + retry: in-app notice with a retry button" tells you what you're buying, "Option A" doesn't.

Batching. Up to four questions per call means you see related decisions together, so you can answer them consistently (threshold and link TTL interact with storage cost). Ask for "the three decisions that change the design most" first. Deep interviews take several rounds. Community practitioners report good results with "ask me questions, one at a time... multiple choice" and presenting designs "in sections of maybe 200-300 words at a time" (Jesse Vincent, community post). That's consistent with the docs' pattern.

Interview in plan mode. The SDK docs note that clarifying questions "are especially common in plan mode, where Claude explores the codebase and asks questions before proposing a plan". Running the interview in plan mode means Claude can read code to make its options concrete without editing anything.

Effort. One Claude Code team member describes their loop as "getting the model to interview me then implementing on low effort, reviewing what it built, and then running verification on high effort" (Spending your effort, official blog, framed as personal practice). The interview is where effort pays off least for the code and most for the spec, because a better question set is cheaper than a better implementation of the wrong thing.

Focused Questions

A focused question is one whose answer changes the work, which only you can answer, and which is cheap to answer. Each of the three properties rules out a common waste of your attention:

  • Decision-relevant: if every answer leads to the same code, don't ask. "Should the job log progress?" rarely changes anything.
  • Only you can answer: if the answer is in the code, the docs or git history, Claude should look it up. "Which queue do we use?" is in ADR-014. The docs' interview prompt has Claude interview you "until you could write the spec", not quiz you on what it can read.
  • Cheap to answer: options with consequences beat open prompts. "Above how many rows: 10k / 50k / always async?" takes two seconds.
✗ Unfocused

"What do you want the export to do?" (open, design-on-the-spot) · "Should I write tests?" (answer is always yes; it's in CLAUDE.md) · "Which job library should I use?" (answered by ADR-014) · "Is it OK if I refactor the CSV module?" (no decision content; ask about the risk instead)

✓ Focused

"Above how many rows should exports go async? (10k: most exports stay instant · 50k: fewer jobs, timeout risk · always: one path)" · "On job failure: notify with retry, or retry silently?" · "Should API clients that call the CSV endpoint directly also get 202 for large exports, or keep the old behavior behind a flag?"

When to ask and when to assume. Asking costs your attention, and a wrong assumption costs rework. The rework cost depends on how late the mistake is found. The simulation below makes the tradeoff concrete. One practical rule falls out of it: if a test or the plan review would catch a wrong assumption cheaply, assume and flag it in the plan. If a wrong guess would only show up after release, ask.

Illustrative minutes, not measurements. The map splits every combination of how likely Claude's default is wrong and how expensive a wrong guess is into the regions where each choice is cheapest; your first two sliders place the dot. How early a mistake would be caught and what asking costs you move the borders.
The value-of-information math behind "ask vs assume"

Treat one open question as a decision under uncertainty. Let p be the probability Claude's default is wrong, R the rework cost if it's wrong and found at release, d the probability an earlier check (a test, the plan review) catches it, and r the cheaper rework when it's caught early. Let q be the cost of asking: your interruption plus the context switch.

E[assume] = p · (d · r + (1 − d) · R) and E[ask] = q. Ask when q < p · (d · r + (1 − d) · R). A third strategy, "assume and flag", puts the assumption in the plan's Assumptions section, where your plan review is the check. That raises d for nearly no cost, which is why the assumption ledger is so effective. Most questions end up in one of three regions: ask (high p·R, low d), assume and flag (moderate p, good d), and just assume (low p or negligible R).

The model also explains why interviews work best for big features. R grows with the size of the change, while q stays roughly constant per question and shrinks with good multiple-choice options. This is the standard expected value of information argument from decision analysis (Howard, "Information Value Theory", IEEE Transactions on Systems Science and Cybernetics, 1966), applied to agent work.

Exercise: questions before code

Take a medium-sized backlog item. In a fresh session, run /plan with the interview prompt above (your one-paragraph description plus the docs' template), and stop after the first round of AskUserQuestion. Before answering, sort Claude's questions into three piles: would change the code, Claude could have looked this up, obvious. Then answer, let it write the spec, and start a new session with claude + "Implement @docs/specs/<file>.md".

Show a reference solution

A good first round has two to four questions, all in the first pile, each with options whose descriptions state consequences. If you got lookup questions ("which framework do we use?"), your context pack is missing something: add a CLAUDE.md line or decisions-index entry so the next interview skips it. If you got obvious questions, add "Don't ask about things already answered in CLAUDE.md or docs/decisions/" to the prompt. In the implementation session, notice that Claude never asks the interview's questions again. The spec carried them.

Key takeaways

  • By default Claude fills gaps with plausible assumptions and keeps going, especially in auto mode. Ask for an assumption ledger with an evidence column to make them visible.
  • Ambiguities come in a few shapes (vague quality, unbounded quantity, unnamed actor, open verb, hidden alternative). Only the ones that change the implementation deserve a question.
  • For larger features, let Claude interview you with AskUserQuestion (1–4 questions, 2–4 options, 12-character headers), write the spec to a file, then implement in a fresh session.
  • AskUserQuestion isn't available in subagents or dontAsk mode, and unattended runs can't interview. Resolve questions before you go unattended.
  • Focused questions are decision-relevant, unanswerable from the repo, and cheap to answer. Ask when a wrong guess is likely and would be found late; otherwise assume and flag it in the plan.

Specifications

A specification is where intent, context and answers become one artifact that a session with no history can execute. Every reader of the spec starts cold: a fresh implementation session, a subagent, a cloud session, a teammate. The four items below are the parts that make a spec work for those readers. Structure makes it complete. Negative examples rule out the tempting wrong answers. Acceptance criteria make it checkable, and boundaries keep the work inside its lane.

Structured Briefs

A structured brief is a spec with fixed sections, each of which prevents a specific failure. The best-practices guide gives a spec two jobs: the build session starts from it with "a written definition of done", and "It's also the file you'll point the reviewer at later." A brief that does both names the files and interfaces involved, states what is out of scope, and ends with an end-to-end check that proves the feature works. Anthropic's cloud-sessions guide says the same thing about tickets: "Write each task as a self-contained ticket that states what's wrong, what done looks like, and how to prove it."

SectionPrevents
Goal and user impactSolving a different problem; making the wrong tradeoff
Current behavior (with evidence)Changing the wrong thing; breaking depended-on behavior
Desired behavior (before/after)An ambiguous end state
Files and interfacesWandering exploration; edits in the wrong module
Constraints and decisionsRe-litigating ADRs; new dependencies
Out of scopeScope creep; a "while I was here" refactor
Don't / insteadThe tempting wrong solution
Acceptance criteria"Done" by assertion
VerificationAn unproven end state; nothing for /goal to check
Stop and askGuessing at decisions, or plowing through destructive steps

docs/specs/export-async.md

# Spec: complete invoice exports for large workspaces
Status: approved 2026-10-20 · Owner: @dana · Ticket: TALLY-482

## Goal
No export ever delivers a partial file. Exports ≤10,000 rows still download directly;
larger ones arrive as a 24 h download link via in-app notification.
User impact: finance admins in ~40 large workspaces (tickets labeled export-timeout)
get truncated CSVs at month-end. Priority: correctness over speed.

## Current behavior
- GET /api/exports/invoices.csv streams rows (src/exports/invoiceCsv.ts); the LB cuts at
  30 s (infra/lb.tf:41) after HTTP 200 was sent → truncated file, no error.
- Reproduced by test/exports/characterization.spec.ts › "bug, must change".

## Desired behavior
| Case | After |
|---|---|
| ≤10,000 rows | unchanged: direct download, same columns and order |
| >10,000 rows | 202 + job; in-app notification with a signed link (24 h) |
| job fails after retries | notification with retry; no partial file is ever offered |
| empty range / no role | unchanged (header-only CSV / 403) |

## Files and interfaces
- src/api/exports.ts (routing by row count), src/exports/invoiceCsv.ts (row generator)
- new src/jobs/exportInvoices.job.ts + src/jobs/registry.ts
- src/storage/signedUrl.ts (reuse), src/notifications/inApp.ts (reuse)
- tests in test/exports/

## Constraints and decisions
- ADR-014: use the existing Postgres-backed queue. ADR-021: never email the file.
- No new runtime dependencies. No schema migrations in this change.

## Out of scope
XLSX, scheduled exports, column changes, progress bars.

## Don't / instead
- Don't buffer the whole CSV in memory (src/legacy/reportExport.ts does; it OOMs on
  large workspaces). Instead, stream the row generator into the storage upload.
- Don't raise the LB timeout. Instead, keep the direct path for exports that fit in it.

## Acceptance criteria
1. Given 500 rows, when exported, then 200 with the full CSV (same header as golden file).
2. Given exactly 10,000 rows, then the direct path is used. Given 10,001, then 202 + job.
3. Given the 120k-row fixture, then the job completes and the stored file has 120,001 lines.
4. Given a job that throws twice, then it retries and, on final failure, notifies with
   retry and stores no file.
5. Given a member without finance_admin or owner, then 403 on both paths.

## Verification
npm test -- test/exports && npm run lint && npm run typecheck (print exit codes), then
run the app locally and export the 120k fixture workspace: expect 202, a notification,
and a downloaded file with 120,001 lines (wc -l).

## Stop and ask
Before any change outside the files above, any new dependency, or if the 120k fixture
takes longer than 5 minutes.

Commit the spec (for example under docs/specs/) and hand it to the implementation session as a file: claude --permission-mode plan "Read docs/specs/export-async.md and plan its implementation", or, inside a session, /plan Implement @docs/specs/export-async.md. Keeping specs in sync with the code, and spec files versus plan files, are covered in core-3, Specifications.

Pick a sample or paste your own brief. The linter checks the sections and signals above with simple pattern rules, a simplified version of the rubric in the brief_lint.py lab below; the scorecard marks the weakest section. A high score means the brief is complete enough for a cold reader. It doesn't mean the decisions in it are right.

What you build: a deterministic linter (no model, no network) that scores a Markdown brief, grades every acceptance criterion for observability, checks the done condition against what a /goal evaluator could see, finds contradictions, maps each boundary to the control that would enforce it (a permissions.deny/ask rule, a hook, or a done-condition check), and turns the gaps into an interview of up to four questions shaped like a valid AskUserQuestion payload. It writes the report, the interview JSON and a suggested /goal line to delivery-2/out/.

cd labs && python3 delivery-2/brief_lint.py
python3 delivery-2/brief_lint.py my_brief.md --fail-under 80   # CI mode: exit 1 below 80

What to observe: the weak sample reads fine at a glance but scores 0/100 ("not delegable yet"). Its done condition, "When everything works and the code is clean", has no check and no end state, and the brief contradicts itself twice, so the interview puts those conflicts first. The strong sample scores 100, yet its enforcement map shows that only two of its six boundaries can become permission rules. "Never edit the TAX_BPS values" can't, because rules match tools and paths, not file content, so the lab suggests a pinning test or a hook. A perfect score grades the text, not whether the controls exist.

Open the lab walkthrough

Why structure beats length, and how long a brief should be

The cold-reader test. A spec is read by a session with none of your conversation, often by a subagent whose "only content you pass from parent to subagent is the Agent tool's prompt string" (Agent SDK docs). Every term that relies on shared history ("the timeout thing", "like we discussed") is a hole. Fixed sections force you to write down the parts you'd otherwise assume the reader knows.

Length. There's no documented optimum for spec length, and the CLAUDE.md guidance doesn't transfer directly: a spec is read once per task, not on every request. The practical constraint is adherence. Every line Claude must hold in mind competes with the code it reads, and the best-practices guide keeps context focused for the same reason: "a focused context gets you better answers and costs less." Aim for each sentence to be a decision, a fact with a citation, or a check. The example above is about 60 lines, and every line would change the implementation if removed. That's the same pruning test as for CLAUDE.md, applied to a task.

Specs versus plans. The spec says what and how you'll know. The plan, produced in plan mode from the spec, says in what order and which files. Keep them separate: you approve the spec with stakeholders, and you review the plan against the spec. A spec that contains step-by-step implementation is a plan that skipped review.

Cloud and parallel sessions. For claude --cloud runs, the official field guide adds "Split parallel tasks along file boundaries", which is one more reason the Files and interfaces section exists. Two specs that list overlapping files will produce merge conflicts (see delivery-3, Execution). Source: Claude Code in the cloud.

Negative Examples

A negative example names a specific wrong solution, so Claude doesn't reach for it. Negative examples matter because the wrong solutions that cost the most are the tempting ones: raising the timeout, buffering the file in memory, emailing the CSV. Each is the first thing a reasonable engineer would try, so a reasonable model tries it too.

Always pair "don't" with "instead". Practitioners put it bluntly: "Don't Just Say 'Never.'... Always provide an alternative" (Shrivu Shankar, community post). A bare prohibition leaves Claude to find the next-nearest wrong solution. "Don't raise the load balancer timeout" invites "raise the app server timeout". "Don't raise any timeout; instead keep the direct path only for exports that fit inside 30 s" closes the whole family. The reason helps too: "it OOMs on large workspaces" lets Claude recognize a variant you didn't list.

Point at real code. The strongest negative example is a file in your repo: "Don't follow src/legacy/reportExport.ts (buffers the whole file); follow src/exports/invoiceCsv.ts (streams)." Claude can open both files and see the difference, which beats any description.

For visual work, name the styles you don't want. The same guide observes that "avoid a generic look" just swaps one default for another. Specific exclusions ("no gradients, no card shadows, no emoji in headings") work better.

✗ Prohibitions without alternatives

Don't use Redis. Don't email anything. Don't break the API. Don't make it slow. NEVER change the CSV.

Five "don'ts" with no "instead", one shouted rule (on current models, emphasis "mostly makes Claude over-apply the rule"), and two vague ones ("break", "slow").

✓ Paired, specific, with reasons

Don't add a queue library; instead define a job in src/jobs/ (ADR-014). Don't email the file; instead notify in-app with a signed link (ADR-021, PII). Keep the ≤10k response byte-identical: three customers' scripts parse it.

Positive examples are model-dependentFew-shot examples of desired output are contested guidance in 2026. An official 2025 context-engineering post recommends them, while Claude Code team members said in a community interview that examples in system prompts are "no longer best practice" for the newest models. Treat it as an empirical question: try with and without on your own tasks and model. Pointing to an exemplar file in the repo is a different technique, and it reliably helps.

Acceptance Criteria

Acceptance criteria (ACs) are the behaviors the change must exhibit, each stated so a test or command can confirm it. The Given/When/Then form works well with Claude because each part maps to code: Given is a fixture, When is the call, Then is the assertion. "Given exactly 10,000 rows, when exported, then the direct path is used" becomes a test in one step.

What separates good ACs from decoration:

  • Numbers and boundaries. "Large exports go async" has no boundary. "10,000 → direct, 10,001 → job" has two test cases, and off-by-one bugs live exactly there.
  • Failure behavior. At least one AC for what happens when things go wrong (the job throws, the user lacks the role). Claude covers happy paths unprompted and skips failure paths unless asked.
  • Observable, not structural. "Uses the job queue" is structure. "Returns 202 and a notification arrives" is behavior. Structural requirements belong in constraints.
  • Few and prioritized. Five ACs that a reviewer can hold in their head beat twenty that nobody checks.
A spec is a drawing someone else has to build from. Here Tally's large-export path is drawn as a part, a diverter, in plan (from above) and elevation (from the front). Requests come in at the inlet. A gate sends exports of up to N rows down the 30 s direct chute to the browser, and the rest into a holding tank: the background job, which streams the file out along the signed link to the stored CSV. Every acceptance criterion is a dimension or a leader callout on the part. The hatched zones are the don'ts, each noted with its instead: the chute's forbidden extension, the tank filled with the whole file, the attachment port blanked off. The glowing ? marks are the dimensions nobody has set, which is exactly where Claude would guess. Click a dimension (or focus it and press Enter) to set it from 2 to 4 options shaped like an AskUserQuestion; the SPEC.md excerpt beside it gains the matching acceptance criterion. The values are the page's illustrative Tally example.

ACs versus the definition of done. ACs are about the product's behavior. The DoD adds process checks: lint, typecheck, scope, "no test deleted". The /goal condition usually says "all ACs have passing tests" plus the process checks. How the ACs are verified once the change exists (requirements coverage, observable behavior, completion evidence) is delivery-4's Acceptance topic.

Pitfall: criteria that drift from their testsA test named "handles large exports" can be counted as covering criterion 3 while asserting only that the response is 202, not that the stored file has 120,001 lines. Over a few revisions the criterion and the test drift apart, and the coverage table still says "covered". Require each test to quote the criterion's Then clause in its name or a comment, and when a criterion changes in the spec, ask Claude to list which tests must change with it.

Have Claude draft them, then attack them. "From the desired-behavior table, write Given/When/Then acceptance criteria. Then, for each criterion, describe one wrong implementation that would still satisfy it." Any AC with an easy wrong implementation needs another case. You'll use this idea again with tests in Evaluation.

Boundaries

Boundaries define the lane the work stays in: which files may change, which actions are off limits (push, deploy, migrate), what budget it may spend, and when to stop and ask. Writing them in the spec makes them clear. Enforcing them in Claude Code makes them hold. That distinction is the whole topic.

Top to bottom, the layers go from advice Claude can forget to mechanisms that Claude Code or the OS applies; left to right are the things a boundary has to cover. Prose layers can be forgotten or summarized away. Hooks are deterministic but run your own logic, so treat them as defense in depth. Permission rules are applied by Claude Code: deny and ask hold in every mode, while allow does nothing in bypassPermissions. The sandbox constrains shell commands at the OS level, for every process they start, but covers nothing else. Hover or focus a column to list what protects it.

Enforce the boundaries that matter. For Tally:

  • Scope: list allowed files in the spec, and check it in the DoD (git diff --name-only). For hard limits, add Edit(...) deny rules for directories that must not change. For the strongest isolation, run in a worktree (claude --worktree export-async), so even a bad run can't touch your main checkout.
  • Actions: add deny rules for Bash(git push *) and deploy commands in project settings. Remember that a Bash deny rule doesn't stop the same command wrapped another way, so for untrusted or unattended runs, turn on the sandbox (/sandbox, off by default).
  • Budget: in headless runs, cap with --max-turns and --max-budget-usd, and pre-approve exactly what's needed with --allowedTools plus --permission-mode dontAsk, which denies anything else. In interactive goal runs, put the turn bound in the /goal condition.
  • Stop and ask: a short standing rule in CLAUDE.md, as Anthropic's Opus 5.5 guide suggests: "Stop and ask only when you can't continue without me, or before anything destructive." Add task-specific triggers in the spec.
# An unattended, bounded run of the same spec (illustrative budget)
claude -p "Read docs/specs/export-async.md and implement it. Follow its Stop-and-ask section
by stopping and reporting instead of asking." \
  --permission-mode dontAsk \
  --allowedTools "Read" "Edit" "Bash(npm test *)" "Bash(npm run lint)" "Bash(npm run typecheck)" "Bash(git diff *)" \
  --max-turns 60 --max-budget-usd 5 \
  --output-format json

The json result carries result, session_id, total_cost_usd and permission_denials. The denials list is a useful boundary report: every action Claude tried that your boundaries refused. On v2.1.302+, a -p run with no mode set starts in Manual, so calls that need approval are denied unless allowed. Passing the mode explicitly makes the run's behavior obvious to the next reader.

Not a boundary: bypassPermissions--dangerously-skip-permissions (the same as --permission-mode bypassPermissions) removes the permission layer entirely. The docs say it's for "Isolated containers and VMs only" and that it "offers no protection against prompt injection or unintended actions". Deny rules still apply, but your other boundaries are gone. Use it only inside a sandboxed container or VM with no credentials you can't afford to lose.
Why prose boundaries leak, and the order in which Claude Code evaluates enforcement

Leak 1: compaction. A boundary stated in a message is subject to summarization. The auto mode docs say "Boundaries are not stored as rules ... a boundary can be lost if context compaction removes the message that stated it." The spec file survives only as well as the summary keeps it, unless Claude re-reads it. The plan from plan mode is re-injected after compaction, which is one reason to carry the boundaries into the plan.

Leak 2: delegation. A subagent gets the task message Claude writes, not your spec, unless the message includes it. Explore and Plan don't load CLAUDE.md. Permission rules, by contrast, apply to subagents' tool calls as well.

Evaluation order. Permission rules "are evaluated in order: deny, then ask, then allow. The first match in that order determines the outcome, and rule specificity doesn't change the order." "If a tool is denied at any level, no other level can allow it." PreToolUse hooks run before the permission-mode check, and "A hook that exits with code 2 stops the tool call before permission rules are evaluated", but a hook's allow can't override a deny rule. So: deny rules for the boundary, hooks for logic a glob can't express (for example no edits outside the paths listed in the active spec; match Bash as well as Edit|Write, or the hook never sees shell writes), sandbox for shell containment. Sources: permissions, hooks guide, sandboxing.

Protected paths. Some paths are guarded regardless of your rules: writes to .git, .claude (with exceptions such as .claude/worktrees/), .vscode, .husky, shell rc files and .mcp.json, among others, are "never auto-approved, except in bypassPermissions mode and in interactive terminal sessions in plan mode with bypass permissions available", and permissions.allow rules don't pre-approve them. By mode: Manual and accept edits prompt, auto mode routes the write to the classifier, and dontAsk denies it. A spec that asks Claude to edit .husky/pre-commit therefore gets a prompt in Manual, a classifier decision in auto mode, and a denial in a dontAsk headless run. The last one surprises people: plan for it in the spec, or make that edit yourself.

Exercise: write the brief, then probe it

Write a spec for a real change using the section list above (or let an interview write it). Then probe it in a fresh session in plan mode: "Read @docs/specs/<file>.md. Without planning yet, list (1) every question you'd still need answered, (2) every file you'd expect to change that isn't in Files and interfaces, (3) any acceptance criterion with a wrong implementation that would satisfy it." Fix the spec until all three lists are empty or deliberately accepted. Finally, add a deny rule for one boundary that matters.

Show a reference solution

Expect list (2) to find the shared registration file (here src/jobs/registry.ts) or a types file. Add it to the spec or mark it as allowed. Expect list (3) to find a boundary gap such as "exactly 10,000 rows". Add the boundary case. Typical remaining questions are about rollout (feature flag? which customers first?), which belongs in the spec as a decision or an explicit non-goal. For the deny rule, a good candidate is Edit(/db/migrations/**) in .claude/settings.json. Verify it by asking Claude to touch a migration and confirming the denial.

Key takeaways

  • Write specs for a cold reader: name files and interfaces, state what's out of scope, and end with an end-to-end verification step.
  • Each section of a structured brief prevents a specific failure. Score briefs on completeness, then review the decisions separately.
  • Negative examples target the tempting wrong solutions. Pair every "don't" with an "instead" and a reason, and point at real files.
  • Acceptance criteria are Given/When/Then with numbers, boundaries and failure behavior. Ask Claude for a wrong implementation that would pass each one.
  • State boundaries in the spec and enforce the important ones: deny rules, worktrees, the sandbox, headless caps. Use bypassPermissions only in an isolated container or VM.

Decomposition

A spec says what must be true at the end. Decomposition decides how to get there: in what order, with which pauses for review, tracked how, and done by whom. In Claude Code the main tool is plan mode, where Claude researches and proposes without editing, and you review, edit and approve. Around it sit dependency ordering, checkpoints (Claude Code's automatic ones and the human gates you design), task lists that survive compaction, and delegation to subagents.

Plan Mode

Plan mode "tells Claude to research and propose changes without making them. Claude reads files, runs shell commands to explore, and writes a plan, but does not edit your source." Edits stay blocked until you approve the plan (the one exception is an interactive terminal session started with bypass permissions available). It's the permission mode plan, and you enter it in three ways:

  • /plan [description] enters plan mode from the prompt, and with a description it starts on that task right away. This is the reliable way, because from auto mode (the default start mode on v2.1.283+) reaching plan with Shift+Tab takes three presses (auto → Manual → accept edits → plan). Older advice says "press Shift+Tab twice", which is true only when starting from Manual.
  • Shift+Tab until the status bar shows ⏸ plan mode on. Press it again to leave plan mode without approving.
  • claude --permission-mode plan to start a session in it, or "defaultMode": "plan" in .claude/settings.json to make it the project default for terminal sessions.

What happens during planning. Reads run freely. Shell commands depend on the session: with auto mode available and useAutoModeDuringPlan on (the default), the auto mode classifier reviews each command instead of prompting you. Without it, anything outside the built-in read-only set prompts. So plan mode isn't strictly read-only for the shell, but it never edits source. When Claude needs to research the codebase, it delegates to the built-in Plan subagent, so exploration output stays in a separate context window. When the plan is ready, Claude calls ExitPlanMode, which "presents a plan for approval", and you choose:

OptionEffect
Yes, and use auto modeApprove and implement in auto mode. It reads "Yes, auto-accept edits" when auto mode isn't available to the session, and "Yes, and switch to BYPASS PERMISSIONS (no further prompts) for this session" when the session started with bypass permissions enabled.
Yes, manually approve editsApprove and review each edit individually.
No, keep planningStay in plan mode and tell Claude what to change. This is where your review goes.
Yes, clear context and … (optional)Appears first when showClearContextOnPlanAccept is true. Approves, clears the planning context, and implements from the plan alone.

Press Ctrl+G at the approval prompt to open the plan in your text editor and edit it directly. Plan files are written to ~/.claude/plans by default, and plansDirectory (a path relative to the project root) moves them, for example into the repo so plans can be reviewed like code. Approving a plan also gives the session a generated title. If the context is later compacted, the plan is re-injected.

One planning round from /plan to approval, replayed line by line in an illustrative terminal (not a captured session). The review is the loop at steps 6 and 7: "No, keep planning" with your feedback, or Ctrl+G to edit the plan yourself. When auto mode isn't available, the first approval option reads "Yes, auto-accept edits".

How to review and edit a plan

A plan is the cheapest point to catch a wrong approach. A bad step costs one sentence of feedback now, or a rewrite later. Review it against the spec, not against your taste:

  1. Coverage: does every acceptance criterion map to at least one step that implements it and one that verifies it?
  2. Scope: does every file the plan touches appear in the spec's Files and interfaces list? Is anything from Out of scope creeping in?
  3. Order: are characterization tests before the refactor, the refactor before the new path, and the routing change after the job exists?
  4. Verification per step: does each code-changing step say how it will be checked (which test, which command)?
  5. Assumptions: is there an Assumptions section, and does any unconfirmed assumption change the design?
  6. Risky steps: are push, migration, deletion and deploy steps either absent or marked as human checkpoints?
  7. Constraints and decisions: does any step contradict an ADR or constraint (a new dependency, emailing the file)?

Then choose how to respond. Small, specific corrections are fastest with Ctrl+G: reorder two steps, delete the out-of-scope one, add a verification line. Corrections that need Claude to rethink (a different approach, a missed constraint) go through No, keep planning with a numbered list of findings, so Claude revises the plan rather than patching your edits. If the plan is wrong at the root, that's information about your spec: fix the spec and re-plan.

Pick a plan Claude might produce for the Tally spec. The reviewer runs the seven checks above and pins each finding as a comment in the margin, beside the step it concerns. Each comment has a fix you can apply, the way you would with Ctrl+G, and the plan updates in place. The feedback box assembles the comments still open: it's what you'd paste after choosing No, keep planning.

What you build: a deterministic reviewer that reads a plan in Markdown (like the files plan mode writes to ~/.claude/plans or your plansDirectory) and the brief it implements, builds a criterion-by-step coverage matrix, and flags scope violations, steps that contradict a negative example or boundary, edits to files that don't exist, unrequested work, vague steps and plans that never run a command. It ends with a verdict named after plan mode's approval options and, for "No, keep planning", the feedback text to paste. It runs offline on two sample plans against the strong discount-codes brief. --real asks claude -p for a plan in plan mode with read-only tools on a temp copy (costs money; capped by --max-budget-usd).

cd labs && python3 delivery-2/plan_review.py
python3 delivery-2/plan_review.py --plan ~/.claude/plans/<file>.md --brief my_brief.md --repo /path/to/repo

What to observe: the good plan maps AC1–AC5 to steps that each carry a command and gets "Yes, and use auto mode". The drifting plan reads like a reasonable refactor, but the review finds it changes the DISCOUNTS keys (ruled out by a negative example and AC4), edits a file that doesn't exist and is outside scope, touches TAX_BPS (a boundary), and never runs a test. Verdict: "No, keep planning". Note how coverage isn't satisfaction: the step that touches DISCOUNTS, AC4's subject, contradicts the criterion, so the matrix marks it with an x.

Open the lab walkthrough

When to skip the plan. Plan mode adds overhead: if you could describe the diff in one sentence, skip the plan. Plan when you're uncertain about the approach, the change spans multiple files, or you don't know the code.

Plan mode internals: tools, models, and where plans keep their blocks

Tools. EnterPlanMode lets Claude switch into plan mode on its own "to design an approach before coding" (no permission needed). ExitPlanMode presents the plan and requires your approval. It takes no specifier in permission rules. Subagents normally don't get EnterPlanMode or ExitPlanMode, except that ExitPlanMode stays available to a subagent whose permissionMode is plan.

Where blocks hold. "Plan mode keeps its blocks wherever Claude Code runs without an interactive terminal, including non-interactive runs with -p, Agent SDK sessions, and conversations in the VS Code extension's chat panel." In an interactive terminal session started with bypass permissions available, plan mode's blocks aren't enforced: Claude is instructed not to edit, but nothing stops it. Don't combine the two if you rely on plan mode as a gate.

Shell commands while planning. useAutoModeDuringPlan has user, local or managed scope. "A repository can't turn it off for you." Set it to false to get a prompt for every command outside the read-only set during planning. The auto mode classifier also reviews SendMessage calls in plan mode while it's reviewing commands.

Model split. The opusplan model setting "uses opus during plan mode, then switches to sonnet for execution". It's a cost lever when planning needs the strongest reasoning and execution doesn't. Use opusplan[1m] if you need 1M context in both phases where the models don't default to it. Plan mode can switch models without opusplan too: the model-config docs describe "a Haiku session that would normally upgrade to Sonnet in plan mode", so a plan-mode run started on haiku to save money may plan, and bill, on Sonnet. Check the result event's per-model usage.

Plan approval never times out. Even with askUserQuestionTimeout set, "permission prompts, including plan approval, never auto-resolve on idle." An unattended plan-mode session waits for you. Sources: permission-modes, tools-reference, model-config.

Dependencies

Steps have dependencies: the job can't be wired into the route before it exists, and the refactor shouldn't start before characterization tests pin the current behavior. Writing them down turns a plan from a list into a graph. That tells you three things a list hides: the critical path (the longest chain, which bounds how fast the work can go however you parallelize), which steps are independent and could run in parallel, and where parallel branches must join (merge points).

Ask for the graph. "For each step in the plan, list the steps it depends on and the files it changes. Mark steps that could run in parallel because they share no files." The "share no files" part is the practical test of independence. The official cloud-sessions guide says "Split parallel tasks along file boundaries, merge the branches in a sensible order." Two steps that both edit src/jobs/registry.ts aren't independent, whatever the plan says.

Tally's plan as beads on strings, on an axis of units. Each step is a bead as long as its work. Pull the end and the chain that bounds the finish goes taut (in the accent) while every other string sags by its slack. The critical path, the longest chain of dependencies, keeps a small accent tick in every strategy: in a fan-out it is the taut string, while in one session the session's serial work bounds the finish instead. Knots are merge points, where strings join, and a file conflict shows as two strings caught on the same file bead. The strategy decides how the strings are threaded. One session puts every bead on one string; subagents hang the delegated beads (hatched) on side strings; a worktree fan-out gives every dependency its own string. Click a bead to delegate it, and the checkpoints are hands holding every string at that moment. Units of work and token multipliers are illustrative. The structure (the critical path, conflicts, merge points) is what to read.

Common ordering rules for product changes, which you can put in your planning prompt or CLAUDE.md:

  • Characterize, then refactor, then change behavior. Each step keeps the previous one's tests green.
  • Producers before consumers: the job before the route that enqueues it, the storage helper before the job that uploads.
  • Shared registration files (routers, registries, DI containers) are serialization points. Do them in one step, or last.
  • Reversible before irreversible. Deletions of old paths come after the new path is verified.

Checkpoints

"Checkpoint" means two different things in Claude Code work, and you need both.

Claude Code's automatic checkpoints. "Every prompt you send that starts a turn creates a new checkpoint." Claude Code snapshots files before its edits, and you open the rewind menu with Esc Esc on an empty prompt or /rewind (aliases /checkpoint, /undo). It offers to restore code and conversation, the conversation only, or code only, or to summarize from a point. Checkpoints persist across resume, so you can try a risky approach and rewind if it fails. Their limits are the important part:

  • Bash changes are tracked only on files Claude already edited with its file tools: "A file that only Bash commands changed isn't tracked and stays as it is." So a file that only a codegen script or npm install touched isn't undone by rewind, while a sed -i on a file Claude had already edited is.
  • Subagent edits usually aren't restored. For every subagent except a foreground forked skill (context: fork with background: false), "rewinding restores only the files Claude had already edited in your conversation. The subagent's edits to other files stay, so use version control, such as Git, to revert them."
  • Remote side effects (a pushed branch, a migrated database, a sent notification) are never undone.
  • "Checkpoints are separate from git" and "are designed for quick, session-level recovery". Keep using git for history.

Human checkpoints you design. These are pauses in the plan where Claude stops, shows evidence and waits: after the characterization tests and refactor (behavior unchanged?), before the routing change goes live behind the flag, before any irreversible step. Write them into the plan as explicit steps:

Plan file (excerpt: one step)

3. Extract the row generator from src/api/exports.ts into src/exports/invoiceCsv.ts.
   Verify: npm test -- test/exports (all characterization tests green).
   CHECKPOINT: stop, show the diff stat and test output, and wait for "continue".
   Commit: "refactor(exports): extract row generator (no behavior change)".

Commit after each verified step. Commits are durable checkpoints that cover what /rewind can't (files only Bash changed, subagent edits) and give a reviewer small, bisectable steps. The two kinds work together: /rewind for exploring within a step, commits and human gates between steps.

Pitfall: rewinding a Bash changeClaude ran npm run db:gen, which regenerated src/db/schema.gen.ts, and then you rewind to before it. The conversation and Claude's own file edits go back, but the regenerated file stays as it is: only a Bash command ever changed it, so it was never tracked. Use git status after any rewind that crosses a Bash step, or work in a worktree you can discard.

Task Lists

A task list is the plan in a form that tracks progress: pending, in progress, done. Claude Code has two kinds, and on current models the default has changed.

Built-in task tools. TaskCreate, TaskGet, TaskList and TaskUpdate (or the older TodoWrite when CLAUDE_CODE_ENABLE_TASKS=0) feed the checklist you toggle with Ctrl+T, which shows up to five tasks and persists across compaction. Since v2.1.268 these tools are provided by default only on Opus 4.7, Sonnet 4.6, Haiku 4.5 and earlier models. The docs explain: "On newer models, Claude keeps track of multi-step work without a written checklist, and the tools' definitions and reminders take up context." On Opus 5.5, Sonnet 5.5 or Fable the list stays empty unless you opt in:

CLAUDE_CODE_ENABLE_TODO_TOOLS=1 claude          # task tools on any model and provider
# share one list across sessions (~/.claude/tasks/export-async/); needs the task tools
CLAUDE_CODE_ENABLE_TODO_TOOLS=1 CLAUDE_CODE_TASK_LIST_ID=export-async claude

Background and cloud sessions provide the tools on every model regardless. Subagents get them only when your session has them.

A task file in the repo. For work that spans sessions or people, a TASKS.md checklist is often better: it's reviewable, committed and diffable, and it survives anything. Anthropic's Opus 5.5 guide recommends exactly this ("Keep a checklist in TASKS.md"), because a list in a file outlives compaction and session boundaries. Add an evidence column, so each tick has a reason:

TASKS.md

# TASKS: export-async (spec: docs/specs/export-async.md)
| # | Task | Depends | Status | Evidence |
|---|---|---|---|---|
| 1 | Characterization + golden header tests | – | done | test/exports/characterization.spec.ts: 6 passed, 1 failing (bug, expected) |
| 2 | Extract row generator | 1 | done | commit 3f2a91c; npm test -- test/exports: 7 passed |
| 3 | exportInvoices job + registry | 2 | in progress | |
| 4 | Signed link via src/storage | 2 | pending | |
| 5 | Route by row count (≤10k direct) | 3, 4 | pending | |
| 6 | In-app notification + failure path | 3 | pending | |
| 7 | Async, boundary and failure tests (120k fixture) | 5, 6 | pending | |

For long or unattended runs this file is the state that carries over between sessions (work "on only one feature at a time", keep progress in files, commit often, as Anthropic's long-running harnesses post recommends). Progress tracking and stage splitting are covered in core-3, Tasks.

Delegation

Delegation means handing a step to a subagent, a worker that runs "in its own context window with a custom system prompt, specific tool access, and independent permissions" and returns a summary. In decomposition, you're deciding which steps to delegate and what to hand over.

Good candidates are steps that read a lot and return a little, or that benefit from a fresh view:

  • Investigation: "use a subagent to investigate how our auth system handles token refresh" (common workflows) keeps the reading out of your main context.
  • Verification and review: the best-practices review prompt, pointed at the spec: use a subagent to review the diff against the spec, check every requirement is implemented and the listed edge cases have tests, report gaps that affect correctness and skip style. A fresh reviewer "hasn't seen your reasoning" (best practices).
  • Independent units: file-disjoint steps in the dependency graph. For large mechanical changes, /batch <instruction> "decomposes the work into 5 to 30 independent units, and presents a plan", then runs one background subagent per unit, each in its own worktree.

What a subagent receives. A regular (non-fork) subagent "doesn't see your conversation history, the skills you've already invoked, or the files Claude has already read". It gets the delegation message Claude writes, the CLAUDE.md hierarchy (except Explore and Plan) and a git status snapshot. So the decomposition must produce a delegation brief per step: objective, inputs (the spec section, the files), boundaries, output format, and how to report failure. Explicit rules that must reach the subagent go in that message. Forks are the exception: a fork "inherits the entire conversation so far" and receives "the main conversation's exact tool pool". Fork mode is on by default, and "Claude can start a fork on its own", so check which kind ran before assuming isolation. Briefs, handoff contracts and result formats are taught in depth in agents-4, Delegation.

.claude/agents/export-verifier.md

---
name: export-verifier
description: Verifies an export change against its spec in a fresh context. Use
  proactively after implementation steps that touch src/exports or src/jobs.
tools: Read, Bash
model: sonnet
---
You verify, you don't fix. Given a spec path and a diff range:
1. Map each acceptance criterion to the test that covers it (file:line) or "none".
2. Run `npm test -- test/exports` and report the exit code and failing test names.
3. Run `git diff --name-only <range>` and list files outside the spec's
   "Files and interfaces".
Report as a table: criterion | covered by | result. Report only gaps that affect
correctness or the stated requirements.

That's .claude/agents/export-verifier.md. The description is how Claude decides to delegate, and "use proactively" encourages it. The tools list is deliberately short: with only Read and Bash, the verifier searches and runs tests through Bash, and without Edit or Write it can't "fix" the thing it's grading.

Pitfall: delegating the questionsAskUserQuestion "is not currently available in subagents" spawned through the Agent tool (forks, which keep the main tool pool, are the exception). A regular subagent that hits an ambiguity guesses, or returns early. Resolve the interview before delegating, and have delegation briefs say "if X is unclear, stop and report it" instead of "ask".

Cost. "Running several sessions or subagents at once multiplies token usage." Subagents have run in the background by default since v2.1.198, and their requests count toward the same usage limits as the main conversation. Agent teams (experimental, behind CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1) use "approximately 7x more tokens than standard sessions when teammates run in plan mode." Delegate to save context or gain an independent view, not as a default.

Choosing granularity: when decomposition hurts

Too coarse. One step called "implement async export" gives you no checkpoint, no per-step verification, and a diff too big to review. The plan reviewer can't map criteria to steps because there's only one step.

Too fine. Fifteen steps of "add import", "add type" each carry coordination overhead: more checkpoints to answer, more commits, and, if delegated, a subagent that re-reads the same files each time. Each subagent pays its own startup context (system prompt, CLAUDE.md, tool definitions). That's why the toy model in the graph widget charges a per-subagent overhead.

Coupled steps parallelize badly. Anthropic's multi-agent research post (2025) observed that domains with many dependencies between agents are a poor fit for multi-agent systems, and that most coding tasks have fewer truly parallelizable parts than research. Tooling such as /batch, dynamic workflows and agent teams has made coordination much easier since, but two steps that must agree on an interface still need to agree on it first. Define the interface in an earlier step (a types file, a function signature, a test) and let both depend on it.

A heuristic. A step is the right size when (1) it has one verification you can name, (2) its diff fits in one review sitting, and (3) you'd be willing to approve it without having seen the next step. Nesting is capped: subagents can spawn subagents "up to three layers below the main conversation" (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH), with up to 20 running concurrently by default (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS, v2.1.217+).

Exercise: have Claude decompose, then audit it

With a spec from the previous topic, run /plan Implement @docs/specs/<file>.md. For each step give: depends-on, files changed, how it will be verified, and whether it needs a human checkpoint. End with an Assumptions section. Review the plan with the seven-point checklist. Use Ctrl+G for at least one direct edit and No, keep planning for at least one finding. After approval, ask Claude to write the plan as TASKS.md with an evidence column, and delegate the verification step to a subagent like export-verifier.

Show a reference solution

Typical first-draft findings: one or two acceptance criteria without a verifying step (usually boundaries and failure paths), a shared file (a registry, a router) edited in two "parallel" steps, and no checkpoint before the behavior change. Fix order and checkpoints yourself with Ctrl+G, and send missing coverage back as feedback ("criteria 2 and 4 have no verifying step; add tests for 10,000/10,001 rows and for a job that fails after retries"). The finished TASKS.md should match the plan's dependency structure. The verifier's report should list every criterion with a covering test. If any row says "none", that's a gap the implementer missed, and the verifier did its job.

Key takeaways

  • Plan mode researches and proposes without editing source. Enter it with /plan (from auto mode, Shift+Tab takes three presses). Review against the spec, edit small things with Ctrl+G, and send substantive findings through "No, keep planning".
  • Review plans for coverage, scope, order, per-step verification, assumptions, risky steps and constraint violations. A plan that's wrong at the root means the spec needs fixing.
  • Write dependencies and changed files per step. File overlap, not the plan's wording, decides what can run in parallel. Shared registration files are serialization points.
  • Claude Code's checkpoints (/rewind) don't cover files that only Bash changed, most subagent edits, or remote side effects. Add human checkpoints and commits between verified steps.
  • On current models the built-in task tools are off by default (v2.1.268+). Opt in with CLAUDE_CODE_ENABLE_TODO_TOOLS=1, or keep a TASKS.md with an evidence column.
  • Delegate investigation, verification and file-disjoint units. Subagents start without your conversation and can't use AskUserQuestion, so brief them completely and resolve questions first.

Evaluation

The last translation step is deciding, before the work starts, how you'll judge it. That means what you expect back, what quality bar applies, what counts as evidence, and which tests encode the spec. Evaluation designed up front changes the work itself: a session that knows it must show test output runs the tests, and a suite with boundary cases rules out boundary bugs. Evaluation designed afterwards only measures how far off the work landed. This topic builds the evaluation half of the brief. Delivery-4 covers running it on what ships.

Expectations

Expectations are what you expect to receive when Claude finishes: the deliverables (a diff, new tests, an ADR draft, a PR description), the report, and the stopping behavior. Stating them is cheap, and it removes a common frustration: work that's done but delivered in a form you have to reconstruct.

Ask for a final report with a fixed shape. Put it in the spec or a project skill so every task ends the same way:

CLAUDE.md or the spec (excerpt: final-report section)

## Final report (end every task with this)
1. Summary: what changed and why, in 3 sentences.
2. Acceptance criteria: table of criterion | test (file:line) | result.
3. Evidence: each command you ran last, with its exit code and the relevant output
   lines (failing test names, counts). No "should pass".
4. Scope: output of `git diff --stat` against the base branch.
5. Not done / open risks: anything skipped, assumed or unverified, and where you looked.

The last item matters most. It gives Claude a sanctioned place to say "I couldn't verify the 120k fixture locally" instead of rounding it up to success. Anthropic's Opus 5.5 guide frames the whole idea in one line: "Say what 'done' looks like and when you want it to stop and ask. Then let it work."

Decide how hard the expectations gate the stop. The best-practices guide describes a ladder, from "Claude deciding for itself all the way to Claude Code enforcing it":

The session scene is drawn once: Claude's context window with the author's intent, the transcript, the tools, the files on disk and the exit codes of the checks. Under it are the four checkers, left to right: more setup, less attention needed. With nothing chosen, each part says who can see it. Hover or focus a checker and its sightlines light what it sees; a dashed line is a partial view, such as the /goal evaluator, which can only judge what Claude has surfaced in the conversation. The further right, the less the checker shares the author's view. Climb as unattended time grows. The prompt version "works for any task, today, with no setup". /goal "matters for long background runs", and a Stop hook "is enforced by Claude Code (the harness)". A verification subagent or /code-review adds a reviewer that never saw your conversation. Source: best practices.

Quality Bars

A quality bar is the standard a change must meet beyond "it works": test coverage of new behavior, error handling, performance budgets, readability, no stray TODOs. The right bar depends on the work. A spike to learn whether streaming to S3 works needs none of it, while a billing change needs all of it. If you don't state the bar, Claude picks one, and models tend to over-engineer unasked-for robustness in some places and skip the boring parts (failure paths, boundary tests) in others.

State the bar per change type in CLAUDE.md, and override it in the spec when needed:

CLAUDE.md (excerpt: quality-bar section)

## Quality bar
- Production changes: every acceptance criterion has a test; failure paths are tested;
  no new `any`; user-facing copy goes through src/i18n/.
- Spikes (branch prefix spike/): no tests required; leave a README note with findings.
- Never: commented-out code, TODOs without a ticket number, suppressed lint rules.

Effort is a lever for the bar, not for the approach. Effort levels (/effort low|medium|high|xhigh|max; medium is the default on Opus 5.5) modulate, in the words of a Claude Code team member, "how much verification and edgecase testing Claude did and how much of its own judgement it used". The same post adds the limit: "increasing effort tends to reduce failures due to missing edgecases... but does not fix when the model has the wrong approach" (Spending your effort). Raise effort for edge-case-heavy work. Fix a wrong approach in the plan.

Review against the bar with the right tool.

ConcernClaude Code tool
Correctness bugs in the diff/code-review (bundled skill; reviews in a fresh subagent; --fix applies findings)
Cleanup: reuse, simplification, efficiency, abstraction level/simplify (four parallel review agents; "doesn't look for correctness bugs")
Does the running app actually do it?/verify, which you invoke (builds, runs and observes the app "rather than relying on tests or type checks"; since v2.1.215 "/verify runs only when you invoke it")
Does the diff meet this spec?A subagent prompted with the spec and the criteria (like export-verifier above)
Pitfall: the reviewer that always finds something"A reviewer that's asked to find problems will always find something. 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", and cap review rounds. The Claude Code team learned this the hard way: one PR "went through more than fifty rounds of review and fixes overnight", so they now cap it: "After three rounds, the reviewer asks the author to step back and reconsider the approach" (How the Claude Code team does code review). The quality bar is what turns a review finding into "must fix" or "optional".

Evidence Requirements

Evidence is output that lets someone who wasn't there confirm a claim: the command and its exit code, the failing test names, the line count of the generated file, a screenshot. An assertion is a claim without that output: "tests pass", "I verified the fix", "should work now". The best-practices guide: "ask Claude for evidence: the command it ran and its output, or the screenshot. 'All tests pass' on its own tells you very little, and reading the output is faster than rerunning the check yourself. For a session you weren't watching, it's also the only evidence you have."

Evidence has a mechanical role too. The /goal evaluator and a prompt-based Stop hook can only judge what's in the conversation. So "print the exit code" isn't just politeness. It's the difference between an evaluator that can confirm the condition and one that has to take Claude's word for it.

Each line comes from a plausible end-of-task report. Classify it, then read why. One rule: a claim is evidence only if a reader could check it from what's shown, without re-running anything.

Write evidence requirements per criterion. For each acceptance criterion, say what evidence proves it, and prefer evidence that's cheap to produce and hard to fake:

CriterionRequired evidence
≤10k rows unchangedGolden header test and the 500-row test passing; test names in the output
10,000 vs 10,001 routingTwo boundary tests passing, by name
120k fixture completesTest output plus wc -l of the stored file: 120001
Failure pathTest that forces two failures and asserts the notification and the absence of a file
Scopegit diff --name-only output
Works in the running appA curl -w '%{http_code}' transcript Claude produces, showing 202, or a /verify result (you invoke it, so not in an unattended run)
Step through a seven-turn goal run on the Tally change. After each turn the toy evaluator checks the condition's clauses against what the transcript surfaced, like the real one, which doesn't run commands or read files; the clause whose status changed this turn is marked. Switch scenarios to see how a vague condition, hidden output, background work or an impossible clause changes the verdicts.
Why "the agent grading itself" fails, and the cheapest independent check

Self-assessment bias. The session that wrote the code has the strongest prior that it works. It remembers its intent, not just the result. Anthropic's long-running-apps harness work separates a generator from an evaluator for this reason (Harness design for long-running application development). The best-practices guide says the same about review: /code-review uses "a fresh subagent that never saw your conversation", so "It isn't swayed by the reasoning that produced the code." /goal builds this in at low cost: "completion is decided by a fresh model rather than the one doing the work".

The evaluator's blind spot. That fresh model sees only the transcript. It's independent of Claude's reasoning but dependent on Claude's reporting. Two habits close the gap. Require raw output, not summaries ("print the exit code and the failing test names"). And add one deterministic check that doesn't depend on the transcript at all: a command-type Stop hook that runs the tests itself (next concept). The hook can't be fooled by a confident sentence.

Cost. Evidence is also the cheapest verification for you. A report with test names, exit codes and a diff stat takes seconds to review. A report with assertions means re-running everything, which is the "makes you the test suite" failure the session started with.

Tests

Tests are the acceptance criteria in executable form, and the strongest evidence Claude can produce. Written before the code, they're also a spec that can't be misread. The best-practices guide's central advice is "Give Claude something it can run that comes back pass or fail", and a test file is the first check it lists. You can go further and split writer and tester: one session writes the tests, another writes code to pass them.

Test-first with Claude Code.

  1. From the acceptance criteria, have Claude write the tests and run them. They should fail for the right reason (missing behavior, not a syntax error). Commit them.
  2. Freeze them. Add "no test in test/exports/ is modified" to the /goal condition, or for a hard guarantee a temporary deny rule Edit(/test/exports/**) in .claude/settings.local.json while the implementation runs.
  3. Implement until they pass. A fresh session works well, since it can't "remember" what the tests were supposed to mean.

Are your tests strong enough? A test suite is only as good as the wrong implementations it rejects. Happy-path tests (the kind Claude writes unprompted) pass for many wrong implementations. Boundary and failure tests are what catch them. The widget below is a tiny mutation test: each "mutant" is a plausible wrong implementation of Tally's export routing, and you pick which tests to include.

Toggle tests on and off. A mutant survives if every selected test still passes against it, and its row is marked. Survivors are bugs your suite would ship.

Keep Claude on the test bar with a Stop hook. /goal checks a condition by reading the transcript. A command-type Stop hook runs the check itself, in every session in its scope, whatever Claude says. The common version, with a stop_hook_active early exit, nudges Claude to run the tests before finishing: it blocks once, and the next stop goes through. The version below is a bounded gate: it keeps blocking while the export tests fail, up to five times per session, counted in a state file. Neither is the gate of record. CI is.

#!/usr/bin/env bash
# .claude/hooks/require-export-tests.sh: keep Claude working while test/exports fails,
# for at most MAX_BLOCKS blocked stops per session. CI stays the real gate.
input=$(cat)
MAX_BLOCKS=5
PATHS="src/exports src/jobs src/api/exports.ts"
# Gate only when export code differs from main: committed on this branch, uncommitted, or new.
if git diff --quiet main...HEAD -- $PATHS && git diff --quiet HEAD -- $PATHS \
   && [ -z "$(git ls-files --others --exclude-standard -- $PATHS)" ]; then exit 0; fi
# Our own counter: stop_hook_active alone would allow one retry, and Claude Code's
# 8-continuation cap resets on every tool call, so it doesn't bound a fix-and-retry loop.
sid=$(jq -r '.session_id' <<<"$input")
state="${TMPDIR:-/tmp}/export-gate-$sid"
n=$(cat "$state" 2>/dev/null || echo 0)
if OUT=$(npm test --silent -- test/exports 2>&1); then rm -f "$state"; exit 0; fi
if [ "$n" -ge "$MAX_BLOCKS" ]; then
  rm -f "$state"   # give up: allow the stop, and tell the user why
  jq -n --arg m "Export tests still failing after $MAX_BLOCKS blocked stops; allowing the stop. CI will catch it." '{systemMessage: $m}'
  exit 0
fi
echo $((n + 1)) > "$state"
echo "Export tests are failing (block $((n + 1)) of $MAX_BLOCKS). Fix them before finishing. Last lines:" >&2
echo "$OUT" | tail -n 20 >&2
exit 2   # exit 2 on Stop: Claude receives stderr and keeps working

.claude/settings.json (excerpt: merge this "hooks" key into the settings file above, which already holds the permissions; pasting it over the file would drop them)

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/require-export-tests.sh", "timeout": 300 }
        ]
      }
    ]
  }
}

Register it in .claude/settings.json and make the script executable. Exit 2 on a Stop hook routes stderr to Claude as the reason to continue (the JSON alternative is {"decision": "block", "reason": "..."}). Four details decide how much this hook can promise:

  • Nudge or gate. stop_hook_active is true while Claude is continuing because a stop hook blocked. A script that exits 0 when it's set lets Claude stop on its second attempt even if the tests still fail, which makes it a one-time nudge. That's the right choice for reminders ("run the formatter before finishing").
  • Bound it yourself. Claude Code overrides a Stop hook only "after it blocks eight times in a row with no tool call from Claude in between", and the count resets every time Claude calls a tool. A Claude that keeps editing and re-running tests is never released by that cap, so a gate needs its own limit: the state-file counter above, and --max-turns and --max-budget-usd in headless runs. A turn clause in a /goal condition doesn't help here: when the evaluator clears the goal, this hook still blocks.
  • Gate on the branch diff, not the working tree. You commit after each verified step, so a git status check would skip the tests as soon as Claude commits. Comparing against main keeps the check on until the branch passes.
  • It fails open. A Stop hook that crashes or times out lets the stop through, and onFailure has no effect on Stop. That's one more reason CI, not the hook, is the gate that decides what merges.

Test the script while a test fails: echo '{"session_id":"t1","stop_hook_active":true}' | .claude/hooks/require-export-tests.sh; echo $? should print the failure lines and 2. Run it six times: the sixth run prints the systemMessage JSON and exits 0.

Hooks run your code with your permissions"Command hooks execute shell commands with your full user permissions." A committed Stop hook runs for everyone who trusts the repo, and in -p and SDK sessions project hooks run "in a folder you've never trusted". Keep gate scripts small, readable and reviewed. They're a quality gate, not a security boundary. Gates at scale (hooks as gates, CI gates, release blockers) are delivery-4's Quality Gates topic.
Stop hook vs /goal vs CI: which gate for which job
/goalCommand Stop hookPrompt Stop hookCI
Who decidesSmall fast model reading the transcriptYour script (exit code / JSON)A model reading the hook inputYour pipeline
Can be fooled by assertionsYes, if the condition is vague or output is hiddenNo: it runs the checkYes, like /goalNo
Holds across retriesUntil met, judged impossible, or stalledWith a stop_hook_active early exit, one nudge; as a gate, as long as your own counter allows; fails open if it crashesSame choice as command hooksYes: the gate of record
ScopeOne sessionEvery session in the settings scopeEvery session in scopeEvery push or PR
SetupOne lineScript + settingsSettings onlyWorkflow file
Best forTask-specific DoDRepo-wide "tests must pass" barJudgment checks ("are all requested tasks complete?")The authoritative merge gate

Cost and latency. A Stop hook runs at the end of every turn, including "what does this function do?" questions. The script above skips the suite only when the branch has no export changes, so on the feature branch every turn runs the export tests, and while they fail even a question-only turn is blocked (up to the counter's limit). Narrow the gate if that bites: record in the same state file that this session edited export files and check that first. A PostToolUse hook on Edit|Write can record file edits, but it never sees a sed -i or a codegen run. For Bash calls the hook can read tool_response.bashEditDiff (v2.1.269+, public beta), but by default that list is recorded "only in auto mode and bypassPermissions mode, and only when Claude Code directs Claude to edit files through Bash". bashEditDiffEnabled: true records it in every mode, but only from user, managed or --settings JSON; a true in the repo's .claude/settings.json "can't turn the recording on". The docs also say to use the list "to find what to review, not to enforce a policy". So if you narrow the gate, fail toward running the tests: treat any Bash call without a diff as one that may have edited export files. Keep hook checks to seconds. A full suite belongs in CI. Command hooks default to a 600-second timeout. onFailure (v2.1.295+) has no effect on Stop, so a crashing hook script doesn't block the stop.

Prompt hooks can say "impossible". A type: "prompt" Stop hook returns {"ok": false, "reason": "..."} to keep Claude working, and can add "impossible": true "to mark the condition as one that can never be satisfied, in which case Claude Code allows the stop". That's the same three-way verdict /goal uses, because /goal is built on it. Sources: hooks: Stop, prompt-based hooks.

Exercise: a test-first handoff

For a small feature in your repo: (1) in one session, have Claude turn the acceptance criteria into failing tests, run them, and commit. (2) Ask it to describe three wrong implementations that would pass those tests, and add a test that kills each one. (3) In a fresh session, set /goal <tests> exit 0; no file under <test dir> is modified; print exit codes; or stop after 20 turns and let it implement. (4) Install the bounded Stop hook above for your test command and confirm it blocks a stop while a test fails, and gives up after its limit.

Show a reference solution

Step (2) is where most of the value is. Expect at least one surviving wrong implementation at a boundary (≤ vs <) and one at a failure path. In step (3), check the evaluator's reasons with Ctrl+O. A good run shows "not yet met" verdicts citing specific failing tests, then "met" once exit codes are printed. If the goal is met suspiciously early, your condition is too vague or Claude summarized instead of printing output. For step (4), verify with echo '{"session_id":"t1","stop_hook_active":true}' | ./hook.sh; echo $? while a test fails: expect 2 and the failure lines on stderr. If you get 0 on the first run, the script has a stop_hook_active early exit and is only a nudge. Keep CI as the gate that decides merges.

Key takeaways

  • State expectations up front: deliverables, a fixed final-report shape with an evidence section, and a sanctioned "not done / open risks" section.
  • Set the quality bar per change type. Effort raises edge-case diligence but doesn't fix a wrong approach. Use /code-review for correctness, /simplify for cleanup, /verify (you invoke it) for the running app, and a spec-aware subagent for "does it meet this spec".
  • Require evidence (commands, exit codes, test names, counts), not assertions. The /goal evaluator can only judge what Claude surfaces.
  • Write tests from acceptance criteria first, freeze them during implementation, and strengthen them until plausible wrong implementations fail.
  • A command-type Stop hook with a stop_hook_active early exit nudges Claude to run the tests before finishing. For a bounded gate, drop the early exit and count blocks in a state file, because the 8-continuation cap resets on every tool call. Keep it fast. It fails open, so CI stays the real gate.

Session wrap-up

You started with one sentence, "CSV export is broken for big customers. Make it work.", and turned it into a set of Claude Code artifacts, each of which removes one class of failure before code exists:

TopicArtifactWhere it livesFailure it prevents
IntentDoD as a /goal condition; impact, before/after table, non-goalsSpec + sessionStopping when it "looks done"; the wrong tradeoff
ContextProduct facts, map, decisions index; path-scoped rules; deny/ask rulesCLAUDE.md, .claude/rules/, .claude/settings.json, docs/decisions/Re-litigating ADRs; wrong conventions; forgotten constraints
RequirementsAssumption ledger; AskUserQuestion interviewPlan + specSilent defaults in the design
SpecificationsStructured brief with don't/instead, ACs, boundariesdocs/specs/export-async.mdCold-reader gaps; tempting wrong solutions; scope creep
DecompositionReviewed plan, dependency order, checkpoints, TASKS.md, verifier subagentPlan mode, repo, .claude/agents/Wrong order; unreviewable diffs; context bloat
EvaluationFinal-report shape, quality bar, evidence table, tests, Stop hookCLAUDE.md, spec, test/, .claude/hooks/Done by assertion; weak tests; unattended drift

The assembled kickoff

With the spec from Structured Briefs committed, the whole execution is three commands. Everything Claude needs is in files, so any of these can run in a fresh session, a worktree or the cloud:

# 1. Plan against the spec, in an isolated worktree (review with the seven checks; Ctrl+G to edit)
claude --worktree export-async --permission-mode plan \
  "Read docs/specs/export-async.md. Plan it with depends-on, files and verification per step,
   human checkpoints before behavior changes, and an Assumptions section."

# 2. After approval ("Yes, and use auto mode"), gate the stop on the definition of done:
#    /goal npm test -- test/exports exits 0 including the 120k fixture; lint and typecheck exit 0;
#    git diff --name-only only lists the spec's files; no test deleted or skipped;
#    print each exit code; or stop after 25 turns and report what's still failing.

# 3. Independent check before the PR
#    "Use the export-verifier subagent on docs/specs/export-async.md against main...HEAD."

Commands 2 and 3 are typed inside the session. The Stop hook and deny rules in .claude/settings.json apply throughout without being mentioned.

Connections

Labs

Scores a brief, grades acceptance criteria and the done condition, finds contradictions, maps boundaries to enforcing controls, and drafts an AskUserQuestion interview and a /goal line. Offline and deterministic; pass a path to lint your own spec, or --fail-under for CI.

cd labs && python3 delivery-2/brief_lint.py

Open the lab walkthrough

Builds a criterion-by-step coverage matrix, flags scope violations, contradictions, nonexistent files, unrequested work and plans that never run a command, and returns a plan-mode verdict with the "No, keep planning" feedback. Offline on the bundled good and drifting plans; --plan, --brief and --repo for your own.

cd labs && python3 delivery-2/plan_review.py

Open the lab walkthrough

Flashcards

What to do next

  1. Take the next real ticket on your board through the whole pipeline: interview, spec, plan review, /goal, verifier subagent. Time each step. Most people find the spec takes longer than expected, and the implementation takes less.
  2. Add three things to your repo that outlive the ticket: a decisions index in CLAUDE.md, one path-scoped rule with an exemplar file, and a quality-bar section with a final-report shape.
  3. Turn your spec template into a project skill (.claude/skills/spec/SKILL.md with disable-model-invocation: true) so /spec <ticket> starts the interview the same way every time.
  4. Continue to delivery-3, where these artifacts drive exploration, planning, parallel execution and delivery.