$ 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
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
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
Core File Tools
Execution
BashTool is the "crown jewel"
Agent Tools
Sub-agents: explore, plan, general, verification, claudeCodeGuide
Task Management
Team / Multi-Agent
Web
MCP Integration
Scheduling
Communication
Specialized
Planning
Safety Systems
## 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.