@aibyzero/cm-workflow 0.19.0 → 0.20.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 (82) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +8 -0
  4. package/README.md +8 -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/package.json +1 -1
  10. package/runtime/js/autonomy.mjs +159 -3
  11. package/runtime/js/check-coverage.mjs +130 -0
  12. package/runtime/js/cm-ai/acceptance-contract.mjs +252 -0
  13. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +14 -6
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  16. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  17. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  18. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  19. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  20. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  21. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  22. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  23. package/runtime/js/cm-ai/drive-core.mjs +6 -2
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +2 -2
  25. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  26. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  27. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  28. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  29. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  30. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  31. package/runtime/js/cm-ai/review-package.mjs +2 -2
  32. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  33. package/runtime/js/cm-ai/task-runner.mjs +38 -13
  34. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  35. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  36. package/runtime/js/cm-prd/change.mjs +17 -1
  37. package/runtime/js/cm-prd/summary.mjs +5 -0
  38. package/runtime/js/node-test-selection.mjs +38 -0
  39. package/runtime/js/run-analysis.mjs +153 -0
  40. package/runtime/js/session-boundary.mjs +17 -5
  41. package/runtime/js/session-handoff.mjs +5 -2
  42. package/scripts/cm-acceptance-preview.mjs +26 -0
  43. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  44. package/scripts/cm-ai-acceptance-contract.test.mjs +185 -0
  45. package/scripts/cm-ai-admission.test.mjs +5 -2
  46. package/scripts/cm-ai-blockage.test.mjs +120 -0
  47. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  48. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  49. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  50. package/scripts/cm-ai-progress.test.mjs +7 -0
  51. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  52. package/scripts/cm-ai-run.test.mjs +23 -1
  53. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  54. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  55. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  56. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  57. package/scripts/cm-autonomy-review-r1.test.mjs +93 -0
  58. package/scripts/cm-autonomy.mjs +3 -1
  59. package/scripts/cm-autonomy.test.mjs +10 -9
  60. package/scripts/cm-check-runtime.sh +1 -1
  61. package/scripts/cm-delivery-evidence.mjs +59 -0
  62. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  63. package/scripts/cm-drive-liveness.test.mjs +6 -0
  64. package/scripts/cm-driver-light-import.test.mjs +32 -0
  65. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  66. package/scripts/cm-node-test-selection.test.mjs +108 -0
  67. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  68. package/scripts/cm-prd-completion.test.mjs +12 -0
  69. package/scripts/cm-prd-host.mjs +3 -1
  70. package/scripts/cm-prd-host.test.mjs +18 -1
  71. package/scripts/cm-prd-summary.test.mjs +19 -4
  72. package/scripts/cm-review-inventory.test.mjs +21 -6
  73. package/scripts/cm-run-analysis.mjs +21 -0
  74. package/scripts/cm-run-analysis.test.mjs +120 -0
  75. package/scripts/cm-start-check.mjs +60 -53
  76. package/scripts/cm-start-check.test.mjs +76 -1
  77. package/scripts/cm-usage-report.py +8 -3
  78. package/scripts/cm019-r1-contract.test.mjs +137 -0
  79. package/scripts/cm019-review-gates.test.mjs +97 -0
  80. package/skills/cm-ai/references/js-host.md +5 -1
  81. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  82. package/skills/cm-prd/references/js-host.md +1 -0
@@ -7,6 +7,7 @@ import {spawn} from 'node:child_process';
7
7
  import {once} from 'node:events';
8
8
  import {createInterface} from 'node:readline';
9
9
  import {fileURLToPath} from 'node:url';
10
+ import {analyzeRunRows} from '../runtime/js/run-analysis.mjs';
10
11
  import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
11
12
  import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
12
13
  const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
@@ -148,6 +149,10 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
148
149
  send({requestId:'summary',operation:'prepare_summary'});
149
150
  }else if(message.requestId==='summary'){
150
151
  assert.equal(message.result.status,'human_summary_prepared');assert.equal(message.result.readyForAwaitingReview,true);
152
+ assert.equal(message.result.acceptancePreview.taskGrammar,3);
153
+ assert.deepEqual(message.result.acceptancePreview.scope.features,['1.guide']);
154
+ assert.equal(message.result.acceptancePreview.approvalAuthorized,false);
155
+ assert.equal(message.result.acceptancePreview.executionAuthorized,false);
151
156
  assert.deepEqual(message.result.currentFeatures,['1.guide']);
152
157
  assert.match(message.result.notes.join('\n'),/历史 feature 2.history.*旧版归档/);
153
158
  assert.equal(message.result.totals.tasks,1);assert.equal(message.result.checklist.every(item=>!item.checked),true);
@@ -166,7 +171,14 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
166
171
  assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).status,'awaiting_review');
167
172
  assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'))).features,['1.guide','2.history']);
168
173
  send({requestId:'status',operation:'status'});
169
- }else if(message.requestId==='status'){status=message.result;send({type:'host_close',sessionId});}
174
+ }else if(message.requestId==='status'){
175
+ status=message.result;
176
+ if(mode==='self-check'){
177
+ assert.deepEqual(status.acceptancePreview,status.summaryState.acceptancePreview);
178
+ assert.equal(status.acceptancePreview.taskGrammar,3);
179
+ }
180
+ send({type:'host_close',sessionId});
181
+ }
170
182
  }
171
183
  assert.equal((await closed)[0],0,stderr);
172
184
  assert.equal(status.stage,mode==='cancel'?'cancelled':mode==='draft'?'draft_ready':mode==='self-check'?'self_check_reported_passed':'analysis_ready');
@@ -175,6 +187,11 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
175
187
  assert.equal(fs.existsSync(path.join(dir,'1.guide')),false);
176
188
  }
177
189
  const events=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
190
+ const timing=analyzeRunRows(events).timing;
191
+ assert(timing.pairedSegments>0,'actual PRD producer timing must be recognized');
192
+ assert.equal(timing.unrecognizedEvents,0);assert.equal(timing.incompleteSegments,0);
193
+ if(mode==='draft'){assert(timing.combinedSegments>=3);assert(timing.stages.some(x=>x.stage==='design_generation'));}
194
+ if(mode==='codex'||mode==='claude')assert(timing.closedForInput>=1);
178
195
  assert.equal(events.filter(event=>event.event==='run_start').length,1);
179
196
  const done=events.filter(event=>event.event==='run_done');assert.equal(done.length,1);
180
197
  assert.equal(done[0].outcome,mode==='cancel'?'cancelled':'incomplete');
@@ -10,13 +10,13 @@ import {preparePrdReview} from '../runtime/js/cm-prd/review-preparation.mjs';
10
10
  import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
11
11
  import {recordPrdHostDisposition,createPrdDispositionOwner} from '../runtime/js/cm-prd/review-disposition.mjs';
12
12
  import {inspectPrdSummaryEvidence,createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
13
- import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange} from '../runtime/js/cm-prd/change.mjs';
13
+ import {inspectPrdChangeSnapshot,inspectPrdChangeProposal,applyPrdChange,createPrdChange} from '../runtime/js/cm-prd/change.mjs';
14
14
  import {approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
15
15
  import {loadConfig} from './cm-workflow-config.mjs';
16
16
  import {TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
17
17
  import {writeSpecsStatus} from '../runtime/js/specs-status.mjs';
18
18
  const sha=content=>createHash('sha256').update(content).digest('hex');
19
- function fixture(t,{pendingCorrection=false}={}){
19
+ function fixture(t,{pendingCorrection=false,mandatory=false}={}){
20
20
  const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-summary-marks-')));
21
21
  t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));fs.mkdirSync(path.join(specs,'.reviews'));
22
22
  const inputs=[];
@@ -24,7 +24,7 @@ function fixture(t,{pendingCorrection=false}={}){
24
24
  const findings=pendingCorrection&&feature==='1.guide'?[{id:'R1',severity:'P2',path:`${feature}/tasks.md`,
25
25
  message:'Clarify task split',evidence:'Synthetic finding'}]:[];
26
26
  const documents=[{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Read guide'},
27
- {path:'design.md',content:'## 方案摘要\nDocumentation'}, {path:'tasks.md',content:'- [ ] T-001: Guide\n - 范围: `README.md`'}];
27
+ {path:'design.md',content:'## 方案摘要\nDocumentation'}, {path:'tasks.md',content:`- [ ] T-001: ${mandatory?'必验: ':''}Guide\n - 范围: \`README.md\``}];
28
28
  const prepared=preparePrdReview({specs,stage:'split',feature,draft:{draftDigest:'a'.repeat(64),features:[{name:feature.split('.')[1],directory:feature,documents}]}});
29
29
  claimPrdReview({...prepared.paths,package_sha256:prepared.packageDigest});
30
30
  publishPrdReview({specs,reviewPackage:prepared.reviewPackage,packageDigest:prepared.packageDigest,authorContextId:'author',
@@ -41,7 +41,7 @@ function fixture(t,{pendingCorrection=false}={}){
41
41
  return {specs,mark,inputs};
42
42
  }
43
43
  test('summary includes completed historical feature and exact new feature with runtime metadata',async t=>{
44
- const {specs,mark}=fixture(t),before=inspectPrdSummaryEvidence(specs);mark();
44
+ const {specs,mark}=fixture(t,{mandatory:true}),before=inspectPrdSummaryEvidence(specs);mark();
45
45
  const evidence=inspectPrdSummaryEvidence(specs);
46
46
  assert.equal(evidence.features.length,2);assert.deepEqual(evidence.specFiles,before.specFiles);
47
47
  assert.equal(evidence.features[0].reviews.split.gate.runtimeMarksNormalized,true);
@@ -56,6 +56,10 @@ test('summary includes completed historical feature and exact new feature with r
56
56
  evidence:['Synthetic documentation fixture']}))})});
57
57
  const summary=await owner(specs,new AbortController().signal);
58
58
  assert.equal(summary.status,'human_summary_prepared');
59
+ assert.equal(summary.acceptancePreview.status,'needs_clarification');
60
+ assert.equal(summary.acceptancePreview.approvalAuthorized,false);
61
+ assert.equal(summary.acceptancePreview.executionAuthorized,false);
62
+ assert(summary.acceptancePreview.features[0].tasks[0].issues.some(issue=>issue.message.includes('no explicit task/case mapping')));
59
63
  assert.equal(summary.readyForAwaitingReview,false);
60
64
  assert.deepEqual(summary.blockers,['mechanical_self_check_failed']);
61
65
  assert.deepEqual(summary.mechanicalSelfCheck.findings,[{feature:'1.guide',code:'new_task_not_pending'}]);
@@ -281,3 +285,14 @@ test('historical gate failure still rejects publication when history changes aft
281
285
  fs.appendFileSync(path.join(specs,'1.guide/requirements.md'),'\nAnother edit after preparation');
282
286
  assert.throws(()=>publishPrdAwaitingReview({specs,summary,writeEnabled:true}),/prd_summary_inputs_changed/);
283
287
  });
288
+
289
+ test('R1 G5 change preview inventory includes unchanged features outside proposal scope',t=>{
290
+ const {specs}=fixture(t),admission={specs,project:specs,feature:'1.guide',cases:null,skillDir:path.resolve('skills/cm-prd')};
291
+ const options={admission,runtime:'codex',call:()=>assert.fail('status is read-only')};
292
+ const original=createPrdChange(options),state=structuredClone(original.checkpoint());
293
+ state.stage='change_confirmation';state.proposal={proposalDigest:'a'.repeat(64),removed:[],features:[{directory:'1.guide',
294
+ documents:['requirements.md','design.md','tasks.md'].map(name=>({path:name,content:fs.readFileSync(path.join(specs,'1.guide',name),'utf8')}))}]};
295
+ const value=createPrdChange({...options,restored:state}).status();
296
+ assert.deepEqual(value.acceptancePreview.featureInventory,['1.guide','2.appendix']);
297
+ assert.deepEqual(value.acceptancePreview.scope.features,['1.guide']);
298
+ });
@@ -434,6 +434,8 @@ import {buildDeveloperPrompt,readDeveloperRequest} from '../runtime/js/cm-ai/dev
434
434
  import {requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
435
435
  import {reviewResult,reviewPaths,reviewReceipt} from '../runtime/js/cm-ai/review-runner.mjs';
436
436
  import {checkCompletion} from '../runtime/js/cm-ai/gate-bridge.mjs';
437
+ import {encodeAcceptanceEvidence,acceptanceCoverage} from '../runtime/js/cm-ai/acceptance-contract.mjs';
438
+ import {createHostHandoff} from '../runtime/js/cm-ai/host-handoff.mjs';
437
439
 
438
440
  function specificationFixture(t,{cases=true,design='export function normalizePriority(value): Priority;\n'}={}){
439
441
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-specification-')));
@@ -530,22 +532,35 @@ for(const size of [65536,65537,1024*1024+4])test(`design byte limit ${size} pres
530
532
  assert(design.startsWith(material.designExcerpt));
531
533
  });
532
534
 
533
- test('new specification and legacy packages both retain receipt completion eligibility',t=>{
534
- const f=specificationFixture(t),baseline=f.capture();
535
+ test('new specification requires bound acceptance evidence while legacy receipt eligibility is retained',t=>{
536
+ const f=specificationFixture(t);
537
+ f.writeSpec('tasks.md',fs.readFileSync(path.join(f.specsRoot,f.feature,'tasks.md'),'utf8').replace('T-001: implement','T-001: 必验: implement'));f.approve();
538
+ const baseline=f.capture();
535
539
  const legacyBaseline=captureReviewBaseline({root:f.code,identity,scope:['code.js'],requirements:['requirements.md']});
536
540
  write(f.code,'code.js','after');
537
- const current=createReviewPackage({root:f.code,baseline,checks});
541
+ const contract=baseline.specification.acceptanceContract;
542
+ const acceptedChecks=contract.requiredCommands.map((command,index)=>({...checks[0],id:`declared-${index}`,
543
+ command:command.map((token,at)=>at===0&&token==='node'?process.execPath:token)}));
544
+ const incomplete=createReviewPackage({root:f.code,baseline,checks:acceptedChecks});
545
+ const handoffPath=path.join(f.specsRoot,'.reviews','priority-T-001-a1-handoff.json');
546
+ fs.mkdirSync(path.dirname(handoffPath),{recursive:true});
547
+ const evidence=encodeAcceptanceEvidence({contract,identity,items:contract.obligations.map(item=>({...item,satisfied:true,
548
+ evidence:'Synthetic fixture approval input, not a product execution'})),facts:null,coverage:acceptanceCoverage(contract,acceptedChecks)});
549
+ createHostHandoff({root:f.code,baseline,checks:acceptedChecks,handoffPath,evidence:[evidence]});
550
+ const current=createReviewPackage({root:f.code,baseline,checks:acceptedChecks,handoffPath});
538
551
  const old=createReviewPackage({root:f.code,baseline:legacyBaseline,checks});
539
552
  const {unchangedScope,packageDigest,...oldBody}=old,legacy={...oldBody,packageDigest:digest(oldBody)};
540
- for(const pkg of [current,legacy]){
553
+ for(const pkg of [incomplete,current,legacy]){
541
554
  assert.deepEqual(readReviewPackage(pkg),pkg);
542
555
  const result=reviewResult({verdict:'approved',packageDigest:pkg.packageDigest,examinedPaths:reviewPaths(pkg),findings:[],summary:'Synthetic review'},pkg);
543
556
  const request=requestFor({invocationId:'receipt',identity,role:'reviewer',provider:'claude',requestedModel:'fixture',contextId:'reviewer',payload:{reviewPackage:pkg,priorReview:null}});
544
557
  const call={invocationId:request.invocationId,started:true,terminal:'succeeded',requestDigest:request.requestDigest,resultDigest:digest(result),
545
558
  provider:'claude',contextId:'reviewer',requestedModel:'fixture',effectiveModel:'fixture',channel:'fixture'};
546
559
  const receipt=reviewReceipt({request,call,result,reviewPackage:pkg,developerProvider:'codex',fallbackReasons:[]});
547
- assert.equal(checkCompletion({receipt,registered:receipt,execution:call,reviewPackage:pkg,identity}).outcome,'eligible');
548
- assert.equal(verifyReviewPackage({root:f.code,baseline:pkg===current?baseline:legacyBaseline,checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
560
+ if(pkg===incomplete)assert.throws(()=>checkCompletion({receipt,registered:receipt,execution:call,reviewPackage:pkg,identity}),{code:'verification_precheck_failed'});
561
+ else assert.equal(checkCompletion({receipt,registered:receipt,execution:call,reviewPackage:pkg,identity}).outcome,'eligible');
562
+ assert.equal(verifyReviewPackage({root:f.code,baseline:pkg===legacy?legacyBaseline:baseline,checks:pkg===legacy?checks:acceptedChecks,
563
+ ...(pkg===current?{handoffPath}:{}),reviewPackage:pkg,expectedDigest:pkg.packageDigest}).outcome,'matched');
549
564
  }
550
565
  });
551
566
 
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import {fileURLToPath} from 'node:url';
4
+ import {inspectRunAnalysis,runAnalysisLines} from '../runtime/js/run-analysis.mjs';
5
+ const usage='用法: cm-run-analysis.mjs --specs DIR [--run-id ID] [--json]\n读取规格目录的运行日志;不执行工作流或修改状态。\n';
6
+ export function main(argv=process.argv.slice(2),{stdout=process.stdout,stderr=process.stderr}={}){
7
+ if(argv.length===1&&['--help','-h'].includes(argv[0])){stdout.write(usage);return 0;}
8
+ try{
9
+ const options={};
10
+ for(let i=0;i<argv.length;i++){
11
+ const name=argv[i];if(!['--specs','--run-id','--json'].includes(name)||Object.hasOwn(options,name))throw Error('run_analysis_arguments_invalid');
12
+ if(name==='--json')options[name]=true;
13
+ else{const value=argv[++i];if(!value||value.startsWith('--'))throw Error('run_analysis_arguments_invalid');options[name]=value;}
14
+ }
15
+ if(!options['--specs'])throw Error('run_analysis_arguments_invalid');
16
+ const report=inspectRunAnalysis({specs:path.resolve(options['--specs']),runId:options['--run-id']??null});
17
+ stdout.write(options['--json']?JSON.stringify(report)+'\n':runAnalysisLines(report).join('\n')+'\n');return 0;
18
+ }catch(error){const reason=error.code??error.message;
19
+ stderr.write(`运行分析不可用:${/^run_analysis_[a-z_]+$/.test(reason)?reason:'run_analysis_read_failed'}\n`);return 2;}
20
+ }
21
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=main();
@@ -0,0 +1,120 @@
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
+ import {withHostProgress,startHostProgress} from '../runtime/js/cm-ai/host-progress.mjs';
9
+ import {recordCmAiQaDecision,recordCmAiQaRun} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
10
+ import {analyzeRunRows,inspectRunAnalysis,runAnalysisLines} from '../runtime/js/run-analysis.mjs';
11
+ const cli=fileURLToPath(new URL('./cm-run-analysis.mjs',import.meta.url));
12
+ const base={run_id:'run-1',workflow:'cm-ai',runtime:'codex',stage:'develop',role:'developer',adapter:'codex-cli',requested_model:'configured',source:'native-cli-terminal',purpose:'workflow-execution'};
13
+ const claim=(id,extra={})=>({...base,event:'model_call',phase:'claimed',call_id:id,...extra});
14
+ const usage=(id,extra={})=>({...base,event:'model_usage',phase:'complete',call_id:id,usage_state:'observed',outcome:'success',input_tokens:10,output_tokens:5,...extra});
15
+ const progress=(phase,time,extra={})=>({run_id:'run-1',workflow:'cm-prd',event:'progress',phase,operation_id:'prd-design',phase_name:'design_generation',segment:1,at:`2026-01-01T00:${time}Z`,...(phase==='complete'?{outcome:'completed'}:{}),...extra});
16
+ function fixture(t,rows){const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-analysis-')));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));fs.writeFileSync(path.join(dir,'运行日志.jsonl'),rows.map(x=>JSON.stringify(x)).join('\n')+'\n');return dir;}
17
+
18
+ test('reuses native usage identity, reasoning subset and unavailable semantics',()=>{
19
+ const report=analyzeRunRows([claim('a'),usage('a',{outcome:'error',cache_write_tokens:3,reasoning_tokens:4}),claim('b'),usage('b',{usage_state:'unavailable',input_tokens:undefined,output_tokens:undefined}),claim('c')]);
20
+ assert.equal(report.usage.status,'partial');assert.equal(report.usage.summary.observed_calls,1);
21
+ assert.equal(report.usage.summary.outcomes.error,1);assert.equal(report.usage.summary.unavailable_calls,1);
22
+ assert.equal(report.usage.summary.unresolved_claims,1);assert.equal(report.usage.summary.output_tokens,5);
23
+ assert.equal(report.usage.native_components.fields.reasoning_tokens.tokens,4);
24
+ assert.equal(report.usage.native_components.fields.cache_read_tokens.tokens,null);
25
+ assert.equal(report.repetitions.groups[0].count,3);
26
+ });
27
+ test('claim mismatch, missing prior claim, duplicate call and invalid reasoning are never counted',()=>{
28
+ const report=analyzeRunRows([usage('missing'),claim('a'),usage('a',{stage:'review'}),claim('b'),usage('b',{reasoning_tokens:6}),claim('c'),usage('c'),usage('c')]);
29
+ assert.equal(report.usage.summary.observed_calls,1);assert.equal(report.usage.summary.invalid_calls,4);
30
+ assert.equal(report.usage.summary.unresolved_claims,2);assert.equal(report.usage.status,'partial');
31
+ });
32
+ test('paired phase segments exclude waiting gaps and union combined call overlaps',()=>{
33
+ const rows=[progress('start','00:00'),progress('complete','00:10',{outcome:'awaiting_input'}),
34
+ progress('start','05:00',{segment:2,timing_scope:'combined_host_call'}),
35
+ progress('start','05:00',{operation_id:'prd-task',phase_name:'task_split',timing_scope:'combined_host_call'}),
36
+ progress('complete','05:20',{segment:2,timing_scope:'combined_host_call'}),
37
+ progress('complete','05:20',{operation_id:'prd-task',phase_name:'task_split',timing_scope:'combined_host_call'})];
38
+ const r=analyzeRunRows(rows).timing;assert.equal(r.activeIntervalUnionMs,30000);assert.equal(r.closedForInput,1);
39
+ assert.equal(r.combinedSegments,2);assert.equal(r.waitingMs,null);assert.equal(r.stages[0].durationMs,30000);
40
+ });
41
+ test('timing never pairs across run, workflow, operation, duplicate or inverted order',()=>{
42
+ const r=analyzeRunRows([progress('start','00:00'),progress('complete','00:10',{run_id:'run-2'}),
43
+ progress('complete','00:10',{workflow:'cm-ai'}),progress('start','00:00',{operation_id:'duplicate'}),progress('start','00:00',{operation_id:'duplicate'}),progress('complete','00:10',{operation_id:'duplicate'}),
44
+ progress('complete','00:10',{operation_id:'inverted'}),progress('start','00:00',{operation_id:'inverted'})]).timing;
45
+ assert.equal(r.pairedSegments,0);assert.equal(r.activeIntervalUnionMs,null);assert.equal(r.incompleteSegments,4);assert.equal(r.unrecognizedEvents,1);
46
+ });
47
+ test('selects original run, deduplicates exact events, rejects conflicting identity and preserves legacy unknown',()=>{
48
+ const a=claim('a',{event_id:'event-1'});const r=analyzeRunRows([a,a,usage('a'),claim('other',{run_id:'run-2'}),{event:'legacy'}],{runId:'run-1'});
49
+ assert.deepEqual(r.runs,['run-1']);assert.equal(r.deduplicatedEvents,1);assert.equal(r.ignoredHistoricalRows,1);
50
+ assert.equal(r.usage.summary.observed_calls,1);
51
+ assert.throws(()=>analyzeRunRows([a,{...a,stage:'review'}]),/log_invalid/);
52
+ assert.throws(()=>analyzeRunRows([a],{runId:'absent'}),/run_not_found/);
53
+ });
54
+ test('QA repetitions are unique operation starts, command execution remains unknown',()=>{
55
+ const start={run_id:'run-1',workflow:'cm-ai',event:'test_run',phase:'start',feature:'1.login',task:'T-001',operation_id:'qa-1'};
56
+ const r=analyzeRunRows([start,start,{...start,operation_id:'qa-2'}]).repetitions;
57
+ assert.equal(r.groups[0].count,2);assert.equal(r.commandReexecution,'unavailable');
58
+ });
59
+ test('actual CLI reads one stable log and does not modify logs or state',t=>{
60
+ const dir=fixture(t,[claim('a'),usage('a'),progress('start','00:00'),progress('complete','00:10')]);
61
+ const state=path.join(dir,'.cm-run.json');fs.writeFileSync(state,'{"run_id":"do-not-use-pointer"}');
62
+ const before=fs.readdirSync(dir).map(name=>[name,fs.readFileSync(path.join(dir,name)),fs.statSync(path.join(dir,name)).mtimeMs]);
63
+ const result=spawnSync(process.execPath,[cli,'--specs',dir,'--run-id','run-1','--json'],{encoding:'utf8'});
64
+ assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).usage.summary.observed_calls,1);
65
+ for(const [name,bytes,mtime] of before){assert.deepEqual(fs.readFileSync(path.join(dir,name)),bytes);assert.equal(fs.statSync(path.join(dir,name)).mtimeMs,mtime);}
66
+ assert.equal(fs.readdirSync(dir).length,before.length);
67
+ });
68
+ test('malformed, symlink and oversized authoritative logs fail closed without raw input',t=>{
69
+ const dir=fixture(t,[]),file=path.join(dir,'运行日志.jsonl');fs.writeFileSync(file,'SECRET-BAD-JSON');
70
+ let r=spawnSync(process.execPath,[cli,'--specs',dir,'--json'],{encoding:'utf8'});assert.equal(r.status,2);assert.doesNotMatch(r.stderr,/SECRET/);
71
+ fs.unlinkSync(file);fs.writeFileSync(path.join(dir,'other'),'{}');fs.symlinkSync('other',file);assert.throws(()=>inspectRunAnalysis({specs:dir}),/unavailable/);
72
+ fs.unlinkSync(file);fs.writeFileSync(file,'');fs.truncateSync(file,32*1024*1024+1);assert.throws(()=>inspectRunAnalysis({specs:dir}),/unavailable/);
73
+ });
74
+ test('missing Python is explicit unavailable and malicious labels never reach human output',()=>{
75
+ const old=process.env.PATH;try{process.env.PATH='';const r=analyzeRunRows([claim('a'),usage('a')]);assert.equal(r.usage.status,'unavailable');assert.equal(r.usage.reason,'usage_reader_unavailable');}finally{process.env.PATH=old;}
76
+ const r=analyzeRunRows([claim('a',{stage:'\u001b[31mSECRET'}),usage('a',{stage:'\u001b[31mSECRET'})]);
77
+ assert.equal(r.usage.summary.observed_calls,0);assert.equal(r.usage.summary.invalid_claims,1);
78
+ assert.doesNotMatch(runAnalysisLines(r).join('\n'),/SECRET|\u001b/);
79
+ });
80
+
81
+
82
+ test('actual AI progress producer: returned, failed, aborted and unfinished operations remain distinct',async t=>{
83
+ const dir=fixture(t,[]),specsDir=dir,codeProject=path.join(dir,'code');fs.mkdirSync(codeProject);
84
+ const definition={specsDir,codeProject,feature:'1.example'},identity={repositoryId:'analysis-fixture',runId:'run-ai-native',taskId:'T-001',attempt:1};
85
+ const options={definition,identity,stage:'checking'};
86
+ await withHostProgress({...options,signal:new AbortController().signal},async()=>({outcome:'failed'}));
87
+ await assert.rejects(withHostProgress({...options,signal:new AbortController().signal},async()=>{throw Error('fixture failure');}),/fixture failure/);
88
+ const controller=new AbortController(),p=startHostProgress({...options,signal:controller.signal});controller.abort();p.complete('returned');
89
+ startHostProgress({...options,signal:new AbortController().signal});
90
+ const rows=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
91
+ assert(rows.filter(x=>x.event==='progress').every(x=>!Object.hasOwn(x,'segment')));
92
+ const report=inspectRunAnalysis({specs:dir}),timing=report.timing;
93
+ assert.equal(timing.pairedSegments,3);assert.equal(timing.incompleteSegments,1);assert.equal(timing.unrecognizedEvents,0);
94
+ assert.equal(timing.status,'partial');assert.deepEqual(timing.stages[0].outcomes,{returned:1,failed:1,aborted:1});
95
+ assert.equal(timing.waitingMs,null);assert.equal(timing.closedForInput,0);
96
+ assert.match(runAnalysisLines(report).join('\n'),/returned=1, failed=1, aborted=1/);
97
+ const start=rows.find(x=>x.phase==='start');
98
+ const wrong={...rows.find(x=>x.phase==='complete'),event_id:'wrong-task',task:'T-002'};
99
+ assert.equal(analyzeRunRows([start,wrong]).timing.pairedSegments,0);
100
+ assert.equal(analyzeRunRows([{...start,workflow:'cm-prd'}]).timing.unrecognizedEvents,1);
101
+ });
102
+
103
+ test('actual QA writer provides identity and operation fields consumed by repetition analysis',t=>{
104
+ const dir=fixture(t,[]),codeProject=path.join(dir,'code');fs.mkdirSync(codeProject);
105
+ const identity={repositoryId:'analysis-fixture',runId:'run-qa-native',taskId:'T-001',attempt:1},packageDigest='a'.repeat(64);
106
+ const binding={specsDir:dir,codeProject,feature:'1.example',identity,packageDigest,logHome:path.join(dir,'mirror')};
107
+ recordCmAiQaDecision({...binding,decision:{decisionId:'qa-decision',identity,packageDigest,status:'triggered',score:null,reason:'api',at:'2026-01-01T00:00:00Z'}});
108
+ recordCmAiQaRun({...binding,testRunId:'qa-operation-native',mode:'commands',caseCount:1,phase:'start'});
109
+ const row=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse).find(x=>x.event==='test_run');
110
+ assert.equal(row.operation_id,'qa-operation-native');assert.equal(row.feature,'1.example');assert.equal(row.task,'T-001');
111
+ // A second distinct start follows the exact producer shape; does not simulate a QA verdict or retry authorization.
112
+ const report=analyzeRunRows([row,{...row,event_id:'second-observed-start',operation_id:'qa-operation-2'}]);
113
+ assert.equal(report.repetitions.groups[0].count,2);assert.equal(report.repetitions.groups[0].kind,'qa_invocation_start');
114
+ });
115
+
116
+ test('global event identity collisions across runs are rejected before usage deduplication',()=>{
117
+ const a=usage('a',{event_id:'same-event'}),b=usage('b',{run_id:'run-2',event_id:'same-event'});
118
+ assert.throws(()=>analyzeRunRows([a,b]),/log_invalid/);
119
+ assert.throws(()=>analyzeRunRows([a,b],{runId:'run-1'}),/log_invalid/);
120
+ });
@@ -8,7 +8,12 @@ import path from 'node:path';
8
8
  import {pathToFileURL} from 'node:url';
9
9
  import {protectedScopePaths, validateDeveloperScope} from '../runtime/js/cm-ai/developer-adapter.mjs';
10
10
  import {planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
11
+ import {isXcodebuild, isTestAction, advisoryRunsTest as runsTest, mandatoryCheckCoverage} from '../runtime/js/check-coverage.mjs';
11
12
  import {git as safeGit} from '../runtime/js/cm-security/scan.mjs';
13
+ import {captureSpecificationMaterial} from '../runtime/js/cm-ai/specification-material.mjs';
14
+ import {readReviewBaseline} from '../runtime/js/cm-ai/review-package.mjs';
15
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
16
+ import {acceptanceCoverage} from '../runtime/js/cm-ai/acceptance-contract.mjs';
12
17
 
13
18
  // The whole check step of a current-session run is one host call with this deadline
14
19
  // (runtime/js/cm-ai/host-conversation-execution.mjs, outerTimeoutMs). The test
@@ -82,39 +87,6 @@ function checkProtectedScope(scope) {
82
87
  message: `scope 含受保护路径 ${item}:创建运行会被 protected_scope 拒绝。先走人工通道同步该文件,再把它从 scope 里去掉`}));
83
88
  }
84
89
 
85
- const isXcodebuild = tokens => tokens.some(token => path.basename(token) === 'xcodebuild');
86
- // xcodebuild options that take no value (xcodebuild -help, Xcode 26). A bare word counts as an
87
- // action only right after xcodebuild, another bare word (an action or an option's value), an
88
- // -option:value, or one of these. After any other option it may be that option's value
89
- // (`-resultBundlePath test`), so it is not an action: an unknown flag then makes the coverage
90
- // check warn instead of passing, never the other way round.
91
- const XCODE_FLAGS = new Set(['-usage', '-help', '-verbose', '-license', '-checkFirstLaunchStatus', '-runFirstLaunch',
92
- '-checkForNewerComponents', '-downloadAllPlatforms', '-prepareDeviceSupport', '-alltargets', '-parallelizeTargets', '-quiet',
93
- '-hideShellScriptEnvironment', '-showsdks', '-showdestinations', '-showTestPlans', '-showBuildSettings', '-showBuildSettingsForIndex',
94
- '-list', '-version', '-exportArchive', '-exportNotarizedApp', '-skipUnavailableActions', '-exportLocalizations', '-importLocalizations',
95
- '-retry-tests-on-failure', '-run-tests-until-failure', '-disable-concurrent-destination-testing', '-enumerate-tests',
96
- '-resolvePackageDependencies', '-disableAutomaticPackageResolution', '-onlyUsePackageVersionsFromResolvedFile', '-skipPackageUpdates',
97
- '-disablePackageRepositoryCache', '-skipPackagePluginValidation', '-skipMacroValidation', '-skipPackageSignatureValidation', '-json',
98
- '-allowProvisioningUpdates', '-allowProvisioningDeviceRegistration', '-showBuildTimingSummary']);
99
- function xcodeActions(tokens) {
100
- const start = tokens.findIndex(token => path.basename(token) === 'xcodebuild');
101
- if (start === -1) return [];
102
- return tokens.slice(start + 1).filter((token, index, rest) => {
103
- if (token.startsWith('-')) return false;
104
- const before = index === 0 ? null : rest[index - 1];
105
- return before === null || !before.startsWith('-') || before.includes(':') || XCODE_FLAGS.has(before);
106
- });
107
- }
108
- // Modes that list, show, export or set up instead of running the scheme action: a `test` beside them
109
- // selects what to show (xcodebuild -showBuildSettings test) and runs nothing.
110
- const XCODE_NON_RUNNING = new Set(['-usage', '-help', '-license', '-checkFirstLaunchStatus', '-runFirstLaunch', '-downloadAllPlatforms',
111
- '-prepareDeviceSupport', '-downloadPlatform', '-importPlatform', '-downloadComponent', '-importComponent', '-deleteComponent',
112
- '-showComponent', '-showsdks', '-showdestinations', '-showTestPlans', '-showBuildSettings', '-showBuildSettingsForIndex', '-list',
113
- '-find-executable', '-find-library', '-version', '-exportArchive', '-exportNotarizedApp', '-exportLocalizations', '-importLocalizations',
114
- '-enumerate-tests', '-resolvePackageDependencies', '-create-xcframework']);
115
- // Whether a direct xcodebuild actually runs tests; shared by the overlap and the coverage checks.
116
- const isTestAction = tokens => !tokens.some(token => XCODE_NON_RUNNING.has(token))
117
- && xcodeActions(tokens).some(action => action === 'test' || action === 'test-without-building');
118
90
  const optionValue = (tokens, name) => {
119
91
  const at = tokens.indexOf(name);
120
92
  return at === -1 ? '' : tokens[at + 1] ?? '';
@@ -195,24 +167,6 @@ export function readAffectedMap(root) {
195
167
  return null;
196
168
  }
197
169
 
198
- const ONLY = '-only-testing:', SKIP = '-skip-testing:';
199
- const within = (id, target) => id === target || id.startsWith(`${target}/`);
200
- // Whether one check command runs all of test `id`. A direct xcodebuild counts only with a test
201
- // action and only through its selection: unnarrowed, or an -only-testing naming `id` or an
202
- // ancestor. Any other command (wrapper script, other runner) counts when an argument contains
203
- // `id`; the start check cannot see inside it. An -skip-testing on `id`, an ancestor or a part
204
- // of it (one method of the class) means it does not run all of it.
205
- function runsTest(tokens, id) {
206
- if (tokens.some(token => token.startsWith(SKIP)
207
- && (within(id, token.slice(SKIP.length)) || within(token.slice(SKIP.length), id)))) return false;
208
- if (isXcodebuild(tokens)) {
209
- if (!isTestAction(tokens)) return false;
210
- const only = tokens.filter(token => token.startsWith(ONLY)).map(token => token.slice(ONLY.length));
211
- return !tokens.some(token => token.startsWith('-only-testing')) || only.some(target => within(id, target));
212
- }
213
- return tokens.some(token => !token.startsWith('-skip-testing') && token.includes(id));
214
- }
215
-
216
170
  function checkAffectedTests(plan, definition) {
217
171
  const commands = (Array.isArray(plan.checks) ? plan.checks : [])
218
172
  .map(item => item?.command).filter(tokens => Array.isArray(tokens) && tokens.every(token => typeof token === 'string'));
@@ -289,9 +243,62 @@ function checkDirtyScope(definition) {
289
243
  + '运行基线会把它们当起点,交审包里看不到这部分改动;若是上次的任务代码,先还原,确认是有意保留的再继续'}];
290
244
  }
291
245
 
292
- export function startCheck(planFile) {
246
+ // requiredTests comes from the caller's frozen approved contract, never from the
247
+ // mutable affected-test table or the developer's PLAN. Other warnings stay advisory.
248
+ export function checkMandatoryTests(plan, requiredTests) {
249
+ const coverage = mandatoryCheckCoverage({requiredTests,
250
+ commands: (Array.isArray(plan.checks) ? plan.checks : []).map(item => item?.command)});
251
+ if (coverage.satisfied) return [];
252
+ return [{level: 'error', code: 'mandatory_tests_not_covered',
253
+ tests: coverage.missing, unverifiable: coverage.unverifiable,
254
+ message: `已批准必验合同要求 ${coverage.missing.join('、')},当前检查命令未能证明完整选择;`
255
+ + '补充明确执行这些测试的命令。包装脚本须先经原规格流程确认可机械核对的测试映射,不能仅在参数中出现测试名就认定覆盖'}];
256
+ }
257
+
258
+ function approvedStartContract(plan,definition){
259
+ // Old scope-only advisory inputs have no task identity and make no claim
260
+ // about a runnable CM specification. Real run definitions are checked below.
261
+ if(definition.specsDir===undefined&&definition.specification===undefined)return null;
262
+ try{
263
+ if(plan.mode==='resume'){
264
+ const snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,
265
+ identity:{repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});
266
+ const baseline=readReviewBaseline(snapshot.records[0]?.payload?.baseline);
267
+ if(baseline.specificationRoot!==definition.specsDir||baseline.identity.taskId!==definition.identity.taskId)
268
+ throw new Error('owner mismatch');
269
+ return baseline.specification?.acceptanceContract??null;
270
+ }
271
+ // A create-plan may be inspected before any specification has been written.
272
+ // Preserve its old scope/budget diagnostics; this read-only check grants no
273
+ // execution admission. Any existing feature/approval (including symlinks),
274
+ // resume owner or read failure still takes the strict evidence path below.
275
+ if(plan.mode===undefined||plan.mode==='create'){
276
+ const root=definition.specsDir;
277
+ if(typeof root!=='string'||!path.isAbsolute(root)||fs.realpathSync(root)!==root
278
+ ||!fs.lstatSync(root).isDirectory()||typeof definition.feature!=='string'
279
+ ||!/^\d+\.[^/\\\x00-\x1f]+$/.test(definition.feature))throw new Error('invalid specification root');
280
+ const absent=file=>{try{fs.lstatSync(file);return false;}catch(error){if(error.code==='ENOENT')return true;throw error;}};
281
+ if(absent(path.join(root,'.cm-specs-status'))&&absent(path.join(root,definition.feature)))return null;
282
+ }
283
+ return captureSpecificationMaterial({specsRoot:definition.specsDir,feature:definition.feature,
284
+ taskId:definition.identity.taskId}).acceptanceContract;
285
+ }catch{throw new InputError('必验合同无法从已批准规格或原运行读取;先核对规格批准与原运行身份,不能由 PLAN 自报或省略必验范围');}
286
+ }
287
+
288
+ export function startCheck(planFile, {requiredTests = []} = {}) {
293
289
  const {plan, definition} = loadStartInputs(planFile);
294
- return [...checkProtectedScope(definition.scope), ...checkChecks(plan), ...checkAffectedTests(plan, definition), ...checkDirtyScope(definition)];
290
+ const contract=approvedStartContract(plan,definition),mandatory=[];
291
+ if(contract){
292
+ if(contract.unresolved.length)mandatory.push({level:'error',code:'acceptance_mapping_required',
293
+ message:`已批准材料的必验映射尚不明确:${contract.unresolved.join(';')}`});
294
+ // Planned argv is checked before execution; no success evidence is emitted.
295
+ const coverage=acceptanceCoverage(contract,(Array.isArray(plan.checks)?plan.checks:[]).map(item=>({...item,outcome:'passed'})));
296
+ if(!coverage.satisfied)mandatory.push({level:'error',code:'mandatory_checks_not_covered',
297
+ tests:coverage.missing,unverifiable:coverage.unverifiable,commands:coverage.missingCommands,
298
+ message:'当前计划未完整包含冻结的必验检查;补齐检查,不能缩减批准的验收范围'});
299
+ }
300
+ return [...checkProtectedScope(definition.scope), ...checkChecks(plan), ...checkAffectedTests(plan, definition),
301
+ ...checkMandatoryTests(plan, requiredTests), ...mandatory, ...checkDirtyScope(definition)];
295
302
  }
296
303
 
297
304
  export function main(argv = process.argv.slice(2), out = process.stdout, err = process.stderr) {
@@ -6,7 +6,8 @@ import path from 'node:path';
6
6
  import test from 'node:test';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {spawnSync} from 'node:child_process';
9
- import {CHECK_CALL_LIMIT_MS, MAX_SCOPE_PATHS} from './cm-start-check.mjs';
9
+ import {CHECK_CALL_LIMIT_MS, MAX_SCOPE_PATHS, startCheck, checkMandatoryTests} from './cm-start-check.mjs';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
10
11
 
11
12
  const here = path.dirname(fileURLToPath(import.meta.url));
12
13
  const script = path.join(here, 'cm-start-check.mjs');
@@ -52,6 +53,49 @@ const codes = report => report.findings.map(item => item.code);
52
53
  const cmd = (id, command, timeoutMs) => ({id, command, ...(timeoutMs === undefined ? {} : {timeoutMs})});
53
54
  const xcode = (id, ...extra) => cmd(id, ['xcodebuild', 'test', '-scheme', 'App', '-destination', 'id=U1', ...extra]);
54
55
 
56
+ test('frozen required tests produce an error without upgrading unrelated affected-map warnings', t => {
57
+ const p = project(t, {scope: ['src/a.js'], files: {'src/a.js': 'a\n', 'TESTING.md':
58
+ '## 牵连测试\n\n| 路径 | 测试 |\n| --- | --- |\n| src/a.js | AppUITests/OldTests AppUITests/NewTests |\n'},
59
+ checks: [cmd('ui', ['/usr/bin/xcodebuild','test','-scheme','App','-only-testing:AppUITests/NewTests'])]});
60
+ assert.equal(check(p).status, 0, 'without a frozen contract the existing diagnostic remains advisory');
61
+ const findings = startCheck(p.planFile, {requiredTests: ['AppUITests/OldTests']});
62
+ assert.equal(findings.find(item => item.code === 'affected_tests_not_run').level, 'warn');
63
+ assert.equal(findings.find(item => item.code === 'mandatory_tests_not_covered').level, 'error');
64
+ assert.deepEqual(findings.find(item => item.code === 'mandatory_tests_not_covered').tests, ['AppUITests/OldTests']);
65
+ const approvedSubset = startCheck(p.planFile, {requiredTests: ['AppUITests/NewTests']});
66
+ assert.equal(approvedSubset.some(item => item.level === 'error'), true);
67
+ assert.deepEqual(approvedSubset.find(item=>item.code==='mandatory_tests_not_covered').unverifiable,['AppUITests/NewTests']);
68
+ assert.equal(approvedSubset.find(item => item.code === 'affected_tests_not_run').level, 'warn');
69
+ });
70
+
71
+ test('mandatory selection never accepts a wrapper solely because its arguments contain a test name', () => {
72
+ const findings = checkMandatoryTests({checks: [cmd('wrapper', ['bash', 'tests.sh', 'AppUITests/OldTests'])]}, ['AppUITests/OldTests']);
73
+ assert.equal(findings[0].level, 'error');
74
+ assert.deepEqual(findings[0].unverifiable, ['AppUITests/OldTests']);
75
+ assert.deepEqual(checkMandatoryTests({checks: {}}, []), [], 'an absent contract does not change legacy input handling');
76
+ assert.equal(checkMandatoryTests({checks: {}}, ['AppUITests/OldTests'])[0].level, 'error');
77
+ });
78
+
79
+ test('the real CLI reads mandatory checks from approved specs, never the editable PLAN',t=>{
80
+ const p=project(t,{checks:[cmd('tests',[process.execPath,'--test','a.test.js'])]});
81
+ const directory=path.join(path.dirname(p.planFile),'specs');fs.mkdirSync(path.join(directory,'1.demo'),{recursive:true});
82
+ const specsDir=fs.realpathSync(directory),feature='1.demo';
83
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement AC-001\n - 必跑测试: `a.test.js`, `b.test.js`\n');
84
+ fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'- [ ] [AC-001] preserve both tests\n');
85
+ fs.writeFileSync(path.join(specsDir,feature,'design.md'),'simple\n');
86
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
87
+ const config=path.join(path.dirname(p.planFile),'run.json'),definition=JSON.parse(fs.readFileSync(config,'utf8'));
88
+ fs.writeFileSync(config,JSON.stringify({...definition,specsDir,feature,identity:{repositoryId:'fixture',runId:'start-check',taskId:'T-001',attempt:1}}));
89
+ const before=snapshot(specsDir),missing=check(p);
90
+ assert.equal(missing.status,1);assert.ok(codes(missing.report).includes('mandatory_checks_not_covered'));
91
+ const plan=JSON.parse(fs.readFileSync(p.planFile,'utf8'));plan.requiredTests=[];
92
+ fs.writeFileSync(p.planFile,JSON.stringify(plan));assert.equal(check(p).status,1,'PLAN cannot waive approved obligations');
93
+ plan.checks[0].command.push('b.test.js');fs.writeFileSync(p.planFile,JSON.stringify(plan));
94
+ assert.equal(check(p).status,0);assert.deepEqual(snapshot(specsDir),before,'preflight never writes specs');
95
+ fs.appendFileSync(path.join(specsDir,feature,'tasks.md'),' - extra unapproved requirement\n');
96
+ assert.equal(check(p).status,2,'unapproved drift is not treated as no contract');
97
+ });
98
+
55
99
  function snapshot(dir) {
56
100
  const rows = [];
57
101
  const walk = current => {
@@ -404,3 +448,34 @@ test('repository config cannot run programs: fsmonitor, clean, process and requi
404
448
  assert.equal(fs.existsSync(mark), false);
405
449
  assert.equal(r.status, 0);
406
450
  });
451
+
452
+ test('B1 legacy empty-spec preflight keeps scope diagnostics without permitting incomplete mandatory specifications',t=>{
453
+ const p=project(t,{scope:['AGENTS.md','src/a.js'],repo:false,checks:[cmd('syntax',[process.execPath,'--check','src/a.js'])]});
454
+ const specsDir=path.join(fs.realpathSync(p.dir),'specs');fs.mkdirSync(specsDir);
455
+ const config=path.join(p.planDir,'run.json'),definition=JSON.parse(fs.readFileSync(config,'utf8'));
456
+ fs.writeFileSync(config,JSON.stringify({...definition,specsDir,feature:'1.demo',identity:{repositoryId:'fixture',runId:'preflight',taskId:'T-001',attempt:1}}));
457
+ const before=snapshot(specsDir),legacy=check(p);
458
+ assert.equal(legacy.status,1,legacy.err);assert(codes(legacy.report).includes('protected_scope'));
459
+ assert.equal(snapshot(specsDir),before,'scope diagnostics do not create approval or execution evidence');
460
+ const alias=path.join(p.dir,'specs-alias');fs.symlinkSync(specsDir,alias);
461
+ const selected=JSON.parse(fs.readFileSync(config,'utf8'));fs.writeFileSync(config,JSON.stringify({...selected,specsDir:alias}));
462
+ assert.equal(check(p).status,2,'a linked specs root cannot acquire the empty-spec compatibility exception');
463
+ fs.writeFileSync(config,JSON.stringify({...selected,feature:'../escape'}));assert.equal(check(p).status,2,'feature containment is not bypassed');
464
+ fs.writeFileSync(config,JSON.stringify(selected));
465
+ const originalPlan=fs.readFileSync(p.planFile);fs.writeFileSync(p.planFile,JSON.stringify({...JSON.parse(originalPlan),mode:'resume'}));
466
+ assert.equal(check(p).status,2,'resume always requires its original owner');fs.writeFileSync(p.planFile,originalPlan);
467
+ const statusPath=path.join(specsDir,'.cm-specs-status');fs.symlinkSync(path.join(p.dir,'absent-status'),statusPath);
468
+ assert.equal(check(p).status,2,'dangling status link is present, not a legacy absence');fs.unlinkSync(statusPath);
469
+ const originalStat=fs.lstatSync;
470
+ fs.lstatSync=function(file,...args){if(file===statusPath)throw Object.assign(new Error('fixture denied'),{code:'EACCES'});return originalStat.call(this,file,...args);};
471
+ try{assert.throws(()=>startCheck(p.planFile),/必验合同无法/,'read failures are not absence');}finally{fs.lstatSync=originalStat;}
472
+ const external=path.join(p.dir,'external-feature');fs.mkdirSync(external);fs.symlinkSync(external,path.join(specsDir,'1.demo'));
473
+ assert.equal(check(p).status,2,'a linked feature is present evidence, never absence');fs.unlinkSync(path.join(specsDir,'1.demo'));
474
+ fs.symlinkSync(path.join(p.dir,'absent-feature'),path.join(specsDir,'1.demo'));
475
+ assert.equal(check(p).status,2,'dangling feature links also remain strict');fs.unlinkSync(path.join(specsDir,'1.demo'));
476
+ fs.mkdirSync(path.join(specsDir,'1.demo'));fs.writeFileSync(path.join(specsDir,'1.demo','tasks.md'),'- [ ] T-001: 必验: verify all files\n');
477
+ assert.equal(check(p).status,2,'a present mandatory specification without approval cannot be downgraded to legacy');
478
+ fs.rmSync(path.join(specsDir,'1.demo'),{recursive:true});
479
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.demo']}));
480
+ assert.equal(check(p).status,2,'an existing approval with missing source remains a hard input error');
481
+ });
@@ -220,7 +220,10 @@ def add_observed(counts: Dict[str, int], row: Dict[str, Any]) -> None:
220
220
  counts["duration_observed_calls"] += 1
221
221
 
222
222
 
223
- def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
223
+ def build_report(
224
+ log_home: Path, refs: List[RunRef],
225
+ rows_by_run: Optional[Dict[str, List[Tuple[int, Dict[str, Any]]]]] = None,
226
+ ) -> Dict[str, Any]:
224
227
  summary = {
225
228
  "runs": len(refs),
226
229
  "observed_calls": 0,
@@ -249,10 +252,12 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
249
252
 
250
253
  for ref in refs:
251
254
  log_path = safe_log_path(log_home, ref.log_file)
252
- if log_path is None or not log_path.is_file():
255
+ if rows_by_run is None and (log_path is None or not log_path.is_file()):
253
256
  print(f"warning: missing run log for {ref.run_id}", file=sys.stderr)
254
257
  continue
255
- for line_number, row in read_jsonl(log_path):
258
+ # The specs-local report supplies its already validated immutable snapshot.
259
+ rows = read_jsonl(log_path) if rows_by_run is None else rows_by_run.get(ref.run_id, [])
260
+ for line_number, row in rows:
256
261
  if row.get("run_id") != ref.run_id:
257
262
  continue
258
263
  if row.get("event") == "model_call":