@aibyzero/cm-workflow 0.16.1 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-workflow",
3
- "version": "0.16.1",
3
+ "version": "0.16.2",
4
4
  "description": "Spec-driven product development workflow for Codex: external research, PRD, implementation, read-only feature testing, review, QA, fixes, refactors, and documentation.",
5
5
  "author": {
6
6
  "name": "cm-workflow maintainers",
package/CHANGELOG.md CHANGED
@@ -7,6 +7,47 @@
7
7
 
8
8
  (暂无)
9
9
 
10
+ ## 0.16.2 — 2026-09-21
11
+
12
+ **把「文档写了但没测」这个形状本身盘了一遍**
13
+
14
+ - 这一轮修掉的四个缺陷是同一个形状:文档承诺了某个选项,代码里也有那条分支,但从来没有测试走过它——交付方式三选一只测了一种、METRICS 列名「语义升级」只测了新名字、跨会话恢复一条都没有、iOS 软链接没测过。它们不是被写坏的,是没人走过。
15
+ - 新增 `scripts/audit-untested-enums.mjs`:扫 runtime 里 `['a','b'].includes(x)` 形式的枚举,逐个对照测试有没有碰过。当前结果 51 个取值缺覆盖、分布在 49 处。
16
+ - 新增 `docs/untested-branches.md`:把这 51 个人工分成三类——A 类是用户能配的选项或文档明确承诺的行为(`auto_fix: never`、视觉证据 `video`、诊断 `design_change` 升级出口、cm-check 三态、cm-test 两种模式、cm-refactor 规则三态与四个失败码),每条写清「补测试前要先弄清什么」;B 类是内部协议分支;C 类是噪声,明说不要为它们写测试。
17
+ - 文档同时写明这份清单的局限:只认一种写法所以 51 是下限;「测试提到过某字符串」不等于那条分支被真正走到;以及最要紧的一条——那四个缺陷是跑真实项目跑出来的,不是读代码读出来的。
18
+
19
+ **走查配置和诊断对不上,要等独立审查做完才发现**
20
+
21
+ - 走查声明的模块必须和诊断结论一一对上,这条规矩一直有,但只在走查那一步才查——而走查在独立审查之后。配错了的一轮,要先把复现、编写测试、修复、回归、外部审查全跑完,才在最后一步被拦下,整轮白跑。实测踩过一次。
22
+ - 判定抽成独立函数,诊断一落盘就问一次,对不上当场停在 `walkthrough_configuration_mismatch`。
23
+ - 只在「刚诊断完、还没往下走」时改阶段:已经跑过头的存量记录保持原样。这个判断放在记录回放**之后**——回放循环会拿当前阶段去校验下一条记录,插在循环里会让存量记录直接打不开(实现过程中真踩了一次,靠存量运行验出来的)。
24
+
25
+ **任务编号重名要等跑到红灯测试才炸,而且那一轮直接报废**
26
+
27
+ - 证据文件名由任务 slug 和轮次拼出来,跟 runId 无关,所以两次运行用同一个 taskId 就会写同一批文件。这个冲突原本要等红灯测试去发布输出时才撞上 `review_file_conflict`——那时 intent 已经登记,运行留在 `unknown` 且不可重派,等于前面复现、诊断、编写测试全部白跑。实测踩过一次。
28
+ - 名字在建运行时就全都算得出来。现在 `--mode create` 会先检查这批名字有没有被占,占了就报 `fix_evidence_name_taken`,发生在任何记录落盘之前。只列这次配置真的会写的文件,不拦根本不会发生的冲突;只在 create 时检查,恢复已有运行不受影响。
29
+
30
+ **出了错查不出是哪一步拦的**
31
+
32
+ - runtime 里有 1032 种不同的失败码(光 cm-fix 就 204 种),但同一个码常常在好几处抛出——`fix_closeout_unavailable` 就有四处——而对端只看得到一句笼统的 `host_request_failed`。真实的码虽然写到了 stderr,却不说位置。实测代价:为了定位一次收尾失败,只能把整个宿主脚本复制一份、自己包一层打印调用栈才找到,普通使用者做不到这个。
33
+ - 现在 `need()` 在造错误时就把现场记成一个普通字段,诊断行多出 `origin`,例如 `{"diagnostic":"host_request_failed","operation":"finish","code":"fix_finish_authorization_required","origin":"cm-fix/execution.mjs:1003"}`。
34
+ - 两条边界没动:位置按 runtime 根取相对路径,不会带出绝对路径和用户名;只报这套 runtime 里的帧,不报调用方文件,更不会输出 `error.message`。读取方式也仍然是「只看自有数据属性」——`stack` 是访问器属性,只在 `need` 内部对刚造出来的原生 Error 上读,绝不去碰外来对象的访问器。
35
+ - 协议回复、日志、运行状态、任何摘要都逐字节不变:`origin` 只走 stderr。
36
+
37
+ **CI 只跑了 118 份自动检查里的 15 份**
38
+
39
+ - 其余 103 份从来没在 CI 跑过,包括 cm-fix 的整个持久化核心。本轮修的四个缺陷,本地跑全套都能暴露,CI 一个都发现不了。根因是那份逐个点名的清单:新写的检查不会自动进去,攒着攒着就成了这样。
40
+ - 改成通配符跑全部,清单不会再漂。Node 从 22 提到 24.14——JS 流程本来就要求 24.14+,跑 22 属于测一个没人声明支持的配置,核心那批还会被平台闸门当场挡掉。
41
+ - 有 7 份进不了 CI:它们要启动 Codex 沙箱,而沙箱在 Linux 上靠 bubblewrap 建网络隔离,GitHub 托管机器不给这个权限(`bwrap: loopback: Failed RTM_NEWADDR`),跟登录无关、装上 codex 也没用。这 7 份改由 `cm-release-smoke.sh` 在发版时覆盖——那个脚本本来就要求本机装了 codex 和 byz。于是**每个 PR 覆盖 111 份,每次发版覆盖满 118 份**,没有看不见的缺口。
42
+ - CI 里加了一句断言:排除名单必须正好是这 7 份。想往里加东西就得改那句,改动会出现在评审里。
43
+ - 上线前用一条一次性流水线在 Linux + Node 24.14 上实跑了 4 次,111 份每次全绿、耗时稳定在 4 分上下,确认不是把随机红灯搬进 CI。
44
+
45
+ **改过 METRICS 列名之后,所有存量表都被硬拒且没有迁移路径**
46
+
47
+ - `N4-review.md` 把这次改名写成「保持原列顺序,将原『Codex拦截』语义升级为『独立审查拦截』」——同一列换个名字。但代码是整行精确匹配表头,于是任何改名前就存在的 `METRICS.md` 都过不去:cm-fix 收尾报 `metrics_table_invalid`,cm-refactor 报 `refactor_metrics_format`,两条收尾路径一起停,且没有任何升级办法。
48
+ - 现在两处共用同一份表头定义,认得出这张表用过的所有列名。新文件仍写当前列名,**绝不改写用户文件里已有的表头**;真正不是这张表的文件照旧拒绝。
49
+ - 真实项目上验证:一张 `Codex拦截` 的旧表,收尾成功追加新行、表头原样保留、运行走到 completed。
50
+
10
51
  ## 0.16.1 — 2026-09-21
11
52
 
12
53
  **cm-fix 收尾只认 delivery:diff,把 cm-init 自己生成的默认配置锁在门外**
package/README.md CHANGED
@@ -17,7 +17,7 @@
17
17
 
18
18
  ## 最近更新
19
19
 
20
- **0.16.1**
20
+ **0.16.2**
21
21
 
22
22
  - **安装时会问你要不要开启新版提示**。此前安装完只有一句含糊的「自动更新器未自动启用」,已经开启的人也会看到这句(是错的),没开启的人又不会当回事,结果几乎没人用上这个功能。现在安装器会先看你实际配没配,再决定说什么;没配且是手动安装时,问一句、你答 y 才写入。用 `--yes` 静默安装的不会被改动任何配置,只会打印该加什么。
23
23
  - 它**只加一条「有新版就告诉你」的提示**,不会顺手打开后台自动升级——那是另一回事,仍需你自己决定。你的 `settings.json` 里原有的内容(比如自定义状态栏)不会被动。
@@ -148,7 +148,7 @@ $cm-check
148
148
 
149
149
  仓库直接分发 Skills 和脚本,无需在仓库根目录运行 `npm install` 或构建。完整安装行为、覆盖范围和卸载说明见[安装指南](docs/installation.md)。
150
150
 
151
- 需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.16.1 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
151
+ 需要固定版本时可使用 `npx @aibyzero/cm-workflow@0.16.2 install`,请在 CM Workflow 源码仓库以外的目录执行,例如用户主目录。npm 安装入口复用原安装器,要求与覆盖范围见[安装指南](docs/installation.md#npm-installation-macos-codex)。
152
152
 
153
153
  ## 升级旧版本
154
154
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.16.1
1
+ 0.16.2
@@ -73,7 +73,7 @@ Install or upgrade with the same command:
73
73
  npx @aibyzero/cm-workflow@latest install
74
74
  ```
75
75
 
76
- To pin a version, use `npx @aibyzero/cm-workflow@0.16.1 install` from outside
76
+ To pin a version, use `npx @aibyzero/cm-workflow@0.16.2 install` from outside
77
77
  the CM Workflow source checkout (for example, your home directory). Inside a
78
78
  checkout with the same package name and version, npm can select the local
79
79
  uninstalled package and report `cm-workflow: command not found`.
@@ -0,0 +1,73 @@
1
+ # 没有测试走过的分支
2
+
3
+ 一轮真实实跑修掉的四个缺陷是**同一个形状**:文档承诺了某个选项,代码里也确实有那条
4
+ 分支,但从来没有测试走过它。
5
+
6
+ | 文档承诺 | 实际覆盖 | 后果 |
7
+ | --- | --- | --- |
8
+ | 交付方式 `diff` / `branch` / `draft-mr` 三选一 | 每个夹具都写 `diff` | 另外两种的项目永远收不了尾 |
9
+ | METRICS 列名「语义升级,保持原列顺序」 | 只有新列名 | 所有改名前的表被硬拒 |
10
+ | `--mode resume` 换会话恢复 | 一条都没有 | 从来没有人成功恢复过 |
11
+ | iOS 项目照常支持 | 没有带软链接的夹具 | 基线快照拍不出来 |
12
+
13
+ 它们不是被写坏的,是**没人走过**。所以值得把同一形状的其余候选一次列出来,而不是等下
14
+ 一次实跑再撞。
15
+
16
+ `scripts/audit-untested-enums.mjs` 扫 `runtime/js` 里 `['a','b'].includes(x)` 形式的枚举,
17
+ 逐个看 `scripts/*.test.mjs` 里有没有出现过。写这份文档时的结果:**51 个取值缺覆盖,
18
+ 分布在 49 处**。
19
+
20
+ 脚本输出的是**候选,不是待办**——内部记录类型和 `typeof` 判断也会被匹配到。下面是人工
21
+ 分好的类。改完代码后重跑脚本对照。
22
+
23
+ ---
24
+
25
+ ## A 类:用户能配的选项、或文档明确承诺的行为
26
+
27
+ 这一类和上表四个缺陷完全同形,优先补。
28
+
29
+ | 取值 | 位置 | 承诺在哪 | 补测试前要先弄清 |
30
+ | --- | --- | --- | --- |
31
+ | `auto_fix: never` | `cm-ai/host-qa-fix.mjs:21` | `templates/cm-workflow.yml` 写着 `explicit \| never \| auto`;`runtime/workflow-config.md` 说它决定「N6 失败后的三分支」 | `never` 下 QA 失败到底该停在哪、和 `explicit` 的差别是什么 |
32
+ | 视觉证据 `kind: video` | `cm-ai/review-package.mjs:371` | `cm-fix-host.mjs --help` 明写 `before:{path,sha256,kind:screenshot\|video,...}` | 录屏载体的校验和取证跟截图有没有实质差别 |
33
+ | 诊断 `design_change` | `cm-fix/cause-package.mjs` | cm-fix SKILL 第 4 步「升级出口」:停止硬修、转 `$cm-prd --change` 立项 | 这条出口下红灯测试要保留、档案要记「升级立项」,这些有没有真发生 |
34
+ | cm-check `configured` | `cm-check/host.mjs:105` | 三态之一(`configured\|degraded\|unknown`) | 什么条件算 configured,和 degraded 的边界 |
35
+ | cm-test `snapshot` / `evaluation` | `cm-test/session.mjs:47` | 两种模式**都**没被测过 | 两种模式各自的输入和产物 |
36
+ | cm-refactor 规则三态 | `cm-refactor/workflow.mjs:244` | `rule_correct\|rule_missing\|rule_wrong` 全没测过 | 规则判定的输入从哪来、三态各自怎么触发 |
37
+ | cm-refactor 四个失败码 | `cm-refactor/workflow.mjs:322` | 全没测过 | 每个码对应的真实冲突场景 |
38
+
39
+ **建议按模块分批**,不要一次全开。cm-prd、cm-refactor、cm-test、cm-check 这四块各自
40
+ 独立,给一条从没走过的分支补测试,得先读懂那条分支本来该是什么行为——读浅了会写出
41
+ 「形状对但没验到点上」的测试,那比没有更糟:它让人以为测过了。
42
+
43
+ ## B 类:内部协议分支,值得测但不紧急
44
+
45
+ - `cm-ai/claude-tool-preview.mjs:51` —— `gzip` / `zstd` 传输编码,只测过 `identity`
46
+ - `cm-ai/tool-preview.mjs` —— `argument` 提示词传输方式,全部现有用例走 `stdin`
47
+ - `cm-ai/contracts.mjs` —— 状态机取值 `waiting_user` / `deny` / `revoked` / `active`
48
+ - `cm-ai/durable-runner-state.mjs:215,336` —— `grant_expired` / `clock_invalid`
49
+ - `cm-ai/cm-ai-conversation-entry.mjs:48-56` —— `context_refresh` / `run_finalize`
50
+ - `cm-prd/correction-check.mjs:28,45` —— `mechanical_failed` / `context_result`
51
+
52
+ 这些不在用户配置面上,踩中的路径更窄。但 `grant_expired` 和 `clock_invalid` 关系到授权
53
+ 凭据的过期判定,真出问题代价不小,排在 B 类的前面。
54
+
55
+ ## C 类:噪声,不必单独补
56
+
57
+ 脚本会匹配到,但不构成缺口,**不要**为它们单独写测试:
58
+
59
+ - `typeof` 判断里的 `'string'` / `'boolean'` / `'function'`——语言层面,不是业务分支
60
+ - 内部记录类型 `append-intent` / `append-result` / `task-commit-intent`——已被上层用例
61
+ 整条链路间接覆盖,单独断言只会重复
62
+ - 只做透传的错误码 `catch` 列表,例如 `cm-fix/execution.mjs` 里
63
+ `['context_invalid','context_too_large',...].includes(error?.code)`——这些码由抛出方
64
+ 的用例负责,这里只是把它们原样传出去
65
+
66
+ ## 这份清单的局限
67
+
68
+ - 只扫 `['a','b'].includes(x)` 这一种写法。`switch`、对象查表、`Set.has` 都漏掉了,
69
+ 所以 51 是**下限**不是全部。
70
+ - 「测试里出现过这个字符串」只能说明它被提到过,不等于那条分支被真正走到并断言了。
71
+ A 类里每一条仍要人去确认。
72
+ - 最重要的一点:上表那四个缺陷是**跑真实项目**跑出来的,不是读代码读出来的。这份清单
73
+ 补的是读得出来的那部分;拿工作流去跑真实项目,仍然是发现问题最有效的办法。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibyzero/cm-workflow",
3
- "version": "0.16.1",
3
+ "version": "0.16.2",
4
4
  "description": "Spec-driven business development workflow for Pi, Codex, and Claude Code",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -1,7 +1,9 @@
1
1
  // Shared strict data boundary for S2b. No dispatch or approval authority.
2
2
  import { digest } from './contracts.mjs';
3
3
  export { digest };
4
- export const need=(ok,code='invalid_input')=>{if(!ok){const e=new Error(code);e.code=code;throw e;}};
4
+ export const need=(ok,code='invalid_input')=>{
5
+ if(!ok){const e=new Error(code);e.code=code;const at=raisedAt(e);if(at!==null)e.origin=at;throw e;}
6
+ };
5
7
  // Explicit host call budget, shared by live initialization and journal replay.
6
8
  // This is not the short-lived authorization grant expiry.
7
9
  export const validCallTimeout=value=>need(Number.isInteger(value)&&value>=1&&value<=3600000);
@@ -18,9 +20,39 @@ const failureCodes=new Set(['invalid_input','limit_exceeded','call_timeout','can
18
20
  // error.message, which can carry arbitrary provider output or source text.
19
21
  const diagnosticText=value=>typeof value==='string'&&value.length>0&&value.length<=1024
20
22
  &&!/[\x00-\x08\x0b-\x1f]/.test(value);
23
+ // The code alone is often not actionable: fix_closeout_unavailable is raised in
24
+ // four different places and the peer only ever sees host_request_failed, so the
25
+ // only way to tell them apart was to copy the host and add prints by hand. Name
26
+ // the call site as well. Two boundaries hold: the location is rendered relative
27
+ // to the runtime root, so no absolute path (and no username) is emitted, and only
28
+ // frames inside this runtime are reported — never a caller's file, and never
29
+ // error.message, which can carry arbitrary provider output.
30
+ const runtimeRoot=new URL('../',import.meta.url).href;
31
+ const frameLocation=/(?:\(|\bat )(file:\/\/\S*?):(\d+):\d+\)?$/;
32
+ // Only ever called from need(), on an Error this module just constructed, so
33
+ // reading .stack cannot run a foreign getter. executionDiagnostic below still
34
+ // reads origin the same way as every other field: as an own data property,
35
+ // never by dereferencing an accessor on an object someone else made.
36
+ function raisedAt(error) {
37
+ try {
38
+ const stack=error.stack;
39
+ if(typeof stack!=='string')return null;
40
+ for(const line of stack.split('\n')) {
41
+ const match=frameLocation.exec(line.trim());
42
+ if(!match || !match[1].startsWith(runtimeRoot))continue;
43
+ const relative=decodeURIComponent(match[1].slice(runtimeRoot.length));
44
+ // need() lives here, so its own frame is never the scene; the first frame
45
+ // outside this file is the contract that actually refused.
46
+ if(relative==='cm-ai/effect-contract.mjs')continue;
47
+ const origin=`${relative}:${match[2]}`;
48
+ return diagnosticText(origin)?origin:null;
49
+ }
50
+ } catch {/* diagnostics never change the failure path */}
51
+ return null;
52
+ }
21
53
  export function executionDiagnostic(error) {
22
54
  const detail={};
23
- for(const name of ['code','syscall','path','dest']) {
55
+ for(const name of ['code','syscall','path','dest','origin']) {
24
56
  const d=Object.getOwnPropertyDescriptor(error,name);
25
57
  if(d && Object.hasOwn(d,'value') && diagnosticText(d.value))detail[name]=d.value;
26
58
  }
@@ -0,0 +1,22 @@
1
+ // One METRICS.md table shape, shared by the fix and refactor closeouts.
2
+ // The 「Codex拦截」 column was renamed to 「独立审查拦截」 as a semantic upgrade of the
3
+ // same column — N4-review.md says exactly that: keep the original column order, upgrade
4
+ // what the old 「Codex拦截」 means. Matching the header as one exact string turned that
5
+ // rename into a hard wall instead: every METRICS.md written before it is refused with
6
+ // metrics_table_invalid / refactor_metrics_format, both closeouts stop, and there is no
7
+ // migration path. Accept every name this table has ever used, keep writing the current
8
+ // one for new files, and never rewrite the header inside a file the user owns.
9
+ export const METRICS_HEADER='| 任务 | Feature | 开始 | 结束 | 审查轮次 | 独立审查拦截 | QA | 人工介入(次:原因) |';
10
+ export const METRICS_SEPARATOR='| --- | --- | --- | --- | --- | --- | --- | --- |';
11
+
12
+ // Column order and count are identical across the rename, so a row written today lines
13
+ // up under either header. Only these exact lines count: an arbitrary table is still not
14
+ // this table, and is still refused by the callers.
15
+ const ACCEPTED_HEADERS=Object.freeze([METRICS_HEADER,
16
+ '| 任务 | Feature | 开始 | 结束 | 审查轮次 | Codex拦截 | QA | 人工介入(次:原因) |']);
17
+
18
+ export function hasMetricsHeader(content) {
19
+ if(typeof content!=='string')return false;
20
+ const lines=content.split(/\r?\n/);
21
+ return ACCEPTED_HEADERS.some(candidate=>lines.includes(candidate));
22
+ }
@@ -29,13 +29,13 @@ import {publishFixFinalEvidence} from './final-review-evidence.mjs';
29
29
  import {checkN5} from '../../../scripts/cm-task-gate.mjs';
30
30
  import {readProjectInstructionContext} from '../cm-ai/cm-ai-context-refresh.mjs';
31
31
  import {publishFixDossier,publishFixObservationDossier,readFixObservationArchive} from './dossier.mjs';
32
- import {readFixWalkthrough,fixWalkthroughBinding,createFixWalkthrough,inspectFixWalkthrough,verifyFixWalkthroughEvidence} from './walkthrough.mjs';
32
+ import {readFixWalkthrough,fixWalkthroughBinding,createFixWalkthrough,inspectFixWalkthrough,verifyFixWalkthroughEvidence,walkthroughCoversDiagnosis} from './walkthrough.mjs';
33
33
  import {logFixEvent} from './start.mjs';
34
34
  import {inspectFixInvestigation,fixInvestigationRequest} from './investigation.mjs';
35
35
  import {finishFix,fixCompletionProjection,eventsAt,isFixObservationExit} from './finish.mjs';
36
36
  import {specsPermissionArgs} from '../cm-ai/codex-config.mjs';
37
37
  import {protectedFixBridge} from './protected-edits.mjs';
38
- import {fixArchiveRoot,fixDossierRelative} from './layout.mjs';
38
+ import {fixArchiveRoot,fixDossierRelative,assertFixEvidenceNamesFree} from './layout.mjs';
39
39
  import {isVisual,verifyVisualCarrier} from './visual.mjs';
40
40
 
41
41
  const observationId=(kind,cycle)=>`fix-observation-${cycle===1?'':cycle+'-'}${kind}`;
@@ -129,6 +129,7 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
129
129
  shape(configuration.repair,['scope','requirements']);need(runBaseline,'baseline_configuration_required');
130
130
  validateDeveloperScope(configuration.repair.scope);
131
131
  }
132
+ if(create)assertFixEvidenceNamesFree(evidenceSpecsRoot,identity,configuration);
132
133
  if(create&&Object.hasOwn(configuration,'qaSource'))inspectFixQaSource({specsRoot,identity,configuration});
133
134
  const store=openExecutionStore({specsRoot,identity:{repositoryId:identity.repositoryId,runId:identity.runId},create,
134
135
  fingerprints:{workflow:digest('cm-fix-stages-v1'),config:digest(configuration),inputs:digest(identity)}});
@@ -760,9 +761,17 @@ export function openFixExecution(options,{bridge=null,prepare=null,causeReview=n
760
761
  diagnosed=diagnosis(record.payload.value);
761
762
  stage=diagnosed.status==='needs_evidence'?'observation':diagnosed.status==='design_change'?'cause_review_required':
762
763
  diagnosed.crossLayer||diagnosed.affectedModules.length>=3?'cause_review_required':'red_test_required';
764
+
763
765
  }
764
766
  }
765
767
  }
768
+ // 走查声明的模块和诊断对不上,这一轮无论如何走不到收尾。原来要等走查那一步才
769
+ // 发现,而那已经在花钱做完独立审查之后——整轮白跑。诊断一落盘就判得出来。
770
+ // 只在「刚诊断完、还没往下走」时改阶段:已经跑过头的旧记录保持原样。回放循环
771
+ // 会拿当前阶段去校验下一条记录,所以这个判断必须放在循环之后,不能插在循环里。
772
+ if(configuration.walkthrough&&diagnosed?.status==='diagnosed'
773
+ &&['red_test_required','cause_review_required'].includes(stage)
774
+ &&!walkthroughCoversDiagnosis(configuration.walkthrough,diagnosed))stage='walkthrough_configuration_mismatch';
766
775
  if(causeResult?.review?.verdict==='approved'&&stage!=='cancelled'&&repairBaseline===null){
767
776
  try{
768
777
  const current=createFixCausePackage({codeProject:configuration.reproduction.cwd,defect:configuration.defect,
@@ -15,3 +15,29 @@ export function fixArchiveRoot(specsRoot,cwd,create=false){
15
15
  }
16
16
  export const fixDossierRelative=(configuration,name)=>configuration.archiveMode==='bare'?name:`fixes/${name}`;
17
17
  export const fixDossierDirectory=(root,configuration)=>configuration.archiveMode==='bare'?root:path.join(root,'fixes');
18
+
19
+ // 证据文件名由任务 slug 和轮次拼出来,跟 runId 无关——两次运行用同一个 taskId
20
+ // 就会写同一批文件。这个冲突原本要等到红灯测试去发布输出时才被发现,而那时
21
+ // intent 已经登记,运行留在 unknown 且不可重派,等于一整轮报废。名字在建运行
22
+ // 时就全都算得出来,所以在任何记录落盘之前先拒掉,并说清是哪一个名字被占了。
23
+ // 只在 create 时检查:恢复一次已有的运行,本来就该读到自己写下的证据。
24
+ export function fixEvidenceNames(identity,configuration){
25
+ const slug=/^T-FIX-([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(identity.taskId)?.[1];
26
+ if(!slug)return []; // 非法 taskId 由原有的 invalid_fix_slug 负责,不在这里抢答
27
+ const names=[`fix-${slug}-${identity.taskId}-a${identity.attempt}-handoff.json`,
28
+ `fix-${slug}-${identity.taskId}-r${identity.attempt}.md`];
29
+ // 只列这次配置真的会写的文件,免得拦下根本不会发生的冲突。
30
+ if(configuration.redTest&&configuration.redTest.kind!=='visual')
31
+ names.push(`fix-${slug}-a${identity.attempt}-red-output.md`);
32
+ if(configuration.causeReview)names.push(`fix-${slug}-cause-r1.md`);
33
+ return names;
34
+ }
35
+ export function assertFixEvidenceNamesFree(archiveRoot,identity,configuration){
36
+ const reviews=path.join(archiveRoot,'.reviews');
37
+ for(const name of fixEvidenceNames(identity,configuration)){
38
+ let taken=false;
39
+ try{taken=fs.lstatSync(path.join(reviews,name))!==undefined;}
40
+ catch(error){if(error.code!=='ENOENT'&&error.code!=='ENOTDIR')throw error;}
41
+ need(!taken,'fix_evidence_name_taken');
42
+ }
43
+ }
@@ -5,9 +5,7 @@ import path from 'node:path';
5
5
  import {types} from 'node:util';
6
6
  import {readReviewSourceFiles} from '../cm-ai/review-package.mjs';
7
7
  import {id,need,validIdentity} from '../cm-ai/effect-contract.mjs';
8
-
9
- const header='| 任务 | Feature | 开始 | 结束 | 审查轮次 | 独立审查拦截 | QA | 人工介入(次:原因) |';
10
- const separator='| --- | --- | --- | --- | --- | --- | --- | --- |';
8
+ import {METRICS_HEADER as header,METRICS_SEPARATOR as separator,hasMetricsHeader} from '../cm-ai/metrics-table.mjs';
11
9
  const cell=value=>String(value).replaceAll('|','&#124;').replace(/[\r\n]+/g,' ');
12
10
  const same=(event,identity)=>event.workflow==='cm-fix'&&event.node==='FIX'&&event.run_id===identity.runId
13
11
  &&event.repository_id===identity.repositoryId&&event.task===identity.taskId;
@@ -62,7 +60,7 @@ export function appendFixMetrics({specsRoot,identity,dossierFile},{assertOwned})
62
60
  const current=fs.lstatSync(target);need(!current.isSymbolicLink()&&current.dev===stat.dev&&current.ino===stat.ino&&current.size===stat.size,'metrics_file_changed');
63
61
  owned();return {...record,path:target,deduplicated:true};
64
62
  }
65
- if(before.length)need(content.split(/\r?\n/).includes(header),'metrics_table_invalid');
63
+ if(before.length)need(hasMetricsHeader(content),'metrics_table_invalid');
66
64
  const bytes=Buffer.from((before.length?(content.endsWith('\n')?'':'\n'):`${header}\n${separator}\n`)+record.line+'\n');
67
65
  need(before.length+bytes.length<=1024*1024,'limit_exceeded');owned();
68
66
  const current=fs.lstatSync(target);need(!current.isSymbolicLink()&&current.dev===stat.dev&&current.ino===stat.ino&&current.size===stat.size,'metrics_file_changed');
@@ -29,10 +29,16 @@ export function readFixWalkthrough(raw,cwd){
29
29
  return config;
30
30
  }
31
31
 
32
+ // 走查声明的模块要和诊断结论一一对上。抽成单独的判定,好让诊断刚落盘时就能问一次
33
+ // ——原来只有走查那一步会问,而那已经在花钱做完独立审查之后了。
34
+ export function walkthroughCoversDiagnosis(configuration,diagnosis){
35
+ const covered=new Set(configuration.flows.flatMap(flow=>flow.modules));
36
+ return diagnosis.affectedModules.length===covered.size
37
+ &&diagnosis.affectedModules.every(module=>covered.has(module));
38
+ }
32
39
  export function fixWalkthroughBinding({identity,packageDigest,diagnosis,configuration}){
33
40
  validIdentity(identity);hex(packageDigest);
34
- const covered=new Set(configuration.flows.flatMap(flow=>flow.modules));
35
- need(diagnosis.affectedModules.length===covered.size&&diagnosis.affectedModules.every(module=>covered.has(module)),'walkthrough_module_mismatch');
41
+ need(walkthroughCoversDiagnosis(configuration,diagnosis),'walkthrough_module_mismatch');
36
42
  return json({identity,packageDigest,diagnosisDigest:digest(diagnosis),configurationDigest:digest(configuration)});
37
43
  }
38
44
 
@@ -11,6 +11,7 @@ import {writeImmutableWorkflowFile} from '../cm-ai/review-evidence-file.mjs';
11
11
  import {mergeLessons} from '../cm-ai/cm-ai-learning-writer.mjs';
12
12
  import {readLearningRetrospectiveContent} from '../cm-ai/cm-ai-context-refresh.mjs';
13
13
  import {need,shape,json,digest} from '../cm-ai/effect-contract.mjs';
14
+ import {METRICS_HEADER,hasMetricsHeader} from '../cm-ai/metrics-table.mjs';
14
15
  import {inside,canonicalFuture,snapshotSource} from '../cm-test/source-snapshot.mjs';
15
16
  import {openRefactorRecords,readText,replaceText,sha} from './records.mjs';
16
17
  const nonempty=value=>typeof value==='string'&&value.trim().length>0;
@@ -431,8 +432,8 @@ export function createCmRefactorHost(raw,{call}){
431
432
  await publish('dossier',dossierPath(),'# Refactor dossier\n\n'+markdown({analysis,metricAfter:proposal.metricAfter,changed:proposal.changed,reports,
432
433
  delivery:'diff',hostCalls,commandCount,baselineCount:config.baselineCommands.length,differentialCount:judgeBefore.cases.length,
433
434
  learning:proposal.learning,unfixedDefects:proposal.unfixedDefects,deviations:[],usage}));
434
- if(specs){const header='| 任务 | Feature | 开始 | 结束 | 审查轮次 | 独立审查拦截 | QA | 人工介入(次:原因) |',old=context.metrics;
435
- need(!old||old.split(/\r?\n/).includes(header),'refactor_metrics_format');
435
+ if(specs){const header=METRICS_HEADER,old=context.metrics;
436
+ need(!old||hasMetricsHeader(old),'refactor_metrics_format');
436
437
  const at=await records.effect('finish-time','clock',{},()=>new Date().toISOString());
437
438
  const line=`| ${task} | refactor | ${context.startedAt} | ${at} | ${attempt} | ${interceptions} | 等价通过 | ${calls.filter(entry=>entry.input.kind==='refactor_confirm').length}:人门; delivery-diff; agents=${usage.agentCalls}; host_ms=${usage.hostDurationMs}; estimate_tokens=${usage.estimatedTokens??'unavailable'}; actual_tokens=unavailable; commands=${commandCount} |\n`;
438
439
  await write('metrics',path.join(specs,'METRICS.md'),old,(old??`${header}\n| --- | --- | --- | --- | --- | --- | --- | --- |\n`)+(old&&!old.endsWith('\n')?'\n':'')+line,context.metricsMode);}
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ // 盘点 runtime 里「只能取这几个值」的枚举,逐个看测试有没有碰过。
3
+ //
4
+ // 为什么要有这个:一轮真实实跑里修掉的四个缺陷是同一个形状——文档承诺了某个选项,
5
+ // 代码里也确实有那条分支,但从来没有测试走过它。交付方式三选一只测了一种、统计表
6
+ // 列名「语义升级」只测了新名字、跨会话恢复一条都没有、iOS 软链接没测过。它们不是
7
+ // 被写坏的,是没人走过。这个脚本把同一形状的其余候选一次性列出来。
8
+ //
9
+ // 输出是候选,不是待办:内部记录类型和 typeof 判断也会被匹配到,人得自己分类。
10
+ // 分好类的结果见 docs/untested-branches.md;改完代码后重跑本脚本对照。
11
+ //
12
+ // node scripts/audit-untested-enums.mjs 列出所有缺覆盖的枚举取值
13
+ // node scripts/audit-untested-enums.mjs --summary 只报数字
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import {fileURLToPath} from 'node:url';
17
+
18
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
19
+ const summaryOnly=process.argv.includes('--summary');
20
+
21
+ const walk=dir=>fs.readdirSync(dir,{withFileTypes:true}).flatMap(entry=>{
22
+ const full=path.join(dir,entry.name);
23
+ return entry.isDirectory()?walk(full):full.endsWith('.mjs')?[full]:[];
24
+ });
25
+
26
+ const tests=fs.readdirSync(path.join(root,'scripts'))
27
+ .filter(name=>name.endsWith('.test.mjs'))
28
+ .map(name=>fs.readFileSync(path.join(root,'scripts',name),'utf8')).join('\n');
29
+ const covered=value=>tests.includes(`'${value}'`)||tests.includes(`"${value}"`);
30
+
31
+ // 只认最常见的一种写法:['a','b'].includes(x)。漏掉别的写法好过误报一堆。
32
+ const pattern=/\[((?:'[a-z][a-z0-9_.-]*',\s*){1,8}'[a-z][a-z0-9_.-]*')\]\.includes\(/g;
33
+ const findings=[];
34
+ for(const file of walk(path.join(root,'runtime/js'))) {
35
+ fs.readFileSync(file,'utf8').split('\n').forEach((line,index)=>{
36
+ for(const match of line.matchAll(pattern)) {
37
+ const values=match[1].split(',').map(value=>value.trim().slice(1,-1));
38
+ const missing=values.filter(value=>!covered(value));
39
+ if(missing.length)findings.push({file:path.relative(root,file),line:index+1,values,missing});
40
+ }
41
+ });
42
+ }
43
+
44
+ const values=new Set(findings.flatMap(finding=>finding.missing));
45
+ if(!summaryOnly) {
46
+ const byModule=new Map();
47
+ for(const finding of findings) {
48
+ const module=finding.file.split('/')[2]??finding.file;
49
+ byModule.set(module,[...(byModule.get(module)??[]),finding]);
50
+ }
51
+ for(const [module,list] of [...byModule].sort((a,b)=>b[1].length-a[1].length)) {
52
+ process.stdout.write(`\n${module} (${list.length} 处)\n`);
53
+ for(const finding of list)
54
+ process.stdout.write(` ${finding.file}:${finding.line} 缺 ${finding.missing.join(',')}`
55
+ +` 枚举 ${finding.values.join('|')}\n`);
56
+ }
57
+ process.stdout.write('\n');
58
+ }
59
+ process.stdout.write(`缺覆盖的枚举取值 ${values.size} 个,分布在 ${findings.length} 处\n`);
@@ -66,3 +66,28 @@ test('an error whose code cannot be read still collapses without throwing', () =
66
66
  try{assert.equal(failureCode(hostile),'execution_error');}
67
67
  finally{process.stderr.write=original;}
68
68
  });
69
+
70
+ // 光有失败码不够用:像 fix_closeout_unavailable 这种,同一个码在四个地方都会抛,
71
+ // 而对端只看得到一句笼统的 host_request_failed。诊断里得说清是哪一处拦的,
72
+ // 否则只能把宿主复制一份、自己加打印去找——这正是今天实际发生过的事。
73
+ test('a contract refusal names where it was raised, as a runtime-relative location', async () => {
74
+ const {validateCauseReviewer}=await import('../runtime/js/cm-fix/cause-invocation.mjs');
75
+ let raised;
76
+ try{ validateCauseReviewer({reviewerId:'r',adapterId:'a',provider:'codex',
77
+ requestedModel:'m',contextId:'same-host',excludedThreadIds:[]},'same-host'); }
78
+ catch(error){ raised=error; }
79
+ assert.equal(raised.code,'invalid_cause_reviewer');
80
+ const detail=executionDiagnostic(raised);
81
+ assert.equal(detail.code,'invalid_cause_reviewer');
82
+ // 指到真正的现场,而不是 need 自己所在的 effect-contract
83
+ assert.match(detail.origin,/^cm-fix\/cause-invocation\.mjs:\d+$/);
84
+ // 相对 runtime 根,不带绝对路径,免得把用户名之类带出去
85
+ assert.equal(detail.origin.includes('/Users/'),false);
86
+ // 塌缩那条 stderr 诊断同样带上
87
+ assert.match(collapse(raised),/"origin":"cm-fix\/cause-invocation\.mjs:\d+"/);
88
+ });
89
+
90
+ test('a location is only reported for our own runtime, never a caller file', () => {
91
+ // 测试文件不在 runtime 下,构造出来的错误不该被安上位置。
92
+ assert.deepEqual(executionDiagnostic(named('x',{code:'EBADF'})),{code:'EBADF'});
93
+ });
@@ -125,3 +125,44 @@ test('resuming never rewrites the durable host or accepts a reviewer-shaped sess
125
125
  hostContextId:reviewer.contextId}),{code:'invalid_cause_reviewer'});
126
126
  openFixExecution({...options,configuration,create:false,hostContextId:'actual-resumed-host'}).close();
127
127
  }));
128
+
129
+ // 证据文件名由任务 slug 和轮次拼出来,跟 runId 无关,所以两次运行用同一个 taskId
130
+ // 就会写同一批文件。这个冲突原本要等红灯测试去发布输出时才炸——那时候 intent
131
+ // 已经登记,运行直接留在 unknown 且不可重派。名字在建运行时全都算得出来。
132
+ test('a run whose evidence filenames are already taken is refused before anything is recorded',()=>fixture(async(options)=>{
133
+ const reviews=path.join(options.specsRoot,'.reviews');
134
+ fs.mkdirSync(reviews,{recursive:true,mode:0o700});
135
+ const taken=path.join(reviews,`fix-demo-${identity.taskId}-r1.md`);
136
+ fs.writeFileSync(taken,'another run already published under this task id');
137
+ assert.throws(()=>openFixExecution(options),{code:'fix_evidence_name_taken'});
138
+ // 拒绝发生在任何记录之前:没有留下半个运行
139
+ assert.equal(fs.existsSync(path.join(reviews,'.execution',identity.runId)),false);
140
+ // 换一个任务编号就能正常建起来,说明拦的是重名而不是别的
141
+ const renamed={...options,identity:{...identity,taskId:'T-FIX-demo-two'}};
142
+ openFixExecution(renamed).close();
143
+ // 已经建起来的运行,恢复时不会被自己写下的证据挡住
144
+ fs.writeFileSync(path.join(reviews,'fix-demo-two-T-FIX-demo-two-r1.md'),'its own evidence');
145
+ openFixExecution({...renamed,create:false}).close();
146
+ }));
147
+
148
+ // 走查声明的模块必须和诊断结论对得上。这条规矩一直有,但原来只在走查那一步才查
149
+ // ——那已经在花钱做完独立审查之后,整轮白跑。诊断一落盘就判得出来。
150
+ test('a walkthrough that does not line up with the diagnosis stops right after diagnosis',async()=>{
151
+ for(const [modules,expected] of [[['value','not-diagnosed'],'walkthrough_configuration_mismatch'],
152
+ [['value'],'red_test_required']])
153
+ await fixture(async(options)=>{
154
+ const bridge=createHostToolBridge();
155
+ bridge.attach(row=>{if(row.type==='host_request')bridge.accept({type:'host_result',sessionId:row.sessionId,
156
+ callId:row.callId,requestDigest:row.requestDigest,result:cause});});
157
+ const configuration={...options.configuration,walkthrough:{timeoutMs:2000,
158
+ flows:[{id:'value-flow',modules,steps:['Exercise the repaired value'],expected:['Value is 2'],
159
+ kind:'commands',command:[process.execPath,'-e','0']}]}};
160
+ const owner=openFixExecution({...options,configuration},{bridge});
161
+ try{
162
+ const status=await owner.advance({authorized:true});
163
+ assert.equal(status.stage,expected,JSON.stringify(modules));
164
+ // 诊断照常留底,停住不等于把证据弄丢
165
+ assert.equal(status.diagnosis.status,'diagnosed');
166
+ }finally{owner.close();bridge.close();}
167
+ });
168
+ });
@@ -56,3 +56,35 @@ test('FIX metrics projects completed log evidence, preserves content, deduplicat
56
56
  assert.throws(()=>appendFixMetrics(options,control));assert.equal(fs.readFileSync(path.join(root,'fixes',dossierFile),'utf8'),body);
57
57
  }finally{fs.rmSync(root,{recursive:true,force:true});}
58
58
  });
59
+
60
+ // 「Codex拦截」在 N4-review.md 里被明确记为「保持原列顺序,语义升级为独立审查拦截」,
61
+ // 也就是同一列改个名。但表头是整行精确匹配,于是任何改名前就存在的 METRICS.md 都会被
62
+ // 硬拒,收尾整个走不完,而且没有迁移路径。
63
+ test('FIX metrics appends under the renamed legacy header instead of refusing the file',()=>{
64
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-metrics-legacy-')));
65
+ try{
66
+ fs.mkdirSync(path.join(root,'fixes'));
67
+ const dossierFile='20260907-value.md',body='Synthetic completed dossier, fixture only.\n';
68
+ fs.writeFileSync(path.join(root,'fixes',dossierFile),body);
69
+ const identity={repositoryId:'fixture',runId:'metrics-legacy',taskId:'T-FIX-value',attempt:1};
70
+ const common={workflow:'cm-fix',node:'FIX',repository_id:identity.repositoryId,run_id:identity.runId,task:identity.taskId,attempt:1};
71
+ const events=[{...common,event:'task_start',at:'2026-09-07T01:00:00Z',event_id:'start'},
72
+ {...common,event:'review',phase:'complete',review_kind:'implementation',round:1,result:'approved',finding_count:0,package_digest:'a'.repeat(64),event_id:'review'},
73
+ {...common,event:'task_done',at:'2026-09-07T01:01:00Z',event_id:'done',result:'completed',dossier_file:`fixes/${dossierFile}`,
74
+ dossier_sha256:createHash('sha256').update(body).digest('hex'),package_digest:'a'.repeat(64),walkthrough_result:'passed'}];
75
+ fs.writeFileSync(path.join(root,'运行日志.jsonl'),events.map(row=>JSON.stringify(row)).join('\n')+'\n');
76
+ const legacy='| 任务 | Feature | 开始 | 结束 | 审查轮次 | Codex拦截 | QA | 人工介入(次:原因) |';
77
+ const existing=`User notes stay.\n\n${legacy}\n| --- | --- | --- | --- | --- | --- | --- | --- |\n| T-other | other | a | b | 1 | 0 | — | 0 |\n`;
78
+ fs.writeFileSync(path.join(root,'METRICS.md'),existing);
79
+ const options={specsRoot:root,identity,dossierFile},control={assertOwned(){}};
80
+ const written=appendFixMetrics(options,control);
81
+ const bytes=fs.readFileSync(written.path,'utf8');
82
+ assert(bytes.startsWith(existing),'用户原有内容必须一字不动');
83
+ assert(bytes.includes(written.line),'新行要追加进同一张表');
84
+ assert(!bytes.includes('独立审查拦截'),'不擅自改写用户文件里的表头');
85
+ assert.equal(appendFixMetrics(options,control).deduplicated,true);
86
+ // 认得出的旧表头才放行;真正不是这张表的文件照旧拒绝。
87
+ fs.writeFileSync(path.join(root,'METRICS.md'),'User custom table, not recognized.\n');
88
+ assert.throws(()=>appendFixMetrics(options,control),{code:'metrics_table_invalid'});
89
+ }finally{fs.rmSync(root,{recursive:true,force:true});}
90
+ });
@@ -43,6 +43,20 @@ for candidate in python3 python; do
43
43
  done
44
44
  [ -n "$PYTHON_BIN" ] || blocked "Python 3.9+ not found"
45
45
 
46
+ # CI 覆盖不到的那一批:它们要启动 Codex 沙箱,而在 GitHub 托管机器上 bubblewrap
47
+ # 建不了网络隔离(bwrap: loopback: Failed RTM_NEWADDR),装上 codex 也没用。
48
+ # 这个脚本上面已经要求本机装了 codex,所以这里是它们唯一稳定的落点——发版必过。
49
+ # 名单要和 .github/workflows/ci.yml 的 js-tests 排除名单保持一致。
50
+ printf '%s\n' '==> Running the Codex-sandbox tests that CI cannot host'
51
+ ( cd "$ROOT" && node --test \
52
+ scripts/cm-ai-batch-host.test.mjs \
53
+ scripts/cm-ai-bootstrap.test.mjs \
54
+ scripts/cm-ai-host.test.mjs \
55
+ scripts/cm-ai-multi-root.test.mjs \
56
+ scripts/cm-ai-nested-execution.test.mjs \
57
+ scripts/cm-fix-protected-edits.test.mjs \
58
+ scripts/cm-host-check.test.mjs )
59
+
46
60
  printf '%s\n' '==> Validating the public Pi/BYZ package manifest'
47
61
  "$PYTHON_BIN" "$ROOT/scripts/validate-public-repo.py"
48
62