# Code Map: The Complete Topology of 1,884 Files

This chapter draws a panoramic map of the entire codebase—from the macro distribution of 301 directories and 36 top-level modules to the responsibility boundaries of each key subsystem—helping you find your bearings across 1,884 files.

---

## Prologue: Why You Need a Map

You just moved to an unfamiliar city. What do you do before heading out? You open a map to figure out where downtown is, where the residential areas are, and how the hospitals and schools are distributed. You don't need to memorize every street—you need **a sense of direction**.

The Claude Code codebase is such a city. 1,884 TypeScript files, 301 directories, and 36 top-level modules. If you dive straight into reading the code, you'll get lost within three days. But if you spend five minutes with this map first, you'll be able to mentally locate "which district it lives in" for every topic in the chapters that follow.

> **🔑 OS Analogy:** It's like the Settings menu on your phone—Communication, Display, Storage, and Security each have their own sections, and you know where to look for what. This chapter is the "Settings menu tour" of the Claude Code codebase, telling you what functionality lives in each area.

> **🌍 Industry Context: Where does Claude Code's code scale sit?**
>
> AI coding assistants are a fast-growing category, but product sizes vary wildly. Placing Claude Code on the industry coordinate system:
>
> | Product | Language | Scale Estimate | Open Source Status | Positioning |
> |------|------|---------|---------|------|
> | **Claude Code 2.1.88** | TypeScript | ~1,900 files / ~512K lines | Closed-source (source map circulated publicly, allowing source recovery) | Full-featured terminal AI Agent |
> | **CodeX (OpenAI) v0.118.0** | Rust rewrite (95.6%) + TypeScript | Significantly smaller than CC | Open source (Apache 2.0) | Parallel Agent workflow terminal |
> | **OpenCode** | Go + Zig | Medium scale | Open source / 110K+ stars | TUI CLI, 75+ model providers |
> | **Aider** | Python | ~30K lines (author's statement) | Open source (Apache 2.0) | Terminal AI pair programming |
> | **GLM (Z.ai)** | Python + CUDA | Ultra-large scale (744B parameters) | Weights open source | Z Code on-prem coding base |
> | **Cursor** | TypeScript (VS Code fork) | Inherits VS Code's millions of lines + own AI layer | Closed-source | IDE-level AI editor |
> | **Continue.dev** | TypeScript | Medium-scale IDE extension | Open source | VS Code/JetBrains plugin |
>
> **Key observation**: Claude Code's ~512K lines of code make it the **largest by volume** in the "terminal AI assistant" segment—about 17× larger than Aider, and also bigger than CodeX's Rust rewrite or OpenCode's Go+Zig implementation. This isn't due to code bloat, but because Claude Code's functional boundary far exceeds its peers: it's not just a thin shell that "calls APIs + executes commands," but comes with a complete subsystem stack including permissions, sandboxing, MCP protocol, multi-Agent orchestration, terminal React UI, and plugin framework. It's more like a **miniature operating system** than a script tool.
>
> Of course, compared to an IDE-level product like Cursor, Claude Code is still much smaller—Cursor inherits VS Code's massive base. The two have fundamentally different design philosophies: Cursor goes "heavy IDE, light terminal," while Claude Code goes "zero IDE dependency, heavy terminal."

---

## 1. Bird's-Eye View: Top-Level Directory Structure

Open the `src/` directory and you'll see 36 subdirectories and 18 top-level files. Before getting into details, divide them into five zones by **role**:

```
src/
├── 【Heart Zone】System Core Engine
│   ├── main.tsx            ← Entry point, the "city gate"
│   ├── QueryEngine.ts      ← Session dispatch center (manages state flow of each conversation round)
│   ├── query.ts            ← Main loop, the "heart" (AI thinks → executes → feedback loop)
│   ├── Tool.ts             ← Tool base class (universal template for all tools)
│   ├── Task.ts             ← Task definition (records each task's state and progress)
│   ├── context.ts          ← Context construction (collects background info the AI needs)
│   └── setup.ts            ← Setup wizard
│
├── 【Limbs Zone】Execution Capabilities
│   ├── tools/          (184 files) ← 40 built-in tool directories (actions the AI can call, e.g. read file, execute command)
│   ├── commands/       (189 files) ← 101 slash commands (user inputs like /help, /clear)
│   ├── services/       (130 files) ← Background services (quietly running functions: API communication, MCP connection, data compression)
│   └── tasks/          (12 files)  ← Task executor (manages sub-Agent creation and monitoring)
│
├── 【Skin Zone】User Interface
│   ├── components/     (389 files) ← UI component library (buttons, input boxes, message bubbles, etc.)
│   ├── ink/            (96 files)  ← Terminal rendering engine (turns program output into beautiful terminal UI)
│   ├── screens/        (3 files)   ← Top-level pages (main screen, settings, etc.)
│   └── keybindings/    (14 files)  ← Keybindings (e.g. Ctrl+C to exit, ↑↓ to scroll history)
│
├── 【Skeleton Zone】Infrastructure
│   ├── utils/          (564 files) ← Utility function library (general-purpose helpers used everywhere, e.g. path handling, format conversion)
│   ├── hooks/          (104 files) ← Lifecycle hooks (custom logic triggered at specific moments)
│   ├── constants/      (21 files)  ← Constant definitions (unchanging configuration values)
│   ├── types/          (11 files)  ← Type definitions ("templates" for data structures)
│   ├── schemas/        (1 file)   ← JSON Schema (validation rules for data formats)
│   └── state/          (6 files)   ← Global state management (records the program's current running state)
│
└── 【Special Zone】Specialized Features
    ├── bridge/         (31 files)  ← Remote control, the "SSH service"
    ├── buddy/          (6 files)   ← Little animal companion, the "desktop pet"
    ├── voice/          (1 file)   ← Voice mode, "voice recognition driven"
    ├── vim/            (5 files)   ← Vim integration
    ├── memdir/         (8 files)   ← Memory system, "persistent storage"
    ├── plugins/        (2 files)   ← Plugin system entry
    ├── skills/         (20 files)  ← Skill system
    ├── coordinator/    (4 files)   ← Multi-Agent orchestration, "cluster scheduler"
    └── moreright/      (?)        ← Unpublished feature
```

### Numbers at a Glance

| Metric | Value |
|------|------|
| Total TypeScript files | 1,884 |
| Total directories | 301 |
| Top-level modules | 36 directories + 18 files |
| Largest directory | `utils/` (564 files) |
| Tool varieties | 40 built-in tool directories |
| Slash commands | 101 |
| Background service modules | 30+ |

---

## 2. The Five Zones in Detail

### 2.1 Heart Zone: 7 Files Supporting the Entire System

If you want to understand Claude Code, you only need to read 7 files. They're like a city's water supply, power grid, and transportation system—remove any one, and the whole system collapses.

| File | Lines of Code | Role | Plain English |
|------|---------|------|---------|
| `main.tsx` | ~4,700 lines | Entry point and mode routing | The program's "front door"—decides which path you take after entering |
| `QueryEngine.ts` | ~1,300 lines | Session state management | The "notebook"—remembers how far the current conversation has progressed |
| `query.ts` | ~1,700 lines | Main loop | The "heart"—AI thinks → executes → feedback loop |
| `Tool.ts` | ~800 lines | Tool base class interface | The "tool registry"—unified specification for all 40 built-in tool directories |
| `Task.ts` | ~200 lines | Task definition | The "work order"—records each task's state and result |
| `context.ts` | ~300 lines | Context construction | The "background info packet"—collects information the AI needs to know |
| `commands.ts` | ~100 lines | Command registry | The "menu"—lists all slash commands the user can type |

**Key insight**: Although `main.tsx` itself has 4,700 lines (because it carries a lot of CLI configuration), the real "core decision logic"—`query.ts` (main loop) + `QueryEngine.ts` (session state) + `Tool.ts` (tool interface)—adds up to roughly 3,800 lines. The remaining 1,877 files are all subsystems and tools surrounding this kernel. It's like a restaurant: what truly determines food quality is the head chef and a few core recipes (a few thousand lines of core code), but keeping the restaurant running also requires waiters, cashiers, cleaners, and procurement staff (tens of thousands of lines of supporting code).

**Core interfaces at a glance**: `Tool.ts` defines the interface shared by all 40 built-in tool directories—like a "tool registration form" that every tool must fill out, specifying what information each tool must provide (name, input format, how to execute, permission checks). You don't need to understand every line of the code below; just read the Chinese comments to get a feel for "what a tool looks like":

```typescript
// All 40 built-in tool directories implement this type—the "registration form" for each tool
export type Tool<Input, Output, P> = {
  readonly name: string           // Tool name, e.g. "Bash", "FileRead"
  readonly inputSchema: Input     // Zod schema (a "form template" that specifies the type and format of each field), strictly constraining input format
  call(                           // Core: execute the tool
    args: z.infer<Input>,         //   ← Parameters provided by the AI
    context: ToolUseContext,      //   ← Runtime context (state, message history)
    canUseTool: CanUseToolFn,     //   ← Permission check callback
    parentMessage: AssistantMessage
  ): Promise<ToolResult<Output>>
  checkPermissions(               // Permission check: decides Allow/Deny/Ask before execution
    input: z.infer<Input>,
    context: ToolUseContext
  ): Promise<PermissionResult>
  isReadOnly(input): boolean      // Whether read-only (determines concurrency strategy)
  isConcurrencySafe(input): boolean // Whether parallel execution is safe
  isEnabled(): boolean            // Whether enabled under current configuration
  description(input, options): Promise<string>  // Tool description sent to the AI
  // ... plus ~20 more methods/properties (permission matching, UI rendering, search hints, etc.)
}
```

This interface defines **all interaction points** between a tool and the rest of the system—permissions, concurrency, description, lazy loading, UI rendering. If you want to understand "what it means that all 40 built-in tool directories implement the same interface," this code is the answer.

### 2.2 Limbs Zone: The System's Execution Capabilities

**tools/ (40 built-in tool directories, 184 files)**

One directory per tool, directory name equals tool name. These are Claude Code's "hands"—the AI interacts with the external world through these tools:

```
tools/
├── File Operations Trio
│   ├── FileReadTool/     ← Read file
│   ├── FileEditTool/     ← Edit file (diff replacement)
│   └── FileWriteTool/    ← Write file (full overwrite)
│
├── Search Duo
│   ├── GlobTool/         ← Search by filename pattern
│   └── GrepTool/         ← Search by content
│
├── Execution Engine
│   ├── BashTool/         ← Shell command execution
│   └── PowerShellTool/   ← Windows PowerShell
│
├── Agent Family
│   ├── AgentTool/        ← Create sub-Agent
│   ├── SendMessageTool/  ← Send message to existing Agent
│   └── TeamCreateTool/   ← Create Teammate (Swarm mode)
│
├── Task Management Quintet
│   ├── TaskCreateTool/
│   ├── TaskGetTool/
│   ├── TaskListTool/
│   ├── TaskUpdateTool/
│   └── TaskStopTool/
│
├── Extension Tools
│   ├── WebFetchTool/     ← Web page scraping
│   ├── WebSearchTool/    ← Web search
│   ├── MCPTool/          ← Call MCP server tools
│   ├── SkillTool/        ← Call Skill
│   └── ToolSearchTool/   ← Search available tools (meta-tool)
│
└── Special Tools
    ├── NotebookEditTool/ ← Jupyter notebook editing
    ├── AskUserQuestionTool/ ← Ask the user a question
    ├── SleepTool/        ← Wait (for scheduled tasks)
    └── SyntheticOutputTool/ ← Synthetic output (internal use)
```

**commands/ (101 commands, 189 files)**

Slash commands are actions triggered directly by the user (the AI cannot call them). The 101 commands cover everything from `/help` to `/commit` to `/vim`.

**services/ (30+ modules, 130 files)**

Background services are the "invisible workers"—neither users nor AI call them directly, but they are always running:

| Service | What it does |
|------|--------|
| `api/` | Anthropic API call wrapper |
| `mcp/` | MCP server connection management |
| `compact/` | Context compression (6-layer mechanism) |
| `SessionMemory/` | Background AI auto-note-taking |
| `PromptSuggestion/` | Predict the user's next message |
| `analytics/` | Data analytics event collection |
| `oauth/` | OAuth authentication flow |
| `plugins/` | Plugin loading and management |
| `tools/` | Tool dispatch and execution engine |
| `lsp/` | LSP server management |
| `voice.ts` | Voice mode backend |

### 2.3 Skin Zone: A React App in the Terminal

Claude Code's interface isn't cobbled together with `console.log`s—it's a full-fledged **React app** rendered in the terminal.

- **components/** (389 files): One of the largest subdirectories in the entire codebase. React components cover message bubbles, code highlighting, permission dialogs, progress bars, diff previews... The sheer number shows how heavily Claude Code invests in UI experience.
- **ink/** (96 files): Terminal rendering engine based on the Ink framework—translates React virtual DOM into ANSI escape sequences.
- **screens/** (3 files): Only 3 top-level "pages"—REPL (main screen), Setup (setup wizard), and Login (authentication).

**389 UI components, but only 3 pages**—this shows Claude Code's interaction complexity is concentrated within state management inside a single page, not navigation between pages.

### 2.4 Skeleton Zone: Invisible Infrastructure

**utils/ (564 files) — 30% of the codebase**

`utils/` is Claude Code's most massive directory, claiming 30% of the files. It's not a "junk drawer"—it has a clear internal subdirectory structure:

| Subdirectory | File Count | Responsibility |
|--------|--------|------|
| `permissions/` | Many | Permission rule parsing and evaluation |
| `settings/` | Many | Five-layer settings system |
| `sandbox/` | Many | Sandbox adapter |
| `hooks/` | Many | Hook execution engine |
| `telemetry/` | Many | Telemetry and observability |
| `mcp/` | Many | MCP protocol utility functions |
| `git/` | Many | Git operation wrapper |
| `github/` | Many | GitHub API integration |
| `model/` | Many | Model capabilities and selection |
| `messages/` | Many | Message format handling |
| `bash/` | Many | Shell command parsing |
| `skills/` | Many | Skill discovery and loading |
| `swarm/` | Many | Multi-Agent collaboration |
| `memory/` | Many | Memory system |
| `plugins/` | Many | Plugin management |
| `task/` | Many | Task utility functions |
| `background/` | Many | Background task management |

**The true complexity of the system hides here.** `query.ts` (the main loop) is only ~1,700 lines, but it calls into `utils/permissions/`, `utils/hooks/`, and `utils/sandbox/`, each of which has dozens of files. "Kernel + complex subsystems" is Claude Code's fundamental architectural pattern.

**Key dependency relationships inside utils/**:

```
permissions/ ←──── hooks/ (Hooks can return permission decisions)
    │
    ├──→ sandbox/ (Permission system decides whether sandboxing is needed)
    │
    └──→ settings/ (Reads permission rule configuration)
              ↑
          mcp/ (MCP server configuration)
          model/ (Model capability configuration)

git/ ←── github/ (GitHub API depends on git operations)

messages/ ←── skills/ (Skills generate messages)
              memory/ (Memory system reads/writes message history)

bash/ ←── sandbox/ (Sandbox needs to parse command structure)
```

These subdirectories are not isolated "junk drawers"—they form an internally structured cluster of subsystems, with the core dependency direction being: **config (settings) → permissions (permissions) → sandbox (sandbox) → execution (bash)**.

> 📚 **Course Connection**: Claude Code's five-zone division (Heart/Limbs/Skin/Skeleton/Special) is a classic practice of **Layered Architecture** and **Separation of Concerns** taught in software engineering courses. The Heart Zone (core engine) corresponds to the business logic layer, the Limbs Zone (tools/commands) to the application service layer, the Skin Zone (UI components) to the presentation layer, and the Skeleton Zone (utils/hooks/types) to the infrastructure layer—each layer only depends downward, never callbacks upward. This traces back to the layered design philosophy first proposed by Dijkstra in the THE operating system. If you've done MVC or Clean Architecture splits in course projects, Claude Code's five zones are the engineering realization of the same idea at the scale of 1,884 files.

### 2.5 Special Zone: Specialized Feature Modules

| Module | File Count | Status | Description |
|------|--------|------|------|
| `bridge/` | 31 | Production | Remote control system (bridge from Web/IDE to terminal CLI) |

> 💡 **Plain English**: Bridge is like a **remote-controlled drone**—the remote controller = your browser or IDE (local side), the drone = the remotely running Claude Code instance, and the signal link = the Bridge protocol. You click a button on the web page, and the distant Claude does it.
| `coordinator/` | 4 | Production | Multi-Worker orchestration (370-line system prompt) |
| `buddy/` | 6 | Experimental | Terminal animal companion (18 species, Gacha rarity) |
| `voice/` | 1 | Experimental | Voice input (Deepgram STT, 20 languages) |
| `vim/` | 5 | Production | Vim mode integration |
| `memdir/` | 8 | Production | Persistent memory system |
| `skills/` | 20 | Production | Skill definition and discovery |
| `plugins/` | 2 | Production | Plugin system entry |
| `assistant/` | ? | Internal | KAIROS assistant mode (ant-only) |
| `moreright/` | ? | Unknown | Unpublished feature |

---

## 3. Data Flow Perspective: Three Highways

From a data-flow perspective, the entire system has three main "highways":

### 3.1 Main Highway: User Input → AI Response

```
User presses Enter
  →【string: user input text】
  → main.tsx routing (determines whether it's a slash command or chat message)
  →【UserMessage object】
  → QueryEngine.submitMessage()
  →【SystemMessage[]: system prompt + CLAUDE.md + git status】
  → context.ts assembles system prompt
  →【Message[]: complete message array (system + history + user)】
  → query.ts / queryLoop() main loop
    →【API Request: messages + tools + model config】
    → services/api/ calls Anthropic API
    →【AsyncIterable<StreamEvent>: streaming response events】
    → Streamed response
      →【ToolUseBlock: {name, input}】
      → tools/ executes tool call (after permission check)
      →【ToolResultBlockParam: {tool_use_id, content}】
      → Tool result returns
      → Calls API again (while(true) loop)
    →【TextBlock: AI final text response】
    → Final response
    → components/ renders to terminal
```

This is the most critical path—almost every mechanism you'll see in subsequent chapters (permissions, compression, speculative execution, hooks) is a "toll booth" or "gas station" along this road. The core data type passed at each step is annotated in [brackets].

### 3.2 Background Highway: Silent Work After AI Response

```
AI completes response
  → services/SessionMemory/ extracts conversation summary
  → services/PromptSuggestion/ predicts next message
  → utils/fileHistory.ts creates file snapshot
  → [Optional] Speculative execution: starts next AI round with predicted message
```

This highway runs entirely in the background, invisible to the user. But it has a huge impact on the speed of the next interaction.

### 3.3 Extension Highway: External Capability Integration

```
System startup
  → services/mcp/ connects MCP servers
    → mcp__xxx__yyy tools appear in tools/
  → utils/plugins/ loads plugins
    → New Skills appear in skills/
    → New Hooks register in hooks/
  → bridge/ establishes remote connection
    → External IDE/Web can send messages
```

This highway transforms Claude Code from a "standalone tool" into a **platform**.

---

## 4. File Naming Conventions

Claude Code follows a consistent set of file naming conventions. Master them and you can guess a file's content from its name:

| Pattern | Meaning | Example |
|------|------|------|
| `XxxTool/` | A complete AI tool | `BashTool/`, `FileReadTool/` |
| `xxx.ts` (top-level) | Core abstraction definition | `Tool.ts`, `Task.ts`, `query.ts` |
| `xxxs.ts` (plural) | Registry/aggregation | `tools.ts` (registration of all tools), `tasks.ts` |
| `useXxx.ts/tsx` | React Hook | `useVoice.ts`, `useBuddyNotification.tsx` |
| `xxxEnabled.ts` | Feature gate check | `voiceModeEnabled.ts`, `bridgeEnabled.ts` |
| `xxxTypes.ts` | Type definitions | `sandboxTypes.ts`, `memoryTypes.ts` |
| `xxxMode.ts` | Mode configuration | `coordinatorMode.ts` |

---

## 5. Dependency Heatmap: Who Depends on Whom the Most

If you visualize file import relationships as a heatmap, the "hottest" nodes (most depended-upon files) are:

| File/Directory | Dependency Level | Reason |
|-----------|-----------|------|
| `Tool.ts` | Extremely high | All 40 built-in tool directories implement this interface |
| `state/AppStateStore.ts` | Extremely high | Global state, read/written by almost every module |
| `utils/permissions/` | High | Permission checks run through every tool call |
| `types/` | High | Type definitions referenced by all modules |
| `constants/` | High | Constants widely referenced |
| `query.ts` | Medium | Main loop, but only directly called by QueryEngine |
| `main.tsx` | Low | Entry point, only called by system startup—but it **depends on** almost every module |

**Counter-intuitive finding**: `main.tsx` is the system entry point, but in the dependency graph it's a **sink** (depends on many, depended on by few), while `Tool.ts` is the **radiation center** (depends on few, depended on by many). This shows the tool interface is a more "fundamental" abstraction than the entry file.

> 📚 **Course Connection**: This dependency heatmap directly corresponds to **Coupling & Cohesion** analysis in software engineering courses. `Tool.ts`, as the radiation center depended on by 40 built-in tool directory modules yet having minimal dependencies itself, is a textbook example of "high cohesion, low coupling" interface design—it defines a stable abstract contract, and downstream modules depend only on the interface, not on each other. `main.tsx`, as the sink that depends on almost every module, is a live engineering example of the reverse of the **Dependency Inversion Principle** (DIP): the entry layer directly depends on concrete implementations, so any submodule change may ripple back to the entry. If you've studied Robert C. Martin's SOLID principles or drawn UML package dependency arrows, this is the real-world instance.

---

## 6. Scale Comparison with Other Projects

To help you build intuition, here's how Claude Code compares to some well-known projects:

| Project | File Count | Language | Analogy |
|------|--------|------|------|
| Claude Code 2.1.88 | ~1,900 | TypeScript | The protagonist of this book |
| VS Code (core) | ~3,000 | TypeScript | Another "complex system in a terminal/editor" |
| React (core) | ~400 | JavaScript | Just a UI framework, much smaller in scale |
| Express.js | ~160 | JavaScript | Simple web framework |
| Linux Kernel | ~70,000 | C | Claude Code's "spiritual mentor" |

Claude Code's 1,900 files place it in the **large system** tier among frontend/Node.js projects—far beyond typical applications, but not yet at the hyper-scale of VS Code. Its complexity lies not in file count, but in **interaction density between subsystems**.

---

## 7. Chapter Summary

- **7 core files** form the "kernel"; the remaining 1,877 files are "subsystems and drivers"
- **Five zones**: Heart (core engine), Limbs (tools and commands), Skin (UI), Skeleton (infrastructure), Special (specialized features)
- **Three data flows**: Main highway (user → AI), background highway (silent work), extension highway (external integration)
- **utils/ takes 30%**—behind the deceptively simple kernel lies a vast subsystem implementation
- The codebase's **radiation center** is `Tool.ts` (tool interface), not `main.tsx` (entry point)

**💡 How to verify these numbers yourself**: If you have the source code at hand, you can verify all data in this chapter with the following commands:

```bash
# Verify total file count
find src/ -name '*.ts' -o -name '*.tsx' | wc -l

# Verify main.tsx line count
wc -l src/main.tsx

# Verify utils/ file count
find src/utils/ -name '*.ts' -o -name '*.tsx' | wc -l

# Verify tool count (one directory per tool)
ls -d src/tools/*Tool/ | wc -l

# View Tool.ts core interface
grep -n 'export type Tool<' src/Tool.ts
```

Cultivate the habit of "verifying architecture documents with your own hands"—it's more valuable than memorizing specific numbers.

With this map in hand, we can start drilling down layer by layer. In the next chapter, we'll trace a complete startup sequence—from the moment you type `claude` in the terminal.

---

## 8. Code Landing Spots

Below are the precise source locations for the key concepts in this chapter, for readers who want to read along:

| Concept | File | Line | Description |
|------|------|------|------|
| System entry | `src/main.tsx` | :1-20 | Pre-import side effects + module loading starting point, 4,684 lines |
| Tool base class interface | `src/Tool.ts` | :158-248 | `ToolUseContext` type definition—the context structure shared by all 40 built-in tool directories |
| Tool registry | `src/tools.ts` | :193 | `getAllBaseTools()` function—complete list of all tools and conditional loading logic |
| Global state center | `src/state/AppStateStore.ts` | Full text (569 lines) | Application global state definition, referenced by almost all modules |
| Task type definition | `src/Task.ts` | :6-13 | Seven `TaskType` enums—from `local_bash` to `dream` |
| Context construction | `src/context.ts` | :116-189 | `getSystemContext()` + `getUserContext()` two memoized functions |

---

## 9. Critical Analysis

- **Is utils/ taking 30% a design problem or inevitable?** 564 files crammed under one `utils/`—while there are internal subdirectories, it's essentially a catch-all for "can't categorize it elsewhere." Subdirectories like `permissions/`, `sandbox/`, and `hooks/` fully qualify as top-level modules, but staying under `utils/` means deeper import paths and blurrier module boundaries. This is a common degeneration pattern in large TypeScript projects.
- **Feature gate-induced code bloat.** `tools.ts` heavily uses `feature('...')` + `require()` for conditional imports (e.g. `SleepTool`, `MonitorTool`, `WorkflowTool`). This pattern makes the same file behave very differently under different build configurations, increasing comprehension cost. The upside is dead code elimination can reduce artifact size; the downside is developers can't statically infer from source code "which tools actually exist at runtime."
- **The 7 heart zone files carry too many responsibilities.** `main.tsx` has 4,684 lines, simultaneously handling CLI argument parsing, mode routing, Commander configuration, and subcommand definitions. This suggests the system entry point may need further splitting—in the ideal case, the entry file should only do "routing," delegating concrete logic to submodules.
- **Missing explicit module boundaries.** There are no `package.json` workspaces or barrel exports to define a module's public API—any file can import any other file. This is common in rapid iteration, but means dependency relationships can become unmanageable over time (the `Tool.ts` comments even mention "break import cycles").
- **ant-only code scattered throughout public code.** `process.env.USER_TYPE === 'ant'` checks appear in multiple files like `tools.ts` and `prompts.ts`, indicating the internal and public versions share the same codebase. This "single-source fork" model simplifies maintenance, but leaks the existence of internal features (e.g. `ConfigTool`, `TungstenTool`, `REPLTool`).

---

### Multi-Dimensional Navigation Tips

This chapter's five-zone distribution is organized by **directory structure**—the most natural navigation dimension, but not the only useful one. When you need to locate a piece of code in subsequent chapters, you can also cross-reference with the following dimensions:

- **Entity dimension**: Cut in by the four core abstractions—`Tool` / `Task` / `Command` / `Resource`—"I want to find all code related to tool registration" means following the Tool entity to `Tool.ts` → `tools.ts` → `src/tools/*/`
- **Component dimension**: Cut in by the three-layer UI architecture of `screens` / `components` / `hooks`—"I want to find the permission dialog implementation" means going from screens (REPL.tsx) → components (PermissionDialog) → hooks (usePermission) layer by layer
- **Data flow dimension**: Cut in by the three data-flow highways in Section 6 of this chapter—"I want to understand the complete path of a tool call" means following the main highway (query → tool orchestration → tool execution)

> 💡 The directory tree tells you "where files are placed," the entity dimension tells you "which files hold this kind of abstraction," the component dimension tells you "which UI layer handles this interaction," and the data flow dimension tells you "where data comes from and goes to." Using all four dimensions together is more efficient than relying on directory structure alone.

---

> **[Chart placeholder 2.1-A]**: Codebase five-zone distribution diagram—Heart Zone at the center, surrounded by Limbs Zone / Skin Zone / Skeleton Zone / Special Zone
> **[Chart placeholder 2.1-B]**: Three data-flow highways schematic—Main Highway / Background Highway / Extension Highway
> **[Chart placeholder 2.1-C]**: Dependency heatmap—radiation structure centered on Tool.ts
