@aibyzero/cm-workflow 0.21.1 → 0.21.3

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 (72) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +19 -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 +6 -1
  7. package/package.json +1 -1
  8. package/runtime/js/cm-ai/call-timeout.mjs +21 -0
  9. package/runtime/js/cm-ai/checkpoint-package-material.mjs +3 -2
  10. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +5 -1
  11. package/runtime/js/cm-ai/codex-config.mjs +6 -1
  12. package/runtime/js/cm-ai/durable-runner-state.mjs +19 -4
  13. package/runtime/js/cm-ai/fix-code-association.mjs +5 -5
  14. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -15
  15. package/runtime/js/cm-ai/host-documentation.mjs +4 -3
  16. package/runtime/js/cm-ai/host-handoff.mjs +3 -2
  17. package/runtime/js/cm-ai/host-project-execution.mjs +11 -9
  18. package/runtime/js/cm-ai/host-qa-executor.mjs +3 -2
  19. package/runtime/js/cm-ai/host-replay.mjs +28 -8
  20. package/runtime/js/cm-ai/review-package.mjs +101 -33
  21. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  22. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  23. package/runtime/js/cm-ai/spec-amendment.mjs +20 -0
  24. package/runtime/js/cm-ai/symlink-material.mjs +153 -0
  25. package/runtime/js/cm-ai/task-commit.mjs +6 -3
  26. package/runtime/js/cm-ai/task-runner.mjs +14 -6
  27. package/runtime/js/cm-ai/worker-claude-developer.mjs +19 -7
  28. package/runtime/js/cm-ai/worker-codex-developer.mjs +3 -1
  29. package/runtime/js/cm-fix/protected-edits.mjs +57 -36
  30. package/runtime/js/cm-prd/change.mjs +4 -1
  31. package/runtime/js/cm-prd/review-findings.mjs +3 -2
  32. package/runtime/js/cm-prd/review-publication.mjs +3 -2
  33. package/runtime/js/cm-prd/split-design.mjs +4 -4
  34. package/scripts/ci-test-weights.json +1 -0
  35. package/scripts/cm-ai-admission.test.mjs +5 -5
  36. package/scripts/cm-ai-batch-drive.mjs +9 -5
  37. package/scripts/cm-ai-call-timeout.test.mjs +85 -0
  38. package/scripts/cm-ai-control-launch.test.mjs +18 -0
  39. package/scripts/cm-ai-drive.mjs +142 -43
  40. package/scripts/cm-ai-host.mjs +15 -3
  41. package/scripts/cm-ai-host.test.mjs +3 -1
  42. package/scripts/cm-ai-launch-diagnostics.test.mjs +23 -0
  43. package/scripts/cm-ai-review-failure.test.mjs +3 -0
  44. package/scripts/cm-ai-run.mjs +2 -1
  45. package/scripts/cm-ai-scope-revision.test.mjs +35 -3
  46. package/scripts/cm-ai-supersede.test.mjs +51 -3
  47. package/scripts/cm-ai-symlink.test.mjs +481 -0
  48. package/scripts/cm-codex-developer-worker.test.mjs +13 -1
  49. package/scripts/cm-notify-command.test.mjs +3 -0
  50. package/scripts/cm-notify.test.mjs +3 -0
  51. package/scripts/cm-patrol.test.mjs +3 -0
  52. package/scripts/cm-prd-design-phase.test.mjs +31 -0
  53. package/scripts/cm-prd-review-gate.mjs +28 -3
  54. package/scripts/cm-prd-summary.test.mjs +5 -5
  55. package/scripts/cm-skill-hints.mjs +40 -16
  56. package/scripts/cm-skill-hints.test.mjs +91 -0
  57. package/scripts/cm-spec-amend.test.mjs +107 -1
  58. package/scripts/cm-specs-status.test.mjs +5 -5
  59. package/scripts/cm-start-check.mjs +53 -15
  60. package/scripts/cm-start-check.test.mjs +41 -2
  61. package/scripts/cm-task-gate.mjs +42 -13
  62. package/scripts/cm-task-gate.test.mjs +33 -0
  63. package/scripts/cm-tool-preview-context.test.mjs +20 -1
  64. package/scripts/cm-upgrade-compat.test.mjs +7 -0
  65. package/skills/cm-ai/references/js-host.md +1 -0
  66. package/skills/cm-prd/SKILL.md +14 -27
  67. package/skills/cm-prd/references/change-mode.md +2 -0
  68. package/skills/cm-prd/references/cm-optout.md +11 -0
  69. package/skills/cm-prd/references/context-scope.md +2 -1
  70. package/skills/cm-prd/references/js-host.md +2 -2
  71. package/skills/cm-prd/references/requirement-grilling.md +116 -0
  72. package/skills/cm-product-manager/SKILL.md +13 -1
@@ -0,0 +1,481 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {createHash} from 'node:crypto';
7
+ import {spawnSync} from 'node:child_process';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {captureReviewBaseline,createReviewPackage,projectedReviewPackage,readReviewBaseline,readReviewPackage,
10
+ captureScopeRevisionSources,extendReviewBaseline,verifyCompletionReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
11
+ import {digest,JOURNAL_PAYLOAD_LIMIT,requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+ import {checkpointStoragePlan,resolveCheckpointPackage} from '../runtime/js/cm-ai/checkpoint-package-material.mjs';
13
+ import {buildManifest} from './cm-spec-manifest.mjs';
14
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
15
+ import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
16
+ import {captureBeforeSnapshot,replayDelivery} from '../runtime/js/cm-ai/host-replay.mjs';
17
+ import {withHostDocumentation} from '../runtime/js/cm-ai/host-documentation.mjs';
18
+ import {createProjectExecution} from '../runtime/js/cm-ai/host-project-execution.mjs';
19
+ import {applyProtectedEdits,captureProtectedEdits} from '../runtime/js/cm-fix/protected-edits.mjs';
20
+ import {applyDevelopEdits,developPreview,plannedCheckResults,preflightDevelopDeliveries,projectDevelopCheckpoint,
21
+ protectedDevelopEdits} from './cm-ai-drive.mjs';
22
+ import {implementationSha256} from './cm-task-gate.mjs';
23
+
24
+ const identity={repositoryId:'repo',runId:'symlink-test',taskId:'T-001',attempt:1};
25
+ const checks=[{id:'check',command:['check'],outcome:'passed',exitCode:0,evidence:'passed'}];
26
+ const link='mods/mgt-pipeline/lib';
27
+ const hash=target=>createHash('sha256').update('symlink\0').update(target).digest('hex');
28
+ function project(t){
29
+ const top=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-symlink-test-')));
30
+ t.after(()=>fs.rmSync(top,{recursive:true,force:true}));
31
+ const cwd=path.join(top,'code'),answers=path.join(top,'answers'),specsRoot=path.join(cwd,'specs');
32
+ for(const dir of ['mods/mgt-pipeline','lib','lib-next','specs','.git','.reviews'])fs.mkdirSync(path.join(cwd,dir),{recursive:true});
33
+ fs.mkdirSync(answers);
34
+ fs.writeFileSync(path.join(cwd,'lib/file'),'internal');
35
+ fs.writeFileSync(path.join(cwd,'note'),'before');
36
+ fs.writeFileSync(path.join(answers,'content'),'replacement');
37
+ const outside=path.join(top,'outside');
38
+ fs.writeFileSync(outside,'outside sentinel');
39
+ const capture=(scope=[link,'note'],version=3)=>captureReviewBaseline({root:cwd,identity,scope,
40
+ requirements:['lib/file'],specsRoot,version},true);
41
+ const set=(target,p=link)=>fs.symlinkSync(target,path.join(cwd,p));
42
+ return {cwd,answers,specsRoot,outside,capture,set};
43
+ }
44
+ const record=(target,p=link)=>({path:p,type:'symlink',target,size:Buffer.byteLength(target),sha256:hash(target)});
45
+ const delivery=(edits,file='develop.json')=>({file,value:{status:'succeeded',edits}});
46
+ function preflight(f,scope,deliveries,options={}){
47
+ const inputs={deliveries,answersRoot:f.answers,codeProject:f.cwd,specsRoot:f.specsRoot,scope,
48
+ requirements:[],preview:{baseline:{version:3},material:[],exact:false},...options};
49
+ return spawnSync(process.execPath,['--input-type=module','-e',
50
+ `const [inputs]=process.argv.splice(1);
51
+ const {preflightDevelopDeliveries}=await import(${JSON.stringify(new URL('./cm-ai-drive.mjs',import.meta.url).href)});
52
+ preflightDevelopDeliveries(JSON.parse(inputs));`,JSON.stringify(inputs)],{encoding:'utf8',timeout:15000});
53
+ }
54
+
55
+ test('v3 captures links as metadata without opening referents and v2 still rejects them',t=>{
56
+ const {cwd,outside,set,capture}=project(t);
57
+ set('../../lib');set(outside,'outside');set('missing','dangling');set(link,'chain');
58
+ const open=fs.openSync;
59
+ t.mock.method(fs,'openSync',(file,...args)=>{
60
+ assert(![outside,path.join(cwd,'outside'),path.join(cwd,link,'file')].includes(file));
61
+ return open(file,...args);
62
+ });
63
+ const baseline=capture();
64
+ assert.deepEqual(baseline.files.filter(f=>f.type==='symlink'),[record(link,'chain'),record('missing','dangling'),record('../../lib'),record(outside,'outside')]);
65
+ assert(!baseline.files.some(f=>f.path.startsWith(link+'/')));
66
+ assert.deepEqual(readReviewBaseline(baseline),baseline);
67
+ assert.throws(()=>capture(undefined,2),{code:'unsupported_file'});
68
+ const {baselineDigest,symlinkPolicy,...old}={...baseline,version:2};
69
+ assert.throws(()=>readReviewBaseline({...old,baselineDigest:digest(old)}),{code:'invalid_baseline'});
70
+ });
71
+
72
+ test('review binds target, type, untouched scope, and extended scope; projected and real packages agree',t=>{
73
+ const {cwd,set,capture}=project(t);
74
+ set('../../lib');set('missing','dangling');
75
+ const baseline=capture(),scope=[...baseline.scope,'dangling'];
76
+ const extended=extendReviewBaseline(baseline,scope,captureScopeRevisionSources(cwd,baseline,scope));
77
+ fs.writeFileSync(path.join(cwd,'note'),'after');
78
+ let pkg=createReviewPackage({root:cwd,baseline:extended,checks});
79
+ assert.equal(pkg.version,2);
80
+ assert.deepEqual(pkg.unchangedScope,[record('missing','dangling'),record('../../lib')]);
81
+ const projected=projectedReviewPackage({root:cwd,baseline:extended,checks,scopeFiles:[{path:link,symlink:'../../lib-next'}]});
82
+ fs.unlinkSync(path.join(cwd,link));set('../../lib-next');
83
+ pkg=createReviewPackage({root:cwd,baseline:extended,checks});
84
+ assert.deepEqual(projected,pkg);
85
+ assert.deepEqual(readReviewPackage(pkg),pkg);
86
+ assert.deepEqual(pkg.changes.find(c=>c.path===link),{path:link,before:record('../../lib'),after:record('../../lib-next')});
87
+ const {packageDigest,symlinkPolicy,...old}={...pkg,version:1};
88
+ assert.throws(()=>readReviewPackage({...old,packageDigest:digest(old)}),{code:'invalid_package'});
89
+ assert.throws(()=>createReviewPackage({root:cwd,baseline:extended,checks,
90
+ handoffPath:path.join(cwd,link)}),{code:'unsupported_file'});
91
+ fs.unlinkSync(path.join(cwd,link));
92
+ fs.writeFileSync(path.join(cwd,link),'../../lib-next');
93
+ assert.equal(createReviewPackage({root:cwd,baseline:extended,checks}).changes.find(c=>c.path===link).after.type,'file');
94
+ assert.throws(()=>verifyCompletionReviewPackage({root:cwd,baseline:extended,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}),{code:'package_mismatch'});
95
+ fs.unlinkSync(path.join(cwd,'dangling'));set('elsewhere','dangling');
96
+ assert.throws(()=>createReviewPackage({root:cwd,baseline,checks}),{code:'out_of_scope'});
97
+ });
98
+
99
+ test('protected and driver edits share link fingerprints across create, retarget and delete',t=>{
100
+ const {cwd,specsRoot,answers}=project(t);
101
+ const scope=[link];
102
+ for(const [before,target] of [[null,'../../lib'],['../../lib','../../lib-next'],['../../lib-next',null]]){
103
+ const expected=captureProtectedEdits(cwd,scope,{allowSymlinks:true});
104
+ const map={[link]:target===null?{delete:true}:{symlink:target}};
105
+ const edits=protectedDevelopEdits(map,answers,cwd,expected,{allowSymlinks:true,specsRoot});
106
+ assert.deepEqual(edits,[{path:link,beforeSha256:before===null?null:hash(before),...(target===null?{content:null}:{symlink:target})}]);
107
+ applyProtectedEdits({cwd,scope,edits,allowSymlinks:true,specsRoot});
108
+ assert.equal(captureProtectedEdits(cwd,scope,{allowSymlinks:true})[link],target===null?null:hash(target));
109
+ }
110
+ applyDevelopEdits({[link]:{symlink:'../../lib'}},answers,cwd,scope,{allowSymlinks:true,specsRoot});
111
+ assert.equal(fs.readlinkSync(path.join(cwd,link)),'../../lib');
112
+ });
113
+
114
+ test('target validation rejects unsafe edits before writes and driver preflight and apply agree',async t=>{
115
+ const fixture=project(t),{cwd,specsRoot,answers,outside,set}=fixture;
116
+ set('../lib','mods/alias');
117
+ fs.symlinkSync(path.dirname(outside),path.join(cwd,'parent'));
118
+ const options={allowSymlinks:true,specsRoot};
119
+ const apply=(target,edit)=>applyProtectedEdits({cwd,scope:[target],edits:[{path:target,beforeSha256:null,...edit}],...options});
120
+ const unsafe={absolute:outside,escape:'../../../outside',git:'../../.git',specs:'../../specs',reviews:'../../.reviews',
121
+ dangling:'../../missing',chain:'../alias',hiddenChain:'../alias/../mgt-pipeline',empty:'',nul:'a\0b',tooLong:'a'.repeat(1025)};
122
+ for(const [name,target] of Object.entries(unsafe))await t.test(name,subtest=>{
123
+ subtest.after(()=>fs.rmSync(path.join(cwd,link),{force:true}));
124
+ const map={[link]:{symlink:target}},error={code:'invalid_symlink_target'};
125
+ assert.throws(()=>apply(link,{symlink:target}),error);
126
+ const result=preflight(fixture,[link],[delivery(map)]);
127
+ assert.equal(result.status,2,result.stderr);
128
+ assert.match(result.stderr,/invalid_symlink_target/);
129
+ assert.throws(()=>applyDevelopEdits(map,answers,cwd,[link],options),error);
130
+ assert.equal(fs.existsSync(path.join(cwd,link)),false);
131
+ });
132
+ assert.throws(()=>apply('parent/outside',{content:'modified'}),{code:'unsupported_path'});
133
+ assert.throws(()=>applyProtectedEdits({cwd,scope:['new','new/file'],edits:[
134
+ {path:'new',beforeSha256:null,symlink:'lib'},{path:'new/file',beforeSha256:null,content:'text'}],...options}),{code:'unsupported_path'});
135
+ assert.equal(fs.existsSync(path.join(cwd,'new')),false);
136
+ set('../../lib');
137
+ for(const edit of [{content:'text'},{content:'text',mode:'0755'}]){
138
+ assert.throws(()=>applyProtectedEdits({cwd,scope:[link],edits:[{path:link,beforeSha256:hash('../../lib'),...edit}],...options}),{code:'unsupported_path'});
139
+ }
140
+ assert.throws(()=>applyDevelopEdits({[link]:{mode:'0755'}},answers,cwd,[link],options),{code:'unsupported_path'});
141
+ assert.throws(()=>applyDevelopEdits({[link]:{symlink:'../../lib-next',mode:'0755'}},answers,cwd,[link],options),
142
+ /只允许单独的 symlink/);
143
+ const value={status:'succeeded',edits:{[link]:{symlink:'../../lib-next'}}};
144
+ const preview={baseline:{version:3},material:[],exact:false};
145
+ preflightDevelopDeliveries({deliveries:[{file:'develop.json',value}],answersRoot:answers,codeProject:cwd,
146
+ scope:[link],requirements:[],preview,specsRoot,protectedMode:true});
147
+ assert.equal(fs.readlinkSync(path.join(cwd,link)),'../../lib');
148
+ assert.equal(fs.readFileSync(outside,'utf8'),'outside sentinel');
149
+ });
150
+
151
+ test('symlink target validation rejects root underflow even when clamping would find a directory',async t=>{
152
+ const localPath='mods/a/lib',symlink='../../../lib',error={code:'invalid_symlink_target'};
153
+ for(const multipleRoots of [false,true])await t.test(multipleRoots?'multiple code roots':'single code root',async scenario=>{
154
+ const linkPath=multipleRoots?`lib-next/${localPath}`:localPath;
155
+ const codeProjectPaths=multipleRoots?['lib','lib-next']:undefined;
156
+ const scope=[linkPath],edits={[linkPath]:{symlink}};
157
+ function setup(subtest){
158
+ const fixture=project(subtest),{cwd,specsRoot}=fixture;
159
+ const codeRoot=multipleRoots?path.join(cwd,'lib-next'):cwd;
160
+ const codeProjects=codeProjectPaths?.map(prefix=>path.join(cwd,prefix));
161
+ fs.mkdirSync(path.join(codeRoot,'mods/a'),{recursive:true});
162
+ if(multipleRoots){
163
+ fs.mkdirSync(path.join(codeRoot,'lib'));
164
+ assert.equal(path.resolve(cwd,path.dirname(linkPath),symlink),path.join(cwd,'lib'));
165
+ assert.equal(fs.statSync(path.join(cwd,'lib')).isDirectory(),true);
166
+ }
167
+ assert.equal(fs.statSync(path.join(codeRoot,'lib')).isDirectory(),true);
168
+ return {...fixture,codeRoot,options:{allowSymlinks:true,specsRoot,codeProjects}};
169
+ }
170
+ await scenario.test('preflight',subtest=>{
171
+ const fixture=setup(subtest);
172
+ const result=preflight(fixture,scope,[delivery(edits)],fixture.options);
173
+ assert.equal(result.status,2,result.stderr);
174
+ assert.match(result.stderr,/\binvalid_symlink_target\b/);
175
+ });
176
+ await scenario.test('applyDevelopEdits',subtest=>{
177
+ const {cwd,answers,options}=setup(subtest);
178
+ assert.throws(()=>applyDevelopEdits(edits,answers,cwd,scope,options),error);
179
+ assert.equal(fs.lstatSync(path.join(cwd,linkPath),{throwIfNoEntry:false}),undefined);
180
+ });
181
+ await scenario.test('applyProtectedEdits',subtest=>{
182
+ const {cwd,codeRoot,specsRoot}=setup(subtest);
183
+ assert.throws(()=>applyProtectedEdits({cwd:codeRoot,specsRoot,allowSymlinks:true,scope:[localPath],
184
+ edits:[{path:localPath,beforeSha256:null,symlink}]}),error);
185
+ assert.equal(fs.lstatSync(path.join(cwd,linkPath),{throwIfNoEntry:false}),undefined);
186
+ });
187
+ await scenario.test('review package assembly',subtest=>{
188
+ const {cwd,specsRoot,set}=setup(subtest);
189
+ const baseline=captureReviewBaseline({root:cwd,identity,scope,requirements:['lib/file'],
190
+ specsRoot,version:3,...(multipleRoots?{codeProjectPaths}:{})},true);
191
+ set(symlink,linkPath);
192
+ assert.throws(()=>createReviewPackage({root:cwd,baseline,checks}),error);
193
+ });
194
+ });
195
+ });
196
+
197
+ test('v2 driver preflight and both develop adapters reject a symlink answer',async t=>{
198
+ const f=project(t),scope=[link],edits={[link]:{symlink:'../../lib'}};
199
+ const options={allowSymlinks:false,specsRoot:f.specsRoot};
200
+ const refused=/当前运行的基线版本不支持.*软链/;
201
+ await t.test('preflight',()=>{
202
+ const result=preflight(f,scope,[delivery(edits)],{preview:{baseline:{version:2},material:[],exact:false}});
203
+ assert.equal(result.status,2,result.stderr);
204
+ assert.match(result.stderr,refused);
205
+ });
206
+ await t.test('protectedDevelopEdits',()=>{
207
+ assert.throws(()=>protectedDevelopEdits(edits,f.answers,f.cwd,{[link]:null},options),refused);
208
+ });
209
+ await t.test('applyDevelopEdits',()=>{
210
+ assert.throws(()=>applyDevelopEdits(edits,f.answers,f.cwd,scope,options),refused);
211
+ });
212
+ assert.equal(fs.existsSync(path.join(f.cwd,link)),false);
213
+ });
214
+
215
+ test('driver preflight uses completed earlier deliveries to resolve second-round link targets',t=>{
216
+ const f=project(t),target='src/new.js',alias='lib/n',scope=[target,alias];
217
+ const baseline=f.capture(scope);
218
+ const first=delivery({[target]:'content'}),second=delivery({[alias]:{symlink:'../src/new.js'}},'develop-a2.json');
219
+ const result=preflight(f,scope,[first,second]);
220
+ assert.equal(result.status,0,result.stderr);
221
+ assert.equal(fs.existsSync(path.join(f.cwd,target)),false);
222
+ const projected=projectedReviewPackage({root:f.cwd,baseline,checks,scopeFiles:[
223
+ {path:target,contentBase64:fs.readFileSync(path.join(f.answers,'content'),'base64'),mode:0o644},
224
+ {path:alias,symlink:'../src/new.js'}]});
225
+ for(const {value} of [first,second])applyDevelopEdits(value.edits,f.answers,f.cwd,scope,{allowSymlinks:true,specsRoot:f.specsRoot});
226
+ assert.equal(fs.readlinkSync(path.join(f.cwd,alias)),'../src/new.js');
227
+ assert.deepEqual(projected,createReviewPackage({root:f.cwd,baseline,checks}));
228
+ const removed=preflight(f,scope,[delivery({[target]:{delete:true}}),second]);
229
+ assert.equal(removed.status,2,removed.stderr);
230
+ assert.match(removed.stderr,/develop-a2\.json.*invalid_symlink_target/);
231
+ });
232
+
233
+ test('driver reports unsupported disk scope entries as Chinese preflight errors',async t=>{
234
+ const f=project(t);f.set('lib','alias');f.set('lib','bad');
235
+ for(const [file,code,reason] of [['alias/file','unsupported_path',/父级经过软链/],['bad','unsupported_file',/UTF-8/]])await t.test(file,()=>{
236
+ // Inject raw readlink bytes so the non-UTF-8 case also runs on filesystems
237
+ // that refuse to create a link with those target bytes.
238
+ const result=spawnSync(process.execPath,['--input-type=module','-e',
239
+ `import fs from 'node:fs';
240
+ import {preflightDevelopDeliveries} from ${JSON.stringify(new URL('./cm-ai-drive.mjs',import.meta.url).href)};
241
+ const [cwd,answers,file]=process.argv.slice(1);
242
+ if(file==='bad'){
243
+ const readlink=fs.readlinkSync;
244
+ fs.readlinkSync=(p,...args)=>p===cwd+'/bad'?Buffer.from([255,255,255]):readlink(p,...args);
245
+ }
246
+ preflightDevelopDeliveries({codeProject:cwd,answersRoot:answers,scope:[file],requirements:[],
247
+ deliveries:[{file:'develop.json',value:{status:'succeeded',edits:{[file]:'content'}}}],allowSymlinks:true});`,
248
+ f.cwd,f.answers,file],{encoding:'utf8',timeout:15000});
249
+ assert.equal(result.status,2,result.stderr);
250
+ assert.match(result.stderr,/无法读取.*范围/);
251
+ assert.ok(result.stderr.includes(file));assert.ok(result.stderr.includes(code));
252
+ assert.match(result.stderr,reason);
253
+ assert.doesNotMatch(result.stderr,/\n\s+at /);
254
+ });
255
+ });
256
+
257
+ test('legacy batch preflight still sizes protected chmod against the existing file',t=>{
258
+ const f=project(t);
259
+ fs.writeFileSync(path.join(f.cwd,'note'),'text'.repeat(2048));
260
+ const deliveries=[delivery({note:{mode:'0755'}})];
261
+ const options={diskChecks:false,protectedMode:true,inputLimit:4096};
262
+ const old=preflight(f,['note'],deliveries,{...options,allowSymlinks:false});
263
+ assert.equal(old.status,2,old.stderr);
264
+ assert.match(old.stderr,/受保护模式下的应答.*超过宿主输入上限 4096/);
265
+ const current=preflight(f,['note'],deliveries,{...options,allowSymlinks:true});
266
+ assert.equal(current.status,0,current.stderr);
267
+ });
268
+
269
+ test('multi-root protected precheck rejects a link into a sibling before any root writes',async t=>{
270
+ const f=project(t),codeProjects=['lib','lib-next'].map(file=>path.join(f.cwd,file));
271
+ const execution=createProjectExecution({definition:{codeProject:f.cwd,specsDir:f.specsRoot,codeProjects},
272
+ protection:{timeoutMs:5000,checkCommands:codeProjects.map((codeProject,i)=>({
273
+ id:`check-${i}`,codeProject,command:[process.execPath,'-e','0']}))}});
274
+ const scope=['lib/file','lib-next/n'],expected=execution.expected(scope,true);
275
+ const edits=[{path:'lib/file',beforeSha256:expected['lib/file'],content:'new bytes'},
276
+ {path:'lib-next/n',beforeSha256:null,symlink:'../lib/file'}];
277
+ let invoked=false;
278
+ await assert.rejects(execution.commit({scope,edits,expected,identity,allowSymlinks:true,
279
+ signal:new AbortController().signal,onApply:()=>{invoked=true;}}),{code:'invalid_symlink_target'});
280
+ assert.equal(invoked,false);
281
+ assert.equal(fs.readFileSync(path.join(f.cwd,'lib/file'),'utf8'),'internal');
282
+ assert.equal(fs.existsSync(path.join(f.cwd,'lib-next/n')),false);
283
+ });
284
+
285
+ test('documentation fallback snapshots honor the v3 link flag and see an out-of-scope retarget',async t=>{
286
+ const f=project(t),feature='1.docs',scope=['README.md'];
287
+ const featureDir=path.join(f.specsRoot,feature);
288
+ fs.mkdirSync(featureDir);
289
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(featureDir,name),'# Fixture\n');
290
+ fs.writeFileSync(path.join(featureDir,'tasks.md'),'- [ ] T-001: fixture\n');
291
+ fs.writeFileSync(path.join(f.specsRoot,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature]}));
292
+ f.set('../../lib');
293
+ const request=requestFor({invocationId:'docs',identity,role:'developer',provider:'codex',requestedModel:'fixture',
294
+ contextId:'author',payload:{scope,requirements:[{path:'lib/file'}],priorReview:null}});
295
+ const developer={provider:'codex',requestedModel:'fixture',contextId:'author',run:async()=>({
296
+ version:1,invocationId:'docs',contextId:'author',provider:'codex',effectiveModel:'fixture',
297
+ status:'succeeded',accepted:true,result:{outcome:'implemented'}})};
298
+ let syncCalls=0;
299
+ const adapter=withHostDocumentation({developer,specsDir:f.specsRoot,codeProject:f.cwd,feature,scope,
300
+ documentationSync:{paths:scope,run:async()=>{
301
+ syncCalls++;
302
+ fs.unlinkSync(path.join(f.cwd,link));f.set('../../lib-next');
303
+ return {status:'completed'};
304
+ }}});
305
+ const signal=new AbortController().signal;
306
+ await assert.rejects(adapter.run(request,{signal}),{code:'unsupported_file'});
307
+ assert.equal(syncCalls,0);
308
+ await assert.rejects(adapter.run(request,{signal,allowSymlinks:true}),{code:'out_of_scope',message:`out_of_scope: ${link}`});
309
+ assert.equal(syncCalls,1);
310
+ });
311
+
312
+ test('replay restores link text for baseline and red and checks no link points back to the original',async t=>{
313
+ const {cwd,specsRoot,set}=project(t);
314
+ set('../../lib');
315
+ const snapshot=captureBeforeSnapshot(cwd,[link],{allowSymlinks:true});
316
+ fs.unlinkSync(path.join(cwd,link));set('../../lib-next');
317
+ const observed=[];
318
+ const run=snapshot=>replayDelivery({codeProject:cwd,specsDir:specsRoot,snapshot,scope:[link],tests:[link],
319
+ checkCommands:checks,timeoutMs:5000,identity,greenChecks:checks,signal:new AbortController().signal,
320
+ makeCheck:({cwd:copy})=>async()=>{observed.push(fs.readlinkSync(path.join(copy,link)));return checks;}});
321
+ assert.equal((await run(snapshot)).status,'replayed');
322
+ assert.deepEqual(observed,['../../lib','../../lib-next']);
323
+ snapshot.files.set(link,{symlink:path.join(cwd,'lib')});
324
+ assert.equal((await run(snapshot)).reason,'internal_link');
325
+ assert.deepEqual(observed,['../../lib','../../lib-next']);
326
+ });
327
+
328
+ test('task gate hashes link text without reading the referent and rejects lexical escape',t=>{
329
+ const {cwd,set,outside}=project(t);
330
+ const options={allowSymlinks:true};
331
+ set('../../lib');
332
+ const first=implementationSha256(cwd,[link],options);
333
+ fs.writeFileSync(path.join(cwd,'lib/file'),'changed referent');
334
+ assert.equal(implementationSha256(cwd,[link],options),first);
335
+ fs.unlinkSync(path.join(cwd,link));set('../../lib-next');
336
+ assert.notEqual(implementationSha256(cwd,[link],options),first);
337
+ fs.unlinkSync(path.join(cwd,link));set(outside);
338
+ assert.throws(()=>implementationSha256(cwd,[link],options),/outside project root/);
339
+ });
340
+
341
+ function recordHistory(records,payload,kind){
342
+ const body={version:1,seq:records.length+1,id:`runner.${String(records.length+1).padStart(6,'0')}`,
343
+ kind,payload,previousDigest:records.at(-1)?.digest??null};
344
+ records.push({...body,digest:digest(body)});
345
+ }
346
+
347
+ test('inline, archived and referenced checkpoints preserve the same symlink fingerprint',t=>{
348
+ const {cwd,set,capture}=project(t),baseline=capture();
349
+ set('../../lib');
350
+ const reviewPackage=createReviewPackage({root:cwd,baseline,checks});
351
+ const records=[];
352
+ const envelope=(type,fields)=>({version:3,protocol:'cm-task-runner',type,...fields});
353
+ const effect={version:1,id:'develop-link',kind:'develop',identity};
354
+ recordHistory(records,envelope('init',{config:{identity}}),'intent');
355
+ recordHistory(records,envelope('effect-intent',{effect}),'intent');
356
+ const checkpoint={state:'awaiting_review',attempt:1,reviewPackage,
357
+ cache:[{effect,result:{state:'awaiting_review',identity,packageDigest:reviewPackage.packageDigest}}]};
358
+ const payload=(id,checkpoint,fields)=>envelope('effect-checkpoint',{effectId:id,checkpoint,...fields});
359
+ const inline=payload(effect.id,checkpoint,{});
360
+ assert.deepEqual(resolveCheckpointPackage(inline,records,identity),checkpoint);
361
+ const archive=checkpointStoragePlan({records,effectId:effect.id,checkpoint,identity,enabled:true,reserve:JOURNAL_PAYLOAD_LIMIT-8192});
362
+ assert.deepEqual(archive.payloadFields,{packageMaterial:true});
363
+ const stored=payload(effect.id,archive.checkpoint,archive.payloadFields);
364
+ assert.deepEqual(resolveCheckpointPackage(stored,records,identity),checkpoint);
365
+ recordHistory(records,stored,'result');
366
+ const review={...effect,id:'review-link',kind:'review'};
367
+ recordHistory(records,envelope('effect-intent',{effect:review}),'intent');
368
+ const reviewed={...checkpoint,cache:[{effect:review,result:checkpoint.cache[0].result}]};
369
+ const reference=checkpointStoragePlan({records,effectId:review.id,checkpoint:reviewed,identity,enabled:true,reserve:0});
370
+ assert.equal(reference.payloadFields.packageRef.packageDigest,reviewPackage.packageDigest);
371
+ const restored=resolveCheckpointPackage(payload(review.id,reference.checkpoint,reference.payloadFields),records,identity);
372
+ assert.deepEqual(restored.reviewPackage,reviewPackage);
373
+ assert.equal(restored.reviewPackage.changes[0].after.sha256,hash('../../lib'));
374
+ });
375
+
376
+ test('real current-session driver preflights, resumes and completes a new v3 run with a scoped symlink',t=>{
377
+ const fixture=project(t),{cwd,answers,set}=fixture,root=path.dirname(cwd),feature='1.fixture';
378
+ const specsRoot=path.join(root,'specs');
379
+ fs.renameSync(fixture.specsRoot,specsRoot);
380
+ const featureDir=path.join(specsRoot,feature),bin=path.join(root,'bin');
381
+ fs.mkdirSync(featureDir);fs.mkdirSync(bin);
382
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(featureDir,name),'# Fixture\n');
383
+ fs.writeFileSync(path.join(featureDir,'tasks.md'),'- [ ] T-001: fixture\n');
384
+ const write=(file,value)=>fs.writeFileSync(file,JSON.stringify(value));
385
+ write(path.join(specsRoot,'.cm-specs-status'),{status:'approved',features:[feature],specFiles:buildManifest(specsRoot)});
386
+ const definition={version:1,specsDir:specsRoot,codeProject:cwd,feature,identity,scope:[link],requirements:['lib/file']};
387
+ write(path.join(root,'run.json'),definition);
388
+ write(path.join(root,'review.json'),{model:'fixture',preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
389
+ config_fingerprint:configFingerprint({cwd,model:'fixture'})}});
390
+ fs.copyFileSync(fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url)),path.join(bin,'codex'));
391
+ fs.chmodSync(path.join(bin,'codex'),0o700);
392
+ const planFile=path.join(root,'plan.json'),answerFile=path.join(answers,'develop.json');
393
+ const plan={config:'run.json',mode:'create',hostContext:'symlink-host',
394
+ permissions:['--review-config','review.json'],answers:'answers',checks:[{id:'check',command:[process.execPath,'-e','0']}]};
395
+ const answer={status:'succeeded',value:{outcome:'implemented',
396
+ application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}},
397
+ edits:{[link]:{symlink:'../../lib-next'}}};
398
+ write(planFile,plan);
399
+ set('../../lib');
400
+ const drive=operation=>spawnSync(process.execPath,[fileURLToPath(new URL('./cm-ai-drive.mjs',import.meta.url)),
401
+ '--plan',planFile,operation],{encoding:'utf8',timeout:60000,env:{...process.env,
402
+ PATH:bin+path.delimiter+process.env.PATH,CM_WORKFLOW_HOME:path.join(root,'home'),CM_WORKFLOW_LOG_HOME:path.join(root,'logs')}});
403
+ write(answerFile,{...answer,edits:{[link]:{symlink:'../../../outside'}}});
404
+ const refused=drive('start'),store=path.join(specsRoot,'.reviews','.execution',identity.runId,'state.json');
405
+ assert.equal(refused.status,2,refused.stderr);
406
+ assert.match(refused.stderr,/invalid_symlink_target/);
407
+ assert.equal(fs.existsSync(store),false);
408
+ assert.equal(fs.readlinkSync(path.join(cwd,link)),'../../lib');
409
+ write(answerFile,answer);
410
+ const preview=developPreview({definition});
411
+ assert.equal(preview.exact,true);
412
+ const projected=projectDevelopCheckpoint({preview,codeProject:cwd,attempt:1,value:answer,
413
+ projected:new Map([[link,{path:link,symlink:'../../lib-next'}]]),checks:plannedCheckResults(plan.checks)}).pkg;
414
+ const started=drive('start');
415
+ assert.equal(started.status,0,started.stderr);
416
+ assert.equal(JSON.parse(started.stdout).result.state,'awaiting_review',started.stdout);
417
+ write(planFile,{...plan,mode:'resume'});
418
+ write(path.join(answers,'develop-a2.json'),answer);
419
+ const completed=drive('advance');
420
+ assert.equal(completed.status,0,completed.stderr);
421
+ assert.match(fs.readFileSync(path.join(featureDir,'tasks.md'),'utf8'),/- \[x\] T-001/,completed.stdout);
422
+ const journal=JSON.parse(fs.readFileSync(store,'utf8')).records;
423
+ const history=readRunnerHistory(journal,journal[0].payload.config,3);
424
+ assert.equal(history.original.version,3);
425
+ assert.equal(history.state.state,'fixture_completed');
426
+ assert.equal(history.state.reviewPackage.version,2);
427
+ assert.deepEqual(history.state.reviewPackage.changes[0],{path:link,before:record('../../lib'),after:record('../../lib-next')});
428
+ assert.equal(projected.packageDigest,history.state.reviewPackage.packageDigest);
429
+ assert.equal(fs.readlinkSync(path.join(cwd,link)),'../../lib-next');
430
+ });
431
+
432
+ test('real batch driver passes the v3 flag to apply and QA snapshots',t=>{
433
+ const f=project(t),feature='1.batch',root=path.dirname(f.cwd),specsDir=path.join(root,'specs');
434
+ fs.renameSync(f.specsRoot,specsDir);
435
+ f.set('../../lib');
436
+ fs.writeFileSync(path.join(f.cwd,'lib-next/file'),'next fixture');
437
+ for(const args of [['init','-b','main'],['config','user.name','Fixture'],['config','user.email','fixture@example.invalid'],['add','-A'],['commit','-m','baseline']]){
438
+ const git=spawnSync('git',['-C',f.cwd,...args],{encoding:'utf8'});
439
+ assert.equal(git.status,0,git.stderr);
440
+ }
441
+ const featureDir=path.join(specsDir,feature),bin=path.join(root,'bin'),taskAnswers=path.join(f.answers,feature,identity.taskId);
442
+ fs.mkdirSync(featureDir);fs.mkdirSync(bin);fs.mkdirSync(taskAnswers,{recursive:true});
443
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(featureDir,name),'# Fixture\n');
444
+ fs.writeFileSync(path.join(featureDir,'tasks.md'),`- [ ] T-001: fixture\n - 范围: \`${link}\`\n`);
445
+ const write=(file,value)=>fs.writeFileSync(file,JSON.stringify(value));
446
+ write(path.join(specsDir,'.cm-specs-status'),{status:'approved',features:[feature],specFiles:buildManifest(specsDir)});
447
+ const key=`${feature}/${identity.taskId}`,check=[process.execPath,'-e',
448
+ `if(require('node:fs').readlinkSync(${JSON.stringify(link)})!=='../../lib-next') process.exit(1)`];
449
+ write(path.join(root,'batch.json'),{batch:{version:1,repositoryId:'repo',batchId:'symlink-batch',specsDir,codeProject:f.cwd,
450
+ tasks:[{feature,taskId:identity.taskId,scope:[link],requirements:['lib/file']}]},
451
+ workflows:{[key]:{documentationPaths:[],applicableAgentFiles:[],qa:{commands:[{id:'qa-link',command:check,caseIds:[]}],
452
+ environment:{kind:'web',carrier:'browser',target:'fixture',scope:'local'}}}}});
453
+ write(path.join(root,'review.json'),{model:'fixture',preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
454
+ config_fingerprint:configFingerprint({cwd:f.cwd,model:'fixture'})}});
455
+ fs.copyFileSync(fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url)),path.join(bin,'codex'));
456
+ fs.chmodSync(path.join(bin,'codex'),0o700);
457
+ const planFile=path.join(root,'plan.json');
458
+ const plan={config:'batch.json',mode:'create',hostContext:'batch-fixture',
459
+ permissions:['--allow-qa','--review-config','review.json'],answers:'answers',checks:{[key]:[{id:'link',command:check}]}};
460
+ const answer={status:'succeeded',value:{outcome:'implemented',
461
+ application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}},
462
+ edits:{[link]:{symlink:'../../lib-next'}}};
463
+ for(const file of ['develop.json','develop-a2.json'])write(path.join(taskAnswers,file),answer);
464
+ write(path.join(taskAnswers,'qa-assess.json'),{confirmed:true});
465
+ write(path.join(taskAnswers,'documentation-inspect.json'),{status:'completed',reason:'Synthetic fixture'});
466
+ let result;
467
+ for(let i=0;i<5;i++){
468
+ write(planFile,i===0?plan:{...plan,mode:'resume',originalHostContext:plan.hostContext});
469
+ const driven=spawnSync(process.execPath,[fileURLToPath(new URL('./cm-ai-batch-drive.mjs',import.meta.url)),
470
+ '--plan',planFile,'advance'],{encoding:'utf8',timeout:30000,env:{...process.env,
471
+ PATH:bin+path.delimiter+process.env.PATH,CM_WORKFLOW_HOME:path.join(root,'home'),CM_WORKFLOW_LOG_HOME:path.join(root,'logs')}});
472
+ assert.equal(driven.status,0,driven.stderr);
473
+ result=JSON.parse(driven.stdout).result;
474
+ assert.ok(fs.existsSync(path.join(specsDir,'运行日志.jsonl')),`${driven.stdout}\n${driven.stderr}`);
475
+ if(result.state==='run_done')break;
476
+ }
477
+ assert.equal(result.state,'run_done',JSON.stringify(result));
478
+ assert.equal(fs.readlinkSync(path.join(f.cwd,link)),'../../lib-next');
479
+ const rows=fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
480
+ assert.deepEqual(rows.filter(row=>row.event==='test_run'&&row.phase==='complete').map(row=>row.result),['PASS']);
481
+ });
@@ -42,13 +42,25 @@ test('coding argv enables tools without weakening reviewer argv',()=>{
42
42
  for(const name of ['shell_tool','unified_exec','code_mode_host']){
43
43
  assert(reviewDisabled.includes(name));assert(!codingDisabled.includes(name));
44
44
  }
45
- assert.deepEqual(codingDisabled,reviewDisabled.filter(name=>!['shell_tool','unified_exec','code_mode_host'].includes(name)));
45
+ // view_image is a review-only removal (Codex 0.167 / gpt-6.2); coding keeps its old surface.
46
+ assert.deepEqual(codingDisabled,reviewDisabled.filter(name=>!['shell_tool','unified_exec','code_mode_host','view_image'].includes(name)));
46
47
  assert.deepEqual(values(coding,'--enable'),['shell_tool','unified_exec']);
47
48
  assert(!coding.includes('code_mode'));assert(!coding.includes('code_mode_host'));
48
49
  assert(coding.includes('sandbox_workspace_write.network_access=false'));
49
50
  assert.equal(coding.at(-1),'-');assert(!coding.includes('--dangerously-bypass-approvals-and-sandbox'));
50
51
  });
51
52
 
53
+ // 实跑事故(2026-11-17,codex-cli 0.167.0):gpt-6.2-sol 默认多带 request_user_input、view_image
54
+ // 两个工具,审查预检的「零工具」判定必然失败。审查参数关掉这两个;编码参数保持原样。
55
+ test('review argv removes the default tools Codex 0.167 adds for gpt-6.2; coding argv keeps them',()=>{
56
+ const options={cwd:'/fixture',model:'gpt-6.2-sol',schemaPath:'/schema.json'};
57
+ const review=commonArgs(options),coding=developerArgs(options);
58
+ const values=(args,flag)=>args.flatMap((arg,i)=>arg===flag?[args[i+1]]:[]);
59
+ assert(values(review,'--disable').includes('view_image'));
60
+ assert.equal(values(review,'-c').filter(arg=>arg==='tools.experimental_request_user_input.enabled=false').length,1);
61
+ assert(!values(coding,'--disable').includes('view_image'));
62
+ assert(!coding.includes('tools.experimental_request_user_input.enabled=false'));
63
+ });
52
64
  test('coding and review argv both suppress the user skills catalog (2026-09-16: 18249 -> 11706 input tokens)',()=>{
53
65
  const options={cwd:'/fixture',model:'fixture',schemaPath:'/schema.json'};
54
66
  for(const args of [developerArgs(options),commonArgs(options)]){
@@ -11,6 +11,9 @@ import {spawnSync} from 'node:child_process';
11
11
  import {fileURLToPath} from 'node:url';
12
12
  import {parseAssignments,readPrivateFile,readSecret,runSender,responseCodeType,readRegularFile,entryDecision,WINDOWS_UNSUPPORTED,SEND_EXIT} from '../runtime/js/notify-send.mjs';
13
13
  import {main,notifyStatus,switchChannel,turnOff,sendTest,formatTest,previewText,formatPreview,managedSenderPath,classifyCommand,SENDER_SOURCE,TEMPLATES} from './cm-notify.mjs';
14
+ // An exported CM_NOTIFY_OFF silences every notice; these fixtures expect notices on
15
+ // (review 2026-11-17). Tests of the switch itself set it explicitly.
16
+ delete process.env.CM_NOTIFY_OFF;
14
17
 
15
18
  // Every test works in its own temp CM_WORKFLOW_HOME / log home / HOME: the
16
19
  // real ~/.cm-workflow/notify.json would push to the user's phone.
@@ -15,6 +15,9 @@ import {notify,notifyLater,cancelPendingNotice,clearAttention,sessionTitle,sched
15
15
  const DEFAULT_HOME=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-default-home-'));
16
16
  process.env.CM_WORKFLOW_HOME=DEFAULT_HOME;
17
17
  process.on('exit',()=>fs.rmSync(DEFAULT_HOME,{recursive:true,force:true}));
18
+ // The same for the per-process off switch: an exported CM_NOTIFY_OFF would silence every
19
+ // fixture that expects a notice (review 2026-11-17). Tests that need it set it explicitly.
20
+ delete process.env.CM_NOTIFY_OFF;
18
21
  const NOW=Date.parse('2026-10-08T08:00:00.000Z');
19
22
  const DRIVE_CORE=new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
20
23
  const BRIDGE=new URL('../runtime/js/cm-ai/host-tool-bridge.mjs',import.meta.url).href;
@@ -7,6 +7,9 @@ import {spawn,spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {patrol,inspectHosts,processAlive} from './cm-patrol.mjs';
9
9
  import {hostRegistryDir,buildNotifyMessage,removeHostRegistry} from '../runtime/js/notify.mjs';
10
+ // An exported CM_NOTIFY_OFF silences every notice; these fixtures expect notices on
11
+ // (review 2026-11-17). Tests of the switch itself set it explicitly.
12
+ delete process.env.CM_NOTIFY_OFF;
10
13
 
11
14
  const HOST_SESSION=new URL('../runtime/js/cm-ai/host-session.mjs',import.meta.url).href;
12
15
  const PATROL=fileURLToPath(new URL('./cm-patrol.mjs',import.meta.url));
@@ -20,6 +20,9 @@ import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
20
20
  import {inspectAcceptedPrdDesign,acceptedPrdDesignForPlanning} from '../runtime/js/cm-prd/accepted-design.mjs';
21
21
  import {createPrdSummaryOwner,inspectPrdSummaryEvidence,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
22
22
  import {assertPrdReviewsSettled} from '../runtime/js/cm-prd/change.mjs';
23
+ import {writeApprovalSnapshot} from '../runtime/js/cm-ai/spec-amendment.mjs';
24
+ import {writeSpecsStatus} from '../runtime/js/specs-status.mjs';
25
+ import {buildManifest} from './cm-spec-manifest.mjs';
23
26
  import {recordPrdHostDisposition,createPrdDispositionOwner} from '../runtime/js/cm-prd/review-disposition.mjs';
24
27
  const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
25
28
  const riskSignals=high=>({greenfieldAdr:false,architectureOrDataFlow:high,newRuntimeDependencyOrToolchain:false,
@@ -544,6 +547,34 @@ for(const mode of ['failed','drift'])test(`disposed-design split self-check cann
544
547
  else assert.equal((await owner(f.args,new AbortController().signal)).gate.disposition,'self_check_failed');
545
548
  assert.equal(checks,1);assert.equal(fs.existsSync(path.join(f.specs,'.reviews/prd-guide-split-disposition.json')),mode==='failed');
546
549
  });
550
+ // Models a human 「开始」 binding the current specs; the round ledger stays in a temporary home.
551
+ function isolateApprovalHome(t){
552
+ const home=fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-approved-home-')),previous=process.env.CM_WORKFLOW_HOME;
553
+ process.env.CM_WORKFLOW_HOME=home;
554
+ t.after(()=>{if(previous===undefined)delete process.env.CM_WORKFLOW_HOME;else process.env.CM_WORKFLOW_HOME=previous;fs.rmSync(home,{recursive:true,force:true});});
555
+ }
556
+ function approveCurrentSpecs(specs){
557
+ const specFiles=buildManifest(specs),features=[...new Set(specFiles.map(row=>row.path.split('/')[0]))];
558
+ const approval={response:'开始',at:'2026-11-17T00:00:00.000Z'};
559
+ writeSpecsStatus(specs,{status:'approved',at:approval.at,features,specFiles,testCases:specFiles.filter(row=>row.path.endsWith('/test-cases.json')),approval,taskGrammar:3});
560
+ writeApprovalSnapshot(specs,{features,specFiles,approval});
561
+ }
562
+ // Codex 审查 #1:批准基线只替代指纹比对,设计与拆分审查的关联校验照常执行。
563
+ test('change save accepts an approved design after a completed split but keeps the split binding check',async t=>{
564
+ isolateApprovalHome(t);const f=await splitDesignFixture(t);f.edit();
565
+ await createPrdDispositionOwner({checkContext:async payload=>checked(payload)})(f.args,new AbortController().signal);
566
+ fs.writeFileSync(path.join(f.specs,f.feature,'design.md'),f.content+'\nLater approved design');
567
+ assert.throws(()=>assertPrdReviewsSettled(f.specs,[f.feature]));
568
+ approveCurrentSpecs(f.specs);
569
+ assert.doesNotThrow(()=>assertPrdReviewsSettled(f.specs,[f.feature]));
570
+ const g=await splitDesignFixture(t),other=await splitDesignFixture(t,{featureName:'other'});
571
+ other.edit();await createPrdDispositionOwner({checkContext:async payload=>checked(payload)})(other.args,new AbortController().signal);
572
+ g.edit();
573
+ for(const suffix of ['-r1.md','-dispatch.json','-disposition.json'])fs.copyFileSync(
574
+ path.join(other.specs,`.reviews/prd-other-split${suffix}`),path.join(g.specs,`.reviews/prd-guide-split${suffix}`));
575
+ approveCurrentSpecs(g.specs);
576
+ assert.throws(()=>assertPrdReviewsSettled(g.specs,[g.feature]),/prd_review_archive_identity_mismatch/);
577
+ });
547
578
  test('unchanged split disposition preserves legacy accepted binding and both receipt bytes',async t=>{
548
579
  const f=await splitDesignFixture(t),args=structuredClone(f.args);
549
580
  args.decisions[0].status='escalated';args.decisions[0].changedPaths=[];