@aibyzero/cm-workflow 0.16.2 → 0.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +138 -0
  4. package/README.md +2 -2
  5. package/VERSION +1 -1
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +46 -7
  8. package/docs/next-steps.md +110 -0
  9. package/docs/untested-branches.md +24 -18
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
  12. package/runtime/js/cm-ai/cm-ai-admission.mjs +5 -0
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
  15. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
  16. package/runtime/js/cm-ai/drive-core.mjs +68 -0
  17. package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
  18. package/runtime/js/cm-ai/effect-contract.mjs +4 -3
  19. package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
  20. package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
  21. package/runtime/js/cm-ai/host-handoff.mjs +9 -14
  22. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
  23. package/runtime/js/cm-ai/host-session.mjs +2 -2
  24. package/runtime/js/cm-ai/host.mjs +1 -1
  25. package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
  26. package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
  27. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
  28. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
  29. package/runtime/js/cm-ai/task-runner.mjs +41 -8
  30. package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
  31. package/runtime/js/cm-fix/cause-package.mjs +21 -0
  32. package/runtime/js/cm-fix/dossier.mjs +40 -1
  33. package/runtime/js/cm-fix/execution.mjs +360 -83
  34. package/runtime/js/cm-fix/host.mjs +7 -3
  35. package/runtime/js/cm-fix/layout.mjs +14 -6
  36. package/runtime/js/cm-fix/progress.mjs +14 -0
  37. package/runtime/js/cm-fix/protected-edits.mjs +1 -1
  38. package/runtime/js/cm-fix/red-test.mjs +7 -6
  39. package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
  40. package/runtime/js/cm-fix/regression.mjs +16 -10
  41. package/runtime/js/cm-fix/repair.mjs +16 -13
  42. package/runtime/js/cm-fix/test-author.mjs +2 -1
  43. package/runtime/js/cm-fix/test-extension.mjs +45 -0
  44. package/runtime/js/cm-prd/accepted-design.mjs +28 -9
  45. package/runtime/js/cm-prd/analysis.mjs +68 -16
  46. package/runtime/js/cm-prd/change.mjs +21 -1
  47. package/runtime/js/cm-prd/draft-save.mjs +96 -2
  48. package/runtime/js/cm-prd/failed-correction.mjs +51 -0
  49. package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
  50. package/runtime/js/cm-prd/review-correction.mjs +3 -0
  51. package/runtime/js/cm-prd/review-disposition.mjs +33 -15
  52. package/runtime/js/cm-prd/review-findings.mjs +2 -2
  53. package/runtime/js/cm-prd/review-host.mjs +2 -0
  54. package/runtime/js/cm-prd/review-preparation.mjs +28 -1
  55. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  56. package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
  57. package/runtime/js/cm-prd/session.mjs +5 -5
  58. package/runtime/js/cm-prd/split-design.mjs +67 -0
  59. package/runtime/js/cm-prd/summary.mjs +53 -8
  60. package/runtime/js/cm-refactor/workflow.mjs +100 -19
  61. package/scripts/cm-ai-batch-drive.mjs +251 -0
  62. package/scripts/cm-ai-batch-drive.test.mjs +152 -0
  63. package/scripts/cm-ai-contracts.test.mjs +30 -0
  64. package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
  65. package/scripts/cm-ai-drive.mjs +334 -0
  66. package/scripts/cm-ai-drive.test.mjs +251 -0
  67. package/scripts/cm-ai-fix-integration.test.mjs +1 -1
  68. package/scripts/cm-ai-host.mjs +41 -18
  69. package/scripts/cm-ai-host.test.mjs +37 -0
  70. package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
  71. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
  72. package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
  73. package/scripts/cm-ai-review-timeout.test.mjs +30 -0
  74. package/scripts/cm-ai-run.mjs +59 -11
  75. package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
  76. package/scripts/cm-ai-session-chain.test.mjs +261 -0
  77. package/scripts/cm-ai-supersede.test.mjs +320 -0
  78. package/scripts/cm-check-drive.mjs +93 -0
  79. package/scripts/cm-check-drive.test.mjs +62 -0
  80. package/scripts/cm-check-host.test.mjs +47 -0
  81. package/scripts/cm-claude-probe.test.mjs +117 -2
  82. package/scripts/cm-fix-abandon.test.mjs +383 -0
  83. package/scripts/cm-fix-cause-package.test.mjs +31 -1
  84. package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
  85. package/scripts/cm-fix-drive.mjs +168 -0
  86. package/scripts/cm-fix-drive.test.mjs +117 -0
  87. package/scripts/cm-fix-escalation.test.mjs +214 -0
  88. package/scripts/cm-fix-execution.test.mjs +26 -0
  89. package/scripts/cm-fix-host.mjs +4 -2
  90. package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
  91. package/scripts/cm-fix-qa-source.test.mjs +3 -3
  92. package/scripts/cm-fix-session-chain.test.mjs +244 -0
  93. package/scripts/cm-fix-test-extension.test.mjs +246 -0
  94. package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
  95. package/scripts/cm-host-handoff.test.mjs +37 -0
  96. package/scripts/cm-idea-drive.mjs +99 -0
  97. package/scripts/cm-idea-drive.test.mjs +50 -0
  98. package/scripts/cm-init-drive.mjs +191 -0
  99. package/scripts/cm-init-drive.test.mjs +59 -0
  100. package/scripts/cm-log-event.mjs +9 -0
  101. package/scripts/cm-prd-design-phase.test.mjs +355 -15
  102. package/scripts/cm-prd-drive.mjs +308 -0
  103. package/scripts/cm-prd-drive.test.mjs +154 -0
  104. package/scripts/cm-prd-host.mjs +46 -17
  105. package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
  106. package/scripts/cm-prd-review-disposition.test.mjs +133 -7
  107. package/scripts/cm-prd-review-gate.mjs +23 -4
  108. package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
  109. package/scripts/cm-prd-summary.test.mjs +48 -4
  110. package/scripts/cm-refactor-drive.mjs +237 -0
  111. package/scripts/cm-refactor-drive.test.mjs +77 -0
  112. package/scripts/cm-refactor-gaps.test.mjs +276 -0
  113. package/scripts/cm-refactor-host.test.mjs +1 -48
  114. package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
  115. package/scripts/cm-test-drive.mjs +132 -0
  116. package/scripts/cm-test-drive.test.mjs +91 -0
  117. package/scripts/cm-test-session.test.mjs +117 -0
  118. package/scripts/correction-check.test.mjs +38 -0
  119. package/scripts/fixtures/claude-model-marker.mjs +6 -0
  120. package/scripts/fixtures/claude-review-process.mjs +7 -0
  121. package/scripts/fixtures/cm-refactor.mjs +56 -0
  122. package/skills/cm-ai/SKILL.md +1 -1
  123. package/skills/cm-ai/references/N4-review.md +2 -0
  124. package/skills/cm-ai/references/N8-finish.md +1 -0
  125. package/skills/cm-ai/references/js-host.md +80 -3
  126. package/skills/cm-check/references/js-host.md +2 -0
  127. package/skills/cm-fix/SKILL.md +11 -4
  128. package/skills/cm-fix/references/js-host.md +67 -2
  129. package/skills/cm-fix/references/test-extension.md +57 -0
  130. package/skills/cm-idea/references/js-host.md +2 -0
  131. package/skills/cm-init/references/js-host.md +2 -0
  132. package/skills/cm-prd/SKILL.md +8 -8
  133. package/skills/cm-prd/references/js-change-recovery.md +41 -0
  134. package/skills/cm-prd/references/js-host.md +64 -2
  135. package/skills/cm-prd/references/spec-self-check.md +14 -2
  136. package/skills/cm-refactor/SKILL.md +5 -0
  137. package/skills/cm-refactor/references/js-batch.md +3 -1
  138. package/skills/cm-refactor/references/js-host.md +49 -0
  139. package/skills/cm-test/references/js-host.md +5 -0
  140. package/skills/cm-test/references/unit-coverage.md +2 -2
@@ -0,0 +1,320 @@
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 {captureReviewBaseline} from '../runtime/js/cm-ai/review-package.mjs';
7
+ import {createHostHandoff} from '../runtime/js/cm-ai/host-handoff.mjs';
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 {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
14
+ import {createHash} from 'node:crypto';
15
+ import {PassThrough} from 'node:stream';
16
+ import {main as hostMain,withHandoffDiagnostic} from './cm-ai-host.mjs';
17
+ import {prepareReviewedEvidenceSupersession} from '../runtime/js/cm-ai/reviewed-evidence-supersede.mjs';
18
+
19
+ // Reuse the isolated handoff shape from cm-host-handoff.test.mjs. The old
20
+ // receipt deliberately consumes a different byte sequence at the same name.
21
+ test('reviewed handoff collision retains its code and explains both exits',()=>{
22
+ const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-ai-supersede-')));
23
+ try{
24
+ const root=path.join(temp,'code'),reviews=path.join(temp,'reviews');
25
+ fs.mkdirSync(root);fs.mkdirSync(reviews);
26
+ fs.writeFileSync(path.join(root,'a.mjs'),'old');
27
+ fs.writeFileSync(path.join(root,'requirements.md'),'fixture');
28
+ const handoffPath=path.join(reviews,'work-T-002-a1-handoff.json');
29
+ const publish=content=>{
30
+ fs.writeFileSync(path.join(root,'a.mjs'),'old');
31
+ const baseline=captureReviewBaseline({root,
32
+ identity:{repositoryId:'fixture',runId:'run-one',taskId:'T-002',attempt:1},
33
+ scope:['a.mjs'],requirements:['requirements.md']});
34
+ fs.writeFileSync(path.join(root,'a.mjs'),content);
35
+ return createHostHandoff({root,baseline,handoffPath,
36
+ checks:[{id:'unit',command:['node','--test'],outcome:'passed',exitCode:0,evidence:'fixture'}]});
37
+ };
38
+ publish('run one');
39
+ fs.writeFileSync(path.join(reviews,'work-T-002-r1.md'),
40
+ '---\nverdict: approved\nhandoff: work-T-002-a1-handoff.json\n---\n');
41
+ assert.throws(()=>publish('run two'),error=>{
42
+ assert.equal(error.code,'handoff_exists');
43
+ assert.match(error.reason,/--revise-qa-config/);
44
+ assert.match(error.reason,/--rerun-blocked-qa/);
45
+ assert.match(error.reason,/--supersede-reviewed-evidence/);
46
+ return true;
47
+ });
48
+ }finally{fs.rmSync(temp,{recursive:true,force:true});}
49
+ });
50
+
51
+ function runFixture(){
52
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-ai-supersede-run-')));
53
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.work';
54
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
55
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'old\n');
56
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'fixture\n');
57
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
58
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-002: fixture\n');
59
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
60
+ return {root,codeProject,specsDir,feature,tasksPath:path.join(specsDir,feature,'tasks.md'),
61
+ reviewsDir:path.join(specsDir,'.reviews')};
62
+ }
63
+ const identityFor=runId=>({repositoryId:'supersede-fixture',runId,taskId:'T-002',attempt:1});
64
+ const requestFor=identity=>({version:1,operation:'advance',requestId:'advance',identity});
65
+ function executionFor(f,content,verdict='blocked',qaResult=null){
66
+ const reviewer={id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',
67
+ allowed:true,available:true,contexts:['review-one','review-two'],run:(request,{onEvent})=>{
68
+ onEvent({event:'thread.started',provider_thread:`thread-${request.identity.runId}`});
69
+ onEvent({event:'turn.started',item_type:null});onEvent({event:'item.completed',item_type:'agent_message'});
70
+ onEvent({event:'turn.completed',item_type:null});onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
71
+ return {status:'succeeded',value:{verdict,packageDigest:request.payload.reviewPackage.packageDigest,
72
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};
73
+ }};
74
+ const execution={configuration:{kind:'synthetic-host-v1'},timeoutMs:2000,excludedContexts:['control'],
75
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({
76
+ requestedModel:'fixture',worker:async()=>{fs.writeFileSync(path.join(f.codeProject,'a.mjs'),content);
77
+ return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
78
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
79
+ reviewers:[reviewer],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control'],
80
+ authorize:(request,{authorizationAt})=>{
81
+ const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${request.identity.runId}`,
82
+ adapterId:'codex-review-adapter',invocationId:request.invocationId,requestDigest:request.requestDigest,
83
+ identity:request.identity,reviewerId:'reviewer',logicalContextId:request.contextId,
84
+ packageDigest:request.payload.reviewPackage.packageDigest,hostContextId:'control',decisionId:'approved',
85
+ decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
86
+ return {...body,grantDigest:digest(body)};
87
+ }},hostDecision:{status:'approved'},check:createHostCheck({cwd:f.codeProject,
88
+ commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]})};
89
+ if(qaResult){
90
+ execution.qaDecisionProvider={timeoutMs:1000,decide:async binding=>({decisionId:'qa-decision',
91
+ identity:binding.identity,packageDigest:binding.packageDigest,status:'triggered',
92
+ reason:'fixture qa',score:null,at:'2026-09-24T00:00:00Z'})};
93
+ execution.qaExecutor={mode:'commands',caseCount:1,timeoutMs:2000,run:async binding=>{
94
+ const report=path.join(f.reviewsDir,`${binding.testRunId}-execution.md`);
95
+ fs.writeFileSync(report,`# Fixture ${qaResult} QA\n`);
96
+ return {result:qaResult,passed:qaResult==='PASS'?1:0,failed:0,blocked:qaResult==='BLOCKED'?1:0,report};
97
+ }};
98
+ }
99
+ return execution;
100
+ }
101
+ async function start(f,runId,content,options={},verdict='blocked',qaResult=null){
102
+ const identity=identityFor(runId),definition={version:1,specsDir:f.specsDir,codeProject:f.codeProject,
103
+ feature:f.feature,identity,scope:['a.mjs'],requirements:['requirements.md']};
104
+ const run=await openControlRun(definition,'create',executionFor(f,content,verdict,qaResult),options);
105
+ try{return await run.host.handle(requestFor(identity));}finally{run.close();}
106
+ }
107
+
108
+ test('explicit restart archives reviewed bytes and records a new-run authorization',async()=>{
109
+ const f=runFixture();
110
+ try{
111
+ const first=await start(f,'run-one-0001','first\n');
112
+ assert.equal(first.state,'blocked');
113
+ fs.writeFileSync(path.join(f.reviewsDir,'work-T-002-a2-handoff.json'),'{}\n');
114
+ fs.writeFileSync(path.join(f.reviewsDir,'work-T-002-correction-r1.md'),'# Old correction evidence\n');
115
+ fs.writeFileSync(path.join(f.reviewsDir,'work-T-002-qa-extra.json'),'{}\n');
116
+ fs.writeFileSync(path.join(f.reviewsDir,'work-T-002-r2.md'),'# Old second review\n');
117
+ const oldNames=['work-T-002-a1-handoff.json','work-T-002-a2-handoff.json',
118
+ 'work-T-002-correction-r1.md','work-T-002-qa-extra.json','work-T-002-r1.md','work-T-002-r2.md'];
119
+ const old=new Map(oldNames.map(name=>[name,fs.readFileSync(path.join(f.reviewsDir,name))]));
120
+ const priorJournal=fs.readFileSync(path.join(f.reviewsDir,'.execution','run-one-0001','state.json'));
121
+ const without=await start(f,'run-two-0002','second\n');
122
+ assert.equal(without.code,'handoff_exists');assert.equal(without.outcome,'blocked');
123
+ assert.match(without.reason,/--supersede-reviewed-evidence/);
124
+ assert(oldNames.every(name=>fs.existsSync(path.join(f.reviewsDir,name))));
125
+ const plainState=JSON.parse(fs.readFileSync(path.join(f.reviewsDir,'.execution','run-two-0002','state.json')));
126
+ assert(plainState.records.every(row=>row.payload.type!=='evidence-superseded'));
127
+ assert.equal(plainState.records[0].payload.version,3);
128
+ const second=await start(f,'run-three-0003','third\n',{supersedeReason:'Operator confirmed genuine restart'});
129
+ assert.equal(second.state,'blocked');
130
+ const archive=path.join(f.reviewsDir,'.superseded');
131
+ for(const [name,bytes] of old){
132
+ const sha=createHash('sha256').update(bytes).digest('hex');
133
+ assert.deepEqual(fs.readFileSync(path.join(archive,`${name}.${sha.slice(0,16)}`)),bytes);
134
+ }
135
+ const state=JSON.parse(fs.readFileSync(path.join(f.reviewsDir,'.execution','run-three-0003','state.json')));
136
+ const record=state.records.find(row=>row.payload.type==='evidence-superseded')?.payload.record;
137
+ assert(record);assert.deepEqual(record.previousRunIds,['run-one-0001','run-two-0002']);
138
+ assert.deepEqual(record.files.map(file=>file.name),oldNames);
139
+ for(const file of record.files)assert.equal(file.sha256,
140
+ createHash('sha256').update(old.get(file.name)).digest('hex'));
141
+ assert.equal(record.reason,'Operator confirmed genuine restart');
142
+ assert.deepEqual(fs.readFileSync(path.join(f.reviewsDir,'.execution','run-one-0001','state.json')),priorJournal);
143
+ assert(fs.existsSync(path.join(f.reviewsDir,'work-T-002-r1.md')));
144
+ const newStateFile=path.join(f.reviewsDir,'.execution','run-three-0003','state.json');
145
+ const beforeResume=fs.readFileSync(newStateFile);
146
+ const identity=identityFor('run-three-0003');
147
+ const definition={version:1,specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
148
+ identity,scope:['a.mjs'],requirements:['requirements.md']};
149
+ const resumed=await openControlRun(definition,'resume',executionFor(f,'third\n'));
150
+ resumed.close();assert.deepEqual(fs.readFileSync(newStateFile),beforeResume);
151
+ const events=fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse)
152
+ .filter(row=>row.event==='supersede'&&row.run_id==='run-three-0003');
153
+ assert.equal(events.length,1);
154
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
155
+ });
156
+
157
+ test('reviewed run with BLOCKED QA reproduces the collision after the task is reopened',async()=>{
158
+ const f=runFixture();
159
+ try{
160
+ const first=await start(f,'run-qa-one-0001','first\n',{},'approved','BLOCKED');
161
+ assert.equal(first.code,'qa_result_blocked');
162
+ assert.match(fs.readFileSync(f.tasksPath,'utf8'),/\[x\] T-002/);
163
+ await assert.rejects(start(f,'run-qa-refused-0002','second\n',{supersedeReason:'restart'}),error=>
164
+ error.code==='supersede_unavailable'&&/先将该任务改回 - \[ \]/.test(error.reason)
165
+ &&/--supersede-reviewed-evidence/.test(error.reason)&&/--supersede-reason/.test(error.reason));
166
+ // N5 checked the task before N6. The explicit restart rule requires an
167
+ // operator to reopen it; this test keeps that precondition visible.
168
+ fs.writeFileSync(f.tasksPath,'- [ ] T-002: fixture\n');
169
+ const without=await start(f,'run-qa-two-0002','second\n');
170
+ assert.equal(without.code,'handoff_exists');assert.match(without.reason,/--rerun-blocked-qa/);
171
+ const restarted=await start(f,'run-qa-three-0003','third\n',{supersedeReason:'Reopen after blocked QA'});
172
+ assert.equal(restarted.state,'blocked');
173
+ const record=JSON.parse(fs.readFileSync(path.join(f.reviewsDir,'.execution','run-qa-three-0003','state.json')))
174
+ .records.find(row=>row.payload.type==='evidence-superseded')?.payload.record;
175
+ assert(record);assert.deepEqual(record.previousRunIds,['run-qa-one-0001','run-qa-two-0002']);
176
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
177
+ });
178
+
179
+ test('a normally completed previous task cannot be superseded',async()=>{
180
+ const f=runFixture();
181
+ try{
182
+ const completed=await start(f,'run-complete-0001','done\n',{},'approved');
183
+ assert.equal(completed.state,'fixture_completed');
184
+ assert.match(fs.readFileSync(f.tasksPath,'utf8'),/\[x\] T-002/);
185
+ await assert.rejects(start(f,'run-refused-0002','again\n',{supersedeReason:'restart'}),
186
+ error=>error.code==='supersede_unavailable'&&/已将任务标为完成/.test(error.reason));
187
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
188
+ });
189
+
190
+ test('a completed journal with passed QA still refuses supersession after the task is reopened',async()=>{
191
+ const f=runFixture();
192
+ try{
193
+ const completed=await start(f,'run-complete-reopened-0001','done\n',{},'approved','PASS');
194
+ assert.equal(completed.state,'fixture_completed');
195
+ const rows=fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
196
+ assert(rows.some(row=>row.run_id==='run-complete-reopened-0001'&&row.event==='test_run'
197
+ &&row.phase==='complete'&&row.result==='PASS'));
198
+ fs.writeFileSync(f.tasksPath,'- [ ] T-002: fixture\n');
199
+ await assert.rejects(start(f,'run-refused-reopened-0002','again\n',{supersedeReason:'restart'}),
200
+ error=>error.code==='supersede_unavailable'&&/已完成或 QA 已通过/.test(error.reason));
201
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
202
+ });
203
+
204
+ test('supersession recognizes the optional task strikethrough used by admission',async()=>{
205
+ const f=runFixture();
206
+ try{
207
+ assert.equal((await start(f,'run-struck-0001','first\n')).state,'blocked');
208
+ fs.writeFileSync(f.tasksPath,'- [ ] ~~T-002: fixture\n');
209
+ const record=prepareReviewedEvidenceSupersession({specsDir:f.specsDir,codeProject:f.codeProject,
210
+ feature:f.feature,identity:identityFor('run-struck-0002'),reason:'restart',tasksPath:f.tasksPath});
211
+ assert.deepEqual(record.previousRunIds,['run-struck-0001']);
212
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
213
+ });
214
+
215
+ test('lsof warnings do not hide a closed writer, but other diagnostics fail closed',async()=>{
216
+ const {oldWriterOpen}=await import('../runtime/js/cm-ai/reviewed-evidence-supersede.mjs');
217
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-ai-lsof-')));
218
+ try{
219
+ const tool=path.join(root,'lsof');
220
+ const write=(warning,code,stdout='')=>{fs.writeFileSync(tool,`#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(warning)});process.stdout.write(${JSON.stringify(stdout)});process.exit(${code});\n`);fs.chmodSync(tool,0o755);};
221
+ write("lsof: WARNING: can't stat() fuse file system\n",1);
222
+ assert.equal(oldWriterOpen(root,'old-run',{lsofPath:tool}),false);
223
+ write("lsof: WARNING: can't stat() network file system\n",0,'p123\n');
224
+ assert.equal(oldWriterOpen(root,'old-run',{lsofPath:tool}),true);
225
+ write('lsof: unexpected error\n',1);
226
+ assert.throws(()=>oldWriterOpen(root,'old-run',{lsofPath:tool}),
227
+ error=>error.code==='supersede_unavailable'&&/无法核对/.test(error.reason));
228
+ fs.chmodSync(tool,0o644);
229
+ assert.throws(()=>oldWriterOpen(root,'old-run',{lsofPath:tool}),
230
+ error=>error.code==='supersede_unavailable'&&/无法核对/.test(error.reason));
231
+ }finally{fs.rmSync(root,{recursive:true,force:true});}
232
+ });
233
+
234
+ test('a terminal journal is not supersedable while its old writer is still open',async()=>{
235
+ const f=runFixture();
236
+ try{
237
+ const identity=identityFor('run-held-0001');
238
+ const definition={version:1,specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
239
+ identity,scope:['a.mjs'],requirements:['requirements.md']};
240
+ const held=await openControlRun(definition,'create',executionFor(f,'first\n'));
241
+ try{
242
+ assert.equal((await held.host.handle(requestFor(identity))).state,'blocked');
243
+ await assert.rejects(start(f,'run-refused-0002','second\n',{supersedeReason:'restart'}),
244
+ error=>error.code==='supersede_unavailable'&&/writer 仍被进程持有/.test(error.reason));
245
+ }finally{held.close();}
246
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
247
+ });
248
+
249
+ test('supersede refuses missing reason, no prior evidence, an active run, and a checked task',async()=>{
250
+ const f=runFixture();
251
+ try{
252
+ await assert.rejects(start(f,'run-empty-0001','new\n',{supersedeReason:'restart'}),{code:'supersede_unavailable'});
253
+ const identity=identityFor('run-active-0002');
254
+ const definition={version:1,specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
255
+ identity,scope:['a.mjs'],requirements:['requirements.md']};
256
+ const active=await openControlRun(definition,'create',executionFor(f,'first\n'));
257
+ try{
258
+ await assert.rejects(start(f,'run-refused-0003','second\n',{supersedeReason:'restart'}),
259
+ error=>error.code==='supersede_unavailable'&&/仍可继续/.test(error.reason));
260
+ }finally{active.close();}
261
+ const first=await start(f,'run-blocked-0004','first\n');assert.equal(first.state,'blocked');
262
+ await assert.rejects(start(f,'run-refused-0005','second\n',{supersedeReason:''}),
263
+ error=>error.code==='supersede_unavailable'&&/500 字节/.test(error.reason));
264
+ await assert.rejects(start(f,'run-refused-0007','second\n',{supersedeReason:'汉'.repeat(167)}),
265
+ error=>error.code==='supersede_unavailable'&&/500 字节/.test(error.reason));
266
+ fs.writeFileSync(f.tasksPath,'- [x] T-002: fixture\n');
267
+ await assert.rejects(start(f,'run-refused-0006','second\n',{supersedeReason:'restart'}),
268
+ error=>error.code==='supersede_unavailable'&&/已将任务标为完成/.test(error.reason));
269
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
270
+ });
271
+
272
+ test('CLI requires both create-time supersession flags before opening a run',async()=>{
273
+ const output=new PassThrough(),error=new PassThrough();let stderr='';error.on('data',chunk=>stderr+=chunk);
274
+ const base=['serve','--config','/missing/run.json','--mode','create','--host-context','fixture','--allow-development'];
275
+ assert.equal(await hostMain([...base,'--supersede-reviewed-evidence'],
276
+ {input:new PassThrough(),output,error}),1);
277
+ assert.match(stderr,/supersede_unavailable/);
278
+ stderr='';
279
+ assert.equal(await hostMain([...base,'--supersede-reason','restart'],
280
+ {input:new PassThrough(),output,error}),1);
281
+ assert.match(stderr,/supersede_unavailable/);
282
+ });
283
+
284
+ test('host stderr carries the handoff recovery hint while the result keeps its code',async()=>{
285
+ const error=new PassThrough();let stderr='';error.on('data',chunk=>stderr+=chunk);
286
+ const host=withHandoffDiagnostic({handle:async()=>({outcome:'blocked',code:'handoff_exists'})},error);
287
+ assert.equal((await host.handle({operation:'advance'})).code,'handoff_exists');
288
+ assert.match(stderr,/\[host\].*--revise-qa-config.*--rerun-blocked-qa.*--supersede-reviewed-evidence/);
289
+ });
290
+
291
+ test('resume completes an interrupted archive from the durable new-run record',async()=>{
292
+ const f=runFixture();
293
+ try{
294
+ await start(f,'run-first-0001','first\n');
295
+ const identity=identityFor('run-next-0002');
296
+ const definition={version:1,specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
297
+ identity,scope:['a.mjs'],requirements:['requirements.md']};
298
+ const originalLink=fs.linkSync;
299
+ fs.linkSync=function(source,target){
300
+ if(source.endsWith('work-T-002-r1.md'))throw Object.assign(new Error('injected archival crash'),{code:'EIO'});
301
+ return originalLink.call(fs,source,target);
302
+ };
303
+ try{await assert.rejects(openControlRun(definition,'create',executionFor(f,'second\n'),
304
+ {supersedeReason:'restart after blocked review'}),/injected archival crash/);}
305
+ finally{fs.linkSync=originalLink;}
306
+ const stateFile=path.join(f.reviewsDir,'.execution',identity.runId,'state.json');
307
+ const before=fs.readFileSync(stateFile);
308
+ const record=JSON.parse(before).records.find(row=>row.payload.type==='evidence-superseded')?.payload.record;
309
+ assert(record);assert.equal(record.files.length,2);
310
+ const resumed=await openControlRun(definition,'resume',executionFor(f,'second\n'));
311
+ try{
312
+ assert.deepEqual(fs.readFileSync(stateFile),before);
313
+ assert(record.files.every(file=>fs.existsSync(path.join(f.reviewsDir,'.superseded',
314
+ `${file.name}.${file.sha256.slice(0,16)}`))));
315
+ assert(record.files.every(file=>!fs.existsSync(path.join(f.reviewsDir,file.name))));
316
+ const result=await resumed.host.handle(requestFor(identity));
317
+ assert.equal(result.state,'blocked');assert(fs.existsSync(path.join(f.reviewsDir,'work-T-002-r1.md')));
318
+ }finally{resumed.close();}
319
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
320
+ });
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ // cm-check 请求表(由 cm-check-host.mjs -> runtime/js/cm-check/host.mjs 推导):
3
+ // start: check_runtime;host.mjs start() 调用 bridge.call('check_runtime')。本驾驶员实际运行
4
+ // PLAN.checks 中与 cm-check-entry.mjs createCmCheckInvocation 完全相同的 checker+args。
5
+ // start (机械成功且非 --quick): check_semantic;host.mjs start() 的第二个 call,人工判断。
6
+ // status/cancel: 无请求;host.mjs handle()。host-session.mjs operationNames 允许 start/status/cancel。
7
+ // 该宿主没有持久会话;跨进程 resume 必须拒绝。
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import {spawnSync} from 'node:child_process';
11
+ import {fileURLToPath} from 'node:url';
12
+ import {createCmCheckInvocation} from './cm-check-entry.mjs';
13
+ import {loadConfig} from './cm-workflow-config.mjs';
14
+ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
15
+
16
+ const HOST=fileURLToPath(new URL('./cm-check-host.mjs',import.meta.url));
17
+ const KNOWN=new Set(['start','status','cancel']);
18
+ const optionalIds=['statusline','updater','subagents','isolated_review','external_browser'];
19
+ const obj=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
20
+ const nonempty=value=>typeof value==='string'&&value.trim().length>0;
21
+ function valid(ok,label){if(!ok)stop(2,`答案格式错误:${label}`);}
22
+ function semantic(value,root){
23
+ valid(obj(value)&&Object.keys(value).sort().join(',')==='checks,optional','check-semantic.json');
24
+ valid(Array.isArray(value.checks)&&value.checks.length===8&&new Set(value.checks.map(x=>x.id)).size===8,'check-semantic.json.checks');
25
+ for(const row of value.checks){
26
+ valid(obj(row)&&Object.keys(row).sort().join(',')==='evidence,findings,id,status'
27
+ &&Number.isInteger(row.id)&&row.id>=1&&row.id<=8
28
+ &&['passed','failed','blocked','not_applicable'].includes(row.status)
29
+ &&Array.isArray(row.evidence)&&Array.isArray(row.findings)&&row.findings.every(nonempty)
30
+ &&(row.status==='passed'?row.findings.length===0&&row.evidence.length>0:row.findings.length>0)
31
+ &&(row.status!=='failed'||row.evidence.length>0)
32
+ &&(row.status!=='not_applicable'||[1,7].includes(row.id)),`check-semantic.json.checks[${row.id}]`);
33
+ for(const evidence of row.evidence){
34
+ valid(obj(evidence)&&Object.keys(evidence).sort().join(',')==='line,path'
35
+ &&typeof evidence.path==='string'&&!path.isAbsolute(evidence.path)
36
+ &&!evidence.path.split('/').includes('..')&&!evidence.path.includes('\\')
37
+ &&Number.isSafeInteger(evidence.line)&&evidence.line>0,`check-semantic.json evidence ${row.id}`);
38
+ const file=path.join(root,evidence.path);
39
+ valid(fs.existsSync(file)&&fs.lstatSync(file).isFile()&&!fs.lstatSync(file).isSymbolicLink()
40
+ &&fs.realpathSync(file).startsWith(root+path.sep)
41
+ &&evidence.line<=fs.readFileSync(file,'utf8').split('\n').length,
42
+ `check-semantic.json evidence ${evidence.path}:${evidence.line}`);
43
+ }
44
+ }
45
+ valid(Array.isArray(value.optional)&&value.optional.length===optionalIds.length
46
+ &&new Set(value.optional.map(x=>x.id)).size===optionalIds.length,'check-semantic.json.optional');
47
+ for(const row of value.optional)valid(obj(row)&&Object.keys(row).sort().join(',')==='id,reason,status'
48
+ &&optionalIds.includes(row.id)&&['configured','degraded','unknown'].includes(row.status)
49
+ &&nonempty(row.reason),'check-semantic.json.optional');
50
+ }
51
+ function main(){
52
+ if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
53
+ process.stdout.write('用法: cm-check-drive.mjs --plan PLAN.json <start|status|cancel>\nPLAN: skillDir, project, optional config/quick, checks:[{command:[checker,...args]}], answers。start 的机械证据由实际命令产生;check-semantic.json 只存人工判断。宿主没有跨进程恢复。\n');return;
54
+ }
55
+ const {plan,operation,base}=loadPlanFile({name:'cm-check-drive.mjs',known:KNOWN});
56
+ requireFields(plan,['skillDir','project']);
57
+ if(plan.mode==='resume')stop(2,'cm-check 宿主没有持久会话,不能 resume');
58
+ const skillDir=path.resolve(base,plan.skillDir),project=path.resolve(base,plan.project);
59
+ const config=plan.config?path.resolve(base,plan.config):undefined;
60
+ let invocation;
61
+ try{invocation=createCmCheckInvocation({skillDir,project,...(config?{config}:{})});}
62
+ catch(error){stop(2,`宿主输入无效: ${error.code??error.message}`);}
63
+ if(config)try{loadConfig({projectRoot:project,configPath:config});}
64
+ catch(error){stop(2,`PLAN.config 无效: ${config}: ${error.message}`);}
65
+ const checks=plan.checks;
66
+ if(operation==='start'){
67
+ if(!Array.isArray(checks)||checks.length!==1||checks[0]?.id!=='check_runtime'
68
+ ||!Array.isArray(checks[0].command)||checks[0].command.some(x=>typeof x!=='string')
69
+ ||JSON.stringify(checks[0].command)!==JSON.stringify([invocation.checker,...invocation.args]))
70
+ stop(2,'步骤 start 会反问 check_runtime,PLAN.checks 缺少与宿主声明完全一致的真实 checker 命令');
71
+ }
72
+ const answers=plan.answers?path.resolve(base,plan.answers):null;
73
+ const answer=preflightAnswers(operation==='start'&&!plan.quick?['check_semantic']:[],kind=>{
74
+ const file=path.join(answers??base,'check-semantic.json');
75
+ const value=readJson(file,kind);
76
+ if(value===undefined)stop(2,`步骤 start 会反问 ${kind},但答案文件不存在: ${file}`);
77
+ semantic(value,invocation.workflowRoot);return value;
78
+ });
79
+ driveHost({host:HOST,args:['serve','--skill-dir',skillDir,'--project',project,...(config?['--config',config]:[]),...(plan.quick?['--quick']:[])],
80
+ cwd:project,operation,answers:answer,answerFor:row=>{
81
+ if(row.kind==='check_semantic')return {sourceDigest:row.payload.sourceDigest,...answer.check_semantic};
82
+ if(row.kind!=='check_runtime')return null;
83
+ if(JSON.stringify([row.payload?.invocation?.checker,...(row.payload?.invocation?.args??[])])
84
+ !==JSON.stringify(checks[0].command))return null;
85
+ const [command,...args]=checks[0].command;
86
+ const run=spawnSync(command,args,{cwd:project,encoding:'utf8',maxBuffer:16*1024*1024});
87
+ const output=(run.stdout??'')+(run.stderr??'');
88
+ stderr(`实际执行 check_runtime,exit ${run.status??'unavailable'}`);
89
+ return {exitCode:run.error||run.signal?null:run.status,output,
90
+ evidence:`drive actual checker execution: ${command}; exit ${run.status??'unavailable'}${run.error?`; ${run.error.code??run.error.message}`:''}`};
91
+ }});
92
+ }
93
+ main();
@@ -0,0 +1,62 @@
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} from 'node:url';
8
+
9
+ const root=fileURLToPath(new URL('..',import.meta.url));
10
+ function fixture(t,exit=0){
11
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-drive-')));
12
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
13
+ for(const file of ['scripts/cm-check-entry.mjs','scripts/cm-check-host.mjs','scripts/cm-check-drive.mjs',
14
+ 'scripts/cm-workflow-config.mjs','runtime/js/cm-check/host.mjs','runtime/js/cm-ai/drive-core.mjs',
15
+ 'runtime/js/cm-ai/host-tool-bridge.mjs','runtime/js/cm-ai/host-session.mjs','runtime/js/cm-ai/effect-contract.mjs',
16
+ 'runtime/js/cm-ai/contracts.mjs','runtime/js/cm-init/draft-inspection.mjs','skills/cm-check/SKILL.md']){
17
+ fs.mkdirSync(path.dirname(path.join(dir,file)),{recursive:true});fs.copyFileSync(path.join(root,file),path.join(dir,file));
18
+ }
19
+ fs.writeFileSync(path.join(dir,'VERSION'),'0.0.0\n');fs.writeFileSync(path.join(dir,'README.md'),'# Fixture\n');
20
+ const project=path.join(dir,'project');fs.mkdirSync(project);
21
+ const marker=path.join(dir,'marker');
22
+ fs.writeFileSync(path.join(dir,'scripts/cm-check-runtime.sh'),`#!/bin/sh\nprintf 'real stdout\\n'; printf 'real stderr\\n' >&2; printf x >> '${marker}'; exit ${exit}\n`,{mode:0o755});
23
+ const answers=path.join(dir,'answers');fs.mkdirSync(answers);
24
+ const report={checks:Array.from({length:8},(_,i)=>({id:i+1,status:'passed',evidence:[{path:'skills/cm-check/SKILL.md',line:1}],findings:[]})),
25
+ optional:['statusline','updater','subagents','isolated_review','external_browser'].map(id=>({id,status:'degraded',reason:'Fixture unavailable'}))};
26
+ fs.writeFileSync(path.join(answers,'check-semantic.json'),JSON.stringify(report));
27
+ const checker=path.join(dir,'scripts/cm-check-runtime.sh');
28
+ const plan=(over={})=>({skillDir:path.join(dir,'skills/cm-check'),project,answers,
29
+ checks:[{id:'check_runtime',command:[checker,'--project',project,'--print-effective']}],...over});
30
+ const drive=(value,operation='start')=>{
31
+ const file=path.join(dir,'plan.json');fs.writeFileSync(file,JSON.stringify(value));
32
+ return spawnSync(process.execPath,[path.join(dir,'scripts/cm-check-drive.mjs'),'--plan',file,operation],{encoding:'utf8'});
33
+ };
34
+ return {dir,project,marker,answers,report,plan,drive};
35
+ }
36
+ test('real host: actual checker once, then semantic assessment; status is read only',t=>{
37
+ const f=fixture(t),run=f.drive(f.plan());assert.equal(run.status,0,run.stderr);
38
+ const value=JSON.parse(run.stdout).result;assert.equal(value.result.overall,'PASSED');
39
+ assert.equal(value.mechanical.output,'real stdout\nreal stderr\n');assert.equal(fs.readFileSync(f.marker,'utf8'),'x');
40
+ const status=f.drive(f.plan({answers:undefined,checks:undefined}),'status');
41
+ assert.equal(status.status,0,status.stderr);assert.equal(JSON.parse(status.stdout).result.stage,'ready');
42
+ assert.equal(fs.readFileSync(f.marker,'utf8'),'x');
43
+ });
44
+ test('real nonzero checker overrides static passed evidence and stops semantics',t=>{
45
+ const f=fixture(t,7);fs.writeFileSync(path.join(f.answers,'check-runtime.json'),JSON.stringify({exitCode:0}));
46
+ const run=f.drive(f.plan());assert.equal(run.status,0,run.stderr);
47
+ assert.equal(JSON.parse(run.stdout).result.result.overall,'FAILED');assert.equal(fs.readFileSync(f.marker,'utf8'),'x');
48
+ });
49
+ test('preflight missing answer, malformed answer, missing runner, and false resume leave no checker execution',t=>{
50
+ const f=fixture(t);fs.rmSync(path.join(f.answers,'check-semantic.json'));
51
+ let run=f.drive(f.plan());assert.equal(run.status,2);assert.match(run.stderr,/check-semantic\.json/);
52
+ fs.writeFileSync(path.join(f.answers,'check-semantic.json'),'{}');
53
+ run=f.drive(f.plan());assert.equal(run.status,2);assert.match(run.stderr,/答案格式错误/);
54
+ run=f.drive(f.plan({checks:undefined}));assert.equal(run.status,2);assert.match(run.stderr,/PLAN\.checks/);
55
+ run=f.drive(f.plan({mode:'resume'}));assert.equal(run.status,2);assert.match(run.stderr,/不能 resume/);
56
+ assert.equal(fs.existsSync(f.marker),false);
57
+ });
58
+ test('quick mode needs real runner and returns mechanical-only',t=>{
59
+ const f=fixture(t);fs.rmSync(path.join(f.answers,'check-semantic.json'));
60
+ const run=f.drive(f.plan({quick:true}));assert.equal(run.status,0,run.stderr);
61
+ assert.equal(JSON.parse(run.stdout).result.result.overall,'MECHANICAL_ONLY');
62
+ });
@@ -54,6 +54,53 @@ test('mechanical failure stops semantics, repeated start never retries',async t=
54
54
  const value=await host.handle({requestId:'start',operation:'start'});assert.equal(value.result.overall,'FAILED');assert.equal(value.result.semanticChecked,false);
55
55
  assert.match(value.mechanical.output,/original stderr/);await assert.rejects(()=>host.handle({requestId:'again',operation:'start'}),/check_already_started/);assert.equal(calls,1);
56
56
  });
57
+ for(const {name,statuses,core,overall} of [
58
+ {name:'all configured',statuses:['configured'],core:'passed',overall:'PASSED'},
59
+ {name:'all degraded',statuses:['degraded'],core:'passed',overall:'PASSED'},
60
+ {name:'all unknown',statuses:['unknown'],core:'passed',overall:'PASSED'},
61
+ {name:'mixed statuses',statuses:['unknown','configured','degraded'],core:'passed',overall:'PASSED'},
62
+ {name:'configured cannot mask a failed check',statuses:['configured'],core:'failed',overall:'FAILED'},
63
+ ])test(`optional report preserves order and reasons without changing core: ${name}`,async t=>{
64
+ const f=fixture(t);let expectedOptional;
65
+ const host=createCmCheckHost(f.input,{call:async(kind,payload)=>{
66
+ if(kind==='check_runtime')return mechanical(payload);
67
+ const value=assessment(payload);
68
+ // Deliberately report a different order and distinct reasons, including surrounding whitespace.
69
+ value.optional.reverse().forEach((row,i)=>{
70
+ row.status=statuses[i%statuses.length];row.reason=` Synthetic ${row.id}: ${row.status} (${i}) `;
71
+ });
72
+ expectedOptional=structuredClone(value.optional);
73
+ if(core==='failed'){value.checks[1].status='failed';value.checks[1].findings=['Synthetic reproducible broken link'];}
74
+ return value;
75
+ }});
76
+ const report=await host.handle({requestId:'optional',operation:'start'});
77
+ assert.equal(report.result.overall,overall,JSON.stringify(report.result));
78
+ assert.equal(report.result.semanticChecked,true);
79
+ assert.deepEqual(report.result.optional,expectedOptional);
80
+ assert.equal(report.result.checks[1].status,core);
81
+ assert.equal(report.result.findingsCount,core==='failed'?1:0);
82
+ });
83
+
84
+ for(const {name,mutate,reason} of [
85
+ {name:'unknown status enabled',mutate:rows=>{rows[0].status='enabled';},reason:'check_optional_invalid'},
86
+ {name:'uppercase status CONFIGURED',mutate:rows=>{rows[0].status='CONFIGURED';},reason:'check_optional_invalid'},
87
+ {name:'empty reason',mutate:rows=>{rows[0].reason='';},reason:'check_optional_invalid'},
88
+ {name:'whitespace reason',mutate:rows=>{rows[0].reason=' \t\n ';},reason:'check_optional_invalid'},
89
+ {name:'missing id',mutate:rows=>{rows.pop();},reason:'check_optional_incomplete'},
90
+ {name:'duplicate id at unchanged length',mutate:rows=>{rows[1].id=rows[0].id;},reason:'check_optional_incomplete'},
91
+ {name:'extra id',mutate:rows=>{rows.push({id:'unrecognized_tool',status:'configured',reason:'Synthetic extra tool'});},reason:'check_optional_incomplete'},
92
+ {name:'unknown id at unchanged length',mutate:rows=>{rows[0].id='unrecognized_tool';},reason:'check_optional_invalid'},
93
+ ])test(`invalid optional report blocks with exact reason: ${name}`,async t=>{
94
+ const f=fixture(t);
95
+ const host=createCmCheckHost(f.input,{call:async(kind,payload)=>{
96
+ if(kind==='check_runtime')return mechanical(payload);
97
+ const value=assessment(payload);mutate(value.optional);return value;
98
+ }});
99
+ const report=await host.handle({requestId:'optional-invalid',operation:'start'});
100
+ assert.equal(report.result.overall,'BLOCKED',JSON.stringify(report.result));
101
+ assert.equal(report.result.reason,reason);
102
+ });
103
+
57
104
  test('coverage, evidence, stale source/config, core findings and cancellation preserve honest verdicts',async t=>{
58
105
  for(const mode of ['missing','bad-line','stale','source-drift','config-drift','failed','blocked','cancel']){
59
106
  const f=fixture(t);let host;host=createCmCheckHost(f.input,{call:async(kind,payload)=>{