Reading Series

Claude Code: Source Reading Series

A working engineer's read through every subsystem in the Claude Code source.

18 posts6 layers60 source files covered
src/
├── cli.tsxP1
├── main.tsxP1
├──
├── setup.tsP1
├──
├── query.tsP3
├──
├──
├── commands.tsP4
├── Tool.tsP5
├── tools.tsP5
├──
├── Task.tsP11
├── tasks.tsP11
├── tasksP16
├──
├──
├──
├──
└──

Layer 1: The Runtime Host

Before any agent loop runs, Claude Code boots a runtime host.

01
Layer 1

Boot Sequence: How a CLI Becomes a Runtime Host

Read post →

How cli.tsx, main.tsx, and replLauncher.tsx assemble a governed agent session — from startup signal handlers to first REPL render. Includes the T+0/2/137/150ms startup timeline and side-effect hoisting.

Files covered in this post5 files
src/
├── cli.tsx
├── main.tsx
├── entrypoints/
│   └── init.ts
├── setup.ts
└── replLauncher.tsx
02
Layer 1

Input Pipeline: Three Paths, One Router

Read post →

How processUserInput routes text / !bash / /slash into three separate paths, how speculative execution preemptively forks a turn before the user submits, and how prompt suggestions are generated as a background latency optimization.

Files covered in this post2 files
src/
└── utils/
    ├── processUserInput/
    │   └── processUserInput.ts
    ├── speculation/
    │   └── speculativeExecute.ts
    └── promptSuggestion

Layer 2: The Core Loop

The agent loop is not a while(true). This layer explains the real execution unit.

03
Layer 2

Query Loop: Seven Recovery Conditions

Read post →

How query.ts manages the full turn lifecycle as a recoverable AsyncGenerator with seven named recovery conditions, a five-step preprocessing pipeline, and streaming-aware tool execution.

Files covered in this post7 files
src/
├── query.ts
├── query/
│   ├── config.ts
│   ├── tokenBudget.ts
│   └── stopHooks.ts
└── services/
    └── compact/
        ├── autoCompact.ts
        ├── microCompact.ts
        └── contextCollapse.ts
04
Layer 2

Command System: Six-Source Assembly

Read post →

How six source types — built-in, user skills, plugin-injected, project-scoped, MCP-derived, and dynamic — assemble into a memoized command registry that is re-filtered at call time by availability requirements.

Files covered in this post1 file
src/
└── commands.ts

Layer 3: The Capability Surface

What the agent can do is a governed surface assembled per session.

05
Layer 3

Tool Protocol & Registry

Read post →

The 20+ property Tool interface, buildTool() fail-closed defaults, and how 25+ built-in tools are organized into seven categories and assembled per session.

Files covered in this post2 files
src/
├── Tool.ts
└── tools.ts
06
Layer 3

Tool Execution Service: Scheduling, Streaming, Governance

Read post →

How partitionToolCalls schedules concurrent vs serial batches, how StreamingToolExecutor starts tools before the model finishes streaming, and how the tombstone/discard pattern handles fallback cleanup.

Files covered in this post3 files
src/
└── services/
    └── tools/
        ├── toolOrchestration.ts
        ├── toolExecution.ts
        └── StreamingToolExecutor.ts
07
Layer 3

Permission Engine & Sandbox

Read post →

The 7-step permission decision tree with bypass-immune safety gates, AI Classifier for auto-mode, and how the sandbox layer wraps @anthropic-ai/sandbox-runtime as a separate execution isolation system.

Files covered in this post5 files
src/
├── utils/
│   └── permissions/
│       ├── permissions.ts
│       └── permissionSetup.ts
└── hooks/
    ├── useCanUseTool.tsx
    └── toolPermission/
        └── handlers/
            ├── autoHandler.ts
            └── interactiveHandler.ts
08
Layer 3

MCP Assembly: Seven Sources, Three Surfaces

Read post →

How MCP server definitions from seven config sources are deduplicated by content signature, connected, then expanded into runtime-visible Tool objects, Command objects, and Resource entries.

Files covered in this post3 files
src/
└── services/
    └── mcp/
        ├── config.ts
        ├── client.ts
        └── ChromeMcpClient.ts
09
Layer 3

LSP Integration: Persistent Code Intelligence

Read post →

Multi-server LSP stack with a 5-state lifecycle, LRU-bounded diagnostic registry (10 per file / 30 total), and push-based passive diagnostic collection that avoids flooding the model with repeated errors.

Files covered in this post2 files
src/
└── services/
    └── lsp/
        ├── LSPServerInstance.ts
        └── LSPDiagnosticRegistry.ts

Layer 4: The Agent Services

What makes Claude Code behave like a runtime product, not a stateless API client.

10
Layer 4

Memory System: Five Layers

Read post →

Five-layer memory architecture: memdir CLAUDE.md management, Relevant Memories per-turn selector (5th layer), SessionMemory within-session notes, ExtractMemories episodic capture with 4-type taxonomy, and AutoDream background consolidation with 5-gate access control.

Files covered in this post5 files
src/
├── utils/
│   └── memdir.ts
└── services/
    ├── relevantMemories/
    │   └── relevantMemories.ts
    ├── SessionMemory/
    │   └── SessionMemory.ts
    ├── extractMemories/
    │   └── extractMemories.ts
    └── autoDream/
        └── autoDream.ts
11
Layer 4

Task Runtime: Background Work as First-Class Objects

Read post →

Five task types (shell, local_agent, remote_agent, local_main_session, dream), how LocalMainSessionTask backgrounds the main query loop itself, and the lifecycle/observation/cancellation contract every task satisfies.

Files covered in this post3 files
src/
├── Task.ts
├── tasks.ts
└── tasks/
    └── DreamTask/
        └── DreamTask.ts
12
Layer 4

Subagent Runtime: Fork, Scope, Merge

Read post →

How runAgent materializes a child agent turn with its own ToolUseContext, why setAppState is a no-op in async subagents while setAppStateForTasks always reaches the root store, and how fork mode preserves prompt cache coherence.

Files covered in this post3 files
src/
├── tools/
│   └── AgentTool/
│       ├── runAgent.ts
│       └── AgentTool.tsx
└── tasks/
    └── RemoteAgentTask/
        └── RemoteAgentTask.tsx
13
Layer 4

Swarm & Multi-Agent Coordination

Read post →

How coordinatorMode implements a synthesize-first delegation strategy, three swarm backends (TmuxBackend binary tree / ITermBackend / InProcessBackend), and how disjoint file ownership prevents agent interference.

Files covered in this post4 files
src/
├── coordinator/
│   └── coordinatorMode.ts
└── utils/
    └── swarm/
        └── backends/
            ├── TmuxBackend.ts
            ├── ITermBackend.ts
            └── InProcessBackend.ts

Layer 5: The Platform

The platform layer that makes the whole system observable and operable.

14
Layer 5

UI Runtime: Session Control Plane

Read post →

AppStateStore (75+ fields, DeepImmutable<T>) as a session control plane, useSyncExternalStore selectors for re-render control, and the custom Ink frame pipeline (reconcile → Yoga layout → screen buffer → diff → patch).

Files covered in this post3 files
src/
├── state/
│   ├── AppStateStore.ts
│   └── Store.ts
└── ink/
    └── ink.tsx
15
Layer 5

Analytics & Observability

Read post →

Dual-sink event emission (Datadog + first-party BQ), never-type PII enforcement at compile time, OTEL spans instrumented across the full turn via AsyncLocalStorage, and beta session tracing with system-reminder extraction.

Files covered in this post3 files
src/
├── services/
│   └── analytics/
│       └── index.ts
└── utils/
    └── telemetry/
        ├── otel.ts
        └── betaSessionTracing.ts
17
Layer 5

REPL Runtime: The Composition Root

Read post →

REPL.tsx at 5005 lines as the composition root mounting 30+ hooks, the QueryGuard state machine preventing race conditions, stale-read discipline via store.getState(), and the overlay priority stack.

Files covered in this post1 file
src/
└── screens/
    └── REPL.tsx

Synthesis

Five principles distilled from the full source.

16
Synthesis

Architecture Review: Five Principles

Read post →

The five cross-cutting principles that unify the full series: capability assembly, recoverable turn loops, tool execution as a governed subsystem, state as a control plane, and detached work as first-class runtime.

Files covered in this post5 files
src/
├── cli.tsx
├── main.tsx
├── query.ts
├── tools.ts
├── state/
│   └── AppStateStore.ts
├── tasks
└── tools/
    └── AgentTool
18
Synthesis

Tool Implementations: Defense in Depth

Read post →

BashTool five defense layers (tree-sitter AST, read-only validation, path validation, destructive warnings, sandbox routing), FileReadTool device blocking, AgentTool nesting depth limit, and autoCompact circuit breaker.

Files covered in this post5 files
src/
└── tools/
    ├── BashTool/
    │   ├── BashTool.tsx
    │   ├── bashPermissions.ts
    │   └── readOnlyValidation.ts
    ├── FileEditTool/
    │   └── FileEditTool.ts
    └── FileReadTool/
        └── FileReadTool.ts