@aibyzero/cm-workflow 0.16.6 → 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 (90) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +29 -0
  3. package/README.md +32 -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 +84 -9
  9. package/docs/user-guide.md +104 -0
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/cm-ai-admission.mjs +37 -11
  12. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +56 -17
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +172 -33
  15. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  16. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  17. package/runtime/js/cm-ai/drive-bootstrap.mjs +2 -2
  18. package/runtime/js/cm-ai/drive-core.mjs +17 -4
  19. package/runtime/js/cm-ai/durable-runner-state.mjs +29 -0
  20. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -3
  22. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  23. package/runtime/js/cm-ai/host-qa-executor.mjs +89 -19
  24. package/runtime/js/cm-ai/host-session.mjs +46 -6
  25. package/runtime/js/cm-ai/host-tool-bridge.mjs +15 -3
  26. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  27. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  28. package/runtime/js/cm-ai/operator-guidance.mjs +3 -0
  29. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  30. package/runtime/js/cm-ai/task-runner.mjs +6 -1
  31. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  32. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  33. package/runtime/js/cm-fix/execution.mjs +189 -148
  34. package/runtime/js/cm-fix/finish.mjs +2 -19
  35. package/runtime/js/cm-fix/investigation.mjs +25 -9
  36. package/runtime/js/cm-fix/log-events.mjs +29 -0
  37. package/runtime/js/cm-fix/metrics.mjs +3 -2
  38. package/runtime/js/cm-fix/progress.mjs +3 -1
  39. package/runtime/js/cm-prd/analysis.mjs +5 -2
  40. package/runtime/js/cm-prd/review-host.mjs +2 -1
  41. package/runtime/js/cm-test/recovery.mjs +4 -4
  42. package/runtime/js/notify-run.mjs +26 -0
  43. package/runtime/js/notify.mjs +388 -0
  44. package/runtime/model-efficiency.md +17 -0
  45. package/scripts/cm-ai-admission.mjs +14 -3
  46. package/scripts/cm-ai-batch-drive.mjs +2 -2
  47. package/scripts/cm-ai-batch-host.mjs +7 -2
  48. package/scripts/cm-ai-batch-run.mjs +11 -2
  49. package/scripts/cm-ai-batch-run.test.mjs +9 -1
  50. package/scripts/cm-ai-drive.mjs +18 -4
  51. package/scripts/cm-ai-drive.test.mjs +30 -0
  52. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  53. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  54. package/scripts/cm-ai-host.mjs +20 -8
  55. package/scripts/cm-ai-host.test.mjs +88 -0
  56. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  57. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  58. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +77 -4
  59. package/scripts/cm-ai-run.mjs +36 -5
  60. package/scripts/cm-fix-abandon.test.mjs +89 -3
  61. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  62. package/scripts/cm-fix-drive.mjs +9 -1
  63. package/scripts/cm-fix-host.mjs +1 -1
  64. package/scripts/cm-fix-large-log.test.mjs +113 -0
  65. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  66. package/scripts/cm-host-qa-executor.test.mjs +429 -3
  67. package/scripts/cm-log-event.mjs +53 -6
  68. package/scripts/cm-notify.test.mjs +468 -0
  69. package/scripts/cm-patrol.mjs +83 -0
  70. package/scripts/cm-patrol.test.mjs +161 -0
  71. package/scripts/cm-prd-host.mjs +13 -2
  72. package/scripts/cm-prd-host.test.mjs +4 -0
  73. package/scripts/cm-prd-review-host.test.mjs +17 -0
  74. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  75. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  76. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  77. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  78. package/scripts/cm-token-report.mjs +497 -0
  79. package/scripts/cm-token-report.test.mjs +346 -0
  80. package/skills/cm-ai/SKILL.md +7 -3
  81. package/skills/cm-ai/references/N1-init.md +1 -1
  82. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  83. package/skills/cm-ai/references/js-host-modes.md +90 -0
  84. package/skills/cm-ai/references/js-host-qa-recovery.md +110 -0
  85. package/skills/cm-ai/references/js-host-recovery.md +199 -0
  86. package/skills/cm-ai/references/js-host.md +69 -330
  87. package/skills/cm-fix/SKILL.md +2 -0
  88. package/skills/cm-fix/references/js-host.md +16 -9
  89. package/skills/cm-prd/SKILL.md +7 -4
  90. package/skills/cm-prd/references/spec-self-check.md +3 -1
@@ -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
+ });
@@ -20,6 +20,7 @@ import {recordEffectAbandonment} from '../runtime/js/cm-ai/effect-abandon-log.mj
20
20
  import {reviewConsumedHandoff,reviewedHandoffConflict} from '../runtime/js/cm-ai/host-handoff.mjs';
21
21
  import {RUN_ID_RULE,validRunId} from './cm-log-event.mjs';
22
22
  import {JOURNAL_PAYLOAD_LIMIT,boundedReason} from '../runtime/js/cm-ai/effect-contract.mjs';
23
+ import {protectedScopePaths} from '../runtime/js/cm-ai/developer-adapter.mjs';
23
24
  import {closeoutPolicyCandidates} from '../runtime/js/cm-ai/knowledge-closeout.mjs';
24
25
 
25
26
  const usage='cm-ai-run.mjs serve --config RUN_DEFINITION.json --mode create|resume (no provider dispatch)\nNew runs bind approved specification material from specsDir; requirements may be [] or supplemental code-project files. Manifest drift blocks as spec_drift; legacy journals retain their original format.';
@@ -114,7 +115,7 @@ export async function createCodexExecution(configuration,authority){
114
115
  // original checks/handoff/Review. The semantic bridge never writes it.
115
116
  const {isFinalCmAiTask}=await import('../runtime/js/cm-ai/cm-ai-admission.mjs');
116
117
  const sync=documentationPaths.length>0&&isFinalCmAiTask({specsDir:specsRoot,codeProject:config.codeProject,
117
- feature:workflowDefinition.feature,taskId:bound.identity.taskId});
118
+ feature:workflowDefinition.feature,taskId:bound.identity.taskId,featureSelection:workflowDefinition.featureSelection?.feature});
118
119
  const protectedWorker=sync?(request,control)=>worker({...request,prompt:
119
120
  'Before returning, inspect and synchronize these already-approved ordinary documentation paths with the implemented behavior. '
120
121
  +'Keep accurate unchanged documents unchanged. No extra scope or protected instruction writes. '
@@ -150,6 +151,7 @@ export function validateRunDefinition(input){
150
151
  const keys=['version','specsDir','codeProject','feature','identity','scope','requirements'];
151
152
  if(value&&Object.hasOwn(value,'codeProjects'))keys.push('codeProjects');
152
153
  if(value&&Object.hasOwn(value,'taskSelection'))keys.push('taskSelection');
154
+ if(value&&Object.hasOwn(value,'featureSelection'))keys.push('featureSelection');
153
155
  if(!value||typeof value!=='object')fail('invalid_config: expected an object');
154
156
  const unexpected=Object.keys(value).filter(key=>!keys.includes(key));
155
157
  const missing=keys.filter(key=>!Object.hasOwn(value,key));
@@ -172,6 +174,11 @@ export function validateRunDefinition(input){
172
174
  if(Object.hasOwn(value,'taskSelection')&&(!value.taskSelection||value.taskSelection.version!==1
173
175
  ||Object.keys(value.taskSelection).sort().join(',')!=='taskId,version'
174
176
  ||value.taskSelection.taskId!==value.identity.taskId))fail('invalid_task_selection');
177
+ // Explicit batch choice: run this approved feature even while an earlier one
178
+ // has pending tasks. Bound into the definition, so it is part of the run.
179
+ if(Object.hasOwn(value,'featureSelection')&&(!value.featureSelection||value.featureSelection.version!==1
180
+ ||Object.keys(value.featureSelection).sort().join(',')!=='feature,version'
181
+ ||value.featureSelection.feature!==value.feature))fail('invalid_feature_selection');
175
182
  for(const key of ['scope','requirements']){
176
183
  if(!Array.isArray(value[key])||(!value[key].length&&!(key==='requirements'))||value[key].length>256
177
184
  ||value[key].some(p=>typeof p!=='string'||!p||p.includes('\\')||p.includes('\0')
@@ -185,6 +192,18 @@ export function validateRunDefinition(input){
185
192
  }
186
193
  return value;
187
194
  }
195
+ // Read-only, shared by every create entry before it locks, logs or builds an
196
+ // execution: the single-task host, openControlRun and the batch owner.
197
+ export function assertCreatableScope(scope){
198
+ const paths=protectedScopePaths(scope);
199
+ if(paths.length)throw Object.assign(new Error('protected_scope'),{code:'protected_scope',paths,reason:protectedScopeReason(paths)});
200
+ }
201
+ export function protectedScopeReason(paths){
202
+ const listed=paths.slice(0,20).join('、')+(paths.length>20?` 等 ${paths.length} 个`:'');
203
+ return `任务 scope 含受保护路径:${listed}。开发者不能写项目规则(AGENTS.md、CLAUDE.md、.claude/、.codex/)、`
204
+ +'tasks.md、.cm-* 或审查记录;未建运行,未写任何运行记录。从 scope 移除这些路径后重新生成运行定义再 create;'
205
+ +'规则文件的修改走 docs/js-workflow-control.md「项目规则文件的修改通道」。';
206
+ }
188
207
  // Create-time only: an existing journal keeps resuming (and can be abandoned)
189
208
  // exactly as before, while a new run can no longer strand its first develop
190
209
  // effect on a run ID the run log refuses.
@@ -235,6 +254,11 @@ async function openControlRunOwned(definition,mode,execution=null,{rerunUnknownQ
235
254
  const {conversationProtection,externalConversationDefinition}=await import('../runtime/js/cm-ai/host-conversation-execution.mjs');
236
255
  if(!['create','resume'].includes(mode))fail('invalid_mode');
237
256
  if(mode==='create')assertCreatableRunId(definition?.identity);
257
+ // The developer adapter refuses these paths on every dispatch. Refuse the
258
+ // run here, before any journal, intent or execution directory exists, so it
259
+ // cannot strand its first develop effect. A bootstrap run's own instruction
260
+ // paths are checked by createHostBootstrap against its business scope.
261
+ if(mode==='create'&&!execution?.bootstrap)assertCreatableScope(definition?.scope);
238
262
  if(supersedeReason!==null&&mode!=='create')fail('supersede_unavailable');
239
263
  if(allowAbandonEffect&&mode!=='resume')fail('effect_abandon_unavailable');
240
264
  if(allowBootstrapReviewRecovery&&mode!=='resume')fail('bootstrap_review_recovery_unavailable');
@@ -250,7 +274,7 @@ async function openControlRunOwned(definition,mode,execution=null,{rerunUnknownQ
250
274
  ||(rerunUnknownQa||rerunBlockedQa)&&(mode!=='resume'||!execution?.qaExecutor))fail('qa_recovery_authorization_required');
251
275
  const {openTaskExecutionStore}=await import('../runtime/js/cm-ai/task-owner.mjs');
252
276
  const {createCmAiHost}=await import('../runtime/js/cm-ai/host.mjs');
253
- const {inspectCmAiAdmission,matchesCmAiTaskSelection,explainCmAiTaskSelection}=await import('../runtime/js/cm-ai/cm-ai-admission.mjs');
277
+ const {inspectCmAiAdmission,matchesCmAiTaskSelection,explainCmAiTaskSelection,selectedFeature}=await import('../runtime/js/cm-ai/cm-ai-admission.mjs');
254
278
  const {captureReviewBaseline}=await import('../runtime/js/cm-ai/review-package.mjs');
255
279
  if(execution!==null){
256
280
  const {shape,json,validCallTimeout}=await import('../runtime/js/cm-ai/effect-contract.mjs');
@@ -299,15 +323,21 @@ async function openControlRunOwned(definition,mode,execution=null,{rerunUnknownQ
299
323
  if(selectedRoots){
300
324
  if(!execution||conversationProtection(execution)===null)fail('multi_root_protection_required');
301
325
  for(const root of definition.codeProjects){
302
- const selected=inspectCmAiAdmission({specsDir,codeProject:root});
326
+ const selected=inspectCmAiAdmission({specsDir,codeProject:root,...selectedFeature(definition.featureSelection?.feature)});
303
327
  if(mode==='create'&&!matchesCmAiTaskSelection(selected,feature,identity.taskId,selection))
304
328
  return {blocked:selected,close:()=>{}};
305
329
  }
306
330
  }
307
331
  const developer=execution?.documentationSync
308
332
  ?(await import('../runtime/js/cm-ai/host-documentation.mjs')).withHostDocumentation({developer:execution.developer,
309
- documentationSync:execution.documentationSync,specsDir,codeProject,feature,scope,parallelSelection:selection}):execution?.developer;
310
- const admission=inspectCmAiAdmission({specsDir,codeProject});
333
+ documentationSync:execution.documentationSync,specsDir,codeProject,feature,scope,parallelSelection:selection,
334
+ featureSelection:definition.featureSelection?.feature}):execution?.developer;
335
+ const admission=inspectCmAiAdmission({specsDir,codeProject,...selectedFeature(definition.featureSelection?.feature)});
336
+ // An explicitly selected feature with nothing left never creates a run, even
337
+ // when the project as a whole is complete.
338
+ if(mode==='create'&&definition.featureSelection&&admission.requestedFeatureComplete===feature)
339
+ throw Object.assign(new Error('task_selection_mismatch'),{code:'task_selection_mismatch',
340
+ reason:explainCmAiTaskSelection({...admission,state:'ready'},{feature,taskId:identity.taskId,selection})});
311
341
  if(mode==='create'&&admission.state!=='ready')return {blocked:admission,close:()=>{}};
312
342
  if(mode==='create'&&!matchesCmAiTaskSelection(admission,feature,identity.taskId,selection))
313
343
  throw Object.assign(new Error('task_selection_mismatch'),{code:'task_selection_mismatch',
@@ -433,6 +463,7 @@ async function openControlRunOwned(definition,mode,execution=null,{rerunUnknownQ
433
463
  taskLearning:{feature,hostHandoff:true}})},
434
464
  // The entry validates the declaration (single line, with --rerun-blocked-qa) before any durable write.
435
465
  entry:{specsDir,codeProject,feature,identity,rerunUnknownQa,rerunBlockedQa,
466
+ ...(definition.featureSelection?{featureSelection:definition.featureSelection.feature}:{}),
436
467
  ...(knowledgeCloseout===null?{}:{knowledgeCloseout,...(definition.codeProjects?{codeProjects:definition.codeProjects}:{})}),
437
468
  ...(qaEnvironmentFailure===null?{}:{qaEnvironmentFailure}),allowAbandonReview,allowAbandonEffect,allowBootstrapReviewRecovery,...(holdRevision?{holdRevision}:{}),...(selection===null?{}:{parallelSelection:selection}),...(execution===null?{}:{hostDecision:execution.hostDecision,
438
469
  ...Object.fromEntries(['developmentAttempt','hostDecisionProvider','qaDecisionProvider','qaLogHome','qaExecutor','applicableAgentFiles','documentationProvider','documentationResult'].filter(key=>Object.hasOwn(execution,key)).map(key=>[key,execution[key]]))})},
@@ -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');
@@ -0,0 +1,113 @@
1
+ // A project's 运行日志.jsonl only grows. Past 1 MiB, cm-fix read it whole under
2
+ // the review-material limit and every fix run failed at its completion
3
+ // projection, including each later resume (2026-10-07, AI潮
4
+ // api-native-reading-fix-story-return: check_n5 limit_exceeded, then every resume).
5
+ import test from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
11
+ import {createFixHost} from '../runtime/js/cm-fix/host.mjs';
12
+ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
13
+ import {eventsAt} from '../runtime/js/cm-fix/finish.mjs';
14
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
15
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
16
+ import {readReviewSourceFiles} from '../runtime/js/cm-ai/review-package.mjs';
17
+
18
+ const MiB=1024*1024;
19
+ // Valid rows of other runs and workflows, as a long-lived project accumulates.
20
+ function growLog(file,bytes){
21
+ const filler='x'.repeat(900);let written=0,index=0;
22
+ const lines=[];
23
+ while(written<bytes){
24
+ const line=JSON.stringify({schema_version:1,workflow:index%2?'cm-ai':'cm-prd',event:'progress',phase:'start',
25
+ run_id:`other-run-${index}`,at:'2026-10-01T00:00:00Z',detail:filler})+'\n';
26
+ lines.push(line);written+=Buffer.byteLength(line);index++;
27
+ }
28
+ fs.appendFileSync(file,lines.join(''));
29
+ }
30
+
31
+ test('cm-fix completes check_n5, post_review_regression, walkthrough and finish with a run log above 1 MiB',{timeout:120000},async t=>{
32
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-large-log-')));
33
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
34
+ const logHome=process.env.CM_WORKFLOW_LOG_HOME;process.env.CM_WORKFLOW_LOG_HOME=path.join(root,'mirror');
35
+ t.after(()=>{if(logHome===undefined)delete process.env.CM_WORKFLOW_LOG_HOME;else process.env.CM_WORKFLOW_LOG_HOME=logHome;
36
+ fs.rmSync(root,{recursive:true,force:true});});
37
+ fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
38
+ fs.writeFileSync(path.join(cwd,'red.mjs'),"import {value} from './value.mjs';if(value!==2){console.error('BUG');process.exit(1)}");
39
+ fs.writeFileSync(path.join(cwd,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1)");
40
+ fs.writeFileSync(path.join(cwd,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
41
+ const config={identity:{repositoryId:'fixture',runId:'large-log',taskId:'T-FIX-large-log',attempt:1},defect:'Wrong value',
42
+ reproduction:{cwd,command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000},
43
+ redTest:{cwd,testFiles:['red.mjs'],command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000},
44
+ baseline:{cwd,testFiles:['existing.mjs'],commands:[{id:'existing',command:[process.execPath,'existing.mjs']}],timeoutMs:2000},
45
+ repair:{scope:['value.mjs'],requirements:['value.mjs']},
46
+ walkthrough:{timeoutMs:2000,flows:[{id:'value',modules:['value'],steps:['Read value'],expected:['value is 2'],kind:'commands',command:[process.execPath,'red.mjs']}]}};
47
+ const permissions=['--allow-reproduction','--allow-red-test','--allow-baseline','--allow-repair','--allow-regression','--allow-final-review','--allow-walkthrough','--allow-finish'];
48
+ const model='synthetic',review={model,disabledSkills:[],preflight:{passed:true,cli_model:model,prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd,model,disabledSkills:[]})}};
49
+ let calls=0;
50
+ const workerFactory=()=>async({prompt},{onEvent})=>{
51
+ calls++;const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);
52
+ onEvent({event:'thread.started',provider_thread:`thread-${calls}`});
53
+ for(const event of [{event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},
54
+ {event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
55
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:data.reviewPackage.packageDigest,examinedPaths:data.examinedPaths,findings:[],summary:'Synthetic'}};
56
+ };
57
+ const reviewHost=createFixReviewHost({codeProject:cwd,hostContextId:'fixture-host',review,permissions,workerFactory});
58
+ const configuration={hostContextId:'fixture-host',...config,causeReview:reviewHost.reviewer};delete configuration.identity;
59
+ const learning={contextDigest:digest([]),files:[],application:{contextDigest:digest([]),status:'no_relevant_lesson',summary:'No fixture instructions'}};
60
+ const bridge={async call(kind){
61
+ if(kind==='fix_diagnose')return {status:'diagnosed',rootCause:'Wrong value',plan:'Correct value',affectedPaths:['value.mjs'],affectedModules:['value'],crossLayer:false,investigation:{discardedAlternatives:[],boundaryAnalysis:null}};
62
+ if(kind==='fix_repair'){fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=2;');return {outcome:'repaired'};}
63
+ if(kind==='fix_retrospective')return {status:'no_new_lesson',candidates:[],reason:null};
64
+ throw Error(kind);
65
+ }};
66
+ const options={specsRoot,identity:config.identity,configuration,create:true};
67
+ const execution={...reviewHost.execution,bridge,prepare:async()=>learning};
68
+ let owner=openFixExecution(options,execution);t.after(()=>owner.close());
69
+ const hostFor=current=>createFixHost({owner:current,config:{...config,specsRoot},permissions,authority:reviewHost.authority,finalAuthority:reviewHost.finalAuthority});
70
+ let host=hostFor(owner);
71
+ const run=async operation=>{const result=await host.handle({requestId:operation,operation});assert(!result?.error,`${operation}: ${JSON.stringify(result)}`);return result;};
72
+ for(const operation of ['advance','red_test','baseline','repair','regression','retrospective','handoff','final_review','publish_review'])await run(operation);
73
+ const log=path.join(specsRoot,'运行日志.jsonl');
74
+ growLog(log,MiB+256*1024);
75
+ assert(fs.statSync(log).size>MiB);
76
+ // The old whole-file read: exactly the limit this run would have hit.
77
+ assert.throws(()=>readReviewSourceFiles(specsRoot,['运行日志.jsonl']),{code:'limit_exceeded'});
78
+ const ownRows=eventsAt(specsRoot).filter(row=>row.run_id===config.identity.runId);
79
+ assert(ownRows.length>0&&eventsAt(specsRoot).every(row=>row.workflow==='cm-fix'));
80
+ await run('check_n5');
81
+ // A resume opens the owner and projects completion from the log again.
82
+ owner.close();owner=openFixExecution({...options,create:false},execution);host=hostFor(owner);
83
+ for(const operation of ['post_review_regression','walkthrough'])await run(operation);
84
+ growLog(log,64*1024);
85
+ const finished=await run('finish');
86
+ assert.equal(finished.stage??finished.result?.stage,'completed',JSON.stringify(finished));
87
+ owner.close();owner=openFixExecution({...options,create:false},execution);
88
+ assert.equal(owner.status().stage,'completed');
89
+ // Completion still binds this run only: the dossier row and the completion events are its own.
90
+ const done=eventsAt(specsRoot).filter(row=>row.run_id===config.identity.runId&&['task_done','run_done'].includes(row.event));
91
+ assert.deepEqual(done.map(row=>row.event),['task_done','run_done']);
92
+ assert(calls>=1);
93
+ });
94
+
95
+ test('the streamed log reader keeps the single-link, no-symlink and plain-JSON guarantees of the old reader',async t=>{
96
+ const {readStableLogRows}=await import('../runtime/js/cm-ai/log-rows.mjs');
97
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-stable-log-')));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
98
+ const log=path.join(root,'运行日志.jsonl');
99
+ // An accepted historical row of another workflow nested deeper than the host
100
+ // object normalizer allows (40): it must not block a cm-fix read.
101
+ let deep={};for(let index=0;index<60;index++)deep={nested:deep};
102
+ fs.writeFileSync(log,[{workflow:'cm-prd',run_id:'other',data:deep},{workflow:'cm-fix',run_id:'mine',n:1},{workflow:'cm-fix',run_id:'mine',n:2}]
103
+ .map(row=>JSON.stringify(row)).join('\n')+'\n\n');
104
+ const pick=row=>row.workflow==='cm-fix';
105
+ assert.deepEqual(readStableLogRows(log,pick,'fix_log_failed').map(row=>row.n),[1,2]);
106
+ const link=path.join(root,'hard.jsonl');fs.linkSync(log,link);
107
+ assert.throws(()=>readStableLogRows(log,pick,'fix_log_failed'),{code:'fix_log_failed'});
108
+ fs.unlinkSync(link);
109
+ const symlink=path.join(root,'symlink.jsonl');fs.symlinkSync(log,symlink);
110
+ assert.throws(()=>readStableLogRows(symlink,pick,'fix_log_failed'),{code:'fix_log_failed'});
111
+ fs.appendFileSync(log,'{not json\n');
112
+ assert.throws(()=>readStableLogRows(log,pick,'fix_log_failed'),{code:'fix_log_failed'});
113
+ });