@aibyzero/cm-workflow 0.16.2 → 0.16.3

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 (140) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +138 -0
  4. package/README.md +2 -2
  5. package/VERSION +1 -1
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +46 -7
  8. package/docs/next-steps.md +110 -0
  9. package/docs/untested-branches.md +24 -18
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
  12. package/runtime/js/cm-ai/cm-ai-admission.mjs +5 -0
  13. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
  14. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
  15. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
  16. package/runtime/js/cm-ai/drive-core.mjs +68 -0
  17. package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
  18. package/runtime/js/cm-ai/effect-contract.mjs +4 -3
  19. package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
  20. package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
  21. package/runtime/js/cm-ai/host-handoff.mjs +9 -14
  22. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
  23. package/runtime/js/cm-ai/host-session.mjs +2 -2
  24. package/runtime/js/cm-ai/host.mjs +1 -1
  25. package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
  26. package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
  27. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
  28. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
  29. package/runtime/js/cm-ai/task-runner.mjs +41 -8
  30. package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
  31. package/runtime/js/cm-fix/cause-package.mjs +21 -0
  32. package/runtime/js/cm-fix/dossier.mjs +40 -1
  33. package/runtime/js/cm-fix/execution.mjs +360 -83
  34. package/runtime/js/cm-fix/host.mjs +7 -3
  35. package/runtime/js/cm-fix/layout.mjs +14 -6
  36. package/runtime/js/cm-fix/progress.mjs +14 -0
  37. package/runtime/js/cm-fix/protected-edits.mjs +1 -1
  38. package/runtime/js/cm-fix/red-test.mjs +7 -6
  39. package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
  40. package/runtime/js/cm-fix/regression.mjs +16 -10
  41. package/runtime/js/cm-fix/repair.mjs +16 -13
  42. package/runtime/js/cm-fix/test-author.mjs +2 -1
  43. package/runtime/js/cm-fix/test-extension.mjs +45 -0
  44. package/runtime/js/cm-prd/accepted-design.mjs +28 -9
  45. package/runtime/js/cm-prd/analysis.mjs +68 -16
  46. package/runtime/js/cm-prd/change.mjs +21 -1
  47. package/runtime/js/cm-prd/draft-save.mjs +96 -2
  48. package/runtime/js/cm-prd/failed-correction.mjs +51 -0
  49. package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
  50. package/runtime/js/cm-prd/review-correction.mjs +3 -0
  51. package/runtime/js/cm-prd/review-disposition.mjs +33 -15
  52. package/runtime/js/cm-prd/review-findings.mjs +2 -2
  53. package/runtime/js/cm-prd/review-host.mjs +2 -0
  54. package/runtime/js/cm-prd/review-preparation.mjs +28 -1
  55. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  56. package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
  57. package/runtime/js/cm-prd/session.mjs +5 -5
  58. package/runtime/js/cm-prd/split-design.mjs +67 -0
  59. package/runtime/js/cm-prd/summary.mjs +53 -8
  60. package/runtime/js/cm-refactor/workflow.mjs +100 -19
  61. package/scripts/cm-ai-batch-drive.mjs +251 -0
  62. package/scripts/cm-ai-batch-drive.test.mjs +152 -0
  63. package/scripts/cm-ai-contracts.test.mjs +30 -0
  64. package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
  65. package/scripts/cm-ai-drive.mjs +334 -0
  66. package/scripts/cm-ai-drive.test.mjs +251 -0
  67. package/scripts/cm-ai-fix-integration.test.mjs +1 -1
  68. package/scripts/cm-ai-host.mjs +41 -18
  69. package/scripts/cm-ai-host.test.mjs +37 -0
  70. package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
  71. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
  72. package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
  73. package/scripts/cm-ai-review-timeout.test.mjs +30 -0
  74. package/scripts/cm-ai-run.mjs +59 -11
  75. package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
  76. package/scripts/cm-ai-session-chain.test.mjs +261 -0
  77. package/scripts/cm-ai-supersede.test.mjs +320 -0
  78. package/scripts/cm-check-drive.mjs +93 -0
  79. package/scripts/cm-check-drive.test.mjs +62 -0
  80. package/scripts/cm-check-host.test.mjs +47 -0
  81. package/scripts/cm-claude-probe.test.mjs +117 -2
  82. package/scripts/cm-fix-abandon.test.mjs +383 -0
  83. package/scripts/cm-fix-cause-package.test.mjs +31 -1
  84. package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
  85. package/scripts/cm-fix-drive.mjs +168 -0
  86. package/scripts/cm-fix-drive.test.mjs +117 -0
  87. package/scripts/cm-fix-escalation.test.mjs +214 -0
  88. package/scripts/cm-fix-execution.test.mjs +26 -0
  89. package/scripts/cm-fix-host.mjs +4 -2
  90. package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
  91. package/scripts/cm-fix-qa-source.test.mjs +3 -3
  92. package/scripts/cm-fix-session-chain.test.mjs +244 -0
  93. package/scripts/cm-fix-test-extension.test.mjs +246 -0
  94. package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
  95. package/scripts/cm-host-handoff.test.mjs +37 -0
  96. package/scripts/cm-idea-drive.mjs +99 -0
  97. package/scripts/cm-idea-drive.test.mjs +50 -0
  98. package/scripts/cm-init-drive.mjs +191 -0
  99. package/scripts/cm-init-drive.test.mjs +59 -0
  100. package/scripts/cm-log-event.mjs +9 -0
  101. package/scripts/cm-prd-design-phase.test.mjs +355 -15
  102. package/scripts/cm-prd-drive.mjs +308 -0
  103. package/scripts/cm-prd-drive.test.mjs +154 -0
  104. package/scripts/cm-prd-host.mjs +46 -17
  105. package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
  106. package/scripts/cm-prd-review-disposition.test.mjs +133 -7
  107. package/scripts/cm-prd-review-gate.mjs +23 -4
  108. package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
  109. package/scripts/cm-prd-summary.test.mjs +48 -4
  110. package/scripts/cm-refactor-drive.mjs +237 -0
  111. package/scripts/cm-refactor-drive.test.mjs +77 -0
  112. package/scripts/cm-refactor-gaps.test.mjs +276 -0
  113. package/scripts/cm-refactor-host.test.mjs +1 -48
  114. package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
  115. package/scripts/cm-test-drive.mjs +132 -0
  116. package/scripts/cm-test-drive.test.mjs +91 -0
  117. package/scripts/cm-test-session.test.mjs +117 -0
  118. package/scripts/correction-check.test.mjs +38 -0
  119. package/scripts/fixtures/claude-model-marker.mjs +6 -0
  120. package/scripts/fixtures/claude-review-process.mjs +7 -0
  121. package/scripts/fixtures/cm-refactor.mjs +56 -0
  122. package/skills/cm-ai/SKILL.md +1 -1
  123. package/skills/cm-ai/references/N4-review.md +2 -0
  124. package/skills/cm-ai/references/N8-finish.md +1 -0
  125. package/skills/cm-ai/references/js-host.md +80 -3
  126. package/skills/cm-check/references/js-host.md +2 -0
  127. package/skills/cm-fix/SKILL.md +11 -4
  128. package/skills/cm-fix/references/js-host.md +67 -2
  129. package/skills/cm-fix/references/test-extension.md +57 -0
  130. package/skills/cm-idea/references/js-host.md +2 -0
  131. package/skills/cm-init/references/js-host.md +2 -0
  132. package/skills/cm-prd/SKILL.md +8 -8
  133. package/skills/cm-prd/references/js-change-recovery.md +41 -0
  134. package/skills/cm-prd/references/js-host.md +64 -2
  135. package/skills/cm-prd/references/spec-self-check.md +14 -2
  136. package/skills/cm-refactor/SKILL.md +5 -0
  137. package/skills/cm-refactor/references/js-batch.md +3 -1
  138. package/skills/cm-refactor/references/js-host.md +49 -0
  139. package/skills/cm-test/references/js-host.md +5 -0
  140. package/skills/cm-test/references/unit-coverage.md +2 -2
@@ -7,6 +7,38 @@ import {spawn} from 'node:child_process';
7
7
  import {gunzipSync,zstdDecompressSync} from 'node:zlib';
8
8
  import {claudeWorker,claudeReviewFingerprint} from './worker-claude.mjs';
9
9
 
10
+ const UNRECOGNIZED_MODEL_MARKER='[claude-code:unrecognized_model]';
11
+ export function createClaudeModelMarkerDetector(onMarker) {
12
+ let matched=0,found=false,reported=false,jsonTail='';
13
+ const report=()=>{
14
+ if(reported||!found)return;
15
+ reported=true;
16
+ let model=null;
17
+ try {
18
+ const value=JSON.parse(jsonTail.trim());
19
+ if(typeof value?.model==='string'&&/^[a-zA-Z0-9._-]+$/.test(value.model))model=value.model;
20
+ }catch{}
21
+ onMarker({reported_model:model});
22
+ jsonTail='';
23
+ };
24
+ return {
25
+ accept(chunk){
26
+ for(const char of String(chunk)){
27
+ if(reported)break;
28
+ if(found){
29
+ if(char==='\n'||char==='\r'){report();continue;}
30
+ if(jsonTail.length<512)jsonTail+=char;
31
+ else report();
32
+ }else if(char===UNRECOGNIZED_MODEL_MARKER[matched]){
33
+ matched++;
34
+ if(matched===UNRECOGNIZED_MODEL_MARKER.length)found=true;
35
+ }else matched=char===UNRECOGNIZED_MODEL_MARKER[0]?1:0;
36
+ }
37
+ },
38
+ finish:report,
39
+ };
40
+ }
41
+
10
42
  export function claudeProbeSandbox(temp,port) {
11
43
  if(!path.isAbsolute(temp)||!Number.isInteger(port)||port<1||port>65535)throw Error('invalid_probe');
12
44
  return `(version 1)(allow default)(deny network*)
@@ -23,7 +55,7 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
23
55
  const fingerprint=claudeReviewFingerprint({cwd,model,cli});
24
56
  const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-claude-probe-')));
25
57
  const observations=[];
26
- const controller=new AbortController();let stoppedByProbe=false;
58
+ const controller=new AbortController();let stoppedByProbe=false,modelMarker=null;
27
59
  const server=http.createServer((request,response)=>{
28
60
  const index=observations.length;
29
61
  if(index<8)observations.push({valid:false});else observations[0]={valid:false};
@@ -84,11 +116,17 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
84
116
  // Internal diagnostic bootstrap: same worker lifecycle, forced sink and synthetic prompt only.
85
117
  // This object is never returned as a passing receipt without examining the captured request.
86
118
  const worker=claudeWorker({cwd,model,cli,preflight,timeoutMs:15000,
87
- spawnProcess:(command,args,options)=>spawnProcess('/usr/bin/sandbox-exec',
88
- ['-p',claudeProbeSandbox(temp,port),command,...args],{...options,env:{...options.env,
119
+ spawnProcess:(command,args,options)=>{
120
+ const child=spawnProcess('/usr/bin/sandbox-exec',
121
+ ['-p',claudeProbeSandbox(temp,port),command,...args],{...options,env:{...options.env,
89
122
  ANTHROPIC_API_KEY:'cm-synthetic-local-probe',ANTHROPIC_BASE_URL:`http://127.0.0.1:${port}`,
90
123
  CLAUDE_CONFIG_DIR:temp,CLAUDE_CODE_TMPDIR:temp,
91
- CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:'1',TMPDIR:temp}})});
124
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:'1',TMPDIR:temp}});
125
+ const detector=createClaudeModelMarkerDetector(value=>{modelMarker=value;});
126
+ child.stderr.on('data',detector.accept);
127
+ child.stderr.once('end',detector.finish);
128
+ return child;
129
+ }});
92
130
  result=await worker({prompt:'Return JSON for synthetic diagnostic task CM-PROBE-001.'},
93
131
  {signal:controller.signal,onEvent:event=>{
94
132
  if(event.event==='process_closed')closeEvidence=event;
@@ -100,10 +138,11 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
100
138
  }
101
139
  const messages=observations.filter(item=>item.startup!==true);
102
140
  return {model,disabledSkills:[],preflight:{provider:'claude',prompt_transport:'stdin',
103
- config_fingerprint:fingerprint,passed:messages.length>=1&&messages.length<=2&&messages.every(message=>message.valid)
141
+ config_fingerprint:fingerprint,passed:modelMarker===null&&messages.length>=1&&messages.length<=2&&messages.every(message=>message.valid)
104
142
  &&stoppedByProbe&&result?.status==='cancelled'&&closeEvidence!==null&&!closeEvidence.timed_out,
105
143
  local_requests:observations.length,message_requests:messages.length,message_requests_expected:'1-2',
106
144
  listener_closed:closed,isolation:'macos-loopback-sandbox',
107
145
  process_code:result?.code??'unknown',stopped_by_probe:stoppedByProbe,exit_code:closeEvidence?.exit_code??null,
108
- request_checks:observations.map(item=>item.startup?{startup:true}:item.checks??{complete:false})}};
146
+ request_checks:[...observations.map(item=>item.startup?{startup:true}:item.checks??{complete:false}),
147
+ ...(modelMarker?[{model_recognized:false,...modelMarker}]:[])]}};
109
148
  }
@@ -14,6 +14,11 @@ const ACCEPTANCE=/^\s*[-*]\s+(?:\[[ xX]\]\s+)?(?:\[(AC-\d{3,})\]|(AC-\d{3,}))(?=
14
14
  const FEATURE=/^(\d+)\.(.+)$/;
15
15
  const TEST_CASE_VALIDATOR=fileURLToPath(new URL('../../../scripts/validate-test-cases.mjs',import.meta.url));
16
16
 
17
+ export function parseCmAiTaskLine(line){
18
+ const match=line.match(TASK);
19
+ return match?{id:match[2],completed:match[1].toLowerCase()==='x'}:null;
20
+ }
21
+
17
22
  // Greenfield's T-001 scaffolds; its subsequent instruction task (normally
18
23
  // T-002) owns init-equivalent rules. Use the existing parser and approval gate.
19
24
  export function inspectCmAiBootstrapTask({specsDir,codeProject,taskId},inProgress=false) {
@@ -2,8 +2,9 @@
2
2
  import {inspectCmAiAdmission,matchesCmAiTaskSelection} from './cm-ai-admission.mjs';
3
3
  import {inspectCmAiContextRefresh,inspectCmAiTaskLearningInput} from './cm-ai-context-refresh.mjs';
4
4
  import {findCmAiQaDecision,inspectCmAiQaDecision,inspectCmAiQaResult,recordCmAiQaDecision,
5
- latestCmAiQaRun,recordCmAiQaRun,inspectCmAiQaRecovery} from './cm-ai-qa-log.mjs';
5
+ latestCmAiQaRun,recordCmAiQaRun,inspectCmAiQaRecovery,inspectCmAiQaConfigurationRecovery} from './cm-ai-qa-log.mjs';
6
6
  import {recordCmAiRunDone} from './cm-ai-run-finalizer.mjs';
7
+ import {REVIEWED_HANDOFF_HINT} from './host-handoff.mjs';
7
8
  import {readHostQaFixHandoff} from './host-qa-fix.mjs';
8
9
  import {digest,freeze,hex,id,json,need,shape,text,validIdentity} from './effect-contract.mjs';
9
10
 
@@ -38,6 +39,7 @@ const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approv
38
39
  const summary=(operation,status,outcome)=>freeze({version:1,workflow:'cm-ai',operation:operation.operation,
39
40
  requestDigest:digest(operation),identity:status.identity,outcome,state:status.state,code:status.code??null,
40
41
  packageDigest:status.packageDigest??null,pendingAction:pendingAction(status),
42
+ ...(status.code==='handoff_exists'?{reason:REVIEWED_HANDOFF_HINT}:{}),
41
43
  ...(status.state==='blocked'&&status.calls?.at(-1)?.blockedReason!==undefined
42
44
  ?{blockedReason:status.calls.at(-1).blockedReason}:{})});
43
45
  const correctionSummary=(operation,status)=>status.code==='correction_review_required'
@@ -89,7 +91,7 @@ function effectSummary(operation,result,runner,identity) {
89
91
  boundStatus(runner.status(),next);
90
92
  return summary(operation,boundStatus(result,next),'advanced');
91
93
  }
92
- return summary(operation,boundStatus(result,identity),'advanced');
94
+ return summary(operation,boundStatus(result,identity),result?.code==='handoff_exists'?'blocked':'advanced');
93
95
  }
94
96
 
95
97
  function contextEvidence(options,identity,operation) {
@@ -151,6 +153,8 @@ export function createCmAiConversationEntry(options) {
151
153
  if(runner&&Object.hasOwn(runner,'inspectFixAssociation'))runnerKeys.push('inspectFixAssociation');
152
154
  if(runner&&Object.hasOwn(runner,'acceptCompletedFix'))runnerKeys.push('acceptCompletedFix');
153
155
  if(runner&&Object.hasOwn(runner,'attachQa'))runnerKeys.push('attachQa');
156
+ if(runner&&Object.hasOwn(runner,'reviseQa'))runnerKeys.push('reviseQa');
157
+ if(runner&&Object.hasOwn(runner,'supersedeEvidence'))runnerKeys.push('supersedeEvidence');
154
158
  if(runner&&Object.hasOwn(runner,'inspectBootstrapAdmission'))runnerKeys.push('inspectBootstrapAdmission');
155
159
  shape(runner,runnerKeys);
156
160
  for(const name of ['executeEffect','status','cancel','run'])need(typeof runner[name]==='function');
@@ -158,6 +162,7 @@ export function createCmAiConversationEntry(options) {
158
162
  if(Object.hasOwn(runner,'inspectFixAssociation'))need(typeof runner.inspectFixAssociation==='function');
159
163
  if(Object.hasOwn(runner,'acceptCompletedFix'))need(typeof runner.acceptCompletedFix==='function');
160
164
  if(Object.hasOwn(runner,'attachQa'))need(typeof runner.attachQa==='function');
165
+ if(Object.hasOwn(runner,'reviseQa'))need(typeof runner.reviseQa==='function');
161
166
  if(Object.hasOwn(runner,'inspectBootstrapAdmission'))need(typeof runner.inspectBootstrapAdmission==='function');
162
167
 
163
168
  const hostDecision=Object.hasOwn(options,'hostDecision')?json(options.hostDecision):null;
@@ -292,16 +297,21 @@ export function createCmAiConversationEntry(options) {
292
297
  notCancelled();
293
298
  need(pendingExecution===null,'qa_execution_pending');
294
299
  const binding={specsDir:options.specsDir,feature:options.feature,identity:result.identity,packageDigest:result.packageDigest};
295
- let previous,recovery=null;
300
+ let previous,recovery=null,configurationRecovery=false;
296
301
  try{previous=latestCmAiQaRun(binding);}
297
302
  catch(error){
298
- if(error.code!=='qa_result_incomplete')throw error;
299
- if(rerunUnknownQa){
300
- try{recovery=inspectCmAiQaRecovery(binding);}
301
- catch(error){if(error.code!=='qa_execution_unknown')throw error;}
303
+ if(error.code==='qa_result_superseded'){
304
+ recovery=inspectCmAiQaConfigurationRecovery(binding);
305
+ need(recovery!==null,'qa_revision_invalid');configurationRecovery=true;previous=null;
306
+ }else{
307
+ if(error.code!=='qa_result_incomplete')throw error;
308
+ if(rerunUnknownQa){
309
+ try{recovery=inspectCmAiQaRecovery(binding);}
310
+ catch(error){if(error.code!=='qa_execution_unknown')throw error;}
311
+ }
312
+ if(recovery===null)return summary(operation,{...runner.status(),code:'qa_execution_unknown'},'blocked');
313
+ previous=null;
302
314
  }
303
- if(recovery===null)return summary(operation,{...runner.status(),code:'qa_execution_unknown'},'blocked');
304
- previous=null;
305
315
  }
306
316
  if(rerunBlockedQa){
307
317
  need(previous!==null,'qa_rerun_not_blocked_by_evidence');
@@ -312,8 +322,8 @@ export function createCmAiConversationEntry(options) {
312
322
  const repaired=previous?.status==='failed'&&accepted?.testRunId===previous.testRunId;
313
323
  if(previous===null||repaired||rerunBlockedQa){
314
324
  // Later rounds require an accepted completed repair or explicit
315
- // evidence-only BLOCKED recovery. Unknown and unrepaired FAIL stop.
316
- const qaRound=recovery?recovery.qaRound+(rerunBlockedQa?1:0):(repaired?accepted.qaRound+1:1);
325
+ // evidence recovery/configuration revision. Unknown execution stops.
326
+ const qaRound=recovery?recovery.qaRound+(rerunBlockedQa||configurationRecovery?1:0):(repaired?accepted.qaRound+1:1);
317
327
  need(qaRound>=1&&qaRound<=3,'qa_round_invalid');
318
328
  testRunId=`qa-${digest(recovery?{...binding,previousTestRunId:recovery.testRunId}:
319
329
  repaired?{...binding,qaRound,repair:accepted.evidenceDigest}:binding).slice(0,48)}`;
@@ -321,7 +331,7 @@ export function createCmAiConversationEntry(options) {
321
331
  ...(repaired||recovery?{qaRound}: {})};
322
332
  const logInput={...invocation,...(Object.hasOwn(options,'qaLogHome')?{logHome:options.qaLogHome}:{})};
323
333
  notCancelled();
324
- if(recovery){
334
+ if(recovery&&!configurationRecovery){
325
335
  recordCmAiQaRun({...logInput,testRunId:recovery.testRunId,mode:recovery.mode,
326
336
  caseCount:recovery.caseCount,qaRound:recovery.qaRound,phase:rerunBlockedQa?'superseded':'abandoned',
327
337
  ...(rerunBlockedQa?{expectedEnvironment:qaExecutor.configuration?.environment??null}:{})});
@@ -6,6 +6,8 @@ import {fileURLToPath} from 'node:url';
6
6
  import {digest,hex,id,json,need,shape,text,validIdentity} from './effect-contract.mjs';
7
7
  import {readQaAttachment} from './qa-attachment.mjs';
8
8
  import {writeCmAiQaStatus} from './cm-ai-run-finalizer.mjs';
9
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
10
+ import {qaRevisionChain,readQaConfigRevision} from './qa-config-revision.mjs';
9
11
 
10
12
  const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
11
13
  const MiB=1024*1024;
@@ -212,6 +214,15 @@ function blockedEvidenceCases(items,specsDir,environment,code='qa_rerun_not_bloc
212
214
  return blocked.map(row=>row.id).sort();
213
215
  }
214
216
 
217
+ // Supersession is authorized by the owner journal, never a self-reported log digest.
218
+ function validateConfigurationSupersession(row,specsDir,code){
219
+ const snapshot=readExecutionSnapshot({specsRoot:specsDir,identity:{repositoryId:row.repository_id,runId:row.run_id}});
220
+ const {revisions}=qaRevisionChain(snapshot);
221
+ const record=revisions.find(r=>digest(r)===row.qa_revision_digest),config=snapshot.records[0]?.payload?.config;
222
+ need(record&&record.testRunId===row.operation_id&&record.qaRound===row.attempt
223
+ &&record.packageDigest===row.package_digest&&config?.identity?.taskId===row.task&&config?.taskLearning?.feature===row.feature,code);
224
+ }
225
+
215
226
  // Abandonment reuses a round; superseded completed evidence advances it.
216
227
  function validateRunSequence(items,code='qa_round_invalid',specsDir){
217
228
  const starts=[],ids=new Set();let current=null,abandoned=false,superseded=false;
@@ -234,11 +245,18 @@ function validateRunSequence(items,code='qa_round_invalid',specsDir){
234
245
  }else{
235
246
  need(current&&row.operation_id===current.operation_id&&row.attempt===current.attempt&&!abandoned&&!superseded,code);
236
247
  if(row.phase==='superseded'){
237
- need(current.attempt<3&&row.previous_test_run_id===current.operation_id&&row.reason==='host_evidence_problem'
248
+ need(current.attempt<3&&row.previous_test_run_id===current.operation_id
238
249
  &&row.mode===current.mode&&row.case_count===current.case_count,code);
239
250
  const prior=items.filter(entry=>entry.position<item.position&&entry.row.operation_id===row.operation_id);
240
- const blocked=blockedEvidenceCases(prior,specsDir,row.expected_environment,code);
241
- need(JSON.stringify(row.blocked_cases)===JSON.stringify(blocked),code);superseded=true;
251
+ if(row.reason==='qa_configuration_revision'){
252
+ need(prior.filter(entry=>entry.row.phase==='complete').length===1,code);
253
+ validateConfigurationSupersession(row,specsDir,code);
254
+ }else{
255
+ need(row.reason==='host_evidence_problem',code);
256
+ const blocked=blockedEvidenceCases(prior,specsDir,row.expected_environment,code);
257
+ need(JSON.stringify(row.blocked_cases)===JSON.stringify(blocked),code);
258
+ }
259
+ superseded=true;
242
260
  }
243
261
  if(row.phase==='abandoned'){
244
262
  need(row.previous_test_run_id===current.operation_id&&row.reason==='host_terminated'
@@ -308,6 +326,41 @@ export function latestCmAiQaRun(input) {
308
326
  return {testRunId,...inspectCmAiQaResult({...input,testRunId})};
309
327
  }
310
328
 
329
+ // Configuration revision consumes another round. Unknown in-flight QA must be
330
+ // reconciled separately; changing its configuration is not cancellation proof.
331
+ export function inspectCmAiQaRevisionTarget({specsDir,feature,identity,packageDigest}){
332
+ const input={specsDir,feature,identity,packageDigest};
333
+ latestCmAiQaRun(input);
334
+ const rows=qaRunRows(input),starts=validateRunSequence(rows,'qa_round_invalid',input.specsDir),start=starts.at(-1).row;
335
+ need(start.attempt<3,'qa_round_invalid');
336
+ need(!rows.some(({row})=>row.operation_id===start.operation_id&&['superseded','abandoned'].includes(row.phase)),'qa_revision_pending');
337
+ return {testRunId:start.operation_id,qaRound:start.attempt,mode:start.mode,caseCount:start.case_count};
338
+ }
339
+
340
+ export function inspectCmAiQaConfigurationRecovery(input){
341
+ const rows=qaRunRows(input);
342
+ if(rows.at(-1)?.row.reason!=='qa_configuration_revision'||rows.at(-1)?.row.phase!=='superseded')return null;
343
+ validateRunSequence(rows,'qa_round_invalid',input.specsDir);
344
+ const row=rows.at(-1).row;
345
+ return {testRunId:row.operation_id,qaRound:row.attempt,mode:row.mode,caseCount:row.case_count,superseded:true};
346
+ }
347
+
348
+ export function recordCmAiQaConfigurationRevision(input,raw){
349
+ const record=readQaConfigRevision(raw),{specsDir,feature,identity,packageDigest}=input;
350
+ const rows=qaRunRows({specsDir,feature,identity,packageDigest});
351
+ const existing=rows.find(({row})=>row.phase==='superseded'&&row.qa_revision_digest===digest(record));
352
+ if(existing){
353
+ validateConfigurationSupersession(existing.row,input.specsDir,'qa_revision_invalid');
354
+ if(rows.at(-1)===existing)writeCmAiQaStatus({specsDir,feature,identity,phase:'configuration_revised'});
355
+ return;
356
+ }
357
+ const target=inspectCmAiQaRevisionTarget(input);
358
+ need(target.testRunId===record.testRunId&&target.qaRound===record.qaRound,'qa_revision_invalid');
359
+ const result=recordCmAiQaRun({...input,...target,phase:'superseded',configurationRevision:record});
360
+ writeCmAiQaStatus({specsDir,feature,identity,phase:'configuration_revised'});
361
+ return result;
362
+ }
363
+
311
364
  export function recordCmAiQaRun(input) {
312
365
  const keys=['specsDir','codeProject','feature','identity','packageDigest','testRunId','mode','caseCount','phase'];
313
366
  if(Object.hasOwn(input,'result'))keys.push('result');
@@ -316,6 +369,7 @@ export function recordCmAiQaRun(input) {
316
369
  if(Object.hasOwn(input,'previousTestRunId'))keys.push('previousTestRunId');
317
370
  if(Object.hasOwn(input,'deferredCases'))keys.push('deferredCases');
318
371
  if(Object.hasOwn(input,'expectedEnvironment'))keys.push('expectedEnvironment');
372
+ if(Object.hasOwn(input,'configurationRevision'))keys.push('configurationRevision');
319
373
  shape(input,keys);validIdentity(input.identity);id(input.testRunId);hex(input.packageDigest);
320
374
  text(input.specsDir);text(input.codeProject);text(input.feature);
321
375
  need(['commands','browser','all'].includes(input.mode));
@@ -325,7 +379,12 @@ export function recordCmAiQaRun(input) {
325
379
  need(Number.isSafeInteger(qaRound)&&qaRound>=1&&qaRound<=3,'qa_round_invalid');
326
380
  const binding={specsDir:input.specsDir,feature:input.feature,identity:input.identity,packageDigest:input.packageDigest};
327
381
  let passed=[],blockedCases=[];
328
- if(input.phase==='superseded'){
382
+ if(input.configurationRevision){
383
+ need(input.phase==='superseded','qa_revision_invalid');
384
+ const record=readQaConfigRevision(input.configurationRevision),target=inspectCmAiQaRevisionTarget(binding);
385
+ need(record.taskAttempt===input.identity.attempt&&record.testRunId===input.testRunId&&target.testRunId===input.testRunId&&record.packageDigest===input.packageDigest
386
+ &&target.qaRound===qaRound&&record.qaRound===qaRound&&target.mode===input.mode&&target.caseCount===input.caseCount,'qa_revision_invalid');
387
+ }else if(input.phase==='superseded'){
329
388
  const previous=inspectCmAiQaRecovery(binding,{blocked:true,environment:input.expectedEnvironment});
330
389
  blockedCases=previous.blockedCases;
331
390
  need(previous.testRunId===input.testRunId&&previous.qaRound===qaRound
@@ -341,7 +400,7 @@ export function recordCmAiQaRun(input) {
341
400
  let previous;
342
401
  if(Object.hasOwn(input,'previousTestRunId')){
343
402
  const rows=qaRunRows(binding),superseded=rows.at(-1)?.row.phase==='superseded';
344
- previous=inspectCmAiQaRecovery(binding,{blocked:superseded,environment:rows.at(-1)?.row.expected_environment});
403
+ previous=inspectCmAiQaConfigurationRecovery(binding)??inspectCmAiQaRecovery(binding,{blocked:superseded,environment:rows.at(-1)?.row.expected_environment});
345
404
  need((previous.abandoned||previous.superseded)&&previous.testRunId===input.previousTestRunId
346
405
  &&previous.qaRound+(superseded?1:0)===qaRound,'qa_round_invalid');
347
406
  }else previous=latestCmAiQaRun(binding);
@@ -372,6 +431,11 @@ export function recordCmAiQaRun(input) {
372
431
  if(input.phase==='abandoned')Object.assign(data,{previous_test_run_id:input.testRunId,reason:'host_terminated',partial_pass_cases:passed});
373
432
  if(input.phase==='superseded')Object.assign(data,{previous_test_run_id:input.testRunId,
374
433
  reason:'host_evidence_problem',blocked_cases:blockedCases,expected_environment:input.expectedEnvironment??null});
434
+ if(input.configurationRevision){
435
+ delete data.blocked_cases;delete data.expected_environment;
436
+ Object.assign(data,{reason:'qa_configuration_revision',qa_revision_digest:digest(input.configurationRevision)});
437
+ validateConfigurationSupersession({...data,run_id:input.identity.runId},input.specsDir,'qa_revision_invalid');
438
+ }
375
439
  if(input.phase==='complete'){
376
440
  const result=json(input.result);shape(result,['result','passed','failed','blocked','report']);
377
441
  for(const key of ['passed','failed','blocked'])need(Number.isSafeInteger(result[key])&&result[key]>=0,'qa_result_invalid');
@@ -462,6 +526,7 @@ function inspectQaResult(input,failureSource,historical=false) {
462
526
  const latestStart=latestStarts.at(-1);
463
527
  if(!historical)need(latestStart.row.operation_id===input.testRunId,'qa_result_stale');
464
528
  const runs=candidates.filter(item=>item.row.operation_id===input.testRunId);
529
+ if(!historical)need(!runs.some(({row})=>row.phase==='superseded'&&row.reason==='qa_configuration_revision'),'qa_result_superseded');
465
530
  need(runs.length>0,'qa_result_invalid');
466
531
  const starts=runs.filter(item=>item.row.phase==='start'),completes=runs.filter(item=>item.row.phase==='complete');
467
532
  need(starts.length===1&&completes.length===1,'qa_result_incomplete');
@@ -47,12 +47,12 @@ function prepareStatus({specs,target},feature,identity,progress=null) {
47
47
  // Existing status file is only the current log projection, not a task store.
48
48
  export function writeCmAiQaStatus({specsDir,feature,identity,caseId,phase,result}) {
49
49
  validIdentity(identity);text(feature);
50
- need(['case_start','case_complete','case_blocked','complete'].includes(phase));
51
- if(phase!=='complete')id(caseId);
52
- else need(['PASS','FAIL','BLOCKED'].includes(result?.result),'qa_result_invalid');
50
+ need(['case_start','case_complete','case_blocked','complete','configuration_revised'].includes(phase));
51
+ if(phase!=='complete'&&phase!=='configuration_revised')id(caseId);
52
+ if(phase==='complete')need(['PASS','FAIL','BLOCKED'].includes(result?.result),'qa_result_invalid');
53
53
  const prepared=prepareStatus(statusTarget(specsDir),feature,identity,{node:'N6',feature,task:identity.taskId,
54
- detail:phase==='complete'?`QA 结果 ${result.result}(通过 ${result.passed} / 失败 ${result.failed} / 阻断 ${result.blocked})`:`QA ${caseId}: ${phase}`,
55
- state:phase==='complete'?{PASS:'qa_passed',FAIL:'qa_failed',BLOCKED:'qa_blocked'}[result.result]:'qa_running',
54
+ detail:phase==='configuration_revised'?'QA 配置已修订,旧结果仅作历史,等待下一轮':phase==='complete'?`QA 结果 ${result.result}(通过 ${result.passed} / 失败 ${result.failed} / 阻断 ${result.blocked})`:`QA ${caseId}: ${phase}`,
55
+ state:phase==='configuration_revised'?'qa_pending':phase==='complete'?{PASS:'qa_passed',FAIL:'qa_failed',BLOCKED:'qa_blocked'}[result.result]:'qa_running',
56
56
  at:new Date().toTimeString().slice(0,8)});
57
57
  try{
58
58
  fs.renameSync(prepared.temporary,prepared.target);
@@ -0,0 +1,68 @@
1
+ // JSONL host driver transport shared by cm-fix and cm-ai. Policy stays in each driver.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {spawn} from 'node:child_process';
5
+ import readline from 'node:readline';
6
+
7
+ export const stderr=line=>process.stderr.write(`[drive] ${line}\n`);
8
+ export const stop=(code,line)=>{stderr(line);process.exit(code);};
9
+
10
+ export function readJson(file,label){
11
+ try{return JSON.parse(fs.readFileSync(file,'utf8'));}
12
+ catch(error){if(error.code==='ENOENT')return undefined;stop(2,`${label} 不是合法 JSON: ${file}`);}
13
+ }
14
+
15
+ export function loadPlanFile({argv=process.argv.slice(2),name,known}){
16
+ const at=argv.indexOf('--plan');
17
+ const operation=argv.find((arg,index)=>index!==at&&index!==at+1&&!arg.startsWith('--'));
18
+ if(at===-1||!argv[at+1]||!operation)stop(2,`用法: ${name} --plan PLAN.json <operation>`);
19
+ if(!known.has(operation))stop(2,`不认识的步骤 ${operation};宿主支持的见 ${name.replace('-drive','-host')} --help`);
20
+ const planPath=path.resolve(argv[at+1]),base=path.dirname(planPath);
21
+ let plan;
22
+ try{plan=JSON.parse(fs.readFileSync(planPath,'utf8'));}
23
+ catch(error){stop(2,`读不了 ${planPath}: ${error.code??error.message}`);}
24
+ return {operation,plan,base};
25
+ }
26
+
27
+ export function requireFields(value,keys){
28
+ for(const key of keys)if(!Object.hasOwn(value,key))stop(2,`PLAN 缺少字段 ${key}`);
29
+ }
30
+
31
+ export function preflightAnswers(kinds,load){
32
+ const answers={};
33
+ for(const kind of kinds)answers[kind]=load(kind);
34
+ return answers;
35
+ }
36
+
37
+ export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor}){
38
+ const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe']});
39
+ child.stderr.on('data',chunk=>process.stderr.write(chunk));
40
+ const send=value=>child.stdin.write(JSON.stringify(value)+'\n');
41
+ let done=false;
42
+ readline.createInterface({input:child.stdout}).on('line',async line=>{
43
+ let row;try{row=JSON.parse(line);}catch{process.stdout.write(line+'\n');return;}
44
+ if(row.type==='host_ready'){send({requestId:'drive',operation,...request});return;}
45
+ if(row.type==='host_request'){
46
+ let result;
47
+ try{result=await answerFor(row,answers,paths);}catch(error){stderr(`应答 ${row.kind} 失败:${error.message}`);result=null;}
48
+ if(result===null){
49
+ stderr(`宿主问了预检没覆盖的问题 ${row.kind},无法应答;这一步会留在 unknown`);
50
+ send({type:'host_close',sessionId:row.sessionId});return;
51
+ }
52
+ stderr(`应答 ${row.kind}`);
53
+ send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
54
+ return;
55
+ }
56
+ if(row.type==='host_response')return;
57
+ if(row.requestId==='drive'){
58
+ done=true;
59
+ process.stdout.write(JSON.stringify(row,null,2)+'\n');
60
+ if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
61
+ if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
62
+ process.exitCode=row.error?1:0;
63
+ child.stdin.end();
64
+ }
65
+ });
66
+ child.on('error',error=>{stderr(`宿主启动失败:${error.message}`);process.exitCode=1;});
67
+ child.on('exit',code=>{if(!done){stderr(`宿主在给出结果前退出了,exit ${code}`);process.exitCode=1;}});
68
+ }
@@ -1,3 +1,4 @@
1
+ import {readQaConfigRevision} from './qa-config-revision.mjs';
1
2
  // Host-only S3b2b journal grammar. Data validation grants no provider authority.
2
3
  import {digest,need,shape,id,text,hex,json,validIdentity,validTaskLearningInput,validCallTimeout,validBlockedReason,requestFor} from './effect-contract.mjs';
3
4
  import {readReviewBaseline,readReviewPackage,reviewSpecsPath} from './review-package.mjs';
@@ -14,6 +15,7 @@ import {readBootstrapEvidence,validateBootstrapReviewPackage} from './host-boots
14
15
  import {validateCodeProjectPaths,assertCodeProjectSelections} from './code-projects.mjs';
15
16
 
16
17
  const LIMIT=16*1024*1024;
18
+ export const MAX_AI_JOINED_HOSTS=16;
17
19
  const same=(a,b)=>need(digest(a)===digest(b),'runner_history_mismatch');
18
20
  const prefix=(a,b)=>{need(b.length>=a.length,'runner_history_mismatch');same(a,b.slice(0,a.length));};
19
21
  const uuid=s=>need(typeof s==='string' && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(s),'runner_session');
@@ -477,7 +479,10 @@ export function readRunnerHistory(raw,config,version=1) {
477
479
  const completion=version>=2?completionConfig(config,version):null;
478
480
  let original,session,state,pending=null,beforeIntent=null,controlCount=0,controls={},completeIntentDigest=null,transaction=null;
479
481
  let invocation={registration:null,started:null,result:null};
480
- const acceptedFixes=[];let qaAttachment=null;
482
+ const acceptedFixes=[],joinedHosts=[],reviewerThreads=[];let qaAttachment=null,qaRevision=null,joinedForInvocation=false,supersession=null;
483
+ const reviewConfig=(calls=[])=>({...config,reviewInvocation:{...config.reviewInvocation,
484
+ excludedThreadIds:reviewExclusions({excludedThreadIds:[...config.reviewInvocation.excludedThreadIds,...joinedHosts]},
485
+ calls,config.developer.contextId)}});
481
486
  for(const [index,r] of records.entries()) {
482
487
  boundRunnerRecord(r,index+1);
483
488
  if(version>=2)fullEnvelope(r,index,index?records[index-1].digest:null);
@@ -500,7 +505,12 @@ export function readRunnerHistory(raw,config,version=1) {
500
505
  same(original.specsPath??null,completion?reviewSpecsPath(config.root,completion.owner.specsRoot):null);
501
506
  same(original.rootDigest,digestRoot(config.root));state=initialRunnerState(config,session,version);continue;
502
507
  }
503
- if(p.type==='effect-intent') {
508
+ if(version===3&&p.type==='evidence-superseded') {
509
+ shape(p,[...common,'record']);
510
+ need(r.kind==='result'&&index===1&&pending===null&&state.state==='ready'&&supersession===null,'supersede_record_invalid');
511
+ supersession=readEvidenceSupersession(p.record,{feature:config.taskLearning.feature,
512
+ taskId:config.identity.taskId,newRunId:config.identity.runId});
513
+ } else if(p.type==='effect-intent') {
504
514
  shape(p,[...common,'effect']);need(r.kind==='intent' && pending===null,'runner_intent');
505
515
  const e=p.effect;shape(e,['version','id','identity','kind',...(Object.hasOwn(e,'learningInput')?['learningInput']:[])]);
506
516
  validIdentity(e.identity);id(e.id);
@@ -510,18 +520,29 @@ export function readRunnerHistory(raw,config,version=1) {
510
520
  same(e.identity,{...config.identity,attempt:state.attempt});need(e.version===1 && stageAllowed(e.kind,state.state,state.code),'runner_stage');
511
521
  need(completedEffectCount(state.cache)<6 && !state.cache.some(c=>c.effect.id===e.id),'runner_cache');
512
522
  pending=e;beforeIntent=structuredClone(state);controls={};completeIntentDigest=e.kind==='complete'?r.digest:null;
513
- invocation={registration:null,started:null,result:null};
523
+ invocation={registration:null,started:null,result:null};joinedForInvocation=false;
524
+ } else if(version===3&&p.type==='host-joined') {
525
+ shape(p,[...common,'hostContextId']);id(p.hostContextId);
526
+ // Only one join in a pending review effect, before registration. A crash
527
+ // after this record is a valid unknown prefix; opening never adds a join.
528
+ need(r.kind==='result'&&pending?.kind==='review'&&!invocation.registration&&!joinedForInvocation
529
+ &&!controls.cancelled&&!controls.workflowError,'runner_invocation');
530
+ need(![config.reviewInvocation.developerThreadId,...config.reviewInvocation.excludedThreadIds,
531
+ ...joinedHosts].includes(p.hostContextId),'runner_invocation');
532
+ need(![config.developer.contextId,...config.reviewers.flatMap(r=>r.contexts),...reviewerThreads]
533
+ .includes(p.hostContextId),'not_independent');
534
+ need(joinedHosts.length<MAX_AI_JOINED_HOSTS,'host_limit');
535
+ joinedHosts.push(p.hostContextId);joinedForInvocation=true;
514
536
  } else if(version===3&&p.type==='review-invocation-registered') {
515
537
  need(r.kind==='intent'&&pending?.kind==='review'&&!invocation.registration,'runner_invocation');
516
- invocation.registration=readRegistration(p,beforeIntent,pending,config,session);
538
+ invocation.registration=readRegistration(p,beforeIntent,pending,reviewConfig(),session);
517
539
  } else if(version===3&&p.type==='review-invocation-started') {
518
540
  need(r.kind==='result'&&invocation.registration&&!invocation.started&&!invocation.result,'runner_invocation');
519
- invocation.started=readStarted(p,invocation.registration,pending,{...config,reviewInvocation:{...config.reviewInvocation,
520
- excludedThreadIds:reviewExclusions(config.reviewInvocation,beforeIntent.calls,config.developer.contextId)}});
541
+ invocation.started=readStarted(p,invocation.registration,pending,reviewConfig(beforeIntent.calls));
542
+ reviewerThreads.push(invocation.started);
521
543
  } else if(version===3&&p.type==='review-invocation-result') {
522
544
  need(r.kind==='result'&&invocation.registration&&!invocation.result,'runner_invocation');
523
- invocation.result=readInvocationResult(p,invocation.registration,invocation.started,pending,{...config,reviewInvocation:{...config.reviewInvocation,
524
- excludedThreadIds:reviewExclusions(config.reviewInvocation,beforeIntent.calls,config.developer.contextId)}});
545
+ invocation.result=readInvocationResult(p,invocation.registration,invocation.started,pending,reviewConfig(beforeIntent.calls));
525
546
  if(invocation.result.outcome==='cancelled')need(controls.cancelled===true,'runner_control');
526
547
  } else if(p.type==='effect-checkpoint') {
527
548
  shape(p,[...common,'effectId','checkpoint']);need(r.kind==='result' && pending && p.effectId===pending.id,'runner_checkpoint');
@@ -550,7 +571,18 @@ export function readRunnerHistory(raw,config,version=1) {
550
571
  } else if(version===3&&p.type==='qa-attached') {
551
572
  shape(p,[...common,'record']);
552
573
  need(r.kind==='result'&&pending===null&&state.state==='fixture_completed','qa_attach_not_completed');
574
+ need(qaRevision===null,'qa_revision_chain_invalid');
553
575
  need(qaAttachment===null,'qa_attachment_duplicate');qaAttachment=readQaAttachment(p.record);
576
+ } else if(version===3&&p.type==='qa-config-revised') {
577
+ shape(p,[...common,'record']);
578
+ need(r.kind==='result'&&pending===null&&state.state==='fixture_completed','qa_revision_not_completed');
579
+ const revision=readQaConfigRevision(p.record);
580
+ need(revision.packageDigest===state.reviewPackage.packageDigest&&revision.taskAttempt===state.attempt,'package_mismatch');
581
+ if(qaRevision)need(revision.fromFingerprint===qaRevision.toFingerprint
582
+ &&revision.invariantDigest===qaRevision.invariantDigest
583
+ &&revision.previousQaDigest===qaRevision.qaDigest&&revision.qaRound>qaRevision.qaRound,'qa_revision_chain_invalid');
584
+ else need(revision.fromFingerprint===(qaAttachment?.qaFingerprint??completion.fingerprints.config),'qa_revision_chain_invalid');
585
+ qaRevision=revision;
554
586
  } else if(version===3&&p.type==='qa-fix-accepted') {
555
587
  shape(p,[...common,'record']);need(r.kind==='result'&&pending===null&&state.state==='fixture_completed','fix_parent_not_completed');
556
588
  acceptedFixes.push(validateAcceptedFix({record:p.record,previous:acceptedFixes,
@@ -568,10 +600,11 @@ export function readRunnerHistory(raw,config,version=1) {
568
600
  if(pending){state.state='unknown';state.code='reconciliation_required';
569
601
  if(version===3&&invocation.registration)state.reviewInvocation={registration:invocation.registration.record,
570
602
  started:invocation.started,result:invocation.result};}
571
- return {original,session,state,pending,acceptedFixes,qaAttachment,...(version>=2?{transaction}:{})};
603
+ return {original,session,state,pending,acceptedFixes,qaAttachment,...(version===3?{joinedHosts,reviewerThreads,supersession}:{}),...(version>=2?{transaction}:{})};
572
604
  }
573
605
  // Baseline rootDigest uses bytes of the canonical root, not JSON string encoding.
574
606
  import {createHash} from 'node:crypto';
575
607
  import {readQaAttachment} from './qa-attachment.mjs';
608
+ import {readEvidenceSupersession} from './reviewed-evidence-supersession-record.mjs';
576
609
  import fs from 'node:fs';
577
610
  const digestRoot=root=>createHash('sha256').update(fs.realpathSync(root)).digest('hex');
@@ -172,6 +172,7 @@ export function reviewExclusions(invocation,calls,developerContextId){
172
172
  // Host configuration allows 32 exclusions. FIX second-round review additionally
173
173
  // excludes the cause reviewer, first implementation reviewer and logical context.
174
174
  // Preserve that full union; ordinary two-author-attempt callers still fit.
175
- // A run resumed in a new session adds that session's host context to the union,
176
- // so the bound carries one entry more than a single-session run ever needs.
177
- export const MAX_REVIEW_EXCLUSIONS=36;
175
+ // A run resumed in new sessions adds each session that joined it, plus the one
176
+ // running now, to the union: up to 16 joined sessions and the live one on top of
177
+ // the single-session bound.
178
+ export const MAX_REVIEW_EXCLUSIONS=36+17;
@@ -0,0 +1,40 @@
1
+ // Read-only evidence discovery. The writer must still independently reopen with
2
+ // reconstructed expected fingerprints and acquire its normal ownership lock.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {digest,need,shape,id,hex,json} from './effect-contract.mjs';
6
+ export function readExecutionSnapshot({specsRoot,identity}){
7
+ shape(identity,['repositoryId','runId']);Object.values(identity).forEach(id);
8
+ need(path.isAbsolute(specsRoot)&&fs.realpathSync(specsRoot)===specsRoot,'unsupported_path');
9
+ let dir=specsRoot;
10
+ for(const [index,part] of ['.reviews','.execution',identity.runId].entries()){
11
+ dir=path.join(dir,part);const stat=fs.lstatSync(dir);
12
+ need(stat.isDirectory()&&!stat.isSymbolicLink()&&(index===0||(stat.mode&0o077)===0),'unsupported_path');
13
+ }
14
+ const file=path.join(dir,'state.json'),before=fs.lstatSync(file);
15
+ need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1&&(before.mode&0o077)===0
16
+ &&before.size<=16*1024*1024,'unsupported_file');
17
+ const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
18
+ let bytes;
19
+ try{
20
+ bytes=fs.readFileSync(fd);const after=fs.fstatSync(fd),current=fs.lstatSync(file);
21
+ need([after,current].every(s=>['dev','ino','size','mtimeMs','ctimeMs'].every(k=>s[k]===before[k]))
22
+ &&bytes.length===before.size,'snapshot_changed');
23
+ }finally{fs.closeSync(fd);}
24
+ const raw=JSON.parse(bytes.toString('utf8')),v=json(raw,16*1024*1024);
25
+ need(Buffer.from(JSON.stringify(raw)+'\n').equals(bytes),'store_corrupt');
26
+ shape(v,['version','identity','fingerprints','records','revision']);
27
+ need(v.version===1&&digest(v.identity)===digest(identity),'identity_mismatch');
28
+ shape(v.fingerprints,['workflow','config','inputs']);Object.values(v.fingerprints).forEach(hex);
29
+ need(Array.isArray(v.records)&&v.records.length<=1024,'limit_exceeded');
30
+ let previous=null;const ids=new Set();
31
+ for(const [index,r] of v.records.entries()){
32
+ shape(r,['version','seq','id','kind','payload','previousDigest','digest']);id(r.id);hex(r.digest);
33
+ json(r.payload,1024*1024);
34
+ const {digest:checksum,...body}=r;
35
+ need(r.version===1&&r.seq===index+1&&r.previousDigest===previous&&!ids.has(r.id)
36
+ &&['intent','result','cancel','commit-intent','commit-result','finalized'].includes(r.kind)
37
+ &&digest(body)===checksum,'store_corrupt');previous=checksum;ids.add(r.id);
38
+ }
39
+ const {revision,...body}=v;need(digest(body)===revision,'store_corrupt');return v;
40
+ }
@@ -93,7 +93,7 @@ export function resolveReviewTimeout(review,protection){
93
93
  }
94
94
  export function createConversationExecution(definition,hostContextId,bridge,review=null,allowedAttempt=null,workflow=null,allowQa=false,runtime='codex',options={}){
95
95
  definition=json(definition);workflow=workflow===null?null:json(workflow);options=json(options);
96
- shape(options,[...['protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
96
+ shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
97
97
  need(!Object.hasOwn(options,'verificationPrecheck')||typeof options.verificationPrecheck==='boolean','invalid_input');
98
98
  const parallelMember=options.parallelMember??false;need(typeof parallelMember==='boolean','invalid_input');
99
99
  const provider=options.providerDevelopment??null;
@@ -123,11 +123,14 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
123
123
  need(allowedAttempts.length<=2&&new Set(allowedAttempts).size===allowedAttempts.length
124
124
  &&allowedAttempts.every(value=>value===1||value===2),'invalid_review_attempt');
125
125
  const author='cm-conversation-author',reviewContexts=['cm-conversation-review-1','cm-conversation-review-2'];
126
- id(hostContextId);need(![author,...reviewContexts].includes(hostContextId),'not_independent');
126
+ const durableHostContextId=options.originalHostContextId??hostContextId;
127
+ for(const context of [hostContextId,durableHostContextId]){
128
+ id(context);need(![author,...reviewContexts].includes(context),'not_independent');
129
+ }
127
130
  // Keep the unverified native permissions boundary intact for this first host
128
131
  // slice too. A transport is not physical protection of nested specs.
129
132
  need(protection||!definition.specsDir.startsWith(definition.codeProject+path.sep),'nested_specs_protection_required');
130
- const configuration={kind:'cm-current-conversation-v1',...(parallelMember?{parallelMember}:{}),definitionDigest:digest(definition),hostContextId,
133
+ const configuration={kind:'cm-current-conversation-v1',...(parallelMember?{parallelMember}:{}),definitionDigest:digest(definition),hostContextId:durableHostContextId,
131
134
  ...(runtime==='claude'?{runtime}:{}),
132
135
  ...(provider?{providerDevelopment:{model:provider.model,coderRuntime,reviewerRuntime}}:{}),
133
136
  ...(protection?{protection}:{}),
@@ -189,7 +192,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
189
192
  }catch{/* diagnostics never change the verdict */}
190
193
  return {satisfied:verdict.satisfied};
191
194
  }:null;
192
- const execution={configuration,timeoutMs:provider?protection.timeoutMs:1800000,excludedContexts:[hostContextId],hostDecision:null,applicableAgentFiles:[],
195
+ const execution={configuration,timeoutMs:provider?protection.timeoutMs:1800000,excludedContexts:[durableHostContextId],hostDecision:null,applicableAgentFiles:[],
193
196
  ...(verificationGate?{verificationGate}:{}),
194
197
  ...(bootstrap?{bootstrap}:{}),
195
198
  ...(provider?{developmentAttempt:provider.attempt}:{}),
@@ -287,7 +290,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
287
290
  return reviewerRuntime==='codex'?createCodexReviewRun(codexWorker(selectedOptions))(request,control)
288
291
  :createClaudeReviewRun(claudeWorker(selectedOptions))(request,control);
289
292
  }}],
290
- reviewInvocation:{developerThreadId:author,excludedThreadIds:[hostContextId],
293
+ reviewInvocation:{developerThreadId:author,excludedThreadIds:[durableHostContextId],hostContextId,
291
294
  authorize:authority?.authorize??(()=>({status:'denied',code:'permission_denied'}))},
292
295
  };
293
296
  if(definition.codeProjects)execution.applicableAgentFiles=[...new Set([...execution.applicableAgentFiles,