Reverse Engineering

소스맵으로 Claude Code 512K줄을 뜯어
19,380줄 설계 문서로 복원했다

Claude Code는 앤트로픽(Anthropic)이 만든 AI 코딩 도구입니다. 하지만 안에서 어떻게 돌아가는지는 겉에서 보이지 않습니다. 이 페이지는 그 안쪽을 직접 뜯어 복원한 설계 문서를 그림 한 장으로 정리한 것입니다. Claude Code는 터미널(검은 명령창)에 글자로 명령을 쳐서 쓰는 명령줄 도구(CLI, command line interface)입니다. 배포되는 코드는 압축돼 있지만, 소스맵(source map, 압축된 코드를 원래 파일 이름과 구조로 되돌려 볼 수 있게 해 주는 지도 파일)은 공개돼 있습니다. 그 소스맵을 실마리 삼아 약 1,900개 파일, 512K줄이 넘는 코드에서 겉으로 드러나지 않는 내부 설계를 거꾸로 복원했습니다. 이렇게 남이 만든 완성품을 분해해 구조를 알아내는 작업을 리버스 엔지니어링(Reverse Engineering)이라고 합니다. 결과물은 8개 부분으로 나뉜 총 19,380줄 분량의 설계 문서입니다. 사실 확인은 8번 반복해 마쳤습니다. 아래 그림은 그 문서를 아키텍처 시각화(Architecture Visualization)로 옮긴 것입니다. 그림 안의 이름표는 원문 코드의 용어라서 영어 그대로 두었습니다. 함수 이름과 파일 이름처럼 코드에 그대로 나오는 이름은 코드 글씨로 표시했습니다. 그중 훅(hook)은 층에 따라 뜻이 다릅니다. Terminal UI 층의 hooks는 리액트(React) 화면 부품이 상태와 동작을 재사용하도록 묶어 둔 함수입니다. Extensions 층의 Hooks는 정해진 사건 27가지 가운데 하나가 일어나는 순간에 미리 등록한 명령을 끼워 실행하는 장치입니다. 같은 층의 MCP(Model Context Protocol)는 바깥 도구와 자료를 AI에 꽂아 쓰는 연결 규약입니다. 나머지 그림도 몇 곳만 미리 풀어 둡니다. 프로그램은 켜질 때 다섯 단계를 지납니다. 먼저 회사가 직원 컴퓨터에 내려 둔 관리 설정(mobile device management)과 비밀번호 보관함(Keychain)을 읽습니다. 그다음 main·init·action 세 함수를 차례로 거칩니다. 마지막으로 명령을 한 줄씩 읽고 실행하고 결과를 찍는 대화 화면(read, evaluate, print loop)을 띄웁니다. 켜진 뒤에는 명령 하나가 AI와 도구 사이를 돕니다. AI는 답 대신 "이 도구를 쓰겠다"는 신호 블록을 보내기도 합니다. 그 신호마다 도구에 달린 권한 검사 함수가 허용·거부·질문·통과 가운데 하나를 고릅니다. 기억(메모리)은 다섯 겹입니다. 프로젝트 폴더와 사용자 홈 폴더 아래의 숨김 폴더가 그중 두 겹입니다. 맨 아래 파일 구조는 저장소에 실제로 들어 있는 파일 목록입니다. docs 폴더의 여덟 파일이 위의 설계 문서 8편입니다. infrastructure 폴더는 서버 배치와 비용을 다룬 문서입니다.

~1,900
Source Files
512K+
Lines of Code
8
Design Docs
19,380
Doc Lines
Architecture Layers
Claude Code CLI — TypeScript Strict · Bun · ESM-only
Terminal UI
React 19component tree
Ink (custom fork)96 files
Yoga WASMflexbox layout
Commander.jsCLI parser
346 .tsxcomponents
85+ hookscustom hooks
Core Engine
45+ ToolsbuildTool() factory
Query Enginestreaming executor
Concurrencysafe/unsafe flags
Recovery8-stage chain
Cost Trackerper-session USD
Extensions
MCP8 config types (transports)
Pluginsmarketplace + builtin
Skills17 bundled + custom
Hooks27 events
LSPcode intelligence
BridgeIDE comms
Services
API Client4 backends
Auth/OAuthPKCE (Proof Key for Code Exchange) + Keychain
AnalyticsDD + OTel
Settings5-layer merge
Migrations11 sync + 1 async
Security
7 Perm Modesdefault to bubble
23 Bash Checkscross-platform
Path Validator6-step pipeline
Auto-ModeYOLO (묻지 않고 자동 승인) classifier
Startup Pipeline
Phase 0
Side Effects
MDM (mobile device management, settings a company pushes to its devices), Keychain prefetch
Phase 1
main() entry
Basic initialization
Phase 2
preAction
init() → migrations
Phase 3
action()
setup → auth/perms
Phase 4
REPL render
Interactive read, evaluate, print loop · Deferred prefetches
Tool Execution Flow
One command's round trip (prompt → model → tool → result → next turn)
IN
User Input
prompt → QueryEngine
AI
LLM API (streaming)
Anthropic / Bedrock / Vertex / Foundry
tool_use block (the model asks to run a tool)
FN
Tool Execution
Bash, FileEdit, Agent, MCP … 45+
R
ToolResult
data, newMessages, contextModifier, mcpMeta
↺ next LLM turn
8 Design Documents
01
Architecture Overview
5-phase startup, ESM-only (ECMAScript modules, no CommonJS) module system, Bun bundler, 7-layer config, 89 feature flags, 110 global state fields
1,101 lines
startup config feature-flags
02
Core Engine
60+ field tool interface, buildTool() factory (one builder for every tool), concurrency safety flags, 8-stage recovery chain, per-session cost tracking
1,352 lines
tools streaming recovery
03
Permission & Security
7 permission modes, 4-step decision pipeline, 23 bash check IDs, 6-step path validation, YOLO (auto-approve mode) auto-classifier
1,178 lines
permissions bash-security TOCTOU (check/use timing race)
04
Multi-Agent & Memory
3 swarm backends (fork/spawn/in-proc), 7 task types, file-based mailbox, 5-layer memory hierarchy, ETag-based sync (ETag: a server-issued version tag that tells whether a cached copy is stale)
1,416 lines
agents memory teams
05
Extension Systems
6 extension points, MCP (Model Context Protocol) 8 transport types, 27 hook events, plugin marketplace, parallel loading, reconnection strategy
1,709 lines
MCP plugins hooks
06
UI Layer
Custom React reconciler (React 19), Ink fork (96 files), Yoga WASM (WebAssembly) layout, ANSI (terminal escape codes) diff rendering, 346 .tsx components
1,784 lines
React Ink Yoga
07
Services & Infrastructure
4 API backends, OAuth PKCE (Proof Key for Code Exchange, a login flow that stops a stolen login code from being reused) with Keychain, Datadog + OTel (OpenTelemetry, an open standard for collecting usage and error data) analytics, 5-source settings merge, 11+1 migrations
1,845 lines
API OAuth analytics
08
Types, Schemas & API
Branded IDs, Zod schemas, ~100 field SettingsJson, DeepImmutable AppState, 60+ env vars, 89 feature flags, 44 DD (Datadog) events
2,194 lines
TypeScript Zod schemas
Permission Decision Pipeline
0
Config deny rules
immediate deny
1
Tool.checkPermissions()
allow / deny / ask / passthrough
2
Permanent allow rules
skip prompt
3
passthrough → ask conversion
 
4
Post-processing
dontAsk • auto (YOLO) • headless
Agent & Memory Hierarchy
Agent Swarm Backends
Coordinator (orchestrator)
fork
shared context
spawn
independent
in-process
teammate
Memory Hierarchy (5 layers)
[1] Session Memory — in-context summaries
[2] Project Memory .claude/memory/
[3] User Memory ~/.claude/memory/
[4] Team Memory — server-synced shared
[5] External — MCP, LSP (language server), git
Deployment Options
Local Dev
Ollama/vLLM, Docker Stack, RTX 4090
$0–50/mo
AWS
ECS Fargate, Bedrock, Lambda, Cognito
$45–180/mo
Azure
Container Apps, Azure OpenAI, AD B2C
$50–190/mo
Supabase
Edge Functions, Realtime, PostgreSQL, Auth
$0–25/mo
Scale Supabase + API AWS Full Hybrid (Local GPU)
Solo (1 dev) $9–103/mo $240–280/mo $50/mo
Team (10 devs) $46–116/dev $65–110/dev $35–60/dev
Enterprise (100 devs) N/A $45–111/dev $25/dev

LLM token costs represent 60–95% of total spend at every scale.

8 Verification Passes
Pass 1
Type/value accuracy
16 corrections
Pass 2
Blocking implementation gaps
4 fixes
Pass 3
Line-by-line precision
7 corrections
Pass 4
Missing schemas/flows
3 fixes
Pass 5
Bridge, MDM, Keychain, Plugin additions
7 additions
Pass 6
Structural problem warnings
42 caveats
Pass 7
Convergence check
2 micro-fixes
Pass 8
CONVERGED (no further corrections) — 24/24 spot-checks verified
0

Total: 39 corrections + 42 implementation caveats

File Structure
claude-code-reverse-engineering/ README.md docs/ 01-architecture-overview.md (1,101 lines) 02-core-engine.md (1,352 lines) 03-permission-security.md (1,178 lines) 04-multi-agent-memory.md (1,416 lines) 05-extension-systems.md (1,709 lines) 06-ui-layer.md (1,784 lines) 07-services-infrastructure.md (1,845 lines) 08-types-schemas-api.md (2,194 lines) infrastructure/ 01-local-development.md 02-aws-architecture.md 03-azure-architecture.md 04-supabase-backend.md 05-cost-analysis.md 06-architecture-diagram.md terraform/ (10 .tf files — production-ready IaC, infrastructure as code: server setup written as text files)
Disclaimer: 이 문서는 공부와 보안 연구를 위해, 완성된 프로그램을 분해해 구조를 알아낸 것(리버스 엔지니어링)입니다. 원본 Claude Code 프로그램에 대한 모든 권리는 Anthropic이라는 회사에 있습니다. 여기 정리한 분석 문서 자체에만 MIT(누구나 자유롭게 쓰고 고칠 수 있게 허용하는 오픈소스 이용 약관) 라이선스가 적용됩니다.