@aibyzero/cm-workflow 0.16.7 → 0.16.8

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 (58) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +18 -0
  3. package/README.md +26 -1
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/docs/installation.md +1 -1
  8. package/docs/js-workflow-control.md +36 -3
  9. package/docs/user-guide.md +104 -0
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  12. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +27 -6
  13. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +82 -8
  14. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  15. package/runtime/js/cm-ai/drive-core.mjs +17 -4
  16. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  17. package/runtime/js/cm-ai/host-qa-executor.mjs +37 -13
  18. package/runtime/js/cm-ai/host-session.mjs +46 -6
  19. package/runtime/js/cm-ai/host-tool-bridge.mjs +15 -3
  20. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  21. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  22. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  23. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  24. package/runtime/js/cm-fix/execution.mjs +189 -148
  25. package/runtime/js/cm-fix/investigation.mjs +25 -9
  26. package/runtime/js/cm-fix/progress.mjs +3 -1
  27. package/runtime/js/notify-run.mjs +26 -0
  28. package/runtime/js/notify.mjs +388 -0
  29. package/runtime/model-efficiency.md +17 -0
  30. package/scripts/cm-ai-batch-run.mjs +5 -0
  31. package/scripts/cm-ai-batch-run.test.mjs +9 -1
  32. package/scripts/cm-ai-drive.mjs +4 -1
  33. package/scripts/cm-ai-drive.test.mjs +8 -0
  34. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  35. package/scripts/cm-ai-host.mjs +2 -2
  36. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  37. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +77 -4
  38. package/scripts/cm-fix-abandon.test.mjs +89 -3
  39. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  40. package/scripts/cm-fix-drive.mjs +9 -1
  41. package/scripts/cm-fix-host.mjs +1 -1
  42. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  43. package/scripts/cm-host-qa-executor.test.mjs +121 -0
  44. package/scripts/cm-log-event.mjs +31 -5
  45. package/scripts/cm-notify.test.mjs +468 -0
  46. package/scripts/cm-patrol.mjs +83 -0
  47. package/scripts/cm-patrol.test.mjs +161 -0
  48. package/scripts/cm-token-report.mjs +497 -0
  49. package/scripts/cm-token-report.test.mjs +346 -0
  50. package/skills/cm-ai/SKILL.md +7 -3
  51. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  52. package/skills/cm-ai/references/js-host-modes.md +90 -0
  53. package/skills/cm-ai/references/js-host-qa-recovery.md +110 -0
  54. package/skills/cm-ai/references/js-host-recovery.md +199 -0
  55. package/skills/cm-ai/references/js-host.md +67 -329
  56. package/skills/cm-fix/SKILL.md +2 -0
  57. package/skills/cm-fix/references/js-host.md +16 -9
  58. package/skills/cm-prd/SKILL.md +2 -0
@@ -187,7 +187,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
187
187
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Protected current-session invalid_result means local value/Learning validation failed before file writes. Fix the reply, keep the same configuration, host identity and runId, restart with --mode resume and advance: blocked/developer_result_invalid retries develop at the same attempt. no_new_lesson requires reason:null (dogfood incident: nonempty reason previously wrote files then stranded the run as unknown). Already-applied proposals must match expected disk hashes; conflicts block as protected_edit_stale. Worker exceptions/timeouts and old unknown history are not retryable.\n');
188
188
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('New cm-ai runs carry approved specification data in developer requests and review packages: task/verification, all AC lines, design (64 KiB UTF-8 maximum, truncated:true above it), task-related test cases and manifest hashes. Sources must match .cm-specs-status.specFiles or spec_drift blocks. requirements may be [] or additional code-project files; specs never become writable scope. Legacy runs/packages retain their original representation. Dogfood: separate specs/code roots previously left developers and reviewers without task/interface contracts.\n');
189
189
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Completed fixture_completed runs originally without QA may explicitly attach N6 once on --mode resume with --workflow-config (non-null qa) and --allow-qa. Original definition, scope, requirements, identity and non-workflow configuration must match. The immutable qa-attached journal record binds the full resumed config fingerprint; later resumes require that same configuration and fresh --allow-qa. qa still requests qa_assess; no automatic decision or repeated development/Review. Dogfood: missing workflow at create previously stranded mandatory feature QA.\n');
190
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-unknown-qa requires --mode resume and fresh --allow-qa with the original workflow config. Only an unfinished QA invocation whose recorded case results are all PASS and which has no fixed execution report may be abandoned and rerun under a new testRunId at the same qaRound. The abandoned record lists partial_pass_cases; every case is rerun and old PASS evidence is history only. FAIL/BLOCKED results and unclosed resources remain blocked; no complete is fabricated.\n');
190
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-unknown-qa requires --mode resume and fresh --allow-qa with the original workflow config. Only an unfinished QA invocation whose recorded case results are all PASS and which has no fixed execution report may be abandoned and rerun under a new testRunId at the same qaRound. The abandoned record lists partial_pass_cases; every case is rerun and old PASS evidence is history only. FAIL/BLOCKED results and unclosed resources remain blocked; no complete is fabricated. Exception: a call stopped as a whole (qa_execution_timeout) with no report and no FAIL, whose every case_blocked is a host request timeout (host_request_timeout: true; an older row without that field needs the full qa.timeoutMs elapsed since case_start plus an operator --qa-environment-failure REASON attesting no session answer, recorded verbatim as legacy_timeout_attestation, otherwise qa_environment_failure_required) and never session-declared, is superseded (reason host_request_timeout) and rerun at qaRound+1; --rerun-blocked-qa on it is refused as qa_rerun_unknown_qa_required.\n');
191
191
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--rerun-blocked-qa requires --mode resume, the original --workflow-config and fresh --allow-qa. Only the latest completed BLOCKED invocation with zero failures and exclusively host/environment evidence gaps can be superseded: browser evidenceProblem, failed cleanup, environment mismatch, host timeout or a host-declared BLOCKED answer; logic INSUFFICIENT_EVIDENCE or blocked only by a mapped command without exit code; QA commands that produced no exit code (timeout, killed, spawn/output failure). Missing/deferred command rows ([需确认], commands-unavailable, no-applicable-cases, no browser capability) and source drift are excluded. A new testRunId reruns every case at qaRound+1 (maximum 3, the shared QA round budget); superseded and start link previous_test_run_id. The flag is consumed once, never persisted; no development/Review/task replay or new QA decision. Do not combine with --rerun-unknown-qa.\n');
192
192
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('For a QA decision an older host recorded as blocked/host_request_timeout, --rerun-blocked-qa instead re-asks qa_assess once and appends a decision linked by previous_decision_id; history is kept (current hosts report a missed qa_assess window as retryable rejected/qa_decision_timeout and record nothing). --qa-environment-failure REASON (with --rerun-blocked-qa, single line, at most 500 UTF-8 bytes) declares that the non-zero QA command exits of the latest completed FAIL came from the environment: only command exits and logic cases failed solely by them qualify, never browser FAIL or CONTRADICTED; the superseded row records reason, failed_cases and blocked_cases. Every rerun reuses the three-round QA budget. Single-task host only.\n');
193
193
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('--allow-abandon-review: resume 原 run 后发送 abandon_review,request.reason 必须是单行且不超过 500 UTF-8 字节。操作员先确认旧 host 与 review 进程已退出;旗标只消费一次,不写入配置。\n');
@@ -254,7 +254,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
254
254
  workflow===null?'--allow-qa 需要同时提供 --workflow-config':'--allow-qa 需要 --workflow-config 中的 qa 不为 null;本运行没有 QA 时去掉 --allow-qa');
255
255
  need(!(extra.has('--rerun-unknown-qa')&&extra.has('--rerun-blocked-qa')),'qa_recovery_authorization_required');
256
256
  need(!(extra.has('--rerun-unknown-qa')||extra.has('--rerun-blocked-qa'))||(argv[4]==='resume'&&extra.has('--allow-qa')),'qa_recovery_authorization_required');
257
- need(!extra.has('--qa-environment-failure')||extra.has('--rerun-blocked-qa'),'qa_recovery_authorization_required');
257
+ need(!extra.has('--qa-environment-failure')||extra.has('--rerun-blocked-qa')||extra.has('--rerun-unknown-qa'),'qa_recovery_authorization_required');
258
258
  const hasFix=extra.has('--qa-fix-owner-config')||extra.has('--qa-fix-template-config');
259
259
  need(!(extra.has('--qa-fix-owner-config')&&extra.has('--qa-fix-template-config')),'invalid_fix_config');
260
260
  need(!extra.has('--allow-qa-fix-start')||hasFix,'qa_fix_source_required');
@@ -5,6 +5,7 @@ import assert from 'node:assert/strict';
5
5
  import fs from 'node:fs';
6
6
  import os from 'node:os';
7
7
  import path from 'node:path';
8
+ import {fileURLToPath,pathToFileURL} from 'node:url';
8
9
  import {buildManifest} from './cm-spec-manifest.mjs';
9
10
  import {openControlRun} from './cm-ai-run.mjs';
10
11
  import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
@@ -48,7 +49,7 @@ function project(){
48
49
  const state={browserUp:false,documentation:0,reviews:new Map()};
49
50
  const logHome=path.join(specsDir,'.reviews','host-log-mirror');
50
51
  const environment={kind:'web',carrier:'browser',target:'fixture',scope:'local'};
51
- const execution=(feature,{write,retrospective=noLesson,verdict=()=>'approved',decision=null})=>({
52
+ const execution=(feature,{write,retrospective=noLesson,verdict=()=>'approved',decision=null,browser=null,createExecutor=createHostQaExecutor})=>({
52
53
  configuration:{kind:'synthetic-host-v1',hostContextId:'control',workflow:{qa:{commands:[],environment},documentationPaths:[],applicableAgentFiles:[]}},
53
54
  timeoutMs:5000,excludedContexts:['control'],
54
55
  developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async()=>{
@@ -75,12 +76,12 @@ function project(){
75
76
  status:'completed',reason:'Documentation checked',at:'2026-09-28T00:00:00Z'};}},
76
77
  qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:`qa-${binding.identity.runId}`,identity:binding.identity,
77
78
  packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-09-28T00:00:00Z',...decision})},
78
- qaExecutor:createHostQaExecutor({specsDir,codeProject,feature,requirements:['requirements.md'],runtime:'codex',
79
+ qaExecutor:createExecutor({specsDir,codeProject,feature,requirements:['requirements.md'],runtime:'codex',
79
80
  commands:[{id:'unit',command:[process.execPath,'--check','a.mjs'],caseIds:[]}],environment,timeoutMs:60000,logHome,
80
- browser:async browserRequest=>{
81
+ browser:browser??(async browserRequest=>{
81
82
  if(!state.browserUp)return {verdict:'BLOCKED',evidence:[],environment:browserRequest.environment,cleanup:'failed'};
82
83
  const shot=path.join(specsDir,'.reviews','tc-001.txt');fs.writeFileSync(shot,'observed');
83
- return {verdict:'PASS',evidence:[shot],environment:browserRequest.environment,cleanup:'not_needed'};}})});
84
+ return {verdict:'PASS',evidence:[shot],environment:browserRequest.environment,cleanup:'not_needed'};})})});
84
85
  const definition=(feature,taskId,scope)=>({version:1,specsDir,codeProject,feature,
85
86
  identity:{repositoryId:'gate-fixture',runId:`run-${taskId}`,taskId,attempt:1},scope,requirements:['requirements.md']});
86
87
  const advance=async(def,exec,mode,options)=>{
@@ -137,6 +138,72 @@ test('#17 an earlier feature whose QA is BLOCKED keeps the project from run_done
137
138
  assert.equal(status(p).state,'run_done');
138
139
  });
139
140
 
141
+ // The executor as released before dropped-task cases were left out: the current
142
+ // module with that one rule neutralized, imported from a temporary copy.
143
+ async function releasedQaExecutor(){
144
+ const source=fileURLToPath(new URL('../runtime/js/cm-ai/host-qa-executor.mjs',import.meta.url));
145
+ const rule='const dropped=new Set(context.dropped);',text=fs.readFileSync(source,'utf8');
146
+ assert.equal(text.split(rule).length,2,'the dropped-task rule is where this fixture expects it');
147
+ const base=pathToFileURL(path.dirname(source)+path.sep).href;
148
+ const released=text.replace(rule,'const dropped=new Set();')
149
+ .replace(/'\.\.\/\.\.\/\.\.\//g,`'${new URL('../../../',base).href}`).replace(/from '\.\//g,`from '${base}`);
150
+ const file=path.join(fs.mkdtempSync(path.join(isolated,'released-')),'host-qa-executor.mjs');fs.writeFileSync(file,released);
151
+ return (await import(pathToFileURL(file).href)).createHostQaExecutor;
152
+ }
153
+
154
+ // 2026-10-08 aihot: 5.author-column's feature-completion QA (run author-column-T-010) asked the
155
+ // session about cases bound only to [DROPPED] tasks; they stayed BLOCKED and the project gate then
156
+ // held api-native-reading-T-008's finish. Recovery: --rerun-blocked-qa on the original run, then resume.
157
+ test('#17 an earlier BLOCKED round over dropped-task cases is recovered on its original run; the later run then finishes',async()=>{
158
+ const p=project();
159
+ const feature=path.join(p.specsDir,'1.work'),log=path.join(p.specsDir,'运行日志.jsonl');
160
+ const rows=()=>fs.readFileSync(log,'utf8').trim().split('\n').map(JSON.parse);
161
+ const contract=JSON.parse(fs.readFileSync(path.join(feature,'test-cases.json')));
162
+ // TC-001 is the live task's case; TC-002 (non-blocking browser) and TC-003 (blocking logic) are bound only to dropped T-001.
163
+ contract.cases.push({...contract.cases[0],id:'TC-002',blocking:false,taskIds:['T-001']},
164
+ {...contract.cases[0],id:'TC-003',kind:'logic',taskIds:['T-001']});
165
+ fs.writeFileSync(path.join(feature,'test-cases.json'),JSON.stringify(contract));
166
+ fs.writeFileSync(path.join(feature,'tasks.md'),'- [ ] ~~T-001: column work~~ `[DROPPED v2: 数据源未定,暂缓]`\n- [ ] T-002: fixture\n');
167
+ p.reapprove();
168
+ const asked=[];
169
+ const firstExecution=createExecutor=>p.execution('1.work',{createExecutor,
170
+ write:()=>fs.writeFileSync(path.join(p.codeProject,'a.mjs'),'export const a=1;\n'),
171
+ browser:async request=>{
172
+ asked.push(request.case.id);
173
+ // The feature is hidden: the session can only answer BLOCKED for the dropped task's case.
174
+ if(request.case.id!=='TC-001')return {verdict:'BLOCKED',evidence:[],environment:request.environment,cleanup:'not_needed'};
175
+ const shot=path.join(p.specsDir,'.reviews',`${request.case.id}-${asked.length}.txt`);fs.writeFileSync(shot,'observed');
176
+ return {verdict:'PASS',evidence:[shot],environment:request.environment,cleanup:'not_needed'};}});
177
+ const blocked=await p.advance(p.first,firstExecution(await releasedQaExecutor()),'create');
178
+ assert.equal(blocked.code,'qa_result_blocked',JSON.stringify(blocked));assert.deepEqual(asked,['TC-001','TC-002']);
179
+ const oldComplete=rows().find(row=>row.phase==='complete'&&row.run_id==='run-T-002');
180
+ assert.deepEqual([oldComplete.result,oldComplete.case_count,oldComplete.passed,oldComplete.blocked],['BLOCKED',4,2,2]);
181
+ // The recorded round is not reinterpreted: the project gate still reads it as BLOCKED.
182
+ const last=p.definition('2.next','T-003',['b.mjs']);
183
+ const lastExecution=()=>p.execution('2.next',{write:()=>fs.writeFileSync(path.join(p.codeProject,'b.mjs'),'export const b=1;\n')});
184
+ const refused=await p.advance(last,lastExecution(),'create');
185
+ assert.equal(refused.code,'project_qa_not_passed',JSON.stringify(refused));
186
+ assert.deepEqual(refused.outstandingQa,[{feature:'1.work',runId:'run-T-002',taskId:'T-002',attempt:1,status:'qa_blocked'}]);
187
+ const history=fs.readFileSync(log,'utf8'),oldReport=fs.readFileSync(oldComplete.report);
188
+ // Its BLOCKED cases (a session BLOCKED answer, a logic case without a host) are rerun-eligible.
189
+ const recovered=await p.advance(p.first,firstExecution(),'resume',{rerunBlockedQa:true});
190
+ assert.equal(recovered.code,'run_done',JSON.stringify(recovered));
191
+ assert.deepEqual(asked,['TC-001','TC-002','TC-001'],'the dropped task case is never asked again');
192
+ assert(fs.readFileSync(log,'utf8').startsWith(history));assert.deepEqual(fs.readFileSync(oldComplete.report),oldReport);
193
+ const superseded=rows().find(row=>row.phase==='superseded');
194
+ assert.equal(superseded.previous_test_run_id,oldComplete.operation_id);assert.deepEqual(superseded.blocked_cases,['TC-002','TC-003']);
195
+ const start=rows().filter(row=>row.phase==='start'&&row.run_id==='run-T-002').at(-1);
196
+ assert.equal(start.attempt,2);assert.equal(start.previous_test_run_id,oldComplete.operation_id);
197
+ assert.deepEqual(start.dropped_task_cases,[{id:'TC-002',taskIds:['T-001']},{id:'TC-003',taskIds:['T-001']}]);
198
+ const complete=rows().filter(row=>row.phase==='complete'&&row.run_id==='run-T-002').at(-1);
199
+ assert.deepEqual([complete.result,complete.case_count,complete.passed],['PASS',2,2]);
200
+ const notApplicable=fs.readFileSync(complete.report,'utf8').split(/^## /m).find(part=>part.startsWith('not_applicable\n'));
201
+ assert.deepEqual(JSON.parse(notApplicable.slice('not_applicable\n'.length)).map(item=>[item.id,item.verdict,item.reason]),
202
+ [['TC-002','NOT_APPLICABLE','bound only to dropped tasks: T-001'],['TC-003','NOT_APPLICABLE','bound only to dropped tasks: T-001']]);
203
+ const finished=await p.advance(last,lastExecution(),'resume');
204
+ assert.equal(finished.code,'run_done',JSON.stringify(finished));assert.equal(status(p).state,'run_done');
205
+ });
206
+
140
207
  test('#18 unreviewed tampering with the earlier task file still requires correction review and names the file',async()=>{
141
208
  const p=project();
142
209
  await p.advance(p.first,p.firstExecution(),'create');
@@ -50,9 +50,10 @@ function fixture(t,{browser=false}={}){
50
50
  fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'# Fixture\n\n- [AC-001] tab bar shows four tabs\n');
51
51
  fs.writeFileSync(path.join(specsDir,feature,'design.md'),'# Fixture\n');
52
52
  fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
53
- if(browser)fs.writeFileSync(path.join(specsDir,feature,'test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',cases:[
54
- {id:'TC-001',origin:'generated',kind:'browser',blocking:true,acIds:['AC-001'],taskIds:['T-001'],title:'four tabs',
55
- preconditions:['UI test'],steps:['launch on simulator'],expected:['four tabs visible'],cleanup:[]}]}));
53
+ if(browser)fs.writeFileSync(path.join(specsDir,feature,'test-cases.json'),JSON.stringify({schemaVersion:'1.0',feature:'work',
54
+ cases:Array.from({length:browser===true?1:browser},(_,index)=>({id:`TC-00${index+1}`,origin:'generated',kind:'browser',
55
+ blocking:true,acIds:['AC-001'],taskIds:['T-001'],title:'four tabs',
56
+ preconditions:['UI test'],steps:['launch on simulator'],expected:['four tabs visible'],cleanup:[]}))}));
56
57
  const manifest=buildManifest(specsDir);
57
58
  fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:manifest,
58
59
  ...(browser?{testCases:manifest.filter(item=>item.path.endsWith('/test-cases.json'))}:{})}));
@@ -109,7 +110,8 @@ function failingStartShim(f){
109
110
  return dir;
110
111
  }
111
112
 
112
- // answers[kind] may be a value, a function(row) or 'IGNORE' (never answered).
113
+ // answers[kind] may be a value, a function(row) or 'IGNORE' (never answered);
114
+ // a function may also return 'IGNORE', or 'KILL' to SIGKILL the host mid-call.
113
115
  function launch(f,{mode='resume',operation='advance',workflow=null,extra=[],answers={},review=true,pathPrefix=null}={}){
114
116
  return new Promise((resolve,reject)=>{
115
117
  const args=['serve','--config',f.config,'--mode',mode,'--host-context','session-A','--allow-development',
@@ -136,6 +138,8 @@ function launch(f,{mode='resume',operation='advance',workflow=null,extra=[],answ
136
138
  let result;
137
139
  try{result=configured===undefined?defaultAnswer(f,row):typeof configured==='function'?configured(row):configured;}
138
140
  catch(error){child.kill('SIGKILL');clearTimeout(timer);reject(error);return;}
141
+ if(result==='IGNORE')continue;
142
+ if(result==='KILL'){child.kill('SIGKILL');continue;}
139
143
  send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
140
144
  }
141
145
  if(row.requestId==='request'&&(row.result||row.error))send({type:'host_close',sessionId});
@@ -398,3 +402,72 @@ test('#7 decision chain: one linked supersession of a timeout decision, read by
398
402
  assert.throws(()=>inspectFixQaSource({specsRoot:specsDir,identity:qaFixIdentity(qaSource),configuration}),label);
399
403
  }
400
404
  });
405
+
406
+ // A QA call stopped as a whole (qa_execution_timeout, or the host gone) leaves no
407
+ // complete and no report. Here the probe command passes, TC-001 gets no session
408
+ // answer within qa.timeoutMs, and the host dies while TC-002 waits.
409
+ async function timedOutCall(t){
410
+ const f=fixture(t,{browser:2}),workflow=f.workflow('workflow',probeQa({environment:simulator,timeoutMs:1500}));
411
+ const browserQa=['--browser-qa','available'];
412
+ const aborted=await launch(f,{mode:'create',workflow,extra:browserQa,
413
+ answers:{qa_browser:row=>row.payload.case.id==='TC-001'?'IGNORE':'KILL'}});
414
+ assert.notEqual(aborted.code,0);
415
+ const recorded=testRuns(f).map(row=>[row.phase,row.case_id]);
416
+ assert.deepEqual(recorded,[['start',undefined],['case_start','TC-001'],['case_blocked','TC-001'],['case_start','TC-002']]);
417
+ assert.equal(testRuns(f,'case_blocked')[0].host_request_timeout,true);
418
+ return {f,workflow,browserQa};
419
+ }
420
+ const pass=f=>row=>{const file=path.join(f.specsDir,'.reviews',`${row.payload.case.id}.png`);fs.writeFileSync(file,'png');
421
+ return {verdict:'PASS',evidence:[file],environment:row.payload.environment,cleanup:'not_needed'};};
422
+
423
+ test('#26c --rerun-unknown-qa supersedes a call stopped as a whole whose only non-PASS case is a host request timeout',POSIX,async t=>{
424
+ const {f,workflow,browserQa}=await timedOutCall(t);
425
+ const unknown=done(await launch(f,{workflow,extra:browserQa}));
426
+ assert.equal(unknown.code,'qa_execution_unknown');assert.equal(unknown.pendingAction,'reconcile');
427
+ const logBefore=fs.readFileSync(f.log),oldRun=testRuns(f,'start')[0].operation_id;
428
+ // --rerun-blocked-qa needs a completed call; its refusal names the flag that applies.
429
+ const wrong=done(await launch(f,{workflow,extra:[...browserQa,'--rerun-blocked-qa']}));
430
+ assert.equal(wrong.code,'qa_rerun_unknown_qa_required',JSON.stringify(wrong));
431
+ assert(fs.readFileSync(f.log).equals(logBefore));
432
+ const rerun=await launch(f,{workflow,extra:[...browserQa,'--rerun-unknown-qa'],answers:{qa_browser:pass(f)}});
433
+ const result=done(rerun);
434
+ assert.equal(result.state,'run_done',JSON.stringify(result));
435
+ assert(fs.readFileSync(f.log).subarray(0,logBefore.length).equals(logBefore),'history bytes are kept');
436
+ // Every case and command runs again at qaRound+1; no PASS is carried forward.
437
+ assert.deepEqual(rerun.asked.filter(kind=>kind==='qa_browser'),['qa_browser','qa_browser']);
438
+ const [superseded]=testRuns(f,'superseded');
439
+ assert.equal(superseded.operation_id,oldRun);assert.equal(superseded.reason,'host_request_timeout');
440
+ assert.deepEqual([superseded.timed_out_cases,superseded.partial_pass_cases,superseded.request_timeout_ms],[['TC-001'],[],1500]);
441
+ const starts=testRuns(f,'start');
442
+ assert.deepEqual(starts.map(row=>[row.attempt,row.previous_test_run_id]),[[1,undefined],[2,oldRun]]);
443
+ assert.equal(f.rows().filter(row=>row.event==='resource'&&row.phase==='released'&&row.operation_id===starts[1].operation_id).length,1);
444
+ assert.deepEqual(testRuns(f,'complete').map(row=>[row.attempt,row.result]),[[2,'PASS']]);
445
+ assert.equal(done(await launch(f,{workflow,extra:browserQa})).state,'run_done');
446
+ });
447
+
448
+ test('#26c a session-declared BLOCKED, a FAIL or an unattested older timeout row still refuses --rerun-unknown-qa',POSIX,async t=>{
449
+ const {f,workflow,browserQa}=await timedOutCall(t);
450
+ const original=fs.readFileSync(f.log,'utf8');
451
+ const variant=edit=>original.trim().split('\n').map(line=>{const row=JSON.parse(line);
452
+ return JSON.stringify(row.event==='test_run'&&row.phase==='case_blocked'?edit(row):row);}).join('\n')+'\n';
453
+ const legacy=(seconds)=>row=>{const {host_request_timeout,...rest}=row;
454
+ const start=testRuns(f,'case_start')[0].at;return {...rest,at:new Date(Date.parse(start)+seconds*1000).toISOString().replace(/\.\d{3}Z$/,'Z')};};
455
+ const attest=['--qa-environment-failure','session gave no TC-001 answer before the deadline'];
456
+ for(const [name,edit,code,extra] of [
457
+ ['session-declared',row=>({...row,host_declared_blocked:true,host_request_timeout:false}),'qa_execution_unknown',attest],
458
+ ['other BLOCKED',row=>({...row,host_request_timeout:false}),'qa_execution_unknown',attest],
459
+ ['FAIL',row=>({...row,phase:'case_complete',result:'FAIL',host_request_timeout:undefined}),'qa_execution_unknown',attest],
460
+ ['older row, window not elapsed',legacy(0),'qa_execution_unknown',attest],
461
+ // An older host also wrote this row for a PASS answered near the deadline but
462
+ // downgraded to BLOCKED (cleanup failed, other environment): the time span
463
+ // cannot tell them apart, so only the operator's attestation can.
464
+ ['older row, full window, no attestation',legacy(2),'qa_environment_failure_required',[]]]){
465
+ fs.writeFileSync(f.log,variant(edit));const before=fs.readFileSync(f.log);
466
+ const refused=done(await launch(f,{workflow,extra:[...browserQa,'--rerun-unknown-qa',...extra]}));
467
+ assert.equal(refused.code,code,`${name}: ${JSON.stringify(refused)}`);
468
+ assert(fs.readFileSync(f.log).equals(before),name);
469
+ }
470
+ const rerun=done(await launch(f,{workflow,extra:[...browserQa,'--rerun-unknown-qa',...attest],answers:{qa_browser:pass(f)}}));
471
+ assert.equal(rerun.state,'run_done',JSON.stringify(rerun));
472
+ assert.deepEqual(testRuns(f,'superseded').map(row=>[row.timed_out_cases,row.legacy_timeout_attestation]),[[['TC-001'],attest[1]]]);
473
+ });
@@ -52,14 +52,18 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
52
52
  const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);
53
53
  onEvent({event:'thread.started',provider_thread:`fixture-review-${reviewMode==='first_lost_same_thread'?1:reviews}`});
54
54
  if(reviewMode==='lost'||['second_lost','second_lost_retry'].includes(reviewMode)&&reviews===2
55
- ||['first_lost','first_lost_same_thread'].includes(reviewMode)&&reviews===1)throw Error('Synthetic lost review result');
55
+ ||['first_lost','first_lost_same_thread'].includes(reviewMode)&&reviews===1
56
+ ||['rediagnosis_lost','rediagnosis_twice','rediagnosis_context'].includes(reviewMode)&&(reviews===2||reviewMode==='rediagnosis_twice'&&reviews===3))
57
+ throw Error('Synthetic lost review result');
56
58
  for(const event of [{event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},
57
59
  {event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
60
+ const outsidePath=reviewMode==='rediagnosis_invalid'&&reviews===2;
58
61
  const verdict=['changes_requested','second_lost'].includes(reviewMode)||reviewMode==='second_lost_retry'&&reviews===1
59
- ?'changes_requested':'approved';
62
+ ||reviewMode?.startsWith('rediagnosis_')&&reviews===1||outsidePath?'changes_requested':'approved';
60
63
  return {status:'succeeded',value:{verdict,packageDigest:data.reviewPackage.packageDigest,
61
64
  examinedPaths:data.examinedPaths,
62
- findings:verdict==='changes_requested'?[{id:'F1',severity:'P2',path:'value.mjs',message:'Revise value',evidence:'Fixture'}]:[],
65
+ findings:verdict==='changes_requested'?[{id:'F1',severity:'P2',path:outsidePath?'not-in-package.mjs':'value.mjs',message:'Revise value',evidence:'Fixture'}]
66
+ :reviewMode==='rediagnosis_context'?[{id:'C1',severity:'P3',path:'existing.mjs',message:'Prior-round file still fine',evidence:'Fixture'}]:[],
63
67
  summary:'Synthetic review'}};
64
68
  }}):null;
65
69
  if(reviewHost)configuration.causeReview=reviewHost.reviewer;
@@ -67,6 +71,8 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
67
71
  let loseObservation=true,loseRevisionRepair=true;
68
72
  const bridge={async call(kind,payload){
69
73
  if(kind==='fix_diagnose'){
74
+ // Round 1 covers existing.mjs too; the rediagnosis narrows it away.
75
+ if(reviewMode==='rediagnosis_context'&&!payload.reviewFeedback)return {...diagnosis,affectedPaths:['existing.mjs','value.mjs'],crossLayer:true};
70
76
  if(observation&&payload.observationEvidence&&loseObservation){loseObservation=false;throw Error('Lost observation answer');}
71
77
  return crossLayer?{...diagnosis,crossLayer:true}:diagnosis;
72
78
  }
@@ -499,3 +505,83 @@ test('#15 the retried cause review refuses the abandoned reviewer thread',async
499
505
  assert.equal(reused.stage,'unknown');assert.equal(reused.pending,'cause_review');
500
506
  assert(!f.records().some(row=>row.id==='fix-cause-retry-started'));
501
507
  });
508
+
509
+ // A round-2 (post-rediagnosis) cause review with no result used to stay unknown
510
+ // forever: it was excluded from abandon_review, and a finished reviewer whose
511
+ // answer broke the verdict contract left no result record at all.
512
+ async function toRediagnosisReview(f){
513
+ assert.equal((await f.owner().advance({authorized:true})).stage,'cause_review_required');
514
+ await causeDecide(f);assert.equal((await f.owner().reviewCause()).stage,'rediagnosis_required');
515
+ assert.equal((await f.owner().rediagnose({authorized:true,reason:'Address F1'})).stage,'cause_review_required');
516
+ await causeDecide(f);return f.owner().reviewCause();
517
+ }
518
+ const hostFor=(f,permissions)=>createFixHost({owner:f.owner(),config:{...f.configuration,specsRoot:f.specsRoot,identity:f.identity},permissions});
519
+ for(const reviewMode of ['rediagnosis_lost','rediagnosis_invalid'])
520
+ test(`regression: a no-result round-2 cause review (${reviewMode}) is abandoned once via the host and re-dispatched in the same round on a fresh thread`,async t=>{
521
+ const f=await fixture(t,{reviewMode,crossLayer:true});
522
+ const lost=await toRediagnosisReview(f);
523
+ assert.equal(lost.stage,'unknown');assert.equal(lost.reviewAbandonable,'cause_review');
524
+ const round2=f.records().map(row=>row.id).filter(id=>id.startsWith('fix-cause-rediagnosis'));
525
+ if(reviewMode==='rediagnosis_lost'){
526
+ assert.equal(lost.pending,'cause_review');
527
+ assert.deepEqual(round2,['fix-cause-rediagnosis-registered','fix-cause-rediagnosis-started']);
528
+ }else{
529
+ // The finished reviewer's off-contract answer is a recorded failed observation, not a dropped result.
530
+ assert.equal(lost.pending,null);assert.equal(lost.causeReview.observationStatus,'unknown');
531
+ assert.deepEqual(round2,['fix-cause-rediagnosis-registered','fix-cause-rediagnosis-started','fix-cause-rediagnosis-result']);
532
+ assert.deepEqual(f.records().find(row=>row.id==='fix-cause-rediagnosis-result').payload.observation.result,
533
+ {status:'failed',code:'invalid_finding_path'});
534
+ assert.equal(f.reopen().status().reviewAbandonable,'cause_review');
535
+ }
536
+ const prefix=fs.readFileSync(f.statePath),prefixRecords=f.records();
537
+ assert.match((await hostFor(f,['--allow-reproduction','--allow-abandon-review']).handle({requestId:'s',operation:'status'})).progress.nextAction,/abandon_review/);
538
+ await assert.rejects(hostFor(f,['--allow-reproduction','--allow-abandon']).handle({requestId:'a',operation:'abandon_review',reason:'Stopped'}),
539
+ {code:'fix_review_abandon_authorization_required'});
540
+ assert.deepEqual(fs.readFileSync(f.statePath),prefix);
541
+ const abandoned=await hostFor(f,['--allow-reproduction','--allow-abandon-review']).handle({requestId:'a',operation:'abandon_review',reason:'Round-2 reviewer confirmed stopped'});
542
+ assert.equal(abandoned.stage,'cause_review_required');assert.equal(abandoned.causeReviewAbandonment.providerThreadId,'fixture-review-2');
543
+ assert.equal(f.reopen().status().stage,'cause_review_required');
544
+ await causeDecide(f);
545
+ assert.equal((await f.owner().reviewCause()).stage,'red_test_required');
546
+ const records=f.records();
547
+ assert.deepEqual(records.slice(0,prefixRecords.length),prefixRecords);
548
+ assert.deepEqual(records.slice(prefixRecords.length).map(row=>row.id),['fix-cause-rediagnosis-abandoned',
549
+ 'fix-cause-rediagnosis-retry-registered','fix-cause-rediagnosis-retry-started','fix-cause-rediagnosis-retry-result']);
550
+ assert.equal(records.find(row=>row.id==='fix-cause-rediagnosis-retry-started').payload.providerThreadId,'fixture-review-3');
551
+ assert.equal(records.filter(row=>row.id==='fix-rediagnosis-intent').length,1);assert.equal(f.reviews(),3);
552
+ assert.match(fs.readFileSync(path.join(f.specsRoot,'.reviews','fix-abandon-cause-r2.md'),'utf8'),/round: 2\nverdict: approved/);
553
+ const reopened=f.reopen().status();
554
+ assert.equal(reopened.stage,'red_test_required');assert.equal(reopened.causeReview.providerThreadId,'fixture-review-3');
555
+ });
556
+
557
+ test('regression: a second no-result round-2 cause review exhausts that round\'s one-time abandonment without changing the store',async t=>{
558
+ const f=await fixture(t,{reviewMode:'rediagnosis_twice',crossLayer:true});
559
+ await toRediagnosisReview(f);
560
+ const host=()=>hostFor(f,['--allow-reproduction','--allow-abandon-review']);
561
+ assert.equal((await host().handle({requestId:'a',operation:'abandon_review',reason:'First round-2 reviewer stopped'})).stage,'cause_review_required');
562
+ await causeDecide(f);
563
+ const again=await f.owner().reviewCause();
564
+ assert.equal(again.stage,'unknown');assert.equal(again.reviewAbandonBudgetExhausted,true);assert.equal(again.reviewAbandonable,undefined);
565
+ const before=fs.readFileSync(f.statePath);
566
+ await assert.rejects(host().handle({requestId:'b',operation:'abandon_review',reason:'Second round-2 reviewer stopped'}),{code:'fix_review_abandon_budget_exhausted'});
567
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
568
+ assert.equal(f.reopen().status().reviewAbandonBudgetExhausted,true);
569
+ });
570
+
571
+ test('regression: the round-2 cause package carries the prior review\'s examined files as context, on first dispatch and on the retry, and a finding citing them is accepted',async t=>{
572
+ const f=await fixture(t,{reviewMode:'rediagnosis_context',crossLayer:true});
573
+ assert.equal((await toRediagnosisReview(f)).reviewAbandonable,'cause_review');
574
+ await hostFor(f,['--allow-reproduction','--allow-abandon-review']).handle({requestId:'a',operation:'abandon_review',reason:'Round-2 reviewer stopped'});
575
+ await causeDecide(f);
576
+ assert.equal((await f.owner().reviewCause()).stage,'red_test_required');
577
+ const pkgOf=id=>f.records().find(row=>row.id===id).payload.request.payload.reviewPackage;
578
+ assert.equal(pkgOf('fix-cause-registered').contextFiles,undefined);
579
+ for(const id of ['fix-cause-rediagnosis-registered','fix-cause-rediagnosis-retry-registered']){
580
+ const pkg=pkgOf(id);
581
+ assert.deepEqual(pkg.diagnosis.affectedPaths,['value.mjs']);assert.deepEqual(pkg.files.map(file=>file.path),['value.mjs']);
582
+ assert.deepEqual(pkg.contextFiles.map(file=>file.path),['existing.mjs']);
583
+ }
584
+ const review=f.reopen().status().causeReview.review;
585
+ assert.equal(review.verdict,'approved');assert.deepEqual(review.findings.map(row=>row.path),['existing.mjs']);
586
+ assert.equal(f.owner().status().stage,'red_test_required');
587
+ });
@@ -115,3 +115,36 @@ test('F56 M1 cause transition rejects hidden drift beneath a registered test-aut
115
115
  assert.equal(JSON.stringify(reviewed),reviewedBytes);
116
116
  }
117
117
  });
118
+
119
+ test('regression: a round-2 context file that is a registered test admits the test-author transition, and only that',async t=>{
120
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-cause-context-')));
121
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
122
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
123
+ const source='export const value=1;',testBody="import {value} from './value.mjs';if(value!==2)throw Error('BUG');";
124
+ fs.writeFileSync(path.join(cwd,'value.mjs'),source);fs.writeFileSync(path.join(cwd,'regression.mjs'),testBody);
125
+ const hex=c=>c.repeat(64);
126
+ // Round 1 covered value.mjs and regression.mjs; the rediagnosis narrowed affectedPaths to value.mjs.
127
+ const status={stage:'cause_review_required',identity:{repositoryId:'fixture',runId:'context',taskId:'T-FIX-cause',attempt:1},
128
+ learning:null,reproduction:{status:'reproduced',next:'diagnose',observation:{id:'reproduce',command:['node','regression.mjs'],
129
+ outcome:'failed',exitCode:1,evidence:'Synthetic BUG',signatureMatched:true}},
130
+ diagnosis:{status:'diagnosed',rootCause:'Wrong value',plan:'Correct value',crossLayer:false,affectedPaths:['value.mjs'],affectedModules:['value']},
131
+ rediagnosis:{historyDigest:hex('a'),priorPackageDigest:hex('b'),priorObservationDigest:hex('c'),reason:'Address F1',
132
+ reviewFeedback:{verdict:'changes_requested',packageDigest:hex('b'),examinedPaths:['regression.mjs','value.mjs'],
133
+ findings:[{id:'F1',severity:'P2',path:'regression.mjs',message:'Test misses the boundary',evidence:'Fixture'}],summary:'Fixture'}}};
134
+ const capture=()=>createFixCausePackage({codeProject:cwd,defect:'Wrong value',status});
135
+ const reviewed=readFixCausePackage(capture());
136
+ assert.deepEqual(reviewed.contextFiles.map(file=>file.path),['regression.mjs']);
137
+ for(const hiddenDrift of [false,true]){
138
+ fs.writeFileSync(path.join(cwd,'regression.mjs'),testBody+(hiddenDrift?'\n// unregistered edit after cause review':''));
139
+ let registered;
140
+ const author=prepareFixTestAuthor({codeProject:cwd,specsRoot,identity:status.identity,testFiles:['regression.mjs'],
141
+ requirements:['value.mjs'],defect:'Wrong value',diagnosis:status.diagnosis,reproduction:status.reproduction},
142
+ {assertReviewReady(){},bridge:{async call(){fs.appendFileSync(path.join(cwd,'regression.mjs'),'\nif(!Number.isInteger(value))throw Error("boundary");');return {outcome:'authored'};}}});
143
+ const result=await author.execute({authorized:true,signal:new AbortController().signal,register(baseline){registered=baseline;}});
144
+ assert.equal(result.outcome,'authored');
145
+ const verify=()=>verifyFixCauseTransition(reviewed,capture(),registered,result);
146
+ if(hiddenDrift)assert.throws(verify,{code:'cause_review_drift'});else assert.doesNotThrow(verify);
147
+ }
148
+ // Without a registered test transition, any change to a context file is drift.
149
+ assert.throws(()=>verifyFixCauseTransition(reviewed,capture(),null,null),{code:'cause_review_drift'});
150
+ });
@@ -30,6 +30,7 @@
30
30
  // learning.json {status, summary} 恢复时若存档里已有记录会自动复用
31
31
  // diagnosis.json 首次诊断结论对象
32
32
  // diagnosis-rediagnosis.json 显式原运行重新诊断的新结论,不能复用首次文件
33
+ // 两份诊断都在开宿主前用宿主同一校验器检查(如 investigation.discardedAlternatives 最多 3 项)
33
34
  // retrospective.json {status, candidates, reason}
34
35
  // test-edits.json {"仓库内路径": "本目录下的内容文件"};修订轮用 test-edits-a2.json
35
36
  // repair-edits.json 同上;修订轮用 repair-edits-a2.json
@@ -37,6 +38,7 @@ import fs from 'node:fs';
37
38
  import path from 'node:path';
38
39
  import {fileURLToPath} from 'node:url';
39
40
  import {fixEvidenceNames} from '../runtime/js/cm-fix/layout.mjs';
41
+ import {inspectFixDiagnosis,describeFixDiagnosisError} from '../runtime/js/cm-fix/diagnosis.mjs';
40
42
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
41
43
  import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
42
44
 
@@ -138,7 +140,13 @@ export function preflight({operation,plan,paths}){
138
140
  if(recorded){stderr(`恢复:复用存档里已记的学习记录(${recorded.status})`);return recorded;}
139
141
  return need('学习记录','learning.json');
140
142
  }
141
- if(kind==='diagnosis')return need('诊断',operation==='rediagnose'?'diagnosis-rediagnosis.json':'diagnosis.json');
143
+ if(kind==='diagnosis'){
144
+ // 用宿主同一个校验器:不合格的答案在开宿主前就拦下,免得登记了却交不出结论。
145
+ const file=operation==='rediagnose'?'diagnosis-rediagnosis.json':'diagnosis.json';
146
+ const value=need('诊断',file);
147
+ try{inspectFixDiagnosis(value);}catch(error){stop(2,`${path.join(paths.answers,file)}:${describeFixDiagnosisError(error)};改好再来,宿主未启动`);}
148
+ return value;
149
+ }
142
150
  if(kind==='retrospective')return need('复盘','retrospective.json');
143
151
  const file=roundAnswerName(paths.answers,kind,round);
144
152
  const map=need(kind==='test-edits'?'测试内容':'修复内容',file);
@@ -24,7 +24,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
24
24
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('recover_final_review requires --allow-final-review-recovery and exact latest invocationId/packageDigest, previousInvocationStopped:true, and a nonempty reason. The legacy first continuation remains once-only. A further continuation additionally requires a fresh startup --final-review-recovery-invocation ID matching the latest unknown invocation, authorizing exactly one new call. Confirm the previous process stopped; this is a trusted host acknowledgment, not an automatic liveness check. Preparation dispatches nothing. Later final_review requires recovery permission and --allow-final-review; additional cycles require the same invocation binding after restart. Old records, task attempt, reviewed package and the original Review/N5/finish remain unchanged. No automatic retry, cancelled/complete-verdict recovery, missing-thread recovery, business-revision recovery or source-drift bypass. status adds a read-only progress projection, not authorization or current-source verification.\n');
25
25
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('rediagnose requires --allow-rediagnosis, the original resumed run at rediagnosis_required and a nonempty single-line reason up to 1000 UTF-8 bytes. It appends one history-bound diagnosis without repeating reproduction or overwriting cause-r1. A fresh cause review must publish cause-r2 even for a revised single-layer cause. Second rejection reaches rediagnosis_review_limit_reached. Interrupted rediagnosis or its review is not automatically retried or abandoned. Standalone only.\n');
26
26
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_step requires --allow-abandon, stage unknown, an eligible local pending kind, and a nonempty single-line reason up to 1000 UTF-8 bytes. It records the abandoned intent and returns to the required stage; a later separate action redoes the step. At most eight abandonments per run. Review, Learning writeback and handoff remain unavailable.\n');
27
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_review requires its own --allow-abandon-review flag (not --allow-abandon) and the same reason rules. Each run may abandon the cause review once and the second-round final review once, only while that registered review has no review result (interrupted, timed out, disconnected or cancelled); confirm the old reviewer stopped first. It records the abandoned invocation and returns to the review stage; the retry needs the original review flag, a fresh grant and a new reviewer thread. Reviews wait for the review configuration timeoutMs (default 900000), not the reproduction timeout.\n');
27
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_review requires its own --allow-abandon-review flag (not --allow-abandon) and the same reason rules. Each run may abandon each cause review round once (the first round and the post-rediagnosis round 2 separately) and the second-round final review once, only while that registered review has no review result (interrupted, timed out, disconnected or cancelled); confirm the old reviewer stopped first. It records the abandoned invocation and returns to the review stage; the retry needs the original review flag, a fresh grant and a new reviewer thread. Reviews wait for the review configuration timeoutMs (default 900000), not the reproduction timeout.\n');
28
28
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('N6 child configuration may include qaSource {feature, identity, packageDigest, testRunId, handoffDigest}; derive the separate fixed child identity with qaFixIdentity. It requires --allow-qa-fix in addition to existing action flags. Close the parent host first: the original specs-wide owner lock is shared. Creation/resume rechecks the current failed round, project, report and policy; the source is bound to the original fix configuration. This does not resume the parent or automatically rerun QA, and does not authorize provider calls, installation or Git.\n');
29
29
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Second-round retrospective uses the cumulative original baseline, including previously authored tests and Learning scope. It persists the current round reflection and reaches revision_handoff_ready or revision_learning_writeback_required; neither state completes the task or publishes a new handoff. From revision_handoff_ready, handoff publishes a separate a2 handoff containing cumulative changes, current reflection, original red evidence and prior review/Learning history; final_review_package then reads that bound package. Pending Learning blocks publication. final_review requires --allow-final-review, uses fresh-thread exclusions and carries prior findings; publish_review writes the original r2 evidence and review log, and check_n5 runs the original Learning-aware gate. Approval reaches revision_post_review_regression_required, not completion.\n');
30
30
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('prepare_revision requires --allow-repair and either a published first-round changes_requested review or an approved first-round review followed by a package-bound walkthrough result of failed. The latter preserves the approved verdict and carries separate walkthrough failure evidence; passed, blocked, unknown, or drifted evidence cannot authorize this repair. An approved first-round review followed by package-bound post-review regression defect_remaining or regressed can also prepare the second repair when all baseline commands produced complete results. The regression commands must match the first reviewed handoff; passed, inconclusive, unavailable or partial evidence is refused. Regression and walkthrough failure feedback are mutually exclusive and neither replaces the next independent review. It rereads project Learning and persists the second-round preparation in the original store, preserving first-round evidence. repair then uses the original business scope and findings with separate second-round records. regression requires --allow-regression and reruns the original test commands against the second repair, preserving the original red evidence. Success reaches revision_handoff_required, not completion; handoff and final_review use the second-round package; review evidence publication and N5 are connected; post_review_regression requires --allow-regression and reaches revision_closeout_required after the original checks; walkthrough requires --allow-walkthrough and binds the second-round package and identity; finish reuses the original closeout with --allow-finish, preserving first-round history and recording completion for attempt 2. Second-round learning_writeback requires --allow-learning-writeback, includes the resulting AGENTS.md in the cumulative review package and preserves prior Learning history; pending or unknown writeback cannot advance to handoff. A lost repair or regression result stays unknown and is not redispatched.\n');
@@ -64,16 +64,83 @@ test('original run rediagnoses after cause rejection, preserves history, and req
64
64
  await assert.rejects(owner.rediagnose({authorized:true,reason:'Again'}),{code:'fix_rediagnosis_unavailable'});
65
65
  assert.deepEqual(f.counts(),{calls:2,diagnoses:2});
66
66
  }));
67
- test('interrupted rediagnosis replays unknown and never repeats original reproduction or diagnosis',async t=>fixture(t,async f=>{
67
+ const revised={status:'diagnosed',rootCause:'Fixture revised cause',plan:'Fixture plan',affectedPaths:['value.mjs'],affectedModules:['value'],crossLayer:false};
68
+ const tooManyAlternatives={...revised,investigation:{boundaryAnalysis:null,
69
+ discardedAlternatives:[1,2,3,4].map(n=>({option:`Fixture option ${n}`,reason:'Fixture reason'}))}};
70
+ async function hostRediagnose(f,reason='Address F1'){
71
+ const owner=f.owner(),host=createFixHost({owner,config:{...f.options.configuration,...f.options},permissions:['--allow-rediagnosis']});
72
+ const input=new PassThrough();let output='',errors='';
73
+ const sink=new Writable({write(chunk,encoding,done){output+=chunk;done();}});
74
+ const errorOutput=new Writable({write(chunk,encoding,done){errors+=chunk;done();}});
75
+ input.end(JSON.stringify({requestId:'redo',operation:'rediagnose',reason})+'\n');
76
+ await serveCmAiHost({host,input,output:sink,errorOutput});
77
+ return {reply:JSON.parse(output),errors};
78
+ }
79
+ const ids=file=>JSON.parse(fs.readFileSync(file)).records.map(row=>row.id);
80
+ test('regression: invalid rediagnosis answer is invalid_diagnosis, stays pending, and a valid answer under the same intent reaches cause-r2',async t=>fixture(t,async f=>{
68
81
  const before=JSON.parse(fs.readFileSync(f.state)).records;
82
+ f.bridge.call=async kind=>{assert.equal(kind,'fix_diagnose');return tooManyAlternatives;};
83
+ f.reopen();
84
+ const rejected=await hostRediagnose(f);
85
+ assert.deepEqual(rejected.reply.error,{code:'host_request_failed'});
86
+ const diagnostic=JSON.parse(rejected.errors.trim().split('\n').at(-1));
87
+ assert.equal(diagnostic.code,'invalid_diagnosis');assert.match(diagnostic.reason,/investigation\.discardedAlternatives.*最多 3 项,实际 4 项/);
88
+ let owner=f.reopen();
89
+ assert.equal(owner.status().stage,'unknown');assert.equal(owner.status().pending,'rediagnosis');
90
+ const pendingIds=ids(f.state);assert.deepEqual(pendingIds.slice(before.length),['fix-rediagnosis-intent']);
91
+ await assert.rejects(owner.rediagnose({authorized:true,reason:'Retry'}),{code:'invalid_diagnosis'});
92
+ assert.deepEqual(ids(f.state),pendingIds);
93
+ let asked=0;f.bridge.call=async(kind,payload)=>{asked++;assert.equal(payload.reviewFeedback.verdict,'changes_requested');return revised;};
94
+ owner=f.reopen();
95
+ assert.equal((await hostRediagnose(f,'Resubmit valid answer')).reply.result.stage,'cause_review_required');
96
+ const next=JSON.parse(fs.readFileSync(f.state)).records;
97
+ assert.deepEqual(next.slice(0,before.length),before);
98
+ assert.deepEqual(next.slice(before.length).map(row=>row.id),['fix-rediagnosis-intent','fix-rediagnosis-result']);
99
+ assert.equal(next[before.length].payload.reason,'Address F1');
100
+ owner=f.reopen();assert.equal(owner.status().diagnosis.rootCause,'Fixture revised cause');
101
+ assert.equal((await f.review()).stage,'red_test_required');
102
+ assert.match(fs.readFileSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r2.md'),'utf8'),/round: 2\nverdict: approved/);
103
+ assert.equal(asked,1);assert.equal(f.counts().calls,2);
104
+ assert.equal(fs.readFileSync(path.join(f.code,'visits'),'utf8'),'1');
105
+ }));
106
+ for(const secondVerdict of ['approved','changes_requested'])test(`regression: an old journal ending in fix-rediagnosis-intent without a result resumes by re-asking under that intent (${secondVerdict})`,async t=>fixture(t,async f=>{
107
+ // Old runtime: intent appended, answer rejected inside the catch, nothing else written.
69
108
  f.bridge.call=async()=>{throw Error('Fixture lost result');};
70
109
  const result=await f.owner().rediagnose({authorized:true,reason:'Address F1'});
71
110
  assert.equal(result.stage,'unknown');assert.equal(result.pending,'rediagnosis');
72
- const owner=f.reopen();assert.equal(owner.status().pending,'rediagnosis');
111
+ const stuck=fs.readFileSync(f.state),stuckIds=ids(f.state);
112
+ assert.equal(stuckIds.at(-1),'fix-rediagnosis-intent');
113
+ let owner=f.reopen();
73
114
  assert.equal((await owner.advance({authorized:true})).stage,'unknown');
74
- await assert.rejects(owner.rediagnose({authorized:true,reason:'Retry'}),{code:'fix_rediagnosis_unavailable'});
75
- assert.deepEqual(JSON.parse(fs.readFileSync(f.state)).records.slice(0,before.length),before);
115
+ const host=createFixHost({owner,config:{...f.options.configuration,...f.options},permissions:['--allow-rediagnosis']});
116
+ const status=await host.handle({requestId:'s',operation:'status'});
117
+ assert.equal(status.progress.blocker,'rediagnosis_answer_required');assert.match(status.progress.nextAction,/rediagnose/);
118
+ assert.deepEqual(fs.readFileSync(f.state),stuck);
119
+ f.bridge.call=async()=>revised;
120
+ owner=f.reopen();
121
+ assert.equal((await owner.rediagnose({authorized:true,reason:'Resume pending rediagnosis'})).stage,'cause_review_required');
122
+ assert.deepEqual(ids(f.state),[...stuckIds,'fix-rediagnosis-result']);
123
+ assert.deepEqual(JSON.parse(fs.readFileSync(f.state)).records.slice(0,stuckIds.length),JSON.parse(stuck).records);
124
+ // The re-ask used the registered continuation: the review limit still applies.
125
+ const stage=secondVerdict==='approved'?'red_test_required':'rediagnosis_review_limit_reached';
126
+ assert.equal((await f.review()).stage,stage);
127
+ owner=f.reopen();assert.equal(owner.status().stage,stage);
128
+ await assert.rejects(owner.rediagnose({authorized:true,reason:'Again'}),{code:'fix_rediagnosis_unavailable'});
129
+ assert.equal(ids(f.state).filter(id=>id==='fix-rediagnosis-intent').length,1);
76
130
  assert.equal(fs.readFileSync(path.join(f.code,'visits'),'utf8'),'1');
131
+ },{secondVerdict}));
132
+ test('driver preflight refuses an invalid rediagnosis answer before starting the host',async t=>fixture(t,async f=>{
133
+ const config=path.join(f.root,'driver-config.json'),answers=path.join(f.root,'answers');fs.mkdirSync(answers);
134
+ fs.writeFileSync(config,JSON.stringify({specsRoot:f.specsRoot,identity:f.identity,reproduction:f.options.configuration.reproduction}));
135
+ fs.writeFileSync(path.join(answers,'learning.json'),JSON.stringify({status:'no_relevant_lesson',summary:'Fixture'}));
136
+ const run=file=>{fs.writeFileSync(path.join(answers,'diagnosis-rediagnosis.json'),JSON.stringify(file));
137
+ const script=`import {preflight} from ${JSON.stringify(new URL('./cm-fix-drive.mjs',import.meta.url).href)};preflight(${JSON.stringify({operation:'rediagnose',plan:{cwd:f.code,mode:'resume'},paths:{config,answers}})});`;
138
+ return spawnSync(process.execPath,['--input-type=module','-e',script],{encoding:'utf8'});};
139
+ const before=fs.readFileSync(f.state);
140
+ const refused=run(tooManyAlternatives);
141
+ assert.equal(refused.status,2);assert.match(refused.stderr,/diagnosis-rediagnosis\.json.*investigation\.discardedAlternatives.*最多 3 项,实际 4 项.*宿主未启动/);
142
+ assert.equal(run(revised).status,0);
143
+ assert.deepEqual(fs.readFileSync(f.state),before);
77
144
  }));
78
145
  for(const failure of ['source','evidence','reason'])test(`rediagnosis refuses ${failure} before registering a new effect`,async t=>fixture(t,async f=>{
79
146
  const before=fs.readFileSync(f.state);