diff --git a/CHANGELOG.md b/CHANGELOG.md index 15572f3..1043eba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ All notable changes to this documentation set are recorded here. The format foll ## [Unreleased] +### Changed + +- Re-verified all 13 chapters against Claude Code 2.1.227 and upstream commit `54cc51a`; updated current auto memory, compaction, permission modes, MCP configuration, shipped 1M context, and voice interaction, while labeling March source snapshot counts as historical. + ## [1.1.0] — 2026-08-11 ### Fixed diff --git a/README.md b/README.md index fe116fd..66a2a42 100644 --- a/README.md +++ b/README.md @@ -27,9 +27,9 @@ Sourcemap 是前端构建工具生成的调试辅助文件,记录了编译后 我用 Claude Code 对这份源码做了系统化的技术分析,逐模块拆解,写了 13 篇技术文档,中英双语。 -从架构设计到 Agent 循环的六阶段实现,从三层消息压缩体系到权限校验系统,从五层记忆加载到工具的执行流水线。 +从架构设计到 Agent 循环的六阶段实现,从三层消息压缩体系到权限校验系统,从四种指令作用域与自动记忆到工具的执行流水线。 -同时从 82 个 feature flag 里挖出了 Anthropic 还没发布的未来功能蓝图:Kairos 自主运行模式、Context Collapse 上下文折叠、Voice Mode 语音交互。 +同时从 2026 年 3 月快照的 82 个 feature flag 里挖出了 Anthropic 当时探索的未来功能蓝图:Kairos 自主运行模式、Context Collapse 上下文折叠、Voice Mode 语音交互。 最后几篇是我自己的思考:这份代码到底值不值钱、AI Coding 时代工程师怎么做 Code Review、以及从源码里能看到 Claude 封号机制的哪些线索。 @@ -51,16 +51,16 @@ Sourcemap 是前端构建工具生成的调试辅助文件,记录了编译后 | [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 | +| [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、七种配置作用域 | +| [09-MCP 集成](./docs/09-MCP集成.md) | 四种传输类型(CLI 支持三种)、OAuth、三种安装作用域 | ### 前瞻篇 | 文档 | 内容 | |------|------| -| [10-未来功能蓝图](./docs/10-未来功能蓝图.md) | 82 个 feature flag 解析、Kairos 自主模式、Context Collapse、语音模式 | +| [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 封号机制分析 | @@ -104,9 +104,27 @@ bun run dev --version |---|---| | 源码快照 | 2026-03-31 的 sourcemap 还原产物 | | 该构建自报版本 | `2.1.888` | -| 章节内容最近复核 | 2026-04-24(v1.0.0) | +| 章节内容最近复核 | 2026-08-11(Claude Code `2.1.227`,上游提交 `54cc51a`) | | 仓库最近维护 | 2026-08-11(v1.1.0,链接与工具链,未改章节结论) | +这次复核以 npm 发布的 Claude Code `2.1.227` 和 Anthropic 的公开仓库提交 `54cc51a` 为基线。章节中关于 2026-03-31 sourcemap 的源码路径、行数和 feature flag 数量仍然是历史快照,不代表当前内部实现。 + +| 章节 | 复核结果 | +|---|---| +| 01 架构总览 | 历史源码快照保留;当前版本差异见 04、05、06、07、09、10 | +| 02 价值之争 | 分析性内容,无需版本修正 | +| 03 Agent 循环 | 核心循环分析保留为快照内容 | +| 04 上下文工程 | 更新当前模型上下文和记忆说明 | +| 05 消息压缩系统 | 更新当前可配置的自动压缩窗口 | +| 06 权限系统 | 更新当前六种权限模式;42 条规则标注为快照数据 | +| 07 记忆管理 | 更新自动记忆已在当前版本启用 | +| 08 工具与 Skill 系统 | 保留 40+ 这一保守下限,补充当前工具变化说明 | +| 09 MCP 集成 | 更新当前公开的传输类型和配置范围 | +| 10 未来功能蓝图 | 标出自动记忆、语音和 1M 上下文已落地 | +| 11 AI Coding 时代的 Code Review | 分析性内容,无需版本修正 | +| 12 Agent 安全设计 | 同步第 06 章的当前权限模式说明 | +| 13 源码发现 | 将 feature flag、依赖数和自动记忆预测标注为快照或已落地 | + 上游改动导致某章描述失效,请开 [版本漂移 issue](https://github.com/anneheartrecord/claude-code-docs/issues/new?template=version-drift.yml)。这是本仓库最欢迎的一类 issue。 ## 参与贡献 diff --git a/README_EN.md b/README_EN.md index 400064d..751e839 100644 --- a/README_EN.md +++ b/README_EN.md @@ -29,7 +29,7 @@ Ironically, based on git history, this code was most likely written by AI itself I used Claude Code to systematically analyze this source, module by module, producing 13 technical documents in both Chinese and English. -From architecture design to the six-phase Agent loop implementation, from the three-tier message compaction system to the 6,300-line permission system, from five-layer memory loading to the 40+ tool execution pipeline. I also extracted Anthropic's unreleased feature roadmap from 82 feature flags: Kairos autonomous mode, Context Collapse, Voice Mode. +From architecture design to the six-phase Agent loop implementation, from the three-tier message compaction system to the 6,300-line permission system, from four instruction scopes and auto memory to the 40+ tool execution pipeline. I also extracted Anthropic's explored feature directions from the 82 feature flags in the March 2026 snapshot: Kairos autonomous mode, Context Collapse, and Voice Mode. The final documents include my own analysis: whether this code is truly valuable, how engineers should do Code Review in the AI Coding era, and what clues the source reveals about Claude's account ban mechanism. @@ -51,16 +51,16 @@ The final documents include my own analysis: whether this code is truly valuable | [03-Agent Loop](./docs/03-Agent-Loop.md) | Six-phase ReAct loop, AsyncGenerator design, state management, thinking chain preservation | | [04-Context Engineering](./docs/04-Context-Engineering.md) | System prompt construction, CLAUDE.md loading, layered priorities, prefetch caching, prompt cache optimization | | [05-Compaction System](./docs/05-Compaction-System.md) | Three-tier compaction: microcompact, session memory, full compact, circuit breaker, recursion guard | -| [06-Permission System](./docs/06-Permission-System.md) | Three-mode permissions, YOLO classifier, 42 interception rules, filesystem sandbox, dangerous rule stripping | -| [07-Memory System](./docs/07-Memory-System.md) | Five-layer memory loading, @include directives, MEMORY.md management, session memory | +| [06-Permission System](./docs/06-Permission-System.md) | Six permission modes, YOLO classifier, 42 rules from the historical snapshot, filesystem sandbox, dangerous rule stripping | +| [07-Memory System](./docs/07-Memory-System.md) | Four instruction scopes, auto memory, @include directives, MEMORY.md management, session memory | | [08-Tools & Skills](./docs/08-Tools-and-Skills.md) | 40+ tool registry, execution pipeline, pre/post hooks, skill fork mechanism | -| [09-MCP Integration](./docs/09-MCP-Integration.md) | Six transport protocols, OAuth, seven config scopes | +| [09-MCP Integration](./docs/09-MCP-Integration.md) | Four transport types (three CLI transports), OAuth, three installation scopes | ### Forward-Looking | Document | Content | |----------|---------| -| [10-Future Features](./docs/10-Future-Features.md) | 82 feature flags decoded, Kairos autonomous mode, Context Collapse, voice mode | +| [10-Future Features](./docs/10-Future-Features.md) | 82 feature flags from the historical snapshot, Kairos autonomous mode, Context Collapse, shipped voice mode | | [11-AI Code Review](./docs/11-AI-Code-Review.md) | Individual/team/CICD three-layer review paradigm, Review Agent concept | | [12-Agent Security Design](./docs/12-Agent-Security-Design.md) | Three-layer defense system, L0-L4 security maturity model, practical guide | | [13-Source Code Findings](./docs/13-Source-Code-Findings.md) | AI engineering blind spots, production incidents, Claude ban mechanism analysis | @@ -103,9 +103,27 @@ A source teardown goes stale. Rather than leave readers guessing, here is exactl |---|---| | 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) | +| Chapter content last re-verified | 2026-08-11 (Claude Code `2.1.227`, upstream commit `54cc51a`) | | Repository last maintained | 2026-08-11 (v1.1.0 — links and tooling; no chapter conclusions changed) | +This review used the npm-published Claude Code `2.1.227` package and Anthropic's public repository at commit `54cc51a`. Claims about source paths, line counts, and feature-flag totals from the 2026-03-31 sourcemap remain historical snapshot data, not statements about the current private implementation. + +| Chapter | Review result | +|---|---| +| 01 Architecture Overview | Historical source snapshot retained; current differences are covered in 04, 05, 06, 07, 09, and 10 | +| 02 Value Debate | Analytical content, no version correction needed | +| 03 Agent Loop | Core loop analysis retained as snapshot content | +| 04 Context Engineering | Current model context and memory wording updated | +| 05 Compaction System | Current configurable auto-compaction window updated | +| 06 Permission System | Current six permission modes added; 42-rule count marked as snapshot data | +| 07 Memory System | Current auto-memory availability updated | +| 08 Tools and Skills | Conservative 40+ lower bound retained, current tool changes noted | +| 09 MCP Integration | Current public transport types and configuration scope updated | +| 10 Future Features | Auto-memory, voice, and 1M context marked as shipped | +| 11 AI Code Review | Analytical content, no version correction needed | +| 12 Agent Security Design | Current permission-mode wording synced with chapter 06 | +| 13 Source Code Findings | Feature flags, dependency count, and auto-memory prediction marked as snapshot or shipped | + 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 diff --git a/docs/01-Architecture-Overview.md b/docs/01-Architecture-Overview.md index 86c73ae..38eee81 100644 --- a/docs/01-Architecture-Overview.md +++ b/docs/01-Architecture-Overview.md @@ -2,6 +2,8 @@ # 01 Architecture Overview: How Claude Code Actually Runs +> Version scope: the source paths, line counts, permission modes, memory layers, and other exact figures in this chapter describe the March 31, 2026 sourcemap snapshot. They are historical implementation evidence, not a claim about the current private client. + ## First, some background: how the source leaked 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. @@ -71,15 +73,16 @@ The whole picture first, then layer by layer. ┌───────────▼──────────┐ ┌──────────▼───────────────────┐ │ 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 │ +│ March snapshot: │ │ Bash / File / Web / Agent │ +│ 3 modes + 42 rules │ │ Skill / MCP / Task │ +│ ML classifier + jail │ │ │ └──────────────────────┘ └───────────────────────────────┘ │ │ └───────────┬───────────┘ │ ┌───────────────────────▼──────────────────────────────────┐ │ Context and memory layer │ -│ CLAUDE.md five-layer loading / MEMORY.md / Session Memory│ +│ March snapshot: five-layer CLAUDE.md / MEMORY.md │ │ Git status injection / Skill list / permission rules │ │ Three-tier compaction: micro / Session Memory / full │ └───────────────────────┬──────────────────────────────────┘ @@ -130,7 +133,7 @@ Before calling the API the system assembles a complete context. That context det **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 +2. the user's CLAUDE.md memory files, loaded across five priority layers in the March snapshot 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 @@ -155,7 +158,7 @@ If the model decides to call a tool, it emits a `tool_use` block in the response Once `tool_use` arrives, the permission check runs first: -- hardcoded rules: 42 dangerous commands rejected outright, without asking +- March snapshot: 42 dangerous command patterns 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 @@ -192,9 +195,9 @@ If you want to read the source yourself, this table will orient you: | `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/utils/claudemd.ts` | 1,400+ | March snapshot's 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/utils/permissions/` | 6,300+ | March snapshot's 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 | @@ -207,9 +210,9 @@ If you want to read the source yourself, this table will orient you: |---|---|---|---|---| | 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 | +| Permissions | 6,300 lines, March snapshot: 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 | +| Memory | March snapshot: 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 | 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 79aa503..ad31479 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" @@ -2,6 +2,8 @@ # 01 架构总览:Claude Code 到底是怎么跑起来的 +> 版本范围:本章的源码路径、行数、权限模式、记忆层级和其他精确数字均来自 2026 年 3 月 31 日的 sourcemap 快照,属于历史实现证据,不代表当前私有客户端的实现。 + ## 先搞清楚一个背景:这份源码是怎么泄露的 2026 年 3 月,有人发现 Claude Code 发布在 npm 上的客户端包里带了 sourcemap 文件。sourcemap 本来是给开发者做 debug 用的,它记录了打包后的代码和原始源码之间的映射关系。正常情况下发布时应该把它排除掉,但 Anthropic 的构建流程里漏了这一步。 @@ -68,15 +70,15 @@ Claude Code 是 Anthropic 官方出的一个 AI 编程助手,定位是 Coding- ┌───────────▼──────────┐ ┌─────────▼────────────────────┐ │ 权限系统 │ │ 工具执行层 │ │ 6,300 行 / 25 个文件 │ │ 40+ 个工具 │ -│ 三种模式 + 42 条规则 │ │ Bash / File / Web / Agent │ -│ ML 分类器 + 沙箱 │ │ Skill / MCP / Task │ +│ 3 月快照:三种模式 │ │ Bash / File / Web / Agent │ +│ + 42 条规则 + ML 分类器│ │ Skill / MCP / Task │ └──────────────────────┘ └──────────────────────────────┘ │ │ └───────────┬───────────┘ │ ┌───────────────────────▼──────────────────────────────────┐ │ 上下文与记忆层 │ -│ CLAUDE.md 五层加载 / MEMORY.md / Session Memory │ +│ 3 月快照:CLAUDE.md 五层加载 / MEMORY.md │ │ Git 状态注入 / Skill 列表 / 权限规则 │ │ 三层消息压缩:微压缩 / Session Memory / Full Compact │ └───────────────────────┬──────────────────────────────────┘ @@ -126,7 +128,7 @@ Claude Code 是一个 **完整的产品**,从终端 UI 到权限管理到上 **System Prompt 由以下部分拼接而成:** 1. 内置的 Agent 行为规则,告诉模型你是 Claude Code,你能读写文件、执行命令,你应该怎么和用户交互 -2. 用户的 CLAUDE.md 记忆文件,五层优先级加载,从全局到项目到本地 +2. 用户的 CLAUDE.md 记忆文件,在 3 月快照中按五层优先级加载 3. 当前 Git 仓库的状态快照:分支、最近 commit、改动了哪些文件 4. 权限规则:哪些工具可以自动执行,哪些需要用户确认 5. Skill 列表:当前可用的扩展能力 @@ -151,7 +153,7 @@ Claude Code 是一个 **完整的产品**,从终端 UI 到权限管理到上 收到 tool_use 后,系统先做权限检查: -- 硬编码规则:42 条危险命令直接拒绝,不问用户 +- 3 月快照:42 条危险命令模式直接拒绝,不问用户 - ML 分类器:判断这条命令是否安全 - 用户规则:匹配用户配置的 allow/deny 列表 - 弹窗确认:以上都不匹配时,弹窗让用户选择 @@ -187,9 +189,9 @@ Claude Code 是一个 **完整的产品**,从终端 UI 到权限管理到上 | `src/QueryEngine.ts` | 1,300 | 会话状态机,20+ 配置参数 | 想理解会话管理和配置体系 | | `src/main.tsx` | 5,000+ | CLI 入口,什么都塞在里面 | 想理解启动流程 | | `src/context.ts` | 200+ | Git 状态注入、上下文组装 | 想理解 Context Engineering | -| `src/utils/claudemd.ts` | 1,400+ | CLAUDE.md 五层加载、@include | 想理解记忆系统 | +| `src/utils/claudemd.ts` | 1,400+ | 3 月快照的 CLAUDE.md 五层加载、@include | 想理解记忆系统 | | `src/services/compact/` | 26 个文件 | 三层消息压缩 | 想理解长对话管理 | -| `src/utils/permissions/` | 6,300+ | 三模式权限系统 | 想理解安全设计 | +| `src/utils/permissions/` | 6,300+ | 3 月快照的三模式权限系统 | 想理解安全设计 | | `src/services/api/claude.ts` | 800+ | API 客户端、重试、模型 fallback | 想理解 API 层 | | `src/tools.ts` | 300+ | 工具注册表、feature flag 控制 | 想知道有哪些工具 | | `src/services/mcp/` | 12,000+ | MCP 协议集成 | 想理解外部工具接入 | @@ -202,9 +204,9 @@ Claude Code 是一个 **完整的产品**,从终端 UI 到权限管理到上 |------|------------|--------|----------------|---------| | 形态 | 终端 CLI | IDE 插件 | Python 库 | Python 框架 | | Agent 循环 | 自研 ReAct + AsyncGenerator | 不公开 | ReAct / Plan-and-Execute | GroupChat + Planner | -| 权限系统 | 6,300 行,三模式 + ML 分类器 | IDE 级别沙箱 | 基本没有 | 基本没有 | +| 权限系统 | 6,300 行,3 月快照:三模式 + ML 分类器 | IDE 级别沙箱 | 基本没有 | 基本没有 | | 上下文管理 | 三层压缩 + 预取缓存 + prompt cache 优化 | 不公开 | 简单的 token 截断 | 无 | -| 记忆 | 五层 CLAUDE.md + MEMORY.md + Session Memory | 项目级索引 | 手动配置 | ConversableAgent memory | +| 记忆 | 3 月快照:五层 CLAUDE.md + MEMORY.md + Session Memory | 项目级索引 | 手动配置 | ConversableAgent memory | | 工具 | 40+ 内置 + Skill + MCP | 内置 + 插件 | 需要自己注册 | 需要自己注册 | | 代码规模 | 51.5 万行 | 不公开 | ~5 万行 | ~3 万行 | diff --git a/docs/02-Value-Debate.md b/docs/02-Value-Debate.md index 82715a9..c8c040a 100644 --- a/docs/02-Value-Debate.md +++ b/docs/02-Value-Debate.md @@ -2,6 +2,8 @@ # 02 The Value Debate: What Is Leaked Source Code Really Worth? +> Version scope: this chapter analyzes the March 31, 2026 sourcemap snapshot. Its concrete counts, flag states, permission modes, and compaction threshold are historical evidence, not current product behavior. + ## 1️⃣ Background: An Accidental Open-Sourcing In March 2026, Anthropic's AI programming tool **Claude Code** was found to be fully recoverable through deobfuscation of its shipped JavaScript bundles. The result: **515,000 lines of production-grade TypeScript code** covering Agent loops, tool orchestration, permission management, context engineering, message compaction, memory systems, and virtually every other core module in the AI Agent domain. @@ -28,7 +30,7 @@ Specifically, Camp One considered the following modules most valuable: **The six-stage loop design in query.ts** is the core engine of the entire system. Prefetch, context construction, streaming API calls, tool execution, compaction, and continuation decisions form six tightly interconnected stages. The boundary condition handling at each stage represents hard-won lessons from real user scenarios. For example, the auto-compaction trigger threshold is set at **context window minus 13K tokens**, and there is a rule that **thinking blocks must be persisted between tool_use and tool_result**. Discovering these details independently could take weeks or months. -**The three-mode permission system** is another highlight. The default, auto, and plan modes work with a YOLO classifier, Bash pattern matching, and path sandboxing in a layered defense. Most open-source Agent frameworks either have no permission system at all or just a simple allowlist. Claude Code's permission system is **at least two orders of magnitude more sophisticated**. +**The March snapshot's three-mode permission system** is another highlight. Its default, auto, and plan modes work with a YOLO classifier, Bash pattern matching, and path sandboxing in a layered defense. Most open-source Agent frameworks either have no permission system at all or just a simple allowlist. Claude Code's permission system is **at least two orders of magnitude more sophisticated**. **The three-tier message compaction mechanism** solves a core pain point for long-conversation Agents. Micro-compaction, Session Memory, and Full Compact work in a progressive hierarchy, combined with circuit breakers, recursion protection, and Prompt Cache awareness. How to compress historical information without losing critical context is an engineering problem that every long-context Agent must solve, yet the industry rarely discusses it openly. 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 bca7d3d..95f5fc3 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" @@ -2,6 +2,8 @@ # 02 源码泄露的价值之争 +> 版本范围:本章分析的是 2026 年 3 月 31 日的 sourcemap 快照。其中的具体数量、flag 状态、权限模式和压缩阈值属于历史证据,不代表当前产品行为。 + ## 1️⃣ 事件背景:一次意外的开源 2026 年 3 月,Anthropic 旗下的 AI 编程工具 **Claude Code** 被发现其源码可以通过混淆逆向的方式完整还原。总计 **51.5 万行生产级 TypeScript 代码**,涵盖了 Agent 循环、工具编排、权限管理、上下文工程、消息压缩、记忆系统等 AI Agent 领域几乎所有核心模块。 @@ -32,7 +34,7 @@ **query.ts 的六阶段循环设计** 是整个系统的核心引擎。预取、上下文构建、API 流式调用、工具执行、压缩、继续决策,六个阶段环环相扣。每一个阶段的边界条件处理,都是 Anthropic 团队在真实用户场景中踩过无数坑之后沉淀下来的最优解。比如自动压缩的触发阈值设在 **上下文窗口减去 13K token** 的位置,比如 **thinking block 在 tool_use 和 tool_result 之间必须持久化保留** 的规则,这些细节如果自己摸索,可能要花几周甚至几个月。 -**三模式权限系统** 是另一个亮点。default、auto、plan 三种模式,配合 YOLO 分类器、Bash 模式匹配、路径沙箱的分层防御。大部分开源 Agent 框架要么完全没有权限系统,要么只是一个简单的白名单。Claude Code 的权限系统比它们 **领先了至少两个量级**。 +**3 月快照中的三模式权限系统** 是另一个亮点。default、auto、plan 三种模式,配合 YOLO 分类器、Bash 模式匹配、路径沙箱的分层防御。大部分开源 Agent 框架要么完全没有权限系统,要么只是一个简单的白名单。Claude Code 的权限系统比它们 **领先了至少两个量级**。 **三层消息压缩机制** 解决了长对话 Agent 的一个核心痛点。微压缩、Session Memory、Full Compact 三层递进,加上熔断器、递归保护、Prompt Cache 感知。如何在压缩历史信息的同时不丢失关键上下文,这是长上下文 Agent 必须解决但行业内很少有人公开讨论的工程问题。 diff --git a/docs/03-Agent-Loop.md b/docs/03-Agent-Loop.md index d92a2d2..afc057d 100644 --- a/docs/03-Agent-Loop.md +++ b/docs/03-Agent-Loop.md @@ -2,6 +2,8 @@ # 03 The Agent Loop +> Version scope: source paths, line counts, tool counts, and snapshot-specific loop details in this chapter describe the March 31, 2026 sourcemap. The current version coverage is tracked in the README. + ## 1️⃣ What Is an Agent Loop, and Why Does It Matter So Much Before diving into Claude Code's Agent loop, we need to understand a fundamental concept: **large language models are inherently stateless.** You send in some text, it returns some text, and the interaction is over. It does not decide what to do next on its own. It does not proactively read files. It does not execute commands by itself. @@ -105,7 +107,7 @@ tool_use blocks (tool call requests from model output) ↓ Pre-Hook (logging, parameter format validation) ↓ -Permission check (based on default/auto/plan modes, determine if user confirmation is needed) +Permission check (based on the active permission mode, determine if user confirmation is needed) ↓ Tool lookup (match by name in the tool registry) ↓ 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 f57b6f6..5ba46e2 100644 --- "a/docs/03-Agent\345\276\252\347\216\257.md" +++ "b/docs/03-Agent\345\276\252\347\216\257.md" @@ -2,6 +2,8 @@ # 03 Agent 循环 +> 版本范围:本章的源码路径、行数、工具数量和快照特有的循环细节来自 2026 年 3 月 31 日的 sourcemap,当前版本覆盖情况见 README。 + ## 1️⃣ 什么是 Agent 循环,为什么它如此重要 在理解 Claude Code 的 Agent 循环之前,我们需要先搞清楚一个基本概念:**大语言模型本身是无状态的。** 你给它一段文字,它返回一段文字,交互就结束了。它不会自己决定下一步做什么,不会主动去读文件,不会自己执行命令。 @@ -111,7 +113,7 @@ tool_use blocks(模型输出的工具调用请求) ↓ Pre-Hook(前置钩子:记录日志、校验参数格式) ↓ -权限检查(根据 default/auto/plan 三种模式决定是否需要用户确认) +权限检查(根据当前权限模式决定是否需要用户确认) ↓ 查找工具(按名称在工具注册表中匹配) ↓ diff --git a/docs/04-Context-Engineering.md b/docs/04-Context-Engineering.md index fd14708..eac507b 100644 --- a/docs/04-Context-Engineering.md +++ b/docs/04-Context-Engineering.md @@ -8,7 +8,7 @@ In 2025, Shopify CEO Tobi Lütke posted an opinion on social media: we should st To understand context engineering, you first need to understand a fundamental limitation of large language models: **the context window is finite.** -The context window can be thought of as the model's **working memory**. When a human thinks about a complex problem, the amount of information the brain can actively hold in focus is limited. Large language models are the same. Claude's context window ranges from 200K to 1M tokens depending on the model version, with Opus 4.6 already supporting 1M tokens. That sounds large, but in a complex Agent task, this space gets consumed surprisingly fast. +The context window can be thought of as the model's **working memory**. When a human thinks about a complex problem, the amount of information the brain can actively hold in focus is limited. Large language models are the same. Claude's context window ranges from 200K to 1M tokens depending on the model and plan. Opus 4.6 and later support 1M-token context when extended context is available. That sounds large, but in a complex Agent task, this space gets consumed surprisingly fast. Consider what Claude Code needs to fit into the context when handling a large code refactoring task: system instructions, the user's personalized configuration, project rules, the current Git repository status, the complete history of dozens of conversation turns, the results of every tool call, and definition documents for over 40 tools. All of this information competes for the same finite space. @@ -41,7 +41,7 @@ Several engineering details here are worth noting. First, Git status output is * **The CLAUDE.md memory system** is the most complex module in Claude Code's context engineering. The implementation lives in claudemd.ts and spans **1,400 lines**. -CLAUDE.md is a mechanism that lets users tell Claude about project rules and personal preferences. But Claude Code's design goes far beyond a simple config file. It establishes a **five-layer priority loading system**, ranked from low to high: +CLAUDE.md is a mechanism that lets users tell Claude about project rules and personal preferences. Claude Code currently loads four instruction scopes from low to high priority: managed policy, user, project, and local. The first layer is **global admin level**, at the path `/etc/claude-code/CLAUDE.md`. This location is typically configured by enterprise IT administrators to enforce uniform rules across an entire organization. For example, "all code changes must include tests" or "direct operations on production databases are prohibited." @@ -51,21 +51,21 @@ The third layer is **project level**, including `CLAUDE.md` in the project root, The fourth layer is **local level**, with the filename `CLAUDE.local.md`. This file is gitignored and dedicated to personal private configuration. For example, local API key paths or special development environment settings. -The fifth layer is **auto-memory**, controlled by the TEAMMEM feature flag. This is an experimental feature where the system automatically extracts valuable information from conversations and persists it. +Auto memory is a separate mechanism, not a fifth CLAUDE.md layer. In current 2.1.x builds it is enabled by default, stores per-repository notes under `~/.claude/projects//memory/`, and loads the first 200 lines or 25 KB of `MEMORY.md` at session start. It can be toggled from `/memory`, project settings, or `CLAUDE_CODE_DISABLE_AUTO_MEMORY`. -The loading order of these five layers means higher-priority configurations override lower-priority ones. A project-level rule can override a user-level default, and a local-level configuration can override a project-level rule. +The loading order of the four instruction scopes means more specific configurations are loaded later than broader ones. A project-level rule can follow a user-level default, and a local-level configuration can follow a project-level rule. Auto memory is loaded separately as learned context; it is not an instruction scope that overrides CLAUDE.md. -CLAUDE.md also supports a powerful **@include directive system** that allows one CLAUDE.md file to reference the contents of other files. The syntax supports four path formats: `@path` for relative paths, `@./relative` for explicit relative paths, `@~/home` for user directory paths, and `@/absolute` for absolute paths. The system only parses @include directives in **leaf text nodes** and never triggers them inside code blocks. It includes **circular reference detection** using a Set data structure to track already-processed file paths, preventing infinite recursion from A referencing B which references A. The system supports over 200 file extensions and automatically blocks binary files. +CLAUDE.md also supports a powerful **@include directive system** that allows one CLAUDE.md file to reference the contents of other files. The syntax supports four path formats: `@path` for relative paths, `@./relative` for explicit relative paths, `@~/home` for user directory paths, and `@/absolute` for absolute paths. The system only parses @include directives in **leaf text nodes** and never triggers them inside code blocks. It includes **circular reference detection** using a Set data structure to track already-processed file paths, preventing infinite recursion from A referencing B which references A. Current public documentation limits nested imports to four hops. The entire memory system has several **key constants** governing its boundaries: -- `MAX_MEMORY_CHARACTER_COUNT = 40000`: Total character limit after merging all CLAUDE.md content +- `MAX_MEMORY_CHARACTER_COUNT = 40000`: March source snapshot constant for the merged CLAUDE.md character limit - `MAX_ENTRYPOINT_LINES = 200`: Maximum lines for MEMORY.md files - `MAX_ENTRYPOINT_BYTES = 25000`: Maximum bytes for MEMORY.md files -These limits ensure the memory system does not bloat excessively and consume too much context window space. +The two MEMORY.md limits are current documented behavior. The merged CLAUDE.md constant is retained as a historical source snapshot detail; current public documentation does not establish it as a current limit. -**Permission rules** are loaded from two locations: `~/.claude/settings.json` for user-level settings and `.claude-permissions.json` for project-level settings. They are merged and parsed into a **ToolPermissionContext** data structure containing allow, deny, and ask rules. These rules are injected into the system prompt so the model knows which operations can be executed directly, which require user confirmation, and which are explicitly prohibited. +**Permission rules** are loaded from user, project, local, and managed settings. They are merged into allow, deny, and ask rules. These rules govern which operations can be executed directly, which require user confirmation, and which are explicitly prohibited. ## 3️⃣ Layered Priority: When Space Runs Out, Who Goes First @@ -157,7 +157,7 @@ Different Agent systems invest vastly different amounts of effort in context man **Cursor** is reported to have invested heavily in context management, particularly in precise retrieval of code context. It uses **vector retrieval** technology to find code snippets most relevant to the current task. This is complementary to Claude Code's approach: one focuses on **retrieval precision**, the other on **full lifecycle management**. -**Claude Code's** context engineering holds the position of **most systematic** in the industry. The five-layer priority memory loading, six-tier compaction priority, prefetch caching system, dynamic injection strategy, and fine-grained Prompt Cache management form a complete end-to-end solution. The level of investment is reflected in the 1,400 lines of CLAUDE.md loading code and in the engineering discipline of building a dedicated detection module for cache breaks. +**Claude Code's** context engineering holds the position of **most systematic** in the industry. The four-scope instruction loading, six-tier compaction priority, prefetch caching system, dynamic injection strategy, and fine-grained Prompt Cache management form a complete end-to-end solution. The level of investment is reflected in the historical 1,400 lines of CLAUDE.md loading code and in the engineering discipline of building a dedicated detection module for cache breaks. ## 8️⃣ Summary 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 c02cfa6..b9a4794 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" @@ -8,7 +8,7 @@ 要理解上下文工程,先要理解大语言模型的一个基本限制:**上下文窗口是有限的。** -上下文窗口可以理解为模型的 **工作记忆**。人类在思考一个复杂问题时,大脑能同时保持关注的信息量是有限的,大语言模型也是如此。Claude 不同版本的上下文窗口从 200K 到 1M token 不等,Opus 4.6 已经支持 1M token。听起来很大,但在一个复杂的 Agent 任务中,这个空间很快就会被消耗殆尽。 +上下文窗口可以理解为模型的 **工作记忆**。人类在思考一个复杂问题时,大脑能同时保持关注的信息量是有限的,大语言模型也是如此。Claude 不同模型和套餐的上下文窗口从 200K 到 1M token 不等。Opus 4.6 及更高版本在可用扩展上下文时支持 1M token。听起来很大,但在一个复杂的 Agent 任务中,这个空间很快就会被消耗殆尽。 想象一下 Claude Code 在处理一个大型代码重构任务时需要装进上下文的东西:系统指令、用户的个性化配置、项目规则、当前 Git 仓库的状态、几十轮对话的完整历史、每次工具调用的结果、40 多个工具的定义文档。所有这些信息都在争夺同一块有限的空间。 @@ -43,9 +43,7 @@ System prompt 是每次 API 调用都会携带的基础指令,你可以把它 **CLAUDE.md 记忆系统** 是 Claude Code 上下文工程中最复杂的模块,实现代码在 claudemd.ts 中,长达 **1,400 行**。 -CLAUDE.md 是一种让用户告诉 Claude 项目规则和个人偏好的机制。但 Claude Code 的设计远超一个简单的配置文件。它建立了一套 **五层优先级的层级加载系统**,从低到高分别是: - -![CLAUDE.md 五层加载](../imgs/04-ctx-five-layers.png) +CLAUDE.md 是一种让用户告诉 Claude 项目规则和个人偏好的机制。当前版本按优先级从低到高加载四种指令作用域:管理策略、用户、项目和本地。 第一层是 **全局管理级**,路径为 `/etc/claude-code/CLAUDE.md`。这个位置通常由企业 IT 管理员配置,用于在整个组织范围内强制执行统一的规则。比如"所有代码变更必须包含测试"或者"禁止直接操作生产数据库"。 @@ -55,21 +53,21 @@ CLAUDE.md 是一种让用户告诉 Claude 项目规则和个人偏好的机制 第四层是 **本地级**,文件名为 `CLAUDE.local.md`。这个文件被 gitignore,专门存放个人的私有配置。比如本地的 API 密钥路径或者特殊的开发环境设置。 -第五层是 **自动记忆**,通过 TEAMMEM 这个 feature flag 控制。这是一个实验性功能,系统会自动从对话中提取有价值的信息并持久化。 +自动记忆不是 CLAUDE.md 的第五层,而是独立的机制。当前 2.1.x 默认启用自动记忆,将每个仓库的笔记保存到 `~/.claude/projects//memory/`,每次 session 开始时加载 `MEMORY.md` 的前 200 行或 25 KB。可以通过 `/memory`、项目设置或 `CLAUDE_CODE_DISABLE_AUTO_MEMORY` 开关。 -这五层的加载顺序意味着高优先级的配置会覆盖低优先级的配置。一个项目级的规则可以覆盖用户级的默认设置,而本地级的配置又可以覆盖项目级的规则。 +这四种指令作用域的加载顺序意味着越具体的配置越晚加载。项目级规则可以跟随用户级默认设置,本地级配置又可以跟随项目级规则。自动记忆作为学习到的上下文单独加载,不是可以覆盖 CLAUDE.md 的指令作用域。 -CLAUDE.md 还支持一个强大的 **@include 指令系统**,允许一个 CLAUDE.md 文件引用其他文件的内容。语法支持四种路径格式:`@path` 相对路径、`@./relative` 显式相对路径、`@~/home` 用户目录路径、`@/absolute` 绝对路径。系统只在 **叶子文本节点** 中解析 @include 指令,不会在代码块里误触发。同时有 **循环引用检测** 机制,通过一个 Set 数据结构追踪已经处理过的文件路径,防止 A 引用 B、B 又引用 A 导致的无限递归。系统支持 200 多种文件扩展名,会自动屏蔽二进制文件。 +CLAUDE.md 还支持一个强大的 **@include 指令系统**,允许一个 CLAUDE.md 文件引用其他文件的内容。语法支持四种路径格式:`@path` 相对路径、`@./relative` 显式相对路径、`@~/home` 用户目录路径、`@/absolute` 绝对路径。系统只在 **叶子文本节点** 中解析 @include 指令,不会在代码块里误触发。同时有 **循环引用检测** 机制,通过一个 Set 数据结构追踪已经处理过的文件路径,防止 A 引用 B、B 又引用 A 导致的无限递归。当前公开文档将嵌套引用限制为四层。 整个记忆系统有几个 **关键常量** 控制其边界: -- `MAX_MEMORY_CHARACTER_COUNT = 40000`:所有 CLAUDE.md 内容合并后的总字符上限 +- `MAX_MEMORY_CHARACTER_COUNT = 40000`:3 月源码快照中合并 CLAUDE.md 的字符上限 - `MAX_ENTRYPOINT_LINES = 200`:MEMORY.md 文件的最大行数 - `MAX_ENTRYPOINT_BYTES = 25000`:MEMORY.md 文件的最大字节数 -这些限制确保记忆系统不会过度膨胀,在上下文窗口中占据过多空间。 +其中两个 MEMORY.md 限制属于当前公开行为,合并 CLAUDE.md 的常量则保留为历史源码快照细节,当前公开文档没有确认它仍是现行限制。 -**权限规则** 从两个位置加载:`~/.claude/settings.json` 是用户级设置,`.claude-permissions.json` 是项目级设置。两者合并后解析为 **ToolPermissionContext** 数据结构,包含 allow、deny、ask 三种规则。这些规则会被注入到 system prompt 中,让模型知道哪些操作可以直接执行、哪些需要用户确认、哪些被明确禁止。 +**权限规则** 从用户、项目、本地和管理设置中加载,合并为 allow、deny、ask 三种规则。这些规则决定哪些操作可以直接执行、哪些需要用户确认、哪些被明确禁止。 ## 3️⃣ 分层优先级:当空间不够时,谁先走 @@ -167,7 +165,7 @@ Claude Code 对 Prompt Cache 做了两个层面的精细管理。 **Cursor** 据报道在上下文管理上做了大量工作,特别是在代码上下文的精准检索方面。它使用了 **向量检索** 技术来找到与当前任务最相关的代码片段。这和 Claude Code 的方法互补:一个侧重于 **检索精度**,一个侧重于 **全生命周期管理**。 -**Claude Code** 的上下文工程在行业内处于 **系统性最强** 的位置。五层优先级的记忆加载、六级的压缩优先级、预取缓存体系、动态注入策略、Prompt Cache 精细管理,形成了一套完整的端到端解决方案。它的投入程度体现在 1,400 行的 CLAUDE.md 加载代码上,也体现在专门为 cache break 设置检测模块的工程纪律上。 +**Claude Code** 的上下文工程在行业内处于 **系统性最强** 的位置。四种作用域的指令加载、六级的压缩优先级、预取缓存体系、动态注入策略、Prompt Cache 精细管理,形成了一套完整的端到端解决方案。它的投入程度体现在历史快照的 1,400 行 CLAUDE.md 加载代码上,也体现在专门为 cache break 设置检测模块的工程纪律上。 ## 8️⃣ 总结 diff --git a/docs/05-Compaction-System.md b/docs/05-Compaction-System.md index 968d0b3..0e3de72 100644 --- a/docs/05-Compaction-System.md +++ b/docs/05-Compaction-System.md @@ -4,7 +4,7 @@ ## Why Every AI Agent Hits a Compression Wall -Every large language model has a hard limit: the **context window**. Think of it as the model's "working memory capacity," similar to how much information a human brain can hold simultaneously while solving a problem. The total amount of text a model can process in a single conversation is capped. Claude's context window is 200K tokens, GPT-4o's is 128K tokens. These numbers sound large, but in Agent scenarios they get consumed remarkably fast. +Every large language model has a hard limit: the **context window**. Think of it as the model's "working memory capacity," similar to how much information a human brain can hold simultaneously while solving a problem. The total amount of text a model can process in a single conversation is capped. Claude Code sessions commonly use 200K, while supported models can use up to 1M tokens. These numbers sound large, but in Agent scenarios they get consumed remarkably fast. Why so fast? Because Agents are fundamentally different from regular chatbots. In a normal chat, a human and a model exchange messages of a few dozen to a few hundred tokens each. But an Agent needs to read files, execute commands, and search codebases. Each tool call can return thousands of tokens. A single `FileRead` on a 500-line source file easily eats up 2,000-3,000 tokens. A complex programming task might involve **dozens of tool calls**, each stuffing large amounts of content into the context. At this rate, a dozen rounds of interaction can fill up that 200K window. @@ -113,18 +113,18 @@ Session Memory Compact preserves **structured key information**, while Full Comp ### Trigger Conditions -Full Compact activates when token usage exceeds the **context window minus a 13,000-token buffer**, and Session Memory Compact hasn't freed enough space. +In the March source snapshot, Full Compact activated when token usage exceeded the **context window minus a 13,000-token buffer**. Current 2.1.x builds let users set the auto-compact window with `/autocompact`, `--autocompact`, or `CLAUDE_CODE_AUTO_COMPACT_WINDOW` from 100K to 1M tokens. With no override, compaction follows the model's context limit and provider-specific exceptions. Session Memory Compact still runs before Full Compact when it can free enough space. Key constants: ``` -AUTOCOMPACT_BUFFER_TOKENS = 13,000 // trigger buffer -WARNING_THRESHOLD_BUFFER_TOKENS = 20,000 // warning threshold +AUTOCOMPACT_BUFFER_TOKENS = 13,000 // March snapshot only +WARNING_THRESHOLD_BUFFER_TOKENS = 20,000 // March snapshot only MAX_OUTPUT_TOKENS_FOR_SUMMARY = 20,000 // max summary output MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3 // circuit breaker threshold ``` -The 13,000-token buffer ensures the model has enough **generation space**. If compaction only triggers when the context is completely full, the model wouldn't have room to generate a response. The 20,000-token warning threshold is an earlier alert, signaling "getting close to full." +These constants describe the March 31 source snapshot, not a universal current threshold. The current client exposes a configurable auto-compact window and caps it at the selected model's context window. ### Independent Agent Execution 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 ff111fd..521b033 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" @@ -4,7 +4,7 @@ ## 为什么 AI Agent 都绕不开压缩问题 -每一个大语言模型都有一个硬性限制:**上下文窗口**。你可以把它理解为模型的"工作记忆容量",就像人类在解题时脑子里能同时装下的信息量一样,模型在一次对话中能处理的文本总量是有上限的。Claude 的上下文窗口是 200K token,GPT-4o 是 128K token,这些数字看起来很大,但在 Agent 场景下消耗速度极快。 +每一个大语言模型都有一个硬性限制:**上下文窗口**。你可以把它理解为模型的"工作记忆容量",就像人类在解题时脑子里能同时装下的信息量一样,模型在一次对话中能处理的文本总量是有上限的。Claude Code session 常用 200K,上下文扩展可用时支持的模型最高可达 1M token,这些数字看起来很大,但在 Agent 场景下消耗速度极快。 为什么消耗这么快?因为 Agent 和普通聊天不同。普通聊天是人和模型一问一答,每条消息几十到几百个 token。但 Agent 需要读文件、执行命令、搜索代码,每一次工具调用的返回结果可能就是几千个 token。一个 `FileRead` 读一个 500 行的源代码文件,轻松吃掉 2000-3000 token。一个复杂的编程任务可能涉及 **几十次工具调用**,每次都在往上下文里塞入大量内容。按这个速度,十几轮交互就能把 200K 的窗口填满。 @@ -121,18 +121,18 @@ Session Memory Compact 保留的是 **结构化的关键信息**,而 Full Comp ### 触发条件 -当 token 用量超过 **上下文窗口减去 13,000 token 的缓冲区**,且 Session Memory Compact 释放的空间不够时,Full Compact 启动。 +3 月源码快照中,token 用量超过 **上下文窗口减去 13,000 token 的缓冲区**时会启动 Full Compact。当前 2.1.x 版本可以通过 `/autocompact`、`--autocompact` 或 `CLAUDE_CODE_AUTO_COMPACT_WINDOW` 设置 100K 到 1M token 的自动压缩窗口。没有覆盖设置时,压缩跟随模型上下文上限和不同供应商的例外规则。Session Memory Compact 仍会在前面尝试释放空间。 关键常量如下: ``` -AUTOCOMPACT_BUFFER_TOKENS = 13,000 // 触发缓冲区 -WARNING_THRESHOLD_BUFFER_TOKENS = 20,000 // 警告阈值 +AUTOCOMPACT_BUFFER_TOKENS = 13,000 // 仅适用于 3 月快照 +WARNING_THRESHOLD_BUFFER_TOKENS = 20,000 // 仅适用于 3 月快照 MAX_OUTPUT_TOKENS_FOR_SUMMARY = 20,000 // 摘要最大输出 MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3 // 熔断器阈值 ``` -13,000 token 的缓冲区设计是为了给模型留出足够的 **生成空间**。如果等到上下文完全填满才压缩,模型连回复的空间都没有了。20,000 token 的警告阈值则是一个更早的预警线,提醒系统"快要满了"。 +这些常量描述的是 3 月 31 日源码快照,不是当前版本的通用阈值。当前客户端提供可配置的自动压缩窗口,并将它限制在所选模型的上下文窗口内。 ### 独立 Agent 执行 diff --git a/docs/06-Permission-System.md b/docs/06-Permission-System.md index 84bb9ce..786baac 100644 --- a/docs/06-Permission-System.md +++ b/docs/06-Permission-System.md @@ -10,29 +10,32 @@ This is exactly the problem that the permission system solves. It needs to balan Claude Code's permission system is the **single largest module** in the entire codebase, with over 6,300 lines of code spread across 25 files. This level of investment alone speaks to how seriously Anthropic takes Agent security. By comparison, many open-source Agent frameworks have permission mechanisms that amount to a simple whitelist/blacklist, or no permission controls at all. -## 1️⃣ Three Permission Modes +## 1️⃣ Six Permission Modes in 2.1.x -Claude Code offers three permission modes to accommodate different usage scenarios and risk appetites: +Claude Code's current CLI accepts six permission mode values. `manual` is the CLI value for the user-facing **Manual** mode; public documentation labels that mode `default`. | Mode | How It Works | Best For | |------|-------------|----------| -| **default** | Prompts user confirmation for every tool call | Maximum safety, ideal when working with sensitive code or production environments | -| **auto** | ML classifier pre-assesses risk; only high-risk actions prompt the user | Day-to-day development, requires Opus 4.6 or higher | -| **plan** | Model plans actions first with confidence scores; only low-confidence actions prompt | Complex multi-step tasks | +| **manual (public docs: default)** | Manual review for actions that require approval; reads and built-in read-only commands can run without prompting | Sensitive work | +| **acceptEdits** | Automatically accepts file edits and common filesystem commands | Iterating on code | +| **plan** | Reads and proposes a plan without making changes | Planning before changes | +| **auto** | Uses background safety checks to reduce prompts | Long tasks | +| **dontAsk** | Runs only pre-approved tools and denies anything else | Locked-down scripts and CI | +| **bypassPermissions** | Skips ordinary permission checks; use only in isolated containers or VMs | Sandboxed automation | -### Default Mode: Full Human Confirmation +### Manual Mode: Human Review -This is the most conservative mode. Every time the Agent wants to execute a tool call, the flow is: +This is the most conservative interactive mode for operations that require approval. The flow is: 1. Display the tool name, parameters, and affected file paths to the user 2. User chooses: **Allow** to proceed / **Deny** to reject / **Allow-All-For-This-Tool** to permit all future calls of this tool 3. After choosing Allow-All, that tool won't prompt again for the rest of the session -The strength of Default mode is maximum safety since all operations go through human review. The weakness is low efficiency. A complex task might involve dozens of tool calls, and confirming each one severely disrupts workflow. This is why Claude Code provides two additional modes. +The strength of Manual mode is maximum oversight. The weakness is low efficiency. A complex task might involve dozens of approval prompts, so Claude Code provides five other modes for different tradeoffs. ### Auto Mode: ML Classifier-Assisted Judgment -Auto mode introduces an **ML classifier** to automate safety judgments, dramatically reducing the number of prompts requiring human confirmation: +Auto mode introduces background safety checks, including an **ML classifier** for eligible commands, to reduce the number of prompts requiring human confirmation: ``` Tool call request @@ -47,27 +50,26 @@ Low confidence or medium risk → Prompt user for confirmation The **YOLO classifier** has an interesting name. YOLO in internet culture stands for "You Only Live Once," implying "just go for it." In Claude Code's context, it refers to a classifier that makes a side-query call to the Claude model to evaluate command safety. Its implementation lives in `yoloClassifier.ts`, and it works by sending the bash command about to be executed, the command pattern, and current environment information to Claude, which then judges whether the command is safe and returns a match result with a confidence score. -Auto mode requires Opus 4.6 or higher because the classifier's accuracy directly depends on the model's judgment capability. Running the classifier with a weaker model would lead to higher error rates: either letting dangerous commands through, or generating frequent false positives that interrupt users. +Auto mode availability depends on the account and model. The current CLI exposes it when its requirements are met; it is not a universal three-mode feature of the March source snapshot. ### Plan Mode: Planning Before Execution -Plan mode's approach is to have the model plan before executing: +Plan mode's approach is to explore and plan before implementation: -1. The model outputs an execution plan listing every step it intends to take -2. Each step carries a **confidence score** indicating how certain the model is about that operation's safety -3. High-confidence steps execute automatically -4. Low-confidence steps pause for user confirmation +1. The model reads the relevant project context +2. It proposes an implementation plan +3. File changes wait for approval before execution This mode is especially well-suited for complex multi-step tasks. Users can see the complete plan first and intervene on questionable steps, without needing to make decisions at every single step. It works with the `/plan` command, allowing users to proactively trigger planning mode. -## 2️⃣ 42 Dangerous Patterns: The Default Safety Barrier +## 2️⃣ 42 Dangerous Patterns in the March Source Snapshot -The code hardcodes **42 auto-reject bash patterns**. Under default permission configuration, these patterns are automatically intercepted. +The leaked March 31 source snapshot listed **42 bash patterns**. This exact count and list are historical snapshot data, not a verified description of current 2.1.227 behavior. Current public documentation describes a tiered permission system with built-in read-only commands and configurable deny, ask, and allow rules. However, a common misconception needs to be clarified: **these rules are not absolutely unbypassable.** If a user explicitly configures an allow rule in `settings.json`, such as `Bash(python*)`, then python commands will be permitted. If `bypassPermissions` mode is used, all restrictions are skipped entirely. -The 42 patterns actually take effect in these scenarios: -- In **default mode**, when no allow rule matches, these commands trigger a confirmation prompt +In the March snapshot, the 42 patterns took effect in these scenarios: +- In **manual mode**, when no allow rule matched, these commands triggered a confirmation prompt - In **auto mode**, the ML classifier will not auto-approve these patterns; they must go through user confirmation - When **entering auto mode**, Dangerous Rule Stripping automatically removes allow rules that involve these patterns, preventing the classifier from auto-approving based on old rules @@ -125,20 +127,21 @@ Users can customize permission rules in `~/.claude/settings.json` for more granu Rules support **wildcard matching**. `Bash(git log *)` matches all commands starting with `git log`. The processing order is: -1. Check deny rules; match triggers auto-reject -2. Check allow rules; match triggers auto-allow -3. No match on either falls through to the current permission mode's default flow +1. Check deny rules; a match blocks the tool +2. Check ask rules; a match requires confirmation +3. Check allow rules; a match permits the tool +4. No match falls through to the current permission mode's default flow This design lets users customize based on their work context. For instance, a frontend developer might allow `npm run build` and `npm run test` because these commands are safe in their project. But the same commands might behave completely differently in another project, making this configuration inherently project-specific. -## 4️⃣ Permission Mode State Machine +## 4️⃣ Permission Mode Transitions -Switching between the three modes follows strict state machine rules: +The March source snapshot described these mode transitions: ``` -default ──→ bypass, when user explicitly enables dangerouslySkipPermissions -bypass ──→ default, when user disables or after N operations, auto-reverts -default ──→ auto, when classifier is enabled and user gives explicit consent +manual ──→ bypassPermissions, when the user explicitly enables bypass +manual ──→ auto, when classifier access is enabled and the user consents +any mode ──→ plan, when the user starts a planning session ``` There's a critical safety mechanism here: **Dangerous Rule Stripping**. @@ -174,7 +177,7 @@ This kind of behavioral learning has precedents in traditional security systems. | Project | Permission Mechanism | Security Depth | Adaptability | |---------|---------------------|---------------|-------------| -| **Claude Code** | 3 modes + 42 hardcoded rules + ML classifier + file sandbox + behavioral learning | Multi-layered defense in depth | High: denial tracking + rule stripping | +| **Claude Code** | 6 modes + March snapshot's 42 rules + ML classifier + file sandbox | Multi-layered defense in depth | Current behavior varies by mode and model | | **Cursor** | User confirmation prompts | Single layer | None | | **Aider** | Whitelisted commands | Single layer | None | | **OpenAI Codex CLI** | Sandbox mode + confirmation prompts | Two layers | None | 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 9d877df..5982f60 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" @@ -10,35 +10,35 @@ Claude Code 的权限系统是整个代码库中 **规模最大的单一模块**,超过 6,300 行代码分布在 25 个文件中。这个投入规模本身就说明了 Anthropic 对 Agent 安全性的重视程度。相比之下,很多开源 Agent 框架的权限机制只是一个简单的白名单/黑名单,甚至完全没有权限控制。 -## 1️⃣ 三种权限模式 +## 1️⃣ 六种权限模式 -![三种权限模式](../imgs/06-perm-three-modes.png) - - -Claude Code 提供了三种权限模式,适应不同的使用场景和风险偏好: +当前 CLI 接受六种权限模式值。`manual` 是面向用户的 **Manual** 模式在 CLI 中的值,公开文档将这个模式标为 `default`。 | 模式 | 工作方式 | 适用场景 | |------|---------|---------| -| **default** | 每次工具调用都弹窗让用户确认 | 最安全,适合接触敏感代码和生产环境时使用 | -| **auto** | ML 分类器预判风险,只有高风险操作才弹窗 | 日常开发,需要 Opus 4.6 或更高版本模型 | -| **plan** | 模型先规划动作并给出置信度评分,低置信度才弹窗 | 复杂的多步骤任务 | +| **manual(公开文档:default)** | 需要审批的操作由人工确认,读取和内置只读命令可以免弹窗 | 敏感工作 | +| **acceptEdits** | 自动接受文件编辑和常见文件系统命令 | 迭代编写代码 | +| **plan** | 只读取并提出计划,不进行修改 | 修改前规划 | +| **auto** | 使用后台安全检查,减少弹窗 | 长任务 | +| **dontAsk** | 只运行预先批准的工具,其他操作直接拒绝 | 锁定的脚本和 CI | +| **bypassPermissions** | 跳过普通权限检查,只应在隔离容器或虚拟机中使用 | 沙箱自动化 | -### Default 模式:完全人工确认 +### Manual 模式:人工审核 -这是最保守的模式。Agent 每次想要执行一个工具调用时,流程如下: +这是交互场景下最保守的模式。对于需要审批的操作,流程如下: 1. 向用户展示工具名称、参数、影响的文件路径 2. 用户选择:**Allow** 放行 / **Deny** 拒绝 / **Allow-All-For-This-Tool** 放行该工具的所有后续调用 3. 如果用户选择了 Allow-All,该工具在本次 session 内后续调用不再弹窗 -Default 模式的优点是安全性最高,所有操作都经过人工审核。缺点是效率低下,一个复杂任务可能涉及几十次工具调用,每次都要确认非常打断工作流。这就是为什么 Claude Code 还提供了另外两种模式。 +Manual 模式的优点是监督最充分。缺点是效率低下,一个复杂任务可能涉及几十次审批。这就是为什么 Claude Code 还提供了另外五种模式。 ### Auto 模式:ML 分类器辅助判断 ![YOLO分类器决策流程](../imgs/06-perm-yolo-classifier.png) -Auto 模式引入了一个 **ML 分类器** 来自动化安全判断,大幅减少需要人工确认的次数: +Auto 模式引入后台安全检查,其中包括对符合条件的命令使用 **ML 分类器**,从而减少需要人工确认的次数: ``` 工具调用请求 @@ -53,30 +53,29 @@ YOLO 分类器预判 这里的 **YOLO 分类器** 名字很有意思。YOLO 在互联网文化中是 "You Only Live Once" 的缩写,暗示"放手去做"。但在 Claude Code 的上下文中,它指的是一个通过 side-query 调用 Claude 模型来评估命令安全性的分类器。它的实现在 `yoloClassifier.ts` 文件中,工作方式是:把即将执行的 bash 命令、命令模式、当前环境信息发送给 Claude,让模型判断这个命令是否安全,并返回匹配结果和置信度评分。 -Auto 模式需要 Opus 4.6 或更高版本的模型支持,因为分类器的准确性直接依赖模型的判断能力。用较弱的模型运行分类器会导致误判率升高,要么放过了危险命令,要么频繁误报打断用户。 +Auto 模式是否可用取决于账号和模型。当前 CLI 只有在满足条件时才会展示它,不再是 3 月源码快照中的固定三模式之一。 ### Plan 模式:规划先行 -Plan 模式的思路是让模型在执行之前先做规划: +Plan 模式的思路是让模型在修改前先探索和规划: -1. 模型输出一份执行计划,列出即将执行的每一步 -2. 每一步都带有一个 **置信度评分**,表示模型对该操作安全性的确信程度 -3. 高置信度的步骤自动执行 -4. 低置信度的步骤暂停,等待用户确认 +1. 模型读取相关的项目上下文 +2. 模型提出实施计划 +3. 文件修改在执行前等待用户批准 这种模式特别适合复杂的多步骤任务。用户可以先看到完整的计划,对有疑虑的步骤进行干预,而不需要在每一步都做决定。它配合 `/plan` 命令使用,让用户可以主动触发规划模式。 -## 2️⃣ 42 条危险模式:默认的安全防线 +## 2️⃣ 3 月源码快照中的 42 条危险模式 ![42条危险模式](../imgs/06-perm-42-rules.png) -代码中硬编码了 **42 条自动拒绝的 bash 模式**。在默认权限配置下,这些模式会被自动拦截。 +泄露的 3 月 31 日源码快照列出了 **42 条 bash 模式**。这个精确数量和清单属于历史快照数据,不是当前 2.1.227 行为的已验证描述。当前公开文档描述的是分层权限系统,包括内置只读命令以及可配置的 deny、ask、allow 规则。 但需要澄清一个常见的误解:**这些规则并非绝对不可绕过。** 如果用户在 `settings.json` 中显式配置了 allow 规则,比如 `Bash(python*)`,那么 python 命令就会被放行。如果使用了 `bypassPermissions` 模式,所有限制都会被跳过。 -这 42 条模式真正发挥作用的场景是: -- 在 **default 模式** 下,没有匹配到 allow 规则时,这些命令会弹窗要求用户确认 +在 3 月快照中,这 42 条模式发挥作用的场景是: +- 在 **manual 模式** 下,没有匹配到 allow 规则时,这些命令会弹窗要求用户确认 - 在 **auto 模式** 下,ML 分类器不会自动放行这些模式,必须走用户确认 - 进入 **auto 模式时**,Dangerous Rule Stripping 会自动剥离涉及这些模式的 allow 规则,防止分类器按旧规则自动放行 @@ -134,23 +133,24 @@ git, kubectl, aws/gcloud/gsutil 规则支持 **通配符匹配**。`Bash(git log *)` 会匹配所有以 `git log` 开头的命令。规则的处理顺序是: -1. 检查 deny 规则,命中则自动拒绝 -2. 检查 allow 规则,命中则自动放行 -3. 都不命中,走当前权限模式的默认流程 +1. 检查 deny 规则,命中则阻止工具 +2. 检查 ask 规则,命中则要求确认 +3. 检查 allow 规则,命中则允许工具 +4. 都不命中,走当前权限模式的默认流程 这个设计让用户可以根据自己的工作场景做定制。比如一个前端开发者可以放行 `npm run build` 和 `npm run test`,因为这些命令在自己的项目中是安全的。但同一条命令在另一个项目中可能有完全不同的行为,所以这种配置天然是项目相关的。 -## 4️⃣ 权限模式状态机 +## 4️⃣ 权限模式切换 ![权限模式状态机](../imgs/06-perm-state-machine.png) -三种模式之间的切换遵循严格的状态机规则: +3 月源码快照描述了这些模式切换: ``` -default ──→ bypass,用户主动开启 dangerouslySkipPermissions -bypass ──→ default,用户关闭或达到 N 次操作后自动回退 -default ──→ auto,分类器启用且用户明确同意 +manual ──→ bypassPermissions,用户主动开启 bypass +manual ──→ auto,分类器可用且用户明确同意 +任意模式 ──→ plan,用户启动规划 session ``` 这里有一个重要的安全机制:**Dangerous Rule Stripping**,危险规则剥离。 @@ -189,7 +189,7 @@ Dangerous Rule Stripping 通过在模式切换时主动清理潜在的危险 all | 项目 | 权限机制 | 安全层次 | 自适应能力 | |------|---------|---------|-----------| -| **Claude Code** | 三模式 + 42 条硬编码规则 + ML 分类器 + 文件沙箱 + 行为学习 | 多层纵深防御 | 高,denial tracking + rule stripping | +| **Claude Code** | 六模式 + 3 月快照的 42 条规则 + ML 分类器 + 文件沙箱 | 多层纵深防御 | 当前行为取决于模式与模型 | | **Cursor** | 用户确认弹窗 | 单层 | 无 | | **Aider** | 白名单命令 | 单层 | 无 | | **OpenAI Codex CLI** | 沙箱模式 + 确认弹窗 | 两层 | 无 | diff --git a/docs/07-Memory-System.md b/docs/07-Memory-System.md index c312eac..e9803dc 100644 --- a/docs/07-Memory-System.md +++ b/docs/07-Memory-System.md @@ -26,9 +26,9 @@ This records "what the Agent has done before." This category accumulates automat The separation of these two categories is a significant design decision. Instruction memory is **declarative**, describing "what things should be like." Conversation memory is **procedural**, recording "what happened." Mixing them together leads to information management chaos: today's debugging notes shouldn't live in the same place as permanent code style standards. -## 2️⃣ CLAUDE.md Five-Layer Loading System +## 2️⃣ CLAUDE.md Scopes and Auto Memory -CLAUDE.md is the core carrier of Claude Code's instruction memory. Its loading system is divided into five tiers, from lowest to highest priority: +CLAUDE.md is the core carrier of Claude Code's instruction memory. Current 2.1.x builds load four instruction scopes, from broadest to most specific: ``` Priority from low to high: @@ -49,14 +49,11 @@ Priority from low to high: → Personal project config, added to gitignore, not shared → Typical content: local environment-specific settings, personal dev preferences -5. Auto Memory feature flag: TEAMMEM - → Team auto-synced memory, not yet officially released - → Design goal: let team members' Agents automatically share valuable discoveries ``` -Higher-priority content overrides **conflicting** lower-priority content, while non-conflicting content from all levels is preserved. In practice, content from all tiers is concatenated together and injected into the system prompt, loaded in order from lowest to highest priority. When instructions from two tiers contradict each other, the higher-priority instruction appearing later wins, because LLMs have stronger attention weight on instructions positioned later in the context. Non-conflicting instructions from any tier all remain effective simultaneously. Within the same tier, multiple files under the rules directory are merged in alphabetical order. +Higher-priority content follows **conflicting** lower-priority content, while non-conflicting content from all four scopes is preserved. Auto memory is separate: it is on by default, stores per-repository notes in `~/.claude/projects//memory/`, and loads the first 200 lines or 25 KB of `MEMORY.md` in every session. Use `/memory`, `autoMemoryEnabled`, or `CLAUDE_CODE_DISABLE_AUTO_MEMORY` to manage it. -The inspiration for this five-layer design is clear: **it is isomorphic to configuration management hierarchies in software engineering**. Consider CSS cascading rules, Kubernetes ConfigMap override chains, or Git's configuration levels. They all follow the same pattern: more specific configuration overrides more general configuration, local overrides global. Claude Code applies this well-proven pattern to Agent instruction memory management. +The inspiration for this scoped design is clear: **it is isomorphic to configuration management hierarchies in software engineering**. Consider CSS cascading rules, Kubernetes ConfigMap override chains, or Git's configuration levels. They all follow the same pattern: more specific configuration follows more general configuration. Claude Code applies this well-proven pattern to Agent instruction memory management. This hierarchical design solves a very common real-world need: **different projects within the same company require different Agent behaviors, yet share some company-wide universal standards**. Global admin level holds universal standards, project level holds project-specific standards, local level holds personal preferences, all without interference. @@ -87,14 +84,13 @@ Introducing a file inclusion mechanism also introduces security risks. Claude Co - **Code block immunity**: The @ symbol is only parsed in leaf text nodes; @ inside markdown code blocks does not trigger file inclusion. This prevents @ in code examples from being misinterpreted - **Circular reference detection**: A Set data structure tracks already-processed file paths. If A includes B and B includes A, the detection mechanism stops on the second encounter with A, preventing infinite recursion -- **File type filtering**: Supports 200+ text file extensions, automatically blocking binary files. This prevents the Agent from accidentally loading compiled artifacts or image files as instructions -- **Total size limit**: All content brought in by @include has a total character cap of 40,000. This prevents a malicious or mistaken configuration from injecting massive text into the system prompt, which would both waste tokens and potentially override important instructions +- **Nested import depth**: Current public documentation limits nested `@` imports to four hops. Code spans and fenced code blocks are skipped when imports are detected. ## 4️⃣ MEMORY.md: Long-Term Memory Written by the Agent Itself MEMORY.md has a fundamental difference from CLAUDE.md: **CLAUDE.md is written by humans for the Agent to read; MEMORY.md is written by the Agent for itself to read**. -When the Agent discovers information worth remembering during its work, such as user preferences, special project conventions, or recurring problem patterns, it proactively writes this information to MEMORY.md. At the start of the next session, this information gets loaded into the system prompt, allowing the Agent to "remember" what it learned previously. +Auto memory lets Claude save information worth remembering during its work, such as build commands, debugging insights, project conventions, and user preferences. It stores an index and topic files under the repository's memory directory, then loads the index at the start of the next session. ### Capacity Limits @@ -116,7 +112,7 @@ Claude Code's source also contains several memory-related feature modules that r - **memoryAge.ts**: Tracks the age of each memory entry. Old entries may be outdated; tracking age lays the foundation for future "memory eviction" strategies - **memoryScan.ts**: Scans memory content with pattern matching to identify duplicate, conflicting, or outdated entries -- **EXTRACT_MEMORIES feature flag**: Automatically extracts key memories from conversations, not yet officially released. Once enabled, MEMORY.md will evolve from "Agent proactively writes" to "system automatically extracts," dramatically reducing the mental overhead of memory management +- **EXTRACT_MEMORIES and TEAMMEM feature flags**: These names belong to the March source snapshot. Automatic memory extraction is now a shipped user-facing feature, controlled by auto-memory settings rather than by those snapshot flags. - **MEMORY_SHAPE_TELEMETRY feature flag**: Memory shape telemetry that collects statistics on user memory usage to guide future optimizations ## 5️⃣ Session Memory: Session-Level Short-Term Memory @@ -159,13 +155,13 @@ This bears similarity to the **priority inversion** problem in operating systems | Project | Instruction Memory | Conversation Memory | Hierarchy | Automation Level | |---------|-------------------|--------------------|-----------|-----------------| -| **Claude Code** | CLAUDE.md five-layer system + @include | MEMORY.md + Session Memory | Five-layer override | Medium-high, Session Memory auto-persists | +| **Claude Code** | Four CLAUDE.md scopes + @include | Auto memory + Session Memory | Four-scope override | Medium-high, auto memory persists project notes | | **Cursor** | .cursorrules single file | No persistence | Single layer | Low | | **GitHub Copilot** | .github/copilot-instructions.md | None | Single layer | Low | | **Aider** | .aider.conf.yml config | None | Single layer | Low | | **Devin** | Built-in knowledge base | Limited session memory | Opaque | Medium | -Claude Code clearly leads the industry in memory system design. The five-layer loading system provides complete coverage from global to local. @include supports modular organization. The separation of MEMORY.md and Session Memory ensures long-term and short-term memory don't interfere with each other. Behind these design decisions lies a clear understanding: **an Agent's capability ceiling depends on how much correct context information it can access**. The memory system is the source of that context information, and its quality directly determines Agent performance. +Claude Code clearly leads the industry in memory system design. The four instruction scopes provide coverage from managed policy to local project preferences. @include supports modular organization. Auto memory and Session Memory separate durable project notes from short-term compaction context. Behind these design decisions lies a clear understanding: **an Agent's capability ceiling depends on how much correct context information it can access**. The memory system is the source of that context information, and its quality directly determines Agent performance. --- 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 e74255f..bcebbe5 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" @@ -29,12 +29,9 @@ Claude Code 的记忆分为两大类,各自承担不同的职责: 两类记忆的分离是一个重要的设计决策。指令记忆是 **声明式的**,描述"应该是什么样";会话记忆是 **过程式的**,记录"发生了什么"。混在一起会导致信息管理混乱:今天的调试记录不应该和永久的代码风格规范放在同一个地方。 -## 2️⃣ CLAUDE.md 五层加载体系 +## 2️⃣ CLAUDE.md 作用域与自动记忆 -![五层记忆加载体系](../imgs/07-mem-five-layers.png) - - -CLAUDE.md 是 Claude Code 指令记忆的核心载体。它的加载体系分为五个层级,从低优先级到高优先级依次是: +CLAUDE.md 是 Claude Code 指令记忆的核心载体。当前 2.1.x 版本加载四种指令作用域,从范围最广到最具体依次是: ``` 优先级从低到高: @@ -55,14 +52,11 @@ CLAUDE.md 是 Claude Code 指令记忆的核心载体。它的加载体系分为 → 个人项目配置,加入 gitignore,不共享 → 典型内容:本地环境特殊配置、个人开发偏好 -5. 自动记忆 feature flag: TEAMMEM - → 团队自动同步的记忆,尚未正式发布 - → 设计目标:让团队成员的 Agent 自动共享有价值的发现 ``` -高优先级的内容会覆盖低优先级的**冲突**配置,不冲突的部分全部保留。实际上所有层级的内容都会被拼接在一起注入到 system prompt 中,加载顺序从低到高。当两个层级的指令存在矛盾时,排在后面的高优先级指令会胜出,因为 LLM 对上下文中靠后位置的指令有更强的注意力权重。不冲突的指令无论来自哪个层级,都会同时生效。同一层级内,rules 目录下的多个文件按字母序合并。 +高优先级的内容会跟随低优先级的**冲突**配置,不冲突的部分全部保留。自动记忆是独立机制:当前默认开启,将每个仓库的笔记保存到 `~/.claude/projects//memory/`,每次 session 加载 `MEMORY.md` 的前 200 行或 25 KB。可以通过 `/memory`、`autoMemoryEnabled` 或 `CLAUDE_CODE_DISABLE_AUTO_MEMORY` 管理。 -这个五层设计的灵感来源很明显:**它和软件工程中的配置管理层级是同构的**。想一下 CSS 的层叠规则、Kubernetes 的 ConfigMap 覆盖链、Git 的配置层级。它们都遵循同一个模式:更具体的配置覆盖更通用的配置,本地的覆盖全局的。Claude Code 把这个久经验证的模式应用到了 Agent 的指令记忆管理中。 +这个作用域设计的灵感来源很明显:**它和软件工程中的配置管理层级是同构的**。想一下 CSS 的层叠规则、Kubernetes 的 ConfigMap 覆盖链、Git 的配置层级。它们都遵循同一个模式:更具体的配置跟随更通用的配置。Claude Code 把这个久经验证的模式应用到了 Agent 的指令记忆管理中。 这种层级设计解决了一个现实中很常见的需求:**同一家公司的不同项目需要不同的 Agent 行为,但又有一些公司级的通用规范**。全局管理级放通用规范,项目级放项目特定的规范,本地级放个人偏好,互不干扰。 @@ -96,14 +90,13 @@ CLAUDE.md 是 Claude Code 指令记忆的核心载体。它的加载体系分为 - **代码块免疫**:只在叶子文本节点中解析 @ 符号,markdown 代码块内的 @ 不会触发文件包含。这防止了代码示例中的 @ 被误解析 - **循环引用检测**:通过 Set 数据结构追踪已处理的文件路径。如果 A 包含 B,B 又包含 A,检测机制会在第二次遇到 A 时停止,避免无限递归 -- **文件类型过滤**:支持 200+ 种文本文件扩展名,自动屏蔽二进制文件。这防止 Agent 意外将编译产物或图片文件作为指令加载 -- **总量限制**:所有 @include 引入的内容总字符上限 40,000。这防止一个恶意的或失误的配置把大量文本注入到 system prompt 中,既浪费 token 又可能覆盖重要指令 +- **嵌套引用深度**:当前公开文档将嵌套 `@` 引用限制为四层。检测引用时会跳过代码片段和 fenced code block。 ## 4️⃣ MEMORY.md:Agent 自己写的长期记忆 MEMORY.md 和 CLAUDE.md 有一个根本区别:**CLAUDE.md 是人写给 Agent 看的,MEMORY.md 是 Agent 自己写给自己看的**。 -当 Agent 在工作中发现了值得记住的信息,比如用户的偏好、项目的特殊约定、反复出现的问题模式,它会主动将这些信息写入 MEMORY.md。下次 session 开始时,这些信息会被加载到 system prompt 中,Agent 就能"记住"之前学到的东西。 +自动记忆会保存工作中值得记住的信息,比如构建命令、调试经验、项目约定和用户偏好。它把索引和主题文件保存在仓库专属的 memory 目录,下次 session 开始时加载索引。 ### 容量限制 @@ -125,7 +118,7 @@ Claude Code 源码中还包含几个与记忆相关的功能模块,展示了 - **memoryAge.ts**:追踪每条记忆条目的年龄。旧的记忆条目可能已经过时,追踪年龄为未来实现"记忆淘汰"策略奠定基础 - **memoryScan.ts**:对记忆内容做扫描和模式匹配,用于识别重复、冲突或过时的记忆条目 -- **EXTRACT_MEMORIES feature flag**:自动从对话中提取关键记忆,目前尚未正式发布。这个功能一旦启用,MEMORY.md 将从"Agent 主动写入"进化为"系统自动提取",大幅降低记忆管理的心智负担 +- **EXTRACT_MEMORIES 和 TEAMMEM feature flag**:这些名称属于 3 月源码快照。自动记忆提取已经成为当前版本的正式用户功能,通过自动记忆设置控制,不再由这些快照 flag 控制。 - **MEMORY_SHAPE_TELEMETRY feature flag**:记忆形态遥测,收集用户记忆使用的统计数据来指导未来优化 ## 5️⃣ Session Memory:会话级短期记忆 @@ -171,13 +164,13 @@ system prompt = | 项目 | 指令记忆 | 会话记忆 | 层级系统 | 自动化程度 | |------|---------|---------|---------|-----------| -| **Claude Code** | CLAUDE.md 五层体系 + @include | MEMORY.md + Session Memory | 五层覆盖 | 中高,Session Memory 自动沉淀 | +| **Claude Code** | CLAUDE.md 四种作用域 + @include | 自动记忆 + Session Memory | 四层覆盖 | 中高,自动记忆持久化项目笔记 | | **Cursor** | .cursorrules 单文件 | 无持久化 | 单层 | 低 | | **GitHub Copilot** | .github/copilot-instructions.md | 无 | 单层 | 低 | | **Aider** | .aider.conf.yml 配置 | 无 | 单层 | 低 | | **Devin** | 内置 knowledge base | 有限的 session 记忆 | 不透明 | 中 | -Claude Code 在记忆系统的设计上明显领先于同类产品。五层加载体系提供了从全局到本地的完整覆盖,@include 支持模块化组织,MEMORY.md 和 Session Memory 的分离确保了长短期记忆互不干扰。这些设计决策背后是一个清晰的认识:**Agent 的能力上限取决于它能获得多少正确的上下文信息**。记忆系统是上下文信息的源头,它的质量直接决定了 Agent 的表现。 +Claude Code 在记忆系统的设计上明显领先于同类产品。四种指令作用域覆盖了从管理策略到本地项目偏好的范围,@include 支持模块化组织,自动记忆和 Session Memory 将持久化项目笔记与短期压缩上下文分开。这些设计决策背后是一个清晰的认识:**Agent 的能力上限取决于它能获得多少正确的上下文信息**。记忆系统是上下文信息的源头,它的质量直接决定了 Agent 的表现。 --- diff --git a/docs/08-Tools-and-Skills.md b/docs/08-Tools-and-Skills.md index cfb3be9..15c7b04 100644 --- a/docs/08-Tools-and-Skills.md +++ b/docs/08-Tools-and-Skills.md @@ -8,7 +8,7 @@ Behind this design lies a broader industry trend: **AI Agents are evolving from ## 1️⃣ Tool Registration: A Panorama of 40+ Built-in Tools -Claude Code registers over 40 built-in tools, placing it in the top tier of the industry. For comparison, GitHub Copilot Agent has roughly 10 tools, Cursor has around 15, and the open-source Aider has only two broad categories: file editing and command execution. +The 40+ figure is a conservative lower bound from the March source snapshot, not a current registry total. Current 2.1.x builds also expose tools for scheduled tasks, LSP, PowerShell, background monitoring, worktrees, workflows, and cross-session messaging. Exact availability varies by model, plan, and host. **What does a high tool count mean?** It means the Agent can make more granular operational choices. For example, many Agents have only a single generic "execute command" tool, requiring file searches via `find` and content searches via `grep`. Claude Code breaks these into dedicated **GlobTool** and **GrepTool**, each with carefully designed parameters and return formats. This makes it easier for the model to pick the right tool, reducing errors and improving speed. @@ -59,10 +59,9 @@ API returns tool_use blocks └────────┬─────────┘ ↓ ┌──────────────────┐ -│ Permission Check │ Three permission modes: -│ │ default → judge by built-in rules -│ │ auto → auto-approve trusted tools -│ │ plan → only allow read-only operations +│ Permission Check │ Six permission modes: +│ │ manual (public docs: default), acceptEdits, plan +│ │ auto, dontAsk, bypassPermissions │ │ │ │ Checking flow: │ │ 1. Hardcoded danger patterns → reject @@ -141,7 +140,7 @@ Use this Skill when the user asks for ... ### Skill Execution: Sub-Agent Isolation -When a Skill is invoked, Claude Code doesn't execute it directly in the main Agent loop. Instead, it **forks an independent sub-Agent**. This design mirrors the process isolation philosophy in operating systems. +When a Skill is invoked, Claude Code runs it through the Skill tool. A Skill can execute in the main conversation or request an isolated background sub-Agent with `context: fork`; the March source snapshot's always-fork description is historical. ``` User types /my-skill or Agent selects autonomously 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 9a43f17..e144c8b 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" @@ -11,7 +11,7 @@ ![40+工具全景图](../imgs/08-tools-panorama.png) -Claude Code 内置注册了超过 40 个工具。这个数量在行业中属于第一梯队。作为对比,GitHub Copilot Agent 大约有 10 个工具,Cursor 有 15 个左右,而开源的 Aider 只有文件编辑和命令执行两大类。 +40+ 是 3 月源码快照中的保守下限,不是当前注册表的总数。当前 2.1.x 版本还提供定时任务、LSP、PowerShell、后台监控、worktree、工作流和跨 session 消息等工具,具体可用性取决于模型、套餐和运行环境。 **工具数量多意味着什么?** 意味着 Agent 可以做更精细的操作选择。举个例子,很多 Agent 只有一个通用的"执行命令"工具,搜索文件需要通过 `find` 命令,搜索内容需要通过 `grep` 命令。而 Claude Code 把这些拆成了独立的 **GlobTool** 和 **GrepTool**,每个工具都有精心设计的参数和返回格式。这样做的好处是模型更容易选对工具,出错率更低,速度也更快。 @@ -65,10 +65,9 @@ API 返回 tool_use blocks └────────┬─────────┘ ↓ ┌──────────────────┐ -│ 权限检查 │ 三种权限模式: -│ │ default → 按内置规则判断 -│ │ auto → 自动放行受信工具 -│ │ plan → 只允许只读操作 +│ 权限检查 │ 六种权限模式: +│ │ manual(公开文档:default)、acceptEdits、plan +│ │ auto、dontAsk、bypassPermissions │ │ │ │ 检查流程: │ │ 1. 硬编码危险模式 → 直接拒绝 @@ -152,7 +151,7 @@ allowed-tools: # 可选,限定这个 Skill 可以使用哪些工具 ### Skill 的执行:子 Agent 隔离 -调用 Skill 时,Claude Code 不是在主 Agent 循环中直接执行,而是 **fork 出一个独立的子 Agent**。这个设计和操作系统中的进程隔离思路一致。 +调用 Skill 时,Claude Code 通过 Skill 工具运行它。Skill 可以在主对话中执行,也可以通过 `context: fork` 请求一个隔离的后台子 Agent;3 月源码快照中“总是 fork”的描述属于历史状态。 ``` 用户输入 /my-skill 或 Agent 自主选择 diff --git a/docs/09-MCP-Integration.md b/docs/09-MCP-Integration.md index 91af767..30f0717 100644 --- a/docs/09-MCP-Integration.md +++ b/docs/09-MCP-Integration.md @@ -12,40 +12,32 @@ Before 2024, every AI Agent integrated with external services **in its own bespo This follows the same logic as USB. Before USB, every peripheral had its own connector standard. USB unified the interface, making any device plug-and-play. MCP aims to be the USB of the AI Agent ecosystem. -Claude Code's MCP implementation runs deep. The entire MCP subsystem lives in `src/services/mcp/`, comprising **24 files and 12,000+ lines of code**, making it one of the largest subsystems in Claude Code. This scale shows that Anthropic treats MCP as Claude Code's most critical extension mechanism, investing substantial engineering resources. +The March source snapshot's MCP subsystem lived in `src/services/mcp/` and comprised **24 files and 12,000+ lines of code**. Treat those counts as historical, since the current implementation is not public. -## 2️⃣ Seven Configuration Scopes: From Individual to Enterprise +## 2️⃣ Three MCP Installation Scopes -MCP Server configurations support seven different scope levels. This design serves use cases ranging from individual developers to large enterprises. +Current public Claude Code documentation describes three CLI installation scopes. Managed settings, plugins, and claude.ai connectors are additional configuration sources, not extra CLI scopes. | Scope | Configuration Location | Typical Use Case | Priority | |-------|----------------------|------------------|----------| -| **local** | Config file in the project directory | Tools used only in the current project, like a project-specific database client | Highest | -| **user** | Config file under ~/.claude/ | Personal global tools, like your own knowledge base MCP | High | -| **project** | .claude/ directory, checked into git | Team-shared project tools, like a team's API testing tool | Medium | -| **dynamic** | Injected via code at runtime | Tools dynamically registered by plugins or IDEs | Medium | -| **enterprise** | Admin-unified configuration | Enterprise-mandated security audit tools | Medium-low | -| **claudeai** | Anthropic official configuration | MCP services provided by Anthropic | Low | -| **managed** | Remote management platform | Centrally governed enterprise toolsets | Lowest | +| **local** | `~/.claude.json`, under the current project | Private tools used only in the current project | Project-specific | +| **user** | `~/.claude.json` | Personal tools available across projects | User-wide | +| **project** | `.mcp.json`, checked into git | Team-shared project tools | Shareable | -**Why so many levels?** Consider a real scenario: you're a developer at a company. The IT department uses the enterprise scope to mandate security scanning MCP tools. Your team shares CI/CD-related MCP tools via the project scope. You personally configure your favorite note-taking tool through the user scope. The current project has a project-specific database management tool in the local scope. All of these are **active simultaneously** in Claude Code, with higher-priority configs overriding same-named lower-priority ones. +These scopes cover private project tools, personal tools, and shareable team tools. Managed policies and other integrations can add further sources, but they should not be counted as CLI installation scopes. -This multi-layered configuration design is common in traditional software — Git has system/global/local configs, NPM has multi-level .npmrc files. But MCP extends to seven layers, reflecting that the AI Agent tool ecosystem is far more complex than traditional development tooling. +## 3️⃣ Four Transport Types, Three CLI Add Transports -## 3️⃣ Six Transport Protocols: Adapting to Every Runtime Environment - -MCP defines the standard interface, but how data actually travels between Agent and Server requires concrete transport protocols. Claude Code supports six: +MCP defines the standard interface, while transport determines how the Agent communicates with a Server. Current public documentation covers four transport types. The `--transport` CLI option accepts stdio, SSE, and HTTP; WebSocket is configured with JSON or `claude mcp add-json`. | Protocol | Technical Mechanism | Best For | |----------|-------------------|----------| | **stdio** | Communicates via standard input/output. Agent launches the Server process and exchanges JSON messages through stdin/stdout | Local tools — simplest and most reliable | | **sse** | Server-Sent Events, HTTP-based unidirectional streaming. Agent sends HTTP requests, Server pushes results via SSE stream | Remote tools with real-time push support | -| **sse-ide** | IDE-specific SSE variant, with connections managed by VS Code or similar IDEs | IDE integration environments | -| **http** | Standard HTTP REST request-response | Remote API services | -| **ws** | WebSocket bidirectional communication | Scenarios requiring two-way real-time communication | -| **sdk** | In-process SDK call, no network involved, direct function call within the same process | Built-in tools with extreme performance requirements | +| **http** | Streamable HTTP request and response | Remote API services | +| **ws** | WebSocket bidirectional communication, configured through JSON | Servers requiring two-way real-time communication | -**stdio is the most commonly used protocol** because most MCP Servers are small local programs. The Agent starts them and communicates through pipes — simple and direct. But as the MCP ecosystem grows, more and more Servers are remote services, making HTTP, SSE, and WebSocket increasingly important. +**stdio is the most commonly used protocol** because many MCP Servers are small local programs. SSE remains documented for compatibility, while streamable HTTP and WebSocket cover remote services. **Each protocol requires independent connection management, retry logic, and error handling code.** This is one of the main reasons the MCP module is so large. A broken stdio connection might mean the process crashed and needs restarting. A failed HTTP connection might be a network issue requiring exponential backoff retries. A dropped WebSocket connection might need re-handshake authentication. Each protocol's failure modes are entirely different and require specialized handling. @@ -59,7 +51,7 @@ Configuration example: { "mcpServers": { "my-server": { - "transport": "http", + "type": "http", "url": "https://api.example.com/mcp", "oauth": { "clientId": "your-client-id", @@ -80,7 +72,7 @@ How the OAuth flow works within MCP: 5. Subsequent calls automatically include the token 6. Token is automatically refreshed upon expiry -**Claude Code also supports XAA, or Cross-App Access.** This is a more advanced authentication mechanism that allows multiple MCP Servers to share authentication from a single identity provider. For example, if your company has a unified SSO system, all internal MCP Servers can use the same authentication through XAA. Users only need to log in once to access all tools. +The March source snapshot also mentioned XAA, or Cross-App Access. That claim is not part of the current public MCP configuration documentation, so it should be treated as unverified rather than as a current Claude Code feature. ## 5️⃣ Permission Management: MCP Tools Under Security Governance @@ -98,11 +90,11 @@ This design ensures a critical security property: **a third-party MCP Server doe 12,000 lines for a protocol integration is substantial by any standard. Here's where the complexity comes from: -**First, full implementation of six transport protocols.** Each protocol has its own connection establishment, message serialization, error recovery, and timeout handling code. The transport layer alone likely accounts for 3,000-4,000 lines. +**First, support for four documented transport types.** Each transport has its own connection establishment, message serialization, error recovery, and timeout handling code. The transport layer alone likely accounts for 3,000-4,000 lines in the historical snapshot. -**Second, complete OAuth flow implementation.** OAuth 2.0 is inherently complex, involving authorization code flows, token refresh, PKCE security extensions, and error handling. Add XAA cross-application authentication support, and the auth module likely accounts for 2,000-3,000 lines. +**Second, complete OAuth flow implementation.** OAuth 2.0 is inherently complex, involving authorization code flows, token refresh, PKCE security extensions, and error handling. The historical XAA mention is unverified, so the auth module likely accounts for 2,000-3,000 lines based on OAuth and related handling alone. -**Third, merge logic for seven configuration scopes.** Different levels need merging, overriding, and conflict resolution. Each scope has different loading mechanisms and storage locations. Configuration management likely accounts for 1,500-2,000 lines. +**Third, merge logic for three installation scopes.** Different levels need merging, overriding, and conflict resolution. Each scope has different loading mechanisms and storage locations. Configuration management likely accounts for 1,500-2,000 lines in the historical snapshot. **Fourth, extensive defensive code.** MCP Servers are third-party code. They might return malformed data, time out, crash, or return oversized responses. Claude Code must handle all these edge cases to ensure a buggy MCP Server doesn't bring down the entire Agent. @@ -122,7 +114,7 @@ As of early 2026, the MCP ecosystem has reached meaningful scale. Major MCP Serv MCP's industry influence is expanding. Beyond Claude Code, VS Code's GitHub Copilot has also started supporting MCP, and AI coding tools like Cursor and Windsurf are following suit. **MCP is becoming the de facto standard for AI Agent tool invocation.** -But MCP also faces challenges. The protocol itself is still evolving rapidly, and version compatibility is a concern. The existence of six transport protocols suggests the community hasn't reached consensus on the optimal transport mechanism. Additionally, MCP Server quality varies widely, and there's no unified security audit standard. +But MCP also faces challenges. The protocol itself is still evolving rapidly, and version compatibility is a concern. The existence of several transport types reflects different runtime needs. Additionally, MCP Server quality varies widely, and there's no unified security audit standard. 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.** 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 3738193..77377f9 100644 --- "a/docs/09-MCP\351\233\206\346\210\220.md" +++ "b/docs/09-MCP\351\233\206\346\210\220.md" @@ -15,46 +15,32 @@ 这和 USB 的思路一致。在 USB 之前,每个外设都有自己的接口标准。USB 统一了接口,任何设备都可以即插即用。MCP 要做的就是 AI Agent 生态的 USB。 -Claude Code 对 MCP 的实现非常深入。整个 MCP 子系统位于 `src/services/mcp/` 目录,包含 **24 个文件、12,000+ 行代码**,是 Claude Code 代码量最大的子系统之一。这个规模说明 Anthropic 把 MCP 视为 Claude Code 最核心的扩展机制,投入了大量工程资源。 +3 月源码快照中的 MCP 子系统位于 `src/services/mcp/` 目录,包含 **24 个文件、12,000+ 行代码**。这些数量属于历史记录,因为当前实现并未公开。 -## 2️⃣ 七种配置作用域:从个人到企业的全覆盖 +## 2️⃣ 三种 MCP 安装作用域 -![七层配置作用域](../imgs/09-mcp-seven-scopes.png) - - -MCP Server 的配置支持七种不同的作用域层级。这个设计是为了满足从个人开发者到大型企业的各种使用场景。 +当前 Claude Code 公开文档描述了三种 CLI 安装作用域。管理策略、插件和 claude.ai 连接器是额外的配置来源,不应算作 CLI 作用域。 | 作用域 | 配置位置 | 典型使用场景 | 优先级 | |--------|---------|-------------|--------| -| **local** | 项目目录下的配置文件 | 只在当前项目中使用的工具,比如项目专用的数据库客户端 | 最高 | -| **user** | ~/.claude/ 下的配置文件 | 个人全局工具,比如你自己搭建的知识库 MCP | 高 | -| **project** | .claude/ 目录,会被 checkin 到 git | 团队共享的项目工具,比如团队公共的 API 测试工具 | 中 | -| **dynamic** | 运行时通过代码注入 | 插件或 IDE 动态注册的工具 | 中 | -| **enterprise** | 管理员统一配置 | 企业级强制要求的安全审计工具 | 中低 | -| **claudeai** | Anthropic 官方配置 | 由 Anthropic 官方提供的 MCP 服务 | 低 | -| **managed** | 远程管理平台 | 集中管控的企业工具集 | 最低 | - -**为什么需要这么多层级?** 考虑一个真实场景:你是某家公司的开发者。公司 IT 部门通过 enterprise 作用域强制配置了安全扫描 MCP 工具。你的团队通过 project 作用域共享了 CI/CD 相关的 MCP 工具。你个人通过 user 作用域配置了自己喜欢的笔记工具。当前项目通过 local 作用域配置了项目专用的数据库管理工具。所有这些在 Claude Code 中**同时生效**,高优先级的配置覆盖低优先级的同名配置。 - -这种多层配置的设计在传统软件中很常见,比如 Git 的 system/global/local 三层配置,NPM 的 .npmrc 多层配置。但 MCP 把层级扩展到了七层,这反映了 AI Agent 工具生态的复杂性远超传统开发工具。 - -## 3️⃣ 六种传输协议:适配各种运行环境 +| **local** | `~/.claude.json` 中当前项目的配置 | 仅当前项目使用的私有工具 | 项目专用 | +| **user** | `~/.claude.json` | 跨项目可用的个人工具 | 用户级 | +| **project** | `.mcp.json`,checkin 到 git | 团队共享的项目工具 | 可共享 | -![六种传输协议](../imgs/09-mcp-six-protocols.png) +这三种作用域分别覆盖项目私有工具、个人工具和可共享的团队工具。管理策略和其他集成可以增加配置来源,但不应计入 CLI 安装作用域。 +## 3️⃣ 四种传输类型,CLI 支持三种添加方式 -MCP 定义了标准接口,但数据怎么在 Agent 和 Server 之间传输,需要具体的传输协议。Claude Code 支持六种: +MCP 定义了标准接口,传输类型决定 Agent 如何与 Server 通信。当前公开文档覆盖四种传输类型。CLI 的 `--transport` 选项接受 stdio、SSE 和 HTTP,WebSocket 通过 JSON 或 `claude mcp add-json` 配置。 | 协议 | 技术原理 | 适用场景 | |------|---------|---------| | **stdio** | 通过标准输入输出通信,Agent 启动 Server 进程,通过 stdin/stdout 交换 JSON 消息 | 本地工具,最简单最可靠 | | **sse** | Server-Sent Events,基于 HTTP 的单向流式推送,Agent 发 HTTP 请求,Server 通过 SSE 流推送结果 | 远程工具,支持实时推送 | -| **sse-ide** | IDE 专用的 SSE 变体,由 VS Code 等 IDE 托管连接 | IDE 集成环境 | -| **http** | 标准 HTTP REST 请求响应 | 远程 API 服务 | -| **ws** | WebSocket 双向通信 | 需要双向实时通信的场景 | -| **sdk** | 进程内 SDK 调用,不走网络,直接在同一个进程内调用 | 性能要求极高的内置工具 | +| **http** | Streamable HTTP 请求和响应 | 远程 API 服务 | +| **ws** | WebSocket 双向通信,通过 JSON 配置 | 需要双向实时通信的 Server | -**stdio 是最常用的协议**,因为大多数 MCP Server 就是一个本地运行的小程序。Agent 启动它,通过管道通信,简单直接。但随着 MCP 生态的发展,越来越多的 Server 是远程服务,这时候 HTTP、SSE、WebSocket 就变得重要了。 +**stdio 是最常用的协议**,因为许多 MCP Server 都是本地运行的小程序。SSE 仍为兼容性保留,Streamable HTTP 和 WebSocket 则覆盖远程服务。 **每种协议都需要独立的连接管理、重试逻辑和错误处理代码。** 这是 MCP 模块代码量大的主要原因之一。一个 stdio 连接断了,可能是进程崩溃了,需要重启。一个 HTTP 连接失败了,可能是网络问题,需要退避重试。一个 WebSocket 连接断了,可能需要重新握手认证。每种协议的异常模式完全不同,都需要专门处理。 @@ -68,7 +54,7 @@ MCP 定义了标准接口,但数据怎么在 Agent 和 Server 之间传输, { "mcpServers": { "my-server": { - "transport": "http", + "type": "http", "url": "https://api.example.com/mcp", "oauth": { "clientId": "your-client-id", @@ -89,7 +75,7 @@ OAuth 流程在 MCP 中的运作方式: 5. 后续调用自动携带 token 6. Token 过期时自动刷新 -**Claude Code 还支持 XAA,即 Cross-App Access。** 这是一个更高级的认证机制,允许多个 MCP Server 共享同一个身份提供商的认证。比如你的公司有一个统一的 SSO 系统,所有内部 MCP Server 都可以通过 XAA 使用同一套认证,用户只需要登录一次就能访问所有工具。 +3 月源码快照还提到 XAA,即 Cross-App Access。当前公开的 MCP 配置文档没有这项说明,因此应将其视为未经验证的快照内容,而不是当前 Claude Code 功能。 ## 5️⃣ 权限管理:MCP 工具也受安全管控 @@ -110,11 +96,11 @@ MCP 工具接入后,并非可以随意调用。它们和 Claude Code 的内置 12,000 行代码做一个协议集成,这个规模在任何标准下都不小。分析其复杂度来源: -**第一,六种传输协议的完整实现。** 每种协议都有自己的连接建立、消息序列化、错误恢复、超时处理代码。仅传输层就可能占了 3,000-4,000 行。 +**第一,四种已公开传输类型的支持。** 每种传输都有自己的连接建立、消息序列化、错误恢复、超时处理代码。历史快照中仅传输层就可能占了 3,000-4,000 行。 -**第二,OAuth 流程的完整实现。** OAuth 2.0 本身就是一个复杂的协议,涉及授权码流程、token 刷新、PKCE 安全扩展、错误处理。加上 XAA 跨应用认证的支持,认证模块可能占了 2,000-3,000 行。 +**第二,OAuth 流程的完整实现。** OAuth 2.0 本身就是一个复杂的协议,涉及授权码流程、token 刷新、PKCE 安全扩展、错误处理。XAA 的历史快照提及未经验证,因此认证模块可能仅凭 OAuth 和相关处理就占了 2,000-3,000 行。 -**第三,七种配置作用域的合并逻辑。** 不同层级的配置需要合并、覆盖、冲突解决。每种作用域有不同的加载方式和存储位置。配置管理可能占了 1,500-2,000 行。 +**第三,三种安装作用域的合并逻辑。** 不同层级的配置需要合并、覆盖、冲突解决。每种作用域有不同的加载方式和存储位置。历史快照中配置管理可能占了 1,500-2,000 行。 **第四,大量的防御性代码。** MCP Server 是第三方代码,它可能返回格式错误的数据、超时、崩溃、返回超大响应。Claude Code 需要对所有这些异常情况做处理,确保一个有问题的 MCP Server 不会拖垮整个 Agent。 @@ -134,7 +120,7 @@ MCP 工具接入后,并非可以随意调用。它们和 Claude Code 的内置 MCP 的行业影响正在扩大。除了 Claude Code,VS Code 的 GitHub Copilot 也开始支持 MCP,Cursor、Windsurf 等 AI 编码工具也在跟进。**MCP 正在成为 AI Agent 工具调用的事实标准。** -但 MCP 也面临挑战。协议本身还在快速演进中,版本兼容性是个问题。六种传输协议的存在也说明社区对最佳传输方案还没有共识。此外,MCP Server 的质量参差不齐,缺乏统一的安全审计标准。 +但 MCP 也面临挑战。协议本身还在快速演进中,版本兼容性是个问题。多种传输类型反映了不同运行环境的需求。此外,MCP Server 的质量参差不齐,缺乏统一的安全审计标准。 对于开发者来说,现在投入精力学习和使用 MCP 是值得的。**它代表了 AI 工具生态的发展方向:标准化、可组合、安全可控。** diff --git a/docs/10-Future-Features.md b/docs/10-Future-Features.md index 889af46..aeae366 100644 --- a/docs/10-Future-Features.md +++ b/docs/10-Future-Features.md @@ -6,9 +6,9 @@ In software development, a **Feature Flag** is a common release strategy. Developers write the code for a new feature but keep it deactivated, controlling whether it takes effect through a boolean switch. This lets teams safely merge incomplete features into the main branch and turn them on when the time is right. -Claude Code's source contains **82 Feature Flags**, controlled via the `feature('FLAG_NAME')` function. In the publicly available external build, this function always returns false, meaning all flagged features are disabled. But the code itself remains intact and fully readable. +The March source snapshot contained **82 Feature Flags**, controlled via the `feature('FLAG_NAME')` function. Its public-build behavior and the all-false classification describe that snapshot, not a current feature inventory. By 2.1.227, auto memory is enabled by default, 1M context is available for supported models, and voice interaction has shipped. -This means we can read these disabled code paths to **glimpse Anthropic's technical roadmap**. These features may still be in testing, may already be in use internally, or may ultimately be abandoned. But they at minimum represent directions that Anthropic's engineering team has seriously considered. +This means we can read these snapshot code paths to **glimpse directions Anthropic considered**. Some may still be in testing or may have been abandoned, while others have since shipped. The feature flag table below remains a March snapshot classification. ## 2️⃣ Kairos: From Q&A Tool to Autonomous Agent @@ -60,7 +60,7 @@ Similar approaches already exist in the industry. Microsoft's AutoGen framework **Related Flag:** VOICE_MODE -Voice Mode adds voice input and output support to Claude Code. The Agent is no longer limited to terminal text interaction — it can communicate with users through voice. +Voice interaction and dictation are available in current 2.1.x builds, so this is now a shipped capability rather than a future-only feature. The `VOICE_MODE` flag below is a snapshot artifact. This might seem like a nice-to-have feature, but combined with Kairos autonomous mode, its significance grows substantially. **When an Agent is working autonomously in the background, voice is a very natural notification and interaction method.** You're drinking coffee, and the Agent tells you via voice: "PR has been submitted, all tests passed, awaiting your review." You reply by voice: "Change the log level to debug and run it again." This is far more natural than opening a terminal and typing. @@ -94,7 +94,7 @@ Workflow Scripts let users codify proven workflows: what to do in step one, step **FAST_MODE:** Fast mode, likely using a lower-latency but slightly less capable model for simple tasks, trading quality for speed. -**CONTEXT_1M:** Million-token context support. This would dramatically improve the Agent's ability to handle large codebases. The current context limit is one of the biggest bottlenecks when an Agent works on complex projects. +**CONTEXT_1M:** Million-token context support is available for supported models in current 2.1.x builds. Availability and limits still depend on the model and account. ## 9️⃣ Complete Feature Flag Category Table 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 2fa81db..fd99446 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" @@ -8,9 +8,9 @@ 在软件开发中,**Feature Flag** 是一种常见的发布策略。开发者把新功能的代码写好但不激活,通过一个布尔开关控制其是否生效。这让团队可以把未完成的功能安全地合并到主分支,等时机成熟再打开。 -Claude Code 的源码中包含 **82 个 Feature Flag**,通过 `feature('FLAG_NAME')` 函数控制。在外部公开的构建版本中,这个函数永远返回 false,所有被 Flag 保护的功能都处于禁用状态。但代码本身还在,逻辑完整可读。 +3 月源码快照中包含 **82 个 Feature Flag**,通过 `feature('FLAG_NAME')` 函数控制。外部构建中的全 false 行为和分类都属于该快照,不是当前功能清单。截至 2.1.227,自动记忆默认开启,支持的模型可使用 1M 上下文,语音交互也已经发布。 -这意味着我们可以通过阅读这些被禁用的代码,**窥见 Anthropic 的技术路线图**。这些功能可能还在测试中,可能已经在内部使用,也可能最终被放弃。但它们至少代表了 Anthropic 工程团队认真考虑过的方向。 +这意味着我们可以通过阅读这些快照代码,**窥见 Anthropic 曾经考虑过的方向**。有些功能可能仍在测试或已经放弃,另一些则已经发布。下面的 Feature Flag 表仍然是 3 月快照的分类。 ## 2️⃣ Kairos:从问答工具到自主 Agent @@ -68,7 +68,7 @@ Kairos 是一整套自主运行框架,由 6 个 Feature Flag 组成。在所 **相关 Flag:** VOICE_MODE -Voice Mode 让 Claude Code 支持语音输入和输出。Agent 不再局限于终端文字交互,可以通过语音和用户沟通。 +当前 2.1.x 版本已经支持语音交互和听写,因此它不再只是未来功能。下面的 `VOICE_MODE` flag 属于快照遗留名称。 这看起来像一个 nice-to-have 的功能,但结合 Kairos 自主模式来看,意义就大了。**当 Agent 在后台自主工作时,语音是一种非常自然的通知和交互方式。** 你在喝咖啡,Agent 通过语音告诉你"PR 已经提了,测试全部通过,等你 Review"。你语音回复"把日志级别改成 debug 重新跑一遍"。这比打开终端敲键盘自然得多。 @@ -102,7 +102,7 @@ Workflow Scripts 让用户把经过验证的工作流固化下来:第一步做 **FAST_MODE:** 快速模式,可能使用低延迟但能力稍弱的模型来处理简单任务,在速度和质量之间做权衡。 -**CONTEXT_1M:** 百万 token 上下文支持。这将大幅提升 Agent 处理大型代码库的能力。目前的上下文限制是 Agent 处理复杂项目时最大的瓶颈之一。 +**CONTEXT_1M:** 当前 2.1.x 版本已为支持的模型提供百万 token 上下文。具体可用性和限制仍取决于模型与账户。 ## 9️⃣ 完整 Feature Flag 分类表 diff --git a/docs/11-AI-Code-Review.md b/docs/11-AI-Code-Review.md index 2d0a426..789b99b 100644 --- a/docs/11-AI-Code-Review.md +++ b/docs/11-AI-Code-Review.md @@ -2,9 +2,11 @@ # 11 Code Review in the AI Coding Era +> Version scope: the source-leak example and its exact counts refer to the March 31, 2026 sourcemap snapshot. + ## 1️⃣ It Started with a Sourcemap Leak -In 2025, Claude Code's complete source code was publicly reconstructed. The reason was almost laughable: **the build process failed to exclude sourcemap files.** Sourcemaps are debug-aid files generated by JavaScript build tools that record the mapping between compiled code and original source. With .map files in hand, the original code can be reconstructed almost perfectly. +In March 2026, Claude Code's complete source code was publicly reconstructed. The reason was almost laughable: **the build process failed to exclude sourcemap files.** Sourcemaps are debug-aid files generated by JavaScript build tools that record the mapping between compiled code and original source. With .map files in hand, the original code can be reconstructed almost perfectly. This project has 515,000 lines of code. TypeScript type definitions have zero errors. Every async function has proper error handling. The code structure is clean and well-organized. From a code quality perspective, it's nearly impeccable. Yet on the most fundamental release security question of "what files should the build output contain," there was a fatal oversight. 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 61a6999..64aaa0f 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" @@ -2,12 +2,14 @@ # 11 AI Coding 时代的 Code Review +> 版本范围:本章的源码泄露案例和精确数量均指向 2026 年 3 月 31 日的 sourcemap 快照。 + ## 1️⃣ 从一次 Sourcemap 泄露说起 ![Sourcemap泄露教训](../imgs/11-review-sourcemap-lesson.png) -2025 年,Claude Code 的完整源码被公开还原。原因令人哭笑不得:**构建流程中没有排除 sourcemap 文件**。Sourcemap 是 JavaScript 构建工具生成的调试辅助文件,记录了编译后代码与原始源码的映射关系。只要拿到 .map 文件,就能几乎完美地还原出原始代码。 +2026 年 3 月,Claude Code 的完整源码被公开还原。原因令人哭笑不得:**构建流程中没有排除 sourcemap 文件**。Sourcemap 是 JavaScript 构建工具生成的调试辅助文件,记录了编译后代码与原始源码的映射关系。只要拿到 .map 文件,就能几乎完美地还原出原始代码。 这个项目有 51.5 万行代码,TypeScript 类型定义零错误,每个异步函数都有完善的错误处理,代码结构清晰整齐。从代码质量的角度看,它几乎无可挑剔。但就是在"构建产物应该包含哪些文件"这个最基础的发布安全问题上,出了致命的遗漏。 diff --git a/docs/12-Agent-Security-Design.md b/docs/12-Agent-Security-Design.md index 350de19..cd6393b 100644 --- a/docs/12-Agent-Security-Design.md +++ b/docs/12-Agent-Security-Design.md @@ -8,7 +8,7 @@ When most teams build Agents, their priority list looks like this: first, get th The Claude Code source code leak gave us a rare opportunity to see just how much a top-tier Agent company invests in security. -The answer: **6,300 lines of code, 25 files, the heaviest single module in the entire codebase.** Heavier than the Agent loop, heavier than message compression, heavier than MCP integration. +The March source snapshot contained **6,300 lines of code across 25 files**, making permission handling its heaviest single module. The current private implementation cannot be verified against that count. Anthropic voted with lines of code: **Constraining what an Agent must not do is more important than enabling what an Agent can do.** @@ -26,9 +26,9 @@ This means Agent security can't be guaranteed by code review alone. **You must i Claude Code's approach was to build a three-layer defense system. -## 2️⃣ First Line of Defense: 42 Hardcoded Rules +## 2️⃣ First Line of Defense: 42 Rules in the March Snapshot -The code has 42 hardcoded auto-deny bash patterns. Regardless of user configuration or permission mode, the Agent can never execute these commands. +The source snapshot listed 42 hardcoded auto-deny Bash patterns. That exact count and its behavior are historical claims, not a current public implementation contract. Current public documentation describes a tiered deny, ask, and allow permission system. **Cross-platform code execution — 16 rules:** @@ -78,21 +78,24 @@ Output: { **Using AI to constrain AI.** The model's understanding of bash semantics far surpasses any regex matching. It can understand the combined semantics of commands, the final effect of pipe chains, and the implicit meaning of arguments. -Of course, this layer has costs. Every tool call requires an additional API request. So Claude Code only enables the classifier in auto mode, and requires Opus 4.6 or above — lower-end models don't have sufficient judgment accuracy. +Of course, this layer has costs. Every tool call can require an additional API request. The availability and behavior of automatic classification depend on the current account and model rather than a documented Opus 4.6 minimum. ## 4️⃣ Third Line of Defense: Manual User Confirmation The most traditional and most reliable layer. When the Agent wants to execute a tool, a prompt pops up showing the tool name, parameters, and scope of impact. The user clicks Allow or Deny. -Claude Code offers three permission modes for users to choose from: +Claude Code currently exposes six permission mode values. `manual` is the CLI value for the user-facing Manual mode; public documentation labels that mode `default`: | Mode | Best For | How It Works | |------|----------|--------------| -| **default** | Beginners, sensitive operations | Every tool call requires confirmation | -| **auto** | Daily development, experienced users | ML classifier auto-judges; only uncertain calls prompt | -| **plan** | Long-running tasks | Model outputs a full plan with confidence per step; only low-confidence steps require confirmation | - -The three modes cover the full spectrum from maximum safety to maximum efficiency. Users can flexibly switch based on the risk level of their current task. +| **manual (public docs: default)** | Sensitive operations | Read-only work can proceed; other actions follow permission rules and may prompt | +| **acceptEdits** | Editing workflows | Automatically accepts file edits while retaining other checks | +| **plan** | Planning and review | Explores and plans without making changes until approval | +| **auto** | Automatic operation | Uses automatic checks where available | +| **dontAsk** | Pre-approved workflows | Does not prompt, and denies actions without an allow rule | +| **bypassPermissions** | Trusted isolated environments | Skips permission prompts | + +These six modes cover different levels of confirmation and automation. Users can switch modes based on the risk level of the current task. ## 5️⃣ An Easily Overlooked Design: Dangerous Rule Stripping 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 c2ac044..8c64103 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" @@ -11,7 +11,7 @@ Claude Code 的源码泄露给了我们一个难得的机会,看看一家最顶尖的 Agent 公司在安全上到底投入了多少。 -答案是:**6,300 行代码,25 个文件,全代码库最重的单一模块。** 比 Agent 循环重,比消息压缩重,比 MCP 集成重。 +答案是:3 月源码快照中有 **6,300 行代码、25 个文件**,权限处理是其中最重的单一模块。当前私有实现无法用这个数量复核。 Anthropic 用代码量投了票:**约束 Agent 不做什么,比让 Agent 能做什么更重要。** @@ -32,12 +32,12 @@ Agent 的行为是**概率性的**。同样的用户输入,模型可能选择 Claude Code 的做法是建了一套三层防御体系。 -## 2️⃣ 第一层防线:42 条硬编码规则 +## 2️⃣ 第一层防线:3 月快照中的 42 条规则 ![42条硬编码规则分类](../imgs/12-sec-42-rules-breakdown.png) -代码里写死了 42 条自动拒绝的 bash 模式。不管用户怎么配置,不管什么权限模式,这些命令 Agent 永远不能执行。 +源码快照列出了 42 条硬编码的 Bash 自动拒绝模式。这个数量和行为属于历史描述,不是当前公开实现的契约。当前公开文档描述的是 deny、ask、allow 分层权限系统。 **跨平台代码执行类 16 条:** @@ -87,21 +87,24 @@ Claude Code 引入了 **YOLO 分类器**。这个分类器通过一次 side-quer **用 AI 来约束 AI。** 模型对 bash 语义的理解远超任何正则匹配。它能理解命令的组合语义、管道链的最终效果、参数的隐含含义。 -当然这一层有成本。每次工具调用都多一次 API 请求。所以 Claude Code 只在 auto 模式下启用分类器,而且要求 Opus 4.6 以上的模型才支持,低端模型的判断准确率不够。 +当然这一层有成本。每次工具调用都可能多一次 API 请求。自动分类的可用性和行为取决于当前账户与模型,公开文档没有规定必须使用 Opus 4.6 以上。 ## 4️⃣ 第三层防线:用户手动确认 最传统也最可靠的一层。Agent 想执行工具时弹窗,展示工具名、参数、影响范围,用户点 Allow 或 Deny。 -Claude Code 提供了三种权限模式让用户选择: +Claude Code 当前提供六种权限模式值。`manual` 是面向用户的 Manual 模式在 CLI 中的值,公开文档将这个模式标为 `default`: | 模式 | 适合谁 | 工作方式 | |------|--------|---------| -| **default** | 新手、做敏感操作时 | 每次工具调用都弹窗确认 | -| **auto** | 日常开发、老手 | ML 分类器自动判断,只有不确定的才弹窗 | -| **plan** | 跑长任务时 | 模型先输出完整计划和每步置信度,低置信度才确认 | - -三种模式覆盖了从最安全到最高效的全场景。用户可以根据当前任务的风险级别灵活切换。 +| **manual(公开文档:default)** | 敏感操作 | 只读工作可继续,其他操作按权限规则处理并可能弹窗 | +| **acceptEdits** | 编辑工作流 | 自动接受文件编辑,保留其他检查 | +| **plan** | 规划和审查 | 只探索和规划,批准后再修改 | +| **auto** | 自动运行 | 在可用时使用自动检查 | +| **dontAsk** | 已预授权的工作流 | 不弹窗,没有 allow 规则的操作会被拒绝 | +| **bypassPermissions** | 受信任的隔离环境 | 跳过权限弹窗 | + +六种模式覆盖了不同的确认和自动化级别。用户可以根据当前任务的风险级别切换。 ## 5️⃣ 一个容易被忽视的设计:Dangerous Rule Stripping diff --git a/docs/13-Source-Code-Findings.md b/docs/13-Source-Code-Findings.md index f60a056..19e12aa 100644 --- a/docs/13-Source-Code-Findings.md +++ b/docs/13-Source-Code-Findings.md @@ -38,15 +38,15 @@ The fix was three lines of code: stop retrying after 3 consecutive failures. **An automated process without a retry limit is a ticking time bomb.** This lesson holds true in any distributed system. -## 5️⃣ 82 Feature Flags All Hardcoded to false +## 5️⃣ 82 Feature Flags in the March Snapshot ```typescript const feature = (_name: string) => false; ``` -One line of code turns off all unreleased features. Bun's bundler performs dead code elimination, stripping all code wrapped in flags from the build output. +The March snapshot used this one-line implementation to classify unreleased features. Bun's bundler performed dead code elimination around those flags, stripping flagged code from that build's output. It is not evidence that every current feature flag is false. -**But the code is still there in the source.** You can see every feature Anthropic is developing: Kairos autonomous mode, Context Collapse, Voice Mode for voice interaction, Verification Agent for automated verification. The technical roadmap of a top-tier Agent company, written in plain text in the code. +**But the code was still there in the source snapshot.** It exposed directions Anthropic had considered, including Kairos autonomous mode, Context Collapse, Voice Mode, and Verification Agent. Some directions have since shipped, including voice interaction, 1M context for supported models, and auto memory. ## 6️⃣ Compression Summaries Use an Elegant Prompt Technique @@ -56,7 +56,7 @@ Let the model think clearly before summarizing, without wasting context space. T ## 7️⃣ 583 Dependencies -A CLI tool with 583 npm dependencies. When AI encounters a problem while writing code, it `npm install`s first — if a third-party library can solve it, it will never hand-write the solution. A human would weigh whether a feature that only takes 20 lines of code really justifies pulling in a library with tens of thousands of lines. AI doesn't make this trade-off. +A March source reconstruction contained 583 npm dependencies. The count belongs to that historical package and should not be treated as the current distribution's dependency count. When AI encounters a problem while writing code, it `npm install`s first. A human would weigh whether a feature that only takes 20 lines of code really justifies pulling in a library with tens of thousands of lines. AI doesn't make this trade-off. **Every additional dependency is another supply chain attack surface.** @@ -107,15 +107,15 @@ After thoroughly analyzing this source code, and combining it with my own experi **Claude Code is evolving toward a platform, and its evolutionary path overlaps heavily with the design philosophy of Agent platforms like OpenClaw.** -The most obvious signal: cross-session memory. The MEMORY.md mechanism in the source code has already implemented a basic version of cross-session memory persistence. The EXTRACT_MEMORIES and TEAMMEM feature flags indicate Anthropic is working on two things — automatic memory extraction and team memory sharing. This aligns perfectly with OpenClaw's design philosophy: an Agent shouldn't start as a blank slate every time it launches. It needs to remember who the user is, what they prefer, and where things left off last time. OpenClaw achieved instance-level state persistence through COS storage early on. Claude Code is now heading in the same direction, just via a different path — one uses the file system, the other uses object storage. +The most obvious signal is cross-session memory. Claude Code now provides auto memory by default, storing machine-local project notes under the project's Claude directory. The EXTRACT_MEMORIES and TEAMMEM names belong to the source snapshot; they do not establish that team-shared memory is a current feature. This aligns with OpenClaw's design philosophy: an Agent should not start as a blank slate every time it launches. The second signal is native channel integration. On March 20, 2025, Claude gained the ability to connect to Telegram through MCP plugins. This means the Agent is no longer confined to a terminal waiting for users to come to it — it can proactively exist within the communication tools users already use daily. OpenClaw was designed around channels from day one — WeChat, WeCom, Slack, Discord. Where the Agent lives depends on where the user is. Claude Code is now beginning to understand this. It's foreseeable that Claude Code will natively support more channels in the future, rather than just bridging through MCP. WhatsApp, Line, Lark — these are all just a matter of time. -The third signal is the continuous lowering of the usage barrier. Looking at Claude Code's product iteration trajectory: from manually configuring API keys to one-click login, from pure CLI to VS Code integration, from manually writing CLAUDE.md to automatic memory extraction. Every step lowers the bar. The ultimate goal is clear: **let people who don't understand technology get things done with an Agent.** OpenClaw's Skills marketplace is the ultimate expression of this philosophy — users don't need to understand prompt engineering; they just pick a ready-made Skill and use it. Claude Code's Skills system is already doing the same thing. +The third signal is the continuous lowering of the usage barrier. Looking at Claude Code's product iteration trajectory: from manually configuring API keys to one-click login, from pure CLI to VS Code integration, and from manually writing all memory notes to shipped auto memory. Every step lowers the bar. The ultimate goal is clear: **let people who don't understand technology get things done with an Agent.** OpenClaw's Skills marketplace is the ultimate expression of this philosophy. Claude Code's Skills system is already doing the same thing. But lowering the barrier doesn't mean sacrificing the ceiling. This is the fourth prediction: **for advanced users, Agent platforms will provide increasingly more professional modes.** -The 82 feature flags in Claude Code's source code are evidence. Default configuration is enough for ordinary users, but capable users can unlock entirely different experiences through flag combinations: custom compression strategies, permission mode adjustments, MCP toolchain configuration, Hooks for workflow automation. This layered design — simple to start, deep to master — is a common trait of all successful developer tools. Git is like this, Vim is like this, Kubernetes is like this too. +The 82 feature flags in the source snapshot are evidence of directions the codebase had explored, not a supported mechanism for users to unlock hidden features. Current users can configure compression, permission modes, MCP toolchains, and Hooks through documented interfaces. This layered design is simple to start and deep to master. OpenClaw's Planner-Executor architecture and Claude Code's ReAct loop are essentially solving the same problem: how to keep an Agent controllable during complex tasks. OpenClaw uses DAGs for task orchestration; Claude Code uses AsyncGenerator for tool loops. Different implementations, but the design philosophy is the same — **give the Agent autonomy, but always preserve human intervention points.** 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 364ecf4..87c2b70 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" @@ -49,15 +49,15 @@ AI 不会主动拆文件,因为拆文件意味着要跨文件维护导入关 **没有重试上限的自动化流程就是一颗定时炸弹。** 这条经验放在任何系统里都成立。 -## 5️⃣ 82 个 Feature Flag 全部 hardcode 为 false +## 5️⃣ 3 月快照中的 82 个 Feature Flag ```typescript const feature = (_name: string) => false; ``` -一行代码把所有未发布功能关掉,Bun 打包时做 dead code elimination,被 flag 包裹的代码直接从构建产物中删除。 +这行代码是 3 月快照对未发布功能的分类方式。Bun 打包时对这些 flag 做 dead code elimination,把被包裹的代码从该构建产物中删除。它不能证明当前所有 feature flag 仍然是 false。 -**但源码里这些代码还在。** 你能看到 Anthropic 正在开发的所有功能:Kairos 自主模式、Context Collapse 上下文折叠、Voice Mode 语音交互、Verification Agent 自动验证。一家最顶尖 Agent 公司的技术蓝图,明文写在代码里。 +**但快照源码里这些代码还在。** 你能看到 Anthropic 曾经考虑过的方向:Kairos 自主模式、Context Collapse、Voice Mode、Verification Agent。其中一些已经发布,包括语音交互、支持模型的 1M 上下文和自动记忆。 ## 6️⃣ 压缩摘要用了一个精妙的 prompt 技巧 @@ -67,7 +67,7 @@ const feature = (_name: string) => false; ## 7️⃣ 583 个依赖 -一个 CLI 工具,583 个 npm 依赖。AI 写代码遇到问题先 npm install,能用第三方库解决的绝不手写。人会权衡这个功能 20 行代码就能搞定,有没有必要引一个万行的库,而 AI 不做这个权衡。 +3 月源码还原版本包含 583 个 npm 依赖。这个数量属于历史包,不能当作当前发行版的依赖数量。AI 写代码遇到问题先 npm install,能用第三方库解决的绝不手写。人会权衡这个功能 20 行代码就能搞定,有没有必要引一个万行的库,而 AI 不做这个权衡。 **每多一个依赖就会让整个系统膨胀一点,也多一个供应链攻击面。** @@ -120,17 +120,17 @@ const feature = (_name: string) => false; **Claude Code 正在向平台化演进,而它的演进路径和 OpenClaw 这类 Agent 平台的设计哲学高度重合。** -先说最明显的一个信号:跨 session 记忆,源码中的 MEMORY.md 机制已经实现了基础版的跨会话记忆持久化,EXTRACT_MEMORIES 和 TEAMMEM 这两个 feature flag 说明 Anthropic 正在做两件事——自动记忆提取和团队记忆共享。这和 OpenClaw 的设计思路完全一致:Agent 不应该每次启动都是一张白纸,它需要记住用户是谁、偏好什么、上次做到了哪里。 +先说最明显的一个信号:跨 session 记忆。Claude Code 当前默认提供自动记忆,把项目笔记保存在项目对应的 Claude 目录中。EXTRACT_MEMORIES 和 TEAMMEM 只是源码快照中的名称,不能证明当前已经支持团队共享记忆。这和 OpenClaw 的设计思路一致:Agent 不应该每次启动都是一张白纸。 第二个信号是原生渠道接入。2025 年 3 月 20 日,Claude 已经能通过 MCP 插件接入 Telegram。这意味着 Agent 不再局限于终端里等用户来找它,而是可以主动存在于用户日常使用的通讯工具中。OpenClaw 从第一天起就是围绕渠道设计的——微信、企业微信、Slack、Discord,Agent 在哪里取决于用户在哪里。 Claude Code 现在也开始接入这一点。可以预见,未来 Claude Code 会原生支持更多渠道,而不仅仅是通过 MCP 做桥接,WhatsApp、Line、飞书,这些都是时间问题。 -第三个信号是使用门槛的持续下降。看 Claude Code 的产品迭代方向,从需要手动配置 API key 到一键登录,从纯命令行到 VS Code 集成,从需要自己写 CLAUDE.md 到自动记忆提取。每一步都在降低使用 bar。终极目标很清晰:**让不懂技术的人也能用 Agent 做事。** +第三个信号是使用门槛的持续下降。看 Claude Code 的产品迭代方向,从需要手动配置 API key 到一键登录,从纯命令行到 VS Code 集成,再到已经发布的自动记忆。每一步都在降低使用 bar。终极目标很清晰:**让不懂技术的人也能用 Agent 做事。** 但降低门槛不意味着牺牲上限。这是第四个判断:**对于高级用户,Agent 平台会提供越来越多的专业模式。** -Claude Code 源码中的 82 个 feature flag 就是证据。普通用户用默认配置就够了,但有能力的用户可以通过 flag 组合解锁完全不同的使用体验:自定义压缩策略、调整权限模式、配置 MCP 工具链、编写 Hooks 做流程自动化。这种分层设计——入门简单、进阶深邃——是所有成功的开发者工具的共同特征。Git 是这样,Vim 是这样,Kubernetes 也是这样。 +源码快照中的 82 个 feature flag 说明当时探索过一些方向,但不是用户可以解锁隐藏功能的受支持机制。当前用户可以通过公开接口配置压缩、权限模式、MCP 工具链和 Hooks。这种分层设计入门简单,也能满足高级使用。 我的判断是:未来 12 个月内,Claude Code 和 OpenClaw 这类平台会在功能上快速趋同。Claude Code 会变得更像一个平台(多渠道、持久记忆、团队协作),OpenClaw 会变得更智能(更强的模型、更好的推理能力),最终的竞争不在于谁的模型更强或者谁的功能更多,而在于谁能在**降低使用门槛**和**提升能力上限**之间找到最好的平衡。