English static mirror for SEO/GEO · AI-assisted translation · Read Chinese original

Anatomy of Claude Code: How a Production-Grade AI Agent System Is Built

Forum topic · 小凯 · 2026-04-29

Summary

Analyzes the paper "Dive into Claude Code: The Design Space of Today's and Future AI Agent Systems" (arXiv 2604.14228, VILA Lab @ MBZUAI & UCL), which reverse-engineers Claude Code's ~512K lines of TypeScript across ~1,900 files. The core finding: AI decision logic is only 1.6% of the codebase, while 98.4% is deterministic infrastructure — permission gating, context compression, recovery, and extensibility. The paper traces 13 design principles back to five human values (human decision authority, safety, reliable execution, capability amplification, contextual adaptability), then dissects a 9-step execution pipeline, a 5-layer context compression stack, 7 independent security layers (with a critical shared token-budget failure mode that bypasses checks when a command has more than 50 subcommands), and four extensibility mechanisms with progressive context cost. It also contrasts Claude Code with OpenClaw and proposes six future research directions, offering actionable guidance for agent builders on context, security, and harness design.

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
  • 2. Safety and Security

  • Seven independent layers (but they share a performance constraint!)
  • Principles: defense-in-depth, deterministic sandbox, boundary validation
  • 3. Reliable Execution

  • Five-layer context compression pipeline, reactive recovery
  • Principles: lazy loading, budget awareness, fault isolation
  • 4. Capability Amplification

  • Four extension mechanisms: MCP, Plugins, Skills, Hooks
  • Principles: open protocols, layered extensibility, ecosystem compatibility
  • 5. Contextual Adaptability

  • Four-level CLAUDE.md hierarchy, file memory, sub-agent delegation
  • Principles: tiered context, persistent memory, adaptive learning
  • 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 check

    5-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

  • assemble() — what the model sees (instructions, tool schemas)
  • model() — what the model can reach (available tools)
  • execute() — whether/how operations run (permission rules, hooks)
  • Sub-Agent Delegation: SkillTool vs AgentTool

    Key Design Choice

  • SkillTool: injects instructions into the current context (cheap, same window)
  • AgentTool: spawns a new isolated context window (~7x token cost, but context-safe)
  • 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:

  • Local coding tools → per-action security evaluation is essential
  • Personal-assistant gateways → boundary-level access control is more reasonable
  • 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

    Notable Independent Observations

    On the "1.6% vs 98.4%" framing

    The number is a powerful narrative but must be read carefully. Claude Code's "simple while-loop" is simple because complexity is outsourced to the Anthropic LLM API, the MCP ecosystem, and the operating system itself. Counting those in would raise the AI-related code share substantially. Even so, the core argument stands: the quality of the deterministic harness is the differentiator.

    On the shared failure mode of security layers

    This is one of the paper's most valuable findings. Seven security layers look like defense-in-depth, but they share a token-budget constraint — a hidden common-cause failure. Under extreme load (subcommands > 50), every layer fails simultaneously. True defense-in-depth requires independent resource bases.

    On the append-only JSONL design

    Claude Code's choice of append-only JSONL for session persistence trades query capability for auditability and simplicity. It exemplifies a recurring meta-pattern: auditability over queryability. In an era of AI system black-boxes, this "everything can be reconstructed" design philosophy deserves respect.

    References

  • Paper: arXiv 2604.14228
  • GitHub: VILA-Lab/Dive-into-Claude-Code
  • Build guide: Build Your Own AI Agent

Tags

#ai-agent#claude-code#system-architecture#context-compression#agent-security#model-context-protocol#arxiv-2604#harness-design

This page is an English static mirror generated for search and AI citation. It may be a full translation or structured summary of the Chinese original. Canonical interactive discussion lives on the Chinese page: https://zhichai.net/topic/177618901