From 4f9669a634a025189814ddd08e45ce770666ca5b Mon Sep 17 00:00:00 2001 From: Charles Cheng Date: Tue, 11 Aug 2026 10:19:05 +0800 Subject: [PATCH 1/6] fix(links): make chapter cross-links resolve on GitHub, not just the site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every cross-link inside docs/ was written as docs/.md. With docsify's relativePath disabled those resolved from the site root and worked on the published site, but in GitHub's file view they resolved to docs/docs/.md and 404'd — which is what anyone browsing or forking the repo actually hits. Switch relativePath on and rewrite the 56 chapter cross-links to same-directory relative paths, correct in both contexts. _sidebar.md and _home.md move to root-absolute paths, as relativePath requires. Also fixes a link in 12-Agent-Security-Design.md pointing at 13-啃完51万行源码的发现与Claude的封号机制.md, a name that stopped existing when chapter 13 was renamed — dead everywhere, not just on GitHub. --- _home.md | 49 +++++++++++++------ _sidebar.md | 26 +++++----- ...66\346\236\204\346\200\273\350\247\210.md" | 4 +- docs/02-Value-Debate.md | 6 +-- ...67\345\200\274\344\271\213\344\272\211.md" | 6 +-- docs/03-Agent-Loop.md | 10 ++-- "docs/03-Agent\345\276\252\347\216\257.md" | 10 ++-- docs/04-Context-Engineering.md | 4 +- ...13\346\226\207\345\267\245\347\250\213.md" | 4 +- docs/05-Compaction-System.md | 4 +- ...13\347\274\251\347\263\273\347\273\237.md" | 4 +- docs/06-Permission-System.md | 4 +- ...03\351\231\220\347\263\273\347\273\237.md" | 4 +- docs/07-Memory-System.md | 4 +- ...60\345\277\206\347\256\241\347\220\206.md" | 4 +- docs/08-Tools-and-Skills.md | 4 +- ...4\270\216Skill\347\263\273\347\273\237.md" | 4 +- docs/09-MCP-Integration.md | 4 +- "docs/09-MCP\351\233\206\346\210\220.md" | 4 +- docs/10-Future-Features.md | 4 +- ...37\350\203\275\350\223\235\345\233\276.md" | 4 +- docs/11-AI-Code-Review.md | 2 +- ...266\344\273\243\347\232\204Code-Review.md" | 2 +- docs/12-Agent-Security-Design.md | 4 +- ...11\345\205\250\350\256\276\350\256\241.md" | 4 +- docs/13-Source-Code-Findings.md | 2 +- ...00\344\272\233\345\217\221\347\216\260.md" | 2 +- index.html | 2 +- 28 files changed, 101 insertions(+), 84 deletions(-) diff --git a/_home.md b/_home.md index cf4da78..fd724f0 100644 --- a/_home.md +++ b/_home.md @@ -1,4 +1,4 @@ -[English](./README_EN.md) +[English](/README_EN.md) ![License](https://img.shields.io/badge/license-MIT-green) @@ -36,29 +36,29 @@ Sourcemap 是前端构建工具生成的调试辅助文件,记录了编译后 | 文档 | 内容 | |------|------| -| [01-架构总览](./docs/01-架构总览.md) | 整体架构、技术栈、核心文件、一次请求的完整旅程 | -| [02-源码泄露的价值之争](./docs/02-源码泄露的价值之争.md) | 产物 vs Harness 能力,两派观点分析,代码是快照能力是动态的 | +| [01-架构总览](/docs/01-架构总览.md) | 整体架构、技术栈、核心文件、一次请求的完整旅程 | +| [02-源码泄露的价值之争](/docs/02-源码泄露的价值之争.md) | 产物 vs Harness 能力,两派观点分析,代码是快照能力是动态的 | ### 核心模块篇 | 文档 | 内容 | |------|------| -| [03-Agent 循环](./docs/03-Agent循环.md) | 六阶段 ReAct 循环、AsyncGenerator 设计、状态管理、思维链保留 | -| [04-上下文工程](./docs/04-上下文工程.md) | System Prompt 构建、CLAUDE.md 加载、分层优先级、预取缓存、Prompt Cache 优化 | -| [05-消息压缩系统](./docs/05-消息压缩系统.md) | 三层压缩:微压缩、Session Memory、Full Compact,熔断器、递归保护 | -| [06-权限系统](./docs/06-权限系统.md) | 三模式权限、YOLO 分类器、42 条拦截规则、文件沙箱、Dangerous Rule Stripping | -| [07-记忆管理](./docs/07-记忆管理.md) | 五层记忆加载、@include 指令、MEMORY.md 管理、Session Memory | -| [08-工具与 Skill 系统](./docs/08-工具与Skill系统.md) | 40+ 工具注册、执行流水线、Pre/Post Hook、Skill fork 机制 | -| [09-MCP 集成](./docs/09-MCP集成.md) | 六种传输协议、OAuth、七种配置作用域 | +| [03-Agent 循环](/docs/03-Agent循环.md) | 六阶段 ReAct 循环、AsyncGenerator 设计、状态管理、思维链保留 | +| [04-上下文工程](/docs/04-上下文工程.md) | System Prompt 构建、CLAUDE.md 加载、分层优先级、预取缓存、Prompt Cache 优化 | +| [05-消息压缩系统](/docs/05-消息压缩系统.md) | 三层压缩:微压缩、Session Memory、Full Compact,熔断器、递归保护 | +| [06-权限系统](/docs/06-权限系统.md) | 三模式权限、YOLO 分类器、42 条拦截规则、文件沙箱、Dangerous Rule Stripping | +| [07-记忆管理](/docs/07-记忆管理.md) | 五层记忆加载、@include 指令、MEMORY.md 管理、Session Memory | +| [08-工具与 Skill 系统](/docs/08-工具与Skill系统.md) | 40+ 工具注册、执行流水线、Pre/Post Hook、Skill fork 机制 | +| [09-MCP 集成](/docs/09-MCP集成.md) | 六种传输协议、OAuth、七种配置作用域 | ### 前瞻篇 | 文档 | 内容 | |------|------| -| [10-未来功能蓝图](./docs/10-未来功能蓝图.md) | 82 个 feature flag 解析、Kairos 自主模式、Context Collapse、语音模式 | -| [11-AI Coding 时代的 Code Review](./docs/11-AI-Coding时代的Code-Review.md) | 个人/团队/CICD 三层 Review 范式、Review Agent 设想 | -| [12-从权限系统学 Agent 安全设计](./docs/12-从Claude%20Code权限系统学Agent安全设计.md) | 三层防御体系拆解、L0-L4 安全成熟度模型、落地建议 | -| [13-啃完源码之后的一些发现](./docs/13-啃完源码之后的一些发现.md) | AI 工程化短板、生产事故、Claude 封号机制分析 | +| [10-未来功能蓝图](/docs/10-未来功能蓝图.md) | 82 个 feature flag 解析、Kairos 自主模式、Context Collapse、语音模式 | +| [11-AI Coding 时代的 Code Review](/docs/11-AI-Coding时代的Code-Review.md) | 个人/团队/CICD 三层 Review 范式、Review Agent 设想 | +| [12-从权限系统学 Agent 安全设计](/docs/12-从Claude%20Code权限系统学Agent安全设计.md) | 三层防御体系拆解、L0-L4 安全成熟度模型、落地建议 | +| [13-啃完源码之后的一些发现](/docs/13-啃完源码之后的一些发现.md) | AI 工程化短板、生产事故、Claude 封号机制分析 | ## 关键数据 @@ -74,8 +74,25 @@ Sourcemap 是前端构建工具生成的调试辅助文件,记录了编译后 | 消息压缩阈值 | 上下文窗口 - 13,000 token | | npm 依赖 | 583 个包 | +## 版本覆盖范围 + +源码解读一定会过时,所以这里把「分析基于哪个快照」写清楚。 + +| 项 | 值 | +|---|---| +| 源码快照 | 2026-03-31 的 sourcemap 还原产物 | +| 该构建自报版本 | `2.1.888` | +| 章节内容最近复核 | 2026-04-24(v1.0.0) | +| 仓库最近维护 | 2026-08-11(v1.1.0) | + +上游改动导致某章描述失效,欢迎开 [版本漂移 issue](https://github.com/anneheartrecord/claude-code-docs/issues/new?template=version-drift.yml)。 + +## 参与贡献 + +最有价值的贡献不是加内容,是**指出哪里写错了**。事实纠错优先级最高,issue 7 天内首次回应,详见 [贡献指南](https://github.com/anneheartrecord/claude-code-docs/blob/main/CONTRIBUTING.md)。 + ## License -本仓库为技术分析文档,不包含 Claude Code 源码本身。分析内容基于公开可获取的 sourcemap 还原代码。 +[MIT](https://github.com/anneheartrecord/claude-code-docs/blob/main/LICENSE)。本仓库只包含原创技术分析文档,不再分发 Claude Code 源码本身。 -MIT +Claude 与 Claude Code 是 Anthropic PBC 的商标,本项目与 Anthropic 无从属或背书关系。 diff --git a/_sidebar.md b/_sidebar.md index d834964..232f374 100644 --- a/_sidebar.md +++ b/_sidebar.md @@ -1,20 +1,20 @@ - [首页](/) - **概览篇** - - [01-架构总览](docs/01-架构总览.md) - - [02-源码泄露的价值之争](docs/02-源码泄露的价值之争.md) + - [01-架构总览](/docs/01-架构总览.md) + - [02-源码泄露的价值之争](/docs/02-源码泄露的价值之争.md) - **核心模块篇** - - [03-Agent 循环](docs/03-Agent循环.md) - - [04-上下文工程](docs/04-上下文工程.md) - - [05-消息压缩系统](docs/05-消息压缩系统.md) - - [06-权限系统](docs/06-权限系统.md) - - [07-记忆管理](docs/07-记忆管理.md) - - [08-工具与 Skill 系统](docs/08-工具与Skill系统.md) - - [09-MCP 集成](docs/09-MCP集成.md) + - [03-Agent 循环](/docs/03-Agent循环.md) + - [04-上下文工程](/docs/04-上下文工程.md) + - [05-消息压缩系统](/docs/05-消息压缩系统.md) + - [06-权限系统](/docs/06-权限系统.md) + - [07-记忆管理](/docs/07-记忆管理.md) + - [08-工具与 Skill 系统](/docs/08-工具与Skill系统.md) + - [09-MCP 集成](/docs/09-MCP集成.md) - **前瞻篇** - - [10-未来功能蓝图](docs/10-未来功能蓝图.md) - - [11-AI Coding 时代的 Code Review](docs/11-AI-Coding时代的Code-Review.md) - - [12-从权限系统学 Agent 安全设计](docs/12-从Claude%20Code权限系统学Agent安全设计.md) - - [13-啃完源码之后的一些发现](docs/13-啃完源码之后的一些发现.md) + - [10-未来功能蓝图](/docs/10-未来功能蓝图.md) + - [11-AI Coding 时代的 Code Review](/docs/11-AI-Coding时代的Code-Review.md) + - [12-从权限系统学 Agent 安全设计](/docs/12-从Claude%20Code权限系统学Agent安全设计.md) + - [13-啃完源码之后的一些发现](/docs/13-啃完源码之后的一些发现.md) diff --git "a/docs/01-\346\236\266\346\236\204\346\200\273\350\247\210.md" "b/docs/01-\346\236\266\346\236\204\346\200\273\350\247\210.md" index 691009f..79aa503 100644 --- "a/docs/01-\346\236\266\346\236\204\346\200\273\350\247\210.md" +++ "b/docs/01-\346\236\266\346\236\204\346\200\273\350\247\210.md" @@ -1,4 +1,4 @@ -[English](docs/01-Architecture-Overview.md) +[English](01-Architecture-Overview.md) # 01 架构总览:Claude Code 到底是怎么跑起来的 @@ -229,4 +229,4 @@ Claude Code 的工程复杂度远超开源 Agent 框架。这是因为一个面 现在你对 Claude Code 的整体架构有了一个全貌认知。接下来我们逐个模块深入拆解。 -下一篇 [02-源码泄露的价值之争](docs/02-源码泄露的价值之争.md) 会聊聊这份代码到底值不值钱,以及 Harness Engineering 的真正壁垒在哪。 +下一篇 [02-源码泄露的价值之争](02-源码泄露的价值之争.md) 会聊聊这份代码到底值不值钱,以及 Harness Engineering 的真正壁垒在哪。 diff --git a/docs/02-Value-Debate.md b/docs/02-Value-Debate.md index 86b3637..82715a9 100644 --- a/docs/02-Value-Debate.md +++ b/docs/02-Value-Debate.md @@ -1,4 +1,4 @@ -[中文](docs/02-源码泄露的价值之争.md) +[中文](02-源码泄露的价值之争.md) # 02 The Value Debate: What Is Leaked Source Code Really Worth? @@ -74,7 +74,7 @@ Several are particularly noteworthy: These feature flags paint a clear picture: Anthropic is evolving Claude Code from a programming assistant into a **general-purpose autonomous Agent platform**. -**The future technical roadmap of one of the world's top AI Agent companies may be more valuable than the existing architecture itself.** See [10-Future Features](docs/10-Future-Features.md) for details. +**The future technical roadmap of one of the world's top AI Agent companies may be more valuable than the existing architecture itself.** See [10-Future Features](10-Future-Features.md) for details. ## 6️⃣ Summary @@ -90,4 +90,4 @@ But ultimately, **what is truly valuable is the Harness Engineering capability t --- -> Next: [03-Agent Loop](docs/03-Agent-Loop.md) +> Next: [03-Agent Loop](03-Agent-Loop.md) diff --git "a/docs/02-\346\272\220\347\240\201\346\263\204\351\234\262\347\232\204\344\273\267\345\200\274\344\271\213\344\272\211.md" "b/docs/02-\346\272\220\347\240\201\346\263\204\351\234\262\347\232\204\344\273\267\345\200\274\344\271\213\344\272\211.md" index 649255a..bca7d3d 100644 --- "a/docs/02-\346\272\220\347\240\201\346\263\204\351\234\262\347\232\204\344\273\267\345\200\274\344\271\213\344\272\211.md" +++ "b/docs/02-\346\272\220\347\240\201\346\263\204\351\234\262\347\232\204\344\273\267\345\200\274\344\271\213\344\272\211.md" @@ -1,4 +1,4 @@ -[English](docs/02-Value-Debate.md) +[English](02-Value-Debate.md) # 02 源码泄露的价值之争 @@ -82,7 +82,7 @@ Agent 领域也是如此。**代码是快照,能力是动态的。** 这些 feature flag 勾勒出了一幅清晰的图景:Anthropic 正在把 Claude Code 从一个编程助手,进化为一个 **通用型自主 Agent 平台**。 -**一家最顶尖 AI Agent 公司的未来技术蓝图,可能比现有的架构实现更有价值。** 详见 [10-未来功能蓝图](docs/10-未来功能蓝图.md)。 +**一家最顶尖 AI Agent 公司的未来技术蓝图,可能比现有的架构实现更有价值。** 详见 [10-未来功能蓝图](10-未来功能蓝图.md)。 ## 6️⃣ 总结 @@ -100,4 +100,4 @@ Agent 领域也是如此。**代码是快照,能力是动态的。** --- -> 下一篇:[03-Agent循环](docs/03-Agent循环.md) +> 下一篇:[03-Agent循环](03-Agent循环.md) diff --git a/docs/03-Agent-Loop.md b/docs/03-Agent-Loop.md index dc0bb52..d92a2d2 100644 --- a/docs/03-Agent-Loop.md +++ b/docs/03-Agent-Loop.md @@ -1,4 +1,4 @@ -[中文](docs/03-Agent循环.md) +[中文](03-Agent循环.md) # 03 The Agent Loop @@ -78,7 +78,7 @@ Another key design is **session-level caching**. This information rarely changes This stage assembles the complete request to send to the API. It is the **most information-dense** part of the entire loop. The request contains four core components: -**system prompt** provides the model with foundational instructions. It is dynamically assembled from multiple sources: built-in Agent behavior rules, user memory from CLAUDE.md, current Git repository status, and permission mode descriptions. This component's design is extremely refined. See [04-Context Engineering](docs/04-Context-Engineering.md) for details. +**system prompt** provides the model with foundational instructions. It is dynamically assembled from multiple sources: built-in Agent behavior rules, user memory from CLAUDE.md, current Git repository status, and permission mode descriptions. This component's design is extremely refined. See [04-Context Engineering](04-Context-Engineering.md) for details. **messages** is the complete conversation history. This includes messages sent by the user, the model's previous replies, and results from all prior tool calls. This is the model's **primary source of information** for understanding the current task's progress. @@ -118,7 +118,7 @@ tool_result appended to message history **Parallel execution** is an important performance optimization. If the model requests reading three files simultaneously, all three read operations proceed in parallel rather than queuing up one after another. For complex tasks, this can significantly reduce total wait time. -**Permission checking** is the core safety mechanism. Based on the current permission mode and the specific tool type, the system decides whether to execute directly, auto-approve, or show a confirmation dialog. See [06-Permission System](docs/06-Permission-System.md) for details. +**Permission checking** is the core safety mechanism. Based on the current permission mode and the specific tool type, the system decides whether to execute directly, auto-approve, or show a confirmation dialog. See [06-Permission System](06-Permission-System.md) for details. **Pre-Hook and Post-Hook** are interception points before and after tool execution. Pre-hooks can validate parameters and log operations; post-hooks can sanitize tool output and write audit logs. This **aspect-oriented** design separates the core tool execution logic from peripheral concerns, making the code easier to maintain. @@ -128,7 +128,7 @@ After each tool execution completes, the system checks whether the current **tok This stage addresses a practical problem: when an Agent handles complex tasks, it may loop dozens of times, appending new content to the message history each iteration. Without any cleanup, the message history continuously grows until it exceeds the model's context window limit, causing the Agent to crash. -Claude Code designed a three-tier progressive compaction strategy: **micro-compaction** clears detailed output from earlier tool calls, **Session Memory** persists key information to durable storage, and **Full Compact** compresses the entire conversation history into a summary. See [05-Compaction System](docs/05-Compaction-System.md) for specifics. +Claude Code designed a three-tier progressive compaction strategy: **micro-compaction** clears detailed output from earlier tool calls, **Session Memory** persists key information to durable storage, and **Full Compact** compresses the entire conversation history into a summary. See [05-Compaction System](05-Compaction-System.md) for specifics. ### Stage 6: Continue Decision @@ -213,4 +213,4 @@ This loop's design reveals a core reality of current Agent engineering: **model --- -> Next: [04-Context Engineering](docs/04-Context-Engineering.md) +> Next: [04-Context Engineering](04-Context-Engineering.md) diff --git "a/docs/03-Agent\345\276\252\347\216\257.md" "b/docs/03-Agent\345\276\252\347\216\257.md" index 10e52bb..f57b6f6 100644 --- "a/docs/03-Agent\345\276\252\347\216\257.md" +++ "b/docs/03-Agent\345\276\252\347\216\257.md" @@ -1,4 +1,4 @@ -[English](docs/03-Agent-Loop.md) +[English](03-Agent-Loop.md) # 03 Agent 循环 @@ -82,7 +82,7 @@ Claude Code 的每一次循环迭代被分成了六个阶段。你可以把它 这个阶段负责组装发送给 API 的完整请求,是整个循环中 **信息密度最高** 的环节。请求包含四个核心部分: -**system prompt** 是给模型的基础指令。它由多个来源动态拼接而成:内置的 Agent 行为规则、CLAUDE.md 中的用户记忆、当前 Git 仓库的状态信息、权限模式的描述。这一块的设计非常精细,详见 [04-上下文工程](docs/04-上下文工程.md)。 +**system prompt** 是给模型的基础指令。它由多个来源动态拼接而成:内置的 Agent 行为规则、CLAUDE.md 中的用户记忆、当前 Git 仓库的状态信息、权限模式的描述。这一块的设计非常精细,详见 [04-上下文工程](04-上下文工程.md)。 **messages** 是完整的对话历史。包括用户发送的消息、模型之前的回复、以及之前所有工具调用的结果。这是模型理解当前任务进展的 **核心信息来源**。 @@ -124,7 +124,7 @@ tool_result 追加到消息历史 其中 **并行执行** 是一个重要的性能优化。如果模型同时请求读取三个文件,这三个读取操作会并行进行,而不是一个一个排队等待。对于复杂任务,这可以显著减少总等待时间。 -**权限检查** 是安全的核心保障。根据当前的权限模式和具体的工具类型,系统决定是直接执行、自动放行还是弹出确认对话框。详见 [06-权限系统](docs/06-权限系统.md)。 +**权限检查** 是安全的核心保障。根据当前的权限模式和具体的工具类型,系统决定是直接执行、自动放行还是弹出确认对话框。详见 [06-权限系统](06-权限系统.md)。 **Pre-Hook 和 Post-Hook** 是工具执行前后的拦截点。前置钩子可以校验参数、记录日志;后置钩子可以清洗工具返回的结果、写入审计日志。这种 **面向切面** 的设计让工具执行的核心逻辑和周边逻辑分离,代码更容易维护。 @@ -134,7 +134,7 @@ tool_result 追加到消息历史 这个阶段解决的是一个现实问题:Agent 在处理复杂任务时,可能会循环几十轮,每一轮都会往消息历史中追加新的内容。如果不做任何清理,消息历史会不断膨胀,最终超过模型的上下文窗口限制,导致 Agent 崩溃。 -Claude Code 设计了三层递进的压缩策略:**微压缩** 清理掉早期工具调用的详细输出,**Session Memory** 把关键信息沉淀到持久化存储,**Full Compact** 把整段对话历史压缩成一份摘要。具体细节见 [05-消息压缩系统](docs/05-消息压缩系统.md)。 +Claude Code 设计了三层递进的压缩策略:**微压缩** 清理掉早期工具调用的详细输出,**Session Memory** 把关键信息沉淀到持久化存储,**Full Compact** 把整段对话历史压缩成一份摘要。具体细节见 [05-消息压缩系统](05-消息压缩系统.md)。 ### 阶段六:继续决策 @@ -223,4 +223,4 @@ Claude Code 的 Agent 循环本质上做了一件事:**把一个无状态的 --- -> 下一篇:[04-上下文工程](docs/04-上下文工程.md) +> 下一篇:[04-上下文工程](04-上下文工程.md) diff --git a/docs/04-Context-Engineering.md b/docs/04-Context-Engineering.md index d0b3fea..fd14708 100644 --- a/docs/04-Context-Engineering.md +++ b/docs/04-Context-Engineering.md @@ -1,4 +1,4 @@ -[中文](docs/04-上下文工程.md) +[中文](04-上下文工程.md) # 04 Context Engineering @@ -167,4 +167,4 @@ Claude Code's intensity of investment in this area, in terms of both code volume --- -> Next: [05-Compaction System](docs/05-Compaction-System.md) +> Next: [05-Compaction System](05-Compaction-System.md) diff --git "a/docs/04-\344\270\212\344\270\213\346\226\207\345\267\245\347\250\213.md" "b/docs/04-\344\270\212\344\270\213\346\226\207\345\267\245\347\250\213.md" index f55fedf..c02cfa6 100644 --- "a/docs/04-\344\270\212\344\270\213\346\226\207\345\267\245\347\250\213.md" +++ "b/docs/04-\344\270\212\344\270\213\346\226\207\345\267\245\347\250\213.md" @@ -1,4 +1,4 @@ -[English](docs/04-Context-Engineering.md) +[English](04-Context-Engineering.md) # 04 上下文工程 @@ -177,4 +177,4 @@ Claude Code 在这个领域的投入强度,从代码量和设计精细度上 --- -> 下一篇:[05-消息压缩系统](docs/05-消息压缩系统.md) +> 下一篇:[05-消息压缩系统](05-消息压缩系统.md) diff --git a/docs/05-Compaction-System.md b/docs/05-Compaction-System.md index bd64140..968d0b3 100644 --- a/docs/05-Compaction-System.md +++ b/docs/05-Compaction-System.md @@ -1,4 +1,4 @@ -[中文](docs/05-消息压缩系统.md) +[中文](05-消息压缩系统.md) # 05 Compaction System @@ -217,4 +217,4 @@ Claude Code's approach ranks highest in both information retention and engineeri --- -Next: [06-Permission-System](docs/06-Permission-System.md) +Next: [06-Permission-System](06-Permission-System.md) diff --git "a/docs/05-\346\266\210\346\201\257\345\216\213\347\274\251\347\263\273\347\273\237.md" "b/docs/05-\346\266\210\346\201\257\345\216\213\347\274\251\347\263\273\347\273\237.md" index 5371073..ff111fd 100644 --- "a/docs/05-\346\266\210\346\201\257\345\216\213\347\274\251\347\263\273\347\273\237.md" +++ "b/docs/05-\346\266\210\346\201\257\345\216\213\347\274\251\347\263\273\347\273\237.md" @@ -1,4 +1,4 @@ -[English](docs/05-Compaction-System.md) +[English](05-Compaction-System.md) # 05 消息压缩系统 @@ -228,4 +228,4 @@ Claude Code 的方案在信息保留度和工程复杂度上都是最高的, --- -下一篇:[06-权限系统](docs/06-权限系统.md) +下一篇:[06-权限系统](06-权限系统.md) diff --git a/docs/06-Permission-System.md b/docs/06-Permission-System.md index 790af4f..84bb9ce 100644 --- a/docs/06-Permission-System.md +++ b/docs/06-Permission-System.md @@ -1,4 +1,4 @@ -[中文](docs/06-权限系统.md) +[中文](06-权限系统.md) # 06 Permission System @@ -184,4 +184,4 @@ Claude Code's permission system surpasses competitors in both depth and breadth. --- -Next: [07-Memory-System](docs/07-Memory-System.md) +Next: [07-Memory-System](07-Memory-System.md) diff --git "a/docs/06-\346\235\203\351\231\220\347\263\273\347\273\237.md" "b/docs/06-\346\235\203\351\231\220\347\263\273\347\273\237.md" index 9864450..9d877df 100644 --- "a/docs/06-\346\235\203\351\231\220\347\263\273\347\273\237.md" +++ "b/docs/06-\346\235\203\351\231\220\347\263\273\347\273\237.md" @@ -1,4 +1,4 @@ -[English](docs/06-Permission-System.md) +[English](06-Permission-System.md) # 06 权限系统 @@ -199,4 +199,4 @@ Claude Code 的权限系统在深度和广度上都远超同类产品。这种 --- -下一篇:[07-记忆管理](docs/07-记忆管理.md) +下一篇:[07-记忆管理](07-记忆管理.md) diff --git a/docs/07-Memory-System.md b/docs/07-Memory-System.md index ac7ddf8..c312eac 100644 --- a/docs/07-Memory-System.md +++ b/docs/07-Memory-System.md @@ -1,4 +1,4 @@ -[中文](docs/07-记忆管理.md) +[中文](07-记忆管理.md) # 07 Memory System @@ -169,4 +169,4 @@ Claude Code clearly leads the industry in memory system design. The five-layer l --- -Next: [08-Tools-and-Skills](docs/08-Tools-and-Skills.md) +Next: [08-Tools-and-Skills](08-Tools-and-Skills.md) diff --git "a/docs/07-\350\256\260\345\277\206\347\256\241\347\220\206.md" "b/docs/07-\350\256\260\345\277\206\347\256\241\347\220\206.md" index 36cac77..e74255f 100644 --- "a/docs/07-\350\256\260\345\277\206\347\256\241\347\220\206.md" +++ "b/docs/07-\350\256\260\345\277\206\347\256\241\347\220\206.md" @@ -1,4 +1,4 @@ -[English](docs/07-Memory-System.md) +[English](07-Memory-System.md) # 07 记忆管理 @@ -181,4 +181,4 @@ Claude Code 在记忆系统的设计上明显领先于同类产品。五层加 --- -下一篇:[08-工具与Skill系统](docs/08-工具与Skill系统.md) +下一篇:[08-工具与Skill系统](08-工具与Skill系统.md) diff --git a/docs/08-Tools-and-Skills.md b/docs/08-Tools-and-Skills.md index 81adac0..cfb3be9 100644 --- a/docs/08-Tools-and-Skills.md +++ b/docs/08-Tools-and-Skills.md @@ -1,4 +1,4 @@ -[中文](docs/08-工具与Skill系统.md) +[中文](08-工具与Skill系统.md) # 08 Tools and Skills @@ -221,4 +221,4 @@ All these design choices point in the same direction: **making the Agent more re Claude Code clearly leads in tool system completeness. However, more tools also mean a higher probability of the model picking the wrong one. Anthropic mitigates this through carefully crafted tool descriptions and usage guidelines in the system prompt, but this remains an area of ongoing optimization. -Next: [09-MCP Integration](docs/09-MCP集成.md) +Next: [09-MCP Integration](09-MCP集成.md) diff --git "a/docs/08-\345\267\245\345\205\267\344\270\216Skill\347\263\273\347\273\237.md" "b/docs/08-\345\267\245\345\205\267\344\270\216Skill\347\263\273\347\273\237.md" index bb5aa69..9a43f17 100644 --- "a/docs/08-\345\267\245\345\205\267\344\270\216Skill\347\263\273\347\273\237.md" +++ "b/docs/08-\345\267\245\345\205\267\344\270\216Skill\347\263\273\347\273\237.md" @@ -1,4 +1,4 @@ -[English](docs/08-Tools-and-Skills.md) +[English](08-Tools-and-Skills.md) # 08 工具与 Skill 系统 @@ -235,4 +235,4 @@ Skill 系统设计了多层容量限制,防止 Skill 数量失控导致性能 Claude Code 在工具系统的完备性上明显领先。但也要看到,工具越多,模型选错工具的概率也越高。Anthropic 通过精心设计的工具描述和 system prompt 中的使用指南来缓解这个问题,但这依然是一个持续优化的方向。 -下一篇:[09-MCP 集成](docs/09-MCP集成.md) +下一篇:[09-MCP 集成](09-MCP集成.md) diff --git a/docs/09-MCP-Integration.md b/docs/09-MCP-Integration.md index 63483ad..91af767 100644 --- a/docs/09-MCP-Integration.md +++ b/docs/09-MCP-Integration.md @@ -1,4 +1,4 @@ -[中文](docs/09-MCP集成.md) +[中文](09-MCP集成.md) # 09 MCP Integration @@ -126,4 +126,4 @@ But MCP also faces challenges. The protocol itself is still evolving rapidly, an For developers, investing time in learning and using MCP now is worthwhile. **It represents the direction of AI tool ecosystems: standardized, composable, and securely controllable.** -Next: [10-Future Features](docs/10-未来功能蓝图.md) +Next: [10-Future Features](10-未来功能蓝图.md) diff --git "a/docs/09-MCP\351\233\206\346\210\220.md" "b/docs/09-MCP\351\233\206\346\210\220.md" index 385c991..3738193 100644 --- "a/docs/09-MCP\351\233\206\346\210\220.md" +++ "b/docs/09-MCP\351\233\206\346\210\220.md" @@ -1,4 +1,4 @@ -[English](docs/09-MCP-Integration.md) +[English](09-MCP-Integration.md) # 09 MCP 集成 @@ -138,4 +138,4 @@ MCP 的行业影响正在扩大。除了 Claude Code,VS Code 的 GitHub Copilo 对于开发者来说,现在投入精力学习和使用 MCP 是值得的。**它代表了 AI 工具生态的发展方向:标准化、可组合、安全可控。** -下一篇:[10-未来功能蓝图](docs/10-未来功能蓝图.md) +下一篇:[10-未来功能蓝图](10-未来功能蓝图.md) diff --git a/docs/10-Future-Features.md b/docs/10-Future-Features.md index 1116ce6..889af46 100644 --- a/docs/10-Future-Features.md +++ b/docs/10-Future-Features.md @@ -1,4 +1,4 @@ -[中文](docs/10-未来功能蓝图.md) +[中文](10-未来功能蓝图.md) # 10 Future Features Roadmap @@ -198,4 +198,4 @@ The code is scattered with production lesson annotations prefixed by **BQ**. The For engineers building AI Agent systems, **these production lessons are more practically valuable than any design patterns textbook.** -Next: [11-AI Code Review](docs/11-AI-Coding时代的Code-Review.md) +Next: [11-AI Code Review](11-AI-Coding时代的Code-Review.md) diff --git "a/docs/10-\346\234\252\346\235\245\345\212\237\350\203\275\350\223\235\345\233\276.md" "b/docs/10-\346\234\252\346\235\245\345\212\237\350\203\275\350\223\235\345\233\276.md" index 00cd91a..2fa81db 100644 --- "a/docs/10-\346\234\252\346\235\245\345\212\237\350\203\275\350\223\235\345\233\276.md" +++ "b/docs/10-\346\234\252\346\235\245\345\212\237\350\203\275\350\223\235\345\233\276.md" @@ -1,4 +1,4 @@ -[English](docs/10-Future-Features.md) +[English](10-Future-Features.md) # 10 未来功能蓝图 @@ -208,4 +208,4 @@ Workflow Scripts 让用户把经过验证的工作流固化下来:第一步做 对于正在构建 AI Agent 系统的工程师来说,**这些生产教训比任何设计模式书籍都更有实践价值。** -下一篇:[11-AI Coding 时代的 Code Review](docs/11-AI-Coding时代的Code-Review.md) +下一篇:[11-AI Coding 时代的 Code Review](11-AI-Coding时代的Code-Review.md) diff --git a/docs/11-AI-Code-Review.md b/docs/11-AI-Code-Review.md index 06baec9..2d0a426 100644 --- a/docs/11-AI-Code-Review.md +++ b/docs/11-AI-Code-Review.md @@ -1,4 +1,4 @@ -[中文](docs/11-AI-Coding时代的Code-Review.md) +[中文](11-AI-Coding时代的Code-Review.md) # 11 Code Review in the AI Coding Era diff --git "a/docs/11-AI-Coding\346\227\266\344\273\243\347\232\204Code-Review.md" "b/docs/11-AI-Coding\346\227\266\344\273\243\347\232\204Code-Review.md" index 1e07470..61a6999 100644 --- "a/docs/11-AI-Coding\346\227\266\344\273\243\347\232\204Code-Review.md" +++ "b/docs/11-AI-Coding\346\227\266\344\273\243\347\232\204Code-Review.md" @@ -1,4 +1,4 @@ -[English](docs/11-AI-Code-Review.md) +[English](11-AI-Code-Review.md) # 11 AI Coding 时代的 Code Review diff --git a/docs/12-Agent-Security-Design.md b/docs/12-Agent-Security-Design.md index 4353e04..350de19 100644 --- a/docs/12-Agent-Security-Design.md +++ b/docs/12-Agent-Security-Design.md @@ -1,4 +1,4 @@ -[中文](docs/12-从Claude Code权限系统学Agent安全设计.md) +[中文](12-从Claude Code权限系统学Agent安全设计.md) # 12 Learning Agent Security Design from Claude Code's Permission System @@ -142,4 +142,4 @@ Claude Code achieved L4. Most open-source Agents are still at L0. ## Next -[13 - Source Code Findings and Ban Mechanism](docs/13-啃完51万行源码的发现与Claude的封号机制.md) +[13 - Source Code Findings and Ban Mechanism](13-Source-Code-Findings.md) diff --git "a/docs/12-\344\273\216Claude Code\346\235\203\351\231\220\347\263\273\347\273\237\345\255\246Agent\345\256\211\345\205\250\350\256\276\350\256\241.md" "b/docs/12-\344\273\216Claude Code\346\235\203\351\231\220\347\263\273\347\273\237\345\255\246Agent\345\256\211\345\205\250\350\256\276\350\256\241.md" index 205b087..c2ac044 100644 --- "a/docs/12-\344\273\216Claude Code\346\235\203\351\231\220\347\263\273\347\273\237\345\255\246Agent\345\256\211\345\205\250\350\256\276\350\256\241.md" +++ "b/docs/12-\344\273\216Claude Code\346\235\203\351\231\220\347\263\273\347\273\237\345\255\246Agent\345\256\211\345\205\250\350\256\276\350\256\241.md" @@ -1,4 +1,4 @@ -[English](docs/12-Agent-Security-Design.md) +[English](12-Agent-Security-Design.md) # 12 从 Claude Code 权限系统学 Agent 安全设计 @@ -154,4 +154,4 @@ Claude Code 做到了 L4。大部分开源 Agent 还在 L0。 ## 下一篇 -[13-啃完51万行源码的发现与 Claude 的封号机制](docs/13-啃完源码之后的一些发现.md) +[13-啃完源码之后的一些发现](13-啃完源码之后的一些发现.md) diff --git a/docs/13-Source-Code-Findings.md b/docs/13-Source-Code-Findings.md index 9390268..f60a056 100644 --- a/docs/13-Source-Code-Findings.md +++ b/docs/13-Source-Code-Findings.md @@ -1,4 +1,4 @@ -[中文](docs/13-啃完源码之后的一些发现.md) +[中文](13-啃完源码之后的一些发现.md) # 13 Findings from Devouring 510K Lines of Source Code, and Claude's Ban Mechanism diff --git "a/docs/13-\345\225\203\345\256\214\346\272\220\347\240\201\344\271\213\345\220\216\347\232\204\344\270\200\344\272\233\345\217\221\347\216\260.md" "b/docs/13-\345\225\203\345\256\214\346\272\220\347\240\201\344\271\213\345\220\216\347\232\204\344\270\200\344\272\233\345\217\221\347\216\260.md" index 0f66a53..364ecf4 100644 --- "a/docs/13-\345\225\203\345\256\214\346\272\220\347\240\201\344\271\213\345\220\216\347\232\204\344\270\200\344\272\233\345\217\221\347\216\260.md" +++ "b/docs/13-\345\225\203\345\256\214\346\272\220\347\240\201\344\271\213\345\220\216\347\232\204\344\270\200\344\272\233\345\217\221\347\216\260.md" @@ -1,4 +1,4 @@ -[English](docs/13-Source-Code-Findings.md) +[English](13-Source-Code-Findings.md) # 13 啃完 51 万行源码的发现,与 Claude 的封号机制 diff --git a/index.html b/index.html index 3f67bf0..8003f68 100644 --- a/index.html +++ b/index.html @@ -48,7 +48,7 @@ }, auto2top: true, coverpage: false, - relativePath: false, + relativePath: true, homepage: '_home.md', } From 8486a46a50c3a5aa938172858c46d3894ea5f7e4 Mon Sep 17 00:00:00 2001 From: Charles Cheng Date: Tue, 11 Aug 2026 10:19:06 +0800 Subject: [PATCH 2/6] chore: add the MIT LICENSE file the READMEs have always claimed Both READMEs have declared MIT since the first release but no LICENSE file was ever committed, so GitHub showed the repo as unlicensed. Adds a scope note making explicit that no Claude Code source is redistributed here and that quoted excerpts remain their owners'. Also stops tracking .idea/. --- .gitignore | 12 ++++++++++++ .idea/.gitignore | 8 -------- .idea/claude-code-anatomy.iml | 9 --------- .idea/modules.xml | 8 -------- .idea/vcs.xml | 6 ------ LICENSE | 31 +++++++++++++++++++++++++++++++ 6 files changed, 43 insertions(+), 31 deletions(-) create mode 100644 .gitignore delete mode 100644 .idea/.gitignore delete mode 100644 .idea/claude-code-anatomy.iml delete mode 100644 .idea/modules.xml delete mode 100644 .idea/vcs.xml create mode 100644 LICENSE diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6e1ff48 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +# IDE +.idea/ +.vscode/ +*.iml + +# OS +.DS_Store +Thumbs.db + +# Editor scratch +*.swp +*~ diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b8..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/.idea/claude-code-anatomy.iml b/.idea/claude-code-anatomy.iml deleted file mode 100644 index 5e764c4..0000000 --- a/.idea/claude-code-anatomy.iml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 79228e1..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1dd..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7edddca --- /dev/null +++ b/LICENSE @@ -0,0 +1,31 @@ +MIT License + +Copyright (c) 2026 Charles Cheng (@anneheartrecord) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Scope note + +This repository contains original technical analysis and documentation only. +It does not redistribute Claude Code source code. Short code excerpts quoted +inside the chapters are used for commentary and analysis, and remain the +property of their respective owners. "Claude" and "Claude Code" are trademarks +of Anthropic PBC; this project is not affiliated with or endorsed by Anthropic. From a0ee9ed7930e07610210841efc708a4f8dadac28 Mon Sep 17 00:00:00 2001 From: Charles Cheng Date: Tue, 11 Aug 2026 10:19:06 +0800 Subject: [PATCH 3/6] feat(ci): check links and bilingual parity on every push MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit check_links.py validates every local link and enforces the per-context convention, so the class of bug fixed two commits back cannot come back silently. check_bilingual.py pairs chapters by number and flags any that exist in one language only or whose two sides have drifted apart in size. Runs on push, on pull requests, and weekly — rot arrives without anyone touching the repo. --- .github/workflows/docs-check.yml | 26 +++++++ scripts/check_bilingual.py | 72 +++++++++++++++++++ scripts/check_links.py | 114 +++++++++++++++++++++++++++++++ 3 files changed, 212 insertions(+) create mode 100644 .github/workflows/docs-check.yml create mode 100755 scripts/check_bilingual.py create mode 100755 scripts/check_links.py diff --git a/.github/workflows/docs-check.yml b/.github/workflows/docs-check.yml new file mode 100644 index 0000000..290c505 --- /dev/null +++ b/.github/workflows/docs-check.yml @@ -0,0 +1,26 @@ +name: docs-check + +on: + push: + branches: [main] + pull_request: + # Catch rot that arrives without anyone touching the repo. + schedule: + - cron: "0 2 * * 1" + workflow_dispatch: + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Validate links and link conventions + run: python3 scripts/check_links.py + + - name: Validate bilingual chapter parity + run: python3 scripts/check_bilingual.py diff --git a/scripts/check_bilingual.py b/scripts/check_bilingual.py new file mode 100755 index 0000000..de43a35 --- /dev/null +++ b/scripts/check_bilingual.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Check that every chapter exists in both Chinese and English. + +Chapters are paired by their numeric prefix: docs/04-上下文工程.md is the +Chinese side of docs/04-Context-Engineering.md. A chapter that exists in only +one language is a gap; a pair whose lengths diverge sharply usually means one +side received an update the other did not. + +Run from the repo root. Exits non-zero when a chapter is missing a language. +""" + +from __future__ import annotations + +import glob +import os +import re +import sys + +NUMBER = re.compile(r"^(\d{2})-") +# A chapter is the English side when its body is mostly ASCII. +CJK = re.compile(r"[一-鿿]") + +# Ratio beyond which the two sides are flagged as possibly out of sync. +DIVERGENCE = 1.6 + + +def language_of(path: str) -> str: + text = open(path, encoding="utf-8").read() + cjk = len(CJK.findall(text)) + return "zh" if cjk > len(text) * 0.05 else "en" + + +def main() -> int: + chapters: dict[str, dict[str, str]] = {} + for path in sorted(glob.glob("docs/*.md")): + match = NUMBER.match(os.path.basename(path)) + if not match: + continue + chapters.setdefault(match.group(1), {})[language_of(path)] = path + + missing: list[str] = [] + diverged: list[str] = [] + + for number, pair in sorted(chapters.items()): + if len(pair) < 2: + have = next(iter(pair)) + missing.append(f"chapter {number}: only {have} exists ({pair[have]})") + continue + zh_size = os.path.getsize(pair["zh"]) + en_size = os.path.getsize(pair["en"]) + # Chinese is denser per byte-normalized concept, so compare loosely. + ratio = max(zh_size, en_size) / max(1, min(zh_size, en_size)) + if ratio > DIVERGENCE: + diverged.append( + f"chapter {number}: {ratio:.2f}x size gap " + f"(zh {zh_size:,}B / en {en_size:,}B) — check they still agree" + ) + + if missing: + print(f"✗ {len(missing)} chapter(s) missing a language:\n") + print("\n".join(missing)) + if diverged: + print(f"\n⚠ {len(diverged)} chapter pair(s) may be out of sync:\n") + print("\n".join(diverged)) + if not missing and not diverged: + print(f"✓ {len(chapters)} chapters, both languages present and comparable") + + return 1 if missing else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check_links.py b/scripts/check_links.py new file mode 100755 index 0000000..356dc68 --- /dev/null +++ b/scripts/check_links.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""Validate every local Markdown and image link in the repo. + +The site runs docsify with `relativePath: true`, which means each context +resolves links differently. Getting it wrong produces links that work on the +published site but 404 on GitHub, or the reverse. The rules: + + docs/*.md cross-links are same-directory relative -> 04-上下文工程.md + _sidebar.md root-absolute -> /docs/04-上下文工程.md + _home.md root-absolute -> /docs/04-上下文工程.md + README*.md GitHub-relative -> ./docs/04-上下文工程.md + +Run from the repo root. Exits non-zero on any violation. +""" + +from __future__ import annotations + +import glob +import os +import re +import sys +import urllib.parse + +MD_LINK = re.compile(r"(? str: + """Replace code blocks and spans with spaces of equal length. + + Link syntax inside code is illustrative, not a link — the contributing + guide documents the link conventions by showing them. Blanking rather + than deleting keeps every offset intact so reported line numbers stay + correct. + """ + for pattern in (FENCE, CODE_SPAN): + text = pattern.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), text) + return text + + +def is_external(target: str) -> bool: + return target.startswith(("http://", "https://", "mailto:", "#")) + + +def resolve(source: str, target: str) -> str: + """Map a link to the repo-relative path it should point at on disk.""" + path = urllib.parse.unquote(target.split("#", 1)[0]) + if not path: + return "" + if path.startswith("/"): + return path.lstrip("/") + return os.path.normpath(os.path.join(os.path.dirname(source), path)) + + +def check_style(source: str, target: str) -> str | None: + """Return a message when a link works but uses the wrong convention.""" + if source.startswith("docs/") and target.startswith("docs/"): + return "chapter cross-links must be same-directory relative, not 'docs/...'" + if source in ROOT_PAGES and not target.startswith("/"): + return "sidebar/home links must be root-absolute, starting with '/'" + if source in README_PAGES and target.startswith("/"): + return "README links are read on GitHub, use './docs/...' not '/docs/...'" + return None + + +def main() -> int: + sources = sorted(glob.glob("docs/*.md")) + [ + p for p in (*ROOT_PAGES, *README_PAGES, "CONTRIBUTING.md", "CONTRIBUTING_EN.md") + if os.path.exists(p) + ] + + broken: list[str] = [] + style: list[str] = [] + checked = 0 + + for source in sources: + text = blank_code(open(source, encoding="utf-8").read()) + for pattern in (MD_LINK, IMG_LINK): + for match in pattern.finditer(text): + target = match.group(1).strip() + if is_external(target) or not target: + continue + checked += 1 + path = resolve(source, target) + if path and not os.path.exists(path): + line = text[: match.start()].count("\n") + 1 + broken.append(f"{source}:{line} -> {target}") + continue + problem = check_style(source, target) + if problem: + line = text[: match.start()].count("\n") + 1 + style.append(f"{source}:{line} -> {target}\n {problem}") + + if broken: + print(f"✗ {len(broken)} broken link(s):\n") + print("\n".join(broken)) + if style: + print(f"\n✗ {len(style)} link(s) using the wrong convention:\n") + print("\n".join(style)) + if broken or style: + print(f"\nchecked {checked} local links across {len(sources)} files") + return 1 + + print(f"✓ {checked} local links across {len(sources)} files, all resolve") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From ae1686fb7aa5a4a22e4173d978bf3fcd144eea79 Mon Sep 17 00:00:00 2001 From: Charles Cheng Date: Tue, 11 Aug 2026 10:19:06 +0800 Subject: [PATCH 4/6] docs: add contributing guide, code of conduct, and issue templates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit States what this repo actually wants — factual corrections over new content — and sets an evidence bar: a correction needs a source path plus symbol, reproducible steps, or official documentation. Separate templates for chapter corrections, version drift, and new chapter proposals, so drift reports carry the upstream version they were observed in. --- .github/ISSUE_TEMPLATE/chapter-correction.yml | 67 +++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 8 +++ .github/ISSUE_TEMPLATE/new-chapter.yml | 42 ++++++++++++ .github/ISSUE_TEMPLATE/version-drift.yml | 50 ++++++++++++++ .github/PULL_REQUEST_TEMPLATE.md | 32 +++++++++ CODE_OF_CONDUCT.md | 35 ++++++++++ CONTRIBUTING.md | 57 ++++++++++++++++ CONTRIBUTING_EN.md | 57 ++++++++++++++++ 8 files changed, 348 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/chapter-correction.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/new-chapter.yml create mode 100644 .github/ISSUE_TEMPLATE/version-drift.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 CONTRIBUTING_EN.md diff --git a/.github/ISSUE_TEMPLATE/chapter-correction.yml b/.github/ISSUE_TEMPLATE/chapter-correction.yml new file mode 100644 index 0000000..94b59ca --- /dev/null +++ b/.github/ISSUE_TEMPLATE/chapter-correction.yml @@ -0,0 +1,67 @@ +name: Chapter correction / 章节纠错 +description: A passage contradicts the actual source behavior, a number is wrong, or a module's responsibility is misdescribed +title: "[correction] " +labels: ["correction", "needs-triage"] +body: + - type: markdown + attributes: + value: | + Factual corrections are the highest-priority issue type here. A teardown that states something wrong gets quoted downstream as a conclusion, so thank you for catching it. + + 修正事实性错误是本仓库优先级最高的 issue。源码解读一旦写错,会被读者当结论引用。 + + - type: dropdown + id: chapter + attributes: + label: Chapter / 章节 + options: + - "01 — Architecture Overview / 架构总览" + - "02 — Value Debate / 源码泄露的价值之争" + - "03 — Agent Loop / Agent 循环" + - "04 — Context Engineering / 上下文工程" + - "05 — Compaction System / 消息压缩系统" + - "06 — Permission System / 权限系统" + - "07 — Memory System / 记忆管理" + - "08 — Tools and Skills / 工具与 Skill 系统" + - "09 — MCP Integration / MCP 集成" + - "10 — Future Features / 未来功能蓝图" + - "11 — AI Code Review / AI Coding 时代的 Code Review" + - "12 — Agent Security Design / 从权限系统学 Agent 安全设计" + - "13 — Source Code Findings / 啃完源码之后的一些发现" + validations: + required: true + + - type: input + id: language + attributes: + label: Which language version / 哪个语言版本 + description: Chinese, English, or both + placeholder: both + validations: + required: true + + - type: textarea + id: quote + attributes: + label: Quote the passage / 引用原文 + description: Copy the sentence or table row as it currently reads, and say which section it is in. + validations: + required: true + + - type: textarea + id: correction + attributes: + label: What it should say / 正确的描述是什么 + validations: + required: true + + - type: textarea + id: evidence + attributes: + label: Evidence / 证据 + description: | + Required. Any one of: a source file path plus symbol name, reproducible steps that demonstrate the behavior, or a link to official documentation. An issue without evidence will be sent back before it can be acted on. + + 必填。三者任一即可:源码文件路径 + 符号名 / 可复现的操作步骤 / 官方文档链接。没有证据的 issue 会被要求补充后才处理。 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..80824ae --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: true +contact_links: + - name: Read the docs online / 在线阅读 + url: https://anneheartrecord.github.io/claude-code-docs/ + about: The published site, with search across all 13 chapters. + - name: Contributing guide / 贡献指南 + url: https://github.com/anneheartrecord/claude-code-docs/blob/main/CONTRIBUTING.md + about: What corrections are wanted, and the evidence bar for a factual correction. diff --git a/.github/ISSUE_TEMPLATE/new-chapter.yml b/.github/ISSUE_TEMPLATE/new-chapter.yml new file mode 100644 index 0000000..8f2ac72 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new-chapter.yml @@ -0,0 +1,42 @@ +name: New chapter proposal / 新章节提议 +description: Propose a module or theme that deserves its own teardown +title: "[chapter] " +labels: ["new-chapter", "needs-triage"] +body: + - type: markdown + attributes: + value: | + Proposals are welcome; whole AI-generated chapters submitted as pull requests are not. Open this first so the scope and the angle can be agreed on. + + 欢迎提议新章节;但不接受直接提交 AI 生成的整章 PR。先开这个 issue,把范围和切入角度谈好。 + + - type: input + id: topic + attributes: + label: Topic / 主题 + validations: + required: true + + - type: textarea + id: why + attributes: + label: Why it deserves a chapter / 为什么值得单开一章 + description: What would a reader building an agent product be able to do afterward that they cannot do now? + validations: + required: true + + - type: textarea + id: scope + attributes: + label: What the chapter would cover / 章节大致覆盖什么 + description: Rough section list is enough. + validations: + required: true + + - type: checkboxes + id: overlap + attributes: + label: Overlap check / 重叠检查 + options: + - label: I have read the existing 13 chapters and this is not already covered + required: true diff --git a/.github/ISSUE_TEMPLATE/version-drift.yml b/.github/ISSUE_TEMPLATE/version-drift.yml new file mode 100644 index 0000000..4d60009 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/version-drift.yml @@ -0,0 +1,50 @@ +name: Version drift / 版本漂移 +description: Upstream changed, and a chapter now describes a mechanism that no longer exists +title: "[drift] " +labels: ["version-drift", "needs-triage"] +body: + - type: markdown + attributes: + value: | + The analysis was performed against a specific source snapshot — see the version coverage table in the README. Upstream moves; chapters go stale. Reporting drift is how this stays honest. + + 本仓库的分析基于某个特定的源码快照(见 README 的版本覆盖表)。上游会变,章节会过时。报告漂移是这份文档保持诚实的方式。 + + - type: input + id: chapter + attributes: + label: Chapter / 章节 + placeholder: "06 — Permission System" + validations: + required: true + + - type: textarea + id: described + attributes: + label: What the chapter describes / 章节里怎么写的 + validations: + required: true + + - type: textarea + id: actual + attributes: + label: What upstream does now / 上游现在的行为 + validations: + required: true + + - type: input + id: version + attributes: + label: Version you observed this in / 你观察到的版本 + description: Output of `claude --version`, or the npm version. + placeholder: "2.1.227" + validations: + required: true + + - type: textarea + id: evidence + attributes: + label: Evidence / 证据 + description: Source path plus symbol, reproducible steps, changelog entry, or official documentation. + validations: + required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..4665e06 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,32 @@ + + +## What this changes / 改了什么 + + + +## Type / 类型 + +- [ ] Factual correction / 事实纠错 +- [ ] Version drift update / 版本漂移更新 +- [ ] Translation or wording / 翻译与表述 +- [ ] Links, formatting, tooling / 链接、排版、工具链 +- [ ] New content / 新增内容 (discussed in an issue first / 已在 issue 中讨论过) + +## Evidence / 证据 + + + +## Checklist / 自检 + +- [ ] `python3 scripts/check_links.py` passes / 通过 +- [ ] `python3 scripts/check_bilingual.py` passes / 通过 +- [ ] Chinese and English sides both updated, if the change is factual / 事实性改动已中英双语同步 +- [ ] Commit messages follow Conventional Commits / commit message 符合 Conventional Commit +- [ ] This PR does one thing / 这个 PR 只解决一件事 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..0be498f --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,35 @@ +# Code of Conduct + +## Our pledge + +We as members, contributors, and maintainers pledge to make participation in this project a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our standards + +Behavior that contributes to a positive environment: + +- Correcting a factual error is welcome and encouraged; correcting it with evidence is what makes it useful. +- Disagreeing about a technical claim on the technical merits. +- Accepting a correction gracefully when your own claim turns out to be wrong. +- Being patient with contributors writing in their second language — this project is bilingual by design. + +Unacceptable behavior: + +- Harassment, insults, or derogatory comments, public or private. +- Personal or political attacks. +- Publishing others' private information without explicit permission. +- Any conduct that would reasonably be considered inappropriate in a professional setting. + +## Scope + +This Code of Conduct applies in all project spaces — issues, pull requests, discussions — and when an individual is representing the project in public spaces. + +## Enforcement + +Report unacceptable behavior by opening a private security advisory on this repository, or by contacting the maintainer through the address on their GitHub profile. All complaints will be reviewed and investigated promptly and fairly. The maintainer is obligated to respect the privacy and security of the reporter. + +Maintainers who do not follow or enforce this Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +Adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 2.1. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..e28bc05 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,57 @@ +[English](./CONTRIBUTING_EN.md) + +# 贡献指南 + +这是一个技术分析文档仓库。最有价值的贡献不是「加内容」,而是**指出哪里写错了**——源码解读一旦有事实性错误,会被读者当成结论直接引用。 + +## 我最需要的三类贡献 + +| 类型 | 说明 | 走哪条路 | +|---|---|---| +| **事实纠错** | 某段描述与源码实际行为不符、数字有误、模块职责搞反了 | 开 issue,用 `章节纠错` 模板 | +| **版本漂移** | 上游已变更,某章描述的机制已过时 | 开 issue,用 `版本漂移` 模板 | +| **翻译与表述** | 中英双语版本内容不一致、译文别扭、术语不统一 | 直接提 PR | + +不接受的:纯 typo 批量 PR(直接开 issue 我一次改完更快)、AI 生成的整章新内容、与 Agent 架构无关的话题。 + +## 事实纠错必须带证据 + +这是硬性要求。只说「我觉得不对」无法处理,issue 会被要求补充后才处理。一条合格的纠错至少包含: + +1. **章节与位置**:哪一篇、哪一节、原文怎么写的(引用原句)。 +2. **你认为的正确描述**。 +3. **证据**:源码文件路径 + 符号名 / 行为可复现的操作步骤 / 官方文档链接,三者任一。 + +## PR 流程 + +```bash +git checkout -b fix/<章节号>-<简述> +# 改完后自检 +python3 scripts/check_links.py +git commit -m "fix(docs): <说明>" +``` + +- commit message 用 Conventional Commit(`fix` / `docs` / `feat` / `chore`)。 +- **中英双语同步**:改了 `docs/04-上下文工程.md` 的事实性内容,就要同步改 `docs/04-Context-Engineering.md`,反之亦然。只改一边的 PR 我会打回。 +- 改完跑一次 `python3 scripts/check_links.py`,确保没有引入坏链。 +- 一个 PR 只解决一件事。 + +## 链接怎么写 + +站点用 docsify 且开了 `relativePath: true`,所以: + +- `docs/` **内部**互链用同目录相对路径:``[04-上下文工程](04-上下文工程.md)`` +- `_sidebar.md`、`_home.md` 用**根绝对路径**:``[01-架构总览](/docs/01-架构总览.md)`` +- `README.md` 是给 GitHub 看的,用 `./docs/xxx.md` + +写错会导致「站点能跳、GitHub 404」或反过来。`scripts/check_links.py` 会拦住。 + +## 维护节奏 + +- issue 我会在 **7 天内**给出首次回应(标记分类或要求补证据)。 +- 事实纠错类 issue 优先级最高。 +- 每次上游出现影响章节结论的重大变更,会开一个 tracking issue,合并后打 tag 发 release,见 [CHANGELOG.md](./CHANGELOG.md)。 + +## 行为准则 + +参与本项目即表示你同意遵守 [Code of Conduct](./CODE_OF_CONDUCT.md)。 diff --git a/CONTRIBUTING_EN.md b/CONTRIBUTING_EN.md new file mode 100644 index 0000000..92808ce --- /dev/null +++ b/CONTRIBUTING_EN.md @@ -0,0 +1,57 @@ +[中文](./CONTRIBUTING.md) + +# Contributing + +This is a technical analysis repository. The most valuable contribution is not adding content — it is **telling me where I got it wrong**. A factual error in a source-code teardown gets quoted downstream as a conclusion. + +## The three contributions I want most + +| Type | What it means | Where it goes | +|---|---|---| +| **Factual correction** | A passage contradicts actual source behavior, a number is wrong, a module's responsibility is misdescribed | Open an issue using the `Chapter correction` template | +| **Version drift** | Upstream changed; a chapter now describes a mechanism that no longer exists | Open an issue using the `Version drift` template | +| **Translation & wording** | The Chinese and English versions disagree, a translation reads awkwardly, terminology is inconsistent | Send a PR directly | + +Not accepted: bulk typo-only PRs (open one issue instead — faster for both of us), AI-generated whole new chapters, topics unrelated to agent architecture. + +## Corrections must carry evidence + +This is a hard requirement. "I think this is wrong" cannot be acted on and will be sent back for detail. A usable correction includes at least: + +1. **Chapter and location** — which document, which section, quote the original sentence. +2. **What you believe the correct description is.** +3. **Evidence** — a source file path plus symbol name, reproducible steps that show the behavior, or a link to official documentation. Any one of the three. + +## PR workflow + +```bash +git checkout -b fix/- +# after editing, self-check +python3 scripts/check_links.py +git commit -m "fix(docs): " +``` + +- Use Conventional Commits (`fix` / `docs` / `feat` / `chore`). +- **Keep both languages in sync.** If you change factual content in `docs/04-Context-Engineering.md`, update `docs/04-上下文工程.md` too, and vice versa. Single-language factual PRs will be sent back. +- Run `python3 scripts/check_links.py` before pushing. +- One PR, one concern. + +## How to write links + +The site runs docsify with `relativePath: true`, so: + +- Cross-links **inside** `docs/` use same-directory relative paths: ``[04-Context Engineering](04-Context-Engineering.md)`` +- `_sidebar.md` and `_home.md` use **root-absolute** paths: ``[01-Architecture Overview](/docs/01-Architecture-Overview.md)`` +- `README.md` is read on GitHub, so it uses `./docs/xxx.md` + +Getting this wrong produces links that work on the site but 404 on GitHub, or the reverse. `scripts/check_links.py` catches it. + +## Maintenance cadence + +- Issues get a first response **within 7 days** (triaged, or sent back for evidence). +- Factual corrections are the highest priority. +- When upstream changes something that invalidates a chapter's conclusion, a tracking issue is opened; once merged, a tag and release follow. See [CHANGELOG.md](./CHANGELOG.md). + +## Code of Conduct + +By participating you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md). From 520276dbef81c9f9a002c9d5ad808bf02c053dbe Mon Sep 17 00:00:00 2001 From: Charles Cheng Date: Tue, 11 Aug 2026 10:19:06 +0800 Subject: [PATCH 5/6] docs(01): bring the English architecture overview to parity The English chapter 01 was a 5.2 KB summary against 15 KB of Chinese, missing the source-leak background, what Claude Code is, how it differs from an agent framework, the six-step request journey, the industry comparison, and the key-numbers table. Chapter 01 is the entry point for every English reader. Translated from the existing Chinese analysis; no new claims, same numbers. Adds the four illustrations the Chinese side already had. --- docs/01-Architecture-Overview.md | 328 +++++++++++++++++++++---------- 1 file changed, 224 insertions(+), 104 deletions(-) diff --git a/docs/01-Architecture-Overview.md b/docs/01-Architecture-Overview.md index 34d95fc..86c73ae 100644 --- a/docs/01-Architecture-Overview.md +++ b/docs/01-Architecture-Overview.md @@ -1,121 +1,241 @@ -[中文](docs/01-架构总览.md) +[中文](01-架构总览.md) -# 01 Architecture Overview +# 01 Architecture Overview: How Claude Code Actually Runs -## One-Line Summary +## First, some background: how the source leaked -Claude Code is a ReAct Agent based on AsyncGenerator that interacts with users through a terminal UI. Its core loop is "build context → call API → execute tools → decide whether to continue." +In March 2026, someone noticed that the Claude Code client package published to npm shipped with sourcemap files. Sourcemaps exist for debugging — they record the mapping between bundled code and the original source. They should be excluded at publish time, but Anthropic's build pipeline missed that step. -## Tech Stack +Someone used the sourcemaps to reconstruct the complete TypeScript source: 515,000 lines across 2,766 files, the entire logic of the Claude Code client laid bare. -| Layer | Technology | -|---|------| -| Runtime | Bun 1.3.11+ | -| Language | TypeScript 6.0.2 | -| UI | React 19.2.4 + ink (terminal rendering) | -| CLI | Commander.js 14.0.0 | -| API | Anthropic SDK + AWS Bedrock + Azure + Vertex | -| Lint | Biome 2.4.10 | -| Bundler | Bun native bundler | +**Note that only the client-side code leaked.** Claude Code uses a textbook client-server split. The client runs in your terminal and handles user interaction, tool execution, permission management, and context assembly. The server is Anthropic's API, which handles model inference. The model itself and the server-side logic did not leak. -## Overall Architecture +The client code alone is valuable enough, because the competitive edge of an agent product does not live in the model call. It lives in **how you release the model's capability safely, efficiently, and reliably**. That is the domain of harness engineering, and the client code is a complete harness implementation. + +## What Claude Code is + +If you have never used it, thirty seconds of context. + +Claude Code is Anthropic's official AI programming assistant, positioned as a coding agent, running in your terminal. You type `claude` and land in a conversational interface. You ask in natural language for it to write code, edit code, read files, search the codebase, run commands, do research. It decides on its own which tool to use, which file to read, which command to run — like a colleague sitting next to you pair programming. + +Unlike the ChatGPT or Claude web chat box, Claude Code **operates your machine directly**. It reads and writes your filesystem, executes bash commands, and opens a browser to fetch pages. + +As a product its competitors are Cursor, Windsurf, and GitHub Copilot CLI. As an architecture it is a standard **ReAct agent**, and the core loop is: think → call a tool → observe the result → keep thinking. + +## Tech stack + +| Layer | Technology | Why this one | +|---|---|---| +| Runtime | Bun 1.3.11+ | Faster than Node.js, native TypeScript, bundler built in | +| Language | TypeScript 6.0.2 | Type safety — 515K lines is unmaintainable without a type system | +| Terminal UI | React 19.2.4 + ink | Renders the terminal interface with the React component model | +| CLI framework | Commander.js 14.0.0 | Mature command-line argument parsing | +| API | Anthropic SDK | Calls Claude models; also supports AWS Bedrock, Azure, and Vertex | +| Code quality | Biome 2.4.10 | Lint and format in one, faster than ESLint plus Prettier | + +## Overall architecture + +The whole picture first, then layer by layer. + +![Architecture layers](../imgs/01-arch-layer-stack.png) ``` -┌─────────────────────────────────────────────┐ -│ CLI Entry (cli.tsx) │ -│ Fast path: --version etc. return early │ -└────────────────┬────────────────────────────┘ - │ - ┌────────▼─────────┐ - │ Init (init.ts) │ - │ - Bootstrap │ - │ - Load config │ - │ - Prefetch context │ - └────────┬─────────┘ - │ - ┌───────────▼──────────────┐ - │ Commander CLI (main.tsx) │ - │ - Auth: login/logout │ - │ - Plugins: install/list │ - │ - MCP: add/remove │ - │ - Main logic: REPL/print │ - └───────────┬──────────────┘ - │ - ┌────────────▼─────────────────┐ - │ QueryEngine │ - │ - Session state machine │ - │ - Message history management │ - │ - Auto-compaction scheduling │ - │ - 20+ config parameters │ - └────────────┬─────────────────┘ - │ - ┌────────────▼─────────────────┐ - │ Query Loop (query.ts) │ - │ ┌──────────────────────┐ │ - │ │ 1. Prefetch context │ │ - │ │ 2. Build system prompt│ │ - │ │ 3. Stream API call │ │ - │ │ 4. Parse tool calls │ │ - │ │ 5. Permission + exec │ │ - │ │ 6. Compact + continue?│ │ - │ └──────────────────────┘ │ - └────────────┬─────────────────┘ - │ - ┌────────────▼──────────────────┐ - │ Tool Execution Layer (40+ tools) │ - │ Bash / File series / Web series │ - │ Agent / Skill / MCP / Task │ - └──────────────────────────────┘ +┌──────────────────────────────────────────────────────────┐ +│ User types in the terminal │ +└───────────────────────┬──────────────────────────────────┘ + │ +┌───────────────────────▼──────────────────────────────────┐ +│ CLI entry layer │ +│ cli.tsx → init.ts → main.tsx │ +│ Parses argv, initializes config, starts the REPL or │ +│ executes a single command │ +└───────────────────────┬──────────────────────────────────┘ + │ +┌───────────────────────▼──────────────────────────────────┐ +│ Session layer │ +│ QueryEngine.ts (1,300 lines) │ +│ Owns the conversation lifecycle, message history, and │ +│ auto-compaction scheduling. Effectively a session-level │ +│ state machine tracking 20+ config parameters │ +└───────────────────────┬──────────────────────────────────┘ + │ +┌───────────────────────▼──────────────────────────────────┐ +│ Agent core loop │ +│ query.ts (1,700 lines) │ +│ The full ReAct implementation: │ +│ prefetch → build prompt → call API → run tools → │ +│ compact → continue? │ +│ This is the heart of the system │ +└───────────┬───────────────────────┬──────────────────────┘ + │ │ +┌───────────▼──────────┐ ┌──────────▼───────────────────┐ +│ Permission system │ │ Tool execution layer │ +│ 6,300 lines/25 files │ │ 40+ tools │ +│ 3 modes + 42 rules │ │ Bash / File / Web / Agent │ +│ ML classifier + jail │ │ Skill / MCP / Task │ +└──────────────────────┘ └───────────────────────────────┘ + │ │ + └───────────┬───────────┘ + │ +┌───────────────────────▼──────────────────────────────────┐ +│ Context and memory layer │ +│ CLAUDE.md five-layer loading / MEMORY.md / Session Memory│ +│ Git status injection / Skill list / permission rules │ +│ Three-tier compaction: micro / Session Memory / full │ +└───────────────────────┬──────────────────────────────────┘ + │ +┌───────────────────────▼──────────────────────────────────┐ +│ API client layer │ +│ claude.ts (800+ lines) │ +│ Calls the Anthropic API with streaming output │ +│ Model fallback chain: Opus → Sonnet → Small │ +│ Retry logic, prompt cache optimization, multi-backend │ +└──────────────────────────────────────────────────────────┘ ``` -## Core File Reference +### How this differs from a general agent framework -| File | Lines | Responsibility | -|------|------|------| -| `src/query.ts` | 1,700 | Main query loop, streaming orchestration | -| `src/QueryEngine.ts` | 1,300 | Session state machine, 20+ config parameters | -| `src/main.tsx` | 5,000+ | CLI bootstrap, permission initialization | -| `src/Tool.ts` | 400+ | Tool interface definition | -| `src/tools.ts` | 300+ | Tool registry, feature flag control | -| `src/context.ts` | 200+ | Git status, context assembly | -| `src/services/api/claude.ts` | 800+ | API client, retry, model fallback | -| `src/utils/permissions/` | 6,300+ | Three-mode permission system | -| `src/services/compact/` | 26 files | Three-layer message compaction | -| `src/services/mcp/` | 12,000+ | MCP protocol integration | -| `src/utils/claudemd.ts` | 1,400+ | CLAUDE.md five-layer loading | +Most agent frameworks on the market — LangChain, AutoGen, CrewAI — are **libraries**. They hand you an API and you call it from your own code to build an agent. -## Data Flow +Claude Code is **a finished product**. Terminal UI, permission management, context engineering, message compaction: all implemented in-house, with no agent framework underneath. -A complete user request follows this path: +That means the code contains a lot of things an agent framework will never tell you: +- how to do real-time streaming rendering inside a terminal +- how to degrade gracefully when the user's network drops +- how to compact automatically when the context is nearly full +- how to prefetch in the background without the user noticing +- how to maximize prompt cache hit rate to hold cost down + +**Those engineering details are the most valuable part of this source.** + +## The complete journey of one request + +![The complete journey of one request](../imgs/01-arch-request-journey.png) + +What happens between typing a line in the terminal and seeing the agent reply? + +### Step 1: capture the input + +You type and hit enter. The REPL layer classifies what kind of input it is: + +- starts with `!` → **execute the shell command directly**, bypassing the agent. `! ls`, `! git status`. It is a shortcut so you can run a command without leaving Claude Code; output goes straight to the terminal +- starts with `/` → a **slash command** such as `/clear`, `/compact`, `/help`. These are built-in shortcuts the client handles itself +- otherwise → **natural language**, which enters the agent loop and goes to the model + +### Step 2: assemble the context + +Before calling the API the system assembles a complete context. That context determines what the model sees, knows, and can do. + +**The system prompt is concatenated from:** + +1. built-in agent behavior rules telling the model it is Claude Code, that it can read and write files and execute commands, and how it should interact with the user +2. the user's CLAUDE.md memory files, loaded across five priority layers from global to project to local +3. a snapshot of the current Git repository: branch, recent commits, which files changed +4. permission rules: which tools may run automatically and which need confirmation +5. the Skill list: the extension capabilities currently available + +All of it concatenated is the model's system prompt. This process is **context engineering**, and a later chapter covers it in detail. + +### Step 3: streaming API call + +With the request assembled, a streaming API call goes out through the Anthropic SDK. The model returns tokens one at a time and the client renders each one to the terminal as it arrives, so the user watches the model "type." + +If the model decides to call a tool, it emits a `tool_use` block in the response carrying the tool name and arguments. To read a file, it emits: + +```json +{ + "type": "tool_use", + "name": "Read", + "input": { "file_path": "/src/main.ts", "limit": 100 } +} ``` -User input - ↓ -REPL capture → Determine input type: !command (direct shell exec) / /slash command / natural language (Agent loop) - ↓ -QueryEngine.query() → Assemble system prompt + message history - ↓ -Query loop begins - ↓ -Prefetch: memory files, Skill list, Git status (skip if cache hit) - ↓ -Build API request: system prompt + messages + tools + thinking config - ↓ -Stream call to Anthropic API → Render tokens to terminal in real time - ↓ -Parse response: plain text → output directly | tool_use → enter tool execution - ↓ -Tool execution: Pre-Hook → Permission check → Parallel execution → Post-Hook - ↓ -Append tool_result to message history - ↓ -Compaction check: token usage over threshold? → Micro-compact / Session Memory / Full Compact - ↓ -Continue check: stop_reason === 'tool_use' → continue loop | 'end_turn' → finish - ↓ -Output final result -``` -## Was It Written by AI? +### Step 4: permission check and tool execution + +Once `tool_use` arrives, the permission check runs first: + +- hardcoded rules: 42 dangerous commands rejected outright, without asking +- ML classifier: judges whether this command is safe +- user rules: matched against the user's configured allow and deny lists +- confirmation prompt: when none of the above match, ask the user + +After the check passes the tool runs, and multiple tool calls can run in parallel. + +When execution finishes, the tool result is appended to the message history as `tool_result`. + +### Step 5: compaction check + +The total token count of the message history is checked. If it approaches the context window limit, compaction triggers: + +1. **Micro-compact**: clear out old tool outputs, the content whose relevance decays fastest +2. **Session Memory**: settle key information into memory files to free context space +3. **Full compact**: fork a separate agent to summarize everything, condensing the whole conversation history into one summary + +### Step 6: continue or stop + +Look at the `stop_reason` the API returned: + +- `tool_use`: the model wants another tool, so go back to step 3 and loop +- `end_turn`: the model considers the task complete, so stop +- `max_tokens`: output hit the ceiling and may need to continue + +A complex task can loop dozens of times. Ask Claude Code to refactor a module and it may read several files to understand the current state, edit the code, run the tests, find a failure, edit again, run again — each tool call is one turn of the loop. + +## Core file reference + +If you want to read the source yourself, this table will orient you: + +| File | Lines | What it does | When to read it | +|---|---|---|---| +| `src/query.ts` | 1,700 | Agent core loop, six-phase streaming orchestration | Understanding how the agent runs | +| `src/QueryEngine.ts` | 1,300 | Session state machine, 20+ config parameters | Understanding session management and config | +| `src/main.tsx` | 5,000+ | CLI entry, everything crammed in | Understanding the startup path | +| `src/context.ts` | 200+ | Git status injection, context assembly | Understanding context engineering | +| `src/utils/claudemd.ts` | 1,400+ | CLAUDE.md five-layer loading, @include | Understanding the memory system | +| `src/services/compact/` | 26 files | Three-tier message compaction | Understanding long-conversation management | +| `src/utils/permissions/` | 6,300+ | Three-mode permission system | Understanding the security design | +| `src/services/api/claude.ts` | 800+ | API client, retry, model fallback | Understanding the API layer | +| `src/tools.ts` | 300+ | Tool registry, feature flag control | Finding out which tools exist | +| `src/services/mcp/` | 12,000+ | MCP protocol integration | Understanding external tool integration | + +## Side by side with other agents + +![Side by side with other agents](../imgs/01-arch-industry-compare.png) + +| Dimension | Claude Code | Cursor | LangChain Agent | AutoGen | +|---|---|---|---|---| +| Form | Terminal CLI | IDE plugin | Python library | Python framework | +| Agent loop | In-house ReAct + AsyncGenerator | Not public | ReAct / Plan-and-Execute | GroupChat + Planner | +| Permissions | 6,300 lines, 3 modes + ML classifier | IDE-level sandbox | Essentially none | Essentially none | +| Context management | Three-tier compaction + prefetch cache + prompt cache optimization | Not public | Simple token truncation | None | +| Memory | Five-layer CLAUDE.md + MEMORY.md + Session Memory | Project-level index | Manual configuration | ConversableAgent memory | +| Tools | 40+ built in, plus Skill and MCP | Built in plus plugins | Register your own | Register your own | +| Codebase size | 515K lines | Not public | ~50K lines | ~30K lines | + +Claude Code's engineering complexity far exceeds that of the open-source agent frameworks. An agent product facing real users has to handle one to two orders of magnitude more edge cases than an agent framework does. + +## Key numbers + +![Capability dashboard](../imgs/01-arch-capability-dashboard.png) + +| Metric | Value | +|---|---| +| Codebase | 515,498 lines of TypeScript/TSX | +| Files | 2,766 | +| Build output | 25.89 MB, 5,344 modules | +| Built-in tools | 40+ | +| Feature flags | 82 | +| Permission rules | 42 hardcoded dangerous patterns | +| Compaction threshold | Context window − 13,000 tokens | +| npm dependencies | 583 packages | + +## Was it written by AI? + +Yes. All 20 commits come from `claude-code-best`, and three of them carry `Co-Authored-By: Claude Opus 4.6`. 515,000 lines compiled with zero errors on the first try. [02-Value-Debate](02-Value-Debate.md) has the details. + +## Next + +You now have a whole-system picture of Claude Code. From here we go module by module. -Yes. All 20 commits come from claude-code-best, with three commits bearing `Co-Authored-By: Claude Opus 4.6`. 515,000 lines of code compiled with zero errors on the first try. See [02-Value-Debate](docs/02-Value-Debate.md) for details. +Next up, [02-Value-Debate](02-Value-Debate.md) asks whether this code is actually worth anything, and where the real moat in harness engineering lies. From ab45027ce8130ab4245a7ea6e2d901e3762bced1 Mon Sep 17 00:00:00 2001 From: Charles Cheng Date: Tue, 11 Aug 2026 10:19:06 +0800 Subject: [PATCH 6/6] docs: record version coverage and start a changelog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A source teardown goes stale, so state which snapshot it was verified against instead of leaving readers to guess: source snapshot date, the version that build self-reported, when chapters were last re-verified, and when the repo was last maintained. Points drift at the issue template. Syncs the two READMEs — the Chinese side was missing the git-history paragraph and the reproduction steps the English side had. --- CHANGELOG.md | 47 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++---- README_EN.md | 30 ++++++++++++++++++++++++++---- 3 files changed, 118 insertions(+), 8 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..15572f3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,47 @@ +# Changelog + +All notable changes to this documentation set are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/) adapted for documentation: + +- **MAJOR** — a chapter's conclusion changed, or chapters were added/removed +- **MINOR** — substantive content added to an existing chapter +- **PATCH** — corrections, link fixes, translation and wording repairs + +## [Unreleased] + +## [1.1.0] — 2026-08-11 + +### Fixed + +- All 56 chapter cross-links resolved to `docs/.md` from inside `docs/`, which 404'd in GitHub's file view and only worked on the docsify site. They are now same-directory relative and correct in both contexts. ([#1](https://github.com/anneheartrecord/claude-code-docs/pull/1)) +- `docs/12-Agent-Security-Design.md` linked to `13-啃完51万行源码的发现与Claude的封号机制.md`, a filename that no longer exists after chapter 13 was renamed. Dead in every context. +- The Chinese chapter 12 pointed at chapter 13 under its old title. +- `_sidebar.md` and `_home.md` now use root-absolute paths, required once `relativePath` is enabled. + +### Added + +- `LICENSE` — MIT, matching the declaration the READMEs have carried since the first release, plus a scope note clarifying that no Claude Code source is redistributed here. +- `CONTRIBUTING.md` / `CONTRIBUTING_EN.md` — what corrections are wanted, the evidence bar for a factual correction, and the link conventions. +- `CODE_OF_CONDUCT.md` — Contributor Covenant 2.1. +- `scripts/check_links.py` — validates every local Markdown and image link and enforces the per-context link convention. +- `scripts/check_bilingual.py` — flags chapters that exist in only one language or whose two sides have drifted apart in size. +- GitHub Actions workflow running both checks on every push and pull request. +- Issue templates for chapter corrections, version drift, and new chapter proposals; a pull request template. +- Version coverage table in both READMEs, recording which source snapshot the analysis was verified against. +- English chapter 01 expanded from a summary to full parity with the Chinese: source-leak background, what Claude Code is, how it differs from an agent framework, the six-step request journey, the industry comparison table, and the key-numbers table. It was previously 5.2 KB against 15 KB of Chinese. + +### Changed + +- docsify `relativePath` switched to `true` so a single link form works on the published site and on GitHub. +- `.idea/` removed from version control and added to `.gitignore`. + +## [1.0.0] — 2026-04-24 + +### Added + +- 13 chapters of teardown analysis in Chinese and English, covering architecture, the agent loop, context engineering, the compaction system, permissions, memory, tools and skills, MCP integration, the feature-flag roadmap, code review in the AI coding era, agent security design, and closing findings. +- 59 hand-drawn illustrations across all 13 chapters. +- docsify site published to GitHub Pages. + +[Unreleased]: https://github.com/anneheartrecord/claude-code-docs/compare/v1.1.0...HEAD +[1.1.0]: https://github.com/anneheartrecord/claude-code-docs/compare/v1.0.0...v1.1.0 +[1.0.0]: https://github.com/anneheartrecord/claude-code-docs/releases/tag/v1.0.0 diff --git a/README.md b/README.md index 6f1a0ea..bf90ea3 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,12 @@ # Claude Code 源码解剖 -![License](https://img.shields.io/badge/license-MIT-green) +[![License](https://img.shields.io/github/license/anneheartrecord/claude-code-docs?color=green)](./LICENSE) +[![docs-check](https://github.com/anneheartrecord/claude-code-docs/actions/workflows/docs-check.yml/badge.svg)](https://github.com/anneheartrecord/claude-code-docs/actions/workflows/docs-check.yml) ![Docs](https://img.shields.io/badge/docs-13%20articles-blue) ![Language](https://img.shields.io/badge/language-中文%20%7C%20English-orange) ![Lines](https://img.shields.io/badge/analyzed-515K%20lines-red) -![AI](https://img.shields.io/badge/AI%20Powered-Claude%20Code-purple) +[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen)](./CONTRIBUTING.md) > 📖 **在线阅读:** https://anneheartrecord.github.io/claude-code-docs/ @@ -20,6 +21,8 @@ Sourcemap 是前端构建工具生成的调试辅助文件,记录了编译后 但客户端的这部分代码已经足够有价值了。因为 Agent 产品的核心竞争力不只在模型调用侧,也在于**怎么通过设计 Agent 将模型的能力安全、高效、稳定地释放出来**。 +有意思的是,从 git 历史看,这份代码本身很可能就是 AI 写的:20 个 commit 全部来自同一个账号 claude-code-best,其中三个带着 `Co-Authored-By: Claude Opus 4.6`。51.5 万行代码一次编译零报错。**AI 把功能写得挑不出毛病,却栽在一个基础的发布配置细节上。** + ## 这个仓库做了什么 我用 Claude Code 对这份源码做了系统化的技术分析,逐模块拆解,写了 13 篇技术文档,中英双语。 @@ -63,6 +66,23 @@ Sourcemap 是前端构建工具生成的调试辅助文件,记录了编译后 | [13-啃完源码之后的一些发现](./docs/13-啃完源码之后的一些发现.md) | AI 工程化短板、生产事故、Claude 封号机制分析 | +## 上手复现 + +被还原出来的源码仓库可以直接跑: + +```bash +git clone https://github.com/anthropics/claude-code.git +cd claude-code + +bun install +bun run build +# ✓ Bundled 5344 modules in 554ms +# cli.js 25.89 MB + +bun run dev --version +# 2.1.888 (Claude Code) +``` + ## 关键数据 | 指标 | 数据 | @@ -76,8 +96,29 @@ Sourcemap 是前端构建工具生成的调试辅助文件,记录了编译后 | 消息压缩阈值 | 上下文窗口 - 13,000 token | | npm 依赖 | 583 个包 | +## 版本覆盖范围 + +源码解读一定会过时,所以这里把「分析基于哪个快照」写清楚,而不是让读者去猜。 + +| 项 | 值 | +|---|---| +| 源码快照 | 2026-03-31 的 sourcemap 还原产物 | +| 该构建自报版本 | `2.1.888` | +| 章节内容最近复核 | 2026-04-24(v1.0.0) | +| 仓库最近维护 | 2026-08-11(v1.1.0,链接与工具链,未改章节结论) | + +上游改动导致某章描述失效,请开 [版本漂移 issue](https://github.com/anneheartrecord/claude-code-docs/issues/new?template=version-drift.yml)。这是本仓库最欢迎的一类 issue。 + +## 参与贡献 + +最有价值的贡献不是加内容,是**指出哪里写错了**。事实纠错优先级最高,issue 7 天内首次回应。 + +- 纠错与提议:见 [贡献指南](./CONTRIBUTING.md)(事实纠错必须带证据) +- 变更记录:见 [CHANGELOG.md](./CHANGELOG.md) +- 本地自检:`python3 scripts/check_links.py && python3 scripts/check_bilingual.py` + ## License -本仓库为技术分析文档,不包含 Claude Code 源码本身。分析内容基于公开可获取的 sourcemap 还原代码。 +[MIT](./LICENSE)。本仓库只包含原创的技术分析文档,不再分发 Claude Code 源码本身;章节中引用的少量代码片段用于评述与分析,版权归原作者所有。 -MIT +Claude 与 Claude Code 是 Anthropic PBC 的商标,本项目与 Anthropic 无从属或背书关系。 diff --git a/README_EN.md b/README_EN.md index 5cf9438..47e541a 100644 --- a/README_EN.md +++ b/README_EN.md @@ -2,11 +2,12 @@ # Claude Code Source Anatomy -![License](https://img.shields.io/badge/license-MIT-green) +[![License](https://img.shields.io/github/license/anneheartrecord/claude-code-docs?color=green)](./LICENSE) +[![docs-check](https://github.com/anneheartrecord/claude-code-docs/actions/workflows/docs-check.yml/badge.svg)](https://github.com/anneheartrecord/claude-code-docs/actions/workflows/docs-check.yml) ![Docs](https://img.shields.io/badge/docs-13%20articles-blue) ![Language](https://img.shields.io/badge/language-中文%20%7C%20English-orange) ![Lines](https://img.shields.io/badge/analyzed-515K%20lines-red) -![AI](https://img.shields.io/badge/AI%20Powered-Claude%20Code-purple) +[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen)](./CONTRIBUTING_EN.md) > 📖 **Read Online:** https://anneheartrecord.github.io/claude-code-docs/ @@ -94,8 +95,29 @@ bun run dev --version | Compaction Threshold | Context window - 13,000 tokens | | Dependencies | 583 packages | +## Version coverage + +A source teardown goes stale. Rather than leave readers guessing, here is exactly which snapshot the analysis was verified against. + +| Item | Value | +|---|---| +| Source snapshot | sourcemap reconstruction dated 2026-03-31 | +| Version that build self-reported | `2.1.888` | +| Chapter content last re-verified | 2026-04-24 (v1.0.0) | +| Repository last maintained | 2026-08-11 (v1.1.0 — links and tooling; no chapter conclusions changed) | + +If an upstream change has invalidated something a chapter says, please open a [version drift issue](https://github.com/anneheartrecord/claude-code-docs/issues/new?template=version-drift.yml). It is the most welcome issue type here. + +## Contributing + +The most valuable contribution is not adding content — it is **telling me where I got it wrong**. Factual corrections are the top priority, and issues get a first response within 7 days. + +- Corrections and proposals: see the [contributing guide](./CONTRIBUTING_EN.md) (corrections must carry evidence) +- Change history: see [CHANGELOG.md](./CHANGELOG.md) +- Local checks: `python3 scripts/check_links.py && python3 scripts/check_bilingual.py` + ## License -This repository contains technical analysis documentation only, not Claude Code source code itself. Analysis is based on publicly accessible sourcemap-reconstructed code. +[MIT](./LICENSE). This repository contains original technical analysis only and does not redistribute Claude Code source; short excerpts quoted inside chapters are used for commentary and remain the property of their owners. -MIT +Claude and Claude Code are trademarks of Anthropic PBC. This project is not affiliated with or endorsed by Anthropic.