Skip to content
Source Analysis

Source Analysis

What actually happens when you type a message into Claude Code?

Based on the @anthropic-ai/claude-code 2.1.88 npm release (since removed from npm history), reverse-engineered through source map → path statistics → semantic layering → cross-validation. Dissecting an industrial-grade agent harness system containing 1,902 source files, 43 tools, and 97 commands.

Docs + Visual Map side by side. Docs explain why things are designed this way; the visual map answers where they are and how they connect. Both share the same five-topic skeleton and data model. Open docs on one side, the visual map on the other.

Start Here

Deep Dives

Reading Paths

Different backgrounds call for different entry points. Pick the path that fits your goals:

Path 1: User Perspective

Understand why Claude Code behaves the way it does — why tools get denied, why long sessions compress, why some commands are hidden.

  1. Runtime Loop — follow a request through seven stages
  2. Execution Governance — understand the allow/deny decision chain
  3. Command Surface — find the internal mapping for commands you use
  4. Cost Tracking — understand token metering and compression triggers

Path 2: Agent Builder

Extract reusable design patterns from an industrial-grade agent system — query loop, tool governance, context compaction, memory loops.

  1. Architecture Map — establish the six-layer structure
  2. Runtime Loop — understand the query loop heartbeat and state machine
  3. Tool Plane — understand tool registration, governance, and execution model
  4. Memory System — understand five-layer compression and long-session continuity
  5. Coordinator Mode — understand multi-Worker orchestration

Path 3: Reverse Engineering Researcher

Fully map the system’s capability boundaries and evolution direction — from stable trunk to experimental edges.

  1. Architecture Map — reduce 1,902 files to six structural layers
  2. Tool Plane + Command Surface — full capability surface scan
  3. Signals & Extensions — identify mature vs. experimental capabilities
  4. All Deep Dive pages — verify source path evidence one by one

General Advice

Regardless of path, use the Visual Map alongside the docs — docs explain why things are designed this way, the visual map answers where they are and how they connect.

How to read this alongside official materials

Official materials are best for confirming feature definitions, supported boundaries, and minimal examples. The source-analysis section is better for understanding how the system is organized, why those constraints exist, and which patterns are worth carrying into your own agent engineering.

Recommended order:

  1. Use official docs to confirm capability primitives and current boundaries
  2. Read Research Method to establish the frame
  3. Then move into Runtime Loop and Tool Plane
  4. Use Engineering Playbook to reorganize those capabilities into a rollout path
  5. Finally treat Memory System, Coordinator Mode, and MCP & Bridge as transferable engineering samples

This avoids two common misreads: taking official minimal examples as complete system design, or treating local signals in a single source snapshot as long-term product commitments.

Key Findings

Claude Code is not a simple LLM wrapper CLI. The 1,902 source files reverse-engineered from the source map reveal a carefully designed agent harness system — the model is just one unreliable component, surrounded by a complete outer-loop orchestration:

  1. query loop is the heartbeat: a while(true) loop (query.ts lines 241-1728) driving “sample → tool → permission → recover/continue/stop” cycles
  2. tools are managed interfaces, not bare functions: 43 tools registered through Tool.ts, each declaring readonly, concurrencySafe, sandboxed traits, passing through four governance layers before execution
  3. context is not unlimited: five-layer compression (Micro → TimeBased → APISide → SessionMemory → Full) triggers automatically at ~93% token threshold
  4. memory lives beyond transcripts: CLAUDE.md, memdir, SessionMemory, daily logs collectively maintain cross-session continuity
  5. security is not an add-on layer: permission modes, rule matching, hook interception, OS-level sandboxing are architecturally embedded in the execution path
  6. sub-agents are not “just another agent”: 6 built-in sub-agent types, each with independent toolsets and isolation strategies

Four Runtime Invariants

Reading source by directory gives you a feature list. What actually holds the runtime together are four invariants that must hold simultaneously — understanding these matters more than understanding any single module:

InvariantWhat It MeansMaintained By
Trace topology must not breaktool_use cannot dangle; thinking blocks cannot be cut at wrong boundaries; error recovery cannot expose half-formed statequery.ts recovery graph
Cache prefix must not driftOnce the model has seen content, its fate is frozen in subsequent turns; tool ordering and sub-agent prefixes all converge on this constrainttoolResultStorage.ts / microCompact.ts
Capability surface must not open all at onceTools, MCP, skills are not pre-loaded — they’re exposed in layers, discovered lazily, activated by path/timingTool.ts / ToolSearchTool / loadSkillsDir.ts
Continuity must not depend solely on transcriptStable continuity is distributed across CLAUDE.md, memdir, SessionMemory, daily logs, and other externalized artifactsattachments.ts / memdir/* / SessionMemory/*

The value of these invariants: what’s worth migrating to your own agent design is not a specific function, but which invariant it’s paying for.

Lessons for Agent Builders

Claude Code’s source is not just a product implementation — it’s a reference sample for Agent Harness Engineering. Design principles you can directly adopt:

PrincipleClaude Code’s PracticeSource Evidence
Treat model as unreliableAll tools default to isReadOnly=false, isConcurrencySafe=falsesrc/Tool.ts lines 362–480
Query loop is the heartbeatwhile(true) loop with 7 continue + 1 return exitssrc/query.ts lines 307–1728
Tools are managed interfacesPermission mode → rule matching → hook interception → sandboxsrc/utils/permissions/ + src/hooks/ + src/utils/sandbox/
Context is working memoryFive-layer compression (Micro → TimeBased → APISide → SessionMemory → Full)src/services/compact/
Error path is the main pathprompt-too-long → auto compact → resume; max_tokens → retry with recovery countquery.ts maxOutputTokensRecoveryCount
Verification must be independentBuilt-in verificationAgent — never let the implementer grade themselvessrc/tools/AgentTool/built-in/

Cognitive Science in the Source

Claude Code’s design is not purely engineering — some decisions are deeply influenced by cognitive science (credited to Anthropic’s Character Lead, Amanda Askell):

  • Memory filtering: The system doesn’t mechanically store all conversations; it only retains “surprising” information — the orienting response from cognitive science
  • Avoiding learned helplessness: The system records both successes and failures, not just errors — preventing the AI from becoming overly cautious
  • Progressive trust: New users start with restricted permissions that build up gradually — mirroring trust-building in human social interactions

Visual Entry Points

The visual map at code.claudecn.com provides interactive structure diagrams, tool trait badges, Agent Loop animation, and global search. Each tool card shows readonly / parallel-safe / sandboxed / deferred interface trait labels — more intuitive than docs alone.

Evidence System

Primary Evidence Sources

EvidencePurposeKey Content
package.jsonRelease boundaryVersion 2.1.88, bin entry cli.js, Node ≥ 18
cli.js.mapSource path index1,902 ../src/ user source files, 47 top-level modules
sdk-tools.d.tsTool contractsTool schema, input/output type definitions
vendor/Cross-platform dependenciesripgrep (code search), audio-capture (voice input)

Project Structure Diagram

    flowchart LR
  Package["claudecode/package<br/>v2.1.88"]
  Package --> Pkg["package.json<br/>release boundary"]
  Package --> Readme["README.md<br/>product positioning"]
  Package --> Map["cli.js.map<br/>1,902 source paths"]
  Package --> Schema["sdk-tools.d.ts<br/>tool contracts"]
  Package --> Vendor["vendor/<br/>ripgrep + audio-capture"]
  Map --> Entry["src/entrypoints + src/cli<br/>entry routing"]
  Map --> Tools["src/tools<br/>43 tool entities"]
  Map --> Commands["src/commands<br/>97 command entries"]
  Map --> Services["src/services<br/>service orchestration"]
  Map --> UI["src/components + src/ink<br/>terminal UI"]
  Map --> Memory["src/memdir + SessionMemory<br/>memory and compression"]
  Map --> Ext["src/skills + src/bridge<br/>extension fabric"]
  

Further Reading