← All Posts

The Anatomy of Claude Code's Architecture

Model reasons; the harness enforces. ~1.6% of Claude Code is AI decision-making; 98.4% is infrastructure. A one-pager on the agent loop, permissions, context shapers, tools, subagents, and session persistence.

August 7, 2026·6 min read

Model reasons; the harness enforces. Roughly 1.6% of the logic is AI decision-making; 98.4% is infrastructure. The core agent loop is a simple while-loop - almost everything that makes Claude Code safe, resumable, and extensible lives in the systems around it. A single queryLoop powers every interface (CLI, headless, SDK, IDE).

TL;DR: Claude Code is less a chat wrapper than an operating harness: one execution engine for every surface, deny-first permissions, aggressive context management under a ~200K-token ceiling, and append-only session transcripts that favor auditability over query power. This one-pager maps seven system components, the nine-step turn pipeline, five pre-model context shapers, the permission stack, extensibility injection points, subagent delegation, and how sessions survive resume without replaying trust.


1 · System at a Glance - 7 Components

High-level system structure: User → Interfaces → Agent Loop, with Permissions, Tools, and State over the Execution Environment

User → Interfaces → Agent Loop, with three systems hanging off the loop: Permission System (allow / ask / deny), Tools (tool results), and State & Persistence (load / persist) - all reaching the Execution Environment (files / shell / web / MCP).

#ComponentRole
1UserSubmits prompts, approves permissions, reviews output
2InterfacesInteractive CLI, headless (claude -p), Agent SDK, IDE / Desktop / Browser
3Agent LoopqueryLoop async generator: model call → tool dispatch → result → repeat
4Permission SystemDeny-first rules + auto-mode ML classifier + hook interception
5ToolsUp to 54 built-in + MCP, assembled via assembleToolPool
6State & PersistenceAppend-only JSONL transcripts, prompt history, subagent sidechains
7Execution EnvironmentShell (sandboxed), filesystem, web fetch, MCP connections

Four design questions every coding agent must answer - Claude Code's answers: Reasoning lives in the model (the harness enforces) · one execution engine for all surfaces · default safety is deny-first · the binding constraint is the ~200K-token context window.


2 · The Turn Loop - 9-Step Pipeline

Runtime turn flow: settings through stop-condition, with deny feedback and tool-result loops

Runtime turn flow:

  1. Settings resolution
  2. State init
  3. Context assembly
  4. Five pre-model shapers
  5. Model call
  6. Tool dispatch
  7. Permission gate
  8. Tool execution (sync / subagent / background)
  9. Stop-condition check

On deny, deny feedback loops back for more iterations. The turn ends with no tool use → assistant response.

Recovery: max-output-token escalation (≤3 retries/turn) · reactive compaction (≤once/turn) · prompt-too-long → context-collapse overflow → reactive compaction → terminate · streaming and fallback-model switching.


3 · Context Construction & the 5 Pre-Model Shapers

Context construction: nine ordered sources and five pre-model shapers

Five context shapers run sequentially before every model call, cheapest first:

StageStrategyTrigger
Budget ReductionPer-message size capsAlways active
SnipTrim older historyFeature-gated (HISTORY_SNIP)
MicrocompactCache-aware fine-grained compressionAlways (time-based)
Context CollapseRead-time virtual projection (non-destructive)Feature-gated (CONTEXT_COLLAPSE)
Auto-CompactFull model-generated summary (last resort)When all else fails

9 ordered context sources: System prompt → Environment info → CLAUDE.md hierarchy → Path-scoped rules → Auto-memory → Tool metadata → Conversation history → Tool results → Compact summaries.

CLAUDE.md hierarchy (4 levels): Managed (/etc/claude-code/) · User (~/.claude/) · Project (CLAUDE.md, .claude/rules/*.md) · Local (CLAUDE.local.md, gitignored).

Critical choice: CLAUDE.md is user context (probabilistic compliance), not system prompt - permission rules provide the deterministic enforcement layer.

File-based memory: no embeddings / no vector DB - an LLM scans memory-file headers and selects ≤5 relevant files on demand. Fully inspectable, editable, and version-controllable.


4 · Permission System - Deny-First

Permission gate: tool use through Policy Core to Deny, Allow, or Ask

Tool use → Policy Core (Rules · Modes · Hooks) → decision: Deny (denied result) / Allow (execute) / Ask (user or auto-classifier). Deny always overrides allow, even when allow is more specific.

7 permission modes (trust ↑): plan · default · acceptEdits · auto (ML classifier) · dontAsk · bypassPermissions · bubble (internal subagent escalation).

Seven independent safety layers - a request must pass all applicable ones:

  1. Tool pre-filtering (denied tools removed from the model's view)
  2. Deny-first rule evaluation
  3. Permission-mode constraints
  4. Auto-mode ML classifier (separate LLM safety call)
  5. Shell sandboxing (filesystem + network isolation)
  6. Non-restoration on resume (permissions never persist across sessions)
  7. Hook-based interception (PreToolUse hooks modify / block)

5 · Tools & Extensibility - 3 Injection Points

Three injection points in the agent loop and tool pool assembly

Tool pool assembly (5 steps): Base enumeration (≤54) → Mode filtering → Deny pre-filtering → MCP integration → Deduplication.

Four extension mechanisms (graduated context cost):

MechanismCostCapability
HooksZero27 events · 4 execution types (shell, LLM, webhook, subagent verifier)
SkillsLowSKILL.md (15+ frontmatter fields), injected via SkillTool meta-tool
PluginsMedium10 component types (commands, agents, skills, hooks, MCP, LSP, styles…)
MCP ServersHighExternal tools via 7 transports (stdio, SSE, HTTP, WebSocket, SDK, IDE)

Three injection points:

  • assemble() - what the model sees
  • model() - what it can reach
  • execute() - whether / how an action runs

6 · Subagent Delegation

Subagent delegation: parent spawns isolated sidechains; only summaries return

SkillTool vs AgentTool: SkillTool injects instructions into the current context (cheap, same window); AgentTool spawns a new isolated context window (≈7× tokens, but context-safe).

6 built-in types (+ custom .claude/agents/*.md): Explore · Plan · General-purpose · Claude Code Guide · Verification · Statusline-setup.

3 isolation modes: Worktree (git filesystem isolation) · Remote (internal-only) · In-process (default) - shared filesystem, isolated conversation.

Sidechains: each subagent writes its own .jsonl; only the summary returns to the parent - full history never enters parent context. Multi-instance coordination via POSIX flock(), zero external deps.


7 · Session Persistence

Session persistence channels, compaction flow, and Rewind / Resume / Fork

3 persistence channels:

ChannelPurpose
Session transcriptsAppend-only JSONL, chain-patched at compaction boundaries
Global prompt historyhistory.jsonl, reverse-read for ↑-arrow recall
Subagent sidechainsSeparate JSONL per subagent

Compaction flow: remove old tool outputs → generate session summary → mark compact boundary. Checkpoints enable Rewind / Resume / Fork.

Safety: permissions are never restored on resume - trust is re-established each session (accepted friction to keep the invariant). Trade-off: append-only JSONL favors auditability and simplicity over query power - every event is human-readable and reconstructable without special tooling.