@aibyzero/cm-workflow 0.20.0 → 0.21.1

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.
Files changed (78) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +13 -1
  4. package/VERSION +1 -1
  5. package/docs/installation.md +1 -1
  6. package/docs/js-workflow-control.md +1 -1
  7. package/docs/proposals/spec-amendment-tiers.md +100 -0
  8. package/package.json +1 -1
  9. package/runtime/js/acceptance-language.mjs +32 -0
  10. package/runtime/js/autonomy.mjs +15 -6
  11. package/runtime/js/cm-ai/acceptance-contract.mjs +8 -3
  12. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +35 -2
  14. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  15. package/runtime/js/cm-ai/drive-core.mjs +9 -2
  16. package/runtime/js/cm-ai/durable-runner-state.mjs +12 -4
  17. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  18. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  19. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  20. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  21. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  22. package/runtime/js/cm-ai/review-package.mjs +20 -6
  23. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  24. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  25. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  26. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  27. package/runtime/js/cm-ai/task-commit-codec.mjs +4 -2
  28. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  29. package/runtime/js/cm-ai/task-runner.mjs +26 -9
  30. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  31. package/runtime/js/cm-prd/change.mjs +35 -4
  32. package/runtime/js/cm-prd/self-check.mjs +36 -6
  33. package/runtime/js/cm-prd/session.mjs +8 -3
  34. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  35. package/runtime/js/task-scope.mjs +4 -1
  36. package/runtime/test-contract.md +1 -0
  37. package/scripts/cm-ai-acceptance-contract.test.mjs +10 -0
  38. package/scripts/cm-ai-admission.mjs +8 -2
  39. package/scripts/cm-ai-admission.test.mjs +15 -2
  40. package/scripts/cm-ai-batch-run-fixture.mjs +5 -1
  41. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  42. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  43. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  44. package/scripts/cm-ai-drive.mjs +18 -11
  45. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  46. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  47. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  48. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  49. package/scripts/cm-autonomy-review-r1.test.mjs +49 -0
  50. package/scripts/cm-check-runtime.sh +4 -1
  51. package/scripts/cm-drive-liveness.test.mjs +8 -0
  52. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  53. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  54. package/scripts/cm-journal-limit.test.mjs +69 -0
  55. package/scripts/cm-notify.test.mjs +6 -4
  56. package/scripts/cm-prd-completion.test.mjs +37 -0
  57. package/scripts/cm-prd-drive.mjs +1 -1
  58. package/scripts/cm-prd-host.test.mjs +1 -1
  59. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  60. package/scripts/cm-prd-self-check.test.mjs +24 -1
  61. package/scripts/cm-prd-summary.test.mjs +6 -0
  62. package/scripts/cm-review-inventory.test.mjs +5 -1
  63. package/scripts/cm-skill-hints.json +1 -1
  64. package/scripts/cm-skill-hints.mjs +66 -3
  65. package/scripts/cm-skill-hints.test.mjs +96 -0
  66. package/scripts/cm-spec-amend.mjs +68 -0
  67. package/scripts/cm-spec-amend.test.mjs +510 -0
  68. package/scripts/cm-specs-status.test.mjs +6 -0
  69. package/scripts/cm-start-check.mjs +82 -2
  70. package/scripts/cm-start-check.test.mjs +64 -1
  71. package/scripts/cm-task-scope.test.mjs +3 -2
  72. package/scripts/test-journal-limit-1mib.mjs +4 -0
  73. package/scripts/validate-public-repo.py +4 -0
  74. package/skills/cm-ai/references/N1-init.md +23 -1
  75. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  76. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  77. package/skills/cm-ai/references/js-host.md +2 -1
  78. package/skills/cm-prd/references/js-change-recovery.md +1 -0
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ // Tiered re-approval of in-flight spec corrections; see runtime/js/cm-ai/spec-amendment.mjs.
3
+ // inspect 只读:给出 0/1/2 级与原因
4
+ // prepare 1 级时把批准时与现在的规格副本、审查提示写到 --out 目录
5
+ // apply 0 级直接换绑;1 级需独立审查输出(--review-output)与审查者(--reviewer)
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {inspectSpecAmendment,publicAmendment,prepareSpecAmendment,applySpecAmendment} from '../runtime/js/cm-ai/spec-amendment.mjs';
10
+
11
+ const usage=`usage: cm-spec-amend.mjs inspect --specs-dir PATH
12
+ cm-spec-amend.mjs prepare --specs-dir PATH --out EMPTY_DIR
13
+ cm-spec-amend.mjs apply --specs-dir PATH --reason TEXT [--review-output FILE --reviewer TEXT]`;
14
+
15
+ const NEXT={
16
+ null:'规格与批准时相同,不需要换绑。',
17
+ 0:'0 级:只追加了版本记录行。运行 apply --reason 直接换绑,不需要审查,也不需要用户回复「开始」。',
18
+ 1:'1 级:执行中补正。先 prepare,把 review-prompt.md 交给另一个新上下文的审查者(不是写补正的人),保存其完整输出,再 apply --review-output --reviewer。生效后在下一条消息里告诉用户改了什么,不必等回复。',
19
+ 2:'2 级:要用户本人批准。展示改动摘要,请用户回复「开始」,再走 cm-ai-admission.mjs --approve。',
20
+ };
21
+
22
+ function parse(argv){
23
+ const [command,...rest]=argv;
24
+ if(!command||command==='--help'||command==='-h')return {help:true};
25
+ if(!['inspect','prepare','apply'].includes(command))throw new Error('unknown command');
26
+ const flags={'--specs-dir':'specsDir','--out':'outDir','--reason':'reason','--review-output':'reviewOutput','--reviewer':'reviewer'};
27
+ const allowed={inspect:['specsDir'],prepare:['specsDir','outDir'],apply:['specsDir','reason','reviewOutput','reviewer']}[command];
28
+ const result={command};
29
+ for(let index=0;index<rest.length;index++){
30
+ const key=flags[rest[index]];
31
+ if(!key||!allowed.includes(key)||index+1>=rest.length||Object.hasOwn(result,key))throw new Error('invalid arguments');
32
+ result[key]=rest[++index];
33
+ }
34
+ if(!result.specsDir)throw new Error('--specs-dir is required');
35
+ if(command==='prepare'&&!result.outDir)throw new Error('--out is required');
36
+ if(command==='apply'&&!result.reason)throw new Error('--reason is required');
37
+ return result;
38
+ }
39
+
40
+ export function main(argv=process.argv.slice(2),{stdout=process.stdout,stderr=process.stderr}={}){
41
+ let input;
42
+ try{input=parse(argv);}catch(error){stderr.write(`${usage}\nERROR: ${error.message}\n`);return 2;}
43
+ if(input.help){stdout.write(`${usage}\n`);return 0;}
44
+ const specsDir=path.resolve(input.specsDir);
45
+ try{
46
+ if(input.command==='inspect'){
47
+ const result=publicAmendment(inspectSpecAmendment(specsDir));
48
+ stdout.write(`${JSON.stringify({...result,next:NEXT[result.tier]})}\n`);return 0;
49
+ }
50
+ if(input.command==='prepare'){
51
+ const result=prepareSpecAmendment(specsDir,{outDir:input.outDir});
52
+ stdout.write(`${JSON.stringify({...result,next:NEXT[result.tier]})}\n`);return result.tier===1?0:1;
53
+ }
54
+ let reviewOutput;
55
+ if(input.reviewOutput!==undefined)reviewOutput=fs.readFileSync(path.resolve(input.reviewOutput),'utf8');
56
+ const result=applySpecAmendment(specsDir,{reason:input.reason,reviewOutput,reviewer:input.reviewer});
57
+ stdout.write(`${JSON.stringify({...result,...(result.applied?{}:{next:NEXT[result.tier]})})}\n`);
58
+ return result.applied?0:1;
59
+ }catch(error){
60
+ stderr.write(`${JSON.stringify({error:{code:error.code??error.message}})}\n`);return 1;
61
+ }
62
+ }
63
+
64
+ function isMain(entry){
65
+ if(!entry)return false;
66
+ try{return fs.realpathSync(entry)===fileURLToPath(import.meta.url);}catch{return path.resolve(entry)===fileURLToPath(import.meta.url);}
67
+ }
68
+ if(isMain(process.argv[1]))process.exitCode=main();
@@ -0,0 +1,510 @@
1
+ // Fixtures for tiered spec re-approval: each tier-1 condition has a counterexample
2
+ // that must fall back to tier 2 (user "开始"), and tier 1 only applies with a
3
+ // review verdict bound to the exact delta.
4
+ import test from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import {spawnSync} from 'node:child_process';
10
+ import {fileURLToPath} from 'node:url';
11
+ import {approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
12
+ import {applySpecAmendment,withApprovalLock} from '../runtime/js/cm-ai/spec-amendment.mjs';
13
+
14
+ // The round ledger lives under CM_WORKFLOW_HOME; never touch the real home.
15
+ const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-spec-amend-home-'));
16
+ process.env.CM_WORKFLOW_HOME=isolatedHome;
17
+ process.on('exit',()=>fs.rmSync(isolatedHome,{recursive:true,force:true}));
18
+ const admission=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
19
+ const amend=fileURLToPath(new URL('./cm-spec-amend.mjs',import.meta.url));
20
+
21
+ const TASKS=`# 登录 — 任务清单
22
+
23
+ ## 任务版本
24
+ | 日期 | 版本 | 说明 |
25
+ | --- | --- | --- |
26
+ | 2026-11-01 | v1 | 初始 |
27
+
28
+ ## 任务列表
29
+ - [ ] T-001: 登录页
30
+ - 范围: \`src/login.js\`
31
+ - 验收: AC-001
32
+ - [ ] T-002: 登录接口
33
+ - 范围: \`src/api.js\`
34
+ - 验证: 断言错误密码返回 401
35
+ - 验收: AC-002
36
+ - T-002 依赖 T-001
37
+ `;
38
+ const CASES={schemaVersion:'1.0',feature:'login',cases:[{id:'TC-001',origin:'user',kind:'logic',blocking:true,
39
+ acIds:['AC-002'],taskIds:['T-002'],title:'错误密码被拒',preconditions:[],steps:['提交错误密码'],expected:['返回 401'],cleanup:[]}]};
40
+
41
+ function fixture(run,{cases=false}={}){
42
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-spec-amend-')));
43
+ const specs=path.join(root,'specs'),code=path.join(root,'code'),feature=path.join(specs,'1.login');
44
+ fs.mkdirSync(feature,{recursive:true});fs.mkdirSync(code);fs.writeFileSync(path.join(code,'README.md'),'existing\n');
45
+ fs.writeFileSync(path.join(feature,'requirements.md'),'# 需求\n\n- [AC-001] 显示登录页\n- [AC-002] 错误密码被拒\n');
46
+ fs.writeFileSync(path.join(feature,'design.md'),'# 设计\n\n模块 1:登录页。\n');
47
+ fs.writeFileSync(path.join(feature,'tasks.md'),TASKS);
48
+ if(cases)fs.writeFileSync(path.join(feature,'test-cases.json'),JSON.stringify(CASES,null,2)+'\n');
49
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'awaiting_review',features:['1.login'],testCases:[]}));
50
+ const file=name=>path.join(feature,name);
51
+ const edit=(name,change)=>fs.writeFileSync(file(name),change(fs.readFileSync(file(name),'utf8')));
52
+ const cli=(entry,args)=>{
53
+ const result=spawnSync(process.execPath,[entry,...args],{encoding:'utf8'});
54
+ return {status:result.status,stderr:result.stderr,json:result.stdout.trim()?JSON.parse(result.stdout.trim().split('\n').at(-1)):null};
55
+ };
56
+ const approve=(extra=[])=>cli(admission,['--specs-dir',specs,'--code-project',code,'--approve','--approval-response','开始',...extra]);
57
+ const inspect=()=>cli(amend,['inspect','--specs-dir',specs]).json;
58
+ const admit=()=>cli(admission,['--specs-dir',specs,'--code-project',code]).json;
59
+ const review=(digest,verdict='approved')=>{
60
+ const target=path.join(root,`review-${Math.random().toString(16).slice(2)}.txt`);
61
+ fs.writeFileSync(target,`审查过程……\n{"cmSpecAmendReview":1,"deltaDigest":"${digest}","verdict":"${verdict}","findings":[]}\n`);
62
+ return target;
63
+ };
64
+ const apply=(args)=>cli(amend,['apply','--specs-dir',specs,'--reason','补正',...args]);
65
+ try{return run({root,specs,code,edit,approve,inspect,admit,review,apply,cli});}
66
+ finally{fs.rmSync(root,{recursive:true,force:true});}
67
+ }
68
+
69
+ const addTask=text=>text.replace('- T-002 依赖 T-001','- [ ] T-003: 修复错误密码提示\n - 范围: `src/api.js`\n - 验收: AC-002\n- T-002 依赖 T-001');
70
+
71
+ test('approval writes a reviewed snapshot; --no-spec-amend records policy off',()=>{
72
+ fixture(({specs,approve})=>{
73
+ const result=approve();assert.equal(result.status,0,result.stderr);
74
+ assert.deepEqual(result.json.specAmend,{policy:'reviewed',files:3,snapshot:'written'});
75
+ const snapshot=JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-approved.json'),'utf8'));
76
+ assert.equal(snapshot.approval.response,'开始');assert.deepEqual(snapshot.amendments,[]);
77
+ });
78
+ fixture(({approve})=>{assert.equal(approve(['--no-spec-amend']).json.specAmend.policy,'off');});
79
+ });
80
+
81
+ test('unchanged specs report nothing to re-bind',()=>fixture(({approve,inspect})=>{
82
+ approve();const result=inspect();assert.equal(result.tier,null);assert.deepEqual(result.changedFiles,[]);
83
+ }));
84
+
85
+ test('tier 0: appended version row re-binds without review or a new 开始',()=>fixture(({approve,inspect,apply,admit,edit})=>{
86
+ approve();
87
+ edit('tasks.md',text=>text.replace('| 2026-11-01 | v1 | 初始 |','| 2026-11-01 | v1 | 初始 |\n| 2026-11-04 | v2 | 范围与验收不变 |'));
88
+ assert.equal(admit().reason,'spec_drift');
89
+ assert.equal(inspect().tier,0);
90
+ const applied=apply([]);assert.equal(applied.status,0,JSON.stringify(applied.json));
91
+ assert.equal(admit().state,'ready');
92
+ }));
93
+
94
+ // Port review #2: re-binding keeps the grammar the approval bound (2 here), never the newest constant.
95
+ test('tier 0 re-bind keeps the approved task grammar',()=>fixture(({specs,approve,inspect,apply,edit})=>{
96
+ approve();
97
+ const grammar=()=>JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'),'utf8')).taskGrammar;
98
+ assert.equal(grammar(),2);
99
+ edit('tasks.md',text=>text.replace('| 2026-11-01 | v1 | 初始 |','| 2026-11-01 | v1 | 初始 |\n| 2026-11-04 | v2 | 范围与验收不变 |'));
100
+ assert.equal(inspect().tier,0);
101
+ assert.equal(apply([]).status,0);
102
+ assert.equal(grammar(),2);
103
+ }));
104
+
105
+ // Port review #1: a version note that weakens an existing task's acceptance is a requirement change.
106
+ test('version row changing an existing task acceptance is tier 2, other acceptance wording goes to review',()=>{
107
+ fixture(({approve,inspect,apply,edit})=>{
108
+ approve();
109
+ edit('tasks.md',text=>text.replace('| 2026-11-01 | v1 | 初始 |','| 2026-11-01 | v1 | 初始 |\n| 2026-11-04 | v2 | T-002 验收要求变更:TC-001 可忽略 |'));
110
+ const result=inspect();
111
+ assert.equal(result.tier,2);assert(result.reasons.includes('version_row_changes_acceptance:1.login/T-002'),JSON.stringify(result.reasons));
112
+ assert.equal(apply([]).status,1);
113
+ });
114
+ fixture(({approve,inspect,edit})=>{
115
+ approve();
116
+ edit('tasks.md',text=>text.replace('| 2026-11-01 | v1 | 初始 |','| 2026-11-01 | v1 | 初始 |\n| 2026-11-04 | v2 | AC-002 改为真机验收 |'));
117
+ assert.equal(inspect().tier,1);
118
+ });
119
+ // Codex review: full-width ids, named AC/TC ids without keywords and unnamed weakening
120
+ // notes never stay tier 0.
121
+ for(const [note,tier] of [['T-002 验收改为只测成功路径',2],['T-002 验收改为只测成功路径',2],
122
+ ['AC-002 验收改为可忽略',1],['AC-002:错误密码由阻断改成提示',1],['TC-001 的断言由 401 调整到 200',1],
123
+ ['验收改为只测成功路径',1],['T-001 文案微调',1],
124
+ // Codex review r2: wording outside any weakening list, English, increases and split ids.
125
+ ['降低验收门槛:错误密码返回 200 也通过',1],['放宽断言:允许任意状态码',1],['只需成功登录',1],['仅测成功路径',1],
126
+ ['跳过错误密码测试',1],['Skip negative tests; accept any HTTP status',1],['加强验收:新增错误密码检查',1],
127
+ ['范围不变,跳过错误密码测试',1],['行为与验收不变',0],['检查与断言不放宽',0],['无其他改动',0],
128
+ // Codex review r3: only a note made entirely of unchanged statements stays tier 0.
129
+ ['补记沟通,无其他改动',1],['范围与验收不变,但失败场景免跑',1],['验收不变式:错误密码返回 200 也通过',1],
130
+ ['并非范围与验收不变,失败场景免跑',1],['错误密码由 401 变成 200',1],['Omit negative scenarios; HTTP 200 is sufficient',1],
131
+ ['范围与验收不变 | 跳过错误密码测试',1],
132
+ // Dogfood (aihot copy): a named existing task with test wording is a requirement change, as in the standing authorization.
133
+ ['T-002 跳过英文断言',2]])
134
+ fixture(({approve,inspect,edit})=>{
135
+ approve();
136
+ edit('tasks.md',text=>text.replace('| 2026-11-01 | v1 | 初始 |',`| 2026-11-01 | v1 | 初始 |\n| 2026-11-04 | v2 | ${note} |`));
137
+ assert.equal(inspect().tier,tier,note);
138
+ });
139
+ // Substance written into the date or version cell is not hidden by a plain description.
140
+ fixture(({approve,inspect,edit})=>{
141
+ approve();
142
+ edit('tasks.md',text=>text.replace('| 2026-11-01 | v1 | 初始 |','| 2026-11-01 | v1 | 初始 |\n| 跳过错误密码测试 | v2 | 范围与验收不变 |'));
143
+ assert.equal(inspect().tier,1);
144
+ });
145
+ // Dogfood (aihot specs7 copy): "范围与验收不变" is how real version rows record an
146
+ // unchanged scope; a note made only of such statements stays tier 0.
147
+ fixture(({approve,inspect,edit})=>{
148
+ approve();
149
+ edit('tasks.md',text=>text.replace('| 2026-11-01 | v1 | 初始 |','| 2026-11-01 | v1 | 初始 |\n| 2026-11-04 | v2 | 范围与验收不变 |'));
150
+ assert.equal(inspect().tier,0);
151
+ });
152
+ });
153
+
154
+ test('tier 0 does not cover edits to an existing version row',()=>fixture(({approve,inspect,edit})=>{
155
+ approve();edit('tasks.md',text=>text.replace('| 初始 |','| 初始(改写) |'));
156
+ assert.equal(inspect().tier,1);
157
+ }));
158
+
159
+ test('tier 1: new task on an existing AC plus wider unfinished scope applies after a bound review',()=>fixture(({root,specs,approve,inspect,apply,admit,edit,review,cli})=>{
160
+ approve();
161
+ edit('tasks.md',text=>addTask(text).replace(' - 范围: `src/login.js`',' - 范围: `src/login.js`, `test/login.test.js`'));
162
+ const inspected=inspect();
163
+ assert.equal(inspected.tier,1,JSON.stringify(inspected));
164
+ assert.deepEqual(inspected.changedTasks,['1.login/T-001']);assert.deepEqual(inspected.newTasks,['1.login/T-003']);
165
+ assert.equal(apply([]).json.refused,'review_output_required');
166
+ const out=path.join(root,'packet');
167
+ const prepared=cli(amend,['prepare','--specs-dir',specs,'--out',out]);
168
+ assert.equal(prepared.status,0,prepared.stderr);
169
+ assert.ok(fs.existsSync(path.join(out,'before/1.login/tasks.md')));assert.ok(fs.existsSync(path.join(out,'after/1.login/tasks.md')));
170
+ assert.match(fs.readFileSync(path.join(out,'review-prompt.md'),'utf8'),new RegExp(inspected.deltaDigest));
171
+ assert.equal(apply(['--review-output',review(inspected.deltaDigest)]).json.refused,'reviewer_required');
172
+ assert.equal(apply(['--review-output',review(inspected.deltaDigest,'changes_requested'),'--reviewer','codex']).json.refused,'review_not_approved');
173
+ assert.equal(apply(['--review-output',review('0'.repeat(64)),'--reviewer','codex']).json.refused,'review_delta_mismatch');
174
+ const applied=apply(['--review-output',review(inspected.deltaDigest),'--reviewer','codex gpt-6.1-sol high']);
175
+ assert.equal(applied.status,0,JSON.stringify(applied.json));
176
+ assert.equal(admit().state,'ready');
177
+ const status=JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'),'utf8'));
178
+ assert.equal(status.approval.response,'开始');
179
+ const snapshot=JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-approved.json'),'utf8'));
180
+ assert.equal(snapshot.amendments.length,1);assert.equal(snapshot.amendments[0].reviewer,'codex gpt-6.1-sol high');
181
+ assert.equal(inspect().tier,null);
182
+ }));
183
+
184
+ test('a review bound to an earlier delta is refused after another edit',()=>fixture(({approve,inspect,apply,edit,review})=>{
185
+ approve();edit('tasks.md',addTask);
186
+ const digest=inspect().deltaDigest;
187
+ edit('tasks.md',text=>text.replace('修复错误密码提示','修复错误密码提示与重试'));
188
+ assert.equal(apply(['--review-output',review(digest),'--reviewer','codex']).json.refused,'review_delta_mismatch');
189
+ }));
190
+
191
+ test('tier 1 also re-binds after a cm-prd style reset to awaiting_review',()=>fixture(({specs,approve,inspect,apply,admit,edit,review})=>{
192
+ approve();edit('tasks.md',addTask);
193
+ const status=JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-status'),'utf8'));
194
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({...status,status:'awaiting_review',approval:null}));
195
+ assert.equal(admit().state,'awaiting_spec_approval');
196
+ const inspected=inspect();assert.equal(inspected.tier,1);
197
+ assert.equal(apply(['--review-output',review(inspected.deltaDigest),'--reviewer','codex']).status,0);
198
+ assert.equal(admit().state,'ready');
199
+ }));
200
+
201
+ const HUMAN=[
202
+ ['requirements changed','requirements.md',text=>text+'- [AC-003] 记住我\n',/^requirements_changed:/],
203
+ ['design changed','design.md',text=>text+'模块 2:新增。\n',/^design_changed:/],
204
+ ['task removed','tasks.md',text=>text.replace(/- \[ \] T-001[\s\S]*?验收: AC-001\n/,'').replace('- T-002 依赖 T-001\n',''),/^task_removed:/],
205
+ ['task dropped','tasks.md',text=>text.replace('- [ ] T-001: 登录页','- [ ] ~~T-001: 登录页~~ `[DROPPED v2]`'),/^task_dropped:/],
206
+ ['new task without acceptance','tasks.md',text=>text.replace('- T-002 依赖','- [ ] T-003: 顺手优化\n- T-002 依赖'),/^new_task_without_acceptance:/],
207
+ ['new task with unknown acceptance','tasks.md',text=>text.replace('- T-002 依赖','- [ ] T-003: 新能力\n - 验收: AC-009\n- T-002 依赖'),/^new_task_unknown_acceptance:/],
208
+ ['new task already completed','tasks.md',text=>text.replace('- T-002 依赖','- [x] T-003: 已做\n - 验收: AC-001\n- T-002 依赖'),/^new_task_completed:/],
209
+ ['unfinished task loses its acceptance link','tasks.md',text=>text.replace(' - 验收: AC-002\n',' - 验收: 无\n'),/^task_acceptance_removed:/],
210
+ ];
211
+ for(const [name,file,change,reason] of HUMAN){
212
+ test(`tier 2: ${name}`,()=>fixture(({approve,inspect,apply,edit})=>{
213
+ approve();edit(file,change);
214
+ const result=inspect();assert.equal(result.tier,2,JSON.stringify(result));
215
+ assert.ok(result.reasons.some(item=>reason.test(item)),JSON.stringify(result.reasons));
216
+ assert.equal(apply([]).json.refused,'spec_amend_needs_human');
217
+ }));
218
+ }
219
+
220
+ test('tier 2: a task completed after approval cannot be rewritten',()=>fixture(({approve,inspect,edit})=>{
221
+ approve();edit('tasks.md',text=>text.replace('- [ ] T-001: 登录页','- [x] T-001: 登录页'));
222
+ assert.equal(inspect().tier,null,'a runtime completion mark alone is not a spec change');
223
+ edit('tasks.md',text=>text.replace(' - 范围: `src/login.js`',' - 范围: `src/login.js`, `src/extra.js`'));
224
+ assert.ok(inspect().reasons.some(item=>item.startsWith('completed_task_changed:')));
225
+ }));
226
+
227
+ test('tier 2: existing test case changed or removed; added case stays tier 1',()=>{
228
+ const edited=change=>fixture(({approve,inspect,edit})=>{approve();edit('test-cases.json',change);return inspect();},{cases:true});
229
+ const modify=edited(text=>text.replace('返回 401','返回 4xx'));
230
+ assert.equal(modify.tier,2);assert.ok(modify.reasons.some(item=>item.startsWith('test_case_changed:')));
231
+ const remove=edited(text=>{const value=JSON.parse(text);value.cases=[];return JSON.stringify(value);});
232
+ assert.equal(remove.tier,2);
233
+ const header=edited(text=>{const value=JSON.parse(text);value.schemaVersion='1.1';return JSON.stringify(value);});
234
+ assert.equal(header.tier,2);assert.ok(header.reasons.some(item=>item.startsWith('test_cases_changed:')));
235
+ const add=edited(text=>{const value=JSON.parse(text);value.cases.push({...value.cases[0],id:'TC-002',origin:'generated',title:'锁定提示'});return JSON.stringify(value);});
236
+ assert.equal(add.tier,1,JSON.stringify(add));
237
+ });
238
+
239
+ test('tier 2: new feature directory, policy off, missing or mismatched snapshot',()=>{
240
+ fixture(({specs,approve,inspect})=>{
241
+ approve();const feature=path.join(specs,'2.logout');fs.mkdirSync(feature);
242
+ for(const file of ['requirements.md','design.md','tasks.md'])fs.copyFileSync(path.join(specs,'1.login',file),path.join(feature,file));
243
+ assert.deepEqual(inspect().reasons,['feature_set_changed']);
244
+ });
245
+ fixture(({approve,inspect,edit})=>{approve(['--no-spec-amend']);edit('tasks.md',addTask);assert.deepEqual(inspect().reasons,['amend_policy_off']);});
246
+ fixture(({specs,approve,inspect,edit})=>{
247
+ approve();edit('tasks.md',addTask);fs.unlinkSync(path.join(specs,'.cm-specs-approved.json'));
248
+ assert.deepEqual(inspect().reasons,['snapshot_missing']);
249
+ });
250
+ fixture(({specs,approve,inspect,edit})=>{
251
+ approve();edit('tasks.md',addTask);
252
+ const target=path.join(specs,'.cm-specs-approved.json'),snapshot=JSON.parse(fs.readFileSync(target,'utf8'));
253
+ // A snapshot synced to the edited bytes by hand fails its own digest.
254
+ snapshot.files=snapshot.files.map(item=>item.path.endsWith('tasks.md')?{...item,content:fs.readFileSync(path.join(specs,item.path),'utf8')}:item);
255
+ fs.writeFileSync(target,JSON.stringify(snapshot));
256
+ assert.deepEqual(inspect().reasons,['snapshot_invalid']);
257
+ });
258
+ });
259
+
260
+ // Review r1 #5: after a cm-prd reset the status no longer anchors the snapshot;
261
+ // a hand-synced snapshot must still not turn a requirements change into tier 0.
262
+ test('awaiting_review: requirements change with a hand-synced snapshot stays tier 2',()=>fixture(({specs,approve,inspect,apply,edit})=>{
263
+ approve();edit('requirements.md',text=>text.replace('错误密码被拒','错误密码可通过'));
264
+ const status=path.join(specs,'.cm-specs-status');
265
+ fs.writeFileSync(status,JSON.stringify({...JSON.parse(fs.readFileSync(status,'utf8')),status:'awaiting_review',approval:null}));
266
+ const target=path.join(specs,'.cm-specs-approved.json'),snapshot=JSON.parse(fs.readFileSync(target,'utf8'));
267
+ snapshot.files=snapshot.files.map(item=>({...item,content:fs.readFileSync(path.join(specs,item.path),'utf8')}));
268
+ fs.writeFileSync(target,JSON.stringify(snapshot));
269
+ assert.deepEqual(inspect().reasons,['snapshot_invalid']);
270
+ assert.equal(apply([]).json.refused,'spec_amend_needs_human');
271
+ }));
272
+
273
+ // Review r1 #4: a snapshot from an earlier approval round never applies to a later one.
274
+ test('a previous round snapshot is rejected and a new approval removes it first',()=>fixture(({specs,approve,inspect,edit})=>{
275
+ approve();
276
+ const target=path.join(specs,'.cm-specs-approved.json'),roundOne=fs.readFileSync(target);
277
+ const status=path.join(specs,'.cm-specs-status');
278
+ fs.writeFileSync(status,JSON.stringify({...JSON.parse(fs.readFileSync(status,'utf8')),status:'awaiting_review',approval:null}));
279
+ const second=approve(['--no-spec-amend']);assert.equal(second.json.specAmend.policy,'off');
280
+ fs.writeFileSync(target,roundOne);
281
+ edit('tasks.md',addTask);
282
+ assert.deepEqual(inspect().reasons,['snapshot_round_mismatch']);
283
+ fs.rmSync(target);fs.mkdirSync(target);fs.writeFileSync(path.join(target,'x'),'');
284
+ fs.writeFileSync(status,JSON.stringify({...JSON.parse(fs.readFileSync(status,'utf8')),status:'awaiting_review',approval:null}));
285
+ const blocked=approve();
286
+ assert.equal(blocked.json.approveRefused,'spec_amend_snapshot_unremovable');
287
+ }));
288
+
289
+ // Review r1 #3: a blank line inside a finished task must not split off its verification.
290
+ test('tier 2: finished task verification after a blank line cannot be weakened',()=>fixture(({approve,inspect,edit})=>{
291
+ edit('tasks.md',text=>text.replace(' - 范围: `src/login.js`\n',' - 范围: `src/login.js`\n\n - 验证: 必须显示错误提示\n'));
292
+ approve();
293
+ edit('tasks.md',text=>text.replace('- [ ] T-001: 登录页','- [x] T-001: 登录页'));
294
+ assert.equal(inspect().tier,null);
295
+ edit('tasks.md',text=>text.replace('必须显示错误提示','可以不显示错误提示'));
296
+ const result=inspect();
297
+ assert.equal(result.tier,2,JSON.stringify(result));
298
+ assert.ok(result.reasons.some(item=>item.startsWith('completed_task_changed:1.login/T-001')));
299
+ }));
300
+
301
+ // Review r1 #2: approval and re-binding are serialized by one lock.
302
+ test('apply refuses while another live process holds the approval lock; a stale lock is replaced',()=>fixture(({specs,approve,inspect,apply,edit,review})=>{
303
+ approve();edit('tasks.md',addTask);
304
+ const lock=path.join(specs,'.cm-specs-approval.lock'),digest=inspect().deltaDigest;
305
+ fs.writeFileSync(lock,JSON.stringify({pid:process.pid,at:new Date().toISOString()}));
306
+ const busy=apply(['--review-output',review(digest),'--reviewer','codex']);
307
+ assert.equal(busy.status,1);assert.match(busy.stderr,/spec_approval_busy/);
308
+ fs.writeFileSync(lock,JSON.stringify({pid:2147483646,at:new Date().toISOString()}));
309
+ assert.equal(apply(['--review-output',review(digest),'--reviewer','codex']).status,0);
310
+ assert.equal(fs.existsSync(lock),false);
311
+ }));
312
+
313
+ // Port review #3: only the reclaim-guard holder deletes another process's lock, so a
314
+ // concurrent reclaimer cannot empty the lock path under a live holder; a holder
315
+ // never releases a lock it does not own; a guard left by a crash blocks reclaim.
316
+ test('stale lock reclaim and release never remove another live owner\'s lock',()=>fixture(({specs})=>{
317
+ const lock=path.join(specs,'.cm-specs-approval.lock'),guard=`${lock}.reclaim`;
318
+ const live=JSON.stringify({pid:process.pid,nonce:'live-owner',at:new Date().toISOString()});
319
+ const dead=JSON.stringify({pid:2147483646,nonce:'dead-owner',at:new Date().toISOString()});
320
+ // Another reclaimer holds the guard: this one neither deletes nor enters.
321
+ fs.writeFileSync(lock,dead);fs.writeFileSync(guard,'other reclaimer');let ran=false;
322
+ assert.throws(()=>withApprovalLock(specs,()=>{ran=true;}),{code:'spec_approval_busy'});
323
+ assert.equal(ran,false);assert.equal(fs.readFileSync(lock,'utf8'),dead);
324
+ // That reclaimer finished and a live owner now holds the lock: still busy, lock untouched.
325
+ fs.unlinkSync(guard);fs.writeFileSync(lock,live);
326
+ assert.throws(()=>withApprovalLock(specs,()=>{ran=true;}),{code:'spec_approval_busy'});
327
+ assert.equal(ran,false);assert.equal(fs.readFileSync(lock,'utf8'),live);assert.equal(fs.existsSync(guard),false);
328
+ // A truly stale lock is reclaimed under the guard; the guard is released.
329
+ fs.writeFileSync(lock,dead);
330
+ withApprovalLock(specs,()=>{ran=true;assert.notEqual(fs.readFileSync(lock,'utf8'),dead);});
331
+ assert.equal(ran,true);assert.equal(fs.existsSync(lock),false);assert.equal(fs.existsSync(guard),false);
332
+ // Release: a lock replaced while held is left in place.
333
+ withApprovalLock(specs,()=>{fs.writeFileSync(lock,live);});
334
+ assert.equal(fs.readFileSync(lock,'utf8'),live);
335
+ // Codex r3: a lock without a readable pid (e.g. a creator paused before writing it)
336
+ // is never reclaimed by age, however old.
337
+ for(const bytes of ['','not json',JSON.stringify({at:'2020-01-01T00:00:00.000Z'})]){
338
+ fs.writeFileSync(lock,bytes);const old=new Date(Date.now()-3600_000);fs.utimesSync(lock,old,old);
339
+ assert.throws(()=>withApprovalLock(specs,()=>{ran=true;}),{code:'spec_approval_busy'});
340
+ assert.equal(fs.readFileSync(lock,'utf8'),bytes);
341
+ }
342
+ // Codex r4: between reading the lock and finding its pid dead, the holder released
343
+ // and a new live holder took the lock. The reclaimer must not delete it or enter.
344
+ {
345
+ const deadPid=2147483645,next=JSON.stringify({pid:process.pid,nonce:'next-owner',at:new Date().toISOString()});
346
+ fs.writeFileSync(lock,JSON.stringify({pid:deadPid,nonce:'released-owner',at:new Date().toISOString()}));
347
+ const kill=process.kill;ran=false;
348
+ process.kill=function(pid,signal){
349
+ if(pid===deadPid){process.kill=kill;fs.unlinkSync(lock);fs.writeFileSync(lock,next);
350
+ throw Object.assign(new Error('ESRCH'),{code:'ESRCH'});}
351
+ return kill.call(this,pid,signal);
352
+ };
353
+ try{assert.throws(()=>withApprovalLock(specs,()=>{ran=true;}),{code:'spec_approval_busy'});}
354
+ finally{process.kill=kill;}
355
+ assert.equal(ran,false);assert.equal(fs.readFileSync(lock,'utf8'),next);assert.equal(fs.existsSync(guard),false);
356
+ }
357
+ // Codex r5: a temp-file cleanup failure after publishing must not leave the lock
358
+ // (or the reclaim guard) behind; once the fault clears the lock is available again.
359
+ for(const reclaim of [false,true]){
360
+ if(reclaim)fs.writeFileSync(lock,JSON.stringify({pid:2147483644,nonce:'dead-for-guard',at:new Date().toISOString()}));
361
+ else if(fs.existsSync(lock))fs.unlinkSync(lock);
362
+ const unlink=fs.unlinkSync,watched=reclaim?`${guard}.`:`${lock}.`;let failed=false;ran=false;
363
+ fs.unlinkSync=function(file,...rest){
364
+ if(!failed&&String(file).startsWith(watched)&&String(file).endsWith('.tmp')&&(reclaim||!String(file).startsWith(`${guard}.`))){
365
+ failed=true;throw Object.assign(new Error('EACCES'),{code:'EACCES'});}
366
+ return unlink.call(this,file,...rest);
367
+ };
368
+ try{assert.throws(()=>withApprovalLock(specs,()=>{ran=true;}),{code:'EACCES'});}
369
+ finally{fs.unlinkSync=unlink;}
370
+ assert.equal(failed,true);assert.equal(ran,false);assert.equal(fs.existsSync(guard),false);
371
+ if(!reclaim)assert.equal(fs.existsSync(lock),false);
372
+ for(const name of fs.readdirSync(specs).filter(item=>item.endsWith('.tmp')))fs.unlinkSync(path.join(specs,name));
373
+ withApprovalLock(specs,()=>{ran=true;});assert.equal(ran,true);assert.equal(fs.existsSync(lock),false);
374
+ }
375
+ // Codex r6: the lock is held by a live owner, so linking fails with EEXIST, and then the
376
+ // temp-file cleanup fails too. The other owner's lock must stay exactly as it was.
377
+ {
378
+ fs.writeFileSync(lock,live);
379
+ const unlink=fs.unlinkSync;let failed=false;ran=false;
380
+ fs.unlinkSync=function(file,...rest){
381
+ if(!failed&&String(file).startsWith(`${lock}.`)&&String(file).endsWith('.tmp')&&!String(file).startsWith(`${guard}.`)){
382
+ failed=true;throw Object.assign(new Error('EACCES'),{code:'EACCES'});}
383
+ return unlink.call(this,file,...rest);
384
+ };
385
+ try{assert.throws(()=>withApprovalLock(specs,()=>{ran=true;}),{code:'EACCES'});}
386
+ finally{fs.unlinkSync=unlink;}
387
+ assert.equal(failed,true);assert.equal(ran,false);
388
+ assert.equal(fs.readFileSync(lock,'utf8'),live);assert.equal(fs.existsSync(guard),false);
389
+ for(const name of fs.readdirSync(specs).filter(item=>item.endsWith('.tmp')))fs.unlinkSync(path.join(specs,name));
390
+ fs.unlinkSync(lock);
391
+ }
392
+ // A lock is visible only with its holder's pid, at its publication: no temp files are left behind.
393
+ assert.equal(fs.existsSync(lock),false);ran=false;
394
+ const link=fs.linkSync;let published=null;
395
+ fs.linkSync=function(from,to,...rest){const result=link.call(this,from,to,...rest);if(to===lock)published=fs.readFileSync(lock,'utf8');return result;};
396
+ try{withApprovalLock(specs,()=>{ran=true;});}finally{fs.linkSync=link;}
397
+ assert.equal(ran,true);assert.equal(JSON.parse(published).pid,process.pid);
398
+ assert.deepEqual(fs.readdirSync(specs).filter(name=>name.startsWith('.cm-specs-approval.lock')),[]);
399
+ }));
400
+
401
+ // Review r1 #1: the packet holds the exact bytes the review digest covers.
402
+ test('prepare packet matches the classified bytes',()=>fixture(({root,specs,approve,inspect,edit,cli})=>{
403
+ // A second, untouched feature must stay out of context/ (review: feature filter had no fixture).
404
+ fs.cpSync(path.join(specs,'1.login'),path.join(specs,'2.signup'),{recursive:true});
405
+ fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'awaiting_review',features:['1.login','2.signup'],testCases:[]}));
406
+ approve();edit('tasks.md',addTask);
407
+ const out=path.join(root,'packet'),prepared=cli(amend,['prepare','--specs-dir',specs,'--out',out]);
408
+ assert.equal(prepared.json.deltaDigest,inspect().deltaDigest);
409
+ assert.equal(fs.readFileSync(path.join(out,'after/1.login/tasks.md'),'utf8'),fs.readFileSync(path.join(specs,'1.login/tasks.md'),'utf8'));
410
+ // Dogfood (wue v4): judging "does not change the approved design" needs the unchanged design.
411
+ for(const name of ['requirements.md','design.md'])
412
+ assert.equal(fs.readFileSync(path.join(out,'context/1.login',name),'utf8'),fs.readFileSync(path.join(specs,'1.login',name),'utf8'));
413
+ assert.equal(fs.existsSync(path.join(out,'context/1.login/tasks.md')),false);
414
+ assert.equal(fs.existsSync(path.join(out,'context/2.signup')),false);
415
+ assert.match(fs.readFileSync(path.join(out,'review-prompt.md'),'utf8'),/context\/ 是涉及的 feature 里没有改动的规格文件/);
416
+ assert.equal(cli(amend,['prepare','--specs-dir',specs,'--out',path.join(specs,'inside')]).status,1);
417
+ }));
418
+
419
+ test('tier 2 after 3 reviewed corrections; a new 开始 resets the count',()=>fixture(({specs,approve,inspect,apply,edit,review})=>{
420
+ approve();
421
+ for(let index=1;index<=3;index++){
422
+ edit('tasks.md',text=>text.replace('- T-002 依赖',`- [ ] T-10${index}: 补修 ${index}\n - 验收: AC-002\n- T-002 依赖`));
423
+ const digest=inspect().deltaDigest;
424
+ assert.equal(apply(['--review-output',review(digest),'--reviewer','codex']).status,0,`round ${index}`);
425
+ }
426
+ edit('tasks.md',text=>text.replace('- T-002 依赖','- [ ] T-104: 补修 4\n - 验收: AC-002\n- T-002 依赖'));
427
+ assert.deepEqual(inspect().reasons,['amend_limit_reached']);
428
+ const status=path.join(specs,'.cm-specs-status');
429
+ fs.writeFileSync(status,JSON.stringify({...JSON.parse(fs.readFileSync(status,'utf8')),status:'awaiting_review',approval:null}));
430
+ assert.equal(approve().status,0);assert.equal(inspect().tier,null);
431
+ }));
432
+
433
+ // Review r2 #2: restoring an older, self-consistent snapshot after a cm-prd reset
434
+ // must not revive its policy; the round file names the current snapshot bytes.
435
+ test('awaiting_review: a restored earlier snapshot does not revive its policy',()=>fixture(({specs,approve,inspect,apply,edit,review})=>{
436
+ approve();
437
+ const target=path.join(specs,'.cm-specs-approved.json'),roundA=fs.readFileSync(target);
438
+ const status=path.join(specs,'.cm-specs-status');
439
+ const reset=()=>fs.writeFileSync(status,JSON.stringify({...JSON.parse(fs.readFileSync(status,'utf8')),status:'awaiting_review',approval:null}));
440
+ reset();assert.equal(approve(['--no-spec-amend']).json.specAmend.policy,'off');
441
+ reset();fs.writeFileSync(target,roundA);edit('tasks.md',addTask);
442
+ const result=inspect();assert.equal(result.tier,2);assert.deepEqual(result.reasons,['snapshot_round_mismatch']);
443
+ assert.equal(apply(['--review-output',review('0'.repeat(64)),'--reviewer','codex']).json.refused,'spec_amend_needs_human');
444
+ }));
445
+
446
+ // Review r2 #1: an approval decided before another approval landed is refused under the lock.
447
+ test('approval decided before a concurrent approval is refused and keeps the newer policy',()=>fixture(({specs,code,cli})=>{
448
+ const outcome=approveCmAiSpecs({specsDir:specs,codeProject:code,codeProjects:[code],approvalResponse:'开始',
449
+ _beforeApprovalLock:()=>{
450
+ const other=cli(admission,['--specs-dir',specs,'--code-project',code,'--approve','--approval-response','开始','--no-spec-amend']);
451
+ assert.equal(other.status,0,other.stderr);
452
+ }});
453
+ assert.equal(outcome.approveRefused,'spec_status_changed_during_approval');
454
+ assert.equal(JSON.parse(fs.readFileSync(path.join(specs,'.cm-specs-approved.json'),'utf8')).policy,'off');
455
+ }));
456
+
457
+ // Review r3 #1: restoring both an older snapshot and an older ledger-free specs
458
+ // backup cannot revive a round the user has since replaced with --no-spec-amend.
459
+ test('awaiting_review: restoring an older specs backup does not revive its round',()=>fixture(({specs,approve,inspect,apply,edit})=>{
460
+ approve();
461
+ const target=path.join(specs,'.cm-specs-approved.json'),roundA=fs.readFileSync(target);
462
+ const status=path.join(specs,'.cm-specs-status');
463
+ const reset=()=>fs.writeFileSync(status,JSON.stringify({...JSON.parse(fs.readFileSync(status,'utf8')),status:'awaiting_review',approval:null}));
464
+ reset();assert.equal(approve(['--no-spec-amend']).json.specAmend.policy,'off');
465
+ reset();fs.writeFileSync(target,roundA);
466
+ assert.deepEqual(inspect().reasons,['snapshot_round_mismatch']);
467
+ assert.equal(apply([]).json.refused,'spec_amend_needs_human');
468
+ edit('tasks.md',addTask);assert.equal(inspect().tier,2);
469
+ }));
470
+
471
+ // Review r3 #2: a failed snapshot write during apply leaves no valid round, even after a reset.
472
+ test('a failed apply snapshot write stays tier 2 after a cm-prd reset',()=>fixture(({specs,approve,inspect,edit,review})=>{
473
+ approve();edit('tasks.md',addTask);
474
+ const digest=inspect().deltaDigest,original=fs.renameSync;
475
+ // Inject one failure into the snapshot's final rename, after status was written.
476
+ fs.renameSync=(from,to)=>{
477
+ if(String(to).endsWith('.cm-specs-approved.json')){fs.renameSync=original;throw Object.assign(new Error('EACCES'),{code:'EACCES'});}
478
+ return original(from,to);
479
+ };
480
+ try{
481
+ assert.throws(()=>applySpecAmendment(specs,{reason:'补正',reviewOutput:fs.readFileSync(review(digest),'utf8'),reviewer:'codex'}),/EACCES/);
482
+ }finally{fs.renameSync=original;}
483
+ const status=path.join(specs,'.cm-specs-status');
484
+ assert.equal(JSON.parse(fs.readFileSync(status,'utf8')).status,'approved');
485
+ assert.deepEqual(inspect().reasons,['snapshot_round_missing']);
486
+ fs.writeFileSync(status,JSON.stringify({...JSON.parse(fs.readFileSync(status,'utf8')),status:'awaiting_review',approval:null}));
487
+ edit('tasks.md',text=>text.replace('- T-002 依赖','- [ ] T-009: 再补\n - 验收: AC-001\n- T-002 依赖'));
488
+ assert.deepEqual(inspect().reasons,['snapshot_round_missing']);
489
+ }));
490
+
491
+ // A new approval voids the previous round before writing; if its own snapshot write
492
+ // then fails, restoring the previous round's snapshot must not revive that round.
493
+ test('a failed approval snapshot write leaves no round to restore',()=>fixture(({specs,code,approve,inspect,edit})=>{
494
+ approve();
495
+ const target=path.join(specs,'.cm-specs-approved.json'),roundA=fs.readFileSync(target);
496
+ const status=path.join(specs,'.cm-specs-status');
497
+ const reset=()=>fs.writeFileSync(status,JSON.stringify({...JSON.parse(fs.readFileSync(status,'utf8')),status:'awaiting_review',approval:null}));
498
+ reset();
499
+ const original=fs.renameSync;
500
+ fs.renameSync=(from,to)=>{
501
+ if(String(to).endsWith('.cm-specs-approved.json')){fs.renameSync=original;throw Object.assign(new Error('EACCES'),{code:'EACCES'});}
502
+ return original(from,to);
503
+ };
504
+ let outcome;
505
+ try{outcome=approveCmAiSpecs({specsDir:specs,codeProject:code,codeProjects:[code],approvalResponse:'开始',specAmend:false});}
506
+ finally{fs.renameSync=original;}
507
+ assert.equal(outcome.specAmend.snapshot,'failed');
508
+ reset();fs.writeFileSync(target,roundA);edit('tasks.md',addTask);
509
+ assert.deepEqual(inspect().reasons,['snapshot_round_missing']);
510
+ }));
@@ -13,6 +13,12 @@ import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
13
13
  import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
14
14
  import {recordPrdHostDisposition} from '../runtime/js/cm-prd/review-disposition.mjs';
15
15
  import {createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
16
+ // Spec approvals write a round ledger under CM_WORKFLOW_HOME; keep it off the real home.
17
+ if(!process.env.CM_WORKFLOW_HOME){
18
+ const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-approval-home-'));
19
+ process.env.CM_WORKFLOW_HOME=isolatedHome;
20
+ process.on('exit',()=>fs.rmSync(isolatedHome,{recursive:true,force:true}));
21
+ }
16
22
  const entry=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
17
23
  const at='2026-09-18T00:00:00.000Z';
18
24
  const keys=['status','summaryDigest','at','features','specFiles','testCases','approval'];