@aibyzero/cm-workflow 0.13.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +28 -2
  4. package/VERSION +1 -1
  5. package/docs/installation.md +18 -3
  6. package/docs/js-workflow-control.md +2 -0
  7. package/docs/user-guide.md +16 -0
  8. package/install.ps1 +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +1 -0
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +53 -22
  12. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +4 -5
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +40 -17
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +103 -23
  15. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -4
  16. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +5 -2
  17. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  18. package/runtime/js/cm-ai/developer-adapter.mjs +17 -5
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +7 -2
  20. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  21. package/runtime/js/cm-ai/execution-store.mjs +25 -5
  22. package/runtime/js/cm-ai/host-check.mjs +20 -1
  23. package/runtime/js/cm-ai/host-conversation-execution.mjs +5 -4
  24. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  25. package/runtime/js/cm-ai/host-qa-executor.mjs +43 -21
  26. package/runtime/js/cm-ai/host-qa-policy.mjs +3 -1
  27. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +41 -3
  28. package/runtime/js/cm-ai/task-runner.mjs +1 -0
  29. package/runtime/js/cm-ai/worker-claude-developer.mjs +2 -1
  30. package/runtime/js/cm-fix/cause-package.mjs +3 -1
  31. package/runtime/js/cm-fix/dossier.mjs +7 -2
  32. package/runtime/js/cm-fix/reproduce.mjs +26 -5
  33. package/runtime/js/cm-init/draft-generation.mjs +3 -2
  34. package/runtime/js/cm-init/draft-inspection.mjs +17 -3
  35. package/runtime/js/cm-init/review-evidence.mjs +1 -1
  36. package/runtime/js/cm-prd/summary.mjs +6 -8
  37. package/runtime/js/cm-security/finalize.mjs +164 -0
  38. package/runtime/js/specs-status.mjs +66 -0
  39. package/scripts/cm-ai-admission.mjs +46 -7
  40. package/scripts/cm-ai-admission.test.mjs +50 -0
  41. package/scripts/cm-ai-batch-host.mjs +72 -10
  42. package/scripts/cm-ai-batch-host.test.mjs +128 -4
  43. package/scripts/cm-ai-batch-run.mjs +351 -17
  44. package/scripts/cm-ai-batch-run.test.mjs +190 -13
  45. package/scripts/cm-ai-bootstrap.test.mjs +10 -3
  46. package/scripts/cm-ai-host.mjs +38 -21
  47. package/scripts/cm-ai-host.test.mjs +75 -5
  48. package/scripts/cm-ai-multi-root.test.mjs +7 -1
  49. package/scripts/cm-ai-nested-execution.test.mjs +8 -2
  50. package/scripts/cm-ai-run.mjs +25 -15
  51. package/scripts/cm-ai-run.test.mjs +48 -0
  52. package/scripts/cm-blocked-reason.test.mjs +104 -0
  53. package/scripts/cm-capability-gate.test.mjs +179 -0
  54. package/scripts/cm-check-host.test.mjs +7 -1
  55. package/scripts/cm-codex-developer-adapter.test.mjs +70 -0
  56. package/scripts/cm-fix-cause-package.test.mjs +18 -1
  57. package/scripts/cm-fix-execution.test.mjs +31 -0
  58. package/scripts/cm-fix-host-review.test.mjs +9 -2
  59. package/scripts/cm-fix-host.test.mjs +2 -1
  60. package/scripts/cm-fix-observation-dossier.test.mjs +2 -0
  61. package/scripts/cm-fix-qa-source.test.mjs +1 -3
  62. package/scripts/cm-fix-reproduce.test.mjs +53 -2
  63. package/scripts/cm-fix-review-recovery.test.mjs +4 -3
  64. package/scripts/cm-host-check.test.mjs +22 -0
  65. package/scripts/cm-host-qa-executor.test.mjs +302 -3
  66. package/scripts/cm-host-qa-policy.test.mjs +34 -0
  67. package/scripts/cm-init-draft-generation.test.mjs +24 -3
  68. package/scripts/cm-init-draft-inspection.test.mjs +80 -0
  69. package/scripts/cm-init-host.mjs +2 -2
  70. package/scripts/cm-init-host.test.mjs +3 -1
  71. package/scripts/cm-init-session.test.mjs +37 -0
  72. package/scripts/cm-log-event.mjs +28 -7
  73. package/scripts/cm-prd-completion.test.mjs +7 -1
  74. package/scripts/cm-prd-design-phase.test.mjs +2 -1
  75. package/scripts/cm-prd-host.test.mjs +3 -2
  76. package/scripts/cm-prd-session-recovery.test.mjs +5 -4
  77. package/scripts/cm-runtime-i18n.mjs +32 -0
  78. package/scripts/cm-runtime-install.mjs +49 -23
  79. package/scripts/cm-runtime.mjs +45 -17
  80. package/scripts/cm-runtime.test.mjs +101 -0
  81. package/scripts/cm-security.mjs +12 -4
  82. package/scripts/cm-security.test.mjs +109 -0
  83. package/scripts/cm-specs-status.test.mjs +130 -0
  84. package/scripts/cm-workflow-config.mjs +4 -0
  85. package/scripts/test-shell-compat.sh +0 -0
  86. package/skills/cm-ai/references/N1-init.md +20 -15
  87. package/skills/cm-ai/references/N6-qa-eval.md +9 -4
  88. package/skills/cm-ai/references/js-host.md +10 -0
  89. package/skills/cm-fix/SKILL.md +5 -4
  90. package/skills/cm-fix/references/js-host.md +13 -0
  91. package/skills/cm-idea/SKILL.md +2 -0
  92. package/skills/cm-init/references/runtime-declaration.md +2 -0
  93. package/skills/cm-prd/SKILL.md +9 -8
  94. package/skills/cm-prd/references/spec-self-check.md +1 -0
  95. package/skills/cm-runtime/SKILL.md +23 -2
  96. package/skills/cm-security/SKILL.md +11 -6
  97. package/skills/cm-security/references/scan-contract.md +45 -1
@@ -5,9 +5,10 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
7
7
  import {readReviewSourceFiles} from '../runtime/js/cm-ai/review-package.mjs';
8
- import {requestFor} from '../runtime/js/cm-ai/effect-contract.mjs';
8
+ import {requestFor,digest} from '../runtime/js/cm-ai/effect-contract.mjs';
9
9
  import {buildCauseReviewPrompt,buildReviewPrompt} from '../runtime/js/cm-ai/codex-review-adapter.mjs';
10
10
  import {inspectProviderCauseReview,inspectProviderReview} from '../runtime/js/cm-ai/provider-review-observation.mjs';
11
+ import {readFixCausePackage} from '../runtime/js/cm-fix/cause-package.mjs';
11
12
  import {inspectFixInvestigation} from '../runtime/js/cm-fix/investigation.mjs';
12
13
 
13
14
  test('cause package binds only selected current source and never advances the fix',async()=>{
@@ -32,6 +33,22 @@ test('cause package binds only selected current source and never advances the fi
32
33
  assert.equal((await owner.advance({authorized:true})).stage,'cause_review_required');
33
34
  const first=owner.causeReviewPackage();assert.equal(first.files.length,1);
34
35
  assert.deepEqual(first.diagnosis.investigation,investigation);
36
+ const withReproduction=reproduction=>{const {packageDigest,...body}=first;
37
+ const value={...body,reproduction};return {...value,packageDigest:digest(value)};};
38
+ const visual={status:'reproduced',next:'diagnose',observation:{kind:'visual',phase:'before',
39
+ carrier:{path:path.join(root,'before.png'),sha256:'a'.repeat(64),kind:'screenshot',description:'Synthetic carrier metadata'},
40
+ environment:{scope:'local',kind:'web',carrier:'browser',target:'fixture'},reason:'Synthetic visual fixture'},
41
+ attempts:[{scenario:'Inspect fixture',dimension:'按描述',outcome:'reproduced'}]};
42
+ for(const reproduction of [first.reproduction,visual]){
43
+ assert.equal(readFixCausePackage(withReproduction(reproduction)).reproduction.attempts.at(-1).outcome,'reproduced');
44
+ const {attempts,...legacy}=reproduction;
45
+ assert.deepEqual(readFixCausePackage(withReproduction(legacy)).reproduction,legacy);
46
+ for(const outcome of ['not_reproduced','unsupported','invalid']){
47
+ const attempt={...attempts[0],outcome};
48
+ assert.throws(()=>readFixCausePackage(withReproduction({...legacy,attempts:[attempt]})),
49
+ {code:outcome==='invalid'?'invalid_fix_reproduction_attempts':'fix_reproduction_attempts_mismatch'});
50
+ }
51
+ }
35
52
  assert.equal(Buffer.from(first.files[0].contentBase64,'base64').toString(),'export const value=1;');
36
53
  assert.equal(JSON.stringify(first).includes('SYNTHETIC_NOT_FOR_PACKAGE'),false);
37
54
  for(const provider of ['codex','claude']){
@@ -4,6 +4,8 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
7
+ import {createFixReproduction} from '../runtime/js/cm-fix/reproduce.mjs';
8
+ import {startFixRun} from '../runtime/js/cm-fix/start.mjs';
7
9
  import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
8
10
  import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
9
11
  const identity={repositoryId:'fix-fixture',runId:'fix-demo',taskId:'T-FIX-demo',attempt:1};
@@ -61,3 +63,32 @@ test('cancel remains durable and changed host configuration cannot reopen',()=>f
61
63
  try{assert.equal((await owner.advance({authorized:true})).stage,'cancelled');}
62
64
  finally{owner.close();}
63
65
  }));
66
+
67
+ test('legacy observation without attempts can publish, finish and resume without rewriting its archive',()=>fixture(async(options,cwd)=>{
68
+ options.configuration.reproduction.command=[process.execPath,'-e',"require('node:fs').appendFileSync('visits','1')"];
69
+ let owner=openFixExecution(options);owner.close();
70
+ // The old producer's exact shape, backed by a real command observation.
71
+ const run=createFixReproduction(options.configuration.reproduction);
72
+ const {attempts,...legacy}=await run({identity},{signal:new AbortController().signal,authorized:true});
73
+ assert.equal(legacy.status,'not_reproduced');
74
+ const state=JSON.parse(fs.readFileSync(path.join(options.specsRoot,'.reviews','.execution',identity.runId,'state.json')));
75
+ const store=openExecutionStore({specsRoot:options.specsRoot,identity:state.identity,fingerprints:state.fingerprints,create:false});
76
+ try{
77
+ store.append({id:'fix-reproduce-intent',kind:'intent',payload:{stage:'reproduce'},expectedRevision:store.snapshot().revision});
78
+ store.append({id:'fix-reproduce-result',kind:'result',payload:{stage:'reproduce',value:legacy},expectedRevision:store.snapshot().revision});
79
+ }finally{store.close();}
80
+ owner=openFixExecution({...options,create:false});
81
+ try{
82
+ assert.equal(owner.status().stage,'observation');assert.equal(owner.status().reproduction.attempts,undefined);
83
+ const published=owner.publishDossier(),bytes=fs.readFileSync(published.dossier.path);
84
+ assert.doesNotMatch(bytes.toString(),/复现尝试/);
85
+ startFixRun(options);
86
+ assert.equal(owner.finish({authorized:true}).observationRunEnded,true);
87
+ owner.close();owner=openFixExecution({...options,create:false});
88
+ assert.deepEqual(fs.readFileSync(owner.publishDossier().dossier.path),bytes);
89
+ fs.writeFileSync(path.join(options.specsRoot,'failure.txt'),'Observed new failure evidence');
90
+ assert.equal(owner.resume({authorized:true,evidenceFiles:['failure.txt']}).stage,'observation_resume_prepared');
91
+ assert.deepEqual(fs.readFileSync(published.dossier.path),bytes);
92
+ assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'1');
93
+ }finally{owner.close();}
94
+ }));
@@ -1,4 +1,4 @@
1
- import test from 'node:test';
1
+ import test,{after} from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
3
  import fs from 'node:fs';
4
4
  import os from 'node:os';
@@ -11,6 +11,13 @@ import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
11
11
  import {checkN4} from './cm-task-gate.mjs';
12
12
  import {fixCompletionProjection} from '../runtime/js/cm-fix/finish.mjs';
13
13
  import {loadConfig,resolveRole} from './cm-workflow-config.mjs';
14
+ const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
15
+
16
+ // Keep runtime declarations and log mirrors independent of the invoking user's home.
17
+ const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-host-review-home-'));
18
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
19
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
20
+ after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
14
21
 
15
22
  for(const runtime of ['codex','claude']){
16
23
  test(`${runtime} CLI cause review requires opt-in and matching diagnostic, then resumes without dispatch`,async()=>{
@@ -81,7 +88,7 @@ test(`${runtime} CLI cause review requires opt-in and matching diagnostic, then
81
88
  }finally{fs.rmSync(root,{recursive:true,force:true});}
82
89
  });
83
90
 
84
- test(`${runtime} CLI stages independently authorize writes and synthetic final review, then resume without redispatch`,{timeout:15000},async()=>{
91
+ test(`${runtime} CLI stages independently authorize writes and synthetic final review, then resume without redispatch`,{timeout:FIXTURE_TIMEOUT_MS},async()=>{
85
92
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-host-author-')));
86
93
  const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
87
94
  fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
@@ -6,6 +6,7 @@ import path from 'node:path';
6
6
  import {PassThrough,Writable} from 'node:stream';
7
7
  import {main} from './cm-fix-host.mjs';
8
8
  import {startFixRun} from '../runtime/js/cm-fix/start.mjs';
9
+ const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
9
10
 
10
11
  test('fix CLI requires launch authorization and uses duplex diagnosis, resume and original store',async()=>{
11
12
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-cli-')));
@@ -64,7 +65,7 @@ test('fix CLI requires launch authorization and uses duplex diagnosis, resume an
64
65
  }finally{fs.rmSync(root,{recursive:true,force:true});}
65
66
  });
66
67
 
67
- test('fix CLI red and baseline flags authorize separate real commands across resume',{timeout:15000},async()=>{
68
+ test('fix CLI red and baseline flags authorize separate real commands across resume',{timeout:FIXTURE_TIMEOUT_MS},async()=>{
68
69
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-cli-checks-')));
69
70
  const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
70
71
  fs.writeFileSync(path.join(cwd,'red.mjs'),"import fs from 'node:fs';fs.appendFileSync('red-calls','1');console.error('BUG');process.exit(1)");
@@ -234,6 +234,8 @@ test(`observation recovery: ${mode}`,async()=>{
234
234
  assert.equal((fs.statSync(archived.dossier.path).mode&0o777),0o600);
235
235
  assert.match(bytes.toString(),/观测中/);assert.match(bytes.toString(),/not_reproduced/);assert.match(bytes.toString(),/等待证据/);
236
236
  assert.equal(archived.diagnosis,null);
237
+ assert.match(bytes.toString(),/## 复现尝试/);
238
+ assert.equal(archived.reproduction.attempts.at(-1).outcome,'not_reproduced');
237
239
  owner.close();owner=openFixExecution({...options,create:false});assert.deepEqual(owner.publishDossier(),archived);
238
240
  await owner.advance({authorized:true});assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'1');
239
241
  assert.throws(()=>owner.finish(),{code:'fix_finish_authorization_required'});
@@ -15,7 +15,7 @@ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
15
15
  import {bindQaFixDefinition} from '../runtime/js/cm-ai/qa-fix-definition.mjs';
16
16
 
17
17
  for(const mode of ['normal','diagnosis drift','parent dispatch','parent cancel','parent observation'])
18
- test(`QA child uses original owner lock, bound failure and explicit CLI authority: ${mode}`,async()=>{
18
+ test(`QA child owns its run lock, bound failure and explicit CLI authority: ${mode}`,async()=>{
19
19
  const drift=mode==='diagnosis drift';
20
20
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-qa-source-')));
21
21
  const specsRoot=path.join(root,'specs'),cwd=path.join(root,'code'),logHome=path.join(root,'logs');
@@ -62,8 +62,6 @@ test(`QA child uses original owner lock, bound failure and explicit CLI authorit
62
62
  assert.throws(()=>openFixExecution({...options,identity:{...identity,runId:'replacement'}}),{code:'fix_qa_identity_mismatch'});
63
63
  parentOwner=openExecutionStore({specsRoot,identity:{repositoryId:parent.repositoryId,runId:parent.runId},create:true,
64
64
  fingerprints:{workflow:'a'.repeat(64),config:'b'.repeat(64),inputs:'c'.repeat(64)}});
65
- assert.throws(()=>openFixExecution(options));
66
- assert.equal(fs.existsSync(path.join(specsRoot,'.reviews','.execution',identity.runId)),false);
67
65
  parentOwner.close();parentOwner=null;
68
66
  const file=path.join(root,'fix.json');
69
67
  const {hostContextId,...data}=configuration;fs.writeFileSync(file,JSON.stringify({specsRoot,identity,...data}));
@@ -3,7 +3,9 @@ import assert from 'node:assert/strict';
3
3
  import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
- import {createFixReproduction} from '../runtime/js/cm-fix/reproduce.mjs';
6
+ import {createFixReproduction,inspectFixReproduction} from '../runtime/js/cm-fix/reproduce.mjs';
7
+
8
+ import {publishFixObservationDossier} from '../runtime/js/cm-fix/dossier.mjs';
7
9
 
8
10
  const identity={repositoryId:'fix-test',runId:'fix-run',taskId:'T-FIX-demo',attempt:1};
9
11
  test('actual reproduction requires authorized command plus matching exit and defect signature',async()=>{
@@ -21,11 +23,60 @@ test('actual reproduction requires authorized command plus matching exit and def
21
23
  const signal=new AbortController().signal;
22
24
  await assert.rejects(run({identity},{signal,authorized:false}),{code:'reproduction_authorization_required'});
23
25
  const result=await run({identity},{signal,authorized:true});assert.equal(result.status,expected);
26
+ assert.equal(result.attempts.length,1);assert.equal(result.attempts[0].outcome,expected);
27
+ assert.deepEqual(inspectFixReproduction(result,{command:[process.execPath,'-e',source],expectedFailure:{exitCode:3}}),result);
24
28
  assert(!result.observation.evidence.includes('BUG:'));
25
29
  await assert.rejects(run({identity},{signal,authorized:true}),{code:'reproduction_already_attempted'});
26
30
  }
27
31
  const missing=createFixReproduction({cwd,command:[path.join(cwd,'missing-command')],
28
32
  expectedFailure:{exitCode:3,outputIncludes:'BUG:'},timeoutMs:1000});
29
- assert.equal((await missing({identity},{signal:new AbortController().signal,authorized:true})).status,'blocked');
33
+ const unavailable=await missing({identity},{signal:new AbortController().signal,authorized:true});
34
+ assert.equal(unavailable.status,'blocked');assert.equal(unavailable.attempts[0].outcome,'unsupported');
30
35
  }finally{fs.rmSync(cwd,{recursive:true,force:true});}
31
36
  });
37
+
38
+ const config={command:['fixture'],expectedFailure:{exitCode:3}};
39
+ function result(status='reproduced'){
40
+ return {status,next:status==='reproduced'?'diagnose':status==='blocked'?'resolve_execution':'observation',
41
+ observation:{id:'reproduce',command:config.command,outcome:status==='blocked'?'unavailable':status==='reproduced'?'failed':'passed',
42
+ exitCode:status==='blocked'?null:status==='reproduced'?3:0,evidence:'fixture evidence',signatureMatched:status==='reproduced'}};
43
+ }
44
+ const attempt=outcome=>({scenario:'empty input',dimension:'input',outcome});
45
+ test('legacy reproduction records without attempts remain readable for all outcomes',()=>{
46
+ for(const status of ['reproduced','not_reproduced','blocked']){
47
+ const legacy=result(status);assert.deepEqual(inspectFixReproduction(legacy,config),legacy);
48
+ }
49
+ assert.deepEqual(inspectFixReproduction({...result(),attempts:[]},config).attempts,[]);
50
+ });
51
+ test('observation requires at least one attempt; strict live validation also rejects missing attempts',()=>{
52
+ assert.throws(()=>inspectFixReproduction({...result('not_reproduced'),attempts:[]},config),{code:'fix_reproduction_attempts_required'});
53
+ assert.throws(()=>inspectFixReproduction(result('not_reproduced'),config,{requireAttempts:true}),{code:'fix_reproduction_attempts_required'});
54
+ assert.equal(inspectFixReproduction({...result('not_reproduced'),attempts:[attempt('not_reproduced')]},config).next,'observation');
55
+ });
56
+ test('last attempt must match the evidence-backed overall conclusion',()=>{
57
+ for(const [status,outcome] of [['reproduced','reproduced'],['not_reproduced','not_reproduced'],['blocked','unsupported']]){
58
+ const value={...result(status),attempts:[attempt('not_reproduced'),attempt(outcome)]};
59
+ assert.deepEqual(inspectFixReproduction(value,config),value);
60
+ for(const other of ['reproduced','not_reproduced','unsupported'].filter(item=>item!==outcome)){
61
+ assert.throws(()=>inspectFixReproduction({...value,attempts:[attempt(other)]},config),{code:'fix_reproduction_attempts_mismatch'});
62
+ }
63
+ }
64
+ assert.throws(()=>inspectFixReproduction({...result('not_reproduced'),status:'reproduced',next:'diagnose',attempts:[attempt('reproduced')]},config),{code:'reproduction_mismatch'});
65
+ });
66
+ test('attempts reject invalid outcomes and malformed scenario records',()=>{
67
+ for(const outcome of ['passed','failed','',null,1]){
68
+ assert.throws(()=>inspectFixReproduction({...result(),attempts:[attempt(outcome)]},config),{code:'invalid_fix_reproduction_attempts'});
69
+ }
70
+ for(const attempts of [null,{},[null],[{...attempt('reproduced'),scenario:''}],[{...attempt('reproduced'),dimension:''}],[{scenario:'x',dimension:'input'}]]){
71
+ assert.throws(()=>inspectFixReproduction({...result(),attempts},config));
72
+ }
73
+ });
74
+
75
+ test('observation dossier rejects empty attempts, including diagnosis needing evidence',()=>{
76
+ for(const status of ['reproduced','not_reproduced']){
77
+ const reproduction={...result(status),attempts:[]};
78
+ assert.throws(()=>publishFixObservationDossier({configuration:{reproduction:config},
79
+ status:{stage:'observation',completionEligible:false,reproduction,diagnosis:{status:'needs_evidence'}}}),
80
+ {code:'fix_reproduction_attempts_required'});
81
+ }
82
+ });
@@ -10,6 +10,7 @@ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
10
10
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
11
11
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
12
12
  import {main} from './cm-fix-host.mjs';
13
+ const FIXTURE_TIMEOUT_MS=Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000);
13
14
 
14
15
  // Real temporary files/commands/owner/CLI; model responses and diagnostics are
15
16
  // synthetic. No live provider, XBrief writes, installation or Git operations.
@@ -81,7 +82,7 @@ async function fixture(t,mode){
81
82
  }
82
83
  const op=operation=>({requestId:operation,operation});
83
84
 
84
- test('revision refuses lost earlier thread before persisting started, keeping replay valid',{timeout:15000},async t=>{
85
+ test('revision refuses lost earlier thread before persisting started, keeping replay valid',{timeout:FIXTURE_TIMEOUT_MS},async t=>{
85
86
  const f=await fixture(t,'revision-reuses-lost-thread');
86
87
  const recovered=await f.cli([f.request,op('final_review'),op('publish_review')],['--allow-final-review-recovery','--allow-final-review']);
87
88
  assert.equal(recovered.at(-1).result.stage,'final_review_changes_requested');
@@ -97,7 +98,7 @@ test('revision refuses lost earlier thread before persisting started, keeping re
97
98
  assert.equal(f.reopen().status().stage,'unknown');assert.equal(f.calls(),3);
98
99
  });
99
100
 
100
- for(const mode of ['twice-then-success','reuse-first-thread','loss-again'])test(`fresh invocation-bound continuation: ${mode}`,{timeout:15000},async t=>{
101
+ for(const mode of ['twice-then-success','reuse-first-thread','loss-again'])test(`fresh invocation-bound continuation: ${mode}`,{timeout:FIXTURE_TIMEOUT_MS},async t=>{
101
102
  const f=await fixture(t,mode);
102
103
  await f.cli([f.request,op('final_review')],['--allow-final-review','--allow-final-review-recovery']);
103
104
  assert.equal(f.calls(),2);
@@ -144,7 +145,7 @@ for(const mode of ['twice-then-success','reuse-first-thread','loss-again'])test(
144
145
  assert.equal(f.reopen().status().stage,'completed');assert.equal(f.calls(),3);
145
146
  });
146
147
 
147
- test('one authorized CLI continuation preserves old history and reaches the original finish',{timeout:15000},async t=>{
148
+ test('one authorized CLI continuation preserves old history and reaches the original finish',{timeout:FIXTURE_TIMEOUT_MS},async t=>{
148
149
  const f=await fixture(t,'success');assert.equal(f.owner().status().stage,'unknown');
149
150
  assert.equal((await f.owner().reviewFinal()).stage,'unknown');assert.equal(f.calls(),1);
150
151
  const denied=await f.cli([f.request]);assert.equal(denied[0].error.code,'host_request_failed');
@@ -14,6 +14,28 @@ const command=(id,code)=>({id,command:[process.execPath,'-e',code]});
14
14
  async function fixture(fn){const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-')));
15
15
  try{await fn(root);}finally{fs.rmSync(root,{recursive:true,force:true});}}
16
16
 
17
+ test('host check evidence retains bounded deterministic test counts',()=>fixture(async cwd=>{
18
+ for(const [output,expected] of [
19
+ ['ℹ tests 20\nℹ pass 20\nℹ fail 0\n',' (tests 20, pass 20, fail 0)'],
20
+ [' ℹ TESTS: 20\r\n tests=99\nPASS = 20\nfail 0',' (tests 20, pass 20, fail 0)'],
21
+ ['tests 1\nsuites 2\npass 3\npassed 4\npassing 5\nfail 6\nfailed 7\nfailing 8\nskipped 9\ntodo 10',
22
+ ' (tests 1, suites 2, pass 3, passed 4, passing 5, fail 6, failed 7, failing 8)'],
23
+ [`tests 20\npass ${'9'.repeat(180)}\nfail 0`,' (tests 20)'],
24
+ ]){
25
+ const check=createHostCheck({cwd,commands:[command('counts',`process.stdout.write(${JSON.stringify(output)})`)]});
26
+ const [result]=await check({identity},control());
27
+ assert.equal(result.outcome,'passed');assert.equal(result.evidence,`host check exited 0${expected}`);
28
+ assert(result.evidence.length<=200);
29
+ }
30
+ }));
31
+
32
+ test('host check evidence excludes credentials paths and timing output',()=>fixture(async cwd=>{
33
+ const output='token: abc123\nduration_ms 155.8\nat /srv/app/secret.js:12\ntests 20 token: abc123\npass 20.5\n';
34
+ const check=createHostCheck({cwd,commands:[command('private',`process.stderr.write(${JSON.stringify(output)})`)]});
35
+ const [result]=await check({identity},control());
36
+ assert.equal(result.outcome,'passed');assert.equal(result.evidence,'host check exited 0');
37
+ }));
38
+
17
39
  test('async output capture rejects safely and waits for process cleanup',()=>fixture(async cwd=>{
18
40
  const check=createHostCheck({cwd,commands:[command('capture',
19
41
  "require('node:fs').writeFileSync('pid',String(process.pid));process.on('SIGTERM',()=>{});console.log('fixture');setInterval(()=>{},1000)")],
@@ -39,8 +39,9 @@ function fixture() {
39
39
  }
40
40
 
41
41
  function begin(f,executor) {
42
+ if(executor.prepare)executor={...executor,...executor.prepare()};
42
43
  const input={...f.binding,mode:executor.mode,caseCount:executor.caseCount};
43
- recordCmAiQaRun({...input,phase:'start',logHome:f.configuration.logHome});
44
+ recordCmAiQaRun({...input,phase:'start',deferredCases:executor.configuration.plan.deferred_cases,logHome:f.configuration.logHome});
44
45
  return input;
45
46
  }
46
47
 
@@ -173,7 +174,8 @@ test('host QA runs a declared command, retains blocking disabled modes and archi
173
174
  assert.equal(rows.filter(row=>row.event==='resource'&&row.phase==='acquired').length,1);
174
175
  assert.equal(rows.filter(row=>row.event==='resource'&&row.phase==='released').length,1);
175
176
  const status=JSON.parse(fs.readFileSync(path.join(input.specsDir,'.cm-status.json'),'utf8'));
176
- assert.equal(status.node,'N6');assert(status.detail.includes('TC-002: case_complete'));
177
+ assert.equal(status.node,'N6');assert.equal(status.state,'qa_passed');
178
+ assert.equal(status.detail,'QA 结果 PASS(通过 3 / 失败 0 / 阻断 0)');
177
179
  }finally{f.cleanup();}
178
180
  });
179
181
 
@@ -340,7 +342,7 @@ test('same-round successors require bound abandonment; repaired FAIL rounds stil
340
342
  if(variant==='wrong-id')rows[index].previous_test_run_id='wrong';
341
343
  if(variant==='duplicate')rows.splice(index,0,rows[index]);
342
344
  if(variant==='reset')rows.at(-1).attempt=2;
343
- if(variant==='changed-mode')rows.at(-1).mode='browser';
345
+ if(variant==='changed-mode'){rows.at(-1).mode='browser';delete rows.at(-1).previous_test_run_id;}
344
346
  fs.writeFileSync(log,rows.map(row=>JSON.stringify(row)).join('\n')+'\n');
345
347
  assert.throws(()=>readCmAiQaRunRound({...query,testRunId:'retry-1'}),undefined,variant);
346
348
  }
@@ -431,3 +433,300 @@ test(`partial PASS recovery reruns the full real executor plan; abandoned crash=
431
433
  }
432
434
  }finally{f.cleanup();}
433
435
  });
436
+
437
+ function plannedExecutor(options) {
438
+ const executor=createHostQaExecutor(options);
439
+ return {...executor,...executor.prepare()};
440
+ }
441
+
442
+ function midFeature(f,{complete=false,empty=false}={}) {
443
+ const root=path.join(f.configuration.specsDir,f.configuration.feature);
444
+ fs.writeFileSync(path.join(root,'tasks.md'),Array.from({length:4},(_,i)=>
445
+ `- [${complete||i===0?'x':' '}] T-00${i+1}: fixture`).join('\n')+'\n');
446
+ const contract=JSON.parse(fs.readFileSync(path.join(root,'test-cases.json')));
447
+ contract.cases=Array.from({length:9},(_,i)=>({...contract.cases[0],id:`TC-00${i+1}`,
448
+ kind:[0,1,7].includes(i)?'logic':'browser',blocking:true,
449
+ taskIds:i===7&&!empty?['T-001']:i===2?['T-003','T-004']:['T-001','T-002']}));
450
+ fs.writeFileSync(path.join(root,'test-cases.json'),JSON.stringify(contract));
451
+ f.configuration.commands=[{...f.configuration.commands[0],id:'npm-test',caseIds:['TC-008']},
452
+ {...f.configuration.commands[0],id:'deferred-test',caseIds:['TC-001','TC-002']}];
453
+ return contract;
454
+ }
455
+
456
+ for(const complete of [false,true])test(`step30 four tasks / nine cases; feature complete=${complete}`,async()=>{
457
+ const f=fixture();
458
+ try{
459
+ const contract=midFeature(f,{complete}),seen=[];
460
+ const executor=plannedExecutor({...f.configuration,
461
+ logic:async request=>{seen.push(request.case.id);return {verdict:'SUPPORTED',evidence:['Synthetic source check']};},
462
+ browser:async request=>{
463
+ seen.push(request.case.id);
464
+ const artifact=path.join(f.configuration.specsDir,'.reviews',`${request.case.id}.txt`);
465
+ fs.writeFileSync(artifact,'Synthetic browser observation');
466
+ return {verdict:'PASS',evidence:[artifact],environment:request.environment,cleanup:'completed'};
467
+ }});
468
+ const plan=executor.configuration.plan;
469
+ const selected=complete?contract.cases.map(item=>item.id):['TC-008'];
470
+ const deferred=complete?[]:contract.cases.filter(item=>item.id!=='TC-008')
471
+ .map(item=>({id:item.id,taskIds:item.taskIds.filter(taskId=>taskId!=='T-001')}));
472
+ assert.deepEqual(plan.cases.map(item=>item.id),selected);
473
+ assert.deepEqual(plan.deferred_cases,deferred);
474
+ assert.deepEqual(plan.commands.map(item=>item.id),complete?['npm-test','deferred-test']:['npm-test']);
475
+ assert.equal(executor.caseCount,complete?11:2);
476
+ const binding=begin(f,executor);
477
+ await assert.rejects(executor.run({...binding,caseCount:executor.caseCount+1},new AbortController().signal),{code:'qa_execution_mismatch'});
478
+ const result=await executor.run(binding,new AbortController().signal);
479
+ assert.equal(result.result,'PASS');assert.equal(result.passed,executor.caseCount);assert.equal(result.blocked,0);
480
+ assert.deepEqual(seen.sort(),selected);
481
+ const report=fs.readFileSync(result.report,'utf8');assert(report.includes(JSON.stringify(deferred,null,2)));
482
+ const rows=fs.readFileSync(path.join(f.configuration.specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
483
+ assert.deepEqual(rows.find(row=>row.phase==='start').deferred_cases,deferred);
484
+ assert(!rows.some(row=>deferred.some(item=>item.id===row.case_id)));
485
+ console.log('STEP30 selection',JSON.stringify({complete,selected,deferred,commands:plan.commands.map(item=>item.id),caseCount:executor.caseCount,result:result.result}));
486
+ }finally{f.cleanup();}
487
+ });
488
+
489
+ test('step30 no applicable case or command remains explicitly BLOCKED',async()=>{
490
+ const f=fixture();
491
+ try{
492
+ midFeature(f,{empty:true});
493
+ fs.writeFileSync(path.join(f.configuration.codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{tests:['logic']}}));
494
+ const executor=plannedExecutor({...f.configuration,logic:()=>assert.fail('no deferred host request'),
495
+ browser:()=>assert.fail('no deferred browser request')});
496
+ assert.equal(executor.configuration.plan.cases.length,0);assert.equal(executor.configuration.plan.commands.length,0);
497
+ assert.equal(executor.configuration.plan.deferred_cases.length,9);
498
+ const binding=begin(f,executor),result=await executor.run(binding,new AbortController().signal);
499
+ assert.equal(result.result,'BLOCKED');assert.equal(result.passed,0);assert.equal(result.blocked,1);
500
+ assert.match(fs.readFileSync(result.report,'utf8'),/no-applicable-cases/);
501
+ recordCmAiQaRun({...binding,phase:'complete',result,logHome:f.configuration.logHome});
502
+ const {codeProject,mode,caseCount,...query}=binding;
503
+ assert.equal(inspectCmAiQaResult(query).status,'blocked');
504
+ }finally{f.cleanup();}
505
+ });
506
+
507
+ for(const afterAbandonment of [false,true])test(`step30 resume old ten-item QA into fresh two-item plan; abandoned=${afterAbandonment}`,async()=>{
508
+ const {createCmAiConversationEntry}=await import('../runtime/js/cm-ai/cm-ai-conversation-entry.mjs');
509
+ const {readCmAiQaRunRound}=await import('../runtime/js/cm-ai/cm-ai-qa-log.mjs');
510
+ const {inspectRunClosure}=await import('./cm-log-event.mjs');
511
+ const f=fixture();
512
+ try{
513
+ midFeature(f);
514
+ const log=path.join(f.configuration.specsDir,'运行日志.jsonl');
515
+ const old={...f.binding,mode:'all',caseCount:10,logHome:f.configuration.logHome};
516
+ recordCmAiQaRun({...old,phase:'start'});
517
+ const rows=()=>fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse);
518
+ fs.appendFileSync(log,JSON.stringify({...rows().at(-1),phase:'case_start',case_id:'TC-003'})+'\n');
519
+ if(afterAbandonment)recordCmAiQaRun({...old,phase:'abandoned'});
520
+ const before=fs.readFileSync(log,'utf8'),seen=[];
521
+ // Host construction precedes N5. Its plan must be refreshed after completion.
522
+ const tasks=path.join(f.configuration.specsDir,f.configuration.feature,'tasks.md');
523
+ const completedTasks=fs.readFileSync(tasks,'utf8');fs.writeFileSync(tasks,completedTasks.replace('[x]','[ ]'));
524
+ const executor=plannedExecutor({...f.configuration,
525
+ logic:async request=>{seen.push(request.case.id);return {verdict:'SUPPORTED',evidence:['Synthetic static observation']};},
526
+ browser:()=>assert.fail('unfinished browser case must never dispatch')});
527
+ assert.equal(executor.configuration.plan.cases.length,0);
528
+ fs.writeFileSync(tasks,completedTasks);
529
+ const completed={state:'fixture_completed',code:null,identity:f.binding.identity,packageDigest:f.binding.packageDigest};
530
+ const entry=createCmAiConversationEntry({specsDir:f.binding.specsDir,codeProject:f.binding.codeProject,
531
+ feature:f.binding.feature,identity:f.binding.identity,runner:{status:()=>completed,
532
+ executeEffect:async()=>assert.fail('no developer/reviewer replay'),cancel:()=>completed,run:async()=>completed},
533
+ qaLogHome:f.configuration.logHome,rerunUnknownQa:true,
534
+ qaDecisionProvider:{timeoutMs:1000,decide:()=>assert.fail('reuse historical decision')},qaExecutor:executor});
535
+ const operation={version:1,operation:'advance',requestId:'step30-resume',identity:f.binding.identity};
536
+ const result=await entry.handle(operation);assert.equal(result.code,'qa_passed',JSON.stringify(result));
537
+ assert.deepEqual(seen,['TC-008']);assert(fs.readFileSync(log,'utf8').startsWith(before));
538
+ const starts=rows().filter(row=>row.phase==='start'),fresh=starts.at(-1);
539
+ assert.equal(starts.length,2);assert.notEqual(fresh.operation_id,f.binding.testRunId);
540
+ assert.equal(fresh.previous_test_run_id,f.binding.testRunId);assert.equal(fresh.case_count,2);
541
+ assert.equal(fresh.deferred_cases.length,8);assert.equal(fresh.attempt,1);
542
+ assert.equal(rows().find(row=>row.phase==='abandoned').case_count,10);
543
+ assert.equal(inspectRunClosure(log,f.binding.identity.runId).closed,true);
544
+ const valid=fs.readFileSync(log,'utf8');
545
+ assert.equal((await entry.handle(operation)).code,'qa_passed');assert.deepEqual(seen,['TC-008']);
546
+ assert.equal(fs.readFileSync(log,'utf8'),valid);
547
+ const {codeProject,testRunId,...query}=f.binding;
548
+ for(const previous of [undefined,'wrong-predecessor']){
549
+ const invalid=rows();const start=invalid.filter(row=>row.phase==='start').at(-1);
550
+ if(previous===undefined)delete start.previous_test_run_id;else start.previous_test_run_id=previous;
551
+ fs.writeFileSync(log,invalid.map(JSON.stringify).join('\n')+'\n');
552
+ assert.throws(()=>readCmAiQaRunRound({...query,testRunId:fresh.operation_id}));
553
+ fs.writeFileSync(log,valid);
554
+ }
555
+ }finally{f.cleanup();}
556
+ });
557
+
558
+ test('step30 completed-but-dropped task does not make a mid-feature case applicable',()=>{
559
+ const f=fixture();
560
+ try{
561
+ midFeature(f);
562
+ const tasks=path.join(f.configuration.specsDir,f.configuration.feature,'tasks.md');
563
+ fs.writeFileSync(tasks,fs.readFileSync(tasks,'utf8').replace('- [ ] T-002: fixture','- [x] ~~T-002: fixture~~ [DROPPED v2]'));
564
+ const executor=plannedExecutor(f.configuration);
565
+ assert.deepEqual(executor.configuration.plan.cases.map(item=>item.id),['TC-008']);
566
+ assert.deepEqual(executor.configuration.plan.deferred_cases.find(item=>item.id==='TC-001'),{id:'TC-001',taskIds:['T-002']});
567
+ }finally{f.cleanup();}
568
+ });
569
+
570
+ test('step30 deferred-only command mappings do not block applicable browser cases',async()=>{
571
+ const f=fixture();
572
+ try{
573
+ const contract=midFeature(f),source=path.join(f.configuration.specsDir,f.configuration.feature,'test-cases.json');
574
+ contract.cases.find(item=>item.id==='TC-008').kind='browser';fs.writeFileSync(source,JSON.stringify(contract));
575
+ f.configuration.commands=f.configuration.commands.filter(item=>item.id==='deferred-test');
576
+ const executor=plannedExecutor({...f.configuration,browser:async request=>{
577
+ const artifact=path.join(f.configuration.specsDir,'.reviews','browser.txt');fs.writeFileSync(artifact,'Synthetic observation');
578
+ return {verdict:'PASS',evidence:[artifact],environment:request.environment,cleanup:'completed'};
579
+ }});
580
+ assert.deepEqual(executor.configuration.plan.modes,['browser']);assert.equal(executor.caseCount,1);
581
+ const result=await executor.run(begin(f,executor),new AbortController().signal);
582
+ assert.equal(result.result,'PASS');assert.equal(result.blocked,0);
583
+ }finally{f.cleanup();}
584
+ });
585
+
586
+ test('step30 invocation selection does not change the legacy persisted executor configuration',()=>{
587
+ const f=fixture();
588
+ try{
589
+ midFeature(f);
590
+ const before=createHostQaExecutor(f.configuration),selected=before.prepare();
591
+ assert.equal(selected.caseCount,2);assert.equal(before.caseCount,11);
592
+ assert.equal(Object.hasOwn(before.configuration.plan,'deferred_cases'),false);
593
+ const tasks=path.join(f.configuration.specsDir,f.configuration.feature,'tasks.md');
594
+ fs.writeFileSync(tasks,fs.readFileSync(tasks,'utf8').replaceAll('[ ]','[x]'));
595
+ const after=createHostQaExecutor(f.configuration);
596
+ assert.deepEqual(after.configuration,before.configuration);
597
+ assert.equal(after.mode,before.mode);assert.equal(after.caseCount,before.caseCount);
598
+ assert.equal(after.prepare().caseCount,11);
599
+ assert.deepEqual(selected.configuration.plan.cases.map(item=>item.id),['TC-008']);
600
+ }finally{f.cleanup();}
601
+ });
602
+
603
+ test('step30b empty mid-feature plan emits one explicit deferred BLOCKED row',async()=>{
604
+ const f=fixture();
605
+ try{
606
+ const contract=midFeature(f,{empty:true});
607
+ const executor=plannedExecutor({...f.configuration,logic:()=>assert.fail('no deferred logic request'),
608
+ browser:()=>assert.fail('no deferred browser request')});
609
+ const plan=executor.configuration.plan;
610
+ const deferred=contract.cases.map(item=>({id:item.id,taskIds:item.taskIds.filter(id=>id!=='T-001')}));
611
+ assert.deepEqual(plan.cases,[]);assert.deepEqual(plan.commands,[]);
612
+ assert.deepEqual(plan.modes,['commands']);assert.equal(executor.mode,'commands');
613
+ assert.equal(executor.caseCount,1);assert.deepEqual(plan.deferred_cases,deferred);
614
+ const binding=begin(f,executor);
615
+ const tasks=path.join(f.configuration.specsDir,f.configuration.feature,'tasks.md');
616
+ const original=fs.readFileSync(tasks,'utf8');
617
+ fs.writeFileSync(tasks,original.replace('- [ ] T-002','- [x] T-002'));
618
+ await assert.rejects(executor.run(binding,new AbortController().signal),{code:'qa_plan_changed'});
619
+ fs.writeFileSync(tasks,original);
620
+ const result=await executor.run(binding,new AbortController().signal);
621
+ assert.equal(result.result,'BLOCKED');assert.equal(result.passed,0);
622
+ assert.equal(result.failed,0);assert.equal(result.blocked,1);
623
+ const report=fs.readFileSync(result.report,'utf8');
624
+ const rows=report.split(/^## /m).slice(2).map(section=>JSON.parse(section.slice(section.indexOf('\n')).trim()));
625
+ assert.deepEqual(rows,[{id:'no-applicable-cases',kind:'commands',verdict:'BLOCKED',
626
+ evidence:['all applicable cases are bound to unfinished tasks; deferred to feature completion',
627
+ ...deferred.map(item=>`${item.id}: ${item.taskIds.join(', ')}`)]}]);
628
+ assert(report.includes(JSON.stringify(deferred,null,2)));
629
+ const log=fs.readFileSync(path.join(f.configuration.specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
630
+ assert.deepEqual(log.find(row=>row.event==='test_run'&&row.phase==='start').deferred_cases,deferred);
631
+ assert(!log.some(row=>row.event==='resource'||row.phase?.startsWith('case_')));
632
+ recordCmAiQaRun({...binding,phase:'complete',result,logHome:f.configuration.logHome});
633
+ const {codeProject,mode,caseCount,...query}=binding;
634
+ assert.equal(inspectCmAiQaResult(query).status,'blocked');
635
+ console.log('STEP30B reproduction',JSON.stringify({selected:plan.cases,deferred:plan.deferred_cases,
636
+ commands:plan.commands,caseCount:executor.caseCount,result,rows}));
637
+ }finally{f.cleanup();assert.equal(fs.existsSync(f.root),false);}
638
+ });
639
+
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()=>{
643
+ const {createCmAiConversationEntry}=await import('../runtime/js/cm-ai/cm-ai-conversation-entry.mjs');
644
+ const {inspectCmAiQaRecovery}=await import('../runtime/js/cm-ai/cm-ai-qa-log.mjs');
645
+ const {inspectRunClosure}=await import('./cm-log-event.mjs');
646
+ const f=fixture();
647
+ try{
648
+ const artifact=path.join(f.binding.specsDir,'.reviews','browser.txt');fs.writeFileSync(artifact,'Synthetic observation');
649
+ if(scenario==='logic')f.configuration.commands[0].caseIds=[];
650
+ if(scenario==='metadata-command')f.configuration.commands[0].id='deferred_cases';
651
+ if(scenario==='commands')f.configuration.commands=[];
652
+ let repaired=false,browserCalls=0,logicCalls=0;
653
+ 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=>{
657
+ browserCalls++;
658
+ if(!repaired&&scenario==='source-drift')fs.appendFileSync(path.join(f.configuration.codeProject,'source.mjs'),'// drift\n');
659
+ 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)
662
+ ?['not-an-evidence-file']: [artifact],
663
+ environment:!repaired&&scenario==='environment'?{...request.environment,target:'different-target'}:request.environment,
664
+ cleanup:!repaired&&scenario==='cleanup'?'failed':'completed'};
665
+ }});
666
+ const binding=begin(f,executor),result=await executor.run(binding,new AbortController().signal);
667
+ const {codeProject,testRunId,mode,caseCount,...query}=binding;
668
+ const base={...binding,logHome:f.configuration.logHome};
669
+ if(scenario!=='incomplete')recordCmAiQaRun({...base,phase:'complete',result});
670
+ if(scenario!=='incomplete'){
671
+ const state=JSON.parse(fs.readFileSync(path.join(binding.specsDir,'.cm-status.json')));
672
+ assert.equal(state.state,result.failed?'qa_failed':'qa_blocked');assert.equal(state.node,'N6');
673
+ assert.equal(state.detail,`QA 结果 ${result.result}(通过 ${result.passed} / 失败 ${result.failed} / 阻断 ${result.blocked})`);
674
+ }
675
+ const log=path.join(binding.specsDir,'运行日志.jsonl'),rows=()=>fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse);
676
+ if(scenario==='round-limit')for(let round=1;round<3;round++){
677
+ const previous=round===1?testRunId:`blocked-${round}`;
678
+ recordCmAiQaRun({...base,testRunId:previous,qaRound:round,phase:'superseded'});
679
+ recordCmAiQaRun({...base,testRunId:`blocked-${round+1}`,qaRound:round+1,previousTestRunId:previous,phase:'start'});
680
+ recordCmAiQaRun({...base,testRunId:`blocked-${round+1}`,qaRound:round+1,phase:'complete',result});
681
+ }
682
+ if(scenario==='superseded-crash'){
683
+ recordCmAiQaRun({...base,phase:'superseded'});
684
+ assert.equal(inspectRunClosure(log,binding.identity.runId).closed,false);
685
+ assert.throws(()=>recordCmAiQaRun({...base,testRunId:'bad-link',qaRound:2,previousTestRunId:'wrong',phase:'start'}));
686
+ }
687
+ const completed={state:'fixture_completed',code:null,identity:binding.identity,packageDigest:binding.packageDigest};
688
+ const options={specsDir:query.specsDir,feature:query.feature,identity:query.identity,codeProject,runner:{status:()=>completed,executeEffect:()=>assert.fail('no development/Review replay'),
689
+ cancel:()=>completed,run:()=>assert.fail('no task replay')},qaExecutor:executor,qaLogHome:f.configuration.logHome,
690
+ qaDecisionProvider:{timeoutMs:1000,decide:()=>assert.fail('no repeated QA decision')}};
691
+ const operation={version:1,operation:'advance',requestId:'rerun-blocked',identity:binding.identity};
692
+ const before=fs.readFileSync(log);
693
+ const without=await createCmAiConversationEntry(options).handle(operation);
694
+ assert.equal(without.code,scenario==='incomplete'?'qa_execution_unknown':result.failed?'qa_failed':'qa_result_blocked');
695
+ if(!result.failed&&scenario!=='incomplete')assert.equal(without.pendingAction,'none');
696
+ 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)){
699
+ const rejected=await entry.handle(operation);
700
+ 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);
702
+ }else{
703
+ const queried=await entry.handle({...operation,operation:'qa_result',packageDigest:binding.packageDigest,testRunId});
704
+ assert.equal(queried.pendingAction,'qa');
705
+ repaired=scenario!=='one-shot';
706
+ const rerun=await entry.handle(operation);
707
+ assert.equal(rerun.code,['logic','one-shot'].includes(scenario)?'qa_result_blocked':'qa_passed',JSON.stringify(rerun));
708
+ assert.equal(browserCalls,2);assert.equal(logicCalls,2);
709
+ assert.equal(rows().filter(row=>row.phase==='superseded').length,1);
710
+ const starts=rows().filter(row=>row.phase==='start');assert.deepEqual(starts.map(row=>row.attempt),[1,2]);
711
+ assert.equal(starts[1].previous_test_run_id,testRunId);assert.notEqual(starts[1].operation_id,testRunId);
712
+ assert.equal(rows().filter(row=>row.phase==='complete').length,2);
713
+ assert.equal(rows().filter(row=>row.event==='qa').length,1);
714
+ assert.equal(inspectRunClosure(log,binding.identity.runId).closed,true);
715
+ assert.throws(()=>inspectCmAiQaResult({...query,testRunId}),{code:'qa_result_stale'});
716
+ const after=fs.readFileSync(log);await entry.handle(operation);
717
+ assert.equal(browserCalls,2);assert.deepEqual(fs.readFileSync(log),after);
718
+ // Replay checks the predecessor's evidence and exact blocked case set.
719
+ for(const tamper of [
720
+ rows=>{rows.find(row=>row.phase==='superseded').blocked_cases=['invented'];},
721
+ rows=>{rows.find(row=>row.phase==='complete').mode='browser';},
722
+ rows=>{rows.find(row=>row.phase==='complete').passed=String(result.passed);},
723
+ rows=>{rows.splice(rows.findIndex(row=>row.phase==='superseded'),1);
724
+ delete rows.filter(row=>row.phase==='start')[1].previous_test_run_id;},
725
+ ]){
726
+ const corrupt=rows();tamper(corrupt);
727
+ fs.writeFileSync(log,corrupt.map(JSON.stringify).join('\n')+'\n');
728
+ assert.throws(()=>inspectCmAiQaRecovery(query,{blocked:true}));fs.writeFileSync(log,after);
729
+ }
730
+ }
731
+ }finally{f.cleanup();}
732
+ });