# A Panoramic Map of the Eight Subsystems

> The goal of this chapter: before you dive into the details of any individual chapter, know what "rooms" exist in the system, what lives in each room, and where the doors between them are.

> **🌍 Industry Context**: The architectures of large-scale AI agent systems all answer the same set of questions: How do you safely execute tools? How do you manage limited context? How do you extend capabilities? **LangChain** uses a three-layer abstraction of Chain → Agent → Tool, **AutoGPT** uses Task → Action → Plugin, and **CrewAI** uses Agent → Task → Crew collaboration. Claude Code's eight subsystems are its answer to these questions—more complete than most frameworks (including unique subsystems like speculative execution and background memory), and also heavier (a 1,884-file engineering effort that dwarfs LangChain Agent's few-hundred-line configuration). This chapter helps you build a global understanding of these eight "rooms."

---

## Why You Need a Panoramic Map

Claude Code is not a linear program—"input → process → output." It is a **multi-centered, multi-looped, concurrent system with background tasks.**

If you jump straight into a detail (like "how does speculative execution work?"), it's easy to get lost in the local mechanics without understanding how that feature relates to everything else.

This map builds your "system intuition" first.

[Chart placeholder 1.4-A: System panoramic architecture diagram (locations and connections of the eight subsystems)]

---

## The Eight Subsystems

### Subsystem 1: Core Engine

**Location**: The heart of the system  
**Files**: `query.ts` (~1,700 lines)

**What it does**: Receives user input and drives the entire AI inference process. It is a `while(true)` loop: call API → process tools → call API again → … → final answer.

**Key components**:
- `queryLoop()`: The main loop function
- `StreamingToolExecutor`: Starts executing tools while the model is still outputting (parallel optimization)
- Six-layer context compression mechanism: progressively compresses conversation history as tokens approach the limit

**Connections to other subsystems**:
- Calls the "Tool System" to execute each tool
- Calls the "Permission System" to check every tool call
- Triggers the "Background Task System" upon completion (SessionMemory, Prompt Suggestion)
- Receives input from the "Context/Prompt Building System"

> 📚 **Course Connection**: The Core Engine's `while(true)` loop is the **event loop** from your operating systems class—the same pattern as Node.js's `libuv` event loop, the browser's message loop, and the OS kernel's scheduling loop. The difference is that Claude Code's loop body is "call AI → execute tools," whereas the OS loop body is "read interrupt → execute system call."

---

### Subsystem 2: Tool System

**Location**: The execution layer of the Core Engine  
**Files**: `tools/`, `Tool.ts`

**What it does**: Manages all available tools, executes tool calls, and returns results.

**Key characteristics**:
- **Concurrency control**: Read-only tools (Read, Glob, Grep) can execute in parallel; write operations (Edit, Bash) execute serially
- **Streaming execution**: `StreamingToolExecutor` begins executing as soon as the model outputs a tool call, without waiting for the model to finish speaking
- **Unified interface**: All tools implement the same `Tool` interface (~20 methods/properties)

**Tool categories**:

| Category | Tools |
|----------|-------|
| File operations | Read, Edit, Write, Glob |
| Command execution | Bash |
| Search | Grep |
| Network | WebFetch |
| AI collaboration | Agent (spawns sub-agents) |
| MCP tools | `mcp__server__tool` format |

> 💡 **Plain English**: The Tool System is like a **Swiss Army knife**—one handle integrating 40 built-in tool blades (scissors, bottle opener, screwdriver…), with only a few deployed at a time. What's more impressive is that you can attach **unlimited accessories** to this knife via MCP. Reading files, writing code, searching, running commands—everything Claude "does" is accomplished by flipping open one of the knife's tools.

[Chart placeholder 1.4-B: Tool concurrent execution sequence diagram (how StreamingToolExecutor works)]

---

### Subsystem 3: Permission System

**Location**: The gatekeeper of the Tool System  
**Files**: `utils/permissions/` (~1,500 lines)

**What it does**: Determines whether each tool call is allowed before execution. A ten-step state machine with six permission modes.

**Permission modes** (from most restrictive to most permissive):

```
plan         → Read-only, no write operations allowed
default      → Prompt the user when uncertain
acceptEdits  → Auto-accept file edits, ask for everything else
dontAsk      → Don't ask but follow rules (used inside sub-agents)
auto         → AI classifier replaces user confirmation
bypassPermissions → Bypass all permissions (except bypass-immune)
```

**Key design**: The Bypass-Immune layer—executed before `bypassPermissions` mode, protecting paths like `.git/` and `.claude/` that cannot be bypassed under any mode.

> 📚 **Course Connection**: Claude Code's Permission System maps to **multi-layer access control** from OS security classes—the ten-step check chain = security pipeline, bypass-immune = kernel-level protection (even root cannot modify), permission prompts = `sudo` confirmation, and Auto mode's AI classifier = policy-based automatic access control (PBAC).

[Chart placeholder 1.4-C: Permission ten-step state machine flowchart]

---

### Subsystem 4: Context & Prompt Building System

**Location**: The "feed inlet" of the Core Engine  
**Files**: `context.ts`, `utils/claudemd.ts`, `utils/settings/`

**What it does**: Assembles the complete System Prompt for every API call, including:
- CLAUDE.md content (loaded and merged from multiple directories)
- Tool list and descriptions
- User settings and rules
- Current git status
- Current date and working directory

**CLAUDE.md loading order**:

```
Traverse upward from current directory to $HOME
  ↓ Find all CLAUDE.md files in .claude/ directories
Collect → deduplicate → sort by priority
  ↓ When adding to context: later entries have higher priority
  (Leveraging the LLM's "recency bias" attention pattern)
```

**Settings priority** (from highest to lowest):
```
Enterprise policy (policySettings)
  ↑
Local settings (localSettings) .claude/settings.local.json
  ↑
Project settings (projectSettings) .claude/settings.json
  ↑
User settings (userSettings) ~/.claude/settings.json
```

> 💡 **Plain English**: The Context Building System is like a **chef's mise en place station**—before every dish (API call), all ingredients (CLAUDE.md, tool descriptions, history, git status) must be laid out. The order matters: least frequently changed ingredients go deepest (system instructions), most frequently changed go outermost (user's latest message), so the inner ingredients can be reused next time (prompt cache hit).

[Chart placeholder 1.4-D: System Prompt assembly diagram (overlay relationships of each source)]

---

### Subsystem 5: Agent & Task System

**Location**: A special extension inside the Tool System  
**Files**: `tools/AgentTool/`, `tasks/`

**What it does**: Creates and manages sub-agents (independent AI instances) and various background tasks.

**Two runtime modes**:

| Mode | Description |
|------|-------------|
| Local sub-agent | Runs in the same process, sharing the filesystem |
| Swarm/Teammate | Multiple Claude instances collaborating (three backends: tmux/iTerm2/in-process) |

**Swarm architecture**:
```
Leader (main Claude)
  ├── Teammate A (researcher@my-team)
  ├── Teammate B (tester@my-team)
  └── Teammate C (builder@my-team)
```

All Teammate permission decisions flow to the Leader (`leaderPermissionBridge`), making the Leader UI the single permission approval entry point.

---

### Subsystem 6: Background Services

**Location**: Triggered after the Core Engine completes  
**Files**: `services/SessionMemory/`, `services/PromptSuggestion/`

**What it does**: After Claude finishes a response, runs two independent AI tasks in the background:

**SessionMemory**:
- Extracts key information from the current conversation
- Writes to `session-memory.md` (9 fixed sections)
- Next time the project is opened, Claude already knows where things left off

**Prompt Suggestion**:
- Predicts your most likely next message (2–12 words)
- Drives "speculation" to run AI ahead of time

> 💡 **Plain English**: Background Services are like a **secretary's wrap-up work**—after the meeting (conversation) ends, the secretary doesn't clock out: first write the meeting minutes (SessionMemory), then guess what the next meeting will discuss (Prompt Suggestion). If the guess is right, the next time the boss speaks, the prepared materials are already waiting (speculative execution).

[Chart placeholder 1.4-E: Background task trigger sequence diagram (relationship with the main loop)]

---

### Subsystem 7: Speculation System

**Location**: An independent parallel execution track  
**Files**: `services/PromptSuggestion/speculation.ts`

**What it does**: Uses the time you spend reading Claude's response and thinking about your next input to run AI ahead of time:

```
Claude finishes responding
  → Predict what you're most likely to type (Prompt Suggestion)
  → Secretly run AI once with the predicted input (Speculation)
  → You press Enter
  → If your input matches the prediction: result is ready, response time ≈ 0
  → If not: discard the prediction and process normally
```

**Key mechanism**: Copy-on-Write overlay filesystem—file operations during speculative execution write to a temporary overlay directory without affecting real files; if the prediction is correct, the overlay merges into the main directory; if incorrect, the overlay is discarded.

> 💡 **Plain English**: Speculative execution is like a **restaurant's advanced prep**—not only are ingredients prepped in advance, but the kitchen guesses what you'll order, cooks it ahead of time, and holds the plate ready. Right guess = instant service, zero wait. Wrong guess = throw it out and start over, losing the cost of one dish. The system secretly "guesses your order" during the seconds you spend reading Claude's response.

(Note: This feature is currently for Anthropic internal use only.)

> 📚 **Course Connection**: Speculative execution directly borrows the **branch prediction + speculative execution** concept from computer architecture class. A CPU guesses which path a conditional branch will take and executes ahead; right guess = zero delay, wrong guess = rollback (pipeline flush). Claude Code's Copy-on-Write overlay filesystem is the software equivalent of a "pipeline flush"—when the prediction is wrong, all temporary file changes are discarded.

---

### Subsystem 8: Extension System

**Location**: An outer layer wrapping all other subsystems  
**Files**: `utils/plugins/`, `utils/hooks/`, `services/mcp/`, `skills/`

**What it does**: Provides three different levels of extensibility:

**MCP (Model Context Protocol)**:
- Connects to external tool servers
- Lets third-party services register new tools
- 8 transport protocols (stdio/HTTP/WebSocket, etc.)

**Hooks**:
- Injects custom logic at 27 event nodes in the system
- 4 execution types (shell command/prompt/AI Agent/HTTP)
- Can block operations, modify inputs, and listen to events

**Plugins**:
- Packages and distributes Commands, Skills, Hooks, and MCP servers
- Installed via Marketplace
- Triple security protection (name whitelist, impersonation detection, homoglyph defense)

[Chart placeholder 1.4-F: Extension system three-layer structure diagram (relationship between MCP/Hooks/Plugins)]

---

## Subsystem Comparison with Other AI Coding Tools

> 🌍 Claude Code is not the only tool with these subsystems, but it is unique in its **completeness**:

| Subsystem | Claude Code | Cursor | Aider | GitHub Copilot |
|-----------|-------------|--------|-------|----------------|
| Core Engine | ✅ while(true) Agent Loop | ✅ Agent Mode | ✅ main loop | ✅ Agent mode |
| Tool System | 43 built-in + unlimited MCP | ~15 built-in | ~10 | ~10 |
| Permission System | 10-step check chain + 6 modes | Simplified confirmation popups | CLI --yes flag | Sandbox restrictions |
| Context Building | Multi-source CLAUDE.md + 9 layers | .cursorrules + AI rules | .aider.conf + repo map | Editor context |
| Agent Nesting | Multi-layer sub-agents + Swarm | Single-layer multi-step | No sub-agents | Single-layer |
| Background Tasks | SessionMemory + PromptSuggestion | None | None | None |
| Speculative Execution | ✅ Copy-on-Write | ❌ | ❌ | ❌ |
| Extension System | MCP + Hooks + Plugins + Skills | Extensions API | None | Extensions API |

---

## Subsystem Relationship Matrix

[Chart placeholder 1.4-G: Subsystem dependency relationship matrix (which subsystems call which)]

Simplified text description:

```
Core Engine     →  Tool System
Core Engine     →  Permission System
Core Engine     →  Context Building System (receives input)
Core Engine     →  Background Services (triggered on completion)
Background Services → Speculation System
Tool System     →  Agent & Task System
Extension System → All other systems (injects via Hooks, adds tools via MCP)
```

---

## Using This Map to Read Subsequent Chapters

Each chapter zooms into the internals of one subsystem. As you read, ask yourself:

1. **Where is this subsystem on the map?**
2. **What is its upstream (where does input come from) and downstream (where does output go)?**
3. **What problem does its existence solve?**

These three questions matter more than understanding implementation details. Once you understand the "why," the implementation details gain meaning.

---

## Key Source Code Entry Points

Core files corresponding to the eight subsystems:

- `src/main.tsx` — **Core Engine**: boot sequence, REPL loop, global state (4,684 lines)
- `src/tools/` — **Tool System**: 40 built-in tool directories
- `src/utils/permissions/` — **Permission System**: permission checks, YOLO mode classifier, rejection tracking
- `src/services/api/claude.ts` — **Context Building System**: API calls, token budgeting, prompt cache management
- `src/state/` — **State Management**: application state, session state, file snapshots
- `src/utils/forkedAgent.ts` — **Agent & Task System**: sub-agent creation and cache sharing
- `src/hooks/` — **Extension System (Hooks)**: registration and execution of 27 hook events
- `src/services/mcp/` — **Extension System (MCP)**: external tool server protocol implementation
