Dive into Claude Code
The Design Space of Today's and Future AI Agent Systems
English | 中文
A comprehensive source-level architectural analysis of Claude Code (v2.1.88, ~1,900 TypeScript files, ~512K lines of code), combined with a curated collection of community analyses, a design-space guide for agent builders, and cross-system comparisons.
[!TIP]
TL;DR -- Only 1.6% of Claude Code's codebase is AI decision logic. The other 98.4% is deterministic infrastructure -- permission gates, context management, tool routing, and recovery logic. The agent loop is a simple while-loop; the real engineering complexity lives in the systems around it. This repo dissects that architecture and distills it into actionable design guidance for anyone building AI agent systems.
Table of Contents
From Our Paper
Beyond the Paper
Key Highlights
- 98.4% Infrastructure, 1.6% AI -- The agent loop is a simple while-loop; the real complexity is permission gates, context management, and recovery logic.
- 5 Values → 13 Principles → Implementation -- Every design choice traces back to human authority, safety, reliability, capability, and adaptability.
- Bounded Analysis with an Approval Fallback -- In the legacy shell-parser path, more than 50 subcommands triggers an
ask decision.
- 2 CVEs Revealed a Pre-Trust Window -- In earlier releases, MCP servers and settings environment variables took effect before the user accepted the trust dialog.
- The Cross-Cutting Harness Resists Reimplementation -- The loop is easy to copy; hooks, classifier, compaction, and isolation are not.
Reading Guide
1,884 files · ~512K lines · v2.1.88 · 7 safety layers · 5 compaction stages · 54 tools · 27 hook events · 4 extension mechanisms · 7 permission modes
The architecture sections describe Claude Code v2.1.88. The design guide and resource catalog extend that analysis with work reviewed through October 6, 2026, and Claude Code and Codex release notes checked through October 14, 2026. The main PDF link opens arXiv v3, October 10, 2026, which redraws the layered architecture (Figure 3) and the context figure (Figure 6) and clarifies resume and pre-trust behavior. arXiv v2 and the April 2026 repository PDF remain available as archives.
Architecture at a Glance
Claude Code answers four design questions that every production coding agent must face:
| Question |
Claude Code's Answer |
| Where does reasoning live? |
Model reasons; harness enforces. ~1.6% AI, 98.4% infrastructure. |
| How many execution engines? |
One queryLoop for all interfaces (CLI, SDK, IDE). |
| Default safety posture? |
Deny-first: deny > ask > allow. Strictest rule wins. |
| Binding resource constraint? |
~200K (older models) / 1M (Claude 4.6 series) context window. Context-management stages activate under their own conditions. |
The system decomposes into 7 components (User → Interfaces → Agent Loop → Permission System → Tools → State & Persistence → Execution Environment) across 5 architectural layers.
[!NOTE]
For the full architectural deep dive -- 7 safety layers, 9-step turn pipeline, 5-layer compaction, and more -- see docs/architecture.md.
↑ Back to top
Values and Design Principles
The architecture traces from 5 human values through 13 design principles to implementation:
| Value |
Core Idea |
| Human Decision Authority |
Humans retain control via principal hierarchy. When a 93% prompt-approval rate revealed approval fatigue, response was restructured boundaries, not more warnings. |
| Safety, Security, Privacy |
System protects even when human vigilance lapses. 7 safety mechanisms. |
| Reliable Execution |
Does what was meant. Gather-act-verify loop. Graceful recovery. |
| Capability Amplification |
"A Unix utility, not a product." 98.4% is deterministic infrastructure enabling the model. |
| Contextual Adaptability |
CLAUDE.md hierarchy, graduated extensibility, trust trajectories that evolve over time. |
The 13 Design Principles
| Principle |
Design Question |
| Deny-first with human escalation |
Should unrecognized actions be allowed, blocked, or escalated? |
| Graduated trust spectrum |
Fixed permission level, or spectrum users traverse over time? |
| Defense in depth |
Single safety boundary, or multiple overlapping ones? |
| Externalized programmable policy |
Hardcoded policy, or externalized configs with lifecycle hooks? |
| Context as scarce resource |
Single-pass truncation or graduated pipeline? |
| Append-only durable state |
Mutable state, snapshots, or append-only logs? |
| Minimal scaffolding, maximal harness |
Invest in scaffolding or operational infrastructure? |
| Values over rules |
Rigid procedures or contextual judgment with deterministic guardrails? |
| Composable multi-mechanism extensibility |
One API or layered mechanisms at different costs? |
| Reversibility-weighted risk assessment |
Same oversight for all, or lighter for reversible actions? |
| Transparent file-based config and memory |
Opaque DB, embeddings, or user-visible files? |
| Isolated subagent boundaries |
Shared context/permissions, or isolation? |
| Graceful recovery and resilience |
Fail hard, or recover silently? |
The paper also applies a sixth evaluative lens -- long-term capability preservation -- citing evidence that developers in AI-assisted conditions score 17% lower on comprehension tests.
↑ Back to top
The Agentic Query Loop
The core is a ReAct-pattern while-loop: assemble context → call model → dispatch tools → check permissions → execute → repeat. Implemented as an AsyncGenerator yielding streaming events.
Before a model call, context management considers five stages in order: Budget Reduction → Snip → Microcompact → Context Collapse → Auto-Compact. Feature gates, settings, and thresholds determine which stages change the context.
9-step pipeline per turn: Settings resolution → State init → Context assembly → Conditional context management → Model call → Tool dispatch → Permission gate → Tool execution → Stop condition
Two execution paths:
StreamingToolExecutor -- begins executing tools as they stream in (latency optimization)
- Fallback
runTools -- classifies tools as concurrent-safe or exclusive
Recovery: Max output token escalation (3 retries), reactive compaction (once per turn), prompt-too-long handling, streaming fallback, fallback model
5 stop conditions: No tool use, max turns, context overflow, hook intervention, explicit abort
↑ Back to top
Safety and Permissions
7 permission modes form a graduated trust spectrum: plan → default → acceptEdits → auto (ML classifier) → dontAsk → bypassPermissions (+ internal bubble).
Deny-first: A broad deny overrides a narrow allow in rule evaluation. 7 safety layers cover tool filtering, permission decisions, hooks, and sandboxing. In v2.1.88, the session bypass flag and computer-use app allowlist are not stored in the transcript, so a session resumed in a new process starts without them; these temporary states are separate from persistent permission settings.
[!WARNING]
Bounded analysis: The legacy parser limits per-subcommand analysis to avoid blocking the event loop. If that path produces more than 50 subcommands, it returns ask. This fallback requests an approval decision; it does not automatically allow the command.
More details: authorization pipeline, auto-mode classifier, CVEs
Authorization pipeline: Pre-filtering (strip denied tools) → PreToolUse hooks → Deny-first rule evaluation → Permission handler (4 branches: coordinator, swarm worker, speculative classifier, interactive)
Auto-mode classifier (yoloClassifier.ts): Separate LLM call with internal/external permission templates. Two-stage: fast-filter + chain-of-thought.
Pre-trust execution window: 2 patched CVEs share this root cause -- in earlier releases, MCP server connections and settings environment variables took effect during initialization before the user accepted the trust dialog, creating a structurally privileged attack window outside the deny-first pipeline. In the analyzed v2.1.88 snapshot, the standard interactive startup path requires trust acceptance before hooks run, project MCP servers connect, or project settings environment variables beyond a safe allowlist apply.