Reverse Engineering Claude Code

A bottom-up, building-blocks reverse-engineering guide to the Claude Code codebase (2.1.88 through 2.1.331).

This is the ninth book in the OpenAgents book library and a full-book companion to Coder's Claude Code field-guide chapter. It teaches the entire Claude Code architecture (~1,884 TypeScript/TSX files across 1,910 tracked repository files in the 2.1.88 snapshot, plus an epilogue mapping eight months of drift through 2.1.331) from the ground up. Instead of dumping a reference manual or diving headfirst into an 800 KB main.tsx, the book starts with the smallest zero-dependency atoms—branded IDs, a 34-line reactive store, an 8-line lazy schema wrapper, an 88-line bounded async-generator multiplexer—and builds upward layer by layer until every subsystem snaps into place.

By the final chapter, you will not just know where features live in Claude Code; you will understand why every abstraction was forced into existence by real production constraints: prompt-cache economics, cold-start latency, circular imports, concurrent tool execution, permission boundaries, context-window exhaustion, terminal rendering at 60 FPS, and multi-agent coordination.


Who This Book Is For

  • Engineers building AI agents and coding assistants who want to see how a production-grade agent harness solves tool scheduling, permissions, compaction, hooks, MCP, subagents, and streaming UI.
  • Systems-minded TypeScript developers curious how a massive CLI/TUI application manages module graphs, dead-code elimination, custom React reconciliation in the terminal, and zero-dependency state stores.
  • Codebase archaeologists who want a disciplined, source-verified map of every layer in the Claude Code architecture.

Pedagogical Method: Strict Bottom-Up Assembly

Every chapter follows the same rule: no magic boxes.

  1. No forward dependencies. A chapter only builds on primitives explained in earlier chapters (or explicitly flags a forward reference as a seam to be filled in later).
  2. Every claim cites real code. Every interface, invariant, and edge case points to exact repo-relative file paths and symbols verified directly against the pinned 2.1.88 snapshot (and tagged with evidence labels in Chapter 25 for 2.1.89–2.1.331).
  3. Explain the why before the what. Before reading an implementation, each section frames the production failure mode that forced the design—cache busting, NTLM credential leaks on UNC paths, import cycles, stale usage counts after compaction, or subagents mutating the parent's React tree.

Repository Snapshot Caveats

This book is an external-system reverse-engineering manuscript (status: "written" in `chapters.json`). The proprietary Claude Code TypeScript source tree is not vendored in the OpenAgents repository; source citations such as Tool.ts, query.ts, and state/store.ts refer to the pinned 2.1.88 snapshot. Readers should know five concrete facts up front (covered in full in Chapter 00):

  1. Version: Claude Code 2.1.88 (with Chapter 25 carrying forward to 2.1.331). The snapshot carries no version string (the build injects MACRO.VERSION), so the version comes from matching the code against the official changelog. Everything listed through 2.1.87 is present (for example the X-Claude-Code-Session-Id header and the .jj/.sl exclusions from 2.1.86, and the if field on hooks from 2.1.85). The 2.1.89 entry, which also covers the unlisted 2.1.88, is largely present too: the PermissionDenied hook, the "defer" hook decision, CLAUDE_CODE_NO_FLICKER, showThinkingSummaries, TaskCreated and /buddy. Nothing from 2.1.90 onward is in the snapshot; 2.1.88 is the build published on 2026-03-31.
  2. Source-only snapshot: There is no tracked package.json, tsconfig.json, lockfile, or test runner config in the snapshot. Treat code listings as architectural truth rather than a runnable build recipe.
  3. A few imported files are absent: Some modules imported by tracked source—most notably types/message.ts, query/transitions.ts, services/contextCollapse/, and services/skillSearch/—are not present in the snapshot. Where a chapter touches those boundaries, it documents what can be verified from call sites and marks absent definitions explicitly (cataloged in Appendix B).
  4. Build-time feature gating (bun:bundle): Many modules sit behind feature('...') guards and process.env.USER_TYPE === 'ant' checks for Bun dead-code elimination (DCE). Presence in the snapshot does not mean a feature ships in every build (cataloged in Appendix A).
  5. React Compiler output in .tsx files: Tracked .tsx files include React Compiler memoization transforms (import { c as _c } from "react/compiler-runtime") and inline base64 source maps containing the original pre-compiled TSX.

Directory Layout

text
claude-code/book/
├── README.md                                                     # You are here
├── SUMMARY.md                                                    # Book navigation & SSR table of contents
├── chapters.json                                                 # Machine-checked chapter registry (25 written chapters)
├── examples.json                                                 # Empty Coax example inventory (written survey book)
├── OUTLINE.md                                                    # Complete 9-part, 25-chapter curriculum
├── ARCHITECTURE_MAP.md                                           # Visual layer cake, dependency DAG, cross-cutting themes
├── EDITORIAL_GUIDE.md                                            # Authoring craft, chapter template, verification rules
├── GLOSSARY.md                                                   # Living dictionary of codebase types, terms, and gates
├── prologue-how-to-read-a-1900-file-agent.md                     # Prologue (Ch 00): Codebase anatomy & 5 recurring idioms
├── ch001-atoms-types-stores-and-primitives.md                    # Ch 1: Layer 0 leaf primitives
├── ch002-the-tool-contract.md                                    # Ch 2: Tool.ts, buildTool, GlobTool, tools.ts
├── ch003-command-and-message-contracts.md                        # Ch 3: Command contract, processUserInput, messages.ts
├── ch004-prompt-engineering-and-cache-boundaries.md              # Ch 4: context.ts, system prompt & cache boundaries
├── ch005-talking-to-the-model.md                                 # Ch 5: API client, streaming, retries, usage & cost
├── ch006-executing-tools.md                                      # Ch 6: Tool execution, hooks, batching & spill storage
├── ch007-the-heartbeat-query-loop.md                             # Ch 7: query.ts AsyncGenerator turn state machine
├── ch008-session-envelope-query-engine-and-transcripts.md        # Ch 8: QueryEngine.ts, JSONL transcripts & /rewind
├── ch009-five-layer-compaction-pipeline.md                       # Ch 9: 5-stage compaction pipeline & circuit breaker
├── ch010-memory-systems-claudemd-auto-memory-and-dream.md        # Ch 10: CLAUDE.md, memdir, SessionMemory & autoDream
├── ch011-the-permission-engine.md                                # Ch 11: Permission modes, rules, classifier & modals
├── ch012-shell-execution-sandboxing-and-workspace-tools.md       # Ch 12: Bash/PowerShell, sandbox & workspace tools
├── ch013-the-hook-system.md                                      # Ch 13: Hook events, 4 backends, SSRF guard & snapshots
├── ch014-configuration-settings-and-enterprise-policy.md         # Ch 14: Settings cascade, live watch, MDM & migrations
├── ch015-model-context-protocol-mcp.md                           # Ch 15: MCP transports, OAuth/XAA, elicitation & ToolSearch
├── ch016-skills-plugins-output-styles-and-lsp.md                 # Ch 16: Skills, 3-layer plugins, output styles & LSP
├── ch017-background-task-runtime.md                              # Ch 17: 7 task kinds, disk outputs, cron & sleep wakeups
├── ch018-subagents-context-forking-and-worktrees.md              # Ch 18: Subagent isolation, cache-sharing forks & worktrees
├── ch019-agent-teams-swarms-and-coordinator-mode.md              # Ch 19: Teammate mailboxes, permission bridge & coordinator
├── ch020-inside-ink-terminal-react-renderer.md                   # Ch 20: Custom React renderer, pure-TS Yoga & Screen diffing
├── ch021-the-interactive-repl-screens-keybindings-and-vim.md     # Ch 21: REPL.tsx, QueryGuard, keybinding chords & Vim mode
├── ch022-cold-start-mastery-cli-init-main.md                     # Ch 22: cli.tsx fast-paths, init.ts, main.tsx & shutdown
├── ch023-machine-readable-modes-headless-sdk-and-control-protocols.md # Ch 23: print.ts, StructuredIO NDJSON & MCP server mode
├── ch024-across-the-wire-remote-sessions-bridge-and-direct-connect.md # Ch 24: REPL bridge, CCR transports & upstreamproxy
├── ch025-bringing-it-to-the-present.md                           # Ch 25: Epilogue — 2.1.88 to 2.1.331 changelog & binary diff
├── appendix-a-feature-flags-and-env-knobs.md                     # App A: Complete 90-flag feature() & env-knob inventory
├── appendix-b-missing-snapshot-boundaries.md                     # App B: 187-target boundary audit & call-site reconstructions
└── appendix-c-mini-harness-blueprint.md                          # App C: ~500-line educational toy clone & production crosswalk

Reference Guides, Prologue, and Appendices

GuideFileRole
Master Curriculum & Chapter BlueprintsOUTLINE.md9-part, 25-chapter blueprint
Layered Architecture & Dependency MapARCHITECTURE_MAP.mdVisual 9-layer cake & dependency DAG
Authoring & Verification GuideEDITORIAL_GUIDE.mdCraft, chapter template & verification rules
Codebase GlossaryGLOSSARY.mdTypes, terms, and build gates (v6)
Prologue (Chapter 00)How to Read a 1,900-File AgentCodebase anatomy & 5 recurring idioms
Appendix AFeature Flags & Environment Knobs90 feature() gates & env-knob inventory
Appendix BMissing Snapshot Boundaries187-target audit & call-site reconstructions
Appendix CMini-Harness Blueprint~500-line toy clone & production crosswalk

Chapters

All 25 numbered chapters are complete (written status in `chapters.json`):

ChapterStatus
1. The Atoms: Identity, Reactive Stores, Lazy Schemas, and Async GeneratorsWritten: anthropic/claude-code@2.1.88
2. The Tool Contract: Defining What an Agent Can DoWritten: anthropic/claude-code@2.1.88
3. The Command & Message Contracts: User Input Meets the ModelWritten: anthropic/claude-code@2.1.88
4. Prompt Engineering as Systems Engineering: Context & Cache BoundariesWritten: anthropic/claude-code@2.1.88
5. Talking to the Model: API Client, Streaming, Retries, and AccountingWritten: anthropic/claude-code@2.1.88
6. Executing Tools: Validation, Hooks, Concurrency, and Streaming ExecutionWritten: anthropic/claude-code@2.1.88
7. The Heartbeat: `query.ts` and the Agentic Turn State MachineWritten: anthropic/claude-code@2.1.88
8. The Session Envelope: `QueryEngine.ts` and Transcript PersistenceWritten: anthropic/claude-code@2.1.88
9. The Five-Layer Compaction PipelineWritten: anthropic/claude-code@2.1.88
10. Memory Systems: `CLAUDE.md`, Auto-Memory, Session Memory, and Auto-DreamWritten: anthropic/claude-code@2.1.88
11. The Permission Engine: Modes, Rules, Classifiers, and PersistenceWritten: anthropic/claude-code@2.1.88
12. Shell Execution, Sandboxing, and Core Workspace ToolsWritten: anthropic/claude-code@2.1.88
13. The Hook System: Intercepting Every Lifecycle EventWritten: anthropic/claude-code@2.1.88
14. Configuration, Settings Precedence, and Enterprise PolicyWritten: anthropic/claude-code@2.1.88
15. Model Context Protocol (MCP): Clients, Transports, Auth, and Tool SearchWritten: anthropic/claude-code@2.1.88
16. Skills, Plugins, Output Styles, and LSP IntelligenceWritten: anthropic/claude-code@2.1.88
17. The Background Task Runtime: Unified State, Disk-Backed Output, Notifications, and Proactive SchedulingWritten: anthropic/claude-code@2.1.88
18. Subagents, Context Forking, and Git WorktreesWritten: anthropic/claude-code@2.1.88
19. Agent Teams, Swarms, and Coordinator Mode: Multi-Agent IPC, Permission Bubbling, and Pure OrchestrationWritten: anthropic/claude-code@2.1.88
20. Inside `ink/`: A Custom React Renderer for the TerminalWritten: anthropic/claude-code@2.1.88
21. The Interactive REPL: Screens, Input, Keybindings, and Vim ModeWritten: anthropic/claude-code@2.1.88
22. Cold Start Mastery: From `entrypoints/cli.tsx` Through `init.ts` to `main.tsx`Written: anthropic/claude-code@2.1.88
23. Machine-Readable Modes: Headless CLI, Agent SDK, and Control ProtocolsWritten: anthropic/claude-code@2.1.88
24. Across the Wire: Remote Sessions, Always-On Bridge, and Direct ConnectWritten: anthropic/claude-code@2.1.88
25. Bringing It to the Present: From 2.1.88 to 2.1.331Written: anthropic/claude-code@2.1.88..2.1.331

Cross-Reference to OpenAgents Coax Counterparts

While this book reverse-engineers Claude Code's TypeScript architecture in full, Coder: Coding Agents From Scratch builds OpenAgents' own pure-Coax harness (openagents/core/, coder/tui/, apps/openagents-desktop/) and summarizes what it borrows and leaves in Chapter 25: Claude Code (plus driving the claude CLI directly in Chapter 10: Drive Claude Code). Use the table below to jump from a Claude Code subsystem to its OpenAgents Coax counterpart:

SubsystemReverse Engineering Claude CodeOpenAgents Coax Counterpart (coder/book/)
Agentic turn & query loopCh 7: The Heartbeat (`query.ts`)Ch 1: The simplest loop
Tool contract, validation & batchingCh 2: The Tool Contract, Ch 6: Executing ToolsCh 4: Tools as typed capabilities
Permission engine & OS sandboxingCh 11: The Permission Engine, Ch 12: Shell Execution & SandboxingCh 5: A sandbox and approvals
History condensation & compactionCh 9: The Five-Layer Compaction PipelineCh 7: Condense the history
Subagents, context forking & worktreesCh 18: Subagents, Context Forking, and Git WorktreesCh 14: Forks, subagents and jobs, Ch 41: Worker protocol and sub-agents
Terminal rendering & interactive UICh 20: Inside `ink/`, Ch 21: The Interactive REPLCh 36: A terminal UI, Ch 40: The desktop app
Headless SDK & worker control protocolCh 23: Machine-Readable Modes, Ch 25: 2.1.88 to 2.1.331Ch 10: Drive Claude Code, Ch 41: Worker protocol and sub-agents

Where to Start Reading

  1. Start with **ARCHITECTURE_MAP.md** to get the visual 9-layer map in your head.
  2. Read **Chapter 00: How to Read a 1,900-File Agent** to learn the five recurring idioms that appear in almost every file.
  3. Follow Chapters 1–24 in order—building from leaf atoms (types/ids.ts, state/store.ts) all the way up to entrypoints/cli.tsx, main.tsx, SDK control protocols, and the remote bridge—then finish with Chapter 25 to bridge from 2.1.88 to 2.1.331.
  4. Keep **GLOSSARY.md** and Appendices **A**, **B**, and **C** open as reference guides while exploring the architecture or building your own agent harness (see also Coder: Coding Agents From Scratch).