NEW: Claude Code Security — research preview →

The Longform Guide to Everything Claude Code

Advanced patterns for productive Claude Code sessions: token economics, memory persistence, verification loops, parallelization, and sub-agent orchestration.

ECCRead time: 22 min

title: "The Longform Guide to Everything Claude Code" description: "Advanced patterns for productive Claude Code sessions: token economics, memory persistence, verification loops, parallelization, and sub-agent orchestration." section: "guide" readTime: "22 min" badge: "ECC"

Prerequisite: This guide builds on The Shorthand Guide. Read that first if you haven't set up skills, hooks, subagents, MCPs, and plugins.

In the shorthand guide, the foundational setup was covered: skills, hooks, subagents, MCPs, plugins, and the configuration patterns that form the backbone of an effective Claude Code workflow. That was the setup guide and the base infrastructure.

This longform guide goes into the techniques that separate productive sessions from wasteful ones. If you haven't read the shorthand guide, go back and set up your configs first. What follows assumes you have skills, agents, hooks, and MCPs already configured and working.

The themes here: token economics, memory persistence, verification patterns, parallelization strategies, and the compound effects of building reusable workflows. These are the patterns refined over months of daily use that make the difference between being plagued by context rot early in a session, versus maintaining productive sessions for hours.


Tips and Tricks

Some MCPs Are Replaceable and Will Free Up Your Context Window

For MCPs such as version control (GitHub), databases (Supabase), deployment (Vercel, Railway), etc. — most of these platforms already have robust CLIs that the MCP is essentially just wrapping. The MCP is a nice wrapper but it comes at a cost.

Anthropic's cost guide says the same thing: CLI tools such as gh, aws, gcloud, and sentry-cli are still more context-efficient than MCP servers because they add no per-tool listing, and Claude can run them directly.

To have the CLI function more like an MCP without actually loading the MCP, bundle the functionality into skills. Strip out the tools the MCP exposes that make things easy and turn those into skills. (Custom commands have been merged into skills: a file at .claude/commands/deploy.md and a skill at .claude/skills/deploy/SKILL.md both create /deploy, and skills are the recommended form.)

Example: Instead of having the GitHub MCP loaded at all times, create a gh-pr skill that wraps gh pr create with your preferred options. Instead of the Supabase MCP eating context, create skills that use the Supabase CLI directly.

MCP tool definitions are deferred by default (tool search): only tool names and server instructions enter context until Claude needs a specific tool. That mostly solves the context-window problem, but results still count as tokens, and Claude Code warns when a single tool result exceeds 10,000 tokens (default cap 25,000, adjustable with MAX_MCP_OUTPUT_TOKENS). The CLI + skills approach remains a token optimization method. Run /context to see what is actually consuming space.


Context and Memory Management

Claude Code has two built-in memory layers: CLAUDE.md files you write, and auto memory (MEMORY.md) that Claude writes itself. Manage both with /memory. Auto memory loads the first 200 lines or 25KB at session start. Keep CLAUDE.md concise (under about 200 lines) and move workflow-specific instructions into skills, which load only when invoked.

For handoffs across sessions that go beyond that, a skill that summarizes and checks in on progress, then saves to a file in your project (for example under .claude/sessions/) and appends to it until the end of your session, works well. The next day it can use that as context and pick up where you left off — create a new file for each session so you don't pollute old context into new work.

Session Storage File Tree

Claude creates a file summarizing current state. Review it, ask for edits if needed, then start fresh. For the new conversation, just provide the file path. Particularly useful when you're hitting context limits and need to continue complex work. These files should contain:

  • What approaches worked (verifiably with evidence)
  • Which approaches were attempted but did not work
  • Which approaches have not been attempted and what's left to do

Clearing Context Strategically

Built-in tools for this:

ToolUse
/clear [name]New conversation with empty context. Name the old one so you can /resume it later (or /rename first)
/compact [instructions]Summarize in place, for example /compact Focus on code samples and API usage
/rewind → Summarize from here / up to hereTargeted compaction of part of the conversation; also reached with Esc Esc on an empty prompt
/contextVisualize what is using the context window
/btw <question>Side question that doesn't enter the conversation history

A # Compact instructions section in CLAUDE.md tells Claude what to preserve whenever it compacts.

Plan mode can start execution with a fresh context: when the showClearContextOnPlanAccept setting is enabled, the plan-approval prompt gains a first option that approves the plan and clears the planning context. It is not on by default. This is useful when you've accumulated a lot of exploration context that's no longer relevant to execution.

For strategic compacting, auto-compaction can be turned off (DISABLE_AUTO_COMPACT=1, or the autoCompactEnabled setting) so you compact manually at logical intervals. Be careful: with auto-compact off, a long session simply hits the context limit. A gentler option is to set the auto-compact window with /autocompact 200k (accepts 100K to 1M tokens; also the --autocompact flag, the autoCompactWindow setting, or CLAUDE_CODE_AUTO_COMPACT_WINDOW). On models with a native 1M window, compaction otherwise happens only near the limit (about 967K tokens).

Advanced: Dynamic System Prompt Injection

One pattern worth adopting: instead of solely putting everything in CLAUDE.md (user scope, ~/.claude/CLAUDE.md) or .claude/rules/ (project scope) which loads every session, use CLI flags to inject context dynamically.

claude --append-system-prompt-file ./memory.md

This lets you be more surgical about what context loads when. Know the difference between the flags:

FlagBehavior
--append-system-prompt / --append-system-prompt-fileAdds to the default prompt. Keeps Claude Code's tool guidance and safety instructions
--system-prompt / --system-prompt-fileReplaces the entire default prompt, including tool guidance and safety instructions. Use only when you want a different agent identity

Prefer the append flags for context injection. A conversation records its system prompt on the first request and reuses it on --resume or --continue until it is compacted, so changed flag text takes effect after compaction or in a new conversation (or pass --system-prompt-snapshot off). For personas you switch between, consider output styles instead.

Practical setup:

# Daily development
alias claude-dev='claude --append-system-prompt-file ~/.claude/contexts/dev.md'
 
# PR review mode
alias claude-review='claude --append-system-prompt-file ~/.claude/contexts/review.md'
 
# Research/exploration mode
alias claude-research='claude --append-system-prompt-file ~/.claude/contexts/research.md'

Advanced: Memory Persistence Hooks

There are hooks most people don't know about that help with memory:

  • PreCompact: Fires before compaction (matcher manual or auto). Save important state to a file. Exit code 2 blocks the compaction
  • PostCompact: Fires after compaction completes
  • SessionEnd: Fires when a session terminates. Persist learnings to a file. Hooks here share a short default budget of 1.5 seconds (raise it with a per-hook timeout, up to 60 seconds)
  • SessionStart: Fires on startup, resume, clear, and compact (use the matcher to pick). Plain stdout or additionalContext is added to Claude's context, so you can load previous session notes automatically

Example implementations are in the ECC repo under hooks/memory-persistence/.

Stop is not "session end". The Stop event fires every time Claude finishes responding, so a Stop hook runs once per turn. Use SessionEnd for once-per-session work.


Continuous Learning / Memory

If you've had to repeat a prompt multiple times and Claude ran into the same problem or gave you a response you've heard before — those patterns must be appended to skills (or, for short facts, to CLAUDE.md). Claude's own auto memory covers part of this automatically: it records build commands, patterns, and mistakes to avoid between sessions.

The Problem: Wasted tokens, wasted context, wasted time.

The Solution: When Claude Code discovers something that isn't trivial — a debugging technique, a workaround, some project-specific pattern — save that knowledge as a new skill. Next time a similar problem comes up, Claude can load it based on the skill's description.

Choosing the Hook Event

The ECC continuous-learning skill (listed in its repo as the original Stop-hook pattern-extraction version, with a newer continuous-learning-v2 alongside) extracts patterns from the session transcript. The event choice is a tradeoff:

  • UserPromptSubmit runs on every single message and adds latency to every prompt
  • Stop runs after every response. It is cheap if the script exits quickly, but it is per-turn, not per-session
  • SessionEnd runs once per session, but has the short default time budget noted above, so keep the work light or hand it to a background process

Keep any learning hook fast and non-blocking either way.


Token Optimization

Primary Strategy: Subagent Architecture

Optimize the tools you use and subagent architecture designed to delegate the cheapest possible model that is sufficient for the task. Subagents inherit your session's model unless you set model in the subagent definition (sonnet, opus, haiku, fable, a full ID, or inherit) or set CLAUDE_CODE_SUBAGENT_MODEL.

Model Selection Quick Reference:

Task TypeModelWhy
Exploration/searchHaiku 5.5Fastest and cheapest, good enough for finding files
Simple editsHaiku 5.5Single-file changes, clear instructions
Multi-file implementationSonnet 5.5Fast, strong balance for coding
Complex architectureOpus 5.5Deep reasoning needed
PR reviewsSonnet 5.5Understands context, catches nuance
Security analysisOpus 5.5Can't afford to miss vulnerabilities
Writing docsHaiku 5.5Structure is simple
Debugging complex bugsOpus 5.5 or Fable 5.1Needs to hold entire system in mind
Hardest, longest-running agentic workFable 5.1For when Opus 5.5 at higher effort still falls short

All four current models have a 1M-token context window. List pricing per million input/output tokens: Fable 5.1 $10 / $50, Opus 5.5 $4 / $20, Sonnet 5.5 $2 / $10, Haiku 5.5 from $0.10 / $0.50. Opus 5.5 is the Claude Code default on Pro, Max, Team, Enterprise, and the API. See the model comparison page.

Anthropic's guidance is that Sonnet handles most coding tasks well and costs less than Opus, so reserve Opus for complex architectural decisions or multi-step reasoning. Upgrade when:

  • First attempt failed
  • Task spans many files
  • Architectural decisions needed
  • Security-critical code

The opusplan alias automates a common split: Opus during plan mode, Sonnet for execution.

Token Cost Settings

// ~/.claude/settings.json
{
  "model": "sonnet",
  "effortLevel": "medium",
  "env": {
    "CLAUDE_CODE_SUBAGENT_MODEL": "haiku"
  }
}
SettingWhat it does
modelDefault model alias (sonnet, opus, haiku, fable, opusplan, or a full ID). Without it, Opus 5.5 is the default
effortLevel / /effort / --effortThinking depth: low, medium, high, xhigh, max on current models. Opus 5.5, Sonnet 5.5, and Haiku 5.5 default to medium in Claude Code
CLAUDE_CODE_SUBAGENT_MODELDefault model for subagents with no model of their own
CLAUDE_AUTOCOMPACT_PCT_OVERRIDECompact earlier, at a percentage (1-100) of the auto-compact window. It can only lower the threshold, never raise it
MAX_THINKING_TOKENSFixed thinking budget, only for models that use a fixed budget. Opus 5.5, Sonnet 5.5, Haiku 5.5, and Fable models use adaptive reasoning, ignore nonzero budgets, and can't have thinking turned off. Use effort levels there

Treat any "X% savings" figure for these settings with suspicion. Measure your own sessions with /usage (token and cost estimate, plan usage breakdown) and /insights. Across enterprise deployments Anthropic reports an average of about $13 per developer per active day, with 90% of users under $30.

Tool-Specific Optimizations

Install code intelligence (LSP) plugins for typed languages. Anthropic's cost guide notes that precise symbol navigation (a single go-to-definition) replaces a grep followed by reading several candidate files, and that language servers report type errors after edits without running a compiler.

mgrep (Mixedbread, semantic search) is a popular add-on. Its README reports ~2× fewer tokens than grep-based workflows in a 50-task benchmark with similar or better LLM-judged quality. That is the vendor's own benchmark, so verify on your codebase before relying on it.

You can also offload noisy output to hooks: a hook that greps a log for ERROR and returns only matching lines can cut tens of thousands of tokens to hundreds.

Modular Codebase Benefits:

Having a more modular codebase with main files in the hundreds of lines instead of thousands of lines helps both in token optimization costs and getting a task done right on the first try.


Verification Loops and Evals

Benchmarking Workflow

Compare asking for the same thing with and without a skill and checking the output difference:

Branch the conversation (/branch), run the other attempt in an isolated worktree (claude --worktree <name>) without the skill, pull up a diff at the end, see what was logged.

Eval Pattern Types

  • Checkpoint-Based Evals: Set explicit checkpoints, verify against defined criteria, fix before proceeding
  • Continuous Evals: Run every N minutes or after major changes, full test suite + lint

Give Claude verification targets in the prompt (tests, expected output, screenshots). When it can verify its own work, it catches issues before you ask for fixes. A PostToolUse hook that runs your type checker or linter after edits makes this automatic. For plugin authors, claude plugin eval runs plugin eval suites.

Key Metrics

pass@k: At least ONE of k attempts succeeds
pass^k: ALL k attempts must succeed

Example, if each attempt independently succeeds 70% of the time:
        pass@1 = 70%   pass@3 ≈ 97%   pass@5 ≈ 99.8%
        pass^1 = 70%   pass^3 ≈ 34%   pass^5 ≈ 17%

Use pass@k when you just need it to work. Use pass^k when consistency is essential. Real attempts are rarely independent, so treat these as illustrations of the formulas, not benchmarks.

Orchestrator with Sequential Phases:

Phase 1: RESEARCH (use Explore agent)  → research-summary.md
Phase 2: PLAN (use planner agent)      → plan.md
Phase 3: IMPLEMENT (use tdd-guide)     → code changes
Phase 4: REVIEW (use code-reviewer)    → review-comments.md
Phase 5: VERIFY (use build-resolver)   → done or loop back

Explore is a built-in read-only subagent. The others are example custom subagents from the ECC repo; define your own in .claude/agents/.


Parallelization

When branching conversations in a multi-Claude terminal setup, make sure the scope is well-defined for the actions in the branch and the original conversation. Aim for minimal overlap when it comes to code changes.

Built-in options:

  • /branch [name] — branch the current conversation to try a different direction; return to the original with /resume
  • /fork [prompt] — copy the conversation into a new background session and keep working here
  • claude --bg "task" and claude agents — start and monitor background sessions (agent view)
  • /batch <instruction> — a bundled skill that decomposes a large change into 5 to 30 independent units and runs one background subagent per unit in an isolated worktree
  • /simplify — a bundled skill that runs four review agents in parallel (reuse, simplification, efficiency, abstraction level) and applies the cleanups

Preferred Pattern:

Main chat for code changes, branches or forks for questions about the codebase and its current state, or research on external services.

On Arbitrary Terminal Counts

Avoid setting arbitrary terminal amounts. The addition of a terminal should be out of true necessity.

Your goal should be: how much can you get done with the minimum viable amount of parallelization.

Git Worktrees for Parallel Instances

# Built in: Claude creates the worktree at <repo>/.claude/worktrees/<name>
claude --worktree feature-a
claude -w feature-b --tmux
 
# Or manage worktrees yourself
git worktree add ../project-refactor refactor-branch
cd ../project-refactor && claude

If you are scaling instances AND have multiple Claudes working on overlapping code, it's imperative you use git worktrees and have a very well-defined plan for each. Use /rename <name> (or claude -n <name>) to name all your chats so they are easy to find in /resume.

Two Terminal Setup

The Cascade Method

When running multiple Claude Code instances, organize with a "cascade" pattern:

  • Open new tasks in new tabs to the right
  • Sweep left to right, oldest to newest
  • Focus on at most 3–4 tasks at a time

Groundwork

The Two-Instance Kickoff Pattern

For workflow management, start an empty repo with 2 open Claude instances.

Instance 1: Scaffolding Agent

  • Lays down the scaffold and groundwork
  • Creates project structure
  • Sets up configs (CLAUDE.md, rules, agents)

Instance 2: Deep Research Agent

  • Connects to all your services, web search
  • Creates the detailed PRD
  • Creates architecture mermaid diagrams
  • Compiles the references with actual documentation clips

llms.txt Pattern

Many documentation sites publish an llms.txt (an LLM-optimized index of their pages); try appending /llms.txt to the docs root. Claude Code's own docs have one at https://code.claude.com/docs/llms.txt, and each page is available as Markdown by adding .md to its URL.

Philosophy: Build Reusable Patterns

"Early on, I spent time building reusable workflows/patterns. Tedious to build, but this had a wild compounding effect as models and agent harnesses improved." — @omarsar0

What to invest in:

  • Subagents
  • Skills
  • Plugins
  • Planning patterns
  • MCP tools
  • Context engineering patterns

Best Practices for Agents & Sub-Agents

The Sub-Agent Context Problem

Sub-agents exist to save context by returning summaries instead of dumping everything. But the orchestrator has semantic context the sub-agent lacks. A subagent starts with its own system prompt and the task you pass it, not your conversation history, so it only knows the literal query, not the PURPOSE behind the request.

Subagents can spawn their own subagents, up to three layers below the main conversation by default (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH; set it to 1 to disable nesting). Keep delegation shallow unless you need more.

Iterative Retrieval Pattern

  1. Orchestrator evaluates every sub-agent return
  2. Ask follow-up questions before accepting it
  3. Sub-agent goes back to source, gets answers, returns
  4. Loop until sufficient (cap it at around 3 cycles)

Key: Pass objective context, not just the query.

Key Rules for Sequential Phase Orchestration

  1. Each agent gets ONE clear input and produces ONE clear output
  2. Outputs become inputs for next phase
  3. Never skip phases
  4. Use /clear between phases
  5. Store intermediate outputs in files

Fun Stuff

Custom Status Line

Set it using /statusline — describe what you want (or run it with no arguments to auto-configure from your shell prompt). The status line is a script that receives session JSON on stdin (model, context_window.used_percentage, cost, and more) and prints whatever you want to show.

See also: ccstatusline (community project for custom Claude Code status lines).

Voice Transcription

Talk to Claude Code with your voice. Faster than typing for many people. Claude Code has built-in voice dictation, and third-party tools such as superwhisper and MacWhisper (Mac) also work.

  • Even with transcription mistakes, Claude understands intent

Terminal Aliases

alias c='claude'
alias cc='claude --continue'
alias q='cd ~/Desktop/projects'

Resources

Agent Orchestration:

  • claude-flow — Community-built orchestration project (not affiliated with Anthropic)

Self-Improving Memory:

Official:


References


Third-party configs referenced in both guides come from the community everything-claude-code project (ECC). It is not an Anthropic project; check its repository for current contents.