$ tree --depth=2 /claude-code/src/

Architecture Deep Dive

How Claude Code boots, runs, and manages 184 tools across 28 subsystems. From the first prefetch to the query engine loop.

## Bootstrap Flow

The startup sequence — from first import to interactive REPL

1
Prefetch Side Effects
MDM config read, keychain prefetch, project directory scan — all fire before any user code runs
2
Warning Handler + Env Guards
Process warning suppression, environment validation, platform checks
3
CLI Parser + Trust Gate
Argument parsing, pre-action trust verification before any tool access
4
setup() + Parallel Load
Commands and agents loaded in parallel. Tool pool assembled based on permissions
5
Deferred Init After Trust
Remaining tools unlocked only after trust gate passes. MCP tools loaded here
6
Mode Routing
local | remote | ssh | teleport | direct-connect | deep-link
7
Query Engine Submit Loop
The main REPL loop begins. Codename "nO" — single-threaded master loop
bootstrap_graph.py — simplified flow
prefetch_side_effects()     # MDM, keychain, project scan
  │
  ▼
warning_handler()           # suppress noisy warnings
env_guards()                # platform + version checks
  │
  ▼
cli_parser()                # parse args, flags
trust_gate()                # ← blocks until verified
  │
  ▼
┌─────────────────────────┐
│  setup() — parallel     │
│  ├─ load_commands()     │
│  ├─ load_agents()       │
│  └─ assemble_tool_pool()│
└─────────────────────────┘
  │
  ▼
deferred_init()             # MCP tools, extensions
mode_router()               # local|remote|ssh|teleport
  │
  ▼
query_engine.submit_loop()  # ← the main REPL

## Runtime Architecture

The single-threaded master loop, codename "nO"

QueryEngine

  • Turn-based loop with budget tracking
  • Automatic compaction when context fills
  • Structured output parsing for tool calls
  • Cost tracking per turn and session

Execution Registry

  • Routes prompts to commands + tools
  • Token scoring for tool selection
  • Slash command prefix matching
  • Fallback to general agent

Session Persistence

  • Transcript store with flush/replay
  • Resume from session ID
  • Conversation export (JSON/Markdown)
  • Session sharing via links

Context Management

  • PortContext tracks source, tests, assets
  • Archive availability detection
  • CLAUDE.md file chain resolution
  • Working directory multi-root support
runtime loop — pseudocode
while (session.active) {
  const userInput = await prompt.read();

  // Slash command?
  if (userInput.startsWith('/')) {
    const cmd = registry.matchCommand(userInput);
    if (cmd) { await cmd.execute(ctx); continue; }
  }

  // Submit to query engine
  const response = await queryEngine.submit({
    messages: session.messages,
    tools: toolPool.available(ctx.permissions),
    budget: ctx.remainingBudget,
  });

  // Process tool calls
  for (const toolCall of response.toolCalls) {
    const result = await toolPool.execute(toolCall, ctx);
    session.append(toolCall, result);
  }

  // Compact if needed
  if (session.tokenCount > ctx.compactionThreshold) {
    await session.compact();
  }
}

## Tool System

94 unique tools assembled per-session based on mode and permissions

Tool Pool Assembly

1. Start with full tool registry (94 tools)
2. If simple mode: restrict to BashTool, FileReadTool, FileEditTool only
3. Apply MCP inclusion/exclusion filters
4. Apply ToolPermissionContext deny lists (exact name + prefix)
5. Deferred tools loaded after trust gate

Core File Tools

5 tools
FileReadToolFileEditToolFileWriteToolGlobToolGrepTool

Execution

BashTool is the "crown jewel"

2 tools
BashToolPowerShellTool

Agent Tools

Sub-agents: explore, plan, general, verification, claudeCodeGuide

5 tools
AgentToolforkSubagentrunAgentresumeAgentspawnMultiAgent

Task Management

6 tools
TaskCreateToolTaskGetToolTaskListToolTaskOutputToolTaskStopToolTaskUpdateTool

Team / Multi-Agent

2 tools
TeamCreateToolTeamDeleteTool

Web

2 tools
WebFetchToolWebSearchTool

MCP Integration

4 tools
MCPToolMcpAuthToolListMcpResourcesToolReadMcpResourceTool

Scheduling

3 tools
CronCreateToolCronDeleteToolCronListTool

Communication

2 tools
SendMessageToolAskUserQuestionTool

Specialized

6 tools
LSPToolNotebookEditToolSkillToolTodoWriteToolBriefToolConfigTool

Planning

2 tools
EnterPlanModeToolExitPlanModeV2Tool

Safety Systems

5 tools
gitSafetygitOperationTrackingbashSecuritybashPermissionsdestructiveCommandWarning

## Command System

141 unique commands organized by category — from /help to /buddy

Core

help, version, status, config, doctor, exit

Session

session, resume, compact, clear, rename, export, share, copy

Git/PR

branch, commit, commit-push-pr, diff, review, pr_comments, autofix-pr

Agent

agents, bridge, bridge-kick, btw

Planning

plan, ultraplan, tasks

Navigation

add-dir, files, context

Model

model, effort, fast

Plugin System

plugin, install, reload-plugins, DiscoverPlugins, ManagePlugins, BrowseMarketplace

Remote

remote-env, remote-setup, teleport

Voice

voice

Desktop/IDE

desktop, ide, chrome

Fun/Hidden

buddy, bughunter, stickers, good-claude, thinkback

Internal/Dev

ant-trace, mock-limits, heapdump, perf-issue, debug-tool-call, insights, stats

Security

permissions, security-review, privacy-settings, sandbox-toggle

## Permission System

Multi-layered permission enforcement from trust gate to tool execution

ToolPermissionContext

Every tool execution passes through the permission context, which maintains two deny lists:

interface ToolPermissionContext {
  denyNames: string[];     // exact tool name matches
  denyPrefixes: string[];  // prefix-based blocking
  trustLevel: TrustLevel;  // none | read | write | full
}

Trust-Gated Deferred Init

Tools that require elevated access (MCP, scheduling, agent spawning) are not loaded at boot. They're deferred until the trust gate confirms the user's identity and permissions. This means a compromised or untrusted context can never access dangerous tools — they literally don't exist in the tool pool yet.

BashTool Special Handling

BashTool gets extra layers because it can do anything:

  • destructiveCommandWarning — warns before rm -rf, git reset --hard, etc.
  • preapproved — safe commands that skip confirmation (ls, cat, etc.)
  • bashSecurity — command injection detection
  • bashPermissions — per-project command allowlists

Sandbox Toggle

The sandbox-toggle command switches between sandboxed and unrestricted execution. In sandbox mode, BashTool runs commands in a restricted environment with limited filesystem access and no network.