0
0
via GitHub · Posted Aug 7, 2026 · 1 min read

Dive into Claude Code: AI Agent Architecture Analysis

VILA-Lab/Dive-into-Claude-Code
Library

A Systematic Analysis and Discussion of Claude Code for Designing Today's and Future AI Agent Systems

2,030Stars
315Forks
1Open issues
28Watching
NOASSERTION Updated 1 week ago

A comprehensive technical analysis of Claude Code's architecture that reveals how production AI agent systems are 98.4% deterministic infrastructure—permission gates, context management, and recovery logic—with only 1.6% AI decision logic. The repository provides source-level dissection, design principles, and actionable guidance for anyone building agent systems.

0 comments

README

Dive into Claude Code

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.
  • Defense in Depth with Shared Failure Modes -- 7 safety layers, but all share performance constraints. 50+ subcommands bypass security analysis.
  • 2 CVEs Reveal a Pre-Trust Window -- Extensions execute before the trust dialog appears.
  • The Cross-Cutting Harness Resists Reimplementation -- The loop is easy to copy; hooks, classifier, compaction, and isolation are not.

Reading Guide

If you are a... Start here Then read
Agent Builder Build Your Own Agent Architecture Deep Dive
Security Researcher Safety and Permissions Architecture: Safety Layers
Product Manager Key Highlights Values and Principles
Researcher Full Paper (arXiv) Community Resources

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


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. 5 compaction layers before every model call.

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.


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 independent safety layers.
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.
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.


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 every model call, five compaction shapers run sequentially (cheapest first): Budget Reduction → Snip → Microcompact → Context Collapse → Auto-Compact.

9-step pipeline per turn: Settings resolution → State init → Context assembly → 5 pre-model shapers → 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


7 permission modes form a graduated trust spectrum: plandefaultacceptEditsauto (ML classifier) → dontAskbypassPermissions (+ internal bubble).

Deny-first: A broad deny always overrides a narrow allow. 7 independent safety layers from tool pre-filtering through shell sandboxing to hook interception. Permissions are never restored on resume -- trust is re-established per session.

[!WARNING] Shared failure modes: Defense-in-depth degrades when layers share constraints. Per-subcommand parsing causes event-loop starvation -- commands exceeding 50 subcommands bypass security analysis entirely to prevent the REPL from freezing.

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 -- hooks and MCP servers execute during initialization before the trust dialog appears, creating a structurally privileged attack window outside the deny-first pipeline.


Four mechanisms at graduated context costs: Hooks (zero) → Skills (low) → Plugins (medium) → MCP (high). Three injection points in the agent loop: assemble() (what the model sees), model() (what it can reach), execute() (whether/how actions run).

Tool pool assembly (5-step): Base enumeration (up to 54 tools) → Mode filtering → Deny pre-filtering → MCP integration → Deduplication

27 hook events across 5 categories with 4 execution types (shell, LLM-evaluated, webhook, subagent verifier)

Plugin manifest accepts 10 component types: commands, agents, skills, hooks, MCP servers, LSP servers, output styles, channels, settings, user config

Skills: SKILL.md with 15+ YAML frontmatter fields. Key difference -- SkillTool injects into current context; AgentTool spawns isolated context.


9 ordered sources build the context window. CLAUDE.md instructions are delivered as user context (probabilistic compliance), not system prompt (deterministic). Memory is file-based (no vector DB) -- fully inspectable, editable, version-controllable.

4-level CLAUDE.md hierarchy: Managed (/etc/) → User (~/.claude/) → Project (CLAUDE.md, .claude/rules/) → Local (CLAUDE.local.md, gitignored)

5-layer compaction (graduated lazy-degradation): Budget reduction → Snip → Microcompact → Context Collapse (read-time projection, non-destructive) → Auto-Compact (full model summary, last resort)

Memory retrieval: LLM-based scan of memory-file headers, selects up to 5 relevant files. No embeddings, no vector similarity.


6 built-in types (Explore, Plan, General-purpose, Guide, Verification, Statusline) + custom agents via .claude/agents/*.md. Sidechain transcripts: only summaries return to parent (parent's context is protected from subagent verbosity). Three isolation modes: worktree, remote, in-process. Coordination via POSIX flock().

SkillTool vs AgentTool: SkillTool injects into current context (cheap). AgentTool spawns isolated context (expensive, but prevents context explosion).

Permission override: Subagent permissionMode applies UNLESS parent is in bypassPermissions/acceptEdits/auto (explicit user decisions always take precedence).

Custom agents: YAML frontmatter supports tools, disallowedTools, model, effort, permissionMode, mcpServers, hooks, maxTurns, skills, memory scope, background flag, isolation mode.


Three channels: append-only JSONL transcripts, global prompt history, subagent sidechains. Permissions never restored on resume -- trust is re-established per session. Design favors auditability over query power.

Chain patching: Compact boundaries record headUuid/anchorUuid/tailUuid. The session loader patches the message chain at read time. Nothing is destructively edited on disk.

Checkpoints: File-history checkpoints for --rewind-files, stored at ~/.claude/file-history/<sessionId>/.


New agent-system developments reinforce the same lesson Claude Code makes clear: agent capability is not a model property alone. It comes from the runtime, context layer, execution boundary, tool supply chain, the controls humans have over it, and the evaluation loop around the model.

Design Implication What it means for agent builders Representative signals
Runtime and control plane are first-class design concerns Durable execution, checkpoints, sandboxes, agent inventory, policy, and observability should be designed as parts of the system that users can see, not hidden deployment details. Cursor cloud agents, Google Managed Agents, Microsoft Agent 365, Databricks Omnigent
Context is managed infrastructure Prompts, files, skills, IDE indexes, workspace state, memory namespaces, and interpreter state need lifecycle, provenance, review, and rollback. LangChain Context Hub, AWS AgentCore, Anthropic managed-agent memory
Execution boundary is the safety boundary Permissions, network reachability, filesystem access, credential custody, tenant isolation, and OS sandboxing are core architecture, not late-stage hardening. Codex Windows sandbox, Running Codex safely, Anthropic self-hosted sandboxes
Tools and skills are a supply chain MCP servers, skills, plugins, and agent-to-agent protocols need registries, allowlists, identity, semantic review, versioning, and revocation. NSA MCP security, GitHub MCP allowlists, A2A milestone
Humans become managers and verifiers Agent products should support goals, plans, approvals, interrupts, reviewable diffs, escalation, and constrained multi-agent write authority. Codex from anywhere, Copilot cloud agent, Cognition multi-agents
Observability must close the improvement loop Traces should feed evaluation, failure clustering, policy enforcement, and prompt/tool repair rather than ending as passive logs. LangSmith Engine, OpenAI agent improvement loop, AWS AgentCore Evaluations

These signals do not replace Claude Code's design space; they make its boundaries clearer. The agent loop is the small part. The harness around it is where most capability, safety, and reliability decisions now live. For month-level source notes, see docs/agent-design-space-source-notes.md.


Not a coding tutorial. A guide to the design decisions you must make, derived from architectural analysis.

Every production agent must navigate these decisions:

Decision The Question Key Insight
Reasoning placement How much logic in the model vs. harness? As models converge in capability, the harness becomes the differentiator.
Safety posture How do you prevent harmful actions? Defense-in-depth fails when layers share failure modes.
Context management What does the model see? Design for context scarcity from day one. Graduated > single-pass.
Extensibility How do extensions plug in? Not all extensions need to consume context tokens.
Subagent architecture Shared or isolated context? Agent teams in plan mode cost ~7× tokens. Subagent summary-only returns prevent context blow-up.
Session persistence What carries over? Never restore permissions on resume. Auditability > query power.

Read the full guide: docs/build-your-own-agent.md


The same recurring design questions admit different architectural answers when the deployment context changes. The table below contrasts Claude Code v2.1.88 with two notable peers — OpenClaw, a local-first multi-channel personal-assistant gateway, and NousResearch/hermes-agent, a self-improving multi-deployment agent — across the six design dimensions Section 10 of the paper uses for the OpenClaw comparison. Cells are source-grounded; this is not a feature scoreboard.

Design Dimension Claude Code (v2.1.88) Star OpenClaw Star Hermes-Agent Star
System scope & deployment Per-user CLI / SDK / IDE interface for coding; one queryLoop async generator across entry points. Local-first WebSocket gateway (default port 18789, loopback-bound by default; other binds available); routes ~23 messaging channels to an embedded agent runtime; companion apps for macOS, iOS, Android. Three entry points: hermes (interactive CLI), hermes-agent (programmatic runtime), hermes-acp (ACP server); gateway adapters route messages to per-session AIAgent instances cached LRU-style (max 128, 1 h idle TTL); also runs as MCP server via hermes mcp serve.
Trust model & security Deny-first per-action evaluation; 7 permission modes; LLM-based auto-mode classifier (yoloClassifier / sideQuery); session-scoped permission state (session bypass flag, app allowlist state) is not restored on resume. Single trusted operator per gateway; DM pairing codes, sender allowlists, gateway authentication; per-agent allow / deny tool policy; opt-in sandboxing via Docker / SSH / OpenShell, off by default; non-main mode sandboxes only non-main sessions; hostile multi-tenant isolation explicitly not supported. Dangerous-command pattern detection with per-session approval state; CLI interactive prompts and gateway async prompts; auxiliary-LLM smart approval auto-approves low-risk commands; permanent allowlist persisted in config.yaml; subagent worker threads default to auto-deny dangerous commands (opt-in subagent_auto_approve for batch / cron runs).
Agent runtime & tools Single queryLoop async generator with streamed event yields; environment- and feature-gated tool registry; before-API compaction (Snip, Microcompact, Context Collapse, Auto-Compact) runs conditionally, with Auto-Compact first attempting session-memory compaction. Embedded agent runtime inside the gateway's RPC dispatch (the agent RPC validates parameters, accepts immediately, runs asynchronously, and streams lifecycle / stream events back over the gateway protocol); per-session queue serialization with an optional global lane. While-loop with explicit per-turn iteration budget and grace-call slot; per-turn checkpoint dedup; gateway step_callback hook fires on each iteration; auxiliary-model context compression summarizes middle turns while protecting head and tail.
Extension architecture Four mechanisms at graduated context cost: hooks → skills → plugins → MCP; 27 hook events; 10 plugin component types. Manifest-first plugin system with 12 documented capability categories; central registry exposes tools, channels, provider setup, hooks, HTTP routes, CLI commands, services; separate skills layer with multiple sources (workspace highest precedence) plus the ClawHub public registry; openclaw mcp provides both an MCP server interface and an outbound client registry for other MCP servers. 12 bundled plugins under plugins/ (context_engine, disk-cleanup, example-dashboard, google_meet, hermes-achievements, image_gen, kanban, memory, observability, platforms, spotify, strike-freedom-cockpit); MCP server (mcp_serve.py) exposes 10 tools; ACP adapter (acp_adapter/) exposes Hermes as an ACP server.
Memory & context 4-level CLAUDE.md hierarchy; before-API compaction (Snip, Microcompact, Context Collapse, Auto-Compact); LLM-based selection from file-based Markdown memory files. Workspace bootstrap files (AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md) plus conditional BOOTSTRAP.md / HEARTBEAT.md / MEMORY.md; separate memory system (MEMORY.md, daily notes under memory/YYYY-MM-DD.md, optional DREAMS.md); hybrid vector + keyword search when an embedding provider is configured; experimental dreaming for long-term promotion; pluggable compaction providers. SQLite state store with FTS5 full-text search and WAL-mode concurrent readers; sessions linked by parent_session_id chains for compression-triggered splits; 8 swappable memory backends under plugins/memory/ (byterover, hindsight, holographic, honcho, mem0, openviking, retaindb, supermemory); auxiliary-LLM compression as a separate context-management layer.
Multi-agent architecture Sub-agent delegation via sidechain transcripts; 6 built-in agent definitions (availability conditional on build / mode) plus custom; a single summary message returns to parent (in-process / viewable transcript cases preserve more internal detail); agent-isolation settings include worktree and remote, with an in-process teammate backend in the swarm path. Two layers. (1) Multi-agent routing: per-channel isolated agents with their own workspace, auth profiles, session store, and model configuration, dispatched via deterministic binding rules. (2) Sub-agent delegation: maxSpawnDepth range 1–5, default 1, recommended 2; tool policy varies by depth; project vision (VISION.md) rejects agent-hierarchy frameworks as the default. delegate_task tool spawns child AIAgent instances in a ThreadPoolExecutor (parent blocks until children complete); each child has fresh conversation history, its own task_id, and a restricted toolset (DELEGATE_BLOCKED_TOOLS strips delegate_task, clarify, memory, send_message, execute_code); default depth MAX_DEPTH = 1 (configurable up to cap 3); default 3 concurrent children.

What this contrast reveals. Three observations follow from the table. First, deployment context drives the rest of the design: a per-user coding CLI converges on per-action approval and a single execution loop, a multi-channel gateway converges on perimeter trust and channel-bound agents, and a multi-deployment messaging-and-cloud agent converges on opt-in container/cloud isolation, an LLM-based smart approval, and a swappable-backend memory layer. Second, the extension layer is where each system most clearly differentiates: Claude Code stratifies four mechanisms by context cost, OpenClaw treats extension as registry-managed capabilities at the gateway, and Hermes-Agent ships bundled plugins plus dual MCP server / ACP server interfaces other agents can connect to. Third, memory architectures sit on a spectrum: file-based and inspectable Markdown (Claude Code), file-based plus optional vector + experimental dreaming (OpenClaw), or full-text indexed (FTS5) plus eight swappable plugin backends including dedicated vector / RAG providers (Hermes-Agent). The table is best read not as a scoreboard but as three different fixed points in the same design space.


Find Resources by Design Question

The sections above give Claude Code's own answer to each design question. The catalogs below are organized by resource type instead. This table joins the two, so you can start from a question rather than from a resource type.

Design question Claude Code's answer Where the outside resources are
How does one turn actually run? Agent loop, tool dispatch, recovery. The Agentic Query Loop Architecture Analysis · Open-Source Reimplementations · Coding Agent CLIs · Harness Engineering
Who is allowed to do what? Permissions, approval, sandboxing. Safety and Permissions Security Research & Incidents · Runtime & Sandbox Infrastructure · Product Documentation · Academic Papers
How is the system extended? Hooks, skills, plugins, MCP. Extensibility Skills and Harness Extensions · MCP Ecosystem · Product Documentation
What does the model see? Context assembly, memory, compaction. Context and Memory Memory and Persistent Context · Blog Posts & Technical Articles · Academic Papers
How is work divided? Subagents, teams, orchestration. Subagent Delegation Agent Frameworks and Orchestration · Cross-Vendor Engineering · Cross-System Comparison
What survives a restart? Sessions, checkpoints, persistence. Session Persistence Runtime & Sandbox Infrastructure · Cross-Vendor Engineering
How do you know it worked? Evaluation, benchmarks, trace analysis. New Signals: closing the improvement loop Evaluation & Benchmarks · Academic Papers

For shifts that cut across every axis rather than sitting on one, see New Signals in the Agent Design Space.


A curated map of the repos, reimplementations, and academic papers surrounding Claude Code's architecture.

Official Anthropic Resources

Primary sources referenced throughout the paper — Anthropic's own engineering and research publications, plus product documentation.

Research & Engineering Blogs

Article Topic
Building Effective Agents Foundational: simple composable patterns over heavy frameworks.
Effective Context Engineering for AI Agents Context curation and token-budget management.
The New Rules of Context Engineering for Claude 5 Generation Models Anthropic removed over 80% of Claude Code's system prompt for newer models with no measurable loss on its coding evals. The post recommends replacing blanket rules with model judgment, tool-use examples with clearer interfaces, and up-front context loading with skills and tool definitions loaded on demand. Its broader point is that a harness should be reviewed and pruned as models change, rather than only accumulating instructions.
A Harness for Every Task: Dynamic Workflows in Claude Code Anthropic's design account of programmatic subagent orchestration. It names six reusable patterns — classify-and-act, fan-out-and-synthesize, adversarial verification, generate-and-filter, tournament, and loop-until-done — and moves coordination state from one model context into a script that can run and re-run many isolated agents.
Prompt Caching with Claude Cache reads at 10% cost, writes at 125%; 5-min default TTL. The platform feature that makes Claude Code's cache-aware compaction architecturally meaningful.
Harness Design for Long-Running Application Development Harness architecture for autonomous full-stack dev; multi-agent patterns.
Claude Code Auto Mode: A Safer Way to Skip Permissions ML-classifier approval automation; source of the 93% approval-rate finding.
Auto Mode Is Now the Default in Claude Code Auto mode becomes the default on Pro, Max, and Team plans (announced August 7, 2026, with rollout completed August 14), while Enterprise and the API surfaces (the Claude API, Bedrock, Vertex, and Foundry) stay opt-in. A 1,053-tester study is the argument: manual review caught 13.6% of injected dangerous commands against 89% for the classifier, and the harmful-action rate fell from 6.3% of manually approved sessions to 2.4%. The successor milestone to the auto-mode engineering post above, now a default rather than a setting.
Beyond Permission Prompts: Making Claude Code More Secure and Autonomous Sandbox-based security; 84% reduction in permission prompts.
How We Contain Claude Across Products Containment across claude.ai, Claude Code, and Cowork (May 2026); Claude Code's human-in-the-loop sandbox, approval fatigue, and capping the blast radius.
Measuring AI Agent Autonomy in Practice Longitudinal usage: auto-approve rates grow from ~20% to 40%+ with experience.
Agentic Coding and Persistent Returns to Expertise Anthropic's first quantitative account of how the work actually splits: humans make roughly 70% of planning decisions but only 20% of execution decisions, and a single prompt triggers about 10 Claude actions on average, with some stretches running past 100 actions between human touchpoints. An empirical anchor for the paper's claims about human control surfaces and supervision cost.
Our Framework for Developing Safe and Trustworthy Agents Governance framework for responsible agent deployment.
When AI Builds Itself Anthropic Institute on recursive self-improvement: AI accelerating AI development, the direction-setting and research-taste gaps, and governance scenarios.
Scaling Managed Agents: Decoupling the Brain from the Hands Hosted-service architecture separating reasoning, execution, and session.
An Update on Recent Claude Code Quality Reports Postmortem on three bugs behind perceived quality drops: a reasoning-effort default, a cache optimization bug, and a system-prompt change.
Introducing Claude Opus 4.8 May 2026 model update: sharper judgment and honesty (~4x fewer unremarked code flaws), longer autonomous runs; introduces dynamic workflows in research preview.
Claude Fable 5 and Claude Mythos 5 June 2026 Mythos-class tier sitting above Opus; Fable 5 is the general-use configuration (risky queries fall back to Opus 4.8), with state-of-the-art software-engineering and agentic-coding performance. Access was suspended globally on June 12, 2026 (see next row).
Statement on Suspending Access to Fable 5 and Mythos 5 Anthropic's statement on suspending Fable 5 and Mythos 5. A US export-control directive (June 12, 2026) restricted access for foreign nationals, but Anthropic disabled both models for all users worldwide, just days after launch. A rare case of regulation forcing a deployed frontier model offline, and a concrete example of the compliance and safety pressures that agent systems face in deployment.

Product Documentation

Document Topic
How Claude Code Works Official overview of the agent loop, tools, and terminal automation.
Permissions Tiered permission system, modes, granular rules.
Hooks 27-event hook reference, execution models, lifecycle events.
Memory CLAUDE.md hierarchy, auto memory, learned preferences.
Sub-agents Specialized isolated assistants, custom prompts, tool access.
Orchestrate Subagents at Scale with Dynamic Workflows Claude writes a JavaScript orchestration script; a background runtime fans out to up to 16 concurrent and 1,000 total subagents, with intermediate state held in script variables outside the context window (v2.1.154+). The permission design is the part worth noting: the launch prompt follows your permission mode, but the subagents a workflow spawns always run in acceptEdits and inherit the session tool allowlist regardless of that mode, so file edits are auto-approved inside a run.
Configure Auto Mode The fullest official account of the auto-mode classifier as a policy engine: a four-tier precedence (hard_deny over soft_deny over allow over explicit user intent), rules written as natural-language prose rather than regexes, and one deliberate exclusion. The classifier reads CLAUDE.md but never the shared `.claude/settings.json

Comments (0)

Sign in to join the discussion.

No comments yet

Be the first to share your take.