best-practices.md +577 −0 added
1> ## Documentation Index
2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
3> Use this file to discover all available pages before exploring further.
4
5# Best practices for Claude Code
6
7> Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.
8
9Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely.
10
11This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements.
12
13But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.
14
15This guide covers patterns that have proven effective across Anthropic's internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works under the hood, see [How Claude Code works](/en/how-claude-code-works).
16
17***
18
19Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills.
20
21Claude's context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.
22
23This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. To see how a session fills up in practice, [watch an interactive walkthrough](/en/context-window) of what loads at startup and what each file read costs. Track context usage continuously with a [custom status line](/en/statusline), and see [Reduce token usage](/en/costs#reduce-token-usage) for strategies on reducing token usage.
24
25***
26
27## Give Claude a way to verify its work
28
29<Tip>
30 Include tests, screenshots, or expected outputs so Claude can check itself. This is the single highest-leverage thing you can do.
31</Tip>
32
33Claude performs dramatically better when it can verify its own work, like run tests, compare screenshots, and validate outputs.
34
35Without clear success criteria, it might produce something that looks right but actually doesn't work. You become the only feedback loop, and every mistake requires your attention.
36
37| Strategy | Before | After |
38| ------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
39| **Provide verification criteria** | *"implement a function that validates email addresses"* | *"write a validateEmail function. example test cases: [user@example.com](mailto:user@example.com) is true, invalid is false, [user@.com](mailto:user@.com) is false. run the tests after implementing"* |
40| **Verify UI changes visually** | *"make the dashboard look better"* | *"\[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them"* |
41| **Address root causes, not symptoms** | *"the build is failing"* | *"the build fails with this error: \[paste error]. fix it and verify the build succeeds. address the root cause, don't suppress the error"* |
42
43UI changes can be verified using the [Claude in Chrome extension](/en/chrome). It opens new tabs in your browser, tests the UI, and iterates until the code works.
44
45Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid.
46
47***
48
49## Explore first, then plan, then code
50
51<Tip>
52 Separate research and planning from implementation to avoid solving the wrong problem.
53</Tip>
54
55Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode) to separate exploration from execution.
56
57The recommended workflow has four phases:
58
59<Steps>
60 <Step title="Explore">
61 Enter plan mode. Claude reads files and answers questions without making changes.
62
63 ```txt claude (plan mode) theme={null}
64 read /src/auth and understand how we handle sessions and login.
65 also look at how we manage environment variables for secrets.
66 ```
67 </Step>
68
69 <Step title="Plan">
70 Ask Claude to create a detailed implementation plan.
71
72 ```txt claude (plan mode) theme={null}
73 I want to add Google OAuth. What files need to change?
74 What's the session flow? Create a plan.
75 ```
76
77 Press `Ctrl+G` to open the plan in your text editor for direct editing before Claude proceeds.
78 </Step>
79
80 <Step title="Implement">
81 Switch out of plan mode and let Claude code, verifying against its plan.
82
83 ```txt claude (default mode) theme={null}
84 implement the OAuth flow from your plan. write tests for the
85 callback handler, run the test suite and fix any failures.
86 ```
87 </Step>
88
89 <Step title="Commit">
90 Ask Claude to commit with a descriptive message and create a PR.
91
92 ```txt claude (default mode) theme={null}
93 commit with a descriptive message and open a PR
94 ```
95 </Step>
96</Steps>
97
98<Callout>
99 Plan mode is useful, but also adds overhead.
100
101 For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly.
102
103 Planning is most useful when you're uncertain about the approach, when the change modifies multiple files, or when you're unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan.
104</Callout>
105
106***
107
108## Provide specific context in your prompts
109
110<Tip>
111 The more precise your instructions, the fewer corrections you'll need.
112</Tip>
113
114Claude can infer intent, but it can't read your mind. Reference specific files, mention constraints, and point to example patterns.
115
116| Strategy | Before | After |
117| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
118| **Scope the task.** Specify which file, what scenario, and testing preferences. | *"add tests for foo.py"* | *"write a test for foo.py covering the edge case where the user is logged out. avoid mocks."* |
119| **Point to sources.** Direct Claude to the source that can answer a question. | *"why does ExecutionFactory have such a weird api?"* | *"look through ExecutionFactory's git history and summarize how its api came to be"* |
120| **Reference existing patterns.** Point Claude to patterns in your codebase. | *"add a calendar widget"* | *"look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase."* |
121| **Describe the symptom.** Provide the symptom, the likely location, and what "fixed" looks like. | *"fix the login bug"* | *"users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it"* |
122
123Vague prompts can be useful when you're exploring and can afford to course-correct. A prompt like `"what would you improve in this file?"` can surface things you wouldn't have thought to ask about.
124
125### Provide rich content
126
127<Tip>
128 Use `@` to reference files, paste screenshots/images, or pipe data directly.
129</Tip>
130
131You can provide rich data to Claude in several ways:
132
133* **Reference files with `@`** instead of describing where code lives. Claude reads the file before responding.
134* **Paste images directly**. Copy/paste or drag and drop images into the prompt.
135* **Give URLs** for documentation and API references. Use `/permissions` to allowlist frequently-used domains.
136* **Pipe in data** by running `cat error.log | claude` to send file contents directly.
137* **Let Claude fetch what it needs**. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files.
138
139***
140
141## Configure your environment
142
143A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see [Extend Claude Code](/en/features-overview).
144
145### Write an effective CLAUDE.md
146
147<Tip>
148 Run `/init` to generate a starter CLAUDE.md file based on your current project structure, then refine over time.
149</Tip>
150
151CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context it can't infer from code alone.
152
153The `/init` command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.
154
155There's no required format for CLAUDE.md files, but keep it short and human-readable. For example:
156
157```markdown CLAUDE.md theme={null}
158# Code style
159- Use ES modules (import/export) syntax, not CommonJS (require)
160- Destructure imports when possible (eg. import { foo } from 'bar')
161
162# Workflow
163- Be sure to typecheck when you're done making a series of code changes
164- Prefer running single tests, and not the whole test suite, for performance
165```
166
167CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use [skills](/en/skills) instead. Claude loads them on demand without bloating every conversation.
168
169Keep it concise. For each line, ask: *"Would removing this cause Claude to make mistakes?"* If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!
170
171| ✅ Include | ❌ Exclude |
172| ---------------------------------------------------- | -------------------------------------------------- |
173| Bash commands Claude can't guess | Anything Claude can figure out by reading code |
174| Code style rules that differ from defaults | Standard language conventions Claude already knows |
175| Testing instructions and preferred test runners | Detailed API documentation (link to docs instead) |
176| Repository etiquette (branch naming, PR conventions) | Information that changes frequently |
177| Architectural decisions specific to your project | Long explanations or tutorials |
178| Developer environment quirks (required env vars) | File-by-file descriptions of the codebase |
179| Common gotchas or non-obvious behaviors | Self-evident practices like "write clean code" |
180
181If Claude keeps doing something you don't want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts.
182
183You can tune instructions by adding emphasis (e.g., "IMPORTANT" or "YOU MUST") to improve adherence. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time.
184
185CLAUDE.md files can import additional files using `@path/to/import` syntax:
186
187```markdown CLAUDE.md theme={null}
188See @README.md for project overview and @package.json for available npm commands.
189
190# Additional Instructions
191- Git workflow: @docs/git-instructions.md
192- Personal overrides: @~/.claude/my-project-instructions.md
193```
194
195You can place CLAUDE.md files in several locations:
196
197* **Home folder (`~/.claude/CLAUDE.md`)**: applies to all Claude sessions
198* **Project root (`./CLAUDE.md`)**: check into git to share with your team
199* **Project root (`./CLAUDE.local.md`)**: personal project-specific notes; add this file to your `.gitignore` so it isn't shared with your team
200* **Parent directories**: useful for monorepos where both `root/CLAUDE.md` and `root/foo/CLAUDE.md` are pulled in automatically
201* **Child directories**: Claude pulls in child CLAUDE.md files on demand when working with files in those directories
202
203### Configure permissions
204
205<Tip>
206 Use [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) to let a classifier handle approvals, `/permissions` to allowlist specific commands, or `/sandbox` for OS-level isolation. Each reduces interruptions while keeping you in control.
207</Tip>
208
209By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you're not really reviewing anymore, you're just clicking through. There are three ways to reduce these interruptions:
210
211* **Auto mode**: a separate classifier model reviews commands and blocks only what looks risky: scope escalation, unknown infrastructure, or hostile-content-driven actions. Best when you trust the general direction of a task but don't want to click through every step
212* **Permission allowlists**: permit specific tools you know are safe, like `npm run lint` or `git commit`
213* **Sandboxing**: enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries
214
215Read more about [permission modes](/en/permission-modes), [permission rules](/en/permissions), and [sandboxing](/en/sandboxing).
216
217### Use CLI tools
218
219<Tip>
220 Tell Claude Code to use CLI tools like `gh`, `aws`, `gcloud`, and `sentry-cli` when interacting with external services.
221</Tip>
222
223CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the `gh` CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without `gh`, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits.
224
225Claude is also effective at learning CLI tools it doesn't already know. Try prompts like `Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.`
226
227### Connect MCP servers
228
229<Tip>
230 Run `claude mcp add` to connect external tools like Notion, Figma, or your database.
231</Tip>
232
233With [MCP servers](/en/mcp), you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.
234
235### Set up hooks
236
237<Tip>
238 Use hooks for actions that must happen every time with zero exceptions.
239</Tip>
240
241[Hooks](/en/hooks-guide) run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.
242
243Claude can write hooks for you. Try prompts like *"Write a hook that runs eslint after every file edit"* or *"Write a hook that blocks writes to the migrations folder."* Edit `.claude/settings.json` directly to configure hooks by hand, and run `/hooks` to browse what's configured.
244
245### Create skills
246
247<Tip>
248 Create `SKILL.md` files in `.claude/skills/` to give Claude domain knowledge and reusable workflows.
249</Tip>
250
251[Skills](/en/skills) extend Claude's knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with `/skill-name`.
252
253Create a skill by adding a directory with a `SKILL.md` to `.claude/skills/`:
254
255```markdown .claude/skills/api-conventions/SKILL.md theme={null}
256---
257name: api-conventions
258description: REST API design conventions for our services
259---
260# API Conventions
261- Use kebab-case for URL paths
262- Use camelCase for JSON properties
263- Always include pagination for list endpoints
264- Version APIs in the URL path (/v1/, /v2/)
265```
266
267Skills can also define repeatable workflows you invoke directly:
268
269```markdown .claude/skills/fix-issue/SKILL.md theme={null}
270---
271name: fix-issue
272description: Fix a GitHub issue
273disable-model-invocation: true
274---
275Analyze and fix the GitHub issue: $ARGUMENTS.
276
2771. Use `gh issue view` to get the issue details
2782. Understand the problem described in the issue
2793. Search the codebase for relevant files
2804. Implement the necessary changes to fix the issue
2815. Write and run tests to verify the fix
2826. Ensure code passes linting and type checking
2837. Create a descriptive commit message
2848. Push and create a PR
285```
286
287Run `/fix-issue 1234` to invoke it. Use `disable-model-invocation: true` for workflows with side effects that you want to trigger manually.
288
289### Create custom subagents
290
291<Tip>
292 Define specialized assistants in `.claude/agents/` that Claude can delegate to for isolated tasks.
293</Tip>
294
295[Subagents](/en/sub-agents) run in their own context with their own set of allowed tools. They're useful for tasks that read many files or need specialized focus without cluttering your main conversation.
296
297```markdown .claude/agents/security-reviewer.md theme={null}
298---
299name: security-reviewer
300description: Reviews code for security vulnerabilities
301tools: Read, Grep, Glob, Bash
302model: opus
303---
304You are a senior security engineer. Review code for:
305- Injection vulnerabilities (SQL, XSS, command injection)
306- Authentication and authorization flaws
307- Secrets or credentials in code
308- Insecure data handling
309
310Provide specific line references and suggested fixes.
311```
312
313Tell Claude to use subagents explicitly: *"Use a subagent to review this code for security issues."*
314
315### Install plugins
316
317<Tip>
318 Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.
319</Tip>
320
321[Plugins](/en/plugins) bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic. If you work with a typed language, install a [code intelligence plugin](/en/discover-plugins#code-intelligence) to give Claude precise symbol navigation and automatic error detection after edits.
322
323For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/en/features-overview#match-features-to-your-goal).
324
325***
326
327## Communicate effectively
328
329The way you communicate with Claude Code significantly impacts the quality of results.
330
331### Ask codebase questions
332
333<Tip>
334 Ask Claude questions you'd ask a senior engineer.
335</Tip>
336
337When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer:
338
339* How does logging work?
340* How do I make a new API endpoint?
341* What does `async move { ... }` do on line 134 of `foo.rs`?
342* What edge cases does `CustomerOnboardingFlowImpl` handle?
343* Why does this code call `foo()` instead of `bar()` on line 333?
344
345Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly.
346
347### Let Claude interview you
348
349<Tip>
350 For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the `AskUserQuestion` tool.
351</Tip>
352
353Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.
354
355```text theme={null}
356I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.
357
358Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.
359
360Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.
361```
362
363Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference.
364
365***
366
367## Manage your session
368
369Conversations are persistent and reversible. Use this to your advantage!
370
371### Course-correct early and often
372
373<Tip>
374 Correct Claude as soon as you notice it going off track.
375</Tip>
376
377The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.
378
379* **`Esc`**: stop Claude mid-action with the `Esc` key. Context is preserved, so you can redirect.
380* **`Esc + Esc` or `/rewind`**: press `Esc` twice or run `/rewind` to open the rewind menu and restore previous conversation and code state, or summarize from a selected message.
381* **`"Undo that"`**: have Claude revert its changes.
382* **`/clear`**: reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.
383
384If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run `/clear` and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.
385
386### Manage context aggressively
387
388<Tip>
389 Run `/clear` between unrelated tasks to reset context.
390</Tip>
391
392Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.
393
394During long sessions, Claude's context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.
395
396* Use `/clear` frequently between tasks to reset the context window entirely
397* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions
398* For more control, run `/compact <instructions>`, like `/compact Focus on the API changes`
399* To compact only part of the conversation, use `Esc + Esc` or `/rewind`, select a message checkpoint, and choose **Summarize from here**. This condenses messages from that point forward while keeping earlier context intact.
400* Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization
401* For quick questions that don't need to stay in context, use [`/btw`](/en/interactive-mode#side-questions-with-%2Fbtw). The answer appears in a dismissible overlay and never enters conversation history, so you can check a detail without growing context.
402
403### Use subagents for investigation
404
405<Tip>
406 Delegate research with `"use subagents to investigate X"`. They explore in a separate context, keeping your main conversation clean for implementation.
407</Tip>
408
409Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:
410
411```text theme={null}
412Use subagents to investigate how our authentication system handles token
413refresh, and whether we have any existing OAuth utilities I should reuse.
414```
415
416The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation.
417
418You can also use subagents for verification after Claude implements something:
419
420```text theme={null}
421use a subagent to review this code for edge cases
422```
423
424### Rewind with checkpoints
425
426<Tip>
427 Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.
428</Tip>
429
430Claude automatically checkpoints before changes. Double-tap `Escape` or run `/rewind` to open the rewind menu. You can restore conversation only, restore code only, restore both, or summarize from a selected message. See [Checkpointing](/en/checkpointing) for details.
431
432Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn't work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later.
433
434<Warning>
435 Checkpoints only track changes made *by Claude*, not external processes. This isn't a replacement for git.
436</Warning>
437
438### Resume conversations
439
440<Tip>
441 Name sessions with `/rename` and treat them like branches: each workstream gets its own persistent context.
442</Tip>
443
444Claude Code saves conversations locally, so when a task spans multiple sittings you don't have to re-explain the context. Run `claude --continue` to pick up the most recent session, or `claude --resume` to choose from a list. Give sessions descriptive names like `oauth-migration` so you can find them later. See [Manage sessions](/en/sessions) for the full set of resume, branch, and naming controls.
445
446***
447
448## Automate and scale
449
450Once you're effective with one Claude, multiply your output with parallel sessions, non-interactive mode, and fan-out patterns.
451
452Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done.
453
454### Run non-interactive mode
455
456<Tip>
457 Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json` for streaming JSON output.
458</Tip>
459
460With `claude -p "your prompt"`, you can run Claude non-interactively, without a session. [Non-interactive mode](/en/headless) is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats let you parse results programmatically: plain text, JSON, or streaming JSON.
461
462```bash theme={null}
463# One-off queries
464claude -p "Explain what this project does"
465
466# Structured output for scripts
467claude -p "List all API endpoints" --output-format json
468
469# Streaming for real-time processing
470claude -p "Analyze this log file" --output-format stream-json
471```
472
473### Run multiple Claude sessions
474
475<Tip>
476 Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.
477</Tip>
478
479Pick the parallel approach that fits how much coordination you want to do yourself:
480
481* [Worktrees](/en/worktrees): run separate CLI sessions in isolated git checkouts so edits don't collide
482* [Desktop app](/en/desktop#work-in-parallel-with-sessions): manage multiple local sessions visually, each in its own worktree
483* [Claude Code on the web](/en/claude-code-on-the-web): run sessions on Anthropic-managed cloud infrastructure in isolated VMs
484* [Agent teams](/en/agent-teams): automated coordination of multiple sessions with shared tasks, messaging, and a team lead
485
486Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won't be biased toward code it just wrote.
487
488For example, use a Writer/Reviewer pattern:
489
490| Session A (Writer) | Session B (Reviewer) |
491| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
492| `Implement a rate limiter for our API endpoints` | |
493| | `Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns.` |
494| `Here's the review feedback: [Session B output]. Address these issues.` | |
495
496You can do something similar with tests: have one Claude write tests, then another write code to pass them.
497
498### Fan out across files
499
500<Tip>
501 Loop through tasks calling `claude -p` for each. Use `--allowedTools` to scope permissions for batch operations.
502</Tip>
503
504For large migrations or analyses, you can distribute work across many parallel Claude invocations:
505
506<Steps>
507 <Step title="Generate a task list">
508 Have Claude list all files that need migrating (e.g., `list all 2,000 Python files that need migrating`)
509 </Step>
510
511 <Step title="Write a script to loop through the list">
512 ```bash theme={null}
513 for file in $(cat files.txt); do
514 claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
515 --allowedTools "Edit,Bash(git commit *)"
516 done
517 ```
518 </Step>
519
520 <Step title="Test on a few files, then run at scale">
521 Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The `--allowedTools` flag restricts what Claude can do, which matters when you're running unattended.
522 </Step>
523</Steps>
524
525You can also integrate Claude into existing data/processing pipelines:
526
527```bash theme={null}
528claude -p "<your prompt>" --output-format json | your_command
529```
530
531Use `--verbose` for debugging during development, and turn it off in production.
532
533### Run autonomously with auto mode
534
535For uninterrupted execution with background safety checks, use [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode). A classifier model reviews commands before they run, blocking scope escalation, unknown infrastructure, and hostile-content-driven actions while letting routine work proceed without prompts.
536
537```bash theme={null}
538claude --permission-mode auto -p "fix all lint errors"
539```
540
541For non-interactive runs with the `-p` flag, auto mode aborts if the classifier repeatedly blocks actions, since there is no user to fall back to. See [when auto mode falls back](/en/permission-modes#when-auto-mode-falls-back) for thresholds.
542
543***
544
545## Avoid common failure patterns
546
547These are common mistakes. Recognizing them early saves time:
548
549* **The kitchen sink session.** You start with one task, then ask Claude something unrelated, then go back to the first task. Context is full of irrelevant information.
550 > **Fix**: `/clear` between unrelated tasks.
551* **Correcting over and over.** Claude does something wrong, you correct it, it's still wrong, you correct again. Context is polluted with failed approaches.
552 > **Fix**: After two failed corrections, `/clear` and write a better initial prompt incorporating what you learned.
553* **The over-specified CLAUDE.md.** If your CLAUDE.md is too long, Claude ignores half of it because important rules get lost in the noise.
554 > **Fix**: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook.
555* **The trust-then-verify gap.** Claude produces a plausible-looking implementation that doesn't handle edge cases.
556 > **Fix**: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it.
557* **The infinite exploration.** You ask Claude to "investigate" something without scoping it. Claude reads hundreds of files, filling the context.
558 > **Fix**: Scope investigations narrowly or use subagents so the exploration doesn't consume your main context.
559
560***
561
562## Develop your intuition
563
564The patterns in this guide aren't set in stone. They're starting points that work well in general, but might not be optimal for every situation.
565
566Sometimes you *should* let context accumulate because you're deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it.
567
568Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass?
569
570Over time, you'll develop intuition that no guide can capture. You'll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate.
571
572## Related resources
573
574* [How Claude Code works](/en/how-claude-code-works): the agentic loop, tools, and context management
575* [Extend Claude Code](/en/features-overview): skills, hooks, MCP, subagents, and plugins
576* [Common workflows](/en/common-workflows): step-by-step recipes for debugging, testing, PRs, and more
577* [CLAUDE.md](/en/memory): store project conventions and persistent context