Claude Code: Best practices for agentic coding
anthropic.com ยท article ยท 2025-04-18 source โ Reader ๐ฅ๏ธ
Agent HarnessCapability Provisioning (right-sizing to the task)Claude CodeAgent Context Files (CLAUDE.md / AGENTS.md)Context EngineeringExtended Thinking / ReasoningFeedback LoopsMCP (Model Context Protocol)Multi-Agent OrchestrationTest-Driven Development
Because Claude Code is deliberately low-level and unopinionated, its effectiveness on your problem is set by the harness you engineer around the model โ the context, tools, and workflow you supply โ not by the raw model alone.
practical ยท expository prescriptive guide โ A best-practices guide: it argues 'you should do X' for agentic coding with Claude Code, grounding each recommendation in claims about how the tool and model behave. Organized as six numbered sections (customize setup, give more tools, common workflows, optimize workflow, headless mode, multi-Claude) of experience-derived patterns rather than a single sustained argument.
Structure
| Part | Role |
|---|---|
| Introduction โ Claude Code as an intentionally low-level, unopinionated, scriptable power tool with a resulting best-practices learning curve | States the design philosophy that makes the whole guide necessary: flexibility is pushed onto the user, so the user must supply the workflow |
| ยง1 Customize your setup โ CLAUDE.md files, tuning them as prompts, curating the tool allow-list, installing the gh CLI | The foundational harness-configuration layer: persistent context and permissions the model reads every session |
| ยง2 Give Claude more tools โ bash environment, MCP servers, custom slash commands | Extends the harness with the model's action surface โ shell tools, MCP integrations, and codified reusable prompts |
| ยง3 Try common workflows โ explore-plan-code-commit, TDD, screenshot-iterate, safe YOLO, codebase Q&A, git, GitHub, Jupyter | The core catalogue of repeatable workflow patterns that structure how the human drives the agent |
| ยง4 Optimize your workflow โ be specific, give images, mention files/URLs, course-correct, /clear, checklists/scratchpads, pass data | Cross-cutting techniques for steering the model and managing its context that apply across all workflows |
| ยง5 Use headless mode to automate infra โ issue triage, subjective code review/linting | Extends the tool from interactive assistant to programmatic building block in CI, hooks, and automation |
| ยง6 Uplevel with multi-Claude workflows โ writer/verifier separation, multiple checkouts, git worktrees, headless custom harness (fan-out, pipelining) | Scales beyond a single interactive session by parallelizing and separating context across multiple instances |
Key terms
- CLAUDE.md Agent Context Files (CLAUDE.md / AGENTS.md)
A special markdown file Claude Code automatically pulls into context at the start of a conversation, holding persistent project context (bash commands, core files, code style, testing instructions, repo etiquette, environment setup, warnings); placeable at repo root, parent dirs, child dirs, or home folder, and meant to be treated and iterated on like a prompt - agentic coding
Software development in which an assistant like Claude Code autonomously reads, searches, plans, edits, runs, and iterates on code across multiple steps with tool access, rather than emitting a single completion - extended thinking Extended Thinking / Reasoning
A mode giving Claude additional computation time to evaluate alternatives, triggered by escalating keywords 'think' < 'think hard' < 'think harder' < 'ultrathink' that map directly to progressively larger thinking-budget allocations - explore, plan, code, commit
A versatile workflow in which the user first has Claude read/research relevant material (explicitly not coding yet), then make a plan (optionally with extended thinking), then implement, then commit โ because skipping the first two steps makes Claude jump straight to code - test-driven development Test-Driven Development
An Anthropic-favorite agent workflow: have Claude write tests from expected input/output pairs first (avoiding mock implementations), confirm they fail, commit them, then write code that iterates until all tests pass without modifying the tests โ the tests are the verifiable target Claude iterates against - allowed tools / allowlist
The curated set of tools Claude Code may run without asking; by default it requests permission for anything that could modify the system (file writes, many bash commands, MCP tools), and the user loosens this deliberately conservative deny-by-default posture only for actions that are safe or easily undone - subagents Multi-Agent Orchestration
Secondary Claude instances the main agent spawns to verify details or investigate specific questions โ used especially early in a task to preserve the main context window without much efficiency loss, and to check that an implementation isn't overfitting to its tests - headless mode
Non-interactive invocation of Claude Code via the -p flag for CI, pre-commit hooks, build scripts, and automation โ with --output-format stream-json for structured output; does not persist between sessions and must be triggered each time - course correct
Actively steering Claude mid-task rather than letting it run autonomously โ asking for a plan before code, pressing Escape to interrupt while preserving context, double-tapping Escape to rewind history and edit a prior prompt, or asking Claude to undo changes - safe YOLO mode
Running claude --dangerously-skip-permissions to bypass all permission checks and let Claude work uninterrupted โ recommended only inside a container without internet access to bound the risk of data loss or exfiltration via prompt injection - git worktrees
Multiple branches of one repo checked out into separate directories sharing history, letting several Claude sessions run simultaneously on independent, non-overlapping tasks without merge conflicts โ a lighter-weight alternative to multiple full checkouts - MCP MCP (Model Context Protocol)
The Model Context Protocol, which Claude Code speaks as both server and client; as a client it connects to any number of MCP servers (via project config, global config, or a checked-in .mcp.json) to gain their tools
Propositions
- explicitClaude Code is intentionally low-level and unopinionated โ near-raw model access without a forced workflow โ which makes it flexible, scriptable, and safe but imposes a best-practices learning curve on new users.conf: high
- explicitA CLAUDE.md file, automatically pulled into context when a conversation starts, is the primary place to give Claude persistent project context: common commands, core files, code style, testing instructions, repo etiquette, environment setup, and project-specific warnings.conf: highsupportsCharlie Hills ๐ฆฉ's Post ยท p1 โ This guide is the canonical source for CLAUDE.md as an auto-loaded file carrying persistent per-session, per-project rules.
- explicitCLAUDE.md files should be treated and refined like any frequently used prompt โ kept concise and iterated on (via the prompt improver and emphasis such as IMPORTANT/YOU MUST) โ because adding extensive content without iterating on its effectiveness is a common mistake that hurts instruction-following.conf: highsupportsYour AGENTS.md might be a big problem ยท p7 โ The guide's warning that adding extensive content without iterating is a common mistake anticipates Pocock's thesis that fewer, well-chosen instructions beat a larger exhaustive rule set.
- implicitThe model's effective performance on your codebase is bounded by the harness you assemble around it โ CLAUDE.md context, the curated tool allow-list, MCP servers, and custom bash scripts and slash commands โ not by the raw model weights alone, so configuring that context-and-tool layer is the user's highest-leverage action.conf: highsupportsAgent Harness Engineering ยท p1 โ This canonical 2025 guide's whole premise โ that a deliberately low-level model rewards the context/tools you engineer around it โ is a concrete, early instance of 'a decent model with a great harness beats a great model with a bad harness.'supportsAgent Harness Engineering ยท p2 โ The guide's insistence that you must supply CLAUDE.md, tools, and workflow to get good results is exactly the claim that the gap between what the model can do and what users see is largely a harness gap.
- explicitYou should curate an explicit allow-list of tools, loosening Claude Code's deliberately conservative, deny-by-default permission posture only for actions that are safe or easily undone (e.g. file edits, git commit).conf: high
- explicitdevelopedFor most problems, follow explore โ plan โ code โ commit: have Claude read and research first (explicitly not coding yet, using subagents for hard questions), make a plan, only then implement, then commit โ because without the research-and-plan steps Claude tends to jump straight to coding, which degrades results on problems needing deeper thought.conf: highsupportsAgent Skills ยท p1 โ The observation that Claude jumps straight to coding without explicit research-and-plan steps is a concrete instance of Osmani's claim that a coding agent's default is the shortest path to 'done,' skipping planning and verification.extends โNo Vibes Allowed: Solving Hard Problems in Complex Codebases โ Dex Horthy, HumanLayer ยท p7 โ Both describe essentially the same explore/research โ plan โ implement workflow; this talk adds the explicit context-budget rationale (staying in the smart zone) and compaction discipline as the reason the sequencing works.
- explicitExtended thinking is triggered by escalating keywords โ 'think' < 'think hard' < 'think harder' < 'ultrathink' โ that map directly to progressively larger thinking-budget allocations, giving Claude more computation to evaluate alternatives.conf: highsupportsI benchmarked CC's caveman plugin against 'be brief'. The token math is wild. ยท p8 โ Documenting a keyword-controlled thinking budget as a lever distinct from visible output supports the caveman analysis that models with separate reasoning tokens would not suffer chain-of-thought amputation from output compression.
- implicitThinking budget should scale with problem difficulty: deliberately spend more reasoning on hard planning steps and less on routine work, dialing the budget via the escalating think-keywords.conf: highsupportsPrompting Claude Fable 5 ยท p5 โ The think-keyword ladder (think < think hard < ultrathink) is the 2025 coarse precursor to Fable 5's `effort` setting โ both hold that reasoning allocation should scale with task difficulty as the primary intelligence/cost lever.supports[MODEL] Claude Code is unusable for complex engineering tasks with the Feb updates #42796 ยท p2 โ Anthropic's own guide framing extended thinking as the lever for harder, deeper problems supports the issue's claim that extended thinking tokens are structurally required for multi-step research and careful code modification.
- explicitcontestedTest-driven development becomes even more powerful with agents: have Claude write tests from expected input/output pairs first (avoiding mocks), confirm they fail, commit them, then write code that iterates until all tests pass โ without modifying the tests.conf: highcontradicts โSoftware Teaming in the Age of AI with James Herr and Woody Zuill ยท p11 โ extract-claude-code-best-practices#p9 claims TDD 'becomes even more powerful with agents' (write tests first, iterate until they pass without modifying them); Woody's practitioner experience directly contradicts this โ LLMs have no design intent when writing/using tests, and under pressure hardcode outputs rather than generalizing, so TDD's design function does not transfer.
- implicitcorroboratedA clear, machine-checkable target to iterate against โ a test case, a visual mock/screenshot, or another expected output โ is what makes Claude's iteration converge on quality; given such a target it can make changes, evaluate results, and incrementally improve until it succeeds.conf: highsupports โHow we Claude Code ยท p9 โ Supports and instantiates the best-practices claim that a clear, machine-checkable target (a visual mock/screenshot) drives convergent iteration โ the four-HTML-design-direction demo is a direct, worked example of exactly this pattern applied to UI design.
- explicitcorroboratedActive human course-correction early and often โ forcing a plan before code, pressing Escape to interrupt, double-Escape to rewind and edit a prior prompt, and asking Claude to undo โ generally produces better solutions faster than letting Claude run autonomously to completion.conf: highsupports โ10 Things Developers Want from their Agentic IDEs in 2025 ยท p10 โ Both point to Claude Code's rewind/checkpoint mechanism as the concrete implementation of the rollback capability developers want.
- implicitcorroboratedContext is a finite, degradable resource โ during long sessions the window fills with irrelevant conversation, files, and commands that reduce performance and distract Claude โ so it must be managed deliberately: /clear between tasks, context-quarantining subagents, and external Markdown checklists/scratchpads for multi-step work.conf: highsupportsCharlie Hills ๐ฆฉ's Post ยท p4 โ This guide is the canonical source of the claim that long sessions degrade output because context fills with irrelevant content, and prescribes /clear as the remedy.supportsHarness design for long-running application development ยท p2 โ Recommending /clear plus a scratchpad handoff and context-quarantining subagents is a coarse precursor to the harness paper's structured context-reset-over-compaction finding.supports โThe Orchestrator's Tax ยท p6 โ Restates and specializes the general 'context is a finite, degradable resource' claim into the multi-agent case: the orchestrator specifically is the part of the system that must not be polluted.
- explicitSpecific, detailed instructions โ naming the edge case, pointing to an example file, saying 'avoid mocks' โ markedly raise Claude's first-attempt success rate over vague prompts, because Claude can infer intent but cannot read minds.conf: high
- explicitRunning multiple Claude instances in parallel โ one writing while another reviews or tests, or several git worktrees/checkouts on independent tasks โ outperforms a single Claude handling everything, because separate context windows behave like separate engineers.conf: high
- implicitSeparating generation from verification into distinct instances beats a single agent judging its own work, because a reviewer with separate context is not anchored to the author's reasoning.conf: highsupportsAgent Harness Engineering ยท p7 โ The 'one Claude writes, another verifies' pattern is a concrete, earlier instance of separating generation from evaluation into distinct agents because self-grading skews positive.supportsHarness design for long-running application development ยท p3 โ Separating a verifier with fresh context anticipates the harness paper's finding that a standalone skeptical evaluator is more tractable than making a generator critical of its own work.
- explicitdevelopedHeadless mode (claude -p) embeds Claude Code programmatically into CI, hooks, and pipelines โ fanning out across large batches (e.g. thousands of file migrations, each returning OK/FAIL) or pipelining structured JSON output into downstream commands.conf: highextends โHow building software is changing at Anthropic ยท p12 โ Jarred's interactive fan-out of a single hard migration across many parallel Claude agents is the same 'fanning out' pattern as Claude Code's headless-mode batch fan-out across CI pipelines, applied to a much less mechanical, higher-judgment task.
- implicitThe directory placement of CLAUDE.md is itself a context-budgeting mechanism: files in parent directories are pulled into context automatically at session start, while files in child directories are pulled in only on demand when Claude works with those subtrees, scoping instructions to where they are relevant.conf: highsupportsYour AGENTS.md might be a big problem ยท p6 โ The guide documents the exact loading mechanism โ child-directory CLAUDE.md files pulled in only on demand โ that grounds Pocock's claim that nesting genuinely defers instruction-budget cost.
- explicitcontestedYou should use the # key to have Claude append new instructions to the relevant CLAUDE.md as you work, and commit those changes so teammates benefit โ steadily accreting project knowledge into the file over time.conf: highcontradictsYour AGENTS.md might be a big problem ยท p2 โ This guide actively recommends the #-key habit of appending a rule to CLAUDE.md after issues arise; Pocock identifies exactly this reactive accretion as the mechanism that produces performance-degrading AGENTS.md bloat โ a genuine tension between knowledge accretion and instruction-budget discipline.
Arguments
You should invest effort in engineering the context and tools around Claude Code (CLAUDE.md, allow-list, MCP, custom scripts and slash commands) rather than just prompting the raw model. strength: high
Explicit premises:
- Claude Code automatically pulls context into prompts, which consumes time and tokens but can be optimized through environment tuning.
- CLAUDE.md is auto-loaded and its content becomes part of Claude's prompts.
- Claude inherits your bash environment and can use any tools and scripts you expose to it.
Implicit premises:
- The model's effective capability on your codebase is bounded by the context and tool surface it is given, not by its weights alone.
- Configuration effort amortizes because CLAUDE.md and tool setup are reused every session and shareable across the team.
- A generic setup underperforms one shaped to a specific project's conventions and history.
Inferences:
- If output quality tracks the assembled context and tools, then improving that assembly is the highest-leverage action available to the user.
Give Claude a clear, checkable target (tests, a visual mock, or expected output) and let it iterate against that target. strength: high
Explicit premises:
- Claude's outputs improve significantly with iteration โ typically much better after 2-3 passes.
- Claude performs best when it has a clear target to iterate against.
- With expected outputs like tests, Claude can make changes, evaluate results, and incrementally improve until it succeeds.
Implicit premises:
- Without an external, machine-checkable signal the agent has no reliable gradient to climb and cannot distinguish real improvement from drift.
- The human's role shifts from writing the solution to specifying the acceptance signal.
- A verification signal the agent can run itself (tests, screenshots) is what lets the correction loop close autonomously.
Inferences:
- Therefore the quality ceiling of agentic coding is set by the quality and checkability of the feedback signal, not by prompt wording.
Intervene early โ force a plan before code and correct course continuously โ rather than letting Claude run to completion. strength: high
Explicit premises:
- Without an explicit research-and-plan step, Claude tends to jump straight to coding a solution.
- Asking Claude to research and plan first significantly improves performance on problems requiring deeper thinking.
- Escape and double-Escape preserve context and let you redirect or rewind at any phase.
Implicit premises:
- Errors introduced early compound as the agent builds on them, so early correction is disproportionately cheaper than late correction.
- The human retains judgment the model lacks about whether the chosen approach is the right one.
Inferences:
- Therefore steering at the plan stage yields better and faster results than reviewing a finished but misdirected implementation.
Narratives
- The explore-plan-code-commit workflow: ask Claude to read relevant files/images/URLs without coding (using subagents for hard sub-questions), have it make a plan with extended thinking and optionally save it as a doc/GitHub issue to reset to, then implement, then commit and open a PR.
โ The guide's flagship worked workflow, demonstrating that inserting explicit research and planning phases before coding is what improves results on hard problems. - The agentic TDD workflow: Claude writes tests from input/output pairs (no mocks), runs them to confirm they fail, commits the tests, then writes code that loops โ run, adjust, re-run โ until all tests pass without touching the tests, with a subagent checking it isn't overfitting.
โ Concretely instruments the 'clear target to iterate against' principle, showing tests as the verifiable signal the agent's self-correction loop converges on. - The screenshot-iterate workflow: give Claude a way to take browser screenshots (Puppeteer/iOS-simulator MCP) plus a visual mock, ask it to implement the design, screenshot the result, and iterate 2-3 times until it matches the mock.
โ Shows the same iterate-against-a-target principle in a non-test modality, generalizing the feedback signal from tests to visual output. - The lint-fix checklist workflow: tell Claude to run the lint command and write every error (file + line) to a Markdown checklist, then work through them one by one, verifying and checking off each before moving on.
โ Demonstrates externalizing state into a scratchpad to preserve performance across a long, exhaustive multi-step task โ an antidote to context degradation. - The headless fan-out: have Claude write a script to list, say, 2,000 files to migrate from React to Vue, then loop calling claude -p per file with a scoped toolset, each returning the string OK or FAIL, refining the prompt across runs.
โ Illustrates using headless mode to turn the agent into a programmatic batch worker for large migrations, scaling beyond interactive use. - The multi-Claude write/verify loop: one Claude writes code, then /clear or a second terminal Claude reviews it, then a third reads both code and review and edits accordingly โ optionally with the instances passing notes via separate scratchpad files.
โ Concretely realizes the generation/verification separation, showing separate context windows acting like separate engineers.
Questions addressed
- โ
How should I configure Claude Code so it performs well on my codebase?
Create and iteratively tune CLAUDE.md files, curate the tool allow-list, install gh, and expose bash tools, MCP servers, and custom slash commands. - โ
When and how much should the model think before acting?
Trigger extended thinking with escalating keywords (think < think hard < think harder < ultrathink) mapped to larger thinking budgets, chosen by problem difficulty. - โ
How do I keep a long session from degrading in quality?
Use /clear between tasks, offload investigation to subagents, and externalize multi-step state into Markdown checklists/scratchpads. - โ
How do I keep the agent from jumping to a wrong or premature solution?
Use explore-plan-code-commit, be specific, and course-correct early with plan-first, Escape/double-Escape, and undo. - โ
How do I scale beyond a single interactive session?
Use headless mode (fan-out and pipelining) and multi-Claude workflows across separate terminals, checkouts, or git worktrees. - โญ Which model, or which effort/thinking level, should I use for which step โ and can this be routed automatically?
The guide treats 'Claude' as a single model; it never addresses model selection, per-step model allocation, or automatic routing. - โญ How much do these practices cost (tokens, rate limits) and when is the harness overhead worth it?
Cost, rate limits, and cost/benefit thresholds for multi-Claude and headless fan-out are not discussed.
Gaps
- incompleteNo model-selection or routing guidance. The guide treats 'Claude' as one undifferentiated model and never addresses which model or thinking/effort level to use for which step (e.g. plan with a stronger model, implement with a cheaper one), nor automatic model routing โ a lever the rest of the 2026 corpus treats as first-class. Being dated 2025-04-18, it predates the effort-knob and routing discourse.
Read next: Read against extract-charlie-hills-32-things-claude-code#p5 (Opus-plan / Sonnet-implement allocation), the model-routing concept, and extract-prompting-claude-fable-5#p5 (the effort setting as primary intelligence/latency/cost control). - incompleteThe think-keyword thinking budget is presented as folklore: no numbers for how much budget each level allocates, no account of the cost/latency trade-off of higher budgets, and โ being 2025 โ no notion of a separate reasoning-token budget distinct from visible output. A reader cannot calibrate when 'ultrathink' is worth its cost.
Read next: Read against extract-prompting-claude-fable-5#p5 (the graduated effort setting), extract-claude-code-github-issue (thinking tokens as load-bearing and rationed), and the extended-thinking concept. - incompleteEverything is asserted from Anthropic-internal and community experience with no comparative or quantitative evidence: no A/B of CLAUDE.md-vs-none, no measured effect of subagents on context availability, no failure-rate or effect-size data for any recommended practice. It is impossible to tell which practices generalize versus which are idiosyncratic to Anthropic's workflows.
Read next: Look for controlled Claude Code workflow comparisons and benchmark data (e.g. extract-cc-caveman-benchmark for token measurement); read against extract-charlie-hills-32-things-claude-code#g1, which flags the same evidence gap for a parallel tips list. - incompleteThe CLAUDE.md guidance omits the failure mode later corpus work centers on: bloat. It recommends the #-key 'append a rule' habit and running files through the prompt improver, but gives no instruction-budget ceiling, no progressive-disclosure/nesting strategy beyond raw directory placement, and no account of how many instructions a model can actually follow before adherence degrades.
Read next: Read against extract-pocock-agents-md-problem (the ~150-200 instruction ceiling and nesting-as-progressive-disclosure), the progressive-disclosure concept, and extract-agent-harness-engineering#p4 (every line should trace to a specific failure).closed byAudit your Agent files โ Directly supplies what that gap said was missing: an account of the bloat failure mode the earlier best-practices piece omitted, a progressive-disclosure account for skills (listing budget defaulting to 1% of context, body loaded only on invocation), and a concrete audit-cadence workflow (archive, /doctor, remove, test, decide) in place of the unbounded 'append a rule' habit. - incompleteCost and economics are absent. Multi-Claude parallelism, headless fan-out over thousands of files, and repeated 2-3x iteration all multiply token spend, yet the guide never mentions cost, usage/rate limits, or the threshold at which harness overhead pays for itself.
Read next: Read against extract-anthropic-harness-design-long-running-application-development#p13 (the harness-vs-solo 20x cost multiplier and when it is justified), the ai-unit-economics and usage-limits-rationing concepts. - incompleteNo treatment of how the practices vary by context โ greenfield vs legacy, language, codebase size, solo vs team. Every recommendation is presented as universal, with the implicit assumption that what works inside Anthropic transfers everywhere.
Read next: Look for domain-specific and team-based Claude Code usage guides; read against extract-charlie-hills-32-things-claude-code#g3, which flags the same universality assumption.closed byHow Microsoft Developers Use AI in Real-World Coding | BRK103 โ Same partial closure as above: a first-person, solo-developer, legacy-codebase account of how AI-assisted practice actually varies by context (throwaway vs. long-lived code), though still not team-based and not Claude-Code-specific.
Closes gaps elsewhere
- Your AGENTS.md might be a big problem ยท g2 โ Pocock's progressive-disclosure remedy depends on agents loading nested files only when relevant, but leaves the retrieval mechanism unexplained. This canonical Anthropic guide documents it directly: CLAUDE.md files in parent directories are pulled into context automatically at session start, while files in child directories are pulled in only on demand when Claude works with files in those subtrees โ confirming that nested placement genuinely defers cost rather than loading everything.
Related documents
- Agent Skills
- Agent Harness Engineering
- [FULL WORKSHOP] AI Coding For Real Engineers - Matt Pocock, AI Hero
- The Anatomy of an Agent Harness
- Charlie Hills ๐ฆฉ's Post
- [MODEL] Claude Code is unusable for complex engineering tasks with the Feb updates #42796
- Developer Newsletter: New models, Claude Tag, and dynamic workflows
- Prompting Claude Fable 5
- Just Talk To It - the no-bs Way of Agentic Engineering
- Technology Radar, Volume 34