@aibyzero/cm-workflow 0.16.3 → 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 (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +59 -0
  4. package/README.md +55 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/next-steps.md +14 -24
  9. package/docs/runtime-failover.md +1 -1
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  12. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +30 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +116 -41
  15. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  16. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  17. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  18. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  19. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  21. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  22. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  24. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  25. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  26. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  27. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  28. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  29. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  30. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  31. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  32. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  34. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  35. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  36. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  37. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  38. package/runtime/js/cm-ai/host-session.mjs +20 -5
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  43. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  44. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  45. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  46. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  47. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  48. package/runtime/js/cm-ai/review-package.mjs +427 -31
  49. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  50. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  51. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  52. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  53. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  54. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  55. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  56. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  57. package/runtime/js/cm-fix/execution.mjs +109 -25
  58. package/runtime/js/cm-fix/host-review.mjs +7 -3
  59. package/runtime/js/cm-fix/host.mjs +3 -1
  60. package/runtime/js/cm-fix/progress.mjs +1 -0
  61. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  62. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  63. package/runtime/js/cm-prd/analysis.mjs +2 -1
  64. package/runtime/js/cm-prd/change.mjs +28 -10
  65. package/runtime/js/cm-prd/draft.mjs +5 -2
  66. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  67. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  68. package/runtime/js/cm-prd/self-check.mjs +6 -3
  69. package/runtime/js/cm-prd/summary.mjs +6 -2
  70. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  71. package/runtime/js/spec-task-line.mjs +117 -0
  72. package/runtime/js/specs-status.mjs +14 -3
  73. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  74. package/scripts/cm-ai-admission.mjs +19 -10
  75. package/scripts/cm-ai-admission.test.mjs +65 -1
  76. package/scripts/cm-ai-batch-drive.mjs +93 -21
  77. package/scripts/cm-ai-batch-drive.test.mjs +171 -3
  78. package/scripts/cm-ai-batch-host.mjs +37 -13
  79. package/scripts/cm-ai-batch-host.test.mjs +26 -0
  80. package/scripts/cm-ai-batch-run.mjs +33 -10
  81. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  82. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  84. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  85. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  86. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  87. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  88. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  89. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  90. package/scripts/cm-ai-drive.mjs +480 -47
  91. package/scripts/cm-ai-drive.test.mjs +247 -10
  92. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  93. package/scripts/cm-ai-host.mjs +89 -25
  94. package/scripts/cm-ai-host.test.mjs +274 -12
  95. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  96. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  97. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  98. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  99. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  100. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  101. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  102. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  103. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  104. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  105. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  106. package/scripts/cm-ai-run.mjs +160 -60
  107. package/scripts/cm-ai-run.test.mjs +4 -3
  108. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  109. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  110. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  111. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  112. package/scripts/cm-ai-supersede.test.mjs +571 -17
  113. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  114. package/scripts/cm-capability-gate.test.mjs +21 -2
  115. package/scripts/cm-check-drive.mjs +4 -3
  116. package/scripts/cm-check-drive.test.mjs +17 -1
  117. package/scripts/cm-check-entry.mjs +13 -2
  118. package/scripts/cm-check-host.mjs +2 -2
  119. package/scripts/cm-check-host.test.mjs +57 -1
  120. package/scripts/cm-check-runtime.sh +16 -7
  121. package/scripts/cm-claude-developer-worker.test.mjs +43 -2
  122. package/scripts/cm-claude-probe.test.mjs +9 -1
  123. package/scripts/cm-claude-review-stream.test.mjs +68 -0
  124. package/scripts/cm-claude-worker.test.mjs +11 -4
  125. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  126. package/scripts/cm-failover.mjs +8 -8
  127. package/scripts/cm-fix-abandon.test.mjs +123 -5
  128. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  129. package/scripts/cm-fix-drive.mjs +45 -13
  130. package/scripts/cm-fix-drive.test.mjs +36 -1
  131. package/scripts/cm-fix-host.mjs +9 -6
  132. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  133. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  134. package/scripts/cm-host-check.test.mjs +6 -3
  135. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  136. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  137. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  138. package/scripts/cm-log-event.mjs +17 -0
  139. package/scripts/cm-log-event.test.mjs +31 -0
  140. package/scripts/cm-prd-completion.test.mjs +105 -2
  141. package/scripts/cm-prd-draft.test.mjs +14 -0
  142. package/scripts/cm-prd-drive.mjs +13 -7
  143. package/scripts/cm-prd-drive.test.mjs +10 -0
  144. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  145. package/scripts/cm-prd-review-gate.mjs +126 -81
  146. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  147. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  148. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  149. package/scripts/cm-prd-self-check.test.mjs +6 -0
  150. package/scripts/cm-prd-summary.test.mjs +40 -0
  151. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  152. package/scripts/cm-review-inventory.test.mjs +253 -1
  153. package/scripts/cm-spec-manifest.mjs +28 -10
  154. package/scripts/cm-spec-manifest.test.mjs +8 -4
  155. package/scripts/cm-spec-task-line.test.mjs +138 -0
  156. package/scripts/cm-specs-status.test.mjs +31 -1
  157. package/scripts/cm-task-gate.mjs +18 -10
  158. package/scripts/cm-task-gate.py +1 -1
  159. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  160. package/scripts/fixtures/claude-review-process.mjs +1 -0
  161. package/scripts/fixtures/process-cleanup.mjs +99 -0
  162. package/scripts/test-cm-log-event.py +2 -0
  163. package/scripts/test-cm-prd-review-gate.py +2 -1
  164. package/scripts/test-npm-install.py +1 -1
  165. package/scripts/test-scan-public-safety.py +1 -1
  166. package/scripts/test-shell-compat.sh +67 -0
  167. package/scripts/test-spec-manifest.py +16 -8
  168. package/scripts/test-task-gate.py +2 -2
  169. package/scripts/test-workflow-config.py +1 -0
  170. package/scripts/validate-public-repo.py +1 -0
  171. package/skills/cm-ai/references/N1-init.md +1 -1
  172. package/skills/cm-ai/references/js-host.md +264 -40
  173. package/skills/cm-check/SKILL.md +6 -1
  174. package/skills/cm-check/references/js-host.md +3 -3
  175. package/skills/cm-fix/references/js-host.md +22 -1
  176. package/skills/cm-prd/references/js-change-recovery.md +30 -0
  177. package/skills/cm-prd/references/js-host.md +6 -0
@@ -0,0 +1,95 @@
1
+ // Guards for the test-only fixture process helper (2026-09-28: hung fake
2
+ // reviewers outlived their tests by 17+ hours).
3
+ import test from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {spawn,spawnSync} from 'node:child_process';
9
+ import {fixtureProcesses,guardFixtureSource,killFixtureProcesses,ownerGuardSource} from './fixtures/process-cleanup.mjs';
10
+
11
+ const skip=process.platform==='win32';
12
+ const alive=pid=>{try{process.kill(pid,0);return true;}catch(error){return error.code!=='ESRCH';}};
13
+ async function until(predicate,ms=4000){
14
+ for(const deadline=Date.now()+ms;Date.now()<deadline;){if(predicate())return true;await new Promise(r=>setTimeout(r,25));}
15
+ return predicate();
16
+ }
17
+ function fixture(t){
18
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-fixture-process-')));
19
+ t.after(()=>{killFixtureProcesses(root);fs.rmSync(root,{recursive:true,force:true});});
20
+ return root;
21
+ }
22
+ const hang="process.on('SIGTERM',()=>{});setInterval(()=>{},1000);";
23
+ function readPid(child){
24
+ return new Promise((resolve,reject)=>{let out='';
25
+ child.stdout.on('data',b=>{out+=b;const m=out.match(/^(\d+)\n/);if(m)resolve(Number(m[1]));});
26
+ child.once('error',reject);child.once('close',code=>{if(!/^\d+\n/.test(out))reject(Error(`no pid: ${code}`));});});
27
+ }
28
+
29
+ test('a guarded detached fixture dies with the test process that created it, even when TERM-resistant',{skip},async t=>{
30
+ const root=fixture(t),script=path.join(root,'hang.cjs');
31
+ // The owner stands in for a test process: it spawns the fixture detached, as
32
+ // the host under test does, then dies without any cleanup.
33
+ const owner=spawn(process.execPath,['--input-type=module','-e',`
34
+ import fs from 'node:fs';import {spawn,spawnSync} from 'node:child_process';
35
+ import {ownerGuardSource} from ${JSON.stringify(new URL('./fixtures/process-cleanup.mjs',import.meta.url).href)};
36
+ fs.writeFileSync(${JSON.stringify(script)},ownerGuardSource()+${JSON.stringify(hang)});
37
+ const c=spawn(process.execPath,[${JSON.stringify(script)}],{detached:true,stdio:'ignore'});c.unref();
38
+ process.stdout.write(c.pid+'\\n');setInterval(()=>{},1000);`],{stdio:['ignore','pipe','inherit']});
39
+ const pid=await readPid(owner);
40
+ assert.equal(fixtureProcesses(root).map(row=>row.pid).includes(pid),true);
41
+ await new Promise(r=>setTimeout(r,600));assert.equal(alive(pid),true,'guard must not stop a fixture while its owner lives');
42
+ owner.kill('SIGKILL');
43
+ assert.equal(await until(()=>!alive(pid)),true,`guarded fixture ${pid} outlived its owner`);
44
+ });
45
+
46
+ test('a guarded fixture stops at its lifetime ceiling while the owner lives',{skip},async t=>{
47
+ const root=fixture(t),script=path.join(root,'hang.cjs');
48
+ fs.writeFileSync(script,guardFixtureSource(`#!${process.execPath}\n${hang}`,{maxLifetimeMs:300}),{mode:0o700});
49
+ assert(fs.readFileSync(script,'utf8').startsWith(`#!${process.execPath}\n;(()=>{`));
50
+ const child=spawn(script,[],{stdio:'ignore'});
51
+ const closed=await new Promise(resolve=>child.once('close',(code,signal)=>resolve({code,signal})));
52
+ assert.deepEqual(closed,{code:null,signal:'SIGKILL'});
53
+ assert.throws(()=>ownerGuardSource({maxLifetimeMs:0}),/invalid_owner_guard/);
54
+ });
55
+
56
+ test('killFixtureProcesses removes a marked detached leader and its unmarked TERM-resistant descendant',{skip},async t=>{
57
+ const root=fixture(t),script=path.join(root,'leader.cjs');
58
+ fs.writeFileSync(script,`const c=require('node:child_process').spawn(process.execPath,['-e',${JSON.stringify(hang)}],{stdio:'ignore'});
59
+ process.stdout.write(c.pid+'\\n');${hang}`);
60
+ const leader=spawn(process.execPath,[script],{detached:true,stdio:['ignore','pipe','ignore']});
61
+ const descendant=await readPid(leader);
62
+ assert.equal(fixtureProcesses(root).some(row=>row.pid===descendant),false,'descendant carries no marker');
63
+ const killed=killFixtureProcesses(root);
64
+ assert.deepEqual(killed.map(row=>row.pid),[leader.pid]);
65
+ assert.equal(await until(()=>!alive(descendant)),true,'group kill must reach the descendant');
66
+ assert.deepEqual(fixtureProcesses(root),[]);
67
+ assert.throws(()=>fixtureProcesses('/tmp'),/invalid_fixture_marker/);
68
+ assert.throws(()=>fixtureProcesses('relative/fixture-root'),/invalid_fixture_marker/);
69
+ });
70
+
71
+ test('an unrelated process that merely names the fixture root survives, as does this test group',{skip},async t=>{
72
+ const root=fixture(t),log=path.join(root,'fixture.log');fs.writeFileSync(log,'');
73
+ // Double-fork via sh so these are no descendants of this test, like a user's
74
+ // own tail/grep of a fixture path or a node one-liner with the path as an argument.
75
+ const detach=command=>new Promise((resolve,reject)=>{
76
+ const sh=spawn('/bin/sh',['-c',`${command} >/dev/null 2>&1 </dev/null & echo $!`],{stdio:['ignore','pipe','ignore']});
77
+ let out='';sh.stdout.on('data',b=>out+=b);sh.once('error',reject);sh.once('close',()=>resolve(Number(out.trim())));
78
+ });
79
+ const q=value=>`'${value}'`;
80
+ const unrelated=[await detach(`/usr/bin/tail -f ${q(log)}`),
81
+ await detach(`${q(process.execPath)} -e ${q('setTimeout(()=>{},30000)')} ${q(log)}`)];
82
+ try{
83
+ for(const pid of unrelated)assert(Number.isSafeInteger(pid)&&alive(pid));
84
+ assert.equal(await until(()=>unrelated.every(pid=>fixtureProcesses(root).every(row=>row.pid!==pid)&&
85
+ spawnSync('ps',['-o','ppid=','-p',String(pid)],{encoding:'utf8'}).stdout.trim()==='1')),true);
86
+ assert.deepEqual(killFixtureProcesses(root),[]);
87
+ await new Promise(r=>setTimeout(r,300));
88
+ for(const pid of unrelated)assert.equal(alive(pid),true,`unrelated process ${pid} was killed`);
89
+ // A descendant of this test that carries the root is still taken, without touching this test's group.
90
+ const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)',log],{stdio:'ignore'});
91
+ await until(()=>fixtureProcesses(root).some(row=>row.pid===child.pid));
92
+ assert.deepEqual(killFixtureProcesses(root).map(row=>row.pid),[child.pid]);
93
+ assert.equal(alive(process.pid),true);
94
+ }finally{for(const pid of unrelated)try{process.kill(pid,'SIGKILL');}catch{}}
95
+ });
@@ -8,9 +8,12 @@ import {captureReviewBaseline} from '../runtime/js/cm-ai/review-package.mjs';
8
8
  import {createHostHandoff} from '../runtime/js/cm-ai/host-handoff.mjs';
9
9
  import {loadHandoff,checkN4,checkN5} from './cm-task-gate.mjs';
10
10
  import {developerArgs} from '../runtime/js/cm-ai/worker-codex-developer.mjs';
11
+ import {ownerGuardSource} from './fixtures/process-cleanup.mjs';
11
12
  const identity={repositoryId:'test',runId:'run',taskId:'T-001',attempt:1};
12
13
  const control=()=>({signal:new AbortController().signal});
13
14
  const command=(id,code)=>({id,command:[process.execPath,'-e',code]});
15
+ // Hung checks die with this test process even if the host check never reaps them.
16
+ const hung=(id,code)=>command(id,ownerGuardSource()+code);
14
17
  async function fixture(fn){const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-')));
15
18
  try{await fn(root);}finally{fs.rmSync(root,{recursive:true,force:true});}}
16
19
 
@@ -37,7 +40,7 @@ test('host check evidence excludes credentials paths and timing output',()=>fixt
37
40
  }));
38
41
 
39
42
  test('async output capture rejects safely and waits for process cleanup',()=>fixture(async cwd=>{
40
- const check=createHostCheck({cwd,commands:[command('capture',
43
+ const check=createHostCheck({cwd,commands:[hung('capture',
41
44
  "require('node:fs').writeFileSync('pid',String(process.pid));process.on('SIGTERM',()=>{});console.log('fixture');setInterval(()=>{},1000)")],
42
45
  timeoutMs:3000,onOutput:async()=>{throw Error('synthetic capture failure');}});
43
46
  const [result]=await check({identity},control());
@@ -78,7 +81,7 @@ for(const scenario of [
78
81
  const baseline=captureReviewBaseline({root:cwd,identity,scope:['app.txt'],requirements:['requirements.md']});
79
82
  fs.writeFileSync(path.join(cwd,'app.txt'),'after');
80
83
  const security=scenario.name==='missing-tool'?{id:'security',command:[path.join(temp,'absent-scanner')]}:
81
- command('security',scenario.name==='timeout'?'setInterval(()=>{},1000)':
84
+ (scenario.name==='timeout'?hung:command)('security',scenario.name==='timeout'?'setInterval(()=>{},1000)':
82
85
  // Misleading success text must never override a nonzero exit code.
83
86
  `console.log('PASS synthetic private scanner output');process.exit(${scenario.code})`);
84
87
  const check=createHostCheck({cwd,timeoutMs:scenario.name==='timeout'?1000:5000,
@@ -128,7 +131,7 @@ test('native Codex profile allows business writes but protects specs for project
128
131
  assert.equal(fs.readFileSync(path.join(cwd,'business.txt'),'utf8'),'allowed');
129
132
  }));
130
133
  test('cancelled check dispatches nothing and hung check is unavailable',()=>fixture(async cwd=>{
131
- const check=createHostCheck({cwd,timeoutMs:50,commands:[command('hang','setInterval(()=>{},1000)')]});
134
+ const check=createHostCheck({cwd,timeoutMs:50,commands:[hung('hang','setInterval(()=>{},1000)')]});
132
135
  const ac=new AbortController();ac.abort();await assert.rejects(check({identity},{signal:ac.signal}),{code:'cancelled'});
133
136
  const results=await check({identity},control());assert.equal(results[0].outcome,'unavailable');
134
137
  assert.equal(results[0].evidence,'host check: timeout');
@@ -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
+ });