Content
# Claude-code-open-explain
> In-depth interpretation of Claude Code's architecture design, operation chain, and engineering trade-offs
<p align="center">
<strong>Not just telling you "what it does", but also explaining "why it is designed this way" </strong>
</p>
<p align="center">
<a href="#what-is-this-project">What is this project</a> •
<a href="#if-youre-new-here">For newcomers</a> •
<a href="#reading-route">Reading route</a> •
<a href="#directory">Directory</a> •
<a href="#disclaimer">Disclaimer</a>
</p>
---
## What is this project
Claude Code can be understood as an AI programming orchestrator running in a local terminal.
It is not the model itself, but rather a component that sits between the model and your computer, responsible for:
* Collecting context such as current working directory, Git status, and user configuration
* Dynamically assembling System Prompt and tool descriptions
* Sending requests to the model and receiving results in a streaming manner
* Executing file read/write, Shell, search, MCP, and other tools locally
* Performing permission verification, security checks, and context management before execution
The goal of this repository is not to copy the source code or simply present conclusions, but to clearly explain the important design decisions in the `Claude-code-open` open-source code, especially for readers who are new to concepts such as Agent CLI, Prompt Cache, MCP, and multi-agent.
More specifically, this project aims to solve two things:
1. Help you establish a holistic understanding of Claude Code's architecture
2. Help you truly understand "why it is designed this way"
## Current Status
The current repository is in the **Wave 1 draft** stage.
This means:
* The main chapters have been established
* Most key decisions have started to be bound to source code evidence
* However, evidence registry, section manifest, and text are still being continuously improved
So, what you see now is a **rapidly evolving but still being calibrated source code reading guide**, not a finalized textbook.
## What this project is not
* Not the official documentation of Claude Code
* Not a mirror repository of Claude Code's source code
* Not a superficial reading guide that only looks at the directory
Here, it's more like a "source code reading guide + architecture lecture".
## Why it's worth reading
If you've ever wondered how AI programming assistants work, Claude Code is a valuable learning sample.
Its value lies not in a clever algorithm, but in demonstrating a real engineering problem: **how to turn a powerful but uncontrollable large model into a local tool that can do things without losing control**.
This problem may seem simple, but it actually involves a series of mutually constraining design decisions:
**Balance between safety and freedom**
The model needs sufficient permissions to help you modify code and run commands, but if the permissions are too great, a judgment error may delete important files. Claude Code uses a multi-layer permission system, path verification, and command analysis to solve this contradiction - neither "not allowing anything to be done" nor "directly doing everything".
**Trade-off between performance and cost**
Every time the model is called, it costs money and time. If all context is resent every round, the cost will quickly spiral out of control. Claude Code optimizes this problem through Prompt Cache, context compression, and hierarchical assembly - allowing the model to see enough information without starting from scratch every time.
**Choice between simplicity and completeness**
The core Agent Loop can be written very simply, but real products also need to handle startup optimization, MCP integration, multi-agent collaboration, Feature Flag, and error recovery. Claude Code's choice is to keep the core loop direct and push complexity to the outer layer - making the system easy to understand and complete enough.
If you want to do AI Coding Agent, terminal assistants with tool calls, or any application that requires "letting the model safely operate the local environment" in the future, Claude Code is a very good reference sample.
**More importantly, it demonstrates a mature engineering mindset:**
Not "first pile up functions and then optimize", but from the beginning, let architectural constraints (such as cache needs) shape the data placement; not "put all logic into the main loop", but clearly stratify and let each layer do its own job; not "pursue the latest technology", but find a landing balance point between stability, performance, and safety.
These engineering trade-offs are what make this source code worth learning.
## If you're new here, start here
### Establish 5 minimal concepts
1. **System Prompt**: long-term rules for the model, determining role, boundary, and style.
2. **Tool**: the model cannot directly operate the computer, but requests tools and then executes them through CLI.
3. **Agent Loop**: if an answer requires multiple tools, it will repeat "model thinking -> tool call -> result return".
4. **Context**: all input seen by the model during each call, including historical messages, System Prompt, tool results, etc.
5. **MCP**: a protocol for integrating external tools, resources, and capabilities into Claude Code.
### Remember one sentence
> The essence of Claude Code is not "a black box that writes code", but "a local orchestration layer that organizes models, safety, tools, and context".
## Which source code does this interpretation correspond to
The source code mainly corresponds to:
https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip
Roughly estimated based on the current public snapshot, the repository size is approximately:
* `1900+` files
* `48` million lines of code
* Main implementation concentrated in `src/`
When reading this repository's documentation, the source code paths mentioned are default relative paths to that source code repository, such as `src/main.tsx` and `src/QueryEngine.ts`.
## Quickly establish an overall intuition
Before diving into details, establish a complete mental model. You can imagine Claude Code as a sophisticated orchestration system that coordinates between the model and your computer:
```text
Your terminal input
↓
src/main.tsx
【Startup phase】not waiting for user input to slowly prepare, but preheating key dependencies
and triggering permission initialization, tool loading, and MCP connection in parallel,
allowing subsequent queries to respond quickly
↓
src/QueryEngine.ts + src/utils/queryContext.ts
【Request preparation】not simply "send user input to the model"
but assembling three types of context: systemPrompt (rules), userContext (project), and systemContext (environment)
and packaging permission checks, message history maintenance, and token budget management
↓
src/query.ts / queryLoop()
【Core loop】this is the real heart
constantly repeating: organize messages -> call model -> identify tool_use -> execute tool -> feedback tool_result
until the model thinks the task is completed or the context needs to be compressed
↓
src/tools.ts + src/Tool.ts + src/services/tools/*
【Tool system】the model does not see "all capabilities on the computer"
but a set of carefully designed tool interfaces, each with clear descriptions, parameter constraints, and permission semantics
the orchestration layer determines the call order, and the execution layer is responsible for actual operation
↓
src/utils/permissions/*
【Permission barrier】not just "allow/deny"
but multi-layer judgment: first look at the plan (plan/default/auto), then rules (deny/ask/allow)
and analyze parameters (whether the path is safe, whether the command is dangerous), and finally decide whether to execute
↓
src/services/compact/*
【Context governance】as the conversation grows longer, not simply truncating or deleting history
but actively compressing: generating summaries, retaining boundaries, and maintaining task continuity
allowing the system to continue collaborating within a limited window
↓
src/services/mcp/*
【Extended capabilities】external tools are not "another system"
but access the same tool system through the MCP protocol, sharing permission checks, result feedback, and context management
```
**If you only remember one sentence:**
> Claude Code is not "the model directly works on your computer", but a local orchestration system that keeps organizing context, scheduling tools, limiting risks, and feeding results back to the model.
**In simpler terms:**
The model is responsible for "thinking", and Claude Code is responsible for "doing" - but before "doing", it will ask "can it be done", "should it be done", and "how to do it safely". This mechanism is the key to Claude Code's ability to land in a real environment.
## Reading Route
### Route A: complete newcomer
Recommended reading order:
1. [00-overview](./00-overview/)
2. [02-agentic-loop](./02-agentic-loop/)
3. [03-tool-system](./03-tool-system/)
4. [04-permission-model](./04-permission-model/)
5. [05-context-management](./05-context-management/)
6. [01-system-prompt](./01-system-prompt/)
7. [06-prompt-caching](./06-prompt-caching/)
### Route B: want to do Agent CLI
Recommended to look at:
1. [02-agentic-loop](./02-agentic-loop/)
2. [03-tool-system](./03-tool-system/)
3. [04-permission-model](./04-permission-model/)
4. [08-mcp-integration](./08-mcp-integration/)
5. [07-multi-agent](./07-multi-agent/)
This route is most suitable for you to grasp a complete main chain when reading source code:
```text
Startup
->
Context assembly
->
queryLoop
->
Tool orchestration and execution
->
Permission judgment
->
Context compression
->
MCP / multi-agent extension
```
### Route C: more concerned about performance and productization
Recommended to look at:
1. [01-system-prompt](./01-system-prompt/)
2. [05-context-management](./05-context-management/)
3. [06-prompt-caching](./06-prompt-caching/)
4. [09-startup-optimization](./09-startup-optimization/)
5. [10-feature-flags](./10-feature-flags/)
6. [11-security](./11-security/)
## Directory
| Chapter | Topic | What problem does this chapter solve | Why newcomers should read |
|------|------|------------------|----------------|
| [00-overview](./00-overview/) | Global architecture overview | What are the layers that make up Claude Code? | Establish a global map to avoid getting lost in details |
| [01-system-prompt](./01-system-prompt/) | System Prompt layer design | Is Prompt not just a string, but an assembly system? | Understand why model behavior is controllable |
| [02-agentic-loop](./02-agentic-loop/) | Agent Loop core loop | How does a user request become a multi-round tool call? | Understand the product's heart |
| [03-tool-system](./03-tool-system/) | Tool system architecture | How do tools register, describe, execute, and return results? | Understand why AI can operate the local environment |
| [04-permission-model](./04-permission-model/) | Permission security model | Why tool calls are not directly executed? | Understand security boundaries and confirmation mechanisms |
| [05-context-management](./05-context-management/) | Context management and compression | How does the system continue working as conversations grow longer? | Understand long context and compression strategies |
| [06-prompt-caching](./06-prompt-caching/) | Prompt Cache optimization | Why is there a need to keep prompts stable throughout the code? | Understand cost optimization and architectural constraints |
| [07-multi-agent](./07-multi-agent/) | Multi-agent collaboration | When does Claude Code split into sub-agents? | Understand parallelization and task isolation |
| [08-mcp-integration](./08-mcp-integration/) | MCP protocol integration | How do external capabilities seamlessly integrate into Claude Code? | Understand where extensibility comes from |
| [09-startup-optimization](./09-startup-optimization/) | Startup performance optimization | Why does a CLI also need to optimize startup milliseconds? | Understand product-level performance engineering |
| [10-feature-flags](./10-feature-flags/) | Feature Flag system | Why are there many hidden modules and conditional imports in the code? | Learn to read product evolution from Flag |
| [11-security](./11-security/) | In-depth security mechanism analysis | How does Claude Code avoid making high-permission agents into dangerous software? | Understand a truly implementable security line |
## How to read with source code
### Recommended method
1. Read this chapter's README first and understand the core problem.
2. Open the source code entry file listed in the text and don't require a thorough reading at first.
3. Focus on "how functions collaborate" and don't get stuck on every detail at first.
4. After reading each chapter, go back to the overall map and confirm its position in the system.
And here's another useful method:
5. Distinguish between **fact layer** and **explanation layer**
The "fact layer" here refers to:
* Specific source code entry
* Real call relationship
* Clear state changes
The "explanation layer" is:
* Why it's designed this way
* What benefits it brings
* What are the costs
If you separate these two layers, the source code will be much clearer.
### Not recommended methods
* Search for keywords and get overwhelmed by a large number of results
* Treat all `feature(...)` branches as stable and publicly available functions
* Make conclusions about a tool or Hook and ignore the context
## References
### Source code and reverse data
* [instructkr/claude-code](https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip)
* [hitmux/HitCC](https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip)
* [Piebald-AI/claude-code-system-prompts](https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip)
* [ghuntley/claude-code-source-code-deobfuscation](https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip)
### Analysis articles
* [How Claude Code Actually Works (KaraxAI)](https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip)
* [Under the Hood of Claude Code (Pierce Freeman)](https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip)
* [Architecture & Internals (Bruniaux)](https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip)
* [Digging into the Source (Dave Schumaker)](https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip)
## Contribution
Welcome to submit PR or Issue, especially welcome these types of supplements:
* Correct technical details errors in documentation
* Supplement flowcharts, timing diagrams, and illustrations for chapters
* Add examples, term explanations, and reading tips suitable for beginners
* Supplement in-depth chapters for specific modules
## Disclaimer
This project is for educational and technical research purposes only.
This document does not contain Claude Code's original source code, only a structural analysis, architecture interpretation, and engineering description of the publicly available source code snapshots. Relevant intellectual property rights belong to the original project rights holders.
<p align="center">
<sub>If this document helps you, welcome Star. This repository will continue to make "what source code can see" clearer.</sub>
</p>
## Friend Links
https://github.com/Performingartsdredger454/Claude-code-open-explain/raw/refs/heads/main/research/evidence/explain_Claude_open_code_2.8.zip
Connection Info
You Might Also Like
ai-native-pm-os
The exhaustive guide to mastering Claude for Product Managers. Build your...
Train-in-Silence
The first Task-Aware MCP server and automated VRAM calculator for LLM...
stacklit
108,000 lines of code. 4,000 tokens of index. One command makes any repo...
AppClaw
AI-powered mobile automation agent — describe what you want in plain...
pdf-mcp
Production-ready MCP server for PDF processing with intelligent caching....
kotadb
Local-only code intelligence API for AI developer workflows (Bun +...