Skip to content

Claude Code Complete Guide

Claude Code Advanced Best Practices: 11 Practical Techniques for Hooks, Subagents & Context Management [2026]

  • Target Audience

    Intermediate to advanced users who use Claude Code daily and want more efficient operations

  • What You'll Learn

    11 "eye-opening" operational techniques curated from official Best Practices

  • Reading Time

    ~15 minutes

Introduction: Beyond Basic Tips

"Pass tests/expected output for self-verification," "Use Plan Mode to separate exploration → planning → implementation," "Include specific context in prompts"—these are widely known basic tips.

This article focuses on "constraining through systems" from the official Best Practices, providing practical know-how to break through the wall from intermediate to advanced user.


1. Hooks Are "Mandatory", CLAUDE.md Is "Advisory"

Core Point

Use Hooks for absolute requirements, CLAUDE.md for guidance that requires judgment

Hook Characteristics

  • Automatically execute scripts at specific workflow timings
  • Deterministic control rather than "hoping Claude remembers"
  • Guarantees something happens every time

When to Use Each

RequirementRecommendedReason
Auto-lint after file saveHook (PostToolUse)Must run every time without exception
Block writes to sensitive filesHook (PreToolUse)Security cannot be compromised
Code convention complianceCLAUDE.mdRequires situational judgment
API naming rulesCLAUDE.mdException patterns exist

Implementation Example: Block Writes to Sensitive Files

Following Official Specification

Hook input is JSON passed via stdin. The decision/reason return format is deprecated, so use exit code 2 to block.

First, create a blocking script:

#!/bin/bash
# ./scripts/block-sensitive-writes.sh
set -euo pipefail

INPUT="$(cat)"
TOOL="$(echo "$INPUT" | jq -r '.tool // empty')"
FILE_PATH="$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // empty')"

# Block writes to sensitive file extensions
if [[ "$TOOL" =~ ^(Write|Edit)$ ]] && echo "$FILE_PATH" | grep -qE '\.(env|key|pem)$'; then
  echo "Blocked: sensitive file write is not allowed: $FILE_PATH" >&2
  exit 2  # exit code 2 = block
fi

exit 0

Then configure the Hook in settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          { "type": "command", "command": "./scripts/block-sensitive-writes.sh" }
        ]
      }
    ]
  }
}

Why eye-opening: This moves beyond "constraining via prompts" to placing guardrails on the system side—an SRE/Platform-oriented design.


2. Subagents Run in "Separate Context Windows"

Core Point

Isolate research, verification, and review in separate contexts to prevent contamination and bias

Subagent Characteristics

Subagents defined in .claude/agents/ receive delegated tasks, with each having its own context window, available tools, and instructions.

Difference from Slash Commands

FeatureSlash CommandsSubagents
InvocationExplicit (/command)Task delegation
ContextSharedIndependent
Use CaseRepetitive workflowsDivision of labor, exploration, verification

Effective Use Cases

  1. Research: Explore codebase without polluting main context
  2. Verification: Validate implementation with separate agent
  3. Review: Avoid conversation bias from main session

Why eye-opening: With "context as a resource" premise, "pushing exploration to a separate window" is powerful. It's not just parallelization—it structurally prevents contamination (accumulation of failed approaches).

→ Details: Claude Code Subagent Complete Guide


3. Skills "Auto-Fire" Based on Context

Core Point

Activated by context triggers, not explicit invocation

Skills Positioning

FeatureCharacteristics
CLAUDE.mdAlways-loaded global rules
Slash commandsExplicitly executed repetitive workflows
SkillsAuto-applied domain knowledge
SubagentsIsolated delegated tasks

Implementation Example: API Design Rules as a Skill

Official Specification

Skills are not single .md files but use the skills/<skill-name>/SKILL.md directory structure. YAML frontmatter controls auto-application conditions.

Directory Structure:

.claude/
  skills/
    api-conventions/
      SKILL.md          # Main skill definition (required)
      examples.md       # Expected output examples (optional)
      reference.md      # Detailed guide (optional)

SKILL.md:

---
name: api-conventions
description: API design and endpoint conventions. Applies in API/endpoint/REST/schema design contexts.
---
When writing API endpoints:
- Use RESTful naming conventions (plural nouns: users, orders)
- Use kebab-case for multi-word paths (user-profiles)
- Include version in URL path (/v1/users)
- Return consistent formats:
  - Success: { "data": {...}, "meta": {...} }
  - Error: { "error": { "code": "...", "message": "..." } }

## Additional resources
- examples.md: Expected output examples
- reference.md: Detailed design guidelines (reference when needed)

Manual-Only Skills (Prevent Accidental Triggers)

For dangerous operations like deployment, use disable-model-invocation: true:

---
name: deploy
description: Production deployment procedure
disable-model-invocation: true
context: fork
---
Deploy the application:
1. Run the test suite
2. Build the application
3. Push to the deployment target

Commands vs Skills

Legacy .claude/commands/*.md (slash commands) still exist, but Skills take priority over same-named commands. Commands are being integrated into Skills.

Why eye-opening: Instead of "writing prompts every time," implement tacit knowledge as an "auto-applied knowledge layer".


4. CLAUDE.md Must Be "Short or It Backfires"

Important Principle

For each line, ask "If I remove this, will Claude make mistakes?" If not, remove it.

The Problem with Bloat

When CLAUDE.md becomes too long, the probability of instructions being ignored increases.

Deletion Decision Framework

1. If I remove this instruction, will Claude make mistakes?
   → Yes: Keep
   → No: Remove

2. Can this information be provided elsewhere (README, Skills)?
   → Yes: Move and remove
   → No: Keep

3. Is this instruction always needed, or only in specific contexts?
   → Always: Keep in CLAUDE.md
   → Specific context: Move to Skills

Placement Strategy

LocationPurpose
~/.claude/CLAUDE.mdPersonal settings for all sessions
Project rootTeam-shared rules
Parent directoryShared settings in monorepo
Child directorySpecial rules loaded as needed

Why eye-opening: Not "more is better" but "brevity is a performance requirement".


5. Combat "Approval Fatigue": Allowlist and Sandbox

The Approval Trap

Too many approvals → people click without reviewing → safety decreases

Two Countermeasure Approaches

ApproachEffect
AllowlistReduce interruptions by permitting safe commands
OS-level SandboxIncrease freedom by defining file/network boundaries

Allowlist Configuration Example

{
  "permissions": {
    "allow": [
      "Bash(npm run lint:*)",
      "Bash(npm run test:*)",
      "Bash(git status)",
      "Bash(git diff:*)",
      "Read",
      "Glob",
      "Grep"
    ]
  }
}

Make Sensitive Files Invisible with deny (More Secure Than Hooks)

Evaluation Order: deny → ask → allow

Permissions evaluate deny first. Setting sensitive files to deny makes them "invisible" to Claude (more secure than blocking with Hooks).

{
  "permissions": {
    "allow": [
      "Bash(npm run lint:*)",
      "Bash(npm run test:*)",
      "Bash(git diff:*)",
      "Read",
      "Glob",
      "Grep"
    ],
    "ask": [
      "Bash(git push:*)"
    ],
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)",
      "Bash(curl:*)"
    ]
  }
}

Proper Use of --dangerously-skip-permissions

AppropriateInappropriate
Lint fix automationInternet-connected environment
Boilerplate generationEnvironment with sensitive data
Closed workflowsGeneral development work

Important

--dangerously-skip-permissions should be used in isolated environments without internet.

Enterprise: Disable Dangerous Mode Organization-Wide

To prohibit --dangerously-skip-permissions as an organizational security policy, set disableBypassPermissionsMode: true.

{
  "disableBypassPermissionsMode": true
}

→ Details: Claude Code Auto-Approval Guide


6. "Two Failures = /clear" (Author's Operational Rule)

Core Rule

If you're making corrections on the same issue twice, /clear and restart is faster

Distinguishing Official vs Author's Rule

Official Best Practices states "use /clear frequently" and "context pollution degrades performance" but doesn't specify a "2 times" threshold. The "2 failures" rule in this article is presented as the author's operational guideline.

Why Reset Is Effective

When failed approaches accumulate in a session, context becomes polluted.

Accumulation of failed patterns
    ↓
Claude references past failures
    ↓
Gets pulled in the same direction
    ↓
Further failures

Practical Flow

First failure
    ↓
Analyze cause, request fix
    ↓
Second failure (same issue)
    ↓
★ Execute /clear ★
    ↓
Restart with a "better initial prompt" incorporating learnings

Why eye-opening: Not "persistence makes it better" but operate with the premise that sessions become contaminated.


7. /compact Accepts "Summarization Instructions"

Function

Automatically compresses history as context limit approaches, preserving important code and decisions

Power of Manual Control

# Compress focusing on API changes
/compact Focus on API changes

# Compress while preserving test-related history
/compact Preserve test implementation details

# Compress while keeping error resolution history
/compact Keep error causes and solutions in detail

Why eye-opening: Not "getting summarized" but you specify the summarization "policy" to optimize what information to preserve.


8. Checkpoints Allow Independent Conversation/Code Rollback

Flexible Rollback

Choose to restore conversation only, code only, or both

Checkpoint Characteristics

FeatureDetail
Auto-creationCreated automatically with each Claude action
Cross-sessionPersists across sessions
Independent rollbackCan restore conversation and code independently

Usage Patterns

Pattern 1: Restore conversation only (keep code)
→ Implementation is good, but want to redo explanation

Pattern 2: Restore code only (keep conversation)
→ Discussion was valuable, but want different implementation approach

Pattern 3: Restore both
→ Complete restart

Limitations

  • Does not track external process changes
  • Not a git replacement

Why eye-opening: Rather than "forcing Claude to plan carefully," the design makes trial-and-error safe through system features.

→ Details: Claude Code 2.0 Checkpoint Patterns


9. Separate Specification and Implementation Sessions

Core Point

Create specs through interviews, implement in a new session

graph LR
    A[Session 1: Specification] --> B[SPEC.md]
    B --> C[Session 2: Implementation]

    style A fill:#e1f5fe
    style B fill:#fff9c4
    style C fill:#e8f5e9

Session 1: Specification

Prompt example:
"Please interview me about this feature using the
AskUserQuestion tool to solidify the specification.
Output the final result as SPEC.md."

Session 2: Implementation

Prompt example:
"Please implement according to SPEC.md.
Ask questions if you're unsure about specification interpretation."

Why eye-opening: Rather than "doing everything in one session," separate Spec → Build by context unit for both quality and speed.

→ Related: AskUserQuestion Tool Guide


10. Parallel Sessions Work for Bias Avoidance Too

Writer/Reviewer Pattern

New context is advantageous for review—not influenced by code you just wrote

Value of Parallel Sessions

PurposeEffect
Speed upParallel progress on multiple tasks
Quality improvementBias isolation

Writer/Reviewer Pattern

Session A (Writer): Implement code
    ↓
Share code
    ↓
Session B (Reviewer): Review implementation
→ Review from perspective freed from Writer's thought bias

Test Separation Pattern

Session A: Write tests
    ↓
Commit tests
    ↓
Session B: Write code to pass tests
→ Implement without bias from writing tests

Practical Tip: Physical Isolation with git worktree

Prevent Collision Accidents

Parallel sessions editing the same file simultaneously can cause collision accidents. Official guidance recommends git worktree for physical isolation.

# Create worktree in separate directory
git worktree add ../project-review feature-branch

# Session A works in main directory
# Session B works in worktree directory

Why eye-opening: Similar to human pair programming, but more strictly achieves "bias isolation" through context.


11. Fan-out: "Tune on Few Files → Deploy to All"

Scale Procedure

Tune prompts on 2-3 files before deploying to all

Large-Scale Migration Flow

graph TD
    A[Generate task list] --> B[Trial on 2-3 files]
    B --> C{Success?}
    C -->|No| D[Adjust prompt]
    D --> B
    C -->|Yes| E[Full scale]

    style B fill:#fff9c4
    style E fill:#e8f5e9

Implementation Example

# Step 1: Generate task list
claude -p "Generate list of files for migration/" > tasks.txt

# Step 2: Test on few files
head -3 tasks.txt | while read file; do
  claude -p "Convert this file to Python 3.11" "$file"
done

# Step 3: Check results, adjust prompt
# (Fix if issues found)

# Step 4: Full scale (with permission restrictions)
cat tasks.txt | while read file; do
  claude -p "Convert this file to Python 3.11" \
    --allowedTools "Read,Edit,Grep" \
    --output-format json \
    "$file"
done

Unattended Execution Best Practices

SettingReason
--allowedToolsRestrict permissions to prevent unexpected operations
--output-format jsonMachine-processable output
--output-format stream-jsonReal-time monitoring

Why eye-opening: Defines LLM operations not as "craftsmanship" but as batch processing workflow (prototype → adjust → mass produce).


Summary: Mindset Shift in Operations Design

Traditional ThinkingAdvanced Thinking
Constrain via promptsControl systematically with Hooks
Complete in one sessionSeparate context as a resource
Persistently fixReset after 2 failures
Cover everything in long CLAUDE.mdBrevity is a performance requirement
Judge each approvalStreamline with Allowlist + Sandbox
Artisanal promptingScale with Fan-out

By incorporating these "constrain through systems" approaches, Claude Code operational efficiency improves dramatically.


Appendix: Templates Following Official Specifications

Appendix 1: Subagents Definition Template (frontmatter + skills injection)

Subagents operate around their own system prompt, isolating them from the main conversation's bias.

.claude/agents/code-reviewer.md:

---
name: code-reviewer
description: Reviews code for quality and best practices. Use proactively after code changes.
tools: Read, Glob, Grep
model: sonnet
skills:
  - api-conventions
  - error-handling-patterns
---
You are a senior code reviewer. Focus on code quality, security, and best practices.
Provide specific, actionable feedback.

Key Points:

  • tools: Restrict available tools
  • model: Specify the model to use
  • skills: Specify Skills to preload
Appendix 2: CLAUDE.md Compact Instructions (Standardize Compression Policy)

Including /compact policy in CLAUDE.md ensures consistent policy during auto-compression.

## Compact Instructions

When summarizing this conversation:
- Preserve all API changes and their rationale
- Keep error messages and their solutions
- Maintain the list of modified files
- Summarize exploration attempts briefly
Appendix 3: Parallel Session Management (/rename → /resume)

Name sessions for later resumption:

# Name the session
/rename feature-auth-implementation

# Start new session in another terminal
claude

# Resume named session later
/resume feature-auth-implementation


Source: Best Practices for Claude Code - Claude Code Docs