Last Step/Claude Code Configuration and Workflows20%
Domain 36 task statements20% of the exam

Claude Code Configuration and Workflows

How to configure Claude Code so conventions load for the right files at the right cost, surface skills only when they should, and keep CI runs deterministic while preserving interactive control.

Claude Code is not a single prompt engine but a layered configuration system where four memory locations, path-scoped rules, skill frontmatter, plan mode controls, feedback techniques, and headless flags compose to determine what Claude sees and what it is allowed to do. The exam treats this as the highest weight domain because every other domain's work happens inside this shell. If the wrong CLAUDE.md loads, or a skill clutters the main conversation, or a CI job hangs waiting for input, no downstream prompt or tool fix can recover the session. Understanding the shell is therefore the first order decision.

The domain's six tasks map directly to the six ways the shell fails under pressure. Task 3.1 draws the memory hierarchy and the concatenation versus override rule that decides which team member gets which instruction. Task 3.2 unifies the two legacy slash command paths into the current Skills system and shows when isolation is required. Task 3.3 makes conditional loading token efficient so file-type conventions do not tax unrelated work. Task 3.4 draws the line between planning and acting based on ambiguity, not difficulty. Task 3.5 supplies the feedback order that fixes interpretation without wasting turns. Task 3.6 moves the same system into headless CI where interactive defaults become blocking defects.

Two principles cut across every task. First, always loaded versus on demand is the structuring choice. CLAUDE.md and path-scoped rules are always loaded or conditionally always loaded for matching files, while skills are on demand and only pay context when invoked. Putting on demand procedures in always loaded memory leaks tokens, and putting always loaded standards in on demand skills makes them invisible when needed. Second, instructions are probabilistic while settings are enforced. CLAUDE.md can guide the model but cannot guarantee a boundary, while settings.json permission rules and hook decisions enforce regardless of what Claude decides. Every exam trap that asks which layer guarantees ordering, blocking, or approval tests that distinction.

On this page
  1. 3.1 CLAUDE.md Hierarchy and Scoping Place conventions at the correct scope so they concatenate into every session that needs them and never leak into sessions that do not.
  2. 3.2 Slash Commands and Skills Create on demand slash commands as skills with correct frontmatter so they isolate noise, pre approve tools, and fire only when intended.
  3. 3.3 Path-Specific Rules Load conventions only for files whose path matches a glob so file type rules cover many directories with one file and minimal token cost.
  4. 3.4 Plan Mode and Execution Control Choose plan upfront when ambiguity is stated, execute directly when scope is clear, and use the hybrid for multi file migrations while keeping discovery isolated.
  5. 3.5 Iterative Refinement Steer Claude with examples for interpretation noise, test failures for complex logic, and interview questions for unfamiliar domains, batching only when fixes interact.
  6. 3.6 CI/CD Integration Run Claude Code headlessly with deterministic transcripts and structured findings so a pipeline can block, post inline comments, and preserve context without hanging or repeating noise.
The essentials
Everything below explains why each of these is true.
  1. Four CLAUDE.md locations exist: user at ~/.claude/CLAUDE.md, project at CLAUDE.md or .claude/CLAUDE.md, directory level in any subdirectory, and CLAUDE.local.md appended last at its level. All discovered files concatenate from root down, nothing shadows.
  2. Walk-up chain loads eagerly at launch from working directory up to filesystem root. Subdirectory CLAUDE.md and path-scoped rules load lazily only when Claude reads a file in that subtree or matching that pattern.
  3. @path/to/file is the import directive written directly in CLAUDE.md with no @import keyword. Relative paths resolve against the importing file, max depth four hops, code spans and fenced blocks are skipped.
  4. A flat file at .claude/commands/name.md and a skill at .claude/skills/name/SKILL.md both create slash command /name. The skill path is canonical because it supports supporting files, automatic discovery, and precedence when names collide.
  5. Skill frontmatter fields tested: context fork for isolation, allowed-tools to pre approve tools without prompting, argument-hint to prompt for missing inputs, disable-model-invocation true for explicit only.
  6. Path-scoped rules live in .claude/rules/name.md with YAML frontmatter paths array of globs such as star star slash star dot test dot ts. They load only when a read matches, one file covers test files across 50 plus directories.
  7. Project CLAUDE.md is shared via git. User CLAUDE.md is personal and never reaches a new clone. The new team member drift scenario is always user versus project scope.
  8. Plan mode is for ambiguous multi-file or architectural work with multiple valid approaches. Direct execution is for well understood changes with clear scope and known fix. Plan then execute is the hybrid for migrations across many files.
  9. Explore subagent keeps discovery output out of the main conversation. The benefit is context isolation, not parallelisation. Main agent exploration fills the main window and degrades subsequent responses.
  10. Concrete examples fix inconsistent interpretation first. Test driven iteration fixes complex transformations via failures. Interview pattern surfaces hidden considerations in unfamiliar domains. Batched feedback is for interacting issues, sequential for independent.
  11. In CI, -p is the non-interactive flag. Without it the job hangs waiting for keyboard. --output-format json plus --json-schema validates machine parseable findings in structured_output. Independent review instances beat self review in the same session.
  12. Settings enforce, CLAUDE.md guides. Permissions that must hold belong in settings.json deny rules or PreToolUse hooks, never solely in CLAUDE.md prose.
Task 3.118 min

CLAUDE.md Hierarchy and Scoping

Place conventions at the correct scope so they concatenate into every session that needs them and never leak into sessions that do not.

What you need to know

Claude Code reads configuration from four kinds of locations, each with a distinct scope and sharing property. User level at ~/.claude/CLAUDE.md applies to every project on the machine and is never version controlled. Project level at CLAUDE.md or .claude/CLAUDE.md at the repo root is shared via git to every clone. Directory level CLAUDE.md inside any subdirectory applies only to work in that subtree. CLAUDE.local.md is the companion that loads immediately after CLAUDE.md at the same level and carries personal overrides that remain gitignored. The exam repeatedly asks which file applies in a given scenario and the discriminator is rarely file name but always file scope.

The most heavily tested property is that these layers concatenate rather than override. All discovered CLAUDE.md files are loaded into context ordered from filesystem root down to the working directory, so the file closest to where Claude was launched is read last and carries the last word if instructions conflict, but nothing earlier is discarded. Two files that contradict still both sit in context and the model may pick either. That is why the docs note that contradictory rules may be resolved arbitrarily. Treating depth as shadowing is the most common wrong answer, and the exam correct answer is that CLAUDE.md is guidance, not configuration, and rules that must hold belong in settings.json or hooks.

The @path/to/file import directive is the composition mechanism that keeps a single CLAUDE.md maintainable as a project grows. Past a few hundred lines the file becomes unmanageable and shared standards such as linting rules are referenced from multiple package files. The syntax is @ followed by a path written anywhere in the body with no separate @import keyword, relative paths resolve against the importing file, recursive imports stop at four hops, and parsing skips Markdown code spans and fenced code blocks so an @path shown inside backticks is mentioned literally without triggering expansion. Both root and per package files can import the same shared file, so the rule exists once and is referenced from many sites without duplication.

Two companion mechanisms complete the hierarchy. Path-scoped rules in .claude/rules/ carry YAML frontmatter with a paths array of globs and load only when Claude reads a matching file, so they are the correct answer for file type conventions scattered across many directories. The claudeMdExcludes array in .claude/settings.json takes glob patterns against the CLAUDE.md file path itself and skips discovery of files that would otherwise surface through the walk up chain or lazy subdirectory discovery in a noisy monorepo. There is no allow ask deny override at the CLAUDE.md level, permission rules live in settings.json because CLAUDE.md is instructions, not enforcement.

Three verification and gating details are tested as cause and effect pairs. /memory lists locations Claude Code knows about and is the guide keyed answer for which files are known, while /context reports which files actually loaded into the running session under Memory files, and neither command triggers loading, they only diagnose what is already loaded. The --add-dir flag makes an extra directory reachable to tools but does not load that directory's CLAUDE.md unless the environment variable CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD is set to 1. When the Agent SDK embeds Claude Code, no filesystem settings load by default and an agent that ignores project CLAUDE.md almost always has settingSources not including project, with systemPrompt preset claude_code keeping the standard prompt intact when embedding.

The four locations and what they share

User level at ~/.claude/CLAUDE.md is personal, outside any repo, and never reaches teammates through git. Project level at CLAUDE.md or .claude/CLAUDE.md at the root is the team standard that rides with the code. Directory level in packages/api/CLAUDE.md or packages/web/CLAUDE.md scopes package specific conventions such as Zod validation in the API versus Testing Library in the web app, and loads only when Claude reads a file in that package. CLAUDE.local.md sits beside its peer at the same level, loads last there, and is the gitignored place for a personal database path or a temporary debugging note.

The ordering rule is concatenation from broadest to most specific, with local appended last at its directory. The file closest to the launch directory is read last, so it has the final word if phrasing conflicts, but earlier files are not removed. When two rules truly conflict the model may choose arbitrarily, which is the exam's cue that the requirement belongs in a deterministic layer such as settings.json or a hook rather than in prose.

Import and exclusion with precise semantics

The @path/to/file directive is not a preprocessor include with an @import keyword but a literal @ followed by a path written inline in the CLAUDE.md body. Imported files are expanded and loaded into context at launch alongside the file that referenced them, relative paths resolve against the importing file not the working directory, recursion stops at four hops, and any @path inside backticks or a fenced code block is skipped so examples do not accidentally expand.

claudeMdExcludes in .claude/settings.json takes globs against CLAUDE.md file paths to skip, not against directories the file would have applied to, so a pattern like star star slash experimental slash star star excludes every CLAUDE.md under any experimental directory. This is the fix for noisy monorepos where another team's CLAUDE.md keeps surfacing through the walk up chain or lazy discovery.

Loading triggers and cost

The walk up chain loads eagerly at session start from the working directory up through every parent to the filesystem root, always contributing any CLAUDE.md found on that walk. Subdirectory CLAUDE.md files below the working directory load lazily, entering context only when Claude actually reads a file in that subdirectory, so a session working only in packages/web never pays the context cost of packages/payments/CLAUDE.md.

The same lazy trigger applies to path-scoped rules and to nested CLAUDE.md. When Claude reads a file, the directory file for that file's parent loads if not already present and any path-scoped rule whose glob matches loads. That incremental cost is why per package rules are cheap in a monorepo and why packing all conventions into root CLAUDE.md is wasteful when only one package's rules are needed at a time.

Gating for extra directories and SDK embedding

Extending the view with --add-dir makes the extra directory's code reachable to tools, but loading its CLAUDE.md requires the gate CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD set to 1. Without the gate the code is reachable and the instructions are not, which the exam presents as a one line cause and effect where the learner assumes the flag implies memory loading.

When Claude Code runs embedded via the Agent SDK, the caller selects which filesystem layers are honored through the settingSources selector on query options. By default no filesystem settings load, so an SDK agent that ignores project CLAUDE.md and skills almost always has settingSources not including project. The companion systemPrompt preset claude_code keeps the standard Claude Code system prompt intact when embedding, and omitting it explains missing safety guidance.

Mechanism and API surface

Walk up chain and lazy discovery
Eager walk up at launch from working directory to root, plus lazy load of subdirectory CLAUDE.md and path scoped rules only when a file in that subtree or matching that glob is read. Per package cost is paid only when that package is touched.
@path import semantics
Directive is @path/to/file inline with no keyword, relative to importing file, recursive up to four hops, skipped inside code spans and fenced blocks, imported content loads inline at launch.
claudeMdExcludes glob
Array in .claude/settings.json of globs against CLAUDE.md file paths to skip, not against directories applied to. Use for noisy monorepos where another team's rules keep surfacing.
--add-dir gate
Flag makes extra directory reachable, CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD equals 1 gates loading of that directory's CLAUDE.md. Code reachable does not imply instructions loaded.
SDK settingSources and systemPrompt preset
Agent SDK query settingSources selects which filesystem layers are honored, none by default, must include project to see project CLAUDE.md and skills. systemPrompt preset claude_code preserves standard prompt when embedding.
Diagnostic pair /memory and /context
/memory lists known locations as the guide keyed answer, /context reports which files actually loaded under Memory files in the running session, neither triggers loading, both diagnose what is already present.
Next.js monorepo that drifts for the new teammate then stops drifting
A production walkthrough with the reasoning chain made explicit.

A four person fintech team ships a Next.js monorepo with web, api, and shared packages whose conventions diverge sharply. The api uses Zod for validation, supertest for HTTP tests, and structured logging, the web app uses Testing Library, vitest browser, and a different mocking convention, shared utilities have only type tests. Putting everything in one root CLAUDE.md makes every package pay the cost of every other package's conventions and dilutes attention on the package the developer is actually editing.

The maintainable structure is a root CLAUDE.md for universal standards such as build commands, branch policy, and code review checklist, plus one CLAUDE.md per package that loads only when Claude reads a file there, with both root and per package files importing shared linting standards via @shared/standards/linting.md so the rule exists once. CLAUDE.local.md at the root carries personal overrides such as a differing test database path. Verification is /context in different directories, root shows project CLAUDE.md plus imported linting, packages/api adds its directory file.

The new team member scenario makes the fault visible. Developer A has months of personal accumulation in ~/.claude/CLAUDE.md including team wide API naming, so on Developer A the model reads both user and project CLAUDE.md and appears consistent. Developer B clones the repo and has no team rules in ~/.claude/CLAUDE.md, so the run reads only the project file and drifts toward defaults. The misdiagnosis is to tell Developer B to copy Developer A's dotfile, the correct fix is to move the team conventions from user level to project level so every clone receives them, then verify with /memory for known locations and /context for what actually loaded.

A final subtlety closes the loop. After /compact summarizes a long session, the project root CLAUDE.md appears intact on resume not because it is privileged but because Claude Code rereads it from disk and reinjects it, while nested CLAUDE.md and path scoped rules with paths frontmatter remain lazy and reappear only when a matching file is read. An instruction that seems to vanish after compact is almost never summarisation but lazy loading not yet retriggered.

Distinctions that decide answers

ThisNot thisHow to tell them apart
CLAUDE.md concatenationsettings.json overrideCLAUDE.md concatenates from broadest to most specific, scalars do not replace, conflicts may be resolved arbitrarily. settings.json overrides layer by layer with managed above CLI above local above project above user, scalars replace, arrays concatenate.
User ~/.claude/CLAUDE.mdProject CLAUDE.mdUser lives outside any repo and is not shared via git. Project lives in the repo and is shared on clone. The new team member not receiving instructions almost always has the rule stuck at user level.
At path importAt import directiveThere is no @import keyword, the syntax is @path/to/file directly in the body. An option quoting @import is a distractor.
.claude/rules with paths frontmatterDirectory level CLAUDE.mdPath scoped rules apply to a file pattern across the entire codebase via glob. Directory level applies only to files in that single directory. Co located test files across many directories are the canonical rule case.
CLAUDE.md for always on rulesSkills SKILL.md for on demand workflowsCLAUDE.md loads on every session, skills load only when invoked directly or when description or paths matches intent. Universal API naming belongs in CLAUDE.md or path scoped rules, occasional checklists belong in skills.

Traps

More specific scope wins by shadowing

The tempting answer. Resolve conflicting CLAUDE.md guidance by assuming deeper scope silently overrides shallower scope.

Why it fails. Layers concatenate, both instructions sit in context and the model may pick either when they conflict. Shadowing intuition comes from most config systems but does not apply here, and treating it as configuration misses that enforcement belongs in settings.json or hooks.

What is correct. Write non conflicting guidance, use claudeMdExcludes to skip irrelevant files in monorepos, and move must hold rules to settings.json or hooks where they are enforced.

/memory or /context activates loading

The tempting answer. Run /memory or /context to make Claude load project CLAUDE.md that is currently missing.

Why it fails. Both are diagnostic only. Loading is automatic by location and lazy trigger. Commands list known locations or report what already loaded under Memory files, they never trigger a new load.

What is correct. Place the file at the correct level, use /memory and /context to verify, and fix scope or trigger rather than invoking a diagnostic as an activation step.

Directory level CLAUDE.md for cross directory file type conventions

The tempting answer. Drop a CLAUDE.md into each directory that contains tests to cover test files co located with source across 50 plus directories.

Why it fails. That requires one file per directory and drifts when new directories gain tests. Path scoped rules cover every matching file with one file and one glob such as star star slash star dot test dot ts.

What is correct. Create .claude/rules/testing.md with paths frontmatter carrying the test globs and verify with /context while editing a test file.

Permission rules belong in CLAUDE.md

The tempting answer. Write never run rm dash rf or ask before refunds in CLAUDE.md to block destructive or sensitive tools.

Why it fails. CLAUDE.md is probabilistic and the model may misinterpret or ignore it under pressure. settings.json deny rules are enforced by the client regardless of model choice, and the exam marks the settings path as the guarantee.

What is correct. Put destructive blocks and policy gates in .claude/settings.json permissions, use CLAUDE.md only for guidance that can tolerate interpretation.

Subdirectory CLAUDE.md loads eagerly at start

The tempting answer. Assume a session in packages/web pays context cost for packages/payments CLAUDE.md at launch because all project CLAUDE.md files load eagerly.

Why it fails. Only the walk up chain is eager. Subdirectory files below the working directory are lazy and load only when a file in that subdirectory is read, which is what makes per package rules cheap.

What is correct. Keep per package conventions in their package directory and rely on lazy loading to avoid paying for unrelated packages until touched.

Going deeper than the task statement
Adjacent material that shows up in harder scenario questions.
Managed settings and model restriction

The .claude/settings.json stack includes a managed layer that cannot be overridden even by --settings, plus availableModels that restricts callable models from any lower scope, and companyAnnouncements plus disableBundledSkills and skillOverrides.

Configuration
Skill aware memory and canUseTool gating

Agent SDK canUseTool fires per tool call to allow, deny, or modify at runtime, and a PreToolUse hook returning permissionDecision ask surfaces human approval for sensitive operations such as high value refunds.

Best Practices
Schema hint for typo detection

A $schema pointer to https://json.schemastore.org/claude-code-settings.json enables editor autocomplete and flags misspelled keys such as disableBundleSkills before the file reaches the runtime.

The .mdc Configuration File System
Build it
Build a scoped memory repo and prove what loads where
  1. Create .claude/CLAUDE.md at the repo root with three sections, naming conventions such as camelCase variables and PascalCase components, error handling pattern such as wrap async with try catch and return structured error, and review checklist item such as no hardcoded credentials.
  2. Add packages/api/CLAUDE.md with REST conventions for endpoint naming and validation, then create .claude/rules/testing.md with YAML frontmatter paths covering star star slash star dot test dot ts and sibling patterns and three test conventions.
  3. Add an @path import in .claude/CLAUDE.md referencing ./standards/naming.md, create the imported file with two naming rules, and keep the import outside any code span or fenced block so it expands.
  4. Run /context from the repo root and from packages/api and while editing a dot test dot ts file, recording Memory files each time to confirm root plus imported linting at root, plus directory file in api, plus testing rules only when the edited file matches.
  5. Move one convention from project level to ~/.claude/CLAUDE.md in a simulated second user home and verify that a fresh clone without that home does not see the rule, confirming the user versus project sharing boundary.
  6. Add a second team's CLAUDE.md under experimental slash and set claudeMdExcludes to skip it, then verify /context no longer lists it even when walking near that tree.

Verify. Each directory sees the correct concatenated set, path scoped rules appear only for matching files, @path imports expand inline, and the new teammate receives standards from the repo rather than a dotfile copy.

Answer real questions on this task
8 exam-style questions written against the rules above. You get the reasoning and a note on every wrong option after each answer.
Task 3.216 min

Slash Commands and Skills

Create on demand slash commands as skills with correct frontmatter so they isolate noise, pre approve tools, and fire only when intended.

What you need to know

Custom commands and skills are now one mechanism. A flat Markdown file at .claude/commands/deploy.md creates slash command /deploy, and a directory at .claude/skills/deploy containing SKILL.md also creates /deploy with identical runtime behaviour. The skill path is recommended because it adds capabilities the flat alias cannot: a directory of supporting files alongside the entrypoint, automatic discovery so Claude can load the skill when its description matches the user's intent, and precedence when a skill and a command share the same name, the skill wins. Both paths support the same YAML frontmatter and both keep older .claude/commands files working unchanged.

A skill is a SKILL.md file with YAML frontmatter followed by markdown content, there is no separate skill.json descriptor, no --install-skill flag, and no dedicated npm registry for skills. The lifecycle runs through discovery where Claude Code watches .claude/skills and ~/.claude/skills and plugin skills, installation as adding a file to a discovery location, invocation either explicitly via /name or automatically when the description and intent align, execution where Claude reads the body at load time and either runs inline or as a forked subagent if context fork is set, and result return where output appears in the conversation or is returned to the main session if it ran as a fork.

Three frontmatter options are most directly tested. context fork runs the skill in an isolated subagent so verbose exploration such as file listings and dependency graphs stays contained and the main window remains clean, which is essential for codebase analysis or brainstorming workflows. allowed-tools lists tools that run without a permission prompt while the skill is active while other tools remain callable subject to normal permissions, and to actually remove a tool from the pool list it in disallowed-tools or add deny rules in settings.json, since the true security boundary is deny rules not the allow list. argument-hint is the autocomplete pattern shown when the skill is invoked without required arguments, prompting the developer for the missing values and making parameterised skills discoverable.

The distinction the exam drills is skills versus CLAUDE.md. Skills are on demand task specific workflows whose descriptions stay in context so Claude knows they exist while the full body loads only when invoked, either via /name or automatically when description or paths frontmatter matches the request. CLAUDE.md is always loaded universal standards that apply with no invocation step. The rule is to keep task specific procedures in skills and universal reference material in CLAUDE.md or path scoped rules, so universal API naming belongs in memory and a multi step analysis that runs occasionally belongs in a skill.

Distribution beyond a single repo explains the remaining mechanics. Skills are files discovered from ~/.claude/skills for personal scope, .claude/skills for shared project scope, and plugin or marketplace skills installed via /plugin with manifests in .claude-plugin/plugin.json and sources from GitHub, URL hosted marketplace.json, npm package, or local path, with extraKnownMarketplaces and enabledPlugins honored in settings.json with the same precedence as any other setting. Permission integration is the same system Claude Code uses elsewhere, with three controls: adding Skill to deny rules to disable all skills, Skill(name) or Skill(prefix star) rules to allow or deny a specific skill, and disable-model-invocation true in frontmatter to hide a single skill from automatic invocation while keeping explicit /name.

SKILL.md anatomy and what no longer exists

Every skill is a SKILL.md file whose top matter is YAML frontmatter and whose body is markdown instructions that Claude reads when the skill is loaded. Field name is the display name defaulting to directory name, description is what Claude uses to decide automatic invocation and when combined with when_to_use is capped at 1536 characters in listings, argument-hint prompts for missing args, arguments defines named positional args for dollar name substitution, and allowed-tools grants promptless use of listed tools while the skill is active.

Several invented mechanisms are distractors. There is no skill.json, no --install-skill flag, no npm registry dedicated to skills, and a flat file dropped directly into .claude/skills as review.md does not create /review. The flat file path that creates a slash command is .claude/commands/name.md, while the skills path that creates one is .claude/skills/name/SKILL.md as a directory containing the entrypoint.

Isolation, allow listing, and explicit only invocation

Forked execution is requested with context fork in frontmatter. The skill body runs in an isolated subagent context window, all verbose output stays contained there, and only a concise summary returns to the main conversation. Without the flag the output flows into the main window and degrades snippet quality for subsequent turns, which is the exam correct answer for verbose output clutters the main conversation.

Invocation control has two layers that solve different problems. disable-model-invocation true removes the skill from Claude's automatic invocation so it only runs when the developer types /name, which is correct for security audits or deploy workflows that should not auto fire. allowed-tools and disallowed-tools control tool access while the skill runs, and Skill(name) permission rules such as Skill(commit) or Skill(review-pr star) control which skills are even available to be invoked, with Skill alone disabling all skills.

Discovery locations and team sharing

Claude Code watches skill directories at multiple scopes and picks up live edits within an already known skills directory without a restart, though creating a brand new top level skills directory that did not exist at session start requires a restart. User scope at ~/.claude/skills is personal and applies to every project, project scope at .claude/skills and parent directories up to the repo root is shared via git, plugin skills extend wherever the plugin is installed, and managed policy can deploy organization wide.

The team sharing boundary mirrors CLAUDE.md. Project scoped .claude/skills and .claude/commands are the correct place for a team /review checklist so every clone receives it, while user scoped ~/.claude/skills/brainstorm holds personal workflows. The reverse choices fail, personal scope for a team command means teammates never see it, flat file in .claude/skills without a SKILL.md directory means no command is created.

Built in versus custom and interactive versus print

Built in slash commands split into fixed logic commands such as /clear, /compact, /doctor, /debug, /init, /permissions, /context, /rewind and bundled skill commands such as /batch, /code-review, and /security-review that give Claude instructions and let it orchestrate with tools. Bundled skills can produce variable output and depend on tool availability, unlike fixed commands, and most session management commands are interactive only.

In print mode with -p the distinction matters for CI. Most session management commands do not apply the same way headlessly, while user invoked skills and custom commands do work in -p, you include /skill-name directly in the prompt passed to claude -p. That is why a CI check that needs team review logic invokes /review as part of the headless prompt rather than trying to run /compact or /doctor there.

Mechanism and API surface

Two paths to one slash command
.claude/commands/name.md and .claude/skills/name/SKILL.md both create /name with identical runtime, skill path supports supporting files and auto discovery and wins on same name, both use same frontmatter and both are project or user scoped.
SKILL.md frontmatter schema
name, description plus when_to_use capped at 1536 chars, argument-hint, arguments for dollar name substitution, disable-model-invocation true for explicit only, allowed-tools for promptless tools, context fork for isolation.
Lifecycle Discover then Invoke then Execute
Discover by watching skills directories, install as adding file to a discovery location, invoke explicitly via /name or automatically via description match, execute inline or as forked subagent then return result to main session.
Discovery locations and live change rule
~/.claude/skills personal, .claude/skills project shared via git, plugin skills wherever installed, managed policy org wide, edits within known directories take effect live, brand new top level directory needs restart.
Permission integration for skills
Deny rule Skill disables all, Skill(name) or Skill(prefix star) allows or denies a specific skill, disable-model-invocation true hides single skill from auto invocation, allowed-tools grants tools without prompt while skill is active.
Print mode rule for skills
Most built ins are interactive only, custom skills and user invoked skills work in -p headless mode by including /skill-name in the prompt, which is the CI valid invocation.
Team /review plus personal /brainstorm with correct isolation
A production walkthrough with the reasoning chain made explicit.

A team needs two reusable commands that must have opposite sharing and isolation behavior. The first is /review, a code review workflow with error handling, test coverage for new functions, API naming, and hardcoded credential checks that every teammate must be able to run. The second is /brainstorm, a personal workflow that explores a feature area, lists files, builds dependency graphs, and produces output too verbose for the main conversation. A third is a security audit that must never auto fire but must be available on demand with OWASP guidance.

For /review the correct file is .claude/commands/review.md or as a skill .claude/skills/review/SKILL.md under the repo so the file rides via git. The body is a checklist that runs against the working diff, and teammates get the command on clone. Placing this file in ~/.claude/commands would make it personal and invisible to the team, which is the exam fault for the team command location scenario. Dropping a flat review.md directly into .claude/skills would create no command at all because skills require a directory containing SKILL.md.

For /brainstorm the correct file is ~/.claude/skills/brainstorm/SKILL.md with frontmatter context fork so the workflow runs as an isolated subagent. The verbose listings and excerpts stay contained in the fork and the main conversation receives only the summary, keeping the main window clean for implementation. Without the fork flag the main window fills with exploration noise and subsequent turns degrade, which is the canonical trap for verbose output clutters the main conversation. The skill also lists allowed-tools for Read, Grep, and Glob so those reads run without per use approval while the skill is active, with other tools still governed by baseline permissions.

For the security audit the skill adds disable-model-invocation true so it never auto invokes and requires an explicit /security-review. The body carries OWASP guidance and reporting templates, and permission rules can gate it further with Skill(security-review). A common wrong answer is to place always on security guidance in a skill that never gets invoked, which makes it invisible, or to put a noisy occasional workflow in CLAUDE.md where it costs tokens on every session. The correct split is universal standards in CLAUDE.md or path scoped rules and task procedures in skills with explicit only when the workflow is sensitive.

Distinctions that decide answers

ThisNot thisHow to tell them apart
.claude/commands/name.md.claude/skills/name/SKILL.mdBoth create /name and work the same at runtime, skills path is canonical because it supports supporting files and auto discovery and wins when names collide.
Skills on demand workflowsCLAUDE.md always on standardsSkills load only when invoked directly or when description or paths matches intent. CLAUDE.md loads on every session with no invocation step. Task procedures belong in skills, universal conventions belong in memory.
context fork skillInline skillForked runs in an isolated subagent whose output does not enter the main conversation except as a summary. Inline runs in the main conversation. Verbose exploration belongs in forked skills.
disable-model-invocation trueallowed-tools onlyThe first removes the skill from Claude auto invocation entirely. The second controls which tools run without prompting when it does run. One governs whether it fires, the other governs tool surface while it runs.
Project .claude/skillsUser ~/.claude/skillsProject is shared via git so every clone gets the command. User is personal and not shared. Team commands belong in project, personal workflows belong in user.
Built in fixed commandBundled skill commandFixed runs hardcoded CLI logic such as /clear. Bundled skill such as /code-review gives Claude instructions and lets it orchestrate with tools, so output is variable and tool dependent, and behavior in -p mode differs.

Traps

Flat file directly in .claude/skills

The tempting answer. Create review.md directly inside .claude/skills and expect slash command /review to appear.

Why it fails. Skills require a directory containing SKILL.md, not a loose file. A loose file in .claude/skills is not discovered and no command is created, while the flat file path that does create one is .claude/commands/name.md.

What is correct. Create .claude/skills/review/SKILL.md or .claude/commands/review.md, both of which create /review, and keep the flat versus directory rule straight.

Team command placed in user scope

The tempting answer. Create a team shared command in ~/.claude/commands or ~/.claude/skills because it works on the author's machine.

Why it fails. User scope is personal and not version controlled, so teammates never see the command on clone. The sharing boundary mirrors CLAUDE.md, project scope via git is required for team sharing.

What is correct. Place team commands in .claude/skills or .claude/commands at the repo root so every clone inherits them.

Always on guidance placed in a skill

The tempting answer. Put team wide API naming that should apply to every generation in a skill because skills are flexible.

Why it fails. Skills load on demand, so the convention applies only when the skill is invoked. Universal standards that must apply to every session belong in CLAUDE.md or path scoped rules.

What is correct. Put always on conventions in CLAUDE.md or .claude/rules with paths, and reserve skills for occasional workflows that a developer runs explicitly or that auto trigger via a precise description.

Skipping context fork for a verbose skill

The tempting answer. Omit context fork for codebase analysis or brainstorming because the logic is straightforward without isolation.

Why it fails. Without isolation the verbose listings and excerpts fill the main context window and degrade subsequent quality. Fork keeps the main conversation clean and is the exam answer for that symptom.

What is correct. Add context fork in frontmatter for any skill whose output is noisy or exploratory, and return only a summary to the main session.

allowed-tools as a strict security boundary

The tempting answer. Treat allowed-tools as a strict restrictor that removes all unlisted tools from the skill.

Why it fails. In current Claude Code allowed-tools pre approves listed tools for promptless use while the skill is active, other tools remain callable subject to baseline permissions. The true boundary is disallowed-tools or deny rules in settings.json.

What is correct. Use disallowed-tools or settings.json deny rules when a true removal is needed, and use allowed-tools to grant promptless access for the intended read or write tools.

Expecting every built in to work in -p

The tempting answer. Invoke session management commands such as /clear or /compact headlessly via claude -p for CI orchestration.

Why it fails. Most session management commands are interactive only and do not apply headlessly. User invoked skills and custom commands do work in -p by including /skill-name in the prompt.

What is correct. In CI with -p invoke custom skills via slash name in the prompt and avoid interactive only commands, using print mode flags for output control instead.

Going deeper than the task statement
Adjacent material that shows up in harder scenario questions.
Reference versus task content in the same frontmatter

Reference skills add knowledge inline while task skills give step by step instructions and typically set disable-model-invocation true, with context fork for noisy reference aggregation versus explicit only for destructive tasks like deploy.

Skill Management in Claude Code
Plugin and marketplace distribution

A skill folder with .claude-plugin/plugin.json bundles skills alongside agents, hooks, and MCP servers, and marketplaces sourced from GitHub, URL hosted marketplace.json, npm package, or local path are enabled via extraKnownMarketplaces and enabledPlugins in settings.json with layered precedence.

MCP Integration
Context budget between memory and skills

CLAUDE.md loads on every session and consumes budget always, while skill body loads only when invoked, so long reference material should live in skills rather than memory to avoid taxing every turn until needed.

Configuration
Build it
Ship /review for the team and /brainstorm for yourself with correct isolation
  1. Create .claude/commands/review.md containing a code review checklist with error handling, test coverage, API naming, and credential checks, and verify /review appears after a clone and triggers the checklist.
  2. Create ~/.claude/skills/brainstorm/SKILL.md with frontmatter context fork plus allowed-tools listing Read, Grep, and Glob and argument-hint for the area to explore, and mark whether model invocation is desired for this noisy workflow.
  3. Add a security audit skill with disable-model-invocation true and allowed-tools for reading, confirming it never auto invokes but runs on explicit /security-audit with promptless reads.
  4. Verify sharing boundary, /review works in any clone of the repo while /brainstorm appears only in your home scoped session, and that the brainstorm verbose listings are not visible in the main conversation history after invocation.
  5. Convert one .claude/commands file to .claude/skills/name/SKILL.md and verify both create the same /name with skill precedence when both exist.
  6. Invoke /brainstorm via claude -p with headless flags to confirm custom skills work in print mode while interactive only commands such as /clear do not apply the same way headlessly.

Verify. Team holds a shared /review, personal noisy work stays fork isolated, sensitive audits require explicit invocation, and the same commands behave correctly in interactive and headless shells.

Answer real questions on this task
8 exam-style questions written against the rules above. You get the reasoning and a note on every wrong option after each answer.
Task 3.314 min

Path-Specific Rules

Load conventions only for files whose path matches a glob so file type rules cover many directories with one file and minimal token cost.

What you need to know

Path specific rules are the mechanism for applying conventions conditionally based on which files are being edited, solving the gap that neither root CLAUDE.md nor directory level CLAUDE.md handles well. Root loads for every session regardless of which files are touched, so Terraform conventions burn tokens while editing React components. Directory level applies only to a single directory, so covering test files co located with source across 50 plus directories would require one CLAUDE.md per test directory and inevitable drift. Path scoped rules solve the cross directory, single file type case with one file and one glob.

Rule files live in .claude/rules/ and each carries YAML frontmatter with a paths field whose value is an array of glob patterns using star, star star, question, and bracket semantics matched against the project root. With no frontmatter the file loads for every session, which is useful for universal standards but wasteful when the rule only matters for one file type. With paths such as star star slash star dot test dot ts the file loads only when Claude reads a matching file, staying invisible until relevant and staying cheap until triggered. That conditional cost is the token efficiency the exam tests directly.

The mechanism earns its keep in the canonical scenario of test files beside source files across dozens of directories. A project with src/components/Button.test.tsx next to Button.tsx and similar pairs in api, utils, and pages needs one test convention file, not 50 copies. A path scoped rule with paths star star slash star dot test dot tsx and siblings applies the same naming, assertion, and mocking standards everywhere automatically. The alternatives fail visibly: directory level would need manual placement in every new test directory, root would load test rules while writing an API handler.

Glob breadth is what makes this work. star star matches any number of segments including zero, star matches a single segment, and the match root is the project root, so star star slash star dot test dot tsx matches every test file anywhere in the repo and star star slash routes slash star star slash star dot ts matches every routes file regardless of how many packages expose routes. The closest companion mechanism for the inverse case is claudeMdExcludes in settings.json, which skips discovery of CLAUDE.md files whose file path matches a glob such as star star slash experimental slash star star when another team's rules keep surfacing in a noisy monorepo. There is no native exclusion list inside paths frontmatter itself.

Loading is incremental and composes with the walk up and lazy mechanisms. At launch the walk up chain contributes any CLAUDE.md above the working directory. When Claude reads a file, the subdirectory CLAUDE.md for that file's parent loads if not already present and any path scoped rule whose paths glob matches loads, and once loaded the rule stays in context for the remainder of the session. A unified root file with all convention sets might weigh 800 tokens, while a session editing only Terraform might load universal standards plus the Terraform rule for about 500 tokens, so the savings compound across turns and reduce lost in the middle noise.

Frontmatter shape and match semantics

Each rule in .claude/rules/name.md begins with YAML frontmatter, the only tested key is paths which takes an array of globs. Standard glob semantics apply, star for a single segment, star star for any depth including zero, question for a single character, bracket expressions as in any glob engine. The matching root is the project root, so star star slash star dot test dot tsx matches every test file in any subtree without enumerating directories.

A file with no frontmatter or with an empty paths array is treated as loaded for every session, which is the form for universally applicable standards. That form is intentionally wasteful if the content is file type specific, so the exam marks the path scoped form as the cost correct alternative when the question notes that conventions should not consume tokens while doing unrelated work.

Why directory and root answers fail the canonical case

Directory level CLAUDE.md is scoped to a single directory subtree, so bill a cross directory convention such as test conventions across many source directories with that mechanism and the correct count is one file per directory containing a test. The maintenance burden is to create the file in each current test directory and to add it in every new one, which drifts as copies fall behind, and the exam presents this as the maintenance failure that path scoped rules eliminate.

Root CLAUDE.md is unconditional, it loads for every session even while editing a file the conventions do not apply to. That cost is measurable in context budget and in lost in the middle attention where irrelevant guidance dilutes focus on the work at hand. The exam directly asks which mechanism keeps Terraform conventions from taxing React work and tests path scoped rules versus root as the efficiency choice.

Lazy composition with CLAUDE.md

The lazy trigger is the read operation. When Claude reads a file outside a rule's patterns, that rule does not load. When the read matches, the rule loads and then stays for the session. This is the same trigger as subdirectory CLAUDE.md, which is what keeps per package cost low in monorepos where a session in packages/web never pays for packages/payments until touched.

The incremental view explains the /context observations the exam tests. Start in the root and open a dot test dot ts file under src/utils, the walk up chain contributes universal standards while testing.md matches and loads and api-conventions.md and terraform.md do not. Open a Terraform module under terraform/modules/vpc and terraform.md matches and loads, while earlier test rules persist but no new unrelated rules contribute.

Composition with @path imports and exclusion

Path scoped rules compose with @path imports. A shared file with universal standards can be referenced from multiple path scoped rules via @, or a rule can import shared standards while keeping its own conditional body focused on the matching file type. This avoids duplicating the unconditional part across many rules while keeping the conditional part precise.

The file path glob for claudeMdExcludes is distinct from the directory glob for paths. Excludes match against CLAUDE.md file paths to skip, so a pattern excluding experimental removes every CLAUDE.md under that subtree. The distinction matters because an exclude target such as irrelevant team's CLAUDE.md is a file to skip, not a directory of source to match.

Mechanism and API surface

.claude/rules with paths frontmatter
YAML frontmatter with paths array of globs such as star star slash star dot test dot ts for file type or src slash api slash star star for directory scope, loaded only when a read matches, one file covers cross directory conventions.
Glob semantics and root
star single segment, star star any depth including zero, question single char, bracket expressions, root is project root, so star star slash star dot test dot tsx matches every test file anywhere in the repo.
Universal form without frontmatter
No frontmatter or empty paths means loaded for every session. Correct for universal standards, wasteful for file type specific rules where conditional form saves tokens.
Incremental lazy loading composition
Walk up chain eager at launch, subdirectory CLAUDE.md and matching path rules lazy on read, once loaded rules stay in session, unmatching patterns never contribute in that session.
claudeMdExcludes companion
Array in .claude/settings.json of globs against CLAUDE.md file paths to skip discovery, such as star star slash experimental slash star star, for noisy monorepos where another team's CLAUDE.md keeps surfacing.
Import composition for shared standards
Shared standards imported via @path from multiple path scoped rules keep the unconditional part in one place while each rule keeps its conditional body focused on its glob.
Three convention sets across tests, APIs, and Terraform with token proof
A production walkthrough with the reasoning chain made explicit.

A team holds three convention categories with divergent scopes. Test conventions for naming, assertions, and mocking should apply to star star slash star dot test dot ts and sibling spec patterns wherever they live, API conventions for response shape { data, error, metadata } and Zod validation should apply to src/api, star star slash routes, and dot controller dot ts files, and infrastructure conventions for remote state backend and workspace separation should apply to terraform slash star star and star star slash star dot tf. File type ranges overlap in the filesystem tree but never in the file types touched during a single edit.

The wrong solutions illustrate the cost model. All three sets in root CLAUDE.md load for every session regardless of whether the developer edits a test, an API handler, or a Terraform module, paying around 800 tokens even when only one set is relevant and crowding the middle of context. Directory level CLAUDE.md would need manual placement in every directory containing tests for the first set, which across 50 plus directories is both drift prone and token heavy per directory even when untouched. Skills with paths could auto trigger as workflows, but the requirement is always on background guidance, not an on demand checklist, so rules are the correct always on conditional memory.

The path scoped fix is three rule files. testing.md with paths star star slash star dot test dot ts, star star slash star dot test dot tsx, star star slash star dot spec dot ts, and star star slash star dot spec dot tsx carries describe it blocks, happy path plus error case per file, factory functions for test data, module boundary mocking, and assert behaviour not implementation. api-conventions.md with paths src/api slash star star, star star slash routes slash star star, and star star slash star dot controller dot ts carries endpoint response shape, request validation at handler boundary, request identifier on errors, and explicit rate limit configuration. terraform.md with paths terraform slash star star, star star slash star dot tf, and infrastructure slash star star carries remote backend requirement, workspace separation, and module versioning with changelog.

The runtime proof is via /context per edit. Starting in the repo root and opening a dot test dot ts file under src/utils, the walk up contributes universal standards while testing.md matches and loads and the other two do not. Switching to a Terraform module under terraform slash modules slash vpc slash main dot tf, terraform.md matches and loads while earlier rules persist but no new test or API guidance is added. With all three in root the loaded set is always 800 tokens, with path scoped rules a Terraform only edit is about 500 tokens for universal 300 plus Terraform 200, saving 300 tokens every turn Terraform is edited and compounding across the session.

Distinctions that decide answers

ThisNot thisHow to tell them apart
.claude/rules with pathsDirectory level CLAUDE.mdRules with paths apply to a glob across the entire codebase. Directory level applies only to files in that single directory. Co located test files across many directories are the canonical rule case.
.claude/rules with pathsRoot CLAUDE.mdRules load only when a matching file is read. Root loads on every session. Conditional rules are the token efficient choice for file type specific conventions.
.claude/rules with pathsSkills SKILL.md with pathsBoth can conditionally activate on paths, but rules stay in context as background guidance for matching files while skills load as on demand workflows triggered by intent or paths. Always on convention loading for a file type is a rule.
star star slash star dot test dot tssrc slash star starFile type glob matches test files anywhere regardless of directory. Directory glob matches every file under a fixed subtree. Choose by whether the convention follows extension or directory.
claudeMdExcludesAllow ask deny permissionsclaudeMdExcludes skips specific CLAUDE.md files from discovery. Allow ask deny governs tool permissions. They solve different problems and are tested as a skips files versus governs tools pair.

Traps

Directory CLAUDE.md for cross directory test conventions

The tempting answer. Cover test files co located with source across many directories by adding CLAUDE.md to each directory that contains tests.

Why it fails. That requires one file per directory and a new file for every new test directory, with drift as copies fall behind. Path scoped rules cover the same set with one file and one glob such as star star slash star dot test dot ts.

What is correct. Place the conventions in .claude/rules/testing.md with paths globs for test extensions and verify via /context that the rules appear only when a test file is edited.

Root CLAUDE.md for file type specific conventions

The tempting answer. Put Terraform conventions in root CLAUDE.md because root is the simplest shared location.

Why it fails. Root loads on every session even while editing a React component or an API handler, burning tokens on irrelevant guidance and degrading attention. The exam tests the efficiency loss and expects path scoped rules as the fix.

What is correct. Move file type specific conventions to path scoped rules with targeted globs so they load only when a matching file is read.

Skills instead of rules for always on conventions

The tempting answer. Use a skill with paths frontmatter to load test conventions because skills can also auto activate conditionally.

Why it fails. Skills load as on demand workflows, not as always on background guidance that shapes every edit. Rules stay in context as guidance once loaded, which is the behavior the question about automatic convention loading expects.

What is correct. Use path scoped rules in .claude/rules for automatic always on guidance tied to a file pattern, reserve skills for task workflows.

Forgetting claudeMdExcludes in a noisy monorepo

The tempting answer. Rely on lazy loading to hide another team's CLAUDE.md in a monorepo with many nested memory files.

Why it fails. Walk up and lazy discovery still surface files across the tree, so irrelevant guidance keeps appearing. The mechanism designed to skip them explicitly is claudeMdExcludes as globs against CLAUDE.md file paths.

What is correct. Add an exclude pattern such as star star slash experimental slash star star to skip the unwanted memory files rather than asking Claude to ignore already loaded content.

Directory glob when file type glob is more precise

The tempting answer. Use paths terraform slash star star for Terraform standards because the primary directory is named terraform.

Why it fails. Terraform files are identified by extension star dot tf and can appear outside terraform slash in a monorepo. A file type glob such as star star slash star dot tf covers them everywhere while a directory glob misses non standard locations.

What is correct. Choose file type globs when the convention follows extension, directory globs when it follows directory scope, matching the precision the convention actually requires.

Going deeper than the task statement
Adjacent material that shows up in harder scenario questions.
Multi pattern rule that spans four test extensions

Paths can combine star star slash star dot test dot ts, star star slash star dot test dot tsx, star star slash star dot spec dot ts, and star star slash star dot spec dot tsx in a single rule so one file covers every relevant test file without per extension rules.

Configuration
Unlimited body size for conditional rules

Unlike always loaded CLAUDE.md where brevity matters on every turn, a path scoped rule can be as long as needed because it contributes zero tokens until a matching file is read.

The .mdc Configuration File System
Standardized announcement and model gating

companyAnnouncements for org wide banner text and availableModels to restrict callable models from any lower scope are settings.json companions to path scoped memory, tested alongside claudeMdExcludes as layered precedence.

Best Practices
Build it
Prove conditional loading cuts tokens versus root memory
  1. Create .claude/rules/testing.md with paths for star star slash star dot test dot ts, star star slash star dot test dot tsx, and star star slash star dot spec dot ts plus three test conventions, and .claude/rules/terraform.md with paths terraform slash star star and star star slash star dot tf plus two infra conventions.
  2. Also create .claude/rules/api-conventions.md with paths src slash api slash star star and star star slash routes slash star star plus three API conventions, keeping universal guidance in root .claude/CLAUDE.md only.
  3. From the repo root edit a dot test dot ts file under src/utils, run /context, and record Memory files to show testing rules loaded while API and Terraform rules did not, then edit a Terraform module under terraform and repeat to show the swap.
  4. Move the same conventions into root CLAUDE.md as a second branch and compare loaded memory via /context while editing a utility with no conventions, showing the unified file always contributes while the scoped run contributes only universal plus matching rule.
  5. Demonstrate the directory level failure by sketching how many CLAUDE.md files would be needed to cover test types across many directories versus the single rule file with star star globs.
  6. Set claudeMdExcludes for an experimental subtree, verify /context no longer lists memory under it, and document the saved tokens versus the unconditional baseline.

Verify. The edited file sees only the rule its glob matches, the token count is measurably lower than the unified root baseline, and the same coverage that would need many directory files is handled by one rule per file type.

Answer real questions on this task
8 exam-style questions written against the rules above. You get the reasoning and a note on every wrong option after each answer.
Task 3.416 min

Plan Mode and Execution Control

Choose plan upfront when ambiguity is stated, execute directly when scope is clear, and use the hybrid for multi file migrations while keeping discovery isolated.

What you need to know

Claude Code operates in two main modes whose choice is governed by ambiguity, not difficulty. Plan mode is for complex work where the developer must explore the codebase, evaluate multiple approaches, and design a strategy before changing code. Direct execution is for well understood changes with clear limited scope where the correct approach is already known. The exam consistently applies this rule: if the task description leaves room for design choices, plan mode is correct even when the change sounds small, and if the description is specific enough that one obvious implementation exists, direct execution is correct even when the bug is tricky.

Plan mode fits the enumerated ambiguous set: large scale changes such as monolith to microservices restructuring or module reorganisation, cases where multiple valid approaches exist with different infrastructure requirements, architectural decisions about service boundaries or contracts with downstream cost, multi file modifications such as library migrations affecting dozens of files that require a consistent strategy, and codebase exploration tasks that need dependency or data flow mapping before any change. Direct execution fits the complementary clear scope set: single file bug fixes with a clear stack trace, validation conditionals added to one function, configuration value updates, and any well defined task where the developer knows what to change and how, with no design decision to make.

The hybrid the exam repeatedly tests is plan then execute. Use plan to explore, understand dependencies, evaluate approaches, and design the migration pattern, then switch to direct execution to apply the planned approach file by file with the strategy already decided. A library migration across 30 files is the canonical example, the plan phase finds every importer of the old library, maps API differences, designs the per file pattern, and checks edge cases, while the execute phase applies that pattern consistently so no file diverges from the design.

The Explore subagent is the isolation mechanism that keeps plan phase discovery from polluting the main conversation. Multi phase exploration produces file listings, dependency graphs, code excerpts, and analysis notes, and letting all of that flow into the main window fills context and degrades snippet quality for the implementation step. The Explore subagent runs discovery in its own isolated context window, returns a concise summary to the main session, and keeps the main window clean for the actual change. The verb that pairs with Explore is subagent delegation and the primary benefit is context isolation, not parallelisation.

The most common exam fault is delaying plan mode until complexity shows up. When requirements already state complexity such as restructure the monolith into microservices, choose plan immediately because the complexity is stated, not hidden. Starting direct and switching only when the first surprise appears incurs rework that upfront planning would have avoided. Conversely, a single function fix with a known cause and a clear stack trace is direct execution, and planning there adds overhead without benefit. The discriminator is stated ambiguity at arrival, not emergent difficulty during execution.

How plan mode behaves and how it switches

Plan mode is invoked with /plan and enforces read only exploration, Claude reads files, traces dependencies and data flow, analyses tradeoffs between approaches, and proposes a structured plan covering identified dependencies, evaluated approaches with tradeoffs, and a recommended implementation strategy, without modifying any files. It is not a separate model or system prompt but a behavior constraint layered on the same runtime.

Switching to execution is a developer prompt flow, exiting plan mode and proceeding with implementation, there is no compile time transition, and in headless print mode plan semantics are reached via --permission-mode plan which restricts the session to read only operations for generating reports or plans without touching the repo. The interactive and headless forms share the same read only intent but differ in iteration support.

Explore subagent and the pre ship trio

The Explore subagent is one of the bundled subagents Claude Code ships, invoked through the Task or Agent tool with a description and exploration prompt. It operates with its own context window, runs the discovery, and returns a structured summary as a tool_result block to the main conversation, mirroring any subagent delegation shape while preserving isolation as the primary benefit.

Plan mode composes with the pre ship workflow of /diff plus /code-review. /diff shows what changed in the working directory, /code-review is a bundled skill that reviews the diff and can apply findings via --fix with /code-review ultra for cloud multi agent review, and /security-review is the deeper security pass. Plan is pre change design, diff plus review is pre ship verification, they are complementary not interchangeable.

Criteria the exam keys

Plan mode signals in a stem are phrases such as multiple valid approaches, evaluate tradeoffs, service boundaries, module reorganisation, library migration across many files, or understand existing structure. Ambiguity is the trigger, not line count, and the presence of several plausible integration architectures is enough to select plan immediately rather than waiting for difficulty to emerge.

Direct execution signals are a clear stack trace with a known cause and a single function to change, a configuration value update, or a well defined validation conditional. Scope is the trigger, known location and known approach with limited blast radius, which the exam frames as the case where planning would add overhead without changing the design.

Composition with parallel and background work

Plan mode can fan out to multiple Explore subagents for parallel investigation of different subsystems, then sequence through /batch style decomposition where a large change is split into independent units in separate git worktrees. /agents opens the subagent manager, /tasks lists background work, /background detaches a session while freeing the terminal, and /btw adds a quick aside without bloating main history.

In print mode the composition is more constrained, headless plan is useful for risk reports and plans in CI without edits, but it cannot replace iterative interactive plan mode for complex design where exploration must refine with human feedback. The exam presents which mode for a CI planning step as --permission-mode plan with -p for headless planning.

Mechanism and API surface

/plan read only exploration
Invoked via /plan, reads and analyses dependencies and tradeoffs, produces a structured plan with dependencies, approaches, and recommendation, does not modify files, enforces behavior constraint on the same runtime.
Explore subagent isolation
Bundled subagent invoked via Task or Agent tool, owns its own context window, returns summary to main session, primary benefit is context isolation keeping verbose listings out of the implementation window.
Plan then execute hybrid
Plan phase designs migration pattern and edge handling across many files, execute phase applies pattern file by file consistently. Canonical for 30 file library migrations where single pass would diverge per file.
--permission-mode plan for headless
In -p mode restricts session to read only for plans or risk reports without touching the repo, useful for CI planning steps that should not edit, not a replacement for iterative interactive plan mode.
Pre ship trio /diff /code-review /security-review
/diff shows working directory changes, /code-review bundled skill reviews diff with --fix and ultra cloud multi agent option, /security-review deeper pass, together they form see then review then fix before shipping.
Parallel and background companions
/agents manager, /tasks background list, /background detach, /batch worktree decomposition, /btw aside without bloating history, all compose with plan mode for multi phase orchestration.
Three tasks with different correct modes on the same team
A production walkthrough with the reasoning chain made explicit.

Task one is to restructure a monolith into microservices. The stem lists multi file impact, service boundary design, multiple valid integration architectures with differing infrastructure requirements, and unknown module dependencies that require exploration before any change. The correct mode is plan immediately because complexity is stated in the requirements, not a hidden surprise. During plan the team fans out Explore subagents to trace dependencies in parallel and produces a boundary proposal with tradeoffs, and the main conversation receives only the summary while the verbose discovery stays isolated.

Task two is a null pointer exception in a single function with a clear stack trace, known cause, and a one line null check as the obvious fix. The correct mode is direct execution, the fix is applied, the test passes, and there is no design decision to justify planning. The wrong answer here is to enter plan mode because the bug mentions several files in the trace, the discriminator is not file count but whether a design choice exists, and here none does.

Task three is migration from an old logging library to a new one across 30 files with API differences per importer. The correct mode is plan then execute, the plan identifies every importer, maps the surface difference, designs a per file pattern and notes edge cases such as contextual formatting, and the execute phase applies that pattern consistently so no file diverges. A naive direct pass would have applied the migration inconsistently, which is the failure the exam targets. Starting direct and switching only when files diverge incurs rework that upfront planning would have avoided.

A variant the exam probes is the deferred switch trap, starting direct on a complex migration and moving to plan only when the first few files reveal unexpected coupling. The upfront plan would have discovered that coupling during dependency tracing and produced a different ordering or boundary choice, so the late switch costs at least the work already applied that must be redone. The exam marks the upfront plan as the cost correct answer because rework exceeds planning overhead.

Distinctions that decide answers

ThisNot thisHow to tell them apart
Plan modeDirect executionPlan is for ambiguous tasks with multiple valid approaches, multi file architectural changes, or unknown dependencies. Direct is for well understood changes with clear scope and known approach. Discriminator is ambiguity not difficulty.
Plan alonePlan then execute hybridPlan alone stops at design. Hybrid applies the plan file by file via direct execution. Migrations across many files use the hybrid, pure analysis can stop at plan.
Explore subagentMain agent explorationExplore runs discovery in an isolated window and returns a summary, keeping the main window clean. Main agent exploration fills the main window with verbose listings that degrade later turns.
/plan interactive--permission-mode plan in -p/plan switches interactive Claude Code into read only plan mode. --permission-mode plan is the headless equivalent that restricts a print mode session to read only for CI planning without edits.
/diff plus /code-reviewPlan mode/diff plus /code-review is a pre ship review workflow for changes already made. Plan mode is a pre change design workflow. They are complementary, not interchangeable.
/code-review ultraLocal /code-reviewUltra runs a multi agent review in the cloud for depth at higher cost and time. Local runs a single pass on the local diff. Choose by required depth versus budget.

Traps

Default to direct for multi file architectural work

The tempting answer. Take a monolith to microservices restructuring directly because execution feels faster.

Why it fails. Multi file changes with multiple valid approaches need plan mode to evaluate boundaries and dependencies before code. Starting direct discovers coupling late and forces costly rework, which the exam marks as the cost failure when complexity is already stated.

What is correct. Enter plan mode upfront when the stem already implies ambiguity or architectural choice, use Explore subagents to keep discovery isolated, then execute via the decided strategy.

Plan for a single file fix with a clear stack trace

The tempting answer. Enter plan mode for a one function null guard because thoroughness feels safer.

Why it fails. A well defined single function fix with a known cause and stack trace has no design decision, planning adds overhead without changing the outcome and the exam keys direct execution for this shape.

What is correct. Apply direct execution for fixes where what to change and how are both clear and scope is limited.

Skip the plan then execute hybrid

The tempting answer. Treat plan alone or direct alone as sufficient for a 30 file library migration.

Why it fails. Plan alone never applies the change, direct alone risks applying the pattern inconsistently per file. The hybrid is the tested combination where plan designs consistency and execution applies it file by file.

What is correct. Run plan to produce the per file migration pattern, then apply it via direct execution with consistent verification per file.

Defer plan until complexity shows up

The tempting answer. Start direct and switch to plan only when the first surprise appears to avoid over planning.

Why it fails. When the stem already says complex such as restructure the monolith, ambiguity is present at arrival and deferring incurs rework. The switch cost exceeds the upfront plan cost.

What is correct. Choose plan immediately when the description implies ambiguity, defer only when the stem is genuinely ambiguous about whether complexity exists, not when the stem states it.

Skip Explore subagent for verbose discovery

The tempting answer. Let the main agent list files and graph dependencies directly because an extra subagent feels like indirection.

Why it fails. Verbose discovery clutters the main window and degrades subsequent implementation turns. The Explore subagent's primary value is isolation, keeping the main conversation focused on the decision the discovery informs.

What is correct. Use the Explore subagent for noisy codebase discovery and return only the summary to the main session.

Going deeper than the task statement
Adjacent material that shows up in harder scenario questions.
Pre ship verification as completion of the mode split

The /diff plus /code-review plus /security-review trio with --fix and cloud ultra verifies what execution produced after plan informed the design, which the exam presents as the close the loop companion to mode choice.

Claude Code Slash Commands
Headless plan generation in CI

--permission-mode plan with -p is the headless analogue of interactive plan mode that generates risk reports or plans in CI without edits, with different iteration properties from interactive plan.

CI/CD Integration: --print and Non-Interactive Flags
Worktree decomposition for large migrations

/batch decomposes a large codebase spanning change into independent worktree units, which composes with plan then execute by parallelising the per file apply after the design is set.

Workflow Patterns
Build it
Classify three tasks and run the hybrid on the migration
  1. Select one complex multi file task with architectural choice, one single file bug with a clear stack trace, and one 30 file library migration where many files import the old library with API differences, and label each with ambiguous versus well understood at arrival.
  2. Run the complex task in plan mode with one or two Explore subagents, record the identified dependencies, evaluated approaches with tradeoffs, and recommendation, confirming no files were modified during planning and that verbose listings stayed in the subagent.
  3. Run the single file bug with direct execution, measure time from prompt to fix, and contrast with a staged plan mode attempt to observe planning overhead with no design change.
  4. For the migration run the hybrid, phase one as plan to collect every importer and design the per file pattern with edge handling, phase two as direct execution file by file with consistent verification, and compare against a single pass direct attempt for divergence per file.
  5. Produce a one page decision framework listing four criteria for plan and three for direct with a concrete example per criterion, explicitly noting ambiguity versus difficulty as the discriminator.
  6. Document the Explore isolation proof by showing that the main conversation after discovery contains only a summary while the subagent held the verbose graph.

Verify. Each task lands in its correct mode on arrival, the migration is consistent across files only under plan then execute, and the main window stays clean because discovery was isolated.

Answer real questions on this task
8 exam-style questions written against the rules above. You get the reasoning and a note on every wrong option after each answer.
Task 3.514 min

Iterative Refinement

Steer Claude with examples for interpretation noise, test failures for complex logic, and interview questions for unfamiliar domains, batching only when fixes interact.

What you need to know

First output from Claude Code is rarely the final output, and the exam tests which steering technique to reach for first in each failure shape. The pecking order is stable: concrete input output examples for inconsistent interpretation where prose is being parsed differently each run, test driven iteration for complex transformations with edge cases where failures give unambiguous feedback, and the interview pattern for unfamiliar domains where the developer does not know what questions to ask. Choosing the wrong technique wastes turns, choosing the right one shortens the loop deterministically.

Concrete examples are the fix for interpretation variance. When a prose description of a code transformation produces a different structure each run because phrasing leaves room for judgment, adding more precise prose still relies on interpretation and does not close the room. Two or three concrete before and after pairs showing exact input and exact expected output do. The model generalises the pattern from those pairs more reliably than from any description, so two well chosen examples covering the standard case and one edge case set the pattern more effectively than a longer paragraph.

The switch to examples follows a recognisable pattern the exam can describe without naming it. Observe inconsistency where the same prompt yields different outputs on repeated runs, switch to examples by providing pairs, verify generalisation on a new case not in the example set, and add an edge case example only if the standard case now applies but edge handling still misses. Piling on many examples beyond that adds token cost without proportional reliability, and the exam frames many shot as higher cost for nuanced tasks rather than a better default for interpretation noise.

Test driven iteration is the sister technique for complex transformations where edge cases, null handling, and validation must be consistent. Write the tests first covering happy path, edge cases such as null or empty inputs and boundary conditions, and any performance budget, run the suite, and share the failure output with Claude Code. Expected X got Y is the most unambiguous feedback possible, so the model makes targeted fixes whose next run reduces failing tests deterministically, which prose alone cannot do. The workflow maps to the evaluator optimizer pattern where automated tests are the evaluator and Claude is the generator that refines until the evaluator passes.

The interview pattern and feedback delivery shape complete the set. When working in a domain the developer lacks expertise in, have Claude ask questions before implementing about requirements, edge cases, and constraints, which surfaces considerations such as cache invalidation, TTL policies, consistency choices, and failure modes the developer would otherwise miss. How feedback is batched matters too: batch in one message when fixes interact, for example error shape, logging format, and SDK type must align, so the model sees all constraints at once, and sequence one at a time when fixes are independent so the model does not confuse which feedback maps to which code.

Technique hierarchy and why prose alone fails

Examples demonstrate the pattern via input output pairs, test driven iteration shares failures as feedback, and the interview pattern queries requirements upfront. Prose refinement refines wording but still relies on interpretation, so inconsistent interpretation that persisted across two prose attempts is the signal to stop refining wording and provide pairs instead.

Few shot placement amplifies the fix. Examples embedded at the end of the system prompt as close as possible to the user's message carry the strongest influence because model attention peaks at the beginning and end of context. The same principle applies to in conversation examples, proximity to the task increases the example's effect on the next output.

Test driven iteration as evaluator optimizer

The pattern maps to generator plus evaluator plus optimizer where the developer's test suite is the evaluator. Each shared failure reduces the search space because the model must make the next output pass the named assertion rather than satisfy a vague description. The loop is write tests then share failures then targeted fix until green.

Claude Code composes with headless execution here. In -p mode the CI runner executes the suite, collects the failure output, passes it to a Claude Code turn, and receives the patch, so the same evaluator generator shape runs without interactive presence, with incremental findings fed back until new issues drop to zero.

Interview shape for unfamiliar domains

The prompt explicitly invites questions before implementing, for example ask me about requirements, edge cases, and constraints before implementing a caching layer, or enumerate categories such as inputs, outputs, error cases, performance budgets, and integration points. The model then identifies the domain's hidden categories and the developer answers rather than prescribing the solution upfront.

The exam discriminator is knowing versus not knowing the transformation. If the developer knows the exact before and after shape but the model misinterprets it, use examples. If the developer does not know which considerations matter for correctness in the domain, use the interview pattern. Mixing them, for example examples for unfamiliar caching, misses the hidden tradeoff discovery the interview provides.

Batch versus sequential delivery

Batched feedback arrives in a single message that the model processes together, so interacting constraints such as error code field plus structured logging plus SDK type can be resolved coherently in one patch. Splitting them would risk a fix to one that contradicts another, which the exam presents as the cost of sequencing interacting issues.

Sequential feedback arrives as multiple messages over time and is correct when fixes are independent, such as a naming convention issue and an unrelated indentation issue that do not affect each other. Batching independent issues there confuses mapping of feedback to code region, so the exam presents independent fixes as the case for one at a time delivery.

Mechanism and API surface

Concrete examples in context
Two or three input output pairs placed near the task, often at system prompt end for proximity, from which the model generalises the transformation more reliably than from refined prose, with an extra edge case example only if needed.
Test driven loop with failure sharing
Happy path plus edge cases plus error cases as tests, run suite, share Expected X got Y failures, Claude makes targeted fixes, loop until green. Maps to evaluator optimizer with tests as evaluator.
Interview pattern prompt
Explicit ask me questions about requirements, edge cases, and constraints before implementing, optionally enumerating categories such as TTL, consistency, invalidation, and failure modes for the model to expand.
Batched versus sequential feedback
Batch in one message when fixes interact so all constraints are seen together, sequence one at a time when fixes are independent so feedback maps cleanly to code region.
Few shot calibration versus confidence filtering
Few shot examples showing correct judgement for ambiguous cases teach consistent decision making, while confidence thresholds are poorly calibrated and do not address inconsistent judgement at its root.
Proximity and in context learning
In context learning generalises from examples reliably, with best cost benefit at two to five examples, zero shot cheapest but least reliable for format sensitive tasks, examples closest to the query influence output most.
Type transform that diverged in prose, converged with pairs and tests
A production walkthrough with the reasoning chain made explicit.

A developer must transform every type signature returning Promise<T> into Promise<Result<T, ApiError>> as a discriminated union wrapper across a TypeScript codebase. The first attempt uses prose, convert every async function returning a plain value to a Result wrapper, and three runs produce three structures because plain value is interpreted differently each time, sometimes preserving existing error handling, sometimes replacing it, sometimes wrapping functions that already return rich objects.

The fix is two concrete pairs. Input getUserData(userId string) colon Promise<UserData> becomes Output getUserData plus Promise<Result<UserData, ApiError>>, and Input fetchOrders(customerId string) colon Promise<Order array> becomes Promise<Result<Order array, ApiError>>. With those pairs the model generalises the pattern that any Promise<T> becomes Promise<Result<T, ApiError>> and interpretation variance disappears on a new function not in the example set. The exam keys this as examples over better prose whenever runs diverge for the same description.

A more complex refactor still misses edge handling. The developer adds a test suite covering happy path, null inputs, empty arrays, and boundary conditions, runs it, and shares a failure such as FAIL testMigrationHandlesNullValues Expected null preserved in output JSON Actual null replaced with empty string. Claude sees the exact assertion mismatch and produces a targeted patch that preserves null, and each iteration reduces failing tests until the suite passes, which prose refinement could not do because the failure pinpoints the edge case identity.

A third shape is the unfamiliar domain. A caching layer for a backend API receives the prompt I need a caching layer for the API, before implementing ask me questions about requirements, edge cases, and constraints I should consider, and Claude asks about invalidation strategies such as TTL, event, and write through, TTL policies such as fixed, sliding, and adaptive, consistency as strong versus eventual, and failure modes such as miss, stampede, and stale data. The developer learns what questions matter rather than prescribing a solution that omits them. Batched versus sequential delivery appears in the review pass, three interacting fixes for error shape, logging, and SDK type are batched together while naming and indentation are sequenced separately, producing coherent alignment only when the interacting set is seen together.

Distinctions that decide answers

ThisNot thisHow to tell them apart
Concrete examplesTest driven iterationExamples show the pattern via pairs, test driven shares failures as evaluator feedback. Examples address interpretation variance for simple shapes, tests address complex logic with edge cases and validation.
Concrete examplesInterview patternExamples are for when the developer knows the exact transformation but the model misinterprets it. Interview is for unfamiliar domains where the developer might miss hidden considerations. Different problem, different technique.
Batched feedbackSequential feedbackBatched is for fixes that interact where the model needs all constraints at once. Sequential is for independent fixes where batching would confuse which feedback applies to which region.
Prose refinementExamplesRefined prose still relies on interpretation and does not close interpretation room. Pairs eliminate interpretation room entirely and are the exam answer for runs that diverge for the same prose.
Few shot for judgementConfidence threshold filteringFew shot showing correct judgement for ambiguous cases teaches consistency. Confidence thresholds are poorly calibrated and do not address the root cause of judgement inconsistency.

Traps

Refining prose when interpretation diverges

The tempting answer. Rewrite the description with more precise language because better wording feels more thorough.

Why it fails. More precise prose still relies on interpretation, so variance persists across runs. The exam marks examples as the first line fix for inconsistent interpretation precisely because pairs generalise more reliably than wording.

What is correct. Provide two or three input output pairs, verify generalisation on a new case, and add an edge case pair only if edge handling still misses.

Confusing interview with examples

The tempting answer. Use concrete examples for an unfamiliar caching domain because examples feel universally helpful.

Why it fails. Examples help when the developer knows the exact before and after shape, interview helps when the developer does not yet know which requirements matter. Swapping them misses hidden tradeoff discovery in unfamiliar domains.

What is correct. Use the interview pattern for unfamiliar domains to surface requirements and constraints, use examples when the desired transformation is known but misinterpreted.

Confidence thresholds to fix judgement inconsistency

The tempting answer. Raise a confidence threshold so inconsistent judgement calls are suppressed when below a score.

Why it fails. Thresholds are poorly calibrated and do not teach the decision principle, so inconsistency persists at a different cutoff. Few shot examples showing correct judgement for ambiguous cases directly teach the principle.

What is correct. Add few shot examples with reasoning for judgement calls, not bare pairs but pairs plus the rationale, so the model generalises the decision, not just surface matching.

Batching independent issues

The tempting answer. Batch every piece of feedback together to save turns because batching feels faster.

Why it fails. Batching independent issues confuses which feedback applies to which code region, while batching interacting issues is what benefits from seeing all constraints together. The exam tests the interacts versus independent split.

What is correct. Batch when fixes interact, sequence when they are independent, and gate the choice on whether changing one fix area affects another.

Too many examples beyond the cost benefit sweet spot

The tempting answer. Add many more examples to ensure coverage because more examples feel more thorough.

Why it fails. Two to three well chosen examples covering standard and edge already set the pattern, many shot adds token cost without proportional reliability, and the exam frames two to five as the best ratio for most tasks.

What is correct. Keep examples to two or three plus at most one edge case, then verify on a fresh case rather than piling on more pairs.

Skipping test driven iteration when tests exist

The tempting answer. Continue steering with prose or pairs even though a test suite with clear failures is available.

Why it fails. Test failures are the most unambiguous feedback possible with no interpretation room, leaving them unused wastes deterministic leverage that prose or pairs cannot match for edge case consistency.

What is correct. When a suite exists, share the failure output as the steering signal and let the model target the named assertion, iterating until green.

Going deeper than the task statement
Adjacent material that shows up in harder scenario questions.
Few shot structure with reasoning for judgement

Each example should be a complete input to output demonstration and for judgement tasks should include reasoning not just the pair, so the model learns the decision principle rather than surface pattern alone.

Claude Code Slash Commands
In context learning tradeoffs for example count

Zero shot cheapest but least reliable for format sensitive work, two to five best ratio, many shot five plus helps nuanced tasks at higher token cost, with placement at system prompt end near the task for maximal influence.

Configuration
Evaluator optimizer as architecture level framing

Generator produces output, evaluator scores it via tests or rules, optimizer refines until criteria pass, which formalises test driven iteration as the in session evaluator optimizer with failures as the evaluator signal.

Workflow Patterns
Build it
Prove examples beat prose, tests beat prose for edge cases, and batching matters
  1. Describe a code transform in prose, run it three times with the same prose, and record how interpretation varies in naming, edge handling, or structure.
  2. Replace prose with two or three input output pairs for the same transform, run three times, and compare consistency to the prose only trials, noting guidance about generalisation to a new case not in the pair set.
  3. Write a test suite with happy path, edge cases such as null or empty, and a performance budget, run it, share the failure lines Expected X got Y with Claude Code, and iterate until the suite passes, recording iteration count reduction versus prose only steering.
  4. Use the interview pattern for a task outside your expertise such as a caching layer, prompting Claude to ask about requirements before implementing, and log which considerations surfaced that you had not anticipated such as invalidation, TTL, consistency, and stampede handling.
  5. Batch three interacting fixes such as error shape, logging format, and SDK type in one message versus sequencing them, observing coherence of the single patch versus per step contradictions.
  6. Produce a one page technique chooser mapping inconsistent interpretation to examples first, complex transformations to tests first, and unfamiliar domains to interview first, with batch versus sequential delivery as a second decision.

Verify. The transform converges with pairs where prose diverged, edge cases converge only when driven by test failures, unfamiliar domains produce a more complete design under the interview, and interacting fixes align only when batched.

Answer real questions on this task
8 exam-style questions written against the rules above. You get the reasoning and a note on every wrong option after each answer.
Task 3.618 min

CI/CD Integration

Run Claude Code headlessly with deterministic transcripts and structured findings so a pipeline can block, post inline comments, and preserve context without hanging or repeating noise.

What you need to know

In CI Claude Code stops being an interactive assistant and becomes an automated check or generation step that must run without a keyboard, produce output a machine can parse, and leave the repository in a predictable state. The single most directly tested fact is the -p flag, also --print, which switches the session from interactive expecting input to print mode that processes the prompt, emits the result to stdout, and exits. Without it any CI job invoking claude with a review or generation prompt hangs forever waiting for input that never arrives, and flags that do not exist such as CLAUDE_HEADLESS=true or --batch or stdin redirection from /dev/null are the distractors.

Headless output must be machine parseable because no human watches the run, findings must be consumed to post inline PR comments, update dashboards, or trigger downstream gates. --output-format json wraps the run in an envelope with result text, session_id, and total_cost_usd, and --json-schema validates the final output against JSON Schema draft-07 in print mode only, exposing the validated object in structured_output that CI can extract with jq dot structured_output. The distinction the exam tests is deterministic versus probabilistic enforcement, --json-schema validates against the schema with an internal re prompt on mismatch, while prompt only system prompt instructions to output a shape may drift under tool pressure or long context.

Separation of generation and review context is a correctness requirement in pipelines that both generate and review code. The session that generated a middleware carries the reasoning why that approach was chosen, and asked to review its own output in the same session it is measurably less likely to question its own decisions. The fix is independent review instances, one print mode invocation to generate, a separate print mode invocation to review with no access to the generation session reasoning, which evaluates the code on its own merits and produces more thorough findings than self review.

Incremental review preserves signal to noise across pushes, because without memory of prior findings every run analyses the PR from scratch and re derives the same five issues on every push even after the developer fixed three and deliberately deferred two. A context free re scan cannot distinguish new problems from known deferred ones, so it repeats comments and erodes trust. The fix is to store previous findings as a JSON artifact, include them in the next run's context, and instruct Claude to report only new or still unaddressed issues so fixed items drop out and only fresh or persistent problems reappear.

Two supporting controls complete the headless surface. CLAUDE.md loads in CI just as interactively, so documenting testing standards, fixtures such as test slash factories and test slash fixtures plus test slash setup slash db dot ts, and review severity criteria there lets headless test generation use project patterns rather than generic boilerplate. --permission-mode selects autonomy, default with prompts that abort on unapproved action in -p, acceptEdits to auto accept filesystem edits in the working directory for auto fix jobs, dontAsk to auto deny anything not allow listed for read and report, bypassPermissions to skip prompts entirely in trusted sandboxed runners, and plan for read only headless planning, with --max-turns as a cost bound safety net rather than the primary completion control which remains stop_reason and with Message Batches API as the 50 percent savings path only for latency tolerant overnight reports, not for blocking pre merge checks that need synchronous results within seconds to minutes.

Headless flags and their exact contract

-p is the non interactive gate, it switches Claude Code to print mode where there is no interactive UI, no human approval prompts so anything not explicitly allowed or auto approved aborts the run, no follow up conversation unless resumed with --continue or --resume, and stdin is capped at 10MB as of Claude Code v2.1.128 so larger inputs must be written to a file and referenced in the prompt. --bare is a minimal mode that skips hooks, MCP servers, settings, auto memory, and CLAUDE.md so the same command produces the same result on every machine, reached for when a fast predictable scripted run is needed without project configuration.

--output-format controls transcript shape, text for humans, json for envelope with result, structured_output, total_cost_usd, and session_id, stream-json with --verbose and --include-partial-messages for NDJSON whose last line has type result to surface progress in CI logs rather than blocking silently. --json-schema requires --output-format json and Claude Code v2.1.205 or later, validates the final output against draft-07 before exit with internal re prompt on mismatch, and exposes the validated object in structured_output.

System prompt shape and permission modes for CI

Four system prompt flags exist and the choice determines which default guidance stays. --system-prompt replaces the entire default prompt, --system-prompt-file replaces with a file, --append-system-prompt appends to the default, --append-system-prompt-file appends a file, with append keeping default tool guidance, safety instructions, and coding conventions while replace drops them and should only be used when the pipeline identity differs from Claude Code's coding assistant role.

--permission-mode offers six values. default with standard checking that aborts on unapproved in -p, acceptEdits that auto accepts edits and common filesystem commands in the working directory for lint fix jobs, plan that enforces read only exploration for risk reports, dontAsk that auto denies anything not allow listed for locked down read and report, bypassPermissions that skips prompts in trusted sandboxes and can be disabled org wide, and the general principle of least privilege where only needed tools are allowed via --allowedTools or --disallowedTools rather than over permitting for convenience.

Output validation and where batch fits

Prompt only schema enforcement via --append-system-prompt Never run destructive commands is probabilistic and may drift under tool pressure, long context, or adversarial tool output, while --json-schema is deterministic with validation plus internal re prompt before exit. The correct headless gate is the deterministic one, prompt restrictions are the wrong answer when the stem requires a guarantee that destructive commands are blocked.

The Message Batches API is a cost optimization path with hard constraints, 50 percent savings versus synchronous, up to 24 hour processing window with no SLA and most batches finishing within an hour, no multi turn tool calling within a single batch request, and custom_id correlation for pairs. The matching rule is synchronous for blocking workflows such as pre merge checks where someone is waiting, batch for latency tolerant overnight reports and weekly audits where results are consumed later.

Review isolation and feedback hygiene

Session context isolation governs review quality. Generating in session A and reviewing in session B as two separate claude -p invocations removes generation reasoning from the reviewer's context and yields more thorough findings than self review in a single session, which the exam presents as the correct fix for a pipeline that generates then reviews with the same context.

Incremental review hygiene governs trust. Storing prior findings as an artifact and re including them with an instruction to report only new or still unaddressed issues prevents the duplicate comment failure where fixed issues reappear and known deferred issues are unnecessarily republished on every push, which developers stop reading when it repeats.

Mechanism and API surface

-p print mode gate
Switches Claude Code to non interactive where prompt is processed, result is emitted to stdout, and the process exits, no keyboard required, hanging CI jobs are always the missing -p.
--output-format json envelope
Wraps run with result text, structured_output validated object when schema supplied, total_cost_usd client estimate with per model breakdown, session_id, plus stream-json NDJSON variant for live progress with --verbose and --include-partial-messages.
--json-schema draft-07 validation
Requires --output-format json and v2.1.205 plus, validates final output against draft-07 before exit with internal re prompt on mismatch, deterministic enforcement versus probabilistic prompt only instructions.
System prompt append versus replace
--append-system-prompt keeps default Claude Code guidance plus extra rules, --system-prompt replaces and drops safety guidance, append is the safe default for headless coding, replace only for non coding identities.
--permission-mode six values
default standard with abort on unapproved in -p, acceptEdits auto accept edits in working directory, plan read only, dontAsk auto deny not allow listed, bypassPermissions skip prompts in trusted sandboxes with org disable flag, plus --max-turns cost bound and --bare minimal skips all discovery.
Session isolation and incremental context
Independent claude -p invocations for generate versus review to remove generation reasoning, plus prior findings re included as context with report only new or still unaddressed instruction to avoid duplicate comments across pushes.
Batch API matching rule
50 percent savings but up to 24 hour no SLA processing and no multi turn tool calling per batch request, synchronous for blocking pre merge checks, batch for overnight latency tolerant reports with custom_id correlation.
Pre merge PR check that stops hanging and starts posting inline findings
A production walkthrough with the reasoning chain made explicit.

A team runs Claude Code as a pre merge check in GitHub Actions with the job claude Review this PR for security issues. The job hangs in the log with Claude waiting for interactive input, and the fix is -p, claude -p Review this PR for security issues, after which the run completes and stdout is captured by the runner. The exam presents this as Question 10 in the sample set and the distractors that do not exist remain wrong. Variants such as CLAUDE_HEADLESS, --batch, or stdin redirection are not the documented mechanism.

The next improvement makes the findings usable. claude -p --output-format json --json-schema object with findings array items containing file string, line integer, severity string, and message string produces a JSON envelope where jq dot structured_output extracts the validated array. Each finding has file, line, severity, and message, so the runner posts an inline PR comment at the exact location with severity visible in context rather than dumping a blob of text at the end of the log.

Context isolation is added for a workflow that both generates and reviews. The runner runs claude -p Implement the authentication middleware as session A then claude -p Review the authentication middleware for security, error handling, and edge cases as session B with no shared history. Session B evaluates the code on its merits because it does not carry session A reasoning about why the middleware was designed that way, which is the correct fix for the same session self review that is cheaper but less thorough.

Incremental hygiene and project context close the loop. The runner stores first findings as a JSON artifact and on subsequent pushes runs claude -p --output-format json Review this PR given prior findings from PREVIOUS_FINDINGS, report only new or still unaddressed issues, do not re report deferred ones, so fixed items drop out and only fresh or persistent problems reappear. A CLAUDE.md section for CI documents testing standards such as factory pattern from test slash factories, integration setup via test slash setup slash db dot ts, no private implementation detail testing, available fixtures under test slash fixtures, and severity criteria, so headless generated tests follow team patterns rather than generic boilerplate.

Distinctions that decide answers

ThisNot thisHow to tell them apart
-p flagCLAUDE_HEADLESS, --batch, stdin redirection-p is the documented non interactive flag that processes the prompt and exits. The others do not exist or do not properly disable interactive mode.
--output-format json--output-format textjson is machine parseable with result plus structured_output for programmatic posting, text is human readable. CI pipelines need json, interactive sessions typically use text.
--json-schema validation--append-system-prompt schema instruction--json-schema validates against draft-07 deterministically with internal re prompt. Prompt only instructions are probabilistic and may drift, not suitable as a blocking gate.
Same session self reviewIndependent review instanceSame session retains generation reasoning and is less likely to question its own choices. Independent approaches the code fresh and is more thorough, so CI should generate and review in separate invocations.
Real time synchronous APIMessage Batches APISynchronous has seconds to minutes latency for blocking CI checks. Batches has up to 24 hour window with no SLA for overnight reports and weekly audits only.
--append-system-prompt--system-prompt replaceAppend keeps default Claude Code behavior plus extra rules. Replace drops the default prompt and its safety guidance, used only when the pipeline identity differs from Claude Code coding assistant.
--permission-mode dontAsk--allowedTools for specific toolsdontAsk auto denies anything not allow listed, useful for locked down read and report CI. allowedTools auto approves specific tools while most others remain gated, useful when most tools should still be checked.

Traps

Fixing a hanging CI job with a nonexistent flag

The tempting answer. Set CLAUDE_HEADLESS equals true or add --batch or redirect stdin from /dev/null because the names sound plausible for headless.

Why it fails. None of those flags exist on Claude Code, the interactive gate is the only documented headless switch. Distractors that sound plausible are the most common wrong answer for the hanging CI scenario.

What is correct. Invoke claude -p or --print for every CI headless call, which switches to print mode, processes the prompt, emits to stdout, and exits with no keyboard required.

Same session self review is as good as independent review

The tempting answer. Generate and review in one invocation to save cost because the same session already knows the code.

Why it fails. That session retains its own generation reasoning and justifications, reducing its ability to question the same decisions it just made. Independent review removes that bias and finds more of the issues the generation reasoning would justify away.

What is correct. Run separate claude -p invocations for generation and for review so the reviewer evaluates the code without carrying generation rationale.

Batch API for blocking pre merge checks

The tempting answer. Move pre merge checks to Message Batches API for the 50 percent cost savings.

Why it fails. Pre merge is blocking where a developer cannot merge until the check completes, but Batches has up to 24 hour processing with no SLA, so the pipeline would wait unpredictably and block merges far beyond acceptable latency.

What is correct. Keep real time synchronous calls for blocking pre merge checks and reserve Batches for overnight technical debt reports and similar latency tolerant work.

No incremental review context

The tempting answer. Re analyse the entire PR from scratch on every push because every run is already stateless.

Why it fails. Without prior findings every push re derives the same comments, fixed issues reappear and deliberately deferred issues are republished on every run, which erodes developer trust when the same five issues appear regardless of fixes.

What is correct. Store prior findings as a JSON artifact, include them in the next run, and instruct to report only new or still unaddressed issues.

Prompt only ban on destructive commands

The tempting answer. Enforce Never run destructive commands via --append-system-prompt because prompt instructions feel straightforward.

Why it fails. Prompt instructions are probabilistic and may drift under tool pressure, long context, or adversarial tool output, while permissions and validation flags enforce deterministically regardless of model choice.

What is correct. Gate destructive operations with --permission-mode dontAsk plus permissions deny rules, and gate output shape with --json-schema rather than prompt compliance alone.

No CLAUDE.md for CI

The tempting answer. Run headless without project CLAUDE.md because CI feels like a separate mode.

Why it fails. Claude Code reads CLAUDE.md in CI just as interactively, and without the same testing standards, fixtures, and review criteria the headless run produces low value boilerplate rather than team patterned tests.

What is correct. Keep a CI relevant section in CLAUDE.md covering standards, fixtures, setup, and review criteria so headless runs share the same project knowledge as interactive sessions.

Going deeper than the task statement
Adjacent material that shows up in harder scenario questions.
--bare for deterministic scripted runs

Skips hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md leaving only Bash and file read edit tools, so the same scripted command produces the same result on every runner where project configuration must not affect the outcome.

CI/CD Integration: --print and Non-Interactive Flags
Stream json for live progress in CI logs

--output-format stream-json with --verbose and --include-partial-messages streams NDJSON where the last line has type result, filterable with jq over stream_event text_delta for log forwarding without blocking silently.

Workflow Patterns
Permission least privilege as headless complement to interactive permissions

Interactive .claude/settings.json allow ask deny and headless --permission-mode plus --allowedTools share the same least privilege principle, with over permission causing accidents and under permission causing friction in both shells.

Best Practices
Build it
Wire a pre merge check that blocks plus posts plus preserves context
  1. Write a CI script that runs claude -p with a review prompt for the PR diff, capturing stdout as JSON envelope with --output-format json and verifying the job no longer hangs waiting for input.
  2. Add --json-schema with a schema requiring findings array items with file string, line integer, severity string, and message string, then pipe output to jq dot structured_output and assert schema conformance before any inline posting.
  3. Extend the script to parse the validated findings and post each as an inline PR comment at the exact file and line with severity visible, plus a summary dashboard artifact with session_id and total_cost_usd.
  4. Add a CLAUDE.md CI section listing testing standards such as factory from test slash factories, setup via test slash setup slash db dot ts, 80 percent branch target, and fixtures under test slash fixtures, then verify headless generated tests use the project's factories rather than generic boilerplate.
  5. Split generation and review into two independent claude -p invocations sharing no session context and compare findings versus a same session self review to confirm more thorough review under isolation.
  6. Implement incremental review by storing prior findings as a JSON artifact, including them in the next run's prompt, and asserting that fixed issues drop out while new or still open issues remain, with batch API only for the overnight variant and synchronous for the blocking gate.

Verify. The CI gate runs headlessly without hanging, findings are deterministically validated and appear inline, isolated review is more thorough than self review, and repeated pushes report only new or still open issues.

Answer real questions on this task
8 exam-style questions written against the rules above. You get the reasoning and a note on every wrong option after each answer.
Claude Code Configuration and Workflows exam
12 questions, the same number this domain contributes to the real 60-question paper. Drawn fresh from a larger pool each attempt, so a retake is a different paper. You can reveal the answer to any question while taking the exam, which locks that question. Otherwise answers stay hidden until you submit.
Cross-cutting decision table
DecisionChoose thisOver thisWhy
Where team conventions should liveProject CLAUDE.md or .claude/rules with paths shared via gitUser ~/.claude/CLAUDE.md on one machineProject scope reaches every clone, user scope never reaches a new teammate and causes drift that appears only for the newcomer.
Flat versus skill slash command for a team workflow.claude/skills/name/SKILL.md with supporting files and description.claude/commands/name.md only where skill features are neededSkill path adds directory support and auto discovery and wins on name collision, flat path is alias only.
Verbose workflow isolationSKILL.md with context fork so the fork holds noise and the main session receives a summaryInline skill that streams exploration into the main windowMain window isolation preserves context budget and quality for implementation, inline noise degrades subsequent turns.
Sensitive workflow that should not auto firedisable-model-invocation true plus Skill(name) permission ruleDescription alone or allowed-tools as the controlExplicit only requires the model to be removed from automatic invocation, tool allow listing governs a different axis.
Cross directory test conventions.claude/rules/testing.md with paths star star slash star dot test dot tsxCLAUDE.md per test directoryOne rule with one glob covers every test file even in new directories, directory per test directory drifts and needs manual addition.
Always on versus on demand checkRules in .claude/rules for always on background guidanceSkills for always on guidanceRules stay in context as guidance, skills load as task workflows, always on belongs in the always in layer.
Ambiguous multi file change versus clear single file fixPlan mode or plan then execute when multiple approaches or architectural choice existsDirect execution when scope is clear and approach is knownAmbiguity at arrival is the discriminator, not difficulty, plan avoids rework on the former, direct avoids overhead on the latter.
Discovery output handlingExplore subagent whose result returns as a tool_result summaryMain agent listing and graphing directlySubagent isolation keeps the main window clean, main agent exploration clutters it with listings that persist for every later turn.
Noisy interpretation versus complex edge casesExamples for inconsistent interpretation of a known transform, tests for complex edge heavy transformsMore prose for eitherExamples close interpretation room, tests provide unambiguous Expected X got Y feedback, prose leaves room in both cases.
Hanging CI jobclaude -p print mode with headless flagsCLAUDE_HEADLESS or --batch or stdin redirectionOnly -p is the documented headless gate that processes, emits to stdout, and exits without keyboard.
CI findings posting--output-format json plus --json-schema draft-07 into structured_output then jqPrompt only shape instructionsDeterministic validation with internal re prompt versus probabilistic drift under tool pressure.
Review quality under pipeline budgetIndependent claude -p invocations for generate versus review plus incremental prior findings carry forwardSame session self review without prior artifactIndependent removes generation bias and incremental avoids duplicate comments that erode trust across pushes.
Why wrong answers keep looking correct
Deeper CLAUDE.md silently wins and instructions are overridden like settings. CLAUDE.md concatenates, both instructions sit in context and the model may pick either, while settings.json scalars replace layer by layer. The override intuition applies only to settings, not to memory as guidance.
Flat review.md inside .claude/skills should create slash command /review because the path looks like a skills command. Skills require a directory containing SKILL.md, loose files there create no command, while the flat command path is .claude/commands/name.md. The directory shape is the discriminator.
Allowed-tools strictly removes tools while active, so it is the security boundary. Allowed-tools pre approves listed tools for promptless use while other tools remain callable, the true removal boundary is disallowed-tools or settings.json deny rules. The name suggests restriction but the current runtime implements grant not removal.
More precise prose will fix runs that diverge for the same description. Prose refinement still relies on interpretation, so variance persists, while concrete input output pairs eliminate interpretation room by giving the model the pattern to generalise directly.
Same session review is cheaper and just as thorough as independent review. The generation session carries its own design rationale and is less likely to question it, so findings are measurably less thorough for the same code. Cost savings trade directly against objectivity.
Batch API cost savings apply equally to blocking pre merge checks. Batches run with up to 24 hour window and no SLA, most finish within an hour but none is guaranteed for a blocking gate, so only overnight latency tolerant work is safe for the 50 percent savings, not a merge gate that must answer in minutes.
Last five minutes
Rules
  • If two memory locations conflict, choose concatenate not override, and move the must hold rule to settings.json or a hook rather than trusting CLAUDE.md ordering.
  • If a new teammate drifts from team conventions, the fault is user versus project CLAUDE.md scope, fix by moving the rule from ~/.claude/CLAUDE.md to project CLAUDE.md.
  • If a command should be on demand, put it in .claude/skills/name/SKILL.md with description driven auto invoke, if always on, put it in CLAUDE.md or .claude/rules with paths.
  • If verbose output clutters the main conversation, add context fork to the skill so the fork holds the noise and the main session receives only the summary.
  • If the skill should be explicit only, set disable-model-invocation true and gate with Skill(name) permission, not description alone.
  • If the convention follows file type across many directories, choose path scoped rules with star star slash star dot pattern, not CLAUDE.md per directory, and verify with /context while editing a matching file.
  • If the stem states multiple valid approaches or architectural choice, choose plan or plan then execute, if the stem gives a clear stack trace and single function location, choose direct execution.
  • If inconsistent interpretation persists across prose attempts, provide two or three input output pairs, if complex edge cases persist, share test failures as Expected X got Y.
  • If the CI job hangs waiting for input, the missing flag is -p, if the output must be machine parsed, add --output-format json plus --json-schema for deterministic validation into structured_output.
  • If the pipeline both generates and reviews, use independent claude -p invocations and carry prior findings forward to avoid duplicate comments.
Trigger phrases

Look for new team member versus same branch, flat file inside .claude/skills versus SKILL.md directory, context fork versus inline, disable-model-invocation versus allowed-tools, claudeMdExcludes versus permissions, star star slash star dot test dot tsx versus single directory CLAUDE.md, plan versus direct via stated ambiguity, examples versus interview versus test failures, -p versus CLAUDE_HEADLESS, json plus schema versus prompt only shape, same session versus independent review, batch 50 percent versus real time seconds to minutes.

If you see X, think Y

If you see @path written without an @import keyword but with code span skipping and four hop limit think CLAUDE concatenation and lazy rules. If you see /memory think known locations keyed answer, if you see /context think actual memory files in the running session. If you see --add-dir reachable but no CLAUDE.md loaded think the gate env var not set. If you see skill.json or --install-skill think distractor. If you see prompt only ban on destructive commands think probabilistic not enforceable. If you see test dot ts co located widely think path scoped rules not directory memory.