how-claude-code-works
```markdown
What this skill does
```markdown
---
name: how-claude-code-works
description: Deep dive into Claude Code internals — architecture, agent loop, context engineering, tool system, and security for building or understanding AI coding agents.
triggers:
- how does claude code work internally
- explain claude code architecture
- how does the claude code agent loop work
- claude code context engineering and compression
- claude code tool system internals
- how does claude code handle security and permissions
- build my own ai coding agent like claude code
- claude code hooks and extensibility
---
# How Claude Code Works
> Skill by [ara.so](https://ara.so) — Daily 2026 Skills collection.
A 12-chapter deep dive into Claude Code's 500K+ line TypeScript source, covering architecture, the agent loop, context engineering, tool systems, permissions, multi-agent coordination, memory, skills, and UX design. Companion project to [`claude-code-from-scratch`](https://github.com/Windy3f3f3f3f/claude-code-from-scratch) — 1,300 lines, 8 chapters, build your own Claude Code.
## Reading the Docs
**Online:** https://windy3f3f3f3f.github.io/how-claude-code-works/#/
**Local:**
```bash
git clone https://github.com/Windy3f3f3f3f/how-claude-code-works
cd how-claude-code-works
# Open docs/ folder — plain Markdown, readable in any editor
```
**Chapter map:**
| File | Topic |
|------|-------|
| `docs/quick-start.md` | 10-minute condensed overview |
| `docs/01-overview.md` | Tech choices, 9-phase startup, data flow |
| `docs/02-agent-loop.md` | Dual-layer loop, 7 Continue Sites, streaming tool execution |
| `docs/03-context-engineering.md` | 4-level compression pipeline, cache strategy |
| `docs/04-tool-system.md` | 66 tools, MCP, concurrency, OAuth |
| `docs/05-code-editing-strategy.md` | search-and-replace, uniqueness constraint |
| `docs/06-hooks-extensibility.md` | 23+ hook events, 6-stage pipeline |
| `docs/07-multi-agent.md` | Sub-agents, coordinator, Swarm, Worktree isolation |
| `docs/08-memory-system.md` | 4 memory types, semantic recall, drift defense |
| `docs/09-skills-system.md` | 6-layer skill sources, lazy load, token budget |
| `docs/10-permission-security.md` | 5-layer defense, AST analysis, 23 safety checks |
| `docs/11-user-experience.md` | Ink renderer, Yoga Flexbox, virtual scroll |
| `docs/12-minimal-components.md` | Minimal viable agent, 500→500K line roadmap |
---
## Key Architecture Concepts
### System Architecture
```
User Input
│
▼
QueryEngine (session management)
│
▼
query() main loop ◄──────────────────────┐
│ │
▼ │
Claude API (streaming) │
│ │
├─► Text tokens → stream to terminal │
│ │
└─► Tool calls → ToolExecutionEngine │
│ │
├─ ReadFile │
├─ EditFile │
├─ Shell │
├─ Search │
└─ MCP Tools │
│ │
└─ results ────────┘
Context Engineering layer feeds:
- System prompt
- Git status
- CLAUDE.md files
- Compression pipeline
```
### The Agent Loop (docs/02-agent-loop.md)
Claude Code uses a **dual-layer loop**:
1. **Outer loop** — manages conversation state, compaction triggers, session lifecycle
2. **Inner loop** — single API call → parse response → execute tools → inject results → repeat
**7 Continue Sites** (fault recovery strategies):
- `CONTINUE` — normal tool result injection
- `CONTINUE_WITH_COMPACTION` — context too long, compress then continue
- `CONTINUE_WITH_MAX_TOKENS_RETRY` — upgrade 4K→64K output limit and retry
- `STOP_WITH_RESULT` — final answer reached
- `STOP_WITH_ERROR` — unrecoverable error
- `STOP_WITH_INTERRUPT` — user cancelled
- `STOP_WITH_LIMIT` — turn/cost limit hit
**Tool pre-execution (StreamingToolExecutor):** While the model streams its response, the system parses tool calls and begins executing them concurrently. The ~1s tool I/O latency is hidden inside the model's 5–30s generation window.
### 4-Level Context Compression (docs/03-context-engineering.md)
When context approaches the limit, compression triggers progressively:
```
Level 1: TRUNCATE
└─ Cut large tool outputs in older messages (fast, lossy for old data)
Level 2: DEDUPLICATE
└─ Remove repeated content (near-zero cost)
Level 3: FOLD
└─ Collapse inactive conversation segments (reversible, content intact)
Level 4: SUMMARIZE
└─ Launch sub-agent to summarize entire conversation (last resort)
```
After any compression, the system **auto-restores**:
- The 5 most recently edited files (full content re-injected)
- Active skill context (prevents the model forgetting what it was doing)
### Tool System (docs/04-tool-system.md)
All 66+ tools share one interface:
```typescript
interface Tool {
name: string;
description: string;
inputSchema: ZodSchema;
execute(input: unknown, context: ToolContext): Promise<ToolResult>;
readonly: boolean; // true = can run in parallel
requiresPermission: boolean;
}
```
**Concurrency rules (automatic):**
- Read-only tools → parallel execution
- Write tools → serialized automatically
- Output > 100K chars → written to disk, model receives path + summary
### 5-Layer Permission System (docs/10-permission-security.md)
```
Layer 1: Permission Mode
└─ Trust level restricts available operation classes
Layer 2: Rule Matching
└─ Command pattern whitelist/blacklist
Layer 3: Bash AST Analysis (tree-sitter)
└─ 23 safety checks on parsed shell AST, not regex:
- Command injection detection
- Env variable leak detection
- Special character attacks
- Pipe chain analysis
Layer 4: User Confirmation
└─ Dangerous ops require explicit confirm
200ms debounce prevents accidental keypress confirmation
Layer 5: Hook Validation
└─ User-defined rules, can mutate tool inputs
(e.g. auto-add --dry-run to rm commands)
```
### Hooks System (docs/06-hooks-extensibility.md)
Configure in `.claude/hooks.json` or `CLAUDE.md`:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "my-safety-checker --input-file $CLAUDE_TOOL_INPUT"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "prettier --write $CLAUDE_FILE_PATH"
}
]
}
]
}
}
```
**23+ hook events** including:
- `PreToolUse` / `PostToolUse` — intercept any tool call
- `PreBashCommand` — inspect shell commands before execution
- `OnError` — custom error handling
- `OnSessionStart` / `OnSessionEnd`
- `OnContextCompaction` — triggered before compression
**Hook can return** `PermissionRequest` with 4 capabilities:
1. `APPROVE` — bypass normal permission check
2. `DENY` — block the operation
3. `MODIFY_INPUT` — mutate the tool's input parameters
4. `PROVIDE_REASON` — add explanation shown to user
### Multi-Agent Architecture (docs/07-multi-agent.md)
**3 coordination modes:**
```
Sub-Agent:
Main Agent ──dispatch──► Sub Agent
│
└─ executes task
└─ returns result ──► Main Agent continues
Coordinator (pure orchestration):
Coordinator ──task──► Agent A (reads files, writes code)
Coordinator ──task──► Agent B (runs tests)
Coordinator CANNOT read/write itself — enforces separation
Swarm (peer-to-peer):
Agent "Alice" ◄──mailbox──► Agent "Bob"
Agent "Bob" ◄──mailbox──► Agent "Carol"
Each agent independent, 3 execution backends
```
**Worktree isolation:** Each agent gets its own Git worktree copy to prevent concurrentRelated in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.