<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="zh-Hans"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://maijun-sec.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://maijun-sec.github.io/" rel="alternate" type="text/html" hreflang="zh-Hans" /><updated>2026-12-03T00:36:34+08:00</updated><id>https://maijun-sec.github.io/feed.xml</id><title type="html">maijun blog</title><subtitle>程序分析、AI Agent 与软件供应链安全方向的工程笔记：不止给结论，也给可复现的做法与代价。
</subtitle><author><name>maijun</name></author><entry><title type="html">Dependency-Track v5：它是什么、能做什么，升级前要知道什么</title><link href="https://maijun-sec.github.io/2026/12/03/dependency-track-v5-overview/" rel="alternate" type="text/html" title="Dependency-Track v5：它是什么、能做什么，升级前要知道什么" /><published>2026-12-03T00:18:00+08:00</published><updated>2026-12-03T00:18:00+08:00</updated><id>https://maijun-sec.github.io/2026/12/03/dependency-track-v5-overview</id><content type="html" xml:base="https://maijun-sec.github.io/2026/12/03/dependency-track-v5-overview/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：Dependency-Track 是 OWASP 基金会下的开源软件成分分析平台。它解决的是一个很具体的运维问题：<strong>你的软件里有哪些第三方组件、这些组件哪些有已知漏洞、哪些是误报、哪些可以放行。</strong></p>

  <p>这篇只讲两件事：<strong>它是什么</strong>（归属、许可、数据模型、核心功能）和 <strong>v5 相对 v4 变了什么</strong>（部署形态、存储、通知格式、API，以及几个新能力）。v5 的关键技术实现——持久化执行引擎、CEL 策略引擎、事务性通知外发、PostgreSQL 里的时序指标——不在本文展开，会另做一个系列逐个拆。</p>

  <p>需要提前知道的一件事：<strong>从 v4 升到 v5 不是点一下版本号的事</strong>，官方发布说明里写的是「需要手工操作」。具体是哪几步，本文第四节列出来了。</p>
</blockquote>

<!--more-->

<h2 id="一它是什么">一、它是什么</h2>

<p>Dependency-Track 的自我描述是：<strong>一个智能化的成分分析平台，帮助组织识别并降低软件供应链中的风险。</strong></p>

<p>几个基本信息：</p>

<table>
  <thead>
    <tr>
      <th>项目</th>
      <th>值</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>归属</td>
      <td>OWASP 基金会</td>
    </tr>
    <tr>
      <td>仓库</td>
      <td><code class="language-plaintext highlighter-rouge">DependencyTrack/dependency-track</code></td>
    </tr>
    <tr>
      <td>许可</td>
      <td>Apache License 2.0</td>
    </tr>
    <tr>
      <td>主要语言</td>
      <td>Java</td>
    </tr>
    <tr>
      <td>官网</td>
      <td><a href="https://dependencytrack.org/">https://dependencytrack.org/</a></td>
    </tr>
    <tr>
      <td>仓库创建时间</td>
      <td>2013 年 7 月</td>
    </tr>
    <tr>
      <td>文档</td>
      <td><code class="language-plaintext highlighter-rouge">dependencytrack.github.io/docs</code></td>
    </tr>
  </tbody>
</table>

<p>它的工作方式是<strong>服务端</strong>的，这一点和很多「扫描器」不同：</p>

<ul>
  <li>扫描器是拉取式的——你在 CI 里跑一次，它扫一次，出一次报告。</li>
  <li>Dependency-Track 是常驻式的——它有数据库，有自己的 Web 界面和 REST API，持续维护着「有哪些项目、每个项目有哪些成分、哪些成分有漏洞」这份状态。</li>
</ul>

<p>这个差别决定了它的用法：<strong>扫描器适合在流水线里当门禁，Dependency-Track 更像一个组织级的成分台账</strong>——它的价值随时间积累，而不是随单次扫描。</p>

<p>它接什么格式？<strong>BOM</strong>。上游把 CycloneDX 或 SPDX 的清单交给它，它负责展开成分、比对漏洞、跑策略、发通知。</p>

<p>它<strong>不</strong>做什么？<strong>它不生成 BOM。</strong> BOM 的生产是上游构建工具的事（这和「SBOM 由构建过程产出，而不是由扫描器事后逆向推导」是同一个道理）。Dependency-Track 是 BOM 的消费者。</p>

<h2 id="二基本信息版本线与部署形态">二、基本信息：版本线与部署形态</h2>

<h3 id="21-版本线">2.1 版本线</h3>

<p>当前有两条版本线并行维护：</p>

<ul>
  <li><strong>4.14.x</strong> —— 上一代大版本的维护分支，官方在 2026 年 11 月 18 日还发布了 4.14.7。</li>
  <li><strong>5.x</strong> —— 当前大版本。5.0.0 于 2026 年 6 月 7 日正式发布（此前有 RC 版本）；到 2026 年 11 月 18 日已经到 5.2.2。</li>
</ul>

<p>同日发两个版本，是维护分支的常规节奏：4.14.x 收 bug 修复，5.x 往前走。</p>

<h3 id="22-部署形态">2.2 部署形态</h3>

<p>v5 的分发形态是<strong>只有容器镜像</strong>。发布产物是 API 服务器的发行包（<code class="language-plaintext highlighter-rouge">dependency-track-apiserver-dist.tar.gz</code>）与官方镜像。</p>

<p>对照 v4：v4 有独立的 API 服务器镜像、独立的前端镜像、两者合并的 bundled 镜像，以及一个可执行的 WAR。<strong>v5 取消了这个 WAR 和 bundled 镜像</strong>。</p>

<h3 id="23-存储">2.3 存储</h3>

<p>v5 只支持 <strong>PostgreSQL（要求 14 及以上）</strong>，H2、MySQL、Microsoft SQL Server 都不再支持。</p>

<p>官方给出的理由是：集中在一个数据库引擎上，才能用上 PostgreSQL 特有的能力，而 v4 那层多数据库抽象挡住了这些。</p>

<h2 id="三核心数据模型项目是一切的挂载点">三、核心数据模型：项目是一切的挂载点</h2>

<p>要理解它的功能，先要理解它的数据模型。<strong>在 Dependency-Track 里，「项目（project）」是跟踪单元</strong>——成分、漏洞发现、策略违规、指标，全都挂在项目下面。所有项目合起来叫<strong>组合（portfolio）</strong>。</p>

<p>一个项目包含：</p>

<ul>
  <li><strong>名字 + 可选的版本</strong>，两者合起来标识它；</li>
  <li><strong>分类器（classifier）</strong>，指明它是什么类型的东西（应用、库、容器镜像、固件镜像等，与 CycloneDX 的分类对齐）；</li>
  <li><strong>生态标识符</strong>：Package URL、CPE 或 SWID 标签，任选其一；</li>
  <li><strong>描述性元数据</strong>：分组、描述、作者、供应商、制造商、外部引用；</li>
  <li><strong>标签（tag）</strong> 与 <strong>项目属性（property）</strong>；</li>
  <li><strong>可选的父项目</strong>，形成层级；</li>
  <li><strong>访问列表</strong>，控制哪些团队能看到它；</li>
  <li><strong>生命周期状态</strong>：是否启用、最后一次 BOM 导入时间、最后一次漏洞分析时间、当前风险分。</li>
</ul>

<h3 id="31-几个刻意留给你的决定">3.1 几个刻意留给你的决定</h3>

<p>官方文档专门有一节叫「Dependency-Track 不假设什么」。这几条很值得先知道，因为它们决定了你该怎么建模：</p>

<p><strong>它不规定项目该是什么粒度。</strong> 一个项目可以对应一个库、一个可部署服务、一个服务的某个环境，甚至一整条产品线。<strong>选一个和你做问题分诊、报表的方式匹配的粒度。</strong></p>

<p><strong>版本是不透明的字符串。</strong> 它不解析、不比较、不排序版本号，也不假设类 semver 的排序。所谓「最新版本」是一个<strong>手工维护的标记</strong>，不是算出来的。</p>

<p><strong>项目之间不能有依赖关系。</strong> 组件级的依赖关系写在 BOM 内部；项目之间唯一被跟踪的关系是父子层级，而<strong>这个层级是组织性的，不是依赖图</strong>。如果服务 A 依赖服务 B，这个事实没法表达成项目关系。</p>

<p><strong>名字 + 版本在全实例内唯一。</strong> 同一对名字和版本不能挂在两个不同的父项目下。</p>

<p>这四条合起来是一句提醒：<strong>Dependency-Track 不是依赖图数据库。</strong> 想用它回答「服务 A 到底依赖服务 B 的哪个版本」，得靠别的工具。</p>

<h3 id="32-层级集合项目与访问控制">3.2 层级、集合项目与访问控制</h3>

<p>项目可以有父项目，子项目可以有多个。层级是组织性的，用来按产品、环境、团队分组。</p>

<p>有两件事沿着层级流动：</p>

<ul>
  <li><strong>访问控制</strong> —— 能看到父项目的团队，也能看到它的所有后代。</li>
  <li><strong>集合项目上的聚合指标</strong> —— 只有集合项目会从子项目读指标。</li>
</ul>

<p><strong>集合项目（collection project）</strong> 是一种特殊的父项目：它自己不装成分、不装服务，唯一作用是把子项目的指标汇总起来，有三种模式：</p>

<table>
  <thead>
    <tr>
      <th>模式</th>
      <th>行为</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>汇总所有直接子项目</td>
      <td>把每个直接子项目的指标合并起来</td>
    </tr>
    <tr>
      <td>按标签汇总</td>
      <td>只合并带指定标签的直接子项目</td>
    </tr>
    <tr>
      <td>汇总最新版本</td>
      <td>只合并被标记为「最新版本」的直接子项目</td>
    </tr>
  </tbody>
</table>

<p>集合项目和普通父项目有三处不同：它没有分类器；它不能有成分、服务或依赖图（详情页把这些页签换成「集合项目」页签）；<strong>它不接受 BOM 上传</strong>。</p>

<p>关于活跃状态：项目默认是活跃的。标记为不活跃后，它从活跃的组合视图里消失、不能再当父项目、并且变成保留策略的删除候选。<strong>有活跃子项目的项目不能被标记为不活跃</strong>——活跃项目永远不会被保留策略删掉。</p>

<h2 id="四核心功能">四、核心功能</h2>

<p>官方文档的概念页目录本身就是一份功能清单。下面按能力归一下类。</p>

<h3 id="41-bom-摄取">4.1 BOM 摄取</h3>

<p>接受 CycloneDX 和 SPDX 格式的清单，展开成项目下的成分与依赖关系，并记录导入时间。</p>

<h3 id="42-成分与依赖图">4.2 成分与依赖图</h3>

<p>项目下能看到成分列表、依赖关系、以及每个成分的属性（许可证、PURL、CPE 等）。</p>

<h3 id="43-漏洞分析">4.3 漏洞分析</h3>

<p>两个部分：</p>

<ul>
  <li><strong>数据源</strong> —— 官方有专门的「vulnerability data sources」和「KEV data sources」两页。NVD 是其中之一；ENISA EU KEV 目录也在支持列表里（发布说明里能看到针对它的更新）。KEV 类数据源的作用是标出「已被真实利用」的漏洞，让优先级排序有据可依。</li>
  <li><strong>内部分析器</strong> —— 把成分的 PURL/CPE 与漏洞库匹配。v4 里这个分析器有一个可选的兜底：当成分没有 CPE 时，用 Lucene 做模糊匹配去内部漏洞库里找。<strong>v5 砍掉了这个兜底</strong>（原因见第六节）。</li>
</ul>

<h3 id="44-vex">4.4 VEX</h3>

<p>支持 VEX（漏洞利用性交换）文档，让发布方声明某个漏洞对自己的产品<strong>实际不受影响</strong>（not affected / fixed / under investigation），从而避免把已知的误报反复报出来。</p>

<h3 id="45-漏洞策略">4.5 漏洞策略</h3>

<p>v5 新增/强化的一块：<strong>漏洞策略（vulnerability policy）</strong> 让操作者在发现结果到达前端或触发通知之前，先做审计或抑制。</p>

<h3 id="46-组件完整性校验v5-新增">4.6 组件完整性校验（v5 新增）</h3>

<p>这一条直接对应供应链攻击里最难防的一类。官方描述是：<strong>Dependency-Track 会标记那些哈希与上游包仓库发布的不一致的组件。</strong> 它能抓住<strong>仿冒包（typosquatting）和仓库侧的篡改</strong>——这两类正是 v4 留给下游扫描器去管的。</p>

<p>值得注意的是它防的是什么、不是防什么：<strong>它防的是「这个制品不是上游那个制品」，不是「这个制品有漏洞」。</strong> 完整性校验和漏洞分析是两条正交的线。</p>

<h3 id="47-组件策略">4.7 组件策略</h3>

<p>针对成分本身的策略（比如按许可证、按分组、按使用方式判定），用来支撑许可证合规和准入决策。</p>

<h3 id="48-通知">4.8 通知</h3>

<p>按项目、标签、等级等条件触发通知。v5 把通知的数据格式换成了 <strong>Protobuf</strong>，并新增了按通知载荷任意字段做过滤的表达式（详见第六节）。</p>

<h3 id="49-时序指标">4.9 时序指标</h3>

<p>v5 把 v4 那种「在 Java 任务里逐行重算的时点计数器」换成了<strong>真正的时序指标</strong>，直接在 PostgreSQL 里计算。</p>

<h3 id="410-访问控制">4.10 访问控制</h3>

<p>用户、团队、权限三者构成。项目的访问列表决定谁能看到它；能看父项目就能看后代；持有 <code class="language-plaintext highlighter-rouge">PORTFOLIO_ACCESS_CONTROL_BYPASS</code> 权限的团队可以绕过访问列表。</p>

<p><strong>组合访问控制（portfolio access control）</strong> 在 v4 里是带已知缺口和明显开销的 beta 功能，v5 补齐了缺口并重做了实现，让开销随项目数量增长保持在可控范围。</p>

<h3 id="411-工作负载身份联合">4.11 工作负载身份联合</h3>

<p>v5 概念页里有专门一节讲它——让外部身份（比如云厂商的短期身份）来访问 Dependency-Track 的 API，而不需要分发长期凭据。</p>

<h2 id="五v5-相对-v4-变了什么">五、v5 相对 v4 变了什么</h2>

<p>官方在《About changes in v5》里有一句话定调：<strong>v5 对平台做了大范围重构，但不是重写</strong>——底层技术和很多子系统是从 v4 原样继承的。多数改动针对的是 v4 暴露局限的地方：可扩展性与可靠性、策略引擎、运维复杂度；另有几节覆盖的是 v4 完全没有的新能力。</p>

<p>按「用户能看到什么」归类：</p>

<h3 id="51-新的能力">5.1 新的能力</h3>

<table>
  <thead>
    <tr>
      <th>能力</th>
      <th>说明</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>组件完整性校验</td>
      <td>比对成分哈希与上游仓库发布值，识别仿冒包与仓库侧篡改</td>
    </tr>
    <tr>
      <td>组合访问控制转正</td>
      <td>从 beta 变为正式能力，重做实现以控制开销</td>
    </tr>
    <tr>
      <td>保留策略</td>
      <td>按配置周期清理不活跃的项目版本与时序指标（v4 里两者都无上限地增长）</td>
    </tr>
    <tr>
      <td>集中式密钥</td>
      <td>各集成的凭据集中存一处，按部署选定的密钥管理后端托管，便于审计与轮换</td>
    </tr>
    <tr>
      <td>独立的管理端点</td>
      <td>单独的 management server，跑在独立端口，提供 Prometheus 指标与 Kubernetes 风格的存活/就绪探针，把抓取与探针的生命周期从用户流量里分开</td>
    </tr>
    <tr>
      <td>时序指标</td>
      <td>指标变成数据库里的正经时序，不再是 Java 任务逐行重算</td>
    </tr>
  </tbody>
</table>

<h3 id="52-行为变化">5.2 行为变化</h3>

<ul>
  <li><strong>可扩展性与持久化</strong> —— v5 移除了 v4 的进程内单点（内存队列 + 本地索引）。Web 节点与 worker 节点可以独立横向扩展，后台工作通过 PostgreSQL 支撑的队列分发。长任务（BOM 处理、漏洞分析、通知投递）跑在持久化执行引擎上：<strong>重启或崩溃后从中断处继续，而不是随 JVM 一起消失</strong>；失败步骤自动按指数退避重试。</li>
  <li><strong>通知语义</strong> —— 运行时把每条通知写进一个<strong>事务性发件箱（transactional outbox）</strong>，与触发它的那次变更在同一个事务里，然后由中继异步分发。契约是<strong>至少一次投递</strong>：消费方必须能容忍重复，但不会有事件在半路悄悄消失。</li>
  <li><strong>策略引擎</strong> —— v4 的策略编辑器是一堆固定操作符的条件列表；v5 换成了新引擎，并且支持用 <strong>CEL（Common Expression Language）</strong> 写表达式条件。同一套引擎也驱动漏洞策略。</li>
  <li><strong>通知过滤</strong> —— v4 的告警只能按项目、标签、等级、分组过滤；v5 的告警可以按通知载荷的<strong>任意字段</strong>做过滤。</li>
</ul>

<h3 id="53-资源占用">5.3 资源占用</h3>

<p>官方说 v5 的运行时基线内存和 CPU 都低于 v4，主要来自去掉了内存队列、Lucene 索引和 v4 的指标重算循环。</p>

<h2 id="六升级前要知道的几件事">六、升级前要知道的几件事</h2>

<p>这一节是本文最实用的部分。<strong>官方在 5.0.0 的发布说明里明确写了：升级需要手工操作。</strong></p>

<h3 id="61-三条硬约束">6.1 三条硬约束</h3>

<ol>
  <li><strong>迁移是手工的。</strong> 有专门的迁移指南，v4 侧必须 <strong>≥ 4.14.2</strong>，且<strong>升级期间必须离线</strong>。</li>
  <li><strong>v5 要求 PostgreSQL 14+</strong>，H2、MySQL、SQL Server 全部不支持。</li>
  <li><strong>官方 Helm chart 在 v5 标签上当时还不兼容</strong>，渲染会失败。官方当时的建议是：如果你是用 Helm 部署的，先别升。</li>
</ol>

<h3 id="62-破坏性变更">6.2 破坏性变更</h3>

<table>
  <thead>
    <tr>
      <th>变更</th>
      <th>影响</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>通知 schema 换成 Protobuf</td>
      <td>主题对象改用 Protobuf；列表字段加 <code class="language-plaintext highlighter-rouge">List</code> 后缀；类枚举值加类型前缀（<code class="language-plaintext highlighter-rouge">INFORMATIONAL</code> → <code class="language-plaintext highlighter-rouge">LEVEL_INFORMATIONAL</code>、<code class="language-plaintext highlighter-rouge">SYSTEM</code> → <code class="language-plaintext highlighter-rouge">SCOPE_SYSTEM</code>、<code class="language-plaintext highlighter-rouge">NEW_VULNERABILITY</code> → <code class="language-plaintext highlighter-rouge">GROUP_NEW_VULNERABILITY</code>）；时间戳统一成毫秒精度。<strong>消费 v4 主题对象的模板需要重写。</strong></td>
    </tr>
    <tr>
      <td>REST API v1 变化</td>
      <td>移除的端点不多，但响应结构有变，<strong>列表端点默认强制分页</strong></td>
    </tr>
    <tr>
      <td>模糊漏洞分析移除</td>
      <td>v4 的内部分析器在成分缺 CPE 时可退回 Lucene 模糊匹配；丢掉 Lucene 就没这个能力了</td>
    </tr>
    <tr>
      <td>分发形态</td>
      <td>只有容器镜像，WAR 与 bundled 镜像都没了。<strong>用 WAR 或 bundled 镜像的运维要迁到分开的 API 服务器与前端镜像</strong></td>
    </tr>
    <tr>
      <td>NVD 镜像端点</td>
      <td>v4 把下载到的 NVD 源文件放在 <code class="language-plaintext highlighter-rouge">/mirror/nvd/*</code> 供其他工具使用；v5 不再持久化这些文件，也不再提供该端点。需要内部镜像的改用官方指南里的做法（从 NIST 直接拉，或自建专用镜像）</td>
    </tr>
  </tbody>
</table>

<h3 id="63-升级前该确认的三件事">6.3 升级前该确认的三件事</h3>

<ol>
  <li><strong>你的部署方式在不在 v5 的支持范围内</strong>（容器镜像 + PostgreSQL）。</li>
  <li><strong>有没有人消费通知</strong>——如果有，Protobuf 的字段改名是硬工作量，不是配置项。</li>
  <li><strong>你的 API 调用方</strong>——列表端点默认分页这一条，可能让没做分页处理的客户端直接拿错数据。</li>
</ol>

<h2 id="七什么时候值得用它什么时候先别上">七、什么时候值得用它，什么时候先别上</h2>

<h3 id="71-值得">7.1 值得</h3>

<ul>
  <li><strong>你的组织里已经有多个产品线，需要一份统一的成分台账。</strong> 组合视图、集合项目、层级访问控制这些能力，都是为「多个团队、多个产品」设计的。</li>
  <li><strong>你需要按组织维度做许可证合规。</strong> 组件策略 + 标签体系是为此设计的。</li>
  <li><strong>你需要一处能回答「这个成分到底受不受影响」的地方。</strong> VEX + 漏洞策略 + 通知过滤，比「扫一次报一堆」实用得多。</li>
  <li><strong>你在意供应链攻击里「制品被替换」这一类。</strong> 组件完整性校验是 v5 新增的、也是最有辨识度的一项。</li>
</ul>

<h3 id="72-先别上">7.2 先别上</h3>

<ul>
  <li><strong>你的团队只有一个产品、几百个依赖。</strong> 这时候一个 CI 里跑的扫描器 + 一份报告可能就够了，起一整套常驻平台是运维负担。</li>
  <li><strong>你没有稳定的 BOM 来源。</strong> <strong>Dependency-Track 不生成 BOM</strong>——没有上游产 BOM 的话，这个平台就是空的。这一点在选型时要先确认。</li>
  <li><strong>你刚做完一次大规模组件升级，短期内不需要再评估。</strong></li>
  <li><strong>你的部署环境暂时没有 PostgreSQL 14+。</strong> 这是硬约束，没有变通。</li>
</ul>

<h2 id="八接下来v5-的关键技术系列">八、接下来：v5 的关键技术系列</h2>

<p>这篇刻意停在「功能层」。因为 v5 真正的技术含量都藏在实现里，而且每一处都对应一个明确的问题：</p>

<ul>
  <li><strong>持久化执行引擎（durable execution engine）</strong> —— 为什么长任务能在崩溃后从断点继续，而不是随 JVM 消失。</li>
  <li><strong>CEL 策略引擎</strong> —— 一套引擎同时驱动组件策略、漏洞策略、通知过滤和工作负载身份绑定（5.2.0 起），它怎么设计才能既可扩展又不至于变成「让人在 UI 里写代码」。</li>
  <li><strong>事务性发件箱 + 至少一次投递</strong> —— 「不丢事件」和「不重复事件」之间的取舍怎么落到代码里。</li>
  <li><strong>PostgreSQL 里的搜索与时序指标</strong> —— 去掉 Lucene 之后，搜索改成直接打在 PostgreSQL 上（官方文档没写清它具体怎么做，这本身是个值得写的点）；以及把时序指标做成「正经的时序」而不是逐行重算。</li>
  <li><strong>单一数据面（single data plane）</strong> —— 为什么砍掉三种数据库支持是一个划算的决定，以及它换来了什么；顺便说清这个「统一」统一的是哪一层——<strong>不是</strong>把所有数据塞进一张表。</li>
</ul>

<p>这几篇会按「问题 → 约束 → 做法 → 代价」的顺序写，单独成系列。</p>

<h2 id="小结">小结</h2>

<p>Dependency-Track 是 OWASP 基金会下的 Apache-2.0 开源项目，一个<strong>常驻式</strong>的成分分析平台：它消费上游产出的 BOM（自己不生成），持续维护「有哪些项目、哪些成分、哪些漏洞」，并按组织维度提供报表、策略和通知。</p>

<p>它的数据模型只有一个支点——<strong>项目</strong>。成分、发现、违规、指标全挂在项目下；项目之间只能有组织性的父子层级，<strong>没有项目级的依赖关系</strong>。这一点在选型时要先想清楚：它不是依赖图数据库。</p>

<p>v5 相对 v4 的变化可以概括成两句：<strong>存储上收敛到一个数据库引擎</strong>（只支持 PostgreSQL 14+，去掉 H2/MySQL/SQL Server），<strong>运行上从单进程变成可水平扩展的 Web + worker</strong>（后台工作持久化、崩溃可续、通知至少一次投递）。新增的能力里，组件完整性校验最有辨识度——它抓的是「制品不是上游那个制品」这类问题，和漏洞分析是正交的两条线。</p>

<p>而升级这件事，官方写得很直白：<strong>需要手工操作</strong>。v4 要 ≥ 4.14.2 且升级期间离线，WAR 与 bundled 镜像消失，通知格式换成 Protobuf（字段有改名），API 列表端点默认分页。这几条都是工作量，不是配置项。</p>

<h2 id="本文引用的来源">本文引用的来源</h2>

<table>
  <thead>
    <tr>
      <th>结论</th>
      <th>出处</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>归属、许可、语言、仓库创建时间、官网</td>
      <td><a href="https://github.com/DependencyTrack/dependency-track">DependencyTrack/dependency-track 仓库</a></td>
    </tr>
    <tr>
      <td>5.0.0 于 2026-06-07 发布；升级需手工操作、v4 需 ≥ 4.14.2 且离线、要求 PostgreSQL 14+、Helm chart 当时不兼容、容器化分发取代 WAR</td>
      <td><a href="https://github.com/DependencyTrack/dependency-track/releases/tag/5.0.0">v5.0.0 发布说明</a></td>
    </tr>
    <tr>
      <td>当前版本号与发布时间（5.2.2 与 4.14.7 同为 2026-11-18）</td>
      <td><a href="https://github.com/DependencyTrack/dependency-track/releases">发布列表</a></td>
    </tr>
    <tr>
      <td>v5 的整体变化：持久化执行与至少一次投递、PostgreSQL 单一数据面、CEL 策略与通知过滤、组件完整性校验、组合访问控制转正、保留策略、集中式密钥、独立管理端点、资源占用下降</td>
      <td><a href="https://dependencytrack.github.io/docs/next/concepts/changes-in-v5/">About changes in v5</a></td>
    </tr>
    <tr>
      <td>破坏性变更：通知 schema 改 Protobuf 与字段改名、REST API v1 与默认分页、Lucene 模糊匹配移除、分发形态变化、NVD 镜像端点移除</td>
      <td>同上（What this breaks 一节）</td>
    </tr>
    <tr>
      <td>项目的定义与字段、刻意不做的假设、版本为不透明字符串、项目之间无依赖关系、层级与集合项目、标签与属性、保留策略、访问控制</td>
      <td><a href="https://dependencytrack.github.io/docs/next/concepts/projects/">About projects</a></td>
    </tr>
    <tr>
      <td>官方概念页给出的功能边界（漏洞数据源、KEV 数据源、漏洞发现、VEX、通知、时序指标、组件策略、组件完整性校验、漏洞策略、访问控制、工作负载身份联合）</td>
      <td><a href="https://dependencytrack.github.io/docs/next/concepts/">Dependency-Track 文档 · Concepts</a></td>
    </tr>
    <tr>
      <td>NVD 与 ENISA EU KEV 数据源在维护中的处理</td>
      <td><a href="https://github.com/DependencyTrack/dependency-track/releases/tag/5.2.2">5.2.2 发布说明</a></td>
    </tr>
  </tbody>
</table>]]></content><author><name>maijun</name></author><category term="软件供应链安全" /><category term="SBOM" /><category term="漏洞管理" /><category term="开源组件" /><summary type="html"><![CDATA[摘要：Dependency-Track 是 OWASP 基金会下的开源软件成分分析平台。它解决的是一个很具体的运维问题：你的软件里有哪些第三方组件、这些组件哪些有已知漏洞、哪些是误报、哪些可以放行。 这篇只讲两件事：它是什么（归属、许可、数据模型、核心功能）和 v5 相对 v4 变了什么（部署形态、存储、通知格式、API，以及几个新能力）。v5 的关键技术实现——持久化执行引擎、CEL 策略引擎、事务性通知外发、PostgreSQL 里的时序指标——不在本文展开，会另做一个系列逐个拆。 需要提前知道的一件事：从 v4 升到 v5 不是点一下版本号的事，官方发布说明里写的是「需要手工操作」。具体是哪几步，本文第四节列出来了。]]></summary></entry><entry><title type="html">AI 模型生产线：从训练数据到上线模型的供应链视角</title><link href="https://maijun-sec.github.io/2026/12/03/ai-model-production-line/" rel="alternate" type="text/html" title="AI 模型生产线：从训练数据到上线模型的供应链视角" /><published>2026-12-03T00:12:00+08:00</published><updated>2026-12-03T00:12:00+08:00</updated><id>https://maijun-sec.github.io/2026/12/03/ai-model-production-line</id><content type="html" xml:base="https://maijun-sec.github.io/2026/12/03/ai-model-production-line/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：软件供应链的整个方法论建立在一个前提上：<strong>同一个制品永远对应同一份哈希</strong>。AI 生产线把这个前提拿掉了——同一份代码、同一份数据、跑两次，出来的权重不是同一个文件。</p>

  <p>这篇不做标准介绍（那部分另有一篇），而是把整条产线摊开看：<strong>六个环节各自留下什么产物、哪些环节天然有标识符、哪些没有、断链最常发生在哪三处</strong>；然后回答一个具体问题——<strong>AI-BOM 在这条线上到底该放在哪个位置</strong>，以及它<strong>替代不了</strong>什么。</p>

  <p>结论先给：AI-BOM 是产线的一份<strong>产出记录</strong>，不是产线的<strong>质量门禁</strong>。它能告诉你「这个模型是用哪些数据训的」，但它挡不住「数据被投毒」。这两件事必须分开算。</p>
</blockquote>

<!--more-->

<h2 id="一这条产线和软件产线到底差在哪">一、这条产线和软件产线到底差在哪</h2>

<p>先把差异说准，后面所有结论都从这里推出来。</p>

<p>软件产线的流程是：写代码 → 提交 → 构建 → 打包 → 发布。每一步的产物都有一个<strong>稳定的内容标识符</strong>：</p>

<ul>
  <li>一次提交有 commit hash；</li>
  <li>一个构建有构建产物的哈希；</li>
  <li>一个容器镜像有 digest；</li>
  <li>一个发布包通常还有版本号。</li>
</ul>

<p>于是「供应链安全」这件事可以有一个非常清晰的定义：<strong>从最终交付物出发，沿着标识符反向走，把每一层依赖还原出来。</strong> SBOM 就是这条反向路径的产物。</p>

<p>AI 生产线是：收集数据 → 清洗标注 → 训练 → 评估 → 打包 → 部署 → 迭代。</p>

<p>问题出在<strong>训练这一环</strong>：它不是一个确定性的函数。</p>

<ul>
  <li>随机种子相同，但分布式训练的梯度归约顺序、GPU 的非确定性算子，仍然会让两次训练出的权重文件不同；</li>
  <li>数据集是「目录」而不是「文件」，一个目录里多进来一条样本、一个标注被改，产物就变了，而目录本身没有哈希；</li>
  <li>训练框架、CUDA 版本、驱动版本、混合精度策略都会改变数值结果。</li>
</ul>

<p><strong>所以在 AI 产线里，「同一个模型」这句话本身就是需要证据的，而不是默认成立的。</strong></p>

<p>这不是一个可以绕过的工程细节，它是后面所有事的前提：</p>

<ul>
  <li>AI-BOM 不能只是「SBOM 加几个字段」，因为 SBOM 的哈希语义在这里失效；</li>
  <li>「可复现」在 AI 里是一个<strong>需要额外工程投入才能获得的属性</strong>（固定种子、锁定数据版本、锁定依赖、固定硬件），而不是默认属性；</li>
  <li>模型可复现 ≠ 模型可信。前者是工程问题，后者是安全问题，两者别混。</li>
</ul>

<h2 id="二产线地图六个环节各自留下什么">二、产线地图：六个环节，各自留下什么</h2>

<p>把产线拆成六段，每段问三个问题：<strong>产物是什么、有没有天然标识符、谁负责</strong>。</p>

<table>
  <thead>
    <tr>
      <th>环节</th>
      <th>主要产物</th>
      <th>天然标识符</th>
      <th>常见存放位置</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>数据收集与清洗</td>
      <td>数据集（目录或分片）</td>
      <td>无（只有名字/URL）</td>
      <td>对象存储、数据湖</td>
    </tr>
    <tr>
      <td>标注</td>
      <td>标注文件</td>
      <td>无</td>
      <td>同上，或标注平台</td>
    </tr>
    <tr>
      <td>训练</td>
      <td>权重文件、训练配置</td>
      <td>权重有哈希；配置没有</td>
      <td>模型仓库、实验跟踪系统</td>
    </tr>
    <tr>
      <td>评估</td>
      <td>指标、评测集、报告</td>
      <td>评测集有哈希</td>
      <td>实验跟踪系统</td>
    </tr>
    <tr>
      <td>打包与登记</td>
      <td>模型卡、数据卡、模型仓库条目</td>
      <td>有版本号</td>
      <td>模型仓库</td>
    </tr>
    <tr>
      <td>部署与推理</td>
      <td>容器镜像、推理服务</td>
      <td>镜像有 digest</td>
      <td>镜像仓库、Kubernetes</td>
    </tr>
  </tbody>
</table>

<p>这张表里最该看的不是「产物是什么」，而是<strong>第三列只有两行是确定的</strong>。</p>

<p>代码有 commit，镜像有 digest。这两样在传统供应链里已经有了对应的管理办法（版本控制、镜像签名与准入）。<strong>真正缺标识符的是数据集和训练配置。</strong> 这两样恰好又是 AI 系统里最影响行为的东西——同一份权重换一个数据集，就是另一个模型。</p>

<p>再往上看第四列：<strong>产物散在四套系统里</strong>。数据在对象存储、权重在模型仓库、镜像在镜像仓库、元数据在实验跟踪系统（MLflow 之类的工具管的就是这一摊）。</p>

<p>这不是「运维没做好」，这是产线的固有形状。<strong>AI-BOM 难产的根本原因不是没人想记，而是没有一个地方能原子地拿到全部信息。</strong> 任何一份清单，都必然是「从多个系统拼出来的」，而拼接就意味着可能拼错、可能漏、可能过时。</p>

<h2 id="三断链最常发生在的三处">三、断链最常发生在的三处</h2>

<h3 id="31-数据集来源许可与去标识">3.1 数据集：来源、许可与去标识</h3>

<p>数据是这条链的起点，也是最容易出事的一环。三个问题各自对应一个真实风险：</p>

<p><strong>来源</strong> —— 这批数据从哪来的？是公开数据集、爬来的、用户上传的，还是采购的？来源不明意味着你无法评估它是否被投毒，也无法评估它是否包含未经授权的内容。</p>

<p><strong>许可与同意</strong> —— 数据能不能用、能不能再分发、里面有没有个人信息、用户是否同意被用于训练。这一组问题在传统软件供应链里<strong>没有对应物</strong>，因为传统供应链里最底层的原料是代码，而代码有作者、有许可证、有分发协议。</p>

<p><strong>去标识</strong> —— 「我们把 PII 去掉了吗」不是布尔问题。「删了姓名但保留了邮编+生日」在很多场景下仍然可以重标识。所以 SPDX 的 <code class="language-plaintext highlighter-rouge">Dataset profile</code> 里，去标识方法（<code class="language-plaintext highlighter-rouge">anonymizationMethodUsed</code>）和数据是否含敏感个人信息（<code class="language-plaintext highlighter-rouge">hasSensitivePersonalInformation</code>）是两个独立字段，不是同一个意思。</p>

<p>这一环还有一个结构性困难：<strong>数据集会变，但它的版本不像代码那样自动带出来。</strong> 数据湖里一个目录的内容随时在被改，而清单里的 <code class="language-plaintext highlighter-rouge">datasetVersion</code> 只是一个字符串。数据版本管理本身就是个独立问题。</p>

<h3 id="32-权重来源可信度与加载格式即执行路径">3.2 权重：来源可信度与「加载格式即执行路径」</h3>

<p>模型权重有两个独立的风险。</p>

<p><strong>第一个是来源。</strong> 从模型仓库拉下来的权重，它的哈希能告诉你「文件没被改过」，但告诉不了你「这个权重是不是在有问题的数据上训出来的」。<strong>签名解决的是完整性，不是来源可信度。</strong> 一个被投毒的模型可以被完整地签上名。</p>

<p><strong>第二个更技术、也更容易被忽略：权重的加载格式本身就是一条执行路径。</strong></p>

<p>Python 生态里，模型的权重常用 pickle 一类的格式保存。<strong>反序列化 pickle 在设计上就是可以执行任意代码的</strong>——这本来是它的功能（能存任意 Python 对象），但用在一个「从外部下载的制品」上，就等于把下载模型变成了下载可执行文件。</p>

<p><code class="language-plaintext highlighter-rouge">safetensors</code> 这类格式的思路是相反的：<strong>只存张量，不存代码</strong>，加载时没有对象重建这一步，因此这条执行路径被收窄了。</p>

<p>这一条和 SBOM 时代没有对应物。在 SBOM 里，最坏的制品是「有漏洞的库」；在 AI 供应链里，最坏的制品可以是「加载即执行」。</p>

<p>（顺带一句：把这件事说清楚不是要否定所有旧格式，而是说<strong>权重制品的格式选择，应该进入供应链策略里</strong>——和「只允许从内部仓库拉取制品」是同一级别的事。）</p>

<h3 id="33-血缘微调模型天然不完整">3.3 血缘：微调模型天然不完整</h3>

<p>产线上产出的模型，大量不是从零训的，而是在某个基座模型上微调而来。</p>

<p>于是模型的构成是三块：<strong>基座权重 + 自己的数据 + 自己的超参</strong>。</p>

<p>前两块的组合产出一个新模型，但——<strong>基座模型的原始训练信息，你多半不知道。</strong> 一个开源基座模型通常只公开了模型卡和技术报告，不公开完整的数据集清单、训练配方和随机种子。</p>

<p>所以 AI 供应链里的血缘断裂<strong>不是流程疏漏，是结构性的</strong>：它源自「你要在一个你无法完全审计的基座上做修改」这个事实本身。</p>

<p>这一点对 AI-BOM 的设计有直接影响：<strong>规范必须能表达「未知」和「部分已知」。</strong> SPDX 的 <code class="language-plaintext highlighter-rouge">AIPackage</code> 里 <code class="language-plaintext highlighter-rouge">informationAboutTraining</code> 是一个可以留空或标「未知」的属性，而不是一个必填的硬门槛——这和许可证那两格必须填形成了对比（许可证必须填，因为它是可判定的事实；训练信息可以填不完整，因为客观上就可能不完整）。</p>

<p><strong>一份诚实的 AI-BOM 里有一堆「未知」，不是缺陷。</strong> 相反，一份把所有字段都填满的 AI-BOM 反而值得怀疑。</p>

<h3 id="34-部署运行时也是供应链的一部分">3.4 部署：运行时也是供应链的一部分</h3>

<p>模型服务起来的这一段，成分和传统应用几乎一样：容器镜像、Python 运行时、推理框架、加速库、系统库。</p>

<p>这一段的供应链管理是可以直接复用 SBOM 时代的成熟做法的——<strong>镜像 digest + 签名 + 准入策略</strong>，一条都不用改。</p>

<p>这其实是个好消息：<strong>AI 产线里最容易做扎实的一段，正好是工具链最成熟的一段。</strong> 难点集中在上游。</p>

<h2 id="四ai-bom-在这条线上该放在哪个位置">四、AI-BOM 在这条线上该放在哪个位置</h2>

<p>把它放回产线地图：</p>

<blockquote>
  <p><strong>AI-BOM 是「打包与登记」这一环的一份产出记录；它既不产生数据，也不验证数据。</strong></p>
</blockquote>

<p>这句话可以拆成三句更具体的：</p>

<ol>
  <li><strong>它不产生质量。</strong> 清单里的 <code class="language-plaintext highlighter-rouge">metric</code>、<code class="language-plaintext highlighter-rouge">fairnessAssessments</code>、<code class="language-plaintext highlighter-rouge">modelExplainability</code> 这些字段，填的是<strong>已经做过的评估的结论</strong>，不是评估本身。没做过的评估，在清单里就只能是空的。</li>
  <li><strong>它不验证完整性。</strong> 清单是静态文本，谁改都能改。真正能保证「线上跑的就是清单里那个」的是<strong>签名 + 准入策略</strong>：制品在构建时签名，部署前校验签名，校验通过才放行。清单是被签名的东西之一。</li>
  <li><strong>它不保证数据可信。</strong> 清单记录「用数据集 X 训练」，但不回答「X 是不是被投毒过」。数据可信度来自<strong>上游的获取与审核流程</strong>，不在清单这一环。</li>
</ol>

<p>所以一条 AI 供应链的质量保证，实际由三件不同的事构成：</p>

<table>
  <thead>
    <tr>
      <th>要保证的事</th>
      <th>靠什么</th>
      <th>AI-BOM 的角色</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>线上跑的是清单里那个制品</td>
      <td>签名 + 准入策略</td>
      <td>提供被签名的内容</td>
    </tr>
    <tr>
      <td>这个制品的组成是可解释的</td>
      <td>清单 + 可追溯的构建过程</td>
      <td>就是清单本身</td>
    </tr>
    <tr>
      <td>组成里的东西本身是可信的</td>
      <td>上游获取、审核、持续监控</td>
      <td>清单提供证据，不提供结论</td>
    </tr>
  </tbody>
</table>

<p><strong>第三行是 AI-BOM 唯一做不到的事，也正是最容易让人误解的地方。</strong> 有了清单不等于数据可信；有了 SBOM 也不等于依赖安全——SBOM 时代我们花了十几年才把这件事讲明白（清单是必要条件，不是充分条件），AI-BOM 不该重走一遍。</p>

<h2 id="五已经在跑的两份清单">五、已经在跑的两份清单</h2>

<p>有意思的是，AI 领域并不缺清单——<strong>模型卡和数据卡已经在生产环境跑了很久</strong>，而且它们填的字段和 AI-BOM 高度重合。</p>

<p><strong>模型卡（model card）</strong> 的提法来自 Google 的研究团队（Model Cards for Model Reporting，2019）：一份描述模型预期用途、评测表现、已知局限、以及伦理考量的文档。它的特点是<strong>叙述性</strong>——它面向人，需要作者做判断，而不是填表。</p>

<p><strong>数据卡（datasheets for datasets）</strong> 的提法来自另一篇同期工作（Datasheets for Datasets，2021）：一份描述数据集的动机、组成、采集过程、预处理、用途、分发方式和维护计划的文档。</p>

<p>和 AI-BOM 的关系可以这样看：</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>模型卡 / 数据卡</th>
      <th>AI-BOM</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>读者</td>
      <td>人</td>
      <td>机器</td>
    </tr>
    <tr>
      <td>形式</td>
      <td>叙述 + 表格</td>
      <td>结构化字段</td>
    </tr>
    <tr>
      <td>判断</td>
      <td>需要作者判断</td>
      <td>可自动校验</td>
    </tr>
    <tr>
      <td>覆盖</td>
      <td>通常只覆盖已交付的模型</td>
      <td>可以覆盖同一模型的多个版本和它们的血缘</td>
    </tr>
    <tr>
      <td>机器可读性</td>
      <td>弱</td>
      <td>强</td>
    </tr>
  </tbody>
</table>

<p><strong>理想的形态是同一份事实的两种表达</strong>：模型卡是给人读的，AI-BOM 是给扫描器和策略引擎读的，内容同源、字段可映射。</p>

<p>现实是：两者各自演化，字段没有对齐，团队常常二选一或者两份都手写。<strong>AI-BOM 的推广难点，一半在标准，一半在「怎么让人别写两遍」。</strong></p>

<h2 id="六监管把这条线推成了什么样">六、监管把这条线推成了什么样</h2>

<p>监管不是这条产线的推动者，但它给「可追溯」这件事定了时间表。</p>

<p><strong>欧盟《人工智能法案》（Regulation (EU) 2024/1689）</strong> 的关键在于它把<strong>技术文档变成了法定义务</strong>。Article 11 要求高风险 AI 系统建立技术文档，附件 IV 规定其内容——其中就包含训练、验证和测试所用数据的说明。也就是说，<strong>「这个模型用哪些数据训的」从工程偏好变成了必须回答的问题</strong>。</p>

<p>这条法律的时间表（Article 113 原文）是：</p>

<table>
  <thead>
    <tr>
      <th>时间</th>
      <th>适用范围</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>2024-08-01</td>
      <td>法案生效</td>
    </tr>
    <tr>
      <td>2025-02-02</td>
      <td>第一章、第二章适用（禁止性做法、AI 素养义务）</td>
    </tr>
    <tr>
      <td>2025-08-02</td>
      <td>治理规则与通用人工智能模型义务适用</td>
    </tr>
    <tr>
      <td>2026-08-02</td>
      <td>法案总体适用</td>
    </tr>
    <tr>
      <td>2028-08-02</td>
      <td>属于 Article 6(1) 与附件 I 范围的高风险系统适用</td>
    </tr>
  </tbody>
</table>

<p>（高风险系统的具体分类在附件 III，附件 I 指的是本身受欧盟产品法规监管、且嵌入受监管产品的高风险系统。）</p>

<p><strong>美国这边是自愿性框架。</strong> NIST 的《AI 风险管理框架 1.0》（AI RMF 1.0）给的是 Govern / Map / Measure / Manage 四个功能的方法论——它教你怎么组织风险管理，但它不规定填什么字段，也不规定格式。</p>

<p><strong>OWASP 侧</strong>维护着大模型应用的风险清单，供应链（模型、数据、框架的来源可信度）与数据/模型投毒都是被单独列出的风险类别。工程侧的安全与隐私实践指南也在同一体系里。</p>

<p>把这三件事放在一起看，得到的判断是：</p>

<ul>
  <li><strong>格式层面，SPDX 与 CycloneDX 已经够用</strong>（见另一篇）；</li>
  <li><strong>方法论层面，NIST AI RMF 和 OWASP 的实践指南是现成的起点</strong>；</li>
  <li><strong>真正缺的是中间那一层</strong>：把方法论里的「记录下来」落到流水线里，产出符合标准格式的 AI-BOM。</li>
</ul>

<h2 id="七落地时的三个决策点">七、落地时的三个决策点</h2>

<p>如果你要开始做，下面三个问题想清楚，能省掉大量返工。</p>

<h3 id="71-这份清单是给谁看的">7.1 这份清单是给谁看的</h3>

<p>不同读者要的字段完全不同：</p>

<ul>
  <li><strong>给审计看</strong> —— 要完整、要能追溯到原始证据、要长期保存（审计会问三年前那一版）。</li>
  <li><strong>给准入策略看</strong> —— 要机器可读、要能自动判定、要频繁更新（每次上线都变）。</li>
  <li><strong>给事故复盘看</strong> —— 要能回答「当时线上跑的是哪个权重、用的是哪批数据」。</li>
</ul>

<p><strong>这三者的更新频率差一个数量级。</strong> 拿一份「审计用」的清单去做准入，会因为更新不及时而失去意义；拿一份「准入用」的清单去审计，会因为缺少证据而无法交付。</p>

<h3 id="72-挂在哪个动作上">7.2 挂在哪个动作上</h3>

<p>建议挂在<strong>上线</strong>这个动作上，不是训练完成时。</p>

<p>原因在 3.3 节说过：训练产物和交付物经常不是一回事——中间还有微调、量化、蒸馏、剪枝。挂在训练完成时，你会得到一份「训练产物」的清单，而审计和准入要的是「交付物」的清单。</p>

<h3 id="73-做不到的部分怎么办">7.3 做不到的部分怎么办</h3>

<p>AI-BOM 的价值有一半来自<strong>它把「不知道」显式记下来</strong>。所以：</p>

<ul>
  <li>基座模型的训练信息不知道，就写「未知」；</li>
  <li>某个字段没法自动填，就留空并说明原因；</li>
  <li>数据集没有版本管理，就先给数据集本身造一个版本号。</li>
</ul>

<p><strong>不要用「先随便填上，以后再补」来换取清单的完整度。</strong> 一份字段齐全但内容不实的清单，比一份诚实的清单危险得多——它会让审计和准入策略都建立在错误的前提上。</p>

<h2 id="小结">小结</h2>

<p>AI 生产线和软件生产线最根本的差别，是「同一个制品对应同一份哈希」这个前提不成立。训练出来的权重不是确定函数的产物，而数据集会变、基座模型的血缘天然不完整。</p>

<p>这条线上六个环节里，只有代码提交和容器镜像有天然标识符；数据、权重、训练配置都在四套分散的系统里。<strong>AI-BOM 难产不是因为没人想记，而是因为没有一个地方能原子地拿到全部信息。</strong></p>

<p>AI-BOM 在产线上的位置是明确的：它是「打包与登记」环节的一份<strong>产出记录</strong>。它不产生质量、不验证完整性、不保证数据可信——这三件事分别要靠评估流程、签名加准入策略、上游审核。清单是必要条件，从来不是充分条件。</p>

<p>模型卡和数据卡已经在生产环境跑了很久，它们和 AI-BOM 的关系是同一份事实的两种表达：一份给人读，一份给机器读。<strong>AI-BOM 推广的难点，一半在标准，一半在怎么让人别写两遍。</strong></p>

<p>监管给了一个硬约束和一张时间表：欧盟《人工智能法案》把技术文档变成法定义务，而数据从哪来必须在文档里答上来。</p>

<h2 id="本文引用的来源">本文引用的来源</h2>

<table>
  <thead>
    <tr>
      <th>结论</th>
      <th>出处</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>模型卡的提法、面向人的叙述式结构、预期用途与已知局限等维度</td>
      <td><a href="https://arxiv.org/abs/1810.03993">Model Cards for Model Reporting</a></td>
    </tr>
    <tr>
      <td>数据卡的提法（动机、组成、采集、预处理、用途、分发、维护）</td>
      <td><a href="https://arxiv.org/abs/2103.00010">Datasheets for Datasets</a></td>
    </tr>
    <tr>
      <td>权重的序列化格式问题，以及只存张量、不存代码的替代方案</td>
      <td><a href="https://github.com/huggingface/safetensors">safetensors 项目</a></td>
    </tr>
    <tr>
      <td>模型登记与版本管理在产线中的位置</td>
      <td><a href="https://mlflow.org/docs/latest/ml/model-registry/">MLflow Model Registry 文档</a></td>
    </tr>
    <tr>
      <td>产物来源可追溯的通用做法：构建溯源</td>
      <td><a href="https://slsa.dev/spec/v1.0/">SLSA 规范</a></td>
    </tr>
    <tr>
      <td>制品签名与准入校验</td>
      <td><a href="https://github.com/sigstore/cosign">Sigstore cosign 项目</a></td>
    </tr>
    <tr>
      <td>AI 风险管理的组织方法（Govern / Map / Measure / Manage）</td>
      <td><a href="https://www.nist.gov/publications/artificial-intelligence-risk-management-framework-ai-rmf-10">NIST AI Risk Management Framework 1.0</a></td>
    </tr>
    <tr>
      <td>大模型应用风险清单中供应链与数据/模型投毒作为独立风险类别</td>
      <td><a href="https://owasp.org/www-project-top-10-for-large-language-model-applications/">OWASP Top 10 for LLM Applications 项目页</a></td>
    </tr>
    <tr>
      <td>欧盟《人工智能法案》的编号、Article 11 技术文档义务，以及生效与分阶段适用的日期</td>
      <td><a href="https://eur-lex.europa.eu/eli/reg/2024/1689/oj">Regulation (EU) 2024/1689（EUR-Lex）</a>、<a href="https://ai-act-service-desk.ec.europa.eu/en/ai-act/article-113">Article 113 原文（AI Act Service Desk）</a>、<a href="https://digital-strategy.ec.europa.eu/en/policies/regulatory-framework-ai">欧盟委员会监管框架说明</a></td>
    </tr>
  </tbody>
</table>]]></content><author><name>maijun</name></author><category term="软件供应链安全" /><category term="AI 生产线" /><category term="模型卡" /><category term="数据治理" /><summary type="html"><![CDATA[摘要：软件供应链的整个方法论建立在一个前提上：同一个制品永远对应同一份哈希。AI 生产线把这个前提拿掉了——同一份代码、同一份数据、跑两次，出来的权重不是同一个文件。 这篇不做标准介绍（那部分另有一篇），而是把整条产线摊开看：六个环节各自留下什么产物、哪些环节天然有标识符、哪些没有、断链最常发生在哪三处；然后回答一个具体问题——AI-BOM 在这条线上到底该放在哪个位置，以及它替代不了什么。 结论先给：AI-BOM 是产线的一份产出记录，不是产线的质量门禁。它能告诉你「这个模型是用哪些数据训的」，但它挡不住「数据被投毒」。这两件事必须分开算。]]></summary></entry><entry><title type="html">AI-BOM：模型和数据集的清单格式，SPDX 与 CycloneDX 怎么写</title><link href="https://maijun-sec.github.io/2026/12/03/ai-bom-standard/" rel="alternate" type="text/html" title="AI-BOM：模型和数据集的清单格式，SPDX 与 CycloneDX 怎么写" /><published>2026-12-03T00:05:00+08:00</published><updated>2026-12-03T00:05:00+08:00</updated><id>https://maijun-sec.github.io/2026/12/03/ai-bom-standard</id><content type="html" xml:base="https://maijun-sec.github.io/2026/12/03/ai-bom-standard/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：软件物料清单（SBOM）回答的是「这个软件用了哪些组件、哪些组件有已知漏洞」。AI 系统要回答一组平行的问题：模型是哪一版、用哪些数据训的、数据从哪来、里面有没有个人信息、做过什么风险评估、推理要多少能耗。<strong>AI-BOM（AI Bill of Materials，AI 物料清单）</strong> 就是承载这些答案的机器可读清单。</p>

  <p>读完你会拿到三样东西：一是 <strong>AI-BOM 现在到底有几套格式</strong>——不是一个，而是三套并行，其中两套已经是正式规范，一套还在孵化；二是 <strong>SPDX 3.0.1 与 CycloneDX 1.6/1.7 分别怎么表示模型和数据集</strong>（按字段拆开讲，不是笼统地说「都能记」）；三是 <strong>官方组织在推什么</strong>——OWASP 的 ECMA 标准化、Linux Foundation 主导的 SPDX profile 化、OWASP AIBOM 项目自己的格式工作流，以及一件必须先说清的事：<strong>OWASP AIBOM 的格式规范目前还没有发布</strong>。</p>

  <p>本文出现的每一个字段名、版本号和日期都取自规范原文或官方发布稿，文末逐条给了出处。</p>
</blockquote>

<!--more-->

<h2 id="一先把ai-bom这个词拆开">一、先把「AI-BOM」这个词拆开</h2>

<p>SBOM 的逻辑很朴素：一个软件用了哪些组件、版本是什么、有没有已知漏洞——把它写成一份机器可读的清单，就能拿去和漏洞库比对、和准入策略对齐、和许可证清单核对。</p>

<p>AI 系统要回答的是一组平行的问题，只不过对象换了：</p>

<table>
  <thead>
    <tr>
      <th>要回答的问题</th>
      <th>在 AI 里的具体形态</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>这个东西是哪一版？</td>
      <td>模型版本、微调轮次、权重文件的哈希</td>
    </tr>
    <tr>
      <td>它由什么构成？</td>
      <td>训练数据、数据处理脚本、基础模型</td>
    </tr>
    <tr>
      <td>里面有没有已知问题？</td>
      <td>数据投毒、被污染的开源权重、有漏洞的推理运行时</td>
    </tr>
    <tr>
      <td>有没有合规风险？</td>
      <td>数据集里有没有个人信息、许可证能不能用、有没有做过风险评估</td>
    </tr>
    <tr>
      <td>代价有多大？</td>
      <td>训练、微调、推理各消耗多少能源</td>
    </tr>
  </tbody>
</table>

<p>把这些答案组织成一份清单，就是 AI-BOM。<strong>它的价值不在于「多一个文档」，而在于让上面那张表里的每一格都能被机器读出来。</strong> 人工写的模型卡是给人看的；AI-BOM 是给流水线、扫描器和策略引擎看的。</p>

<p>但有一个前提必须先说清楚：<strong>AI-BOM 不是一个标准，它现在是三套并行的东西。</strong></p>

<ol>
  <li><strong>SPDX 3.0.1 的 AI profile 与 Dataset profile</strong> —— 已经发布的正式规范，Linux Foundation 托管。</li>
  <li><strong>CycloneDX 1.6 / 1.7 里的模型与数据组件</strong> —— 已经发布的正式规范，OWASP 基金会托管，已进 ECMA 标准化。</li>
  <li><strong>OWASP AIBOM 项目自己的格式</strong> —— 孵化中的工作，格式规范<strong>尚未发布</strong>。</li>
</ol>

<p>下面先把前两套的字段讲清楚，再讲第三套现在在做什么。</p>

<h2 id="二spdx-301把-ai-做成两个独立的-profile">二、SPDX 3.0.1：把 AI 做成两个独立的 profile</h2>

<h3 id="21-为什么-30-是一次重写而不是加字段">2.1 为什么 3.0 是一次重写，而不是加字段</h3>

<p>SPDX 2.x 的数据模型是「扁平的 Package」：一个包有名字、版本、许可证、哈希，组件之间靠一小撮关系类型连起来。这套模型描述源代码和二进制很好用，但<strong>没有地方放「这个模型是怎么训出来的」「这份数据是怎么收集的」</strong>——它没有为「模型」和「数据集」准备过位置。</p>

<p>SPDX 3.0 的做法不是加字段，而是<strong>换骨架</strong>：把数据模型改成「带类型的元素 + 关系」，然后按用途切成若干个 <strong>profile</strong>。当前规范里的 profile 包括 Core、Software、Security、Licensing、Dataset、<strong>AI</strong>、Build、Lite、Extension。AI 相关的是两个：</p>

<ul>
  <li><strong>AI profile</strong> —— 描述模型（和以模型为交付物的 AI 系统）。</li>
  <li><strong>Dataset profile</strong> —— 描述数据集。</li>
</ul>

<p>3.0 于 2024 年 4 月 16 日由 Linux Foundation 发布（北美开源峰会期间），3.0.1 是其后的修订版，也是当前规范站上的默认版本。</p>

<h3 id="22-ai-profileaipackage-的-21-个属性">2.2 AI profile：<code class="language-plaintext highlighter-rouge">AIPackage</code> 的 21 个属性</h3>

<p>AI profile 的核心类是 <code class="language-plaintext highlighter-rouge">AIPackage</code>。它的属性可以按用途分成六组：</p>

<p><strong>模型身份</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">typeOfModel</code> —— 模型类型（例如「梯度提升树」这一类描述）。</li>
  <li><code class="language-plaintext highlighter-rouge">domain</code> —— 适用领域。</li>
  <li><code class="language-plaintext highlighter-rouge">autonomyType</code> —— 自主程度。</li>
</ul>

<p><strong>训练过程</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">informationAboutTraining</code> —— 训练相关的自由描述。</li>
  <li><code class="language-plaintext highlighter-rouge">hyperparameter</code> —— 超参数。</li>
  <li><code class="language-plaintext highlighter-rouge">modelDataPreprocessing</code> —— 数据预处理方式。</li>
  <li><code class="language-plaintext highlighter-rouge">informationAboutApplication</code> —— 使用场景相关的信息。</li>
</ul>

<p><strong>数据与合规</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">useSensitivePersonalInformation</code> —— 是否使用了敏感个人信息。</li>
</ul>

<p><strong>评估与可解释</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">metric</code> —— 评估指标。</li>
  <li><code class="language-plaintext highlighter-rouge">metricDecisionThreshold</code> —— 指标的判定阈值。</li>
  <li><code class="language-plaintext highlighter-rouge">modelExplainability</code> —— 可解释性说明。</li>
  <li><code class="language-plaintext highlighter-rouge">limitation</code> —— 已知局限。</li>
</ul>

<p><strong>风险与标准符合性</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">safetyRiskAssessment</code> —— 安全风险评估结论，对应一个风险等级词表。</li>
  <li><code class="language-plaintext highlighter-rouge">standardCompliance</code> —— 声明符合哪些标准。</li>
</ul>

<p><strong>能耗</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">energyConsumption</code> —— 总量，配套 <code class="language-plaintext highlighter-rouge">energyQuantity</code> 与 <code class="language-plaintext highlighter-rouge">energyUnit</code>。</li>
  <li><code class="language-plaintext highlighter-rouge">trainingEnergyConsumption</code> —— 训练环节能耗。</li>
  <li><code class="language-plaintext highlighter-rouge">finetuningEnergyConsumption</code> —— 微调环节能耗。</li>
  <li><code class="language-plaintext highlighter-rouge">inferenceEnergyConsumption</code> —— 推理环节能耗。</li>
</ul>

<p>把训练、微调、推理的能耗拆成三个独立属性，是这份规范里最有意思的一处设计：<strong>它承认「一个模型」在不同环节的代价差异极大</strong>，只报一个总数会把这件事抹平。</p>

<p>配套的类还有 <code class="language-plaintext highlighter-rouge">EnergyConsumption</code> 与 <code class="language-plaintext highlighter-rouge">EnergyConsumptionDescription</code>，配套的词表有 <code class="language-plaintext highlighter-rouge">EnergyUnitType</code> 与 <code class="language-plaintext highlighter-rouge">SafetyRiskAssessmentType</code>。</p>

<h3 id="23-dataset-profiledatasetpackage-的-15-个属性">2.3 Dataset profile：<code class="language-plaintext highlighter-rouge">DatasetPackage</code> 的 15 个属性</h3>

<p>数据集侧是 <code class="language-plaintext highlighter-rouge">DatasetPackage</code>，属性分三类：</p>

<p><strong>数据本身</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">datasetType</code>、<code class="language-plaintext highlighter-rouge">datasetSize</code>、<code class="language-plaintext highlighter-rouge">datasetNoise</code> —— 类型、规模、噪声情况。</li>
  <li><code class="language-plaintext highlighter-rouge">datasetAvailability</code> —— 可得性（对外公开还是内部受限）。</li>
  <li><code class="language-plaintext highlighter-rouge">datasetUpdateMechanism</code> —— 更新机制。</li>
</ul>

<p><strong>数据是怎么来的</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">dataCollectionProcess</code> —— 收集过程。</li>
  <li><code class="language-plaintext highlighter-rouge">dataPreprocessing</code> —— 预处理方式。</li>
  <li><code class="language-plaintext highlighter-rouge">anonymizationMethodUsed</code> —— 用了哪种去标识方法。</li>
</ul>

<p><strong>数据能用来做什么</strong></p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">intendedUse</code> —— 预期用途。</li>
  <li><code class="language-plaintext highlighter-rouge">knownBias</code> —— 已知偏差。</li>
  <li><code class="language-plaintext highlighter-rouge">hasSensitivePersonalInformation</code> —— 是否含敏感个人信息。</li>
  <li><code class="language-plaintext highlighter-rouge">confidentialityLevel</code> —— 机密级别。</li>
  <li><code class="language-plaintext highlighter-rouge">sensor</code> —— 采集设备相关（传感器数据场景）。</li>
</ul>

<p>这组字段基本就是一次合规审计会问的清单。<strong><code class="language-plaintext highlighter-rouge">hasSensitivePersonalInformation</code> 和 <code class="language-plaintext highlighter-rouge">confidentialityLevel</code> 同时出现在模型侧和数据侧，是有意的</strong>——模型继承了数据的属性，登记时两边都要填。</p>

<h3 id="24-关系清单的价值在图上不在条目上">2.4 关系：清单的价值在图上，不在条目上</h3>

<p>SPDX 3.0 的关系类型是一张固定词表。与 AI 相关的几条：</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">trainedOn</code> —— 「from 元素在 to 元素上训练过」。这就是「模型 ← 数据集」这条边。</li>
  <li><code class="language-plaintext highlighter-rouge">testedOn</code> —— 「from 元素在 to 元素上被测试过」。测试集和训练集分开记，靠这条边区分。</li>
  <li><code class="language-plaintext highlighter-rouge">hasTest</code> —— 测试制品。</li>
  <li><code class="language-plaintext highlighter-rouge">hasDataFile</code> —— 「from 元素把 to 元素当作数据文件」。这一条的说明里明确写了：<strong>数据文件可以是「一个 AI 模型文件」</strong>，并且特别提示：训练数据集、测试数据集、配置数据、构建输入输出数据，应该优先用 <code class="language-plaintext highlighter-rouge">trainedOn</code>、<code class="language-plaintext highlighter-rouge">testedOn</code>、<code class="language-plaintext highlighter-rouge">hasTest</code>、<code class="language-plaintext highlighter-rouge">configures</code>、<code class="language-plaintext highlighter-rouge">hasInput</code>、<code class="language-plaintext highlighter-rouge">hasOutput</code> 这几条更精确的关系，而不是笼统地用 <code class="language-plaintext highlighter-rouge">hasDataFile</code>。</li>
</ul>

<p>这个区分很关键：<strong>「模型里引用了一个文件」和「模型是用这个数据集训出来的」是两种完全不同的断言</strong>，混在一个关系类型里，溯源就断了。</p>

<p>其余常用关系还有 <code class="language-plaintext highlighter-rouge">contains</code>、<code class="language-plaintext highlighter-rouge">dependsOn</code>、<code class="language-plaintext highlighter-rouge">generates</code>、<code class="language-plaintext highlighter-rouge">usesTool</code>、<code class="language-plaintext highlighter-rouge">packagedBy</code>、<code class="language-plaintext highlighter-rouge">invokedBy</code> 等，都是 Core profile 里的通用关系。</p>

<h3 id="25-一条硬约束许可证不能空着">2.5 一条硬约束：许可证不能空着</h3>

<p>AI profile 对一致性（conformance）有明确要求：</p>

<blockquote>
  <p>对于每一个 <code class="language-plaintext highlighter-rouge">AIPackage</code>，必须恰好存在一个类型为 <code class="language-plaintext highlighter-rouge">hasConcludedLicense</code> 的 <code class="language-plaintext highlighter-rouge">/Core/Relationship</code>，其 <code class="language-plaintext highlighter-rouge">from</code> 是该元素、<code class="language-plaintext highlighter-rouge">to</code> 是 <code class="language-plaintext highlighter-rouge">/SimpleLicensing/AnyLicenseInfo</code>；并且必须恰好存在一个类型为 <code class="language-plaintext highlighter-rouge">hasDeclaredLicense</code> 的同类关系。</p>
</blockquote>

<p>翻译过来就是：<strong>模型清单里，「声明的许可证」和「结论许可证」两个字段都得填，缺一个就不符合 AI profile。</strong></p>

<p><code class="language-plaintext highlighter-rouge">hasDeclaredLicense</code> 的语义是「由工具自动检测得出」；<code class="language-plaintext highlighter-rouge">hasConcludedLicense</code> 的语义是「清单作者人工判定的结论」。两者分开，是为了能表达「工具检出来是 MIT，但作者认为有额外限制」这种情况。</p>

<p>这条约束的实际影响是：<strong>模型权重和数据集的许可证不是「可选信息」，它是一致性的前提。</strong> 在一个还在争论「开源模型能不能商用」的时期，这条约束比任何一条建议都更能说明 SPDX 3.0 的取向。</p>

<h3 id="26-序列化">2.6 序列化</h3>

<p>SPDX 3.0 支持 JSON-LD、RDF/Turtle，以及旧版的 tag-value 与表格格式；每个元素带全局唯一的 IRI，所以一份 Build profile 的文档可以引用一份 AI profile 文档里的同一个制品而不必重复元数据。AI profile 的命名空间是 <code class="language-plaintext highlighter-rouge">https://spdx.org/rdf/3.0.1/terms/AI</code>。</p>

<h2 id="三cyclonedx-16--17把模型卡挂在组件上">三、CycloneDX 1.6 / 1.7：把模型卡挂在组件上</h2>

<h3 id="31-思路不动骨架加类型和加字段">3.1 思路：不动骨架，加类型和加字段</h3>

<p>CycloneDX 的数据模型一直是「组件（component）+ 服务 + 依赖关系」。它没有像 SPDX 3.0 那样重写骨架，而是<strong>在组件类型枚举里加了两个值，再给组件加了一个可选的子对象</strong>。</p>

<p>CycloneDX 1.6（2024 年 4 月）把组件类型扩展到了这些：</p>

<p><code class="language-plaintext highlighter-rouge">application</code>、<code class="language-plaintext highlighter-rouge">framework</code>、<code class="language-plaintext highlighter-rouge">library</code>、<code class="language-plaintext highlighter-rouge">container</code>、<code class="language-plaintext highlighter-rouge">platform</code>、<code class="language-plaintext highlighter-rouge">operating-system</code>、<code class="language-plaintext highlighter-rouge">device</code>、<code class="language-plaintext highlighter-rouge">device-driver</code>、<code class="language-plaintext highlighter-rouge">firmware</code>、<code class="language-plaintext highlighter-rouge">file</code>、<strong><code class="language-plaintext highlighter-rouge">machine-learning-model</code></strong>、<strong><code class="language-plaintext highlighter-rouge">data</code></strong>、<code class="language-plaintext highlighter-rouge">cryptographic-asset</code>。</p>

<p>也就是说，<strong>模型是 <code class="language-plaintext highlighter-rouge">machine-learning-model</code> 类型的组件，数据集是 <code class="language-plaintext highlighter-rouge">data</code> 类型的组件</strong>——这是理解 CycloneDX 路线最关键的一句。</p>

<h3 id="32-modelcard组件上的模型卡">3.2 <code class="language-plaintext highlighter-rouge">modelCard</code>：组件上的模型卡</h3>

<p><code class="language-plaintext highlighter-rouge">machine-learning-model</code> 类型的组件可以挂一个 <code class="language-plaintext highlighter-rouge">modelCard</code> 对象，分三块：</p>

<p><strong><code class="language-plaintext highlighter-rouge">modelParameters</code></strong> —— 模型本身的参数</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">approach</code> —— 方法（监督/自监督等）。</li>
  <li><code class="language-plaintext highlighter-rouge">task</code> —— 任务类型。</li>
  <li><code class="language-plaintext highlighter-rouge">architectureFamily</code> —— 架构族。</li>
  <li><code class="language-plaintext highlighter-rouge">modelArchitecture</code> —— 具体架构。</li>
  <li><code class="language-plaintext highlighter-rouge">datasets</code> —— 用到的数据集（指向 BOM 里的其他组件）。</li>
  <li><code class="language-plaintext highlighter-rouge">inputs</code> / <code class="language-plaintext highlighter-rouge">outputs</code> —— 输入输出规格。</li>
</ul>

<p><strong><code class="language-plaintext highlighter-rouge">quantitativeAnalysis</code></strong> —— 量化分析</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">performanceMetrics</code> —— 性能指标。</li>
  <li><code class="language-plaintext highlighter-rouge">graphics</code> —— 图表附件。</li>
</ul>

<p><strong><code class="language-plaintext highlighter-rouge">considerations</code></strong> —— 使用考量</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">users</code> —— 适用人群。</li>
  <li><code class="language-plaintext highlighter-rouge">useCases</code> —— 适用场景。</li>
  <li><code class="language-plaintext highlighter-rouge">technicalLimitations</code> —— 技术局限。</li>
  <li><code class="language-plaintext highlighter-rouge">performanceTradeoffs</code> —— 性能取舍。</li>
  <li><code class="language-plaintext highlighter-rouge">ethicalConsiderations</code> —— 伦理考量。</li>
  <li><code class="language-plaintext highlighter-rouge">environmentalConsiderations</code> —— 环境考量。</li>
  <li><code class="language-plaintext highlighter-rouge">fairnessAssessments</code> —— 公平性评估。</li>
</ul>

<p>另外 <code class="language-plaintext highlighter-rouge">modelCard</code> 还能挂一组 <code class="language-plaintext highlighter-rouge">properties</code>（名值对），用来放标准没有覆盖但你想记的字段——这是 CycloneDX 一贯的扩展方式。</p>

<p>对照一下就会发现：<strong><code class="language-plaintext highlighter-rouge">modelCard.considerations</code> 和 SPDX <code class="language-plaintext highlighter-rouge">AIPackage</code> 的 <code class="language-plaintext highlighter-rouge">limitation</code> / <code class="language-plaintext highlighter-rouge">safetyRiskAssessment</code> / <code class="language-plaintext highlighter-rouge">standardCompliance</code> 覆盖的是同一片地面，但切分方式不同。</strong> CycloneDX 按「读者想知道什么」切，SPDX 按「合规要证明什么」切。</p>

<h3 id="33-componentdata数据集挂在哪">3.3 <code class="language-plaintext highlighter-rouge">componentData</code>：数据集挂在哪</h3>

<p>数据集侧对应的是 <code class="language-plaintext highlighter-rouge">componentData</code>，它带这些字段：</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">type</code> —— 取值是 <code class="language-plaintext highlighter-rouge">source-code</code>、<code class="language-plaintext highlighter-rouge">configuration</code>、<strong><code class="language-plaintext highlighter-rouge">dataset</code></strong>、<code class="language-plaintext highlighter-rouge">definition</code>、<code class="language-plaintext highlighter-rouge">other</code>。</li>
  <li><code class="language-plaintext highlighter-rouge">name</code>、<code class="language-plaintext highlighter-rouge">contents</code>、<code class="language-plaintext highlighter-rouge">description</code>、<code class="language-plaintext highlighter-rouge">bom-ref</code>。</li>
  <li><code class="language-plaintext highlighter-rouge">classification</code> —— 数据分类。</li>
  <li><code class="language-plaintext highlighter-rouge">sensitiveData</code> —— 是否敏感数据。</li>
  <li><code class="language-plaintext highlighter-rouge">graphics</code> —— 图表。</li>
  <li><strong><code class="language-plaintext highlighter-rouge">governance</code></strong> —— 治理信息（对应 <code class="language-plaintext highlighter-rouge">dataGovernance</code> / <code class="language-plaintext highlighter-rouge">dataGovernanceResponsibleParty</code> / <code class="language-plaintext highlighter-rouge">dataClassification</code> 这几个定义）。</li>
</ul>

<p>注意 CycloneDX 在这里比 SPDX 多了一层：<strong><code class="language-plaintext highlighter-rouge">governance</code> 把「谁负责这份数据、怎么管」显式放进格式里</strong>。SPDX 把治理信息放在 <code class="language-plaintext highlighter-rouge">DatasetPackage</code> 的 <code class="language-plaintext highlighter-rouge">confidentialityLevel</code>、<code class="language-plaintext highlighter-rouge">intendedUse</code> 这些属性上；CycloneDX 把它做成了一个可以整体挂载的对象。</p>

<h3 id="34-17-新增的出处声明">3.4 1.7 新增的「出处声明」</h3>

<p>CycloneDX 1.7 于 2025 年 10 月 21 日由 OWASP 基金会发布。这次发布的重点是三块：</p>

<ul>
  <li><strong>CBOM 增强</strong> —— 标准化了密码算法族清单、椭圆曲线清单，这两份清单可以脱离 CycloneDX 独立使用。</li>
  <li><strong>出处声明（Citations）</strong> —— 这是最值得注意的一块。官方公告里的原话是：SBOM 很少是一步生成的，它们经常被多个工具加工、在流水线里被转换、或者从零散数据里慢慢拼起来；<strong>如果没有恰当的归属，信息从哪来、怎么生成的、谁负责，就越来越难追踪</strong>。出处声明提供的是一个正式机制，用来声明信息的来源、生成方式与责任方，让每一步加工、每一个外部引用、每一次工具贡献都可追溯、可审计。</li>
  <li><strong>知识产权透明度</strong> —— 首次支持专利与专利族，让 BOM 能表达除组件之外的知识产权权利与义务。</li>
</ul>

<p>1.7 还把 <code class="language-plaintext highlighter-rouge">formulation</code> 的适用范围扩大了（从「组件和服务」扩到「BOM 内任何可引用对象」），支持带版本范围的外部组件、多个 SPDX 许可证表达式并存的写法、许可证表达式的细节与属性、外部引用上的 <code class="language-plaintext highlighter-rouge">properties</code>，以及用 TLP（交通灯协议）在 metadata 里标注分发限制。</p>

<p>后续的 1.7.1（2026 年 6 月）与 1.7.2（2026 年 9 月）都是修 bug 的小版本；1.6.2 与 1.5.1 是同期回移到旧版本线的修复版本。</p>

<h3 id="35-标准化ecma-424">3.5 标准化：ECMA-424</h3>

<p>CycloneDX 1.6 在 2024 年 6 月被 Ecma International 批准为 <strong>ECMA-424 第 1 版</strong>；按 1.7 发布公告的说法，1.7 预计在 2025 年 12 月被批准为 ECMA-424 第 2 版。</p>

<p>这一步是 AI-BOM 从「社区格式」变成「国际标准格式」的关键节点。<strong>如果一个格式要进采购清单、要进监管口径，它必须有一个稳定的、有版本治理的组织在背后。</strong></p>

<h2 id="四两套格式怎么选">四、两套格式怎么选</h2>

<table>
  <thead>
    <tr>
      <th>维度</th>
      <th>SPDX 3.0.1</th>
      <th>CycloneDX 1.6 / 1.7</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>托管方</td>
      <td>Linux Foundation</td>
      <td>OWASP 基金会（Ecma TC54）</td>
    </tr>
    <tr>
      <td>标准化状态</td>
      <td>社区规范</td>
      <td>ECMA-424 国际标准</td>
    </tr>
    <tr>
      <td>模型怎么表示</td>
      <td>AI profile 里的 <code class="language-plaintext highlighter-rouge">AIPackage</code></td>
      <td><code class="language-plaintext highlighter-rouge">machine-learning-model</code> 类型的组件 + <code class="language-plaintext highlighter-rouge">modelCard</code></td>
    </tr>
    <tr>
      <td>数据集怎么表示</td>
      <td>Dataset profile 里的 <code class="language-plaintext highlighter-rouge">DatasetPackage</code></td>
      <td><code class="language-plaintext highlighter-rouge">data</code> 类型组件 + <code class="language-plaintext highlighter-rouge">componentData</code></td>
    </tr>
    <tr>
      <td>关系怎么表达</td>
      <td>全局关系词表（<code class="language-plaintext highlighter-rouge">trainedOn</code>、<code class="language-plaintext highlighter-rouge">testedOn</code> 等）</td>
      <td>组件依赖图 + <code class="language-plaintext highlighter-rouge">modelCard.modelParameters.datasets</code></td>
    </tr>
    <tr>
      <td>许可证约束</td>
      <td><strong>硬约束</strong>：每个 <code class="language-plaintext highlighter-rouge">AIPackage</code> 必须有声明和结论两个许可证关系</td>
      <td>走 CycloneDX 通用的组件许可证机制</td>
    </tr>
    <tr>
      <td>能耗</td>
      <td>训练/微调/推理分别有字段</td>
      <td>需自行扩展</td>
    </tr>
    <tr>
      <td>序列化</td>
      <td>JSON-LD、RDF、tag-value、表格</td>
      <td>JSON、XML、Protobuf</td>
    </tr>
  </tbody>
</table>

<p>选哪套，不看「哪个更强」，看三件事：</p>

<ol>
  <li><strong>你的流水线现在出什么。</strong> 已经在出 CycloneDX 的团队，用 1.6 的 <code class="language-plaintext highlighter-rouge">machine-learning-model</code> 加 <code class="language-plaintext highlighter-rouge">modelCard</code> 是最短路径；已经在用 SPDX 的团队，走 AI profile 才有意义。</li>
  <li><strong>你要不要许可证这层硬约束。</strong> SPDX 的 AI profile 把许可证变成了一致性前提，这是 SPDX 3.0 相对 CycloneDX 的一处实质性收紧。</li>
  <li><strong>你要不要图。</strong> SPDX 的关系是全局词表、跨 profile 自由连；CycloneDX 的依赖关系在组件图里更直观，但模型与数据集之间的边要通过 <code class="language-plaintext highlighter-rouge">modelCard</code> 里的引用来表达。</li>
</ol>

<p><strong>这两套不是二选一。</strong> 生态里常见的状态是：内部用 CycloneDX 跑流水线，对外交付时按需要转成 SPDX。但转换是有成本的，字段不是一一对应（这是选型时要提前确认的事，别等交付前一天才发现）。</p>

<h2 id="五官方组织在推什么">五、官方组织在推什么</h2>

<p>这一节是本文里最需要「有出处」的部分，因为「在推什么」变化很快。</p>

<h3 id="51-owasp标准化--指南--工具生态">5.1 OWASP：标准化 + 指南 + 工具生态</h3>

<p>OWASP 基金会在 CycloneDX 1.7 发布公告里给出的动作是三件：</p>

<ol>
  <li><strong>ECMA 标准化</strong>（见 3.5）。</li>
  <li><strong>三本权威指南同时发布</strong>：《Authoritative Guide to SBOM》第三版、《Authoritative Guide to CBOM》第二版，以及<strong>《Authoritative Guide to MBOM》第一版</strong>。</li>
  <li>官方称支持 CycloneDX 的工具<strong>超过 250 个</strong>。</li>
</ol>

<p>这里有个<strong>很容易搞混的缩写</strong>，值得单独提醒：<strong>MBOM 是「模型物料清单」，不是 AI-BOM</strong>。两者都在「AI 相关物料清单」这个话题里，但不是同一个东西。</p>

<h3 id="52-linux-foundationspdx-的-profile-化">5.2 Linux Foundation：SPDX 的 profile 化</h3>

<p>SPDX 3.0 的最大变化就是第一节说的 profile 化——把原来一个扁平的模型拆成按用途划分的 profile，让不同角色只解析自己关心的部分。这是 SPDX 在 AI 时代的核心动作：<strong>它没有新增一个「AI 专用格式」，而是让 AI 成为主数据模型里的一等公民。</strong></p>

<h3 id="53-owasp-aibom-项目自己定义一份格式">5.3 OWASP AIBOM 项目：自己定义一份格式</h3>

<p>OWASP 下面有一个 <strong>AI Bill of Materials（AIBOM）项目</strong>，定位是 <strong>Incubator Project（孵化项目）</strong>，项目页标注的版本是 <strong>0.8</strong>。项目站已从 <code class="language-plaintext highlighter-rouge">owasp.github.io/owasp-aibom/</code> 迁到 <strong><a href="https://owaspaibom.org/">https://owaspaibom.org/</a></strong>，仓库在 <a href="https://github.com/OWASP/www-project-aibom">https://github.com/OWASP/www-project-aibom</a>。</p>

<p>它把工作拆成 <strong>10 条工作流（workstreams）</strong>，其中和「格式」直接相关的几条：</p>

<ul>
  <li><strong>Formats</strong> —— 负责 AI-BOM 的 schema 设计与演进，格式规范覆盖 JSON、XML、YAML，并处理版本兼容与互操作。</li>
  <li><strong>Tools</strong> —— 生成、校验、分析 AIBOM 的工具，含与既有 DevOps/MLOps 工具链的集成。</li>
  <li><strong>Prerequisites</strong> —— 评估落地 AIBOM 的前置条件。<strong>这一条工作流的公开进展里有一句话值得单独拎出来</strong>：该团队正在评估现有的 AI 物料清单标准，<strong>明确点名 CycloneDX 1.6 与 SPDX 3.0</strong>，判断它们对 AI 系统需求的覆盖程度，以及是否需要在数据集版本管理、微调参数等领域做扩展。</li>
  <li><strong>Policy</strong> —— 与监管机构打交道，做合规映射与政策建议。</li>
  <li><strong>Integrity/Quality</strong> —— 数据质量标准、校验与验证框架、信任与证明机制、审计与合规流程。</li>
</ul>

<p>项目的路线图分五个阶段，其中前两阶段的发布目标都定在 <strong>2026 年 2 月</strong>：阶段一是《AIBOM Operationalizing Guide and Best Practices》，阶段二是 <strong>AIBOM 格式的评审与标准化</strong>；阶段三的开发工具目标在 2026 年 3 月。</p>

<p>社区侧的动作是常规的：OWASP Slack 上的 <code class="language-plaintext highlighter-rouge">#project-aibom-community</code> 频道与按工作流分的频道、YouTube 频道、会议与线下活动。</p>

<h3 id="54-一个必须说清楚的事实">5.4 一个必须说清楚的事实</h3>

<p><strong>截至现在，OWASP AIBOM 项目仓库里还没有发布的格式规范文件。</strong> 仓库当前的内容是站点骨架：首页、关于信息、路线图、指导、新闻、活动、赞助、加入方式、工作流说明等几个页面文件，以及图片资源；规范本身（schema、示例、字段定义）尚未进仓库。<code class="language-plaintext highlighter-rouge">info.md</code> 里标注的 0.8 是<strong>项目版本</strong>，不是已发布的规范版本。</p>

<p>这条事实很重要，因为它决定了现在该怎么做：</p>

<ul>
  <li><strong>要今天就产出一份 AI-BOM</strong>，只能用已经发布的规范——SPDX 3.0.1 的 AI/Dataset profile，或 CycloneDX 1.6/1.7。</li>
  <li><strong>要跟进 AIBOM 自己的格式</strong>，现在能做的是参与工作流、跟踪路线图，而不是照着一个还不存在的 schema 写代码。</li>
</ul>

<h3 id="55-owasp-genaiaibom-生成器">5.5 OWASP GenAI：AIBOM 生成器</h3>

<p>OWASP GenAI Security Project 下面有一个 <strong>AI Bill of Materials（AIBOM）Initiative</strong>，目标是让组织能看清自己 AI 系统的模型组件。</p>

<p>这个项目在 <strong>RSAC 2025</strong> 上发布过一个开源工具，能为托管在 Hugging Face 上的模型生成 AI 软件物料清单；项目自己在 2025 年 12 月的公告里说，这个工具后来搬进了 OWASP（公告标题是「AIBOM Generator 的旅程与它在 OWASP 的新家」）。</p>

<p>OWASP GenAI Security Project 在 2026 年 3 月的公告里提到，社群规模已超过 2.5 万成员，并在 RSA 2026 之前扩充了 AI 安全框架与配套资源。</p>

<h2 id="六现在能做什么做不到什么">六、现在能做什么，做不到什么</h2>

<h3 id="61-现在就能做的">6.1 现在就能做的</h3>

<ol>
  <li><strong>从模型卡倒着填。</strong> 你的模型卡（model card）里已有的信息，大部分能直接映射到 CycloneDX 的 <code class="language-plaintext highlighter-rouge">modelCard</code> 或 SPDX 的 <code class="language-plaintext highlighter-rouge">AIPackage</code>。这是投入产出比最高的一条路。</li>
  <li><strong>先在一两个模型上试。</strong> 不要一上来就要求全公司所有模型都登记。先挑一个要对外交付的、一个要过合规的，把字段填到 80% 以上，看看缺的那几格能不能补上。</li>
  <li><strong>数据集先登记来源和许可。</strong> <code class="language-plaintext highlighter-rouge">datasetType</code>、<code class="language-plaintext highlighter-rouge">datasetAvailability</code>、<code class="language-plaintext highlighter-rouge">hasSensitivePersonalInformation</code>、<code class="language-plaintext highlighter-rouge">confidentialityLevel</code> 这几格，价值最高、也最容易填。</li>
  <li><strong>给产物算哈希。</strong> 权重文件、容器镜像的哈希是 AI-BOM 里最容易被自动化、也最容易验证的部分。<code class="language-plaintext highlighter-rouge">safetensors</code> 这类只存张量不存代码的格式，在这一步能省掉很多麻烦。</li>
</ol>

<h3 id="62-现在做不到的">6.2 现在做不到的</h3>

<ol>
  <li><strong>一份清单不等于一个保证。</strong> AI-BOM 记录的是<strong>既有事实</strong>，它不产生任何保证。「清单里有这个模型」和「这个模型是可信的」是两回事——后者要靠签名、准入策略、评审流程来保证。</li>
  <li><strong>填不全的字段就是填不全。</strong> 尤其是在开源权重上做微调的场景：基座模型的原始训练信息你多半不知道，<code class="language-plaintext highlighter-rouge">informationAboutTraining</code> 这一格只能留空或者标「未知」。<strong>这恰恰是规范的价值</strong>——它把「你不知道」这件事显式记下来，而不是让你悄悄不写。</li>
  <li><strong>跨格式转换不是免费的。</strong> 两种格式的字段不是一一对应，转换会丢信息。</li>
</ol>

<h3 id="63-我的建议">6.3 我的建议</h3>

<p>如果现在要动手：</p>

<ul>
  <li><strong>先用 CycloneDX 1.6</strong>，因为大部分团队的 CI 已经在出 CycloneDX，模型作为 <code class="language-plaintext highlighter-rouge">machine-learning-model</code> 组件加进去是增量改动。</li>
  <li><strong>同时把许可证这一格补上。</strong> 这是 SPDX 的一致性硬要求，也是将来要过合规时最先被问到的。</li>
  <li><strong>把 AI-BOM 挂在「模型上线」这个动作上，而不是挂在「训练完成」上。</strong> 因为训练产物和交付物经常不是一回事——中间可能还有微调、量化、蒸馏。挂在上线动作上，才拿得到最终交付物的那份清单。</li>
</ul>

<h2 id="小结">小结</h2>

<p>AI-BOM 现在有三套并行的格式：<strong>SPDX 3.0.1 的 AI 与 Dataset 两个 profile</strong>（已发布的规范，许可证是硬约束，能耗拆成训练/微调/推理三段），<strong>CycloneDX 1.6/1.7 的模型组件与模型卡</strong>（已进 ECMA-424，1.7 新增了出处声明），以及 <strong>OWASP AIBOM 项目自己规划的格式</strong>（孵化中，规范尚未发布）。</p>

<p>选哪套取决于你的流水线已经在出什么、要不要许可证那层硬约束、要不要跨制品的图。</p>

<p>官方在推的力度是清楚的：OWASP 走 ECMA 标准化加权威指南加工具生态；Linux Foundation 让 AI 成为 SPDX 主模型的一等公民；OWASP AIBOM 项目用 10 条工作流从格式、工具、政策、完整性四个方向同时推。</p>

<p>而最该记住的一句是：<strong>清单只记录事实，不产生保证。</strong> 想让一份 AI-BOM 真的有用，得先想清楚它要回答谁的问题——是审计、是准入策略、还是下一次事故复盘。答案不同，要记的字段和更新的频率都不同。</p>

<h2 id="本文引用的来源">本文引用的来源</h2>

<table>
  <thead>
    <tr>
      <th>结论</th>
      <th>出处</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>SPDX 3.0 于 2024-04-16 由 Linux Foundation 发布；3.0 引入 profile 化数据模型</td>
      <td><a href="https://www.linuxfoundation.org/press/spdx-3-revolutionizes-software-management-in-systems-with-enhanced-functionality-and-streamlined-use-cases">Linux Foundation 新闻稿：SPDX 3.0 Revolutionizes Software Management</a></td>
    </tr>
    <tr>
      <td>SPDX 3.0.1 的 profile 列表、命名空间、AI profile 的一致性要求（<code class="language-plaintext highlighter-rouge">hasDeclaredLicense</code> 与 <code class="language-plaintext highlighter-rouge">hasConcludedLicense</code> 各恰好一个）</td>
      <td><a href="https://spdx.github.io/spdx-spec/v3.0.1/model/AI/AI/">SPDX 3.0.1 规范 · AI profile</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">AIPackage</code> 的 21 个属性（身份、训练、评估、风险、能耗）与两个词表</td>
      <td><a href="https://spdx.github.io/spdx-spec/v3.0.1/model/AI/">SPDX 3.0.1 规范 · AI profile 目录</a>、<a href="https://spdx.github.io/spdx-spec/v3.0.1/model/AI/Classes/AIPackage/">AI 类</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">DatasetPackage</code> 的 15 个属性与三个词表</td>
      <td><a href="https://spdx.github.io/spdx-spec/v3.0.1/model/Dataset/">SPDX 3.0.1 规范 · Dataset profile 目录</a></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">trainedOn</code>、<code class="language-plaintext highlighter-rouge">testedOn</code>、<code class="language-plaintext highlighter-rouge">hasDataFile</code>（说明里明确含「an AI model file」）等关系类型的官方定义</td>
      <td><a href="https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Vocabularies/RelationshipType/">SPDX 3.0.1 规范 · RelationshipType 词表</a></td>
    </tr>
    <tr>
      <td>CycloneDX 1.6 的组件类型枚举含 <code class="language-plaintext highlighter-rouge">machine-learning-model</code> 与 <code class="language-plaintext highlighter-rouge">data</code>；<code class="language-plaintext highlighter-rouge">modelCard</code>、<code class="language-plaintext highlighter-rouge">componentData</code> 的字段结构</td>
      <td><a href="https://github.com/CycloneDX/specification/blob/master/schema/bom-1.6.schema.json">CycloneDX 1.6 JSON Schema</a></td>
    </tr>
    <tr>
      <td>CycloneDX 1.7 于 2025-10-21 发布；出处声明、专利与知识产权透明度、TLP；ECMA-424 第 1/2 版的批准节奏；三本权威指南（含 MBOM）；250+ 工具</td>
      <td><a href="https://cyclonedx.org/news/cyclonedx-v1.7-released/">CycloneDX v1.7 发布公告</a></td>
    </tr>
    <tr>
      <td>CycloneDX 1.7.1 / 1.7.2 / 1.6.2 / 1.5.1 的发布时间与内容</td>
      <td><a href="https://github.com/CycloneDX/specification/releases">CycloneDX 规范仓库发布列表</a></td>
    </tr>
    <tr>
      <td>OWASP AIBOM 项目是孵化项目、版本 0.8、10 条工作流、Formats 与 Prerequisites 工作流的职责、对 CycloneDX 1.6 与 SPDX 3.0 的评估、五阶段路线图与时间点</td>
      <td><a href="https://github.com/OWASP/www-project-aibom">OWASP AIBOM 项目仓库</a>（<code class="language-plaintext highlighter-rouge">info.md</code>、<code class="language-plaintext highlighter-rouge">tab_workstreams.md</code>、<code class="language-plaintext highlighter-rouge">tab_guidance.md</code>、<code class="language-plaintext highlighter-rouge">tab_roadmap.md</code>）</td>
    </tr>
    <tr>
      <td>OWASP AIBOM 项目站已迁至 owaspaibom.org</td>
      <td><a href="https://github.com/OWASP/owasp-aibom">项目站迁移说明</a></td>
    </tr>
    <tr>
      <td>OWASP GenAI 的 AIBOM Initiative；RSAC 2025 发布的 AIBOM 生成器与后续并入 OWASP；社群规模</td>
      <td><a href="https://genai.owasp.org/owasp-aibom/">OWASP GenAI Security Project · AI Bill of Materials</a>、<a href="https://genai.owasp.org/2025/12/18/evolving-ai-transparency-the-journey-of-the-aibom-generator-and-its-new-home-at-owasp/">AIBOM 生成器公告</a>、<a href="https://genai.owasp.org/2026/03/17/owasp-genai-security-project-expands-ai-security-frameworks-ahead-of-rsa-2026-celebrates-continued-sponsor-support/">2026 年 3 月项目公告</a></td>
    </tr>
  </tbody>
</table>]]></content><author><name>maijun</name></author><category term="软件供应链安全" /><category term="AI 清单" /><category term="SBOM" /><category term="SPDX" /><summary type="html"><![CDATA[摘要：软件物料清单（SBOM）回答的是「这个软件用了哪些组件、哪些组件有已知漏洞」。AI 系统要回答一组平行的问题：模型是哪一版、用哪些数据训的、数据从哪来、里面有没有个人信息、做过什么风险评估、推理要多少能耗。AI-BOM（AI Bill of Materials，AI 物料清单） 就是承载这些答案的机器可读清单。 读完你会拿到三样东西：一是 AI-BOM 现在到底有几套格式——不是一个，而是三套并行，其中两套已经是正式规范，一套还在孵化；二是 SPDX 3.0.1 与 CycloneDX 1.6/1.7 分别怎么表示模型和数据集（按字段拆开讲，不是笼统地说「都能记」）；三是 官方组织在推什么——OWASP 的 ECMA 标准化、Linux Foundation 主导的 SPDX profile 化、OWASP AIBOM 项目自己的格式工作流，以及一件必须先说清的事：OWASP AIBOM 的格式规范目前还没有发布。 本文出现的每一个字段名、版本号和日期都取自规范原文或官方发布稿，文末逐条给了出处。]]></summary></entry><entry><title type="html">[AetherCode] AI Agent 的 hook：在模型动手之前，留一个能插手的口子</title><link href="https://maijun-sec.github.io/2026/12/02/hook-in-ai-agents/" rel="alternate" type="text/html" title="[AetherCode] AI Agent 的 hook：在模型动手之前，留一个能插手的口子" /><published>2026-12-02T08:30:00+08:00</published><updated>2026-12-02T08:30:00+08:00</updated><id>https://maijun-sec.github.io/2026/12/02/hook-in-ai-agents</id><content type="html" xml:base="https://maijun-sec.github.io/2026/12/02/hook-in-ai-agents/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：模型决定调某个工具之后、工具真正动手之前，是整个 agent 循环里唯一一段「你还能改主意」的窗口。hook 就是开在这个窗口上的口子——它让你看见模型想做什么，并且能说「不」，或者「换个做法」。</p>

  <p><strong>读完你会拿到三样东西</strong>：一是 hook 在业界已经收敛出来的形状（查了三家的官方文档：Claude Code、Cursor、OpenCode），包括它们各自的事件清单和三种做决定的方式；二是 <strong>AetherCode 的 hook 机制</strong>是怎么设计的，以及三个值得单独拿出来讲的设计选择；三是<strong>哪些场景该用 hook</strong>——用一个具体案例（git-ai 怎么用 hook 记录「哪几行是 AI 写的」）把判断标准讲清楚。</p>

  <p>第三节还会把 AetherCode 当前的状态摊开讲：<strong>哪些 hook 点真的接线了、哪些只是声明了</strong>，以及两个必须先说清的边界（hook 抛异常是 fail-open；hook 没有超时）。</p>
</blockquote>

<!--more-->

<h2 id="一hook-是什么业界已经收敛的形状">一、hook 是什么：业界已经收敛的形状</h2>

<p>先说结论，再给证据。</p>

<p><strong>hook 是「在 agent 生命周期的某个时刻，把控制权交给你一段代码」的机制。</strong> 你交出去的那段代码能拿到当时的数据，并且能返回一个决定：这个动作继续、换个参数继续、还是到此为止。</p>

<p>它的价值不在于「多一个回调」，而在于<strong>这个回调拿到的是结构化的数据</strong>（上游管这叫 payload）。这一点后面会展开——它是区分「玩具 hook」和「能写出通用逻辑的 hook」的分水岭。</p>

<h3 id="三家的官方口径">三家的官方口径</h3>

<p>这三家我都查了官方文档，不是凭印象。</p>

<p><strong>Claude Code</strong>（<code class="language-plaintext highlighter-rouge">code.claude.com/docs/en/hooks</code>）目前列了 <strong>34 个事件</strong>，官方把它们归成三种节奏：</p>

<table>
  <thead>
    <tr>
      <th>节奏</th>
      <th>事件</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>每会话一次</td>
      <td><code class="language-plaintext highlighter-rouge">SessionStart</code>、<code class="language-plaintext highlighter-rouge">SessionEnd</code></td>
    </tr>
    <tr>
      <td>每轮一次</td>
      <td><code class="language-plaintext highlighter-rouge">UserPromptSubmit</code>、<code class="language-plaintext highlighter-rouge">Stop</code>、<code class="language-plaintext highlighter-rouge">StopFailure</code></td>
    </tr>
    <tr>
      <td>每次工具调用</td>
      <td><code class="language-plaintext highlighter-rouge">PreToolUse</code>、<code class="language-plaintext highlighter-rouge">PostToolUse</code>、<code class="language-plaintext highlighter-rouge">PostToolUseFailure</code>、<code class="language-plaintext highlighter-rouge">PermissionRequest</code></td>
    </tr>
  </tbody>
</table>

<p>其余二十来个是更细的 hook 点：<code class="language-plaintext highlighter-rouge">PreCompact</code> / <code class="language-plaintext highlighter-rouge">PostCompact</code>（上下文压缩前后）、<code class="language-plaintext highlighter-rouge">SubagentStart</code> / <code class="language-plaintext highlighter-rouge">SubagentStop</code>（子代理）、<code class="language-plaintext highlighter-rouge">PreModelSwitch</code>（换模型前）、<code class="language-plaintext highlighter-rouge">FileChanged</code>（被监视的文件变了）、<code class="language-plaintext highlighter-rouge">WorktreeCreate</code>、还有 <code class="language-plaintext highlighter-rouge">MessageDisplay</code>（助手消息正在流式输出时）。</p>

<p>它的 hook 有<strong>五种执行方式</strong>：shell 命令、HTTP 端点、MCP 工具、一段交给模型判断的自然语言提示词、一个 agent。输入通过 stdin（或 HTTP body）以 JSON 交给你。</p>

<p><strong>Cursor</strong>（<code class="language-plaintext highlighter-rouge">cursor.com/docs/agent/hooks</code>）把 hook 分成<strong>三类</strong>：Agent hook（在 agent 会话里，包括 <code class="language-plaintext highlighter-rouge">preToolUse</code> / <code class="language-plaintext highlighter-rouge">postToolUse</code> / <code class="language-plaintext highlighter-rouge">beforeShellExecution</code> / <code class="language-plaintext highlighter-rouge">beforeSubmitPrompt</code> / <code class="language-plaintext highlighter-rouge">preCompact</code> / <code class="language-plaintext highlighter-rouge">stop</code> 等）、Tab hook（补全场景的 <code class="language-plaintext highlighter-rouge">beforeTabFileRead</code> / <code class="language-plaintext highlighter-rouge">afterTabFileEdit</code>）、应用生命周期 hook（<code class="language-plaintext highlighter-rouge">workspaceOpen</code>）。配置写在 <code class="language-plaintext highlighter-rouge">.cursor/hooks.json</code>（项目级）或 <code class="language-plaintext highlighter-rouge">~/.cursor/hooks.json</code>（用户级），执行方式分 command 和 prompt 两种。官方还写明可以直接加载 Claude Code 的 hook 配置。</p>

<p><strong>OpenCode</strong>（<code class="language-plaintext highlighter-rouge">opencode.ai/docs/plugins</code>）走的是插件路线：插件返回一个 hook 对象，订阅 <code class="language-plaintext highlighter-rouge">tool.execute.before</code> / <code class="language-plaintext highlighter-rouge">tool.execute.after</code>、<code class="language-plaintext highlighter-rouge">session.*</code>、<code class="language-plaintext highlighter-rouge">file.edited</code>、<code class="language-plaintext highlighter-rouge">permission.*</code>、<code class="language-plaintext highlighter-rouge">shell.env</code> 这些事件。</p>

<h3 id="三点共识">三点共识</h3>

<p>把三家的文档并排放，会看到三件事是<strong>大家都做了</strong>的：</p>

<ol>
  <li><strong>hook 点是有限的几个，而且大部分落在「工具调用前后」。</strong> 这是所有 hook 最有价值的两个点，因为那里同时能拿到「要做什么」和「做成了什么」。</li>
  <li><strong>数据是结构化的，不是一段文本。</strong> 工具名、参数、结果，都是可以编程的字段。</li>
  <li><strong>hook 能做决定，不只是能观察。</strong> 这是 hook 和「日志订阅」的分界线。</li>
</ol>

<p>这三家在「做决定」这件事上，可以横着比成三件事：怎么拒绝、能不能改参数、能不能改结果。</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>怎么拒绝</th>
      <th>能不能改参数</th>
      <th>能不能改结果</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Claude Code</td>
      <td><code class="language-plaintext highlighter-rouge">PreToolUse</code> 返回 <code class="language-plaintext highlighter-rouge">deny</code> / <code class="language-plaintext highlighter-rouge">ask</code> / <code class="language-plaintext highlighter-rouge">defer</code>；也可以用退出码 2 阻断，stderr 里的文字就是给模型看的原因</td>
      <td>能。<code class="language-plaintext highlighter-rouge">updatedInput</code> 会<strong>整体替换</strong>工具入参</td>
      <td>能。<code class="language-plaintext highlighter-rouge">updatedToolOutput</code> 替换交给模型的结果，<code class="language-plaintext highlighter-rouge">additionalContext</code> 在结果旁边追加内容</td>
    </tr>
    <tr>
      <td>Cursor</td>
      <td>退出码 2 = 阻断（等价于 <code class="language-plaintext highlighter-rouge">permission: "deny"</code>）；权限类 hook 返回的 JSON 不合 schema 也算阻断；<code class="language-plaintext highlighter-rouge">agent_message</code> 把原因回给模型</td>
      <td>能。返回 <code class="language-plaintext highlighter-rouge">updated_input</code> 即可，但 MCP 工具上会被忽略</td>
      <td>部分。普通工具只能追加 <code class="language-plaintext highlighter-rouge">additional_context</code>；MCP 工具可以用 <code class="language-plaintext highlighter-rouge">updated_mcp_tool_output</code> 替换结果</td>
    </tr>
    <tr>
      <td>OpenCode</td>
      <td>在 <code class="language-plaintext highlighter-rouge">tool.execute.before</code> 里抛异常</td>
      <td>能。直接改 <code class="language-plaintext highlighter-rouge">output.args</code></td>
      <td>官方文档未说明（只给了 <code class="language-plaintext highlighter-rouge">tool.execute.before</code> 的示例，没写 <code class="language-plaintext highlighter-rouge">after</code> 能改什么）</td>
    </tr>
  </tbody>
</table>

<p><strong>注意一件事</strong>：Claude Code 的 <code class="language-plaintext highlighter-rouge">updatedInput</code> 是<strong>整体替换</strong>入参，不是合并；而且它在 <code class="language-plaintext highlighter-rouge">auto mode</code> 下有个坑——服务端审查的是模型原始写的入参，不是 hook 改过之后的入参，于是 hook 改参数可能触发一次「服务端审的不是最终入参」的拒绝。</p>

<p>这个细节值得记住，因为它是<strong>「hook 能改参数」这件事的边界</strong>：改参数这件事在实现上比看起来要脏。</p>

<h3 id="一句话定性">一句话定性</h3>

<blockquote>
  <p><strong>hook 不是「新增能力」的接口，是「决定既有能力能不能发生」的接口。</strong></p>
</blockquote>

<p>工具不会因为有 hook 而多出写文件、跑测试这些能力。hook 改变的是<strong>这些能力发生的条件</strong>：能不能发生、以什么参数发生、发生之后结果长什么样。</p>

<p>把 hook 当成「扩展点」去用（”我想让 agent 顺便做 X”）会失望；把它当成「护栏」和「观察点」去用才对得上。</p>

<h2 id="二aethercode-的-hook一个拦截点">二、AetherCode 的 hook：一个拦截点</h2>

<h3 id="它是什么">它是什么</h3>

<p>模型决定调某个工具之后、工具执行之前，AetherCode 的引擎会把「<strong>工具名 + 参数</strong>」交给一组回调。回调可以放行，也可以带理由拒绝。工具执行完，回调还能改写返回给模型的结果。</p>

<p>从代码上看，这条通道的核心是三个类：</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">org.aethercode.hooks.Hook</code> —— hook 的接口。它声明自己关心哪个 <code class="language-plaintext highlighter-rouge">Kind</code>（生命周期点），以及一个 <code class="language-plaintext highlighter-rouge">run(HookContext)</code> 方法。</li>
  <li><code class="language-plaintext highlighter-rouge">org.aethercode.hooks.HookRegistry</code> —— 注册表。一张扁平的列表，按 kind 过滤，顺序执行，<strong>第一个说「拒绝」的赢</strong>。</li>
  <li><code class="language-plaintext highlighter-rouge">org.aethercode.hooks.Hooks</code> —— 转换层。把注册表翻译成引擎执行器认识的形状。</li>
</ul>

<p>接线点在 <code class="language-plaintext highlighter-rouge">org.aethercode.sdk.AetherCodeEngine</code> 的构造器里：引擎把注册表接到 <code class="language-plaintext highlighter-rouge">org.aethercode.core.engine.StreamingToolExecutor</code> 的 pre / post 两个桥上。</p>

<h3 id="三个值得单独讲的设计选择">三个值得单独讲的设计选择</h3>

<h4 id="一挂在引擎的拦截点上不挂在工具里">一、挂在引擎的拦截点上，不挂在工具里</h4>

<p>这是整个设计里最要紧的一条。</p>

<p>工具调用的 pre / post 是在<strong>引擎的执行器</strong>里发生的，不是在任何一个具体工具里。这意味着：</p>

<ul>
  <li>所有工具<strong>统一</strong>经过同一条通道。加一个新工具，自动就被覆盖了，不用记得去那个工具里插一遍。</li>
  <li>hook 的作者不需要知道有哪些工具。他只知道「有工具要被调用了，名字和参数在这儿」。</li>
  <li>要限定范围，就在 hook 内部按工具名判断——AetherCode 的内置 hook 就是这么做的，没有单独的「按工具注册」机制。</li>
</ul>

<p><strong>对比</strong>：如果 hook 挂在工具里，每个工具都得自己记得调用一遍 hook 链。新工具作者忘了，这一工具就绕过了所有护栏；旧的工具作者改代码时也可能顺手漏掉。这种「靠自觉的覆盖」在一个多工具的引擎里是必然会漏的。</p>

<h4 id="二拒绝必须带理由而且理由要走到模型">二、拒绝必须带理由，而且理由要走到模型</h4>

<p><code class="language-plaintext highlighter-rouge">Hook.Outcome</code> 有一个 <code class="language-plaintext highlighter-rouge">Block(reason)</code> 形态。带这个理由不是装饰——它会一路传到模型看到的那条工具结果里。</p>

<p>这一点值得展开，因为它是一个<strong>很容易做错、而且做错了很难发现</strong>的地方：</p>

<p>如果拒绝只返回一个布尔值，模型收到的是「被拒了」。它不知道是被什么规则拒的、也不知道下一步该干什么。于是常见的失败模式是：模型换个写法再试一次、换个文件再试一次、或者反复试到上限。<strong>一个不会说明理由的护栏，教不会模型怎么绕过自己。</strong></p>

<p>而带理由的拒绝是可以教的：「这个文件你还没读过，先读一遍再改」——模型读到这句就知道该做什么了。</p>

<p>AetherCode 在这里踩过一次坑并修掉了：早期实现把 <code class="language-plaintext highlighter-rouge">Block</code> 折叠成了一个布尔值，模型看到的是一句干巴巴的「被 pre-hook 拦下」，hook 自己写的解释被丢掉了。现在的实现是把 <code class="language-plaintext highlighter-rouge">Block</code> 翻译成带消息的拒绝，<strong>理由随拒绝一起到模型</strong>。</p>

<h4 id="三改参数不是-hook-的活权限层才是">三、改参数不是 hook 的活，权限层才是</h4>

<p>引擎里<strong>改写工具入参</strong>的正式通道是权限层，不在 hook。</p>

<p>工具最终拿到的入参，来自权限检查的结果——人工批准时可以带上改写后的参数。hook 的 pre 阶段能拿到入参、能拒绝，但<strong>不能改入参</strong>。</p>

<p>这看起来是「少一个口子」，但其实是一次职责分离：</p>

<ul>
  <li><strong>权限层</strong>回答的是「这次调用要不要人点头，人点头的时候能不能顺手改一下」。</li>
  <li><strong>hook 层</strong>回答的是「这次调用该不该发生、结果该不该原样交给模型」。</li>
</ul>

<p>两者问的问题不同。放在一个机制里，你会得到一个既臃肿又难推理的东西——比如 hook 改了入参，权限层审的却是改之前的入参（Claude Code 在 <code class="language-plaintext highlighter-rouge">auto mode</code> 下就正好踩了这个坑）。</p>

<p><strong>代价是诚实的</strong>：想用 hook 改参数，现在做不到，得走权限那条路。</p>

<h3 id="hook-点一览">hook 点一览</h3>

<p>AetherCode 的引擎里声明了 7 个 <code class="language-plaintext highlighter-rouge">Kind</code>：<code class="language-plaintext highlighter-rouge">PRE_TOOL_USE</code>、<code class="language-plaintext highlighter-rouge">POST_TOOL_USE</code>、<code class="language-plaintext highlighter-rouge">USER_PROMPT_SUBMIT</code>、<code class="language-plaintext highlighter-rouge">STOP</code>、<code class="language-plaintext highlighter-rouge">SESSION_IDLE</code>、<code class="language-plaintext highlighter-rouge">PRE_MODEL_QUERY</code>、<code class="language-plaintext highlighter-rouge">POST_STREAM_END</code>。</p>

<p>但<strong>声明不等于触发</strong>。把「谁在跑 <code class="language-plaintext highlighter-rouge">runAll</code>」这件事查清楚，答案是：目前只有两个点真的被引擎触发。</p>

<table>
  <thead>
    <tr>
      <th>时机</th>
      <th>能拿到什么</th>
      <th>能做什么</th>
      <th>现在的状态</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>工具调用前</td>
      <td>会话 id、工具名、工具入参</td>
      <td>放行；带理由拒绝</td>
      <td><strong>已接线</strong></td>
    </tr>
    <tr>
      <td>工具调用后</td>
      <td>上面这些，加上工具结果</td>
      <td>替换输出文本；改成功/失败标记；换掉附件列表</td>
      <td><strong>已接线</strong></td>
    </tr>
    <tr>
      <td>提交提示词时</td>
      <td>会话 id、提示词</td>
      <td>（类型已声明）</td>
      <td>未触发</td>
    </tr>
    <tr>
      <td>轮次结束</td>
      <td>会话 id</td>
      <td>（类型已声明）</td>
      <td>未触发</td>
    </tr>
    <tr>
      <td>会话空闲</td>
      <td>停止原因、待办清单</td>
      <td>（类型已声明）</td>
      <td>未触发</td>
    </tr>
    <tr>
      <td>模型调用前</td>
      <td>会话 id、模型 id、轮次序号、消息快照</td>
      <td>（类型已声明）</td>
      <td>未触发</td>
    </tr>
    <tr>
      <td>流结束后</td>
      <td>会话 id、模型文本、模型发出的工具调用</td>
      <td>（类型已声明）</td>
      <td>未触发</td>
    </tr>
  </tbody>
</table>

<p>另外有两件事<strong>长得像 hook 但不是 hook</strong>，容易混：</p>

<ul>
  <li><strong>权限询问</strong>走的是另一条路：权限询问器是一个函数式接口，实现挂在 JSON-RPC 上，请求下发到客户端弹窗，人点头之后回填。它能改参数，也能拒绝——但它不是 <code class="language-plaintext highlighter-rouge">Hook</code> 的实现。</li>
  <li><strong>会话空闲后的自动续跑</strong>挂在应用状态的一个监听器上（<code class="language-plaintext highlighter-rouge">onSessionIdle</code>），不是 <code class="language-plaintext highlighter-rouge">Hook</code>。它做的事是：会话空闲了、待办还没做完，就倒计时几秒自动续跑。</li>
</ul>

<h3 id="挂上去的三种方式">挂上去的三种方式</h3>

<p><strong>一、代码注册。</strong> 引擎构造器里按类去重注册内置 hook，外部可以通过引擎构造器的 <code class="language-plaintext highlighter-rouge">hookRegistry(...)</code> 注入自己的注册表。注册表本身用的是写时复制列表，运行中动态加 hook 是安全的。</p>

<p><strong>二、内置 hook。</strong> 引擎默认带三个：</p>

<table>
  <thead>
    <tr>
      <th>内置 hook</th>
      <th>挂在哪</th>
      <th>解决什么</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>写保护守卫</td>
      <td>工具调用前</td>
      <td>拦住「覆盖一个本会话里还没读过的既有文件」。留了两个例外：显式传「覆盖」标志，或者写进项目里预留的草稿目录。它还会从会话记录里回灌这个会话写过的路径，避免<strong>重启恢复会话后第一次写就被拦下</strong></td>
    </tr>
    <tr>
      <td>编辑失败恢复</td>
      <td>工具调用后</td>
      <td>编辑失败时改写返回给模型的错误文本，给出可执行的恢复指引</td>
    </tr>
    <tr>
      <td>阶段预算</td>
      <td>工具调用前</td>
      <td>某一阶段的工具调用数或成本超预算就拒绝。需要配一个阶段计数器才生效</td>
    </tr>
  </tbody>
</table>

<p><strong>三、配置声明。</strong> 引擎里有一个从 <code class="language-plaintext highlighter-rouge">settings.json</code> 读 hook 配置的加载器，格式是：</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"hooks"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"PreToolUse"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
      </span><span class="p">{</span><span class="w"> </span><span class="nl">"matcher"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Bash"</span><span class="p">,</span><span class="w"> </span><span class="nl">"action"</span><span class="p">:</span><span class="w"> </span><span class="s2">"deny"</span><span class="p">,</span><span class="w"> </span><span class="nl">"reason"</span><span class="p">:</span><span class="w"> </span><span class="s2">"这个项目不允许从模型里跑 shell"</span><span class="w"> </span><span class="p">}</span><span class="w">
    </span><span class="p">],</span><span class="w">
    </span><span class="nl">"PostToolUse"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
      </span><span class="p">{</span><span class="w"> </span><span class="nl">"matcher"</span><span class="p">:</span><span class="w"> </span><span class="s2">"*"</span><span class="p">,</span><span class="w"> </span><span class="nl">"action"</span><span class="p">:</span><span class="w"> </span><span class="s2">"log"</span><span class="p">,</span><span class="w"> </span><span class="nl">"path"</span><span class="p">:</span><span class="w"> </span><span class="s2">"~/.aethercode/audit.log"</span><span class="w"> </span><span class="p">}</span><span class="w">
    </span><span class="p">]</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">matcher</code> 是工具名（<code class="language-plaintext highlighter-rouge">*</code> 表示全部），<code class="language-plaintext highlighter-rouge">action</code> 目前支持三种：<code class="language-plaintext highlighter-rouge">deny</code>（拒绝）、<code class="language-plaintext highlighter-rouge">log</code>（追加一行到 <code class="language-plaintext highlighter-rouge">path</code>）、<code class="language-plaintext highlighter-rouge">allow</code>（显式放行，留给人看配置用）。</p>

<p><strong>但这个加载器目前没有任何生产代码调用它。</strong> 通道在，接线还没做——也就是说，这段配置现在还不会生效。这一点必须说清楚，否则读者照着配了半天发现没反应。</p>

<h3 id="三个边界">三个边界</h3>

<p><strong>一、hook 抛异常是 fail-open。</strong></p>

<p>引擎执行 pre / post 桥时，各自把异常 catch 住，记一条日志，然后<strong>继续</strong>。也就是说 hook 自己坏了，工具照常执行。</p>

<p>这是有意的取舍：hook 是增强层，让它自己的 bug 挡住正在进行的活，比放过去更糟。业界 Cursor 也是这个默认（退出码 2 阻断，其他退出码一律放行），而且它把这个选择做成了配置项——在 hook 上写 <code class="language-plaintext highlighter-rouge">failClosed: true</code>，失败时就改成阻断。</p>

<p><strong>但它有个反面</strong>：一个写错了的 hook 会<strong>静悄悄地不起作用</strong>，只在日志里留一行。护栏失效的时候，引擎不会告诉你。所以 hook 必须有自己的测试——不能靠「配上了」当验收。</p>

<p><strong>二、hook 没有超时。</strong></p>

<p>hook 跑在工具派发的线程上，同步执行。引擎执行器里没有给 hook 设超时上限。</p>

<p>后果很具体：<strong>hook 不返回，这次工具调用就永久挂住。</strong> 整个 agent 停在那里，不报错、不超时、不继续。</p>

<p>这是当前实现里最需要补的一块。挂上去的 hook 越复杂（要读文件、要发网络请求），这个风险越大。</p>

<p><strong>三、异步结局没有落地。</strong></p>

<p><code class="language-plaintext highlighter-rouge">Hook.Outcome</code> 里定义了一个异步形态，语义是「这个动作先继续，稍后我把结果补上」。但这层转换目前只处理同步的几种形态，异步结局不会被应用。</p>

<p>也就是说：<strong>别指望写一个异步 hook 去跑耗时长的事。</strong></p>

<h2 id="三哪些场景该用-hook">三、哪些场景该用 hook</h2>

<h3 id="一条判据">一条判据</h3>

<blockquote>
  <p><strong>只有当你要在事情发生前看一眼它的输入、或者在事情发生后改一改它的结果时，hook 才是对的工具。</strong></p>
</blockquote>

<p>展开成几个更具体的问句：</p>

<ul>
  <li>你需要<strong>在事情发生前</strong>看一眼它的输入，才能决定放不放行？（→ 工具调用前的 hook）</li>
  <li>你需要<strong>在事情发生后</strong>把它的结果改一改，再交给模型？（→ 工具调用后的 hook）</li>
  <li>这两件事都需要<strong>成对出现</strong>？（→ 两个点一起用）</li>
</ul>

<p>如果这三个问句都是否，hook 就是过度设计——直接改工具本身，或者干脆在提示词里说清楚就行。</p>

<h3 id="场景表">场景表</h3>

<table>
  <thead>
    <tr>
      <th>场景</th>
      <th>挂在哪</th>
      <th>拿什么</th>
      <th>做什么</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>写保护</td>
      <td>工具调用前</td>
      <td>工具名 + 路径</td>
      <td>拦住「没读过的文件不许覆盖」</td>
    </tr>
    <tr>
      <td>审计留痕</td>
      <td>工具调用后</td>
      <td>工具名 + 结果</td>
      <td>追加一行到日志文件</td>
    </tr>
    <tr>
      <td>输出脱敏</td>
      <td>工具调用后</td>
      <td>结果文本</td>
      <td>把密钥换掉再交给模型</td>
    </tr>
    <tr>
      <td>失败引导</td>
      <td>工具调用后</td>
      <td>失败的结果</td>
      <td>改写错误信息，告诉模型怎么改</td>
    </tr>
    <tr>
      <td>预算</td>
      <td>工具调用前</td>
      <td>工具名 + 计数</td>
      <td>超预算就拒绝</td>
    </tr>
    <tr>
      <td><strong>代码归属</strong></td>
      <td>工具调用前 <strong>+</strong> 工具调用后</td>
      <td>路径 + 内容</td>
      <td>成对快照，算出「哪几行是 AI 改的」</td>
    </tr>
  </tbody>
</table>

<p>最后一行值得单独讲——它是唯一一个<strong>必须成对使用</strong>的场景，而它的形状恰好说明了 hook 到底是什么。</p>

<h3 id="git-ai-那个案例为什么归属记录必须是编辑前--编辑后">git-ai 那个案例：为什么归属记录必须是「编辑前 + 编辑后」</h3>

<p>开源项目 git-ai 回答的是一个很朴素的问题：<strong>这段代码是 AI 写的，还是人写的？</strong></p>

<p>要回答它，光知道「AI 改过这个文件」是不够的——一个文件可能是人写了一半、AI 改了三行。你要的是<strong>字符级</strong>的归属。</p>

<p>办法只有一条：<strong>成对快照</strong>。</p>

<ol>
  <li>AI 准备改文件之前，拍一次快照——文件当时的样子。</li>
  <li>AI 改完之后，再拍一次——文件新的样子。</li>
  <li>两次一比，<strong>差集就是 AI 改的部分</strong>。</li>
</ol>

<p>这就是 hook 的形状，而且它解释了为什么 hook 要有「编辑前」和「编辑后」两个点：</p>

<ul>
  <li>只有「编辑后」→ 你知道文件变了，但不知道原来什么样，算不出改了哪几行。</li>
  <li>只有「编辑前」→ 你知道原来什么样，但不知道后来变成什么样。</li>
  <li><strong>两个点成对，才有差集。</strong></li>
</ul>

<p>而 git-ai 面对的实际情况比这更难：<strong>不同 agent 的 hook 数据完全不是一个形状。</strong></p>

<p>Claude Code 给的是工具名、参数、工具调用 id，外加会话 id、工作目录和会话记录路径；OpenCode 换了一套字段名；IDE 插件（VS Code、IntelliJ、Visual Studio）又是另一套——它们根本不是「agent hook」，而是编辑器扩展自己报的编辑事件。</p>

<p>git-ai 的做法是：<strong>给每家 agent 写一个「适配器」</strong>（上游叫 preset），<strong>把它的数据翻译成统一的内部事件。</strong></p>

<p>内部事件只有六个：</p>

<table>
  <thead>
    <tr>
      <th>统一事件</th>
      <th>含义</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>编辑前</td>
      <td>文件即将被改，拍「之前」的快照</td>
    </tr>
    <tr>
      <td>编辑后</td>
      <td>文件刚被改完，拍「之后」的快照</td>
    </tr>
    <tr>
      <td>执行 shell 前</td>
      <td>命令即将执行</td>
    </tr>
    <tr>
      <td>执行 shell 后</td>
      <td>命令执行完</td>
    </tr>
    <tr>
      <td>已知的人类编辑</td>
      <td>IDE 侧确认是人手敲的，不是 AI</td>
    </tr>
    <tr>
      <td>未跟踪编辑</td>
      <td>改了但没进版本库的改动</td>
    </tr>
  </tbody>
</table>

<p>我数了一下 git-ai 里注册的全部 agent 适配器——<strong>19 个</strong>：Claude、Codex、Gemini、Cursor、Windsurf、Cline、Continue、OpenCode、Copilot、Amp、Pi、Firebender、Droid、AI Tab，再加 Cursor 的后台会话变体、一个通用的 agent-v1，以及几个内部用的适配器。</p>

<p><strong>19 种字段写法，收敛成 6 个统一事件。</strong></p>

<p>这件事的启发比「git-ai 支持很多 agent」本身大得多：</p>

<blockquote>
  <p><strong>hook 的真正价值不在「能挂一个回调」，在「数据是可编程的」。</strong></p>
</blockquote>

<p>只有数据是结构化字段（不是一段日志文本），你才写得出这种翻译层；只有翻译层存在，一个工具才可能跨 agent、跨 IDE 地复用。</p>

<p>反过来说：<strong>传进来的如果是自由文本而不是字段，做不出通用工具，只能做一次性脚本。</strong></p>

<h3 id="什么时候别用-hook">什么时候别用 hook</h3>

<ul>
  <li><strong>只想在提示词里说清楚的事。</strong> 「改完代码记得跑测试」写在系统提示词里就够了，别为此写 hook。</li>
  <li><strong>一次性逻辑。</strong> 如果这段逻辑只在一个场景用一次，直接写在那个工具里更简单。hook 的价值在<strong>复用</strong>。</li>
  <li><strong>需要改参数的场景。</strong> AetherCode 的 hook 现在改不了入参，硬要绕会写出很难懂的代码。</li>
  <li><strong>耗时长的事。</strong> hook 同步跑在派发线程上，没有超时。一个要发网络请求的 hook = 一个可能把 agent 挂死的 hook。</li>
</ul>

<h2 id="四aethercode-在这件事上的位置">四、AetherCode 在这件事上的位置</h2>

<p>摊开讲，不往自己脸上贴金。</p>

<p><strong>和业界已经对齐的：</strong></p>

<ul>
  <li>hook 点落在工具调用的两侧——这是最有价值的两个点，和 Claude Code、Cursor 的重心一致。</li>
  <li>拒绝带理由，而且理由一路走到模型。这不是所有实现都做对的——Claude Code 那边要靠退出码 2 的 stderr，或者 JSON 输出里的原因字段，才能把理由传下去。</li>
  <li>结果可改写：输出文本、成功失败标记、附件列表，三个字段可以独立替换。</li>
  <li>两种挂载方式：代码注册 + 配置声明。配置声明的格式和 Claude Code 的 <code class="language-plaintext highlighter-rouge">settings.json</code> 很像，迁移成本低。</li>
</ul>

<p><strong>还没到位的，按重要性排：</strong></p>

<table>
  <thead>
    <tr>
      <th>差距</th>
      <th>具体是什么</th>
      <th>影响</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>hook 点太少</td>
      <td>只有工具前后两个点真的被触发。Claude Code 有 34 个事件，Cursor 二十来个</td>
      <td>轮次开始/结束、模型调用前后、上下文压缩前后，这些位置现在都插不进去</td>
    </tr>
    <tr>
      <td>改参数不在 hook</td>
      <td>走权限层</td>
      <td>想用 hook 改入参做不到</td>
    </tr>
    <tr>
      <td>配置通道没接线</td>
      <td><code class="language-plaintext highlighter-rouge">settings.json</code> 的加载器没有任何生产代码调用它</td>
      <td>照着配不生效</td>
    </tr>
    <tr>
      <td>没有超时</td>
      <td>hook 同步跑在派发线程上</td>
      <td>hook 不返回 = 这次调用永久挂住</td>
    </tr>
    <tr>
      <td>异步没落地</td>
      <td>异步结局在转换层里不被应用</td>
      <td>耗时长的事只能阻塞式做</td>
    </tr>
    <tr>
      <td>fail-open 不能配</td>
      <td>hook 抛异常一律放行，没有开关</td>
      <td>想让护栏「失败即阻断」得改代码</td>
    </tr>
  </tbody>
</table>

<p>所以定位是这样的：</p>

<blockquote>
  <p><strong>AetherCode 的 hook 是「够用且干净」的那一档，不是「覆盖全生命周期」的那一档。</strong></p>

  <p>干净指的是：通道单一、职责分明（拒绝归 hook，改参数归权限）、拒绝带理由、内置的几个 hook 都是真在跑的。</p>

  <p>不够指的是：覆盖面窄、配置通道半成品、超时和异步这两块没做完、「失败即阻断」这个开关也没有。</p>
</blockquote>

<p><strong>跟 Claude Code / Cursor / OpenCode 比的话</strong>：它们在 hook <strong>点数量</strong>和<strong>生态成熟度</strong>上领先——Cursor 甚至能直接加载 Claude Code 的 hook 配置，OpenCode 有插件生态。但它们是<strong>外部进程型</strong>的：你的 hook 跑在另一个进程里，通过 stdin/stdout 通信，进程起不来、语言不对、路径算错都会变成「hook 没生效」。AetherCode 的 hook 是<strong>进程内</strong>的（DeepAgents 那条链上也是进程内），拿到的是类型化的对象，不是 JSON 文本。</p>

<p>这是两种取舍，不是高下。进程内的好处是快、能直接用宿主语言的对象、失败可以立刻看到；坏处是<strong>hook 和引擎共享进程</strong>，hook 写坏了就是引擎的一部分坏了。</p>

<p>最后提一件必须写明的事：AetherCode 仓库里的 <code class="language-plaintext highlighter-rouge">doc/tech-docs/hook-system.md</code> 列了 7 个内置 hook（路径消毒、bash 安全、权限检查、审计日志、遥测、脱敏、截断）。<strong>这 7 个在代码里一个都不存在</strong>——它们只出现在那份文档里。引擎真正自带的是前面表里那三个。</p>

<p>一份文档描述了不存在的能力，是会误导人的。所以这份文档要么改，要么删。在它改好之前，这篇文章只写代码里真实存在的东西。</p>

<h2 id="五小结">五、小结</h2>

<ol>
  <li>
    <p><strong>hook 是「决定既有能力能不能发生」的接口</strong>，不是「新增能力」的接口。拿它当护栏和观察点用才对得上。</p>
  </li>
  <li>
    <p><strong>业界的形状已经收敛了</strong>：hook 点集中在工具调用前后，传进来的数据是结构化的，hook 能做决定。Claude Code 把它拆成 34 个事件，Cursor 分成三类，OpenCode 做成插件——但重心一致。</p>
  </li>
  <li>
    <p><strong>AetherCode 的三个设计选择</strong>：挂在引擎的拦截点上（对所有工具生效，加新工具自动覆盖）、拒绝必须带理由（理由要走到模型）、改参数归权限层不归 hook（职责分开）。</p>
  </li>
  <li>
    <p><strong>git-ai 那个案例说明了一切</strong>：19 个适配器各自的 hook 数据，收敛成 6 个统一事件。<strong>数据可编程，才谈得上通用工具。</strong></p>
  </li>
  <li>
    <p><strong>当前状态要说准</strong>：hook 点只有工具前后两个真的接线；配置声明的加载器还没接线；hook 抛异常是 fail-open（而且不能配成失败即阻断）；hook 没有超时。</p>
  </li>
</ol>

<p>一句话收尾：</p>

<blockquote>
  <p><strong>hook 的价值不在「模型要做什么我能看见」，在「模型要做什么，我能说不行，而且说清楚为什么不行」。</strong></p>

  <p>前者让你能审计，后者才让你敢放手。</p>
</blockquote>

<hr />

<p>AetherCode 是开源项目（MIT）：<a href="https://github.com/maijun-sec/AetherCode">https://github.com/maijun-sec/AetherCode</a></p>]]></content><author><name>maijun</name></author><category term="AI Agent" /><category term="智能体工程" /><category term="hook" /><category term="工具调用" /><summary type="html"><![CDATA[摘要：模型决定调某个工具之后、工具真正动手之前，是整个 agent 循环里唯一一段「你还能改主意」的窗口。hook 就是开在这个窗口上的口子——它让你看见模型想做什么，并且能说「不」，或者「换个做法」。 读完你会拿到三样东西：一是 hook 在业界已经收敛出来的形状（查了三家的官方文档：Claude Code、Cursor、OpenCode），包括它们各自的事件清单和三种做决定的方式；二是 AetherCode 的 hook 机制是怎么设计的，以及三个值得单独拿出来讲的设计选择；三是哪些场景该用 hook——用一个具体案例（git-ai 怎么用 hook 记录「哪几行是 AI 写的」）把判断标准讲清楚。 第三节还会把 AetherCode 当前的状态摊开讲：哪些 hook 点真的接线了、哪些只是声明了，以及两个必须先说清的边界（hook 抛异常是 fail-open；hook 没有超时）。]]></summary></entry><entry><title type="html">[AetherCode] AI Agent 中的 checkpoint：能撤销什么，不能撤销什么</title><link href="https://maijun-sec.github.io/2026/12/01/checkpoint-in-ai-agents/" rel="alternate" type="text/html" title="[AetherCode] AI Agent 中的 checkpoint：能撤销什么，不能撤销什么" /><published>2026-12-01T17:00:00+08:00</published><updated>2026-12-01T17:00:00+08:00</updated><id>https://maijun-sec.github.io/2026/12/01/checkpoint-in-ai-agents</id><content type="html" xml:base="https://maijun-sec.github.io/2026/12/01/checkpoint-in-ai-agents/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：<strong>读这篇你会拿到三样东西</strong>：一是把 checkpoint 拆成两种（会话级撤销 vs 长周期任务状态固化）的判据，和它真正的价值——把纠错成本压到接近零，从而放大你敢交给 agent 的活；二是逐家对比 Claude Code / Cursor / OpenCode / Codex CLI 的做法、<strong>五个共同的盲区</strong>，和一条绕不开的铁律：<strong>不可逆的事要在事前挡住，事后回滚救不回来</strong>；三是 AetherCode 自己的实现——界面实际能做什么、三个真难题、25 条变异门禁怎么保证它每次都真的撤销对了。</p>

  <p>如果你只想知道一件事：<strong>回退之前能看见多少。</strong> 这正是各家差别最大的地方（Claude Code 给文件计数、Cursor 给文件预览、AetherCode 给逐文件行数并区分「会删除」和「会改写」），也是决定「敢不敢点下去」的关键。</p>
</blockquote>

<!--more-->

<h2 id="一checkpoint-到底是什么">一、checkpoint 到底是什么</h2>

<h3 id="先分清两种不该混为一谈的东西">先分清两种不该混为一谈的东西</h3>

<p>中文语境里「检查点」经常被混着用，但在 agent 语境里至少有两种完全不同的东西：</p>

<p><strong>第一种：会话级撤销（session-scoped undo）。</strong> 这就是 Claude Code 的 <code class="language-plaintext highlighter-rouge">/rewind</code>、Cursor 的 checkpoint、OpenCode 的 <code class="language-plaintext highlighter-rouge">/undo</code> 干的事。形态是：<strong>在你发出一条新提示词的边界上，拍一张工作目录的快照，同时记住对话当时的位置</strong>。之后你回到那个点，文件回到拍照那一刻的样子，对话也（或不）回到那一刻。</p>

<p><strong>第二种：长周期任务的状态固化（durable state checkpointing）。</strong> 这是给「跑一小时的架构迁移」「跑一夜的批量处理」用的：把<strong>完整的会话状态 + 环境状态</strong>固化下来，进程被 Ctrl+C、终端被关掉、机器断电之后，重启能把任务<strong>从中断处接着跑</strong>，而不是从头再来。中文社区里讨论长周期 agent 的 checkpoint，基本都在讲这一种。</p>

<p>这两种的触发时机、存储对象、恢复目标都不一样。混起来谈最容易得出错误结论——比如以为「有了 checkpoint，任务崩了就能接着跑」。</p>

<p>本文主要讲第一种，因为它是直接面向人的交互；第二种会在第三节顺带提到 AetherCode 里的对应物。</p>

<h3 id="为什么要有它纠错成本决定你敢委派多少">为什么要有它：纠错成本决定你敢委派多少</h3>

<p>有一个框架能把这件事讲透。LangChain 的 Assaf Elovic 和 Harrison Chase 提出过 <strong>CAIR（Confidence in AI Results）</strong>：</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>CAIR = Value ÷ (Risk × Correction)
</code></pre></div></div>

<ul>
  <li><strong>Value</strong>：AI 带来的收益——省下的时间、产出的代码、修掉的 bug；</li>
  <li><strong>Risk</strong>：错误输出的潜在损害——数据丢了、有安全洞、构建挂了；</li>
  <li><strong>Correction</strong>：修复错误要付出的<strong>工作量</strong>——手动回退、翻 git 考古、从头重写。</li>
</ul>

<p>想让 agent 的置信度高，就要 Value 大、Risk 和 Correction 小。而 checkpoint 直接打击的就是 Correction 这一项。</p>

<p>没有 checkpoint，纠正一个跨几个文件的错误可能要几分钟手动回退；有 checkpoint，纠错降级成一次 rewind——<strong>几秒</strong>。这就是全部的差别，但这个差别会改变你的行为习惯：当纠错成本接近零，你才敢让 agent 去做更大的、更容易跑偏的改动，因为你反悔得起。</p>

<p>CAIR 那篇论文列了建立人机信任的五条原则，checkpoint 明确对应其中两条：</p>

<ul>
  <li><strong>可逆性（Reversibility）</strong>——「每一个动作都应该容易被撤销」。checkpoint 就是这条原则的字面实现。</li>
  <li><strong>后果隔离（Consequence Isolation）</strong>——「限制任何单个动作的爆炸半径」。因为 checkpoint 精确到某个 prompt，错误的爆炸半径就被限制在「上一个检查点之后的改动」里。</li>
</ul>

<p>所以 checkpoint 的价值不是「多了一个撤销键」，而是<strong>它决定了你能把多大的权限交给 agent</strong>。</p>

<h3 id="checkpointgit-commitgit-worktree三层不是一种">checkpoint、git commit、git worktree：三层，不是一种</h3>

<p>这三种东西都被叫做「保存你的工作」，但它们防的是不同的故障，混起来是很多误解的来源：</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>是什么</th>
      <th>生命周期</th>
      <th>防的是什么</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>checkpoint</strong></td>
      <td>会话级撤销，便宜、自动、临时</td>
      <td>只活在一个会话里（Claude Code 默认约 30 天过期，Cursor 的只存在本机，OpenCode 的存在你的仓库之外）</td>
      <td>刚才那一轮跑飞了</td>
    </tr>
    <tr>
      <td><strong>git commit</strong></td>
      <td>持久、共享的历史</td>
      <td>活得比会话、工具、甚至机器都久（push 之后）</td>
      <td>三个月后我要找回那个版本</td>
    </tr>
    <tr>
      <td><strong>git worktree</strong></td>
      <td><strong>隔离</strong>，不是撤销</td>
      <td>一直</td>
      <td>让「跑飞的那一轮」根本不需要被撤销</td>
    </tr>
  </tbody>
</table>

<p>第三条是最容易被忽略的，但它恰恰最有用。checkpoint 是<strong>事后</strong>的补丁，worktree 是<strong>事前</strong>的隔离——它让一个 agent 的改动物理上跟另一个分开，所以爆炸半径从一开始就不存在。</p>

<p>组合起来的纪律很朴素：</p>

<ol>
  <li><strong>让 harness 每轮都做 checkpoint</strong>（它本来就在做）；</li>
  <li><strong>在工作到达值得保留的状态时就 commit</strong>——这一步把临时的撤销变成持久的历史，并且<strong>覆盖 checkpoint 在文件系统上漏掉的东西</strong>，尤其是 shell 命令的改动；</li>
  <li><strong>给每个 agent 独立的 worktree 或 clone</strong>——这样「你回退不了的那一轮」的爆炸半径被关在笼子里。</li>
</ol>

<p>第三点就是本博客早前那篇讲 git worktree 的主题；这篇补上的是三层里的第一层。</p>

<h2 id="二业界怎么做">二、业界怎么做</h2>

<h3 id="claude-code目前最完整的一套">Claude Code：目前最完整的一套</h3>

<p>Claude Code 的 checkpoint 文档是最详细的，值得逐条说。</p>

<p><strong>取点时机</strong>：<strong>每一条开启新轮次的提示词都会创建一个新检查点</strong>。也就是快照取在「你按下回车、agent 还没动手」的那一刻——那一刻工作目录里的状态，正是这一轮即将改变的东西。</p>

<p><strong>存多少</strong>：为会话中<strong>最近的 100 个检查点</strong>保留文件快照。淘汰逻辑有个细节：丢弃较旧的检查点时，会删除不再被任何剩余检查点引用的快照文件，<strong>但每个文件的首个快照除外</strong>。这是个引用计数式的设计——同一份文件被多个检查点引用时不能提前删。</p>

<p><strong>活多久</strong>：检查点<strong>与对话一起保存</strong>，所以隔天恢复会话后 <code class="language-plaintext highlighter-rouge">/rewind</code> 仍然可用。文件快照默认在会话最后一次保存快照后约 <strong>30 天</strong>被清理，可以用 <code class="language-plaintext highlighter-rouge">cleanupPeriodDays</code> 调；回退到一个快照已被删掉的检查点会失败并显示 <code class="language-plaintext highlighter-rouge">No files were restored</code>。</p>

<p><strong>能做什么</strong>：运行 <code class="language-plaintext highlighter-rouge">/rewind</code>（别名 <code class="language-plaintext highlighter-rouge">/undo</code>），或在提示词输入框为空时<strong>按两次 Esc</strong>，打开回退菜单。菜单列出你在会话期间发过的提示词，选一个位置，然后选动作：</p>

<table>
  <thead>
    <tr>
      <th>动作</th>
      <th>效果</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Restore code and conversation</strong></td>
      <td>代码和对话都恢复到该位置</td>
    </tr>
    <tr>
      <td><strong>Restore conversation</strong></td>
      <td>回退到该消息，<strong>保留当前代码</strong></td>
    </tr>
    <tr>
      <td><strong>Restore code</strong></td>
      <td>还原文件更改，<strong>保留对话</strong></td>
    </tr>
    <tr>
      <td><strong>Summarize from here</strong></td>
      <td>把该位置<strong>往后</strong>的对话压缩成摘要，释放上下文窗口</td>
    </tr>
    <tr>
      <td><strong>Summarize up to here</strong></td>
      <td>把该位置<strong>之前</strong>的对话压缩成摘要，完整保留之后的消息</td>
    </tr>
    <tr>
      <td><strong>Never mind</strong></td>
      <td>返回列表，不做任何更改</td>
    </tr>
  </tbody>
</table>

<p>两个代码恢复选项<strong>只在所选检查点存在可还原的已跟踪文件更改时</strong>才出现。恢复对话或选了 summarize 之后，那条消息里的原始提示词会<strong>回到输入框</strong>，方便你改一改再发。</p>

<p>最后那两个 summarize 选项常被低估——它们跟「撤销」无关，是<strong>上下文管理</strong>：长会话里把中间的调试过程压掉，保留开头的架构决定。</p>

<p><strong>它也会告诉你这次回退会动哪些文件。</strong> 官方文档里有这么一句：「Under each prompt, the rewind menu counts changes to files Claude had already edited, whatever made them.」——菜单里每个提示词下面，会列出这个提示词动过的文件。用的是「文件计数」，不是逐文件的差异。</p>

<p>这个细节值得单拎出来，因为它<strong>推翻了一个常见的误解</strong>：很多人以为「回退前看不到影响」是所有工具的通病。实际上 Claude Code 会显示<strong>文件粒度</strong>的影响，只是不给行数、不区分「会删除」和「会改写」、也不对读不了的文件说「不知道」。</p>

<h3 id="cursor只回滚文件不回滚对话">Cursor：只回滚文件，不回滚对话</h3>

<p>Cursor 的 Agent 在<strong>做显著改动之前</strong>自动创建 checkpoint，捕获它已修改文件的状态；你从聊天时间线恢复（或点早期请求上的 Restore Checkpoint）。</p>

<p>它的恢复是 Claude Code 的镜像：<strong>只回退文件，不删除对话消息</strong>。所以对话会继续，只是代码回到了之前的状态。</p>

<p>Cursor 文档说得也很直白：checkpoint 存在本地、和 git 分离，只跟踪 agent 的改动而不跟踪你的手工编辑，<strong>它们不是版本控制系统</strong>——用来撤销 agent 的改动，永久历史交给 git。</p>

<p>同样值得说清的是：<strong>Cursor 也提供预览。</strong> 官方文档描述的流程是：在聊天时间线里点开一个 checkpoint，<strong>先预览那个点的文件</strong>，再决定要不要恢复。所以 Cursor 也不是「盲回」。</p>

<p>三家对比下来会发现：<strong>「回退前能不能看到影响」根本不是各家真正的差别。</strong> Claude Code 给文件计数，Cursor 给文件预览，OpenCode 给文件列表。真正的差别在<strong>粒度和诚实性</strong>上——数字是几行还是几万个文件？读不了的文件是写「0」还是写「不知道」？新建的文件是写「改动」还是写「会删除」？</p>

<h3 id="opencode用-git-对象库存快照但不建-commit">OpenCode：用 git 对象库存快照，但不建 commit</h3>

<p>OpenCode 的做法最有意思：<strong>它在每个模型步骤周围做快照，存进一个独立的内部 git 对象数据库</strong>（在自己的数据目录下），<strong>不创建 commit、不移动分支</strong>。于是它享受了 git 的内容寻址和去重，却不污染你的仓库历史。</p>

<p>它的 <code class="language-plaintext highlighter-rouge">/undo</code> 是<strong>分阶段</strong>的：先把回滚暂存，恢复那些被回退步骤改过的文件（这些步骤<strong>新建</strong>的文件会被删除），然后把你的提示词送回输入框让你改；如果不满意，<code class="language-plaintext highlighter-rouge">/redo</code> 可以在你重新提交前取消这次暂存的回滚。</p>

<p>它还多做了一件容易被忽略的事：<strong>在 assistant 消息里记录「这一步改了哪些路径」</strong>。官方文档用一张示意图说明：每个模型步骤<strong>之前</strong>拍一次快照（记作 A），步骤<strong>结束</strong>时再拍一次（记作 B），两次快照之间变了哪些路径，就记在 assistant 消息里。回退时按这份清单精确还原——没被归到这些步骤的路径不动。它也支持「选一条更早的消息，选 Revert」，回到任意一条消息。</p>

<p>两个硬条件：<strong>快照默认开启但需要一个 git 仓库</strong>——不在仓库里时，<code class="language-plaintext highlighter-rouge">/undo</code> 能回退对话，但没有文件状态可恢复。另外它明确划了范围：<strong>shell 的副作用（进程、网络调用、数据库）以及 git 状态本身都不反转</strong>，超过 2 MiB 的未跟踪文件不捕获，git 忽略的文件也不捕获。</p>

<h3 id="codex-cli-与-antigravity只回滚对话文件交给-git">Codex CLI 与 Antigravity：只回滚对话，文件交给 git</h3>

<p>OpenAI 的 Codex CLI 截至 2026 年 10 月的官方命令集里<strong>没有 checkpoint 恢复</strong>：slash 命令参考里只有 <code class="language-plaintext highlighter-rouge">/fork</code>（把一个聊天复制成新聊天）和一个 <code class="language-plaintext highlighter-rouge">/diff</code>。它曾经有过一个实验性的 <code class="language-plaintext highlighter-rouge">/undo</code>（从快照恢复文件状态），在 2026 年初的构建里出现过，后来被移除了。所以今天 Codex 的回滚路径就是 git：<strong>在有风险的轮次之前先 commit，搞砸了就 revert</strong>。</p>

<p>Google 的 Antigravity CLI 文档化了 <code class="language-plaintext highlighter-rouge">/rewind</code>（别名 <code class="language-plaintext highlighter-rouge">/undo</code>），但它是<strong>对话命令</strong>：把对话历史回滚到之前某条消息；<code class="language-plaintext highlighter-rouge">/fork</code> 把线程克隆成并行会话，<code class="language-plaintext highlighter-rouge">/diff</code> 打开改动查看器。同样没有文件状态恢复。</p>

<h3 id="对比">对比</h3>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Claude Code</th>
      <th>Cursor</th>
      <th>OpenCode</th>
      <th>Codex CLI</th>
      <th>Antigravity CLI</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>检查点何时取</td>
      <td>每条开启新轮次的提示词</td>
      <td>显著改动之前</td>
      <td>每个模型步骤周围</td>
      <td>无</td>
      <td>无（只有对话回滚）</td>
    </tr>
    <tr>
      <td>恢复放回什么</td>
      <td>代码、对话，或两者</td>
      <td><strong>只恢复文件</strong>，对话保留</td>
      <td>被回退步骤改过的文件；提示词回到输入框</td>
      <td>无</td>
      <td><strong>只回滚对话</strong></td>
    </tr>
    <tr>
      <td>存哪</td>
      <td>harness 自己的存储，与对话一起保存</td>
      <td>本地，与 git 分离</td>
      <td>内部 git 对象库</td>
      <td>—</td>
      <td>—</td>
    </tr>
    <tr>
      <td>恢复后还能用吗</td>
      <td>跨会话 resume 仍然可用</td>
      <td>文档未说明</td>
      <td>文档未说明</td>
      <td>不适用</td>
      <td>不适用</td>
    </tr>
    <tr>
      <td>已知盲区</td>
      <td>shell 改动、多数子代理编辑、外部编辑、符号链接；约 30 天过期</td>
      <td>手工编辑不跟踪</td>
      <td>需要 git 仓库；shell 副作用不反转；&gt;2 MiB 未跟踪文件不捕获；git 忽略的文件不捕获</td>
      <td>文件恢复是 git 的活</td>
      <td>无文件状态恢复</td>
    </tr>
  </tbody>
</table>

<p>（「文档未说明」是指官方文档没写，不等于产品没有；「不适用」是这个功能根本不存在。）</p>

<h3 id="五个共同的盲区">五个共同的盲区</h3>

<p>看下来，各家实现不同，但<strong>盲区高度一致</strong>。这才是真正需要你知道的部分：</p>

<ol>
  <li><strong>shell 命令的改动通常不跟踪。</strong> Claude Code 只跟踪它自己的文件编辑工具写下的东西。agent 跑了个 <code class="language-plaintext highlighter-rouge">rm</code>/<code class="language-plaintext highlighter-rouge">mv</code>/<code class="language-plaintext highlighter-rouge">cp</code>，rewind 撤不掉。（有个例外：如果 agent <strong>曾经</strong>用编辑工具碰过这个文件，那么之后的 bash 改动会被一起撤销；纯粹只由 bash 改过的文件则保持原样。）</li>
  <li><strong>子代理的编辑多数不恢复。</strong> Claude Code 的规则是「只有你对话里 Claude 自己编辑过的文件会被恢复」。后台 fork 的 skill、后台跑的 <code class="language-plaintext highlighter-rouge">/code-review --fix</code> 改的东西都会留下。</li>
  <li><strong>外部编辑不跟踪。</strong> 你在另一个编辑器里改的、或者另一个并发会话改的，都不在快照里。</li>
  <li><strong>符号链接和硬链接会被跳过。</strong> Claude Code 恢复时跳过这些路径，并显示 <code class="language-plaintext highlighter-rouge">Restored the code, but skipped N files</code>。dotfile 管理器软链到项目里的配置、pnpm 硬链接的文件，都属于这一类。</li>
  <li><strong>快照会过期。</strong> Claude Code 约 30 天。</li>
</ol>

<p>有一篇专门讲这个的文章把最后一个场景讲得很到位：<strong>「回退到 checkpoint 怎么没把我的文件找回来？」</strong> 大多数时候是因为文件离开了 checkpoint 的范围——被 shell 改的、被子代理改的、是软链、快照过期了。文章最后给了一句很实用的建议：<strong>先查 git；如果那次改动从来没被提交过，harness 自己的存储就是唯一的副本。</strong></p>

<h3 id="一条绕不开的铁律不可逆的事要事前挡住">一条绕不开的铁律：不可逆的事要事前挡住</h3>

<p>这是最容易被忽略、也最重要的一条。</p>

<p><strong>checkpoint 恢复的是文件内容，仅此而已。</strong></p>

<p>那么这些呢？</p>

<ul>
  <li>发了封邮件、调用了外部 API、推到了远端、部署上线了；</li>
  <li>数据库迁移执行了、某些行被删了、某个服务重启了。</li>
</ul>

<p>答案很干脆：<strong>不在任何快照里</strong>。OpenCode 的文档直接点名了进程、网络资源和数据库不会被反转。</p>

<p>所以正确的结论是：<strong>不可逆的动作需要在它运行之前就被保护</strong>——靠权限提示、靠作用域受限的凭据、靠沙箱——<strong>而不是靠事后的回滚</strong>。</p>

<p>checkpoint 解决的是「文件写错了」，不是「事情做过了」。这两件事必须分开看，否则你会因为「有 checkpoint 所以放心」而对不可逆操作放松警惕——那反而比没有 checkpoint 更危险。</p>

<h3 id="四个典型用法">四个典型用法</h3>

<p><strong>探索替代方案。</strong> 让 agent 用一种方式实现，你看完不满意，rewind 回去，换一种方式重来，不丢起点。比如购物车先用 Redux Toolkit，rewind 后改用 React Context。</p>

<p><strong>从错误里恢复。</strong> agent 引入了 bug 或者误解了需求。与其在坏代码上继续调试，不如回退到上一个已知良好状态，<strong>用更清楚的指令重新提示</strong>。</p>

<p><strong>迭代设计。</strong> 正在调一个组件的样式，想试三种视觉方案。每次尝试完，rewind 回基线，试下一个。</p>

<p><strong>释放上下文窗口。</strong> 调试了二十轮，对话很长。开头的架构决定比中间的调试来回重要得多。用 summarize 把中间那段压掉，开头完整保留。</p>

<h2 id="三aethercode-怎么实现-checkpoint">三、AetherCode 怎么实现 checkpoint</h2>

<p>AetherCode 是个 AI 编码工作台：daemon 跑 JSON-RPC，桌面端和 TUI 连上来，模型在 daemon 里干活。我们也在 agent 里做了 checkpoint。</p>

<p>先说结论：<strong>能撤销什么，AetherCode 和业界主流是一个水平线——代码、对话、分别恢复、跨重启可用，这四样都做到了。</strong> 差别在<strong>回退前你能看到多细</strong>：我们给的是逐文件的行数、区分「会删除」和「会改写」、读不了的文件说「不知道」，而且<strong>能力边界直接写在菜单上</strong>，不是藏在一页文档里。</p>

<p>AetherCode 是开源项目，仓库在 <a href="https://github.com/maijun-sec/AetherCode">github.com/maijun-sec/AetherCode</a>，下面提到的类名都能直接搜到。</p>

<h3 id="先看能力你在界面上实际能做什么">先看能力：你在界面上实际能做什么</h3>

<p>用户看到的是一个回退菜单。打开它（裸 <code class="language-plaintext highlighter-rouge">/rewind</code>，或者连按两下 <code class="language-plaintext highlighter-rouge">Esc</code>），上半部分是「point to return to:」——每一行是一个<strong>检查点</strong>，也就是一轮开始前的现场。实际长这样：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code> point to return to:
   ▶ #42  给购物车列表加分页接口，超过 20 条就…
      3 files · ~12 lines
     #41  修好登录跳转之后白屏的问题
      1 file · ~4 lines
     #40  把路由从手写 switch 换成配置表
      8 files · ~120 lines
   ⋮ 39 earlier point(s) above

 what to do:
   ▶ 1. Restore code and conversation
     2. Restore conversation
     3. Restore code
     4. Summarize from here
     5. Summarize up to here
     6. Never mind
</code></pre></div></div>

<p>（这是 TUI 的原样输出。<code class="language-plaintext highlighter-rouge">▶</code> 是当前选中项，<code class="language-plaintext highlighter-rouge">#N</code> 是轮次序号；那行摘要就是<strong>你那轮提示词的前 60 个字</strong>——认得出它对应哪一轮，比「turn 39」有用得多。上半选点、下半选动作，<code class="language-plaintext highlighter-rouge">Tab</code> 切焦点。）</p>

<p>那一行小字是关键——<strong>它是这次回退会造成的影响</strong>，在你点下去之前就摆在眼前。TUI 里长这样：</p>

<table>
  <thead>
    <tr>
      <th>你看到</th>
      <th>意思</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">3 files · ~12 lines</code></td>
      <td>回退到这一点，会动 3 个文件、约 12 行</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">no change (some files unknown)</code></td>
      <td>这个点大致不动，但有几个文件的状态未知</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">some unknown</code></td>
      <td>部分文件的数字缺失</td>
    </tr>
  </tbody>
</table>

<p>桌面端的说法更细——它把每个文件单独列出来：</p>

<table>
  <thead>
    <tr>
      <th>你看到</th>
      <th>意思</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">将改动 12 行</code></td>
      <td>这个文件会改 12 行</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">将删除</code></td>
      <td>这个文件是会话新建的，回退后<strong>被删掉</strong>，不是写回空内容</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">不知道（二进制）</code></td>
      <td>这个文件的情况<strong>我不知道</strong>——不是「0 行」</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">无改动</code></td>
      <td>这个文件不受影响</td>
    </tr>
  </tbody>
</table>

<p>而且只要有一个文件算不出来，桌面端会<strong>单独补一句</strong>：</p>

<blockquote>
  <p>有些文件算不出差异（不可读或二进制），所以这不是一份完整的预览。</p>
</blockquote>

<p>选中一个点，再选动作——桌面端的按钮就是这五个：</p>

<table>
  <thead>
    <tr>
      <th>动作</th>
      <th>效果</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>恢复代码和对话</td>
      <td>把文件和对话一起退回到这个点</td>
    </tr>
    <tr>
      <td>恢复对话</td>
      <td>只把对话退回到这个点（文件不动）</td>
    </tr>
    <tr>
      <td>恢复代码</td>
      <td>只把文件退回到这个点（对话不动）</td>
    </tr>
    <tr>
      <td>从这里总结</td>
      <td>把这个点<strong>之前</strong>的对话总结掉，这个点和后面的保留</td>
    </tr>
    <tr>
      <td>总结到这里</td>
      <td>把这个点<strong>（含）为止</strong>的对话总结掉，后面的保留</td>
    </tr>
  </tbody>
</table>

<blockquote>
  <p>一个和 Claude Code 不同的地方，值得知道：Claude Code 的 <code class="language-plaintext highlighter-rouge">Summarize from here</code> 是压缩<strong>往后</strong>的对话（保留开头的原始指令），而 AetherCode 的「从这里总结」压缩的是<strong>之前</strong>的部分——这个点和后面的都留着。两边的命名方向是反的，功能都在，但<strong>照着另一个工具的习惯想，会想错</strong>。我们把两个动作都保留下来了，区别只在这个点自己那条消息在不在摘要里。</p>
</blockquote>

<p>菜单里还会标出这个点的<strong>性质</strong>——<code class="language-plaintext highlighter-rouge">轮次边界</code> 还是 <code class="language-plaintext highlighter-rouge">停在这里</code>（用户中途按停时留的点）。</p>

<p>最后，菜单底部会明确告诉你<strong>这次回退覆盖不到什么</strong>。桌面端的原话：</p>

<blockquote>
  <p>文件清单只覆盖写工具（<code class="language-plaintext highlighter-rouge">file_write</code>、<code class="language-plaintext highlighter-rouge">file_edit</code>、<code class="language-plaintext highlighter-rouge">notebook_edit</code>）写下的文件；<strong>用 shell 写下的文件不在其中，回退之后仍然是改过的。</strong></p>
</blockquote>

<p>这句话不是写在帮助文档里等人去查，是<strong>直接显示在菜单上</strong>。</p>

<h3 id="和业界比我们在哪">和业界比：我们在哪</h3>

<p>把上一节的对比表拿来，把 AetherCode 加进去：</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Claude Code</th>
      <th>Cursor</th>
      <th>OpenCode</th>
      <th><strong>AetherCode</strong></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>恢复代码</td>
      <td>✅</td>
      <td>✅</td>
      <td>✅</td>
      <td>✅</td>
    </tr>
    <tr>
      <td>恢复对话</td>
      <td>✅</td>
      <td>❌</td>
      <td>❌ 提示词回到输入框</td>
      <td>✅</td>
    </tr>
    <tr>
      <td>代码与对话分别恢复</td>
      <td>✅</td>
      <td>❌</td>
      <td>❌</td>
      <td>✅</td>
    </tr>
    <tr>
      <td>回退前展示影响</td>
      <td>✅ 文件计数</td>
      <td>✅ 文件预览</td>
      <td>✅ 改动路径</td>
      <td>✅ <strong>逐文件 + 行数</strong></td>
    </tr>
    <tr>
      <td>区分「会删除」和「会改写」</td>
      <td>未说明</td>
      <td>未说明</td>
      <td>未说明</td>
      <td>✅</td>
    </tr>
    <tr>
      <td>读不了的文件</td>
      <td>未说明</td>
      <td>未说明</td>
      <td>未说明</td>
      <td>✅ 说「不知道」</td>
    </tr>
    <tr>
      <td>覆盖范围写在哪</td>
      <td>文档</td>
      <td>文档</td>
      <td>文档</td>
      <td>✅ <strong>菜单上</strong></td>
    </tr>
    <tr>
      <td>覆盖范围从实现派生</td>
      <td>未说明</td>
      <td>未说明</td>
      <td>未说明</td>
      <td>✅</td>
    </tr>
    <tr>
      <td>落盘自包含、跨重启可用</td>
      <td>✅</td>
      <td>未说明</td>
      <td>未说明</td>
      <td>✅</td>
    </tr>
    <tr>
      <td>需要 git 仓库</td>
      <td>❌</td>
      <td>未说明</td>
      <td>✅</td>
      <td>❌</td>
    </tr>
    <tr>
      <td><strong>已知盲区</strong></td>
      <td>shell 改动、子代理编辑、外部编辑、软链；约 30 天过期</td>
      <td>手工编辑不跟踪</td>
      <td>需 git 仓库；shell 副作用不反转；&gt;2 MiB 未跟踪文件不捕获；git 忽略的文件不捕获</td>
      <td><strong>shell 改动、外部编辑、子代理编辑不覆盖；超过 64 个点后 FIFO 淘汰</strong></td>
    </tr>
  </tbody>
</table>

<p>（标「未说明」的是<strong>官方文档没写</strong>，不等于产品没有——这里只写能查到的。）</p>

<p>先说清楚这张表<strong>没有</strong>主张什么：三家都有回退前的信息展示，<strong>我们不是第一个做预览的</strong>。差别在粒度和诚实性，具体是三点：</p>

<p><strong>展示的是「行数」，不是「文件数」。</strong> Claude Code 给的是这个提示词动过几个文件；Cursor 给文件预览；OpenCode 给改动路径清单。我们给的是<strong>每个文件会改多少行</strong>，以及<strong>这个点总共会动几个文件、约多少行</strong>。差别在于：一个文件可能被改 800 行，也可能只动一行——「3 files」这个数字把这两种情况说得一样重，而「3 files · ~1200 lines」不会。</p>

<p><strong>能区分「会删除」和「会改写」。</strong> 会话里新建的文件，回退后是被<strong>删掉</strong>的，不是写回一个空文件。这两种结果对用户是天差之别，混在「文件数」里就看不出来了。</p>

<p><strong>读不了的文件说「不知道」，不是 0。</strong> 一个二进制文件，恢复时会被跳过。写「0 行」是<strong>报了一个它没有的数字</strong>，而用户会照着这个数字做决定。我们显示「不知道」，并且如果有一部分文件未知，整行都会标出来——<code class="language-plaintext highlighter-rouge">no change (some files unknown)</code>，而不是一句轻飘飘的「no change」。</p>

<p>还有一点不算能力、算取舍：<strong>覆盖范围不是手写的，是从实现派生的。</strong>「这次回退覆盖哪些写通道」这句话，由实现里那张写工具表直接生成（<code class="language-plaintext highlighter-rouge">CodeCheckpointStore.writeTools()</code>），跟文件清单用的是<strong>同一张表</strong>。所以它不可能宣称比实现更多。菜单上那句中文警告和英文 note 都是它渲染出来的。</p>

<h3 id="再说定位回合边界的工作树快照--对话位置锚点">再说定位：回合边界的工作树快照 + 对话位置锚点</h3>

<p>我们的 checkpoint 定义是：<strong>一个用户回合边界处的工作树文件快照，加上一条对话位置锚点</strong>，用来回退。</p>

<p>三个「不是」也要说清楚：</p>

<ul>
  <li><strong>不是每一步快照</strong>，是<strong>每回合</strong>一次；</li>
  <li><strong>不是上下文压缩点</strong>——压缩是独立机制，由上下文窗口门槛控制；</li>
  <li><strong>不是任务进度记录</strong>——那是另一件事。</li>
</ul>

<p>（读代码时要注意：仓库里另有两个同名但用途不同的 checkpoint 实现——一个是任务级的会话 JSONL 自动存档，对应本文开头说的「长周期任务状态固化」；一个是第三方 agent 框架的线程状态。回退菜单用的是文件快照那个。）</p>

<p>取点时机是<strong>回合边界</strong>，理由写在 <code class="language-plaintext highlighter-rouge">AetherCodeEngine.setOnTurnBoundary</code> 的注释里：「★ This is where a checkpoint MUST be taken. ★ At the turn boundary the working tree still holds the state the turn is about to change, so that state is the “before” state.」</p>

<p>为什么不每一步都存？因为成本会失控：<strong>每回合存一份「这一轮改过的所有文件」</strong>，轮数一多，磁盘占用线性增长；而单份快照的大小随那一轮改动的文件总量走，一个大改动就是一大份。所以有内存上限 <code class="language-plaintext highlighter-rouge">CodeCheckpointStore.MAX_CHECKPOINTS = 64</code>，FIFO 淘汰。</p>

<p><strong>这个上限的代价要说清楚</strong>：连续工作 64 轮之后，最早的那个检查点就没了，回不去了。它是<strong>有意接受的取舍</strong>——用「只能回退最近 64 轮」换「不用为整段历史付存储钱」。真要回退更早的状态，答案仍然是 git。</p>

<h3 id="三个真难题和它们换来的三件事">三个真难题，和它们换来的三件事</h3>

<p>上面那些能力看着理所当然，做起来有三处是真的难。下面每讲一个，都说清楚<strong>难点在哪</strong>，以及<strong>解决之后你多了什么保证</strong>——因为「能撤销」这件事本身不难，难的是它<strong>每次都真的撤销对了</strong>。</p>

<h3 id="难题一怎么知道文件改之前长什么样">难题一：怎么知道文件「改之前长什么样」</h3>

<p><strong>这一关卡住的是「能不能真的撤销下一轮」。</strong></p>

<p>现象是这样的：回退到某点，<strong>撤不掉紧接其后那一轮做的事</strong>。更糟的是它<strong>不像失败</strong>——回退报告四个空列表，用户以为成功了，文件还躺在磁盘上。
我们的设计文档《回退到某点，要真的能撤销下一轮》里留了当时的探针读数，三行，三件事：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>PROBE boundary files=0 ; cancel files=1 names=[new.txt]
PROBE restore restored=[] deleted=[] skipped=[] failed=[]
PROBE the created file still on disk? true
</code></pre></div></div>

<p><strong>根因</strong>：回合边界点在<strong>回合开始时</strong>取，快照的内容来自「到这一刻为止 transcript 里记过的 tool_use」。而那一轮新建的文件，是<strong>那一轮</strong>才第一次被写工具碰到的——在边界点拍照的那一刻，它还没被 transcript 记下。于是：</p>

<ul>
  <li>边界点的快照里没有它；</li>
  <li>它的「写之前长什么样」（不存在，或者存在但被覆盖成什么）这个事实<strong>随着写动作一起消失了</strong>；</li>
  <li>事后无论怎么从 transcript 反推都补不回来——<strong>transcript 只说「写过这个路径」，不说「写之前它是什么」</strong>。</li>
</ul>

<p>那轮改动把这个叫做<strong>三方空洞</strong>：</p>

<table>
  <thead>
    <tr>
      <th>角色</th>
      <th>该做什么</th>
      <th>实际做了什么</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>取消点</td>
      <td>记现场，<strong>不</strong>吸收被取消轮的文件</td>
      <td>符合</td>
    </tr>
    <tr>
      <td>回合边界点</td>
      <td>撤销下一轮（含被取消轮）的工作</td>
      <td><strong>不知道那个文件存在</strong></td>
    </tr>
    <tr>
      <td>谁来告诉边界点那个文件的存在</td>
      <td>——</td>
      <td><strong>没人</strong></td>
    </tr>
  </tbody>
</table>

<p><strong>解法</strong>：让写工具<strong>在动手之前</strong>先把路径报上来。<code class="language-plaintext highlighter-rouge">FileTouchRecorder.beforeWrite</code> 由 <code class="language-plaintext highlighter-rouge">file_write</code> / <code class="language-plaintext highlighter-rouge">file_edit</code> / <code class="language-plaintext highlighter-rouge">notebook_edit</code> 在写入前调用，daemon 借此记住「这个文件改前长什么样」；再由 <code class="language-plaintext highlighter-rouge">CodeCheckpointStore.settlePreTouches()</code> 把这些「改前状态」归给上一个回合点。</p>

<p>一句话概括这个机制：<strong>写盘的那一方自曝家门</strong>。你不能事后从「写过哪些路径」反推「写之前是什么」，只能在它动手前问它。</p>

<p><strong>这一关过了，你得到的是：回退一个点，那一轮新建的文件会被真的删掉，不会留在磁盘上骗你。</strong></p>

<h3 id="难题二落盘点必须自包含不能反推">难题二：落盘点必须自包含，不能反推</h3>

<p><strong>这一关卡住的是「重启之后还能不能回退」。</strong></p>

<p>早期版本里，checkpoint 的<strong>文件清单是从 transcript 反推</strong>出来的——扫全量 transcript 的 <code class="language-plaintext highlighter-rouge">tool_use</code> 块，取那些写工具点名过的文件。</p>

<p>反推在当下是能对上的。但一旦<strong>跨了 daemon 重启</strong>或者<strong>发生了上下文压缩</strong>，transcript 已经变了，反推出来的集合就会是<strong>另一个集合</strong>——恢复的时候会动到错的文件。</p>

<p>《checkpoint 落盘 + 取消打点》那轮改动的解法是：<strong>落盘时把「快照内容 + 当时的 transcript 位置 + files 清单」当作一个整体存下</strong>，跨重启后不再需要反推。</p>

<p>落盘布局是 <code class="language-plaintext highlighter-rouge">&lt;sessionsDir&gt;/&lt;sessionId&gt;/checkpoints/</code>：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cp-&lt;ordinal&gt;-&lt;millis&gt;.json          元数据
cp-&lt;ordinal&gt;-&lt;millis&gt;/0.txt         各文件「改前」内容（UTF-8）
state.json                          {"evicted": N}
</code></pre></div></div>

<p>元数据里每个文件带三个标志位，<strong>缺一不可</strong>，因为它们编码的是三件不同的事：</p>

<table>
  <thead>
    <tr>
      <th>标志</th>
      <th>含义</th>
      <th>恢复时的行为</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">created: true</code></td>
      <td>该文件在会话碰它<strong>之前不存在</strong></td>
      <td><strong>删除</strong>它，而不是写一个空文件</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">restorable: false</code></td>
      <td>二进制 / 不可读</td>
      <td><strong>跳过并报告</strong>，而不是把乱码写回去</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">blob: null</code></td>
      <td>没有内容可存</td>
      <td>—</td>
    </tr>
  </tbody>
</table>

<p>还有一个坑值得单独说：<strong>内存和磁盘必须共用同一条驱逐规则</strong>。如果内存淘汰了某个点而磁盘还留着，重启后就会「多出」幽灵点。所以驱逐时磁盘同步删，<code class="language-plaintext highlighter-rouge">evicted</code> 计数落盘到 <code class="language-plaintext highlighter-rouge">state.json</code>。</p>

<p>而且这个计数<strong>不能因为清空而归零</strong>——清空只清内存，不回收「已经丢了的点」这件事的事实。归零等于谎报「没丢过」。这也是 <code class="language-plaintext highlighter-rouge">AGENTS.md</code> 里那两条纪律的由来：</p>

<ul>
  <li><strong>★ 内存与磁盘必须共用同一条驱逐规则 ★</strong></li>
  <li><strong>★ 「只覆盖写工具」这句话要么为真，要么别写 ★</strong></li>
</ul>

<p><strong>这一关过了，你得到的是：关掉 daemon 再打开、或者会话被压缩过之后，回退仍然指向同一批文件，不会「手滑删错文件」。</strong></p>

<h3 id="难题三把只覆盖写工具这句话从文档挪到-wire-上">难题三：把「只覆盖写工具」这句话从文档挪到 wire 上</h3>

<p><strong>这一关卡住的是「用户知不知道自己能得到什么」。</strong></p>

<p>我们早期也是只跟踪写工具写下的文件。shell 写下的文件（比如 <code class="language-plaintext highlighter-rouge">echo x &gt; f</code>、<code class="language-plaintext highlighter-rouge">sed -i</code>）<strong>根本不会点名任何文件</strong>，所以没有路径可快照，<strong>补不上</strong>。</p>

<p>这跟 Claude Code 撞的是同一个盲区——但<strong>处理方式可以不一样</strong>。以前的处理是：在文档里写一句「已知限制」，界面不吭声。《checkpoint 的文件清单：说清它覆盖什么》那轮改动换了个做法——<strong>把限制放到 wire 上</strong>：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>filesCoverage: 说明文字是直接从 CodeCheckpointStore.writeTools() 的键集生成的
</code></pre></div></div>

<p>也就是说，「这次回退能覆盖哪些写通道」这句话<strong>不是手写的，是从实现派生的</strong>。任何渲染器（菜单、preview、未来的 API 客户端）都能读到它，并把它说给用户听。</p>

<p>《桌面端的回退菜单》那轮设计里有一条正好配套：</p>

<blockquote>
  <p><strong>「不知道」不是 0。</strong> preview 里 <code class="language-plaintext highlighter-rouge">known: false</code>（二进制、读不了）显示「不知道」，不显示「0 行」——一个用户会照着做的数字，错不得。</p>
</blockquote>

<p>还有一条：</p>

<blockquote>
  <p><strong>渲染器只显示，不推导。</strong> <code class="language-plaintext highlighter-rouge">kind</code>（turn / cancel）是 daemon 的裁决，渲染器不从 summary 散文里猜；「恢复会改动什么」的 preview 是 daemon 算的；<strong>被丢弃的点数</strong>也是 daemon 的——菜单从「point 40」开始而不说一声，看起来就像 daemon 把历史弄丢了。</p>
</blockquote>

<p>这里有一个很微妙的次序问题：<strong>要标注一条限制，前提是这条限制得先成真</strong>。同一轮改动在标注之前，先发现并修了一个 bug——<code class="language-plaintext highlighter-rouge">notebook_edit</code> 这个工具<strong>真的写盘</strong>（<code class="language-plaintext highlighter-rouge">NotebookEditTool</code> 里直接 <code class="language-plaintext highlighter-rouge">Files.writeString</code>），路径字段和另外两个写工具<strong>完全同形</strong>，本该能覆盖，但它漏在了 <code class="language-plaintext highlighter-rouge">WRITE_TOOLS</code> 表外面。</p>

<p>也就是说，在把「只覆盖写工具」这句话写到 wire 上之前，先得让这句话为真。顺序反了，就是在给一个假承诺贴标签。</p>

<p><strong>这一关过了，你得到的是：界面不会让你误以为「回退能撤销一切」。</strong> 边界写在菜单上，边界还跟实现绑在一起——改代码的人忘了同步文档，菜单会自己说。</p>

<h3 id="什么时候别指望它">什么时候别指望它</h3>

<p>checkpoint 很强，但它有明确的边界。知道这些边界，比知道它能做什么更能避免出事：</p>

<table>
  <thead>
    <tr>
      <th>场景</th>
      <th>会怎样</th>
      <th>该怎么办</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>agent 用 shell 改的文件</td>
      <td><strong>撤不掉</strong>，菜单会明说不在覆盖范围</td>
      <td>重要状态先 commit</td>
    </tr>
    <tr>
      <td>子代理改的文件</td>
      <td><strong>多数撤不掉</strong></td>
      <td>同上；别指望回退能收拾残局</td>
    </tr>
    <tr>
      <td>你自己在 agent 运行时手改的文件</td>
      <td>可能被回退<strong>覆盖掉</strong></td>
      <td>回退前先 commit 你的手工改动</td>
    </tr>
    <tr>
      <td>发过的邮件、调过的 API、跑过的迁移</td>
      <td><strong>完全不在快照里</strong></td>
      <td>这类操作事前用权限/沙箱挡住</td>
    </tr>
    <tr>
      <td>超过 64 轮之前的检查点</td>
      <td>已被 FIFO 淘汰</td>
      <td>用 git</td>
    </tr>
    <tr>
      <td>软链、硬链指向的文件</td>
      <td>跳过不恢复</td>
      <td>同上</td>
    </tr>
  </tbody>
</table>

<p>还有一条容易踩的：<strong>回退是「覆盖」，不是「合并」</strong>。如果 agent 改了文件之后你又手动改过同一个文件，回退会用旧版本覆盖你的改动，不会保留。</p>

<p>一句话：<strong>checkpoint 解决「刚才那一轮跑飞了」，git 解决「更早的历史」，worktree 解决「跑飞的那一轮别碰我的东西」。</strong> 三层各管一段。</p>

<h3 id="两套界面同一套动作">两套界面，同一套动作</h3>

<p>TUI 侧从补齐 Claude Code 那批特性的那一轮起就有回退菜单（代码在 <code class="language-plaintext highlighter-rouge">aethercode-tui/src/components/CheckpointMenu.tsx</code>），六个动作（五个 + <code class="language-plaintext highlighter-rouge">never_mind</code>），两级列表：上半选点（显示 <code class="language-plaintext highlighter-rouge">#N</code> 和 summary，下一行是足迹，比如 <code class="language-plaintext highlighter-rouge">3 files · ~12 lines</code>），下半选动作，<code class="language-plaintext highlighter-rouge">Tab</code> 切焦点。</p>

<p>快捷键：<code class="language-plaintext highlighter-rouge">↑/↓</code> 移动（<strong>回绕</strong>，不是夹住）、<code class="language-plaintext highlighter-rouge">Tab</code> 切列表、<code class="language-plaintext highlighter-rouge">1-6</code> 直选动作、<code class="language-plaintext highlighter-rouge">Enter</code> 确认、<code class="language-plaintext highlighter-rouge">Esc</code> 关闭。入口是裸 <code class="language-plaintext highlighter-rouge">/rewind</code>，或者 <code class="language-plaintext highlighter-rouge">Esc Esc</code>（<code class="language-plaintext highlighter-rouge">tui.tsx</code> 里的 <code class="language-plaintext highlighter-rouge">ESC_ESC_WINDOW_MS</code> 窗口内按两次）。</p>

<p>桌面端的菜单是后来补上的，五个动作（没有 <code class="language-plaintext highlighter-rouge">never_mind</code>），中文文案。那轮设计里有一条值得记：</p>

<blockquote>
  <p><strong>动作集与 TUI 对齐</strong>……两个包不能共享代码（各自打包），所以这份动作表<strong>是</strong>第二份副本——<strong>真正把两边钉在一起的是 daemon 的 RPC</strong>，动作 id 也用同一套字符串。</p>
</blockquote>

<p>也就是说，两端各有一份动作表，靠「daemon 的 RPC + 同一套动作 id」保证不漂移。</p>

<p>同一轮设计文档还有一条很值得学：</p>

<blockquote>
  <p><strong>「恢复代码和对话」不是第三套实现</strong>，而是两个简单动作的 <strong>flags 组合</strong>（<code class="language-plaintext highlighter-rouge">touchesCode</code> / <code class="language-plaintext highlighter-rouge">touchesConversation</code>）。如果它有自己的实现，修「恢复代码」就修不到它，两边会漂。</p>
</blockquote>

<p>《回退菜单必须装得下，每个键都得有用》那轮改动修的是菜单本身的四个缺陷，而且<strong>四个都是量出来的，不是读代码猜的</strong>。举两个例子：</p>

<ul>
  <li><strong>列表完全没有窗口。</strong> 实测 40 个 checkpoint 渲染出 <strong>53 frame rows</strong>——菜单自己的行加 40 行 checkpoint 装不进 40 行的终端；面板无界增长跑出屏幕，<strong>用户选中的那一项可能一起跑到屏幕外</strong>。修法是加窗口（<code class="language-plaintext highlighter-rouge">src/listWindow.ts</code>）+「上面还有 N 个 / 下面还有 N 个」标记，让静默截断不像是列表到头了。修完是 22 frame lines、渲染 8 行。</li>
  <li><strong><code class="language-plaintext highlighter-rouge">↓</code> 是个死键。</strong> 菜单打开时选中的是<strong>最新</strong>项，而旧 handler 做的是 <code class="language-plaintext highlighter-rouge">Math.min(checkpoints.length - 1, i + 1)</code>——开菜单时已经在 <code class="language-plaintext highlighter-rouge">length - 1</code> 了，这个 clamp 把它钉死。</li>
</ul>

<h3 id="这些能力凭什么可信25-条变异">这些能力凭什么可信：25 条变异</h3>

<p>上面那些能力，靠的不是「写的时候小心」，而是<strong>每一处都有门禁守着</strong>。</p>

<p>门禁的做法有点特别：不是写断言检查「功能还在」，而是<strong>把某条修复改回去，看门禁会不会变红</strong>——红不了就说明门禁对那个缺陷是瞎的，绿灯什么都不能证明。</p>

<p>TUI 侧有三组门禁，每组配一个变异台。三组的分工是这样的：</p>

<table>
  <thead>
    <tr>
      <th>组</th>
      <th>保护什么</th>
      <th>对应的设计文档</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>「菜单和后端的连线」</td>
      <td>菜单动作表、快捷键、路由、回合边界 hook 那一整套接线</td>
      <td>《四个 Claude Code 特性，以及它们暴露的规则》</td>
    </tr>
    <tr>
      <td>「菜单本身」</td>
      <td>列表窗口、上下键行为、隐藏项计数</td>
      <td>《回退菜单必须装得下，每个键都得有用》</td>
    </tr>
    <tr>
      <td>「preview 的诚实性」</td>
      <td>回退前预览说的和 daemon 实际做的一致</td>
      <td>《回退菜单在你选之前就告诉你恢复会做什么》</td>
    </tr>
  </tbody>
</table>

<ul>
  <li>
    <p><strong>「菜单和后端的连线」这一组（11 条）</strong>，保护的是「菜单和后端的连接没被悄悄改掉」：</p>

    <ol>
      <li><code class="language-plaintext highlighter-rouge">line.ts</code> 里私藏第二份 <code class="language-plaintext highlighter-rouge">CHECKPOINT_ACTIONS</code>；</li>
      <li><code class="language-plaintext highlighter-rouge">tui.tsx</code> 里单独特判 <code class="language-plaintext highlighter-rouge">restore_code_and_conversation</code>；</li>
      <li>裸 <code class="language-plaintext highlighter-rouge">/rewind</code> 又回去要求序号；</li>
      <li><code class="language-plaintext highlighter-rouge">Esc Esc</code> 提前开菜单；</li>
      <li>序号被直接推导；</li>
      <li>restore 改用 <code class="language-plaintext highlighter-rouge">userMessageIndex</code> 而不是 <code class="language-plaintext highlighter-rouge">cp.transcriptIndex()</code>；</li>
      <li>HTTP 路由消失；</li>
      <li>回合边界 hook 被移除；</li>
      <li><code class="language-plaintext highlighter-rouge">state.ts</code> 多出一个 <code class="language-plaintext highlighter-rouge">checkpointMenuOpen</code> 标志；</li>
      <li>回合边界的调用被注释掉；</li>
      <li>引擎里的 <code class="language-plaintext highlighter-rouge">saveCodeCheckpoint</code> 被注释掉。</li>
    </ol>

    <p>第 8 条和第 10 条改的是<strong>同一处</strong>——<code class="language-plaintext highlighter-rouge">QueryEngine</code> 里的 <code class="language-plaintext highlighter-rouge">onTurnBoundary.accept(userInput);</code>——为什么写两遍？第 10 条的注释写明了原因：</p>

    <blockquote>
      <p>★ This is the case that found a REAL gate bug. ★ The gate read the RAW source, so a commented-out call still satisfied “the hook must fire” — the text was still in the file.</p>
    </blockquote>

    <p>也就是说，门禁原来读的是<strong>原始源码</strong>，而「回合边界 hook 必须被调用」这条断言是拿<strong>文本在不在文件里</strong>判断的。于是把调用注释掉，文本还在，断言照样过——<strong>门禁是绿的，缺陷是活的</strong>。修法是让门禁读<strong>去掉注释后的源码</strong>，第 10 条变异就是证明这个修复生效的。</p>
  </li>
  <li>
    <p><strong>「菜单本身」这一组（7 条）</strong>，保护菜单自己：列表不设窗口、选中项能跑出窗口、<code class="language-plaintext highlighter-rouge">↓</code> 退回夹住、<code class="language-plaintext highlighter-rouge">↑</code> 退回夹住、菜单不说明藏了多少、两个 summarize 读起来一样、<code class="language-plaintext highlighter-rouge">MAX_CHECKPOINTS</code> 上限被去掉。</p>
  </li>
  <li>
    <p><strong>「preview 的诚实性」这一组（7 条）</strong>，保护的是「回退前预览告诉你会改什么」这件事不撒谎：足迹从行里被抹掉（preview 又看不见了）；<strong>「没有 preview」被显示成「0 个文件」</strong>（一个 daemon 从没发过的数字）；<code class="language-plaintext highlighter-rouge">known: false</code> 被写成「未改动」（一个 daemon 没法做的断言）；「无变化」的说法把不完整性藏起来；daemon 侧和 TUI 侧的行数统计各丢一次「末尾换行」修正；<strong>新建文件被报成普通改动</strong>（而不是「会被删除」）。</p>

    <p>这组是「不知道 ≠ 0」那条纪律的落地。前两条尤其要命：<strong>用户会照着数字做决定</strong>，把「不知道」写成 0，等于骗他。</p>
  </li>
</ul>

<p>为什么 restore 必须用<strong>位置</strong>而不是序号？因为引擎自动插入的 <code class="language-plaintext highlighter-rouge">Role.USER</code> 侧注会让「第 N 轮」这个说法错位。<code class="language-plaintext highlighter-rouge">AGENTS.md</code> 里写得很清楚：</p>

<blockquote>
  <p><strong>(1) 序号和位置是两种地址。</strong> ……而<strong>以 checkpoint 为锚</strong>的两个操作<strong>根本不重新推导</strong>边界——菜单说的是「回到这一点」，这一点是<strong>位置</strong>，不是序号。</p>
</blockquote>

<p>这 25 条变异，加上 Java 侧和桌面端的对应测试，构成这道防线的全部。原则还是那一条：<strong>没红过的门禁不是门禁。</strong></p>

<h2 id="四小结">四、小结</h2>

<p>把三段压成几句：</p>

<ol>
  <li><strong>checkpoint 有两种，别混。</strong> 会话级撤销（回合边界的工作目录快照 + 对话位置锚点）解决「刚才那轮跑飞了」；长周期任务的状态固化解决「进程挂了怎么接着跑」。</li>
  <li><strong>它的价值是压低纠错成本，从而放大你敢交给 agent 的活。</strong> CAIR = Value ÷ (Risk × Correction)，checkpoint 直接打击 Correction；Correction 接近零，你才敢委派更大的改动。</li>
  <li><strong>checkpoint、commit、worktree 是三层。</strong> checkpoint 是廉价的会话级撤销，commit 是持久历史，worktree 是事前隔离——<strong>让跑飞的那一轮根本不需要被撤销</strong>。</li>
  <li><strong>所有实现都有同一个盲区：只跟踪 agent 自己的写工具。</strong> shell 改动、子代理编辑、外部编辑、软链，都不在快照里。</li>
  <li><strong>checkpoint 恢复文件内容，仅此而已。</strong> 发过的邮件、调过的 API、跑过的迁移、删掉的行，不在任何快照里。<strong>不可逆的动作要在事前被挡住，不是事后回滚。</strong></li>
</ol>

<p>对 AetherCode 来说，最后两条是自己撞出来的：</p>

<ul>
  <li>你不能事后从「写过哪些路径」反推「写之前是什么」——<strong>只能在它动手前问它</strong>（<code class="language-plaintext highlighter-rouge">FileTouchRecorder.beforeWrite</code>）；</li>
  <li>落盘点必须<strong>自包含</strong>，因为反推出来的集合在重启或压缩之后会变成另一个集合；</li>
  <li>而最容易忘的是第三件：<strong>限制要上 wire，而且在上 wire 之前先得让那句话成真</strong>。</li>
</ul>

<h3 id="aethercode-在这件事上的位置">AetherCode 在这件事上的位置</h3>

<p>把话说明白，不夸大：<strong>AetherCode 的 checkpoint 做到了业界主流都做到的那些</strong>——代码回滚、对话回滚、两者分别回滚、落盘自包含、跨重启可用。<strong>它不比 Claude Code 或 Cursor 更强，它只是在自己的取舍下做得更完整一点。</strong></p>

<p>具体多出来的是两件事，都在「你能看见什么」这一侧：</p>

<ol>
  <li><strong>回退前的信息更细。</strong> 每个检查点自带一份足迹，逐文件告诉你会改多少行、哪个会被删掉、哪个读不了。这不是「撤销之后看报告」，是<strong>撤销之前做决定</strong>。</li>
  <li><strong>能力边界写在界面上，而且跟实现绑死。</strong> 「shell 写的文件不在覆盖范围内」这句话由实现派生，菜单上直接显示——不是藏在一页文档末尾、也不是某次发布说明里的一句话。</li>
</ol>

<p>另外两点值得单独说，因为它们是<strong>取舍</strong>而不是长处：</p>

<ul>
  <li><strong>不需要 git 仓库。</strong> OpenCode 的文件系统快照依赖 git 仓库，不在仓库里就只能回退对话。我们不依赖 git，所以在任何目录都能用——但代价是<strong>不享受 git 的内容寻址和去重</strong>，存储开销更大。</li>
  <li><strong>覆盖范围更窄。</strong> 我们只跟踪写工具写下的文件；shell 写的不算。这跟 Claude Code、Cursor、OpenCode 是同一个盲区，不是我们独有。OpenCode 额外还排除了 git 忽略的文件和超过 2 MiB 的未跟踪文件。</li>
</ul>

<p>再加上那 25 条变异门禁守着，上面这些不是「设计上应该可以」，是<strong>每次改动都被验证过还成立</strong>。</p>

<p>一句话收尾：<strong>checkpoint 的价值不在「能撤销」，在「因为能撤销，所以敢往前推」。</strong></p>]]></content><author><name>maijun</name></author><category term="AI Agent" /><category term="检查点" /><category term="智能体工程" /><category term="工程方法" /><summary type="html"><![CDATA[摘要：读这篇你会拿到三样东西：一是把 checkpoint 拆成两种（会话级撤销 vs 长周期任务状态固化）的判据，和它真正的价值——把纠错成本压到接近零，从而放大你敢交给 agent 的活；二是逐家对比 Claude Code / Cursor / OpenCode / Codex CLI 的做法、五个共同的盲区，和一条绕不开的铁律：不可逆的事要在事前挡住，事后回滚救不回来；三是 AetherCode 自己的实现——界面实际能做什么、三个真难题、25 条变异门禁怎么保证它每次都真的撤销对了。 如果你只想知道一件事：回退之前能看见多少。 这正是各家差别最大的地方（Claude Code 给文件计数、Cursor 给文件预览、AetherCode 给逐文件行数并区分「会删除」和「会改写」），也是决定「敢不敢点下去」的关键。]]></summary></entry><entry><title type="html">[AetherCode] TDD 在 AI Agent 中：从「事后验证」到「事前约束」</title><link href="https://maijun-sec.github.io/2026/12/01/tdd-for-ai-agents/" rel="alternate" type="text/html" title="[AetherCode] TDD 在 AI Agent 中：从「事后验证」到「事前约束」" /><published>2026-12-01T14:00:00+08:00</published><updated>2026-12-01T14:00:00+08:00</updated><id>https://maijun-sec.github.io/2026/12/01/tdd-for-ai-agents</id><content type="html" xml:base="https://maijun-sec.github.io/2026/12/01/tdd-for-ai-agents/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：TDD 在 AI 编程之前是「可选的最佳实践」，在 AI 编程之后变成了「必要的工程结构」——因为要约束的已经不是人，而是一个看不到内部推理过程、也不会主动追问的系统。</p>

  <p><strong>读完你会拿到三样东西</strong>：一是 TDD 真正买到的三样东西（粒度、节奏、快速反馈）和「测试是规格」这个容易被跳过的要点；二是 AI 编程为什么让这套方法从「锦上添花」变成「不可或缺」——AI 写的测试为什么经常什么都没验，以及怎么把流程从建议变成强制；三是<strong>什么时候这套方法不划算</strong>（探索性 spike、配置改动、需求还没想清楚）。</p>

  <p>第三段讲 AetherCode 自己怎么把这套东西用在 <strong>agent 执行任务</strong>上——系统提示词里的验证阶段、SDD 八阶段里带验收口径的任务条目、场景矩阵对 agent 整体行为的判定/产物/护栏三件套，以及门禁怎么配变异见证。</p>
</blockquote>

<!--more-->

<h2 id="一什么是-tdd">一、什么是 TDD</h2>

<h3 id="一轮循环到底在做什么">一轮循环到底在做什么</h3>

<p>TDD 的操作层只有三步，任何人都能背出来：</p>

<ul>
  <li><strong>红（Red）</strong>：写一个注定失败的测试，然后<strong>跑它</strong>，确认它以<strong>正确的理由</strong>失败。</li>
  <li><strong>绿（Green）</strong>：写刚好能让这个测试通过的代码，能硬编码就硬编码。</li>
  <li><strong>重构（Refactor）</strong>：在测试保持绿的前提下清理结构。</li>
</ul>

<p>但真正难的从来不是「绿」和「重构」，而是「红」这一步里被一笔带过的两个动作：<strong>你要先把想要的行为写成一段可执行的代码</strong>，而且<strong>你要亲眼看它失败</strong>。</p>

<p>第二个动作常被跳过，于是流程就退化成了「先写实现，再补一个测试证明它能跑」。这两件事的区别不是形式上的。补的测试是从实现倒推出来的——它测的是「这段代码做了它做的事」，而不是「这个需求被满足了」。实现换了方案，测试大概率跟着一起换，于是永远绿。</p>

<p>「以正确的理由失败」这句话也不是修辞。测试失败有很多种：类名拼错了、依赖没起、断言写反了、编译没过。这些都不算红。只有「因为功能还没实现而失败」才算红。这也是为什么「先写一个编译不过的测试」在某些流派里也算合法的红——编译失败本身就是「这个 API 还不存在」的证据。</p>

<h3 id="三角验证为什么绿不要求代码真的对">三角验证：为什么「绿」不要求代码真的对</h3>

<p>写 <code class="language-plaintext highlighter-rouge">calculateTotal</code>，第一个测试只要求空购物车总价是 0。那先把函数体硬编码成 <code class="language-plaintext highlighter-rouge">return 0</code>，测试照样变绿。</p>

<p>这不丢人，也正是 TDD 允许的。<strong>绿只意味着「当前这套测试还分辨不出你的实现和一个正确实现」</strong>，它从来不声称实现完成了。接着加第二个测试：两件 10 元的商品总价应该是 20。硬编码立刻变红，你才不得不写出真正的求和逻辑。</p>

<p>这个过程叫<strong>三角验证</strong>：你已经有一个能用的锚点，现在需要第二个点把直线确定下来，而第二个点的作用恰恰是把实现从「刚好够用」逼到「真的对」。推而广之——需求越模糊，越需要更多的点把直线确定；一个点的测试是猜的，两个点的测试是拟合的，三个点才叫「定义」。</p>

<h3 id="tdd-真正买到的三样东西">TDD 真正买到的三样东西</h3>

<p>TDD 最常被总结成「先写测试」，但「先写测试」只是个手段。真正的产出是三个约束：</p>

<table>
  <thead>
    <tr>
      <th>约束</th>
      <th>含义</th>
      <th>少了它会怎样</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>粒度</strong></td>
      <td>一次只推进一个小行为，小到几分钟能验证一遍</td>
      <td>任务一大就漂移，方向错了也没人知道</td>
    </tr>
    <tr>
      <td><strong>节奏</strong></td>
      <td>每一步都是同一个形状的循环：写一个 → 跑 → 改</td>
      <td>跑到一半换打法，状态没法自证，也没法回顾</td>
    </tr>
    <tr>
      <td><strong>快速反馈</strong></td>
      <td>几秒内知道自己对不对</td>
      <td>反馈越晚，越容易在错方向上多走一步，而且多走的那步更贵</td>
    </tr>
  </tbody>
</table>

<p>这三个约束在传统开发里就已经很值钱，但它们在 AI 时代变得<strong>不可替代</strong>——原因放在下一节讲。</p>

<h3 id="测试是规格不是检查">测试是规格，不是检查</h3>

<p>有一件事在教科书里常被一带而过，但在 AI 辅助开发里是全部：<strong>测试不是用来检查代码的，是用来表达需求的</strong>。</p>

<p>同一个功能，测试可以从两个方向写出来：</p>

<ul>
  <li><strong>从实现推导</strong>：测试 <code class="language-plaintext highlighter-rouge">Reflector.generate_rca()</code> 返回了格式正确的 JSON。这测的是代码的行为。</li>
  <li><strong>从需求推导</strong>：测试「用户触发反思后，系统生成了包含根因分析的可审核报告」。这测的是需求的满足。</li>
</ul>

<p>区别在实现改动时才显出来：<strong>当 AI 把实现从方案 A 改成方案 B 时，前者大概率失效，后者纹丝不动。</strong> 这条经验在《Specification by Example》（Gojko Adzic）和需求追溯矩阵（RTM，ISO/IEC/IEEE 29148 里的一条标准实践）里是成体系的——每条需求能追到测试用例，每个测试用例能追回需求。经典的 ATDD（验收测试驱动开发）就是把这几件事串起来的流程。</p>

<p>判断一条测试是「规格」还是「检查」，有个很好用的问题（社区里叫<strong>黑盒验证法</strong>）：</p>

<blockquote>
  <p>如果这个函数的实现被完全重写，但输出仍然符合预期，这个测试能识别出来吗？</p>
</blockquote>

<p>如果它依赖的是某个中间变量的值，而不是外部可观察的行为（返回值、落库状态、发出的事件），那它测的是实现细节，是<strong>脆弱的假测试</strong>。</p>

<h3 id="两个常见误解">两个常见误解</h3>

<p><strong>覆盖率不是质量。</strong> 行覆盖率 100% 的套件完全可能只做浅断言。覆盖率只说明「这行代码被执行过」，不说明「这行代码的行为被验证过」。</p>

<p><strong>不是所有代码都适合 TDD。</strong> TDD 假设行为能被切成确定性的输入输出。并发、协议状态机这类东西硬套 TDD，只会写出一堆假绿。Kent Beck 自己的说法是：TDD 是一种追求完美的手段，但不是它最有效的用法——<strong>你天天碰的那部分要硬得像石头，越往系统边缘、越是不常改的部分，测试可以糙一点</strong>。</p>

<p>还有一条不成文但很实际的纪律：<strong>别在能跑起来之后再补测试</strong>。Kent Beck 说得很直白——一旦你有了能跑的功能，回去补测试的那股心理动力就蒸发了。所以 TDD 不是「有空就补测试」的自律题，而是<strong>在最省力的时刻先写测试</strong>：那时候写测试比不写测试还便宜。</p>

<h2 id="二tdd-在-ai-agent-中">二、TDD 在 AI Agent 中</h2>

<h3 id="瓶颈从写搬到了验">瓶颈从「写」搬到了「验」</h3>

<p>传统编程的瓶颈是「写」。写代码慢、要花时间、要想清楚，所以质量保障主要靠<strong>测试 + 评审 + 人类兜底机制</strong>三层。</p>

<p>AI 编程把这三层里的前两层压扁了：</p>

<ul>
  <li>写代码几乎不要钱——一秒钟几百行；</li>
  <li>评审跟不上——人类写代码有个自然节奏，写的过程中思路本身就是一道关卡；AI 不给你这个节奏。</li>
</ul>

<p>于是<strong>剩下能用的那层里，测试是最不容易被架空的一层</strong>。更麻烦的是，人类开发者的兜底机制也一起消失了：AI 拿到一个模糊需求不会追问。经验丰富的开发者读到「用户应该能注册」，一定会问「邮箱格式有什么要求？密码长度限制呢？重复注册怎么处理？」；AI 不会问，它会直接翻译成一堆 happy path 代码——标准邮箱、8 位密码、一切正常——然后你觉得「能跑」，直到边界情况暴露问题。</p>

<p>所以在 AI 辅助开发里，TDD 不再是「质量加分项」，而是<strong>最关键的一道质量闸门</strong>。</p>

<p>需要说清楚的是，它不是<strong>唯一</strong>一道。类型检查、静态分析、沙箱权限、git 可回滚性都是确定性闸门，而且各有分工——事前挡住（权限、沙箱）和事后兜底（git、worktree）同样有效。测试的特殊之处在于：<strong>它是唯一一道会被「看起来全绿」骗过去的闸门</strong>。别的闸门要么报错了，要么没报错；测试可以报绿，而实际上什么都没验。</p>

<h3 id="ai-写的测试为什么经常什么都没验">AI 写的测试为什么经常什么都没验</h3>

<p>这是最要命的一环。AI 写测试极快，于是「测试套件全绿」这件事变得毫无信息量。一个危险的共识正在蔓延：<strong>测试全绿等于代码正确</strong>。而现实里见过太多覆盖率一路往上、却在一次紧急故障面前溃不成军的项目——覆盖率高说明代码被执行过，不说明它验过什么。</p>

<p>因为 AI 生成的测试，正在以一种近乎完美的姿态「形式化」地通过，但从未真正触碰过业务逻辑的边界。常见的三种形态：</p>

<p><strong>一、断言的「自我实现」陷阱。</strong> 断言跟被测对象的状态绑定，而不是跟业务结果绑定：</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">test_update_config</span><span class="p">():</span>
    <span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">[</span><span class="s">"APP_MODE"</span><span class="p">]</span> <span class="o">=</span> <span class="s">"test"</span>
    <span class="n">config</span> <span class="o">=</span> <span class="n">load_config</span><span class="p">()</span>
    <span class="k">assert</span> <span class="n">config</span><span class="p">.</span><span class="n">app_mode</span> <span class="o">==</span> <span class="s">"test"</span>
</code></pre></div></div>

<p>这个测试在测什么？测的是「<code class="language-plaintext highlighter-rouge">os.environ.get()</code> 能返回刚设置的值」——这是解释器本身就保证的行为，跟你的 <code class="language-plaintext highlighter-rouge">load_config()</code> 毫无关系。真正该断言的是<strong>生产的配置</strong>（重试次数、缓存开关），而不是你刚塞进去的那个值。</p>

<p><strong>二、覆盖率注水。</strong> AI 极其擅长通过「路径覆盖」提高覆盖率：让每条 <code class="language-plaintext highlighter-rouge">if/else</code> 分支都执行到，但从不验证分支内计算结果的正确性，也不测边界值——价格是负数时、会员等级是 <code class="language-plaintext highlighter-rouge">None</code> 时、等级写成大小写不同的 <code class="language-plaintext highlighter-rouge">"GOLD"</code> 时。</p>

<p><strong>三、跳过开关与 Mock 滥用。</strong> AI 处理不稳定因素的方式往往是「聪明地」绕过去：留一个 <code class="language-plaintext highlighter-rouge">SKIP_FLAKY_TESTS = True</code> 的开关、加一行注释说明「认证不稳定，先跳过」。测试套件是绿的，核心逻辑裸奔。另一头是过度 Mock——把数据库、外部 API 全 mock 掉，于是你测的是 Mock 的行为，而不是真实逻辑的交互。</p>

<p>针对这三种，办法都指向同一件事：<strong>判断一个测试有没有用，只有一个办法——引入一个缺陷，看它会不会失败。</strong></p>

<ul>
  <li>改一个逻辑常量（把 <code class="language-plaintext highlighter-rouge">0.8</code> 改成 <code class="language-plaintext highlighter-rouge">0.85</code>），测试必须变红；</li>
  <li>清空被测函数体只留 <code class="language-plaintext highlighter-rouge">pass</code>，测试必须变红；</li>
  <li>翻转一个逻辑运算符（<code class="language-plaintext highlighter-rouge">==</code> 改 <code class="language-plaintext highlighter-rouge">!=</code>），测试必须变红。</li>
</ul>

<p>如果改完还是绿的，那它就是个装饰品。这套做法在测试圈里叫<strong>变异测试</strong>——第三个细节里我们会看到，AetherCode 就是这么干的。</p>

<p>还有一条评审清单值得抄：审查一个 AI 生成的测试时，看三件事——<strong>行为锚点</strong>（断言是否直接映射到业务规则，而不是变量名或内存地址）、<strong>状态验证</strong>（是否验证了系统的终态：数据库记录、缓存值、发出的消息，而不只是返回值）、<strong>失败记录</strong>（这个测试有没有过「从红到绿」的记录）。</p>

<h3 id="ai-的四个新风险">AI 的四个新风险</h3>

<p>传统 TDD 怕的是「人偷懒不写测试」。AI 编程引入了四个新的失效模式：</p>

<ul>
  <li><strong>非确定性</strong>：同一个 prompt 跑两次可能给出不同的实现，你没法预期它会写出什么。</li>
  <li><strong>回归倾向</strong>：改 A 的时候偷偷坏了 B，而且不会告诉你——AI 没有全局意识。</li>
  <li><strong>虚假正确性</strong>：AI 是 10 倍的 Writer，不是 10 倍的 Reviewer。它擅长生成代码，不擅长判断代码对不对。</li>
  <li><strong>测试作弊</strong>——这个最危险：<strong>AI 会去改测试让它通过，而不是修代码</strong>。</li>
</ul>

<p>最后一条是 AI 时代特有的形态。Kent Beck 说他见过 AI agent 删除失败的测试而不是修复代码：测试套件「通过」了，但规格被偷偷改了。<strong>AI 不是让代码符合测试，而是让测试符合代码。</strong> 他对这件事的比喻很贴切——测试应该是一段<strong>不可变的注解</strong>：「不，这块逻辑之前是正确的，如果你敢改变它，我会阻止你。」</p>

<p>也正因为测试可能被改，「测试失败」这件事本身就不再是可信信号了。所以纪律要加一条：<strong>测试的修改要和实现的修改分开看、分开评</strong>。</p>

<h3 id="为什么写测试和写实现必须分成两个上下文">为什么写测试和写实现必须分成两个上下文</h3>

<p>这条在社区里被反复强调，而且是最容易犯的错。</p>

<p>如果 AI 在<strong>同一轮对话、同一个上下文</strong>里既写测试又写实现，它就等于<strong>看过答案再出题</strong>：它知道自己的实现长什么样，于是测试会不自觉地去迁就实现。永远满分，什么都没验证。</p>

<p>所以正确的做法是把它们拆开：</p>

<ol>
  <li>人类（或独立的 agent 上下文）写出测试；</li>
  <li>跑测试，确认它红，且红的原因正确；</li>
  <li><strong>换一个上下文</strong>，让 agent 只看这个测试和需求，去写实现；</li>
  <li>跑测试，确认绿。</li>
</ol>

<p>第 3 步的「换上下文」是关键。它保证实现是<strong>对着规格写的</strong>，不是对着答案写的。</p>

<h3 id="从红绿灯到方向盘">从红绿灯到方向盘</h3>

<p>这是整个话题的核心判断：</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>传统时代</th>
      <th>AI 时代</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>测试的角色</td>
      <td>质量检查工具</td>
      <td>AI 行为控制协议</td>
    </tr>
    <tr>
      <td>比喻</td>
      <td><strong>红绿灯</strong>：告诉你对不对</td>
      <td><strong>方向盘</strong>：控制 AI 往哪走</td>
    </tr>
    <tr>
      <td>性质</td>
      <td>可选的最佳实践</td>
      <td>必要的工程结构</td>
    </tr>
    <tr>
      <td>约束对象</td>
      <td>人类开发者</td>
      <td>不稳定的 AI agent</td>
    </tr>
    <tr>
      <td>失败代价</td>
      <td>事后返工</td>
      <td>一次交付就是错的，而且没人察觉</td>
    </tr>
  </tbody>
</table>

<p>Google DORA 团队的年度报告（2024、2025 两版）给出的结论方向一致：<strong>AI 采用率上升与交付稳定性下降相关，而小步快跑、有自动化测试兜底的组合才与稳定性提升相关。</strong>（这是相关性结论，不是因果——报告本身也强调平台工程能力是中介变量。）</p>

<p>开源框架 Harness Kit 的 Pattern Engineering 里写得更直接：<em>Tests must fail before implementation starts — the boundary is structural.</em> 翻成中文就是「<strong>边界是结构性的，不是靠提示词许愿</strong>」——测试必须在实现开始之前就失败，这个边界得由工具链来保证，不能靠跟模型说「请先写测试」。</p>

<p>转向之所以成立，正是因为 TDD 提供的恰好是 AI 最缺的那三样东西：把大任务切成小步的<strong>粒度</strong>、每次都一样形状的<strong>节奏</strong>、以及秒级的<strong>快速反馈</strong>。</p>

<h3 id="落地把意图和强制分成两层">落地：把「意图」和「强制」分成两层</h3>

<p>社区实践里最有价值的一条结构，是把流程要求拆成两层：</p>

<ul>
  <li><strong>引导层</strong>：告诉 AI 该怎么做。写在 <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> 这类说明文件里，提供上下文和意图。</li>
  <li><strong>强制层</strong>：不让 AI 做错事。做成工具链里的拦截钩子，在固定时点执行，模型愿不愿意都照样跑。</li>
</ul>

<p>举个具体例子：拦在 AI 写文件之前，读一份测试结果文件——<strong>如果当前一个失败测试都没有，就拦截写入</strong>，理由写得很直白：「所有测试都通过了。请先写一个失败的测试，再实现代码。」</p>

<p><strong>引导层可以商量，强制层不商量。</strong> 这个区分很要紧：只写一句「请先写测试」在 <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> 里，模型是可以「选择不听」的——它是一段建议，不是一条规则。而拦截钩子是确定性的，不管模型怎么想都会执行。</p>

<p>顺带说，这跟一条更普遍的工程原则是同一件事：<strong>凡是能用状态机、钩子、RPC 卡住的地方，就不要指望提示词</strong>。提示词是意图，机制才是执行。</p>

<h3 id="人写什么ai-写什么">人写什么，AI 写什么</h3>

<p>TDD 不要求你接受一份写死的规格。Kent Beck 建议人先自己写一份<strong>测试清单</strong>（Test List），把想验证的行为、边界、坑都列出来，再让 agent 审一遍、提遗漏。</p>

<p><strong>这一步不要交给 agent 起头</strong>——你对业务和领域的上下文比它多，而且你会追问。社区里有一版更细的四层做法可以参考：</p>

<ol>
  <li><strong>测试场景识别</strong>：把每条验收标准展开成场景（正常路径、边界情况、错误路径）；</li>
  <li><strong>测试点梳理</strong>：每个场景拆成二值的检查项，只回答「测什么」；</li>
  <li><strong>测试用例定义</strong>：每个检查项展开成「给定什么输入、执行什么操作、期望什么输出」——<strong>这是给 AI 最精确的指令</strong>；</li>
  <li><strong>测试开发文档</strong>：把用例映射到具体的测试文件、函数名、测试类型，产出一张覆盖矩阵。</li>
</ol>

<p>第一层有个隐藏收益：<strong>展开场景的过程本身就是对需求的第二次检验</strong>。写到「用户纠正的是意见分歧而非事实错误时不应触发」这一条时，你被迫回答「意见分歧和事实错误的边界在哪」——答不上来，说明验收标准还不够精确。</p>

<p>分工也就清楚了：<strong>清单和场景是人写的，测试代码可以是 AI 写的，但顺序不能反。</strong></p>

<h3 id="什么时候这套方法不划算">什么时候这套方法不划算</h3>

<p>上面讲的是「值得这么做」的情况。也有明确不划算的几种，知道了能省下不少无效努力：</p>

<table>
  <thead>
    <tr>
      <th>场景</th>
      <th>为什么不适合</th>
      <th>换什么做法</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>探索性 spike</strong></td>
      <td>目标还不确定，写测试等于给一个不知道长什么样的东西定死接口</td>
      <td>先在 worktree 里放开写，事后人工审 diff；想保留就补测试</td>
    </tr>
    <tr>
      <td><strong>配置、文档、一次性脚本</strong></td>
      <td>没有行为可断言，写出来的测试只是在测自己</td>
      <td>用 schema 校验、lint、格式检查代替</td>
    </tr>
    <tr>
      <td><strong>大规模机械重构</strong></td>
      <td>补测试的成本远高于重构本身</td>
      <td>先保证现有测试是绿的（它就是回归网），重构后跑一遍</td>
    </tr>
    <tr>
      <td><strong>依赖真机、真网络的集成</strong></td>
      <td>测试本身就不稳定，红绿分不清是真错还是环境抖</td>
      <td>单独一层，跑在定时任务里，不进 CI 的必经路径</td>
    </tr>
    <tr>
      <td><strong>需求本身还没想清楚</strong></td>
      <td>测试只能锁住你已经想清楚的部分</td>
      <td>先把需求写下来（哪怕是散文），再谈测试</td>
    </tr>
  </tbody>
</table>

<p>最后一条最要紧，也最常被跳过：<strong>「先写测试」要求人先把需求想清楚，而人往往正是想不清楚的那一方。</strong> 所以「清单和场景是人写的」这条纪律在实践里经常落不了地——不是懒，是<strong>真的想不清楚</strong>。这时候更该做的是先把问题写下来，而不是硬凑一份测试清单。</p>

<h2 id="三aethercode-怎么把-tdd-用在-agent-身上">三、AetherCode 怎么把 TDD 用在 agent 身上</h2>

<p>AetherCode 是个 AI 编码工作台：daemon 跑 JSON-RPC，桌面端和 TUI 连上来，模型在 daemon 里干活。既然我们做的就是「让 agent 写代码」这件事，那么第一个问题不是「我们的代码有多少测试」，而是——<strong>agent 干活的时候，测试在哪儿起作用？</strong></p>

<p>AetherCode 是开源项目，仓库在 <a href="https://github.com/maijun-sec/AetherCode">github.com/maijun-sec/AetherCode</a>，下面提到的类名和文档都能直接搜到。</p>

<p>下面按 agent 执行一个任务的实际链路来讲。</p>

<h3 id="agent-的系统提示词里就有验证这一阶段">agent 的系统提示词里就有「验证」这一阶段</h3>

<p><code class="language-plaintext highlighter-rouge">SystemPrompt.defaultWorkflow()</code> 给所有 agent 定了四个阶段：<strong>Phase 1 — Plan → Phase 2 — Explore → Phase 3 — Implement → Phase 4 — Verify</strong>。</p>

<p>第四阶段的原文要求：</p>

<blockquote>
  <ul>
    <li>After implementing a change, run the test suite (or the project’s build command — <code class="language-plaintext highlighter-rouge">mvn test</code>, <code class="language-plaintext highlighter-rouge">npm test</code>, <code class="language-plaintext highlighter-rouge">pytest</code>, <code class="language-plaintext highlighter-rouge">cargo test</code>, <code class="language-plaintext highlighter-rouge">go test</code>, etc.). <strong>Do not skip this step.</strong></li>
    <li>If the tests fail, fix the failures before claiming done.</li>
    <li>“I’ll let the user run the tests” is not acceptable when the test command is one line and takes seconds.</li>
    <li><strong>A “done” claim must include: what you changed, what you tested, what you did NOT test, and any caveats.</strong> A two-line “done” summary with no caveats is almost always wrong.</li>
  </ul>
</blockquote>

<p>这一段小标题是 <code class="language-plaintext highlighter-rouge">Phase 4 — Verify (no "trust me" claims)</code>。</p>

<p>最后那条要求最值得注意：<strong>「你测了什么」和「你</strong>没<strong>测什么」必须一起报</strong>。这是对上面「AI 是 10 倍 Writer 不是 10 倍 Reviewer」的直接补丁——不让它自己宣称完备，让它把盲区显式说出来。</p>

<p>顺带说，<code class="language-plaintext highlighter-rouge">aethercode-prompts</code> 里还有一条 <code class="language-plaintext highlighter-rouge">DefaultSystemPromptSnapshotTest</code>，断言这四个阶段必须以带标签的段落存在，而不是在散文里提一句。<strong>提示词本身也被测试钉住了</strong>——不然改个措辞，四道工序就悄悄少了一道。</p>

<h3 id="复杂任务走-sdd-八阶段规格先冻结任务带验收口径">复杂任务走 SDD 八阶段：规格先冻结，任务带验收口径</h3>

<p>四阶段工作流适合中等任务。真正大的需求走 SDD（规格驱动）那条线，一共八个阶段，每个阶段有固定输入、固定产物、固定的可做与不可做：</p>

<table>
  <thead>
    <tr>
      <th>阶段</th>
      <th>做什么</th>
      <th>产物</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1 constitution</td>
      <td>项目原则（必做）</td>
      <td><code class="language-plaintext highlighter-rouge">constitution.md</code></td>
    </tr>
    <tr>
      <td>2 specify</td>
      <td>需求分析（必做）</td>
      <td><code class="language-plaintext highlighter-rouge">spec.md</code>，带 FR-NN / NFR-NN / <strong>AC-NN（Given-When-Then）</strong></td>
    </tr>
    <tr>
      <td>3 clarify</td>
      <td>需求澄清（选做）</td>
      <td><code class="language-plaintext highlighter-rouge">clarify.json</code></td>
    </tr>
    <tr>
      <td>4 plan</td>
      <td>详细设计（必做）</td>
      <td><code class="language-plaintext highlighter-rouge">design.md</code>，带接口契约</td>
    </tr>
    <tr>
      <td>5 analyze</td>
      <td>一致性分析（选做）</td>
      <td><code class="language-plaintext highlighter-rouge">analyze.json</code>（gap / conflict / coverage）</td>
    </tr>
    <tr>
      <td>6 tasks</td>
      <td>任务分析（必做）</td>
      <td><code class="language-plaintext highlighter-rouge">tasks.md</code>，每条任务带 <strong><code class="language-plaintext highlighter-rouge">acceptance_check</code></strong></td>
    </tr>
    <tr>
      <td>7 implement</td>
      <td>执行实现（必做）</td>
      <td>源代码 + <code class="language-plaintext highlighter-rouge">dev.log</code></td>
    </tr>
    <tr>
      <td>8 converge</td>
      <td>收敛验证（选做）</td>
      <td><code class="language-plaintext highlighter-rouge">convergence.json</code></td>
    </tr>
  </tbody>
</table>

<p>这套阶段定义放在 <code class="language-plaintext highlighter-rouge">aethercode-sdd/src/main/resources/skills/sdd/references/phase-*.md</code> 里。三个设计最值得说：</p>

<p><strong>一、规格是 frozen 的。</strong> 第 7 阶段的「Forbidden behaviors」里第一条就是：不允许修改 <code class="language-plaintext highlighter-rouge">constitution.md</code> / <code class="language-plaintext highlighter-rouge">spec.md</code> / <code class="language-plaintext highlighter-rouge">design.md</code> / <code class="language-plaintext highlighter-rouge">tasks.md</code>，理由写得很清楚——<strong>spec 是 source of truth</strong>。agent 不能一边改需求一边说「我按需求做完了」。</p>

<p><strong>二、每条任务自带验收口径。</strong> 第 6 阶段产出的 <code class="language-plaintext highlighter-rouge">tasks.md</code>，每条任务长这样：</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gu">## T-NN: &lt;title&gt;</span>
<span class="p">-</span> depends_on: (none / [T-MM])
<span class="p">-</span> files_to_create_or_modify: <span class="nt">&lt;list&gt;</span>
<span class="p">-</span> acceptance_check: <span class="nt">&lt;verifiable&gt;</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">acceptance_check: &lt;verifiable&gt;</code> 这一行是关键：<strong>验收标准是结构化条目，不是提示词里的一句话</strong>。它跟 <code class="language-plaintext highlighter-rouge">Task</code> 那个 record 是两回事——<code class="language-plaintext highlighter-rouge">aethercode-tasks</code> 的 <code class="language-plaintext highlighter-rouge">Task</code> 只有 <code class="language-plaintext highlighter-rouge">id / type / status / description / parentTaskId / createdAtMs / endedAtMs</code>，不带验收字段；验收标准活在这些 markdown 产物里。任务拆分的粒度也很有意思，第 6 阶段的暂停消息摘要示例是「15 个 T-NN 任务：5 算法 × 3 数组类型 = 15 实现 + 1 单元测试 + 1 mvn test」——<strong>测试本身就是一条任务</strong>。</p>

<p><strong>三、收敛阶段把验收变成结构化产物。</strong> 第 8 阶段只产出一个文件 <code class="language-plaintext highlighter-rouge">convergence.json</code>：</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"validation"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"tool"</span><span class="p">:</span><span class="w"> </span><span class="s2">"mvn"</span><span class="p">,</span><span class="w"> </span><span class="nl">"pass"</span><span class="p">:</span><span class="w"> </span><span class="mi">12</span><span class="p">,</span><span class="w"> </span><span class="nl">"fail"</span><span class="p">:</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="nl">"skipped"</span><span class="p">:</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="nl">"command"</span><span class="p">:</span><span class="w"> </span><span class="s2">"mvn test"</span><span class="w"> </span><span class="p">},</span><span class="w">
  </span><span class="nl">"requirements_coverage"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"covered"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"FR-1"</span><span class="p">,</span><span class="w"> </span><span class="s2">"FR-2"</span><span class="p">],</span><span class="w"> </span><span class="nl">"missing"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"FR-3"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">
  </span><span class="nl">"edge_case_coverage"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"covered"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"empty array"</span><span class="p">],</span><span class="w"> </span><span class="nl">"missing"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"already sorted"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">
  </span><span class="nl">"recommendation"</span><span class="p">:</span><span class="w"> </span><span class="s2">"ready-to-merge|fix-X|extend-tests"</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>请注意 <code class="language-plaintext highlighter-rouge">requirements_coverage</code> 这一项——它按 <strong>FR-NN 编号</strong>核对哪些需求被覆盖了，而不是按代码路径核对。这就是第一节说的「<strong>测试锚定在需求上，不锚定在实现上</strong>」的落地形态：agent 换了实现方案，FR 编号不变，覆盖情况照旧能判。</p>

<p><code class="language-plaintext highlighter-rouge">recommendation</code> 三个取值也说明了设计意图：<code class="language-plaintext highlighter-rouge">ready-to-merge</code> 是「可以合了」，<code class="language-plaintext highlighter-rouge">fix-X</code> 是「有具体要修的」，<code class="language-plaintext highlighter-rouge">extend-tests</code> 是「需求没被测到，去补测试」。三者都不是「绿了就行」。</p>

<p>另外，第 7 阶段的暂停消息里，交付必须带测试读数：「测试结果：mvn test 通过 X 个，失败 0 个」。<strong>报不出读数的交付不算交付。</strong></p>

<h3 id="tdd-本身是一个可调用的工作流">TDD 本身是一个可调用的工作流</h3>

<p>上面是 SDD 那条「先规格后实现」的线。另一条线是直接把 TDD 做成一个配方——<code class="language-plaintext highlighter-rouge">workflows/tdd-feature.yaml</code>：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1. RED    — write a single failing test that names the behaviour.
2. GREEN  — write the minimum code to make the test pass.
3. REFACTOR — clean up without changing behaviour; keep the test green.

Never write implementation code before the test exists and fails.
</code></pre></div></div>

<p>第一步的措辞是 <strong>a single failing test</strong>——一个，不是一批。这正是第二节说的「一次只写一个失败测试」的铁律，落到了机器可执行的形式上。</p>

<p><code class="language-plaintext highlighter-rouge">workflows/</code> 下还有五个同类配方：<code class="language-plaintext highlighter-rouge">code-review.yaml</code>、<code class="language-plaintext highlighter-rouge">explain-failure.yaml</code>、<code class="language-plaintext highlighter-rouge">migrate-deps.yaml</code>、<code class="language-plaintext highlighter-rouge">security-audit.yaml</code>、<code class="language-plaintext highlighter-rouge">add-changelog.yaml</code>。它们由 <code class="language-plaintext highlighter-rouge">WorkflowEngine</code> / <code class="language-plaintext highlighter-rouge">WorkflowLoader</code> / <code class="language-plaintext highlighter-rouge">WorkflowValidator</code> 执行，<code class="language-plaintext highlighter-rouge">SessionSpawner</code> 负责起会话。</p>

<p>有一点容易被忽略：<strong>工作流里还带预算</strong>。<code class="language-plaintext highlighter-rouge">limits</code> 段定义了 <code class="language-plaintext highlighter-rouge">wallClockMs</code>、<code class="language-plaintext highlighter-rouge">tokens</code>、<code class="language-plaintext highlighter-rouge">calls</code>、<code class="language-plaintext highlighter-rouge">fileWrites</code> 的上限。也就是说——<strong>预算也是规格的一部分</strong>。「写测试」这件事在 agent 身上，不只是「写对」，还有「别写飘」。</p>

<h3 id="agent-整体行为用场景矩阵验收">agent 整体行为用场景矩阵验收</h3>

<p>前面几层都在管「agent 写的代码对不对」。但 agent 这个东西本身还有另一类性质：它会跟用户环境打交道，会读文件、会调工具、可能写到不该写的地方。这些行为不是某个函数的单元测试能覆盖的。</p>

<p>所以我们有一层<strong>场景矩阵</strong>：<code class="language-plaintext highlighter-rouge">scripts/bench-scenarios.mjs</code> 加 <code class="language-plaintext highlighter-rouge">.aethercode/bench-scenarios/</code> 下的夹具。每个场景自己起一个 daemon，走真 HTTP RPC 和真的 WebSocket 事件流，然后查三件事：</p>

<ul>
  <li><strong>判定（verdict）</strong>：daemon 在协议上给出的判定对不对。要同时查三处——<code class="language-plaintext highlighter-rouge">run_start</code> 帧里带的判定、轮询 <code class="language-plaintext highlighter-rouge">getState</code> 拿到的判定、以及 wire 上的 reason 字段——并且三处必须一致。</li>
  <li><strong>产物（outcome）</strong>：按场景类型查实际结果。文件落盘而且非空、文件真的被改了（哈希变了）、引用的是本仓库真实的 file:line、没有上网、命令真跑了、turn budget 触发而且标记为 error……每个场景的 <code class="language-plaintext highlighter-rouge">mode</code> 决定查哪几项。</li>
  <li><strong>护栏（guard）</strong>：边界有没有被越过。这一件最容易被忽略，也最值钱。</li>
</ul>

<p>护栏那一层有两个细节值得单独说。一个是只读场景：判定了「只读」，那就必须<strong>零新增文件</strong>、<strong>没碰过写通道</strong>。另一个是<strong>「用户的东西没被动」</strong>——<code class="language-plaintext highlighter-rouge">snapshotAgents()</code> 把 <code class="language-plaintext highlighter-rouge">~/.aethercode/agents/</code> 下每个文件逐个算 sha256 前后比对，<code class="language-plaintext highlighter-rouge">snapshotRepo()</code> 把 <code class="language-plaintext highlighter-rouge">git ls-files</code> 列出的每个 tracked 文件逐个算 sha256 前后比对。为什么连用户自己的 agent 注册表都要查？因为它<strong>在沙箱之外</strong>，只盯着沙箱看不见这种损坏。</p>

<p>还有一条：<strong>期望值是写死在台架里的，不是从读数反推的</strong>。我们那份《场景矩阵》的设计文档里的原话是——期望是设计契约，不是快照。否则台架就只是把分类器对着自己照镜子。</p>

<p>这套矩阵不是摆设，它抓到过真缺陷：有一轮判定说「只读」，但工具池实际上能写，结果多出来 4 个没人要的文件。</p>

<p>跑完的读数记在 <code class="language-plaintext highlighter-rouge">.aethercode/bench-scenarios/summary.json</code>：<strong>114 通过，2 失败</strong>。这两个数不是给谁看的成绩单，而是下次改动时的对照基线——<strong>要看的不是失败数本身，是失败集合有没有新增</strong>。那 2 个是长期已登记的已知项，不是新冒出来的。</p>

<p>跟单元测试的关系是<strong>互补</strong>不是替代：单元测试钉代码内部的不变量，场景矩阵钉<strong>产品行为契约</strong>，而且跑在真 daemon 上。</p>

<h3 id="评测层让-agent-真干活然后判它过不过">评测层：让 agent 真干活，然后判它过不过</h3>

<p>再往上一层，是「agent 这个能力本身好不好」。<code class="language-plaintext highlighter-rouge">aethercode-core</code> 的 <code class="language-plaintext highlighter-rouge">eval</code> 包是这么定义的：</p>

<table>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">EvalRequest</code> 带 <code class="language-plaintext highlighter-rouge">description</code> / <code class="language-plaintext highlighter-rouge">userMessage</code> / <code class="language-plaintext highlighter-rouge">input</code> / <strong><code class="language-plaintext highlighter-rouge">expectedBehavior</code></strong>（期望行为的列表）/ <strong><code class="language-plaintext highlighter-rouge">passCriteria</code></strong>（判过的具体条件）/ <strong><code class="language-plaintext highlighter-rouge">scoringMethod</code></strong>（<code class="language-plaintext highlighter-rouge">deterministic</code></td>
      <td><code class="language-plaintext highlighter-rouge">llm-judge</code></td>
      <td><code class="language-plaintext highlighter-rouge">human</code>）/ <code class="language-plaintext highlighter-rouge">tags</code>。</td>
    </tr>
  </tbody>
</table>

<p><code class="language-plaintext highlighter-rouge">DeterministicEvaluator</code> 从 <code class="language-plaintext highlighter-rouge">passCriteria.get("checks")</code> 取检查项——<strong>取不到就直接判不通过</strong>（<code class="language-plaintext highlighter-rouge">score 0.0</code>，<code class="language-plaintext highlighter-rouge">pass false</code>）。这是一条硬规定：没有判定标准的任务，不许「默认通过」。</p>

<p>跑这些评测的 <code class="language-plaintext highlighter-rouge">AgentRunner</code> 则负责把 agent 关在笼子里：强制成本与时延上限、完整 trace、确定性权限（不允许中途弹窗打断）、强制 loop 检测。<strong>评测一个 agent，测的往往是它有没有失控，而不是它聪不聪明。</strong></p>

<p>再外面一层是 <code class="language-plaintext highlighter-rouge">aethercode-evals</code> 模块：<code class="language-plaintext highlighter-rouge">benchmarks/</code> 下接了 HumanEval、MMLU、SWE-bench、AgentInstruct 四套公开基准，还有 <code class="language-plaintext highlighter-rouge">capability/</code> 下按能力维度分的十几套（planning / memory / state / reflect / tooluse / multitool / robustness / safety / canary / interface / loop / multiagent）。真 LLM 那条门禁是 <code class="language-plaintext highlighter-rouge">BenchmarkReportRealLlmTest</code>：9 个 benchmark、每题 5 个样本、由 <code class="language-plaintext highlighter-rouge">adapter.grade(task, out)</code> 判过不过，读数是一张 <code class="language-plaintext highlighter-rouge">Benchmark / Attempt / Pass@1</code> 的表加 TOTAL。</p>

<p>它默认<strong>不跑</strong>，要两个条件同时满足才跑：<code class="language-plaintext highlighter-rouge">-Daethercode.evals.realLlm=true</code> 和环境里有 <code class="language-plaintext highlighter-rouge">MINIMAX_API_KEY</code>。类注释里写明了原因：大约 270 道题、27 万 input token、20 分钟，<strong>默认构建既不该烧钱也不该变慢</strong>。</p>

<p>这个「双重闸门」的设计值得记一笔：需要真实模型、需要真实开销的验证，和必须永远绿的验证，是<strong>两种东西</strong>，不该混在一条命令里。</p>

<h3 id="门禁自己有牙才可信">门禁自己有牙才可信</h3>

<p>前面说过：判断一个测试有没有用，办法是引入一个缺陷看它会不会失败。听起来简单，落到工程上有一堆细节要处理对。</p>

<p>我们这边叫<strong>变异台架</strong>。做法是：把源码复制到临时沙箱 → 施加<strong>一处</strong>变异（用正则改一处）→ 跑真门禁 → 断言门禁<strong>必须变红</strong>。门禁还绿，就说明这个变异存活了，说明这个门禁对那个缺陷是瞎的。</p>

<p>头注释把这件事说得很直白：</p>

<blockquote>
  <p>a gate that has never been seen red is not a gate.</p>
</blockquote>

<p>以及：</p>

<blockquote>
  <p>Each mutation below breaks ONE thing the gate claims to protect, and the gate MUST report a failure. If a mutation survives, the gate is blind to that defect and the assertion is vacuous.</p>
</blockquote>

<p>台架本身有两个坑，都是踩出来的：</p>

<p><strong>一、门禁必须在第一次变异之前是绿的。</strong> <code class="language-plaintext highlighter-rouge">mutation-baseline.mjs</code> 里的 <code class="language-plaintext highlighter-rouge">requireGreenBaseline</code> 专门做这件事。理由很实在：一个本来就是红的门禁，在任何变异下都还是红，于是每个用例都会报「抓住了」——<strong>但那是因为错误的原因，这台架等于什么都没测</strong>。所以基线不绿就直接拒绝运行。</p>

<p><strong>二、空转不能当成绿。</strong> 我们那份《任务矩阵与一致性流程》的设计文档里记过一次：台架报「0 caught, 0 missed」并且<strong>退出 0</strong>，空转被当成了通过。</p>

<p>同一份文档还把「变异见证」做成了制度：<strong>一个行为配一个见证</strong>，不是一个规则配一个见证。读数长这样：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>RESULT: 18 caught, 0 missed, 18 attempted
</code></pre></div></div>

<p>「见证」是一个专门的测试用例，用来证明某条断言还活着。它必须和被保护的断言<strong>对得上</strong>——文档里记过一次打偏：见证断言的是 <code class="language-plaintext highlighter-rouge">look-alike</code> 这个词，变异却打在 <code class="language-plaintext highlighter-rouge">CONTAINS</code> 上，被改的词和被断言的词根本不是同一个，那个变异自然打不中见证。改到 <code class="language-plaintext highlighter-rouge">look-alike</code> 那句上才抓住。</p>

<p>台架有两代，跑法不同：TUI 的 <code class="language-plaintext highlighter-rouge">scripts/test/</code> 下 24 个 <code class="language-plaintext highlighter-rouge">r*-mutate.mjs</code> 是手动跑的（文件头自述「NOT part of npm test」），另有 3 个放在项目根的 <code class="language-plaintext highlighter-rouge">.aethercode/</code> 下；7 个 <code class="language-plaintext highlighter-rouge">*-mutation.test.mjs</code> 则在 <code class="language-plaintext highlighter-rouge">npm test</code> 里，随 CI 跑。</p>

<h3 id="必须绿的和要花钱的物理分开">必须绿的和要花钱的，物理分开</h3>

<p>上面几层加起来有个共同点：<strong>它们大多不在 CI 里</strong>。</p>

<p><code class="language-plaintext highlighter-rouge">.github/workflows/test.yml</code> 的两条 job 是 <code class="language-plaintext highlighter-rouge">java-test</code>（<code class="language-plaintext highlighter-rouge">mvn -B -ntp test</code> 全树，外加把几个关键测试类单独钉一遍）和 <code class="language-plaintext highlighter-rouge">ts-test</code>（<code class="language-plaintext highlighter-rouge">pnpm -r --workspace-concurrency=2 test</code>，外加三个 bench/smoke 脚本）。在 <code class="language-plaintext highlighter-rouge">.github</code> 里 grep <code class="language-plaintext highlighter-rouge">bench-scenarios</code>、<code class="language-plaintext highlighter-rouge">realLlm</code>、<code class="language-plaintext highlighter-rouge">mutation</code>、<code class="language-plaintext highlighter-rouge">evals</code> —— <strong>零匹配</strong>。</p>

<p>也就是说：场景矩阵、真 LLM 报告、evals 套件、27 个独立变异台架，都<strong>不在 CI</strong>；只有那 7 个 in-suite 的变异门禁跟着 <code class="language-plaintext highlighter-rouge">pnpm -r test</code> 进 CI。</p>

<p>这个切分是刻意的：</p>

<ul>
  <li><strong>必须永远绿的</strong>（单元测试、in-suite 变异门禁、bench/smoke）进 CI，它们快、免费、不需要密钥；</li>
  <li><strong>需要真实模型或真实开销的</strong>（场景矩阵、真 LLM 报告、完整 evals）手动或定时跑，它们的读数进基线，用来跟下一轮比。</li>
</ul>

<h3 id="基线纪律套件本来就是红的">基线纪律：套件本来就是红的</h3>

<p>最后一条纪律，是从上面那层自然长出来的。</p>

<p><strong>先说清楚适用前提</strong>：如果你手里是一套全绿的套件，下面这段不适用于你——全绿的时候「跑一遍看有没有新增失败」就够了。真正需要这套纪律的，是<strong>你有一份长期红的套件</strong>的时候，比如历史遗留的断言、依赖外部环境的集成测试、长期挂着没人修的 flaky。</p>

<p>我们的测试套件就是这种：1846 个测试里有 49 个失败，是历史遗留，不是产品坏了。这件事一旦是常态，「这次改完套件红了」这句话就完全不能用来判断「我是不是搞坏了」。</p>

<p>所以我们把两条写进了 <code class="language-plaintext highlighter-rouge">AGENTS.md</code>：</p>

<ul>
  <li><strong>规则一：比对失败集合要读原始字节，不要信控制台的转述。</strong> 门禁的失败集合要按「名字」比，不要按「控制台输出」比。真实翻车过一次：同一个测试在两次运行里分别显示成 <code class="language-plaintext highlighter-rouge">StatusBar: contains the ?? suggested rendering</code> 和 <code class="language-plaintext highlighter-rouge">StatusBar: contains the 💡 suggested rendering</code>——看着像两个不同的失败，其实是同一个，差异只是终端把一个字符解码坏了。</li>
  <li><strong>规则二：基线是一次测量，不是一个假设。</strong> 改完代码后，在 HEAD 的干净 <code class="language-plaintext highlighter-rouge">git worktree</code> 上跑<strong>同一批</strong>失败文件，比对失败<strong>集合</strong>而不是总数。当时的读数是 1846 例 / 49 失败，基线也是 49 失败，集合完全相同，新增 0、消失 0。</li>
</ul>

<p>结论也就变了：能拿去汇报的不是「零失败」，而是「<strong>零新增失败</strong>」。</p>

<p>还有一条配套的：<strong>套件比上轮红时，第一嫌疑是量具坏了，不是产品回归了</strong>。</p>

<h2 id="小结">小结</h2>

<p>如果把三段压成一句话，那就是：<strong>TDD 在 AI 时代的价值，不在于「多写了几个测试」，而在于它把一件原本靠人类自觉的事，变成了可执行、可强制、可复核的结构。</strong></p>

<p>具体到几条：</p>

<ol>
  <li><strong>TDD 买到的不是测试，是粒度、节奏和快速反馈。</strong> 这三样恰好是 AI 最缺的，也是它在写代码时最需要有人强制的。</li>
  <li><strong>AI 写的测试必须被「证伪」过才算数。</strong> 引入一个缺陷，它不变红，那就是装饰品——这句话同时适用于人写的测试。</li>
  <li><strong>写测试和写实现必须分开成两个上下文。</strong> 同一轮里干完这两件事，等于看过答案再出题。</li>
  <li><strong>引导层可以商量，强制层不商量。</strong> 能用钩子、状态机、契约卡住的地方，就不要指望提示词。</li>
  <li><strong>让 agent 干活，就给它一个可判定的验收口径。</strong> 判定、产物、护栏三件事都要能自动查；查不了的东西等于没有。</li>
</ol>

<p>对 AetherCode 自己来说，最后一条是这两年做得最多的一件事：<strong>把「agent 说它做完了」变成「机器核对它做完了」</strong>。规格先冻结、任务带验收口径、实现要报测试读数、收敛阶段按 FR 编号核对覆盖、场景矩阵查判定和产物和护栏、门禁自己要配变异见证、必须绿的和要花钱的物理分开、套件本来就是红的所以只比集合不比总数。</p>

<p>一环扣一环，但每环的判据都是同一个：<strong>这条测试，能不能抓住一个故意制造的缺陷？</strong> 抓不住，它就不该被信任。</p>]]></content><author><name>maijun</name></author><category term="AI Agent" /><category term="测试驱动开发" /><category term="智能体工程" /><category term="工程方法" /><summary type="html"><![CDATA[摘要：TDD 在 AI 编程之前是「可选的最佳实践」，在 AI 编程之后变成了「必要的工程结构」——因为要约束的已经不是人，而是一个看不到内部推理过程、也不会主动追问的系统。 读完你会拿到三样东西：一是 TDD 真正买到的三样东西（粒度、节奏、快速反馈）和「测试是规格」这个容易被跳过的要点；二是 AI 编程为什么让这套方法从「锦上添花」变成「不可或缺」——AI 写的测试为什么经常什么都没验，以及怎么把流程从建议变成强制；三是什么时候这套方法不划算（探索性 spike、配置改动、需求还没想清楚）。 第三段讲 AetherCode 自己怎么把这套东西用在 agent 执行任务上——系统提示词里的验证阶段、SDD 八阶段里带验收口径的任务条目、场景矩阵对 agent 整体行为的判定/产物/护栏三件套，以及门禁怎么配变异见证。]]></summary></entry><entry><title type="html">[AetherCode] git worktree 实战：给每个 AI Agent 一个独立工作目录</title><link href="https://maijun-sec.github.io/2026/12/01/git-worktree-for-ai-agents/" rel="alternate" type="text/html" title="[AetherCode] git worktree 实战：给每个 AI Agent 一个独立工作目录" /><published>2026-12-01T10:30:00+08:00</published><updated>2026-12-01T10:30:00+08:00</updated><id>https://maijun-sec.github.io/2026/12/01/git-worktree-for-ai-agents</id><content type="html" xml:base="https://maijun-sec.github.io/2026/12/01/git-worktree-for-ai-agents/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：一个仓库、几个 AI 同时改代码，最先崩的往往不是模型，而是文件系统。<code class="language-plaintext highlighter-rouge">git worktree</code> 是 git 自带的答案：同一份对象库，多个独立工作目录，谁也不踩谁。但它的坑比它的功能多——本文先把机制和七个坑讲清楚（前面五个是本机跑出来的原始报错，第六条是硬规则的推论，第七条是检出语义），再说清 AI Agent 到底为什么需要它、什么时候不该用它，最后讲 AetherCode 自己怎么用：一套「建 → 用 → 合 → 删」的方案怎么落地，以及其中几处真实缺陷各自教会了什么。</p>
</blockquote>

<p><strong>先交代一件还没做完的事</strong>：AetherCode 的 worktree 生命周期里，桌面端那条路径目前<strong>还没接上</strong>——面板写着「下一个会话绑到 xxx」，实际绑到的是 daemon 的启动目录。这是已知且未修的缺口，本文单独讲一节。</p>

<!--more-->

<h2 id="先把-worktree-是什么说准">先把 worktree 是什么说准</h2>

<p><code class="language-plaintext highlighter-rouge">git worktree</code> 让一个仓库同时拥有<strong>多个工作目录</strong>。每个目录里是完整的源码树，但它们共用同一份对象库——不是各存一份。</p>

<p>我在本机实测（Git 2.40.0.windows.1）建了一个仓库，然后加了一个 worktree：</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git worktree add &lt;root&gt;/wt-feature <span class="nt">-b</span> feature/x HEAD
Preparing worktree <span class="o">(</span>new branch <span class="s1">'feature/x'</span><span class="o">)</span>
HEAD is now at 0106db3 init
</code></pre></div></div>

<p>关键在 worktree 目录里的 <code class="language-plaintext highlighter-rouge">.git</code> —— 它<strong>不是目录，是一个文件</strong>：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gitdir: C:/Users/maijun/AppData/Local/Temp/mj-wt-demo/demo/.git/worktrees/wt-feature
</code></pre></div></div>

<p>主仓库那边相应多了一个 <code class="language-plaintext highlighter-rouge">.git/worktrees/</code> 目录。而 worktree 自己的 <code class="language-plaintext highlighter-rouge">.git/objects</code> <strong>不存在</strong>——它没有自己的对象库，所有对象都从主仓库那一份里取。</p>

<p>这就是 worktree 和 clone 的根本差别：<strong>clone 是复制，worktree 是共享</strong>。共享带来三个直接的好处：</p>

<ul>
  <li>建一个 worktree 几乎不花时间也不占磁盘（大仓库上尤其明显）；</li>
  <li>各个 worktree 里的提交、分支、标签天然是同一套，不需要 push/pull 来同步；</li>
  <li>在 worktree 里提交的 commit，主仓库立刻就能看到。</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">git worktree list --porcelain</code> 把这些信息列出来，空行分段，一段一个 worktree：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>worktree C:/Users/maijun/AppData/Local/Temp/mj-wt-demo/demo
HEAD 0106db315cbda7ecd2b54d0adf24ad0d60378b1e
branch refs/heads/main

worktree C:/Users/maijun/AppData/Local/Temp/mj-wt-demo/wt-feature
HEAD 0106db315cbda7ecd2b54d0adf24ad0d60378b1e
branch refs/heads/feature/x
</code></pre></div></div>

<h3 id="它和-branch-差在哪">它和 branch 差在哪</h3>

<p>branch 和 worktree 是<strong>正交</strong>的两件事：branch 是提交的指针，worktree 是文件的一份检出。平时我们只在一个目录里切分支，感觉它们是一回事；一旦要同时持有两份工作状态，就得把这两件事拆开。</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>clone</th>
      <th>branch</th>
      <th>worktree</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>一份对象库</td>
      <td>否，各存一份</td>
      <td>共用</td>
      <td>共用</td>
    </tr>
    <tr>
      <td>独立的工作目录</td>
      <td>是</td>
      <td>否，只有一个目录</td>
      <td>是</td>
    </tr>
    <tr>
      <td>目录里 <code class="language-plaintext highlighter-rouge">.git</code> 的形态</td>
      <td>目录</td>
      <td>目录</td>
      <td><strong>文件</strong>，指向 <code class="language-plaintext highlighter-rouge">.git/worktrees/&lt;名字&gt;</code></td>
    </tr>
    <tr>
      <td>能否同时持有两份工作状态</td>
      <td>能</td>
      <td>不能</td>
      <td>能</td>
    </tr>
    <tr>
      <td>建一个的开销</td>
      <td>大（复制对象库）</td>
      <td>零（只是移动指针）</td>
      <td>小（写一次 checkout）</td>
    </tr>
  </tbody>
</table>

<h2 id="七个坑">七个坑</h2>

<p>下面七条里，前五条是本机跑出来的原始报错，第六条是从坑一那条硬规则推出来的，第七条是 <code class="language-plaintext highlighter-rouge">git worktree add</code> 的检出语义。</p>

<h3 id="坑一同一个分支不能被两个-worktree-同时检出">坑一：同一个分支不能被两个 worktree 同时检出</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git worktree add &lt;root&gt;/wt-dup feature/x
Preparing worktree <span class="o">(</span>checking out <span class="s1">'feature/x'</span><span class="o">)</span>
fatal: <span class="s1">'feature/x'</span> is already checked out at <span class="s1">'C:/Users/.../wt-feature'</span>
</code></pre></div></div>

<p>这是 git 的硬规则：<strong>一个分支只能被一个工作目录检出</strong>。它同时也解释了坑六。</p>

<h3 id="坑二-b-撞上已存在的分支会直接失败">坑二：<code class="language-plaintext highlighter-rouge">-b</code> 撞上已存在的分支会直接失败</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git worktree add &lt;root&gt;/wt-again <span class="nt">-b</span> feature/x HEAD
Preparing worktree <span class="o">(</span>new branch <span class="s1">'feature/x'</span><span class="o">)</span>
fatal: a branch named <span class="s1">'feature/x'</span> already exists
</code></pre></div></div>

<p>这条最要命，因为它<strong>不是边缘情况，它就是重试的样子</strong>。上一次 <code class="language-plaintext highlighter-rouge">worktree add</code> 已经把分支建出来了，只是 checkout 被中断；重试时分支已在，命令直接报错。任何「创建失败就重试」的逻辑都会踩到它。</p>

<h3 id="坑三有未提交改动时-remove-会拒绝">坑三：有未提交改动时 remove 会拒绝</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git worktree remove &lt;root&gt;/wt-feature
fatal: <span class="s1">'C:\...\wt-feature'</span> contains modified or untracked files, use <span class="nt">--force</span> to delete it
</code></pre></div></div>

<p>git 在这里是对的：有未提交改动就删目录，等于销毁工作成果。要删就得显式 <code class="language-plaintext highlighter-rouge">--force</code>，让「我知道我在删什么」这件事留在命令行上。</p>

<h3 id="坑四手工删掉目录git-还记着它">坑四：手工删掉目录，git 还记着它</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git worktree list
C:/.../demo      0106db3 <span class="o">[</span>main]
C:/.../wt-stale  0106db3 <span class="o">[</span>stale/x] prunable
</code></pre></div></div>

<p>注意那个 <code class="language-plaintext highlighter-rouge">prunable</code>。目录没了，登记还在。<code class="language-plaintext highlighter-rouge">git worktree prune</code> 清掉。</p>

<p>这条在 agent 场景里出现频率很高：进程被 kill、机器重启、临时目录被清理器扫掉，都会留下这种僵尸登记。它们不占磁盘，却会让「我到底有哪些 worktree」这个问题的答案失真。</p>

<h3 id="坑五locked-的-worktree--force-也不管用">坑五：locked 的 worktree，<code class="language-plaintext highlighter-rouge">--force</code> 也不管用</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git worktree lock &lt;root&gt;/wt-locked
<span class="nv">$ </span>git worktree remove <span class="nt">--force</span> &lt;root&gt;/wt-locked
fatal: cannot remove a locked working tree<span class="p">;</span> use <span class="s1">'remove -f -f'</span> to override or unlock first
</code></pre></div></div>

<p>注意 git 自己给的提示是 <strong><code class="language-plaintext highlighter-rouge">remove -f -f</code></strong>，两个 <code class="language-plaintext highlighter-rouge">-f</code>。一个 <code class="language-plaintext highlighter-rouge">-f</code> 是「我知道这有未提交改动」，两个 <code class="language-plaintext highlighter-rouge">-f</code> 是「我知道这被锁着」——两级确认。</p>

<p>而 worktree 什么时候会被锁？<strong>上一次 <code class="language-plaintext highlighter-rouge">worktree add</code> 没跑完的时候</strong>。git 会先写一个标记着 <code class="language-plaintext highlighter-rouge">initializing</code> 的锁文件，再做 checkout；checkout 中途被打断，锁就留下了。这正好和坑二接上：分支建出来了，目录可能只初始化了一半。</p>

<h3 id="坑六合并不能在-worktree-里做">坑六：合并不能在 worktree 里做</h3>

<p>这条不是报错，是前面那条硬规则的推论：<strong>目标分支已经被检出在别处时，你没法在 worktree 里再检出它</strong>。所以合并必须发生在<strong>目标分支当前所在的那个仓库</strong>里，也就是主仓库。</p>

<p>这条对 agent 编排影响很大，下面 AetherCode 那节会看到它怎么被写进代码。</p>

<h3 id="坑七worktree-装的是-commit-的内容不是你工作区的内容">坑七：worktree 装的是 commit 的内容，不是你工作区的内容</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git worktree add &lt;root&gt;/wt-clean <span class="nt">-b</span> feature/clean HEAD
</code></pre></div></div>

<p>输出的形态和上面建第一个 worktree 时一样：<code class="language-plaintext highlighter-rouge">Preparing worktree</code> 之后跟一行 <code class="language-plaintext highlighter-rouge">HEAD is now at &lt;sha&gt;</code>。这行信息本身就在说明——<strong>worktree 里装的是那个 commit 上的内容</strong>，主工作区里还没提交的改动一行也不会跟过去。</p>

<p>这是「给每个 agent 一个目录」这个用法的前提级事实：agent 拿到的不是你的现场，而是从 commit 重新铺出来的一份干净副本。想把主工作区里的未提交改动带进 worktree，没有捷径：改动必须先变成一个 commit，worktree 才拿得到它。要么先在主工作区提交、再基于那个 commit 建 worktree；要么反过来，让改动在 worktree 里做出来，之后合回去（AetherCode 的 <code class="language-plaintext highlighter-rouge">mergeWorktree</code> 干的就是这件事）。</p>

<h2 id="ai-agent-为什么需要它">AI Agent 为什么需要它</h2>

<p>先说清楚要隔离的是什么。一个仓库里同时跑几个 agent，不出乱子的前提是三层隔离都成立：</p>

<table>
  <thead>
    <tr>
      <th>隔离的层次</th>
      <th>隔离的是什么</th>
      <th>靠什么实现</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>文件</td>
      <td>两个 agent 同时改同一个文件不会互相覆盖</td>
      <td>各自一份工作目录</td>
    </tr>
    <tr>
      <td>提交</td>
      <td>一个 agent 的 commit 不会插进另一个 agent 的提交序列中间</td>
      <td>各自一条分支</td>
    </tr>
    <tr>
      <td>对象库</td>
      <td>不会因为每人一份仓库副本而把对象存 N 遍</td>
      <td>worktree 天然共享</td>
    </tr>
  </tbody>
</table>

<p>前两层容易想到，第三层经常被忽略。clone 也能做到前两层，但代价是每个 agent 一份完整对象库——大仓库上这是几十兆到几 GB 的差别，而且<strong>克隆出来的副本之间不再自动同步</strong>：<code class="language-plaintext highlighter-rouge">git pull</code> 要在每个副本里各做一次，改错了还得挨个收拾。</p>

<p>worktree 三层一起解决，而且不需要额外同步。</p>

<p>于是「一个 agent 一个 worktree」就成了很自然的分工：</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>agent A ──► worktree A  ──► 分支 aethercode/task-a
agent B ──► worktree B  ──► 分支 aethercode/task-b
agent C ──► worktree C  ──► 分支 aethercode/task-c
                    └──────► 全部挂在同一个仓库的对象库上
</code></pre></div></div>

<p>工作目录也<strong>要放在仓库外面</strong>。放在仓库内部（比如 <code class="language-plaintext highlighter-rouge">&lt;repo&gt;/.worktrees/&lt;name&gt;</code>）有两个问题：一是 agent 的文件操作工具可能把 worktree 目录本身当成待改的文件（改到自己的脚手架）；二是 git 会把未忽略的目录算进工作树状态，<code class="language-plaintext highlighter-rouge">git status</code> 立刻变脏。放到临时目录或专门的 scratch 目录下，这两个问题都没有。</p>

<h2 id="什么时候不要用-worktree">什么时候不要用 worktree</h2>

<p>隔离是有代价的，不是所有任务都值得付这份代价。</p>

<ol>
  <li><strong>只有单个 agent 的普通任务。</strong> worktree 的全部价值来自「多个 agent 同时干活」这件事。单 agent、单任务、一条分支往前推的时候，多建一个目录只是多一次 checkout、多一份要清理的东西，切分支就够了。</li>
  <li><strong>构建产物很重的仓库，先解决依赖复现再说。</strong> worktree 装的是 commit 的内容，<code class="language-plaintext highlighter-rouge">dist/</code>、<code class="language-plaintext highlighter-rouge">node_modules</code> 这些都不在里面（后面「当测量基准」那节还会正面撞上同一个问题）。每个 worktree 都重建一遍依赖，隔离省下来的时间全还回去了。</li>
  <li><strong>需要共享同一份未提交改动的场景。</strong> worktree 之间共享的只有对象库，工作区状态是各自分离的（见坑七）。两个 agent 想基于同一份还没提交的改动开工，worktree 帮不上忙——这类场景要么先把改动提交成 commit，要么干脆共用一个目录串行做。</li>
  <li><strong>只是想看一眼某个文件或某条命令的结果。</strong> <code class="language-plaintext highlighter-rouge">git show</code> 就够了；建一个 worktree 再删掉，是拿最重的办法解决最轻的问题。</li>
</ol>

<h2 id="aethercode-的方案">AetherCode 的方案</h2>

<p>AetherCode 是开源的多智能体编码工作台（Java / Maven 多模块）：daemon 跑 JSON-RPC，前端（desktop / TUI）连上来，模型在 daemon 里干活。仓库在 <a href="https://github.com/maijun-sec/AetherCode">https://github.com/maijun-sec/AetherCode</a>，下面提到的类名都能直接搜到。</p>

<p>这一节讲我们自己的 worktree 支持是怎么设计的——核心实现是 <code class="language-plaintext highlighter-rouge">aethercode-sdk</code> 里的 <code class="language-plaintext highlighter-rouge">WorktreeManager</code>，协议层在 <code class="language-plaintext highlighter-rouge">aethercode-protocol</code> 的 <code class="language-plaintext highlighter-rouge">AetherCodeMethods</code>，前端在 <code class="language-plaintext highlighter-rouge">aethercode-desktop</code> 和 <code class="language-plaintext highlighter-rouge">aethercode-tui</code>。<strong>先说清楚一件事</strong>：这套生命周期在桌面端还有一段没接上（<code class="language-plaintext highlighter-rouge">createEngine</code> 那条 RPC 不解析 worktree），后面有一节会具体讲。</p>

<p>两处约定，免得读的时候别扭：</p>

<ul>
  <li>引用源码注释时，注释是<strong>设计意图</strong>，不是独立证据——注释和代码出自同一个人，读者分不清它是先有的设计记录还是事后补的叙事。所以每处注释后面我都补了<strong>能从外部观察到的行为差异</strong>（改前改后各是什么、靠哪个用例发现的、运行时到底吐了什么）。</li>
  <li>文中偶尔出现的 <code class="language-plaintext highlighter-rouge">Rxxx</code> 是<strong>本项目的内部迭代编号</strong>，外部读者可以忽略；注释引用里这类编号已经去掉，只保留讲机制的那部分。</li>
</ul>

<p>整体链路是这样的：</p>

<pre><code class="language-mermaid">graph LR;
    A["addWorktree&lt;br/&gt;建目录 + 建分支"] --&gt; B["createSession&lt;br/&gt;会话 cwd 切进去"]
    B --&gt; C["agent 在这个目录里干活"]
    C --&gt; D["mergeWorktree&lt;br/&gt;回到源仓库合并"]
    D --&gt; E["removeWorktree&lt;br/&gt;删目录 + 删分支"]
</code></pre>

<h3 id="命名与落位">命名与落位</h3>

<p>分支名固定加前缀：<code class="language-plaintext highlighter-rouge">aethercode/&lt;name&gt;</code>。落位则有两个来源，优先级是「显式参数 → 环境变量 → 兜底」：</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">AETHERCODE_WORKTREE_ROOT</code>：worktree 根目录；</li>
  <li>兜底是 <code class="language-plaintext highlighter-rouge">java.io.tmpdir</code> 下的 <code class="language-plaintext highlighter-rouge">aethercode-worktrees</code>。</li>
</ul>

<p>源仓库（worktree 挂靠的那个仓库）同样是一条解析链：显式参数 → 每个 manager 的 setter → 环境变量 <code class="language-plaintext highlighter-rouge">AETHERCODE_WORKTREE_SOURCE_REPO</code> → CLI 参数 <code class="language-plaintext highlighter-rouge">--worktree-source-repo</code>。</p>

<p><code class="language-plaintext highlighter-rouge">WorktreeManager</code> 的字段声明上留了一段很坦白的自白，值得原样引用：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/** The source repo resolved from the environment,
 *  read ONCE at construction. The javadoc
 *  used to promise "per-manager setter → env var
 *  → stub" but the env var was never actually
 *  read, so every deployment without an explicit
 *  {@code sourceRepo} argument silently degraded
 *  to the empty-directory stub. The resolution
 *  now happens here so the promise holds. */</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="nc">String</span> <span class="n">envSourceRepo</span><span class="o">;</span>
</code></pre></div></div>

<p><strong>注释里写了、环境变量也定义了，但没有任何代码去读它</strong>——于是所有没显式传参的部署全都悄悄降级成了「空目录」，而用户以为自己在用 git 隔离。这条后来由一轮专门的修复补上了。</p>

<p>上面那段是<strong>设计意图（源码注释原话）</strong>，本身不算证据。真正能从外部验证的行为差异有两条：<strong>改前</strong>，任何没有显式传 <code class="language-plaintext highlighter-rouge">sourceRepo</code> 的部署都静默降级成空目录，用户从面板上看不出区别；<strong>改后</strong>，环境变量 <code class="language-plaintext highlighter-rouge">AETHERCODE_WORKTREE_SOURCE_REPO</code> 真的会被读到，协议层的 <code class="language-plaintext highlighter-rouge">worktreeStatus</code> RPC 会返回 <code class="language-plaintext highlighter-rouge">available = false</code> 加一条 <code class="language-plaintext highlighter-rouge">reason</code>，桌面端把这行标成 <code class="language-plaintext highlighter-rouge">plain dir</code> 徽章、并把原因原样显示出来。结论由服务端给，RPC 响应和界面文案都能直接核对。</p>

<h3 id="降级必须显式不能看起来像">降级必须显式，不能「看起来像」</h3>

<p>上面那个降级是真实存在的设计：拿不到源仓库、<code class="language-plaintext highlighter-rouge">git</code> 不在 PATH 上、或者那个路径根本不是 git 仓库时，代码会<strong>创建一个空目录</strong>当作 worktree，让会话仍然能跑。</p>

<p>问题在于——<strong>空目录和真 worktree 在早期版本里长得一模一样</strong>：分支是 <code class="language-plaintext highlighter-rouge">null</code>，源仓库是 <code class="language-plaintext highlighter-rouge">null</code>。用户看着面板上那一行「一切正常」，实际上一行 git 隔离都没有。</p>

<p>修复的方式不是加更多字段，而是<strong>让结论由服务端直接给</strong>。状态结构体 <code class="language-plaintext highlighter-rouge">WorktreeManager.WorktreeState</code>：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="n">record</span> <span class="nf">WorktreeState</span><span class="o">(</span><span class="nc">String</span> <span class="n">name</span><span class="o">,</span> <span class="nc">Path</span> <span class="n">path</span><span class="o">,</span> <span class="nc">String</span> <span class="n">branch</span><span class="o">,</span> <span class="nc">String</span> <span class="n">sourceRepo</span><span class="o">,</span>
                            <span class="kt">boolean</span> <span class="n">isolated</span><span class="o">,</span> <span class="nc">String</span> <span class="n">reason</span><span class="o">)</span> <span class="o">{</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">isolated</code> 说这是不是真的 git 隔离，<code class="language-plaintext highlighter-rouge">reason</code> 说不隔离的具体原因。两个字段<strong>永远存在</strong>，不是「有才代表真」。源码注释把这条讲得很清楚（<code class="language-plaintext highlighter-rouge">WorktreeManager.WorktreeState</code> 的字段注释原话）：</p>

<blockquote>
  <p><code class="language-plaintext highlighter-rouge">branch != null</code> and <code class="language-plaintext highlighter-rouge">isolated == true</code> mean the same thing today, but they are separate fields on purpose: the wire contract must not make the client infer the verdict from the presence of an optional field — the verdict comes from the server, not from the client’s own parsing.</p>
</blockquote>

<p>翻译成人话：<strong>「有分支」是巧合，「是不是真隔离」是结论</strong>。让客户端从「字段有没有值」去推断结论，等于把判断逻辑复制到每个客户端——两份逻辑迟早会漂移。</p>

<p><strong>能从外部验证的是</strong>：这两个字段一路透到协议层——<code class="language-plaintext highlighter-rouge">worktreeStatus</code> RPC 返回的 <code class="language-plaintext highlighter-rouge">available</code> 与 <code class="language-plaintext highlighter-rouge">reason</code> 就是它们本身，没有第三处再推断一次；两个前端读的都是这同一份结论。</p>

<p>前端据此把每一行标成 <code class="language-plaintext highlighter-rouge">git</code> 或 <code class="language-plaintext highlighter-rouge">plain dir</code> 两个徽章，降级的那一行还把 <code class="language-plaintext highlighter-rouge">reason</code> 原样显示出来（桌面端 <code class="language-plaintext highlighter-rouge">WorktreePanel</code> 组件）。用户申请了隔离却没拿到，界面直接说清楚原因和补救办法：</p>

<blockquote>
  <p><code class="language-plaintext highlighter-rouge">"&lt;name&gt;" was created as a plain directory, NOT git isolation. </code> + reason</p>
</blockquote>

<p>协议层则把「能不能做真隔离」做成一个单独的 RPC <code class="language-plaintext highlighter-rouge">worktreeStatus</code>，返回 <code class="language-plaintext highlighter-rouge">available</code> 布尔值加 <code class="language-plaintext highlighter-rouge">reason</code>（<code class="language-plaintext highlighter-rouge">AetherCodeMethods.worktreeStatus</code>）。注释同样点明：<strong>探针只写一份</strong>——</p>

<blockquote>
  <p>The manager owns the probe — the protocol layer does not re-implement it (two copies of a probe drift).</p>
</blockquote>

<p><strong>能从外部验证的是</strong>：探针逻辑只有 manager 一处，协议层只做转发——全仓库只有一个 <code class="language-plaintext highlighter-rouge">worktreeStatus</code> RPC，两个前端读的都是这一份 <code class="language-plaintext highlighter-rouge">available</code> / <code class="language-plaintext highlighter-rouge">reason</code>。桌面端和 TUI 的徽章文案不同，但判定来源是同一个。</p>

<h3 id="进程调-git-的两个坑">进程调 git 的两个坑</h3>

<p>worktree 的逻辑最终都要落到「起一个 git 子进程」上。AetherCode 在这一步踩过两个非常经典的坑，两个都有源码注释记录。</p>

<p><strong>第一个：stdin 被继承了，会吃掉 RPC 流。</strong></p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// detach STDIN. Without it git INHERITS</span>
<span class="c1">// the daemon's stdin — which, in the stdio</span>
<span class="c1">// daemon, is the JSON-RPC pipe carrying the</span>
<span class="c1">// client's requests! A git command that reads</span>
<span class="c1">// stdin (or a pager / credential prompt) then</span>
<span class="c1">// CONSUMES the RPC stream, corrupting the</span>
<span class="c1">// protocol.</span>
</code></pre></div></div>

<p>stdio 模式下 daemon 的标准输入就是 JSON-RPC 的管道。git 子进程如果继承了它，一旦 git 想读 stdin（翻页器、凭据提示、甚至 <code class="language-plaintext highlighter-rouge">worktree add</code> 的 checkout 阶段），就会把客户端的请求当成自己的输入吃掉——<strong>协议直接损坏</strong>，而且症状是「daemon 好像卡住了」，极难定位。</p>

<p><strong>能从外部验证的是</strong>：改前，stdio 模式下 daemon 的 RPC 流被 git 读走，客户端表现为「daemon 卡住」、协议损坏；改后，git 子进程的 stdin 是一个开起来立刻关掉的管道，读到的永远是立即的 EOF——所以 <code class="language-plaintext highlighter-rouge">git worktree add</code> 的 checkout 阶段不会被输入阻塞，命令能自己跑完。</p>

<p>解法是显式切断：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">ProcessBuilder</span> <span class="n">pb</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ProcessBuilder</span><span class="o">(</span><span class="n">full</span><span class="o">).</span><span class="na">directory</span><span class="o">(</span><span class="nc">Path</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="n">cwd</span><span class="o">).</span><span class="na">toFile</span><span class="o">())</span>
        <span class="o">.</span><span class="na">redirectErrorStream</span><span class="o">(</span><span class="kc">true</span><span class="o">)</span>
        <span class="o">.</span><span class="na">redirectInput</span><span class="o">(</span><span class="nc">ProcessBuilder</span><span class="o">.</span><span class="na">Redirect</span><span class="o">.</span><span class="na">PIPE</span><span class="o">);</span>
<span class="nc">Process</span> <span class="n">p</span> <span class="o">=</span> <span class="n">pb</span><span class="o">.</span><span class="na">start</span><span class="o">();</span>
<span class="c1">// close the stdin pipe → git sees EOF immediately</span>
<span class="n">p</span><span class="o">.</span><span class="na">getOutputStream</span><span class="o">().</span><span class="na">close</span><span class="o">();</span>
</code></pre></div></div>

<p>开一个管道然后立刻关掉，git 读 stdin 时拿到的是立即的 EOF。注释里还解释了为什么不用 <code class="language-plaintext highlighter-rouge">Redirect.from(new File("/dev/null"))</code>——那在 Windows 上不通用。</p>

<p><strong>第二个：<code class="language-plaintext highlighter-rouge">waitFor()</code> 排在读流之前，管道缓冲区会塞满。</strong></p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// drain the output CONCURRENTLY with the</span>
<span class="c1">// wait. The old code called waitFor() FIRST and</span>
<span class="c1">// read the stream AFTER — a textbook pipe-buffer</span>
<span class="c1">// deadlock: `git worktree add` prints "Updating</span>
<span class="c1">// files: N%" for every file, which overflows</span>
<span class="c1">// the 64KB pipe buffer, git blocks on write,</span>
<span class="c1">// and waitFor() times out even though git is</span>
<span class="c1">// making progress.</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">git worktree add</code> 在大仓库上会为每个文件打印一行 <code class="language-plaintext highlighter-rouge">Updating files: N%</code>，输出量轻松超过 64KB 的管道缓冲区。老代码先 <code class="language-plaintext highlighter-rouge">waitFor()</code> 再读流——git 写不进去卡住，<code class="language-plaintext highlighter-rouge">waitFor()</code> 等不到退出，超时。而 git 其实一直在干活，只是进度卡在缓冲区里。<strong>结果是 worktree 停在半初始化的状态，还带着一个写着 <code class="language-plaintext highlighter-rouge">initializing</code> 的锁文件</strong>——也就是坑五。</p>

<p><strong>能从外部验证的是</strong>：改前，git 阻塞在写、<code class="language-plaintext highlighter-rouge">waitFor()</code> 超时，worktree 停在半初始化状态并留下 <code class="language-plaintext highlighter-rouge">initializing</code> 锁文件（这正是坑五要 <code class="language-plaintext highlighter-rouge">remove -f -f</code> 的那种残留）；改后，输出由另一个线程并发抽干，主线程只等退出，worktree 能正常建完。</p>

<p>修法是另起一个线程并发地抽干输出，主线程只管等：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">StringBuilder</span> <span class="n">sb</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">StringBuilder</span><span class="o">();</span>
<span class="nc">Thread</span> <span class="n">drain</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Thread</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="kt">var</span> <span class="n">br</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">InputStreamReader</span><span class="o">(</span>
            <span class="n">p</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">(),</span> <span class="nc">StandardCharsets</span><span class="o">.</span><span class="na">UTF_8</span><span class="o">)))</span> <span class="o">{</span>
        <span class="nc">String</span> <span class="n">line</span><span class="o">;</span>
        <span class="k">while</span> <span class="o">((</span><span class="n">line</span> <span class="o">=</span> <span class="n">br</span><span class="o">.</span><span class="na">readLine</span><span class="o">())</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="n">sb</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">line</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="s">"\n"</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">Exception</span> <span class="n">ignored</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// the stream closes when the process dies</span>
    <span class="o">}</span>
<span class="o">},</span> <span class="s">"worktree-git-drain"</span><span class="o">);</span>
<span class="n">drain</span><span class="o">.</span><span class="na">setDaemon</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
<span class="n">drain</span><span class="o">.</span><span class="na">start</span><span class="o">();</span>
</code></pre></div></div>

<p>这两条坑合起来有个共同的教训，源码里也点破了：<strong>工具的契约要从它的源码里读</strong>。「进程退出后再读输出」只在输出能装进管道缓冲区时才是安全的——而这个前提从来没人写在文档里。</p>

<h3 id="失败与重试的语义">失败与重试的语义</h3>

<p><strong>创建：分支已存在就改成「挂上去」，而不是再试一次。</strong></p>

<p>对应坑二。<code class="language-plaintext highlighter-rouge">WorktreeManager.addWorktree</code> 先按正常路径建分支，失败了先问一句「这个分支是不是已经在了」：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">try</span> <span class="o">{</span>
    <span class="n">runGit</span><span class="o">(</span><span class="n">effSourceRepo</span><span class="o">,</span>
            <span class="s">"worktree"</span><span class="o">,</span> <span class="s">"add"</span><span class="o">,</span> <span class="n">path</span><span class="o">.</span><span class="na">toString</span><span class="o">(),</span> <span class="s">"-b"</span><span class="o">,</span> <span class="n">branch</span><span class="o">,</span> <span class="n">effBaseBranch</span><span class="o">);</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">Exception</span> <span class="n">first</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">if</span> <span class="o">(!</span><span class="n">branchExists</span><span class="o">(</span><span class="n">effSourceRepo</span><span class="o">,</span> <span class="n">branch</span><span class="o">))</span> <span class="o">{</span>
        <span class="k">throw</span> <span class="n">first</span><span class="o">;</span>  <span class="c1">// a real failure — surface it</span>
    <span class="o">}</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">"R388b: branch {} already exists — attaching to it instead of creating it"</span><span class="o">,</span>
            <span class="n">branch</span><span class="o">);</span>
    <span class="n">runGit</span><span class="o">(</span><span class="n">effSourceRepo</span><span class="o">,</span>
            <span class="s">"worktree"</span><span class="o">,</span> <span class="s">"add"</span><span class="o">,</span> <span class="n">path</span><span class="o">.</span><span class="na">toString</span><span class="o">(),</span> <span class="n">branch</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>注意它是<strong>先分清「分支已存在」和「真的失败」</strong>，而不是无脑重试。判断分支存不存在用 <code class="language-plaintext highlighter-rouge">git branch --list</code> 而不是 <code class="language-plaintext highlighter-rouge">show-ref</code> 或 <code class="language-plaintext highlighter-rouge">rev-parse</code>，理由也在注释里：<code class="language-plaintext highlighter-rouge">--list</code> 接受模式、查不到就返回空列表，而 <code class="language-plaintext highlighter-rouge">rev-parse</code> 失败时会把输入原样打出来——那样「查不到」和「命令回显了我的参数」就分不清了。</p>

<p><strong>能从外部验证的是</strong>：改前，重试一次撞上 <code class="language-plaintext highlighter-rouge">-b</code> 就直接失败（就是坑二那条 <code class="language-plaintext highlighter-rouge">a branch named 'feature/x' already exists</code>），worktree 建不出来；改后，同样再跑一次不会报错，而是换成挂到已有分支上的那条命令，worktree 出现在 <code class="language-plaintext highlighter-rouge">git worktree list</code> 里、面板上多出一行。</p>

<p><strong>删除：git 没放手，就不许忘记它。</strong></p>

<p>老代码是「先从内存表里删掉，再去删目录」。git 删除失败时，<strong>daemon 已经忘了这个 worktree，但 git 还留着它</strong>：列表里没有了（因为 daemon 查的是自己的表），git 那边的登记还在，分支也还在。用户想按名字重试删除都做不到——因为函数会告诉你「没这个东西」。</p>

<p>现在的做法是反过来的（<code class="language-plaintext highlighter-rouge">WorktreeManager.removeWorktree</code>）：<strong>先查再删，只有 git 真的放手了才从表里移除</strong>。</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">WorktreeState</span> <span class="n">st</span> <span class="o">=</span> <span class="n">resolveForMerge</span><span class="o">(</span><span class="n">name</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">st</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
</code></pre></div></div>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="o">(</span><span class="n">gitRemoved</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">states</span><span class="o">.</span><span class="na">remove</span><span class="o">(</span><span class="n">name</span><span class="o">);</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">"R149: removed worktree {}"</span><span class="o">,</span> <span class="n">name</span><span class="o">);</span>
<span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">warn</span><span class="o">(</span><span class="s">"R388b: worktree {} still tracked by git — keeping it registered so it can be retried"</span><span class="o">,</span>
            <span class="n">name</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>删除命令本身也分两级，对应坑五：先 <code class="language-plaintext highlighter-rouge">git worktree remove --force</code>，失败再 <code class="language-plaintext highlighter-rouge">git worktree remove -f -f</code>。两次都失败才退化成直接删目录，而且<strong>这时不删表里的记录</strong>，只记一条警告：</p>

<blockquote>
  <p>a silent “removed” here is how a worktree becomes an orphan.</p>
</blockquote>

<p><strong>能从外部验证的是</strong>：改后 git 没放手时，登记留在表里，用户按名字重试删除能接着走——日志里会留下一条 <code class="language-plaintext highlighter-rouge">still tracked by git — keeping it registered so it can be retried</code> 的警告，而不是一条「已删除」。这条警告本身就是现成的运行时输出，不必另外造例子。</p>

<h3 id="合并要保守">合并要保守</h3>

<p>worktree 的生命周期如果只有「建」和「删」，那中间缺一环：分支推上去了，worktree 和分支却永远留着。所以要补一个「合回去」的动作。</p>

<p>这一步做得很克制（<code class="language-plaintext highlighter-rouge">WorktreeManager.mergeWorktree</code> 的注释原话）：</p>

<blockquote>
  <p>The operation is deliberately conservative: it does NOT push, does NOT delete the branch by default, and REFUSES a dirty worktree. A merge that silently discarded uncommitted work would be a data-loss bug in the name of convenience.</p>
</blockquote>

<p>具体到三条拒绝规则：</p>

<ul>
  <li><strong>worktree 里有未提交改动 → 整个操作拒绝</strong>，不只拒绝删除。理由写得很实在：合并本身是安全的（合的是 commit），但后面删 worktree 会把那些未提交的东西一起销毁。与其悄悄丢，不如整件事不做。</li>
  <li><strong>目标分支和源分支相同 → 拒绝</strong>。</li>
  <li><strong>合并冲突 → 拒绝，并回滚</strong>。冲突会让仓库停在 MERGING 状态，用户下一条命令会被 git 拒掉，所以代码在捕获冲突后显式调 <code class="language-plaintext highlighter-rouge">git merge --abort</code>。</li>
</ul>

<p><strong>能从外部验证的是</strong>：这三条规则的表现都是<strong>RPC 直接返回失败</strong>，不是静默合并——合并成功时留下的是一个 <code class="language-plaintext highlighter-rouge">--no-ff</code> 的合并提交，提交信息里带着被合分支的名字；拒绝时用户拿到的是失败，而不是一个「看起来成功」的结果。</p>

<p>合并的动作本身，正好落在坑六上——<strong>从源仓库发起，而不是从 worktree 里发起</strong>：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Merge from the SOURCE REPO, not from inside the</span>
<span class="c1">// worktree: git refuses to check out a branch that</span>
<span class="c1">// is already checked out in another worktree, so</span>
<span class="c1">// merging from inside the worktree into another</span>
<span class="c1">// branch is not possible. Merging from the repo</span>
<span class="c1">// whose HEAD is the target branch is.</span>
</code></pre></div></div>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">runGit</span><span class="o">(</span><span class="n">repo</span><span class="o">,</span> <span class="s">"merge"</span><span class="o">,</span> <span class="s">"--no-ff"</span><span class="o">,</span> <span class="n">source</span><span class="o">,</span> <span class="s">"-m"</span><span class="o">,</span>
        <span class="s">"merge worktree '"</span> <span class="o">+</span> <span class="n">name</span> <span class="o">+</span> <span class="s">"' ("</span> <span class="o">+</span> <span class="n">source</span> <span class="o">+</span> <span class="s">") into "</span> <span class="o">+</span> <span class="n">target</span><span class="o">);</span>
</code></pre></div></div>

<p><strong>能从外部验证的是</strong>：合并发起在哪个仓库，直接决定 git 允不允许——目标分支已经被检出在源仓库里，所以只能在源仓库合进它。同一个道理也体现在判断干不干净的那一步上（见下）。</p>

<p><code class="language-plaintext highlighter-rouge">--no-ff</code> 保留一个合并提交，于是「这个分支是从哪儿合过来的」在历史里看得见。</p>

<p>还有一个容易被忽略的细节：<strong>判断 worktree 干不干净，<code class="language-plaintext highlighter-rouge">git status</code> 必须在 worktree 自己的目录里跑</strong>，不能在源仓库里跑。源仓库的 <code class="language-plaintext highlighter-rouge">git status</code> 显示的是源仓库自己那份工作区的状态，跟这个分支所在的 worktree 没关系。代码里专门找到了那个分支对应的 worktree 路径再执行（<code class="language-plaintext highlighter-rouge">WorktreeManager.gitStatus</code>）：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Path</span> <span class="n">wtPath</span> <span class="o">=</span> <span class="n">findWorktreePath</span><span class="o">(</span><span class="n">repo</span><span class="o">,</span> <span class="n">branch</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(</span><span class="n">wtPath</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="k">return</span> <span class="s">""</span><span class="o">;</span>
<span class="k">return</span> <span class="nf">runGitForOutput</span><span class="o">(</span><span class="n">wtPath</span><span class="o">.</span><span class="na">toString</span><span class="o">(),</span> <span class="s">"status"</span><span class="o">,</span> <span class="s">"--porcelain"</span><span class="o">).</span><span class="na">trim</span><span class="o">();</span>
</code></pre></div></div>

<h3 id="列表与动作必须说同一件事">列表与动作必须说同一件事</h3>

<p>这是我们踩过最有代表性的一段。</p>

<p>worktree 列表的来源是<strong>两处的并集</strong>：daemon 自己创建的（内部登记表），加上 git 那边知道的（<code class="language-plaintext highlighter-rouge">git worktree list --porcelain</code>）。第二个来源是故意加的——用户自己用 <code class="language-plaintext highlighter-rouge">git worktree add</code> 建的 worktree，也应该能在面板里看到并挂上去。</p>

<p>并集就得去重，而这里去重的键不是名字而是<strong>路径</strong>（<code class="language-plaintext highlighter-rouge">AetherCodeMethods.listWorktrees</code>）：daemon 自己建的 worktree 同时出现在两张表里，不去重就会显示两遍。麻烦在于两边的路径<strong>不是字符串相等</strong>——git 报的是正斜杠（<code class="language-plaintext highlighter-rouge">D:/work/...</code>），JVM 手里是反斜杠（<code class="language-plaintext highlighter-rouge">D:\work\...</code>），而 <code class="language-plaintext highlighter-rouge">toAbsolutePath()</code> 并不统一分隔符。于是朴素比较会把同一个 worktree 当成两个。</p>

<p>解法是拿归一化后的路径当键：转绝对路径、反斜杠折成正斜杠、转小写（Windows 路径大小写不敏感）、去掉结尾斜杠。</p>

<p>顺带一提，两个前端对这份列表的呈现方式不一样：桌面端每行自带 <code class="language-plaintext highlighter-rouge">Merge</code> 和 <code class="language-plaintext highlighter-rouge">Remove</code> 按钮（降级的那行 <code class="language-plaintext highlighter-rouge">Merge</code> 是禁用的）；TUI 则没有行内按钮，动作走快捷键——<code class="language-plaintext highlighter-rouge">n</code> 新建、<code class="language-plaintext highlighter-rouge">m</code> 合并、<code class="language-plaintext highlighter-rouge">d</code> 删除选中、回车合并选中项，徽章是 <code class="language-plaintext highlighter-rouge">[git]</code> 和 <code class="language-plaintext highlighter-rouge">[plain dir]</code>。</p>

<p>但<strong>动作只查了第一处</strong>。于是列表里明明显示着，用户一点「合并」，daemon 回了这么一句：</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mergeWorktree   → "no such worktree: r388-e2e"
</code></pre></div></div>

<p><strong>daemon 刚把 worktree 展示给用户，转头就说不认识它。</strong></p>

<p>这个缺陷不是单元测试发现的——二十多个用例全都通过，因为它们<strong>每个都通过 manager 创建 worktree</strong>，所以 worktree 永远在登记表里。测不到的那一种，恰恰是「存在于 git、但不在登记表里」。最后是跑打包产物的端到端探针，用一个真的 git 仓库当源，才撞出来。</p>

<p><strong>这就是测试上的差异</strong>：缺陷存在的那段时间里，二十多个单元用例全绿——因为它们每个都从 manager 建 worktree，测不到「worktree 只存在于 git」这一种；把它撞出来的是跑打包产物的<strong>端到端探针</strong>（用一个真的 git 仓库当源）。换句话说，能抓住它的不是单元用例，而是端到端那条路径：要让用例覆盖住它，就必须从外部建一个 worktree 再走一遍面板。</p>

<p>修复方式很直接：动作也走同一个解析函数 <code class="language-plaintext highlighter-rouge">WorktreeManager.resolveForMerge</code>——先查登记表，查不到就去 git 的列表里找，找到就补上解析出来的源仓库：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">private</span> <span class="nc">WorktreeState</span> <span class="nf">resolveForMerge</span><span class="o">(</span><span class="nc">String</span> <span class="n">name</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">name</span> <span class="o">==</span> <span class="kc">null</span> <span class="o">||</span> <span class="n">name</span><span class="o">.</span><span class="na">isBlank</span><span class="o">())</span> <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
    <span class="nc">WorktreeState</span> <span class="n">st</span> <span class="o">=</span> <span class="n">states</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">name</span><span class="o">);</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">st</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="k">return</span> <span class="n">st</span><span class="o">;</span>

    <span class="nc">String</span> <span class="n">repo</span> <span class="o">=</span> <span class="n">resolvedSourceRepo</span><span class="o">();</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">repo</span> <span class="o">==</span> <span class="kc">null</span> <span class="o">||</span> <span class="n">repo</span><span class="o">.</span><span class="na">isBlank</span><span class="o">())</span> <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>

    <span class="nc">String</span> <span class="n">wanted</span> <span class="o">=</span> <span class="n">name</span><span class="o">.</span><span class="na">trim</span><span class="o">();</span>
    <span class="k">for</span> <span class="o">(</span><span class="nc">WorktreeState</span> <span class="n">git</span> <span class="o">:</span> <span class="n">listGitWorktrees</span><span class="o">())</span> <span class="o">{</span>
        <span class="kt">boolean</span> <span class="n">nameMatches</span> <span class="o">=</span> <span class="n">wanted</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">git</span><span class="o">.</span><span class="na">name</span><span class="o">());</span>
        <span class="kt">boolean</span> <span class="n">pathMatches</span> <span class="o">=</span> <span class="n">wanted</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">git</span><span class="o">.</span><span class="na">path</span><span class="o">().</span><span class="na">getFileName</span><span class="o">().</span><span class="na">toString</span><span class="o">());</span>
        <span class="k">if</span> <span class="o">(!</span><span class="n">nameMatches</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="n">pathMatches</span><span class="o">)</span> <span class="k">continue</span><span class="o">;</span>
        <span class="c1">// git's record has no sourceRepo; the worktree</span>
        <span class="c1">// belongs to the repo we just asked.</span>
        <span class="k">return</span> <span class="k">new</span> <span class="nf">WorktreeState</span><span class="o">(</span><span class="n">git</span><span class="o">.</span><span class="na">name</span><span class="o">(),</span> <span class="n">git</span><span class="o">.</span><span class="na">path</span><span class="o">(),</span> <span class="n">git</span><span class="o">.</span><span class="na">branch</span><span class="o">(),</span>
                <span class="n">repo</span><span class="o">,</span> <span class="n">git</span><span class="o">.</span><span class="na">isolated</span><span class="o">(),</span> <span class="n">git</span><span class="o">.</span><span class="na">reason</span><span class="o">());</span>
    <span class="o">}</span>
    <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<p>我们内部的一份设计文档把这类缺陷叫作「<strong>列表和动作对『什么存在』各说各话</strong>」（那份文档在 AetherCode 仓库里，文件名带内部编号）：</p>

<blockquote>
  <p>the <strong>list</strong> is a claim about what exists, sourced from two places; the <strong>action</strong> resolves from one of them; so the list can promise something the action will refuse. <strong>The user is the one who finds out</strong>, because the gap only opens on the worktrees the manager did not create.</p>
</blockquote>

<p>这条对任何「列表 + 动作」型界面都成立：<strong>列表是承诺，动作是兑付，两者必须读同一份数据</strong>。</p>

<p>上面那段运行时输出是最硬的证据——<code class="language-plaintext highlighter-rouge">mergeWorktree</code> 回的是 <code class="language-plaintext highlighter-rouge">no such worktree: r388-e2e</code>，而同一个 worktree 明明就在 <code class="language-plaintext highlighter-rouge">listWorktrees</code> 的结果里。修复之后的那条返回文案我没有留存，所以这里只保留能复现的这一条，不另编一个「修好之后应该长什么样」的输出。</p>

<h3 id="会话怎么绑到-worktree-上">会话怎么绑到 worktree 上</h3>

<p>先说契约。会话规格是 <code class="language-plaintext highlighter-rouge">aethercode-sdk</code> 里的 <code class="language-plaintext highlighter-rouge">SessionSpec</code> record，四个字段：<code class="language-plaintext highlighter-rouge">sessionId</code>、<code class="language-plaintext highlighter-rouge">cwd</code>、<code class="language-plaintext highlighter-rouge">worktree</code>、<code class="language-plaintext highlighter-rouge">model</code>。</p>

<p><code class="language-plaintext highlighter-rouge">cwd</code> 和 <code class="language-plaintext highlighter-rouge">worktree</code> <strong>互斥</strong>，而且互斥是在 <code class="language-plaintext highlighter-rouge">SessionSpec</code> 的构造器里强制的：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// cwd and worktree are mutually exclusive</span>
<span class="k">if</span> <span class="o">(</span><span class="n">cwd</span> <span class="o">!=</span> <span class="kc">null</span> <span class="o">&amp;&amp;</span> <span class="n">worktree</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">throw</span> <span class="k">new</span> <span class="nf">IllegalArgumentException</span><span class="o">(</span><span class="s">"cwd and worktree are mutually exclusive"</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>这个互斥是对的：worktree 本身就是「在哪个目录干活」的答案，再叠一个 <code class="language-plaintext highlighter-rouge">cwd</code> 就出现了两个互相矛盾的答案。放在构造器里而不是散在各个 RPC 里，意味着<strong>任何入口都绕不过去</strong>。</p>

<p>然后是绑定过程。<code class="language-plaintext highlighter-rouge">AetherCodeMethods.createSession</code> 收到 <code class="language-plaintext highlighter-rouge">worktree</code> 之后，按三级顺序解析出路径：先查 daemon 自己的登记表 → 再查 <code class="language-plaintext highlighter-rouge">git worktree list --porcelain</code> → 都没有就自动建一个。解析出来的路径成为会话的 <code class="language-plaintext highlighter-rouge">cwd</code>，再调 <code class="language-plaintext highlighter-rouge">engine.setCwd(...)</code> 让模型看到的是 worktree 里的文件。</p>

<p>这里的「切目录」不是 <code class="language-plaintext highlighter-rouge">chdir</code>，也不是给子进程传一个参数就完事。实际链路是三段：</p>

<ol>
  <li><code class="language-plaintext highlighter-rouge">engine.setCwd(path)</code> 把路径写进会话状态；</li>
  <li>工具层从这个状态里读出当前目录；</li>
  <li>shell 工具把它交给 <code class="language-plaintext highlighter-rouge">ProcessBuilder.directory(cwd)</code>。</li>
</ol>

<p>也就是说，<strong>「模型在哪个目录干活」是贯穿到每个工具里的一条路径，不是进程级的工作目录切换</strong>。这条设计让同一个 daemon 里的多个会话可以同时待在不同目录——而 daemon 本身的工作目录从头到尾没动过。</p>

<h3 id="一条路径还没接上">一条路径还没接上</h3>

<p>这里有个值得单独说的缺口，因为它正好是上面那条纪律的反面。</p>

<p><strong><code class="language-plaintext highlighter-rouge">createSession</code> 这条 RPC 解析 worktree，<code class="language-plaintext highlighter-rouge">createEngine</code> 这条不解析。</strong></p>

<p>桌面端走的是后者。用户在面板里选中一个 worktree，面板底部会显示（桌面端 <code class="language-plaintext highlighter-rouge">WorktreePanel</code> 组件）：</p>

<blockquote>
  <p>Next new session binds to &lt;name&gt;</p>
</blockquote>

<p>store 随后发起（桌面端 <code class="language-plaintext highlighter-rouge">store/index.ts</code> 的 <code class="language-plaintext highlighter-rouge">newSession</code>）：</p>

<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">selectedWorktree</span> <span class="o">=</span> <span class="kd">get</span><span class="p">().</span><span class="nx">selectedWorktree</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">r</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">rpc</span><span class="p">.</span><span class="nx">createEngine</span><span class="p">({</span>
  <span class="na">sessionId</span><span class="p">:</span> <span class="nx">newId</span><span class="p">,</span>
  <span class="na">cwd</span><span class="p">:</span> <span class="nx">selectedWorktree</span> <span class="p">?</span> <span class="kc">null</span> <span class="p">:</span> <span class="nx">cwd</span><span class="p">,</span>
  <span class="na">worktree</span><span class="p">:</span> <span class="nx">selectedWorktree</span><span class="p">,</span>
  <span class="na">model</span><span class="p">:</span> <span class="kc">null</span><span class="p">,</span>
<span class="p">});</span>
</code></pre></div></div>

<p>RPC 侧把 <code class="language-plaintext highlighter-rouge">worktree</code> 塞进 <code class="language-plaintext highlighter-rouge">SessionSpec</code>，交给 <code class="language-plaintext highlighter-rouge">SessionManager.create(spec)</code>，最终落到 daemon 的引擎工厂 <code class="language-plaintext highlighter-rouge">Main.buildEngineForSession(SessionSpec)</code>。而那个方法里，worktree 分支是<strong>一个空块</strong>：</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">java</span><span class="o">.</span><span class="na">nio</span><span class="o">.</span><span class="na">file</span><span class="o">.</span><span class="na">Path</span> <span class="n">sessionCwd</span> <span class="o">=</span> <span class="k">this</span><span class="o">.</span><span class="na">cwd</span><span class="o">;</span>
<span class="k">if</span> <span class="o">(</span><span class="n">spec</span><span class="o">.</span><span class="na">worktree</span><span class="o">()</span> <span class="o">!=</span> <span class="kc">null</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="n">spec</span><span class="o">.</span><span class="na">worktree</span><span class="o">().</span><span class="na">isBlank</span><span class="o">())</span> <span class="o">{</span>
    <span class="c1">// the worktree path is conventionally a</span>
    <span class="c1">// sub-directory of the daemon's worktree root.</span>
    <span class="c1">// sessionCwd stays as this.cwd for now; the</span>
    <span class="c1">// git-worktree integration is out of scope for now.</span>
<span class="o">}</span>
<span class="k">if</span> <span class="o">(</span><span class="n">spec</span><span class="o">.</span><span class="na">cwd</span><span class="o">()</span> <span class="o">!=</span> <span class="kc">null</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="n">spec</span><span class="o">.</span><span class="na">cwd</span><span class="o">().</span><span class="na">isBlank</span><span class="o">())</span> <span class="o">{</span>
    <span class="n">sessionCwd</span> <span class="o">=</span> <span class="n">java</span><span class="o">.</span><span class="na">nio</span><span class="o">.</span><span class="na">file</span><span class="o">.</span><span class="na">Paths</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">spec</span><span class="o">.</span><span class="na">cwd</span><span class="o">()).</span><span class="na">toAbsolutePath</span><span class="o">().</span><span class="na">normalize</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">sessionCwd</code> 停在 daemon 自己的目录上。上面那段注释自己承认了——「worktree 的接入留到以后」——但注释是注释，代码是代码：<strong>面板承诺「下一个会话绑到 xxx」，实际绑到的是 daemon 的启动目录</strong>。</p>

<p>而 <code class="language-plaintext highlighter-rouge">SessionSpec.effectiveCwd(defaultCwd)</code> 这个本该兜底的辅助方法，也只认 <code class="language-plaintext highlighter-rouge">cwd</code>，不看 <code class="language-plaintext highlighter-rouge">worktree</code>。</p>

<p>这类缺口之所以难发现，是因为<strong>每一环单独看都是对的</strong>：协议层收下了 <code class="language-plaintext highlighter-rouge">worktree</code> 参数，<code class="language-plaintext highlighter-rouge">SessionSpec</code> 好好地存着它，面板好好地显示了它，RPC 也好好地返回了 <code class="language-plaintext highlighter-rouge">ok</code>。只有把它们串起来走一遍，才会发现中间那一环是空的。</p>

<p><strong>这是目前已知、还没修的缺口。</strong> 它能潜伏这么久，是因为 worktree 的其它部分做到了「每一个状态都能自证」，让人很难怀疑这一环没接上。恰恰说明「每个组件都自洽」不等于「串起来是对的」：<strong>承诺和兑付要分开验。</strong></p>

<h3 id="除了给-agent-用我们还拿它当基准">除了给 agent 用，我们还拿它当基准</h3>

<p>worktree 在我们这儿还有第二种用法，跟 agent 无关：<strong>当测量基准</strong>。</p>

<p>想知道「这一轮改动到底引入了哪些新的失败」，光看当前工作树是不够的——当前工作树里已经攒着历史遗留的失败。正确做法是拿 HEAD 拉一份<strong>干净的检出</strong>，在<strong>同一台机器、同一份依赖</strong>下把同样的测试再跑一遍，然后比<strong>失败集合</strong>，而不是比失败总数。</p>

<p>后来有一轮专门做这件事（对应的设计文档在 AetherCode 仓库里，文件名带内部编号），做法就是上面这条：主工作树 1846 个测试、49 条失败；HEAD 基准树跑同样的 18 个文件，也是 49 条；两个失败集合逐条比对，<strong>新增 0 条、消失 0 条</strong>。</p>

<p>这组数字要一个一个对得上，口径也得说清楚：</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>主工作树</th>
      <th>HEAD 基准树</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>跑的测试数</td>
      <td>1846</td>
      <td>没记下来</td>
    </tr>
    <tr>
      <td>失败条数</td>
      <td>49</td>
      <td>49</td>
    </tr>
    <tr>
      <td>失败落在几个文件</td>
      <td>18</td>
      <td>同样的 18 个文件</td>
    </tr>
    <tr>
      <td>失败集合差异</td>
      <td>—</td>
      <td>新增 0 条、消失 0 条</td>
    </tr>
  </tbody>
</table>

<p><strong>基线侧一共跑了多少个测试，当时没有记下来</strong>——能对上的口径是「同样的 18 个文件」，也就是以失败集所在的那批文件为准，不是以全部 1846 个测试为准。这正是要把它记下来的理由：基线跑了什么、用了什么依赖，事后不写下来，下次就没人能复核。</p>

<p>结论不是「零失败」，而是「零<strong>新增</strong>失败」——后者才是能拿去汇报的东西。</p>

<p>更早一轮用的是同一招（那份运行控制文档同样在 AetherCode 仓库里，文件名带内部编号）：拉一份上一版的干净检出，在同一台机器、同一份 <code class="language-plaintext highlighter-rouge">node_modules</code> 下跑全量，把失败的<strong>名字</strong>抓下来逐条对账，而不是靠「我记得」来判断。</p>

<p>这里有个只有真跑过才会撞上的坑：<strong>干净检出里没有构建产物</strong>。那一轮的基线树上，<code class="language-plaintext highlighter-rouge">dist/ac-tui.js is fresh</code> 这类门禁是红的——因为 worktree 里没有 <code class="language-plaintext highlighter-rouge">dist/</code>，那是<strong>检出方式的产物</strong>，不是产品的毛病。</p>

<p><strong>依赖是怎么复现的，这一步必须写下来</strong>，否则上面那张表全是假数据：基线树和主工作树共用<strong>同一份 <code class="language-plaintext highlighter-rouge">node_modules</code></strong>，做法是把它接到基线树里，而不是每个基线各装一份。接法有几种（拷贝、软链、预置目录都行），Windows 上最省事的是做一个目录联接：</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">cmd</span><span class="w"> </span><span class="nx">/c</span><span class="w"> </span><span class="nx">mklink</span><span class="w"> </span><span class="nx">/J</span><span class="w"> </span><span class="err">&lt;</span><span class="nx">baseline</span><span class="err">&gt;</span><span class="nx">\node_modules</span><span class="w"> </span><span class="err">&lt;</span><span class="nx">main</span><span class="err">&gt;</span><span class="nx">\node_modules</span><span class="w">
</span></code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">dist/</code> 不一样——它是<strong>构建产物</strong>，干净检出里本来就没有，只能在基线树上重新构建一次；构建缓存同理。</p>

<p>⇒ <strong>用 worktree 当基准时，基线必须把构建环境一起复现，不能只有源码。</strong> 少复现一样东西，基线就假失败，然后你会去修一个根本没坏的缺陷。</p>

<p>⇒ <strong>可执行的检查项：基线跑之前，先确认 <code class="language-plaintext highlighter-rouge">dist/</code>、<code class="language-plaintext highlighter-rouge">node_modules</code>、构建缓存这三样在不在——缺一样，基线就假失败。</strong></p>

<h2 id="能直接抄的几条纪律">能直接抄的几条纪律</h2>

<p>把上面这些收一收。括号里标的是每条纪律的来源，可以反着查回对应的坑或缺陷：</p>

<ol>
  <li><strong>worktree 放在仓库外面</strong>，别放在仓库里的隐藏目录。放在仓库内会被 agent 的文件工具当成待改文件，也会让 <code class="language-plaintext highlighter-rouge">git status</code> 变脏。（←「AI Agent 为什么需要它」）</li>
  <li><strong>一个 agent 一个 worktree、一条分支</strong>。分支名加统一前缀（<code class="language-plaintext highlighter-rouge">aethercode/&lt;name&gt;</code>），这样清理时能一眼分辨出哪些分支是自己的。（←「AI Agent 为什么需要它」＋「命名与落位」）</li>
  <li><strong>创建要能重试</strong>。<code class="language-plaintext highlighter-rouge">-b</code> 撞上已存在的分支不是失败，是「去挂上去」；但要先分清「分支已存在」和「真的失败」。（← 坑二 ·「失败与重试的语义：创建」）</li>
  <li><strong>删除要分级</strong>：<code class="language-plaintext highlighter-rouge">remove --force</code> → <code class="language-plaintext highlighter-rouge">remove -f -f</code> → 直接删目录。最后一步是兜底，一旦走到这一步就<strong>不要忘记这个 worktree</strong>，让用户能重试。（← 坑五 ·「失败与重试的语义：删除」）</li>
  <li><strong>失败时不要清空状态</strong>。「git 还没放手」和「已经删掉了」是两件事，前者必须还能按名字重试。（←「失败与重试的语义：删除」）</li>
  <li><strong>合并要保守</strong>：脏 worktree 整个操作拒绝；冲突要 abort；合并从目标分支所在的仓库发起，而不是从 worktree 里发起。（←「合并要保守」＋ 坑六）</li>
  <li><strong>降级必须显式</strong>：能不能做真隔离由服务端给一个明确的布尔值加原因，客户端不许从「字段有没有值」去推断。空目录可以当兜底，但绝不能让它看起来像真隔离。（←「降级必须显式，不能「看起来像」」）</li>
  <li><strong>列表和动作读同一份数据</strong>。这条不限于 worktree——凡是「界面上列出来的」和「按钮能操作的」，都得走同一个解析路径。（←「列表与动作必须说同一件事」）</li>
  <li><strong>承诺和兑付要分开验</strong>。每个组件单独看都自洽（参数收下了、字段存着了、界面显示对了），不等于串起来是对的。<strong>把一条完整链路从用户点下去走到实际生效，中间每一跳都要走一遍。</strong>（←「一条路径还没接上」）</li>
  <li><strong>拿 worktree 当基准时，要连构建环境一起复现</strong>。干净检出里没有构建产物，依赖产物的门禁会假失败——你会去修一个根本没坏的缺陷。（←「除了给 agent 用，我们还拿它当基准」）</li>
  <li><strong>子进程的 stdin 一定要切断</strong>，输出一定要并发抽干。前者在 JSON-RPC / stdio 服务里会吃掉协议流，后者会撞上管道缓冲区死锁。（←「进程调 git 的两个坑」）</li>
</ol>

<h2 id="小结">小结</h2>

<ol>
  <li><strong><code class="language-plaintext highlighter-rouge">git worktree</code> 是共享，不是复制。</strong>同一个仓库多个工作目录，共用一份对象库；目录里的 <code class="language-plaintext highlighter-rouge">.git</code> 是一个指向 <code class="language-plaintext highlighter-rouge">.git/worktrees/&lt;名字&gt;</code> 的文件。建一个几乎不花钱，也不需要额外同步。</li>
  <li><strong>它的坑比它的功能多</strong>，而且都不是罕见路径：同分支不能双检出、<code class="language-plaintext highlighter-rouge">-b</code> 撞上已有分支会失败（这正是重试的样子）、脏目录不能删、手工删目录会留下 <code class="language-plaintext highlighter-rouge">prunable</code> 僵尸、locked 要两个 <code class="language-plaintext highlighter-rouge">-f</code>、合并不能在 worktree 里做，以及 worktree 装的是 commit 的内容、不是主工作区里未提交的改动。</li>
  <li><strong>AI Agent 需要的是三层隔离</strong>：文件、提交、对象库。worktree 一次给全，而且不用为每个 agent 复制一份仓库。<strong>但不是所有任务都值得付这份隔离成本</strong>——单 agent、依赖很重、或者要共享同一份未提交改动时，先想清楚。</li>
  <li><strong>AetherCode 的方案</strong>给出了一套生命周期：建（<code class="language-plaintext highlighter-rouge">addWorktree</code>）→ 用（会话绑定，<code class="language-plaintext highlighter-rouge">cwd</code> 与 worktree 互斥）→ 合（<code class="language-plaintext highlighter-rouge">mergeWorktree</code>，保守、拒绝脏 worktree）→ 删（<code class="language-plaintext highlighter-rouge">removeWorktree</code>，分级重试、失败不遗忘）。<strong>但这套生命周期在桌面端还没走通</strong>——<code class="language-plaintext highlighter-rouge">createEngine</code> 那条 RPC 不解析 worktree，面板说绑到 xxx、实际绑到 daemon 的启动目录（见「一条路径还没接上」）。</li>
  <li><strong>几处真实缺陷各自留下一条纪律</strong>：注释写了但代码没读 ⇒ 降级要显式且带原因；stdin 继承与管道死锁 ⇒ 子进程契约要从源码读；git 没放手就忘了登记 ⇒ 失败时不要清空状态；列表与动作各读一处 ⇒ 两者必须读同一份数据；参数一路传到底却没人解析 ⇒ 承诺和兑付要分开验。</li>
  <li><strong>worktree 还有第二种用法：当测量基准。</strong> 拿 HEAD 拉一份干净检出当基线，比的是失败<strong>集合</strong>而不是失败总数——结论应该是「零<strong>新增</strong>失败」，而不是「零失败」。基线要连构建环境一起复现，否则会拿到一堆假失败。</li>
</ol>

<blockquote>
  <p>这套实现里最值得记的，其实不是 worktree 的用法——那部分 git 手册上写着——而是<strong>每一个「看起来正常」的状态是怎么被证伪的</strong>。空目录冒充 worktree、僵尸登记冒充存在、列表冒充承诺、参数冒充生效，这四件事的共同点是：它们都长得像正常，直到有人认真去查。</p>
</blockquote>

<p><em>如果这篇文章对你有用，欢迎在 <a href="https://github.com/maijun-sec/maijun-sec.github.io">GitHub</a> 上提 issue 讨论。</em></p>]]></content><author><name>maijun</name></author><category term="AI Agent" /><category term="git worktree" /><category term="代码隔离" /><category term="智能体工程" /><summary type="html"><![CDATA[摘要：一个仓库、几个 AI 同时改代码，最先崩的往往不是模型，而是文件系统。git worktree 是 git 自带的答案：同一份对象库，多个独立工作目录，谁也不踩谁。但它的坑比它的功能多——本文先把机制和七个坑讲清楚（前面五个是本机跑出来的原始报错，第六条是硬规则的推论，第七条是检出语义），再说清 AI Agent 到底为什么需要它、什么时候不该用它，最后讲 AetherCode 自己怎么用：一套「建 → 用 → 合 → 删」的方案怎么落地，以及其中几处真实缺陷各自教会了什么。 先交代一件还没做完的事：AetherCode 的 worktree 生命周期里，桌面端那条路径目前还没接上——面板写着「下一个会话绑到 xxx」，实际绑到的是 daemon 的启动目录。这是已知且未修的缺口，本文单独讲一节。]]></summary></entry><entry><title type="html">git-ai 源码剖析：AI 代码归属的两层结构——证据、启发式，以及什么时候放弃</title><link href="https://maijun-sec.github.io/2026/11/30/git-ai-authorship/" rel="alternate" type="text/html" title="git-ai 源码剖析：AI 代码归属的两层结构——证据、启发式，以及什么时候放弃" /><published>2026-11-30T12:00:00+08:00</published><updated>2026-11-30T12:00:00+08:00</updated><id>https://maijun-sec.github.io/2026/11/30/git-ai-authorship</id><content type="html" xml:base="https://maijun-sec.github.io/2026/11/30/git-ai-authorship/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：开源项目 git-ai 能回答「这段代码是 AI 写的还是人写的」。但它的答案分两层，而且这两层和 README 讲的不太一样：<strong>证据层靠智能体主动上报，把改动整块归集到具体的归属键上；恢复层确实用了启发式，靠时间窗和提交元数据补洞</strong>。本文基于 v1.7.7 的源码逐层拆开——上报什么、证据不足时怎么猜、猜到什么程度为止、什么时候干脆放弃、归属数据以什么格式存进 Git Notes、历史被改写时它靠什么活下来。</p>
</blockquote>

<p>口径先交代一句，免得读错方向：证据层的「行级」指的是<strong>归属键精确到行号区间</strong>，不是逐行判定——整块 hunk 都会归给 AI，所以它给出的 AI 占比是<strong>偏高口径</strong>；恢复层的启发式同样只往上加。会把占比压低的是「未跟踪」——没装扩展、没配合上报的行压根不在分母里。文末附源码位置索引，正文里引用的源码位置都在里面，可以逐条回查。</p>

<!--more-->

<h2 id="先把结论说准">先把结论说准</h2>

<p>git-ai 的 README 里有一句话，位置在 <code class="language-plaintext highlighter-rouge">README.md</code> 的 FAQs 一节（”How does it work?” 那段）：</p>

<blockquote>
  <p><em>Git AI does not use AI or heuristics to “detect” AI code — the Agents report exactly which lines they wrote, providing the most accurate, explicit attribution possible.</em></p>
</blockquote>

<p>这句话<strong>对了一半</strong>。</p>

<p>对的那一半是主干：它确实<strong>没有</strong>任何按代码风格、注释密度、命名习惯去猜「像不像 AI 写的」的逻辑。这类启发式在别处很常见——但在这里不存在。</p>

<p>不对的那一半是「does not use heuristics」这个绝对说法。源码里有一整个模块专门在做启发式<strong>恢复</strong>（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code>，88KB）：当证据不足、某些行还没有归属时，它会用 bash 历史的时间窗、session 事件的时间窗、commit 的作者身份和 trailer 来补。另有几个兜底路径，会把整个 commit 判给某个 agent。</p>

<p>所以准确的说法是<strong>两层结构</strong>：</p>

<table>
  <thead>
    <tr>
      <th>层</th>
      <th>干什么</th>
      <th>依据</th>
      <th>精度</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>证据层</td>
      <td>主力</td>
      <td>智能体主动上报它写了哪些行</td>
      <td>行级</td>
    </tr>
    <tr>
      <td>恢复层</td>
      <td>补洞</td>
      <td>时间窗、提交元数据、身份</td>
      <td>行级到 commit 级</td>
    </tr>
  </tbody>
</table>

<p>而且这两层之间有明确的优先级和明确的<strong>放弃条件</strong>——这才是这个项目最值得学的地方。</p>

<p>整条链路大致是这样：</p>

<pre><code class="language-mermaid">graph LR;
    A["智能体改代码"] --&gt;|"hook 触发"| B["git-ai checkpoint"]
    B --&gt; C["适配器解析&lt;br/&gt;定 CheckpointKind"]
    C --&gt; D["工作区账本&lt;br/&gt;按基线 SHA 分目录"]
    D --&gt; E["daemon 发现提交&lt;br/&gt;trace2 事件 + reflog"]
    E --&gt; F["对齐上报与提交&lt;br/&gt;算 accepted"]
    F -.-&gt;|"证据不足的行"| R["恢复层&lt;br/&gt;时间窗 / commit 元数据"]
    R -.-&gt; F
    F --&gt; G["写 note&lt;br/&gt;refs/notes/ai"]
    G --&gt; H["push 到远端&lt;br/&gt;GitHub"]
</code></pre>

<h2 id="边界与坑">边界与坑</h2>

<p>用之前该知道的限制，先列在这里，后面再逐条展开。</p>

<ol>
  <li><strong>归属依赖智能体配合。</strong> 智能体不调 <code class="language-plaintext highlighter-rouge">checkpoint</code>，就没有数据。这是设计取舍，不是 bug，但意味着<strong>归属的覆盖率等于智能体的覆盖率</strong>。</li>
  <li><strong>「未跟踪」不是「人写的」。</strong> 统计时务必把分母限定在有归属的行上。</li>
  <li><strong>已知人类需要 IDE 扩展。</strong> 没有扩展，人手动改过的行只会体现为「AI 写的那行被人改过」，而不是一条独立的 <code class="language-plaintext highlighter-rouge">h_</code> 记录。</li>
  <li><strong>note 内容对有仓库权限的人可见。</strong> 包括模型名、agent 名、以及背后那个人的姓名和邮箱。<strong>完整的 prompt 不进仓库</strong>，留在本地——但如果你打算把归属数据推到公开仓库，那等于公开了「这个仓库的代码主要由哪些模型生成、用什么邮箱提交」这类信息。</li>
  <li><strong>AI 占比是偏高口径。</strong> AI 的改动整块归 AI，连纯空白也算；恢复层的启发式也只往上加。只有「未跟踪」那一侧会把占比压低——统计时先看未跟踪占比，再谈 AI 占比。</li>
  <li><strong>兜底路径会整块 commit 地误判。</strong> 靠环境变量探测后台 agent 的那条路径，判据是环境不是内容：带着 <code class="language-plaintext highlighter-rouge">CLAUDE_CODE_REMOTE=true</code>、<code class="language-plaintext highlighter-rouge">HOSTNAME=cursor</code> 这类变量手工提交代码，那些没有归属的行会被记成 agent 写的，模型名还标成 <code class="language-plaintext highlighter-rouge">unknown</code>。用它产出的归属前，先确认这个 commit 确实由那个后台 agent 产生。</li>
  <li><strong>历史大规模重写不支持</strong>：<code class="language-plaintext highlighter-rouge">git mv</code>、<code class="language-plaintext highlighter-rouge">filter-branch</code>、<code class="language-plaintext highlighter-rouge">filter-repo</code>、<code class="language-plaintext highlighter-rouge">git replace</code>。</li>
  <li><strong>多仓库根目录下，Bash 归属可能失效</strong>：智能体如果一次操作跨多个仓库，而命令的工作目录不在对应仓库里，基于 stat-diff 的那部分就推不出来（README 能力表里标注为 ⚠️）。</li>
  <li><strong>旧格式的 <code class="language-plaintext highlighter-rouge">overriden_lines</code> 字段在实现里恒为 0。</strong> 规范说这个计数器应该在「人改了 AI 的行」时递增（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 的 “Prompt Record Object (Legacy)” 一节里 <code class="language-plaintext highlighter-rouge">overriden_lines</code> 那行），但源码里四个构造点全都写死成 <code class="language-plaintext highlighter-rouge">0</code>（<code class="language-plaintext highlighter-rouge">src/authorship/authorship_log_serialization.rs</code> 里四处构造 <code class="language-plaintext highlighter-rouge">PromptRecord</code> 的地方）。底层有 <code class="language-plaintext highlighter-rouge">LineAttribution.overrode</code> 字段记录「这行被人覆盖过」（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 的 <code class="language-plaintext highlighter-rouge">find_dominant_author_for_line_candidates</code> 里算 <code class="language-plaintext highlighter-rouge">overrode</code> 那段），只是<strong>没有写进 note 格式</strong>。所以别指望从 note 里读到这个数。</li>
</ol>

<h2 id="证据层让智能体自己说">证据层：让智能体自己说</h2>

<h3 id="上报的入口">上报的入口</h3>

<p>智能体每写一次代码，就调用一次 <code class="language-plaintext highlighter-rouge">git ai checkpoint</code>，把这次编辑的信息报上来。麻烦在于各家智能体 hook 传上来的数据格式并不统一——Claude Code、Codex、Cursor、Copilot 各有各的字段名和结构。git-ai 的做法是给每一种智能体各写一套<strong>适配器</strong>，专门负责把该智能体的数据解析成统一的内部事件（源码目录 <code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/presets/</code>，trait 名 <code class="language-plaintext highlighter-rouge">AgentPreset</code>；上游源码里这套东西叫 <code class="language-plaintext highlighter-rouge">preset</code>，本文一律叫「适配器」），覆盖 Claude Code、Codex、Cursor、Copilot、OpenCode、Windsurf、Gemini、Droid、Amp、Continue 等十几种。</p>

<p>以 Claude Code 的适配器为例（<code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/presets/claude.rs</code> 里 <code class="language-plaintext highlighter-rouge">ClaudePreset::parse</code>），它从 hook 的 JSON 数据里取这样几个字段：</p>

<table>
  <thead>
    <tr>
      <th>字段</th>
      <th>用途</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">cwd</code></td>
      <td>本次编辑发生在哪个目录下</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transcript_path</code></td>
      <td>本次会话的对话记录文件路径</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">session_id</code></td>
      <td>智能体侧的会话标识</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">tool_name</code></td>
      <td>用了哪个工具（Write / Edit / Bash …）</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">tool_use_id</code></td>
      <td>单次工具调用的标识</td>
    </tr>
  </tbody>
</table>

<p>其中 <code class="language-plaintext highlighter-rouge">transcript_path</code> 还被用来提取模型名——<code class="language-plaintext highlighter-rouge">crate::streams::model_extraction::extract_model</code> 直接去读对话记录文件，把当前用的模型抽出来。这解释了为什么归属数据能精确到某个具体模型：<strong>不是猜的，是从智能体的会话文件里读出来的。</strong></p>

<h3 id="关键在于调用的是哪个适配器">关键在于「调用的是哪个适配器」</h3>

<p>这是整个证据层最核心的一行逻辑。<strong>一次 checkpoint 是 AI 还是人，不看内容，只看调用它的是哪个适配器</strong>——适配器名记在 <code class="language-plaintext highlighter-rouge">preset_name</code> 变量里，分支只有两条（<code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/orchestrator.rs</code> 里 <code class="language-plaintext highlighter-rouge">execute_post_file_edit</code>）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">checkpoint_kind</span> <span class="o">=</span> <span class="k">match</span> <span class="n">preset_name</span> <span class="p">{</span>
    <span class="s">"ai_tab"</span> <span class="k">=&gt;</span> <span class="nn">CheckpointKind</span><span class="p">::</span><span class="n">AiTab</span><span class="p">,</span>
    <span class="n">_</span> <span class="k">=&gt;</span> <span class="nn">CheckpointKind</span><span class="p">::</span><span class="n">AiAgent</span><span class="p">,</span>
<span class="p">};</span>
</code></pre></div></div>

<p>适配器解析完，最终落成四种 <code class="language-plaintext highlighter-rouge">CheckpointKind</code>（<code class="language-plaintext highlighter-rouge">src/authorship/working_log.rs</code> 的 <code class="language-plaintext highlighter-rouge">CheckpointKind</code> 枚举）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">pub</span> <span class="k">enum</span> <span class="n">CheckpointKind</span> <span class="p">{</span>
    <span class="n">Human</span><span class="p">,</span>
    <span class="n">AiAgent</span><span class="p">,</span>
    <span class="n">AiTab</span><span class="p">,</span>
    <span class="n">KnownHuman</span><span class="p">,</span>
<span class="p">}</span>
</code></pre></div></div>

<p>四个取值分别对应：未跟踪（<code class="language-plaintext highlighter-rouge">Human</code>，是个哨兵值，后面会看到它写 note 时会被剔除）、编码智能体（<code class="language-plaintext highlighter-rouge">AiAgent</code>）、IDE 内联补全（<code class="language-plaintext highlighter-rouge">AiTab</code>）、已知人类（<code class="language-plaintext highlighter-rouge">KnownHuman</code>）。</p>

<p>判定是不是 AI，只有一个布尔函数（<code class="language-plaintext highlighter-rouge">src/authorship/working_log.rs</code> 里 <code class="language-plaintext highlighter-rouge">CheckpointKind::is_ai</code>）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">pub</span> <span class="k">fn</span> <span class="nf">is_ai</span><span class="p">(</span><span class="k">self</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">bool</span> <span class="p">{</span>
    <span class="nd">matches!</span><span class="p">(</span><span class="k">self</span><span class="p">,</span> <span class="nn">CheckpointKind</span><span class="p">::</span><span class="n">AiAgent</span> <span class="p">|</span> <span class="nn">CheckpointKind</span><span class="p">::</span><span class="n">AiTab</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p><strong>没有分数，没有概率，没有权重。</strong>这就是个二值判断。</p>

<h3 id="工具要先分类">工具要先分类</h3>

<p>并不是每次工具调用都值得记账。<code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/bash_tool.rs</code> 的 <code class="language-plaintext highlighter-rouge">ToolClass</code> 定义了三分类：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">pub</span> <span class="k">enum</span> <span class="n">ToolClass</span> <span class="p">{</span>
    <span class="cd">/// A known file-edit tool (Write, Edit, etc.) — handled by existing preset logic.</span>
    <span class="n">FileEdit</span><span class="p">,</span>
    <span class="cd">/// A bash/shell tool — handled by the stat-diff system.</span>
    <span class="n">Bash</span><span class="p">,</span>
    <span class="cd">/// Unrecognized tool — skip checkpoint.</span>
    <span class="n">Skip</span><span class="p">,</span>
<span class="p">}</span>
</code></pre></div></div>

<ul>
  <li><strong>FileEdit</strong>（Write、Edit 等）：智能体明确说「我改了这个文件的这些行」，按工具语义取增量；</li>
  <li><strong>Bash</strong>：智能体跑了句 <code class="language-plaintext highlighter-rouge">cat &gt; foo.py &lt;&lt;EOF</code>，从命令本身看不出改了哪些行，只能靠<strong>文件系统状态比对</strong>反推；</li>
  <li><strong>Skip</strong>：认不出来的工具直接跳过，不硬猜。</li>
</ul>

<h3 id="ai-的归属比人更粗">AI 的归属比人更「粗」</h3>

<p>有个反直觉但很重要的细节：<strong>AI checkpoint 会把整块 hunk 都算成 AI 的</strong>，哪怕里面有些 token 根本没变。源码注释写得很清楚（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 里 <code class="language-plaintext highlighter-rouge">process_changed_hunk</code> 的 <code class="language-plaintext highlighter-rouge">force_split</code> 那段注释）：</p>

<blockquote>
  <p>所有新字节归 AI，包括恰好与旧内容相同的 token（如 <code class="language-plaintext highlighter-rouge">)</code> 或重名的变量）</p>
</blockquote>

<p>为什么要这样？因为如果沿用「相同内容继承旧归属」的规则，AI 改写过的代码会继承它原来主人的归属——那显然不对。所以 AI 的改动走 <code class="language-plaintext highlighter-rouge">force_split</code>，整块重新归给 AI。</p>

<p>配套的还有两条：</p>

<ul>
  <li><strong>AI checkpoint 关闭代码移动检测</strong>（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 里 <code class="language-plaintext highlighter-rouge">update_attributions_for_checkpoint</code> 的 Phase 3）。注释：AI 的格式化 / 重构 checkpoint 应当把重写区域归给 AI，而不是保留原来的主人。</li>
  <li><strong>AI 的纯空白改动也算 AI 的</strong>（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 里 <code class="language-plaintext highlighter-rouge">transform_attributions</code> 处理 AI 删除与 AI 插入的两处分支）。而已知人类则不适用这条规则（同文件 <code class="language-plaintext highlighter-rouge">find_dominant_author_for_line_candidates</code> 里 <code class="language-plaintext highlighter-rouge">include_ai_whitespace</code> 的判断）——人敲的格式化操作不会因此被算成 AI 的，但 AI 敲的会。</li>
</ul>

<p>同一行被多个作者碰过时，<strong>时间戳最新的胜出</strong>（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 里 <code class="language-plaintext highlighter-rouge">find_dominant_author_for_line_candidates</code> 选最新时间戳那段）。</p>

<p>这组规则的统计含义要说清楚：<strong>AI 行数是上界，不是逐行事实。</strong> 一块 hunk 里只要有一行是 AI 动的，整块就都算 AI 的；AI 做的纯空白改动同样算。所以「AI 写了多少行」这个数字天然偏大——它回答的是「哪些行被 AI 碰过」，而不是「哪些行是 AI 敲出来的」。反过来，人敲的行只要落进 AI 改过的那块 hunk，也会被一并记到 AI 那一侧。</p>

<h3 id="落在哪">落在哪</h3>

<p>上报的数据不会直接进 git 对象，而是先落到工作区的一份账本里（<code class="language-plaintext highlighter-rouge">src/git/repo_storage.rs</code> 里 <code class="language-plaintext highlighter-rouge">RepoStorage::for_repo_path</code> 与 <code class="language-plaintext highlighter-rouge">RepoStorage::ensure_config_directory</code> 定下的目录结构）：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;git_dir&gt;/ai/
├── working_logs/
│   └── &lt;base_commit_sha&gt;/
│       ├── INITIAL              # 未提交改动的初始归属
│       ├── checkpoints.jsonl    # 每次 checkpoint 的流水
│       └── blobs/&lt;sha256&gt;       # 文件内容快照，文件名即内容哈希
└── logs/
</code></pre></div></div>

<p>用 SHA 做目录名是有讲究的：账本是<strong>相对于某个基线</strong>成立的，一旦提交完成，基线就变了，账本也要跟着搬家。源码里 <code class="language-plaintext highlighter-rouge">rename_working_log</code>（<code class="language-plaintext highlighter-rouge">src/git/repo_storage.rs</code> 的 <code class="language-plaintext highlighter-rouge">RepoStorage::rename_working_log</code>）专门干这件事。</p>

<h2 id="恢复层证据不足时怎么补">恢复层：证据不足时怎么补</h2>

<p>前面那条证据层链路是主干。但现实里总有漏掉的情况：智能体没装扩展、装的是系统不认识的 agent、agent 崩了没上报……这些行就变成「无归属」。</p>

<p>git-ai 对这些行不是简单地扔掉，也不是简单地算成人写的，而是走一层<strong>有序的恢复流程</strong>（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">recover_attribution</code>）：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1. recover_bash_mtime            # ① bash 历史时间窗
2. recover_adjacent_edges        # ② 相邻行外推
3. recover_session_event_mtime   # ③ session 事件时间窗
4. recover_commit_metadata       # ④ commit 元数据匹配
5. recover_remaining_as_known_human  # ⑤ 兜底归给人
</code></pre></div></div>

<p><strong>顺序是有意义的</strong>：越靠前证据越强。① 靠的是 bash 历史里命令执行的时间，③ 靠的是 session 事件的时间，④ 靠的是 commit 里留下的文字痕迹。</p>

<h3 id="时间窗3-秒">时间窗：3 秒</h3>

<p>两条时间窗路径用的都是 <strong>±3 秒</strong>（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 里 <code class="language-plaintext highlighter-rouge">BASH_RECOVERY_WINDOW_NS</code> 与 <code class="language-plaintext highlighter-rouge">SESSION_EVENT_RECOVERY_WINDOW_NS</code> 两个常量）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">const</span> <span class="n">BASH_RECOVERY_WINDOW_NS</span><span class="p">:</span> <span class="nb">u128</span> <span class="o">=</span> <span class="mi">3_000_000_000</span><span class="p">;</span>
<span class="k">const</span> <span class="n">BASH_RECOVERY_COARSE_TIMESTAMP_NS</span><span class="p">:</span> <span class="nb">u128</span> <span class="o">=</span> <span class="mi">1_000_000_000</span><span class="p">;</span>
<span class="k">pub</span><span class="p">(</span><span class="k">crate</span><span class="p">)</span> <span class="k">const</span> <span class="n">SESSION_EVENT_RECOVERY_WINDOW_NS</span><span class="p">:</span> <span class="nb">u128</span> <span class="o">=</span> <span class="mi">3_000_000_000</span><span class="p">;</span>
</code></pre></div></div>

<p>（中间那个 <code class="language-plaintext highlighter-rouge">BASH_RECOVERY_COARSE_TIMESTAMP_NS</code> 是 1 秒的粗粒度时间戳，跟这条 ±3 秒的窗口不是一回事，列出来是为了让这段引用保持源码原样。）</p>

<p>含义是：如果某个 bash 命令的执行时间和某次文件修改的时间差在 3 秒内，就认为这次修改可能是那条命令造成的。</p>

<p>但时间窗是弱证据，所以候选还要<strong>分级</strong>（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">BashCandidateTier</code> 枚举）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">#[derive(Clone,</span> <span class="nd">Copy,</span> <span class="nd">Debug,</span> <span class="nd">PartialEq,</span> <span class="nd">Eq)]</span>
<span class="k">enum</span> <span class="n">BashCandidateTier</span> <span class="p">{</span>
    <span class="n">ExistingCommitSession</span><span class="p">,</span>
    <span class="n">WorkdirAncestor</span><span class="p">,</span>
    <span class="n">CwdAncestor</span><span class="p">,</span>
    <span class="n">TimeOnly</span><span class="p">,</span>
<span class="p">}</span>
</code></pre></div></div>

<p>分级由同文件的 <code class="language-plaintext highlighter-rouge">BashCandidateTier::score</code> 给出：<code class="language-plaintext highlighter-rouge">ExistingCommitSession</code> 0、<code class="language-plaintext highlighter-rouge">WorkdirAncestor</code> 1、<code class="language-plaintext highlighter-rouge">CwdAncestor</code> 2、<code class="language-plaintext highlighter-rouge">TimeOnly</code> 3。分数越小越靠前，只有时间对得上、别的都对不上的候选，排在最后一级。</p>

<p>session 事件那条路径更严格：<strong>只有仓库地址完全相等这一级被接受</strong>。设计文档 <code class="language-plaintext highlighter-rouge">docs/session-event-attribution-recovery-plan.md</code> 的「Solver: Session Event Mtime Recovery」一节写明了理由：</p>

<blockquote>
  <p>Time-only evidence is not strong enough because unrelated active agent sessions can have nearby event timestamps.</p>
</blockquote>

<p>也就是说，光靠「时间差不多」不能作为归属依据，还得确认是同一个仓库。</p>

<h3 id="commit-元数据文字里的痕迹">commit 元数据：文字里的痕迹</h3>

<p>还有一路是靠 commit 自己的信息（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">detect_commit_metadata_agents</code>）：</p>

<ul>
  <li><strong>trailer 探测</strong>（同文件 <code class="language-plaintext highlighter-rouge">detect_commit_metadata_agents</code> 里那几段）：找 <code class="language-plaintext highlighter-rouge">claude-session:</code>、<code class="language-plaintext highlighter-rouge">codex-session:</code>、<code class="language-plaintext highlighter-rouge">cursor-session:</code> 这类 trailer，以及 <code class="language-plaintext highlighter-rouge">Co-authored-by:</code>；</li>
  <li><strong>身份标记匹配</strong>（同文件 <code class="language-plaintext highlighter-rouge">detect_agent_from_identity</code> 与 <code class="language-plaintext highlighter-rouge">contains_identity_marker</code>）：commit 的 author 身份串里是否含有某个工具的标记词。匹配要求标记词前后是非字母数字边界，避免误命中。</li>
</ul>

<p>匹配上之后，这个 commit 里<strong>所有还没归属的行</strong>都归给检测出的 agent，metadata 里记 <code class="language-plaintext highlighter-rouge">"solver": "commit_metadata"</code>。</p>

<h3 id="兜底无-hook-的后台-agent">兜底：无 hook 的后台 agent</h3>

<p>还有一条更激进的路径（<code class="language-plaintext highlighter-rouge">src/authorship/background_agent.rs</code>）。它靠<strong>环境变量和文件系统特征</strong>判断当前跑在什么 agent 里（同文件的 <code class="language-plaintext highlighter-rouge">detect</code> 函数）：</p>

<table>
  <thead>
    <tr>
      <th>特征</th>
      <th>判定</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CLAUDE_CODE_REMOTE=true</code></td>
      <td><code class="language-plaintext highlighter-rouge">claude-web</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">HOSTNAME=cursor</code> 且 <code class="language-plaintext highlighter-rouge">CURSOR_AGENT=1</code></td>
      <td><code class="language-plaintext highlighter-rouge">cursor-agent</code></td>
    </tr>
    <tr>
      <td>任意 <code class="language-plaintext highlighter-rouge">CLOUD_AGENT_*</code> 前缀</td>
      <td><code class="language-plaintext highlighter-rouge">cloud-agent</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CODEX_INTERNAL_ORIGINATOR_OVERRIDE=codex_web_agent</code></td>
      <td><code class="language-plaintext highlighter-rouge">codex-cloud</code>（会话 id 取自 <code class="language-plaintext highlighter-rouge">CODEX_THREAD_ID</code>）</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">GIT_AI_CLOUD_AGENT=1</code></td>
      <td><code class="language-plaintext highlighter-rouge">git-ai-cloud-agent</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/opt/.devin/devin_id</code> 存在</td>
      <td><code class="language-plaintext highlighter-rouge">devin</code></td>
    </tr>
  </tbody>
</table>

<p>如果判定出的是源码里的 <code class="language-plaintext highlighter-rouge">NoHooks</code> 分支（<code class="language-plaintext highlighter-rouge">claude-web</code> 和 <code class="language-plaintext highlighter-rouge">cursor-agent</code> 走的是 <code class="language-plaintext highlighter-rouge">WithHooks</code> 分支，不触发这一步），<code class="language-plaintext highlighter-rouge">fill_unattributed_lines</code>（<code class="language-plaintext highlighter-rouge">src/authorship/background_agent.rs</code> 的同名函数）会把该 commit 里<strong>所有无归属的行</strong>全部归给它，模型名标成 <code class="language-plaintext highlighter-rouge">unknown</code>。</p>

<p>这条路径的判据是<strong>环境</strong>，不是代码内容。代价是它<strong>整块 commit 地误判</strong>：只要你带着这些环境变量手工提交过代码，那些没有归属的行就会被记成「agent 写的」，模型名还标成 <code class="language-plaintext highlighter-rouge">unknown</code>。换个说法——它的适用条件是「这个 commit 确实由那个后台 agent 产生」；这个条件一旦不成立，它给的就不是「依据比较弱的证据」，而是<strong>方向相反的强证据</strong>。</p>

<h3 id="什么时候放弃">什么时候放弃</h3>

<p>恢复层最重要的一条纪律是<strong>什么时候不猜</strong>。源码里有一处注释写得极好（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">recover_attribution</code> 里讲 fail-closed 那段）：</p>

<blockquote>
  <p>宁可把它们留成未归属；<strong>丢失归属是可以接受的，编造归属不行</strong>。</p>
</blockquote>

<p>数据库打不开、查询出错的时候，正确的输出是「留空」，不是「归给人」。</p>

<p>兜底归给人也有门槛（<code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">should_recover_remaining_as_known_human</code>）：只有<strong>在这个 commit 里完全没有已落地的 AI 归属</strong>时，才把剩下的行归给人。理由很实在——如果这个 commit 明明有 AI 参与过，剩下的行大概率也是 AI 的，只是没抓到证据。</p>

<p>还有一处防误判的规则值得单独提（<code class="language-plaintext highlighter-rouge">src/daemon/checkpoint.rs</code> 的 <code class="language-plaintext highlighter-rouge">KNOWN_HUMAN_MIN_SECS_AFTER_AI</code> 常量，以及 <code class="language-plaintext highlighter-rouge">execute_resolved_checkpoint</code> 里那段拒绝逻辑）：<strong>AI checkpoint 之后 1 秒内到达的「已知人类」编辑，直接丢弃</strong>。</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">const</span> <span class="n">KNOWN_HUMAN_MIN_SECS_AFTER_AI</span><span class="p">:</span> <span class="nb">u64</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
</code></pre></div></div>

<p>注释解释得很清楚：这些多半是 IDE 在 AI 写完文件后自动触发的保存事件，不是人的真实敲击。这条规则防的是「AI 写完 → IDE 保存 → 扩展报了个 known human → 归属被抢走」这个很常见的误判链条。</p>

<h2 id="ai-还是人其实是三态">「AI 还是人」其实是三态</h2>

<p>这是全文最想强调的一点，也是最容易读错的地方。</p>

<p><code class="language-plaintext highlighter-rouge">CheckpointKind</code> 四个取值里，<code class="language-plaintext highlighter-rouge">Human</code> 这个哨兵值在写 note 的时候会被<strong>直接剔除</strong>（<code class="language-plaintext highlighter-rouge">src/authorship/virtual_attribution.rs</code> 的 <code class="language-plaintext highlighter-rouge">build_attestations_from_attributions</code> 里跳过 <code class="language-plaintext highlighter-rouge">Human</code> 那几行）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="n">line_attr</span><span class="py">.author_id</span> <span class="o">==</span> <span class="nn">CheckpointKind</span><span class="p">::</span><span class="n">Human</span><span class="nf">.to_str</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">continue</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>所以最终落到 note 里的，只有三类东西：</p>

<table>
  <thead>
    <tr>
      <th>状态</th>
      <th>归属键前缀</th>
      <th>含义</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>AI 生成</td>
      <td><code class="language-plaintext highlighter-rouge">s_</code>（新）或裸 hex（旧）</td>
      <td>智能体上报过，且对齐后确认进了提交</td>
    </tr>
    <tr>
      <td>已知人类</td>
      <td><code class="language-plaintext highlighter-rouge">h_</code></td>
      <td>IDE 扩展<strong>观测到人手动编辑</strong>过的行</td>
    </tr>
    <tr>
      <td>未跟踪</td>
      <td>无</td>
      <td>没有任何归属记录，<strong>来源未知</strong></td>
    </tr>
  </tbody>
</table>

<p>第三种状态最容易被误读：</p>

<blockquote>
  <p><strong>「未跟踪」不等于「人写的」。</strong></p>
</blockquote>

<p>一份仓库如果压根没装智能体扩展、或者代码是在装之前写的，那所有行都处于「未跟踪」状态。它既不是 AI，也不是已知的人类——它只是<strong>没有证据</strong>。</p>

<p>这个区分在统计上直接落地了。<code class="language-plaintext highlighter-rouge">src/authorship/stats.rs</code> 的 <code class="language-plaintext highlighter-rouge">CommitStats</code> 结构体里，human / unknown / AI 三个归属计数并列，其中 <code class="language-plaintext highlighter-rouge">unknown_additions</code> 的算法是（同文件的 <code class="language-plaintext highlighter-rouge">stats_from_authorship_log</code> 收尾处）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Unknown additions: lines with no attestation at all (not AI-accepted, not KnownHuman)</span>
<span class="n">commit_stats</span><span class="py">.unknown_additions</span> <span class="o">=</span> <span class="n">git_diff_added_lines</span>
    <span class="nf">.saturating_sub</span><span class="p">(</span><span class="n">commit_stats</span><span class="py">.ai_accepted</span><span class="p">)</span>
    <span class="nf">.saturating_sub</span><span class="p">(</span><span class="n">known_human_accepted</span><span class="p">);</span>
</code></pre></div></div>

<p>终端进度条也分三段显示（<code class="language-plaintext highlighter-rouge">src/authorship/stats.rs</code> 的 <code class="language-plaintext highlighter-rouge">write_stats_to_terminal</code> 里画 bar 那几行）：<code class="language-plaintext highlighter-rouge">█</code> 是已知人类、<code class="language-plaintext highlighter-rouge">░</code> 是 AI、<code class="language-plaintext highlighter-rouge">·</code> 是未跟踪，而且未跟踪占比不到 1% 时那一段根本不显示。</p>

<p>把「没证据」默认当成「人写的」，在统计上会<strong>低估</strong> AI 占比；而证据层整块归集、恢复层又只往上加的机制，会<strong>抬高</strong> AI 占比。两个方向的偏差同时存在，所以拿到一个仓库的「AI 占比」要先问两件事：未跟踪那一段占多少，以及 AI 那一段是在「整块归集」的口径下统计的还是在逐行记录的口径下统计的。在合规上，把「无法追溯」默认当成「已确认合规」，是把风险洗白——这两种误判都不是显示问题，是结论问题。</p>

<h3 id="已知人类的证据来自-ide-扩展">「已知人类」的证据来自 IDE 扩展</h3>

<p><code class="language-plaintext highlighter-rouge">h_</code> 前缀的记录不是从 git 历史里猜的。<code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/presets/known_human.rs</code>（也就是上面说的「已知人类」适配器）解析的是 IDE 扩展上报的数据：<code class="language-plaintext highlighter-rouge">editor</code> / <code class="language-plaintext highlighter-rouge">editor_version</code> / <code class="language-plaintext highlighter-rouge">extension_version</code>、<code class="language-plaintext highlighter-rouge">cwd</code>、<code class="language-plaintext highlighter-rouge">edited_filepaths</code>、<code class="language-plaintext highlighter-rouge">dirty_files</code>。</p>

<p>也就是说，<strong>「这行是人敲的」是需要装扩展、并且扩展确实观测到编辑才能拿到的强证据</strong>，不是默认假设。规范里对应的一句话是（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 的 1.2.4 Metadata Section 一节里「Human Record Object」那段）：known human attribution represents lines that were explicitly observed being typed by a human in an IDE with the git-ai extension installed。</p>

<h3 id="三个哈希">三个哈希</h3>

<p>归属键的设计很克制——定长十六进制前缀加哈希，<strong>键本身不带明文</strong>（元数据段另有一份人类身份记录，见后文）：</p>

<p>| 键 | 构造方式 | 稳定性 |
| — | — | — |
| 会话 ID <code class="language-plaintext highlighter-rouge">s_&lt;14 hex&gt;</code> | <code class="language-plaintext highlighter-rouge">"s_" + SHA256("&lt;tool&gt;:&lt;conversation_id&gt;")[0..14]</code> | 同一会话的所有 checkpoint 相同 |
| 追踪 ID <code class="language-plaintext highlighter-rouge">t_&lt;14 hex&gt;</code> | <code class="language-plaintext highlighter-rouge">"t_" + 14 位随机十六进制 | 每次 checkpoint 调用都不同 |
| 人类哈希 </code>h_&lt;14 hex&gt;<code class="language-plaintext highlighter-rouge"> | </code>“h_” + SHA256(“<author_identity>")[0..14]` | 同一提交者身份恒定 |</author_identity></p>

<p>会话 ID 用「工具名 + 会话 ID」做哈希输入，保证跨工具不会撞；追踪 ID 每次调用都换新，用来区分同一个会话里的不同批次。人类哈希的输入是 git 提交者身份串（例如 <code class="language-plaintext highlighter-rouge">Alice Smith &lt;alice@example.com&gt;</code>），所以同一个人在任何仓库里都是同一个键。</p>

<h2 id="身份兜底按提交者推断">身份兜底：按提交者推断</h2>

<p>还有一条性质完全不同的路径，值得单独说。</p>

<p>有些 AI 工具<strong>自己就是提交者</strong>——它们以独立的 bot 账号直接提交代码。这类 commit 的作者身份本身就是证据。<code class="language-plaintext highlighter-rouge">src/authorship/agent_detection.rs</code> 里维护了两张映射表：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">const</span> <span class="n">AGENT_EMAIL_MAPPINGS</span><span class="p">:</span> <span class="o">&amp;</span><span class="p">[(</span><span class="o">&amp;</span><span class="nb">str</span><span class="p">,</span> <span class="o">&amp;</span><span class="nb">str</span><span class="p">)]</span> <span class="o">=</span> <span class="o">&amp;</span><span class="p">[</span>
    <span class="p">(</span><span class="s">"cursoragent@cursor.com"</span><span class="p">,</span> <span class="s">"cursor-agent"</span><span class="p">),</span>
    <span class="p">(</span><span class="s">"+copilot@users.noreply.github.com"</span><span class="p">,</span> <span class="s">"github-copilot-agent"</span><span class="p">),</span>
    <span class="p">(</span>
        <span class="s">"+devin-ai-integration[bot]@users.noreply.github.com"</span><span class="p">,</span>
        <span class="s">"devin"</span><span class="p">,</span>
    <span class="p">),</span>
    <span class="p">(</span><span class="s">"noreply@anthropic.com"</span><span class="p">,</span> <span class="s">"claude-web"</span><span class="p">),</span>
    <span class="p">(</span><span class="s">"noreply@openai.com"</span><span class="p">,</span> <span class="s">"codex-cloud"</span><span class="p">),</span>
    <span class="p">(</span><span class="s">"roomote@roocode.com"</span><span class="p">,</span> <span class="s">"roo-background"</span><span class="p">),</span>
<span class="p">];</span>
</code></pre></div></div>

<p>匹配规则有两条（<code class="language-plaintext highlighter-rouge">src/authorship/agent_detection.rs</code> 的 <code class="language-plaintext highlighter-rouge">match_email_to_agent</code>）：</p>

<ul>
  <li><strong>精确匹配</strong>——邮箱全等；</li>
  <li><strong>后缀匹配</strong>——GitHub 的 noreply 邮箱形如 <code class="language-plaintext highlighter-rouge">198982749+Copilot@users.noreply.github.com</code>，前面那串数字是用户 ID、会变，所以对以 <code class="language-plaintext highlighter-rouge">+</code> 开头的模式只比后缀。</li>
</ul>

<p>匹配上之后，<code class="language-plaintext highlighter-rouge">simulate_agent_authorship</code>（<code class="language-plaintext highlighter-rouge">src/authorship/agent_detection.rs</code> 的同名函数）会<strong>模拟</strong>出一条归属记录（函数名就叫 simulate）：整个 commit 的所有行都算这个工具写的，模型名标成 <code class="language-plaintext highlighter-rouge">unknown</code>，会话 ID 直接用 commit SHA。</p>

<p>注意这条路径的性质：<strong>它判断的是「这个提交是谁做的」，不是「这段代码像不像 AI 写的」。</strong>依据是账号身份这个客观事实，代价是精度从行级退化到 commit 级，模型信息也丢了。</p>

<p>把这三条路径放在一起，「怎么识别 AI 写的还是人写的」的完整答案就是：</p>

<table>
  <thead>
    <tr>
      <th>路径</th>
      <th>依据</th>
      <th>精度</th>
      <th>性质</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>显式上报</td>
      <td>agent 说它写了哪些行</td>
      <td>行级</td>
      <td>证据</td>
    </tr>
    <tr>
      <td>恢复层</td>
      <td>时间窗 / commit 元数据 / 环境特征</td>
      <td>行级到 commit 级</td>
      <td>启发式</td>
    </tr>
    <tr>
      <td>身份兜底</td>
      <td>提交者是已知的 agent 账号</td>
      <td>commit 级</td>
      <td>证据</td>
    </tr>
  </tbody>
</table>

<p>第三条本质上也属于证据层——它凭的是客观的账号身份，不含任何猜测；单列出来，是因为它的精度只到 commit 级，代价是模型信息也丢了。</p>

<p><strong>没有任何一条是靠代码风格去猜的。</strong></p>

<h2 id="数据落在哪git-notes">数据落在哪：Git Notes</h2>

<h3 id="为什么不改-commit">为什么不改 commit</h3>

<p>最直觉的做法是把「这行是 AI 写的」写进 commit message 或者代码注释。但两个都不行：前者无法表达行级归属，后者污染源码且在代码移动后立刻失效。</p>

<p>git-ai 的选择是 <strong>Git Notes</strong>——一种附着在任意 Git 对象上的旁路元数据，写它不改变被附着对象的 SHA。</p>

<p>存放位置被规范强制约束（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 的 1.1 节「Notes Reference」）：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>- Authorship logs MUST be stored under the `refs/notes/ai` namespace
- Implementations MUST NOT use the default `refs/notes/commits` namespace to avoid conflicts with other tools
- Each commit SHA MAY have at most one authorship log attached
</code></pre></div></div>

<p>用 <code class="language-plaintext highlighter-rouge">refs/notes/ai</code> 而不是默认的 <code class="language-plaintext highlighter-rouge">refs/notes/commits</code>，是为了不和别的工具抢同一个命名空间——这是把 notes 当成<strong>公共基础设施</strong>来用的自觉。源码里的常量在 <code class="language-plaintext highlighter-rouge">src/git/refs.rs</code> 顶部（<code class="language-plaintext highlighter-rouge">AI_AUTHORSHIP_FULL_REF</code>、<code class="language-plaintext highlighter-rouge">AI_AUTHORSHIP_FORK_TRACKING_REF</code>、<code class="language-plaintext highlighter-rouge">AI_AUTHORSHIP_PUSH_REFSPEC</code>）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">pub</span> <span class="k">const</span> <span class="n">AI_AUTHORSHIP_FULL_REF</span><span class="p">:</span> <span class="o">&amp;</span><span class="nb">str</span> <span class="o">=</span> <span class="s">"refs/notes/ai"</span><span class="p">;</span>
<span class="k">pub</span> <span class="k">const</span> <span class="n">AI_AUTHORSHIP_FORK_TRACKING_REF</span><span class="p">:</span> <span class="o">&amp;</span><span class="nb">str</span> <span class="o">=</span> <span class="s">"refs/notes/ai-remote/fork"</span><span class="p">;</span>
<span class="k">pub</span> <span class="k">const</span> <span class="n">AI_AUTHORSHIP_PUSH_REFSPEC</span><span class="p">:</span> <span class="o">&amp;</span><span class="nb">str</span> <span class="o">=</span> <span class="s">"refs/notes/ai:refs/notes/ai"</span><span class="p">;</span>
</code></pre></div></div>

<h3 id="一条-note-长什么样">一条 note 长什么样</h3>

<p>note 的正文由两段组成，中间用一行 <code class="language-plaintext highlighter-rouge">---</code> 分隔（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 的 1.2 节「Log Format」）：</p>

<ol>
  <li><strong>归属段（Attestation Section）</strong>：按文件列出「哪些行属于哪个键」；</li>
  <li><strong>元数据段（Metadata Section）</strong>：一个 JSON 对象，存会话记录、人类记录、版本信息。</li>
</ol>

<p>下面是标准文档里的完整示例（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 的 1.2.5 节「Complete Example (Sessions Format)」），原样照抄：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>src/main.rs
  s_c9883b05a2487d::t_9f8e7d6c5b4a32 1-10,15-20
  s_c9883b05a2487d::t_a1b2c3d4e5f678 25,30-35
  h_31dce776f88375 42-50
src/lib.rs
  s_e7f2a90b31cc48::t_deadbeef012345 1-50
---
{
  "schema_version": "authorship/3.0.0",
  "git_ai_version": "1.4.5",
  "base_commit_sha": "7734793b756b3921c88db5375a8c156e9532447b",
  "prompts": {},
  "humans": {
    "h_31dce776f88375": {
      "author": "Developer &lt;dev@example.com&gt;"
    }
  },
  "sessions": {
    "s_c9883b05a2487d": {
      "agent_id": {
        "tool": "cursor",
        "id": "6ef2299e-a67f-432b-aa80-3d2fb4d28999",
        "model": "claude-sonnet-4-5-20250514"
      },
      "human_author": "dev@example.com"
    },
    "s_e7f2a90b31cc48": {
      "agent_id": {
        "tool": "claude",
        "id": "conv_abc123def456",
        "model": "claude-sonnet-4-5-20250514"
      },
      "human_author": "dev@example.com",
      "custom_attributes": {
        "team": "backend"
      }
    }
  }
}
</code></pre></div></div>

<p>这个格式有几个值得琢磨的细节：</p>

<ul>
  <li><strong>分隔线是格式的一部分，不是排版。</strong> 规范明确要求 <code class="language-plaintext highlighter-rouge">---</code> 独占一行、前面后面没有空白（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 的 1.2.2 节「Overall Structure」里那句 “The divider <code class="language-plaintext highlighter-rouge">---</code> MUST appear on its own line”）。这样做是为了让读取器可以<strong>只读前半段</strong>：<code class="language-plaintext highlighter-rouge">git ai blame</code> 要在几毫秒内给出行级作者，完全不需要加载会话和 prompt 的元数据。先按分隔线切一下，再决定要不要读后半段，是很典型的「按访问模式设计格式」。</li>
  <li><strong>行号是 1 起始的</strong>，闭区间，且推荐连续行写成区间（<code class="language-plaintext highlighter-rouge">1-10</code> 而不是 <code class="language-plaintext highlighter-rouge">1,2,3,...,10</code>）。</li>
  <li><strong>键的前缀决定去哪张表里查</strong>：<code class="language-plaintext highlighter-rouge">s_</code> 查 <code class="language-plaintext highlighter-rouge">sessions</code>，<code class="language-plaintext highlighter-rouge">h_</code> 查 <code class="language-plaintext highlighter-rouge">humans</code>，裸 hex 查 <code class="language-plaintext highlighter-rouge">prompts</code>。三种格式可以在同一条 note 里混用，这是从旧版本升级时的过渡设计。</li>
  <li><strong>文件名带空格要加引号</strong>：<code class="language-plaintext highlighter-rouge">"src/my file.rs"</code>。这是从「按分隔符切文件」的解析器里学到的教训——不引号包裹就切不开。</li>
</ul>

<p>还有两点「字段不存在」本身也是信息：</p>

<ul>
  <li><strong>note 里没有「自己属于哪个 commit」的字段</strong>——commit SHA 就是 git notes 的 key，它隐含在 notes 树的路径里，冗余存一份反而有不一致的风险。（元数据段里的 <code class="language-plaintext highlighter-rouge">base_commit_sha</code> 指父提交，不是它自己。）</li>
  <li><strong>note 里没有时间戳</strong>——<code class="language-plaintext highlighter-rouge">AuthorshipMetadata</code> 及其子结构都没有时间字段（<code class="language-plaintext highlighter-rouge">src/authorship/authorship_log_serialization.rs</code> 的 <code class="language-plaintext highlighter-rouge">AuthorshipMetadata</code> 结构体定义）。时间只存在于<strong>本地</strong>的 <code class="language-plaintext highlighter-rouge">checkpoints.jsonl</code> 里（<code class="language-plaintext highlighter-rouge">src/authorship/working_log.rs</code> 的 <code class="language-plaintext highlighter-rouge">Checkpoint</code> 结构体定义）。</li>
</ul>

<p>也就是说，推到远端的那份数据是<strong>关于代码的静态事实</strong>，不含时间维度。想做时间序列分析，得靠本地数据或者托管服务。</p>

<h3 id="规范和实现差了一处">规范和实现差了一处</h3>

<p>规范 <code class="language-plaintext highlighter-rouge">2.5</code> 节（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 的 2.5「Stash / Pop」）要求 stash 的归属写进另一个命名空间 <code class="language-plaintext highlighter-rouge">refs/notes/ai-stash</code>——stash 记录挂在 stash commit 的 SHA 上，和普通 commit 混在同一个命名空间里会串。</p>

<p>但在 v1.7.7 的 <code class="language-plaintext highlighter-rouge">src/</code> 目录里，<code class="language-plaintext highlighter-rouge">refs/notes/ai-stash</code> <strong>一次都没出现过</strong>（源码零命中）；只有规范本身（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 的 2.5 节里「Stash Push / Save」那段）和测试文件里还留着它——测试里那几处只是描述旧行为的注释。实际实现把 stash 归属存成 <code class="language-plaintext highlighter-rouge">&lt;git-dir&gt;/ai/stashes_v2/&lt;stash-sha&gt;/</code>——一个工作区账本形态的目录（<code class="language-plaintext highlighter-rouge">src/authorship/rewrite_stash.rs</code> 里 <code class="language-plaintext highlighter-rouge">stashes_v2_dir</code> / <code class="language-plaintext highlighter-rouge">stash_entry_dir</code> 那几个函数）。</p>

<p>这是读开源项目源码时值得留意的一类现象：<strong>规范写的是「应该怎样」，实现可能只走到一半</strong>。规范是给其他实现者看的契约，而这份参考实现自己未必已经完全对齐。判断一个行为到底是什么，得看代码，不能只看规范。</p>

<h3 id="note-是怎么写进去的">note 是怎么写进去的</h3>

<p>一个实现细节：写 note 用的不是 <code class="language-plaintext highlighter-rouge">git notes add</code>，而是 <code class="language-plaintext highlighter-rouge">git fast-import</code> 直接构造 notes 树（<code class="language-plaintext highlighter-rouge">src/git/refs.rs</code> 的 <code class="language-plaintext highlighter-rouge">notes_add_batch</code>）。源码注释解释了原因——<code class="language-plaintext highlighter-rouge">git notes add</code> 在小树上会产生扁平条目，和 fanout 目录混用会让 <code class="language-plaintext highlighter-rouge">git notes merge</code> 出问题。git-ai 自己按两字符 fanout 组织路径（<code class="language-plaintext highlighter-rouge">src/git/refs.rs</code> 的 <code class="language-plaintext highlighter-rouge">write_note_path</code>），保证树形结构一致。</p>

<p>这个细节看着琐碎，但它解释了为什么 note 的写入不依赖任何 git 配置，也不会因为用户的 <code class="language-plaintext highlighter-rouge">core.notesRef</code> 设置而跑偏。</p>

<h2 id="三分钟自己看一眼">三分钟自己看一眼</h2>

<p>上面讲的全是机制。想确认它在自己仓库里到底是什么行为，装上、跑两条命令看一眼就够了。</p>

<p><strong>先装上。</strong> 安装脚本就是后面 CI 那节里用的那一个：</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-fsSL</span> https://usegitai.com/install.sh | bash
</code></pre></div></div>

<p>装完把 <code class="language-plaintext highlighter-rouge">~/.git-ai/bin</code> 加进 PATH（<code class="language-plaintext highlighter-rouge">install.sh</code> 里设的 <code class="language-plaintext highlighter-rouge">INSTALL_DIR</code> 就是它）。</p>

<p><strong>看别人仓库里已有的 note。</strong> 在一个已经被 git-ai 记录过的仓库里：</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log <span class="nt">--show-notes</span><span class="o">=</span><span class="s2">"ai"</span>
</code></pre></div></div>

<p>每个 commit 后面会挂着一段 note：先是归属段（文件名 + 行号区间 + 归属键），然后是单独一行的 <code class="language-plaintext highlighter-rouge">---</code>，再是 JSON 元数据。这段 note 就是「这个 commit 的行归属」本身——它是普通的 git 对象，clone 下来就在，不需要额外的工具。</p>

<p><strong>看单个文件的行归属。</strong></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git ai blame &lt;path/to/file&gt;
</code></pre></div></div>

<p>输出里每一行都会带上归属标注：AI 写的行、已知人类写的行，以及<strong>没有任何证据覆盖的行</strong>。第三类最值得看——它既不等于「人写的」，也不等于「AI 写的」，只是没有证据。</p>

<blockquote>
  <p>这几条命令的输出具体长什么样，取决于仓库里装了什么、agent 配没配；上面说的是「你会看到哪几类信息」，不是逐字的输出。真跑一遍比看文档快。</p>
</blockquote>

<h2 id="怎么进-github">怎么进 GitHub</h2>

<p>推送用的是最朴素的办法——一条 refspec（<code class="language-plaintext highlighter-rouge">src/git/sync_authorship.rs</code> 的 <code class="language-plaintext highlighter-rouge">build_authorship_push_args</code>）：</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">args</span><span class="nf">.push</span><span class="p">(</span><span class="s">"push"</span><span class="nf">.to_string</span><span class="p">());</span>
<span class="n">args</span><span class="nf">.push</span><span class="p">(</span><span class="s">"--quiet"</span><span class="nf">.to_string</span><span class="p">());</span>
<span class="n">args</span><span class="nf">.push</span><span class="p">(</span><span class="s">"--no-recurse-submodules"</span><span class="nf">.to_string</span><span class="p">());</span>
<span class="n">args</span><span class="nf">.push</span><span class="p">(</span><span class="s">"--no-verify"</span><span class="nf">.to_string</span><span class="p">());</span>
<span class="n">args</span><span class="nf">.push</span><span class="p">(</span><span class="s">"--no-signed"</span><span class="nf">.to_string</span><span class="p">());</span>
<span class="n">args</span><span class="nf">.push</span><span class="p">(</span><span class="n">remote_name</span><span class="nf">.to_string</span><span class="p">());</span>
<span class="n">args</span><span class="nf">.push</span><span class="p">(</span><span class="n">AI_AUTHORSHIP_PUSH_REFSPEC</span><span class="nf">.to_string</span><span class="p">());</span>
</code></pre></div></div>

<p>也就是 git-ai 实际拼出来的那条命令（<code class="language-plaintext highlighter-rouge">-c core.hooksPath=/dev/null</code> 是关掉 git hook 用的，Windows 上源码里那一支是 <code class="language-plaintext highlighter-rouge">core.hooksPath=NUL</code>）：</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git <span class="nt">-c</span> core.hooksPath<span class="o">=</span>/dev/null push <span class="nt">--quiet</span> <span class="nt">--no-recurse-submodules</span> <span class="nt">--no-verify</span> <span class="nt">--no-signed</span> &lt;remote&gt; refs/notes/ai:refs/notes/ai
</code></pre></div></div>

<p><strong>没有用 REST API，没有写 PR comment，没有建 check run。</strong>归属数据以普通的 Git 对象形式躺在远端仓库的一个特殊 ref 下，用任何 Git 客户端都能读——README 的 FAQs 一节（”How does it work?”）给的就是这条命令：</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log <span class="nt">--show-notes</span><span class="o">=</span><span class="s2">"ai"</span>
</code></pre></div></div>

<p>这个选择带来几个直接的好处：</p>

<ul>
  <li>远端可以正常 clone、fetch、mirror，<strong>不需要 git-ai 也能拿到数据</strong>——任何实现了这份标准（<code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code> 开篇那段说这是开放标准）的工具都能读；</li>
  <li>不依赖任何一家的私有 API，GitHub、GitLab、自建 Gitea 都能用；</li>
  <li>访问控制沿用仓库本身的权限模型，不需要额外一套。</li>
</ul>

<h3 id="推送不是一次直推">推送不是一次直推</h3>

<p><code class="language-plaintext highlighter-rouge">git push</code> 之前还有一步。实际流程是<strong>先 fetch、合并、再 push</strong>（<code class="language-plaintext highlighter-rouge">src/git/sync_authorship.rs</code> 的 <code class="language-plaintext highlighter-rouge">push_authorship_notes</code> 与 <code class="language-plaintext highlighter-rouge">fetch_and_merge_tracking_notes</code>）：</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git <span class="nt">-c</span> core.hooksPath<span class="o">=</span>/dev/null fetch <span class="nt">--no-tags</span> <span class="nt">--recurse-submodules</span><span class="o">=</span>no <span class="nt">--no-write-fetch-head</span> <span class="nt">--no-write-commit-graph</span> <span class="nt">--no-auto-maintenance</span> &lt;remote&gt; +refs/notes/ai:refs/notes/ai-remote/&lt;remote&gt;
git <span class="nt">-c</span> core.hooksPath<span class="o">=</span>/dev/null push <span class="nt">--quiet</span> <span class="nt">--no-recurse-submodules</span> <span class="nt">--no-verify</span> <span class="nt">--no-signed</span> &lt;remote&gt; refs/notes/ai:refs/notes/ai
</code></pre></div></div>

<p>中间那个 <code class="language-plaintext highlighter-rouge">refs/notes/ai-remote/&lt;remote&gt;</code> 是专门用来存远端副本的 tracking ref。合并用的是 <code class="language-plaintext highlighter-rouge">-s ours</code> 策略，失败时降级重试；<strong>push 不带 force</strong>，要求 fast-forward，非 fast-forward 时最多重试三轮。</p>

<p>这个设计解决的是多人和协作场景下的一个真实问题：两个人各自在本地产生了 note，直接推会互相覆盖。先把远端的拉下来合并，再推自己的，才不会丢数据。</p>

<p>对 fork 的 PR，CI 里还有额外处理：先探测 fork 上有没有 notes ref（<code class="language-plaintext highlighter-rouge">git ls-remote &lt;fork&gt; refs/notes/ai</code>），有就 fetch 进 <code class="language-plaintext highlighter-rouge">refs/notes/ai-remote/fork</code>，然后<strong>只把这个 PR 涉及的那几个 commit 的 note 拷进 <code class="language-plaintext highlighter-rouge">refs/notes/ai</code></strong>（<code class="language-plaintext highlighter-rouge">src/ci/ci_context.rs</code> 的 <code class="language-plaintext highlighter-rouge">import_fork_notes_for_commits</code>）。为什么不能整包合并，源码注释说得很清楚（<code class="language-plaintext highlighter-rouge">src/git/refs.rs</code> 的 <code class="language-plaintext highlighter-rouge">copy_missing_notes_for_commits_from_ref</code> 上面那段文档注释）：</p>

<blockquote>
  <p>这刻意不做整体合并。源 ref 里可能含有来自 fork 的<strong>不可信 note</strong>，所以调用方必须精确指定哪些 commit 的 note 才允许进入本地的归属 ref。</p>
</blockquote>

<h3 id="还有一条不走-github-的路">还有一条不走 GitHub 的路</h3>

<p>上面说的是默认模式。但 git-ai 还有第二种存储后端，这个后端<strong>和 GitHub 没关系</strong>。</p>

<p>配置里有个 <code class="language-plaintext highlighter-rouge">NotesBackendKind</code> 枚举（<code class="language-plaintext highlighter-rouge">src/config.rs</code> 顶部），两个取值：</p>

<table>
  <thead>
    <tr>
      <th>后端</th>
      <th>note 落在哪</th>
      <th>能推到 GitHub 吗</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">GitNotes</code>（默认）</td>
      <td><code class="language-plaintext highlighter-rouge">refs/notes/ai</code>，是 git 对象</td>
      <td>✅ 走上面那条 refspec</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Http</code></td>
      <td><code class="language-plaintext highlighter-rouge">~/.git-ai/internal/notes-db</code> + 远端服务</td>
      <td>❌ 推送被显式短路（<code class="language-plaintext highlighter-rouge">src/git/sync_authorship.rs</code> 的 <code class="language-plaintext highlighter-rouge">push_authorship_notes</code> 开头那段）</td>
    </tr>
  </tbody>
</table>

<p><strong>选了 Http 后端，note 就不再进 git 仓库，也就不再进 GitHub。</strong>它先落到本地的一个 SQLite 队列里（<code class="language-plaintext highlighter-rouge">synced=0</code>），daemon 每三秒把一批 flush 到服务端，走的是 <code class="language-plaintext highlighter-rouge">POST /worker/notes/upload</code>；反向拉取是 <code class="language-plaintext highlighter-rouge">GET /worker/notes/?commits=&lt;sha1,sha2,...&gt;</code>（<code class="language-plaintext highlighter-rouge">src/api/notes.rs</code>）。客户端只是把 note 原文整段上传，服务端怎么存、是否解析，这个 OSS 仓库里看不到。</p>

<p>什么时候会切到 Http 后端？规则在 <code class="language-plaintext highlighter-rouge">src/config.rs</code> 的 <code class="language-plaintext highlighter-rouge">build_config</code> 里（<code class="language-plaintext highlighter-rouge">default_kind</code> 那几行）：<strong>配了 API key 且没有显式指定后端时，默认切到 Http</strong>。也就是说，登录使用托管服务之后，归属数据就走托管服务了——只有保持本地模式，数据才会随 git push 进入 GitHub。</p>

<p>另外，仓库里还带了一个 <code class="language-plaintext highlighter-rouge">git-ai notes migrate</code> 命令（<code class="language-plaintext highlighter-rouge">src/commands/notes_migrate.rs</code>），可以把已有的 <code class="language-plaintext highlighter-rouge">refs/notes/ai</code> 全量上传到 Http 后端，做模式迁移。</p>

<blockquote>
  <p>这两条路的取舍很清楚：<strong>要数据跟着仓库走、跟着 clone 走、要任何工具都能读，就用 Git Notes；要服务端托管和跨仓库聚合，就用 Http 后端。</strong>鱼与熊掌不可兼得——HTTP 后端的数据不在 git 里，clone 仓库是拿不到的。</p>
</blockquote>

<h3 id="隐私的边界">隐私的边界</h3>

<p>代价也很直白：<strong>note 的内容对所有有仓库读权限的人可见</strong>。仓库自己写的隐私说明（<code class="language-plaintext highlighter-rouge">data-privacy.md</code> 的 “Data written to your git repository” 一节）把这点列得很清楚——模型、agent、哪些行是 AI 生成的、以及背后那个人的 git 身份（姓名和邮箱），全都进仓库。而<strong>完整的 prompt 不会进仓库</strong>，它留在开发者本地的 SQLite 里（<code class="language-plaintext highlighter-rouge">data-privacy.md</code> 的 “Local-only data” 一节）。这个切分是合理的：元数据进版本库（大家都能看，本来也没什么秘密），内容不进（那是私人的）。</p>

<p>不过这份隐私说明和实现之间还有一处出入：<code class="language-plaintext highlighter-rouge">data-privacy.md</code> 那节列的「Model, agent, and accepted-rate percentages」说写进 notes 的内容包含「accepted-rate percentages」，但当前的 session 格式（也就是 <code class="language-plaintext highlighter-rouge">s_</code> 开头的键）里，<code class="language-plaintext highlighter-rouge">SessionRecord</code> 结构体（<code class="language-plaintext highlighter-rouge">src/authorship/authorship_log.rs</code> 的 <code class="language-plaintext highlighter-rouge">SessionRecord</code> 定义）<strong>没有任何统计字段</strong>——<code class="language-plaintext highlighter-rouge">accepted_lines</code>、<code class="language-plaintext highlighter-rouge">overriden_lines</code> 这些只存在于旧格式的 <code class="language-plaintext highlighter-rouge">PromptRecord</code> 里。所以新生成的 note 并不带接受率数据。</p>

<h2 id="历史被改写时归属怎么活下来">历史被改写时，归属怎么活下来</h2>

<p>这是整个系统里最难的部分。它的规范（<code class="language-plaintext highlighter-rouge">docs/rewrite-ops-spec.md</code>）开头先立了四条<strong>第一性原理不变量</strong>，这四条比任何具体实现都更值得读：</p>

<blockquote>
  <p><strong>I1 — 证据规则。</strong> 一行代码只有在两种情况下才有归属：checkpoint 证据，或者已有的归属记录通过<strong>不可变的 git 对象数据</strong>连到了新位置。<strong>不允许</strong>基于相似度、时间戳、或者「大概是同一行」的推断。</p>

  <p><strong>I2 — 守恒规则。</strong> 如果一行内容在改写后<strong>由 git 自己的 tree diff 判定为未变</strong>，它的归属跟着它走（包括跨文件重命名）。如果 git 的 diff 说这块变了，旧归属就地丢弃——新内容需要新证据。</p>

  <p><strong>I3 — 不可变规则。</strong> 改写决策的每个输入，在决策时刻都必须不可变：commit SHA、tree SHA、blob 内容、note、持久化的账本快照、以及由命令确切拥有的 ref 变更。<strong>活的工作区</strong>只有在 checkpoint 处理内部、在 checkpoint 那一刻才是合法输入；git 退出后才跑的 daemon 副作用，绝不能去读工作区并把它当成刚才那条命令的状态。</p>

  <p><strong>I4 — Fail-closed 规则。</strong> 当 I1–I3 需要的事实拿不到时（比如延迟执行的改写无法确定精确的前后 tip），正确的输出是<strong>不迁移</strong>——<strong>归属有缺口是可以接受的，错误归属不行</strong>。</p>
</blockquote>

<p>这四条读完，很多设计就自解释了。比如 I3 里那句「这条规则杀死了历史上的 mtime 保护快照和活工作区 stash 恢复竞态」——这是被真实 bug 逼出来的约束，不是预防性编程。</p>

<h3 id="核心算法九步迁移">核心算法：九步迁移</h3>

<p>把一组「源 commit → 目标 commit」的映射搬过去，流程是固定的（<code class="language-plaintext highlighter-rouge">docs/rewrite-ops-spec.md</code> 的 “Core note-shift algorithm” 一节）：</p>

<ol>
  <li>批量读所有源和目标的 note；</li>
  <li>把每个唯一的 commit SHA 一次性解析成 tree SHA（一次 <code class="language-plaintext highlighter-rouge">git rev-parse</code>）；</li>
  <li>对所有 tree 对跑<strong>一次</strong> <code class="language-plaintext highlighter-rouge">git diff-tree --stdin -p -U0 -M -r</code>；</li>
  <li>解析每个 pair 的 hunk 和重命名；</li>
  <li>算出「保留段」（所有 hunk 之外的区域）和累计行号偏移；</li>
  <li>把落在保留段里的归属区间做行号位移；<strong>与任何 hunk 重叠的区间直接丢弃</strong>（I2）；</li>
  <li>与目标已有的 note 合并（冲突解决可能已经写过归属），按 <code class="language-plaintext highlighter-rouge">(文件路径, 哈希)</code> 去重并合并区间；</li>
  <li>把 <code class="language-plaintext highlighter-rouge">base_commit_sha</code> 更新成目标 commit；</li>
  <li>批量写回目标 note。</li>
</ol>

<p>有个性能约定挺有意思（<code class="language-plaintext highlighter-rouge">docs/rewrite-ops-spec.md</code> 的 “Core note-shift algorithm” 一节里 “Performance contract” 那段）：<strong>每批改写启动的 git 子进程数量是 O(1)，不是 O(commit 数) 也不是 O(文件数)</strong>。与历史规模成正比的工作被塞进单次 git 调用内部（<code class="language-plaintext highlighter-rouge">diff-tree --stdin</code>、<code class="language-plaintext highlighter-rouge">range-diff</code>、<code class="language-plaintext highlighter-rouge">rev-list</code>、<code class="language-plaintext highlighter-rouge">log --stdin</code> + <code class="language-plaintext highlighter-rouge">patch-id --stable</code>）——这是 git 本身能给的性能下限。</p>

<p>还有个<strong>明知故犯的局限</strong>，规范里写得很坦率（同一节里 “Known, intentional limitation” 那段）：</p>

<blockquote>
  <p>算法是行级的。hunk 内部被重写的内容会丢掉旧归属，哪怕人会说「这还是同一行，只是改了措辞」。模糊匹配是 I1 禁止的启发式层。</p>
</blockquote>

<p>另外一处是刻意的收紧（同一文档 “Non-fast-forward” 一节里那段 “Note (intentional, not a regression)”）：冲突区内容变了又没有对应的解决 checkpoint 时，<strong>故意留成无归属</strong>。规范里说明了理由——老行为会按位置把旧归属映射到改写后的行上，那违反了 I1 和 I2，所以被移除了。</p>

<h3 id="各操作的处理方式">各操作的处理方式</h3>

<table>
  <thead>
    <tr>
      <th>操作</th>
      <th>归属怎么处理</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">rebase</code>（1:1）</td>
      <td>逐个复制到新 SHA，行号不变（内容没变）</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">rebase</code>（调序）</td>
      <td>行号按新顺序重算</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">rebase</code>（squash）</td>
      <td>多个 commit 的会话记录合并，行号按最终文件状态算；同一行被不同会话改过时，<strong>最后一个会话胜出</strong></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">rebase</code>（拆分）</td>
      <td>原归属按行拆分到各个新 commit，每个 commit 只带自己 diff 里出现的行</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">cherry-pick</code></td>
      <td>复制到新 SHA，行号按新位置重算；用 <code class="language-plaintext highlighter-rouge">patch-id --stable</code> 配对源和目标</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">merge --squash</code></td>
      <td>归属从已提交的 note <strong>迁到工作区账本</strong>，下次提交时自然带上</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">reset --soft/--mixed</code></td>
      <td>同上，迁到工作区账本</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">reset --hard</code></td>
      <td>工作区账本清空，但<strong>已提交的 note 不删</strong></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">stash</code></td>
      <td>账本存进 <code class="language-plaintext highlighter-rouge">&lt;git-dir&gt;/ai/stashes_v2/</code>，pop 出来时再迁回工作区</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">commit --amend</code></td>
      <td>原 note + 工作区账本合并后写到新 SHA；原 note 删除</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">merge</code>（产生 merge commit）</td>
      <td>merge commit 只记<strong>冲突解决</strong>产生的那部分</td>
    </tr>
  </tbody>
</table>

<p>「迁到工作区账本」这个概念是整套设计里最巧的一笔。它解决的是这样一类问题：<code class="language-plaintext highlighter-rouge">merge --squash</code> 之后代码还<strong>没有提交</strong>，归属数据既不在任何一个 commit 上（因为还没 commit），也不该丢。git-ai 给它找了个去处——工作区账本，等下一次提交时自然被吸收进去。</p>

<h3 id="不支持的场景">不支持的场景</h3>

<p>README 的能力表里明确列了几个「不支持」：</p>

<table>
  <thead>
    <tr>
      <th>操作</th>
      <th>状态</th>
      <th>原因</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">git mv</code></td>
      <td>❌</td>
      <td>重命名还没被跟踪，归属不会跟着文件走</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">git filter-branch</code> / <code class="language-plaintext highlighter-rouge">git filter-repo</code></td>
      <td>❌</td>
      <td>批量历史重写不跟踪</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">git replace</code></td>
      <td>❌</td>
      <td>对象替换不跟踪</td>
    </tr>
  </tbody>
</table>

<p>前三条都是「历史被大规模重写」的场景，本质上和 rebase 一样要重算归属，但实现难度高得多。git-ai 选择先不支持，这是合理的取舍。</p>

<h2 id="github-上还差一环ci">GitHub 上还差一环：CI</h2>

<p>上面说的所有归属保住逻辑，都发生在<strong>本地</strong>。但在 GitHub 上，合并 PR 时还有一道坎：</p>

<ul>
  <li><strong>Squash and Merge</strong>：把 N 个 PR commit 压成 1 个新 commit，SHA 全变；</li>
  <li><strong>Rebase and Merge</strong>：把 PR commit 重新 base 到主干，每个 commit 的 SHA 都变。</li>
</ul>

<p>这两种合并方式都会让 PR 里积累的归属归零。git-ai 的解法是让 CI 在合并后补算一次。</p>

<p>源码里带的 GitHub Actions 模板在 <code class="language-plaintext highlighter-rouge">src/ci/workflow_templates/github.yaml</code>，完整内容不长：</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">name</span><span class="pi">:</span> <span class="s">Git AI</span>

<span class="na">on</span><span class="pi">:</span>
  <span class="na">pull_request</span><span class="pi">:</span>
    <span class="na">types</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">closed</span><span class="pi">,</span> <span class="nv">synchronize</span><span class="pi">]</span>

<span class="na">jobs</span><span class="pi">:</span>
  <span class="na">git-ai</span><span class="pi">:</span>
    <span class="na">if</span><span class="pi">:</span> <span class="s">github.event.pull_request.merged == </span><span class="no">true</span><span class="s"> || github.event.action == 'synchronize'</span>
    <span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
    <span class="na">permissions</span><span class="pi">:</span>
      <span class="na">contents</span><span class="pi">:</span> <span class="s">write</span>

    <span class="na">steps</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Install git-ai</span>
        <span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
          <span class="s">curl -fsSL https://usegitai.com/install.sh | bash</span>
          <span class="s">echo "$HOME/.git-ai/bin" &gt;&gt; $GITHUB_PATH</span>
      <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Run git-ai</span>
        <span class="na">id</span><span class="pi">:</span> <span class="s">run-git-ai</span>
        <span class="na">env</span><span class="pi">:</span>
          <span class="na">GITHUB_TOKEN</span><span class="pi">:</span> <span class="s">$</span>
        <span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
          <span class="s">git config --global user.name "github-actions[bot]"</span>
          <span class="s">git config --global user.email "github-actions[bot]@users.noreply.github.com"</span>
          <span class="s">git-ai ci github run</span>
</code></pre></div></div>

<p>几个点：</p>

<ul>
  <li>触发条件是 <strong>PR closed 且已合并</strong>，或者 <strong>PR 内容更新</strong>（<code class="language-plaintext highlighter-rouge">synchronize</code>）；</li>
  <li>权限只申请了 <code class="language-plaintext highlighter-rouge">contents: write</code>——<strong>够用来推 notes，不够用来动代码</strong>。这是最小权限的正确写法；</li>
  <li>用 <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code> 鉴权，且它只用于<strong>克隆认证</strong>（<code class="language-plaintext highlighter-rouge">src/ci/github.rs</code> 的 <code class="language-plaintext highlighter-rouge">get_github_ci_context</code> 里 <code class="language-plaintext highlighter-rouge">authenticate_clone_url</code> 那几行）；</li>
  <li>提交者身份被设成 <code class="language-plaintext highlighter-rouge">github-actions[bot]</code>，所以 CI 补算出来的归属不会污染任何人的 git 身份。</li>
</ul>

<p>GitLab 有对应的实现（<code class="language-plaintext highlighter-rouge">src/ci/gitlab.rs</code>），走的是 <code class="language-plaintext highlighter-rouge">PRIVATE-TOKEN</code> / <code class="language-plaintext highlighter-rouge">JOB-TOKEN</code>。</p>

<h2 id="几个值得抄的工程决策">几个值得抄的工程决策</h2>

<p>抛开功能不谈，这个项目里有几个设计选择我觉得可以直接搬到别的场景。</p>

<h3 id="一分层并且每层都写清什么时候不猜">一、分层，并且每层都写清「什么时候不猜」</h3>

<p>最值得学的不是「它用了启发式」，而是<strong>它把启发式的边界写死了</strong>：时间窗是 3 秒、候选分四个等级、session 事件要求仓库地址完全相等、兜底归人有前提条件、数据库不可用就留空。</p>

<p><strong>「证据不足时留空，而不是猜一个」</strong>——这条纪律在归属系统里和在分析引擎里是同一条。留空是可观测的、可统计的（「未跟踪 8%」是一个可以拿去做决策的数字）；猜出来的归属不可观测，一旦错了，你连它错在哪都不知道。</p>

<h3 id="二把不确定显式建模成一种状态">二、把「不确定」显式建模成一种状态</h3>

<p>「未跟踪」是三态模型里的第三态，它的存在让「AI 占比」这个数字有了确定的含义——<strong>在有归属的行里，AI 占多少</strong>，而不是「整个仓库里 AI 写了几行」。后者在装了扩展的老仓库上会严重偏低，在没装扩展的仓库上会直接是 0。反方向也要留个心眼：整块 hunk 归 AI 的归集规则，又会把 AI 那一侧抬高。所以「AI 占比」是两个方向的偏差叠在一起的净值，不是逐行事实。</p>

<h3 id="三用旁路元数据换掉侵入式标注">三、用旁路元数据换掉侵入式标注</h3>

<p>不改 commit、不改源码、不加注释，代价是「归属不在文件里」，换来的是零侵入、零污染、commit 照常可用。<strong>能挂在对象外面就不要挂在里面。</strong></p>

<h3 id="四连分隔线都是格式契约">四、连分隔线都是格式契约</h3>

<p><code class="language-plaintext highlighter-rouge">---</code> 这一行不只是排版，它是<strong>读取策略的一部分</strong>。热路径只读前半段，冷路径才读后半段。格式设计时先问「谁会读哪一段」，比先问「长什么样」更有用。</p>

<h3 id="五不拦截-git就不要装-git-hook">五、不拦截 git，就不要装 git hook</h3>

<p>README 强调「不依赖 git hook」（<code class="language-plaintext highlighter-rouge">README.md</code> 的 “Our Choices” 一节里 “No performance overhead” 那条），就 git hook 而言<strong>属实</strong>：源码里搜不到任何 <code class="language-plaintext highlighter-rouge">pre-commit</code> / <code class="language-plaintext highlighter-rouge">post-commit</code> 的安装逻辑，core hooks 功能已经下线，<code class="language-plaintext highlighter-rouge">src/commands/git_hook_handlers.rs</code> 的文件头写明这个模块现在只剩下「检测并清理历史遗留的 hook 符号链接」。</p>

<p>那 commit 是怎么被发现的？靠 <strong>daemon</strong>。git-ai 会写一条<strong>全局</strong> git 配置 <code class="language-plaintext highlighter-rouge">trace2.eventTarget</code> 指向 daemon 的 socket（<code class="language-plaintext highlighter-rouge">src/commands/install_hooks.rs</code> 的 <code class="language-plaintext highlighter-rouge">configure_daemon_trace2</code>），daemon 解析 trace2 事件流，识别出 <code class="language-plaintext highlighter-rouge">CommitCreated</code>（<code class="language-plaintext highlighter-rouge">src/daemon/analyzers/history.rs</code> 的 <code class="language-plaintext highlighter-rouge">HistoryAnalyzer::analyze</code> 里那段）；同时 daemon 还跟踪 git 的 reflog 来感知 ref 移动（<code class="language-plaintext highlighter-rouge">src/daemon/ref_cursor.rs</code>）。</p>

<blockquote>
  <p>这里有三点值得记下来：</p>

  <ol>
    <li>README 自己有点自相矛盾——<code class="language-plaintext highlighter-rouge">README.md</code> 的 “Do I have to set up agent hooks?” 一节又说「Git AI manages the agent hooks」。准确的说法是：<strong>不用 git hook，但确实要装 agent hook</strong>（写进各智能体的配置文件，Claude Code 那边是 <code class="language-plaintext highlighter-rouge">~/.claude/settings.json</code>，见 <code class="language-plaintext highlighter-rouge">src/mdm/agents/claude_code.rs</code> 的 <code class="language-plaintext highlighter-rouge">ClaudeCodeInstaller::settings_path</code>；安装器接口在 <code class="language-plaintext highlighter-rouge">src/mdm/hook_installer.rs</code> 的 <code class="language-plaintext highlighter-rouge">HookInstaller</code> trait）。智能体不配合，整套机制就没有输入。</li>
    <li><code class="language-plaintext highlighter-rouge">trace2.eventTarget</code> 写的是<strong>全局</strong> git 配置，影响该用户<strong>所有仓库的所有 git 调用</strong>。README 只说「No per-repo setup」，没提这个全局副作用。</li>
    <li>二进制里确实保留了一个 git 代理分支（<code class="language-plaintext highlighter-rouge">src/main.rs</code> 的 <code class="language-plaintext highlighter-rouge">main</code> 末尾那行 <code class="language-plaintext highlighter-rouge">handle_git</code> 调用，当二进制以 <code class="language-plaintext highlighter-rouge">git</code> 这个名字被调用时透明转发）。不过官方安装脚本只把它装成 <code class="language-plaintext highlighter-rouge">~/.git-ai/bin/git-ai</code>（<code class="language-plaintext highlighter-rouge">install.sh</code> 里设 <code class="language-plaintext highlighter-rouge">INSTALL_DIR</code> 那几行），并不替换 <code class="language-plaintext highlighter-rouge">git</code>，所以日常路径仍是 daemon。</li>
  </ol>
</blockquote>

<h2 id="小结">小结</h2>

<ol>
  <li><strong>git-ai 的答案分两层。</strong> 证据层靠智能体主动上报，做到行级精确；恢复层确实用了启发式（3 秒时间窗、commit 元数据匹配、环境特征探测），用来给证据不足的行补洞。<strong>没有任何一层是靠代码风格猜的。</strong></li>
  <li><strong>判定的核心是「调用的是哪个适配器」</strong>，不是内容分析。<code class="language-plaintext highlighter-rouge">CheckpointKind</code> 四个取值，<code class="language-plaintext highlighter-rouge">is_ai()</code> 一个布尔，<strong>没有置信度、没有权重</strong>。</li>
  <li><strong>状态是三态不是两态</strong>：AI、已知人类、未跟踪。<strong>未跟踪意味着没有证据，不等于人写的。</strong> 统计里的分母必须是「有归属的行」。</li>
  <li><strong>存储用 Git Notes，落在 <code class="language-plaintext highlighter-rouge">refs/notes/ai</code></strong>，正文是「归属段 + <code class="language-plaintext highlighter-rouge">---</code> + JSON 元数据」两段式；分隔线是格式契约，热路径只读前半段。</li>
  <li><strong>进 GitHub 靠一条 refspec</strong>：<code class="language-plaintext highlighter-rouge">git push &lt;remote&gt; refs/notes/ai:refs/notes/ai</code>。不用私有 API，别的工具按同一份开放标准也能读。但注意配了 API key 后会切到 Http 后端，那条路<strong>不进 GitHub</strong>。</li>
  <li><strong>历史改写靠四条不变量</strong>：证据规则、守恒规则、不可变规则、fail-closed。核心是 I1 和 I4——<strong>不允许相似度推断，事实不足就不迁移</strong>。</li>
  <li><strong>GitHub 上的合并会毁掉归属</strong>，得靠 CI 补算——模板在 <code class="language-plaintext highlighter-rouge">src/ci/workflow_templates/github.yaml</code>，只申请 <code class="language-plaintext highlighter-rouge">contents: write</code> 一个权限。</li>
  <li><strong>规范和实现会不一致，文档和源码也会不一致。</strong> 这篇文章里最值得记住的也许不是技术细节，而是：<strong>读开源项目必须读代码，不能只读 README。</strong></li>
</ol>

<hr />

<h2 id="附一源码位置索引">附一：源码位置索引</h2>

<p>本文基于 <a href="https://github.com/git-ai-project/git-ai">git-ai-project/git-ai</a> 的 <code class="language-plaintext highlighter-rouge">main</code> 分支（<code class="language-plaintext highlighter-rouge">Cargo.toml</code> 版本 <code class="language-plaintext highlighter-rouge">1.7.7</code>）分析。为了让每条结论都能回查，正文里引用到的源码位置都在下面：</p>

<table>
  <thead>
    <tr>
      <th>主题</th>
      <th>位置</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>不做风格检测的声明</td>
      <td><code class="language-plaintext highlighter-rouge">README.md</code> 的 FAQs 一节（”How does it work?” 那段）</td>
    </tr>
    <tr>
      <td>适配器（上游叫 preset）的目录与 trait</td>
      <td><code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/presets/</code>、<code class="language-plaintext highlighter-rouge">AgentPreset</code></td>
    </tr>
    <tr>
      <td>checkpoint 适配器与 <code class="language-plaintext highlighter-rouge">CheckpointKind</code> 的对应</td>
      <td><code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/orchestrator.rs</code> 的 <code class="language-plaintext highlighter-rouge">execute_post_file_edit</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CheckpointKind</code> 四值与 <code class="language-plaintext highlighter-rouge">is_ai()</code></td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/working_log.rs</code> 的 <code class="language-plaintext highlighter-rouge">CheckpointKind</code>、<code class="language-plaintext highlighter-rouge">CheckpointKind::is_ai</code></td>
    </tr>
    <tr>
      <td>本地流水条目（只存本地的那份）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/working_log.rs</code> 的 <code class="language-plaintext highlighter-rouge">Checkpoint</code></td>
    </tr>
    <tr>
      <td>Claude Code 上报适配器</td>
      <td><code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/presets/claude.rs</code> 的 <code class="language-plaintext highlighter-rouge">ClaudePreset::parse</code></td>
    </tr>
    <tr>
      <td>模型名从会话文件里抽取</td>
      <td><code class="language-plaintext highlighter-rouge">crate::streams::model_extraction::extract_model</code></td>
    </tr>
    <tr>
      <td>「已知人类」适配器（IDE 扩展上报的数据）</td>
      <td><code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/presets/known_human.rs</code> 的 <code class="language-plaintext highlighter-rouge">KnownHumanPreset::parse</code></td>
    </tr>
    <tr>
      <td>工具三分类</td>
      <td><code class="language-plaintext highlighter-rouge">src/commands/checkpoint_agent/bash_tool.rs</code> 的 <code class="language-plaintext highlighter-rouge">ToolClass</code></td>
    </tr>
    <tr>
      <td>AI 整块归属（force_split）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 的 <code class="language-plaintext highlighter-rouge">process_changed_hunk</code></td>
    </tr>
    <tr>
      <td>AI 关闭移动检测</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 的 <code class="language-plaintext highlighter-rouge">update_attributions_for_checkpoint</code></td>
    </tr>
    <tr>
      <td>AI 的删除 / 插入分支（含纯空白）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 的 <code class="language-plaintext highlighter-rouge">transform_attributions</code></td>
    </tr>
    <tr>
      <td>同一行最新时间戳胜出、已知人类不含 AI 空白</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 的 <code class="language-plaintext highlighter-rouge">find_dominant_author_for_line_candidates</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">overrode</code>（人覆盖 AI）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_tracker.rs</code> 的 <code class="language-plaintext highlighter-rouge">find_dominant_author_for_line_candidates</code>（<code class="language-plaintext highlighter-rouge">LineAttribution::overrode</code>）</td>
    </tr>
    <tr>
      <td>恢复层求解器顺序</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">recover_attribution</code></td>
    </tr>
    <tr>
      <td>3 秒时间窗常量</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">BASH_RECOVERY_WINDOW_NS</code>、<code class="language-plaintext highlighter-rouge">SESSION_EVENT_RECOVERY_WINDOW_NS</code></td>
    </tr>
    <tr>
      <td>粗粒度时间戳常量（与上面的窗口不是一回事）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">BASH_RECOVERY_COARSE_TIMESTAMP_NS</code></td>
    </tr>
    <tr>
      <td>bash 候选分级与打分</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">BashCandidateTier</code>、<code class="language-plaintext highlighter-rouge">BashCandidateTier::score</code></td>
    </tr>
    <tr>
      <td>session 事件路径要求仓库地址完全相等</td>
      <td><code class="language-plaintext highlighter-rouge">docs/session-event-attribution-recovery-plan.md</code> 的 “Solver: Session Event Mtime Recovery” 一节</td>
    </tr>
    <tr>
      <td>fail-closed（宁可留空不编造）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">recover_attribution</code>（fail-closed 注释）</td>
    </tr>
    <tr>
      <td>commit 元数据 marker 匹配</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">detect_commit_metadata_agents</code>、<code class="language-plaintext highlighter-rouge">detect_agent_from_identity</code>、<code class="language-plaintext highlighter-rouge">contains_identity_marker</code></td>
    </tr>
    <tr>
      <td>兜底归给人的门槛</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/attribution_recovery.rs</code> 的 <code class="language-plaintext highlighter-rouge">should_recover_remaining_as_known_human</code></td>
    </tr>
    <tr>
      <td>后台 agent 环境探测</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/background_agent.rs</code> 的 <code class="language-plaintext highlighter-rouge">detect</code></td>
    </tr>
    <tr>
      <td>无 hook 时把整块 commit 归给它</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/background_agent.rs</code> 的 <code class="language-plaintext highlighter-rouge">fill_unattributed_lines</code></td>
    </tr>
    <tr>
      <td>agent 账号邮箱 / 用户名映射</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/agent_detection.rs</code> 的 <code class="language-plaintext highlighter-rouge">AGENT_EMAIL_MAPPINGS</code>、<code class="language-plaintext highlighter-rouge">AGENT_USERNAME_MAPPINGS</code>、<code class="language-plaintext highlighter-rouge">match_email_to_agent</code></td>
    </tr>
    <tr>
      <td>整 commit 归属的模拟</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/agent_detection.rs</code> 的 <code class="language-plaintext highlighter-rouge">simulate_agent_authorship</code></td>
    </tr>
    <tr>
      <td>KnownHuman 1 秒排斥</td>
      <td><code class="language-plaintext highlighter-rouge">src/daemon/checkpoint.rs</code> 的 <code class="language-plaintext highlighter-rouge">KNOWN_HUMAN_MIN_SECS_AFTER_AI</code>、<code class="language-plaintext highlighter-rouge">execute_resolved_checkpoint</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">human</code> 哨兵在写 note 时被剔除</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/virtual_attribution.rs</code> 的 <code class="language-plaintext highlighter-rouge">build_attestations_from_attributions</code></td>
    </tr>
    <tr>
      <td>统计里的三个归属计数（含 unknown）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/stats.rs</code> 的 <code class="language-plaintext highlighter-rouge">CommitStats</code>、<code class="language-plaintext highlighter-rouge">stats_from_authorship_log</code></td>
    </tr>
    <tr>
      <td>终端进度条的三段显示</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/stats.rs</code> 的 <code class="language-plaintext highlighter-rouge">write_stats_to_terminal</code></td>
    </tr>
    <tr>
      <td>Git Notes 命名空间与推送 refspec</td>
      <td><code class="language-plaintext highlighter-rouge">src/git/refs.rs</code> 的 <code class="language-plaintext highlighter-rouge">AI_AUTHORSHIP_FULL_REF</code>、<code class="language-plaintext highlighter-rouge">AI_AUTHORSHIP_FORK_TRACKING_REF</code>、<code class="language-plaintext highlighter-rouge">AI_AUTHORSHIP_PUSH_REFSPEC</code></td>
    </tr>
    <tr>
      <td>用 <code class="language-plaintext highlighter-rouge">git fast-import</code> 写 notes 树</td>
      <td><code class="language-plaintext highlighter-rouge">src/git/refs.rs</code> 的 <code class="language-plaintext highlighter-rouge">notes_add_batch</code>、<code class="language-plaintext highlighter-rouge">write_note_path</code></td>
    </tr>
    <tr>
      <td>推送前的 fetch-merge 流程</td>
      <td><code class="language-plaintext highlighter-rouge">src/git/sync_authorship.rs</code> 的 <code class="language-plaintext highlighter-rouge">push_authorship_notes</code>、<code class="language-plaintext highlighter-rouge">fetch_and_merge_tracking_notes</code></td>
    </tr>
    <tr>
      <td>推送命令的构造</td>
      <td><code class="language-plaintext highlighter-rouge">src/git/sync_authorship.rs</code> 的 <code class="language-plaintext highlighter-rouge">build_authorship_push_args</code></td>
    </tr>
    <tr>
      <td>两种 notes 后端的选择规则</td>
      <td><code class="language-plaintext highlighter-rouge">src/config.rs</code> 的 <code class="language-plaintext highlighter-rouge">NotesBackendKind</code>、<code class="language-plaintext highlighter-rouge">build_config</code></td>
    </tr>
    <tr>
      <td>HTTP 后端的上传 / 拉取协议</td>
      <td><code class="language-plaintext highlighter-rouge">src/api/notes.rs</code> 的 <code class="language-plaintext highlighter-rouge">upload_notes</code>、<code class="language-plaintext highlighter-rouge">read_notes</code></td>
    </tr>
    <tr>
      <td>工作区账本的磁盘布局</td>
      <td><code class="language-plaintext highlighter-rouge">src/git/repo_storage.rs</code> 的 <code class="language-plaintext highlighter-rouge">RepoStorage</code>、<code class="language-plaintext highlighter-rouge">PersistedWorkingLog</code></td>
    </tr>
    <tr>
      <td>账本按基线 SHA 改名</td>
      <td><code class="language-plaintext highlighter-rouge">src/git/repo_storage.rs</code> 的 <code class="language-plaintext highlighter-rouge">RepoStorage::rename_working_log</code></td>
    </tr>
    <tr>
      <td>stash 归属的实际落点</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/rewrite_stash.rs</code> 的 <code class="language-plaintext highlighter-rouge">stashes_v2_dir</code>、<code class="language-plaintext highlighter-rouge">stash_entry_dir</code></td>
    </tr>
    <tr>
      <td>三种归属记录的结构体定义</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/authorship_log.rs</code> 的 <code class="language-plaintext highlighter-rouge">HumanRecord</code>、<code class="language-plaintext highlighter-rouge">PromptRecord</code>、<code class="language-plaintext highlighter-rouge">SessionRecord</code></td>
    </tr>
    <tr>
      <td>note 元数据段的结构定义（没有时间字段）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/authorship_log_serialization.rs</code> 的 <code class="language-plaintext highlighter-rouge">AuthorshipMetadata</code></td>
    </tr>
    <tr>
      <td>旧计数器的构造点（<code class="language-plaintext highlighter-rouge">overriden_lines</code> 恒为 0）</td>
      <td><code class="language-plaintext highlighter-rouge">src/authorship/authorship_log_serialization.rs</code> 里构造 <code class="language-plaintext highlighter-rouge">PromptRecord</code> 的四处</td>
    </tr>
    <tr>
      <td>改写操作的四条不变量</td>
      <td><code class="language-plaintext highlighter-rouge">docs/rewrite-ops-spec.md</code> 的 Invariants (first principles) 一节</td>
    </tr>
    <tr>
      <td>核心 note-shift 九步算法</td>
      <td><code class="language-plaintext highlighter-rouge">docs/rewrite-ops-spec.md</code> 的 Core note-shift algorithm 一节</td>
    </tr>
    <tr>
      <td>行级算法的固有局限</td>
      <td><code class="language-plaintext highlighter-rouge">docs/rewrite-ops-spec.md</code> 的 Core note-shift algorithm 一节（Known, intentional limitation 段）</td>
    </tr>
    <tr>
      <td>trace2 事件接入 daemon</td>
      <td><code class="language-plaintext highlighter-rouge">src/commands/install_hooks.rs</code> 的 <code class="language-plaintext highlighter-rouge">configure_daemon_trace2</code></td>
    </tr>
    <tr>
      <td>daemon 识别提交事件</td>
      <td><code class="language-plaintext highlighter-rouge">src/daemon/analyzers/history.rs</code> 的 <code class="language-plaintext highlighter-rouge">HistoryAnalyzer::analyze</code></td>
    </tr>
    <tr>
      <td>daemon 跟踪 reflog</td>
      <td><code class="language-plaintext highlighter-rouge">src/daemon/ref_cursor.rs</code> 的 <code class="language-plaintext highlighter-rouge">RefCursor</code></td>
    </tr>
    <tr>
      <td>core hooks 已下线</td>
      <td><code class="language-plaintext highlighter-rouge">src/commands/git_hook_handlers.rs</code> 的文件头注释、<code class="language-plaintext highlighter-rouge">src/main.rs</code> 的 <code class="language-plaintext highlighter-rouge">main</code> 里 <code class="language-plaintext highlighter-rouge">is_git_hook_binary_name</code> 那段</td>
    </tr>
    <tr>
      <td>GitHub CI 工作流模板</td>
      <td><code class="language-plaintext highlighter-rouge">src/ci/workflow_templates/github.yaml</code> 的 <code class="language-plaintext highlighter-rouge">git-ai</code> job</td>
    </tr>
    <tr>
      <td>GitHub CI 的克隆鉴权</td>
      <td><code class="language-plaintext highlighter-rouge">src/ci/github.rs</code> 的 <code class="language-plaintext highlighter-rouge">get_github_ci_context</code></td>
    </tr>
    <tr>
      <td>GitLab CI 的实现</td>
      <td><code class="language-plaintext highlighter-rouge">src/ci/gitlab.rs</code></td>
    </tr>
    <tr>
      <td>fork PR 的 note 处理</td>
      <td><code class="language-plaintext highlighter-rouge">src/ci/ci_context.rs</code> 的 <code class="language-plaintext highlighter-rouge">import_fork_notes_for_commits</code>、<code class="language-plaintext highlighter-rouge">src/git/refs.rs</code> 的 <code class="language-plaintext highlighter-rouge">copy_missing_notes_for_commits_from_ref</code></td>
    </tr>
    <tr>
      <td>智能体扩展的安装路径与安装器接口</td>
      <td><code class="language-plaintext highlighter-rouge">src/mdm/agents/claude_code.rs</code> 的 <code class="language-plaintext highlighter-rouge">ClaudeCodeInstaller::settings_path</code>、<code class="language-plaintext highlighter-rouge">src/mdm/hook_installer.rs</code> 的 <code class="language-plaintext highlighter-rouge">HookInstaller</code></td>
    </tr>
    <tr>
      <td>官方安装脚本的安装目录</td>
      <td><code class="language-plaintext highlighter-rouge">install.sh</code> 里设 <code class="language-plaintext highlighter-rouge">INSTALL_DIR</code> 那几行</td>
    </tr>
    <tr>
      <td>notes 模式迁移命令</td>
      <td><code class="language-plaintext highlighter-rouge">src/commands/notes_migrate.rs</code></td>
    </tr>
    <tr>
      <td>隐私边界说明</td>
      <td><code class="language-plaintext highlighter-rouge">data-privacy.md</code></td>
    </tr>
    <tr>
      <td>开放标准全文</td>
      <td><code class="language-plaintext highlighter-rouge">specs/git_ai_standard_v3.0.0.md</code></td>
    </tr>
  </tbody>
</table>

<hr />

<p><em>如果这篇文章对你有用，欢迎在 <a href="https://github.com/maijun-sec/maijun-sec.github.io">GitHub</a> 上提 issue 讨论。</em></p>]]></content><author><name>maijun</name></author><category term="AI Agent" /><category term="代码归属" /><category term="Git Notes" /><category term="智能体工程" /><summary type="html"><![CDATA[摘要：开源项目 git-ai 能回答「这段代码是 AI 写的还是人写的」。但它的答案分两层，而且这两层和 README 讲的不太一样：证据层靠智能体主动上报，把改动整块归集到具体的归属键上；恢复层确实用了启发式，靠时间窗和提交元数据补洞。本文基于 v1.7.7 的源码逐层拆开——上报什么、证据不足时怎么猜、猜到什么程度为止、什么时候干脆放弃、归属数据以什么格式存进 Git Notes、历史被改写时它靠什么活下来。 口径先交代一句，免得读错方向：证据层的「行级」指的是归属键精确到行号区间，不是逐行判定——整块 hunk 都会归给 AI，所以它给出的 AI 占比是偏高口径；恢复层的启发式同样只往上加。会把占比压低的是「未跟踪」——没装扩展、没配合上报的行压根不在分母里。文末附源码位置索引，正文里引用的源码位置都在里面，可以逐条回查。]]></summary></entry><entry><title type="html">中间表示的「特性丢失」审计：先量清楚，再谈优化</title><link href="https://maijun-sec.github.io/2026/11/30/ir-feature-loss-audit/" rel="alternate" type="text/html" title="中间表示的「特性丢失」审计：先量清楚，再谈优化" /><published>2026-11-30T11:00:00+08:00</published><updated>2026-11-30T11:00:00+08:00</updated><id>https://maijun-sec.github.io/2026/11/30/ir-feature-loss-audit</id><content type="html" xml:base="https://maijun-sec.github.io/2026/11/30/ir-feature-loss-audit/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：把源码翻译成自己的中间表示时，总会丢掉一些东西。真正危险的不是「丢了」，而是<strong>丢了却不知道</strong>——规则匹配不到某个形状时，你会以为是规则写得不对，而实际上是 IR 根本没表达那个形状。本文给出一套可执行的审计方法：<strong>特性清单 → 探针 → 数字</strong>。</p>
</blockquote>

<!--more-->

<h2 id="ir-选型是取舍这没争议">IR 选型是取舍，这没争议</h2>

<p>静态分析引擎几乎都要做一道选择题：用什么中间表示。</p>

<table>
  <thead>
    <tr>
      <th>表示</th>
      <th>擅长</th>
      <th>短板</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>AST</td>
      <td>语法结构、上下文绑定</td>
      <td>控制流不显式，路径信息要另外提取</td>
    </tr>
    <tr>
      <td>三地址码（TAC）</td>
      <td>统一多语言、便于做数据流</td>
      <td>类型与求值上下文大量丢失</td>
    </tr>
    <tr>
      <td>CFG</td>
      <td>控制流显式、可做数据流</td>
      <td>表达式语义需要额外承载</td>
    </tr>
    <tr>
      <td>SSA</td>
      <td>变量定义唯一、便于传播</td>
      <td>需要 φ 函数与支配关系构造</td>
    </tr>
    <tr>
      <td>依赖图（PDG/CDG）</td>
      <td>显式表达数据/控制依赖</td>
      <td>构造代价高，语义信息薄</td>
    </tr>
  </tbody>
</table>

<p>选哪个都可以。<strong>没有普适最优解，只有针对目标规则的取舍</strong>——这部分没什么好争的。</p>

<p>有争议的是另一件事：<strong>你怎么知道你的 IR 丢了什么？</strong></p>

<h2 id="真正的风险不可见的丢失">真正的风险：不可见的丢失</h2>

<p>下面两种引擎，代码质量可能一模一样，但能力差距巨大：</p>

<ul>
  <li><strong>引擎 A</strong>：IR 能表达「这个值来自某个对象的某个方法」，规则也覆盖了这个形状。</li>
  <li><strong>引擎 B</strong>：IR 里方法调用的接收者类型一律记成「未知」，规则覆盖了这个形状但<strong>永远匹配不上</strong>。</li>
</ul>

<p>引擎 B 的现象非常熟悉：</p>

<blockquote>
  <p>规则写得挺好，语料里就是一条都不报。</p>
</blockquote>

<p>这时候人的第一反应通常是「规则写得不够细 / 模式不够准」，于是去调规则、调模式、调阈值。<strong>但真正的原因是 IR 层面根本没有那个信息</strong>，规则匹配得再准也没用。</p>

<p>更麻烦的是，丢失往往是<strong>部分丢失</strong>：</p>

<ul>
  <li>表达式结构保留了，但<strong>接收者类型</strong>丢了；</li>
  <li>控制流保留了，但<strong>循环次数/上界</strong>丢了；</li>
  <li>赋值关系保留了，但<strong>求值顺序</strong>丢了；</li>
  <li>语法树保留了，但<strong>作用域绑定</strong>丢了。</li>
</ul>

<p>部分丢失是最难查的，因为它看起来「基本能用」，只是某些形状对不上。</p>

<h2 id="丢失的三种形态">丢失的三种形态</h2>

<p>审计时把丢失归成三类，因为三类的修法完全不同：</p>

<h3 id="形态一结构性丢失">形态一：结构性丢失</h3>

<p>语法结构本身没了。</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 源码</span>
<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="n">arr</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">user_input</span><span class="p">;</span> <span class="p">}</span>
</code></pre></div></div>

<p>如果 IR 只保留「一条 <code class="language-plaintext highlighter-rouge">arr[i] = user_input</code> 的赋值」，那「循环下标 <code class="language-plaintext highlighter-rouge">i</code> 与数组下标同源」这个事实就消失了——而这恰恰是<strong>缓冲区越界类规则</strong>需要的信息。</p>

<p><strong>判据</strong>：规则想匹配的是「结构」（循环、switch、try-catch），IR 里根本没有对应节点。
<strong>修法</strong>：改 IR（补充节点），成本最高。</p>

<h3 id="形态二语义性丢失">形态二：语义性丢失</h3>

<p>结构还在，但语义信息被抹平了。</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 源码</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">x</span> <span class="o">=</span> <span class="n">cond</span> <span class="o">?</span> <span class="n">sanitize</span><span class="p">(</span><span class="n">user</span><span class="p">)</span> <span class="o">:</span> <span class="n">user</span><span class="p">;</span>
</code></pre></div></div>

<p>「把条件表达式降级成两个分支再合流」这类改写，会把「这个分支上值是消毒过的」这个事实降级成「两个分支的合流」。合流之后，消毒语义就没了。</p>

<p><strong>判据</strong>：规则想匹配的是「语义状态」（是否消毒过、值域、符号性），IR 里这个维度是空的或者被统一掉了。
<strong>修法</strong>：给 IR 加维度（给值附加标签/摘要），成本中等。</p>

<h3 id="形态三上下文性丢失">形态三：上下文性丢失</h3>

<p>表达式和结构都在，但「它处在什么上下文里」没了。</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 源码</span>
<span class="n">obj</span><span class="p">.</span><span class="n">method</span><span class="p">(</span><span class="n">user</span><span class="p">);</span>
</code></pre></div></div>

<p>「<code class="language-plaintext highlighter-rouge">obj</code> 是什么类型」没了，于是所有 <code class="language-plaintext highlighter-rouge">method</code> 调用长得都一样。</p>

<p><strong>判据</strong>：规则想匹配的是「上下文」（接收者类型、所属类、命名空间）。
<strong>修法</strong>：在 IR 里补上下文（类型推断、接收者标注），成本视语言而定。</p>

<blockquote>
  <p>这三类的<strong>影响面</strong>不一样，所以<strong>先分清是哪一类</strong>，再决定要不要修。
形态一要改 IR 的<strong>结构</strong>：IR 里要新增节点种类，所有规则的匹配路径都得跟着重新过一遍。
形态三通常只是给<strong>已有的节点补属性</strong>：不新增节点种类，只有需要这个属性的规则会受影响，其它规则的匹配路径不变。
一个看起来「规则不准」的现象，根因可能是形态三——而形态三不动 IR 结构，所以先查它。</p>
</blockquote>

<h2 id="审计方法特性清单--探针--数字">审计方法：特性清单 → 探针 → 数字</h2>

<h3 id="第一步列特性清单">第一步：列特性清单</h3>

<p>把<strong>源语言里存在、且你的规则可能关心的</strong>语义特性列出来。清单来源有三个：</p>

<ul>
  <li>你的规则集合：每条规则需要哪些信息才能成立？</li>
  <li>语言的语义规范：哪些语义是语言定义的、不可丢失的？</li>
  <li>历史误报/漏报：每一次「规则不生效」的现场。</li>
</ul>

<p>把清单做成表格，每行一个特性：</p>

<table>
  <thead>
    <tr>
      <th>特性</th>
      <th>类别</th>
      <th>需要它的规则数</th>
      <th>相关规则</th>
      <th>IR 中是否保留</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>循环下标与数组下标同源</td>
      <td>结构性</td>
      <td>？</td>
      <td>越界类</td>
      <td>？</td>
    </tr>
    <tr>
      <td>值是否经过消毒</td>
      <td>语义性</td>
      <td>？</td>
      <td>污点类</td>
      <td>？</td>
    </tr>
    <tr>
      <td>方法调用的接收者类型</td>
      <td>上下文性</td>
      <td>？</td>
      <td>大量规则</td>
      <td>？</td>
    </tr>
    <tr>
      <td>赋值与使用的求值顺序</td>
      <td>语义性</td>
      <td>？</td>
      <td>并发/时序类</td>
      <td>？</td>
    </tr>
  </tbody>
</table>

<p>「需要它的规则数」这一列不用精确，点得清是哪几条规则就行。它只用来判断<strong>这一行值不值得往下做</strong>，不参与任何精度结论——怎么用，见下一小节。</p>

<h3 id="这一步的边界哪些特性可以直接划掉">这一步的边界：哪些特性可以直接划掉</h3>

<p>清单不是越长越好。下面两类行，应该在列清单的时候就当场划掉：</p>

<ul>
  <li><strong>IR 的设计目标本就不表达该特性。</strong> 有些中间表示是刻意做薄的——它要的是一份能统一多语言的数据流骨架，而不是完整的语言语义。这类特性不用写探针，也不用进探针文件集。</li>
  <li><strong>没有任何规则需要它。</strong> 每一行都要能回答「哪条规则需要它」。一行都答不上来，说明它对当前规则集没有价值，同样划掉。</li>
</ul>

<p>所以这一步的产出不是「一张尽量全的表」，而是「<strong>一张每一行都有人要的表</strong>」。行数越少越好——因为每一行都要配探针、跑语料、数位置。</p>

<h3 id="第二步为每条特性写探针">第二步：为每条特性写「探针」</h3>

<p>探针 = <strong>一个最小的、能暴露该特性是否丢失的代码片段 + 期望在 IR 里看到的形态</strong>。</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 探针：方法调用的接收者类型</span>
<span class="n">Foo</span> <span class="n">p1</span> <span class="o">=</span> <span class="n">build</span><span class="p">();</span>        <span class="c1">// build() 返回 Foo</span>
<span class="n">p1</span><span class="p">.</span><span class="n">doThing</span><span class="p">(</span><span class="n">user</span><span class="p">);</span>       <span class="c1">// 期望：IR 中该调用的接收者类型为 Foo</span>
</code></pre></div></div>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 探针：循环下标与数组下标同源</span>
<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">arr</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">user</span><span class="p">;</span>       <span class="c1">// 期望：IR 中 arr 的下标与 i 同源</span>
<span class="p">}</span>
</code></pre></div></div>

<p>探针的关键要求：</p>

<ol>
  <li><strong>最小</strong>——只包含被测特性，不掺杂其它语义。否则你分不清是哪个特性丢了。</li>
  <li><strong>可判定</strong>——你知道期望的 IR 形态长什么样，能明确回答「保留 / 丢失」。</li>
  <li><strong>可批量</strong>——同一语言里能收集到多个实例，才能看出「是个案还是通例」。</li>
</ol>

<h3 id="第三步把探针放进语料先量数字">第三步：把探针放进语料，<strong>先量数字</strong></h3>

<p>这一步是整件事里最容易被跳过、也最不该跳过的一步：</p>

<blockquote>
  <p><strong>在讨论「某个特性丢了多少处」之前，先把这个特性在语料里有几处记录下来。</strong>
否则你会拿着「这个形状我没找到」去报告结论，而它在语料里可能压根就没出现过——那不是丢失，是语料里没有这个形状。</p>
</blockquote>

<p>把探针批量扔进语料，统计：</p>

<table>
  <thead>
    <tr>
      <th>特性</th>
      <th>语料中该形状出现次数</th>
      <th>IR 中保留的比例</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>循环下标与数组下标同源</td>
      <td>37</td>
      <td>0%</td>
    </tr>
    <tr>
      <td>方法调用的接收者类型</td>
      <td>812</td>
      <td>12%</td>
    </tr>
  </tbody>
</table>

<p>有了这张表，结论才成立：</p>

<ul>
  <li>「循环下标与数组下标同源 0% 保留」→ <strong>形态一丢失</strong>，需要改 IR 的结构。</li>
  <li>「方法调用的接收者类型 12% 保留」→ <strong>形态三丢失</strong>，但只有 12% 保留 —— 说明大部分时候<strong>拿不到</strong>，剩下 88% 是类型推断没覆盖到的情况，改动范围明确。</li>
</ul>

<blockquote>
  <p>12% 保留不等于「12% 的规则会漏」。这个比例只描述 <strong>IR 的表达能力</strong>，还没有对照规则的需求看：只有那些<strong>需要</strong>接收者类型的规则才受它影响，而需要它的规则到底占多少，得回到特性清单里那一列去查。</p>
</blockquote>

<p>反过来，如果你没量过「语料里有几处」，你会得到「循环下标与数组下标同源好像丢了」这种无法证伪的说法，然后基于它做决策。</p>

<h3 id="一次探针评测长什么样">一次探针评测长什么样</h3>

<p>「探针 → 数字」这一步最容易各做各的：同一批探针，不同人报出来的比例可以差很远。差别通常不在测量，而在<strong>没人说清楚这个百分比是怎么定义的</strong>。下面把一次评测的输入、输出、判定标准都写出来。</p>

<p><strong>输入</strong></p>

<table>
  <thead>
    <tr>
      <th>输入项</th>
      <th>说明</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>探针文件集</td>
      <td>每个特性一组最小代码片段。一组可以包含多个变体（不同的接收者类型、不同的分支形态），变体是用来区分「整体保留」和「部分保留」的</td>
    </tr>
    <tr>
      <td>语料版本</td>
      <td>明确到一次提交或一个发布号。语料里该形状出现几次是分母，语料一换分母就变，两次评测的数字不能直接比</td>
    </tr>
    <tr>
      <td>判定规则</td>
      <td>每个特性写一句「保留 / 丢失」怎么判。判据最好是能在 IR dump 上直接看出来的形态，而不是「感觉丢了」</td>
    </tr>
  </tbody>
</table>

<p><strong>输出表的每一列</strong></p>

<table>
  <thead>
    <tr>
      <th>列</th>
      <th>定义</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>特性</td>
      <td>与特性清单里的行一一对应，不另起名字</td>
    </tr>
    <tr>
      <td>语料中该形状出现次数</td>
      <td>语料里满足该特性的位置总数，是分母</td>
    </tr>
    <tr>
      <td>IR 中保留的处数</td>
      <td>上述位置中，IR 里还能看出该特性的数量，是分子</td>
    </tr>
    <tr>
      <td>保留比例</td>
      <td>分子 ÷ 分母，取整</td>
    </tr>
  </tbody>
</table>

<p><strong>判定标准</strong></p>

<ol>
  <li><strong>二元优先。</strong> 一个位置只有「保留 / 丢失」两种结论。判成「部分保留」等于没判——要么把形态拆细到可判定，要么承认这一形态当前判不了。</li>
  <li><strong>判定要能指到位置。</strong> 每一条判定都指向 IR dump 里的一个具体位置，别人才能复核，而不是只能相信你的计数。</li>
  <li><strong>判据本身也要校准。</strong> 先找一个你确定 IR 表达不了的例子，确认判定规则会把它判成「丢失」；再找一个你确定表达了的，确认它被判成「保留」。判据错了，后面所有比例都是错的。</li>
  <li><strong>先数分母，再数分子。</strong> 先把「语料里有几处」数出来，再数「其中保留了几处」。反过来做，得到的比例没有意义。</li>
</ol>

<blockquote>
  <p>上面那张表里的数字是<strong>示例读数</strong>；换成你自己的语料，列的含义不变，数字要重数。</p>
</blockquote>

<p>这个动作的重量比听上去轻：探针是人工放进语料的，判定是看 IR dump 的，计数是逐个数位置的。真正费事的是<strong>把判定规则写到第二个人也能照着判的程度</strong>——这一步偷懒，评测结果就只能自己看，说不出「可复现」这三个字。</p>

<h2 id="应用零读数的分诊顺序">应用：零读数的分诊顺序</h2>

<p>「规则在某个语言上一条都不报」是个非常有迷惑性的读数。它至少有三种完全不同的成因：</p>

<table>
  <thead>
    <tr>
      <th>成因</th>
      <th>含义</th>
      <th>证据</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>规则没注册</td>
      <td>该语言的规则条目压根不在配置里</td>
      <td>在配置里查该语言的条目 → 没有</td>
    </tr>
    <tr>
      <td>源认不出</td>
      <td>IR 里那个形状压根没生成</td>
      <td>探针：IR dump 里找该形状 → 没有</td>
    </tr>
    <tr>
      <td>传播不到</td>
      <td>源认出来了，但污点没流到 sink</td>
      <td>探针：源处有标签，sink 处没有</td>
    </tr>
  </tbody>
</table>

<p><strong>顺序不能倒。</strong> 倒过来会把「配置缺口」当成「算法缺口」，然后花几天去优化一个根本没注册的规则。</p>

<p>分诊的最短路径：</p>

<pre><code class="language-mermaid">graph TB;
    Z["读数 = 0"] --&gt; D{"规则在该语言上&lt;br/&gt;注册过吗"}
    D --&gt;|"配置里没有该语言的条目"| F1["配置缺口&lt;br/&gt;补配置条目"]
    D --&gt;|"有"| S{"源能认出来吗"}
    S --&gt;|"IR dump 里没有该形状"| F2["IR 特性丢失&lt;br/&gt;写探针、做审计"]
    S --&gt;|"有"| P{"污点传到 sink 了吗"}
    P --&gt;|"没有"| F3["传播问题&lt;br/&gt;查 join / kill 语义"]
    P --&gt;|"到了"| F4["sink 模式太窄&lt;br/&gt;放宽模式"]
</code></pre>

<blockquote>
  <p>这张表只管<strong>漏报</strong>方向（读数为 0）。误报方向是另一个问题：要查的是「这条 finding 的污点从哪来的」——污点是不是一开始就贴错了、还是传播过程中被扩散到了不该到的地方、还是 sink 的匹配模式太宽。这条链的入口和出口都跟上面三步不同，<strong>不要硬套同一张表</strong>。</p>
</blockquote>

<h2 id="纪律清单">纪律清单</h2>

<ol>
  <li><strong>IR 的取舍可以讨论，IR 的丢失不能靠感觉。</strong> 特性丢失必须可度量。</li>
  <li><strong>特性清单先于探针，探针先于结论。</strong> 跳过任何一步，结论都不可证伪。</li>
  <li><strong>先量「语料里有几处」，再量「IR 保留了几处」。</strong> 第一个数字是第二个数字的分母。</li>
  <li><strong>区分丢失的三种形态</strong>——形态三（上下文）不动 IR 的结构，先查它。</li>
  <li><strong>零读数先查注册，再查源，再查传播。</strong> 顺序倒过来会把配置缺口当算法缺口。</li>
  <li><strong>探针要能批量。</strong> 个案说明不了通例。</li>
</ol>

<h2 id="小结">小结</h2>

<p>选 IR 是审美与目标的权衡，<strong>审计 IR 的丢失是工程纪律</strong>。两者的区别在于：前者可以讨论「我觉得哪个更好」，后者必须有数字。</p>

<p>一个可复用的自检问题是：</p>

<blockquote>
  <p><strong>「我现在说某个特性丢了 X%」——这个 X 是量出来的，还是估出来的？</strong></p>
</blockquote>

<p>如果答不上来，那这条结论就还不该写进设计文档。</p>

<hr />

<p><em>如果这篇文章对你有用，欢迎在 <a href="https://github.com/maijun-sec/maijun-sec.github.io">GitHub</a> 上提 issue 讨论。</em></p>]]></content><author><name>maijun</name></author><category term="程序分析" /><category term="程序表示" /><category term="引擎工程" /><category term="方法论" /><summary type="html"><![CDATA[摘要：把源码翻译成自己的中间表示时，总会丢掉一些东西。真正危险的不是「丢了」，而是丢了却不知道——规则匹配不到某个形状时，你会以为是规则写得不对，而实际上是 IR 根本没表达那个形状。本文给出一套可执行的审计方法：特性清单 → 探针 → 数字。]]></summary></entry><entry><title type="html">误报治理：先普查总体，再归因</title><link href="https://maijun-sec.github.io/2026/11/30/false-positive-triage/" rel="alternate" type="text/html" title="误报治理：先普查总体，再归因" /><published>2026-11-30T10:00:00+08:00</published><updated>2026-11-30T10:00:00+08:00</updated><id>https://maijun-sec.github.io/2026/11/30/false-positive-triage</id><content type="html" xml:base="https://maijun-sec.github.io/2026/11/30/false-positive-triage/"><![CDATA[<blockquote>
  <p><strong>摘要</strong>：修误报时，直觉靠不住：盯着第一条误报看并修掉它，成本最低但收益可能最低。本文给出一条可复用的路径——<strong>先普查总体、按形状分类计数、再从最大的一类下手</strong>，并重点讲一个反直觉的坑：<strong>用来做归因的脚本本身也是量具，它也可能是坏的，而且坏得比分析器还隐蔽。</strong></p>
</blockquote>

<!--more-->

<h2 id="先划边界多大的问题才值得普查">先划边界：多大的问题才值得普查</h2>

<p>这套方法解决的是<strong>「多到看不完」</strong>的问题，不是所有误报都值得走一遍流程。</p>

<ul>
  <li><strong>就几条</strong>：直接看。逐条读代码、改一处、跑一遍，这个循环本身最快。给三条误报搭一套归因脚本，是拿工程量换了一张根本用不上的地图。</li>
  <li><strong>一轮看不完</strong>：值得普查。判据不是误报的具体条数，而是<strong>你要花多久才能把它们逐条过完</strong>。过一遍要不了半小时的，直接过；过不完、要按小时甚至按天算的，就该先分类。</li>
  <li><strong>规模不大，但同一类问题反复出现</strong>：也值得普查。一次性投入换来的分类表可以复用，下一轮不用从零开始。</li>
</ul>

<p><strong>从今天下午开始，最小的一步只有一件事</strong>：把当前的误报清单导出成一个纯文本文件，每条后面补上<strong>关键代码片段</strong>——先不要动任何分析代码。</p>

<p>这一步不需要脚本，也不需要做任何判断，只需要复制粘贴。做完它，后面分类的原料就齐了；不做它，后面所有的计数都没有依据。文末的「最小可行版本」给了一张可以直接照着填的表。</p>

<h2 id="症状">症状</h2>

<p>某条规则报了一大批误报。为了把方法讲清楚，下面用一个<strong>假设的例子</strong>贯穿全文：假设有 <strong>108 条误报</strong>，分散在若干种形状上，而真实缺陷只有零星几条。</p>

<blockquote>
  <p>这组数字是<strong>示意数据</strong>，用来演示每一步怎么做、账怎么算。它不是某次实测的读数——要带走的是方法，不是这些数字。</p>
</blockquote>

<p>摆在面前有两个选择：</p>

<ul>
  <li><strong>A</strong>：逐条看。每条误报读一遍代码，判断为什么错，然后改引擎。改完再跑，看数字降了多少。</li>
  <li><strong>B</strong>：先搞清楚这 108 条<strong>分别属于哪几种形态</strong>，再决定改什么。</li>
</ul>

<p>直觉都选 A，因为 A 立刻能开始动手，而且每修一条都有即时的成就感。</p>

<h2 id="为什么直觉不可靠">为什么直觉不可靠</h2>

<p>A 的问题不在于「慢」，而在于<strong>它把一个统计问题当成了一串独立问题</strong>。</p>

<p>具体地说：</p>

<ol>
  <li><strong>你会先修最容易修的，而不是最该修的。</strong> 第一条误报往往就在手边，修它的心理成本最低。但它在总体里可能只占 1%，改完数字从 108 变成 107，收益接近于零。</li>
  <li><strong>你不知道自己漏了什么。</strong> 修完 20 条，数字降到 88，剩下 88 条是什么形状？不知道。于是下一轮又从最容易的开始，循环往复。</li>
  <li><strong>改动会互相干扰，你归因不了。</strong> 修 A 类误报的改动可能顺手影响了 B 类，导致 B 类误报变成了另一种误报（而不是消失）。没有分类计数，你连「这次改动到底净减少了多少」都算不出来。</li>
  <li><strong>你还可能被错误的直觉带偏。</strong> 「这个 sink 看起来就不该报」——但真正的问题可能在 source 识别上，在传播上，或者在规则的适用条件上。你盯着报错点改，改的是错的地方。</li>
</ol>

<p>A 不是不能做，而是<strong>在你知道该修什么之前做它，代价是浪费</strong>。B 的产出是一张地图，A 是沿着地图走。</p>

<h2 id="先普查把误报按形状分类">先普查：把误报按「形状」分类</h2>

<p>普查要回答的问题是：<strong>这批误报在结构上分成哪几类，每类多少条。</strong></p>

<p>「形状」指的是<strong>产生这条误报的结构性原因</strong>，不是表面现象。比如：</p>

<table>
  <thead>
    <tr>
      <th>形状</th>
      <th>结构性原因</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>消毒后仍报</td>
      <td>消毒函数没有被识别为「消除污点」的转换</td>
    </tr>
    <tr>
      <td>跨函数参数传播丢失</td>
      <td>被调方对形参的处理没有回传给调用方</td>
    </tr>
    <tr>
      <td>分支合流误判</td>
      <td>合流点取并集，分支上的消毒语义被整体抹掉</td>
    </tr>
    <tr>
      <td>同一表达式被重复计入</td>
      <td>一个源在一条路径上被计了多次</td>
    </tr>
  </tbody>
</table>

<p>分类怎么定？<strong>不要预先定。</strong> 先把每条误报的<strong>关键代码片段</strong>记录下来，再回头看它们彼此之间「哪里不一样」——差异点就是候选的分类维度。</p>

<p>普查的产出应该是一张表：</p>

<table>
  <thead>
    <tr>
      <th>形状</th>
      <th>条数</th>
      <th>占比</th>
      <th>是否可修</th>
      <th>修复的预期净收益</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>71</td>
      <td>66%</td>
      <td>是</td>
      <td>高</td>
    </tr>
    <tr>
      <td>B</td>
      <td>29</td>
      <td>27%</td>
      <td>部分</td>
      <td>中</td>
    </tr>
    <tr>
      <td>C</td>
      <td>6</td>
      <td>5%</td>
      <td>难</td>
      <td>低</td>
    </tr>
    <tr>
      <td>D</td>
      <td>2</td>
      <td>2%</td>
      <td>否</td>
      <td>—</td>
    </tr>
  </tbody>
</table>

<p>（占比取整到整数，合计 100%。）</p>

<p>有了这张表，选择就变成了算术：<strong>先修 A</strong>。</p>

<p>这一步还顺手回答了一个之前没想到的关键问题：<strong>这批误报里有多少是「本来就修不了」的</strong>。如果没有普查，你会一直以为「修完这 108 条就干净了」；普查之后你发现其中 2 条属于设计层面的固有限制，可以直接停止在那上面投入。</p>

<h2 id="陷阱归因脚本自己也是量具">陷阱：归因脚本自己也是量具</h2>

<p>普查到这一步，会自然引入一个脚本：<strong>把扫描产物里的 finding（一条报警条目）和「我人工确认过的误报清单」对上</strong>，从而自动算出每一类的条数。</p>

<p>这个脚本是整个流程里<strong>最关键、也最容易坏</strong>的部件。因为它坏掉的方式非常隐蔽：</p>

<blockquote>
  <p><strong>坏掉的归因脚本不会报错，它只会给你一份看起来很像证据的清单。</strong></p>
</blockquote>

<p>下面三个坑，我全踩过。它们有一个共同点：<strong>出错时，脚本输出的不是异常，而是一份「整齐的、看起来很可信的」分布表</strong>。</p>

<h3 id="坑一键没归一化--已检出被列成漏报">坑一：键没归一化 —— 「已检出」被列成「漏报」</h3>

<p>最常见的一种。脚本一边从扫描产物取文件名，一边从人工清单取文件名，两边用不同的取法：</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># 产物里的 file 字段是完整路径
</span><span class="n">scan_key</span> <span class="o">=</span> <span class="n">finding</span><span class="p">[</span><span class="s">"file"</span><span class="p">]</span>                      <span class="c1"># "/repo/src/app/handler.c"
</span>
<span class="c1"># 人工清单里写的是不含扩展名的短名
</span><span class="n">manual_key</span> <span class="o">=</span> <span class="n">row</span><span class="p">[</span><span class="s">"name"</span><span class="p">]</span>                       <span class="c1"># "handler"
</span>
<span class="c1"># 直接比
</span><span class="k">if</span> <span class="n">scan_key</span> <span class="o">==</span> <span class="n">manual_key</span><span class="p">:</span> <span class="p">...</span>                 <span class="c1"># 永远不相等
</span></code></pre></div></div>

<p>结果：<strong>每一个文件都被列成「漏报」</strong>，包括那些明明扫描出来了的。</p>

<p>更隐蔽的变体：归一化只做了一半——去掉了扩展名、去了目录，但<strong>大小写、全角与半角、非字母数字字符</strong>没统一；或者一边去扩展名、另一边不去。</p>

<blockquote>
  <p><strong>纪律：归一化必须发生在「取键」的那一步，不是「比对」的那一步。</strong>
两边都调用同一个归一化函数，函数只有一个入口。</p>

  <p><strong>而且：脚本写完必须先自检。</strong> 拿一个<strong>你已经确认检出过</strong>的文件去跑它——脚本必须把它列成「命中」。如果它列成「漏报」，脚本本身就是坏的，后面所有归因结论全部作废。</p>
</blockquote>

<h3 id="坑二键空间用错--查不到--不存在">坑二：键空间用错 —— 查不到 ≠ 不存在</h3>

<p>另一个方向的坑。你想查「这个节点属于哪个文件」，于是用了一个你手熟的方法去查。但那个 id 来自<strong>另一套索引的键空间</strong>，不是你这边的。</p>

<p>典型的样子：两个索引系统对同一个函数的 id 采用了不同编码——一套用「所属作用域 + 签名」做键，另一套只用签名做键。你拿前者去查后者的键，<strong>静默返回空</strong>。而空值极易被读成「这条边不存在」或者「它们在同一个文件里」。</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code># 判定式：查到的值 != null &amp;&amp; !查到的值.equals(期望值)
# 查到的值恒为 null ⇒ 整个判定恒为假 ⇒ 所有记录都被判成「同一个」
# 读数形状：某一类计数整片为 0   ← 假的
</code></pre></div></div>

<blockquote>
  <p><strong>纪律：拿到一个陌生的 id，先问「它是哪种键空间的键」，再决定用哪个索引查。</strong>
「查不到」不等于「不存在」。打印 id 的形状（在另一个索引里能不能命中），再下结论。</p>

  <p><strong>读数出现整片归零或整片归同类时，先怀疑键空间用错，再怀疑分析器。</strong></p>
</blockquote>

<h3 id="坑三键太粗--不同的记录被合并了">坑三：键太粗 —— 不同的记录被合并了</h3>

<p>归一化过了头，也会出事。键必须<strong>唯一</strong>区分一条记录。</p>

<p>真实的例子：同一个键里本来带着归属信息（哪个模块、哪个子目录），归一化时把分隔符和非字母数字全去掉——<strong>归属信息被一起丢掉了</strong>。于是：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>"A 组的某个键 有 finding"
   → 被算成 "B 组的同一个键 也有 finding"
</code></pre></div></div>

<p>这类错误不会自己暴露：两边各自的键单看都「挺规整」，只有把两边并排比对，才会发现同一份记录被安到了别的归属上。</p>

<blockquote>
  <p><strong>纪律：产出记录的一方和归因的一方必须共用同一把尺子。</strong>
而且，脚本写完后要打印「有多少条记录在归一化之后重名」——<strong>重名数不为 0，就是键不够用</strong>。</p>
</blockquote>

<h3 id="一个共同的判据">一个共同的判据</h3>

<p>这三个坑其实是同一件事的三个入口：</p>

<blockquote>
  <p><strong>归因链上的每一环都要单独验一遍。</strong>
不要因为「这一步看起来很机械」就跳过验证。</p>
</blockquote>

<p>一份可信的分类分布表，应该能这样自证：</p>

<ul>
  <li>随便挑一个「命中」的样本，脚本能指出它；</li>
  <li>随便挑一个「不命中」的样本，脚本确实不指它；</li>
  <li><strong>把归一化故意改坏一次，分类分布应该明显变化</strong>——如果分布纹丝不动，说明这张表根本没在用键做区分。</li>
</ul>

<p>最后这一条尤其值得做：<strong>故意破坏一次，看你的量具会不会报警</strong>。不会报警的量具，不能用来支撑结论。</p>

<h2 id="修完之后量净收益">修完之后：量「净收益」</h2>

<p>修完不等于赢。<strong>真实发现和误报要一起看</strong>：</p>

\[\text{净收益} = \Delta \text{TP} - \Delta \text{FP}_{\text{新增}}\]

<p>这里先把口径说清楚：$\Delta \text{FP}_{\text{新增}}$ 只算<strong>这次改动新引入的误报</strong>。减少的误报不直接计分——它省下的是分析员逐条确认的时间，和「多找到一个真实缺陷」不是一个量纲，混在一起相减容易算出好看的假数字。</p>

<p>只看 FP 下降会骗人：把规则整个关掉，FP 归零，可真实发现也跟着归零，$\Delta \text{TP} = -61$，净收益直接是负的。</p>

<p>回到前面那个<strong>假设的</strong>例子，改完之后账是这样记的：</p>

<table>
  <thead>
    <tr>
      <th>指标</th>
      <th>改造前</th>
      <th>改造后</th>
      <th>净变化</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>该规则的误报</td>
      <td>108</td>
      <td>0</td>
      <td>−108</td>
    </tr>
    <tr>
      <td>该规则的真实发现</td>
      <td>61</td>
      <td>122</td>
      <td>+61</td>
    </tr>
    <tr>
      <td><strong>净收益</strong></td>
      <td>—</td>
      <td>—</td>
      <td><strong>+61</strong></td>
    </tr>
  </tbody>
</table>

<p>（数字还是示意数字，但算法是真的。）</p>

<h3 id="那个-61-是怎么来的">那个 +61 是怎么来的</h3>

<p><strong>这个 +61 不是「修误报的副产品」。</strong> 如果这次改动只是<strong>把规则的判定条件收紧</strong>——多加一个「必须满足某形状」的前置条件——那误报会掉，真实发现也会跟着掉，两边同时掉，净收益仍然是负的。这种改动数字看着漂亮，实质是<strong>用漏报换误报</strong>。</p>

<p>示意里的 +61 之所以站得住，靠的是另一件事：<strong>误报和漏报同源于同一处判定</strong>。</p>

<p>具体地说：某个中间量的判定在一处写错了，而且是<strong>两头都错</strong>。一头算多了——把不该算进来的事实算进来了，于是报出并不成立的缺陷；另一头算少了——该算进来的事实没算进来，于是该报的缺陷被压了下去。修这一处判定，误报那头的「多算」消失，漏报那头的「少算」也同时消失，于是真实发现跟着上升。</p>

<p>所以这个数字背后必须有一条<strong>因果链</strong>：改动落在「哪一处判定」→ 为什么这处判定同时造成了两头的错 → 因此真实发现为什么跟着涨。缺了这条链，「真实发现 +61」就只是一个好看的数字，不能拿去汇报。</p>

<p>反过来也成立：<strong>如果你的改动只有误报在动、真实发现没动，那净收益就是零</strong>——不管误报降了多少。而如果真实发现上升、误报总数却没降，说明新引入的误报把修掉的抵掉了，这时候净收益得回到上面那个公式上算，不能凭「多找到了」就说赚。</p>

<blockquote>
  <p>注意这里的<strong>顺序</strong>：先普查分类，再动手改，然后一次性量净收益。如果每改一处就量一次，很容易被中间态误导——比如某个中间改动把误报从 108 降到 30，同时把真实发现从 61 打到 20，看起来「误报降了七成」，实际是净亏。</p>
</blockquote>

<h2 id="纪律清单">纪律清单</h2>

<ol>
  <li><strong>先普查，后动手。</strong> 把总体按形状分类、计数、排序，再决定修什么。</li>
  <li><strong>普查之前不动代码。</strong> 否则你会失去「改造前的基线」，净收益就无从计算。</li>
  <li><strong>归因脚本是量具，必须自检。</strong> 至少三关：已知命中样本能命中；已知不命中样本不命中；故意破坏后读数会变。</li>
  <li><strong>两边取键走同一个函数。</strong> 归一化在取键时做，不在比对时做。</li>
  <li><strong>键必须唯一区分记录。</strong> 打完印检查归一化后有没有重名。</li>
  <li><strong>读数异常时先怀疑量具。</strong> 整片归零、整片归同类、跨类别不一致——这三个形状通常意味着键空间或归一化出了问题，而不是分析器出了问题。</li>
  <li><strong>用净收益结账。</strong> 只看误报下降会被「把规则关掉」骗过去。</li>
</ol>

<h2 id="最小可行版本">最小可行版本</h2>

<p>上面整套流程，第一遍不用全做。<strong>三个动作 + 一张表</strong>就能起步。</p>

<p><strong>动作一：导出清单。</strong> 把当前误报导成纯文本，每条一行：规则名、位置、原始消息。</p>

<p><strong>动作二：给每条贴上关键片段。</strong> 把报错位置前后的代码抄进清单。<strong>这一条不能省</strong>——分类靠的是片段之间的差异，不是靠规则名或消息文本。</p>

<p><strong>动作三：回头找差异，不预设分类。</strong> 把片段并排读，标出「这几条长得不一样」的维度，维度就是候选分类。<strong>先别急着起名字</strong>，名字是最后一步的事。</p>

<p><strong>表模板</strong>（空表，照着填）：</p>

<table>
  <thead>
    <tr>
      <th>误报编号</th>
      <th>规则名</th>
      <th>位置</th>
      <th>关键片段</th>
      <th>形状（自己起名）</th>
      <th>该形状下的条数</th>
      <th>能否修</th>
      <th>预期净收益</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
    </tr>
    <tr>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
      <td> </td>
    </tr>
  </tbody>
</table>

<p><strong>每一列该怎么填</strong>：</p>

<table>
  <thead>
    <tr>
      <th>列</th>
      <th>填什么</th>
      <th>常见填错的地方</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>误报编号</td>
      <td>清单里的序号，方便回溯</td>
      <td>拿规则名当编号：一条规则报多次就分不清是哪条</td>
    </tr>
    <tr>
      <td>规则名</td>
      <td>触发的规则标识</td>
      <td>填规则的中文描述——同一规则的不同消息会看起来像两类</td>
    </tr>
    <tr>
      <td>位置</td>
      <td>文件 + 函数名（或任何能唯一定位到一处代码的说明）</td>
      <td>只填文件名：同一文件里多条误报会混在一起</td>
    </tr>
    <tr>
      <td>关键片段</td>
      <td>报错点前后的代码，要能看出这条为什么被判出来</td>
      <td>抄一大段无关代码：差异会被淹没</td>
    </tr>
    <tr>
      <td>形状</td>
      <td>你自己起的分类名</td>
      <td>直接抄规则名——那不是分类，是同一个维度重复计数</td>
    </tr>
    <tr>
      <td>该形状下的条数</td>
      <td>归并之后的条数</td>
      <td>估一个大概：宁可数一遍</td>
    </tr>
    <tr>
      <td>能否修</td>
      <td>是 / 部分 / 否</td>
      <td>全填「是」——不能修的那几条，往往才是决定要不要普查的关键</td>
    </tr>
    <tr>
      <td>预期净收益</td>
      <td>高 / 中 / 低</td>
      <td>用「修起来容易」代替：容易修不等于收益高</td>
    </tr>
  </tbody>
</table>

<p>表填完，「先修哪个」就变成了算术，不用再讨论。<strong>注意「能否修」这一列</strong>：如果最大的一类是「不能修」，普查的结论就是「不用普查」——那也省下了后面的全部投入。</p>

<h2 id="小结">小结</h2>

<p>修误报看起来是个手艺活，其实是<strong>统计 + 分类</strong>的活：先拿到一张分布图，再按图施工。而这张分布图由脚本生成，所以<strong>脚本的质量就是结论的质量</strong>。</p>

<p>最值得记住的一条是：当你发现某个结论「整齐得可疑」——比如「所有文件都漏报了」「某一类计数整片为 0」「跨类别判定互相打架」——第一反应应该是<strong>量具坏了</strong>，而不是<strong>分析器坏了</strong>。</p>

<hr />

<p><em>如果这篇文章对你有用，欢迎在 <a href="https://github.com/maijun-sec/maijun-sec.github.io">GitHub</a> 上提 issue 讨论。</em></p>]]></content><author><name>maijun</name></author><category term="程序分析" /><category term="误报治理" /><category term="精度" /><category term="工程方法" /><summary type="html"><![CDATA[摘要：修误报时，直觉靠不住：盯着第一条误报看并修掉它，成本最低但收益可能最低。本文给出一条可复用的路径——先普查总体、按形状分类计数、再从最大的一类下手，并重点讲一个反直觉的坑：用来做归因的脚本本身也是量具，它也可能是坏的，而且坏得比分析器还隐蔽。]]></summary></entry></feed>