@aibyzero/cm-workflow 0.19.0 → 0.21.0

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 (127) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +38 -0
  4. package/README.md +15 -1
  5. package/VERSION +1 -1
  6. package/docs/architecture.md +3 -0
  7. package/docs/cm-acceptance-completion.md +185 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +1 -1
  10. package/docs/proposals/spec-amendment-tiers.md +100 -0
  11. package/package.json +1 -1
  12. package/runtime/js/acceptance-language.mjs +32 -0
  13. package/runtime/js/autonomy.mjs +168 -3
  14. package/runtime/js/check-coverage.mjs +130 -0
  15. package/runtime/js/cm-ai/acceptance-contract.mjs +257 -0
  16. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +49 -8
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  21. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  22. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  24. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  25. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  27. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  28. package/runtime/js/cm-ai/drive-core.mjs +15 -4
  29. package/runtime/js/cm-ai/durable-runner-state.mjs +10 -6
  30. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  32. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  33. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  34. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  35. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  36. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  37. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  38. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  39. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  40. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  41. package/runtime/js/cm-ai/review-package.mjs +22 -8
  42. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  43. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  44. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  45. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  46. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  47. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  48. package/runtime/js/cm-ai/task-runner.mjs +64 -22
  49. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  50. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  51. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  52. package/runtime/js/cm-prd/change.mjs +52 -5
  53. package/runtime/js/cm-prd/self-check.mjs +36 -6
  54. package/runtime/js/cm-prd/session.mjs +8 -3
  55. package/runtime/js/cm-prd/summary.mjs +5 -0
  56. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  57. package/runtime/js/node-test-selection.mjs +38 -0
  58. package/runtime/js/run-analysis.mjs +153 -0
  59. package/runtime/js/session-boundary.mjs +17 -5
  60. package/runtime/js/session-handoff.mjs +5 -2
  61. package/runtime/js/task-scope.mjs +4 -1
  62. package/runtime/test-contract.md +1 -0
  63. package/scripts/cm-acceptance-preview.mjs +26 -0
  64. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  65. package/scripts/cm-ai-acceptance-contract.test.mjs +195 -0
  66. package/scripts/cm-ai-admission.mjs +8 -2
  67. package/scripts/cm-ai-admission.test.mjs +20 -4
  68. package/scripts/cm-ai-blockage.test.mjs +120 -0
  69. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  70. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  71. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  72. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  73. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  74. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  75. package/scripts/cm-ai-drive.mjs +18 -11
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  77. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  78. package/scripts/cm-ai-progress.test.mjs +7 -0
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  80. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  81. package/scripts/cm-ai-run.test.mjs +23 -1
  82. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  83. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  84. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  85. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  86. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  87. package/scripts/cm-autonomy-review-r1.test.mjs +142 -0
  88. package/scripts/cm-autonomy.mjs +3 -1
  89. package/scripts/cm-autonomy.test.mjs +10 -9
  90. package/scripts/cm-check-runtime.sh +5 -2
  91. package/scripts/cm-delivery-evidence.mjs +59 -0
  92. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  93. package/scripts/cm-drive-liveness.test.mjs +14 -0
  94. package/scripts/cm-driver-light-import.test.mjs +32 -0
  95. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  96. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  97. package/scripts/cm-journal-limit.test.mjs +69 -0
  98. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  99. package/scripts/cm-node-test-selection.test.mjs +108 -0
  100. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  101. package/scripts/cm-prd-completion.test.mjs +49 -0
  102. package/scripts/cm-prd-drive.mjs +1 -1
  103. package/scripts/cm-prd-host.mjs +3 -1
  104. package/scripts/cm-prd-host.test.mjs +19 -2
  105. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  106. package/scripts/cm-prd-self-check.test.mjs +24 -1
  107. package/scripts/cm-prd-summary.test.mjs +25 -4
  108. package/scripts/cm-review-inventory.test.mjs +25 -6
  109. package/scripts/cm-run-analysis.mjs +21 -0
  110. package/scripts/cm-run-analysis.test.mjs +120 -0
  111. package/scripts/cm-spec-amend.mjs +68 -0
  112. package/scripts/cm-spec-amend.test.mjs +510 -0
  113. package/scripts/cm-specs-status.test.mjs +6 -0
  114. package/scripts/cm-start-check.mjs +140 -53
  115. package/scripts/cm-start-check.test.mjs +139 -1
  116. package/scripts/cm-task-scope.test.mjs +3 -2
  117. package/scripts/cm-usage-report.py +8 -3
  118. package/scripts/cm019-r1-contract.test.mjs +137 -0
  119. package/scripts/cm019-review-gates.test.mjs +97 -0
  120. package/scripts/test-journal-limit-1mib.mjs +4 -0
  121. package/scripts/validate-public-repo.py +4 -0
  122. package/skills/cm-ai/references/N1-init.md +23 -1
  123. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  124. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  125. package/skills/cm-ai/references/js-host.md +7 -2
  126. package/skills/cm-prd/references/js-change-recovery.md +2 -1
  127. package/skills/cm-prd/references/js-host.md +1 -0
@@ -0,0 +1,177 @@
1
+ import test,{after} from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {buildManifest} from './cm-spec-manifest.mjs';
9
+ import {openControlRun} from './cm-ai-run.mjs';
10
+ import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
11
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
12
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
13
+ import {previewDelivery,recordDelivery,deliveryCandidate,deliveryProjection,deliveryLines,readDeliveryRecords,deliveryFile} from '../runtime/js/cm-ai/delivery-evidence.mjs';
14
+ import {completionSummary,completionLines} from '../runtime/js/cm-ai/completion-summary.mjs';
15
+ import {deliveryMain} from './cm-delivery-evidence.mjs';
16
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
17
+ import {PassThrough,Writable} from 'node:stream';
18
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-delivery-fixture-')));
19
+ const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
20
+ process.env.CM_WORKFLOW_HOME=path.join(root,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(root,'logs');
21
+ after(()=>{for(const [k,v] of Object.entries(saved))if(v===undefined)delete process.env[k];else process.env[k]=v;fs.rmSync(root,{recursive:true,force:true});});
22
+ const identity={repositoryId:'delivery-fixture',runId:'delivery-run',taskId:'T-001',attempt:1},feature='1.demo';
23
+ const cli=fileURLToPath(new URL('./cm-delivery-evidence.mjs',import.meta.url));
24
+ async function fixture(){
25
+ const local=fs.mkdtempSync(path.join(root,'project-')),specsDir=path.join(local,'specs'),codeProject=path.join(local,'code');
26
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
27
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'export const a=1;\n');fs.writeFileSync(path.join(codeProject,'requirements.md'),'fixture\n');
28
+ for(const [name,body] of [['requirements.md','# R\n'],['design.md','# D\n'],['tasks.md','- [ ] T-001: fixture\n- [ ] T-002: remaining\n']])fs.writeFileSync(path.join(specsDir,feature,name),body);
29
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
30
+ const definition={version:1,codeProject,specsDir,feature,identity,scope:['a.mjs'],requirements:['requirements.md']};
31
+ const execution={configuration:{kind:'synthetic-host-v1'},timeoutMs:4000,excludedContexts:['control'],
32
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async()=>{
33
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'export const a=2;\n');
34
+ return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
35
+ check:createHostCheck({cwd:codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]}),
36
+ verificationGate:async request=>request.acceptanceContract?{satisfied:true,items:request.acceptanceContract.obligations.map(item=>({...item,satisfied:true,evidence:'Synthetic fixture verified'}))}:{satisfied:true},
37
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,contexts:['review1','review2'],run:(request,{onEvent})=>{
38
+ onEvent({event:'thread.started',provider_thread:'independent-fixture'});onEvent({event:'turn.started',item_type:null});
39
+ onEvent({event:'item.completed',item_type:'agent_message'});onEvent({event:'turn.completed',item_type:null});onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
40
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic independent review'}};
41
+ }}],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control']}};
42
+ let opened=await openControlRun(definition,'create',execution);
43
+ const ask=()=>opened.host.handle({version:1,operation:'advance',requestId:'advance',identity});
44
+ try{assert.equal((await opened.host.handle({version:1,operation:'start',requestId:'start',identity})).state,'awaiting_review');}finally{opened.close();}
45
+ opened=await openControlRun(definition,'resume',execution,{decision:{status:'approved'}});let result;
46
+ try{result=await ask();assert.equal(result.state,'fixture_completed',JSON.stringify(result));}finally{opened.close();}
47
+ const artifact=path.join(local,'build.txt'),report=path.join(local,'owner-report.txt'),verificationReport=path.join(local,'deployed-check.txt');
48
+ fs.writeFileSync(artifact,'build bytes');fs.writeFileSync(report,'human observed flow');fs.writeFileSync(verificationReport,'post deploy check');
49
+ const options={specsDir,repositoryId:identity.repositoryId,runId:identity.runId,feature,artifact,kind:'acceptance',
50
+ statement:{actor:'fixture-owner',environment:'staging',outcome:'accepted',note:'fixture manual declaration'},report};
51
+ const projection=()=>{const candidate=deliveryCandidate(options);return deliveryProjection({...options,identity,packageDigest:candidate.packageDigest,specificationDigest:candidate.specificationDigest});};
52
+ return {local,specsDir,codeProject,options,verificationReport,result,projection};
53
+ }
54
+ const accept={confirm:async(_preview,phrase)=>phrase};
55
+
56
+ test('real completed owner: preview is read-only, explicit declaration is bound and cannot finish a feature',async()=>{
57
+ const f=await fixture(),journal=path.join(f.specsDir,'.reviews','.execution',identity.runId,'state.json'),bytes=fs.readFileSync(journal),mtime=fs.statSync(journal).mtimeMs;
58
+ const preview=previewDelivery(f.options);assert.equal(preview.candidate.packageDigest,f.result.packageDigest);
59
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.delivery')),false);
60
+ assert.equal(f.projection().productAcceptance.status,'unknown');
61
+ await assert.rejects(recordDelivery(f.options),{code:'delivery_confirmation_required'});
62
+ await assert.rejects(recordDelivery(f.options,{confirm:async()=> 'yes'}),{code:'delivery_confirmation_refused'});
63
+ const record=await recordDelivery(f.options,accept);assert.equal(record.sequence,1);assert.equal(record.provenance,'interactive-terminal-declaration');
64
+ assert.equal(readDeliveryRecords(f.specsDir).length,1);assert.equal(f.projection().productAcceptance.status,'recorded');
65
+ const summary=completionSummary({specsDir:f.specsDir,feature,result:f.result});
66
+ assert.equal(summary.productAcceptance.status,'recorded');assert.notEqual(summary.feature.status,'passed');assert.notEqual(summary.project.status,'completed');
67
+ assert.match(completionLines(summary).at(-1),/staging \[.*\] 声明已记录(accepted)/);
68
+ assert.deepEqual(fs.readFileSync(journal),bytes);assert.equal(fs.statSync(journal).mtimeMs,mtime);
69
+ const rejected=await recordDelivery({...f.options,statement:{...f.options.statement,outcome:'rejected'}},accept);
70
+ assert.equal(rejected.previousDigest,record.recordDigest);assert.equal(readDeliveryRecords(f.specsDir).length,2);
71
+ assert.equal(f.projection().productAcceptance.environments[0].statement.outcome,'rejected');
72
+ });
73
+
74
+ test('confirmation rechecks artifact, report, code candidate and record head; no stale approval is applied',async()=>{
75
+ const f=await fixture();
76
+ for(const file of [f.options.artifact,f.options.report,path.join(f.codeProject,'a.mjs')]){
77
+ const original=fs.readFileSync(file);
78
+ await assert.rejects(recordDelivery(f.options,{confirm:async(_p,phrase)=>{fs.appendFileSync(file,'drift');return phrase;}}));
79
+ fs.writeFileSync(file,original);assert.equal(readDeliveryRecords(f.specsDir).length,0);
80
+ }
81
+ await assert.rejects(recordDelivery(f.options,{confirm:async(_p,phrase)=>{await recordDelivery(f.options,accept);return phrase;}}),{code:'delivery_preview_changed'});
82
+ assert.equal(readDeliveryRecords(f.specsDir).length,1);
83
+ });
84
+
85
+ test('latest declaration, environment and candidate are never replaced by an older success',async()=>{
86
+ const f=await fixture();await recordDelivery(f.options,accept);
87
+ const candidate=deliveryCandidate(f.options),base={specsDir:f.specsDir,feature,identity,packageDigest:candidate.packageDigest,specificationDigest:candidate.specificationDigest};
88
+ assert.equal(deliveryProjection({...base,packageDigest:'f'.repeat(64)}).productAcceptance.status,'stale');
89
+ assert.equal(deliveryProjection({...base,current:false}).productAcceptance.status,'stale');
90
+ const code=path.join(f.codeProject,'a.mjs'),before=fs.readFileSync(code);fs.appendFileSync(code,'// changed');
91
+ assert.equal(completionSummary({specsDir:f.specsDir,feature,result:f.result}).productAcceptance.status,'stale');
92
+ fs.writeFileSync(code,before);
93
+ assert.equal(deliveryProjection({...base,artifactSha256:'b'.repeat(64)}).productAcceptance.status,'stale');
94
+ fs.appendFileSync(f.options.report,'changed');assert.equal(deliveryProjection(base).productAcceptance.status,'stale');
95
+ fs.writeFileSync(f.options.report,'human observed flow');
96
+ await recordDelivery({...f.options,statement:{...f.options.statement,environment:'production',outcome:'revoked'}},accept);
97
+ const value=deliveryProjection(base);assert.equal(value.productAcceptance.environments.length,2);
98
+ assert.match(deliveryLines(value)[0],/production \[.*\] 声明已记录(revoked)/);
99
+ });
100
+
101
+ test('deployment execution and post-deployment verification remain distinct, with separate evidence',async()=>{
102
+ const f=await fixture(),options={...f.options,kind:'deployment',statement:{actor:'fixture-operator',environment:'staging',execution:'succeeded',verification:'unknown',note:'deployment declaration'}};
103
+ await recordDelivery(options,accept);assert.equal(f.projection().deployment.environments[0].statement.verification,'unknown');
104
+ await assert.rejects(recordDelivery({...options,statement:{...options.statement,verification:'passed'}},accept),{code:'delivery_verification_report_required'});
105
+ await recordDelivery({...options,statement:{...options.statement,verification:'passed'},verificationReport:f.verificationReport},accept);
106
+ fs.appendFileSync(f.verificationReport,'changed');assert.equal(f.projection().deployment.status,'stale');
107
+ await recordDelivery({...options,statement:{...options.statement,execution:'failed'}},accept);
108
+ assert.equal(f.projection().deployment.environments[0].statement.execution,'failed');assert.equal(readDeliveryRecords(f.specsDir).length,3);
109
+ });
110
+
111
+ test('malformed records and unsafe source links fail closed; read-only CLI cannot bypass terminal confirmation',async()=>{
112
+ const f=await fixture();await recordDelivery(f.options,accept);
113
+ const file=path.join(f.specsDir,'.reviews','.delivery','000001','record.json'),original=fs.readFileSync(file);
114
+ const raw=JSON.parse(original);raw.statement.outcome='accepted-by-ai';fs.writeFileSync(file,JSON.stringify(raw));
115
+ assert.throws(()=>readDeliveryRecords(f.specsDir));assert.equal(f.projection().productAcceptance.status,'unknown');fs.writeFileSync(file,original);
116
+ const linked=path.join(f.local,'linked.txt');fs.symlinkSync(f.options.artifact,linked);assert.throws(()=>deliveryFile(linked));
117
+ const args=['--specs',f.specsDir,'--repository',identity.repositoryId,'--run',identity.runId,'--feature',feature,'--artifact',f.options.artifact];
118
+ const status=spawnSync(process.execPath,[cli,'status',...args,'--json'],{encoding:'utf8'});assert.equal(status.status,0,status.stderr);assert.equal(JSON.parse(status.stdout).productAcceptance.status,'recorded');
119
+ const recordArgs=[...args,'--kind','acceptance','--actor','owner','--environment','staging','--note','tested','--report',f.options.report,'--outcome','accepted'];
120
+ const refused=spawnSync(process.execPath,[cli,'record',...recordArgs],{encoding:'utf8',input:'yes\n'});
121
+ assert.equal(refused.status,2);assert.match(refused.stderr,/delivery_interactive_terminal_required/);assert.equal(readDeliveryRecords(f.specsDir).length,1);
122
+ const bypass=spawnSync(process.execPath,[cli,'record',...recordArgs,'--yes'],{encoding:'utf8'});assert.equal(bypass.status,2);
123
+ assert.deepEqual(fs.readFileSync(file),original);
124
+ });
125
+
126
+ test('interactive CLI records only the displayed digest; competing publication cannot overwrite history',async()=>{
127
+ const f=await fixture(),input=new PassThrough();input.isTTY=true;
128
+ let shown='',errors='';const output=new Writable({write(chunk,_encoding,done){const value=chunk.toString();shown+=value;
129
+ const phrase=value.match(/RECORD acceptance [a-f0-9]{64}/)?.[0];if(phrase)queueMicrotask(()=>input.write(phrase+'\n'));done();}});output.isTTY=true;
130
+ const args=['record','--specs',f.specsDir,'--repository',identity.repositoryId,'--run',identity.runId,'--feature',feature,'--artifact',f.options.artifact,
131
+ '--kind','acceptance','--actor','fixture-owner','--environment','staging','--note','manual fixture','--report',f.options.report,'--outcome','accepted'];
132
+ assert.equal(await deliveryMain(args,{input,output,error:{write(value){errors+=value;}}}),0,errors);input.destroy();
133
+ assert.match(shown,/interactive-terminal-declaration/);assert.equal(readDeliveryRecords(f.specsDir).length,1);
134
+ const originalRename=fs.renameSync;let collided=false;
135
+ fs.renameSync=function(from,to){if(!collided&&to.endsWith('000002')){collided=true;fs.mkdirSync(to);
136
+ fs.writeFileSync(path.join(to,'record.json'),fs.readFileSync(path.join(from,'record.json')));}
137
+ return originalRename(from,to);};
138
+ try{await assert.rejects(recordDelivery(f.options,accept),{code:'delivery_concurrent_write'});}finally{fs.renameSync=originalRename;}
139
+ assert.equal(readDeliveryRecords(f.specsDir).length,2,'one atomic publication survives collision');
140
+ await recordDelivery(f.options,accept);assert.equal(readDeliveryRecords(f.specsDir).length,3,'losing stage does not block later append');
141
+ fs.renameSync=()=>{throw Object.assign(new Error('fixture interrupted publication'),{code:'EIO'});};
142
+ try{await assert.rejects(recordDelivery(f.options,accept),{code:'EIO'});}finally{fs.renameSync=originalRename;}
143
+ assert.equal(readDeliveryRecords(f.specsDir).length,3);
144
+ await recordDelivery(f.options,accept);assert.equal(readDeliveryRecords(f.specsDir).length,4,'interrupted unpublished stage is preserved without corrupting committed rows');
145
+ });
146
+
147
+ test('record capacity is rejected before confirmation, preserving a fully readable ledger',async()=>{
148
+ const f=await fixture(),first=await recordDelivery(f.options,accept);let previous=first.recordDigest;
149
+ const {recordDigest,...template}=first;
150
+ for(let sequence=2;sequence<=1000;sequence++){
151
+ const body={...template,sequence,previousDigest:previous},record={...body,recordDigest:digest(body)};
152
+ const dir=path.join(f.specsDir,'.reviews','.delivery',String(sequence).padStart(6,'0'));fs.mkdirSync(dir);
153
+ fs.writeFileSync(path.join(dir,'record.json'),JSON.stringify(record)+'\n');previous=record.recordDigest;
154
+ }
155
+ let asked=false;await assert.rejects(recordDelivery(f.options,{confirm:async()=>{asked=true;return 'yes';}}),{code:'delivery_record_limit'});
156
+ assert.equal(asked,false);assert.equal(readDeliveryRecords(f.specsDir).length,1000);
157
+ });
158
+
159
+ test('R1 G8 environment casing and surrounding spaces cannot hide a later revocation',async()=>{
160
+ const f=await fixture();await recordDelivery(f.options,accept);
161
+ await recordDelivery({...f.options,statement:{...f.options.statement,environment:'Staging ',outcome:'revoked'}},accept);
162
+ const value=f.projection().productAcceptance;assert.equal(value.environments.length,1);
163
+ assert.equal(value.environments[0].environment,'staging');assert.equal(value.environments[0].statement.outcome,'revoked');
164
+ });
165
+
166
+ test('R1 G9 harmless Finder metadata does not hide delivery records while malformed entries still fail',async()=>{
167
+ const f=await fixture();await recordDelivery(f.options,accept);
168
+ const dir=path.join(f.specsDir,'.reviews','.delivery');fs.writeFileSync(path.join(dir,'.DS_Store'),'finder metadata');
169
+ assert.equal(readDeliveryRecords(f.specsDir).length,1);assert.equal(f.projection().productAcceptance.status,'recorded');
170
+ fs.mkdirSync(path.join(dir,'garbage'));assert.throws(()=>readDeliveryRecords(f.specsDir));
171
+ });
172
+
173
+ test('R1 G10 a display evidence budget reports unknown without hashing a large artifact',async()=>{
174
+ const f=await fixture();await recordDelivery(f.options,accept);const candidate=deliveryCandidate(f.options);
175
+ const value=deliveryProjection({...f.options,identity,packageDigest:candidate.packageDigest,specificationDigest:candidate.specificationDigest,maxEvidenceBytes:1});
176
+ assert.equal(value.productAcceptance.status,'unknown');assert.equal(value.productAcceptance.environments[0].reason,'delivery_evidence_budget_exceeded');
177
+ });
@@ -81,3 +81,17 @@ for(const mode of ['watchdog','unexpected-exit'])test(`owned same-group worker c
81
81
  await new Promise(resolve=>setTimeout(resolve,50));
82
82
  assert.throws(()=>process.kill(pid,0),{code:'ESRCH'});
83
83
  });
84
+
85
+ test('R1 G11 malformed optional completion display does not change the returned business result',t=>{
86
+ const out=run(t,`ready();process.stdin.once('data',()=>send({requestId:'drive',result:{state:'fixture_completed',completion:{version:1}}}));process.stdin.on('end',()=>process.exit(0));`);
87
+ assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'fixture_completed');
88
+ assert.match(out.stderr,/完成摘要显示失败/);
89
+ });
90
+
91
+ // Codex review: a create captures its baseline before host_ready, and the Git ignore
92
+ // query alone may take GIT_IGNORE_TIMEOUT_MS; the startup budget must not kill it first.
93
+ test('default startup budget outlasts the Git ignore query of the baseline capture',async()=>{
94
+ const {DRIVE_LIVENESS_DEFAULTS}=await import('../runtime/js/cm-ai/drive-core.mjs');
95
+ const {GIT_IGNORE_TIMEOUT_MS}=await import('../runtime/js/cm-ai/review-package.mjs');
96
+ assert(DRIVE_LIVENESS_DEFAULTS.startupMs>GIT_IGNORE_TIMEOUT_MS);
97
+ });
@@ -0,0 +1,32 @@
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 {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath,pathToFileURL} from 'node:url';
8
+ import {CHECK_DRIVE_COPIED_FILES} from './cm-check-drive-files.mjs';
9
+
10
+ const root=fileURLToPath(new URL('..',import.meta.url));
11
+ test('R1 B1 shared driver imports from the original check-only runtime without runner dependencies',t=>{
12
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-light-driver-')));
13
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
14
+ for(const file of CHECK_DRIVE_COPIED_FILES){
15
+ const target=path.join(dir,file);fs.mkdirSync(path.dirname(target),{recursive:true});fs.copyFileSync(path.join(root,file),target);
16
+ }
17
+ for(const file of ['completion-summary.mjs','delivery-evidence.mjs','task-runner.mjs'])
18
+ assert.equal(fs.existsSync(path.join(dir,'runtime/js/cm-ai',file)),false,'test uses the original partial runtime inventory');
19
+ const source=`import {driveHost} from ${JSON.stringify(pathToFileURL(path.join(dir,'runtime/js/cm-ai/drive-core.mjs')).href)};
20
+ import {completionLines,deliveryLines} from ${JSON.stringify(pathToFileURL(path.join(dir,'runtime/js/cm-ai/operator-guidance.mjs')).href)};
21
+ if(typeof driveHost!=='function'||completionLines(null).length!==0||deliveryLines({}).length!==2)process.exitCode=1;`;
22
+ const run=spawnSync(process.execPath,['--input-type=module','-e',source],{cwd:dir,encoding:'utf8'});
23
+ assert.equal(run.status,0,run.stderr);assert.equal(run.stdout,'');
24
+ });
25
+
26
+ test('R1 B1 legacy formatter exports reuse the exact lightweight formatting functions',async()=>{
27
+ const light=await import('../runtime/js/cm-ai/operator-guidance.mjs');
28
+ const completion=await import('../runtime/js/cm-ai/completion-summary.mjs');
29
+ const delivery=await import('../runtime/js/cm-ai/delivery-evidence.mjs');
30
+ assert.equal(typeof light.completionLines,'function');assert.equal(typeof light.deliveryLines,'function');
31
+ assert.equal(completion.completionLines,light.completionLines);assert.equal(delivery.deliveryLines,light.deliveryLines);
32
+ });
@@ -53,6 +53,55 @@ test(`existing observation identity closes without reproduction replay or comple
53
53
  }finally{owner.close();fs.rmSync(root,{recursive:true,force:true});}
54
54
  });
55
55
 
56
+ // A recorded T-OBS observation keeps its identity and archive across new evidence:
57
+ // resume reads the obs.<slug> archive, the continued dossier appends to it, and a
58
+ // second observation exit is recorded without completion (review follow-up).
59
+ test('existing observation identity resumes on new evidence and exits again without completion',async()=>{
60
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-obs-resume-')));
61
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
62
+ const identity={repositoryId:'fixture',runId:'same-run',taskId:'T-OBS-original-identity',attempt:1};
63
+ const configuration={hostContextId:'fixture-host',defect:'Busy; root unknown',reproduction:{cwd,
64
+ command:[process.execPath,'-e',"require('node:fs').appendFileSync('visits','1');process.exit(0)"],
65
+ expectedFailure:{exitCode:1,outputIncludes:'BUSY'},timeoutMs:2000}};
66
+ const options={specsRoot,identity,configuration,create:true};
67
+ let owner=openFixExecution(options,{prepare:async()=>learning});
68
+ try{
69
+ startFixRun({specsRoot,identity,configuration});
70
+ assert.equal((await owner.advance({authorized:true})).stage,'observation');
71
+ const first=owner.finish({authorized:true});
72
+ assert.equal(first.observationRunEnded,true);assert.equal(first.completionEligible,false);
73
+ assert.match(path.basename(first.dossier.path),/^\d{8}-obs\.original-identity\.md$/);
74
+ const archived=fs.readFileSync(first.dossier.path);
75
+ assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'1');
76
+ const exitEvent=fs.readFileSync(path.join(specsRoot,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse).find(row=>row.event==='run_done');
77
+ fs.writeFileSync(path.join(specsRoot,'failure.txt'),'BUSY: new observed failure, synthetic fixture');
78
+ owner=openFixExecution({...options,create:false});
79
+ const prepared=owner.resume({authorized:true,evidenceFiles:['failure.txt']});
80
+ assert.equal(prepared.stage,'observation_resume_prepared');assert.deepEqual(prepared.identity,identity);
81
+ assert.equal(prepared.observationResume.eventId,exitEvent.event_id);
82
+ assert.equal(prepared.observationResume.dossier.sha256,exitEvent.dossier_sha256);
83
+ assert.equal(path.posix.basename(prepared.observationResume.dossier.path),path.basename(first.dossier.path));
84
+ assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'1');
85
+ owner.close();owner=openFixExecution({...options,create:false},{prepare:async()=>learning});
86
+ assert.equal((await owner.advance({authorized:true})).stage,'observation_not_reproduced');
87
+ const draft=owner.publishDossier(),continued=fs.readFileSync(draft.dossier.path);
88
+ assert.equal(draft.dossier.path,first.dossier.path);
89
+ assert.deepEqual(continued.subarray(0,archived.length),archived);
90
+ assert.match(continued.toString(),/恢复观测(仍未完成)/);
91
+ const again=owner.finish({authorized:true});
92
+ assert.equal(again.observationRunEnded,true);assert.equal(again.completionEligible,false);assert.deepEqual(again.identity,identity);
93
+ const rows=fs.readFileSync(path.join(specsRoot,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
94
+ const exits=rows.filter(row=>row.event==='run_done');
95
+ assert.equal(exits.length,2);assert.equal(exits[1].observation_exit_event_id,exitEvent.event_id);
96
+ assert.equal(exits[1].dossier_sha256,draft.dossier.sha256);
97
+ assert.equal(exits[1].phase,'observation');assert.equal(exits[1].result,'observing');
98
+ // Resume re-runs the reproduction exactly once; neither exit replays it.
99
+ assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'11');
100
+ assert(!rows.some(row=>row.event==='task_done'));assert(!fs.existsSync(path.join(specsRoot,'METRICS.md')));
101
+ assert.deepEqual(fs.readdirSync(path.dirname(first.dossier.path)).filter(name=>name.endsWith('.md')),[path.basename(first.dossier.path)]);
102
+ }finally{owner.close();fs.rmSync(root,{recursive:true,force:true});}
103
+ });
104
+
56
105
  for(const taskId of ['T-OBS-../escape','T-OBS-UPPER','T-OTHER-safe','T-OBS-safe/escape','T-OBS-a--b','T-OBS-','T-OBS-foo.md','T-OBS-café','T-OBS-foo\\escape'])
57
106
  test(`observation archive rejects malformed or unsupported id ${taskId}`,()=>{
58
107
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-obs-invalid-')));
@@ -8,7 +8,7 @@ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs'
8
8
  import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
9
9
  import {captureReviewBaseline,createReviewPackage,readReviewPackage} from '../runtime/js/cm-ai/review-package.mjs';
10
10
  import * as presentation from '../runtime/js/cm-ai/review-presentation.mjs';
11
- import {digest,requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ import {digest,requestFor,JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
12
12
 
13
13
  const MiB=1024*1024,STATE_LIMIT=16*MiB,workflow='cm-fix-stages-v1';
14
14
  const copy=value=>JSON.parse(JSON.stringify(value));
@@ -120,13 +120,23 @@ test('a real CM-fix journal stores a repeated canonical review larger than one M
120
120
  assert.deepEqual(JSON.parse(fs.readFileSync(f.stateFile,'utf8')).records[prepared.seq-1],prepared);
121
121
  });
122
122
 
123
- test('ordinary large data, non-fix workflows and false workflow fingerprints retain the one MiB limit',t=>{
123
+ test('the fix workflow keeps its one MiB physical limit for data it cannot compress',t=>{
124
124
  const f=fixture(t);rejectAppend(f,'large-ordinary',{ordinary:'x'.repeat(MiB)});
125
125
  const {reviewPackage}=material(f,64);rejectAppend(f,'small-package-large-ordinary',{reviewPackage,ordinary:'x'.repeat(MiB)});
126
126
  rejectAppend(f,'arbitrary-nested-review',{arbitrary:{reviewPackage:material(f).reviewPackage}});
127
+ });
128
+
129
+ // Ordinary runs store large records as they are, up to the journal record limit
130
+ // (Wue specs8 T-001: a 1.17 MB develop checkpoint). They are never compressed or
131
+ // marked, so the fix workflow's encoding rules above do not apply to them.
132
+ test('non-fix workflows and false workflow fingerprints store large records unencoded up to the journal limit',t=>{
127
133
  for(const mode of ['cm-ai-stages-v1','cm-ai-batch-v1','wrong-fingerprint']){
128
- const other=fixture(t,{mode}),large=material(other).reviewPackage;
129
- rejectAppend(other,'large-review',{reviewPackage:large});
134
+ const other=fixture(t,{mode}),large=material(other).reviewPackage,input=entry(other,'large-review',{reviewPackage:large});
135
+ assert.ok(Buffer.byteLength(JSON.stringify(input.payload))>MiB,mode);
136
+ assert.equal(appendFits(other.store().snapshot(),input),true,mode);
137
+ const saved=other.store().append(input);assert.deepEqual(saved.records.at(-1).payload,input.payload);
138
+ assert.equal(Object.hasOwn(JSON.parse(fs.readFileSync(other.stateFile,'utf8')),'storageEncoding'),false,mode);
139
+ rejectAppend(other,'over-journal-limit',{ordinary:'x'.repeat(JOURNAL_PAYLOAD_LIMIT)});
130
140
  }
131
141
  });
132
142
 
@@ -0,0 +1,69 @@
1
+ // 存档单条上限 4 MiB(Wue specs8 T-001 的审查包约 1.17 MB,1 MiB 时装不下):
2
+ // 默认值、只许调小的测试开关、普通运行的大记录写入与读回、cm-fix 压缩标记不误打。
3
+ import test,{after} from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {spawnSync} from 'node:child_process';
9
+ import {fileURLToPath} from 'node:url';
10
+ import {JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
12
+ import {appendFits} from '../runtime/js/cm-ai/execution-store-limits.mjs';
13
+ import {packFixJournalState} from '../runtime/js/cm-ai/review-presentation.mjs';
14
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
15
+
16
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
17
+ const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-journal-limit-'));
18
+ after(()=>fs.rmSync(isolated,{recursive:true,force:true}));
19
+ const limitWith=value=>{
20
+ const env={...process.env};delete env.CM_JOURNAL_PAYLOAD_LIMIT_TEST;if(value!==undefined)env.CM_JOURNAL_PAYLOAD_LIMIT_TEST=value;
21
+ const run=spawnSync(process.execPath,['--input-type=module','-e',`import {JOURNAL_PAYLOAD_LIMIT} from ${JSON.stringify(path.join(root,'runtime/js/cm-ai/effect-contract.mjs'))};process.stdout.write(String(JOURNAL_PAYLOAD_LIMIT));`],{encoding:'utf8',env});
22
+ assert.equal(run.status,0,run.stderr);return Number(run.stdout);
23
+ };
24
+
25
+ test('默认 4 MiB;测试开关只许调小,调大与非法值忽略',()=>{
26
+ const MiB=1024*1024;
27
+ assert.equal(limitWith(undefined),4*MiB);
28
+ assert.equal(limitWith(String(MiB)),MiB);
29
+ for(const bad of [String(8*MiB),String(4*MiB),'abc','-1',String(1024),'1.5'])assert.equal(limitWith(bad),4*MiB,bad);
30
+ assert.equal(JOURNAL_PAYLOAD_LIMIT,4*MiB,'本测试进程没有设开关');
31
+ });
32
+
33
+ test('普通运行:1.2 MB 的记录写得进、读得回,不被打上 cm-fix 压缩标记',()=>{
34
+ const specsRoot=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'store-')));
35
+ const options={specsRoot,identity:{repositoryId:'size',runId:'size-run'},fingerprints:{workflow:'a'.repeat(64),config:'b'.repeat(64),inputs:'c'.repeat(64)}};
36
+ let store=openExecutionStore({...options,create:true});
37
+ const payload={s:'x'.repeat(1200*1024)};
38
+ try{
39
+ const input={id:'big',kind:'result',payload,expectedRevision:store.snapshot().revision};
40
+ assert.equal(appendFits(store.snapshot(),input),true);
41
+ store.append(input);
42
+ }finally{store.close();}
43
+ store=openExecutionStore({...options,create:false});
44
+ try{assert.deepEqual(store.snapshot().records.at(-1).payload,payload);}finally{store.close();}
45
+ const file=fs.readdirSync(path.join(specsRoot,'.reviews','.execution','size-run')).find(name=>name==='state.json');
46
+ const physical=JSON.parse(fs.readFileSync(path.join(specsRoot,'.reviews','.execution','size-run',file),'utf8'));
47
+ assert.equal(Object.hasOwn(physical,'storageEncoding'),false);
48
+ // 只读发现路径(驾驶员 status/advance 先走它)按同一上限读回,不再写死 1 MiB(Wue specs8 T-001 第 2 轮 limit_exceeded)
49
+ assert.deepEqual(readExecutionSnapshot({specsRoot,identity:{repositoryId:'size',runId:'size-run'}}).records.at(-1).payload,payload);
50
+ });
51
+
52
+ test('整份状态打包:非 cm-fix 运行的大记录不打压缩标记',()=>{
53
+ const state={version:1,identity:{repositoryId:'r',runId:'r'},fingerprints:{workflow:'a'.repeat(64)},revision:'0'.repeat(64),
54
+ records:[{version:1,seq:1,id:'init',kind:'intent',payload:{s:'x'.repeat(1100*1024)},previousDigest:null,digest:'0'.repeat(64)}]};
55
+ assert.equal(Object.hasOwn(packFixJournalState(state),'storageEncoding'),false);
56
+ });
57
+
58
+ // Wue specs8 T-001: the store accepted a 1.2 MB develop checkpoint but the runner's
59
+ // own payload builder still used json()'s 1 MiB default, failed inside the store
60
+ // operation and poisoned the run as store_failure.
61
+ test('the runner builds and bounds a record between 1 MiB and the journal limit, and refuses one above it', async () => {
62
+ const {runnerPayload,runnerPayloadV3,boundRunnerRecord}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
63
+ const big={effectId:'develop-1',blob:'x'.repeat(1200*1024)};
64
+ for(const payload of [runnerPayloadV3('effect-checkpoint',big),runnerPayload('effect-checkpoint',big,2)]){
65
+ assert.ok(Buffer.byteLength(JSON.stringify(payload))>1024*1024);
66
+ assert.doesNotThrow(()=>boundRunnerRecord({id:'runner.000002',kind:'result',payload},2));
67
+ }
68
+ assert.throws(()=>runnerPayloadV3('effect-checkpoint',{blob:'x'.repeat(JOURNAL_PAYLOAD_LIMIT)}));
69
+ });
@@ -0,0 +1,82 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import {mandatoryCheckCoverage} from '../runtime/js/check-coverage.mjs';
4
+
5
+ const xcode = (...selection) => ['/usr/bin/xcodebuild', 'test', '-scheme', 'App', ...selection];
6
+ const coverage = (requiredTests, ...commands) => mandatoryCheckCoverage({requiredTests, commands});
7
+
8
+ test('frozen Xcode test selection rejects omitted classes and skipped methods', () => {
9
+ const required = ['AppUITests/OldTests', 'AppUITests/NewTests'];
10
+ assert.deepEqual(coverage(required, xcode('-only-testing:AppUITests/NewTests')),
11
+ {satisfied: false, missing: required, unverifiable: ['AppUITests/NewTests']});
12
+ assert.deepEqual(coverage(required, xcode('-only-testing:AppUITests')),
13
+ {satisfied:false,missing:required,unverifiable:required});
14
+ assert.equal(coverage(['AppUITests/OldTests'], xcode('-only-testing:AppUITests', '-skip-testing:AppUITests/OldTests/testExisting')).satisfied, false);
15
+ assert.deepEqual(coverage(['AppUITests/OldTests'], ['/usr/bin/xcrun', 'xcodebuild', ...xcode('-only-testing:AppUITests/OldTests').slice(1)]),
16
+ {satisfied:false,missing:['AppUITests/OldTests'],unverifiable:['AppUITests/OldTests']});
17
+ });
18
+
19
+ test('build, enumeration and values named test are not execution selection', () => {
20
+ for (const command of [xcode('-enumerate-tests'), xcode('-showBuildSettings'),
21
+ ['/usr/bin/xcodebuild', '-resultBundlePath', 'test', 'build-for-testing']])
22
+ assert.equal(coverage(['AppUITests/OldTests'], command).satisfied, false, JSON.stringify(command));
23
+ assert.deepEqual(coverage(['AppUITests/OldTests'], xcode('-only-testing', 'AppUITests/OldTests')).unverifiable,
24
+ ['AppUITests/OldTests']);
25
+ });
26
+
27
+ test('a wrapper mentioning a test or xcodebuild cannot prove mandatory coverage', () => {
28
+ for (const command of [['bash', 'checks.sh', 'AppUITests/OldTests'],
29
+ ['echo', 'xcodebuild', 'test'], [process.execPath, 'wrapper.js', 'AppUITests/OldTests']]) {
30
+ const result = coverage(['AppUITests/OldTests'], command);
31
+ assert.deepEqual(result, {satisfied: false, missing: ['AppUITests/OldTests'], unverifiable: ['AppUITests/OldTests']});
32
+ }
33
+ });
34
+
35
+ test('direct Node test files and explicit node --test files are supported without substring matches', () => {
36
+ assert.equal(coverage(['test/a.test.js'], [process.execPath, 'test/a.test.js']).satisfied, true);
37
+ assert.equal(coverage(['test/a.test.js', 'test/b.test.js'], [process.execPath, '--test', './test/a.test.js', 'test/b.test.js']).satisfied, true);
38
+ assert.deepEqual(coverage(['test/a.test.js', 'test/b.test.js'], [process.execPath, '--test', 'test/a.test.js']),
39
+ {satisfied: false, missing: ['test/b.test.js'], unverifiable: []});
40
+ assert.equal(coverage(['test/a.test.js'], [process.execPath, '--test', 'test/a.test.js.bak']).satisfied, false);
41
+ });
42
+
43
+ test('Node filters, discovery, globs and unmodeled options remain unverifiable', () => {
44
+ for (const args of [['--test'], ['--test', 'test/*.test.js'], ['--test', '--test-name-pattern=easy', 'test/a.test.js'],
45
+ ['--test', '--test-shard=1/2', 'test/a.test.js'], ['--test', '--test-only', 'test/a.test.js'],
46
+ ['--eval', "require('./test/a.test.js')"]])
47
+ assert.deepEqual(coverage(['test/a.test.js'], [process.execPath, ...args]),
48
+ {satisfied: false, missing: ['test/a.test.js'], unverifiable: ['test/a.test.js']}, JSON.stringify(args));
49
+ });
50
+
51
+ test('commands from another test family cannot satisfy a frozen test identifier', () => {
52
+ assert.deepEqual(coverage(['test/a.test.js'], xcode()).unverifiable, ['test/a.test.js']);
53
+ assert.deepEqual(coverage(['AppUITests/OldTests.swift'], xcode()).unverifiable, ['AppUITests/OldTests.swift']);
54
+ assert.deepEqual(coverage(['AppUITests/OldTests'], [process.execPath, 'AppUITests/OldTests']).unverifiable, ['AppUITests/OldTests']);
55
+ });
56
+
57
+ test('approved subsets are respected; no contract obligations does not expand the gate', () => {
58
+ assert.deepEqual(coverage(['AppUITests/NewTests'], xcode('-only-testing:AppUITests/NewTests')),
59
+ {satisfied:false,missing:['AppUITests/NewTests'],unverifiable:['AppUITests/NewTests']});
60
+ assert.deepEqual(coverage([], ['bash', 'unknown.sh']), {satisfied: true, missing: [], unverifiable: []});
61
+ assert.deepEqual(coverage(['test/a.js']), {satisfied: false, missing: ['test/a.js'], unverifiable: []});
62
+ });
63
+
64
+ test('invalid frozen test identities are rejected and input is never mutated', () => {
65
+ for (const requiredTests of [null, [''], ['a', 'a'], ['../a'], ['/a'], ['a\0b']])
66
+ assert.throws(() => mandatoryCheckCoverage({requiredTests, commands: []}), {code: 'mandatory_check_contract_invalid'});
67
+ const requiredTests = Object.freeze(['test/a.test.js']);
68
+ const commands = Object.freeze([Object.freeze([process.execPath, '--test', 'test/a.test.js'])]);
69
+ assert.equal(mandatoryCheckCoverage({requiredTests, commands}).satisfied, true);
70
+ });
71
+
72
+ test('a program basename or PATH lookup is not a trusted test engine identity', () => {
73
+ for (const binary of ['node', './node', '/project/node'])
74
+ assert.deepEqual(coverage(['test/a.test.js'], [binary, '--test', 'test/a.test.js']).unverifiable, ['test/a.test.js']);
75
+ for (const binary of ['xcodebuild', '/project/xcodebuild'])
76
+ assert.deepEqual(coverage(['AppUITests/OldTests'], [binary, 'test']).unverifiable, ['AppUITests/OldTests']);
77
+ });
78
+ test('unmodeled Xcode configuration selectors and future flags remain unverifiable',()=>{
79
+ for(const args of [['-only-test-configuration','SmokeOnly'],['-skip-test-configuration','FullTests'],
80
+ ['-testPlan','Subset'],['-future-filter','Easy'],['SWIFT_ACTIVE_COMPILATION_CONDITIONS=OMIT_TESTS']])
81
+ assert.deepEqual(coverage(['AppTests/ImportantTests'],xcode(...args)).unverifiable,['AppTests/ImportantTests']);
82
+ });
@@ -0,0 +1,108 @@
1
+ import assert from 'node:assert/strict';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import {spawnSync} from 'node:child_process';
6
+ import test from 'node:test';
7
+ import {selectedNodeTestFiles} from '../runtime/js/node-test-selection.mjs';
8
+ import {mandatoryCheckCoverage} from '../runtime/js/check-coverage.mjs';
9
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
10
+ import {acceptanceCoverage} from '../runtime/js/cm-ai/acceptance-contract.mjs';
11
+
12
+ const files=['a.test.mjs','b.test.mjs'];
13
+ const argv=(...options)=>[process.execPath,'--test',...options,...files];
14
+ const coverage=command=>mandatoryCheckCoverage({requiredTests:files,commands:[command]});
15
+ const identity={repositoryId:'node-selection',runId:'native-fixture',taskId:'T-001',attempt:1};
16
+ const supported=spawnSync(process.execPath,['--help'],{encoding:'utf8'}).stdout;
17
+
18
+ test('native non-filtering options select exact explicit files without changing argv',()=>{
19
+ for(const options of [
20
+ ['--test-concurrency=2'],['--test-concurrency','2'],
21
+ ['--test-timeout=1000'],['--test-timeout','1000'],
22
+ ...['tap','spec','dot'].flatMap(value=>[['--test-reporter',value],[`--test-reporter=${value}`]]),
23
+ ['--test-reporter=tap','--test-reporter-destination=stdout'],
24
+ ['--test-reporter','spec','--test-reporter-destination','stderr'],
25
+ ['--test-concurrency=2','--test-timeout=1000','--test-reporter=dot','--'],
26
+ ]){
27
+ const command=Object.freeze(argv(...options));
28
+ assert.deepEqual(selectedNodeTestFiles(command),files,JSON.stringify(options));
29
+ assert.deepEqual(coverage(command),{satisfied:true,missing:[],unverifiable:[]});
30
+ }
31
+ assert.deepEqual(selectedNodeTestFiles([process.execPath,'--test-reporter=tap','--test','./a.test.mjs']),['a.test.mjs']);
32
+ });
33
+
34
+ test('every supported option rejects absent, invalid or duplicate values',()=>{
35
+ const cases=[
36
+ ['--test-concurrency'],['--test-timeout'],['--test-reporter'],['--test-reporter-destination'],
37
+ ...['0','-1','1.5','Infinity','2147483648','01',''].flatMap(value=>[
38
+ [`--test-concurrency=${value}`],[`--test-timeout=${value}`]]),
39
+ ['--test-reporter=./custom.mjs'],['--test-reporter=node:custom'],['--test-reporter='],
40
+ ['--test-reporter-destination=stdout'],
41
+ ['--test-reporter=tap','--test-reporter-destination=a.test.mjs'],
42
+ ['--test-reporter=tap','--test-reporter-destination='],
43
+ ['--test','--test'],
44
+ ...[['--test-concurrency=1'],['--test-timeout=1000'],['--test-reporter=tap'],
45
+ ['--test-reporter=tap','--test-reporter-destination=stdout']].map(options=>[...options,...options]),
46
+ ];
47
+ for(const options of cases)assert.deepEqual(coverage(argv(...options)),
48
+ {satisfied:false,missing:files,unverifiable:files},JSON.stringify(options));
49
+ });
50
+
51
+ test('filters, npm wrappers, custom execution hooks and unknown options stay unverifiable',()=>{
52
+ for(const options of [
53
+ ['--test-name-pattern=small'],['--test-skip-pattern=important'],['--test-shard=1/2'],['--test-only'],
54
+ ['--test-rerun-failures=prior.json'],['--test-global-setup=setup.mjs'],['--test-isolation=none'],
55
+ ['--import=preload.mjs'],['--require=preload.cjs'],['--experimental-config-file=config.json'],
56
+ ['--test-update-snapshots'],['--future-filter=small'],['--test-reporter=tap','--test-only'],
57
+ ])assert.deepEqual(coverage(argv(...options)).unverifiable,files,JSON.stringify(options));
58
+ for(const command of [['npm','test','--',...files],['npm','run','test','--',...files],
59
+ ['node','--test',...files],['/project/node','--test',...files]])
60
+ assert.deepEqual(coverage(command).unverifiable,files);
61
+ });
62
+
63
+ test('options stop at the first file and missing files remain missing',()=>{
64
+ for(const command of [[process.execPath,'--test','a.test.mjs','--test-concurrency=1','b.test.mjs'],
65
+ [process.execPath,'--test','*.test.mjs'],[process.execPath,'--test'],
66
+ [process.execPath,'--test-reporter=tap',...files],
67
+ [process.execPath,'--test','--','--test-only',...files]])
68
+ assert.deepEqual(coverage(command).unverifiable,files);
69
+ assert.deepEqual(coverage([process.execPath,'--test','--test-reporter=tap','./a.test.mjs']),
70
+ {satisfied:false,missing:['b.test.mjs'],unverifiable:[]});
71
+ assert.deepEqual(coverage([process.execPath,'--test','--test-reporter=tap','a.test.mjs.bak']),
72
+ {satisfied:false,missing:files,unverifiable:[]});
73
+ });
74
+
75
+ // Real native subprocesses, isolated temporary files, no npm or external access.
76
+ // Options unavailable in an older supported Node are not injected into user
77
+ // commands; here those specific executions are explicitly skipped.
78
+ for(const [name,options] of [
79
+ ['concurrency',['--test-concurrency','1']],
80
+ ['timeout',['--test-timeout=1000']],
81
+ ['tap',['--test-reporter=tap']],['spec',['--test-reporter','spec']],['dot',['--test-reporter=dot']],
82
+ ['destination',['--test-reporter=tap','--test-reporter-destination','stderr']],
83
+ ['separator',['--test-reporter=tap','--',]],
84
+ ])test(`actual host Node execution with ${name} preserves both selected files`,
85
+ {skip:!supported.includes(options[0].split('=')[0])},async()=>{
86
+ const cwd=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-node-selection-')));
87
+ try{
88
+ for(const [index,file] of files.entries())fs.writeFileSync(path.join(cwd,file),
89
+ `import test from 'node:test';import fs from 'node:fs';test('selected ${index}',()=>fs.writeFileSync('ran-${index}','yes'));\n`);
90
+ const command=argv(...options),check=createHostCheck({cwd,commands:[{id:'node-tests',command}],timeoutMs:10000});
91
+ const observed=await check({identity},{signal:new AbortController().signal});
92
+ assert.equal(observed[0].outcome,'passed');assert.deepEqual(observed[0].command,command);
93
+ for(let index=0;index<files.length;index++)assert.equal(fs.readFileSync(path.join(cwd,`ran-${index}`),'utf8'),'yes');
94
+ assert.equal(acceptanceCoverage({requiredTests:files,requiredCommands:[['node',...command.slice(1)]]},observed).satisfied,true);
95
+ }finally{fs.rmSync(cwd,{recursive:true,force:true});}
96
+ });
97
+
98
+ test('native command failure remains failure even when its file selection is modeled',async()=>{
99
+ const cwd=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-node-selection-fail-')));
100
+ try{
101
+ fs.writeFileSync(path.join(cwd,files[0]),"import test from 'node:test';test('failure',()=>{throw Error('fixture');});\n");
102
+ const command=[process.execPath,'--test','--test-reporter=tap',files[0]],
103
+ check=createHostCheck({cwd,commands:[{id:'node-tests',command}],timeoutMs:10000});
104
+ const observed=await check({identity},{signal:new AbortController().signal});
105
+ assert.equal(observed[0].outcome,'failed');
106
+ assert.equal(acceptanceCoverage({requiredTests:[files[0]],requiredCommands:[['node',...command.slice(1)]]},observed).satisfied,false);
107
+ }finally{fs.rmSync(cwd,{recursive:true,force:true});}
108
+ });
@@ -256,10 +256,13 @@ test('importing runtime/js/notify.mjs has no process-exit side effect, also when
256
256
  assert.equal(plain.status,0,plain.stderr);assert.match(plain.stdout,/imported/);
257
257
  // Simulated Node without import.meta.main: copy the whole import graph with
258
258
  // every `import.meta.main` replaced by `undefined`, import that copy.
259
- const copy=(files,dir)=>{for(const file of files){
260
- const target=path.join(dir,file);fs.mkdirSync(path.dirname(target),{recursive:true});
259
+ const copy=(files,dir,root=dir)=>{for(const file of files){
260
+ const target=path.resolve(dir,file);
261
+ assert(target.startsWith(path.resolve(root)+path.sep),`copied module must stay inside the fixture: ${file}`);
262
+ fs.mkdirSync(path.dirname(target),{recursive:true});
261
263
  fs.writeFileSync(target,fs.readFileSync(new URL(file,RUNTIME),'utf8').replaceAll('import.meta.main','undefined'));}};
262
- const runtimeCopy=sandbox(t);copy(graph.concat(['notify-run.mjs']),runtimeCopy);
264
+ const repositoryCopy=sandbox(t),runtimeCopy=path.join(repositoryCopy,'runtime/js');
265
+ copy(graph.concat(['notify-run.mjs']),runtimeCopy,repositoryCopy);
263
266
  const simulated=importChild(path.join(runtimeCopy,'notify.mjs'));
264
267
  assert.equal(simulated.status,0,simulated.stderr);assert.match(simulated.stdout,/imported/);
265
268
  // Negative control: the same simulation does kill an import of the sender,