Skip to content

Claude Code Best Practices Every Developer Should Know

Master Claude Code best practices to optimize agentic workflows, manage context rot, and leverage auto mode for safer, more efficient software engineering.

Tuan Tran Van
35 min read
Contents (22 sections)
  1. You decide what to build, Claude decides how
  2. Context is a finite resource — how do you manage it?
  3. Keep the context window lean in a long session
  4. Explore, then plan, then code
  5. Write prompts that carry their own context
  6. Always give Claude a way to verify its own work
  7. Four ways to enforce verification, from loosest to strictest
  8. Control how hard Claude thinks
  9. CLAUDE.md: short, specific, and pruned often
  10. Turn every correction into a permanent rule
  11. Rules worth hardcoding into your instructions file
  12. Subagents for investigation and adversarial review
  13. Run several sessions at once
  14. Rewind, resume, and hand off
  15. Permissions and auto mode
  16. Choosing the right extension mechanism: skill, hook, MCP, or plugin
  17. Configuration beats prompting
  18. Automate beyond the interactive session
  19. When several agents share one memory
  20. Common failure patterns and how to get out of them
  21. These are defaults, not laws
  22. References

Using Claude Code well means giving up the part of the job most engineers enjoy: writing the implementation yourself. You own the architectural "what," while Claude Code handles the "how" through autonomous tool use and execution. Claude Code best practices come down to a clean , verification signals the model can check without you, and enough domain expertise to earn longer action chains. Get those right and the job stops being syntax and becomes an implementation cycle you run.

The shift is from editor to director. You stop building features character by character and start supplying constraints, verification criteria, and the first architectural plan. Claude works the agentic loop from there: read the codebase, propose changes, iterate until your criteria pass. The director's chair is less comfortable than it sounds. You lose the small satisfaction of typing the fix, and you inherit the harder job of stating exactly what "fixed" means. This asks you to think in outcomes and evidence rather than logic and flow.

An engineer directing the Claude Code agent using established best practices

You decide what to build, Claude decides how

Agentic coding runs on a strict division of labor, and the numbers are lopsided. Analysis of roughly 400,000 Claude Code sessions shows humans making 70% of all planning decisions, such as defining the technical approach and setting "done" criteria, while Claude handles 80% of the execution decisions: file selection, syntax, the exact command to run. You are the architect; the agent grinds through the repository's mechanical details. That split is sharper than it feels from inside a session, where the two blur into one conversation.

Diagram of the split: the human decides what to build, Claude decides how

How much the arrangement amplifies you depends on your domain expertise. Coding proficiency is the baseline; framing the problem precisely is what drives output. High-signal directions buy longer autonomous action chains, and the gap is measurable: a novice prompt averages 5 actions and 600 words of output, while an expert prompt, precise about framing and verification, averages 12 actions and 3,200 words.

Domain knowledge is what lets the agent run without stopping to ask. Catch the edge cases while planning, hand Claude a clear recovery path when a command fails, and it keeps working instead of stalling on an ambiguity. The agent does not replace expertise, it amplifies it. The more understanding you bring in, the more work comes back per instruction, and the more of your own time stays on the problem instead of the implementation.

As sessions move toward end-to-end use, the tool stops looking like a debugger and starts looking like an operator: deploying code, analyzing data, running automated pipelines. That raises the bar on you — it does not lower it. If you cannot state the intended outcome, the agent will not reach it. Which is the encouraging part, oddly enough: proficiency in your specific domain gets you almost as far as deep technical mastery.

Context is a finite resource — how do you manage it?

The context window is the resource that runs out, and it degrades well before it fills. Because the transformer architecture creates n² pairwise relationships between , the model's ability to recall specific details decreases as the token count grows. That is "context rot." The attention budget is finite, and every irrelevant log line or stray file read spends part of it; the bill arrives later as a long-range reasoning failure, or an instruction from the top of the session quietly dropped. Manage the budget the way you would manage memory in a high-performance system.

Illustration of a context window filling up as output quality degrades

Compaction is the built-in defense. When a session nears its limit, Claude summarizes the history to preserve architectural decisions and unresolved bugs while discarding redundant tool outputs. In Claude Code, that summary also preserves the last five accessed files, so you do not lose your place. You can trigger it yourself with the /compact command, and use /btw for side questions you want kept out of the persistent conversation history.

Retrieval should be just-in-time. Rather than pre-loading every file into the session, let Claude pull context as it needs it, using file paths, grep, and glob. It is closer to how you actually read a codebase: an index, not the whole thing held in your head. And when the task changes, be aggressive with /clear. A reset context stops yesterday's debugging cycle from steering today's feature.

Then there is "Imperfect Recall." In collaborative environments, the "deletion hazard" (the risk of a project requirement being accidentally removed or ignored) actually falls as the number of maintainers rises, and your sessions behave the same way. Persist the rules in CLAUDE.md, push research into specialized , and the main session stops turning into a "kitchen sink" that degrades on its own. What you want is the smallest set of high-signal tokens that still produces the outcome you are after.

Keep the context window lean in a long session

/clear and /compact are the blunt instruments. The finer control is knowing where you stand before quality drops. Watch consumption with /usage or a custom status line and intervene around 70% capacity, because by the time the output tells you, you have already lost an exchange or two to it. The symptoms are specific: the same suggestion twice, a constraint you set an hour ago quietly ignored, an approach you already rejected coming back as a fresh proposal.

Compaction does not have to be a black box. /compact <instructions> steers the summary, so you can insist the list of modified files or the exact test command survives it. You can also compact one end of the conversation instead of all of it: from the rewind menu, "Summarize from here" condenses everything after a chosen checkpoint and leaves earlier context intact, while "Summarize up to here" does the reverse. Turning automatic compaction off hands you the timing. Do that when you know a summary is about to land in the middle of something delicate.

The rest is housekeeping — the kind that pays off over hours rather than in the moment. Keep the connected-tool list lean and load tool definitions only when they are needed; every idle server costs context on every turn. Push long-running commands to the background with Ctrl+B instead of watching them scroll. And when you have to wait on a slow job, poll it with widening delays. A status check every minute for twenty minutes buys nothing that three checks would not, and it fills the window with noise.

Explore, then plan, then code

Four phases, in order: Explore, Plan, Implement, Commit. Splitting research from execution matters most on complex tasks where the architectural approach is not settled yet. Jump straight into implementation and you tend to get brittle code that ignores the patterns already in the system and the constraints nobody wrote down.

The four-phase Explore, Plan, Implement, Commit cycle for working with Claude Code

"Plan Mode" (Shift+Tab) locks the environment during research. Claude reads files and answers questions but cannot change anything, which is where you check whether it actually understood the problem, before a line of code exists. For complex migrations or feature additions, start the session there:

bash
claude --permission-mode plan

Once exploration is done, ask Claude for a detailed implementation plan and read it. Ctrl+G opens it in your text editor so you can edit it directly, and that is the primary point of control in the whole workflow. Only when the plan is sound do you leave plan mode and let implementation run. Claude executes the code changes, you verify them through tests, then you commit.

On small work the ceremony is a tax. A typo, one renamed variable, an extra log line: ask for the change directly. My rule of thumb is that if you can describe the required diff in one sentence, planning is overhead. The judgment call is weighing that overhead against the risk of an implementation that goes the wrong way.

Write prompts that carry their own context

Precision in the instruction is the cheapest correction you will ever make. Scope the task to a file and a scenario, and say what you want from the tests: "write a test for foo.py covering the case where the user is logged out, avoid mocks" gets you somewhere that "add tests for foo.py" does not. When the question is about why the code looks the way it does, point Claude at the artifact that holds the answer instead of asking it to speculate. Telling it to read a class's git history and summarize how the API came to be grounds the answer in what actually happened. And when you want consistency, name the pattern to copy: point at an existing widget implementation and tell Claude to follow it, instead of describing your conventions from memory.

Bug reports work best as symptom plus suspected location plus a definition of fixed. "Users report login fails after session timeout, check the token refresh in src/auth/, write a failing test that reproduces it, then fix it" contains a hypothesis, a search boundary, and an acceptance criterion. Compare that to "fix the login bug," which contains none of them and buys you a round of questions.

How you get content in matters as much as how you word it. Reference files with @ instead of describing where the code lives, paste or drag images straight into the prompt for anything visual, and hand over documentation URLs, allowlisting the domains you use constantly through /permissions so you stop approving the same fetch. When the input is already on disk, pipe it: cat error.log | claude beats pasting a log by hand. Better still, tell Claude to go fetch what it needs with Bash commands or MCP tools, because guessing in advance what it will want is usually wasted effort. That does not make vague prompts useless. "What would you improve in this file?" is an exploration, and it surfaces things you would not have known to ask about.

Always give Claude a way to verify its own work

An agentic loop is only as good as its verification signals. With no automated check, you are the check, reading every change by hand to catch errors. So give Claude something that comes back pass or fail: a test suite, a build exit code, a linter output. Evidence-based signals let it iterate on its own until the work is demonstrably correct, and evidence beats the model's assertion that it succeeded every single time.

Which gate you use depends on the task, and the options form a ladder rather than a switch. Whichever rung you pick, when the requirements really are ambiguous Claude can call the AskUserQuestion tool instead of guessing, so verification runs against the intent you meant and not the one it inferred.

Verification strategies

StrategyDescriptionTechnical Criteria Needed
UI/UX ChangesVisual correctness of designScreenshot comparison; browser DOM state; CSS property validation.
Bug FixesRoot cause resolutionSuccessful build exit codes (0); passing unit/integration tests; log diffs.
Logic/CorrectnessAlgorithmic accuracyPassing specific test cases; linter outputs; type-checker success.
Security ReviewVulnerability preventionClean scans from security subagents; static analysis tool reports.

For high-stakes implementation, spawn a verification subagent: a fresh model instance that reviews the primary agent's work. A second opinion from a subagent that didn't write the code is worth more than the same model checking itself, because the verifier's job is to refute the result, not defend it. You end up with more confidence and less manual review, and your own role shifts to reading the evidence at the end.

Four ways to enforce verification, from loosest to strictest

The check itself is only half the decision. The other half is how hard it gates the stop. Four rungs, each trading setup effort for attention you get back.

The loosest is the prompt: ask Claude to run the check and iterate inside the same message. No configuration, works on any task today, and nothing whatsoever stops the model from declaring victory early. A /goal condition is one rung up, because a separate evaluator re-checks it after every turn and Claude keeps working until the goal resolves. That one survives the model losing the thread mid-session.

Stricter still is a Stop hook: your check runs as a script and deterministically blocks the turn from ending until it passes. A hook cannot be reasoned with, which is the point. It does have a ceiling: Claude Code overrides it and ends the turn after eight consecutive blocks, so a permanently failing gate stalls instead of looping forever. Strictest of all is a second opinion: a verification subagent, or a workflow where a fresh model tries to refute its own findings, so the agent doing the work is never the one grading it.

Below all four sits a cheaper habit: a PostToolUse hook that runs your type-checker or linter after every single edit. It catches a mistake while it is one file deep instead of after it has cascaded. That is also the answer to Claude reporting a task complete when it is not — an agent that says "done" over handlers with empty error branches is not lying so much as using the only signal it has. Wire the check to the stop and "done" starts meaning done.

Then ask for the artifact, every time: the test output, the command and what it returned, the screenshot. Reading evidence is faster than re-running the verification yourself, and it works for sessions you were not watching. Tell Claude to address root causes too, because an agent optimizing for a green check will happily suppress the error instead of fixing it.

Control how hard Claude thinks

Reasoning effort is a dial, and almost nobody touches it. The thinking keywords escalate in plain language: think, then think hard, then think harder, then ultrathink. You type them as ordinary words in the prompt, with no configuration change and no model switch. Most tasks do not need any of them. The ones that do are the architectural decisions where a mediocre answer costs hours downstream. Asked to design a service split, standard mode returned three reasonable options; the higher-effort run surfaced two constraints that had not come up at all — cross-service transaction boundaries, and the cost of onboarding the existing monitoring setup. The final choice changed completely. You can also set an effort level explicitly, and dialing it down for mechanical work saves real tokens.

The related move is splitting the model across phases. Use the more capable model for planning and advisory work, then hand execution to a faster one once the approach is settled. You are paying the premium where judgment happens rather than on every generated line.

Both dials point at the same weakness. The model's default failure of taste is over-engineering, and left alone it reaches for abstraction layers and flexibility nobody asked for. Ask for the simplest thing that could possibly work, and make Claude critique its own output before it writes: name the problems, the cases it missed, what a reviewer would flag. Self-critique before the edit is much cheaper than a review after it.

CLAUDE.md: short, specific, and pruned often

CLAUDE.md holds your project's persistent memory. Run /init to generate a starter file with your project's specific build commands, code style, and non-obvious conventions. It gets read at the start of every session, which is how Claude gets context it cannot infer from the source code alone. It also rots in two specific ways: "Instruction Staleness," where rules outlive the thing they described, and "Content Fragility," where so many rules pile up that the model starts ignoring the important ones.

So prune it, ruthlessly. If an instruction is self-evident (e.g., "write clean code"), or if Claude has clearly picked the pattern up from the existing codebase, delete the rule. Bloat increases the deletion hazard and feeds "Imperfect Recall." Treat the file as a symptom log too: if Claude keeps asking questions the file already answers, the phrasing is ambiguous and needs a technical rewrite, not a second copy of the same rule.

Project memory guidelines

✅ Include in CLAUDE.md❌ Exclude from CLAUDE.md
Specific build/test commands (e.g., make docker-build)Standard language conventions (e.g., "use camelCase")
Non-obvious architectural decisionsFrequently changing data or versions
Required environment variables and setupLong tutorials or documentation links
Project-specific branch and PR naming rulesVague practices like "ensure high quality"

A good CLAUDE.md describes your specific environment, not software engineering in general. Concrete commands first:

markdown
# Code style
 
- Use ES modules (import/export) syntax only.
- Prefer functional components over classes in /src/ui.
 
# Workflow
 
- Run `npm run lint` after every file edit.
- IMPORTANT: All database migrations must include a rollback script in /migrations/down.

Turn every correction into a permanent rule

Pruning keeps the file readable. What makes it valuable is the opposite habit: end every correction with an instruction to update the file so the mistake cannot recur. One developer who adopted this measured the effect over four days. Corrections ran about once every three to four interactions on day one, and once every eight to ten by day four. The file grew from 127 lines to 156 in that time, and every new line came from a real failure instead of a guess about what might go wrong.

Density is the constraint that makes this work. Around 60 lines is where adherence is best and 200 is the practical ceiling; past that, rules further down get quietly deprioritized. The same developer's file went from 847 lines to 127 in a single 40-minute pass, cutting everything Claude already did correctly by default. Teams that keep theirs near 2,500 tokens report the same thing. When the file has to hold more than that, split it instead of lengthening it: a root file with the universal rules, and per-directory files alongside the packages they govern. Conditional blocks do the same job inside one file — rules wrapped in <important if="language=go"> simply do not exist for Claude in a session where it is writing Python.

A few commands do the maintenance for you. /init generates a starter from your project structure, /context confirms it actually loaded, and /doctor proposes cuts for anything derivable from the codebase. Files can import others with @path/to/import. And emphasis is zero-sum: marking one line IMPORTANT makes it stand out, marking ten makes none of them stand out.

Some teams push state out of CLAUDE.md entirely, into files the agent maintains: a decision log recording what was decided, the reasoning, and which alternatives were rejected, plus a log of failed approaches recording what did not compile and what finally did. The second one exists because an approach that failed on Tuesday is otherwise a fresh idea again on Friday.

Rules worth hardcoding into your instructions file

Some instructions earn permanent residence because each one blocks a specific, recurring failure. Start by locking the stack: name the language, framework, package manager, database, and linter, and tell Claude to flag conflicts but use the defined stack anyway. Without that rule the model defaults to whatever it saw most in training and proposes abstractions your project cannot take. Then add a scope restrictor. Modify only what the current task touches, note secondary issues instead of fixing them. That is what stops the drive-by refactor where a one-line query fix arrives bundled with reorganized imports and renamed variables, turning a reviewable diff into an unreviewable one.

Next, a hard wall around destructive work. Before deleting a file, overwriting code, dropping records, or running anything with external side effects like a deployment or a migration, the agent stops, lists exactly what will be affected, and waits for explicit confirmation in the current message. Claude Code has real filesystem access; this is the rule that keeps one misread prompt from being expensive. Banning filler openers belongs here too, for a much smaller reason: when you are iterating fast, a preamble before every answer is friction you pay for on every single turn.

The last group comes from the failure modes Andrej Karpathy has catalogued in coding models. Demand the simplest code that could possibly work, with no abstractions or flexible layers nobody requested. Require the agent to say when it is unsure — about a library's behavior, an endpoint, an approach — instead of filling the gap with a plausible guess. That gap is where confident invented API calls come from. And close every task with a strict list: files changed, one line per file, plus any follow-up needed. After a multi-file refactor that list is the difference between reviewing the change and hunting for it.

Subagents for investigation and adversarial review

Subagents are specialized assistants that run in their own context windows, which is the whole point: they spend their attention budget instead of yours. The built-in ones, "Explore" for read-only research and "Plan" for strategy, can search a large codebase or read a verbose log and hand back a paragraph, without flooding your main history. The lead agent's reasoning quality depends on that isolation.

A subagent running in its own isolated context, separate from the main conversation

Foreground and background subagents behave differently. Foreground subagents block your main conversation until they finish and pass permission prompts directly to you. Background subagents run concurrently while you keep working; if one needs permission for a tool call, Claude Code surfaces a prompt in your main session and names the specific subagent asking for it, so you get parallel workstreams without giving up security control.

The pattern worth stealing is "Writer/Reviewer." Hand a diff to a fresh subagent for adversarial review. Because that subagent sees only the code and your criteria, never the conversation that led to the change, it judges security vulnerabilities or logic gaps without inheriting the reasoning that produced them. Git worktrees keep these agents from colliding, giving each one its own repository copy branched from HEAD.

Two system limits will stop a session before you understand why. By default, Claude Code allows up to 20 concurrent subagents and a nesting depth of 3 layers, and a subagent at the depth limit that tries to spawn another gets an error back from the Agent tool. Use /tasks to watch what is running in the background and steer anything drifting off-track.

Run several sessions at once

The subagent version of Writer/Reviewer has a bigger sibling: stop thinking of Claude Code as an assistant you talk to and start treating it as capacity you schedule. Boris Cherny, who built Claude Code, runs five sessions in his terminal numbered one through five, with notifications telling him which one needs input, plus another five to ten in the browser, sometimes fifteen at once.

The discipline that makes that work is one responsibility per session. A developer who tried it with three terminal sessions and two browser ones assigned the API routes to one, the dashboard components to another, and debugging to a third. The first hour felt slower because of the context switching. By the second, the bottleneck had moved from waiting on the model to reviewing its output: six components shipped in 4.5 hours against a normal three to four.

Isolation is what keeps this from turning into merge pain. claude -w launches a session inside a git worktree, so each instance has its own working directory and branch; combine that with tmux panes and you can watch several at once. Running parallel sessions against the same checkout is where it goes wrong — two sessions editing the same utility file is a conflict you created yourself. Agent teams and dynamic workflows push the same idea further when you want the coordination handled for you.

The part nobody advertises is how many of these you throw away. Cherny reports discarding 10 to 20 percent of sessions; the developer following his tips landed near 15 percent and concluded he was still killing them too late, with two of the abandoned ones burning more than twenty minutes before he pulled the plug. The skill, then, is recognizing a rabbit hole inside about five minutes. A dead session is a sunk cost, and dragging it forward costs more than starting again with what you just learned.

Rewind, resume, and hand off

Conversations are persistent and reversible, and the controls for that are worth learning before the session where you need them. Esc stops Claude mid-action while preserving context, so you can redirect instead of starting over. Esc twice, or /rewind, opens the rewind menu, which restores more selectively than people expect: conversation only, code only, both, or a summary from a chosen message. "Undo that" asks Claude to revert its own changes.

There is one limit that matters, and it bites hardest when you have stopped thinking about it — checkpoints only track changes made through the file-editing tools, so anything a Bash command or an external process did is not captured. This is not a replacement for git, and treating it as one is how you lose work.

Because checkpoints make experiments cheap, you can tell Claude to try the risky approach and rewind if it does not pan out, rather than planning every move in advance. Checkpoints are saved with the conversation, so closing the terminal and resuming later still leaves them available.

Across sittings, claude --continue picks up the last conversation and claude --resume lets you choose from a list. Name sessions with /rename and treat them like branches, one per workstream, so oauth-migration is findable next week. However you resume, end a working session by having Claude write a short summary: what was completed, what is in progress, and the exact next step. That handoff note is what lets the next session start with clean context instead of an archaeology exercise.

Permissions and auto mode

"Auto mode" is the default for Pro, Max, and Team plans, and the reason is permission fatigue. In manual mode, users approve roughly 97% of prompts, often clicking through without reading. A prompt that always gets a yes is not a security control, it is a speed bump. Auto mode replaces it with a specialized classifier that reviews tool calls automatically and blocks the actions that are irreversible, destructive, or directed outside your local environment.

Testing says the swap is the safer one. In a controlled study of 1,053 testers, humans caught only 13.6% of dangerous commands, while the classifier caught 89%. Further adversarial by Apollo Research hardened it, reducing the miss rate on synthetic attacks to approximately 7%. The design targets mass process kills, unauthorized data exfiltration, and privilege escalation.

Configure around it. Allowlist the routine, safe commands like npm run lint or git commit, and put "hard-deny" rules on high-risk actions such as sending code to external URLs, so they need a manual override even in auto mode. Three blocks in a row and Claude Code falls back to manual approval, which is its way of telling you something in your setup is fighting the classifier.

None of this makes high-stakes production infrastructure safe. For critical changes, switch back to manual mode and read every edit and command yourself. Auto mode exists to unblock legitimate work so your attention is still there for the 3% of decisions that actually matter.

Choosing the right extension mechanism: skill, hook, MCP, or plugin

Extending Claude Code is mostly a question of how much determinism you need. Four options:

Comparison of the four Claude Code extension mechanisms: Skill, Hook, MCP and Plugin

  1. Model Context Protocol (MCP):
    • Connects Claude to external data sources.
    • Example: Use claude mcp add to integrate Jira, Figma, or production databases.
  2. Hooks:
    • Deterministic, mandatory gates that run scripts at specific lifecycle points.
    • Example: A PreToolUse hook that scans SQL commands for DROP or DELETE and exits with code 2 to block the operation.
  3. Skills:
    • Advisory workflows or domain knowledge stored in .claude/skills/.
    • Example: A fix-issue skill that guides Claude through a standard 8-step PR creation process.
  4. Plugins:
    • Bundled units of skills, hooks, and MCP servers.
    • Example: A "Security Auditor" plugin that adds specific tools and automated hooks for vulnerability scanning.

Of the four, hooks are the one that enforces anything. CLAUDE.md instructions advise; a hook runs. A PreToolUse hook that programmatically blocks write operations gives you read-only database access as a hard security boundary, not a request the agent can talk itself out of.

Skills make the opposite trade: reusable workflows Claude loads on demand. Because they are preloaded per task, they keep your CLAUDE.md from bloating. Use skills for recurring project-specific tasks like "Prepare Release Notes" or "Validate API Schema," and use MCP when the work has to reach a third-party SaaS tool from your local environment.

Configuration beats prompting

There is a habit worth breaking: re-establishing the same constraints at the top of every request. "Only read files, don't modify anything. Focus on the internal package. Use our error handling conventions." Every single time. The alternative is to put the constraints in files, where they hold whether or not you remembered to type them. The .claude/ directory takes commands/ for reusable slash commands, agents/ for subagents with explicitly restricted tool access, and skills/ for portable knowledge modules.

The difference is enforcement rather than convenience. An agent defined with Read, Grep, and Glob and nothing else physically cannot modify a file, no matter what the conversation asks it to do. The prompt requests a constraint; the configuration imposes one. Once a reviewer agent exists, "don't modify anything" disappears from your prompts because it is no longer a thing you have to say. Skills can be isolated the same way — context: fork in the frontmatter runs the skill in its own subagent and discards that context when it finishes, so a skill that reads forty files to produce a report does not leave forty files sitting in your main session afterwards.

Hooks are the strongest version of this, and they are architecturally different from everything else here: PreToolUse, PostToolUse, and Stop run outside the model's reasoning loop, consume no tokens, and interrupt nothing. They are side-channel automation attached to Claude's actions, not part of them. A PostToolUse hook running your formatter after every write means formatting is never something you ask for. A PreToolUse hook intercepts irreversible actions — deletions, overwrites, force-pushes — and demands confirmation before they proceed.

Two smaller rules round this out. Anything you do more than twice a day should become a slash command; /commit-push-pr gets used dozens of times daily by the people who wrote it. And when you write a skill, the highest-signal section is not the overview or the examples. It is Gotchas: the failure modes Claude actually hit in real use, written down when they happened. Build that section first and update it every time something breaks, because verified failures compound in a way that explanatory prose does not.

/sandbox is the last piece. It runs shell commands in an isolated environment where the blast radius is small enough to lower the approval threshold — reportedly around 84% fewer permission prompts.

Automate beyond the interactive session

claude -p "your prompt" runs Claude without an interactive terminal, which is how it gets into CI pipelines, pre-commit hooks, and data pipelines. The output formats let you parse the result: plain text by default, --output-format json for a single object with a result field, and --output-format stream-json --verbose for one JSON object per line when you want to process output as it arrives.

Fanning out is where this stops being a convenience. For a large migration, have Claude write the list of files that need changing to a file, then loop over it, scoping each unattended invocation with --allowedTools so the runs can only do what you intended. Refine the prompt against the first two or three files before turning it loose on two thousand. In a git repository, /batch <instruction> does the orchestration for you, splitting the change across five to thirty subagents that each work in their own worktree and open a pull request. On a schedule, /loop runs a workflow repeatedly on your machine: /loop 30m /code-review every thirty minutes. That reaches something CI structurally cannot, because CI only ever sees a merged diff, while a local loop sees your current working state and the constraints established this session.

Two details save real time here. When you drive Claude through the Agent SDK instead of the CLI, --bare skips context discovery: locating CLAUDE.md files, loading configuration, checking the environment. That happens once in an interactive session but on every invocation in batch. A daily pipeline running roughly 300 files with one agent each went from about 40 minutes to 18. The other detail is to prefer command-line tools for anything external. gh, aws, gcloud, sentry-cli are the most context-efficient way to reach a service, far cheaper than scraping an API by hand, and Claude picks up unfamiliar ones readily. Telling it to run foo-cli --help and then use the tool works more often than not.

When several agents share one memory

Once you are running several agents against the same project, they each keep their own memory, and you become the integration layer — copying decisions between windows by hand. The obvious fixes do not hold up. A shared folder of documents stores text, not knowledge: nothing in it says that a deploy, a service, and a person are different kinds of thing, so a question whose answer is spread across two hundred files means reading all two hundred or hallucinating. A similarity search over fails the other way. It returns passages that sound like your question and holds no relationships at all, so it cannot start at a customer, follow it to their open tickets, and land on the commit that probably broke things.

Shared memory has to do three jobs: assemble context across connected facts, persist new knowledge after the task ends, and coordinate many writers without anyone clobbering anyone.

Coordination is the genuinely new one, and it needs a shared vocabulary before it needs anything else. Three agents recording the same event as "deploy," "deployment," and "release" produce a store where the query for deploys returns a partial answer that looks complete. Agreeing on the entity types and how they are identified, before anyone writes, is what prevents that.

The coordination model to copy is version control. Agents do not write to shared truth directly; each writes to its own branch, works in parallel without blocking anyone, and produces a proposal. Every merge needs approval: yours, or a policy rule that auto-approves routine low-risk changes from a trusted agent while routing anything larger to a human. One rule generalizes furthest, and it is the one I would carry into any setup like this. An agent never approves its own change. Non-overlapping edits merge cleanly, and genuine disagreements surface as explicit conflicts naming the record, the field, and both competing values, instead of one write silently winning.

Because nothing is overwritten in place, every accepted change carries who made it, when, and what came before. That is an audit trail without a separate audit log, and a state you can read exactly as it was before any merge. It is also deliberate machinery, not a default to reach for early: writes land in tens to hundreds of milliseconds rather than under one, and if you only need , or one writer, or high-throughput transactions, the simpler tool is the right one.

Common failure patterns and how to get out of them

Most bad sessions are recognizable early. The classic is the "Kitchen Sink Session": one window, too many unrelated tasks, a context bloated with things that stopped mattering an hour ago, and reasoning errors following right behind. The fix costs nothing: /clear between features.

The "Over-specified CLAUDE.md" announces itself too. If Claude asks questions your instructions already answer, the file is long enough that the model is missing rules, and the answer is deletion rather than more text. And when a specific correction fails twice, stop; do not try a third time. Follow the Two-Strike Rule: /clear the session and start fresh with a more detailed, refined prompt built from what the failed attempts taught you. Of everything here, that is the rule I would defend hardest, because the third attempt is a negotiation with a context that has already learned the wrong thing.

If a technical approach fails outright, /rewind puts you back at a known-good state without needing a git commit for every minor iteration. Use /btw for side-explorations that should stay out of the main implementation history.

"Infinite exploration" is the failure that looks like diligence. Ask Claude to "investigate" something without a boundary and it reads hundreds of files, filling the context before it has answered anything. Scope the investigation to a directory and a question, or push it into a subagent so the reading happens somewhere that is not your main session.

The quietest failure is the "Trust-then-Verify Gap." A plausible implementation with no tests is not a finished implementation, however good the diff looks, so do not ship it. Require evidence-based signals. If you cannot verify the work with a script or a test, the task is not done, and the feedback loop that would have caught the problem does not exist yet.

These are defaults, not laws

Everything above is a starting point that works in general, and a few of the rules earn an explicit counterweight. Planning has overhead. One developer spent eight minutes planning a thirty-second change before that sank in. It pays when you are uncertain about the approach, when the change spans several files, or when you do not know the code you are about to modify. On anything smaller it is a tax.

The adversarial reviewer needs the same skepticism applied to it. A reviewer asked to find gaps will find some, because that is what you asked for, and chasing every one of them produces exactly the over-engineering you were trying to avoid: extra abstraction layers, defensive code, tests for cases that cannot occur. Tell the reviewer to flag only what affects correctness or the stated requirements, and treat the rest as optional.

It is also worth noticing what the person who built Claude Code actually runs. Cherny describes his own setup as "surprisingly vanilla" — no elaborate stack of MCP servers, no two-thousand-line instructions file. The power comes from disciplined fundamentals: plan before you code, verify the work, keep context clean, compound what you learn. If the author of the tool is not over-engineering his configuration, the hours you spend tuning yours are probably not where the gains are.

So what you are actually building is judgment. Sometimes you should let context accumulate, because you are deep in one problem and the history is the valuable part. Sometimes the right move is to skip the plan and let Claude explore, or to leave the prompt vague because you want to see how the problem gets interpreted before you constrain it. Pay attention to what worked: when the output was good, notice the prompt structure, the context you supplied, the mode you were in; when it struggled, ask whether the context was noisy, the prompt vague, or the task too big for one pass.

The mechanics belong to the agent now: file manipulation, syntax, the command that finally exits clean. What is left for you is the architecture, the constraints, and a precise definition of done. That was the hard part before any of this existed, and it still is.

References

Check yourself

Three quick questions to see whether the main ideas stuck.

  1. How should the work be split between you and Claude Code?
  2. What makes an agentic loop trustworthy?
  3. What should you do every time you correct Claude?

Share this article

AI glossary