best-practices.md +596 −0 created
1# Best Practices for Claude Code
2
3> Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.
4
5Claude 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.
6
7This 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.
8
9But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.
10
11This 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).
12
13***
14
15Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills.
16
17Claude'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.
18
19This 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. For detailed strategies on reducing token usage, see [Reduce token usage](/en/costs#reduce-token-usage).
20
21***
22
23## Give Claude a way to verify its work
24
25<Tip>
26 Include tests, screenshots, or expected outputs so Claude can check itself. This is the single highest-leverage thing you can do.
27</Tip>
28
29Claude performs dramatically better when it can verify its own work, like run tests, compare screenshots, and validate outputs.
30
31Without 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.
32
33| Strategy | Before | After |
34| ------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
35| **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"* |
36| **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"* |
37| **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"* |
38
39UI changes can be verified using the [Claude in Chrome extension](/en/chrome). It opens a browser, tests the UI, and iterates until the code works.
40
41Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid.
42
43***
44
45## Explore first, then plan, then code
46
47<Tip>
48 Separate research and planning from implementation to avoid solving the wrong problem.
49</Tip>
50
51Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [Plan Mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to separate exploration from execution.
52
53The recommended workflow has four phases:
54
55<Steps>
56 <Step title="Explore">
57 Enter Plan Mode. Claude reads files and answers questions without making changes.
58
59 ```txt claude (Plan Mode) theme={null}
60 read /src/auth and understand how we handle sessions and login.
61 also look at how we manage environment variables for secrets.
62 ```
63 </Step>
64
65 <Step title="Plan">
66 Ask Claude to create a detailed implementation plan.
67
68 ```txt claude (Plan Mode) theme={null}
69 I want to add Google OAuth. What files need to change?
70 What's the session flow? Create a plan.
71 ```
72 </Step>
73
74 <Step title="Implement">
75 Switch back to Normal Mode and let Claude code, verifying against its plan.
76
77 ```txt claude (Normal Mode) theme={null}
78 implement the OAuth flow from your plan. write tests for the
79 callback handler, run the test suite and fix any failures.
80 ```
81 </Step>
82
83 <Step title="Commit">
84 Ask Claude to commit with a descriptive message and create a PR.
85
86 ```txt claude (Normal Mode) theme={null}
87 commit with a descriptive message and open a PR
88 ```
89 </Step>
90</Steps>
91
92<Callout>
93 Plan Mode is useful, but also adds overhead.
94
95 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.
96
97 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.
98</Callout>
99
100***
101
102## Provide specific context in your prompts
103
104<Tip>
105 The more precise your instructions, the fewer corrections you'll need.
106</Tip>
107
108Claude can infer intent, but it can't read your mind. Reference specific files, mention constraints, and point to example patterns.
109
110| Strategy | Before | After |
111| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
112| **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."* |
113| **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"* |
114| **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."* |
115| **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"* |
116
117Vague 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.
118
119### Provide rich content
120
121<Tip>
122 Use `@` to reference files, paste screenshots/images, or pipe data directly.
123</Tip>
124
125You can provide rich data to Claude in several ways:
126
127* **Reference files with `@`** instead of describing where code lives. Claude reads the file before responding.
128* **Paste images directly**. Copy/paste or drag and drop images into the prompt.
129* **Give URLs** for documentation and API references. Use `/permissions` to allowlist frequently-used domains.
130* **Pipe in data** by running `cat error.log | claude` to send file contents directly.
131* **Let Claude fetch what it needs**. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files.
132
133***
134
135## Configure your environment
136
137A 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).
138
139### Write an effective CLAUDE.md
140
141<Tip>
142 Run `/init` to generate a starter CLAUDE.md file based on your current project structure, then refine over time.
143</Tip>
144
145CLAUDE.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**.
146
147The `/init` command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.
148
149There's no required format for CLAUDE.md files, but keep it short and human-readable. For example:
150
151```markdown CLAUDE.md theme={null}
152# Code style
153- Use ES modules (import/export) syntax, not CommonJS (require)
154- Destructure imports when possible (eg. import { foo } from 'bar')
155
156# Workflow
157- Be sure to typecheck when you're done making a series of code changes
158- Prefer running single tests, and not the whole test suite, for performance
159```
160
161CLAUDE.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.
162
163Keep 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!
164
165| ✅ Include | ❌ Exclude |
166| ---------------------------------------------------- | -------------------------------------------------- |
167| Bash commands Claude can't guess | Anything Claude can figure out by reading code |
168| Code style rules that differ from defaults | Standard language conventions Claude already knows |
169| Testing instructions and preferred test runners | Detailed API documentation (link to docs instead) |
170| Repository etiquette (branch naming, PR conventions) | Information that changes frequently |
171| Architectural decisions specific to your project | Long explanations or tutorials |
172| Developer environment quirks (required env vars) | File-by-file descriptions of the codebase |
173| Common gotchas or non-obvious behaviors | Self-evident practices like "write clean code" |
174
175If 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.
176
177You 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.
178
179CLAUDE.md files can import additional files using `@path/to/import` syntax:
180
181```markdown CLAUDE.md theme={null}
182See @README.md for project overview and @package.json for available npm commands.
183
184# Additional Instructions
185- Git workflow: @docs/git-instructions.md
186- Personal overrides: @~/.claude/my-project-instructions.md
187```
188
189You can place CLAUDE.md files in several locations:
190
191* **Home folder (`~/.claude/CLAUDE.md`)**: Applies to all Claude sessions
192* **Project root (`./CLAUDE.md`)**: Check into git to share with your team, or name it `CLAUDE.local.md` and `.gitignore` it
193* **Parent directories**: Useful for monorepos where both `root/CLAUDE.md` and `root/foo/CLAUDE.md` are pulled in automatically
194* **Child directories**: Claude pulls in child CLAUDE.md files on demand when working with files in those directories
195
196### Configure permissions
197
198<Tip>
199 Use `/permissions` to allowlist safe commands or `/sandbox` for OS-level isolation. This reduces interruptions while keeping you in control.
200</Tip>
201
202By 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 two ways to reduce these interruptions:
203
204* **Permission allowlists**: Permit specific tools you know are safe (like `npm run lint` or `git commit`)
205* **Sandboxing**: Enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries
206
207Alternatively, use `--dangerously-skip-permissions` to bypass all permission checks for contained workflows like fixing lint errors or generating boilerplate.
208
209<Warning>
210 Letting Claude run arbitrary commands can result in data loss, system corruption, or data exfiltration via prompt injection. Only use `--dangerously-skip-permissions` in a sandbox without internet access.
211</Warning>
212
213Read more about [configuring permissions](/en/settings) and [enabling sandboxing](/en/sandboxing#sandboxing).
214
215### Use CLI tools
216
217<Tip>
218 Tell Claude Code to use CLI tools like `gh`, `aws`, `gcloud`, and `sentry-cli` when interacting with external services.
219</Tip>
220
221CLI 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.
222
223Claude 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.`
224
225### Connect MCP servers
226
227<Tip>
228 Run `claude mcp add` to connect external tools like Notion, Figma, or your database.
229</Tip>
230
231With [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.
232
233### Set up hooks
234
235<Tip>
236 Use hooks for actions that must happen every time with zero exceptions.
237</Tip>
238
239[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.
240
241Claude 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."* Run `/hooks` for interactive configuration, or edit `.claude/settings.json` directly.
242
243### Create skills
244
245<Tip>
246 Create `SKILL.md` files in `.claude/skills/` to give Claude domain knowledge and reusable workflows.
247</Tip>
248
249[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`.
250
251Create a skill by adding a directory with a `SKILL.md` to `.claude/skills/`:
252
253```markdown .claude/skills/api-conventions/SKILL.md theme={null}
254---
255name: api-conventions
256description: REST API design conventions for our services
257---
258# API Conventions
259- Use kebab-case for URL paths
260- Use camelCase for JSON properties
261- Always include pagination for list endpoints
262- Version APIs in the URL path (/v1/, /v2/)
263```
264
265Skills can also define repeatable workflows you invoke directly:
266
267```markdown .claude/skills/fix-issue/SKILL.md theme={null}
268---
269name: fix-issue
270description: Fix a GitHub issue
271disable-model-invocation: true
272---
273Analyze and fix the GitHub issue: $ARGUMENTS.
274
2751. Use `gh issue view` to get the issue details
2762. Understand the problem described in the issue
2773. Search the codebase for relevant files
2784. Implement the necessary changes to fix the issue
2795. Write and run tests to verify the fix
2806. Ensure code passes linting and type checking
2817. Create a descriptive commit message
2828. Push and create a PR
283```
284
285Run `/fix-issue 1234` to invoke it. Use `disable-model-invocation: true` for workflows with side effects that you want to trigger manually.
286
287### Create custom subagents
288
289<Tip>
290 Define specialized assistants in `.claude/agents/` that Claude can delegate to for isolated tasks.
291</Tip>
292
293[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.
294
295```markdown .claude/agents/security-reviewer.md theme={null}
296---
297name: security-reviewer
298description: Reviews code for security vulnerabilities
299tools: Read, Grep, Glob, Bash
300model: opus
301---
302You are a senior security engineer. Review code for:
303- Injection vulnerabilities (SQL, XSS, command injection)
304- Authentication and authorization flaws
305- Secrets or credentials in code
306- Insecure data handling
307
308Provide specific line references and suggested fixes.
309```
310
311Tell Claude to use subagents explicitly: *"Use a subagent to review this code for security issues."*
312
313### Install plugins
314
315<Tip>
316 Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.
317</Tip>
318
319[Plugins](/en/plugins) bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic.
320
321For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/en/features-overview#match-features-to-your-goal).
322
323***
324
325## Communicate effectively
326
327The way you communicate with Claude Code significantly impacts the quality of results.
328
329### Ask codebase questions
330
331<Tip>
332 Ask Claude questions you'd ask a senior engineer.
333</Tip>
334
335When 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:
336
337* How does logging work?
338* How do I make a new API endpoint?
339* What does `async move { ... }` do on line 134 of `foo.rs`?
340* What edge cases does `CustomerOnboardingFlowImpl` handle?
341* Why does this code call `foo()` instead of `bar()` on line 333?
342
343Using 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.
344
345### Let Claude interview you
346
347<Tip>
348 For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the `AskUserQuestion` tool.
349</Tip>
350
351Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.
352
353```
354I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.
355
356Ask 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.
357
358Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.
359```
360
361Once 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.
362
363***
364
365## Manage your session
366
367Conversations are persistent and reversible. Use this to your advantage!
368
369### Course-correct early and often
370
371<Tip>
372 Correct Claude as soon as you notice it going off track.
373</Tip>
374
375The 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.
376
377* **`Esc`**: Stop Claude mid-action with the `Esc` key. Context is preserved, so you can redirect.
378* **`Esc + Esc` or `/rewind`**: Press `Esc` twice or run `/rewind` to open the rewind menu and restore previous conversation and code state.
379* **`"Undo that"`**: Have Claude revert its changes.
380* **`/clear`**: Reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.
381
382If 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.
383
384### Manage context aggressively
385
386<Tip>
387 Run `/clear` between unrelated tasks to reset context.
388</Tip>
389
390Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.
391
392During long sessions, Claude's context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.
393
394* Use `/clear` frequently between tasks to reset the context window entirely
395* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions
396* For more control, run `/compact <instructions>`, like `/compact Focus on the API changes`
397* 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
398
399### Use subagents for investigation
400
401<Tip>
402 Delegate research with `"use subagents to investigate X"`. They explore in a separate context, keeping your main conversation clean for implementation.
403</Tip>
404
405Since 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:
406
407```
408Use subagents to investigate how our authentication system handles token
409refresh, and whether we have any existing OAuth utilities I should reuse.
410```
411
412The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation.
413
414You can also use subagents for verification after Claude implements something:
415
416```
417use a subagent to review this code for edge cases
418```
419
420### Rewind with checkpoints
421
422<Tip>
423 Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.
424</Tip>
425
426Claude automatically checkpoints before changes. Double-tap `Escape` or run `/rewind` to open the checkpoint menu. You can restore conversation only (keep code changes), restore code only (keep conversation), or restore both.
427
428Instead 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.
429
430<Warning>
431 Checkpoints only track changes made *by Claude*, not external processes. This isn't a replacement for git.
432</Warning>
433
434### Resume conversations
435
436<Tip>
437 Run `claude --continue` to pick up where you left off, or `--resume` to choose from recent sessions.
438</Tip>
439
440Claude Code saves conversations locally. When a task spans multiple sessions (you start a feature, get interrupted, come back the next day) you don't have to re-explain the context:
441
442```bash theme={null}
443claude --continue # Resume the most recent conversation
444claude --resume # Select from recent conversations
445```
446
447Use `/rename` to give sessions descriptive names (`"oauth-migration"`, `"debugging-memory-leak"`) so you can find them later. Treat sessions like branches. Different workstreams can have separate, persistent contexts.
448
449***
450
451## Automate and scale
452
453Once you're effective with one Claude, multiply your output with parallel sessions, headless mode, and fan-out patterns.
454
455Everything 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.
456
457### Run headless mode
458
459<Tip>
460 Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json` for streaming JSON output.
461</Tip>
462
463With `claude -p "your prompt"`, you can run Claude headlessly, without an interactive session. Headless mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats (plain text, JSON, streaming JSON) let you parse results programmatically.
464
465```bash theme={null}
466# One-off queries
467claude -p "Explain what this project does"
468
469# Structured output for scripts
470claude -p "List all API endpoints" --output-format json
471
472# Streaming for real-time processing
473claude -p "Analyze this log file" --output-format stream-json
474```
475
476### Run multiple Claude sessions
477
478<Tip>
479 Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.
480</Tip>
481
482There are two main ways to run parallel sessions:
483
484* [Claude Desktop](/en/desktop): Manage multiple local sessions visually. Each session gets its own isolated worktree.
485* [Claude Code on the web](/en/claude-code-on-the-web): Run on Anthropic's secure cloud infrastructure in isolated VMs.
486
487Beyond 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.
488
489For example, use a Writer/Reviewer pattern:
490
491| Session A (Writer) | Session B (Reviewer) |
492| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
493| `Implement a rate limiter for our API endpoints` | |
494| | `Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns.` |
495| `Here's the review feedback: [Session B output]. Address these issues.` | |
496
497You can do something similar with tests: have one Claude write tests, then another write code to pass them.
498
499### Fan out across files
500
501<Tip>
502 Loop through tasks calling `claude -p` for each. Use `--allowedTools` to scope permissions for batch operations.
503</Tip>
504
505For large migrations or analyses, you can distribute work across many parallel Claude invocations:
506
507<Steps>
508 <Step title="Generate a task list">
509 Have Claude list all files that need migrating (e.g., `list all 2,000 Python files that need migrating`)
510 </Step>
511
512 <Step title="Write a script to loop through the list">
513 ```bash theme={null}
514 for file in $(cat files.txt); do
515 claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
516 --allowedTools "Edit,Bash(git commit:*)"
517 done
518 ```
519 </Step>
520
521 <Step title="Test on a few files, then run at scale">
522 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.
523 </Step>
524</Steps>
525
526You can also integrate Claude into existing data/processing pipelines:
527
528```bash theme={null}
529claude -p "<your prompt>" --output-format json | your_command
530```
531
532Use `--verbose` for debugging during development, and turn it off in production.
533
534### Safe Autonomous Mode
535
536Use `claude --dangerously-skip-permissions` to bypass all permission checks and let Claude work uninterrupted. This works well for workflows like fixing lint errors or generating boilerplate code.
537
538<Warning>
539 Letting Claude run arbitrary commands is risky and can result in data loss, system corruption, or data exfiltration (e.g., via prompt injection attacks). To minimize these risks, use `--dangerously-skip-permissions` in a container without internet access.
540
541 With sandboxing enabled (`/sandbox`), you get similar autonomy with better security. Sandbox defines upfront boundaries rather than bypassing all checks.
542</Warning>
543
544***
545
546## Avoid common failure patterns
547
548These are common mistakes. Recognizing them early saves time:
549
550* **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.
551 > **Fix**: `/clear` between unrelated tasks.
552* **Correcting over and over.** Claude does something wrong, you correct it, it's still wrong, you correct again. Context is polluted with failed approaches.
553 > **Fix**: After two failed corrections, `/clear` and write a better initial prompt incorporating what you learned.
554* **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.
555 > **Fix**: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook.
556* **The trust-then-verify gap.** Claude produces a plausible-looking implementation that doesn't handle edge cases.
557 > **Fix**: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it.
558* **The infinite exploration.** You ask Claude to "investigate" something without scoping it. Claude reads hundreds of files, filling the context.
559 > **Fix**: Scope investigations narrowly or use subagents so the exploration doesn't consume your main context.
560
561***
562
563## Develop your intuition
564
565The 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.
566
567Sometimes 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.
568
569Pay 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?
570
571Over 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.
572
573## Related resources
574
575<CardGroup cols={2}>
576 <Card title="How Claude Code works" icon="gear" href="/en/how-claude-code-works">
577 Understand the agentic loop, tools, and context management
578 </Card>
579
580 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">
581 Choose between skills, hooks, MCP, subagents, and plugins
582 </Card>
583
584 <Card title="Common workflows" icon="list-check" href="/en/common-workflows">
585 Step-by-step recipes for debugging, testing, PRs, and more
586 </Card>
587
588 <Card title="CLAUDE.md" icon="file-lines" href="/en/memory">
589 Store project conventions and persistent context
590 </Card>
591</CardGroup>
592
593
594---
595
596> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt