claude-code-deep-dive
```markdown
What this skill does
```markdown
---
name: claude-code-deep-dive
description: Expertise in the Claude Code deep dive research report — navigating the extracted source, understanding the agent architecture, prompt assembly system, tool execution pipeline, and all major subsystems reverse-engineered from the npm package source map.
triggers:
- "explain how Claude Code works internally"
- "show me the claude code architecture"
- "how does claude code assemble its system prompt"
- "explain the agent tool and subagent system"
- "how do skills plugins and hooks work in claude code"
- "walk me through the tool execution pipeline"
- "what files are in the extracted source"
- "how does claude code handle permissions and mcp"
---
# Claude Code Deep Dive
> Skill by [ara.so](https://ara.so) — Daily 2026 Skills collection.
## What This Project Is
This repository is a **systematic reverse-engineering research report** of `@anthropic-ai/claude-code` — reconstructed from the `cli.js.map` source map bundled inside the published npm package. The map's `sourcesContent` field contained **4,756 original TypeScript source files**, making full architectural analysis possible.
The report covers:
- Complete source structure of Claude Code
- How the system prompt is dynamically assembled
- The AgentTool / SkillTool protocol
- Built-in agent roles and the agent dispatch chain
- Plugin / Skill / Hook / MCP runtime integration
- Permission and tool execution pipelines
- Why Claude Code behaves more like an Agent Operating System than a simple CLI wrapper
### Primary Artifacts
| Path | Description |
|---|---|
| `claude-code-deep-dive-xelatex.pdf` | Full research report (PDF) |
| `extracted-source/` | All 4,756 reconstructed TypeScript source files |
| `extracted-source/src/constants/prompts.ts` | Main system prompt assembly |
| `extracted-source/src/tools/AgentTool/` | Agent dispatch system |
| `extracted-source/src/tools/SkillTool/` | Skill invocation system |
| `extracted-source/src/services/tools/` | Tool execution + hook pipeline |
---
## Navigating the Extracted Source
```bash
# Clone the repo
git clone https://github.com/tvytlx/claude-code-deep-dive.git
cd claude-code-deep-dive
# Top-level source layout
ls extracted-source/src/
# entrypoints/ constants/ tools/ services/ utils/
# commands/ components/ coordinator/ memdir/
# plugins/ hooks/ bootstrap/ tasks/
```
### Key File Locations
```
extracted-source/src/
├── constants/
│ └── prompts.ts # ← THE main system prompt assembler
├── tools/
│ ├── AgentTool/
│ │ ├── AgentTool.tsx # Agent tool definition + UI
│ │ ├── runAgent.ts # Agent execution loop
│ │ └── prompt.ts # Agent-specific prompt fragments
│ ├── SkillTool/
│ │ ├── SkillTool.tsx
│ │ └── prompt.ts
│ ├── FileRead.ts
│ ├── FileEdit.ts
│ ├── FileWrite.ts
│ ├── Bash.ts
│ ├── Glob.ts
│ ├── Grep.ts
│ └── TodoWrite.ts
├── services/
│ ├── tools/
│ │ ├── toolExecution.ts # Full tool execution pipeline
│ │ └── toolHooks.ts # Pre/post hook integration
│ └── mcp/ # MCP bridge
├── entrypoints/
│ ├── cli.tsx # Main CLI entry
│ ├── init.ts
│ ├── mcp.ts # MCP server mode
│ └── sdk/ # SDK consumer entry
└── commands.ts # All slash commands registered
```
---
## Core Architecture Concepts
### 1. System Prompt Assembly (`prompts.ts`)
Claude Code does **not** use a static system prompt. `getSystemPrompt()` is a runtime assembler:
```typescript
// Conceptual reconstruction of getSystemPrompt()
function getSystemPrompt(context: SessionContext): string {
// STATIC PREFIX — suitable for prompt caching
const staticSections = [
getSimpleIntroSection(), // Identity + CYBER_RISK_INSTRUCTION
getSimpleSystemSection(), // Runtime rules (hooks, compression, tags)
getSimpleDoingTasksSection(), // Engineering behavior constraints
getActionsSection(), // Risk/destructive action rules
getUsingYourToolsSection(), // Tool grammar (FileRead > cat, etc.)
getSimpleToneAndStyleSection(),
getOutputEfficiencySection(),
].join('\n');
// DYNAMIC SUFFIX — session-specific, NOT cached
// Boundary: SYSTEM_PROMPT_DYNAMIC_BOUNDARY
const dynamicSections = [
getSessionSpecificGuidanceSection(context), // Current tool set + feature gates
getMemorySection(context),
getEnvInfoSection(context),
getLanguageSection(context),
getOutputStyleSection(context),
getMcpInstructionsSection(context),
getScratchpadSection(context),
getFunctionResultClearingSection(context),
getTokenBudgetSection(context),
].filter(Boolean).join('\n');
return staticSections + SYSTEM_PROMPT_DYNAMIC_BOUNDARY + dynamicSections;
}
```
**Key insight**: The `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` marker separates cache-friendly static content from per-session dynamic content. Moving content across this boundary has cost implications.
### 2. Agent Dispatch Chain
```
User Request
│
▼
AgentTool.tsx ← tool definition, permission check, UI rendering
│
▼
runAgent.ts ← spawns isolated agent context
│ - forks session state
│ - injects agent-specific system prompt (prompt.ts)
│ - sets up sub-tool allowlist
▼
query() ← model inference loop (shared with main loop)
│
▼
toolExecution.ts ← same pipeline as main agent
```
```typescript
// Simplified agent invocation pattern (from AgentTool reconstruction)
const agentResult = await runAgent({
task: toolInput.task,
parentSession: currentSession,
allowedTools: resolveAgentTools(context), // Subset of parent tools
agentPrompt: getAgentPrompt(agentType), // From AgentTool/prompt.ts
mcpTools: filteredMcpTools,
});
```
### 3. Tool Execution Pipeline
Every tool call (including MCP tools) passes through:
```
Model emits tool_use block
│
▼
toolExecution.ts
├── 1. Permission check (permission mode + user grants)
├── 2. Pre-execution hooks (toolHooks.ts → external hook scripts)
├── 3. Actual tool.call() invocation
├── 4. Post-execution hooks
├── 5. Analytics event emission
└── 6. Result returned as tool_result block
```
```typescript
// Conceptual pipeline (reconstructed from toolExecution.ts)
async function executeTool(tool: Tool, input: unknown, ctx: ExecContext) {
// Step 1: Permission
const permitted = await checkPermission(tool, input, ctx);
if (!permitted) return permissionDeniedResult(tool);
// Step 2: Pre-hook
const hookDecision = await runPreHooks(tool, input, ctx);
if (hookDecision.block) return hookDecision.result;
// Step 3: Execute
const result = await tool.call(input, ctx);
// Step 4: Post-hook
await runPostHooks(tool, input, result, ctx);
// Step 5: Analytics
emitToolEvent(tool.name, input, result);
return result;
}
```
### 4. Built-in Agent Types
From `AgentTool/prompt.ts` and session guidance sections:
| Agent Type | Role |
|---|---|
| Default subagent | General task execution with full tool access |
| Explore agent | Read-only codebase exploration |
| Plan agent | Task decomposition and planning (no file writes) |
| Verification agent | Mandatory post-task verification contract |
| Review agent | Code review with structured output |
### 5. Skill System
Skills are **prompt-native workflow packages** — not just documentation:
```typescript
// SkillTool invocation (reconstructed)
interface SkillInvocation {
skillName: string; // e.g. "fix-tests"
args: Record<string, string>;
}
// Skills contribute to command system at startup
const allCommands = [
...builtinCommands,
...pluginCommands,
...skillCommands, // Slash commands from installed skills
...bundledSkills,
...dynamicSkills, // DiscRelated 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.