# Claude Code: Architecture & Feature Analysis

*Analysis of the extracted source code from @anthropic-ai/claude-code v2.1.88*

---

## Overview

**Claude Code** is Anthropic's official terminal-based AI coding assistant - a sophisticated agentic coding harness built with TypeScript and React/Ink (for terminal UI). The codebase comprises ~500+ source files organized into a modular architecture.

**Note**: This repository contains source code extracted from the npm package's source map (`cli.js.map`). See README.md for details on how the leak occurred.

---

## Architecture

### Core Components

| Directory | Purpose |
|-----------|---------|
| `src/screens/` | Top-level UI screens (REPL, resume, etc.) |
| `src/components/` | React/Ink UI components |
| `src/tools/` | Tool implementations (Bash, Edit, Grep, etc.) |
| `src/commands/` | Slash command implementations |
| `src/skills/` | Skill definitions and loading |
| `src/services/` | Core services (API, MCP, compact, etc.) |
| `src/utils/` | Utility functions and helpers |
| `src/hooks/` | React hooks |
| `src/state/` | State management (AppState) |
| `src/tasks/` | Background task types and management |
| `src/bridge/` | IDE bridge/remote integration |
| `src/memdir/` | Memory directory management |

### Key Entry Points

- **`src/main.tsx`**: Main application entry (REPL mode)
- **`src/QueryEngine.ts`**: Core query lifecycle management
- **`src/Tool.ts`**: Tool context and permission system
- **`src/Task.ts`**: Task type definitions

---

## Notable Features

### 1. Multi-Agent "Swarm" System

**Location**: `src/utils/swarm/`

A full multi-agent orchestration system enabling multiple Claude instances to collaborate:

- **tmux-based layouts**: Spawns teammate Claude instances in separate tmux panes
- **In-process teammates**: Lightweight agent instances within the same process
- **Mailbox communication**: Inter-agent messaging system for coordination
- **Color-coded agents**: Visual identification (agentColorManager)
- **Permission bridging**: Leader agent can approve tool uses for workers

```typescript
// From src/utils/swarm/constants.ts
const TEAM_LEAD_NAME = 'team-lead'
const SWARM_SESSION_NAME = 'claude-swarm'
```

### 2. Plan Mode V2

**Location**: `src/utils/planModeV2.ts`, `src/tools/AgentTool/built-in/planAgent.ts`

Read-only planning mode where agents explore codebases and design implementation plans:

- **READ-ONLY enforcement**: Plan agents cannot edit files
- **Parallel exploration**: Multiple "Explore" agents can run simultaneously
- **Subscription tiering**:
  - Max/Enterprise/Team: 3 planning agents
  - Standard: 1 planning agent
- **"Pewter Ledger" experiment**: A/B testing plan file size optimization to reduce rejection rates

### 3. Auto Dream - Memory Consolidation

**Location**: `src/services/autoDream/`

A background agent that consolidates learnings across multiple sessions:

- Triggers after 24 hours AND 5+ sessions
- Reads multiple session transcripts
- Edits `MEMORY.md` with consolidated patterns
- Visible as a "dream" background task in UI

```typescript
// Default thresholds
const DEFAULTS = {
  minHours: 24,
  minSessions: 5,
}
```

### 4. Sophisticated Security Layer

**Location**: `src/utils/permissions/`, `src/tools/BashTool/bashSecurity.ts`

Multi-layered security approach:

- **AI-based classifier**: Auto-approves safe commands using ML
- **"YOLO mode"** (auto-mode): Extensive allowlist for safe operations
- **Bash security validation**:
  - Detects obfuscated commands
  - Blocks Zsh-specific dangerous builtins (`zmodload`, `sysopen`, `zpty`, `ztcp`)
  - Validates against command injection patterns
  - Tree-sitter based parsing for accurate analysis
  - IFS injection detection
  - Comment/quote desync detection

**Permission modes**:
- `default`: Standard user approval required
- `bypass`: Skip permissions (dangerous)
- `auto`: AI decides on safe operations

### 5. Memory System

**Location**: `src/memdir/`, `src/utils/memory/`

Hierarchical memory with strict typing:

**Memory types** (4 taxonomy):
- `user`: User preferences, role, knowledge
- `feedback`: Guidance on what to avoid/keep doing
- `project`: Project context, goals, initiatives
- `reference`: Pointers to external systems

**Memory scopes**:
- `user`: `~/.claude/memory/` (global)
- `project`: `.claude/memory/` (version controlled)
- `local`: `.claude/memory-local/` (not version controlled)
- `auto`: `~/.claude/auto-memory/` (AI-extracted)
- `teamMem`: Shared team memory (feature-flagged)

**Features**:
- Frontmatter parsing for metadata
- Auto-memory extraction from conversations
- Entry point truncation (200 lines / 25KB limit)
- Memory file detection and indexing

### 6. Session Compaction

**Location**: `src/services/compact/`

When context window approaches limit:

- Runs AI-powered conversation summarization
- Preserves critical context (recent turns, plans)
- Pre/post-compact hooks for extensibility
- "Snip" mode for SDK to bound memory
- File/skill budgeting for reconstruction

### 7. LSP Integration

**Location**: `src/tools/LSPTool/`

Full Language Server Protocol support for code intelligence:

- **Operations**: goToDefinition, findReferences, hover, documentSymbol, workspaceSymbol, call hierarchy (incoming/outgoing)
- Spawns LSP servers per language
- 10MB file size limit
- Connection status tracking

### 8. Built-in Agent Types

**Location**: `src/tools/AgentTool/built-in/`

| Agent | Purpose | Model |
|-------|---------|-------|
| **Explore** | Fast read-only codebase search | Haiku (external), inherit (internal) |
| **Plan** | Software architect for implementation planning | inherit |
| **General-purpose** | Multi-step research and coding tasks | Default |
| **Verification** | Testing and validation | - |
| **Statusline setup** | VS Code integration setup | - |

### 9. Feature Flagging & Experiments

**Location**: `src/services/analytics/growthbook.ts`

Extensive A/B testing framework:

- GrowthBook integration for remote config
- Feature flags control major functionality
- Dead code elimination via `bun:bundle` for unused features
- Experiment tracking for analytics

Notable flags:
- `TEAMMEM`: Team memory sharing
- `COORDINATOR_MODE`: Coordinator agent mode
- `VOICE_MODE`: Voice input/output
- `PROACTIVE`/`KAIROS`: Proactive suggestions
- `HISTORY_SNIP`: Snip-based compaction

### 10. Background Tasks

**Location**: `src/tasks/`

Multiple task types with unified management:

| Type | Description |
|------|-------------|
| `local_bash` | Shell command execution |
| `local_agent` | Forked subagent |
| `remote_agent` | Remote Claude session |
| `in_process_teammate` | In-process swarm worker |
| `dream` | Memory consolidation |
| `monitor_mcp` | MCP server monitoring |

Task IDs use prefix + random suffix (e.g., `b1a2b3c4d` for bash)

### 11. Git Worktree Support

**Location**: `src/utils/worktree.ts`, `src/tools/*WorktreeTool/`

- Creates isolated git worktrees for experiments
- Keep or remove worktree on exit
- Useful for testing without affecting main branch

### 12. Computer Use

**Location**: `src/utils/computerUse/`

- Platform-specific implementations (macOS via Swift, Windows, Linux)
- Executor for computer use operations
- Permission gating

### 13. VCR Mode

**Location**: `src/services/vcr.ts`

Cassette-based recording/replay:
- Records API interactions for testing
- Reproducible conversations
- Used in test suites

### 14. Remote Session Support

**Location**: `src/bridge/`, `src/utils/background/remote/`

Multiple remote modes:
- **SSH sessions**: Remote execution via SSH
- **Direct connect**: Direct TCP connection
- **Bridge mode**: IDE integration (VS Code, JetBrains)

### 15. Skill System

**Location**: `src/skills/`, `src/utils/hooks/`

Three types of skills:

| Type | Location | Description |
|------|----------|-------------|
| **Bundled** | Compiled into CLI | Built-in skills like `/commit`, `/schedule` |
| **Disk-based** | `.claude/skills/` | User-defined custom skills |
| **Plugin** | Installed via marketplace | Third-party skill packages |

Skill features:
- Custom prompts and system messages
- Tool allowlisting/disallowing
- Reference files (extracted on first use)
- Memory scopes
- Hook integration

---

## Interesting Technical Decisions

### 1. Bun-Specific Features

Extensive use of `bun:bundle` feature():
- Dead code elimination for unused features
- Conditional imports keep build size down
- Feature flags compile out entire code paths

### 2. React for Terminal UI

Uses **Ink** framework to render React components in terminal:
- Virtual scroll for message history
- Theme system
- Keyboard event handling
- Layout engine (Yoga)

### 3. Zod Validation

JSON schema validation using Zod throughout:
- Tool input/output schemas
- Configuration validation
- Message type validation

### 4. Token Budgeting

Sophisticated token counting and estimation:
- Real-time token counting from API responses
- Estimation for messages before sending
- Budget-aware compaction
- Per-model token limits

### 5. File State Caching

Caches file reads to reduce I/O:
- `FileStateCache` with configurable size limit
- Cache merging across forked agents
- Cache invalidation on edits

### 6. Git Integration

Deep git integration:
- Commit attribution tracking
- File history (snapshots with rewind)
- Branch management
- Worktree support
- `.gitignore` awareness

---

## Tool Ecosystem

| Tool | Purpose |
|------|---------|
| `BashTool` | Execute shell commands |
| `FileEditTool` | Edit files with precise string replacement |
| `FileReadTool` | Read file contents |
| `FileWriteTool` | Write/create files |
| `GlobTool` | File pattern matching |
| `GrepTool` | Content search with ripgrep |
| `LSPTool` | Code intelligence via LSP |
| `MCPTool` | Model Context Protocol servers |
| `AgentTool` | Spawn subagents |
| `AskUserQuestionTool` | Interactive prompts |
| `EnterPlanModeTool` / `ExitPlanModeTool` | Plan mode control |
| `TaskCreateTool` / `TaskUpdateTool` | Task management |
| `ScheduleCronTool` | Cron job scheduling |
| `RemoteTriggerTool` | Remote agent triggers |
| `WebSearchTool` | Web search |
| `NotebookEditTool` | Jupyter notebook editing |

---

## Slash Commands

Common built-in commands (`/command`):

| Command | Purpose |
|---------|---------|
| `/commit` | Create git commits |
| `/review` | Review PR/code |
| `/clear` | Clear conversation/caches |
| `/diff` | Show git diffs |
| `/plan` | Enter plan mode |
| `/fast` | Toggle fast mode |
| `/agents` | Manage custom agents |
| `/schedule` | Manage scheduled tasks |
| `/config` | Configure settings |
| `/memory` | Manage memory |
| `/compact` | Compact conversation |
| `/export` | Export conversation |

---

## Configuration

**Global config**: `~/.claude/settings.json`
**Project config**: `.claude/settings.json`
**Keybindings**: `~/.claude/keybindings.json`

Key settings:
- `permissionMode`: Permission approval behavior
- `autoApproveRules`: Always-allow patterns
- `memoryDir`: Custom memory directory
- `mainLoopModel`: Default Claude model
- `thinking`: Extended thinking config

---

## Dependencies of Note

- `@anthropic-ai/sdk`: Claude API client
- `@modelcontextprotocol/sdk`: MCP support
- `ink`: Terminal React renderer
- `react`: UI framework
- `zod`: Schema validation
- `chokidar`: File watching
- `vscode-languageserver-protocol`: LSP types
- `commander`: CLI argument parsing

---

## Security Considerations

The codebase reveals extensive security hardening:

1. **Command validation**: Multiple layers of bash/power shell command analysis
2. **Path validation**: Prevents directory traversal attacks
3. **Permission denials**: Tracked and logged
4. **Sandbox**: Optional sandboxing for dangerous operations
5. **Secret scanning**: Detects secrets in team memory

---

## Notable Code Patterns

1. **Lazy schema evaluation**: `lazySchema()` for deferred Zod schema creation
2. **Abort controllers**: Pervasive cancellation support
3. **Generator-based streaming**: `AsyncGenerator<SDKMessage>` pattern
4. **Feature-gated imports**: Conditional requires for DCE
5. **Closure-scoped state**: Singleton patterns via closures

---

## Summary

Claude Code is a **production-grade agentic coding harness** with:

- Enterprise-level multi-agent orchestration
- Sophisticated memory and learning systems
- Deep security hardening
- Extensive integrations (LSP, MCP, Git)
- A/B testing framework
- Background task management
- Plugin/skill ecosystem

This is far more than a simple chat interface - it's a complete development environment built around AI assistance.
