Anatomy of Claude Code: How a Production-Grade AI Agent System Is Built
> Paper: *Dive into Claude Code: The Design Space of Today's and Future AI Agent Systems* > arXiv: 2604.14228 | v2.1.88, ~1,900 TypeScript files, ~512K lines of code > Authors: Jiacheng Liu, Xiaohan Zhao, Xinyi Shang, Zhiqiang Shen (VILA Lab, MBZUAI & UCL) > Published: 2026-04-14
One-Line Summary
Claude Code is a "simple while-loop wearing heavy armor": core AI decision logic is only 1.6% of the code, while 98.4% is deterministic infrastructure — permission gating, context compression, recovery, and the extensibility framework. The real differentiator is not the model, but the harness surrounding it.
Five Human Values → Thirteen Design Principles
The paper traces architecture back to five fundamental human needs:
1. Human Decision Authority
- The user always holds the final decision
- Principles: progressive trust, deny-by-default, permissions never auto-restored across sessions
- Seven independent layers (but they share a performance constraint!)
- Principles: defense-in-depth, deterministic sandbox, boundary validation
- Five-layer context compression pipeline, reactive recovery
- Principles: lazy loading, budget awareness, fault isolation
- Four extension mechanisms: MCP, Plugins, Skills, Hooks
- Principles: open protocols, layered extensibility, ecosystem compatibility
- Four-level
CLAUDE.mdhierarchy, file memory, sub-agent delegation - Principles: tiered context, persistent memory, adaptive learning
assemble()— what the model sees (instructions, tool schemas)model()— what the model can reach (available tools)execute()— whether/how operations run (permission rules, hooks)- SkillTool: injects instructions into the current context (cheap, same window)
- AgentTool: spawns a new isolated context window (~7x token cost, but context-safe)
- Local coding tools → per-action security evaluation is essential
- Personal-assistant gateways → boundary-level access control is more reasonable
- Paper: arXiv 2604.14228
- GitHub: VILA-Lab/Dive-into-Claude-Code
- Build guide: Build Your Own AI Agent
2. Safety and Security
3. Reliable Execution
4. Capability Amplification
5. Contextual Adaptability
Key insight: The 13 principles form a complete traceability chain from human values to implementation choices. Every design decision can be traced upward to a human need.
Core Architecture: 9-Step Pipeline + 5-Layer Compression
9-Step Execution Pipeline (per iteration)
1. Settings parsing → 2. State initialization → 3. Context assembly → 4. Five pre-model shaping stages → 5. Model invocation → 6. Tool dispatch → 7. Permission gating → 8. Tool execution → 9. Stop-condition check5-Layer Context Compression (lowest overhead first)
| Stage | Strategy | Trigger | |------|------|------| | Budget trimming | Per-message size cap | Always on | | Snipping | Trim older history |HISTORY_SNIP flag |
| Micro-compaction | Cache-aware fine-grained compression | Always on (time-based) |
| Context collapse | Virtual projection at read time (non-destructive) | CONTEXT_COLLAPSE flag |
| Auto-compaction | Full model-generated summary (last resort) | When other stages fail |Core tension: The context window is the most fundamental scarce resource. Every other architectural decision — lazy loading, deferred tool schema loading, sub-agents returning only summaries — is forced by this constraint.
Security System: 7 Independent Layers + One Fatal Flaw
The Seven Layers
1. Tool pre-filtering (remove denied tools from model view) 2. Deny-by-default rule evaluation 3. Permission mode constraints (7 modes) 4. Auto mode ML classifier (independent LLM call) 5. Shell sandbox (filesystem + network isolation) 6. Permissions never auto-restored on session resume 7. Hook-based interception (PreToolUse / PostToolUse)Fatal Discovery: Shared Failure Mode
The paper exposes a critical vulnerability: all seven security layers share the same economic constraint — token cost. When a command contains more than 50 subcommands, the system completely skips security analysis. This is not a bug, but an architectural-level trade-off.Four CVEs Reveal a Pre-Trust Window
Extensions execute before the trust dialog appears. There is a "pre-trust window" between security and UX that extensions can exploit for malicious code execution.Extensibility: Four Mechanisms with Progressive Context Cost
| Mechanism | Context Cost | Key Capability |
|------|-----------|----------|
| Hooks | Zero | 27 events, 4 execution types |
| Skills | Low | SKILL.md YAML frontmatter, on-demand injection |
| Plugins | Medium | 10 component types |
| MCP servers | High | External tools, 7 transport types |
Design wisdom: Not every extension must consume tokens. Hooks handle lifecycle events without touching the context window; Skills are injected only when relevant. Reserve high-context-cost mechanisms for scenarios that genuinely introduce new tool classes.
Three Injection Points
Sub-Agent Delegation: SkillTool vs AgentTool
Key Design Choice
Three Isolation Modes
| Mode | Mechanism | Default | |------|------|------| | Worktree | Git worktree (filesystem isolation) | No | | Remote | Remote execution (internal) | No | | In-process | Shared filesystem, isolated conversation | Yes |Side-chain Transcripts
Each sub-agent writes its own.jsonl file, returning only a summary to the parent. Full history never enters the parent context. Multiple instances coordinate via POSIX flock() — zero external dependencies.Comparison with OpenClaw: Same Question, Different Answers
| Dimension | Claude Code | OpenClaw |
|------|-------------|----------|
| System scope | CLI/IDE coding harness, per-session process | Persistent WS gateway daemon, multi-channel control plane |
| Trust model | Deny-by-default, per-action, 7 permission modes | Single trusted operator, DM pairing, optional per-session/agent/shared sandbox |
| Agent runtime | Async-generator queryLoop() as the hub | Pi-agent runner embedded in gateway RPC dispatch |
| Extension architecture | 4 mechanisms with progressive cost: MCP/Plugins/Skills/Hooks | Manifest-first plugin system, 12 capability types, MCP built-in |
| Memory & context | CLAUDE.md 4-level + 5-layer compression | Workspace bootstrap files + MEMORY.md + optional hybrid search + experimental dreaming |
| Multi-agent & routing | Task-delegated sub-agents, worktree isolation | Independent agents + bound channel dispatch; sub-agent nesting depth configurable |
Core conclusion: There is no single "best" agent architecture. Deployment context dictates design choices:
Six Future Design Directions
1. Scalable autonomy with human oversight: as model capability rises, how to reduce UX friction while preserving human authority? 2. Multimodal and real-time interaction: beyond text-based interaction paradigms 3. Federated and distributed agents: cross-device, cross-organization collaboration 4. Long-term memory and personalization: from session-level memory to user-level lifelong learning 5. Formal verification of security architecture: prove safety properties with formal methods 6. Ecosystem interoperability: cross-platform, cross-framework agent collaboration standards
Actionable Recommendations for Agent Builders
1. Answer six design questions first: where does reasoning live? what is the security posture? how is context managed? how is extensibility done? how do sub-agents work? how are sessions persisted? 2. Design for context scarcity from day one: treat context compression as a first-class citizen, not a retrofit 3. Security layers must fail independently: ensure different mechanisms do not share resource constraints or failure modes 4. Progressive layering over monolithic mechanisms: stack independent stages for security, context, and extensibility 5. Model free, harness enforced: let the model do what it excels at (reasoning, planning); use deterministic code to enforce boundaries 6. Permissions never auto-restore across sessions: security state must not implicitly persist across session boundaries