@aibyzero/cm-workflow 0.21.2 → 0.21.4

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 (45) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +9 -0
  3. package/README.md +7 -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/durable-runner-state.mjs +19 -4
  12. package/runtime/js/cm-ai/fix-code-association.mjs +5 -5
  13. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -15
  14. package/runtime/js/cm-ai/host-documentation.mjs +4 -3
  15. package/runtime/js/cm-ai/host-handoff.mjs +3 -2
  16. package/runtime/js/cm-ai/host-project-execution.mjs +11 -9
  17. package/runtime/js/cm-ai/host-qa-executor.mjs +3 -2
  18. package/runtime/js/cm-ai/host-replay.mjs +28 -8
  19. package/runtime/js/cm-ai/review-package.mjs +101 -33
  20. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  21. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  22. package/runtime/js/cm-ai/symlink-material.mjs +153 -0
  23. package/runtime/js/cm-ai/task-commit.mjs +6 -3
  24. package/runtime/js/cm-ai/task-runner.mjs +12 -5
  25. package/runtime/js/cm-ai/worker-claude-developer.mjs +19 -7
  26. package/runtime/js/cm-fix/protected-edits.mjs +57 -36
  27. package/scripts/ci-test-weights.json +1 -0
  28. package/scripts/cm-ai-batch-drive.mjs +9 -5
  29. package/scripts/cm-ai-call-timeout.test.mjs +85 -0
  30. package/scripts/cm-ai-control-launch.test.mjs +18 -0
  31. package/scripts/cm-ai-drive.mjs +141 -42
  32. package/scripts/cm-ai-host.mjs +15 -3
  33. package/scripts/cm-ai-host.test.mjs +3 -1
  34. package/scripts/cm-ai-launch-diagnostics.test.mjs +23 -0
  35. package/scripts/cm-ai-run.mjs +2 -1
  36. package/scripts/cm-ai-scope-revision.test.mjs +35 -3
  37. package/scripts/cm-ai-supersede.test.mjs +51 -3
  38. package/scripts/cm-ai-symlink.test.mjs +481 -0
  39. package/scripts/cm-skill-hints.mjs +40 -16
  40. package/scripts/cm-skill-hints.test.mjs +91 -0
  41. package/scripts/cm-start-check.mjs +53 -15
  42. package/scripts/cm-start-check.test.mjs +41 -2
  43. package/scripts/cm-task-gate.mjs +42 -13
  44. package/scripts/cm-task-gate.test.mjs +33 -0
  45. package/skills/cm-ai/references/js-host.md +1 -0
@@ -844,10 +844,23 @@ function executionFor(f,content,verdict='blocked',qaResult=null){
844
844
  }
845
845
  return execution;
846
846
  }
847
- async function start(f,runId,content,options={},verdict='blocked',qaResult=null){
847
+ async function start(f,runId,content,options={},verdict='blocked',qaResult=null,baselineVersion=3){
848
848
  const identity=identityFor(runId),definition={version:1,specsDir:f.specsDir,codeProject:f.codeProject,
849
849
  feature:f.feature,identity,scope:['a.mjs'],requirements:['requirements.md']};
850
- const run=await openControlRun(definition,'create',executionFor(f,content,verdict,qaResult),options);
850
+ const execution=executionFor(f,content,verdict,qaResult);
851
+ let run=await openControlRun(definition,'create',execution,options);
852
+ if(baselineVersion===2){
853
+ run.close();
854
+ const stateFile=path.join(f.reviewsDir,'.execution',runId,'state.json');
855
+ const {revision,...snapshot}=JSON.parse(fs.readFileSync(stateFile,'utf8'));
856
+ assert.deepEqual(snapshot.records.map(row=>row.payload.type),['init']);
857
+ snapshot.records[0].payload.baseline=captureReviewBaseline({root:f.codeProject,specsRoot:f.specsDir,identity,
858
+ scope:['a.mjs','AGENTS.md'],requirements:definition.requirements,
859
+ specification:{specsRoot:f.specsDir,feature:f.feature},version:2});
860
+ snapshot.records=rechain(snapshot.records);
861
+ fs.writeFileSync(stateFile,JSON.stringify({...snapshot,revision:digest(snapshot)})+'\n');
862
+ run=await openControlRun(definition,'resume',execution,options);
863
+ }
851
864
  try{return await run.host.handle(requestFor(identity));}finally{run.close();}
852
865
  }
853
866
 
@@ -953,7 +966,9 @@ test('supersession drift reason lists only the first 20 of 21 paths',async()=>{
953
966
  test('supersession refuses a symlink without reading its target outside the code root',async()=>{
954
967
  const f=runFixture();
955
968
  try{
956
- assert.equal((await start(f,'run-link-old-0001','written\n')).state,'blocked');
969
+ assert.equal((await start(f,'run-link-old-0001','written\n',{},'blocked',null,2)).state,'blocked');
970
+ const original=JSON.parse(fs.readFileSync(path.join(f.reviewsDir,'.execution','run-link-old-0001','state.json'),'utf8'));
971
+ assert.equal(original.records[0].payload.baseline.version,2);
957
972
  fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'old\n');
958
973
  const outside=path.join(f.root,'outside.mjs');
959
974
  fs.writeFileSync(outside,'private fixture\n');
@@ -967,6 +982,39 @@ test('supersession refuses a symlink without reading its target outside the code
967
982
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
968
983
  });
969
984
 
985
+ test('v3 supersession detects an external symlink as drift and never opens its referent',async t=>{
986
+ const f=runFixture();
987
+ t.after(()=>fs.rmSync(f.root,{recursive:true,force:true}));
988
+ const old='run-link-v3-old',next='run-link-v3-new',file=path.join(f.codeProject,'link.mjs'),outside=path.join(f.root,'outside.mjs');
989
+ const stateFile=id=>path.join(f.reviewsDir,'.execution',id,'state.json');
990
+ assert.equal((await start(f,old,'written\n')).state,'blocked');
991
+ const before=fs.readFileSync(stateFile(old));
992
+ assert.equal(JSON.parse(before).records[0].payload.baseline.version,3);
993
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'old\n');
994
+ fs.writeFileSync(outside,'private fixture\n');fs.symlinkSync(outside,file);
995
+ const open=fs.openSync;
996
+ const guard=t.mock.method(fs,'openSync',(candidate,...args)=>{
997
+ assert.ok(![file,outside].includes(candidate),'neither the link nor its referent may be opened');
998
+ return open(candidate,...args);
999
+ });
1000
+ await assert.rejects(start(f,next,'new\n',{supersedeReason:'restart'}),error=>{
1001
+ assert.equal(error.code,'supersede_code_drift');
1002
+ assert.match(error.reason,/link\.mjs.*手动还原/);
1003
+ return true;
1004
+ });
1005
+ assert.equal(fs.existsSync(stateFile(next)),false);
1006
+ assert.deepEqual(fs.readFileSync(stateFile(old)),before);
1007
+ assert.equal((await start(f,next,'new\n',{supersedeReason:'restart',acceptSupersededCodeDrift:true})).state,'blocked');
1008
+ const rows=JSON.parse(fs.readFileSync(stateFile(next),'utf8')).records;
1009
+ assert.deepEqual(rows[0].payload.baseline.files.find(item=>item.path==='link.mjs'),{
1010
+ path:'link.mjs',type:'symlink',target:outside,size:Buffer.byteLength(outside),
1011
+ sha256:createHash('sha256').update('symlink\0').update(outside).digest('hex')});
1012
+ assert.doesNotMatch(JSON.stringify(rows),/private fixture/);
1013
+ assert.deepEqual(fs.readFileSync(stateFile(old)),before);
1014
+ guard.mock.restore();
1015
+ assert.equal(fs.readFileSync(outside,'utf8'),'private fixture\n');
1016
+ });
1017
+
970
1018
  test('host launch prints supersede code drift reason and stderr hint',async()=>{
971
1019
  const f=runFixture();
972
1020
  try{
@@ -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
+ });