Skip to content
>_ Reverse Engineering Claude Code

Dissecting an Agentic Coding Tool

6 min read 1,424 words

A bottom-up, building-blocks reverse-engineering guide to the Claude Code codebase.

This folder is the working manuscript for a technical book that teaches the entire Claude Code codebase (~1,884 TypeScript/TSX files across 1,910 tracked repository files) 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 this repository; 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 this repository.

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 in this checkout.
  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 written directly against the tracked source tree in this repository. Readers should know five concrete facts about the checkout up front (covered in full in Chapter 0):

  1. Version: Claude Code 2.1.88. The source 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: no /powerup, no CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE, no disableSkillShellExecution, no forceRemoteSettingsRefresh, and /tag and /vim (removed in 2.1.92) are still here. 2.1.88 is the one release missing from the changelog, and it is the build published on 2026-03-31, the day this source was imported.
  2. Source-only snapshot: There is no tracked package.json, tsconfig.json, lockfile, or test runner config in this repo. 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 this checkout. Where a chapter touches those boundaries, it documents what can be verified from call sites and marks absent definitions explicitly.
  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 repo does not mean a feature ships in every build.
  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

book/
├── README.md                                                 # You are here
├── OUTLINE.md                                                # Complete 8-part, 24-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
└── chapters/
    ├── 00-how-to-read-a-1900-file-agent.md                   # Prologue: Codebase anatomy & 5 recurring idioms
    ├── 01-atoms-types-stores-and-primitives.md               # Ch 1: Layer 0 leaf primitives
    ├── 02-the-tool-contract.md                               # Ch 2: Tool.ts, buildTool, GlobTool, tools.ts
    ├── 03-command-and-message-contracts.md                   # Ch 3: Command contract, processUserInput, messages.ts
    ├── 04-prompt-engineering-and-cache-boundaries.md         # Ch 4: context.ts, system prompt & cache boundaries
    ├── 05-talking-to-the-model.md                            # Ch 5: API client, streaming, retries, usage & cost
    ├── 06-executing-tools.md                                 # Ch 6: Tool execution, hooks, batching & spill storage
    ├── 07-the-heartbeat-query-loop.md                        # Ch 7: query.ts AsyncGenerator turn state machine
    ├── 08-session-envelope-query-engine-and-transcripts.md   # Ch 8: QueryEngine.ts, JSONL transcripts & /rewind
    ├── 09-five-layer-compaction-pipeline.md                  # Ch 9: 5-stage compaction pipeline & circuit breaker
    ├── 10-memory-systems-claudemd-auto-memory-and-dream.md   # Ch 10: CLAUDE.md, memdir, SessionMemory & autoDream
    ├── 11-the-permission-engine.md                           # Ch 11: Permission modes, rules, classifier & modals
    ├── 12-shell-execution-sandboxing-and-workspace-tools.md  # Ch 12: Bash/PowerShell, sandbox & workspace tools
    ├── 13-the-hook-system.md                                 # Ch 13: Hook events, 4 backends, SSRF guard & snapshots
    ├── 14-configuration-settings-and-enterprise-policy.md    # Ch 14: Settings cascade, live watch, MDM & migrations
    ├── 15-model-context-protocol-mcp.md                      # Ch 15: MCP transports, OAuth/XAA, elicitation & ToolSearch
    ├── 16-skills-plugins-output-styles-and-lsp.md            # Ch 16: Skills, 3-layer plugins, output styles & LSP
    ├── 17-background-task-runtime.md                         # Ch 17: 7 task kinds, disk outputs, cron & sleep wakeups
    ├── 18-subagents-context-forking-and-worktrees.md         # Ch 18: Subagent isolation, cache-sharing forks & worktrees
    ├── 19-agent-teams-swarms-and-coordinator-mode.md         # Ch 19: Teammate mailboxes, permission bridge & coordinator
    ├── 20-inside-ink-terminal-react-renderer.md              # Ch 20: Custom React renderer, pure-TS Yoga & Screen diffing
    ├── 21-the-interactive-repl-screens-keybindings-and-vim.md # Ch 21: REPL.tsx, QueryGuard, keybinding chords & Vim mode
    ├── 22-cold-start-mastery-cli-init-main.md                # Ch 22: cli.tsx fast-paths, init.ts, main.tsx & shutdown
    ├── 23-machine-readable-modes-headless-sdk-and-control-protocols.md # Ch 23: print.ts, StructuredIO NDJSON & MCP server mode
    └── 24-across-the-wire-remote-sessions-bridge-and-direct-connect.md # Ch 24: REPL bridge, CCR transports & upstreamproxy
└── appendices/
    ├── A-feature-flags-and-env-knobs.md                      # App A: Complete 90-flag feature() & env-knob inventory
    ├── B-missing-snapshot-boundaries.md                      # App B: 187-target boundary audit & call-site reconstructions
    └── C-mini-harness-blueprint.md                           # App C: ~500-line educational toy clone & production crosswalk

Manuscript Progress

Section / Chapter File Status
Master Curriculum & Chapter Blueprints OUTLINE.md Complete
Layered Architecture & Dependency Map ARCHITECTURE_MAP.md Complete
Authoring & Verification Guide EDITORIAL_GUIDE.md Complete
Codebase Glossary GLOSSARY.md Complete (v6)
Ch 00: How to Read a 1,900-File Agent 00-how-to-read-a-1900-file-agent.md Complete
Ch 01: The Atoms — Identity, Stores, Lazy Schemas, Generators & Caches 01-atoms-types-stores-and-primitives.md Complete
Ch 02: The Tool Contract — Defining What an Agent Can Do 02-the-tool-contract.md Complete
Ch 03: The Command & Message Contracts — User Input Meets the Model 03-command-and-message-contracts.md Complete
Ch 04: Prompt Engineering as Systems Engineering — Context & Cache Boundaries 04-prompt-engineering-and-cache-boundaries.md Complete
Ch 05: Talking to the Model — API Client, Streaming, Retries, and Accounting 05-talking-to-the-model.md Complete
Ch 06: Executing Tools — Validation, Hooks, Concurrency, and Streaming Execution 06-executing-tools.md Complete
Ch 07: The Heartbeat — query.ts and the Agentic Turn State Machine 07-the-heartbeat-query-loop.md Complete
Ch 08: The Session Envelope — QueryEngine.ts and Transcript Persistence 08-session-envelope-query-engine-and-transcripts.md Complete
Ch 09: The Five-Layer Compaction Pipeline 09-five-layer-compaction-pipeline.md Complete
Ch 10: Memory Systems — CLAUDE.md, Auto-Memory, Session Memory, and Auto-Dream 10-memory-systems-claudemd-auto-memory-and-dream.md Complete
Ch 11: The Permission Engine — Modes, Rules, Classifiers, and Persistence 11-the-permission-engine.md Complete
Ch 12: Shell Execution, Sandboxing, and Core Workspace Tools 12-shell-execution-sandboxing-and-workspace-tools.md Complete
Ch 13: The Hook System — Intercepting Every Lifecycle Event 13-the-hook-system.md Complete
Ch 14: Configuration, Settings Precedence, and Enterprise Policy 14-configuration-settings-and-enterprise-policy.md Complete
Ch 15: Model Context Protocol (MCP) — Clients, Transports, Auth, and Tool Search 15-model-context-protocol-mcp.md Complete
Ch 16: Skills, Plugins, Output Styles, and LSP Intelligence 16-skills-plugins-output-styles-and-lsp.md Complete
Ch 17: The Background Task Runtime 17-background-task-runtime.md Complete
Ch 18: Subagents, Context Forking, and Git Worktrees 18-subagents-context-forking-and-worktrees.md Complete
Ch 19: Agent Teams, Swarms, and Coordinator Mode 19-agent-teams-swarms-and-coordinator-mode.md Complete
Ch 20: Inside ink/ — A Custom React Renderer for the Terminal 20-inside-ink-terminal-react-renderer.md Complete
Ch 21: The Interactive REPL — Screens, Input, Keybindings, and Vim Mode 21-the-interactive-repl-screens-keybindings-and-vim.md Complete
Ch 22: Cold Start Mastery — From entrypoints/cli.tsx Through init.ts to main.tsx 22-cold-start-mastery-cli-init-main.md Complete
Ch 23: Machine-Readable Modes — Headless CLI, Agent SDK, and Control Protocols 23-machine-readable-modes-headless-sdk-and-control-protocols.md Complete
Ch 24: Across the Wire — Remote Sessions, Always-On Bridge, and Direct Connect 24-across-the-wire-remote-sessions-bridge-and-direct-connect.md Complete
Ch 25: Bringing It to the Present — From 2.1.88 to 2.1.331 25-bringing-it-to-the-present.md Complete
Appendix A: Complete Inventory of Build-Time feature() Flags & Environment Knobs A-feature-flags-and-env-knobs.md Complete
Appendix B: Reconstructing the Missing Snapshot Boundaries from Call Sites B-missing-snapshot-boundaries.md Complete
Appendix C: Mini-Harness Blueprint (500-Line Working Toy Clone) C-mini-harness-blueprint.md Complete

Where to Start Reading

  1. Start with ARCHITECTURE_MAP.md to get the visual 9-layer map in your head.
  2. Read Chapter 0: How to Read a 1,900-File Agent to learn the five recurring idioms that appear in almost every file.
  3. Follow Chapters 01–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.
  4. Keep GLOSSARY.md and Appendices A, B, and C open as reference guides while exploring the repo or building your own agent harness.

Manuscript README.md from AtlantisPleb/cc at 5aa286a, synced Nov 24, 2026.

esc