⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
source-reading
带 AI 精读大型开源仓库,产出每句话都能回溯到源码具体行的书稿、课程或技术文档。核心是零幻觉:每一处引用逐字节核实、行号实读、静默删行由脚本抓出。覆盖锁版本锚点、写逐章大纲、八段结构写章节、编成带封面封底的 HTML 书、机器校验、并行子 Agent 生产六件事。当用户要读懂一个陌生的大型仓库、精读某个开源项目源码、把源码整理成一本书、整理成课程或系列文章、做源码解读、写架构分析、或者要派多个 Agent 并行写技术内容时使用。触发词:精读源码、读源码、源码解读、源码分析、拆解这个项目、这个仓库怎么读、把源码写成课、把源码写成书、写源码精读、架构分析、code walkthrough、带我读代码。
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
source-reading-methodology
一套把陌生的大型仓库读成一门课的方法论。给要做同样事情的人用:选一个开源项目,带着 AI 精读它的源码,最后产出一份别人也能看懂、每句话都能验证的成果。
先看成品:三章样张,在线试读。 这本书是按下面这套方法论产出的,原料在 sample/chapters/,用仓库里的 book/build_book.py 一条命令编出来。翻一下再决定要不要照着走一遍。
用这套方法论跑出来的完整成果,是 小山学堂 上的两门源码精读课:DeepSeek Harness 与 OpenAI Codex,合计 61 节。其中 Codex 那门的章节书稿有 1270 处带行号的源码引用,逐字节校验零编造。
Quick Start:把这个仓库发给 Agent
你不需要判断自己用的是哪一种 Agent,也不需要手动找它的 Skill 目录。把这个仓库的地址发给 Agent,再把下面这段话发给它:
阅读这个仓库:https://github.com/itshen/source-reading-methodology
先完整阅读 SKILL.md,把它安装成你可长期使用的 Skill;安装位置和方式由你根据当前运行环境自行判断。
安装完成后,询问我要精读的源码仓库、产出形态和规模,再按 SKILL.md 执行。
Agent 会自己读取仓库、完成安装,并在开始精读之前问清任务。以后你只需要直接说:
帮我精读
~/code/some-repo,我想产出一门课。
怎么判断 AI 真的读进去了
SKILL.md 是唯一入口,一份文件讲完整套流程,需要细节时 AI 会自己去读 templates/ 和 PITFALLS.md。它的反应符合下面五条,说明走对了:
- 先问清产出形态和规模再动手。读懂一个模块和做一门 32 节的课,该走的阶段数完全不同
- 动手第一件事是给目标仓库打 tag、记下 commit。不锁版本,后面写的所有行号迟早失效,而且没人分得清是当初写错还是上游改了
- 每段代码都带
起始行:结束行:文件路径,贴出来的每一行你都能自己跳回去核对 - 查不到的地方明说「未找到对应实现,检索关键词为 X、Y」,宁可空着,也不填一个看起来合理的
- 批量写之前先建校验器。人工复核十万字的行号不现实
反过来,如果 AI 上来就甩章节大纲、代码块没有行号、或者一口答应你「三十二章我这就全写完」,它没按这套走,把 SKILL.md 重新发给它。
一句话内核
让每一个技术论断都可回溯到源码的具体行。
可回溯迫使你真的读到那一行,也让读者能自己验证。AI 辅助读码时幻觉几乎必然发生,它会根据文件名推测实现、根据常见模式补全细节、把注释当成代码行为陈述。一旦掺进去,整份成果的可信度就是零,因为读者无法分辨哪句是真的。
这套方法论里所有的规则,都是为了守住这一条。落到版面上是这样:
图是样张第 3 章的一处引用,声明 codex-rs/core/src/session/turn.rs 的 1368 到 1439 行。左侧行号栏是源文件里的真实行号,读者可以直接跳回仓库对照。中间两处省略之后的行只标 ·:省略跳过了多少行只有源文件知道,宁可不显示,也不显示一个编出来的行号。头部的「第 1 / 3 段」点一下会按连续段依次高亮,让人看清哪几行在源文件里真的连在一起。
四个阶段
产出物分层,每一层的输入是上一层的输出。不要跳级。
阶段一 语料准备 锁版本、备对比语料、建检索脚本
↓
阶段二 大纲 回答「这门课要解答哪一个问题」+ 逐章源码锚点
↓
阶段三 章节书稿 八段结构,每处论断带行号,机器校验
↓
阶段四 成书 编成一本带封面封底的 HTML 书,可读、可查、可传
跳级的后果很具体:没有阶段一的版本锚点,阶段三写的行号三个月后全部失效;没有阶段二的锚点清单,阶段三的并行写作会互相重复又互相矛盾。
你自己要弄明白时,读什么
上面那三种挂法之后,跑流程是 AI 的事。你要搞清楚原理、或者想把这套改造成自己的,才需要往下读:
METHODOLOGY.md(315 行)方法论本体,每条规则都写了来由PITFALLS.md(29 条)全部来自真实事故,不用背,卡住时来查example/同一章从大纲到成书的真实成品,拿不准该填到什么程度时对着它看
有两个节点值得你自己盯,AI 容易滑过去:大纲最花时间也最决定成败,它决定哪些内容进、哪些不进;校验器必须在批量生产之前建好,事后补等于没有。
各阶段对应的模板
| 阶段 | 模板 | 产出 |
|---|---|---|
| 二 · 大纲 | templates/00-outline-template.md | 一份带逐章源码锚点的大纲 |
| 三 · 章节书稿 | templates/01-chapter-spec-template.md | 每章一份 markdown,八段结构 |
| 四 · 成书 | book/build_book.py | 一本 HTML 书,封面加目录加正文加封底 |
| 四 · 课页(可选) | templates/02-page-spec-template.md | 每章一页可玩的课页 |
| 三、四通用 | templates/style_scan.py | 文风禁忌扫描,交付前跑一遍 |
文风扫描器可以直接用,零依赖:
python3 templates/style_scan.py path/to/chapters/
它把句式禁忌写成正则,扫描前剥掉代码块、行内代码和「」直接引用,避免源码字符被误判。只扫面向读者的正文,大纲和规范这类内部文档不在约束范围内。
阶段一没有模板,它是三件具体的事,在 METHODOLOGY.md 里有操作步骤:给主教材打 tag、备齐至少一个同类项目做对照、包一个 ripgrep 检索脚本。
派并行 Agent 之前
规范里每一处含糊都会变成 N 份不同的理解。派活时必须给全四样东西:填好的写作规范(一个文件,不要口头补充)、那一章的大纲条目、全部语料的绝对路径、校验命令加上「必须全绿才算交付」。
METHODOLOGY.md 的并行生产一节列了子 Agent 的四种典型偏差,规范里要提前堵。
目录
├── SKILL.md AI 的唯一入口,一份文件讲完整套流程
├── AGENTS.md 克隆或 fork 之后 AI 自动读到的指引,指向 SKILL.md
├── METHODOLOGY.md 方法论本体,给人读,每条规则都写了来由
├── PITFALLS.md 29 条踩坑清单,分五类
├── templates/ 三份可复用模板加一个文风扫描器
├── book/ 成书构建器:章节 markdown 编成 HTML 书
├── sample/ 样张原料:三章书稿加一份构建配置
├── docs/ 样张构建产物,也是 GitHub Pages 的站点目录
└── example/ 同一章从大纲到成书的真实成品,当尺子用
book/ 是阶段四的实现,改一个 JSON 配置就能出书,用法见 book/README.md。
sample/ 加 docs/ 是那个在线样张的两端:前者是三章原料与配置,后者是编出来的书。想自己试构建器,直接拿这份配置跑:
pip install markdown
python3 book/build_book.py --config sample/book.config.json
example/ 是一条纵向切片:同一章在阶段二、三、四各自的成品,包括大纲节选与成书截图。拿到空模板不知道填到什么程度时,对着它看。
这套方法论跑出来的实际结果
一个 Rust 单仓项目,90 多个 crate。口径写在括号里,避免同一个数出现两种算法。
| 项目 | 数量 |
|---|---|
| 章节书稿 | 32 章,正文 20.8 万汉字(不含代码块与图;连标点空白算 58.1 万字符) |
| 源码引用 | 1270 处带行号引用,逐字节校验零编造、零行号漂移 |
| 交互课页 | 32 页,371 处出处,校验问题 0 处 |
| 跨课互链 | 18 条(候选 64 张对比卡) |
| 并行 Agent | 分三批,每批 8 到 9 个 |
最后两行值得注意。互链候选 64 张最后只挂上 18 条,因为大量卡片拿闭源产品做对照、站内没有对应展开页,硬凑的链接比没有链接更糟。并行生产之所以能跑,靠的是先有逐字节校验器,人工复核十万字的行号不现实。
这类数字不能只写在 README 里,所以每本编出来的书都在封底自带一张逐章数据表和版本锚点,读者照着就能抽查:
上图是三章样张的封底,表里是这三章的实际数据,下面是被精读仓库的 commit 与 tag。这张表是一本书敢不敢让人查的凭证:行号对应哪个版本写清楚了,读者发现对不上,也能分辨是当初写错还是上游后来改了。
成品在 xueai.app,两门课的每一节都能直接看。
交流与关注
这套方法论出自 小山学堂,一个讲 AI 产品与 Agent 工程化的课程站。
- 在线课程:xueai.app
- X:@luoxiaoshan_ai
- GitHub:itshen
如果这份方法论帮到了你,欢迎给仓库点个 Star,也欢迎带着你自己的项目来群里聊聊卡在哪一步。
License
MIT License · Copyright (c) 2026 米羊科技(上海)有限公司 (Miyang Tech (Shanghai) Co., Ltd.)
仓库里的章节书稿、截图与样张页面同样按 MIT 授权。被引用的 openai/codex 源码片段版权归原作者所有,引用用于教学说明。
// HOW IT'S BUILT
// FILES
41 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
SKILL.md11 KB9dab8311f27eupstream ↗
--- name: source-reading description: 带 AI 精读大型开源仓库,产出每句话都能回溯到源码具体行的书稿、课程或技术文档。核心是零幻觉:每一处引用逐字节核实、行号实读、静默删行由脚本抓出。覆盖锁版本锚点、写逐章大纲、八段结构写章节、编成带封面封底的 HTML 书、机器校验、并行子 Agent 生产六件事。当用户要读懂一个陌生的大型仓库、精读某个开源项目源码、把源码整理成一本书、整理成课程或系列文章、做源码解读、写架构分析、或者要派多个 Agent 并行写技术内容时使用。触发词:精读源码、读源码、源码解读、源码分析、拆解这个项目、这个仓库怎么读、把源码写成课、把源码写成书、写源码精读、架构分析、code walkthrough、带我读代码。 --- # 源码精读 把陌生的大型仓库读成可交付的内容。**唯一不可妥协的要求:每一个技术论断都可回溯到源码的具体行。** AI 读码时幻觉几乎必然发生:根据文件名推测实现、根据常见模式补全细节、把注释当成代码行为陈述。掺进去一次,整份产出的可信度就是零,因为读者无法分辨哪句是真的。下面所有规则都是为了守住这一条。 ## 第一步:先定规模,别过度应用 问清产出形态再动手。四阶段全流程很重,小任务不需要。 | 用户要什么 | 走哪些 | |---|---| | 读懂某个模块、回答一个机制问题 | 只用零幻觉引用纪律,不建大纲不做课页 | | 一篇架构分析、一份技术文档 | 阶段一 + 阶段三 | | 一门课、一个系列、多篇连载 | 四阶段全走,并建校验器 | 不确定就问:产出是给自己看还是给别人看,要不要交互演示,篇数大概多少。 ## 零幻觉铁律 动笔前必须做到,每条都是作废级: 1. **每一处引用、每一个行号、每一个类型名与函数名,动笔前用读文件工具实读核实。** 禁止凭印象、禁止根据文件名推测、禁止照抄大纲里的候选行号 2. **代码块与源文件逐字节一致。** 保留原始缩进、属性宏、注释、空行。禁止转译、禁止美化、禁止写「示意代码」 3. 中间跳过内容必须显式写省略标记(含 `...` 的整行注释)。**静默删行会被校验器抓成 FABRICATION** 4. 找不到某个机制的实现,写明 `未找到对应实现,检索关键词为 X、Y、Z`。不许编一个看起来合理的 5. 由推断得出的结论显式标注为推断 6. 引用注释时说明这是注释,不要当成代码行为陈述 7. 数字(行数、文件数、变体个数)必须统计过,统一用 `splitlines()` 口径 8. 引用符号链接时引真实文件,并注明链接关系 引用格式,三部分必填,路径相对仓库根: ```` ```153:160:core/src/session/turn.rs pub(crate) async fn run_turn( sess: Arc<Session>, ... ) -> CodexResult<Option<String>> { ``` ```` ## 四阶段工作流 每一层的输入是上一层的输出,不要跳级。跳级的后果很具体:没有版本锚点,写到第十章时第一章的行号全部失效,且无法判断是当初写错还是后来改了。 ``` - [ ] 阶段一 语料准备:锁版本、备对比语料、建检索脚本 - [ ] 阶段二 大纲:立一个真问题 + 逐章源码锚点 - [ ] 阶段三 章节书稿:八段结构,每处论断带行号 - [ ] 阶段四 成书:编成带封面封底的 HTML 书 - [ ] 贯穿 机器校验(批量生产之前就要建好) ``` ### 阶段一:语料准备 ```bash git -C <repo> tag course-anchor-$(date +%Y%m%d) git -C <repo> rev-parse --short HEAD ``` 把 tag 与 commit 写进所有下游文档的文件头。然后做三件事: 1. **备至少一个同类项目做对照。** 只读一个仓库读不出设计决策,会把作者的选择当成唯一解。对比语料也要锁版本 2. **建 ripgrep 检索脚本,不要建向量库。** 查阅场景是关键词匹配,`rg` 毫秒级、零依赖 3. **找「为什么」的一手材料**,按优先级:仓库根的评审红线文件(`AGENTS.md`、`CONTRIBUTING.md`、`.cursor/rules/`)→ 模块级 README → 模块头注释 → 测试文件 → 官方博客。指向外链的空壳文档要识别出来跳过 评审红线文件优先级最高:每条禁令背后通常都是一次真实事故,这是「为什么不那样做」的唯一一手来源。 ### 阶段二:大纲 用 `templates/00-outline-template.md`。三件事按顺序: 1. **先立一个真问题**,把整门内容收束到一句话。这句话决定哪些内容进、哪些不进。缺了它,大纲会退化成源码目录的中文翻译 2. **写清读者带走什么**,具体到能直接用。「学会 Agent 架构」不算,「一份该不该做沙箱、做到哪一层的决策树」才算 3. **逐章写锚点**:核心问题、源码入口(文件加候选行号)、要分析的设计决策、对比对象、演示方向 已核实的行号标 ✓。**✓ 的含义是曾经核实过,不是现在还对。** 写作时即使看到 ✓ 也要重读,因为真正要引用的可能是相邻的行。 演示方向要在大纲阶段就逐章分配,句式统一。不提前分配,多个写作 Agent 会做出雷同的演示。 ### 阶段三:章节书稿 填 `templates/01-chapter-spec-template.md` 里的占位符,填完的那一份就是唯一写作标准。八段顺序固定: | 段 | 要求 | |---|---| | 场景还原 | 从具体会翻车的情形开局,不从概念定义开局 | | 逐行精读 | 篇幅主体,一段代码一段话交替推进 | | 设计决策分析 | 回答为什么,给出「不这样做会出什么事」 | | 边界条件剖析 | ≥ 2 个「如果…会怎样」,答案落到确切分支和行号 | | 横向对比 | ≥ 1 组,两侧都给路径行号,说清各自代价 | | 演示设计 | 分步 + 每步字幕文案 + 逻辑轨迹面板 | | 可迁移结论 | 哪些值得抄、最小成本形态、哪些是过度设计 | | 思考题 | ≥ 3 道,含 1 道动手验证 | 两段最容易被敷衍,也最能拉开深度:**边界条件**不许答「取决于配置」,必须落到源码里某个 `if` 的某一行;**横向对比**不许写成功能清单对照,要说清另一侧为什么可以没有、或用什么别的东西补上了。 ### 阶段四:成书 把章节 markdown 编成一本带封面、目录、正文、封底的 HTML 书: ```bash pip install markdown cp book/book.config.example.json book.config.json # 填书名、作者、被读仓库与版本锚点 python3 book/build_book.py ``` 封面放阶段二立的那句话与版本锚点,封底放逐章引用数、图数、字数。读者判断一份源码解读值不值得信,看的就是这两样敢不敢摊开。 **带省略的引用块,省略之后的行号构建器不排**,只从两头数,中间留空。跳过了多少行只有源文件知道,编一个看起来合理的行号比不给更糟。 用法与输入格式见 `book/README.md`。校对用 `python3 book/shot_book.py dist`。 产出形态是课程站交互课页时走 `templates/02-page-spec-template.md`,与成书并行不冲突。课页上默认零代码,能在一页上贴的代码量远小于理解所需;演示必须有分步动画、每步一句人话字幕、逻辑轨迹面板。写「做个动画演示这个流程」等于没写。 ## 文风 **能写成正则的进禁忌,不能的进表达偏好。** 无法自动检查的硬性规则等于没有规则。 禁忌交付前必须清零,跑: ```bash python3 templates/style_scan.py path/to/chapters/ ``` 扫描器剥掉代码块、行内代码和「」直接引用后再判,避免源码字符被误报。只扫面向读者的正文,大纲和规范这类内部工作文档不在约束范围内。 **不要用同义替换绕过正则**,比如把「而不是」换成「而非」。禁的是靠否定制造对比这件事,不是那三个字。 完整清单在 `templates/01-chapter-spec-template.md` 第 4 节。 ## 机器校验 **投入产出比最高的一件事,必须在批量生产之前建好。** 人工复核十万字的行号不现实。 至少校验三件: 1. **代码块与源文件逐字节比对**。以内容为准、行号为辅:按省略标记切成连续段,每段要在源文件里找到完全连续的匹配。拼不上判 FABRICATION,行号错了自动校正 2. **文风禁忌扫描** 3. **引用密度下限**。防一种隐蔽作弊:删掉报错的引用让校验变绿 第三条来自真实事故:某章初稿 56 处引用带若干报错,交付时只剩 22 处、全部通过。**校验器只报「现有引用是否正确」,不报「该有的引用是否还在」,这个缺口必须补。** 另外单独写一个脚本查「被引用文件是否存在」「行号是否越界」,逐字节比对验证不了路径写对没有。 校验器会误报,误报会让人开始忽略它的输出,那等于没有校验。每修一个误报都记下判据。 ## 并行生产 规范里每一处含糊都会变成 N 份不同的理解。派活时必须给全四样: 1. 填好的写作规范(一个文件,不要口头补充) 2. 那一章的大纲条目 3. 全部语料的绝对路径。**先确认路径真实存在再说**,凭印象说「某个语料不在本地」会让子 Agent 绕开它 4. 校验命令,以及「必须全绿才算交付」 子 Agent 的四种典型偏差,规范里要提前堵:删引用让校验变绿、滥用省略标记凑字数、把检查糊弄过去、误报上游文档写错(实际命中率约两成)。 要求上报文档错误时带证据,格式固定:**被质疑的原话 → 源码文件与行号 → 那几行的原文 → 为什么对不上**。 并行中陆续收到的上游文档问题不要边收边改,开一个 `PENDING_FIXES.md` 累积,全部回来后统一核实统一修。 ## 参考资料 - 方法论完整版,含每条规则的来由:[METHODOLOGY.md](METHODOLOGY.md) - 29 条踩坑清单,全部来自真实事故,卡住时来查:[PITFALLS.md](PITFALLS.md) - 大纲模板:[templates/00-outline-template.md](templates/00-outline-template.md) - 章节写作规范模板:[templates/01-chapter-spec-template.md](templates/01-chapter-spec-template.md) - 课页规范模板:[templates/02-page-spec-template.md](templates/02-page-spec-template.md) - 成书构建器用法与输入格式:[book/README.md](book/README.md) - 文风扫描器:[templates/style_scan.py](templates/style_scan.py) - 真实成品,同一章从大纲到课页的纵向切片:[example/README.md](example/README.md)book/README.md4.7 KB3715e7da03c0upstream ↗
# 成书:把章节 markdown 编成一本能读的 HTML 书 阶段三写完的章节是 markdown,能读但不好读。这个构建器把它们编成一本带封面、目录、正文与封底的静态书,双击 `index.html` 就能看,也能直接传到任何静态托管上。 --- ## 三步 ```bash pip install markdown cp book/book.config.example.json book.config.json # 改成你这本书的信息 python3 book/build_book.py # 默认读 ./book.config.json open dist/index.html ``` 构建器会打印每章的引用数、图数、汉字数,最后给出总计。 想先看效果,仓库里带了一份现成的三章样张,原料和配置都在 `sample/`: ```bash python3 book/build_book.py --config sample/book.config.json ``` 它输出到 `docs/`,也就是[在线样张](https://itshen.github.io/source-reading-methodology/)那个站点目录。改完主题跑一遍这条命令,样张跟着更新。配置里的相对路径以配置文件所在目录为基准,所以那份配置的 `out` 写的是 `../docs`。 --- ## 配置 ```json { "title": "书名", "subtitle": "一段话说清这本书回答哪个问题", "kicker": "源码精读", "author": "作者", "repo": "https://github.com/owner/repo", "anchor": { "commit": "4f39251a01", "tag": "course-anchor-20260822", "date": "2026-08-22" }, "accent": "#3f4a5a", "chapters": "chapters", "out": "dist" } ``` `repo` 与 `anchor` 是被精读的那个仓库和它的版本锚点,会印在封面和封底。读者据此判断书里的行号还作不作数。 `accent` 换一个色值就换一套配色,其余颜色都是从它推出来的。 --- ## 输入要求 章节 markdown 放在一个目录里,按文件名排序就是章序。每章的开头这样写: ```markdown # 第 1 章:章节标题 > 源码核对基于 owner/repo commit `4f39251a01`(2026-08-22),tag `course-anchor-20260822` > 摘要:目录里显示的一句话,不写就自动取「场景还原」的头一句 ``` `#` 是章名,紧跟的引用块是这一章的元信息,会排在标题下面的小卡片里。标题里的「第 N 章:」在版面上会自动去掉,因为章序单独排。 正文里的三种围栏各有对应的排版: | 围栏 | 出来是什么 | |---|---| | ` ```153:160:path/to/file.rs ` | 带真实行号栏的源码引用块,可复制、可逐段步进 | | ` ```mermaid ` | 图,进入视野时才渲染,带描线动画 | | ` ```rust ` 等普通语言 | 普通代码块 | 每章末尾的 `## 交付自查` 默认不收进书,那是写给制作方看的过程记录。要留就加 `--keep-selfcheck`。 --- ## 行号是怎么排的 这是这个构建器唯一需要解释的地方。 引用块头部声明了 `153:160`,块里如果没有省略,就从 153 一路往下数。**如果中间有省略标记,省略之后的行号是推不出来的**:省略跳过了多少行只有源文件知道。 所以:开头那段从声明的起始行正着数,结尾那段从声明的结束行倒着数,夹在两个省略之间的段落一律留空显示 `·`。宁可不显示,也不显示一个编出来的行号。 带省略的引用块头部会多一个「逐段」按钮,点一下按连续段依次高亮,让读者看清哪几行在源文件里真的连在一起。 省略标记的判据是:整行是注释,且注释符号后面紧接着就是 `...`。 ``` // ... 填 SID 表 ... ← 是省略标记 // 处理 bash -lc "..." 的情况 ← 不是,这是正常注释 ``` 这条判据比「注释行里含 `...`」严。宽判据会把源码里正常的文档注释误当成省略,那些行就不会参与逐字节比对,等于留了一个校验盲区。构建器遇到「没有省略、但行数和声明的区间对不上」时会打印提示,那通常意味着引用头部的起止行写错了。 --- ## 书里有什么动效 都为可读性服务,不为炫技。开了系统的减少动态效果偏好会自动全部关掉。 - 顶部阅读进度条 - 正文分块滚动渐入 - 侧栏目录跟随高亮,点击跳转 - 引用块逐段步进,复制按钮 - 图进入视野才渲染,边线描出来 - 封面数字滚动 - 深浅色切换,记住选择 - 左右方向键翻章 --- ## 校对 ```bash pip install playwright && playwright install chromium python3 book/shot_book.py dist -c ch-04.html ``` 封面、正文、封底各出一张长图,另出一张引用块步进中的局部图,同时报告页面 JS 报错。截图时会强制展开渐入元素,否则滚动太快会截到还没淡入的空白。 --- ## 页脚 每一页底部固定一行署名与方法论仓库链接。这是这套方法论的出处标记,生成出来的书都会带上。example/README.md5.5 KB1bb2b6c2abf8upstream ↗
# 一条纵向切片:同一章从大纲走到课页 拿到空模板容易不知道填到什么程度。这里放同一章在三个阶段的真实成品,对着看就有尺子。 源项目是 openai/codex,Rust 单仓 90 多个 crate。选的是第 1 章,讲这个仓库靠什么阻止核心 crate 继续膨胀。选它的原因:它是首章,不依赖任何前置知识;主题是依赖方向治理,换任何语言、任何规模的项目都成立。 --- ## 三个阶段的成品 | 文件 | 对应阶段 | 看什么 | |---|---|---| | `stage2-outline-entry.md` | 阶段二 · 大纲 | 定位怎么立、锚点写到多细 | | `../sample/chapters/01-crate-governance.md` | 阶段三 · 章节书稿 | 八段结构的完整形态,50 处带行号引用 | | `stage4-book-cover.png` | 阶段四 · 成书 | 封面与目录 | | `stage4-book-stepping.png` | 阶段四 · 成书 | 引用块的行号与逐段步进 | | `stage4-book-colophon.png` | 阶段四 · 成书 | 封底的逐章数据与版本锚点 | | `stage4-page-demo.png` | 阶段四 · 课页(可选形态) | 交互演示区该长什么样 | --- ## 阶段二:大纲 `stage2-outline-entry.md` 两处节选:课程定位,加上第 1 章的锚点条目。 要注意的是定位部分没有直接列章节,而是先回答「这门课解答哪一个问题」,并把答案收束成一句话。这句话决定后面哪些内容进、哪些不进。缺了它,大纲会退化成源码目录的中文翻译。 锚点条目有五个固定字段:核心问题、源码锚点、对比锚点、边界条件示例、互动演示。源码锚点具体到行,比如 `AGENTS.md:72-83`,这样写作 Agent 不用自己找料,直接去核实。 --- ## 阶段三:章节书稿 `../sample/chapters/01-crate-governance.md`,约 6 万字符,50 处带行号引用,3 张图。这一章同时是样张的第 1 章,所以放在 `sample/` 里,不在这个目录下再存一份。 八段结构:场景还原、逐行精读、设计决策分析、边界条件剖析、横向对比、互动演示设计、可迁移结论、思考题。文件末尾有一段交付自查,逐项写实际达成数。 三处值得专门看: **逐行精读**是篇幅主体,一段代码一段话交替推进。每贴一段代码,前面一句说明这段要证明什么,后面用白话讲输入输出。不是贴一大坨再统一解释。 **边界条件剖析**里的追问全部落到源码具体分支,没有一句「取决于配置」。这一段是拉开深度的地方。 **互动演示设计**是写给下一阶段的人看的,包含分步动画、每步的字幕文案、逻辑轨迹面板的每一行伪代码加真实行号。它不写 HTML,但细到照着就能实现。 --- ## 阶段四:成书 三张截图来自 `book/build_book.py` 编出来的书,配置只填了书名、作者、被读仓库和版本锚点。截图对应的书可以直接翻:[三章样张](https://itshen.github.io/source-reading-methodology/),第 1 章就是这一章。 `stage4-book-cover.png` 是封面加目录。封面上那句副标题就是阶段二立的那个问题;下面三个数字(章数、引用数、字数)和版本锚点是给读者判断可信度用的。目录里每章的一句话摘要是从该章「场景还原」的头一句自动取的,不满意可以在章节元信息里写 `> 摘要:`覆盖。 <p align="center"><img src="stage4-book-cover.png" width="82%" alt="成书的封面与目录" /></p> `stage4-book-stepping.png` 是引用块,也是整本书最值得看的一处细节。截图里那一块声明 `167:250`,中间有两处省略: - 开头一段从 167 正着数到 188 - 结尾一段从 250 倒着数回 241 - 夹在两处省略之间的那些行标 `·`,**不给行号** 因为省略跳过了多少行,只有源文件知道。宁可不显示,也不显示一个编出来的行号。头部的「第 1 / 3 段」按钮点一下会按连续段依次高亮,让读者看清哪几行在源文件里真的连在一起。 <p align="center"><img src="stage4-book-stepping.png" width="62%" alt="引用块的真实行号与逐段步进" /></p> `stage4-book-colophon.png` 是封底:逐章的引用数、图数、汉字数,以及被精读仓库的 commit 与 tag。这张表是这本书敢不敢让人查的凭证。 <p align="center"><img src="stage4-book-colophon.png" width="82%" alt="封底的逐章数据与版本锚点" /></p> ## 阶段四的另一条路:交互课页 如果产出形态是课程站的课页而不是书,`stage4-page-demo.png` 是那条路的成品。三样硬要求: 1. 底部一句人话字幕,跟着步进更新 2. 逻辑轨迹面板,一行一句白话,右侧标真实文件与行号(`AGENTS.md L76`、`Cargo.toml L3`),随动画高亮当前行 3. 播放、单步、重置三个按钮,进入视野自动播放一次 <p align="center"><img src="stage4-page-demo.png" width="82%" alt="交互课页的演示区" /></p> 页面上没有源码面板。代码留在书里,页面负责让人明白机制。 截图对应的是线上的实际页面,演示可以真的点:[xueai.app](https://xueai.app/?from=source-reading-methodology) 里「解剖 OpenAI Codex」那一篇的第 1 节。 --- ## 一个提醒 这份样例的行号对应 openai/codex commit `4f39251a01`。上游一直在改,现在照着去查大概已经漂了。这正好说明为什么阶段一要先打 tag:行号是这套方法论的地基,不锁版本,写到第十章时第一章的引用已经全部失效,而且你无法判断是当初写错还是后来改了。README.md11 KBf84a314ffe28upstream ↗
# source-reading-methodology 一套把陌生的大型仓库读成一门课的方法论。给要做同样事情的人用:选一个开源项目,带着 AI 精读它的源码,最后产出一份别人也能看懂、每句话都能验证的成果。 [](https://itshen.github.io/source-reading-methodology/) [](https://xueai.app/?from=source-reading-methodology) [](https://x.com/luoxiaoshan_ai) [](LICENSE) **先看成品:[三章样张,在线试读](https://itshen.github.io/source-reading-methodology/)。** 这本书是按下面这套方法论产出的,原料在 `sample/chapters/`,用仓库里的 `book/build_book.py` 一条命令编出来。翻一下再决定要不要照着走一遍。 <a href="https://itshen.github.io/source-reading-methodology/"><img src="assets/preview-cover.png" width="100%" alt="样张封面与目录" /></a> 用这套方法论跑出来的完整成果,是 [小山学堂](https://xueai.app/?from=source-reading-methodology) 上的两门源码精读课:DeepSeek Harness 与 OpenAI Codex,合计 61 节。其中 Codex 那门的章节书稿有 1270 处带行号的源码引用,逐字节校验零编造。 --- ## Quick Start:把这个仓库发给 Agent 你不需要判断自己用的是哪一种 Agent,也不需要手动找它的 Skill 目录。把这个仓库的地址发给 Agent,再把下面这段话发给它: ```text 阅读这个仓库:https://github.com/itshen/source-reading-methodology 先完整阅读 SKILL.md,把它安装成你可长期使用的 Skill;安装位置和方式由你根据当前运行环境自行判断。 安装完成后,询问我要精读的源码仓库、产出形态和规模,再按 SKILL.md 执行。 ``` Agent 会自己读取仓库、完成安装,并在开始精读之前问清任务。以后你只需要直接说: > 帮我精读 `~/code/some-repo`,我想产出一门课。 ### 怎么判断 AI 真的读进去了 `SKILL.md` 是唯一入口,一份文件讲完整套流程,需要细节时 AI 会自己去读 `templates/` 和 `PITFALLS.md`。它的反应符合下面五条,说明走对了: 1. **先问清产出形态和规模再动手**。读懂一个模块和做一门 32 节的课,该走的阶段数完全不同 2. **动手第一件事是给目标仓库打 tag、记下 commit**。不锁版本,后面写的所有行号迟早失效,而且没人分得清是当初写错还是上游改了 3. **每段代码都带 `起始行:结束行:文件路径`**,贴出来的每一行你都能自己跳回去核对 4. **查不到的地方明说「未找到对应实现,检索关键词为 X、Y」**,宁可空着,也不填一个看起来合理的 5. **批量写之前先建校验器**。人工复核十万字的行号不现实 反过来,如果 AI 上来就甩章节大纲、代码块没有行号、或者一口答应你「三十二章我这就全写完」,它没按这套走,把 `SKILL.md` 重新发给它。 --- ## 一句话内核 **让每一个技术论断都可回溯到源码的具体行。** 可回溯迫使你真的读到那一行,也让读者能自己验证。AI 辅助读码时幻觉几乎必然发生,它会根据文件名推测实现、根据常见模式补全细节、把注释当成代码行为陈述。一旦掺进去,整份成果的可信度就是零,因为读者无法分辨哪句是真的。 这套方法论里所有的规则,都是为了守住这一条。落到版面上是这样: <p align="center"><img src="assets/preview-cite.png" width="470" alt="带真实行号的源码引用块,省略处不编行号" /></p> 图是样张第 3 章的一处引用,声明 `codex-rs/core/src/session/turn.rs` 的 1368 到 1439 行。左侧行号栏是源文件里的真实行号,读者可以直接跳回仓库对照。中间两处省略之后的行只标 `·`:省略跳过了多少行只有源文件知道,宁可不显示,也不显示一个编出来的行号。头部的「第 1 / 3 段」点一下会按连续段依次高亮,让人看清哪几行在源文件里真的连在一起。 --- ## 四个阶段 产出物分层,每一层的输入是上一层的输出。不要跳级。 ``` 阶段一 语料准备 锁版本、备对比语料、建检索脚本 ↓ 阶段二 大纲 回答「这门课要解答哪一个问题」+ 逐章源码锚点 ↓ 阶段三 章节书稿 八段结构,每处论断带行号,机器校验 ↓ 阶段四 成书 编成一本带封面封底的 HTML 书,可读、可查、可传 ``` 跳级的后果很具体:没有阶段一的版本锚点,阶段三写的行号三个月后全部失效;没有阶段二的锚点清单,阶段三的并行写作会互相重复又互相矛盾。 --- ## 你自己要弄明白时,读什么 上面那三种挂法之后,跑流程是 AI 的事。你要搞清楚原理、或者想把这套改造成自己的,才需要往下读: 1. **`METHODOLOGY.md`**(315 行)方法论本体,每条规则都写了来由 2. **`PITFALLS.md`**(29 条)全部来自真实事故,不用背,卡住时来查 3. **`example/`** 同一章从大纲到成书的真实成品,拿不准该填到什么程度时对着它看 有两个节点值得你自己盯,AI 容易滑过去:**大纲最花时间也最决定成败**,它决定哪些内容进、哪些不进;**校验器必须在批量生产之前建好**,事后补等于没有。 ### 各阶段对应的模板 | 阶段 | 模板 | 产出 | |---|---|---| | 二 · 大纲 | `templates/00-outline-template.md` | 一份带逐章源码锚点的大纲 | | 三 · 章节书稿 | `templates/01-chapter-spec-template.md` | 每章一份 markdown,八段结构 | | 四 · 成书 | `book/build_book.py` | 一本 HTML 书,封面加目录加正文加封底 | | 四 · 课页(可选) | `templates/02-page-spec-template.md` | 每章一页可玩的课页 | | 三、四通用 | `templates/style_scan.py` | 文风禁忌扫描,交付前跑一遍 | 文风扫描器可以直接用,零依赖: ```bash python3 templates/style_scan.py path/to/chapters/ ``` 它把句式禁忌写成正则,扫描前剥掉代码块、行内代码和「」直接引用,避免源码字符被误判。只扫面向读者的正文,大纲和规范这类内部文档不在约束范围内。 阶段一没有模板,它是三件具体的事,在 `METHODOLOGY.md` 里有操作步骤:给主教材打 tag、备齐至少一个同类项目做对照、包一个 ripgrep 检索脚本。 ### 派并行 Agent 之前 规范里每一处含糊都会变成 N 份不同的理解。派活时必须给全四样东西:填好的写作规范(一个文件,不要口头补充)、那一章的大纲条目、全部语料的绝对路径、校验命令加上「必须全绿才算交付」。 `METHODOLOGY.md` 的并行生产一节列了子 Agent 的四种典型偏差,规范里要提前堵。 --- ## 目录 ``` ├── SKILL.md AI 的唯一入口,一份文件讲完整套流程 ├── AGENTS.md 克隆或 fork 之后 AI 自动读到的指引,指向 SKILL.md ├── METHODOLOGY.md 方法论本体,给人读,每条规则都写了来由 ├── PITFALLS.md 29 条踩坑清单,分五类 ├── templates/ 三份可复用模板加一个文风扫描器 ├── book/ 成书构建器:章节 markdown 编成 HTML 书 ├── sample/ 样张原料:三章书稿加一份构建配置 ├── docs/ 样张构建产物,也是 GitHub Pages 的站点目录 └── example/ 同一章从大纲到成书的真实成品,当尺子用 ``` `book/` 是阶段四的实现,改一个 JSON 配置就能出书,用法见 `book/README.md`。 `sample/` 加 `docs/` 是那个[在线样张](https://itshen.github.io/source-reading-methodology/)的两端:前者是三章原料与配置,后者是编出来的书。想自己试构建器,直接拿这份配置跑: ```bash pip install markdown python3 book/build_book.py --config sample/book.config.json ``` `example/` 是一条纵向切片:同一章在阶段二、三、四各自的成品,包括大纲节选与成书截图。拿到空模板不知道填到什么程度时,对着它看。 --- ## 这套方法论跑出来的实际结果 一个 Rust 单仓项目,90 多个 crate。口径写在括号里,避免同一个数出现两种算法。 | 项目 | 数量 | |---|---| | 章节书稿 | 32 章,正文 20.8 万汉字(不含代码块与图;连标点空白算 58.1 万字符) | | 源码引用 | 1270 处带行号引用,逐字节校验零编造、零行号漂移 | | 交互课页 | 32 页,371 处出处,校验问题 0 处 | | 跨课互链 | 18 条(候选 64 张对比卡) | | 并行 Agent | 分三批,每批 8 到 9 个 | 最后两行值得注意。互链候选 64 张最后只挂上 18 条,因为大量卡片拿闭源产品做对照、站内没有对应展开页,硬凑的链接比没有链接更糟。并行生产之所以能跑,靠的是先有逐字节校验器,人工复核十万字的行号不现实。 这类数字不能只写在 README 里,所以每本编出来的书都在封底自带一张逐章数据表和版本锚点,读者照着就能抽查: <p align="center"><img src="assets/preview-colophon.png" width="82%" alt="样张封底:逐章数据表与版本锚点" /></p> 上图是三章样张的封底,表里是这三章的实际数据,下面是被精读仓库的 commit 与 tag。这张表是一本书敢不敢让人查的凭证:行号对应哪个版本写清楚了,读者发现对不上,也能分辨是当初写错还是上游后来改了。 成品在 [xueai.app](https://xueai.app/?from=source-reading-methodology),两门课的每一节都能直接看。 --- ## 交流与关注 <table> <tr> <td align="center" width="180"> <img src="assets/group-qrcode.png" width="150" /><br/> <b>交流群</b><br/> <em>微信扫码入群</em> </td> <td align="center" width="180"> <img src="assets/qrcode.jpg" width="150" /><br/> <b>公众号</b><br/> <em>洛小山</em> </td> <td align="center" width="180"> <a href="https://x.com/luoxiaoshan_ai"><img src="assets/x-qrcode.png" width="150" /></a><br/> <b>X</b><br/> <em><a href="https://x.com/luoxiaoshan_ai">@luoxiaoshan_ai</a></em> </td> <td> 这套方法论出自 **小山学堂**,一个讲 AI 产品与 Agent 工程化的课程站。 - 在线课程:[xueai.app](https://xueai.app/?from=source-reading-methodology) - X:[@luoxiaoshan_ai](https://x.com/luoxiaoshan_ai) - GitHub:[itshen](https://github.com/itshen/) 如果这份方法论帮到了你,欢迎给仓库点个 Star,也欢迎带着你自己的项目来群里聊聊卡在哪一步。 </td> </tr> </table> --- ## License MIT License · Copyright (c) 2026 米羊科技(上海)有限公司 (Miyang Tech (Shanghai) Co., Ltd.) 仓库里的章节书稿、截图与样张页面同样按 MIT 授权。被引用的 openai/codex 源码片段版权归原作者所有,引用用于教学说明。assets/group-qrcode.png4.6 KBf0c07ddad739upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/preview-cite.png129 KB4a33414b2714upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/preview-colophon.png120 KBeb9130cd4405upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/preview-cover.png224 KB323f7f326329upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/qrcode.jpg27 KB3c64a977a6b2upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/x-qrcode.png1.6 KBe76df18e2008upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
.gitignore66 Bb58d3b325959upstream ↗
.DS_Store dist/ /book.config.json __pycache__/ *.pyc docs/_shots/AGENTS.md1.8 KB02f0203a683bupstream ↗
# 给 AI 的入口 这个仓库是一套源码精读方法论:带 AI 精读大型开源仓库,产出每句话都能回溯到源码具体行的书稿、课程或技术文档。 ## 要用这套方法论干活 **动手之前先完整读 [`SKILL.md`](SKILL.md)。** 它是唯一入口,一份文件讲完整套流程:四阶段工作流、零幻觉铁律、引用格式、文风约束、机器校验、并行生产。需要细节时再去读 `templates/`、`PITFALLS.md` 和 `book/README.md`,不要凭印象补。 一条不可妥协:**每一个技术论断都可回溯到源码的具体行。** 代码块必须与源文件逐字节一致,行号动笔前用读文件工具实读核实,中间跳过内容要写显式省略标记,查不到就写明「未找到对应实现,检索关键词为 X、Y」。编一个看起来合理的,整份产出的可信度就是零。 接到任务先问清产出形态和规模再动手。读懂一个模块、写一篇架构分析、做一门几十节的课,该走的阶段数完全不同,四阶段全流程很重,小任务不需要。 ## 要改这个仓库本身 - 方法论正文改 `METHODOLOGY.md`,改完确认 `SKILL.md` 里的对应段落没跟它矛盾。两份都是入口,漂移了后来的人会按错的那份做 - 新踩的坑加进 `PITFALLS.md`,写清现象、原因、怎么防。不写抽象教训 - 动过 `book/` 的主题或 `sample/chapters/`,重建样张并确认产物正常: ```bash python3 book/build_book.py --config sample/book.config.json # 产物在 docs/,提交后 Pages 自动发布 python3 book/shot_book.py docs -c ch-02.html # 截图校对,同时报告页面 JS 报错 ``` - 面向读者的正文交付前跑 `python3 templates/style_scan.py <路径>`,句式禁忌必须清零。不要用同义替换绕过正则,禁的是那种表达方式,不是那几个字book/book.config.example.json551 B8b463e86974bupstream ↗
{ "title": "一台 Agent 运行时的安全观", "subtitle": "当它敢在你的机器上跑命令、连网络、带着你的凭据,它凭什么值得被信任。三十二章逐行精读,每一处论断都能回溯到源码的具体某一行。", "kicker": "源码精读", "author": "你的名字", "repo": "https://github.com/openai/codex", "anchor": { "commit": "4f39251a01", "tag": "course-anchor-20260822", "date": "2026-08-22" }, "accent": "#3f4a5a", "lang": "zh-CN", "chapters": "chapters", "out": "dist" }book/build_book.py20 KBf1d8eb656bedupstream ↗
#!/usr/bin/env python3 """把章节 markdown 编成一本可以读的 HTML 书。 用法: python3 book/build_book.py # 读 book.config.json python3 book/build_book.py --config my.json python3 book/build_book.py --keep-selfcheck # 保留每章末尾的交付自查 输入是阶段三产出的章节 markdown,输出是一个自带封面、目录、正文与封底的 静态站点目录,直接用浏览器打开 index.html 即可阅读。 依赖: markdown(pip install markdown) """ from __future__ import annotations import argparse import html import json import re import shutil import sys from dataclasses import dataclass, field from pathlib import Path try: import markdown as md_lib except ImportError: sys.exit("缺少依赖,请先执行: pip install markdown") ROOT = Path(__file__).resolve().parent THEME = ROOT / "theme" METHODOLOGY_NAME = "洛小山·小山学堂方法论" METHODOLOGY_URL = "https://github.com/itshen/source-reading-methodology" MD_EXTENSIONS = ["tables", "attr_list", "sane_lists"] # 章节正文的固定八段,用于给每段配图标与锚点 SECTION_ICONS = { "场景还原": "scene", "逐行精读": "read", "设计决策分析": "why", "边界条件剖析": "edge", "横向对比": "compare", "互动演示设计": "demo", "可迁移结论": "takeaway", "思考题": "quiz", } FENCE_RE = re.compile(r"^(?P<indent>[ \t]*)```(?P<info>[^\n]*)\n(?P<body>.*?)^(?P=indent)```[ \t]*$", re.S | re.M) CITATION_INFO_RE = re.compile(r"^(\d+):(\d+):(.+)$") # 省略标记:整行注释,且注释内容紧接着就是 `...`。 # 含 `...` 但前面还有别的话的注释是正常代码,不算省略。 COMMENT_LEAD_RE = re.compile(r"^\s*(?://+|#+|--|/\*+|<!--|\*)?\s*") @dataclass class Block: """一个从正文里摘出来的围栏块,转换完再塞回去。""" kind: str # citation | mermaid | code html: str CHAPTER_PREFIX_RE = re.compile(r"^第\s*[0-90-9一二三四五六七八九十百]+\s*[章讲课节][::、.\s-]*") @dataclass class Chapter: src: Path index: int title: str meta_lines: list[str] summary: str body_html: str toc: list[tuple[int, str, str]] = field(default_factory=list) # (level, id, text) citations: int = 0 diagrams: int = 0 han: int = 0 @property def out_name(self) -> str: return f"ch-{self.index:02d}.html" @property def short_title(self) -> str: """去掉标题自带的「第 N 章:」,因为版面上已经单独排了章序。""" return CHAPTER_PREFIX_RE.sub("", self.title).strip() or self.title def slugify(text: str, used: set[str]) -> str: base = re.sub(r"[^\w一-鿿-]+", "-", text.strip()).strip("-").lower() base = base or "sec" slug, n = base, 2 while slug in used: slug, n = f"{base}-{n}", n + 1 used.add(slug) return slug def is_gap_line(line: str) -> bool: return COMMENT_LEAD_RE.sub("", line, count=1).startswith("...") def line_numbers(count: int, start: int, end: int, gaps: list[int]) -> list[int | None]: """省略之后的行号是推不出来的,只有开头和结尾两段能确定。 开头那段从 start 正着数,结尾那段从 end 倒着数,夹在两个省略之间的段落一律留空。 宁可不显示,也不显示一个编出来的行号。 """ nums: list[int | None] = [None] * count if not gaps: for i in range(count): nums[i] = start + i return nums for i in range(gaps[0]): nums[i] = start + i tail = list(range(gaps[-1] + 1, count)) for k, i in enumerate(tail): nums[i] = end - (len(tail) - 1 - k) return nums def render_citation(info: str, body: str) -> str: """带行号的源码引用块:显示文件路径、真实行号栏,并按省略标记切段以便步进。""" m = CITATION_INFO_RE.match(info) start, end, path = (int(m.group(1)), int(m.group(2)), m.group(3)) if m else (1, 1, info or "") lines = body.rstrip("\n").split("\n") gaps = [i for i, line in enumerate(lines) if is_gap_line(line)] nums = line_numbers(len(lines), start, end, gaps) if m and not gaps and len(lines) != end - start + 1: print(f" [提示] {path} 声明 {start}:{end} 共 {end - start + 1} 行," f"实际 {len(lines)} 行,行号栏可能对不上") seg, rows = 0, [] for i, line in enumerate(lines): if i in gaps: seg += 1 rows.append( f'<span class="cl gap" data-seg="{seg}">' f'<span class="ln">⋯</span>' f'<span class="lt">{html.escape(line)}</span></span>' ) seg += 1 continue label = str(nums[i]) if nums[i] is not None else "·" rows.append( f'<span class="cl" data-seg="{seg}">' f'<span class="ln">{label}</span>' f'<span class="lt">{html.escape(line)}</span></span>' ) steppable = ' data-steppable="1"' if seg else "" step_btn = '<button class="cite-btn step" type="button">逐段</button>' if seg else "" lines_label = html.escape(info.rsplit(":", 1)[0]) if m else "" head = ( '<div class="cite-head">' f'<span class="cite-path" title="{html.escape(path)}">{html.escape(path)}</span>' f'<span class="cite-lines">{lines_label}</span>' '<span class="cite-tools">' f'{step_btn}' '<button class="cite-btn copy" type="button">复制</button>' "</span></div>" ) return (f'<figure class="cite"{steppable}>{head}' f'<pre class="cite-body"><code>{"".join(rows)}</code></pre></figure>') def render_mermaid(body: str) -> str: return f'<figure class="diagram"><div class="mermaid">{html.escape(body.rstrip())}</div></figure>' def render_code(info: str, body: str) -> str: lang = (info or "text").strip() return (f'<figure class="code"><div class="code-head"><span>{html.escape(lang)}</span>' f'<button class="cite-btn copy" type="button">复制</button></div>' f'<pre><code>{html.escape(body.rstrip())}</code></pre></figure>') def extract_blocks(text: str) -> tuple[str, list[Block]]: """把围栏块换成占位 div,避免 markdown 解析器改动块内容。""" blocks: list[Block] = [] def repl(m: re.Match) -> str: info, body = m.group("info").strip(), m.group("body") if info == "mermaid": blocks.append(Block("mermaid", render_mermaid(body))) elif CITATION_INFO_RE.match(info): blocks.append(Block("citation", render_citation(info, body))) else: blocks.append(Block("code", render_code(info, body))) return f'{m.group("indent")}<div data-block="{len(blocks) - 1}"></div>' return FENCE_RE.sub(repl, text), blocks def restore_blocks(html_text: str, blocks: list[Block]) -> str: def repl(m: re.Match) -> str: return blocks[int(m.group(1))].html return re.sub(r'<div data-block="(\d+)"></div>', repl, html_text) def decorate_sections(body: str, toc: list) -> str: """给二级标题挂锚点与图标类,同时收集目录。""" used: set[str] = set() def h2(m: re.Match) -> str: text = re.sub(r"<[^>]+>", "", m.group(1)) sid = slugify(text, used) kind = SECTION_ICONS.get(text.strip(), "plain") toc.append((2, sid, text)) return (f'<h2 id="{sid}" class="sec sec-{kind}" data-sec="{html.escape(text)}">' f'<span class="sec-mark"></span>{m.group(1)}</h2>') def h3(m: re.Match) -> str: text = re.sub(r"<[^>]+>", "", m.group(1)) sid = slugify(text, used) toc.append((3, sid, text)) return f'<h3 id="{sid}">{m.group(1)}</h3>' body = re.sub(r"<h2>(.*?)</h2>", h2, body, flags=re.S) body = re.sub(r"<h3>(.*?)</h3>", h3, body, flags=re.S) return body def strip_selfcheck(text: str) -> str: """交付自查是写给制作方看的过程记录,成书默认不收。""" m = re.search(r"^##\s*交付自查\s*$", text, re.M) if not m: return text cut = text[: m.start()] return re.sub(r"\n---\s*\n\s*$", "\n", cut) def first_sentence(text: str) -> str: para = "" m = re.search(r"^##\s*场景还原\s*$", text, re.M) if m: rest = text[m.end():].lstrip("\n") para = rest.split("\n\n", 1)[0].strip() if not para: return "" para = re.sub(r"[`*]", "", para.replace("\n", "")) parts = re.split(r"(?<=[。?!])", para) out = "" for p in parts: if not p: continue out += p if len(out) >= 24: break return out[:90] def parse_chapter(path: Path, index: int, keep_selfcheck: bool) -> Chapter: raw = path.read_text(encoding="utf-8") if not keep_selfcheck: raw = strip_selfcheck(raw) m = re.search(r"^#\s+(.+?)\s*$", raw, re.M) title = m.group(1).strip() if m else path.stem rest = raw[m.end():] if m else raw meta_lines: list[str] = [] summary = "" lines = rest.lstrip("\n").split("\n") consumed = 0 for line in lines: if line.startswith(">"): item = line.lstrip("> ").strip() if item.startswith("摘要:"): summary = item[3:].strip() elif item: meta_lines.append(item) consumed += 1 elif not line.strip() and consumed: consumed += 1 break elif not line.strip(): consumed += 1 else: break body_md = "\n".join(lines[consumed:]) summary = summary or first_sentence(raw) stripped, blocks = extract_blocks(body_md) converted = md_lib.markdown(stripped, extensions=MD_EXTENSIONS) toc: list[tuple[int, str, str]] = [] converted = decorate_sections(converted, toc) body_html = restore_blocks(converted, blocks) prose = re.sub(r"<(pre|figure)[^>]*>.*?</\1>", "", body_html, flags=re.S) prose = re.sub(r"<[^>]+>", "", prose) return Chapter( src=path, index=index, title=title, meta_lines=meta_lines, summary=summary, body_html=body_html, toc=toc, citations=sum(1 for b in blocks if b.kind == "citation"), diagrams=sum(1 for b in blocks if b.kind == "mermaid"), han=len(re.findall(r"[一-鿿]", prose)), ) def footer_html() -> str: return ( '<footer class="book-foot">' f'<span>来自 <a href="{METHODOLOGY_URL}" target="_blank" rel="noopener">' f"{METHODOLOGY_NAME}</a></span>" f'<a class="foot-repo" href="{METHODOLOGY_URL}" target="_blank" rel="noopener">' f"{METHODOLOGY_URL.replace('https://', '')}</a>" "</footer>" ) def shell(title: str, cfg: dict, body: str, cls: str, extra_head: str = "") -> str: accent = cfg.get("accent", "#3f4a5a") return f"""<!DOCTYPE html> <html lang="{cfg.get('lang', 'zh-CN')}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>{html.escape(title)}</title> <meta name="description" content="{html.escape(cfg.get('subtitle', ''))}"> <meta name="author" content="{html.escape(cfg.get('author', ''))}"> <style>:root{{--accent:{accent}}}</style> <link rel="stylesheet" href="assets/book.css"> {extra_head} </head> <body class="{cls}"> <div class="progress"><i></i></div> {body} {footer_html()} <script src="assets/book.js"></script> </body> </html> """ def build_cover(cfg: dict, chapters: list[Chapter]) -> str: anchor = cfg.get("anchor", {}) anchor_bits = [b for b in ( f"commit {anchor['commit']}" if anchor.get("commit") else "", f"tag {anchor['tag']}" if anchor.get("tag") else "", anchor.get("date", ""), ) if b] stats = [ ("章", len(chapters)), ("处源码引用", sum(c.citations for c in chapters)), ("万字", round(sum(c.han for c in chapters) / 10000, 1)), ] stat_html = "".join( f'<div class="stat"><b data-count="{v}">0</b><span>{k}</span></div>' for k, v in stats ) toc_html = "".join( f'<li><a href="{c.out_name}"><span class="n">{c.index:02d}</span>' f'<span class="t">{html.escape(c.short_title)}</span>' f'<span class="d">{html.escape(c.summary)}</span></a></li>' for c in chapters ) repo = cfg.get("repo", "") repo_html = (f'<a class="src-repo" href="{html.escape(repo)}" target="_blank" ' f'rel="noopener">{html.escape(repo.replace("https://", ""))}</a>') if repo else "" body = f""" <main class="cover"> <section class="cover-hero"> <p class="kicker">{html.escape(cfg.get('kicker', '源码精读'))}</p> <h1>{html.escape(cfg.get('title', '未命名'))}</h1> <p class="sub">{html.escape(cfg.get('subtitle', ''))}</p> <p class="by">{html.escape(cfg.get('author', ''))}</p> <div class="stats">{stat_html}</div> <p class="anchor">{html.escape(' · '.join(anchor_bits))}</p> {repo_html} <a class="start" href="{chapters[0].out_name if chapters else '#'}">开始阅读</a> </section> <section class="cover-toc reveal"> <h2>目录</h2> <ol class="toc">{toc_html}</ol> <a class="colophon-link" href="colophon.html">关于这本书</a> </section> </main> """ return shell(cfg.get("title", "未命名"), cfg, body, "is-cover") def build_chapter(cfg: dict, ch: Chapter, prev: Chapter | None, nxt: Chapter | None, total: int) -> str: side = "".join( f'<a class="lv{lv}" href="#{sid}">{html.escape(text)}</a>' for lv, sid, text in ch.toc ) meta = "".join(f"<span>{html.escape(x)}</span>" for x in ch.meta_lines) nav = [] nav.append(f'<a class="prev" href="{prev.out_name}">← {html.escape(prev.short_title)}</a>' if prev else '<a class="prev" href="index.html">← 封面</a>') nav.append(f'<a class="next" href="{nxt.out_name}">{html.escape(nxt.short_title)} →</a>' if nxt else '<a class="next" href="colophon.html">关于这本书 →</a>') mermaid = ('<script type="module">' 'import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";' 'window.__mermaid = mermaid;' 'mermaid.initialize({startOnLoad:false,theme:"neutral",' 'fontFamily:"inherit",flowchart:{curve:"basis"}});' 'document.dispatchEvent(new Event("mermaid-ready"));' "</script>") if ch.diagrams else "" body = f""" <header class="topbar"> <a class="home" href="index.html">{html.escape(cfg.get('title', ''))}</a> <span class="pos">{ch.index} / {total}</span> <button class="theme" type="button" aria-label="切换深浅色"></button> </header> <div class="wrap"> <aside class="side"><nav>{side}</nav></aside> <main class="chapter"> <p class="ch-num">第 {ch.index} 章</p> <h1>{html.escape(ch.short_title)}</h1> <div class="ch-meta">{meta}</div> {ch.body_html} <nav class="ch-nav">{''.join(nav)}</nav> </main> </div> {mermaid} """ return shell(f"{ch.title} · {cfg.get('title', '')}", cfg, body, "is-chapter") def build_colophon(cfg: dict, chapters: list[Chapter]) -> str: anchor = cfg.get("anchor", {}) rows = "".join( f"<tr><td>{c.index:02d}</td><td>{html.escape(c.short_title)}</td>" f"<td>{c.citations}</td><td>{c.diagrams}</td><td>{c.han}</td></tr>" for c in chapters ) total_cit = sum(c.citations for c in chapters) total_han = sum(c.han for c in chapters) body = f""" <header class="topbar"> <a class="home" href="index.html">{html.escape(cfg.get('title', ''))}</a> <span class="pos">封底</span> <button class="theme" type="button" aria-label="切换深浅色"></button> </header> <main class="colophon"> <h1>关于这本书</h1> <p class="lead">这本书里的每一处技术论断,都能回溯到源码的具体某一行。 下面这张表是成书时的实际数据,口径写在表头里。</p> <table class="stat-table"> <thead><tr><th>章</th><th>标题</th><th>带行号引用</th><th>图</th><th>正文汉字</th></tr></thead> <tbody>{rows}</tbody> <tfoot><tr><td colspan="2">合计</td><td>{total_cit}</td> <td>{sum(c.diagrams for c in chapters)}</td><td>{total_han}</td></tr></tfoot> </table> <h2>版本锚点</h2> <p>正文里的所有行号对应下面这个版本。上游仓库一直在改,隔一段时间再照着查,行号可能已经漂了。</p> <ul class="anchor-list"> <li>仓库:{html.escape(cfg.get('repo', '未填写'))}</li> <li>commit:<code>{html.escape(anchor.get('commit', '未填写'))}</code></li> <li>tag:<code>{html.escape(anchor.get('tag', '未填写'))}</code></li> <li>核对日期:{html.escape(anchor.get('date', '未填写'))}</li> </ul> <h2>怎么读</h2> <ul class="how-list"> <li>代码块左侧是源文件里的真实行号,可以直接跳回原仓库对照</li> <li>带 <b>逐段</b> 按钮的引用块中间有省略,点一下会按连续段落依次高亮,省略处不会被当成连续代码</li> <li>每章末尾的思考题里至少有一道要动手改代码验证,那一道最值钱</li> </ul> <h2>这本书是怎么做出来的</h2> <p>用一套公开的方法论:先锁版本锚点,再写带源码锚点的大纲,然后按八段结构逐章精读, 最后编成这本书。全程由脚本把每一个代码块拿回源文件逐字节比对,行号错了自动校正, 静默删行会被判定为编造并退回重写。</p> <a class="method-link" href="{METHODOLOGY_URL}" target="_blank" rel="noopener"> 方法论与模板已开源,可直接取用</a> </main> """ return shell(f"关于这本书 · {cfg.get('title', '')}", cfg, body, "is-colophon") def main() -> int: ap = argparse.ArgumentParser(description="把章节 markdown 编成一本 HTML 书") ap.add_argument("--config", default="book.config.json") ap.add_argument("--keep-selfcheck", action="store_true", help="保留每章末尾的交付自查") args = ap.parse_args() cfg_path = Path(args.config) if not cfg_path.is_file(): print(f"找不到配置文件 {cfg_path},可复制 book/book.config.example.json 改") return 1 cfg = json.loads(cfg_path.read_text(encoding="utf-8")) base = cfg_path.resolve().parent src_dir = (base / cfg.get("chapters", "chapters")).resolve() out_dir = (base / cfg.get("out", "dist")).resolve() if not src_dir.is_dir(): print(f"章节目录不存在: {src_dir}") return 1 files = sorted(p for p in src_dir.glob("*.md") if not p.name.startswith("_")) if not files: print(f"{src_dir} 里没有找到章节 markdown") return 1 print(f"读入 {len(files)} 章,来自 {src_dir}") chapters = [parse_chapter(p, i + 1, args.keep_selfcheck) for i, p in enumerate(files)] assets = out_dir / "assets" assets.mkdir(parents=True, exist_ok=True) for name in ("book.css", "book.js"): shutil.copy2(THEME / name, assets / name) (out_dir / "index.html").write_text(build_cover(cfg, chapters), encoding="utf-8") for i, ch in enumerate(chapters): prev = chapters[i - 1] if i else None nxt = chapters[i + 1] if i + 1 < len(chapters) else None (out_dir / ch.out_name).write_text( build_chapter(cfg, ch, prev, nxt, len(chapters)), encoding="utf-8") print(f" 第 {ch.index:2d} 章 {ch.title[:34]:36s} 引用 {ch.citations:3d} " f"图 {ch.diagrams} 汉字 {ch.han}") (out_dir / "colophon.html").write_text(build_colophon(cfg, chapters), encoding="utf-8") print(f"\n成书 {len(chapters)} 章,共 {sum(c.citations for c in chapters)} 处引用、" f"{sum(c.han for c in chapters)} 汉字") print(f"输出目录 {out_dir}") print(f"打开 {out_dir / 'index.html'}") return 0 if __name__ == "__main__": sys.exit(main())book/shot_book.py3.2 KB6dc66bcebaa0upstream ↗
#!/usr/bin/env python3 """给成书截图,用于人工校对排版。 用法: python3 book/shot_book.py <dist 目录> [-o 输出目录] [-c ch-04.html] 封面、正文、封底各出一张长图,正文另出一张引用块步进中的局部图。 依赖: playwright(pip install playwright && playwright install chromium) """ import argparse import sys from pathlib import Path from playwright.sync_api import sync_playwright def main() -> int: ap = argparse.ArgumentParser(description="给成书截图") ap.add_argument("dist", nargs="?", default="dist") ap.add_argument("-o", "--out", default=None, help="截图输出目录,默认 <dist>/_shots") ap.add_argument("-c", "--chapter", default="ch-01.html", help="要截的正文页") args = ap.parse_args() dist = Path(args.dist).resolve() out = Path(args.out).resolve() if args.out else dist / "_shots" if not (dist / "index.html").is_file(): print(f"找不到 {dist / 'index.html'}") return 1 out.mkdir(parents=True, exist_ok=True) chapter = args.chapter pages = [("index.html", "cover"), (chapter, "chapter"), ("colophon.html", "colophon")] errors: list[str] = [] with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page(viewport={"width": 1280, "height": 900}, device_scale_factor=2) page.on("pageerror", lambda e: errors.append(str(e))) page.on("console", lambda m: errors.append(f"console.{m.type}: {m.text}") if m.type == "error" else None) for name, tag in pages: target = dist / name if not target.is_file(): continue page.goto(target.as_uri()) page.wait_for_timeout(900) height = page.evaluate("document.body.scrollHeight") for y in range(0, height + 600, 600): page.evaluate(f"window.scrollTo(0, {y})") page.wait_for_timeout(90) # 渐入靠 IntersectionObserver 触发,快速滚动会来不及。 # 只在截图时强制展开,页面本身的动画逻辑不动。 page.evaluate( "document.querySelectorAll('.reveal').forEach(e => e.classList.add('in'))") page.evaluate("window.scrollTo(0, 0)") page.wait_for_timeout(700) shot = out / f"{tag}.png" page.screenshot(path=str(shot), full_page=True) print(f"{tag:9s} {shot}") # 引用块步进中的样子 page.goto((dist / chapter).as_uri()) page.wait_for_timeout(700) fig = page.locator("figure.cite[data-steppable]").first if fig.count(): fig.scroll_into_view_if_needed() page.wait_for_timeout(400) fig.locator(".cite-btn.step").click() page.wait_for_timeout(600) shot = out / "cite-stepping.png" fig.screenshot(path=str(shot)) print(f"{'步进':9s} {shot}") browser.close() if errors: print("\n页面报错:") for e in dict.fromkeys(errors): print(" " + e) else: print("\n无 JS 报错") return 0 if __name__ == "__main__": sys.exit(main())book/theme/book.css17 KB53166ed81218upstream ↗
/* 源码精读成书样式。全部变量集中在 :root,换主色只改 --accent。 */ :root { --accent: #3f4a5a; --bg: #fbfaf8; --paper: #fff; --ink: #1c1f24; --sub: #5b6270; --faint: #8b93a1; --line: #e7e4de; --code-bg: #f7f6f3; --code-ink: #2b3038; --mark: rgba(63, 74, 90, .1); --shadow: 0 1px 2px rgba(28, 31, 36, .04), 0 8px 28px rgba(28, 31, 36, .05); --serif: "Songti SC", "Source Han Serif SC", "Noto Serif CJK SC", Georgia, serif; --sans: -apple-system, BlinkMacSystemFont, "PingFang SC", "Noto Sans CJK SC", "Microsoft YaHei", system-ui, sans-serif; --mono: "SF Mono", ui-monospace, Menlo, Consolas, "Liberation Mono", monospace; --measure: 40rem; } body.dark { --bg: #14161a; --paper: #191c21; --ink: #e6e6e4; --sub: #a6adb9; --faint: #767e8c; --line: #2a2e35; --code-bg: #1e2127; --code-ink: #d7dae0; --mark: rgba(150, 172, 205, .16); --shadow: 0 1px 2px rgba(0, 0, 0, .3), 0 10px 30px rgba(0, 0, 0, .28); } * { box-sizing: border-box; } html { scroll-behavior: smooth; scroll-padding-top: 76px; } body { margin: 0; background: var(--bg); color: var(--ink); font-family: var(--sans); font-size: 17px; line-height: 1.95; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; } a { color: inherit; } /* ── 顶部阅读进度 ───────────────────────────── */ .progress { position: fixed; inset: 0 0 auto 0; height: 2px; z-index: 60; background: transparent; pointer-events: none; } .progress i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .12s linear; } /* ── 封面 ──────────────────────────────────── */ .is-cover { background: radial-gradient(1100px 620px at 50% -8%, var(--mark), transparent 62%), var(--bg); } .cover { max-width: 62rem; margin: 0 auto; padding: 0 24px 80px; } .cover-hero { min-height: 92vh; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 4px; } .cover-hero .kicker { margin: 0 0 14px; font-size: 13px; letter-spacing: .34em; text-indent: .34em; color: var(--faint); text-transform: uppercase; animation: rise .8s .05s both; } .cover-hero h1 { margin: 0; font-family: var(--serif); font-weight: 700; font-size: clamp(2.2rem, 6vw, 4rem); line-height: 1.28; letter-spacing: -.01em; max-width: 22ch; animation: rise .9s .12s both; } .cover-hero .sub { margin: 20px 0 0; max-width: 34rem; color: var(--sub); font-size: 1.02rem; line-height: 1.85; animation: rise .9s .2s both; } .cover-hero .by { margin: 26px 0 0; font-size: 14px; color: var(--faint); letter-spacing: .08em; animation: rise .9s .28s both; } .stats { display: flex; gap: 40px; margin: 40px 0 0; animation: rise .9s .36s both; } .stat { display: flex; flex-direction: column; align-items: center; } .stat b { font-family: var(--serif); font-size: 2rem; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.2; } .stat span { font-size: 12px; color: var(--faint); letter-spacing: .1em; } .cover-hero .anchor { margin: 34px 0 0; font-family: var(--mono); font-size: 12px; color: var(--faint); animation: rise .9s .44s both; } .src-repo { margin-top: 6px; font-family: var(--mono); font-size: 12px; color: var(--accent); text-decoration: none; border-bottom: 1px solid transparent; animation: rise .9s .48s both; } .src-repo:hover { border-bottom-color: currentColor; } .start { margin-top: 40px; padding: 13px 34px; border-radius: 999px; background: var(--accent); color: #fff; text-decoration: none; font-size: 15px; letter-spacing: .04em; box-shadow: var(--shadow); transition: transform .2s, box-shadow .2s; animation: rise .9s .56s both; } .start:hover { transform: translateY(-2px); box-shadow: 0 10px 30px rgba(28, 31, 36, .16); } .cover-toc { padding: 20px 0 0; } .cover-toc h2 { margin: 0 0 26px; font-family: var(--serif); font-size: 1.3rem; font-weight: 700; letter-spacing: .02em; text-align: center; } ol.toc { list-style: none; margin: 0; padding: 0; } ol.toc li { border-top: 1px solid var(--line); } ol.toc li:last-child { border-bottom: 1px solid var(--line); } ol.toc a { display: grid; grid-template-columns: 3.4rem 1fr; gap: 2px 18px; padding: 20px 14px; text-decoration: none; transition: background .18s, padding-left .18s; } ol.toc a:hover { background: var(--paper); padding-left: 22px; } ol.toc .n { grid-row: 1 / span 2; font-family: var(--serif); font-size: 1.5rem; color: var(--faint); font-variant-numeric: tabular-nums; line-height: 1.4; } ol.toc .t { font-size: 1.02rem; font-weight: 600; line-height: 1.6; } ol.toc .d { font-size: 14px; color: var(--sub); line-height: 1.75; } .colophon-link { display: inline-block; margin-top: 30px; font-size: 14px; color: var(--sub); text-decoration: none; border-bottom: 1px solid var(--line); } .colophon-link:hover { color: var(--accent); border-bottom-color: currentColor; } /* ── 顶栏 ──────────────────────────────────── */ .topbar { position: sticky; top: 0; z-index: 50; display: flex; align-items: center; gap: 16px; padding: 12px 24px; background: color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter: saturate(1.4) blur(10px); border-bottom: 1px solid var(--line); } .topbar .home { font-size: 14px; font-weight: 600; text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .topbar .pos { margin-left: auto; font-family: var(--mono); font-size: 12px; color: var(--faint); font-variant-numeric: tabular-nums; } .topbar .theme { width: 30px; height: 30px; border-radius: 8px; cursor: pointer; border: 1px solid var(--line); background: transparent; color: var(--sub); display: grid; place-items: center; } .topbar .theme::before { content: "◐"; font-size: 15px; } .topbar .theme:hover { border-color: var(--accent); color: var(--accent); } /* ── 正文骨架 ──────────────────────────────── */ .wrap { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, var(--measure)) minmax(0, 1fr); gap: 0 32px; max-width: 84rem; margin: 0 auto; padding: 0 24px; } .side { grid-column: 1; } .side nav { position: sticky; top: 84px; padding: 44px 0 40px; max-height: calc(100vh - 96px); overflow-y: auto; display: flex; flex-direction: column; gap: 2px; border-right: 1px solid var(--line); margin-right: 8px; } .side a { padding: 5px 14px 5px 12px; font-size: 13px; line-height: 1.6; color: var(--faint); text-decoration: none; border-left: 2px solid transparent; transition: color .16s, border-color .16s; } .side a.lv3 { padding-left: 26px; font-size: 12.5px; } .side a:hover { color: var(--ink); } .side a.on { color: var(--accent); border-left-color: var(--accent); font-weight: 600; } .chapter { grid-column: 2; padding: 44px 0 88px; min-width: 0; } .ch-num { margin: 0 0 10px; font-family: var(--mono); font-size: 12px; letter-spacing: .22em; color: var(--faint); } .chapter > h1 { margin: 0 0 20px; font-family: var(--serif); font-weight: 700; font-size: clamp(1.7rem, 3.6vw, 2.4rem); line-height: 1.36; letter-spacing: -.005em; } .ch-meta { display: flex; flex-direction: column; gap: 4px; margin: 0 0 52px; padding: 14px 18px; border-radius: 10px; background: var(--paper); border: 1px solid var(--line); font-family: var(--mono); font-size: 12px; line-height: 1.8; color: var(--sub); } /* ── 章节段落与标题 ────────────────────────── */ .chapter p { margin: 0 0 22px; } .chapter p + p { margin-top: -4px; } h2.sec { position: relative; margin: 72px 0 24px; padding-top: 26px; font-family: var(--serif); font-size: 1.42rem; font-weight: 700; line-height: 1.5; letter-spacing: .01em; border-top: 1px solid var(--line); } h2.sec .sec-mark { position: absolute; top: -1px; left: 0; width: 46px; height: 2px; background: var(--accent); } .chapter h3 { margin: 44px 0 16px; font-size: 1.08rem; font-weight: 700; line-height: 1.65; letter-spacing: .01em; } .chapter h4 { margin: 30px 0 12px; font-size: 1rem; font-weight: 600; } .chapter ul, .chapter ol { margin: 0 0 22px; padding-left: 1.4em; } .chapter li { margin: 0 0 9px; } .chapter li > ul, .chapter li > ol { margin: 9px 0 4px; } .chapter blockquote { margin: 0 0 24px; padding: 4px 0 4px 20px; border-left: 2px solid var(--accent); color: var(--sub); font-size: .97rem; } .chapter blockquote p:last-child { margin-bottom: 0; } .chapter hr { margin: 44px 0; border: 0; border-top: 1px solid var(--line); } .chapter strong { font-weight: 700; } .chapter em { font-style: normal; background: var(--mark); padding: 0 .2em; border-radius: 3px; } code { font-family: var(--mono); font-size: .875em; background: var(--code-bg); color: var(--code-ink); padding: .12em .38em; border-radius: 4px; word-break: break-word; } /* ── 表格 ──────────────────────────────────── */ .chapter table { width: 100%; margin: 0 0 26px; border-collapse: collapse; font-size: 14.5px; line-height: 1.75; background: var(--paper); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; display: table; } .chapter th, .chapter td { padding: 11px 14px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--line); } .chapter th { font-weight: 600; font-size: 13.5px; color: var(--sub); background: var(--code-bg); } .chapter tr:last-child td { border-bottom: 0; } .chapter td code { font-size: .84em; } /* ── 源码引用块 ────────────────────────────── */ figure.cite, figure.code { margin: 0 0 26px; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); overflow: hidden; box-shadow: var(--shadow); } .cite-head, .code-head { display: flex; align-items: center; gap: 12px; padding: 9px 14px; background: var(--code-bg); border-bottom: 1px solid var(--line); font-family: var(--mono); font-size: 11.5px; color: var(--sub); } .cite-path { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl; text-align: left; flex: 1 1 auto; min-width: 0; } .cite-lines { color: var(--faint); flex: 0 0 auto; } .cite-tools { margin-left: auto; display: flex; gap: 6px; flex: 0 0 auto; } .cite-btn { font: inherit; font-size: 11px; cursor: pointer; color: var(--sub); padding: 2px 9px; border-radius: 999px; border: 1px solid var(--line); background: var(--paper); transition: color .15s, border-color .15s; } .cite-btn:hover { color: var(--accent); border-color: var(--accent); } .cite-btn.on { color: #fff; background: var(--accent); border-color: var(--accent); } pre { margin: 0; padding: 14px 0; overflow-x: auto; font-family: var(--mono); font-size: 13px; line-height: 1.75; color: var(--code-ink); } pre code { background: none; padding: 0; font-size: inherit; } .cite-body .cl { display: flex; padding: 0 14px; } .cite-body .ln { flex: 0 0 3.4em; text-align: right; padding-right: 1.1em; color: var(--faint); user-select: none; font-variant-numeric: tabular-nums; } .cite-body .lt { white-space: pre; } .cite-body .cl.gap { color: var(--faint); font-style: italic; } .cite-body .cl.gap .lt { opacity: .7; } /* 逐段步进:未命中的段落压暗,命中的段落上底色 */ figure.cite.stepping .cl { opacity: .28; transition: opacity .25s, background .25s; } figure.cite.stepping .cl.hot { opacity: 1; background: var(--mark); } /* ── 图 ────────────────────────────────────── */ figure.diagram { margin: 0 0 28px; padding: 22px 18px; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); text-align: center; box-shadow: var(--shadow); overflow-x: auto; } figure.diagram .mermaid { font-family: var(--sans); } figure.diagram svg { max-width: 100%; height: auto; } figure.diagram.drawing svg .edgePath path, figure.diagram.drawing svg .flowchart-link, figure.diagram.drawing svg .messageLine0, figure.diagram.drawing svg .messageLine1 { stroke-dasharray: 1000; stroke-dashoffset: 1000; animation: draw 1.1s ease forwards; } figure.diagram.drawing svg .node, figure.diagram.drawing svg .actor, figure.diagram.drawing svg .label { animation: fade .7s .18s both; } /* ── 章末导航 ──────────────────────────────── */ .ch-nav { display: flex; gap: 16px; margin-top: 76px; padding-top: 26px; border-top: 1px solid var(--line); font-size: 14px; } .ch-nav a { flex: 1 1 0; min-width: 0; padding: 16px 18px; border-radius: 10px; background: var(--paper); border: 1px solid var(--line); text-decoration: none; color: var(--sub); line-height: 1.6; transition: border-color .18s, color .18s, transform .18s; } .ch-nav a:hover { color: var(--ink); border-color: var(--accent); transform: translateY(-1px); } .ch-nav .next { text-align: right; } /* ── 封底 ──────────────────────────────────── */ .colophon { max-width: 46rem; margin: 0 auto; padding: 56px 24px 90px; } .colophon h1 { margin: 0 0 18px; font-family: var(--serif); font-size: 2rem; font-weight: 700; } .colophon .lead { color: var(--sub); margin: 0 0 38px; } .colophon h2 { margin: 48px 0 14px; font-family: var(--serif); font-size: 1.2rem; font-weight: 700; } .colophon p { margin: 0 0 18px; } .stat-table { width: 100%; border-collapse: collapse; font-size: 14px; background: var(--paper); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; } .stat-table th, .stat-table td { padding: 9px 12px; border-bottom: 1px solid var(--line); text-align: left; } .stat-table th { font-size: 12.5px; color: var(--sub); background: var(--code-bg); font-weight: 600; } .stat-table td:nth-child(3), .stat-table td:nth-child(4), .stat-table td:nth-child(5), .stat-table th:nth-child(3), .stat-table th:nth-child(4), .stat-table th:nth-child(5) { text-align: right; font-variant-numeric: tabular-nums; } .stat-table tfoot td { font-weight: 700; background: var(--code-bg); } .anchor-list, .how-list { padding-left: 1.3em; } .anchor-list li, .how-list li { margin-bottom: 8px; } .method-link { display: inline-block; margin-top: 12px; padding: 11px 22px; border-radius: 999px; background: var(--accent); color: #fff; text-decoration: none; font-size: 14px; transition: transform .18s; } .method-link:hover { transform: translateY(-1px); } /* ── 页脚:署名固定出现在每一页 ────────────── */ .book-foot { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 6px 14px; padding: 30px 24px 42px; border-top: 1px solid var(--line); font-size: 12.5px; color: var(--faint); text-align: center; } .book-foot a { color: var(--sub); text-decoration: none; border-bottom: 1px solid var(--line); } .book-foot a:hover { color: var(--accent); border-bottom-color: currentColor; } .book-foot .foot-repo { font-family: var(--mono); font-size: 12px; } /* ── 入场动效 ──────────────────────────────── */ .reveal { opacity: 0; transform: translateY(14px); } .reveal.in { opacity: 1; transform: none; transition: opacity .6s ease, transform .6s ease; } @keyframes rise { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: none; } } @keyframes fade { from { opacity: 0; } to { opacity: 1; } } @keyframes draw { to { stroke-dashoffset: 0; } } @media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } *, *::before, *::after { animation: none !important; transition: none !important; } .reveal { opacity: 1; transform: none; } } /* ── 窄屏 ──────────────────────────────────── */ @media (max-width: 1080px) { .wrap { grid-template-columns: minmax(0, 1fr); } .side { display: none; } .chapter { grid-column: 1; max-width: var(--measure); margin: 0 auto; } } @media (max-width: 720px) { body { font-size: 16px; line-height: 1.9; } .cover { padding: 0 18px 60px; } .stats { gap: 26px; } .stat b { font-size: 1.6rem; } ol.toc a { grid-template-columns: 2.6rem 1fr; gap: 2px 12px; padding: 16px 6px; } .chapter { padding: 32px 0 64px; } .wrap { padding: 0 18px; } pre { font-size: 12px; } .cite-body .ln { flex-basis: 2.8em; } .ch-nav { flex-direction: column; } .ch-nav .next { text-align: left; } } /* ── 打印 ──────────────────────────────────── */ @media print { .topbar, .side, .progress, .ch-nav, .start { display: none; } body { background: #fff; font-size: 11pt; } .wrap { display: block; max-width: none; padding: 0; } figure.cite, figure.code, figure.diagram, .chapter table { break-inside: avoid; } h2.sec { break-after: avoid; } .chapter { padding: 0; } }book/theme/book.js7.5 KB8df34226dfa5upstream ↗
/* 成书交互:阅读进度、滚动渐入、目录跟随、引用块逐段步进、图表绘制动画。 全部原生实现,除 mermaid 外无外部依赖。 */ (function () { 'use strict'; var reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; /* ── 深浅色,记住选择 ───────────────────── */ var KEY = 'book-theme'; var saved = localStorage.getItem(KEY); if (saved === 'dark' || (!saved && matchMedia('(prefers-color-scheme: dark)').matches)) { document.body.classList.add('dark'); } var themeBtn = document.querySelector('.theme'); if (themeBtn) { themeBtn.addEventListener('click', function () { var dark = document.body.classList.toggle('dark'); localStorage.setItem(KEY, dark ? 'dark' : 'light'); }); } /* ── 阅读进度 ───────────────────────────── */ var bar = document.querySelector('.progress i'); if (bar) { var tick = function () { var h = document.documentElement.scrollHeight - innerHeight; bar.style.width = (h > 0 ? Math.min(1, scrollY / h) * 100 : 0) + '%'; }; addEventListener('scroll', tick, { passive: true }); addEventListener('resize', tick); tick(); } /* ── 正文分块渐入 ───────────────────────── */ var main = document.querySelector('.chapter, .colophon'); if (main && !reduce) { var targets = main.querySelectorAll( 'p, h2, h3, h4, ul, ol, figure, table, blockquote, .ch-meta, .ch-nav'); var io = new IntersectionObserver(function (entries) { entries.forEach(function (e) { if (!e.isIntersecting) return; e.target.classList.add('in'); io.unobserve(e.target); }); }, { rootMargin: '0px 0px -8% 0px', threshold: 0.02 }); targets.forEach(function (el) { el.classList.add('reveal'); io.observe(el); }); } document.querySelectorAll('.cover .reveal').forEach(function (el) { if (reduce) { el.classList.add('in'); return; } new IntersectionObserver(function (es, ob) { es.forEach(function (e) { if (!e.isIntersecting) return; e.target.classList.add('in'); ob.disconnect(); }); }, { threshold: 0.05 }).observe(el); }); /* ── 封面数字滚动 ───────────────────────── */ document.querySelectorAll('[data-count]').forEach(function (el) { var end = parseFloat(el.dataset.count) || 0; var dec = (el.dataset.count.split('.')[1] || '').length; if (reduce) { el.textContent = end.toFixed(dec); return; } var t0 = null, dur = 900; var run = function (t) { if (t0 === null) t0 = t; var k = Math.min(1, (t - t0) / dur); el.textContent = (end * (1 - Math.pow(1 - k, 3))).toFixed(dec); if (k < 1) requestAnimationFrame(run); }; requestAnimationFrame(run); }); /* ── 侧栏目录跟随 ───────────────────────── */ var links = [].slice.call(document.querySelectorAll('.side a')); if (links.length) { var heads = links.map(function (a) { return document.getElementById(decodeURIComponent(a.getAttribute('href').slice(1))); }); var sync = function () { var best = 0; heads.forEach(function (h, i) { if (h && h.getBoundingClientRect().top <= 120) best = i; }); links.forEach(function (a, i) { a.classList.toggle('on', i === best); }); }; addEventListener('scroll', sync, { passive: true }); sync(); } /* ── 复制 ───────────────────────────────── */ document.querySelectorAll('.cite-btn.copy').forEach(function (btn) { btn.addEventListener('click', function () { var fig = btn.closest('figure'); var code = fig.querySelector('code'); var text = fig.classList.contains('cite') ? [].map.call(code.querySelectorAll('.lt'), function (s) { return s.textContent; }).join('\n') : code.textContent; navigator.clipboard.writeText(text).then(function () { var old = btn.textContent; btn.textContent = '已复制'; setTimeout(function () { btn.textContent = old; }, 1400); }); }); }); /* ── 引用块逐段步进 ───────────────────────── 带省略标记的引用块中间是断开的。按段依次高亮,让读者看清 哪几行在源文件里真的连在一起,省略处不会被当成连续代码。 */ document.querySelectorAll('figure.cite[data-steppable]').forEach(function (fig) { var btn = fig.querySelector('.cite-btn.step'); if (!btn) return; var lines = [].slice.call(fig.querySelectorAll('.cl')); var segs = []; lines.forEach(function (l) { var s = l.dataset.seg; if (segs.indexOf(s) < 0 && !l.classList.contains('gap')) segs.push(s); }); var at = -1, timer = null; var paint = function () { lines.forEach(function (l) { l.classList.toggle('hot', at >= 0 && l.dataset.seg === segs[at]); }); }; var stop = function () { clearInterval(timer); timer = null; at = -1; fig.classList.remove('stepping'); btn.classList.remove('on'); btn.textContent = '逐段'; lines.forEach(function (l) { l.classList.remove('hot'); }); }; btn.addEventListener('click', function () { if (timer) { stop(); return; } fig.classList.add('stepping'); btn.classList.add('on'); at = 0; paint(); btn.textContent = '第 1 / ' + segs.length + ' 段'; timer = setInterval(function () { at += 1; if (at >= segs.length) { stop(); return; } paint(); btn.textContent = '第 ' + (at + 1) + ' / ' + segs.length + ' 段'; }, 1500); }); }); /* ── 图表:进视野再渲染,配绘制动画 ─────── */ function initDiagrams() { var mermaid = window.__mermaid; if (!mermaid) return; var figs = [].slice.call(document.querySelectorAll('figure.diagram')); if (!figs.length) return; var draw = function (fig) { var box = fig.querySelector('.mermaid'); if (!box || box.dataset.done) return; box.dataset.done = '1'; mermaid.run({ nodes: [box] }).then(function () { if (!reduce) { fig.classList.add('drawing'); setTimeout(function () { fig.classList.remove('drawing'); }, 1600); } }).catch(function (err) { box.innerHTML = '<p style="color:var(--faint);font-size:13px">图渲染失败:' + String(err && err.message || err) + '</p>'; }); }; var io = new IntersectionObserver(function (es) { es.forEach(function (e) { if (!e.isIntersecting) return; draw(e.target); io.unobserve(e.target); }); }, { rootMargin: '200px 0px' }); figs.forEach(function (f) { io.observe(f); }); } document.addEventListener('mermaid-ready', initDiagrams); if (window.__mermaid) initDiagrams(); /* ── 左右方向键翻章 ─────────────────────── */ addEventListener('keydown', function (e) { if (e.metaKey || e.ctrlKey || e.altKey) return; var tag = (e.target.tagName || '').toLowerCase(); if (tag === 'input' || tag === 'textarea') return; var sel = e.key === 'ArrowLeft' ? '.ch-nav .prev' : e.key === 'ArrowRight' ? '.ch-nav .next' : null; var a = sel && document.querySelector(sel); if (a) location.href = a.getAttribute('href'); }); })();docs/.nojekyll0 Be69de29bb2d1upstream ↗
docs/assets/book.css17 KB53166ed81218upstream ↗
/* 源码精读成书样式。全部变量集中在 :root,换主色只改 --accent。 */ :root { --accent: #3f4a5a; --bg: #fbfaf8; --paper: #fff; --ink: #1c1f24; --sub: #5b6270; --faint: #8b93a1; --line: #e7e4de; --code-bg: #f7f6f3; --code-ink: #2b3038; --mark: rgba(63, 74, 90, .1); --shadow: 0 1px 2px rgba(28, 31, 36, .04), 0 8px 28px rgba(28, 31, 36, .05); --serif: "Songti SC", "Source Han Serif SC", "Noto Serif CJK SC", Georgia, serif; --sans: -apple-system, BlinkMacSystemFont, "PingFang SC", "Noto Sans CJK SC", "Microsoft YaHei", system-ui, sans-serif; --mono: "SF Mono", ui-monospace, Menlo, Consolas, "Liberation Mono", monospace; --measure: 40rem; } body.dark { --bg: #14161a; --paper: #191c21; --ink: #e6e6e4; --sub: #a6adb9; --faint: #767e8c; --line: #2a2e35; --code-bg: #1e2127; --code-ink: #d7dae0; --mark: rgba(150, 172, 205, .16); --shadow: 0 1px 2px rgba(0, 0, 0, .3), 0 10px 30px rgba(0, 0, 0, .28); } * { box-sizing: border-box; } html { scroll-behavior: smooth; scroll-padding-top: 76px; } body { margin: 0; background: var(--bg); color: var(--ink); font-family: var(--sans); font-size: 17px; line-height: 1.95; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; } a { color: inherit; } /* ── 顶部阅读进度 ───────────────────────────── */ .progress { position: fixed; inset: 0 0 auto 0; height: 2px; z-index: 60; background: transparent; pointer-events: none; } .progress i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .12s linear; } /* ── 封面 ──────────────────────────────────── */ .is-cover { background: radial-gradient(1100px 620px at 50% -8%, var(--mark), transparent 62%), var(--bg); } .cover { max-width: 62rem; margin: 0 auto; padding: 0 24px 80px; } .cover-hero { min-height: 92vh; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 4px; } .cover-hero .kicker { margin: 0 0 14px; font-size: 13px; letter-spacing: .34em; text-indent: .34em; color: var(--faint); text-transform: uppercase; animation: rise .8s .05s both; } .cover-hero h1 { margin: 0; font-family: var(--serif); font-weight: 700; font-size: clamp(2.2rem, 6vw, 4rem); line-height: 1.28; letter-spacing: -.01em; max-width: 22ch; animation: rise .9s .12s both; } .cover-hero .sub { margin: 20px 0 0; max-width: 34rem; color: var(--sub); font-size: 1.02rem; line-height: 1.85; animation: rise .9s .2s both; } .cover-hero .by { margin: 26px 0 0; font-size: 14px; color: var(--faint); letter-spacing: .08em; animation: rise .9s .28s both; } .stats { display: flex; gap: 40px; margin: 40px 0 0; animation: rise .9s .36s both; } .stat { display: flex; flex-direction: column; align-items: center; } .stat b { font-family: var(--serif); font-size: 2rem; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.2; } .stat span { font-size: 12px; color: var(--faint); letter-spacing: .1em; } .cover-hero .anchor { margin: 34px 0 0; font-family: var(--mono); font-size: 12px; color: var(--faint); animation: rise .9s .44s both; } .src-repo { margin-top: 6px; font-family: var(--mono); font-size: 12px; color: var(--accent); text-decoration: none; border-bottom: 1px solid transparent; animation: rise .9s .48s both; } .src-repo:hover { border-bottom-color: currentColor; } .start { margin-top: 40px; padding: 13px 34px; border-radius: 999px; background: var(--accent); color: #fff; text-decoration: none; font-size: 15px; letter-spacing: .04em; box-shadow: var(--shadow); transition: transform .2s, box-shadow .2s; animation: rise .9s .56s both; } .start:hover { transform: translateY(-2px); box-shadow: 0 10px 30px rgba(28, 31, 36, .16); } .cover-toc { padding: 20px 0 0; } .cover-toc h2 { margin: 0 0 26px; font-family: var(--serif); font-size: 1.3rem; font-weight: 700; letter-spacing: .02em; text-align: center; } ol.toc { list-style: none; margin: 0; padding: 0; } ol.toc li { border-top: 1px solid var(--line); } ol.toc li:last-child { border-bottom: 1px solid var(--line); } ol.toc a { display: grid; grid-template-columns: 3.4rem 1fr; gap: 2px 18px; padding: 20px 14px; text-decoration: none; transition: background .18s, padding-left .18s; } ol.toc a:hover { background: var(--paper); padding-left: 22px; } ol.toc .n { grid-row: 1 / span 2; font-family: var(--serif); font-size: 1.5rem; color: var(--faint); font-variant-numeric: tabular-nums; line-height: 1.4; } ol.toc .t { font-size: 1.02rem; font-weight: 600; line-height: 1.6; } ol.toc .d { font-size: 14px; color: var(--sub); line-height: 1.75; } .colophon-link { display: inline-block; margin-top: 30px; font-size: 14px; color: var(--sub); text-decoration: none; border-bottom: 1px solid var(--line); } .colophon-link:hover { color: var(--accent); border-bottom-color: currentColor; } /* ── 顶栏 ──────────────────────────────────── */ .topbar { position: sticky; top: 0; z-index: 50; display: flex; align-items: center; gap: 16px; padding: 12px 24px; background: color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter: saturate(1.4) blur(10px); border-bottom: 1px solid var(--line); } .topbar .home { font-size: 14px; font-weight: 600; text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .topbar .pos { margin-left: auto; font-family: var(--mono); font-size: 12px; color: var(--faint); font-variant-numeric: tabular-nums; } .topbar .theme { width: 30px; height: 30px; border-radius: 8px; cursor: pointer; border: 1px solid var(--line); background: transparent; color: var(--sub); display: grid; place-items: center; } .topbar .theme::before { content: "◐"; font-size: 15px; } .topbar .theme:hover { border-color: var(--accent); color: var(--accent); } /* ── 正文骨架 ──────────────────────────────── */ .wrap { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, var(--measure)) minmax(0, 1fr); gap: 0 32px; max-width: 84rem; margin: 0 auto; padding: 0 24px; } .side { grid-column: 1; } .side nav { position: sticky; top: 84px; padding: 44px 0 40px; max-height: calc(100vh - 96px); overflow-y: auto; display: flex; flex-direction: column; gap: 2px; border-right: 1px solid var(--line); margin-right: 8px; } .side a { padding: 5px 14px 5px 12px; font-size: 13px; line-height: 1.6; color: var(--faint); text-decoration: none; border-left: 2px solid transparent; transition: color .16s, border-color .16s; } .side a.lv3 { padding-left: 26px; font-size: 12.5px; } .side a:hover { color: var(--ink); } .side a.on { color: var(--accent); border-left-color: var(--accent); font-weight: 600; } .chapter { grid-column: 2; padding: 44px 0 88px; min-width: 0; } .ch-num { margin: 0 0 10px; font-family: var(--mono); font-size: 12px; letter-spacing: .22em; color: var(--faint); } .chapter > h1 { margin: 0 0 20px; font-family: var(--serif); font-weight: 700; font-size: clamp(1.7rem, 3.6vw, 2.4rem); line-height: 1.36; letter-spacing: -.005em; } .ch-meta { display: flex; flex-direction: column; gap: 4px; margin: 0 0 52px; padding: 14px 18px; border-radius: 10px; background: var(--paper); border: 1px solid var(--line); font-family: var(--mono); font-size: 12px; line-height: 1.8; color: var(--sub); } /* ── 章节段落与标题 ────────────────────────── */ .chapter p { margin: 0 0 22px; } .chapter p + p { margin-top: -4px; } h2.sec { position: relative; margin: 72px 0 24px; padding-top: 26px; font-family: var(--serif); font-size: 1.42rem; font-weight: 700; line-height: 1.5; letter-spacing: .01em; border-top: 1px solid var(--line); } h2.sec .sec-mark { position: absolute; top: -1px; left: 0; width: 46px; height: 2px; background: var(--accent); } .chapter h3 { margin: 44px 0 16px; font-size: 1.08rem; font-weight: 700; line-height: 1.65; letter-spacing: .01em; } .chapter h4 { margin: 30px 0 12px; font-size: 1rem; font-weight: 600; } .chapter ul, .chapter ol { margin: 0 0 22px; padding-left: 1.4em; } .chapter li { margin: 0 0 9px; } .chapter li > ul, .chapter li > ol { margin: 9px 0 4px; } .chapter blockquote { margin: 0 0 24px; padding: 4px 0 4px 20px; border-left: 2px solid var(--accent); color: var(--sub); font-size: .97rem; } .chapter blockquote p:last-child { margin-bottom: 0; } .chapter hr { margin: 44px 0; border: 0; border-top: 1px solid var(--line); } .chapter strong { font-weight: 700; } .chapter em { font-style: normal; background: var(--mark); padding: 0 .2em; border-radius: 3px; } code { font-family: var(--mono); font-size: .875em; background: var(--code-bg); color: var(--code-ink); padding: .12em .38em; border-radius: 4px; word-break: break-word; } /* ── 表格 ──────────────────────────────────── */ .chapter table { width: 100%; margin: 0 0 26px; border-collapse: collapse; font-size: 14.5px; line-height: 1.75; background: var(--paper); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; display: table; } .chapter th, .chapter td { padding: 11px 14px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--line); } .chapter th { font-weight: 600; font-size: 13.5px; color: var(--sub); background: var(--code-bg); } .chapter tr:last-child td { border-bottom: 0; } .chapter td code { font-size: .84em; } /* ── 源码引用块 ────────────────────────────── */ figure.cite, figure.code { margin: 0 0 26px; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); overflow: hidden; box-shadow: var(--shadow); } .cite-head, .code-head { display: flex; align-items: center; gap: 12px; padding: 9px 14px; background: var(--code-bg); border-bottom: 1px solid var(--line); font-family: var(--mono); font-size: 11.5px; color: var(--sub); } .cite-path { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl; text-align: left; flex: 1 1 auto; min-width: 0; } .cite-lines { color: var(--faint); flex: 0 0 auto; } .cite-tools { margin-left: auto; display: flex; gap: 6px; flex: 0 0 auto; } .cite-btn { font: inherit; font-size: 11px; cursor: pointer; color: var(--sub); padding: 2px 9px; border-radius: 999px; border: 1px solid var(--line); background: var(--paper); transition: color .15s, border-color .15s; } .cite-btn:hover { color: var(--accent); border-color: var(--accent); } .cite-btn.on { color: #fff; background: var(--accent); border-color: var(--accent); } pre { margin: 0; padding: 14px 0; overflow-x: auto; font-family: var(--mono); font-size: 13px; line-height: 1.75; color: var(--code-ink); } pre code { background: none; padding: 0; font-size: inherit; } .cite-body .cl { display: flex; padding: 0 14px; } .cite-body .ln { flex: 0 0 3.4em; text-align: right; padding-right: 1.1em; color: var(--faint); user-select: none; font-variant-numeric: tabular-nums; } .cite-body .lt { white-space: pre; } .cite-body .cl.gap { color: var(--faint); font-style: italic; } .cite-body .cl.gap .lt { opacity: .7; } /* 逐段步进:未命中的段落压暗,命中的段落上底色 */ figure.cite.stepping .cl { opacity: .28; transition: opacity .25s, background .25s; } figure.cite.stepping .cl.hot { opacity: 1; background: var(--mark); } /* ── 图 ────────────────────────────────────── */ figure.diagram { margin: 0 0 28px; padding: 22px 18px; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); text-align: center; box-shadow: var(--shadow); overflow-x: auto; } figure.diagram .mermaid { font-family: var(--sans); } figure.diagram svg { max-width: 100%; height: auto; } figure.diagram.drawing svg .edgePath path, figure.diagram.drawing svg .flowchart-link, figure.diagram.drawing svg .messageLine0, figure.diagram.drawing svg .messageLine1 { stroke-dasharray: 1000; stroke-dashoffset: 1000; animation: draw 1.1s ease forwards; } figure.diagram.drawing svg .node, figure.diagram.drawing svg .actor, figure.diagram.drawing svg .label { animation: fade .7s .18s both; } /* ── 章末导航 ──────────────────────────────── */ .ch-nav { display: flex; gap: 16px; margin-top: 76px; padding-top: 26px; border-top: 1px solid var(--line); font-size: 14px; } .ch-nav a { flex: 1 1 0; min-width: 0; padding: 16px 18px; border-radius: 10px; background: var(--paper); border: 1px solid var(--line); text-decoration: none; color: var(--sub); line-height: 1.6; transition: border-color .18s, color .18s, transform .18s; } .ch-nav a:hover { color: var(--ink); border-color: var(--accent); transform: translateY(-1px); } .ch-nav .next { text-align: right; } /* ── 封底 ──────────────────────────────────── */ .colophon { max-width: 46rem; margin: 0 auto; padding: 56px 24px 90px; } .colophon h1 { margin: 0 0 18px; font-family: var(--serif); font-size: 2rem; font-weight: 700; } .colophon .lead { color: var(--sub); margin: 0 0 38px; } .colophon h2 { margin: 48px 0 14px; font-family: var(--serif); font-size: 1.2rem; font-weight: 700; } .colophon p { margin: 0 0 18px; } .stat-table { width: 100%; border-collapse: collapse; font-size: 14px; background: var(--paper); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; } .stat-table th, .stat-table td { padding: 9px 12px; border-bottom: 1px solid var(--line); text-align: left; } .stat-table th { font-size: 12.5px; color: var(--sub); background: var(--code-bg); font-weight: 600; } .stat-table td:nth-child(3), .stat-table td:nth-child(4), .stat-table td:nth-child(5), .stat-table th:nth-child(3), .stat-table th:nth-child(4), .stat-table th:nth-child(5) { text-align: right; font-variant-numeric: tabular-nums; } .stat-table tfoot td { font-weight: 700; background: var(--code-bg); } .anchor-list, .how-list { padding-left: 1.3em; } .anchor-list li, .how-list li { margin-bottom: 8px; } .method-link { display: inline-block; margin-top: 12px; padding: 11px 22px; border-radius: 999px; background: var(--accent); color: #fff; text-decoration: none; font-size: 14px; transition: transform .18s; } .method-link:hover { transform: translateY(-1px); } /* ── 页脚:署名固定出现在每一页 ────────────── */ .book-foot { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 6px 14px; padding: 30px 24px 42px; border-top: 1px solid var(--line); font-size: 12.5px; color: var(--faint); text-align: center; } .book-foot a { color: var(--sub); text-decoration: none; border-bottom: 1px solid var(--line); } .book-foot a:hover { color: var(--accent); border-bottom-color: currentColor; } .book-foot .foot-repo { font-family: var(--mono); font-size: 12px; } /* ── 入场动效 ──────────────────────────────── */ .reveal { opacity: 0; transform: translateY(14px); } .reveal.in { opacity: 1; transform: none; transition: opacity .6s ease, transform .6s ease; } @keyframes rise { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: none; } } @keyframes fade { from { opacity: 0; } to { opacity: 1; } } @keyframes draw { to { stroke-dashoffset: 0; } } @media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } *, *::before, *::after { animation: none !important; transition: none !important; } .reveal { opacity: 1; transform: none; } } /* ── 窄屏 ──────────────────────────────────── */ @media (max-width: 1080px) { .wrap { grid-template-columns: minmax(0, 1fr); } .side { display: none; } .chapter { grid-column: 1; max-width: var(--measure); margin: 0 auto; } } @media (max-width: 720px) { body { font-size: 16px; line-height: 1.9; } .cover { padding: 0 18px 60px; } .stats { gap: 26px; } .stat b { font-size: 1.6rem; } ol.toc a { grid-template-columns: 2.6rem 1fr; gap: 2px 12px; padding: 16px 6px; } .chapter { padding: 32px 0 64px; } .wrap { padding: 0 18px; } pre { font-size: 12px; } .cite-body .ln { flex-basis: 2.8em; } .ch-nav { flex-direction: column; } .ch-nav .next { text-align: left; } } /* ── 打印 ──────────────────────────────────── */ @media print { .topbar, .side, .progress, .ch-nav, .start { display: none; } body { background: #fff; font-size: 11pt; } .wrap { display: block; max-width: none; padding: 0; } figure.cite, figure.code, figure.diagram, .chapter table { break-inside: avoid; } h2.sec { break-after: avoid; } .chapter { padding: 0; } }docs/assets/book.js7.5 KB8df34226dfa5upstream ↗
/* 成书交互:阅读进度、滚动渐入、目录跟随、引用块逐段步进、图表绘制动画。 全部原生实现,除 mermaid 外无外部依赖。 */ (function () { 'use strict'; var reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; /* ── 深浅色,记住选择 ───────────────────── */ var KEY = 'book-theme'; var saved = localStorage.getItem(KEY); if (saved === 'dark' || (!saved && matchMedia('(prefers-color-scheme: dark)').matches)) { document.body.classList.add('dark'); } var themeBtn = document.querySelector('.theme'); if (themeBtn) { themeBtn.addEventListener('click', function () { var dark = document.body.classList.toggle('dark'); localStorage.setItem(KEY, dark ? 'dark' : 'light'); }); } /* ── 阅读进度 ───────────────────────────── */ var bar = document.querySelector('.progress i'); if (bar) { var tick = function () { var h = document.documentElement.scrollHeight - innerHeight; bar.style.width = (h > 0 ? Math.min(1, scrollY / h) * 100 : 0) + '%'; }; addEventListener('scroll', tick, { passive: true }); addEventListener('resize', tick); tick(); } /* ── 正文分块渐入 ───────────────────────── */ var main = document.querySelector('.chapter, .colophon'); if (main && !reduce) { var targets = main.querySelectorAll( 'p, h2, h3, h4, ul, ol, figure, table, blockquote, .ch-meta, .ch-nav'); var io = new IntersectionObserver(function (entries) { entries.forEach(function (e) { if (!e.isIntersecting) return; e.target.classList.add('in'); io.unobserve(e.target); }); }, { rootMargin: '0px 0px -8% 0px', threshold: 0.02 }); targets.forEach(function (el) { el.classList.add('reveal'); io.observe(el); }); } document.querySelectorAll('.cover .reveal').forEach(function (el) { if (reduce) { el.classList.add('in'); return; } new IntersectionObserver(function (es, ob) { es.forEach(function (e) { if (!e.isIntersecting) return; e.target.classList.add('in'); ob.disconnect(); }); }, { threshold: 0.05 }).observe(el); }); /* ── 封面数字滚动 ───────────────────────── */ document.querySelectorAll('[data-count]').forEach(function (el) { var end = parseFloat(el.dataset.count) || 0; var dec = (el.dataset.count.split('.')[1] || '').length; if (reduce) { el.textContent = end.toFixed(dec); return; } var t0 = null, dur = 900; var run = function (t) { if (t0 === null) t0 = t; var k = Math.min(1, (t - t0) / dur); el.textContent = (end * (1 - Math.pow(1 - k, 3))).toFixed(dec); if (k < 1) requestAnimationFrame(run); }; requestAnimationFrame(run); }); /* ── 侧栏目录跟随 ───────────────────────── */ var links = [].slice.call(document.querySelectorAll('.side a')); if (links.length) { var heads = links.map(function (a) { return document.getElementById(decodeURIComponent(a.getAttribute('href').slice(1))); }); var sync = function () { var best = 0; heads.forEach(function (h, i) { if (h && h.getBoundingClientRect().top <= 120) best = i; }); links.forEach(function (a, i) { a.classList.toggle('on', i === best); }); }; addEventListener('scroll', sync, { passive: true }); sync(); } /* ── 复制 ───────────────────────────────── */ document.querySelectorAll('.cite-btn.copy').forEach(function (btn) { btn.addEventListener('click', function () { var fig = btn.closest('figure'); var code = fig.querySelector('code'); var text = fig.classList.contains('cite') ? [].map.call(code.querySelectorAll('.lt'), function (s) { return s.textContent; }).join('\n') : code.textContent; navigator.clipboard.writeText(text).then(function () { var old = btn.textContent; btn.textContent = '已复制'; setTimeout(function () { btn.textContent = old; }, 1400); }); }); }); /* ── 引用块逐段步进 ───────────────────────── 带省略标记的引用块中间是断开的。按段依次高亮,让读者看清 哪几行在源文件里真的连在一起,省略处不会被当成连续代码。 */ document.querySelectorAll('figure.cite[data-steppable]').forEach(function (fig) { var btn = fig.querySelector('.cite-btn.step'); if (!btn) return; var lines = [].slice.call(fig.querySelectorAll('.cl')); var segs = []; lines.forEach(function (l) { var s = l.dataset.seg; if (segs.indexOf(s) < 0 && !l.classList.contains('gap')) segs.push(s); }); var at = -1, timer = null; var paint = function () { lines.forEach(function (l) { l.classList.toggle('hot', at >= 0 && l.dataset.seg === segs[at]); }); }; var stop = function () { clearInterval(timer); timer = null; at = -1; fig.classList.remove('stepping'); btn.classList.remove('on'); btn.textContent = '逐段'; lines.forEach(function (l) { l.classList.remove('hot'); }); }; btn.addEventListener('click', function () { if (timer) { stop(); return; } fig.classList.add('stepping'); btn.classList.add('on'); at = 0; paint(); btn.textContent = '第 1 / ' + segs.length + ' 段'; timer = setInterval(function () { at += 1; if (at >= segs.length) { stop(); return; } paint(); btn.textContent = '第 ' + (at + 1) + ' / ' + segs.length + ' 段'; }, 1500); }); }); /* ── 图表:进视野再渲染,配绘制动画 ─────── */ function initDiagrams() { var mermaid = window.__mermaid; if (!mermaid) return; var figs = [].slice.call(document.querySelectorAll('figure.diagram')); if (!figs.length) return; var draw = function (fig) { var box = fig.querySelector('.mermaid'); if (!box || box.dataset.done) return; box.dataset.done = '1'; mermaid.run({ nodes: [box] }).then(function () { if (!reduce) { fig.classList.add('drawing'); setTimeout(function () { fig.classList.remove('drawing'); }, 1600); } }).catch(function (err) { box.innerHTML = '<p style="color:var(--faint);font-size:13px">图渲染失败:' + String(err && err.message || err) + '</p>'; }); }; var io = new IntersectionObserver(function (es) { es.forEach(function (e) { if (!e.isIntersecting) return; draw(e.target); io.unobserve(e.target); }); }, { rootMargin: '200px 0px' }); figs.forEach(function (f) { io.observe(f); }); } document.addEventListener('mermaid-ready', initDiagrams); if (window.__mermaid) initDiagrams(); /* ── 左右方向键翻章 ─────────────────────── */ addEventListener('keydown', function (e) { if (e.metaKey || e.ctrlKey || e.altKey) return; var tag = (e.target.tagName || '').toLowerCase(); if (tag === 'input' || tag === 'textarea') return; var sel = e.key === 'ArrowLeft' ? '.ch-nav .prev' : e.key === 'ArrowRight' ? '.ch-nav .next' : null; var a = sel && document.querySelector(sel); if (a) location.href = a.getAttribute('href'); }); })();docs/ch-01.html120 KB1c46caeedc20upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
docs/ch-02.html171 KB1f1a23512c77upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
docs/ch-03.html127 KB5e8bbabdfa91upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
docs/colophon.html3.4 KBad520d21497cupstream ↗
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>关于这本书 · 一台 Agent 运行时的安全观</title> <meta name="description" content="当它敢在你的机器上跑命令、连网络、带着你的凭据,它凭什么值得被信任。这里是三章样张,完整版三十二章精读 openai/codex,每一处论断都能回溯到源码的具体某一行。"> <meta name="author" content="洛小山"> <style>:root{--accent:#3f4a5a}</style> <link rel="stylesheet" href="assets/book.css"> </head> <body class="is-colophon"> <div class="progress"><i></i></div> <header class="topbar"> <a class="home" href="index.html">一台 Agent 运行时的安全观</a> <span class="pos">封底</span> <button class="theme" type="button" aria-label="切换深浅色"></button> </header> <main class="colophon"> <h1>关于这本书</h1> <p class="lead">这本书里的每一处技术论断,都能回溯到源码的具体某一行。 下面这张表是成书时的实际数据,口径写在表头里。</p> <table class="stat-table"> <thead><tr><th>章</th><th>标题</th><th>带行号引用</th><th>图</th><th>正文汉字</th></tr></thead> <tbody><tr><td>01</td><td>crate 治理,一条不许往核心加代码的禁令</td><td>50</td><td>3</td><td>7408</td></tr><tr><td>02</td><td>三层 Turn Loop,任务壳、轮次、采样</td><td>39</td><td>3</td><td>5543</td></tr><tr><td>03</td><td>SSE 驱动的工具闭环,流内建 future,流后统一 drain</td><td>35</td><td>3</td><td>5987</td></tr></tbody> <tfoot><tr><td colspan="2">合计</td><td>124</td> <td>9</td><td>18938</td></tr></tfoot> </table> <h2>版本锚点</h2> <p>正文里的所有行号对应下面这个版本。上游仓库一直在改,隔一段时间再照着查,行号可能已经漂了。</p> <ul class="anchor-list"> <li>仓库:https://github.com/openai/codex</li> <li>commit:<code>4f39251a01</code></li> <li>tag:<code>course-anchor-20260822</code></li> <li>核对日期:2026-08-22</li> </ul> <h2>怎么读</h2> <ul class="how-list"> <li>代码块左侧是源文件里的真实行号,可以直接跳回原仓库对照</li> <li>带 <b>逐段</b> 按钮的引用块中间有省略,点一下会按连续段落依次高亮,省略处不会被当成连续代码</li> <li>每章末尾的思考题里至少有一道要动手改代码验证,那一道最值钱</li> </ul> <h2>这本书是怎么做出来的</h2> <p>用一套公开的方法论:先锁版本锚点,再写带源码锚点的大纲,然后按八段结构逐章精读, 最后编成这本书。全程由脚本把每一个代码块拿回源文件逐字节比对,行号错了自动校正, 静默删行会被判定为编造并退回重写。</p> <a class="method-link" href="https://github.com/itshen/source-reading-methodology" target="_blank" rel="noopener"> 方法论与模板已开源,可直接取用</a> </main> <footer class="book-foot"><span>来自 <a href="https://github.com/itshen/source-reading-methodology" target="_blank" rel="noopener">洛小山·小山学堂方法论</a></span><a class="foot-repo" href="https://github.com/itshen/source-reading-methodology" target="_blank" rel="noopener">github.com/itshen/source-reading-methodology</a></footer> <script src="assets/book.js"></script> </body> </html>docs/index.html3.0 KBad7b845449e6upstream ↗
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>一台 Agent 运行时的安全观</title> <meta name="description" content="当它敢在你的机器上跑命令、连网络、带着你的凭据,它凭什么值得被信任。这里是三章样张,完整版三十二章精读 openai/codex,每一处论断都能回溯到源码的具体某一行。"> <meta name="author" content="洛小山"> <style>:root{--accent:#3f4a5a}</style> <link rel="stylesheet" href="assets/book.css"> </head> <body class="is-cover"> <div class="progress"><i></i></div> <main class="cover"> <section class="cover-hero"> <p class="kicker">源码精读 · 三章样张</p> <h1>一台 Agent 运行时的安全观</h1> <p class="sub">当它敢在你的机器上跑命令、连网络、带着你的凭据,它凭什么值得被信任。这里是三章样张,完整版三十二章精读 openai/codex,每一处论断都能回溯到源码的具体某一行。</p> <p class="by">洛小山</p> <div class="stats"><div class="stat"><b data-count="3">0</b><span>章</span></div><div class="stat"><b data-count="124">0</b><span>处源码引用</span></div><div class="stat"><b data-count="1.9">0</b><span>万字</span></div></div> <p class="anchor">commit 4f39251a01 · tag course-anchor-20260822 · 2026-08-22</p> <a class="src-repo" href="https://github.com/openai/codex" target="_blank" rel="noopener">github.com/openai/codex</a> <a class="start" href="ch-01.html">开始阅读</a> </section> <section class="cover-toc reveal"> <h2>目录</h2> <ol class="toc"><li><a href="ch-01.html"><span class="n">01</span><span class="t">crate 治理,一条不许往核心加代码的禁令</span><span class="d">你要给这台 agent 加一个小功能:每轮对话开头把当前 git 分支名写进模型上下文。</span></a></li><li><a href="ch-02.html"><span class="n">02</span><span class="t">三层 Turn Loop,任务壳、轮次、采样</span><span class="d">你让 coding agent 改一个函数。屏幕上这是一轮对话:你说了一句,它忙了一阵,最后回「改完了」。</span></a></li><li><a href="ch-03.html"><span class="n">03</span><span class="t">SSE 驱动的工具闭环,流内建 future,流后统一 drain</span><span class="d">你让 Codex 读三个文件再写一份摘要。屏幕上模型还在打字:「我先看 src/main.rs…」下一秒,终端里已经响起了第一次读文件的声音。</span></a></li></ol> <a class="colophon-link" href="colophon.html">关于这本书</a> </section> </main> <footer class="book-foot"><span>来自 <a href="https://github.com/itshen/source-reading-methodology" target="_blank" rel="noopener">洛小山·小山学堂方法论</a></span><a class="foot-repo" href="https://github.com/itshen/source-reading-methodology" target="_blank" rel="noopener">github.com/itshen/source-reading-methodology</a></footer> <script src="assets/book.js"></script> </body> </html>example/stage2-outline-entry.md5.1 KB25a3dba909f1upstream ↗
# 阶段二的成品:大纲长什么样 > 这是一份真实大纲的两处节选,源项目是 openai/codex(Rust 单仓,90 多个 crate)。 > 对照 `../templates/00-outline-template.md` 看,能明白每个占位符该填到什么程度。 大纲要先立住定位,再逐章写锚点。下面第一段是定位,第二段是第 1 章的锚点条目。 --- ## 一、定位部分 注意它没有直接列章节,而是先回答「这门课解答哪一个问题」,并把答案收束成一句话。这句话决定了后面哪些内容进、哪些不进。 ## 课程定位 DSH 那门课回答的是「Agent 运行时该长什么样」。这门课回答的是它的下一个问题: > **当这台运行时真的敢在你的机器上跑命令、连网络、改文件、还带着你的凭据,它凭什么值得被信任?** Codex 是目前公开源码里,把「信任」这件事做得最重的 agent。90 多个 crate 里有超过十个只服务于一件事:确定这一条命令能不能跑、以什么身份跑、能碰哪些路径、能连哪些域名、凭据要不要给它看、出事了谁来兜。DSH 用一条运行时不变量(`Model-visible ⟺ logged`)撑起整个系统的可审计性,Codex 用类型系统、策略 DSL、三套操作系统沙箱和一个专门的审查模型撑起整个系统的可控性。 两条路各有代价,这门课把代价摆出来。 ### 与 DSH 专题的关系 不重复讲 DSH 已经讲透的通用机制(事件溯源、插件树、Inbox 三语义、Token 计量投影)。凡是两边都有的机制,本课只讲 Codex 的差异做法并链回 DSH 对应课页;凡是 DSH 没有的(沙箱三平台、Guardian、网络与凭据代理、竞品迁移、Realtime),本课展开讲。 课程最终收束到终章的一句话对照:**DSH 让一切可回放,Codex 让一切可拒绝。** ### 读者带走什么 每章结尾的「可迁移结论」必须落到读者自己的项目上。全课累计交付: - 一套上下文注入的类型化治理方案(能直接抄成自己项目的 code review 规则) - 一套命令审批策略的写法(策略文件自带测试用例这个技巧可独立使用) - 一份「你的 agent 该不该做沙箱、做到哪一层」的决策树 - 一个 LLM 友好的文件编辑协议规范(apply-patch 格式可直接复用) - 一份 Code Mode 上不上的成本清单 --- ## 二、逐章锚点部分 一章一条,五个固定字段:核心问题、源码锚点、对比锚点、边界条件示例、互动演示。 行号后面标 ✓ 表示当时实读核实过。写作时即使看到 ✓ 也要重新读一遍,因为真正要引用的可能是相邻的行。 ### 第 1 章:90 个 crate 与一条「不许往核心加代码」的禁令 **核心问题**:一个 agent 运行时长到 90 个 crate 时,靠什么阻止核心继续膨胀? **Codex 锚点**: - 全仓 crate 清单与规模分布(`tui` 27 万行、`core` 20 万行、`app-server` 5 万行、`core-plugins` 4.2 万行,其余 80 多个各自几千行) - ✓ `AGENTS.md:72-83`「The `codex-core` crate」一节全文精读:**resist adding code to codex-core**,新概念优先找别的 crate 或新建 crate,评审时要主动 push back - ✓ `AGENTS.md:49-61` 模块体量治理:目标 500 行、超过 800 行必须开新模块,并点名了五个高频冲突文件(`tui/src/app.rs`、`chat_composer.rs`、`footer.rs`、`chatwidget.rs`、`bottom_pane/mod.rs`) - ✓ `AGENTS.md:125-131` 单次改动不超过 800 行,复杂逻辑不超过 500 行,超了要拆成可评审的阶段 - 双构建系统:Cargo + Bazel 并行,`MODULE.bazel.lock` 154 万行,`AGENTS.md:37-43` 说明改依赖必须同步刷新 lock、`include_str!` 必须同步改 `BUILD.bazel` **对比锚点**: - DSH:56 包插件树 + Cordis 时空可组合性(`dsh-1`)——DSH 用架构强制解耦,Codex 用评审规则强制解耦,两种做法的成本与失效模式 - Grok Build:60+ crate 的 Rust 组织方式,同语言对照 **边界条件示例**:`core` 明明已经 20 万行,禁令是什么时候立的、之前的债怎么还?(从 git log 找禁令引入时间与随后的拆分 commit。)Bazel 与 Cargo 判定不一致时以哪个为准? **互动演示(Demo 1·模拟器)**:crate 依赖体检台——把 90 个 crate 画成力导向图,节点大小是代码行数,读者点「假装往 core 加一个功能」,动画展示依赖边如何蔓延、哪些下游被迫重编译;再点「按禁令新建 crate」,对比蔓延范围。侧栏实时显示两种做法的增量编译时间估算。 --- ## 从这份条目里能看出的三件事 **锚点要具体到行。** `AGENTS.md:72-83` 这种写法让写作 Agent 不用自己找料,直接去核实。锚点越具体,后面并行写作的一致性越高。 **对比对象在大纲阶段就定死。** 不要留到写作时自由发挥,否则三十章会出现十章都在跟同一个项目对比同一个点。 **演示方向在大纲阶段就分配。** 这里写的是「crate 依赖体检台」,别的章各有各的方向。不提前分配,多个写作 Agent 会做出雷同的演示。example/stage4-book-colophon.png134 KB3aec5b02e9cdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
example/stage4-book-cover.png128 KB1da8b7476f89upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
example/stage4-book-stepping.png140 KBeba70ac74c1dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
example/stage4-page-demo.png220 KB54a3de498a65upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
LICENSE1.1 KBa88a96447814upstream ↗
MIT License Copyright (c) 2026 米羊科技(上海)有限公司 (Miyang Tech (Shanghai) Co., Ltd.) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.METHODOLOGY.md21 KB8ac60274454dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
PITFALLS.md10 KBd5732c90ab64upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
sample/book.config.json607 B8b95f91dbc19upstream ↗
{ "title": "一台 Agent 运行时的安全观", "subtitle": "当它敢在你的机器上跑命令、连网络、带着你的凭据,它凭什么值得被信任。这里是三章样张,完整版三十二章精读 openai/codex,每一处论断都能回溯到源码的具体某一行。", "kicker": "源码精读 · 三章样张", "author": "洛小山", "repo": "https://github.com/openai/codex", "anchor": { "commit": "4f39251a01", "tag": "course-anchor-20260822", "date": "2026-08-22" }, "accent": "#3f4a5a", "lang": "zh-CN", "chapters": "chapters", "out": "../docs" }sample/chapters/01-crate-governance.md59 KB338ef229df1eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
sample/chapters/02-turn-loop.md70 KBcdcfa4df1252upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
sample/chapters/03-sse-tool-loop.md58 KBa42cc5ee4d96upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
templates/00-outline-template.md3.0 KB1218c19842c5upstream ↗
# <一句话立意>:<PROJECT> 源码精读课程大纲 > 主教材:<owner>/<repo>(<语言>,<规模,如 90+ crate / 12 万行 TS>) > 版本锚点:commit `<HASH>`(<DATE>),tag `<TAG>`,本地路径 `<PATH>` > 对比语料:<项目 A>(<语言>)/ <项目 B>(<语言>)/ <项目 C> > 性质:研究型书稿 + 互动课页 > 状态:大纲 v1,共 N 章 + M 附录 --- ## 课程定位 ### 这门课回答哪一个问题 <把整门课收束到一句话。这句话决定哪些内容进、哪些不进。没有它,大纲会退化成源码目录的中文翻译。> 参考两个真实例子: - DeepSeek Harness:Agent 运行时该长什么样,收束到一条运行时不变量 `Model-visible ⟺ logged` - OpenAI Codex:当它敢在你机器上跑命令、连网络、带着你的凭据,它凭什么值得被信任,收束到「DSH 让一切可回放,Codex 让一切可拒绝」 ### 与姊妹课的关系 <如果是系列第二门以后:说明不重复讲什么、只讲差异做法并链回哪里、哪些是本课独有因此展开讲。> <章数与主题分组尽量与前一门对齐,便于逐章互链。> ### 读者带走什么 全课累计交付的可迁移物,每条都要具体到能直接用: - <一套…方案,能直接抄成自己项目的…> - <一份…决策树> - <一个…协议规范,可直接复用> - <一份…成本清单> --- ## 源码语料库 | 用途 | 路径 | 版本锚点 | |---|---|---| | 主教材 | `<PATH>` | `<HASH>` | | 对比语料① | `<PATH>` | `<HASH>` | | 对比语料② | `<PATH>` | `<HASH>` | | 检索脚本 | `<PATH>/search.sh` | — | ### 「为什么」的一手材料清单 按优先级列出本项目实际有哪些,并注明哪些是指向外链的空壳、需要跳过: 1. 评审红线:`<AGENTS.md 等>`(<体积>) 2. crate/模块 README:`<列出>` 3. 模块头注释:`<列出写得完整的几个>` 4. 测试文件:`<命名规律>` 5. 官方博客与文档:`<本地归档路径>` --- ## 章节大纲 <每章按下面这个结构写。行号后标 ✓ 表示已实读核实;未标的一律是候选,写作时必须自己定位。> <注意:✓ 的含义是「曾经核实过」,不是「现在还对」。> ### 第 N 章:<标题> **核心问题:** <这一章要回答的那一个问题> **源码入口:** - `<相对路径>` 第 <A> 至 <B> 行 ✓(<这段是什么>) - `<相对路径>`(候选,<要找什么>) **要分析的设计决策:** - <决策一> - <决策二> - <不这样做会出什么事> **规范性材料:** `<AGENTS.md 第 N 行 / README 某节 / 模块头注释>` **横向对比对象:** <对比语料某文件>,对比点是 <同一个问题的两种答案> **演示形态:** 模拟器 / 决策沙盘 / 格式实验台(三选一) **互链目标:** <姊妹课某页>,或「无直接对照页」 --- ## 附录 - 附录 A:<如全部提示词原文索引> - 附录 B:<如版本差异记录> --- ## 大纲维护记录 | 日期 | 变更 | 原因 | |---|---|---| | <DATE> | v1 建立 | — |templates/01-chapter-spec-template.md14 KB1ba0c57cbf91upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
templates/02-page-spec-template.md6.7 KBfcc9eae50a01upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
templates/style_scan.py3.2 KBca39e5fb41edupstream ↗
#!/usr/bin/env python3 """文风禁忌扫描:把硬性句式禁忌写成正则,交付前自动过一遍。 用法: python3 style_scan.py <文件或目录> [...] python3 style_scan.py ../METHODOLOGY.md ../PITFALLS.md 禁忌清单对应 01-chapter-spec-template.md 第 4 节。换项目时按需增删 BANS, 新增条目的唯一门槛是能写成正则;判断不了的写进「表达偏好」交给人评审。 只扫面向读者的正文(章节书稿、课页)。大纲和写作规范是内部工作文档, 不在约束范围内,扫它们会得到一堆无需处理的命中。 扫描前会剥掉三类内容,否则会误报: 代码块 源码里本来就有这些字符 行内代码 同上 「」直接引用 禁忌清单自己要引用被禁的写法 退出码 0 表示干净,1 表示有命中。 """ import re import sys from pathlib import Path BANS = [ ("全省略号", r"……", "省略号只用一半 …"), ("破折号", r"——", "改成逗号、句号或拆句"), ("不是而是", r"不是[^,。;\n]{1,14}而是", "改成正向陈述"), ("而不是收尾", r"而不是[^,。;\n]{0,14}[。\n]", "改成正向陈述"), ("同义绕过", r"而非[^,。;\n]{0,14}[。\n]", "换词绕不过去,禁的是靠否定制造对比"), ("评价式转述", r"(非常巧妙|很简单|非常有道理|十分精妙|相当优雅)", "平铺转述,不给评价"), ("情绪词", r"(震撼|细思极恐|刺穿|愣住|炸裂)", "描述具体感受"), ("解读前置", r"(这背后其实|这背后有一个)", "直接说判断本身"), ("催感悟", r"你品品", "删掉"), ("自我感悟", r"(我一直觉得|我想到一个词)", "删掉"), ("绝对路径", r"/(Users|home)/[a-zA-Z]", "路径一律相对仓库根"), ("过程性语言", r"(大纲写|大纲说|和大纲不符|按规范要求|本次任务|我负责的这一章)", "读者没见过大纲和规范"), ] def strip_noise(text: str) -> str: text = re.sub(r"```.*?```", "", text, flags=re.S) text = re.sub(r"`[^`\n]*`", "", text) return re.sub(r"「[^」\n]*」", "", text) def scan(path: Path) -> int: body = strip_noise(path.read_text(encoding="utf-8")) hits = 0 for name, pattern, fix in BANS: for m in re.finditer(pattern, body): if hits == 0: print(f"\n{path}") hits += 1 around = body[max(0, m.start() - 30):m.end() + 26].replace("\n", " ") print(f" [{name}] …{around}…") print(f" 改法:{fix}") return hits def collect(args: list[str]) -> list[Path]: files: list[Path] = [] for a in args: p = Path(a) if p.is_dir(): files.extend(sorted(p.rglob("*.md"))) elif p.is_file(): files.append(p) else: print(f"路径不存在:{p}") raise SystemExit(2) return files def main() -> int: if len(sys.argv) < 2: print(__doc__) return 2 files = collect(sys.argv[1:]) total = sum(scan(f) for f in files) print(f"\n共扫 {len(files)} 个文件,命中 {total} 处") return 1 if total else 0 if __name__ == "__main__": sys.exit(main())
Plain-text copy, no login: /skill-bundles/itshen-source-reading-methodology.md