Task Breakdown: Claude Code Source Teaching Guide
Chapter Plan (Learning Path Order)
The guide is organized in 4 phases, progressing from high-level overview to deep internals.
Phase 1: Foundation (Chapters 1-4)
Build the reader's mental model of what Claude Code is, how it starts, and the core abstractions.
Chapter 1: Project Overview & Architecture
- ID: CH01
- CN Title: 第1章 - 项目总览与架构设计
- EN Title: Chapter 01 - Project Overview & Architecture
- Priority: P0
- Effort: L
- Dependencies: None
- Core/Brief: CORE
- Content Outline:
- What is Claude Code? (CLI-based AI coding agent)
- Technology stack overview (TypeScript, React, Bun, Ink, Zod)
- Directory structure walkthrough (all 35 modules with one-line descriptions)
- Architecture diagram: Event-driven AsyncGenerator Pipeline
- Data flow overview: User input -> query loop -> API -> tools -> result
- Key configuration: CLAUDE.md, settings.json, feature flags
- Key Files: project root,
src/directory listing - Acceptance Criteria: Reader can explain the overall architecture and locate any module by purpose
Chapter 2: Startup & Bootstrap
- ID: CH02
- CN Title: 第2章 - 启动流程与初始化
- EN Title: Chapter 02 - Startup & Bootstrap
- Priority: P0
- Effort: L
- Dependencies: CH01
- Core/Brief: CORE
- Content Outline:
- Entry point:
src/entrypoints/cli.tsx(fast-path dispatcher) - Initialization:
src/entrypoints/init.ts(two-phase: pre/post trust dialog) - Global state:
src/bootstrap/state.ts(singleton pattern, 80+ getters/setters) - Main function:
src/main.tsx(Commander.js args, mode branching) - Mode tree: Interactive REPL vs Headless vs MCP Server vs Remote vs Print
- ToolUseContext assembly (the DI "everything bag")
- REPL launch:
src/replLauncher.tsx-> React/Ink rendering
- Entry point:
- Key Files:
entrypoints/cli.tsx,entrypoints/init.ts,bootstrap/state.ts,main.tsx,replLauncher.tsx - Acceptance Criteria: Reader can trace the full startup path from CLI invocation to REPL rendering
Chapter 3: Core Type System
- ID: CH03
- CN Title: 第3章 - 核心类型体系
- EN Title: Chapter 03 - Core Type System
- Priority: P0
- Effort: M
- Dependencies: CH01
- Core/Brief: CORE
- Content Outline:
Tool<Input, Output>interface (the universal tool contract)ToolUseContext(40+ field dependency injection object)buildTool()factory function (Builder pattern with TypeScript generics)Commanddiscriminated union (3 variants: Prompt/Local/LocalJSX)TaskandTaskType(7 task types, 5 status states)PermissionMode,PermissionResult,PermissionDecisionReason(9-variant union)AppState(150+ field DeepImmutable state)- Branded types:
SessionId,AgentId - Zod v4 usage for runtime schema validation
- Key Files:
Tool.ts,Task.ts,types/command.ts,types/permissions.ts,state/AppStateStore.ts,types/ids.ts - Acceptance Criteria: Reader understands all core type contracts and how they interconnect
Chapter 4: State Management
- ID: CH04
- CN Title: 第4章 - 状态管理机制
- EN Title: Chapter 04 - State Management
- Priority: P0
- Effort: M
- Dependencies: CH03
- Core/Brief: CORE
- Content Outline:
- Two-tier state architecture: bootstrap (process-level) vs AppState (React-level)
src/state/store.ts: The 35-line Zustand-style store (createStore, getState, setState, subscribe)src/state/AppStateStore.ts: AppState type definition (150+ fields)src/state/AppState.tsx: React Context Provider + useSyncExternalStoresrc/state/selectors.ts: State selectorssrc/state/onChangeAppState.ts: Side effect handlerssrc/bootstrap/state.ts: Global singleton (when to use which state tier)- Immutability enforcement via DeepImmutable<>
- Key Files:
state/store.ts,state/AppStateStore.ts,state/AppState.tsx,bootstrap/state.ts - Acceptance Criteria: Reader can explain the dual-tier state model and implement a new state field
Phase 2: Core Mechanics (Chapters 5-9)
Deep dive into the engine that powers Claude Code's AI agent behavior.
Chapter 5: The Agentic Loop
- ID: CH05
- CN Title: 第5章 - Agent 循环引擎
- EN Title: Chapter 05 - The Agentic Loop
- Priority: P0
- Effort: XL
- Dependencies: CH03, CH04
- Core/Brief: CORE
- Content Outline:
src/query.ts: Thequery()async generator (while(true) loop)- 7 continue paths: auto-compact, max-token recovery, reactive compact, etc.
src/query/config.ts: QueryConfig assemblysrc/query/stopHooks.ts: Post-response hookssrc/query/tokenBudget.ts: Per-turn token limitssrc/services/api/claude.ts: Anthropic API streaming client- Message format: system prompt + conversation history + tool results
- Streaming events: how tool_use blocks trigger execution
- Stop conditions: end_turn, max_tokens, tool_use
- Key Files:
query.ts,query/,services/api/claude.ts - Acceptance Criteria: Reader can trace a complete API call cycle and explain all 7 continue paths
Chapter 6: Tool System Deep Dive
- ID: CH06
- CN Title: 第6章 - 工具系统深度剖析
- EN Title: Chapter 06 - Tool System Deep Dive
- Priority: P0
- Effort: XL
- Dependencies: CH03, CH05
- Core/Brief: CORE
- Content Outline:
- Tool lifecycle: registration -> selection -> permission check -> execution -> result rendering
src/tools.ts: Tool registry assembly (feature-flag conditional)buildTool()deep dive: how generics ensure type safety- Tool anatomy (using FileReadTool as simple example):
- Input schema (Zod)
call()implementationcheckPermissions()renderToolUseMessage()/renderToolResultMessage()prompt.ts(model-visible description)
- BashTool deep dive: the most complex tool
bashPermissions.ts(2600 lines): command parsing, wildcard matching, speculative classifier- Security model: sandbox, sed detection, env protection
- Tool orchestration:
services/tools/toolOrchestration.ts,StreamingToolExecutor
- Key Files:
tools.ts,Tool.ts,tools/FileReadTool/,tools/BashTool/,services/tools/ - Acceptance Criteria: Reader can implement a new custom tool from scratch following the buildTool() pattern
Chapter 7: Permission System
- ID: CH07
- CN Title: 第7章 - 权限与安全模型
- EN Title: Chapter 07 - Permission & Security Model
- Priority: P0
- Effort: L
- Dependencies: CH06
- Core/Brief: CORE
- Content Outline:
- Permission modes: 5 modes defined in
types/permissions.ts - Permission rule evaluation:
utils/permissions/ useCanUseTool.tsx: The central decision point- Rule check -> allow/deny/ask
- Coordinator permission -> Swarm worker -> Speculative classifier (2s race) -> Interactive dialog
PermissionDecisionReason: 9-variant audit trail- Settings-based permissions: allow/deny lists in settings.json
- Hook-based permissions: PreToolUse/PostToolUse hooks
- BashTool-specific: command analysis, auto-approval classifier
- Permission modes: 5 modes defined in
- Key Files:
types/permissions.ts,hooks/useCanUseTool.tsx,utils/permissions/,tools/BashTool/bashPermissions.ts - Acceptance Criteria: Reader can trace a permission decision through all 9 possible reasons
Chapter 8: Command System
- ID: CH08
- CN Title: 第8章 - 命令系统
- EN Title: Chapter 08 - Command System
- Priority: P1
- Effort: M
- Dependencies: CH03
- Core/Brief: CORE
- Content Outline:
- Command types: PromptCommand, LocalCommand, LocalJSXCommand
src/commands.ts: Registry assembly (70+ commands, feature-flag gating)- Command discovery:
findCommand(),meetsAvailabilityRequirement() - User input processing:
utils/processUserInput/processUserInput.ts - Example commands by category:
- Session: /clear, /compact, /resume
- Config: /config, /permissions, /model
- Info: /cost, /context, /doctor, /help
- How to add a new command
- Key Files:
commands.ts,types/command.ts,commands/(selected examples),utils/processUserInput/ - Acceptance Criteria: Reader understands all 3 command types and can add a new slash command
Chapter 9: QueryEngine & SDK Interface
- ID: CH09
- CN Title: 第9章 - QueryEngine 与 SDK 接口
- EN Title: Chapter 09 - QueryEngine & SDK Interface
- Priority: P1
- Effort: L
- Dependencies: CH05
- Core/Brief: CORE
- Content Outline:
QueryEngineclass: session state managementsubmitMessage(): ~900-line async generator- Message preprocessing
- Budget checking
- Query loop invocation
- SDKMessage emission (mapping StreamEvent -> SDKMessage)
- Transcript persistence
- Snip compaction
ask(): One-shot convenience wrapper- SDK types:
src/entrypoints/sdk/(core/control/runtime split) src/entrypoints/agentSdkTypes.ts: Public type surface- Headless mode vs Interactive mode differences
- Key Files:
QueryEngine.ts,entrypoints/sdk/,entrypoints/agentSdkTypes.ts - Acceptance Criteria: Reader can use QueryEngine programmatically and understands the SDK type surface
Phase 3: UI & Interaction Layer (Chapters 10-13)
How Claude Code renders its terminal interface and handles user interaction.
Chapter 10: Custom Ink Framework
- ID: CH10
- CN Title: 第10章 - 自研终端 UI 框架 (Ink)
- EN Title: Chapter 10 - Custom Terminal UI Framework (Ink)
- Priority: P1
- Effort: XL
- Dependencies: CH04
- Core/Brief: CORE
- Content Outline:
- Why a custom Ink fork? (performance, control, production CLI needs)
- React Reconciler:
src/ink/reconciler.ts(custom fiber implementation) - Layout engine:
src/ink/layout/(Yoga WASM, CSS Flexbox for terminal) - Rendering pipeline: virtual DOM -> layout -> ANSI escape codes
- Terminal I/O:
src/ink/termio/(input parsing, key events, mouse) - Focus management, virtual scrolling, text wrapping
- Component primitives: Box, Text, and custom terminal components
- Key Files:
ink/reconciler.ts,ink/layout/,ink/termio/,ink/render.ts - Acceptance Criteria: Reader understands how React components become terminal output
Chapter 11: REPL & Interactive Session
- ID: CH11
- CN Title: 第11章 - REPL 交互式会话
- EN Title: Chapter 11 - REPL & Interactive Session
- Priority: P1
- Effort: L
- Dependencies: CH10, CH05
- Core/Brief: CORE
- Content Outline:
src/screens/REPL.tsx: The main interactive component (~3000 lines)- Message display pipeline: query events -> message batching -> virtual list
- User input: PromptInput component, typeahead, vim mode
- Permission dialogs: how tool permission requests become UI dialogs
- Task panels: background task monitoring
- Teammate views: multi-agent visual coordination
- Transcript search and navigation
- Key Files:
screens/REPL.tsx,components/PromptInput/,components/messages/,components/permissions/ - Acceptance Criteria: Reader can trace user input through the REPL to tool execution and result display
Chapter 12: Component Library
- ID: CH12
- CN Title: 第12章 - 组件库与设计系统
- EN Title: Chapter 12 - Component Library & Design System
- Priority: P2
- Effort: M
- Dependencies: CH10
- Core/Brief: Brief
- Content Outline:
- Component organization: messages/, permissions/, design-system/, agents/, mcp/
- Design system primitives: Dialog, Tabs, FuzzyPicker, ThemedBox
- Message rendering: how different message types get rendered
- Permission dialog patterns: per-tool permission UI
- Theme system
- Key component walkthroughs (2-3 representative examples)
- Key Files:
components/design-system/,components/messages/,components/permissions/ - Acceptance Criteria: Reader knows where to find any component and understands the design patterns
Chapter 13: Hooks Layer
- ID: CH13
- CN Title: 第13章 - Hooks 层:业务逻辑桥梁
- EN Title: Chapter 13 - Hooks Layer: Business Logic Bridge
- Priority: P1
- Effort: M
- Dependencies: CH11
- Core/Brief: CORE
- Content Outline:
- Role of hooks: wiring business logic to the REPL UI
useCanUseTool.tsx: Central permission hook (recap from CH07 with UI perspective)useLogMessages.ts: Message batching from query loop to React stateuseCommandQueue.ts: Slash command processinguseTextInput.ts: Prompt input state managementuseTypeahead.tsx: Command/file completionuseReplBridge.tsx: Remote bridge synctoolPermission/: Coordinator, interactive, swarm permission handlers
- Key Files:
hooks/useCanUseTool.tsx,hooks/useLogMessages.ts,hooks/useCommandQueue.ts,hooks/toolPermission/ - Acceptance Criteria: Reader understands the hooks as the bridge between business logic and UI
Phase 4: Extension & Advanced (Chapters 14-20)
Services, extensions, and advanced features.
Chapter 14: Context & System Prompt
- ID: CH14
- CN Title: 第14章 - 上下文构建与系统提示
- EN Title: Chapter 14 - Context Construction & System Prompt
- Priority: P1
- Effort: M
- Dependencies: CH05
- Core/Brief: CORE
- Content Outline:
src/context.ts: getUserContext(), getSystemContext()- CLAUDE.md loading: hierarchical (project > user > global)
src/constants/prompts.ts: getSystemPrompt() builder- Memory injection:
src/memdir/(per-project memory files) - Context window management:
src/services/compact/- Auto-compact, micro-compact, snip strategies
- When and how conversations get compressed
- Key Files:
context.ts,constants/prompts.ts,memdir/,services/compact/ - Acceptance Criteria: Reader understands how the system prompt is assembled and how context stays within limits
Chapter 15: MCP Integration
- ID: CH15
- CN Title: 第15章 - MCP 协议集成
- EN Title: Chapter 15 - MCP Protocol Integration
- Priority: P1
- Effort: L
- Dependencies: CH06
- Core/Brief: CORE
- Content Outline:
- What is MCP? Model Context Protocol overview
src/services/mcp/: Client management- 4 transport types: stdio, SSE, HTTP, WebSocket
- Server discovery, OAuth authentication
- Tool/resource enumeration from MCP servers
src/tools/MCPTool/: How MCP tools become Claude Code tools- Permission scoping for MCP tools
- Key Files:
services/mcp/,tools/MCPTool/ - Acceptance Criteria: Reader can explain how external MCP servers extend Claude Code's capabilities
Chapter 16: Sub-Agent & Multi-Agent
- ID: CH16
- CN Title: 第16章 - 子 Agent 与多 Agent 协作
- EN Title: Chapter 16 - Sub-Agent & Multi-Agent Coordination
- Priority: P0
- Effort: L
- Dependencies: CH05, CH06
- Core/Brief: CORE
- Content Outline:
- AgentTool:
src/tools/AgentTool/runAgent.ts: Context forking, MCP connection, recursive query() loopcreateSubagentContext(): Which fields are cloned vs shared- Memory snapshots and resume
- Coordinator Mode:
src/coordinator/coordinatorMode.ts - Swarm coordination:
src/utils/swarm/- Teammate spawning backends (iTerm, Tmux, In-Process)
- Task system:
src/tasks/(7 task types)- InProcessTeammateTask: full sub-REPL in same process
- LocalAgentTask, RemoteAgentTask
- Permission proxy: worker -> leader permission bridge
- AgentTool:
- Key Files:
tools/AgentTool/,coordinator/,utils/swarm/,tasks/ - Acceptance Criteria: Reader understands the full multi-agent architecture and permission delegation model
Chapter 17: Skills & Plugin System
- ID: CH17
- CN Title: 第17章 - Skills 与插件系统
- EN Title: Chapter 17 - Skills & Plugin System
- Priority: P1
- Effort: M
- Dependencies: CH08
- Core/Brief: CORE
- Content Outline:
- Skills: Markdown-driven prompt commands
src/skills/loadSkillsDir.ts: File scanning, frontmatter parsingsrc/skills/bundledSkills.ts: Built-in skills- YAML frontmatter: whenToUse, paths, hooks, model, effort
- Skill invocation via SkillTool
- Plugins: Structured extension packages
src/plugins/: Registrationsrc/services/plugins/: Installation, operations- Plugin capabilities: MCP servers, slash commands, hooks
- How skills and plugins merge into the command registry
- Skills: Markdown-driven prompt commands
- Key Files:
skills/,plugins/,services/plugins/,tools/SkillTool/ - Acceptance Criteria: Reader can create a custom skill and understands the plugin architecture
Chapter 18: Services Layer
- ID: CH18
- CN Title: 第18章 - 服务层:API、分析与 LSP
- EN Title: Chapter 18 - Services Layer: API, Analytics & LSP
- Priority: P2
- Effort: M
- Dependencies: CH05
- Core/Brief: Brief
- Content Outline:
services/api/: Anthropic API client details- BetaMessageStreamParams assembly
- Provider support: Bedrock, Vertex AI
- Retry logic, usage tracking, cost calculation
services/analytics/: GrowthBook + Datadog + first-party eventsservices/lsp/: Language Server Protocol integrationservices/oauth/: OAuth2 authentication flowservices/SessionMemory/: Session memory extractionservices/autoDream/: Background consolidation
- Key Files:
services/api/,services/analytics/,services/lsp/,services/oauth/ - Acceptance Criteria: Reader has a map of all service modules and their responsibilities
Chapter 19: Settings, Configuration & Hooks
- ID: CH19
- CN Title: 第19章 - 配置系统与 Hooks 机制
- EN Title: Chapter 19 - Settings, Configuration & Hooks
- Priority: P1
- Effort: M
- Dependencies: CH03
- Core/Brief: CORE
- Content Outline:
- Multi-source settings merge:
- User:
~/.claude/settings.json - Project:
.claude/settings.json - Enterprise: MDM/HKCU
- CLI flags, remote hosted
- User:
src/utils/settings/: Zod schema validation, merge logic- Hooks system:
src/types/hooks.ts: 9 hook event typessrc/schemas/hooks.ts: Zod schemasrc/utils/hooks/: Hook execution engine- PreToolUse, PostToolUse, PostSampling hooks
- Keybindings:
src/keybindings/(custom shortcuts)
- Multi-source settings merge:
- Key Files:
utils/settings/,types/hooks.ts,schemas/hooks.ts,utils/hooks/,keybindings/ - Acceptance Criteria: Reader understands the full configuration hierarchy and can implement a custom hook
Chapter 20: Peripheral Features & Utilities
- ID: CH20
- CN Title: 第20章 - 周边功能与工具集
- EN Title: Chapter 20 - Peripheral Features & Utilities
- Priority: P2
- Effort: M
- Dependencies: CH01
- Core/Brief: Brief
- Content Outline:
- Bridge:
src/bridge/(remote control from mobile/web) - CLI transports:
src/cli/(SSE, WebSocket, structured IO) - Remote sessions:
src/remote/(CCR integration) - Direct Connect:
src/server/(Unix domain socket) - Vim mode:
src/vim/(vi motions, operators, state machine) - Migrations:
src/migrations/(settings data migration) - Utils overview:
src/utils/(564 files, key sub-areas map)- bash/, permissions/, plugins/, settings/, swarm/, model/, telemetry/
- Buddy, voice, outputStyles, native-ts (brief mentions)
- Bridge:
- Key Files:
bridge/,cli/,remote/,server/,vim/,utils/(overview) - Acceptance Criteria: Reader has a reference map for all peripheral features
Parallel Execution Lanes
Phase 1 (Foundation)
- Lane A: CH01 (no deps)
- Lane B: CH02 (after CH01)
- Lane C: CH03 (after CH01) — can run parallel with CH02
- Lane D: CH04 (after CH03)
- Merge risk: Low (chapters are independent files)
Phase 2 (Core Mechanics)
- Lane A: CH05 (after CH03, CH04)
- Lane B: CH08 (after CH03) — can start parallel with CH05
- Lane C: CH06 (after CH03, CH05) -> CH07 (after CH06)
- Lane D: CH09 (after CH05)
- Merge risk: Low
Phase 3 (UI & Interaction)
- Lane A: CH10 (after CH04) -> CH12 (after CH10)
- Lane B: CH11 (after CH10, CH05) -> CH13 (after CH11)
- Merge risk: Low
Phase 4 (Extension & Advanced)
- Lane A: CH14 (after CH05), CH18 (after CH05) — parallel
- Lane B: CH15 (after CH06), CH16 (after CH05, CH06) — sequential
- Lane C: CH17 (after CH08), CH19 (after CH03) — parallel
- Lane D: CH20 (after CH01) — independent
- Merge risk: Low
Effort Summary
| Effort | Count | Chapters |
|---|---|---|
| S | 0 | — |
| M | 8 | CH03, CH04, CH08, CH12, CH13, CH17, CH18, CH19 |
| L | 7 | CH01, CH02, CH07, CH09, CH15, CH16, CH20 |
| XL | 3 | CH05, CH06, CH10 |
Total: 20 chapters (12 CN + 12 EN files = 40 markdown files)