@aibyzero/cm-workflow 0.16.4 → 0.16.5

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 (167) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +50 -0
  4. package/README.md +12 -1
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/runtime-failover.md +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  11. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  14. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  16. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  17. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  19. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  20. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  21. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  22. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  24. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  26. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  27. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  28. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  29. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  30. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  31. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  33. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  34. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  35. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  36. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  37. package/runtime/js/cm-ai/host-session.mjs +12 -4
  38. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  42. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  45. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  46. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  47. package/runtime/js/cm-ai/review-package.mjs +427 -31
  48. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  49. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  50. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  51. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  52. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  53. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  54. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  55. package/runtime/js/cm-fix/execution.mjs +109 -25
  56. package/runtime/js/cm-fix/host-review.mjs +7 -3
  57. package/runtime/js/cm-fix/host.mjs +3 -1
  58. package/runtime/js/cm-fix/progress.mjs +1 -0
  59. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  60. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  61. package/runtime/js/cm-prd/analysis.mjs +2 -1
  62. package/runtime/js/cm-prd/change.mjs +28 -10
  63. package/runtime/js/cm-prd/draft.mjs +5 -2
  64. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  65. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  66. package/runtime/js/cm-prd/self-check.mjs +6 -3
  67. package/runtime/js/cm-prd/summary.mjs +3 -1
  68. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  69. package/runtime/js/spec-task-line.mjs +117 -0
  70. package/runtime/js/specs-status.mjs +10 -3
  71. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  72. package/scripts/cm-ai-admission.mjs +18 -11
  73. package/scripts/cm-ai-admission.test.mjs +65 -1
  74. package/scripts/cm-ai-batch-drive.mjs +92 -20
  75. package/scripts/cm-ai-batch-drive.test.mjs +164 -3
  76. package/scripts/cm-ai-batch-host.mjs +27 -11
  77. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  78. package/scripts/cm-ai-batch-run.mjs +33 -10
  79. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  80. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  81. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  82. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  84. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  85. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  86. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  87. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  88. package/scripts/cm-ai-drive.mjs +479 -47
  89. package/scripts/cm-ai-drive.test.mjs +240 -10
  90. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  91. package/scripts/cm-ai-host.mjs +84 -25
  92. package/scripts/cm-ai-host.test.mjs +232 -12
  93. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  94. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  95. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  96. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  97. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  98. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  99. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  100. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  101. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  102. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  103. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  104. package/scripts/cm-ai-run.mjs +160 -60
  105. package/scripts/cm-ai-run.test.mjs +4 -3
  106. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  107. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  108. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  109. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  110. package/scripts/cm-ai-supersede.test.mjs +571 -17
  111. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  112. package/scripts/cm-capability-gate.test.mjs +21 -2
  113. package/scripts/cm-check-drive.test.mjs +1 -1
  114. package/scripts/cm-check-host.test.mjs +1 -1
  115. package/scripts/cm-check-runtime.sh +1 -1
  116. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  117. package/scripts/cm-claude-probe.test.mjs +9 -1
  118. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  119. package/scripts/cm-claude-worker.test.mjs +11 -4
  120. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  121. package/scripts/cm-failover.mjs +8 -8
  122. package/scripts/cm-fix-abandon.test.mjs +123 -5
  123. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  124. package/scripts/cm-fix-drive.mjs +45 -13
  125. package/scripts/cm-fix-drive.test.mjs +36 -1
  126. package/scripts/cm-fix-host.mjs +9 -6
  127. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  128. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  129. package/scripts/cm-host-check.test.mjs +6 -3
  130. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  131. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  132. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  133. package/scripts/cm-log-event.mjs +17 -0
  134. package/scripts/cm-log-event.test.mjs +31 -0
  135. package/scripts/cm-prd-completion.test.mjs +75 -0
  136. package/scripts/cm-prd-draft.test.mjs +14 -0
  137. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  138. package/scripts/cm-prd-review-gate.mjs +126 -81
  139. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  140. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  141. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  142. package/scripts/cm-prd-self-check.test.mjs +6 -0
  143. package/scripts/cm-prd-summary.test.mjs +9 -0
  144. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  145. package/scripts/cm-review-inventory.test.mjs +253 -1
  146. package/scripts/cm-spec-manifest.mjs +28 -10
  147. package/scripts/cm-spec-manifest.test.mjs +8 -4
  148. package/scripts/cm-spec-task-line.test.mjs +138 -0
  149. package/scripts/cm-specs-status.test.mjs +12 -1
  150. package/scripts/cm-task-gate.mjs +18 -10
  151. package/scripts/cm-task-gate.py +1 -1
  152. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  153. package/scripts/fixtures/claude-review-process.mjs +1 -0
  154. package/scripts/fixtures/process-cleanup.mjs +99 -0
  155. package/scripts/test-cm-log-event.py +2 -0
  156. package/scripts/test-cm-prd-review-gate.py +2 -1
  157. package/scripts/test-npm-install.py +1 -1
  158. package/scripts/test-scan-public-safety.py +1 -1
  159. package/scripts/test-spec-manifest.py +16 -8
  160. package/scripts/test-task-gate.py +2 -2
  161. package/scripts/test-workflow-config.py +1 -0
  162. package/scripts/validate-public-repo.py +1 -0
  163. package/skills/cm-ai/references/N1-init.md +1 -1
  164. package/skills/cm-ai/references/js-host.md +261 -42
  165. package/skills/cm-fix/references/js-host.md +22 -1
  166. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  167. package/skills/cm-prd/references/js-host.md +6 -0
@@ -4,11 +4,13 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {PassThrough} from 'node:stream';
7
+ import {spawnSync} from 'node:child_process';
8
+ import {fileURLToPath} from 'node:url';
7
9
  import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
8
10
  import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
9
11
  import {createHostQaDecisionProvider} from '../runtime/js/cm-ai/host-qa-policy.mjs';
10
12
  import {createHostQaExecutor} from '../runtime/js/cm-ai/host-qa-executor.mjs';
11
- import {recordCmAiQaDecision,recordCmAiQaRun,inspectCmAiQaResult} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
13
+ import {recordCmAiQaDecision,recordCmAiQaRun,inspectCmAiQaResult,readCmAiQaRunRound} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
12
14
 
13
15
  function fixture() {
14
16
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-qa-exec-')));
@@ -224,7 +226,7 @@ test('host QA cancellation leaves an unfinished invocation and never writes succ
224
226
  }finally{f.cleanup();}
225
227
  });
226
228
 
227
- for(const kind of ['qa_logic','qa_browser','qa_assess'])test(`QA request watchdog settles ${kind} as BLOCKED`,async()=>{
229
+ for(const kind of ['qa_logic','qa_browser','qa_assess'])test(`QA request watchdog settles ${kind} ${kind==='qa_assess'?'as a retryable qa_decision_timeout':'as BLOCKED'}`,async()=>{
228
230
  const f=fixture(),bridge=createHostToolBridge(),sent=[];
229
231
  try{
230
232
  bridge.attach(row=>{if(row.type==='host_request'){
@@ -240,9 +242,12 @@ for(const kind of ['qa_logic','qa_browser','qa_assess'])test(`QA request watchdo
240
242
  }});
241
243
  const call=(name)=>(r,s)=>bridge.call(name,r,s,{timeoutMs:20});
242
244
  if(kind==='qa_assess'){
245
+ // A missed assessment window is a transport outcome: nothing to record.
243
246
  const {testRunId,...binding}=f.binding;
244
- const decision=await createHostQaDecisionProvider({timeoutMs:1000,assess:call(kind)}).decide(binding,new AbortController().signal);
245
- assert.equal(decision.status,'blocked');assert.equal(decision.reason,'host_request_timeout');
247
+ const log=path.join(f.binding.specsDir,'运行日志.jsonl'),before=fs.readFileSync(log);
248
+ await assert.rejects(createHostQaDecisionProvider({timeoutMs:1000,assess:call(kind)}).decide(binding,new AbortController().signal),
249
+ {code:'qa_decision_timeout'});
250
+ assert.deepEqual(fs.readFileSync(log),before);
246
251
  }else{
247
252
  const executor=createHostQaExecutor({...f.configuration,logic:call('qa_logic'),browser:call('qa_browser')});
248
253
  const binding=begin(f,executor),result=await executor.run(binding,new AbortController().signal);
@@ -637,9 +642,82 @@ test('step30b empty mid-feature plan emits one explicit deferred BLOCKED row',as
637
642
  }finally{f.cleanup();assert.equal(fs.existsSync(f.root),false);}
638
643
  });
639
644
 
640
- for(const scenario of ['evidence','cleanup','environment','timeout','logic','commands','product-blocked',
641
- 'source-drift','FAIL','mixed-failure','round-limit','incomplete','superseded-crash','one-shot','metadata-command'])
642
- test(`completed BLOCKED QA explicit rerun: ${scenario}`,async()=>{
645
+ for(const mode of ['unavailable-only','confirmation','failed-and-unavailable','insufficient-and-unavailable','unmapped'])
646
+ test(`logic report rows record why they are BLOCKED: ${mode}`,async()=>{
647
+ const f=fixture();
648
+ try{
649
+ const kill=[process.execPath,'-e','process.kill(process.pid,"SIGKILL")'];
650
+ f.configuration.commands=[{id:'killed',command:kill,caseIds:mode==='unmapped'?[]:['TC-001']},
651
+ ...(mode==='failed-and-unavailable'?[{id:'fails',command:[process.execPath,'-e','process.exit(1)'],caseIds:['TC-001']}]:[])];
652
+ if(mode==='confirmation'){
653
+ const source=path.join(f.binding.specsDir,f.binding.feature,'test-cases.json'),contract=JSON.parse(fs.readFileSync(source));
654
+ contract.cases[0].expected=['[需确认] synthetic expectation'];fs.writeFileSync(source,JSON.stringify(contract));
655
+ }
656
+ const artifact=path.join(f.binding.specsDir,'.reviews','browser.txt');fs.writeFileSync(artifact,'Synthetic observation');
657
+ const executor=createHostQaExecutor({...f.configuration,logic:async()=>({verdict:mode==='insufficient-and-unavailable'?'INSUFFICIENT_EVIDENCE':'SUPPORTED',
658
+ evidence:['Synthetic static observation']}),
659
+ browser:async request=>({verdict:'PASS',evidence:[artifact],environment:request.environment,cleanup:'completed'})});
660
+ const result=await executor.run(begin(f,executor),new AbortController().signal);
661
+ const row=fs.readFileSync(result.report,'utf8').split(/^## /m).filter(part=>part.startsWith('TC-001\n'))
662
+ .map(part=>JSON.parse(part.slice('TC-001'.length+1)))[0];
663
+ assert.equal(row.verdict,mode==='failed-and-unavailable'?'FAIL':'BLOCKED');
664
+ assert.equal(row.commandUnavailable,mode==='unavailable-only'?true:undefined);
665
+ assert.equal(row.needsConfirmation,mode==='confirmation'?true:undefined);
666
+ }finally{f.cleanup();}
667
+ });
668
+
669
+ test('superseded rows written before recovery_rule 2 replay under the original rule; new rows use the contract',async()=>{
670
+ const f=fixture();
671
+ try{
672
+ // The original rule accepted a logic INSUFFICIENT_EVIDENCE case even with [需确认].
673
+ const source=path.join(f.binding.specsDir,f.binding.feature,'test-cases.json'),contract=JSON.parse(fs.readFileSync(source));
674
+ contract.cases[0].expected=['[需确认] synthetic expectation'];fs.writeFileSync(source,JSON.stringify(contract));
675
+ f.configuration.commands[0].caseIds=[];
676
+ const artifact=path.join(f.binding.specsDir,'.reviews','browser.txt');fs.writeFileSync(artifact,'Synthetic observation');
677
+ const executor=createHostQaExecutor({...f.configuration,logic:async()=>({verdict:'INSUFFICIENT_EVIDENCE',evidence:['Synthetic static observation']}),
678
+ browser:async request=>({verdict:'PASS',evidence:[artifact],environment:request.environment,cleanup:'completed'})});
679
+ const binding=begin(f,executor),result=await executor.run(binding,new AbortController().signal);
680
+ const base={...binding,logHome:f.configuration.logHome};recordCmAiQaRun({...base,phase:'complete',result});
681
+ assert.equal(result.result,'BLOCKED');
682
+ // Old executors never wrote the marker; an old host wrote the superseded row without recovery_rule.
683
+ fs.writeFileSync(result.report,fs.readFileSync(result.report,'utf8').replace(/,\n\s*"needsConfirmation": true/g,''));
684
+ const {codeProject,testRunId,mode,caseCount,...query}=binding;
685
+ const writer=fileURLToPath(new URL('./cm-log-event.py',import.meta.url));
686
+ const data={node:'N6',repository_id:binding.identity.repositoryId,feature:binding.feature,task:binding.identity.taskId,
687
+ package_digest:binding.packageDigest,qa_decision_id:'qa-fixture-decision',operation_id:testRunId,attempt:1,mode,case_count:caseCount,
688
+ previous_test_run_id:testRunId,reason:'host_evidence_problem',blocked_cases:['TC-001'],expected_environment:f.configuration.environment};
689
+ const written=spawnSync(process.env.CM_PYTHON_BIN||'python3',[writer,'--workflow','cm-ai','--event','test_run','--phase','superseded',
690
+ '--runtime','codex','--project-root',codeProject,'--specs-dir',binding.specsDir,'--run-id',binding.identity.runId,
691
+ '--detail','QA superseded','--data-json',JSON.stringify(data)],{encoding:'utf8',env:{...process.env,CM_WORKFLOW_LOG_HOME:f.configuration.logHome}});
692
+ assert.equal(written.status,0,written.stderr);
693
+ recordCmAiQaRun({...base,testRunId:'legacy-round-2',qaRound:2,previousTestRunId:testRunId,phase:'start'});
694
+ assert.equal(readCmAiQaRunRound({...query,testRunId:'legacy-round-2'}),2);
695
+ // The same history claimed under the current rule is refused: the contract still says [需确认].
696
+ const log=path.join(binding.specsDir,'运行日志.jsonl'),kept=fs.readFileSync(log,'utf8');
697
+ fs.writeFileSync(log,kept.split('\n').map(line=>{if(!line)return line;const row=JSON.parse(line);
698
+ return row.phase==='superseded'?JSON.stringify({...row,recovery_rule:2}):line;}).join('\n'));
699
+ assert.throws(()=>readCmAiQaRunRound({...query,testRunId:'legacy-round-2'}),{code:'qa_round_invalid'});
700
+ fs.writeFileSync(log,kept);assert.equal(readCmAiQaRunRound({...query,testRunId:'legacy-round-2'}),2);
701
+ // The original rule itself is replayed exactly: it never accepted a SUPPORTED logic case.
702
+ const report=fs.readFileSync(result.report,'utf8');
703
+ fs.writeFileSync(result.report,report.replace('"staticVerdict": "INSUFFICIENT_EVIDENCE"','"staticVerdict": "SUPPORTED"'));
704
+ assert.throws(()=>readCmAiQaRunRound({...query,testRunId:'legacy-round-2'}),{code:'qa_round_invalid'});
705
+ fs.writeFileSync(result.report,report);assert.equal(readCmAiQaRunRound({...query,testRunId:'legacy-round-2'}),2);
706
+ }finally{f.cleanup();}
707
+ });
708
+
709
+ // Report forgeries: the approved contract, not the report marker, decides [需确认].
710
+ const FORGED={'contract-resolved-after-run':'logic-confirmation-insufficient','forged-confirmation-insufficient':'logic-confirmation-insufficient',
711
+ 'forged-confirmation-unavailable':'logic-confirmation-unavailable','forged-browser-confirmation':'needs-confirmation',
712
+ // No browser answer happened: a marker added to the report must not stand in for one.
713
+ 'forged-no-capability':'no-browser-capability','forged-browser-evidence':'needs-confirmation'};
714
+ for(const name of ['evidence','cleanup','environment','timeout','logic','commands','product-blocked',
715
+ 'source-drift','FAIL','mixed-failure','round-limit','incomplete','superseded-crash','one-shot','metadata-command',
716
+ 'legacy-product-blocked','needs-confirmation','command-unavailable','command-exit','declared-command-exit','declared-product-fail',
717
+ 'declared-contradicted','declared-after-repair','declared-superseded-crash','declared-blocked','declared-unknown-verdict',
718
+ 'logic-confirmation-unavailable','logic-confirmation-insufficient','no-browser-capability',...Object.keys(FORGED)])
719
+ test(`completed BLOCKED QA explicit rerun: ${name}`,async()=>{
720
+ const scenario=FORGED[name]??name;
643
721
  const {createCmAiConversationEntry}=await import('../runtime/js/cm-ai/cm-ai-conversation-entry.mjs');
644
722
  const {inspectCmAiQaRecovery}=await import('../runtime/js/cm-ai/cm-ai-qa-log.mjs');
645
723
  const {inspectRunClosure}=await import('./cm-log-event.mjs');
@@ -649,24 +727,62 @@ test(`completed BLOCKED QA explicit rerun: ${scenario}`,async()=>{
649
727
  if(scenario==='logic')f.configuration.commands[0].caseIds=[];
650
728
  if(scenario==='metadata-command')f.configuration.commands[0].id='deferred_cases';
651
729
  if(scenario==='commands')f.configuration.commands=[];
730
+ // [需确认] keeps a case BLOCKED on every round; a rerun can never resolve it.
731
+ const confirmation={'needs-confirmation':1,'logic-confirmation-unavailable':0,'logic-confirmation-insufficient':0}[scenario];
732
+ if(confirmation!==undefined){
733
+ const source=path.join(f.binding.specsDir,f.binding.feature,'test-cases.json'),contract=JSON.parse(fs.readFileSync(source));
734
+ contract.cases[confirmation].expected=['[需确认] synthetic expectation'];fs.writeFileSync(source,JSON.stringify(contract));
735
+ }
736
+ // Environment stand-in outside both roots: killed (no exit code) or exit 65 until it is fixed.
737
+ const ready=path.join(f.root,'environment-ready');
738
+ const exits=['command-exit','declared-command-exit','declared-contradicted','declared-after-repair','declared-superseded-crash','declared-unknown-verdict'];
739
+ const killed=['command-unavailable','logic-confirmation-unavailable'].includes(scenario);
740
+ if([...(killed?[scenario]:[]),...exits].includes(scenario))f.configuration.commands[0].command=[process.execPath,'-e',
741
+ `require('node:fs').existsSync(${JSON.stringify(ready)})||${killed?'process.kill(process.pid,"SIGKILL")':'process.exit(65)'}`];
742
+ const failLike=['FAIL','declared-product-fail'].includes(scenario),contradicted=['mixed-failure','declared-contradicted'].includes(scenario);
743
+ const hostBlocked=['product-blocked','legacy-product-blocked'].includes(scenario);
652
744
  let repaired=false,browserCalls=0,logicCalls=0;
653
745
  const executor=createHostQaExecutor({...f.configuration,
654
- logic:async()=>{logicCalls++;return {verdict:scenario==='mixed-failure'?'CONTRADICTED':
655
- scenario==='logic'?'INSUFFICIENT_EVIDENCE':'SUPPORTED',evidence:['Synthetic static observation']};},
656
- browser:async request=>{
746
+ logic:async()=>{logicCalls++;return {verdict:contradicted?'CONTRADICTED':
747
+ ['logic','logic-confirmation-insufficient'].includes(scenario)?'INSUFFICIENT_EVIDENCE':'SUPPORTED',evidence:['Synthetic static observation']};},
748
+ // Without a browser capability the executor itself blocks the case; no
749
+ // session answered it, so a rerun on the same host cannot change it.
750
+ ...(scenario==='no-browser-capability'?{}:{browser:async request=>{
657
751
  browserCalls++;
658
752
  if(!repaired&&scenario==='source-drift')fs.appendFileSync(path.join(f.configuration.codeProject,'source.mjs'),'// drift\n');
659
753
  if(!repaired&&scenario==='timeout')throw Object.assign(new Error('timeout'),{code:'host_request_timeout'});
660
- return {verdict:!repaired&&scenario==='FAIL'?'FAIL':!repaired&&scenario==='product-blocked'?'BLOCKED':'PASS',
661
- evidence:!repaired&&['evidence','source-drift','round-limit','incomplete','superseded-crash','one-shot','mixed-failure','metadata-command'].includes(scenario)
754
+ return {verdict:!repaired&&failLike?'FAIL':!repaired&&hostBlocked?'BLOCKED':'PASS',
755
+ evidence:!repaired&&['evidence','source-drift','round-limit','incomplete','superseded-crash','one-shot','mixed-failure','declared-contradicted','metadata-command','declared-blocked'].includes(scenario)
662
756
  ?['not-an-evidence-file']: [artifact],
663
757
  environment:!repaired&&scenario==='environment'?{...request.environment,target:'different-target'}:request.environment,
664
758
  cleanup:!repaired&&scenario==='cleanup'?'failed':'completed'};
665
- }});
759
+ }})});
666
760
  const binding=begin(f,executor),result=await executor.run(binding,new AbortController().signal);
667
761
  const {codeProject,testRunId,mode,caseCount,...query}=binding;
668
762
  const base={...binding,logHome:f.configuration.logHome};
669
763
  if(scenario!=='incomplete')recordCmAiQaRun({...base,phase:'complete',result});
764
+ // Older executors wrote host-declared BLOCKED rows without the marker; those stay ineligible.
765
+ if(scenario==='legacy-product-blocked')fs.writeFileSync(result.report,
766
+ fs.readFileSync(result.report,'utf8').replace(/,\n\s*"hostDeclaredBlocked": true/g,''));
767
+ // The contract no longer says [需确认], but the run's own report does: still refused.
768
+ if(name==='contract-resolved-after-run'){
769
+ const source=path.join(f.binding.specsDir,f.binding.feature,'test-cases.json'),contract=JSON.parse(fs.readFileSync(source));
770
+ contract.cases[0].expected=['Synthetic expected behavior'];fs.writeFileSync(source,JSON.stringify(contract));
771
+ }else if(FORGED[name]){
772
+ const forge={'forged-confirmation-insufficient':['TC-001',row=>{delete row.needsConfirmation;}],
773
+ 'forged-confirmation-unavailable':['TC-001',row=>{delete row.needsConfirmation;row.commandUnavailable=true;}],
774
+ 'forged-browser-confirmation':['TC-002',row=>{row.hostDeclaredBlocked=true;}],
775
+ 'forged-no-capability':['TC-002',row=>{row.hostDeclaredBlocked=true;}],
776
+ // A forged evidence problem on a [需确认] case: the contract still refuses it.
777
+ 'forged-browser-evidence':['TC-002',row=>{row.evidenceProblem='qa_evidence_required';}]}[name];
778
+ const parts=fs.readFileSync(result.report,'utf8').split(/^## /m),index=parts.findIndex(part=>part.startsWith(`${forge[0]}\n`));
779
+ const body=parts[index].slice(forge[0].length+1),row=JSON.parse(body);forge[1](row);
780
+ parts[index]=`${forge[0]}\n\n${JSON.stringify(row,null,2)}${body.match(/\s*$/)[0]}`;
781
+ fs.writeFileSync(result.report,parts.map((part,i)=>i?`## ${part}`:part).join(''));
782
+ }
783
+ // A report row outside PASS/FAIL/BLOCKED no longer matches the recorded counts.
784
+ if(scenario==='declared-unknown-verdict')fs.writeFileSync(result.report,
785
+ fs.readFileSync(result.report,'utf8').replace(/("id": "TC-001",[\s\S]*?"verdict": )"FAIL"/,'$1"SKIPPED"'));
670
786
  if(scenario!=='incomplete'){
671
787
  const state=JSON.parse(fs.readFileSync(path.join(binding.specsDir,'.cm-status.json')));
672
788
  assert.equal(state.state,result.failed?'qa_failed':'qa_blocked');assert.equal(state.node,'N6');
@@ -679,6 +795,8 @@ test(`completed BLOCKED QA explicit rerun: ${scenario}`,async()=>{
679
795
  recordCmAiQaRun({...base,testRunId:`blocked-${round+1}`,qaRound:round+1,previousTestRunId:previous,phase:'start'});
680
796
  recordCmAiQaRun({...base,testRunId:`blocked-${round+1}`,qaRound:round+1,phase:'complete',result});
681
797
  }
798
+ if(scenario==='declared-superseded-crash')recordCmAiQaRun({...base,phase:'superseded',
799
+ expectedEnvironment:f.configuration.environment,environmentFailure:'simulator runtime was missing'});
682
800
  if(scenario==='superseded-crash'){
683
801
  recordCmAiQaRun({...base,phase:'superseded'});
684
802
  assert.equal(inspectRunClosure(log,binding.identity.runId).closed,false);
@@ -694,15 +812,36 @@ test(`completed BLOCKED QA explicit rerun: ${scenario}`,async()=>{
694
812
  assert.equal(without.code,scenario==='incomplete'?'qa_execution_unknown':result.failed?'qa_failed':'qa_result_blocked');
695
813
  if(!result.failed&&scenario!=='incomplete')assert.equal(without.pendingAction,'none');
696
814
  assert.deepEqual(fs.readFileSync(log),before);
697
- const entry=createCmAiConversationEntry({...options,rerunBlockedQa:true});
698
- if(['commands','product-blocked','source-drift','FAIL','mixed-failure','round-limit','incomplete'].includes(scenario)){
815
+ if(scenario==='declared-command-exit'){
816
+ // The declaration only travels with the one-shot rerun grant and a superseded row.
817
+ for(const bad of [{qaEnvironmentFailure:'no rerun grant'},{rerunBlockedQa:true,qaEnvironmentFailure:'two\nlines'}])
818
+ assert.throws(()=>createCmAiConversationEntry({...options,...bad}),{code:'qa_recovery_authorization_required'});
819
+ assert.throws(()=>recordCmAiQaRun({...base,testRunId:'declared-start',qaRound:2,phase:'start',environmentFailure:'misplaced'}),
820
+ {code:'qa_recovery_authorization_required'});
821
+ }
822
+ // An accepted repair already owns the next round of that FAIL.
823
+ const repairedRunner=scenario==='declared-after-repair'?{runner:{...options.runner,status:()=>({...completed,
824
+ acceptedQaFix:{qaRound:1,testRunId,evidenceDigest:'c'.repeat(64)}})}}:{};
825
+ const entry=createCmAiConversationEntry({...options,...repairedRunner,rerunBlockedQa:true,
826
+ ...(scenario.startsWith('declared-')&&scenario!=='declared-superseded-crash'?{qaEnvironmentFailure:'simulator runtime was missing'}:{})});
827
+ if(['commands','legacy-product-blocked','needs-confirmation','source-drift','FAIL','mixed-failure','round-limit','incomplete',
828
+ 'command-exit','declared-product-fail','declared-contradicted','declared-after-repair','declared-blocked',
829
+ 'declared-unknown-verdict','logic-confirmation-unavailable','logic-confirmation-insufficient','no-browser-capability'].includes(scenario)){
699
830
  const rejected=await entry.handle(operation);
700
831
  assert.equal(rejected.code,scenario==='round-limit'?'qa_round_invalid':scenario==='incomplete'?'qa_execution_unknown':'qa_rerun_not_blocked_by_evidence');
701
- assert.deepEqual(fs.readFileSync(log),before);assert.equal(browserCalls,1);
832
+ assert.deepEqual(fs.readFileSync(log),before);
833
+ assert.equal(browserCalls,['needs-confirmation','no-browser-capability'].includes(scenario)?0:1);
834
+ if(name==='no-browser-capability'){
835
+ // Neither the durable log nor the report claims a host answer that never happened.
836
+ const row=JSON.parse(fs.readFileSync(result.report,'utf8').split(/^## /m).find(part=>part.startsWith('TC-002\n')).slice('TC-002'.length+1));
837
+ assert.equal(row.hostDeclaredBlocked,undefined);
838
+ assert.equal(rows().find(item=>item.phase==='case_blocked'&&item.case_id==='TC-002').host_declared_blocked,undefined);
839
+ }
702
840
  }else{
703
841
  const queried=await entry.handle({...operation,operation:'qa_result',packageDigest:binding.packageDigest,testRunId});
704
- assert.equal(queried.pendingAction,'qa');
842
+ assert.equal(queried.pendingAction,result.failed?'fix_authorization':'qa');
705
843
  repaired=scenario!=='one-shot';
844
+ if(['command-unavailable',...exits].includes(scenario))fs.writeFileSync(ready,'');
706
845
  const rerun=await entry.handle(operation);
707
846
  assert.equal(rerun.code,['logic','one-shot'].includes(scenario)?'qa_result_blocked':'qa_passed',JSON.stringify(rerun));
708
847
  assert.equal(browserCalls,2);assert.equal(logicCalls,2);
@@ -727,6 +866,42 @@ test(`completed BLOCKED QA explicit rerun: ${scenario}`,async()=>{
727
866
  fs.writeFileSync(log,corrupt.map(JSON.stringify).join('\n')+'\n');
728
867
  assert.throws(()=>inspectCmAiQaRecovery(query,{blocked:true}));fs.writeFileSync(log,after);
729
868
  }
869
+ // The passing successor re-validates its predecessor's exact report and
870
+ // supersession fields, so each forged detail is caught on its own.
871
+ const round2=starts[1].operation_id,firstReport=rows().find(row=>row.phase==='complete'&&row.operation_id===testRunId).report;
872
+ const precise=[];
873
+ if(scenario==='command-unavailable')precise.push(['report',row=>{row.exitCode=0;}],
874
+ ['report',row=>{row.evidence=['No declared project test command'];}],
875
+ ['log',list=>{list.find(row=>row.phase==='superseded').failed_cases=[];}],
876
+ // The logic case is eligible only by its own "blocked by that command" marker.
877
+ ['report',row=>{delete row.commandUnavailable;},'TC-001'],['report',row=>{row.commandEvidence=[];},'TC-001'],
878
+ ['report',row=>{row.needsConfirmation=true;},'TC-001'],
879
+ ['report',row=>{row.staticVerdict='CONTRADICTED';},'TC-001'],
880
+ ['log',list=>{list.find(row=>row.phase==='superseded').recovery_rule=3;}],
881
+ ['contract',contract=>{contract.cases=contract.cases.filter(item=>item.id!=='TC-001');}]);
882
+ // The host-declared BLOCKED needs both the durable log row and the report mirror.
883
+ if(scenario==='product-blocked')precise.push(
884
+ ['log',list=>{delete list.find(row=>row.phase==='case_blocked'&&row.operation_id===testRunId).host_declared_blocked;}],
885
+ ['report',row=>{delete row.hostDeclaredBlocked;},'TC-002']);
886
+ if(['declared-command-exit','declared-superseded-crash'].includes(scenario))precise.push(['report',row=>{row.exitCode=null;}],
887
+ ['report',row=>{row.exitCode=0;}],['log',list=>{list.find(row=>row.phase==='superseded').environment_failure_reason=' ';}],
888
+ ['log',list=>{list.find(row=>row.phase==='superseded').failed_cases=['declared-test'];}],
889
+ ['report',row=>{row.verdict='SKIPPED';},'TC-001']);
890
+ if(precise.length)assert.equal(inspectCmAiQaResult({...query,testRunId:round2}).status,'passed');
891
+ const contractFile=path.join(f.binding.specsDir,f.binding.feature,'test-cases.json'),contractBytes=fs.readFileSync(contractFile);
892
+ for(const [target,tamper,caseId='declared-test'] of precise){
893
+ const report=fs.readFileSync(firstReport,'utf8');
894
+ if(target==='contract'){const contract=JSON.parse(contractBytes);tamper(contract);fs.writeFileSync(contractFile,JSON.stringify(contract));}
895
+ else if(target==='report'){
896
+ const parts=report.split(/^## /m),index=parts.findIndex(part=>part.startsWith(`${caseId}\n`));
897
+ const body=parts[index].slice(caseId.length+1),row=JSON.parse(body);tamper(row);
898
+ parts[index]=`${caseId}\n\n${JSON.stringify(row,null,2)}${body.match(/\s*$/)[0]}`;
899
+ fs.writeFileSync(firstReport,parts.map((part,i)=>i?`## ${part}`:part).join(''));
900
+ }else{const corrupt=rows();tamper(corrupt);fs.writeFileSync(log,corrupt.map(JSON.stringify).join('\n')+'\n');}
901
+ assert.throws(()=>inspectCmAiQaResult({...query,testRunId:round2}),{code:'qa_result_invalid'},`${target} ${tamper}`);
902
+ fs.writeFileSync(firstReport,report);fs.writeFileSync(log,after);fs.writeFileSync(contractFile,contractBytes);
903
+ }
904
+ if(precise.length)assert.equal(inspectCmAiQaResult({...query,testRunId:round2}).status,'passed');
730
905
  }
731
906
  }finally{f.cleanup();}
732
907
  });
@@ -3,6 +3,7 @@ import test from 'node:test';
3
3
  import {PassThrough} from 'node:stream';
4
4
 
5
5
  import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
6
+ import {needPrd} from '../runtime/js/cm-prd/validation-reason.mjs';
6
7
 
7
8
  // Drives one request through the real JSONL transport and returns both channels.
8
9
  async function exchange(request,handle){
@@ -37,6 +38,15 @@ test('the failing operation is named so a strict field set can be told apart', a
37
38
  assert.equal(diagnostics[0].code,'invalid_input');
38
39
  });
39
40
 
41
+ test('known PRD validation reason reaches operator diagnostics but not peer',async()=>{
42
+ const reason={field:'response.at',expected:'new Date().toISOString() form, e.g. 2026-09-08T00:00:00.000Z'};
43
+ const {replies,diagnostics}=await exchange({operation:'final_review',requestId:'r-prd'},()=>{
44
+ needPrd(false,'prd_review_timestamp_invalid',reason);
45
+ });
46
+ assert.deepEqual(replies,[{requestId:'r-prd',error:{code:'host_request_failed'}}]);
47
+ assert.deepEqual(diagnostics[0].reason,reason);
48
+ });
49
+
40
50
  test('a success emits no diagnostic', async () => {
41
51
  const {replies,diagnostics}=await exchange({operation:'status',requestId:'r3'},
42
52
  async()=>({outcome:'reported'}));
@@ -0,0 +1,53 @@
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 {readBrowserCapability} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
7
+ import {main as hostMain} from './cm-ai-host.mjs';
8
+ import {buildManifest} from './cm-spec-manifest.mjs';
9
+
10
+ test('interactive QA capability failure names iOS simulator and the compatible flag',()=>{
11
+ assert.throws(()=>readBrowserCapability(undefined,['ios-simulator']),error=>{
12
+ assert.equal(error.code,'browser_capability_required');
13
+ assert.match(error.reason,/ios-simulator/);
14
+ assert.match(error.reason,/--browser-qa available\|unavailable/);
15
+ assert.match(error.reason,/interactive QA/);
16
+ return true;
17
+ });
18
+ assert.equal(readBrowserCapability('available',['ios-simulator']),'available');
19
+ });
20
+
21
+ test('interactive carrier diagnostic rejects undeclared carrier text',()=>{
22
+ assert.throws(()=>readBrowserCapability(undefined,['/private/synthetic-secret']),{code:'invalid_arguments'});
23
+ });
24
+
25
+ test('single-task CLI names ios-simulator before opening a host',async t=>{
26
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-ios-carrier-')));
27
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
28
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),feature='1.work';
29
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
30
+ fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'- [AC-001]: fixture\n');
31
+ fs.writeFileSync(path.join(specsDir,feature,'design.md'),'# Fixture\n');
32
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
33
+ fs.writeFileSync(path.join(specsDir,feature,'test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',
34
+ cases:[{id:'TC-001',kind:'browser',blocking:true,origin:'user',acIds:['AC-001'],taskIds:['T-001'],
35
+ title:'Simulator check',preconditions:[],steps:['Open app'],expected:['App opens'],cleanup:[]}]}));
36
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],
37
+ specFiles:buildManifest(specsDir)}));
38
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
39
+ const config=path.join(root,'run.json'),workflow=path.join(root,'workflow.json');
40
+ fs.writeFileSync(config,JSON.stringify({version:1,specsDir,codeProject,feature,
41
+ identity:{repositoryId:'fixture',runId:'ios-carrier',taskId:'T-001',attempt:1},
42
+ scope:['target.mjs'],requirements:['requirements.md']}));
43
+ fs.writeFileSync(workflow,JSON.stringify({documentationPaths:[],applicableAgentFiles:[],
44
+ qa:{commands:[],environment:{kind:'app',carrier:'ios-simulator',target:'fixture-app',scope:'local'}}}));
45
+ let stderr='',stdout='';
46
+ const exit=await hostMain(['serve','--config',config,'--mode','create','--host-context','fixture-host',
47
+ '--allow-development','--workflow-config',workflow,'--allow-qa'],{
48
+ output:{write:text=>{stdout+=text;}},error:{write:text=>{stderr+=text;}}});
49
+ assert.equal(exit,1);assert.equal(stdout,'');
50
+ const error=JSON.parse(stderr).error;
51
+ assert.equal(error.code,'browser_capability_required');
52
+ assert.match(error.reason,/ios-simulator/);
53
+ });
@@ -9,6 +9,10 @@ import {fileURLToPath} from 'node:url';
9
9
  const IDENTIFIER=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/;
10
10
  const RESOURCE_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
11
11
  const RUN_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{7,127}$/;
12
+ // The single run ID rule. Workflow run definitions must satisfy it before they
13
+ // create durable state, otherwise the first log write fails inside an effect.
14
+ export const RUN_ID_RULE='8-128 characters of A-Z a-z 0-9 . _ -, starting with a letter or digit';
15
+ export const validRunId=value=>typeof value==='string'&&RUN_ID.test(value);
12
16
  const SENSITIVE_KEY=/(api[_-]?key|authorization|cookie|password|passwd|private[_-]?key|recovery[_-]?code|secret|token)/i;
13
17
  const RESERVED_FIELDS=new Set(['schema_version','event_id','run_id','at','workflow','event','phase','runtime','project','project_path','specs_path','detail']);
14
18
  export const TERMINAL_EVENTS=new Set(['done','run_done']);
@@ -345,6 +349,19 @@ function validateQaSupersession(state,event){
345
349
  throw new UsageError('QA configuration supersession requires the matching completed invocation and revision digest');
346
350
  return;
347
351
  }
352
+ const caseList=(value,count)=>Array.isArray(value)&&value.length===count&&new Set(value).size===value.length
353
+ &&value.every(item=>typeof item==='string'&&RESOURCE_ID.test(item));
354
+ if(event.reason==='declared_environment_failure'){
355
+ const reason=event.environment_failure_reason;
356
+ if(state.active||state.superseded||!start||!complete||complete.result!=='FAIL'||!(complete.failed>0)
357
+ ||start.attempt>=3||event.workflow!=='cm-ai'||event.node!=='N6'||event.previous_test_run_id!==start.operation_id
358
+ ||!caseList(event.failed_cases,complete.failed)||!caseList(event.blocked_cases,complete.blocked)
359
+ ||typeof reason!=='string'||!reason.trim()||Buffer.byteLength(reason,'utf8')>500||/[\r\n\0]/.test(reason)
360
+ ||!['repository_id','run_id','feature','task','package_digest','qa_decision_id','operation_id','attempt','mode','case_count']
361
+ .every(key=>event[key]!==undefined&&event[key]===start[key]&&event[key]===complete[key]))
362
+ throw new UsageError('QA environment-failure supersession requires the matching completed FAIL invocation, case lists and reason');
363
+ return;
364
+ }
348
365
  if(state.active||state.superseded||!start||!complete||complete.result!=='BLOCKED'||complete.failed!==0
349
366
  ||complete.blocked<=0||start.attempt>=3||event.workflow!=='cm-ai'||event.node!=='N6'
350
367
  ||event.reason!=='host_evidence_problem'||event.previous_test_run_id!==start.operation_id
@@ -68,3 +68,34 @@ test('JS log persistence writes project authority, mirrors globally, and dedupli
68
68
  assert.equal(fs.readFileSync(result.project_log,'utf8').trim().split('\n').length,1);
69
69
  }finally{fs.rmSync(root,{recursive:true,force:true});}
70
70
  });
71
+
72
+ test('QA environment-failure supersession needs the matching completed FAIL, both case lists and a single-line reason',()=>{
73
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-log-env-failure-')));
74
+ try{
75
+ const project=path.join(root,'project'),specs=path.join(root,'specs'),runId='env-failure-run';
76
+ fs.mkdirSync(project);fs.mkdirSync(specs);
77
+ const env={...process.env,CM_WORKFLOW_LOG_HOME:path.join(root,'logs')};
78
+ const bound={node:'N6',repository_id:'fixture',feature:'1.work',task:'T-001',package_digest:'a'.repeat(64),
79
+ qa_decision_id:'qa-decision',operation_id:'qa-round-1',attempt:1,mode:'commands',case_count:2};
80
+ const write=(phase,data)=>spawnSync(process.env.CM_PYTHON_BIN||'python3',[pythonWriter,'--workflow','cm-ai','--event','test_run',
81
+ '--phase',phase,'--runtime','codex','--project-root',project,'--specs-dir',specs,'--run-id',runId,'--detail',`QA ${phase}`,
82
+ '--data-json',JSON.stringify({...bound,...data})],{encoding:'utf8',env});
83
+ assert.equal(write('start',{}).status,0);
84
+ assert.equal(write('complete',{result:'FAIL',passed:0,failed:1,blocked:1,report:'r.md'}).status,0);
85
+ const valid={previous_test_run_id:'qa-round-1',reason:'declared_environment_failure',failed_cases:['probe'],
86
+ blocked_cases:['TC-001'],expected_environment:null,environment_failure_reason:'simulator runtime was missing'};
87
+ for(const invalid of [{failed_cases:[]},{blocked_cases:[]},{failed_cases:['probe','probe']},{environment_failure_reason:' '},
88
+ {environment_failure_reason:'two\nlines'},{previous_test_run_id:'other'},{reason:'host_evidence_problem'}]){
89
+ const result=write('superseded',{...valid,...invalid});
90
+ assert.notEqual(result.status,0,JSON.stringify(invalid));
91
+ }
92
+ const accepted=write('superseded',valid);assert.equal(accepted.status,0,accepted.stderr);
93
+ // A BLOCKED invocation (no failures) cannot carry an environment-failure declaration.
94
+ const blockedRun={...bound,operation_id:'qa-round-2',attempt:2};
95
+ assert.equal(write('start',{...blockedRun,previous_test_run_id:'qa-round-1'}).status,0);
96
+ assert.equal(write('complete',{...blockedRun,result:'BLOCKED',passed:1,failed:0,blocked:1,report:'r.md'}).status,0);
97
+ assert.notEqual(write('superseded',{...blockedRun,...valid,previous_test_run_id:'qa-round-2',failed_cases:[]}).status,0);
98
+ assert.equal(write('superseded',{...blockedRun,previous_test_run_id:'qa-round-2',reason:'host_evidence_problem',
99
+ blocked_cases:['TC-001'],expected_environment:null}).status,0);
100
+ }finally{fs.rmSync(root,{recursive:true,force:true});}
101
+ });
@@ -155,6 +155,81 @@ test('change cannot invent completion or erase completed lines; user case change
155
155
  const synthetic={...before,files:{...before.files,'1.guide/test-cases.json':JSON.stringify({cases:[{id:'TC-001',origin:'user',expected:'Original user intent'}]})}};
156
156
  const proposal=inspectPrdChangeProposal(synthetic,raw,['1.guide'],config);assert.equal(proposal.changedUserCases.length,1);
157
157
  });
158
+ // Same declaration grammar as admission/N5: a completed task without a colon is still guarded.
159
+ test('change guards completed tasks written without a colon or with a full-width colon',t=>{
160
+ const dir=fixture(t),config=loadConfig({projectRoot:dir});
161
+ // Approved under the shared grammar (taskGrammar 2), where both spellings are declarations.
162
+ fs.writeFileSync(path.join(dir,'.cm-specs-status'),JSON.stringify({status:'approved',taskGrammar:2}),{mode:0o600});
163
+ for(const spelling of ['- [x] T-001 Existing guide','- [x] T-001:Existing guide']){
164
+ fs.writeFileSync(path.join(dir,'1.guide/tasks.md'),docs()[2].content.replace('- [x] T-001: Existing guide',spelling),{mode:0o600});
165
+ const before=inspectPrdChangeSnapshot(dir),task=revised().find(doc=>doc.path==='tasks.md');
166
+ const erased={status:'draft',summary:'Change',removed:[],features:[{directory:'1.guide',
167
+ documents:revised().map(doc=>doc.path==='tasks.md'?{...doc,content:task.content.replace('- [x] T-001: Existing guide',spelling.replace('[x]','[ ]'))}:doc),
168
+ testCasesReason:'no_observable_behavior'}]};
169
+ assert.throws(()=>inspectPrdChangeProposal(before,erased,['1.guide'],config),/prd_completed_task_changed/,spelling);
170
+ }
171
+ });
172
+ // The approved original is read with its approval's grammar: under a legacy
173
+ // approval an unfenced full-width example is prose, not the completed task.
174
+ test('change guard reads the approved original with the legacy grammar',t=>{
175
+ const dir=fixture(t),config=loadConfig({projectRoot:dir}),example='- [ ] T-001:旧写法示例';
176
+ fs.writeFileSync(path.join(dir,'1.guide/tasks.md'),docs()[2].content.replace('- [x] T-001: Existing guide\n',
177
+ `- [x] T-001: Existing guide\n${example}\n`),{mode:0o600});
178
+ const before=inspectPrdChangeSnapshot(dir),task=revised().find(doc=>doc.path==='tasks.md');
179
+ const fenced={status:'draft',summary:'Fence the old example',removed:[],features:[{directory:'1.guide',
180
+ documents:revised().map(doc=>doc.path==='tasks.md'?{...doc,content:task.content.replace('- [x] T-001: Existing guide\n',
181
+ `- [x] T-001: Existing guide\n\`\`\`md\n${example}\n\`\`\`\n`)}:doc),testCasesReason:'no_observable_behavior'}]};
182
+ const proposal=inspectPrdChangeProposal(before,fenced,['1.guide'],config);
183
+ assert.equal(proposal.proposalDigest.length,64);
184
+ });
185
+ // Fifth review: two cm-prd --change runs before re-approval keep the grammar the
186
+ // last approval bound, carried through the awaiting_review status of the first.
187
+ function sharedGrammarFixture(t){
188
+ const dir=fixture(t),tasks=path.join(dir,'1.guide/tasks.md');
189
+ fs.writeFileSync(tasks,fs.readFileSync(tasks,'utf8').replace('- [ ] T-002: Draft appendix','- [ ] T-002:Draft appendix'),{mode:0o600});
190
+ fs.writeFileSync(path.join(dir,'.cm-specs-status'),JSON.stringify({status:'approved',taskGrammar:2}),{mode:0o600});
191
+ return dir;
192
+ }
193
+ const fullWidth=docs=>docs.map(doc=>doc.path==='tasks.md'?{...doc,content:doc.content.replace('- [ ] T-002: Draft appendix','- [ ] T-002:Draft appendix')}:doc);
194
+ const status=dir=>JSON.parse(fs.readFileSync(path.join(dir,'.cm-specs-status'),'utf8'));
195
+ test('a second change of the same feature before re-approval keeps the approved grammar',t=>{
196
+ const dir=sharedGrammarFixture(t),config=loadConfig({projectRoot:dir}),selected=['1.guide'];
197
+ const first=fullWidth(revised());
198
+ let before=inspectPrdChangeSnapshot(dir);
199
+ let proposal=inspectPrdChangeProposal(before,{status:'draft',summary:'First',removed:[],features:[{directory:'1.guide',
200
+ documents:first,testCasesReason:'no_observable_behavior'}]},selected,config);
201
+ applyPrdChange({specs:dir,before,proposal,selected});
202
+ assert.equal(status(dir).status,'awaiting_review');assert.equal(status(dir).taskGrammar,2);
203
+ const second=first.map(doc=>({...doc,content:doc.content+'\n| 2026-09-08 | v3 | again |\n'
204
+ +(doc.path==='tasks.md'?'- [ ] T-004: [NEW] Another example\n':'Again\n')}));
205
+ before=inspectPrdChangeSnapshot(dir);
206
+ proposal=inspectPrdChangeProposal(before,{status:'draft',summary:'Second',removed:[],features:[{directory:'1.guide',
207
+ documents:second,testCasesReason:'no_observable_behavior'}]},selected,config);
208
+ applyPrdChange({specs:dir,before,proposal,selected});
209
+ assert.equal(status(dir).taskGrammar,2);
210
+ });
211
+ test('a second change of another feature before re-approval still carries the approved grammar',t=>{
212
+ const dir=sharedGrammarFixture(t),config=loadConfig({projectRoot:dir});
213
+ let before=inspectPrdChangeSnapshot(dir);
214
+ let proposal=inspectPrdChangeProposal(before,{status:'draft',summary:'First',removed:[],features:[{directory:'1.guide',
215
+ documents:fullWidth(revised()),testCasesReason:'no_observable_behavior'}]},['1.guide'],config);
216
+ applyPrdChange({specs:dir,before,proposal,selected:['1.guide']});
217
+ before=inspectPrdChangeSnapshot(dir);
218
+ proposal=inspectPrdChangeProposal(before,{status:'draft',summary:'Second',removed:[],features:[{directory:'2.extra',
219
+ documents:docs().map(doc=>({...doc,content:doc.content.replace('[x]','[ ]')})),testCasesReason:'no_observable_behavior'}]},[],config);
220
+ applyPrdChange({specs:dir,before,proposal,selected:[]});
221
+ assert.equal(status(dir).status,'awaiting_review');assert.equal(status(dir).taskGrammar,2);
222
+ });
223
+ test('an unapproved legacy status never switches the change guard to the shared grammar',t=>{
224
+ const dir=fixture(t),config=loadConfig({projectRoot:dir}),tasks=path.join(dir,'1.guide/tasks.md');
225
+ fs.writeFileSync(tasks,fs.readFileSync(tasks,'utf8').replace('- [ ] T-002: Draft appendix','- [ ] T-002:Draft appendix'),{mode:0o600});
226
+ fs.writeFileSync(path.join(dir,'.cm-specs-status'),JSON.stringify({status:'awaiting_review'}),{mode:0o600});
227
+ const before=inspectPrdChangeSnapshot(dir);
228
+ // Under the old grammar the full-width line is prose, so rewriting it as a
229
+ // task in the proposal is a new task and needs its [NEW] mark.
230
+ assert.throws(()=>inspectPrdChangeProposal(before,{status:'draft',summary:'Change',removed:[],features:[{directory:'1.guide',
231
+ documents:revised(),testCasesReason:'no_observable_behavior'}]},['1.guide'],config),/prd_change_new_task_invalid/);
232
+ });
158
233
  test('generate_cases false retains unchanged existing generated cases, forbids new generation',t=>{
159
234
  const dir=fixture(t),before=inspectPrdChangeSnapshot(dir),config=loadConfig({projectRoot:dir});
160
235
  const contract={schemaVersion:'1.0',feature:'guide',cases:[{id:'TC-001',origin:'generated',kind:'logic',blocking:true,
@@ -18,6 +18,20 @@ test('draft structure refuses missing triad, unsafe path and dropped user cases'
18
18
  const unsafe=draft();unsafe.features[0].documents[0].path='../AGENTS.md';assert.throws(()=>inspectPrdDraft(unsafe,options));
19
19
  assert.throws(()=>inspectPrdDraft(draft(),{...options,userCasesProvided:true}));
20
20
  });
21
+ test('draft case reason identifies the feature field without accepting non-null values',()=>{
22
+ const value=draft(),feature=value.features[0];
23
+ feature.documents.push({path:'test-cases.json',content:JSON.stringify({schemaVersion:'1.0',feature:'guide',cases:[]})});
24
+ assert.throws(()=>inspectPrdDraft(value,{nextIndex:1,generateCases:true,userCasesProvided:false}),error=>
25
+ error.code==='prd_draft_cases_invalid'&&error.reason?.field==='features[0].testCasesReason'
26
+ &&/must be null when test cases are present/.test(error.reason.expected));
27
+ });
28
+ test('oversize draft reports the 64 KiB limit and actual serialized bytes',()=>{
29
+ const value=draft();value.summary='a'.repeat(65536);
30
+ const actual=Buffer.byteLength(JSON.stringify(value));
31
+ assert.throws(()=>inspectPrdDraft(value,{nextIndex:1,generateCases:true,userCasesProvided:false}),error=>
32
+ error.code==='limit_exceeded'&&error.reason?.field==='draft'
33
+ &&error.reason.limitBytes===65536&&error.reason.actualBytes===actual);
34
+ });
21
35
  test('analysis -> planner clarification -> draft preserves scope and does not write',async t=>{
22
36
  const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-draft-')));
23
37
  t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));