@aibyzero/cm-workflow 0.16.1 → 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 (147) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +179 -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 +79 -0
  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 +38 -5
  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/metrics-table.mjs +22 -0
  26. package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
  27. package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
  28. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
  29. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
  30. package/runtime/js/cm-ai/task-runner.mjs +41 -8
  31. package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
  32. package/runtime/js/cm-fix/cause-package.mjs +21 -0
  33. package/runtime/js/cm-fix/dossier.mjs +40 -1
  34. package/runtime/js/cm-fix/execution.mjs +369 -83
  35. package/runtime/js/cm-fix/host.mjs +7 -3
  36. package/runtime/js/cm-fix/layout.mjs +34 -0
  37. package/runtime/js/cm-fix/metrics.mjs +2 -4
  38. package/runtime/js/cm-fix/progress.mjs +14 -0
  39. package/runtime/js/cm-fix/protected-edits.mjs +1 -1
  40. package/runtime/js/cm-fix/red-test.mjs +7 -6
  41. package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
  42. package/runtime/js/cm-fix/regression.mjs +16 -10
  43. package/runtime/js/cm-fix/repair.mjs +16 -13
  44. package/runtime/js/cm-fix/test-author.mjs +2 -1
  45. package/runtime/js/cm-fix/test-extension.mjs +45 -0
  46. package/runtime/js/cm-fix/walkthrough.mjs +8 -2
  47. package/runtime/js/cm-prd/accepted-design.mjs +28 -9
  48. package/runtime/js/cm-prd/analysis.mjs +68 -16
  49. package/runtime/js/cm-prd/change.mjs +21 -1
  50. package/runtime/js/cm-prd/draft-save.mjs +96 -2
  51. package/runtime/js/cm-prd/failed-correction.mjs +51 -0
  52. package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
  53. package/runtime/js/cm-prd/review-correction.mjs +3 -0
  54. package/runtime/js/cm-prd/review-disposition.mjs +33 -15
  55. package/runtime/js/cm-prd/review-findings.mjs +2 -2
  56. package/runtime/js/cm-prd/review-host.mjs +2 -0
  57. package/runtime/js/cm-prd/review-preparation.mjs +28 -1
  58. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  59. package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
  60. package/runtime/js/cm-prd/session.mjs +5 -5
  61. package/runtime/js/cm-prd/split-design.mjs +67 -0
  62. package/runtime/js/cm-prd/summary.mjs +53 -8
  63. package/runtime/js/cm-refactor/workflow.mjs +103 -21
  64. package/scripts/audit-untested-enums.mjs +59 -0
  65. package/scripts/cm-ai-batch-drive.mjs +251 -0
  66. package/scripts/cm-ai-batch-drive.test.mjs +152 -0
  67. package/scripts/cm-ai-contracts.test.mjs +30 -0
  68. package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
  69. package/scripts/cm-ai-drive.mjs +334 -0
  70. package/scripts/cm-ai-drive.test.mjs +251 -0
  71. package/scripts/cm-ai-execution-diagnostic.test.mjs +25 -0
  72. package/scripts/cm-ai-fix-integration.test.mjs +1 -1
  73. package/scripts/cm-ai-host.mjs +41 -18
  74. package/scripts/cm-ai-host.test.mjs +37 -0
  75. package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
  76. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
  77. package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
  78. package/scripts/cm-ai-review-timeout.test.mjs +30 -0
  79. package/scripts/cm-ai-run.mjs +59 -11
  80. package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
  81. package/scripts/cm-ai-session-chain.test.mjs +261 -0
  82. package/scripts/cm-ai-supersede.test.mjs +320 -0
  83. package/scripts/cm-check-drive.mjs +93 -0
  84. package/scripts/cm-check-drive.test.mjs +62 -0
  85. package/scripts/cm-check-host.test.mjs +47 -0
  86. package/scripts/cm-claude-probe.test.mjs +117 -2
  87. package/scripts/cm-fix-abandon.test.mjs +383 -0
  88. package/scripts/cm-fix-cause-package.test.mjs +31 -1
  89. package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
  90. package/scripts/cm-fix-drive.mjs +168 -0
  91. package/scripts/cm-fix-drive.test.mjs +117 -0
  92. package/scripts/cm-fix-escalation.test.mjs +214 -0
  93. package/scripts/cm-fix-execution.test.mjs +67 -0
  94. package/scripts/cm-fix-host.mjs +4 -2
  95. package/scripts/cm-fix-metrics.test.mjs +32 -0
  96. package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
  97. package/scripts/cm-fix-qa-source.test.mjs +3 -3
  98. package/scripts/cm-fix-session-chain.test.mjs +244 -0
  99. package/scripts/cm-fix-test-extension.test.mjs +246 -0
  100. package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
  101. package/scripts/cm-host-handoff.test.mjs +37 -0
  102. package/scripts/cm-idea-drive.mjs +99 -0
  103. package/scripts/cm-idea-drive.test.mjs +50 -0
  104. package/scripts/cm-init-drive.mjs +191 -0
  105. package/scripts/cm-init-drive.test.mjs +59 -0
  106. package/scripts/cm-log-event.mjs +9 -0
  107. package/scripts/cm-prd-design-phase.test.mjs +355 -15
  108. package/scripts/cm-prd-drive.mjs +308 -0
  109. package/scripts/cm-prd-drive.test.mjs +154 -0
  110. package/scripts/cm-prd-host.mjs +46 -17
  111. package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
  112. package/scripts/cm-prd-review-disposition.test.mjs +133 -7
  113. package/scripts/cm-prd-review-gate.mjs +23 -4
  114. package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
  115. package/scripts/cm-prd-summary.test.mjs +48 -4
  116. package/scripts/cm-refactor-drive.mjs +237 -0
  117. package/scripts/cm-refactor-drive.test.mjs +77 -0
  118. package/scripts/cm-refactor-gaps.test.mjs +276 -0
  119. package/scripts/cm-refactor-host.test.mjs +1 -48
  120. package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
  121. package/scripts/cm-release-smoke.sh +14 -0
  122. package/scripts/cm-test-drive.mjs +132 -0
  123. package/scripts/cm-test-drive.test.mjs +91 -0
  124. package/scripts/cm-test-session.test.mjs +117 -0
  125. package/scripts/correction-check.test.mjs +38 -0
  126. package/scripts/fixtures/claude-model-marker.mjs +6 -0
  127. package/scripts/fixtures/claude-review-process.mjs +7 -0
  128. package/scripts/fixtures/cm-refactor.mjs +56 -0
  129. package/skills/cm-ai/SKILL.md +1 -1
  130. package/skills/cm-ai/references/N4-review.md +2 -0
  131. package/skills/cm-ai/references/N8-finish.md +1 -0
  132. package/skills/cm-ai/references/js-host.md +80 -3
  133. package/skills/cm-check/references/js-host.md +2 -0
  134. package/skills/cm-fix/SKILL.md +11 -4
  135. package/skills/cm-fix/references/js-host.md +67 -2
  136. package/skills/cm-fix/references/test-extension.md +57 -0
  137. package/skills/cm-idea/references/js-host.md +2 -0
  138. package/skills/cm-init/references/js-host.md +2 -0
  139. package/skills/cm-prd/SKILL.md +8 -8
  140. package/skills/cm-prd/references/js-change-recovery.md +41 -0
  141. package/skills/cm-prd/references/js-host.md +64 -2
  142. package/skills/cm-prd/references/spec-self-check.md +14 -2
  143. package/skills/cm-refactor/SKILL.md +5 -0
  144. package/skills/cm-refactor/references/js-batch.md +3 -1
  145. package/skills/cm-refactor/references/js-host.md +49 -0
  146. package/skills/cm-test/references/js-host.md +5 -0
  147. package/skills/cm-test/references/unit-coverage.md +2 -2
@@ -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,
@@ -3,9 +3,15 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {randomUUID,createHash} from 'node:crypto';
5
5
  import {createReviewPackage,verifyReviewPackage} from './review-package.mjs';
6
+ import {supersedeWorkflowFile} from './review-evidence-file.mjs';
6
7
  import {implementationSha256,loadHandoff} from '../../../scripts/cm-task-gate.mjs';
7
8
  import {digest,json,shape,text,need} from './effect-contract.mjs';
8
9
 
10
+ export const REVIEWED_HANDOFF_HINT='仅 QA 卡住时,配置错误用 --revise-qa-config PREVIOUS.json --qa-config-revision-reason … 恢复原运行,宿主或环境证据不足用 --rerun-blocked-qa。确需重跑任务时,用 --supersede-reviewed-evidence --supersede-reason … 新建运行。';
11
+ function reviewedHandoffConflict(){
12
+ const error=new Error('handoff_exists');error.code='handoff_exists';error.reason=REVIEWED_HANDOFF_HINT;throw error;
13
+ }
14
+
9
15
  function prepareHostHandoff(raw){
10
16
  const input=json(raw,16*1024*1024);
11
17
  shape(input,['root','baseline','checks','handoffPath',...(Object.hasOwn(input,'evidence')?['evidence']:[])]);
@@ -78,18 +84,6 @@ function reviewConsumedHandoff(parent,name,attempt){
78
84
  return lines.slice(1,end).some(line=>line.trim()===`handoff: ${name}`);
79
85
  }
80
86
 
81
- // Archive by link-then-unlink so the bytes survive a crash between the two steps.
82
- function supersedeHandoff(parent,handoffPath,existing){
83
- const archive=path.join(parent,'.superseded');
84
- fs.mkdirSync(archive,{recursive:true,mode:0o700});
85
- const stamp=createHash('sha256').update(existing).digest('hex').slice(0,16);
86
- const target=path.join(archive,`${path.basename(handoffPath)}.${stamp}`);
87
- try{fs.linkSync(handoffPath,target);}catch(error){if(error.code!=='EEXIST')throw error;}
88
- fs.unlinkSync(handoffPath);
89
- const dir=fs.openSync(archive,fs.constants.O_RDONLY);
90
- try{fs.fsyncSync(dir);}finally{fs.closeSync(dir);}
91
- }
92
-
93
87
  // Publish with no-replace semantics, resolving only the collisions that are
94
88
  // provably safe to resolve. Returns nothing; throws on a conflict it may not touch.
95
89
  function publishHandoff(parent,handoffPath,temp,bytes,attempt){
@@ -100,8 +94,9 @@ function publishHandoff(parent,handoffPath,temp,bytes,attempt){
100
94
  const existing=fs.readFileSync(handoffPath);
101
95
  // Republishing identical bytes is the crash-after-link case, already published.
102
96
  if(existing.equals(bytes))return;
103
- need(!reviewConsumedHandoff(parent,path.basename(handoffPath),attempt),'handoff_exists');
104
- supersedeHandoff(parent,handoffPath,existing);
97
+ if(reviewConsumedHandoff(parent,path.basename(handoffPath),attempt))reviewedHandoffConflict();
98
+ // Crash-after-link retries stamp the checked bytes; a second read could change the archive name.
99
+ supersedeWorkflowFile(parent,path.basename(handoffPath),existing);
105
100
  fs.linkSync(temp,handoffPath);
106
101
  }
107
102
 
@@ -6,7 +6,8 @@ import {createFixHost} from '../cm-fix/host.mjs';
6
6
  import {bindQaFixDefinition} from './qa-fix-definition.mjs';
7
7
  import {digest,id,json,need,shape,validIdentity,hex} from './effect-contract.mjs';
8
8
 
9
- export function createQaFixOwnerHost({parent,reopenParent,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={}}){
9
+ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={}}){
10
+ id(hostContextId);id(parentHostContextId);
10
11
  need((fix===null)!==(template===null),'invalid_fix_config');
11
12
  let definition=null;
12
13
  const fixedTemplate=template===null?null:json(template,64*1024);
@@ -42,7 +43,7 @@ export function createQaFixOwnerHost({parent,reopenParent,fix=null,template=null
42
43
  busy=true;try{return await current.host.handle(request);}finally{busy=false;}
43
44
  }
44
45
  const value=json(request);shape(value,['version','requestId','operation','identity','packageDigest','testRunId',
45
- ...(request.operation==='fix_action'?['fixOperation']:[])]);
46
+ ...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='abandon_step'&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
46
47
  need(value.version===1,'invalid_input');id(value.requestId);validIdentity(value.identity);hex(value.packageDigest);id(value.testRunId);
47
48
  if(fixedTemplate)definition=bindQaFixDefinition({template:fixedTemplate,identity:value.identity,
48
49
  packageDigest:value.packageDigest,testRunId:value.testRunId});
@@ -54,7 +55,7 @@ export function createQaFixOwnerHost({parent,reopenParent,fix=null,template=null
54
55
  const acting=value.operation==='fix_action';
55
56
  if(acting)need(['red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback',
56
57
  'handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression',
57
- 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review'].includes(value.fixOperation),'fix_operation_unavailable');
58
+ 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','abandon_step'].includes(value.fixOperation),'fix_operation_unavailable');
58
59
  need(!(advancing||acting)||allowStart,'qa_fix_start_authorization_required');
59
60
  busy=true;let child=null,released=false,result;
60
61
  try{
@@ -63,18 +64,22 @@ export function createQaFixOwnerHost({parent,reopenParent,fix=null,template=null
63
64
  &&digest(status.identity)===digest(value.identity),'qa_fix_parent_not_completed');
64
65
  switching=true;current.close();current=null;released=true;
65
66
  const existing=fs.existsSync(path.join(definition.specsRoot,'.reviews','.execution',definition.identity.runId));
66
- child=openFixExecution({...definition,create:advancing&&!existing},advancing||acting?fixExecution:{});
67
+ // Only a new store needs a creator check. Existing configuration is
68
+ // immutable and checked against its own stored fingerprint by cm-fix.
69
+ if(advancing&&!existing)need([hostContextId,parentHostContextId].includes(definition.configuration.hostContextId),'qa_fix_host_mismatch');
70
+ child=openFixExecution({...definition,hostContextId,create:advancing&&!existing},advancing||acting?fixExecution:{});
67
71
  activeChild=child;
68
72
  let actionResult;
69
73
  if(advancing||acting){
70
74
  const host=createFixHost({owner:child,config:{...definition.configuration,specsRoot:definition.specsRoot,identity:definition.identity},
71
75
  runtime:definition.configuration.runtime??'codex',permissions:[...permissions,'--allow-reproduction'],...fixAuthorities});
72
76
  actionResult=running?await host.run(value.requestId)
73
- :await host.handle({requestId:value.requestId,operation:advancing?'advance':value.fixOperation});
77
+ :await host.handle({requestId:value.requestId,operation:advancing?'advance':value.fixOperation,
78
+ ...(value.fixOperation==='abandon_step'?{reason:value.reason}:{})});
74
79
  }
75
- // Original observing finish intentionally closes its owner. Preserve
80
+ // Original observation/escalation finish intentionally closes its owner. Preserve
76
81
  // that successful incomplete exit without reading a closed store.
77
- if(acting&&value.fixOperation==='finish'&&actionResult?.observationRunEnded===true)
82
+ if(actionResult?.observationRunEnded===true||actionResult?.escalationRunEnded===true)
78
83
  return json({outcome:'blocked',code:'qa_fix_incomplete',fixStage:actionResult.stage,actionResult},12*1024*1024);
79
84
  const observed=child.status();
80
85
  result=observed.stage==='completed'&&observed.completionEligible===true
@@ -2,8 +2,8 @@
2
2
  import {executionDiagnostic} from './effect-contract.mjs';
3
3
 
4
4
  const LIMIT=64*1024;
5
- const operationNames=new Set(['recover_final_review','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
6
- 'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
5
+ const operationNames=new Set(['replace_inputs','read_batch','recover_final_review','abandon_step','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
6
+ 'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','prepare_judge_revision','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
7
7
 
8
8
  // Which contract codes may reach the peer is a deliberate boundary: the host
9
9
  // exposes chosen ones as a blocked result with a reason and redacts the rest to
@@ -16,5 +16,5 @@ export function createCmAiHost(options) {
16
16
  ...(qaExecutor===undefined?{}:{qaExecutor}),
17
17
  ...(documentationProvider===undefined?{}:{documentationProvider}),
18
18
  ...(qaDecisionProvider===undefined?{}:{qaDecisionProvider})});
19
- return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa});
19
+ return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa,reviseQa:runner.reviseQa,supersedeEvidence:runner.supersedeEvidence});
20
20
  }
@@ -0,0 +1,22 @@
1
+ // One METRICS.md table shape, shared by the fix and refactor closeouts.
2
+ // The 「Codex拦截」 column was renamed to 「独立审查拦截」 as a semantic upgrade of the
3
+ // same column — N4-review.md says exactly that: keep the original column order, upgrade
4
+ // what the old 「Codex拦截」 means. Matching the header as one exact string turned that
5
+ // rename into a hard wall instead: every METRICS.md written before it is refused with
6
+ // metrics_table_invalid / refactor_metrics_format, both closeouts stop, and there is no
7
+ // migration path. Accept every name this table has ever used, keep writing the current
8
+ // one for new files, and never rewrite the header inside a file the user owns.
9
+ export const METRICS_HEADER='| 任务 | Feature | 开始 | 结束 | 审查轮次 | 独立审查拦截 | QA | 人工介入(次:原因) |';
10
+ export const METRICS_SEPARATOR='| --- | --- | --- | --- | --- | --- | --- | --- |';
11
+
12
+ // Column order and count are identical across the rename, so a row written today lines
13
+ // up under either header. Only these exact lines count: an arbitrary table is still not
14
+ // this table, and is still refused by the callers.
15
+ const ACCEPTED_HEADERS=Object.freeze([METRICS_HEADER,
16
+ '| 任务 | Feature | 开始 | 结束 | 审查轮次 | Codex拦截 | QA | 人工介入(次:原因) |']);
17
+
18
+ export function hasMetricsHeader(content) {
19
+ if(typeof content!=='string')return false;
20
+ const lines=content.split(/\r?\n/);
21
+ return ACCEPTED_HEADERS.some(candidate=>lines.includes(candidate));
22
+ }
@@ -0,0 +1,85 @@
1
+ // Explicit QA-only configuration succession. No development state is replaced.
2
+ import {digest,json,shape,need,hex,id,text} from './effect-contract.mjs';
3
+ import {createHostQaExecutor} from './host-qa-executor.mjs';
4
+ import {validateHostWorkflowConfiguration} from './host-workflow-capabilities.mjs';
5
+ import {preQaConfigurations,readQaAttachment} from './qa-attachment.mjs';
6
+
7
+ const workflow=material=>material.execution?.workflow?.configuration??material.execution?.workflow;
8
+ export function qaConfigurationSlice(material){
9
+ const qa=workflow(material)?.qa,executor=material.qaExecutor,c=executor?.configuration;
10
+ need(qa&&c?.kind==='cm-host-qa-executor-v1','qa_revision_configuration_required');
11
+ return json({qa,mode:executor.mode,caseCount:executor.caseCount,timeoutMs:executor.timeoutMs,
12
+ executor:{commands:c.commands,environment:c.environment,timeoutMs:c.timeoutMs,
13
+ commandsPlan:c.plan.commands,modes:c.plan.modes}});
14
+ }
15
+ function withQaConfiguration(material,slice){
16
+ const result=structuredClone(json(material)),c=result.qaExecutor.configuration;
17
+ workflow(result).qa=slice.qa;
18
+ Object.assign(result.qaExecutor,{mode:slice.mode,caseCount:slice.caseCount,timeoutMs:slice.timeoutMs});
19
+ Object.assign(c,{commands:slice.executor.commands,environment:slice.executor.environment,timeoutMs:slice.executor.timeoutMs});
20
+ Object.assign(c.plan,{commands:slice.executor.commandsPlan,modes:slice.executor.modes});
21
+ return result;
22
+ }
23
+ export function qaInvariantDigest(material){
24
+ return digest(withQaConfiguration(material,{qa:null,mode:null,caseCount:null,timeoutMs:null,
25
+ executor:{commands:null,environment:null,timeoutMs:null,commandsPlan:null,modes:null}}));
26
+ }
27
+ export function previousQaMaterial(material,previousWorkflow){
28
+ qaConfigurationSlice(material);
29
+ const prior=validateHostWorkflowConfiguration(previousWorkflow),current=workflow(material);
30
+ need(prior.qa!==null,'qa_revision_configuration_required');
31
+ need(digest({...prior,qa:null})===digest({...current,qa:null}),'fingerprint_mismatch');
32
+ const result=structuredClone(json(material)),{kind,plan,capabilities,...configuration}=result.qaExecutor.configuration;
33
+ need(kind==='cm-host-qa-executor-v1','qa_revision_configuration_required');
34
+ // Rebuild the old plan using the same executor validator and unchanged project
35
+ // policy. These callbacks are capability markers and are never dispatched.
36
+ const executor=createHostQaExecutor({...configuration,commands:prior.qa.commands,environment:prior.qa.environment,
37
+ ...(capabilities.logic?{logic:()=>{}}:{}),...(capabilities.browser?{browser:()=>{}}:{})});
38
+ result.qaExecutor={version:1,mode:executor.mode,caseCount:executor.caseCount,timeoutMs:executor.timeoutMs,configuration:executor.configuration};
39
+ workflow(result).qa=prior.qa;
40
+ need(qaInvariantDigest(result)===qaInvariantDigest(material),'fingerprint_mismatch');
41
+ return result;
42
+ }
43
+ export function readQaConfigRevision(raw){
44
+ const r=json(raw);
45
+ shape(r,['version','fromFingerprint','toFingerprint','invariantDigest','previousQaDigest','qaDigest','reason','hostContextId',
46
+ 'revisedAt','packageDigest','testRunId','qaRound','taskAttempt']);
47
+ need(r.version===1,'qa_revision_invalid');
48
+ for(const key of ['fromFingerprint','toFingerprint','invariantDigest','packageDigest','previousQaDigest','qaDigest'])hex(r[key]);
49
+ need(r.fromFingerprint!==r.toFingerprint&&r.previousQaDigest!==r.qaDigest,'qa_revision_unchanged');
50
+ id(r.hostContextId);id(r.testRunId);text(r.reason);
51
+ need(r.reason.trim().length>0&&r.reason.length<=500&&!/[\r\n\0]/.test(r.reason),'qa_revision_authorization_required');
52
+ need(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(r.revisedAt)&&Number.isFinite(Date.parse(r.revisedAt)),'qa_revision_invalid');
53
+ need([1,2].includes(r.taskAttempt),'qa_revision_invalid');
54
+ need(Number.isInteger(r.qaRound)&&r.qaRound>=1&&r.qaRound<3,'qa_round_invalid');
55
+ return r;
56
+ }
57
+ export function qaRevisionChain(snapshot){
58
+ let fingerprint=snapshot.fingerprints.config,invariant=null,attached=false;const revisions=[];
59
+ for(const row of snapshot.records){
60
+ if(row.payload.type==='qa-attached'){
61
+ need(!attached,'qa_attachment_duplicate');attached=true;
62
+ need(revisions.length===0,'qa_revision_chain_invalid');fingerprint=readQaAttachment(row.payload.record).qaFingerprint;
63
+ }
64
+ if(row.payload.type!=='qa-config-revised')continue;
65
+ const r=readQaConfigRevision(row.payload.record);
66
+ need(r.fromFingerprint===fingerprint&&(invariant===null||r.invariantDigest===invariant)
67
+ &&(!revisions.length||(r.previousQaDigest===revisions.at(-1).qaDigest
68
+ &&r.qaRound>revisions.at(-1).qaRound)),'qa_revision_chain_invalid');
69
+ fingerprint=r.toFingerprint;invariant=r.invariantDigest;revisions.push(r);
70
+ }
71
+ return {fingerprint,revisions};
72
+ }
73
+ export function verifyQaRevisionMaterial(snapshot,material,prior=null){
74
+ const {fingerprint,revisions}=qaRevisionChain(snapshot);
75
+ const candidate=prior??material;
76
+ need(digest(candidate)===fingerprint,'fingerprint_mismatch');
77
+ if(revisions.length){
78
+ need(qaInvariantDigest(material)===revisions.at(-1).invariantDigest,'fingerprint_mismatch');
79
+ need(digest(qaConfigurationSlice(candidate))===revisions.at(-1).qaDigest,'fingerprint_mismatch');
80
+ }else{
81
+ const attached=snapshot.records.some(row=>row.payload.type==='qa-attached');
82
+ need((attached?preQaConfigurations(candidate):[candidate]).some(p=>digest(p)===snapshot.fingerprints.config),'fingerprint_mismatch');
83
+ }
84
+ return revisions;
85
+ }
@@ -1,7 +1,7 @@
1
1
  // Immutable file projection shared by review publishers, not an approval issuer.
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
- import {randomUUID} from 'node:crypto';
4
+ import {randomUUID,createHash} from 'node:crypto';
5
5
  import {need} from './effect-contract.mjs';
6
6
 
7
7
  export function writeReviewEvidence({reviewsDir,name,bytes,validate=()=>{},inspectOnly=false,exclusive=false}){
@@ -36,3 +36,20 @@ export function writeImmutableWorkflowFile({reviewsDir,name,bytes,validate=()=>{
36
36
  try{fs.unlinkSync(temp);}catch(error){if(error.code!=='ENOENT')throw error;}
37
37
  }
38
38
  }
39
+
40
+ // Move a workflow file aside without ever deleting its bytes: link into
41
+ // .superseded/ under a content-hash stamp, then unlink the original, so a crash
42
+ // between the two steps leaves both copies rather than neither. Callers decide
43
+ // *whether* a file may be superseded — this only knows how.
44
+ export function supersedeWorkflowFile(dir,name,existing){
45
+ const source=path.join(dir,name),archive=path.join(dir,'.superseded');
46
+ existing??=fs.readFileSync(source);
47
+ fs.mkdirSync(archive,{recursive:true,mode:0o700});
48
+ const stamp=createHash('sha256').update(existing).digest('hex').slice(0,16);
49
+ const target=path.join(archive,`${name}.${stamp}`);
50
+ try{fs.linkSync(source,target);}catch(error){if(error.code!=='EEXIST')throw error;}
51
+ fs.unlinkSync(source);
52
+ const fd=fs.openSync(archive,fs.constants.O_RDONLY);
53
+ try{fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
54
+ return target;
55
+ }
@@ -0,0 +1,144 @@
1
+ // Explicit restart boundary. Discovery reads old stores as immutable snapshots;
2
+ // only the new runner may record the authorization and move named projections.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {createHash} from 'node:crypto';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
9
+ import {readRunnerHistory} from './durable-runner-state.mjs';
10
+ import {supersedeWorkflowFile} from './review-evidence-file.mjs';
11
+ import {need,digest} from './effect-contract.mjs';
12
+ import {readEvidenceSupersession,supersedableEvidenceName} from './reviewed-evidence-supersession-record.mjs';
13
+ import {scanRows} from './cm-ai-qa-log.mjs';
14
+ import {parseCmAiTaskLine} from './cm-ai-admission.mjs';
15
+
16
+ const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
17
+ const unavailable=reason=>{const error=new Error('supersede_unavailable');error.code='supersede_unavailable';error.reason=reason;throw error;};
18
+ const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
19
+
20
+ function taskChecked(tasksPath,taskId){
21
+ const body=fs.readFileSync(tasksPath,'utf8');
22
+ const rows=body.split(/\r?\n/).map(parseCmAiTaskLine).filter(task=>task?.id===taskId);
23
+ if(rows.length!==1)unavailable('tasks.md 中任务身份不唯一或不存在');
24
+ return rows[0].completed;
25
+ }
26
+
27
+ function qaTerminal(specsDir,runId,taskId){
28
+ const log=path.join(specsDir,'运行日志.jsonl');if(!fs.existsSync(log))return 'never_finished';
29
+ let result='never_finished';
30
+ scanRows(log,row=>{
31
+ if(row.workflow!=='cm-ai'||row.run_id!==runId||row.task!==taskId)return;
32
+ if(row.event==='run_done')result='completed';
33
+ else if(result!=='completed'&&row.event==='test_run'&&row.phase==='complete')result=row.result;
34
+ });
35
+ return result;
36
+ }
37
+
38
+ function evidenceNames(reviewsDir,feature,taskId){
39
+ return fs.readdirSync(reviewsDir,{withFileTypes:true}).filter(entry=>entry.isFile()
40
+ &&supersedableEvidenceName(entry.name,feature,taskId))
41
+ .map(entry=>entry.name).sort();
42
+ }
43
+
44
+ export function oldWriterOpen(execution,runId,{lsofPath}={}){
45
+ // Inspect descriptor ownership without opening the old SQLite store.
46
+ const writerFile=path.join(execution,runId,'writer.sqlite');
47
+ const lsof=lsofPath??['/usr/sbin/lsof','/usr/bin/lsof'].find(file=>fs.existsSync(file));
48
+ if(lsof){
49
+ const result=spawnSync(lsof,['-F','p','--',writerFile],
50
+ {timeout:10000,maxBuffer:64*1024,encoding:'utf8'});
51
+ const diagnostics=(result.stderr??'').split(/\r?\n/).filter(line=>line.trim()&&!/^lsof: WARNING:/.test(line));
52
+ if(result.error||result.signal||![0,1].includes(result.status)||diagnostics.length)
53
+ unavailable(`无法核对旧运行 ${runId} 的 writer 状态`);
54
+ if(result.status===0&&!/^p\d+$/m.test(result.stdout))unavailable(`无法核对旧运行 ${runId} 的 writer 状态`);
55
+ return result.status===0;
56
+ }
57
+ const fuser='/usr/bin/fuser';
58
+ if(process.platform==='linux'&&fs.existsSync(fuser)){
59
+ const result=spawnSync(fuser,[writerFile],{timeout:3000,maxBuffer:64*1024,encoding:'utf8'});
60
+ if(result.error||result.signal||![0,1].includes(result.status))
61
+ unavailable(`无法核对旧运行 ${runId} 的 writer 状态`);
62
+ if(result.status===0&&!/\b\d+\b/.test(result.stdout))unavailable(`无法核对旧运行 ${runId} 的 writer 状态`);
63
+ return result.status===0;
64
+ }
65
+ unavailable(`缺少核对旧运行 ${runId} writer 占用的本地工具`);
66
+ }
67
+
68
+ export function prepareReviewedEvidenceSupersession({specsDir,codeProject,feature,identity,reason,tasksPath}){
69
+ if(typeof reason!=='string'||!reason.trim()||Buffer.byteLength(reason,'utf8')>500||/[\r\n\0]/.test(reason))
70
+ unavailable('必须提供单行且不超过 500 字节的 --supersede-reason');
71
+ if(taskChecked(tasksPath,identity.taskId))unavailable('tasks.md 已将任务标为完成;若 QA BLOCKED 后确需重跑,先将该任务改回 - [ ],再以 --supersede-reviewed-evidence 和 --supersede-reason 创建新运行');
72
+ const reviewsDir=path.join(specsDir,'.reviews');
73
+ if(!fs.existsSync(reviewsDir))unavailable('没有可替换的旧任务证据');
74
+ const execution=path.join(reviewsDir,'.execution');
75
+ const previousRunIds=[];
76
+ if(fs.existsSync(execution))for(const entry of fs.readdirSync(execution,{withFileTypes:true})){
77
+ if(!entry.isDirectory()||entry.name===identity.runId)continue;
78
+ const stateFile=path.join(execution,entry.name,'state.json');
79
+ if(!fs.existsSync(stateFile))continue;
80
+ let snapshot;
81
+ try{snapshot=readExecutionSnapshot({specsRoot:specsDir,
82
+ identity:{repositoryId:identity.repositoryId,runId:entry.name}});}
83
+ catch(error){if(error.code==='identity_mismatch')continue;throw error;}
84
+ const first=snapshot.records[0]?.payload;
85
+ if(first?.config?.identity?.taskId!==identity.taskId||first?.config?.taskLearning?.feature!==feature)continue;
86
+ if(first.config.identity.repositoryId!==identity.repositoryId||first.config.identity.runId!==entry.name
87
+ ||first.config.root!==codeProject||first.config.completion?.owner?.specsRoot!==specsDir
88
+ ||first.config.completion?.owner?.tasksPath!==tasksPath)
89
+ unavailable(`旧运行 ${entry.name} 的任务身份或路径不匹配`);
90
+ if(first.version!==3)unavailable(`旧运行 ${entry.name} 的 journal 版本无法验证`);
91
+ const history=readRunnerHistory(snapshot.records,first.config,3);
92
+ if(history.pending||!['blocked','cancelled','unknown','fixture_completed'].includes(history.state.state))
93
+ unavailable(`旧运行 ${entry.name} 仍可继续或有未结操作`);
94
+ if(oldWriterOpen(execution,entry.name))unavailable(`旧运行 ${entry.name} 的 writer 仍被进程持有`);
95
+ const qa=qaTerminal(specsDir,entry.name,identity.taskId);
96
+ if(history.state.state==='fixture_completed'&&!['BLOCKED','never_finished'].includes(qa))
97
+ unavailable(`旧运行 ${entry.name} 已完成或 QA 已通过`);
98
+ previousRunIds.push(entry.name);
99
+ }
100
+ if(!previousRunIds.length)unavailable('没有同 feature、task 的旧运行');
101
+ const names=evidenceNames(reviewsDir,feature,identity.taskId);
102
+ if(!names.length)unavailable('没有可归档的旧任务证据');
103
+ const files=names.map(name=>{
104
+ const p=path.join(reviewsDir,name),stat=fs.lstatSync(p);
105
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1)unavailable(`证据文件不可安全归档:${name}`);
106
+ return {name,sha256:hash(fs.readFileSync(p))};
107
+ });
108
+ return readEvidenceSupersession({version:1,feature,taskId:identity.taskId,newRunId:identity.runId,
109
+ previousRunIds:previousRunIds.sort(),reason,files,authorizedAt:new Date().toISOString()});
110
+ }
111
+
112
+ export function archiveReviewedEvidence(reviewsDir,raw){
113
+ const record=readEvidenceSupersession(raw);
114
+ const archive=path.join(reviewsDir,'.superseded');
115
+ for(const file of record.files){
116
+ const source=path.join(reviewsDir,file.name),target=path.join(archive,`${file.name}.${file.sha256.slice(0,16)}`);
117
+ let archived=false;
118
+ if(fs.existsSync(target)){
119
+ const stat=fs.lstatSync(target);
120
+ need(stat.isFile()&&!stat.isSymbolicLink()&&hash(fs.readFileSync(target))===file.sha256,'supersede_archive_conflict');
121
+ archived=true;
122
+ }
123
+ if(fs.existsSync(source)){
124
+ const stat=fs.lstatSync(source);
125
+ need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink<=2,'supersede_file_changed');
126
+ if(hash(fs.readFileSync(source))===file.sha256)supersedeWorkflowFile(reviewsDir,file.name);
127
+ else need(archived,'supersede_file_changed'); // New run has already published its own bytes.
128
+ }
129
+ need(fs.existsSync(target)&&hash(fs.readFileSync(target))===file.sha256,'supersede_archive_missing');
130
+ }
131
+ return record;
132
+ }
133
+
134
+ export function recordEvidenceSupersession({specsDir,codeProject,identity,record,logHome}){
135
+ const data={node:'N3',feature:record.feature,task:record.taskId,
136
+ previous_run_count:record.previousRunIds.length,file_count:record.files.length,
137
+ record_digest:digest(record),reason:record.reason};
138
+ const args=[writer,'--workflow','cm-ai','--event','supersede','--runtime','codex',
139
+ '--project-root',codeProject,'--specs-dir',specsDir,'--run-id',identity.runId,
140
+ '--at',record.authorizedAt,'--detail','显式归档旧任务证据','--data-json',JSON.stringify(data)];
141
+ const result=spawnSync('python3',args,{timeout:10000,maxBuffer:1024*1024,
142
+ ...(logHome?{env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}}:{})});
143
+ need(!result.error&&result.status===0,'supersede_log_failed');
144
+ }
@@ -0,0 +1,34 @@
1
+ // Strict V3 payload grammar, shared by live authorization and journal replay.
2
+ import {need,shape,id,hex,json} from './effect-contract.mjs';
3
+
4
+ export function readEvidenceSupersession(raw,expected=null){
5
+ const record=json(raw,1024*1024);
6
+ shape(record,['version','feature','taskId','newRunId','previousRunIds','reason','files','authorizedAt']);
7
+ need(record.version===1,'supersede_record_invalid');
8
+ need(typeof record.authorizedAt==='string'
9
+ &&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(record.authorizedAt)
10
+ &&!Number.isNaN(Date.parse(record.authorizedAt)),'supersede_record_invalid');
11
+ for(const key of ['feature','taskId','newRunId'])id(record[key]);
12
+ need(Array.isArray(record.previousRunIds)&&record.previousRunIds.length>0&&record.previousRunIds.length<=128,'supersede_record_invalid');
13
+ const runs=new Set();for(const runId of record.previousRunIds){id(runId);need(!runs.has(runId)&&runId!==record.newRunId,'supersede_record_invalid');runs.add(runId);}
14
+ need(typeof record.reason==='string'&&record.reason.trim()&&Buffer.byteLength(record.reason,'utf8')<=500
15
+ &&!/[\r\n\0]/.test(record.reason),'supersede_reason_required');
16
+ need(Array.isArray(record.files)&&record.files.length>0&&record.files.length<=256,'supersede_record_invalid');
17
+ const names=new Set();for(const file of record.files){
18
+ shape(file,['name','sha256']);
19
+ need(typeof file.name==='string'&&/^[A-Za-z0-9._-]+\.(md|json)$/.test(file.name)
20
+ &&supersedableEvidenceName(file.name,record.feature,record.taskId)
21
+ &&!names.has(file.name),'supersede_record_invalid');
22
+ names.add(file.name);hex(file.sha256);
23
+ }
24
+ if(expected)need(record.feature===expected.feature&&record.taskId===expected.taskId
25
+ &&record.newRunId===expected.newRunId,'supersede_record_invalid');
26
+ return record;
27
+ }
28
+
29
+ export function supersedableEvidenceName(name,feature,taskId){
30
+ const prefix=`${feature.replace(/^\d+\./,'')}-${taskId}-`;
31
+ if(!name.startsWith(prefix))return false;
32
+ const suffix=name.slice(prefix.length);
33
+ return /^(?:a[12]-handoff\.json|r[12]\.md|(?:correction|qa)[A-Za-z0-9._-]*\.(?:md|json))$/.test(suffix);
34
+ }
@@ -1,3 +1,4 @@
1
+ import {readQaConfigRevision} from './qa-config-revision.mjs';
1
2
  import {readQaAttachment} from './qa-attachment.mjs';
2
3
  // Trusted synthetic fixture host; explicit V2 supports isolated task-file writes.
3
4
  import { randomUUID } from 'node:crypto';
@@ -11,7 +12,7 @@ import { digest,need,shape,id,text,json,freeze,arrayItems,validIdentity,validTas
11
12
  import { reviewResult,reviewReceipt } from './review-runner.mjs';
12
13
  import { checkCompletion } from './gate-bridge.mjs';
13
14
  import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
14
- controlledState,stageAllowed,completedEffectCount,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage } from './durable-runner-state.mjs';
15
+ MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,completedEffectCount,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage } from './durable-runner-state.mjs';
15
16
  import {commitRunnerFixture} from './task-commit.mjs';
16
17
  import {inspectProviderReview,hasProviderReviewResult} from './provider-review-observation.mjs';
17
18
  import {attachCmAiTaskLearningApplicationEvidence,attachCmAiTaskLearningEvidence,
@@ -27,6 +28,7 @@ import {publishHostReview} from './host-review-file.mjs';
27
28
  import {reviewExclusions} from './effect-contract.mjs';
28
29
  import {bootstrapConfiguration,readBootstrapEvidence} from './host-bootstrap.mjs';
29
30
  import {validateCodeProjectPaths,assertCodeProjectSelections} from './code-projects.mjs';
31
+ import {readEvidenceSupersession} from './reviewed-evidence-supersession-record.mjs';
30
32
 
31
33
  // Keep default V1 imports free of SQLite initialization/warnings. Native ownership
32
34
  // is loaded synchronously only at the explicit V2 boundary (Node24.14+).
@@ -124,10 +126,14 @@ export function createTaskRunner(options) {
124
126
  if(invocationMode)id(r.adapterId);
125
127
  return {...v,...(invocationMode?{adapterId:r.adapterId}:{}),run};
126
128
  });
127
- let invocationConfig=null,authorize=null;
129
+ let invocationConfig=null,authorize=null,liveHostContextId=null;
128
130
  if(invocationMode){
129
131
  need(reviewers.length===1&&['codex','claude'].includes(reviewers[0].provider)&&reviewers[0].allowed&&reviewers[0].available,'runner_invocation');
130
- shape(options.reviewInvocation,['developerThreadId','excludedThreadIds','authorize']);
132
+ shape(options.reviewInvocation,['developerThreadId','excludedThreadIds','authorize',
133
+ ...(Object.hasOwn(options.reviewInvocation,'hostContextId')?['hostContextId']:[])]);
134
+ liveHostContextId=options.reviewInvocation.hostContextId??null;
135
+ if(liveHostContextId!==null){id(liveHostContextId);
136
+ need(![developer.contextId,...reviewers.flatMap(r=>r.contexts)].includes(liveHostContextId),'not_independent');}
131
137
  authorize=options.reviewInvocation.authorize;need(typeof authorize==='function','runner_invocation');
132
138
  invocationConfig=json({developerThreadId:options.reviewInvocation.developerThreadId,
133
139
  excludedThreadIds:options.reviewInvocation.excludedThreadIds});
@@ -178,6 +184,11 @@ export function createTaskRunner(options) {
178
184
  if(options.persistence.mode==='resume')restored=readRunnerHistory(journal,metadata,version);
179
185
  else need(journal.length===0,'runner_exists');
180
186
  }
187
+ // Transient live identity is deliberately absent from metadata/init bytes.
188
+ const joinedHosts=[...(restored?.joinedHosts??[])];
189
+ if(liveHostContextId!==null)need(!restored?.reviewerThreads.includes(liveHostContextId),'not_independent');
190
+ const liveInvocation=()=>({...invocationConfig,excludedThreadIds:[...new Set([
191
+ ...invocationConfig.excludedThreadIds,...joinedHosts,...(liveHostContextId===null?[]:[liveHostContextId])])]});
181
192
  const specificationSelection=options.specification??null;
182
193
  if(specificationSelection!==null){
183
194
  shape(specificationSelection,['specsRoot','feature']);
@@ -258,7 +269,8 @@ export function createTaskRunner(options) {
258
269
  kind:{init:'result','effect-intent':'intent','effect-checkpoint':'result',control:'cancel',
259
270
  'task-commit-intent':'commit-intent','task-commit-result':'commit-result',
260
271
  'review-invocation-registered':'intent','review-invocation-started':'result','review-invocation-result':'result',
261
- 'qa-fix-accepted':'result','qa-attached':'result'}[type],
272
+ 'host-joined':'result','qa-fix-accepted':'result','qa-attached':'result','qa-config-revised':'result',
273
+ 'evidence-superseded':'result'}[type],
262
274
  payload:version===3?runnerPayloadV3(type,fields):runnerPayload(type,fields,version)};
263
275
  const body={version:1,seq:journal.length+1,...basic,previousDigest:journal.at(-1)?.digest??null};
264
276
  const record={...body,digest:digest(body)};boundRunnerRecord(record,body.seq);
@@ -433,11 +445,17 @@ export function createTaskRunner(options) {
433
445
  try{registeredAt=safeTime();}catch{halt('unknown','clock_invalid');return;}
434
446
  if(registeredAt<authorizationAt){halt('unknown','clock_invalid');return;}
435
447
  try{grant=validateReviewDispatchGrant(grant,{request,reviewerId:adapter.id,adapterId:adapter.adapterId,
436
- packageDigest:reviewPackage.packageDigest,hostContextIds:[invocationConfig.developerThreadId,...invocationConfig.excludedThreadIds],
448
+ packageDigest:reviewPackage.packageDigest,hostContextIds:[invocationConfig.developerThreadId,...liveInvocation().excludedThreadIds],
437
449
  authorizationAt,registeredAt});}
438
450
  catch{halt('unknown','authorization_invalid');return;}
439
451
  const registrationFields={effectId,reviewerId:adapter.id,adapterId:adapter.adapterId,requestDigest:request.requestDigest,
440
452
  authorizationAt,registeredAt,grant};
453
+ // Validate first, then journal the signer immediately before registration.
454
+ // Durable host lists and prior joiners already have replayable authority.
455
+ if(![invocationConfig.developerThreadId,...invocationConfig.excludedThreadIds,...joinedHosts].includes(grant.hostContextId)){
456
+ need(joinedHosts.length<MAX_AI_JOINED_HOSTS,'host_limit');
457
+ persist('host-joined',{hostContextId:grant.hostContextId});joinedHosts.push(grant.hostContextId);
458
+ }
441
459
  persist('review-invocation-registered',registrationFields);
442
460
  sequence=nextSequence;
443
461
  const registration=json({reviewerId:adapter.id,adapterId:adapter.adapterId,requestDigest:request.requestDigest,
@@ -459,7 +477,7 @@ export function createTaskRunner(options) {
459
477
  }
460
478
  call.started=true;
461
479
  const expectation={request,developerThreadId:invocationConfig.developerThreadId,
462
- excludedThreadIds:reviewExclusions(invocationConfig,calls,developer.contextId)};
480
+ excludedThreadIds:reviewExclusions(liveInvocation(),calls,developer.contextId)};
463
481
  const events=[];let started=null,sealed=false,invalid=false,invalidReject;
464
482
  const localController=new AbortController();
465
483
  const abort=()=>localController.abort();controller.signal.addEventListener('abort',abort,{once:true});
@@ -740,7 +758,7 @@ export function createTaskRunner(options) {
740
758
  busy=true;if(v.kind!=='develop')code=null;
741
759
  pending=(async()=>{
742
760
  try {await perform(v);}
743
- catch(error){if(state!=='cancelled')halt(error.code==='spec_drift'?'blocked':'unknown',failureCode(error));}
761
+ catch(error){if(state!=='cancelled'){const code=failureCode(error);halt(code==='spec_drift'?'blocked':'unknown',code);}}
744
762
  if(poisoned)return status();
745
763
  const result=privateStatus();cache.set(v.id,{effect:v,digest:digest(v),result});
746
764
  try{persist('effect-checkpoint',{effectId:v.id,checkpoint:frame()});publication=result;return result;}
@@ -831,7 +849,22 @@ export function createTaskRunner(options) {
831
849
  need(state==='fixture_completed','qa_attach_not_completed');
832
850
  persist('qa-attached',{record});qaAttachment=record;return json(record);
833
851
  };
834
- const api={executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks};
852
+ const reviseQa=raw=>{
853
+ need(invocationMode&&store&&!busy&&!poisoned,'qa_revision_unavailable');
854
+ const record=readQaConfigRevision(raw),current=status();
855
+ need(current.state==='fixture_completed'&&current.code===null,'qa_revision_not_completed');
856
+ need(current.packageDigest===record.packageDigest,'package_mismatch');
857
+ persist('qa-config-revised',{record});return json(record);
858
+ };
859
+ const supersedeEvidence=raw=>{
860
+ need(invocationMode&&store&&!busy&&!poisoned,'supersede_unavailable');
861
+ const record=readEvidenceSupersession(raw,{feature:taskLearning.feature,
862
+ taskId:config.identity.taskId,newRunId:config.identity.runId});
863
+ if(restored?.supersession){need(digest(restored.supersession)===digest(record),'supersede_record_invalid');return json(record);}
864
+ need(journal.length===1&&state==='ready','supersede_unavailable');
865
+ persist('evidence-superseded',{record});return json(record);
866
+ };
867
+ const api={reviseQa,supersedeEvidence,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks};
835
868
  if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
836
869
  if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
837
870
  return Object.freeze(api);