← Back to Blog

Claude Code Best Practices

Claude Code LLMs Best Practices

As AI coding assistants transition from simple autocomplete wrappers into autonomous agents operating directly on your filesystem, managing their instructions, context size, and execution safety becomes a core discipline. Here is an in-depth developer guide to getting the most out of Claude Code.

1. CLAUDE.md Architecture

The CLAUDE.md file acts as the configuration blueprint and rules engine for the agent. Because it is loaded automatically on almost every LLM call, keeping it structured and lightweight is vital.

Symlink Conventions: To link AGENTS.md to CLAUDE.md locally (essential for multi-agent settings), run the symlink command:

ln -s AGENTS.md CLAUDE.md

Here is an optimized directory layout for isolating agent documentation:

agent_docs/
    |- AGENTS.md
    |- code_conventions_and_styles.md
    |- running_tests.md
    |- architecture.md
    |- database_schema.md
    |- data_models.md
    |- messaging_schemas.md
    |- build_commands.md

If your main instructions file has accumulated bloat, you can feed the following prompt to Claude to clean it up:

Please clean up my AGENTS.md file so the main file is short and detailed instructions are split into separate files.

Please do the following:
1. Spot conflicts: If any instructions contradict each other, ask me which one is correct.
2. Isolate the essentials: Leave only the absolute basics in the main AGENTS.md file (like a 1-sentence project summary, package manager, custom commands, and global rules).
3. Categorize everything else: Group the rest of the instructions by topic (e.g., testing, API design) and put each group into its own markdown file.
4. Output the results: Provide the new, short AGENTS.md file (with links to the sub-files), the content for the new sub-files, and a suggested folder structure.
5. Remove fluff: Delete any instructions that are redundant, vague, or obvious (like "write good code").

2. Keep Memory Selective & Avoid Noise

Because LLMs have context limits, keeping active memory clean is critical. Do not feed the model unnecessary code, large datasets, or log files. Limit file reading tool use to only the files relevant to the active task, and delete or archive outdated spec files to avoid confusing the agent.

3. Explore, Research, Plan, Execute

Claude Code leverages built-in, task-specific subagents to delegate work, control context size, and execute commands safely. When writing code, the system runs through a structured loop:

4. Subagent Context Isolation

To prevent context overload and security vulnerabilities, each subagent runs inside an isolated context window with restricted tools.

                graph TD
                    classDef blueBox fill:#2563eb,stroke:#1d4ed8,color:#fff;
                    classDef greenBox fill:#059669,stroke:#047857,color:#fff;
                    classDef purpleBox fill:#7c3aed,stroke:#6d28d9,color:#fff;
                    classDef orangeBox fill:#ea580c,stroke:#c2410c,color:#fff;
                    classDef redBox fill:#dc2626,stroke:#b91c1c,color:#fff;
                    classDef greyBox fill:#4b5563,stroke:#374151,color:#fff;
                    classDef pinkBox fill:#db2777,stroke:#be185d,color:#fff;
                    classDef wallStyle fill:#e2e8f0,stroke:#64748b,stroke-width:4px,font-weight:bold;

                    subgraph Subagent ["Subagent Context"]
                        direction TB
                        S1["System Prompt"]:::blueBox
                        S2["CLAUDE.md"]:::blueBox
                        S3["Tools"]:::blueBox
                        S4["subagents Prompt"]:::redBox
                        S5["User Message FROM Agent()"]:::greenBox
                        
                        subgraph Noise ["Blocked Noise"]
                            direction TB
                            N1["Glob()"]:::purpleBox
                            N2["Bash()"]:::orangeBox
                            N3["Grep()"]:::greyBox
                            N4["Read()"]:::pinkBox
                        end
                        
                        S6["Assistant Output"]:::orangeBox
                        
                        S1 --- S2 --- S3 --- S4 --- S5 --- Noise --- S6
                    end

                    subgraph WallSection [" "]
                        direction TB
                        Firewall["C O N T E X T   F I R E W A L L"]:::wallStyle
                    end

                    subgraph Primary ["Primary Context"]
                        direction TB
                        P1["System Prompt"]:::blueBox
                        P2["CLAUDE.md"]:::blueBox
                        P3["Tools"]:::blueBox
                        P4["Prompt/Message/Command"]:::greenBox
                        P5["Agent() Call"]:::purpleBox
                        P6["Agent() Result"]:::orangeBox
                        
                        P1 --- P2 --- P3 --- P4 --- P5 --- P6
                    end

                    P5 --> S5
                    S6 --> P6
                    
                    N1 -.-x|BLOCKED| Firewall
                    N2 -.-x|BLOCKED| Firewall
                    N3 -.-x|BLOCKED| Firewall
                    N4 -.-x|BLOCKED| Firewall
                

Figure 1: Subagent Firewall architecture isolating noise and tools.

By running agents in isolated sessions, subagents share the prompt cache (parallelism is highly efficient) while preventing large token footprints from polluting the primary loop.

Execution Model Workspace Isolation Cache Sharing Primary Use Case
Fork Shares parent directory (same files) Yes (Optimized caching) Parallel analysis, refactoring, and code generation
Teammate Runs in separate terminal pane/tab Yes Long-running background tasks, monitoring (communicates via mailbox)
Worktree Isolated directory / git branch Yes Complex features, independent tasks avoiding merge conflicts

5. Git Worktrees for Parallel Work

When working on multiple features simultaneously, you can run parallel Claude Code sessions without overlapping modifications by isolating them inside Git worktrees.

# Start Claude in a worktree named "feature-auth"
# Creates .claude/worktrees/feature-auth/ with a new branch
claude --worktree feature-auth

# Start another session in a separate worktree
claude --worktree bugfix-123

6. Configure Permissions

Control what Claude Code can access and execute on your machine. Limiting tool permissions, environment configurations, and network settings prevents unapproved actions and ensures security. A general rule of thumb for coding agents: fewer tools lead to cleaner, more focused results.

Below is a sample permissions configuration file defining allow, ask, and deny boundaries:

{
  "permissions": {
    "allow": [
      "Read(public/**)",
      "Edit(public/**)",
      "Bash(npm run test*)",
      "Bash(git status)",
      "Bash(git diff)"
    ],
    "ask": [
      "Bash(npm install *)",
      "Bash(git commit:*)"
    ],
    "deny": [
      "WebFetch",
      "Read(proprietary/**)",
      "Read(**/.env*)",
      "Read(**/secrets/**)",
      "Bash(rm *)",
      "Bash(curl:*)"
    ]
  },
  "defaultMode": "default",
  "additionalDirectories": []
}

7. Use Hooks for Automation

Hooks are powerful control flow triggers that run custom commands automatically when specific agent tools are executed. For example, you can write a post-tool-use hook that runs formatting, style checks, or tests every time a file is modified:

{
    "hooks": {
        "PostToolUse": [
            {
                "matcher": "Write|Edit|MultiEdit",
                "hooks": [
                    { "type": "command", "command": "bun run format || true" }
                ]
            }
        ]
    }
}

7. Five Compaction Strategies

As the chat session grows, Claude Code automatically compacts the conversation history using five distinct strategies to optimize tokens and keep the context fresh. Use the interactive slider below to explore these strategies:

๐Ÿงน 1. Microcompact

Time-based clearing: Automatically prunes old, transient tool outputs (such as massive shell runs or search results) after a set duration. This keeps the immediate context history relevant and clean.

๐Ÿ“ฆ 2. Context Collapse

Summarization of past loops: Condenses long series of back-and-forth tool invocations and user confirmations into a high-level summary paragraph. This preserves the history of decisions without bloating the active token count.

๐Ÿ“ 3. Session Memory

Externalizing State: Extracts critical configuration values, file lists, and overall task checklists to a separate scratchpad file. This offloads active tracking details from the short-term chat memory.

๐Ÿ“Š 4. Full Compact

Global History Summary: Summarizes the entire conversation from the very first message. Claude replaces the original full history with this comprehensive brief, reclaiming up to 80% of the active context window.

โœ‚๏ธ 5. PTL Truncation

Oldest Message Purge: Drops the oldest messages once a session exceeds limit boundaries. This keeps only the most recent loops in the context while purging historical noise.

Pro-Tip: Run the /compact command manually and pass specific pruning instructions (e.g. /compact focus on API changes) to guide how memory is summarized!

8. The Harness Engineering Matters

Harness engineering is the craft of designing boundaries, automated constraints, and instructions around the model to make it behave predictably in production.

Instead of treating code agents as black boxes, you should build scaffolding structures (like test suites and verification environments) to guide their tool usage and verify outputs. Read our complete guide on Harness Engineering for a detailed analysis of this discipline.

9. Source Code Comments for Machines

When writing source code, add structural, machine-readable comments. AI tools parse function signatures and type annotations to understand constraints. Providing structured cues prevents the model from generating code that violates your architecture.

// For AI Agent Context Parsing:
// @param {string} userId - UUID v4 format only
// @returns {Promise<Object>} Resolved user payload, or throws UserNotFoundError
// WARNING: DO NOT modify this database query structure without updating 
// the active schema file inside docs/db-schema.md first.
function fetchUserProfile(userId) {
  // Query implementation...
}

11. Sessions are Persistent & Resumable

Stop starting fresh conversations for the same task. Long sessions accumulate file indexing caches, active subagent mailbox states, historical build results, and past debugging learnings. Starting fresh forces the model to rebuild its understanding of your codebase from scratch.

# Resume the last active session
claude --continue

# List and choose a previous session to resume
claude --resume

# Fork a new session from a past session ID
claude --fork-session <sessionId>

12. Skills Are for Reusable Knowledge

Skills are persistent, custom functions or knowledge definitions you can save and assign to Claude Code. They serve as reusable scripts that the model can run directly without manual instruction. We will cover Skills in a future detailed blog post.

13. Commands / Rules and etc

Command configurations and rulesets govern what tools are active, how errors are processed, and the custom behaviors of subagents. We can define project policies to prevent rogue commands. We will cover this configuration in an upcoming guide.