@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
@@ -36,25 +36,36 @@ function readPlan(configuration,selectCompleted=true) {
36
36
  need(validateTestCases(contract).length===0&&contract.feature===feature.replace(/^\d+\./,''),'test_cases_invalid');
37
37
  cases=contract.cases;
38
38
  }
39
- const context=selectCompleted?inspectCmAiQaTaskContext({specsDir,codeProject,feature}):{completed:[],pending:0};
39
+ const context=selectCompleted?inspectCmAiQaTaskContext({specsDir,codeProject,feature}):{completed:[],pending:0,dropped:[]};
40
40
  const completed=new Set(context.completed.filter(task=>task.feature===feature).map(task=>task.id));
41
- const applicable=cases.filter(item=>item.blocking||config.policies.tests.includes(item.kind));
41
+ // A case bound only to [DROPPED] tasks has no deliverable to verify (its AC is
42
+ // deferred with the task), blocking or not: it is recorded, never planned.
43
+ const dropped=new Set(context.dropped);
44
+ const droppedOnly=item=>item.taskIds.length>0&&item.taskIds.every(taskId=>dropped.has(taskId));
45
+ // Identified before the test-kind policy, so a command declared only for them is never scheduled.
46
+ const droppedCases=cases.filter(droppedOnly).map(item=>({id:item.id,taskIds:item.taskIds}));
47
+ const droppedIds=new Set(droppedCases.map(item=>item.id));
48
+ const applicable=cases.filter(item=>!droppedIds.has(item.id)&&(item.blocking||config.policies.tests.includes(item.kind)));
42
49
  const deferred=context.pending===0?[]:applicable.map(item=>({id:item.id,
43
50
  taskIds:item.taskIds.filter(taskId=>!completed.has(taskId))})).filter(item=>item.taskIds.length>0);
44
51
  const deferredIds=new Set(deferred.map(item=>item.id));
45
52
  const selected=applicable.filter(item=>!deferredIds.has(item.id));
46
53
  const wanted=new Set(selected.filter(item=>item.kind==='logic').map(item=>item.id));
47
- const scheduled=commands.filter(item=>(config.policies.tests.includes('commands')
48
- &&(context.pending===0||item.caseIds.length===0))||item.caseIds.some(caseId=>wanted.has(caseId)));
54
+ // A command declared only for such cases is not run for them either.
55
+ const droppedCommands=commands.filter(item=>item.caseIds.length>0&&item.caseIds.every(caseId=>droppedIds.has(caseId)))
56
+ .map(item=>({id:item.id,caseIds:item.caseIds}));
57
+ const scheduled=commands.filter(item=>!droppedCommands.some(other=>other.id===item.id)&&((config.policies.tests.includes('commands')
58
+ &&(context.pending===0||item.caseIds.length===0))||item.caseIds.some(caseId=>wanted.has(caseId))));
49
59
  for(const item of commands)for(const caseId of item.caseIds)
50
60
  need(cases.some(candidate=>candidate.id===caseId&&candidate.kind==='logic'),'qa_command_mapping_invalid');
51
61
  const modes=order[config.project.workflow].filter(mode=>mode==='commands'
52
- ?scheduled.length>0||(config.policies.tests.includes('commands')&&(context.pending===0||commands.length===0))
62
+ ?scheduled.length>0||(config.policies.tests.includes('commands')&&(context.pending===0||commands.length===droppedCommands.length))
53
63
  :selected.some(item=>item.kind===mode));
54
64
  const noApplicableCases=context.pending>0&&selected.length===0&&scheduled.length===0;
55
65
  if(noApplicableCases)modes.splice(0,modes.length,'commands');
56
66
  return json({config,cases:selected,...(selectCompleted?{deferred_cases:deferred}:{}),commands:scheduled,modes,
57
- ...(noApplicableCases?{no_applicable_cases:true}:{})});
67
+ ...(noApplicableCases?{no_applicable_cases:true}:{}),...(droppedCases.length?{dropped_task_cases:droppedCases}:{}),
68
+ ...(droppedCommands.length?{dropped_task_commands:droppedCommands}:{})});
58
69
  }
59
70
 
60
71
  function logStep(configuration,binding,event,phase,data,detail) {
@@ -78,20 +89,50 @@ function logStep(configuration,binding,event,phase,data,detail) {
78
89
  feature:configuration.feature,identity:binding.identity,caseId:data.case_id,phase});
79
90
  }
80
91
 
92
+ // Only one kind of slip is asked back: a PASS on the registered environment
93
+ // whose evidence files are unusable (outside {specs}/.reviews, missing or
94
+ // empty). A FAIL, a BLOCKED, another environment or a failed cleanup is never
95
+ // asked again: those stay as judged, and only an explicit recovery reruns them.
96
+ const CORRECTION_INSTRUCTION='Only the evidence list of the previous PASS answer can be corrected. Evidence must be non-empty '
97
+ +'files inside the .reviews directory of the specs root (for example .reviews/qa-evidence/); copy the files you observed '
98
+ +'there and answer again. Keep the verdict, environment and cleanup you actually observed; if you no longer stand by the '
99
+ +'PASS, answer FAIL or BLOCKED.';
100
+ // Every other condition of the verdict must already hold, so the correction can
101
+ // only ever change the evidence: same environment, cleanup as the case requires.
102
+ function answerProblems(configuration,observed,environment,item){
103
+ if(observed.verdict!=='PASS'||observed.cleanup==='failed'||(item.cleanup.length>0&&observed.cleanup!=='completed')
104
+ ||digest(observed.environment)!==digest(environment))return [];
105
+ const problems=[];let files=null;
106
+ try{files=evidence(observed.evidence);}catch{problems.push({code:'evidence_list_invalid'});}
107
+ for(const file of files??[]){
108
+ try{if(fs.statSync(reportFile(configuration.specsDir,file)).size===0)problems.push({code:'evidence_empty',path:file});}
109
+ catch{problems.push({code:'evidence_outside_reviews_or_missing',path:file});}
110
+ }
111
+ return problems;
112
+ }
113
+
81
114
  function evidence(raw) {
82
115
  const result=json(raw);need(Array.isArray(result)&&result.length>0&&result.length<=32,'qa_evidence_required');
83
116
  for(const item of result){text(item);need(item.length<=2000&&!item.includes('\0'),'qa_evidence_required');}
84
117
  return result;
85
118
  }
86
119
 
87
- function saveReport(configuration,binding,rows,summary,deferred) {
120
+ // Cases (and commands declared only for them) bound only to [DROPPED] tasks:
121
+ // listed as NOT_APPLICABLE beside the rows, never counted as PASS/FAIL/BLOCKED.
122
+ const notApplicable=plan=>[
123
+ ...(plan.dropped_task_cases??[]).map(item=>({...item,verdict:'NOT_APPLICABLE',reason:`bound only to dropped tasks: ${item.taskIds.join(', ')}`})),
124
+ ...(plan.dropped_task_commands??[]).map(item=>({...item,kind:'commands',verdict:'NOT_APPLICABLE',
125
+ reason:`declared only for cases bound only to dropped tasks: ${item.caseIds.join(', ')}`}))];
126
+
127
+ function saveReport(configuration,binding,rows,summary,plan) {
88
128
  const reviews=path.join(configuration.specsDir,'.reviews'),stat=fs.lstatSync(reviews);
89
129
  need(stat.isDirectory()&&!stat.isSymbolicLink()&&fs.realpathSync(reviews)===reviews,'qa_report_invalid');
90
130
  const target=path.join(reviews,`${binding.testRunId}-execution.md`);
91
131
  const body=Buffer.from(`# CM QA execution report\n\nOverall: ${summary.result}\n\n`
92
132
  +'Counts are declared command checks plus selected cases, not framework test totals.\n'
93
133
  +'Static verdicts are retained separately; only observed command/browser evidence counts as PASS.\n\n'
94
- +`## deferred_cases\n\n${JSON.stringify(deferred,null,2)}\n\n`
134
+ +`## deferred_cases\n\n${JSON.stringify(plan.deferred_cases,null,2)}\n\n`
135
+ +(notApplicable(plan).length?`## not_applicable\n\n${JSON.stringify(notApplicable(plan),null,2)}\n\n`:'')
95
136
  +rows.map(row=>`## ${row.id}\n\n${JSON.stringify(row,null,2)}\n`).join('\n'));
96
137
  need(body.length<=1024*1024,'limit_exceeded');
97
138
  const fd=fs.openSync(target,fs.constants.O_CREAT|fs.constants.O_EXCL|fs.constants.O_WRONLY|fs.constants.O_NOFOLLOW,0o600);
@@ -177,10 +218,11 @@ export function createHostQaExecutor(options) {
177
218
  for(const stage of plan.modes){
178
219
  const routed=route(stage==='browser'?'browser_qa':'tester');
179
220
  if(stage==='commands'){
221
+ const dropped=notApplicable(plan).map(item=>`${item.id}: ${item.reason}`);
180
222
  if(plan.no_applicable_cases)rows.push({id:'no-applicable-cases',kind:'commands',verdict:'BLOCKED',
181
223
  evidence:['all applicable cases are bound to unfinished tasks; deferred to feature completion',
182
- ...plan.deferred_cases.map(item=>`${item.id}: ${item.taskIds.join(', ')}`)]});
183
- else if(!plan.commands.length)rows.push({id:'commands-unavailable',kind:'commands',verdict:'BLOCKED',evidence:['No declared project test command']});
224
+ ...plan.deferred_cases.map(item=>`${item.id}: ${item.taskIds.join(', ')}`),...dropped]});
225
+ else if(!plan.commands.length)rows.push({id:'commands-unavailable',kind:'commands',verdict:'BLOCKED',evidence:['No declared project test command',...dropped]});
184
226
  for(const command of plan.commands){
185
227
  notCancelled();
186
228
  const check=createHostCheck({cwd:roots?command.codeProject:configuration.codeProject,commands:[{id:command.id,command:command.command}],
@@ -227,11 +269,32 @@ export function createHostQaExecutor(options) {
227
269
  hostRequestTimeout=true;
228
270
  observed={verdict:'BLOCKED',evidence:['host_request_timeout'],environment,cleanup:'failed'};
229
271
  }
230
- notCancelled();shape(observed,['verdict','evidence','environment','cleanup']);
231
- need(['PASS','FAIL','BLOCKED'].includes(observed.verdict),'qa_verdict_invalid');
232
- need(['completed','not_needed','failed'].includes(observed.cleanup),'qa_cleanup_required');
233
- let evidenceProblem=null;
234
- if(observed.verdict!=='BLOCKED')try{
272
+ const validAnswer=()=>{notCancelled();shape(observed,['verdict','evidence','environment','cleanup']);
273
+ need(['PASS','FAIL','BLOCKED'].includes(observed.verdict),'qa_verdict_invalid');
274
+ need(['completed','not_needed','failed'].includes(observed.cleanup),'qa_cleanup_required');};
275
+ validAnswer();
276
+ // One correction round inside the same case, before any verdict is
277
+ // recorded, so a form slip does not spend a whole QA round as BLOCKED.
278
+ let answerCorrection=null;
279
+ const problems=answered?answerProblems(configuration,observed,environment,item):[];
280
+ if(problems.length){
281
+ // The first answer is kept: the correction may only replace its evidence.
282
+ answerCorrection={problems,first:{verdict:observed.verdict,environment:observed.environment,cleanup:observed.cleanup}};
283
+ try{observed=json(await browser(freeze({...request,correction:{problems,instruction:CORRECTION_INSTRUCTION}}),signal));}
284
+ catch(error){
285
+ if(error.code!=='host_request_timeout')throw error;
286
+ hostRequestTimeout=true;answered=false;
287
+ observed={verdict:'BLOCKED',evidence:['host_request_timeout'],environment,cleanup:'failed'};
288
+ }
289
+ validAnswer();
290
+ }
291
+ // A corrected PASS must keep everything but its evidence; any other
292
+ // change to the answer is not a correction and does not pass.
293
+ const changedAnswer=answerCorrection!==null&&observed.verdict==='PASS'
294
+ &&digest({environment:observed.environment,cleanup:observed.cleanup})
295
+ !==digest({environment:answerCorrection.first.environment,cleanup:answerCorrection.first.cleanup});
296
+ let evidenceProblem=changedAnswer?'qa_correction_changed_answer':null;
297
+ if(observed.verdict!=='BLOCKED'&&evidenceProblem===null)try{
235
298
  for(const file of evidence(observed.evidence)){
236
299
  const target=reportFile(configuration.specsDir,file);
237
300
  need(fs.statSync(target).size>0,'qa_evidence_required');
@@ -245,11 +308,15 @@ export function createHostQaExecutor(options) {
245
308
  rows.push({id:item.id,kind:'browser',origin:item.origin,blocking:item.blocking,verdict,
246
309
  evidence:observed.evidence,evidenceProblem,environment:observed.environment,cleanup:observed.cleanup,
247
310
  ...(hostRequestTimeout?{hostRequestTimeout:true}:{}),
311
+ ...(answerCorrection?{answerCorrection}:{}),
248
312
  ...(answered&&observed.verdict==='BLOCKED'?{hostDeclaredBlocked:true}:{})});
249
313
  // The durable log row, appended now through the writer, is the record
250
314
  // that the session itself answered BLOCKED; the report only mirrors it.
251
315
  logStep(configuration,binding,'test_run',verdict==='BLOCKED'?'case_blocked':'case_complete',
252
- {case_id:item.id,result:verdict,...(answered&&observed.verdict==='BLOCKED'?{host_declared_blocked:true}:{})},
316
+ {case_id:item.id,result:verdict,...(answered&&observed.verdict==='BLOCKED'?{host_declared_blocked:true}:{}),
317
+ // Whether this BLOCKED is a host request that timed out without an
318
+ // answer; --rerun-unknown-qa reads it after a whole-call timeout.
319
+ ...(verdict==='BLOCKED'?{host_request_timeout:hostRequestTimeout&&!answered}:{})},
253
320
  'QA browser case finished');
254
321
  }
255
322
  }
@@ -274,14 +341,17 @@ export function createHostQaExecutor(options) {
274
341
  if(row.verdict==='BLOCKED'&&row.staticVerdict==='SUPPORTED'&&!needsConfirmation
275
342
  &&observed.some(result=>result?.outcome==='unavailable'))row.commandUnavailable=true;
276
343
  }
277
- if(rows.length===0)rows.push({id:'qa-unavailable',kind:'commands',verdict:'BLOCKED',evidence:['No executable QA contract']});
344
+ if(rows.length===0)rows.push({id:'qa-unavailable',kind:'commands',verdict:'BLOCKED',evidence:['No executable QA contract',
345
+ ...notApplicable(plan).map(item=>`${item.id}: ${item.reason}`)]});
278
346
  const drift=digest(before.files)!==digest(snapshot().files);
279
- if(drift)for(const row of rows){row.verdict='BLOCKED';row.sourceChanged=true;}
347
+ // Keep each row's own verdict: a later explicit rerun may only recover a row
348
+ // that was PASS or a host-judged BLOCKED before the source changed, never a FAIL.
349
+ if(drift)for(const row of rows){row.verdictBeforeSourceChange=row.verdict;row.verdict='BLOCKED';row.sourceChanged=true;}
280
350
  const passed=rows.filter(item=>item.verdict==='PASS').length,failed=rows.filter(item=>item.verdict==='FAIL').length,
281
351
  blocked=rows.filter(item=>item.verdict==='BLOCKED').length;
282
352
  need(passed+failed+blocked===caseCount,'qa_result_invalid');
283
353
  const summary={result:failed>0?'FAIL':blocked>0?'BLOCKED':'PASS',passed,failed,blocked};
284
- const report=saveReport(configuration,binding,rows,summary,plan.deferred_cases);
354
+ const report=saveReport(configuration,binding,rows,summary,plan);
285
355
  return json({...summary,report});
286
356
  }});
287
357
  }
@@ -1,4 +1,6 @@
1
1
  // JSONL transport only. The existing host/runner owns decisions and durable state.
2
+ import {randomUUID} from 'node:crypto';
3
+ import path from 'node:path';
2
4
  import {executionDiagnostic,need} from './effect-contract.mjs';
3
5
  import {diagnosticReason} from './diagnostic-reason.mjs';
4
6
 
@@ -32,6 +34,22 @@ function reportRequestFailure(errorOutput,operation,error){
32
34
  }catch{/* diagnostics never change the reply */}
33
35
  }
34
36
 
37
+ // Optional idle notice (runtime/js/notify.mjs): counts from the reply of the
38
+ // last real operation while nothing is in flight. Any other session line
39
+ // (including one the host rejects) is the next step and ends the wait; a
40
+ // status/fix_status poll neither ends it nor restarts it, and while a poll is
41
+ // in flight the deadline is held, not reset. Cleared at session end. Loaded
42
+ // lazily; it only notifies and never writes logs, output or state.
43
+ const POLLS=new Set(['status','fix_status']);
44
+ const workflow=path.basename(process.argv[1]??'').replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
45
+ function idleNotice(sessionKey,seq,row,since){
46
+ let cancelled=false,cancel=null;
47
+ import('../notify.mjs').then(({scheduleIdleNotice})=>{
48
+ if(!cancelled)cancel=scheduleIdleNotice({workflow,project:process.cwd(),sessionKey,seq,row,since});
49
+ }).catch(()=>{});
50
+ return ()=>{cancelled=true;cancel?.();};
51
+ }
52
+
35
53
  // A line above the transport limit ends the session. Carry a code and the
36
54
  // limit so every host can name it instead of a generic launch failure.
37
55
  const tooLarge=limit=>Object.assign(new Error('request_too_large'),{code:'request_too_large',limit});
@@ -40,6 +58,20 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
40
58
  let pending=null,buffer=Buffer.alloc(0),failure=null,closeRequested=false;
41
59
  let writing=Promise.resolve();
42
60
  const controls=new Set();let queuedWrites=0;
61
+ const sessionKey=randomUUID(),startedAt=Date.now();let idle=null,seq=0,ended=false,lastRow=undefined,idleSince=0;
62
+ // Host registry (runtime/js/notify.mjs): serialised so a session that ends at
63
+ // once still removes its own entry. Each step is best-effort and synchronous.
64
+ let registry=Promise.resolve(),registered=false;
65
+ const register=(row,operation)=>{if(ended)return;registry=registry.then(()=>import('../notify.mjs'))
66
+ .then(m=>{if(m.writeHostRegistry({sessionKey,workflow,project:process.cwd(),startedAt,row,operation}))registered=true;}).catch(()=>{});};
67
+ register(null,null);
68
+ const clearIdle=()=>{idle?.();idle=null;};
69
+ const nextStep=()=>{clearIdle();lastRow=undefined;};
70
+ const rearm=()=>{
71
+ clearIdle();
72
+ if(lastRow!==undefined&&!failure&&!closeRequested&&!ended&&pending===null&&controls.size===0)idle=idleNotice(sessionKey,seq,lastRow,idleSince);
73
+ };
74
+ const finished=(row,operation)=>{if(!POLLS.has(operation)){lastRow=row;idleSince=Date.now();seq++;}rearm();};
43
75
  const outputError=error=>{failure=error;toolBridge?.close();input.destroy(error);};
44
76
  const inputError=error=>{if(!closeRequested)failure=error;toolBridge?.close();};
45
77
  input.on('error',inputError);
@@ -67,6 +99,7 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
67
99
  let request;
68
100
  try{
69
101
  request=JSON.parse(bytes.toString('utf8'));
102
+ if(POLLS.has(request?.operation))clearIdle();else nextStep();
70
103
  if(toolBridge!==null&&['host_result','host_close'].includes(request?.type)){
71
104
  const accepted=toolBridge.accept(request);closeRequested=accepted.closing===true;
72
105
  reply({type:'host_response',...accepted}).catch(error=>{failure=error;});return;
@@ -74,24 +107,27 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
74
107
  if(!request||typeof request!=='object'||Array.isArray(request)
75
108
  ||typeof request.requestId!=='string'||request.requestId.length>128
76
109
  ||!operationNames.has(request.operation))throw Error('invalid');
77
- }catch{reply({requestId:null,error:{code:'invalid_request'}}).catch(error=>{failure=error;});return;}
110
+ }catch{nextStep();reply({requestId:null,error:{code:'invalid_request'}}).catch(error=>{failure=error;});return;}
78
111
  const requestId=request.requestId;
112
+ let row=null;
79
113
  const invoke=async()=>{
80
- try{await reply({requestId,result:await host.handle(request)});}
114
+ try{const result=await host.handle(request);row={result};await reply({requestId,result});}
81
115
  catch(error){
82
116
  reportRequestFailure(errorOutput,request.operation,error);
83
- await reply({requestId,error:{code:'host_request_failed'}});
117
+ row={error:{code:'host_request_failed'}};
118
+ await reply({requestId,...row});
84
119
  }
120
+ finally{if(!POLLS.has(request.operation))register(row,request.operation);}
85
121
  };
86
122
  // Never queue cancel/status behind a long developer or reviewer call.
87
123
  if(request.operation==='status'||request.operation==='cancel'){
88
124
  // The input reader must not wait for a slow response consumer before it
89
125
  // can deliver the next control request (especially cancellation).
90
- const control=invoke().finally(()=>{controls.delete(control);});
126
+ const control=invoke().finally(()=>{controls.delete(control);finished(row,request.operation);});
91
127
  controls.add(control);control.catch(error=>{failure=error;});return;
92
128
  }
93
129
  if(pending){reply({requestId,error:{code:'host_busy'}}).catch(error=>{failure=error;});return;}
94
- pending=invoke().finally(()=>{pending=null;});
130
+ pending=invoke().finally(()=>{pending=null;finished(row,request.operation);});
95
131
  pending.catch(error=>{failure=error;});
96
132
  }
97
133
  try{
@@ -114,10 +150,14 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
114
150
  }finally{
115
151
  // With a duplex conversation, EOF means no more tool replies can arrive.
116
152
  // Reject that wait as disconnected, not as an explicit user cancellation.
117
- toolBridge?.close();
153
+ toolBridge?.close();ended=true;clearIdle();
118
154
  // EOF is not a user cancellation. Finish the in-flight result before close.
119
155
  try{await Promise.allSettled([...(pending?[pending]:[]),...controls,writing]);}
120
156
  finally{
157
+ // Only now, after every in-flight reply has queued its last registry
158
+ // write (and `ended` stops any later one), remove this session's entry.
159
+ registry=registry.then(()=>import('../notify.mjs')).then(m=>{if(registered)m.removeHostRegistry(sessionKey);}).catch(()=>{});
160
+ await registry;
121
161
  // destroy() emits error/close on a later tick; retain its error listener
122
162
  // until that lifecycle finishes rather than leaking an uncaught error.
123
163
  if(output.destroyed&&!output.closed)await new Promise(resolve=>output.once('close',resolve));
@@ -1,13 +1,25 @@
1
1
  // Duplex transport for a trusted current conversation. This has no task,
2
2
  // permission, dispatch-grant or completion authority and persists no state.
3
3
  import {randomUUID} from 'node:crypto';
4
+ import path from 'node:path';
4
5
  import {digest,json,need,shape} from './effect-contract.mjs';
5
6
 
7
+ // Optional notice (runtime/js/notify.mjs) when one call waits too long for the
8
+ // session. Loaded lazily; it only notifies and never answers or cancels a call.
9
+ function waitNotice(kind,callId){
10
+ let cancelled=false,cancel=null;
11
+ const workflow=path.basename(process.argv[1]??'').replace(/-host\.mjs$/,'').replace(/\.mjs$/,'')||'cm';
12
+ import('../notify.mjs').then(({scheduleWaitNotice})=>{
13
+ if(!cancelled)cancel=scheduleWaitNotice({kind,callId,workflow,project:process.cwd()});
14
+ }).catch(()=>{});
15
+ return ()=>{cancelled=true;cancel?.();};
16
+ }
17
+
6
18
  export function createHostToolBridge({responseLimit=64*1024}={}){
7
19
  need(Number.isSafeInteger(responseLimit)&&responseLimit>=64*1024&&responseLimit<=4*1024*1024,'host_response_limit_invalid');
8
20
  const sessionId=randomUUID();let send=null,pending=null,closed=false;
9
21
  const stop=(code,call=pending)=>{
10
- if(!call||pending!==call)return;pending=null;clearTimeout(call.timer);
22
+ if(!call||pending!==call)return;pending=null;clearTimeout(call.timer);call.notice?.();
11
23
  call.signal.removeEventListener('abort',call.abort);
12
24
  call.reject(Object.assign(new Error(code),{code}));
13
25
  };
@@ -28,7 +40,7 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
28
40
  stop('cancelled',call);
29
41
  Promise.resolve(send({type:'host_call_cancelled',sessionId,callId:request.callId})).catch(()=>{});
30
42
  };
31
- const call={request,signal,abort,resolve,reject,timer:null};pending=call;
43
+ const call={request,signal,abort,resolve,reject,timer:null,notice:waitNotice(kind,request.callId)};pending=call;
32
44
  if(timeoutMs!==null)call.timer=setTimeout(()=>stop('host_request_timeout',call),timeoutMs);
33
45
  signal.addEventListener('abort',abort,{once:true});
34
46
  if(signal.aborted){abort();return;}
@@ -48,7 +60,7 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
48
60
  need(reply.type==='host_result'&&pending!==null&&!closed,'host_response_mismatch');
49
61
  for(const key of ['sessionId','callId','requestDigest'])need(reply[key]===pending.request[key],'host_response_mismatch');
50
62
  }catch(error){return {accepted:false,code:error?.code==='limit_exceeded'?'host_response_too_large':'host_response_mismatch'};}
51
- const call=pending;pending=null;clearTimeout(call.timer);call.signal.removeEventListener('abort',call.abort);
63
+ const call=pending;pending=null;clearTimeout(call.timer);call.notice?.();call.signal.removeEventListener('abort',call.abort);
52
64
  call.resolve(reply.result);return {accepted:true,callId:reply.callId};
53
65
  },
54
66
  close(){closed=true;stop('host_disconnected');},
@@ -80,13 +80,15 @@ export function createHostWorkflowCapabilities({definition,configuration,bridge,
80
80
  const requestTimeout={timeoutMs:configuration.qa.timeoutMs??60000};
81
81
  result.qaDecisionProvider=parallelMember?createParallelMemberQaDecisionProvider():createHostQaDecisionProvider({timeoutMs:60000,
82
82
  assess:(request,signal)=>bridge.call('qa_assess',request,signal,requestTimeout)});
83
- result.qaExecutor=createHostQaExecutor({specsDir,codeProject,feature,requirements,runtime,
83
+ // requestTimeoutMs stays outside the fingerprinted executor configuration;
84
+ // timed-out QA recovery reads older case_blocked rows against it.
85
+ result.qaExecutor=Object.freeze({...createHostQaExecutor({specsDir,codeProject,feature,requirements,runtime,
84
86
  ...(definition.codeProjects?{codeProjects:definition.codeProjects}:{}),
85
87
  ...(bootstrap?{bootstrap:{requirements:bootstrap.configuration.bootstrapRequirements,scope:definition.scope}}:{}),
86
88
  ...configuration.qa,timeoutMs:1800000,logHome,
87
89
  ...(protectedExecution?{specsRoot:specsDir}:{}),
88
90
  logic:(request,signal)=>bridge.call('qa_logic',request,signal,requestTimeout),
89
- browser:(request,signal)=>bridge.call('qa_browser',request,signal,requestTimeout)});
91
+ browser:(request,signal)=>bridge.call('qa_browser',request,signal,requestTimeout)}),requestTimeoutMs:requestTimeout.timeoutMs});
90
92
  }
91
93
  return result;
92
94
  }
@@ -19,3 +19,39 @@ export function scanRows(log,visit) {
19
19
  consume(pending);
20
20
  } finally {if(descriptor!==undefined)fs.closeSync(descriptor);}
21
21
  }
22
+
23
+ // A whole-log reader without the 1 MiB review-material file limit, keeping that
24
+ // reader's file guarantees: one regular single-link file, not a symlink, the
25
+ // same file before, while and after reading (dev/ino/mode/nlink/size/times),
26
+ // read to its recorded size. Lines are parsed with plain JSON.parse, as the
27
+ // historical log readers did; only selected rows are kept, in log order.
28
+ const stableKey=s=>[s.dev,s.ino,s.mode,s.nlink,s.size,s.mtimeNs,s.ctimeNs].join(':');
29
+ export function readStableLogRows(file,select,code){
30
+ let descriptor;
31
+ try{
32
+ const before=fs.lstatSync(file,{bigint:true});
33
+ need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1n,code);
34
+ descriptor=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
35
+ need(stableKey(fs.fstatSync(descriptor,{bigint:true}))===stableKey(before),code);
36
+ const rows=[],chunk=Buffer.alloc(64*1024),decoder=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
37
+ let pending=Buffer.alloc(0),total=0;
38
+ const consume=line=>{
39
+ need(line.length<=MiB,code);const text=decoder.decode(line);
40
+ if(!text.trim())return;
41
+ let row;try{row=JSON.parse(text);}catch{need(false,code);}
42
+ if(select(row))rows.push(row);
43
+ };
44
+ while(true){
45
+ const size=fs.readSync(descriptor,chunk,0,chunk.length,null);if(size===0)break;total+=size;
46
+ need(BigInt(total)<=before.size,code);
47
+ pending=Buffer.concat([pending,chunk.subarray(0,size)]);let newline;
48
+ while((newline=pending.indexOf(10))!==-1){consume(pending.subarray(0,newline));pending=pending.subarray(newline+1);}
49
+ need(pending.length<=MiB,code);
50
+ }
51
+ consume(pending);
52
+ need(BigInt(total)===before.size&&stableKey(fs.fstatSync(descriptor,{bigint:true}))===stableKey(before)
53
+ &&stableKey(fs.lstatSync(file,{bigint:true}))===stableKey(before),code);
54
+ return rows;
55
+ }catch(error){if(error?.code===code)throw error;need(false,code);}
56
+ finally{if(descriptor!==undefined)fs.closeSync(descriptor);}
57
+ }
@@ -49,6 +49,9 @@ export function operatorGuidance(result,{executionActive=false}={}){
49
49
  if(state==='blocked'&&action==='complete')return explain('完成前复核受阻,已有审查结论不能直接当作任务完成。',
50
50
  '核对 reason 中的检查或文件变化;满足原完成条件后,在原运行发送 complete,不重新开发。',
51
51
  'complete',['原 run 与已审交接、范围和包绑定不变','使用当前 packageDigest;由宿主重新核对完成条件']);
52
+ if(code==='protected_scope')return explain('任务 scope 含项目规则或工作流文件,开发在派发前被拒绝,未写入任何文件。',
53
+ '本运行到此结束,原记录保留。从 scope 移除 reason 列出的路径,按原门禁用新 runId 新建运行;规则文件改动走 docs/js-workflow-control.md「项目规则文件的修改通道」。',
54
+ null,['不放宽受保护路径,开发者不能写这些文件','不改写原运行记录']);
52
55
  if(code==='bootstrap_instruction_conflict')return explain('已有项目规则与本次允许的写入基准冲突,规则生成被阻止。',
53
56
  '核对前序规则任务、提交基准和当前文件;当前没有可直接重派的动作,不覆盖已有规则。');
54
57
  if(code==='checks_not_passed')return explain('旧完成阶段的检查未通过,当前不是可重做开发的阻塞。',
@@ -2,21 +2,26 @@
2
2
  // same specs root. A delivery counts only after its own journal replays through
3
3
  // the runner grammar to a committed fixture_completed state: its review package
4
4
  // (and any accepted QA-fix packages) then describe reviewed before->after file
5
- // transitions. This grants nothing, never repairs, and never opens a writer.
5
+ // transitions. A standalone cm-fix run counts the same way once its own owner
6
+ // replays it to its normal completed closeout: its independently approved final
7
+ // review package is the transition. This grants nothing, never repairs, and
8
+ // never opens a writer.
6
9
  import fs from 'node:fs';
7
10
  import path from 'node:path';
8
11
  import {readExecutionSnapshot} from './execution-snapshot.mjs';
9
12
  import {readRunnerHistory} from './durable-runner-state.mjs';
13
+ import {inspectFixCompletionHistory} from '../cm-fix/execution.mjs';
10
14
  import {deliveredAfter,deliveryStep} from './fix-code-association.mjs';
11
15
  import {digest,need} from './effect-contract.mjs';
12
16
 
13
17
  const RUN_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
14
18
  const cache=new Map();
15
19
 
16
- function readDelivery(specsRoot,identity){
20
+ function readDelivery(specsRoot,identity,read={}){
17
21
  try{
18
22
  const snapshot=readExecutionSnapshot({specsRoot,identity});
19
23
  const init=snapshot.records[0]?.payload;
24
+ if(init?.workflow==='cm-fix-stages-v1'){read.fix=true;return readFixDelivery(specsRoot,identity,init.configuration);}
20
25
  if(init?.protocol!=='cm-task-runner'||init.type!=='init'||![2,3].includes(init.version))return null;
21
26
  const history=readRunnerHistory(snapshot.records,init.config,init.version);
22
27
  const state=history.state;
@@ -29,6 +34,18 @@ function readDelivery(specsRoot,identity){
29
34
  ...history.acceptedFixes.map(item=>({pkg:item.evidence.reviewPackage,reviewedAt:fixReviewedAt(specsRoot,item.evidence)}))])});
30
35
  }catch{return null;}
31
36
  }
37
+ // A standalone cm-fix run in this specs root, read through its own owner's
38
+ // read-only replay and completion projection: only a run whose approved final
39
+ // review of the exact package was closed by task_done and run_done qualifies
40
+ // (never a running, abandoned, cancelled or escalated one). A QA-fix child is
41
+ // its parent's delivery, through the parent's acceptance, never its own; a bare
42
+ // archive lives outside any specs root.
43
+ function readFixDelivery(specsRoot,identity,configuration){
44
+ if(Object.hasOwn(configuration??{},'qaSource')||configuration?.archiveMode!==undefined)return null;
45
+ const {identity:fixIdentity,evidence}=inspectFixCompletionHistory({specsRoot,identity});
46
+ return Object.freeze({runId:identity.runId,root:fs.realpathSync(configuration.reproduction.cwd),taskId:fixIdentity.taskId,
47
+ packages:Object.freeze([{pkg:evidence.reviewPackage,reviewedAt:fixReviewedAt(specsRoot,evidence)}])});
48
+ }
32
49
  // A QA fix package's durable review time: the final review registration its
33
50
  // completion evidence cites, read from the fix child's own store, for exactly
34
51
  // that package. Anything else has no time and never orders.
@@ -51,11 +68,17 @@ export function approvedReviewAt(state){
51
68
  &&Number.isSafeInteger(registration.registeredAt)?registration.registeredAt:null;
52
69
  }
53
70
 
71
+ const statVersion=stat=>stat?[stat.dev,stat.ino,stat.size,stat.mtimeMs,stat.ctimeMs].join(':'):null;
72
+ // A cm-fix run completes through its closeout rows in the run log, not its
73
+ // journal, so its entry also follows the log's version.
74
+ function logVersion(specsRoot){try{return statVersion(fs.lstatSync(path.join(specsRoot,'运行日志.jsonl')));}catch{return null;}}
54
75
  function cachedDelivery(specsRoot,repositoryId,runId,stat){
55
- const slot=[specsRoot,repositoryId,runId].join('\0');
56
- const version=[stat.dev,stat.ino,stat.size,stat.mtimeMs,stat.ctimeMs].join(':');
57
- if(cache.get(slot)?.version!==version)cache.set(slot,{version,delivery:readDelivery(specsRoot,{repositoryId,runId})});
58
- return cache.get(slot).delivery;
76
+ const slot=[specsRoot,repositoryId,runId].join('\0'),version=statVersion(stat),hit=cache.get(slot);
77
+ if(hit?.version===version&&(!hit.fix||hit.log===logVersion(specsRoot)))return hit.delivery;
78
+ // Read the log version first: an append during the read is seen next time.
79
+ const log=logVersion(specsRoot),read={fix:false},delivery=readDelivery(specsRoot,{repositoryId,runId},read);
80
+ cache.set(slot,{version,fix:read.fix,log,delivery});
81
+ return delivery;
59
82
  }
60
83
 
61
84
  // Resolve recorded steps to the real, completed, later reviewed packages of the
@@ -19,7 +19,7 @@ import { checkCompletion } from './gate-bridge.mjs';
19
19
  import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
20
20
  MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage,
21
21
  reviewRetrySpent,abandonableReviewResult,developBudget,developBudgetExhausted,
22
- completionBlockCount,completionRetriesExhausted,supersededReviewPayload,bootstrapReviewRecoverable } from './durable-runner-state.mjs';
22
+ completionBlockCount,completionRetriesExhausted,supersededReviewPayload,bootstrapReviewRecoverable,protectedDevelopScope,protectedScopeBlockReason } from './durable-runner-state.mjs';
23
23
  import {commitRunnerFixture} from './task-commit.mjs';
24
24
  import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure} from './provider-review-observation.mjs';
25
25
  import {attachCmAiTaskLearningApplicationEvidence,attachCmAiTaskLearningEvidence,
@@ -911,6 +911,11 @@ export function createTaskRunner(options) {
911
911
  async function perform(v) {
912
912
  if(v.kind==='develop') {
913
913
  need(stageAllowed('develop',state,code,priorReview?.verdict),'stage_mismatch');state='developing';code=null;reason=null;checkNewPaths=null;receipt=null;
914
+ // The adapter would refuse this scope before any provider runs. Block it
915
+ // here instead: no call starts, nothing is written, and the outcome is
916
+ // definite rather than unknown (create refuses such runs already).
917
+ const refusedScope=protectedDevelopScope(metadata);
918
+ if(refusedScope.length){halt('blocked','protected_scope',protectedScopeBlockReason(refusedScope));return;}
914
919
  const previousLearning=learningResult;
915
920
  const previousBootstrap=learningResult?.bootstrap??null;
916
921
  const previousWriteback=learningResult?.writeback??null;
@@ -11,22 +11,38 @@ import {inspectVisualCarrier} from './visual.mjs';
11
11
  export const rediagnosisPackage=value=>({historyDigest:value.historyDigest,priorPackageDigest:value.priorPackageDigest,
12
12
  priorObservationDigest:value.priorObservationDigest,reason:value.reason,reviewFeedback:value.reviewFeedback});
13
13
 
14
- export function createFixCausePackage({codeProject,defect,status}){
14
+ // Round 2 shows the reviewer the round-1 review; every file that review examined
15
+ // or cited (outside the revised affectedPaths) is supplied as read-only context so
16
+ // the reviewer can examine and cite it. Old round-2 packages have no contextFiles.
17
+ const priorReviewPaths=feedback=>[...new Set([...(feedback?.examinedPaths??[]),...(feedback?.findings??[]).map(f=>f?.path)]
18
+ .filter(p=>typeof p==='string'&&!p.startsWith('specs:')))].sort();
19
+ function readContextFiles(codeProject,feedback,affectedPaths){
20
+ const files=[];
21
+ for(const p of priorReviewPaths(feedback).filter(p=>!affectedPaths.includes(p))){
22
+ // Only existing, ordinary source files inside the code root; anything else is omitted, never forged.
23
+ try{files.push(...readReviewSourceFiles(codeProject,[p]));}catch{}
24
+ }
25
+ return files;
26
+ }
27
+
28
+ export function createFixCausePackage({codeProject,defect,status,context=true}){
15
29
  need((status.stage==='cause_review_required'||status.stage==='observation_cause_review_correction_required'&&status.causeReviewCorrection)
16
30
  &&status.reproduction?.status==='reproduced'
17
31
  &&status.diagnosis!==null,'fix_cause_review_unavailable');
32
+ const contextFiles=context&&status.rediagnosis?readContextFiles(codeProject,status.rediagnosis.reviewFeedback,status.diagnosis.affectedPaths):[];
18
33
  const value=json({version:1,kind:'cm-fix-cause-review-package',identity:status.identity,defect,
19
34
  reproduction:status.reproduction,diagnosis:status.diagnosis,learning:status.learning,
20
35
  ...(status.rediagnosis?{rediagnosis:rediagnosisPackage(status.rediagnosis)}:{}),
21
36
  ...(status.causeReviewCorrection?{correction:status.causeReviewCorrection}:{}),
22
- files:readReviewSourceFiles(codeProject,status.diagnosis.affectedPaths)},4*1024*1024);
37
+ files:readReviewSourceFiles(codeProject,status.diagnosis.affectedPaths),...(contextFiles.length?{contextFiles}:{})},4*1024*1024);
23
38
  return json({...value,packageDigest:digest(value)},4*1024*1024);
24
39
  }
25
40
 
26
41
  export function readFixCausePackage(raw){
27
42
  const value=json(raw,4*1024*1024);
28
43
  shape(value,['version','kind','identity','defect','reproduction','diagnosis','learning','files','packageDigest',
29
- ...(Object.hasOwn(value,'correction')?['correction']:[]),...(Object.hasOwn(value,'rediagnosis')?['rediagnosis']:[])]);
44
+ ...(Object.hasOwn(value,'correction')?['correction']:[]),...(Object.hasOwn(value,'rediagnosis')?['rediagnosis']:[]),
45
+ ...(Object.hasOwn(value,'contextFiles')?['contextFiles']:[])]);
30
46
  if(value.rediagnosis){
31
47
  shape(value.rediagnosis,['historyDigest','priorPackageDigest','priorObservationDigest','reason','reviewFeedback']);
32
48
  need([value.rediagnosis.historyDigest,value.rediagnosis.priorPackageDigest,value.rediagnosis.priorObservationDigest].every(v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v)), 'invalid_package');
@@ -62,6 +78,12 @@ export function readFixCausePackage(raw){
62
78
  text(d.rootCause);text(d.plan);need(Array.isArray(d.affectedModules)&&d.affectedModules.length>0,'invalid_package');
63
79
  d.affectedModules.forEach(text);
64
80
  need(Array.isArray(d.affectedPaths)&&digest([...d.affectedPaths].sort())===digest(files.map(file=>file.path)),'invalid_package');
81
+ if(Object.hasOwn(value,'contextFiles')){
82
+ need(value.rediagnosis&&Array.isArray(value.contextFiles)&&value.contextFiles.length>0,'invalid_package');
83
+ const context=readReviewSourceRecords(value.contextFiles).map(file=>file.path),allowed=priorReviewPaths(value.rediagnosis.reviewFeedback);
84
+ need(digest(context)===digest([...context].sort())&&new Set(context).size===context.length
85
+ &&context.every(p=>allowed.includes(p)&&!d.affectedPaths.includes(p)),'invalid_package');
86
+ }
65
87
  shape(r,['status','next','observation',...(Object.hasOwn(r,'attempts')?['attempts']:[])]);
66
88
  need(r.status==='reproduced'&&r.next==='diagnose','invalid_package');inspectFixReproductionAttempts(r);
67
89
  const o=r.observation;
@@ -78,23 +100,30 @@ export function readFixCausePackage(raw){
78
100
  return value;
79
101
  }
80
102
 
81
- export const causeReviewPaths=pkg=>pkg.files.map(file=>file.path);
103
+ export const causeReviewPaths=pkg=>[...pkg.files,...(pkg.contextFiles??[])].map(file=>file.path);
82
104
 
83
105
  // Validate the original package, then admit only the exact registered test transition.
84
106
  export function verifyFixCauseTransition(original,current,authorBaseline,authorResult){
85
107
  const reviewed=readFixCausePackage(original),now=readFixCausePackage(current);
86
108
  const expected=new Map(reviewed.files.map(file=>[file.path,file]));
109
+ // Round-2 context files (e.g. an existing regression test the narrowed
110
+ // diagnosis no longer covers) admit the same registered test transition;
111
+ // any other change to them is drift.
112
+ const expectedContext=new Map((reviewed.contextFiles??[]).map(file=>[file.path,file]));
87
113
  if(authorBaseline&&authorResult){
88
114
  const authored=inspectFixTestAuthor(authorResult,authorBaseline);
89
115
  need(authored.outcome==='authored','cause_review_drift');
90
116
  const before=new Map(authorBaseline.files.map(file=>[file.path,file]));
91
117
  for(const file of authored.testFiles){
92
- if(!expected.has(file.path))continue;
93
- need(digest(inventory([before.get(file.path)]))===digest(inventory([expected.get(file.path)])),'cause_review_drift');
94
- expected.set(file.path,file);
118
+ const target=expected.has(file.path)?expected:expectedContext.has(file.path)?expectedContext:null;
119
+ if(!target)continue;
120
+ need(digest(inventory([before.get(file.path)]))===digest(inventory([target.get(file.path)])),'cause_review_drift');
121
+ target.set(file.path,file);
95
122
  }
96
123
  }
97
124
  need(digest(inventory(now.files))===digest(inventory([...expected.values()])),'cause_review_drift');
125
+ need(Object.hasOwn(now,'contextFiles')===Object.hasOwn(reviewed,'contextFiles')
126
+ &&digest(inventory(now.contextFiles??[]))===digest(inventory([...expectedContext.values()])),'cause_review_drift');
98
127
  const {packageDigest,...body}=now;
99
- need(digest({...body,files:reviewed.files})===reviewed.packageDigest,'cause_review_drift');
128
+ need(digest({...body,files:reviewed.files,...(reviewed.contextFiles?{contextFiles:reviewed.contextFiles}:{})})===reviewed.packageDigest,'cause_review_drift');
100
129
  }