Claude
Skills
Sign in
Back

how-claude-code-works

Included with Lifetime
$97 forever

```markdown

Writing & Docs

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 concurrent

Related in Writing & Docs