Deep Source Code Analysis Report
Generated: 2026-04-01 | Analysis Tool: Claude Code Analysis Framework
Claude Code employs a three-layer compression strategy to manage the context window in long conversations
When approaching token limits, automatically summarizes old messages into compact digests, preserving key information while saving space
Removes zombie messages and stale markers, cleaning up no-longer-needed intermediate states and temporary data
Restructures context for efficiency, reorganizing message order and grouping
Supports four agent modes, from simple tasks to complex collaboration scenarios
| Mode | Process | Messages | Use Case |
|---|---|---|---|
| default | In-process | Shared | Simple tasks |
| fork | Child process | Fresh | Context isolation |
| worktree | Child process | Fresh | Git worktree |
| remote | Bridge session | Isolated | Container/remote |
Claude Code's 43+ built-in tools are organized into 9 major categories, each with specific purposes and behavioral patterns
Claude Code demonstrates 12 layered mechanisms for production AI agents, each building on the previous
while-true loop in query.ts, calls Claude API, checks stop_reason, executes tools
"One loop & Bash is all you need"
Tool.ts + tools.ts, each tool registers into dispatch map, loop stays identical
"Adding a tool = adding one handler"
EnterPlanMode + TodoWrite, list steps first then execute, doubles completion rate
"An agent without a plan drifts"
AgentTool + fork, each child gets fresh context, keeps main conversation clean
"Break big tasks; clean context per subtask"
SkillTool + memdir, inject via tool_result not system prompt
"Load knowledge when you need it"
Three-layer strategy: autoCompact + snipCompact + contextCollapse
"Context fills up; make room"
TaskCreate/Update/Get/List, file-based task graph
"Big goals → small tasks → disk"
DreamTask + LocalShellTask, daemon threads run commands
"Slow ops in background; agent keeps thinking"
TeamCreate/Delete + InProcessTeammateTask, persistent teammates
"Too big for one → delegate to teammates"
SendMessageTool, request-response pattern drives all negotiation
"Shared communication rules"
coordinator/coordinatorMode, idle cycle + auto-claim
"Teammates scan and claim tasks themselves"
EnterWorktree/ExitWorktree, tasks manage goals, worktrees manage directories
"Each works in its own directory"
Full-chain streaming from Claude API to UI using AsyncGenerator
Multi-layer protection: input validation → hooks → rules → interactive → tool check
Supports 5 transport types: stdio/sse/http/ws/sdk with OAuth 2.0 authentication
Supports 4 agent modes: Fork/In-Process/Remote/Worktree
Three-layer strategy: autoCompact (summarize) + snipCompact (trim) + contextCollapse (restructure)
JSONL format storage, supports resume/continue/fork-session
Terminal UI based on Ink, component-based design, theming support
Supports custom plugins and skills, highly extensible
Capybara (v8) is the current version codename, officially released
Feature flag system, currently in internal use
Internal TestingNext major version, codename confirmed
Active DevelopmentPush-to-talk voice mode ready, awaiting gate for release
Awaiting ReleaseNext generation Claude models currently in development
TrainingComprehensive security audit and vulnerability analysis for Claude Code
alwaysAllow/alwaysDeny/alwaysAsk rules with fail-closed defaults
Deep integration with @anthropic-ai/sandbox-runtime, filesystem isolation
Comprehensive command validation and sanitization, prevents command injection
Standard OAuth 2.0 flow with PKCE to prevent authorization code interception
Comprehensive security check logging and telemetry
Path traversal detection and filesystem access controls
The Claude Code codebase demonstrates mature security practices with multiple layers of protection. The permission system, sandbox integration, and command validation are particularly strong. The identified issues are primarily edge cases and hardening opportunities rather than fundamental vulnerabilities.
Claude Code implements a multi-layered defense-in-depth security architecture covering authentication, authorization, sandbox isolation, input validation, MCP security, and secret management
Core File: src/utils/auth.ts (2003 lines)
Prevents concurrent refresh race conditions
Project settings access protection
export async function getAnthropicApiKeyWithSource(): Promise<{
apiKey: string
source: AuthTokenSource
}> {
// Priority: env var > file descriptor > macOS keychain > config file
const envKey = process.env.ANTHROPIC_API_KEY
if (envKey) return { apiKey: envKey, source: 'env' }
const fdKey = await getApiKeyFromApiKeyHelper() // Secure IPC
if (fdKey) return { apiKey: fdKey, source: 'api-key-helper' }
if (process.platform === 'darwin') {
const keychainKey = await getApiKeyFromKeychain()
if (keychainKey) return { apiKey: keychainKey, source: 'keychain' }
}
return { apiKey: await getApiKeyFromConfig(), source: 'config' }
}
| Pattern | Resolves To | Use Case |
|---|---|---|
//path |
Absolute path | System directories |
/path |
Settings-relative | Project configuration |
~/path |
User home directory | User files |
path |
Working directory relative | Default paths |
Detailed implementation analysis of Claude Code's 12-layer progressive Agent Harness
// QueryEngine.ts - Main entry point
async *submitMessage(
prompt: string | ContentBlockParam[],
options?: SubmitMessageOptions
): AsyncGenerator {
// 1. Process user input
const processed = await this.processUserInput(prompt, options)
// 2. Fetch system prompt
const systemPrompt = await this.fetchSystemPrompt()
// 3. Enter query loop
for await (const event of this.queryLoop(processed, systemPrompt, options)) {
// Stream SDK messages to client
yield event
}
}
| Feature | In-Process (AsyncLocalStorage) | Tmux (CLI Args) |
|---|---|---|
| Isolation | Context isolation | Process isolation |
| Overhead | Low (same process) | High (subprocess) |
| Use Case | Fast tasks | Isolated tasks |
| Crash | Affects main process | Independent crash |
Detect .git file
Mount main git directory