@aibyzero/cm-workflow 0.21.6 → 0.25.0

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 (212) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +58 -0
  3. package/README.md +18 -3
  4. package/VERSION +1 -1
  5. package/docs/architecture.md +9 -0
  6. package/docs/cm-acceptance-completion.md +3 -1
  7. package/docs/cm-control-policy-v2.md +35 -3
  8. package/docs/execution-optimizations.md +1 -1
  9. package/docs/external-models.md +1 -0
  10. package/docs/human-correction.md +1 -1
  11. package/docs/installation.md +42 -16
  12. package/docs/js-workflow-control.md +65 -30
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +5 -3
  15. package/docs/user-guide.md +6 -6
  16. package/package.json +1 -1
  17. package/runtime/js/cm-ai/batch-location.mjs +14 -0
  18. package/runtime/js/cm-ai/batch-plan.mjs +6 -2
  19. package/runtime/js/cm-ai/checkpoint-package-material.mjs +9 -2
  20. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  21. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  22. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  24. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  25. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  26. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  27. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  28. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  29. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  30. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  31. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  32. package/runtime/js/cm-ai/host-check.mjs +4 -2
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +23 -2
  34. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  35. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  36. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  37. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  38. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  39. package/runtime/js/cm-ai/host-session.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  45. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  46. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  47. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  48. package/runtime/js/cm-ai/review-package.mjs +25 -4
  49. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  50. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  51. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  52. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  53. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  54. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  55. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  56. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  57. package/runtime/js/cm-ai/tool-preview.mjs +6 -0
  58. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  59. package/runtime/js/cm-fix/execution.mjs +47 -9
  60. package/runtime/js/cm-fix/finish.mjs +9 -1
  61. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  62. package/runtime/js/cm-idea/session.mjs +22 -3
  63. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  64. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  65. package/runtime/js/cm-prd/analysis.mjs +27 -9
  66. package/runtime/js/cm-prd/change.mjs +29 -8
  67. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  68. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  69. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  70. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  71. package/runtime/js/cm-prd/self-check.mjs +121 -9
  72. package/runtime/js/cm-prd/session.mjs +55 -13
  73. package/runtime/js/cm-prd/summary.mjs +34 -6
  74. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  75. package/runtime/js/cm-refactor/records.mjs +82 -11
  76. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  77. package/runtime/js/executor-version.mjs +81 -0
  78. package/runtime/js/python-log-writer.mjs +15 -0
  79. package/runtime/js/run-analysis.mjs +136 -11
  80. package/runtime/logging.md +6 -0
  81. package/runtime/review.md +3 -1
  82. package/runtime/workflow-config.md +1 -1
  83. package/scripts/ci-test-weights.json +1 -0
  84. package/scripts/cm-ai-admission.mjs +27 -1
  85. package/scripts/cm-ai-admission.test.mjs +34 -2
  86. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  87. package/scripts/cm-ai-batch-drive.mjs +54 -17
  88. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  89. package/scripts/cm-ai-batch-host.mjs +55 -9
  90. package/scripts/cm-ai-batch-host.test.mjs +22 -3
  91. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  92. package/scripts/cm-ai-batch-merge.mjs +102 -0
  93. package/scripts/cm-ai-batch-plan.mjs +55 -2
  94. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  95. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  96. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  97. package/scripts/cm-ai-batch-run.mjs +435 -33
  98. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  99. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  100. package/scripts/cm-ai-checkpoint-package-material.test.mjs +28 -0
  101. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  102. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  103. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  104. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  105. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  106. package/scripts/cm-ai-drive.mjs +66 -14
  107. package/scripts/cm-ai-drive.test.mjs +13 -3
  108. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  109. package/scripts/cm-ai-host.mjs +16 -8
  110. package/scripts/cm-ai-host.test.mjs +12 -0
  111. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  112. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  113. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  114. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  115. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  116. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  117. package/scripts/cm-ai-run.mjs +42 -11
  118. package/scripts/cm-ai-run.test.mjs +26 -0
  119. package/scripts/cm-ai-supersede.test.mjs +10 -2
  120. package/scripts/cm-capability-gate.test.mjs +1 -1
  121. package/scripts/cm-check-runtime.sh +9 -0
  122. package/scripts/cm-codex-clean-env.test.mjs +40 -0
  123. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  124. package/scripts/cm-developer-self-review.test.mjs +27 -0
  125. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  126. package/scripts/cm-efficiency-response.test.mjs +2 -1
  127. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  128. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  129. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  130. package/scripts/cm-executor-version-records.test.mjs +256 -0
  131. package/scripts/cm-executor-version.test.mjs +250 -0
  132. package/scripts/cm-external-model-host.test.mjs +6 -1
  133. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  134. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  135. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  136. package/scripts/cm-fix-drive.mjs +7 -2
  137. package/scripts/cm-fix-drive.test.mjs +45 -0
  138. package/scripts/cm-fix-entry.mjs +5 -2
  139. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  140. package/scripts/cm-fix-host.mjs +9 -2
  141. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  142. package/scripts/cm-host-check.test.mjs +12 -0
  143. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  144. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  145. package/scripts/cm-idea-drive.mjs +5 -2
  146. package/scripts/cm-idea-entry.mjs +5 -2
  147. package/scripts/cm-idea-host.mjs +3 -1
  148. package/scripts/cm-init-drive.mjs +8 -5
  149. package/scripts/cm-init-entry.mjs +5 -2
  150. package/scripts/cm-init-host.mjs +6 -2
  151. package/scripts/cm-log-event.mjs +10 -2
  152. package/scripts/cm-log-event.test.mjs +29 -0
  153. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  154. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  155. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  156. package/scripts/cm-prd-completion.test.mjs +67 -4
  157. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  158. package/scripts/cm-prd-drive.mjs +89 -20
  159. package/scripts/cm-prd-drive.test.mjs +109 -4
  160. package/scripts/cm-prd-entry.mjs +5 -2
  161. package/scripts/cm-prd-host.mjs +89 -20
  162. package/scripts/cm-prd-host.test.mjs +17 -8
  163. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  164. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  165. package/scripts/cm-prd-review-gate.mjs +11 -4
  166. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  167. package/scripts/cm-prd-self-check.test.mjs +1 -1
  168. package/scripts/cm-refactor-drive.mjs +10 -4
  169. package/scripts/cm-refactor-entry.mjs +5 -2
  170. package/scripts/cm-refactor-host.mjs +3 -1
  171. package/scripts/cm-run-analysis.test.mjs +373 -1
  172. package/scripts/cm-runtime-i18n.mjs +3 -3
  173. package/scripts/cm-runtime-install.mjs +19 -10
  174. package/scripts/cm-runtime.mjs +2 -4
  175. package/scripts/cm-runtime.test.mjs +55 -13
  176. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  177. package/scripts/cm-skill-hints-exam.mjs +3 -1
  178. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  179. package/scripts/cm-skill-hints.mjs +106 -10
  180. package/scripts/cm-skill-hints.test.mjs +162 -6
  181. package/scripts/cm-skill-judge.mjs +2 -1
  182. package/scripts/cm-statusline.test.mjs +54 -0
  183. package/scripts/cm-task-gate.mjs +88 -18
  184. package/scripts/cm-task-scope.test.mjs +1 -1
  185. package/scripts/cm-test-drive.mjs +13 -8
  186. package/scripts/cm-test-entry.mjs +5 -2
  187. package/scripts/cm-test-host.mjs +3 -1
  188. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  189. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  190. package/scripts/fixtures/prd-review-gate-python-oracle.py +9 -0
  191. package/scripts/policy-binding-compat.test.mjs +3 -2
  192. package/scripts/test-cm-prd-review-gate.py +25 -0
  193. package/skills/cm-ai/SKILL.md +1 -1
  194. package/skills/cm-ai/references/N1-init.md +4 -3
  195. package/skills/cm-ai/references/N4-review.md +6 -3
  196. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  197. package/skills/cm-ai/references/js-host-recovery.md +4 -1
  198. package/skills/cm-ai/references/js-host.md +25 -5
  199. package/skills/cm-fix/references/js-host.md +20 -0
  200. package/skills/cm-fix/references/test-extension.md +1 -1
  201. package/skills/cm-prd/SKILL.md +8 -6
  202. package/skills/cm-prd/references/ai-draft.md +81 -0
  203. package/skills/cm-prd/references/change-mode.md +2 -0
  204. package/skills/cm-prd/references/greenfield.md +2 -0
  205. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  206. package/skills/cm-prd/references/js-host.md +9 -6
  207. package/skills/cm-prd/references/light-mode.md +19 -0
  208. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  209. package/skills/cm-prd/references/spec-self-check.md +1 -0
  210. package/skills/cm-prd/references/summary-card.md +1 -0
  211. package/skills/cm-runtime/SKILL.md +6 -6
  212. package/templates/statusline/cm-statusline.sh +63 -1
@@ -41,7 +41,7 @@ const prefix=(a,b)=>{need(b.length>=a.length,'runner_history_mismatch');same(a,b
41
41
  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');
42
42
  const states=['ready','awaiting_review','approved','changes_requested','fixture_completed','blocked','unknown','cancelled','pending_review'];
43
43
  export const stageAllowed=(kind,state,code=null,reviewVerdict=null)=>
44
- kind==='develop'&&state==='blocked'&&['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed','bootstrap_instruction_conflict','develop_call_timeout','develop_answer_invalid',...RECHECK_CODES,DEVELOP_REDO_CODE,DISPATCH_RETRY_CODE,DEVELOP_INTERRUPTED_CODE,...DOCUMENTATION_SYNC_CODES].includes(code)
44
+ kind==='develop'&&state==='blocked'&&['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_continuation_scope_mismatch','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed','bootstrap_instruction_conflict','develop_call_timeout','develop_answer_invalid',...RECHECK_CODES,DEVELOP_REDO_CODE,DISPATCH_RETRY_CODE,DEVELOP_INTERRUPTED_CODE,...DOCUMENTATION_SYNC_CODES].includes(code)
45
45
  ||kind==='review'&&state==='pending_review'&&REVIEW_RETRY_CODES.includes(code)
46
46
  ||kind==='complete'&&state==='blocked'&&(['completion_checks_changed','completion_package_changed',COMPLETE_RECHECK_CODE].includes(code)
47
47
  ||code==='review_package_changed'&&reviewVerdict==='approved')
@@ -532,21 +532,28 @@ export const completedEffectCount=(cache,calls=[],recheckEffects=[])=>cache.filt
532
532
  // The six-effect cap counts develop and review effects only; completion (above),
533
533
  // QA, documentation and finalization hold no slot.
534
534
  export const MAX_RUNNER_EFFECTS=6;
535
+ // An authorized third controlled review gets exactly one develop and one review
536
+ // slot counted from its authorization, never fewer than the original caps leave
537
+ // (user decision 2026-12-01, dogfood finding 12: a failed-check retry had used the
538
+ // original slots, leaving only a full restart). The baseline is derived on replay.
539
+ export const REVIEW_CONTINUATION_SLOTS=2;
540
+ const callCap=continuation=>continuation?Math.max(MAX_RUNNER_CALLS,continuation.baseCalls+REVIEW_CONTINUATION_SLOTS):MAX_RUNNER_CALLS;
541
+ const effectCap=continuation=>continuation?Math.max(MAX_RUNNER_EFFECTS,continuation.baseEffects+REVIEW_CONTINUATION_SLOTS):MAX_RUNNER_EFFECTS;
535
542
  // Only develop and review intents need a free slot; complete is gated by stage.
536
543
  // Only journal-derived rework identities may use the one extra slot. Once its
537
544
  // develop intent is recorded, even a free timeout slot cannot dispatch again.
538
- export const effectSlotFree=(kind,cache,calls,recheckEffects=[],rework=null,effectId=null,before=null)=>{
545
+ export const effectSlotFree=(kind,cache,calls,recheckEffects=[],rework=null,effectId=null,before=null,continuation=null)=>{
539
546
  if(kind==='complete')return true;
540
547
  const checkOnly=kind==='develop'&&before?.state==='blocked'&&RECHECK_CODES.includes(before.code);
541
548
  if(rework&&kind==='develop'&&!checkOnly&&(rework.developerConsumed||effectId!==rework.developerEffectId))return false;
542
549
  const bound=rework&&(kind==='develop'&&!rework.developerConsumed&&effectId===rework.developerEffectId
543
550
  ||checkOnly&&rework.developerConsumed
544
551
  ||kind==='review'&&rework.developerConsumed&&/^review-2(?:-retry-[1-9][0-9]*)?(?:-resume-[1-9][0-9]*)?$/.test(effectId??''));
545
- return completedEffectCount(cache,calls,recheckEffects)<MAX_RUNNER_EFFECTS+(bound?1:0);
552
+ return completedEffectCount(cache,calls,recheckEffects)<effectCap(continuation)+(bound?1:0);
546
553
  };
547
554
  export const verificationBlockCount=(cache,recheckEffects=[])=>cache.filter(entry=>entry.effect.kind==='develop'
548
555
  &&entry.result?.state==='blocked'
549
- &&['verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed','bootstrap_instruction_conflict','develop_call_timeout'].includes(entry.result?.code)
556
+ &&['verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_continuation_scope_mismatch','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed','bootstrap_instruction_conflict','develop_call_timeout'].includes(entry.result?.code)
550
557
  ||developTimeoutEffect(entry)||developAnswerInvalidEffect(entry)||developRecheckSource(entry)||developRedoSource(entry)||developDispatchFailedEffect(entry)
551
558
  ||documentationSyncSource(entry)||recheckEffects.includes(entry.effect.id)).length;
552
559
  // A delivery is only worth starting while it could still be reviewed: its own
@@ -557,13 +564,13 @@ export const verificationBlockCount=(cache,recheckEffects=[])=>cache.filter(entr
557
564
  // also holds a counted call, so the call term decides; the effect term keeps
558
565
  // the rule true for blocks that could stop before their developer call.)
559
566
  export const developBudget=(s,recheckEffects=[])=>({calls:countedCalls(s.calls,s.cache),effects:completedEffectCount(s.cache,s.calls,recheckEffects)});
560
- export const developBudgetExhausted=(s,recheckEffects=[],rework=null)=>{
567
+ export const developBudgetExhausted=(s,recheckEffects=[],rework=null,continuation=null)=>{
561
568
  if(!stageAllowed('develop',s.state,s.code,s.priorReview?.verdict))return false;
562
569
  // A re-check makes no developer call: only its review needs one.
563
570
  const used=developBudget(s,recheckEffects),calls=RECHECK_CODES.includes(s.code)?1:2;
564
571
  const credit=rework&&s.attempt===2&&s.state==='blocked'
565
572
  &&(!rework.developerConsumed&&s.code==='develop_checks_not_passed'||rework.developerConsumed&&RECHECK_CODES.includes(s.code))?1:0;
566
- return used.calls+calls>MAX_RUNNER_CALLS||used.effects+2>MAX_RUNNER_EFFECTS+credit;
573
+ return used.calls+calls>callCap(continuation)||used.effects+2>effectCap(continuation)+credit;
567
574
  };
568
575
  // At most this many re-checks after a blocked completion. Each re-runs only the
569
576
  // local checks and the commit gate, so a small fixed bound keeps the journal
@@ -641,15 +648,51 @@ export function applyDevelopmentRework(records,s,config,original,record,rechecks
641
648
  'development_rework_unavailable');
642
649
  return {...s,state:'blocked',code:'develop_checks_not_passed',reason:null};
643
650
  }
651
+ // Third controlled review (review-continuation-authorized). Like development_rework
652
+ // it is derived from history: any v2 single-task run stopped on review_limit may be
653
+ // explicitly authorized at launch. The authorization keeps attempt 2, both original
654
+ // receipts and every count; it only lets one more in-scope correction delivery
655
+ // reach one more fresh review.
656
+ export const REVIEW_CONTINUATION_REJECTED='review_continuation_rejected';
657
+ export function reviewContinuationBinding(records,s,config,used=null){
658
+ const [first,second]=s.receipts??[];
659
+ need(used===null&&config.controlPolicy?.version===2
660
+ &&config.controlPolicy.development==='conversation'&&config.controlPolicy.bootstrap==='disabled'&&config.bootstrap==null
661
+ &&(config.parallelSelection??null)===null&&!config.codeProjectPaths&&!config.externalModels&&!config.executionPolicy
662
+ &&config.developer.requestedModel==='current-session'
663
+ // Batch members (cm-ai-batch-run.mjs batchTaskRunId, both generations) are
664
+ // refused by their fixed run-ID shape: the batch entry has no grant path.
665
+ &&!/^task-[0-9a-f]{48}$/.test(config.identity.runId)
666
+ &&s.state==='blocked'&&s.code==='review_limit'&&s.attempt===2
667
+ &&s.taskCommit==null&&!s.cancellationRequested&&!s.cancelAfterCommit&&!s.workflowError
668
+ &&s.receipts.length===2&&first.identity.attempt===1&&second.identity.attempt===2
669
+ &&first.result.verdict==='changes_requested'&&second.result.verdict==='changes_requested'
670
+ &&s.priorReview?.verdict==='changes_requested'&&digest(s.receipt)===digest(second)
671
+ &&s.reviewPackage?.identity.attempt===2&&s.reviewPackage.packageDigest===second.packageDigest,'review_continuation_unavailable');
672
+ return {fromDigest:records.at(-1).digest,packageDigest:second.packageDigest,
673
+ receiptDigests:[first.receiptDigest,second.receiptDigest]};
674
+ }
675
+ export function applyReviewContinuation(records,s,config,record,used=null){
676
+ const binding=reviewContinuationBinding(records,s,config,used);
677
+ for(const key of Object.keys(binding))same(record[key],binding[key]);
678
+ hex(record.markerSha256);
679
+ need(typeof record.reason==='string'&&record.reason.trim().length>0&&Buffer.byteLength(record.reason,'utf8')<=500
680
+ &&!/[\r\n\0]/.test(record.reason),'review_continuation_reason_required');
681
+ need(typeof record.at==='string'&&Number.isFinite(Date.parse(record.at))&&new Date(record.at).toISOString()===record.at,
682
+ 'review_continuation_unavailable');
683
+ // Back to the second round's revision state: the r2 findings stay the prior
684
+ // review the correction answers; attempt and both receipts stay as recorded.
685
+ return {...s,state:'changes_requested',code:null,reason:null,receipt:null,reviewInvocation:null};
686
+ }
644
687
  export const MAX_COMPLETION_RETRIES=3;
645
688
  export const completionRetriesExhausted=s=>s.state==='blocked'&&COMPLETION_RETRY_CODES.includes(s.code)
646
689
  &&completionBlockCount(s.cache)>MAX_COMPLETION_RETRIES;
647
690
  export const completionRetryLimitReason=({fromCode,completionBlocks})=>
648
691
  `completion_retry_limit: 完成前复查已 ${completionBlocks} 次被拦下(最多重试 ${MAX_COMPLETION_RETRIES} 次),上次停在 blocked/${fromCode}。`
649
692
  +'先修好检查环境(结果不稳定的检查、会在代码根生成新文件的命令),再用 --supersede-reviewed-evidence 新建运行';
650
- export const developRetryLimitReason=({countedCalls:calls,countedEffects:effects,fromState,fromCode})=>
651
- `develop_retry_limit: 本运行已用 ${calls} 次计数调用(上限 ${MAX_RUNNER_CALLS})、${effects} 个计数 effect`
652
- +`(上限 ${MAX_RUNNER_EFFECTS}),再交付一次将无法送审;上次停在 ${fromState}${fromCode?`/${fromCode}`:''}。`
693
+ export const developRetryLimitReason=({countedCalls:calls,countedEffects:effects,fromState,fromCode},continuation=null)=>
694
+ `develop_retry_limit: 本运行已用 ${calls} 次计数调用(上限 ${callCap(continuation)})、${effects} 个计数 effect`
695
+ +`(上限 ${effectCap(continuation)}),再交付一次将无法送审;上次停在 ${fromState}${fromCode?`/${fromCode}`:''}。`
653
696
  +'按该原因修好根因后,用 --supersede-reviewed-evidence 新建运行';
654
697
  // The latest review of the current attempt was checkpointed unknown with a
655
698
  // journaled, never-accepted result: a final message cut off by a timeout, or a
@@ -947,7 +990,7 @@ function invocationCall(call,registration,started,result,before) {
947
990
  &&call.resultDigest===digest(result.outcome==='observed'?result.inspection.review:result)
948
991
  &&before.sequence+1===Number(request.invocationId.split('.').at(-1)),'runner_call');
949
992
  }
950
- function checkpoint(before,raw,effect,config,original,session,controls,version=1,taskCommit=null,invocation=null,carried=null,documentation=null,recheckEffects=[],rework=null) {
993
+ function checkpoint(before,raw,effect,config,original,session,controls,version=1,taskCommit=null,invocation=null,carried=null,documentation=null,recheckEffects=[],rework=null,continuation=null) {
951
994
  const s=json(raw,LIMIT);
952
995
  shape(s,['state','code','attempt','session','sequence','reviewPackage','currentChecks','receipt','receipts','calls','cache',
953
996
  ...(Object.hasOwn(s,'reason')?['reason']:[]),
@@ -970,12 +1013,12 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
970
1013
  // An abandoned invocation holds no effect slot (its pending effect was never
971
1014
  // checkpointed, or its journaled result was abandoned), so it holds no call
972
1015
  // slot either; the attempt's one redispatch is bounded by reviewRetrySpent.
973
- need(Array.isArray(s.calls) && countedCalls(s.calls,s.cache)<=MAX_RUNNER_CALLS && s.sequence===s.calls.length,'runner_calls');
1016
+ need(Array.isArray(s.calls) && countedCalls(s.calls,s.cache)<=callCap(continuation) && s.sequence===s.calls.length,'runner_calls');
974
1017
  // The current check-only intent is already derived from the validated journal;
975
1018
  // its checkpoint still has to pass the unchanged-call/Learning checks below.
976
1019
  const rechecks=version===3&&effect.kind==='develop'&&before.state==='blocked'&&RECHECK_CODES.includes(before.code)
977
1020
  ?[...recheckEffects,effect.id]:recheckEffects;
978
- need(Array.isArray(s.receipts) && s.receipts.length<=2 && Array.isArray(s.cache) && completedEffectCount(s.cache,s.calls,rechecks)<=MAX_RUNNER_EFFECTS+(rework?.developerConsumed?1:0),'runner_limits');
1021
+ need(Array.isArray(s.receipts) && s.receipts.length<=(continuation?3:2) && Array.isArray(s.cache) && completedEffectCount(s.cache,s.calls,rechecks)<=effectCap(continuation)+(rework?.developerConsumed?1:0),'runner_limits');
979
1022
  prefix(before.calls,s.calls);prefix(before.receipts,s.receipts);prefix(before.cache,s.cache);
980
1023
  need(s.cache.length===before.cache.length+1,'runner_cache');
981
1024
  const entry=s.cache.at(-1);shape(entry,['effect','digest','result']);same(entry.effect,effect);same(entry.digest,digest(effect));
@@ -1072,13 +1115,14 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
1072
1115
  // between the checks and the review package. No package exists, so no review
1073
1116
  // round was spent; the attempt counter does not move either.
1074
1117
  // develop_unchanged_after_review: attempt 2 matched the rejected attempt-1 artifact.
1075
- if(developerCall?.terminal==='succeeded'&&['verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large'].includes(s.code)) {
1118
+ if(developerCall?.terminal==='succeeded'&&['verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_continuation_scope_mismatch','develop_empty_changes','develop_requirement_missing','develop_package_too_large'].includes(s.code)) {
1076
1119
  // s.receipt is null for every develop checkpoint (above); at attempt 2 the
1077
1120
  // state before still holds the attempt-1 receipt, so only receipts compare.
1078
1121
  need(digest(s.reviewPackage)===digest(before.reviewPackage),'runner_develop');
1079
1122
  same(s.receipts,before.receipts);
1080
1123
  if(s.code==='develop_unchanged_after_review')
1081
1124
  need(before.attempt===2&&['changes_requested','approved'].includes(before.priorReview?.verdict),'runner_develop');
1125
+ if(s.code==='develop_continuation_scope_mismatch')need(continuation!==null&&before.attempt===2,'runner_develop');
1082
1126
  expectedState='blocked';expectedCode=s.code;
1083
1127
  }
1084
1128
  if(added[0]?.terminal==='succeeded'&&s.code==='bootstrap_review_mismatch'){
@@ -1126,6 +1170,7 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
1126
1170
  same(rawReceipt,accepted);same(s.receipt,accepted);same(s.priorReview,result);
1127
1171
  if(result.verdict==='approved')expectedState='approved';
1128
1172
  else if(result.verdict==='changes_requested'&&before.attempt===1){expectedState='changes_requested';expectedAttempt=2;}
1173
+ else if(continuation){expectedState='blocked';expectedCode=REVIEW_CONTINUATION_REJECTED;}
1129
1174
  else {expectedState='blocked';expectedCode=result.verdict==='changes_requested'?'review_limit':'review_blocked';}
1130
1175
  if(s.code==='review_package_changed'){
1131
1176
  need(typeof s.reason==='string'&&s.reason.length>0,'runner_diagnostic');
@@ -1256,7 +1301,9 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
1256
1301
  function completionConfig(config,version){
1257
1302
  shape(config,['root','identity','scope','requirements','excludedContexts','timeoutMs','developer','reviewers','completion',
1258
1303
  ...(version===3?['reviewInvocation']:[]),...(Object.hasOwn(config,'taskLearning')?['taskLearning']:[]),
1259
- ...['bootstrap','codeProjectPaths','knowledgeCloseout','externalModels','executionPolicy','controlPolicy','parallelSelection'].filter(key=>Object.hasOwn(config,key))]);
1304
+ ...['bootstrap','codeProjectPaths','knowledgeCloseout','externalModels','executionPolicy','controlPolicy','parallelSelection','completionCheckReuse','qaCadence'].filter(key=>Object.hasOwn(config,key))]);
1305
+ if(Object.hasOwn(config,'completionCheckReuse'))need(config.completionCheckReuse==='reviewed-unchanged-v1'&&version===3,'runner_config');
1306
+ if(Object.hasOwn(config,'qaCadence'))need(config.qaCadence==='feature-v1'&&version===3,'runner_config');
1260
1307
  if(Object.hasOwn(config,'controlPolicy')){same(config.controlPolicy,readControlPolicy(config.controlPolicy));need(version===3,'runner_version');}
1261
1308
  if(Object.hasOwn(config,'parallelSelection')){
1262
1309
  shape(config.parallelSelection,['version','group']);need(config.parallelSelection.version===1&&Array.isArray(config.parallelSelection.group)
@@ -1355,7 +1402,7 @@ export function readRunnerHistory(raw,config,version=1) {
1355
1402
  let acceptedIntegration=null;
1356
1403
  let invocation={registration:null,started:null,result:null};let registrationRecord=null,startedRecord=null,resultRecord=null,lastReview=null;
1357
1404
  const acceptedFixes=[],joinedHosts=[],reviewerThreads=[];let qaAttachment=null,qaRevision=null,joinedForInvocation=false,supersession=null;
1358
- let scopeRevisions=0,developmentRework=null;
1405
+ let scopeRevisions=0,developmentRework=null,reviewContinuation=null;
1359
1406
  const answerGaps={developRecheck:0,completeRecheck:0,developRedo:0,developDispatch:0,documentationSync:0,reviewRedispatch:{1:0,2:0}};
1360
1407
  const developRecheckEffects=[];
1361
1408
  // Q16: documentation-sync-started records by digest, and the pending develop's.
@@ -1472,7 +1519,12 @@ export function readRunnerHistory(raw,config,version=1) {
1472
1519
  if(Object.hasOwn(e,'learningInput')){need(e.kind==='develop'&&Object.hasOwn(config,'taskLearning'),'runner_learning');
1473
1520
  validTaskLearningInput(e.learningInput,e.identity,config.taskLearning.feature);}
1474
1521
  same(e.identity,{...config.identity,attempt:state.attempt});need(e.version===1 && stageAllowed(e.kind,state.state,state.code,state.priorReview?.verdict),'runner_stage');
1475
- need(effectSlotFree(e.kind,state.cache,state.calls,developRecheckEffects,developmentRework,e.id,state) && !state.cache.some(c=>c.effect.id===e.id),'runner_cache');
1522
+ need(effectSlotFree(e.kind,state.cache,state.calls,developRecheckEffects,developmentRework,e.id,state,reviewContinuation) && !state.cache.some(c=>c.effect.id===e.id),'runner_cache');
1523
+ // After a continuation grant, replay applies the same reserve-a-review-slot rule as
1524
+ // live dispatch: a delivery that could no longer be reviewed is refused (review r1 of
1525
+ // finding 12). Runs without a grant keep their historical replay unchanged.
1526
+ if(reviewContinuation&&e.kind==='develop')
1527
+ need(!developBudgetExhausted(state,developRecheckEffects,developmentRework,reviewContinuation),'runner_retry_limit');
1476
1528
  if(developmentRework){
1477
1529
  if(e.kind==='develop')developmentRework.developerConsumed=true;
1478
1530
  if(e.kind==='review'&&e.id===developmentRework.reviewEffectId)developmentRework.reviewConsumed=true;
@@ -1533,7 +1585,7 @@ export function readRunnerHistory(raw,config,version=1) {
1533
1585
  if(['packageMaterial','packageRef'].some(key=>Object.hasOwn(p,key)))need(packageMaterialEligible(config,version),'checkpoint_package_material_invalid');
1534
1586
  const recovered=resolveCheckpointPackage(p,records.slice(0,index),lastReview.effect.identity);
1535
1587
  state=checkpoint(lastReview.before,recovered,lastReview.effect,config,original,session,lastReview.controls,version,
1536
- state.taskCommit??null,{...lastReview.invocation,result:lastReview.reconciliation.result},supersession?.carriedReview??null,null,developRecheckEffects,developmentRework);
1588
+ state.taskCommit??null,{...lastReview.invocation,result:lastReview.reconciliation.result},supersession?.carriedReview??null,null,developRecheckEffects,developmentRework,reviewContinuation);
1537
1589
  lastReview=null;
1538
1590
  }
1539
1591
  } else if(version===3&&p.type==='develop-retry-limit') {
@@ -1541,10 +1593,10 @@ export function readRunnerHistory(raw,config,version=1) {
1541
1593
  // be reviewed. Every field is recomputed from the replayed state.
1542
1594
  shape(p,[...common,'fromState','fromCode','countedCalls','countedEffects']);
1543
1595
  const used=developBudget(state,developRecheckEffects);
1544
- need(r.kind==='result'&&pending===null&&developBudgetExhausted(state,developRecheckEffects,developmentRework)&&p.fromState===state.state
1596
+ need(r.kind==='result'&&pending===null&&developBudgetExhausted(state,developRecheckEffects,developmentRework,reviewContinuation)&&p.fromState===state.state
1545
1597
  &&p.fromCode===state.code&&p.countedCalls===used.calls&&p.countedEffects===used.effects,'runner_retry_limit');
1546
1598
  state.state='blocked';state.code='develop_retry_limit';
1547
- state.reason=developRetryLimitReason(p);lastReview=null;
1599
+ state.reason=developRetryLimitReason(p,reviewContinuation);lastReview=null;
1548
1600
  } else if(version===3&&p.type==='develop-answer-retry') {
1549
1601
  // Written by advance for a current-session answer the host rejected as
1550
1602
  // invalid; replay re-derives the whole condition from the journal.
@@ -1572,7 +1624,7 @@ export function readRunnerHistory(raw,config,version=1) {
1572
1624
  state.state='blocked';state.code=code;state.reason=developRecheckReason(code,state.cache.at(-1).result.code,state.cache.at(-1).result.reason);lastReview=null;
1573
1625
  } else if(version===3&&p.type==='scope-revised') {
1574
1626
  shape(p,[...common,'fromDigest','effectId','failedCheckpointDigest','previousScopeDigest','baselineDigest','scope','files','reason','at']);
1575
- need(r.kind==='result'&&pending===null&&transaction===null&&p.fromDigest===records[index-1].digest,'scope_revision_unavailable');
1627
+ need(r.kind==='result'&&pending===null&&transaction===null&&reviewContinuation===null&&p.fromDigest===records[index-1].digest,'scope_revision_unavailable');
1576
1628
  need(!developBudgetExhausted(state,developRecheckEffects,developmentRework),'scope_revision_budget_exhausted');
1577
1629
  const next=applyScopeRevision(state,config,original,p,scopeRevisions);
1578
1630
  original=next.baseline;config={...config,scope:next.scope};scopeRevisions++;
@@ -1580,10 +1632,20 @@ export function readRunnerHistory(raw,config,version=1) {
1580
1632
  shape(p,[...common,'fromDigest','effectId','failedCheckpointDigest','limitDigest','deliveryDigest','packageDigest',
1581
1633
  'receiptDigest','baselineDigest','scopeDigest','configDigest','developerEffectId','reviewEffectId',
1582
1634
  'effectCredit','sourceDigest','reason','at']);
1583
- need(r.kind==='result'&&pending===null&&transaction===null,'development_rework_unavailable');
1635
+ need(r.kind==='result'&&pending===null&&transaction===null&&reviewContinuation===null,'development_rework_unavailable');
1584
1636
  state=applyDevelopmentRework(records.slice(0,index),state,config,original,p,developRecheckEffects,developmentRework);
1585
1637
  developmentRework={developerEffectId:p.developerEffectId,reviewEffectId:p.reviewEffectId,sourceDigest:p.sourceDigest,
1586
1638
  authorizationDigest:r.digest,developerConsumed:false,reviewConsumed:false};lastReview=null;
1639
+ } else if(version===3&&p.type==='review-continuation-authorized') {
1640
+ // Third controlled review pilot: one per run, only from the replayed
1641
+ // review_limit with both receipts and the remaining develop+review budget.
1642
+ shape(p,[...common,'fromDigest','packageDigest','receiptDigests','markerSha256','reason','at']);
1643
+ need(r.kind==='result'&&pending===null&&transaction===null&&scopeRevisions===0&&developmentRework===null
1644
+ &&p.fromDigest===records[index-1].digest,'review_continuation_unavailable');
1645
+ state=applyReviewContinuation(records.slice(0,index),state,config,p,reviewContinuation);
1646
+ const base=developBudget(state,developRecheckEffects);
1647
+ reviewContinuation={authorizationDigest:r.digest,markerSha256:p.markerSha256,fromDigest:p.fromDigest,at:p.at,reason:p.reason,
1648
+ baseCalls:base.calls,baseEffects:base.effects};lastReview=null;
1587
1649
  } else if(version===3&&p.type==='completion-rework-requested') {
1588
1650
  shape(p,[...common,'effectId','failedCheckpointDigest','packageDigest','receiptDigest','artifactDigest','handoffDigest',
1589
1651
  'fromAttempt','toAttempt','reason','at']);
@@ -1860,7 +1922,7 @@ export function readRunnerHistory(raw,config,version=1) {
1860
1922
  if(material||reference)need(packageMaterialEligible(config,version),'checkpoint_package_material_invalid');
1861
1923
  const checkpointValue=resolveCheckpointPackage(p,records.slice(0,index),pending.identity);
1862
1924
  state=checkpoint(beforeIntent,checkpointValue,pending,config,original,session,controls,version,state.taskCommit??null,invocation,
1863
- supersession?.carriedReview??null,pendingDocumentation,developRecheckEffects,developmentRework);pendingDocumentation=null;
1925
+ supersession?.carriedReview??null,pendingDocumentation,developRecheckEffects,developmentRework,reviewContinuation);pendingDocumentation=null;
1864
1926
  if(version===3&&pending.kind==='develop'&&beforeIntent.state==='blocked'&&RECHECK_CODES.includes(beforeIntent.code))
1865
1927
  developRecheckEffects.push(pending.id);
1866
1928
  lastReview=version===3&&pending.kind==='review'&&invocation.result?{effect:pending,request:invocation.registration.request,
@@ -1955,7 +2017,7 @@ export function readRunnerHistory(raw,config,version=1) {
1955
2017
  const workerVoidable=pending!==null&&pendingWorkerVoidable(pending,lastIntentIndex,records.length);
1956
2018
  return {original,effectiveScope:config.scope,scopeRevisions,session,state,pending,acceptedFixes,qaAttachment,answerGaps,
1957
2019
  ...(acceptedIntegration===null?{}:{acceptedIntegration}),
1958
- developmentRework,developRecheckEffects,developRecheckRecovery:pending===null?developRecheckCancellationBinding(records,state,config):null,
2020
+ developmentRework,reviewContinuation,developRecheckEffects,developRecheckRecovery:pending===null?developRecheckCancellationBinding(records,state,config):null,
1959
2021
  ...(version===3?{joinedHosts,reviewerThreads,supersession,pendingAbandonable,reviewResultAbandon,
1960
2022
  interrupted,workers,pendingInterruptible:interruptible,pendingReviewExhausted:pendingReviewExhausted(),
1961
2023
  pendingResultAbandonable:pending!==null&&pendingResultAbandonable(),
@@ -3,6 +3,7 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {digest,need,shape,id,hex,json,JOURNAL_PAYLOAD_LIMIT} from './effect-contract.mjs';
6
+ import {checkCreatedBy,storeStateKeys} from '../executor-version.mjs';
6
7
  import {fixJournalWorkflow,journalPhysicalLimit,packFixJournalPayload,unpackFixJournalState} from './review-presentation.mjs';
7
8
  export function readExecutionSnapshot({specsRoot,identity}){
8
9
  shape(identity,['repositoryId','runId']);Object.values(identity).forEach(id);
@@ -25,8 +26,10 @@ export function readExecutionSnapshot({specsRoot,identity}){
25
26
  const raw=JSON.parse(bytes.toString('utf8'));
26
27
  need(Buffer.from(JSON.stringify(raw)+'\n').equals(bytes),'store_corrupt');
27
28
  const v=unpackFixJournalState(raw);
28
- shape(v,['version','identity','fingerprints','records','revision']);
29
- need(v.version===1&&digest(v.identity)===digest(identity),'identity_mismatch');
29
+ // Read-only: a v2 run created by a newer executor is still shown, never advanced here.
30
+ shape(v,storeStateKeys(v));
31
+ need((v.version===1||v.version===2)&&digest(v.identity)===digest(identity),'identity_mismatch');
32
+ if(v.version===2)checkCreatedBy(v.createdBy);
30
33
  shape(v.fingerprints,['workflow','config','inputs']);Object.values(v.fingerprints).forEach(hex);
31
34
  need(Array.isArray(v.records)&&v.records.length<=1024,'limit_exceeded');
32
35
  let previous=null;const ids=new Set();
@@ -9,6 +9,8 @@ import { need,shape,id,hex,json,digest,freeze,JOURNAL_PAYLOAD_LIMIT } from './ef
9
9
  import { isSupportedExecutionPlatform } from './execution-platform.mjs';
10
10
  import { MiB,STATE_LIMIT,PHYSICAL_LIMIT } from './execution-store-limits.mjs';
11
11
  import {fixJournalWorkflow,journalPhysicalLimit,packFixJournalPayload,packFixJournalState,unpackFixJournalState} from './review-presentation.mjs';
12
+ import {createdByRecord,assertResumable,storeStateKeys,executorRelease,EXECUTOR_REASON_CODES} from '../executor-version.mjs';
13
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
12
14
 
13
15
  const APP_ID=0x434d5831;
14
16
  const PROTOCOL_SQL='CREATE TABLE protocol(version INTEGER NOT NULL CHECK(version=1))';
@@ -49,8 +51,12 @@ function readState(p,{withBytes=false}={}) {
49
51
  }finally{fs.closeSync(fd);}
50
52
  }
51
53
  function validateState(raw,options) {
52
- const v=json(raw,STATE_LIMIT);shape(v,['version','identity','fingerprints','records','revision']);
53
- need(v.version===1,'store_version');
54
+ const v=json(raw,STATE_LIMIT);
55
+ // v1: created before runs recorded their executor (shown as unknown, resumed as before).
56
+ // v2: createdBy is fixed at creation; an older executor never advances it.
57
+ shape(v,storeStateKeys(v));
58
+ need(v.version===1||v.version===2,'store_version');
59
+ if(v.version===2)assertResumable(v.createdBy);
54
60
  need(digest(v.identity)===digest(options.identity),'identity_mismatch');
55
61
  need(digest(v.fingerprints)===digest(options.fingerprints),'fingerprint_mismatch');
56
62
  need(Array.isArray(v.records) && v.records.length<=1024,'limit_exceeded');
@@ -196,6 +202,16 @@ function probeLegacyWriter(legacyPath){
196
202
  }
197
203
  }
198
204
  export { appendFits } from './execution-store-limits.mjs';
205
+ // Owners call this before writing anything of their own (bindings, archive
206
+ // directories, guards): create needs a known release; resume refuses a run a
207
+ // newer release created. Other read failures are left to the store's own open.
208
+ export function assertExecutorMayOpen({specsRoot,identity,create}){
209
+ if(create){executorRelease();return;}
210
+ let snapshot;
211
+ try{snapshot=readExecutionSnapshot({specsRoot:fs.realpathSync(specsRoot),identity:{repositoryId:identity.repositoryId,runId:identity.runId}});}
212
+ catch(error){if(EXECUTOR_REASON_CODES.has(error?.code))throw error;return;}
213
+ if(snapshot.version===2)assertResumable(snapshot.createdBy);
214
+ }
199
215
  export function openExecutionStore(input) {
200
216
  const options=json(input);shape(options,['specsRoot','identity','fingerprints','create']);
201
217
  shape(options.identity,['repositoryId','runId']);Object.values(options.identity).forEach(id);
@@ -204,6 +220,8 @@ export function openExecutionStore(input) {
204
220
  && path.isAbsolute(options.specsRoot) && path.resolve(options.specsRoot)===options.specsRoot,'unsupported_path');
205
221
  need(isSupportedExecutionPlatform(),'unsupported_platform');
206
222
  need(!fs.lstatSync(options.specsRoot).isSymbolicLink(),'unsupported_path');
223
+ // Read before anything exists on disk: no half-created run without a release.
224
+ const createdBy=options.create?createdByRecord():null;
207
225
  const root=fs.realpathSync(options.specsRoot);directory(root,false,false);
208
226
  const reviews=path.join(root,'.reviews'),execution=path.join(reviews,'.execution');
209
227
  directory(reviews,options.create,false);directory(execution,options.create);
@@ -230,7 +248,7 @@ export function openExecutionStore(input) {
230
248
  need(sameInode(certificate,readiness(lockPath,inspectionFd)),'store_ownership');noJournal(lockPath);
231
249
  };
232
250
  const statePath=path.join(dir,'state.json');
233
- if(options.create)atomicState(dir,seal({version:1,identity:options.identity,fingerprints:options.fingerprints,records:[]}));
251
+ if(options.create)atomicState(dir,seal({version:2,identity:options.identity,fingerprints:options.fingerprints,createdBy,records:[]}));
234
252
  let physicalState=null,validatedBytes=null,validatedLogical=null;
235
253
  const snapshot=()=>{
236
254
  need(!closed,'store_closed');need(!poisoned,'store_poisoned');
@@ -54,7 +54,15 @@ export function acquireExternalRunGuard(definition,{strictOnly=false}={}){
54
54
  const binding={version:1,kind:'cm-external-code-binding',specsDir},file=codeBinding(codeProject);
55
55
  if(!fs.existsSync(file))try{writeModelJson(file,binding,{expectedSha256:null,replace:false});}
56
56
  catch(error){if(!['model_configuration_exists','model_configuration_changed'].includes(error.code))throw error;}
57
- need(digest(readModelJsonRecord(file).value)===digest(binding),'external_code_specs_conflict');
57
+ const bound=readModelJsonRecord(file).value;
58
+ if(digest(bound)!==digest(binding)){
59
+ // Rebinding is deliberately not automatic: old evidence, path aliases and live writers
60
+ // cannot all be proven settled here. Say where the code root belongs and the safe way out.
61
+ // Name only the bound folder (not the full local path), and only for a well-formed record.
62
+ const valid=bound?.version===1&&bound?.kind==='cm-external-code-binding'&&typeof bound?.specsDir==='string'&&path.isAbsolute(bound.specsDir);
63
+ process.stderr.write(`[cm-ai] ${valid?`代码根已绑定规格目录 ${JSON.stringify(path.basename(bound.specsDir))}`:'代码根的绑定记录无法识别'}(外部模型/效率策略运行的归属保护,防止换规格掩盖旧运行的未结调用)。换用新规格时,请用 git worktree add 另开一个代码工作树来跑新规格;旧运行仍在原工作树恢复;不要删除或改写 .cm-external-models-v1.json。\n`);
64
+ need(false,'external_code_specs_conflict');
65
+ }
58
66
  const root=path.join(specsDir,'.cm-external-models-v1');
59
67
  try{fs.mkdirSync(root,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
60
68
  const stat=fs.lstatSync(root);
@@ -100,8 +100,10 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
100
100
  if(onOutput){
101
101
  try{
102
102
  const returned=onOutput({stream:streamName,chunk:Buffer.from(chunk)});
103
- if(types.isPromise(returned))Promise.prototype.then.call(returned,()=>{},()=>{});
104
- need(returned===undefined);
103
+ // An async callback cannot be awaited here, so its capture is not guaranteed:
104
+ // refuse it. Any other return value is ignored (a stray `stream.write(...)`
105
+ // result once failed every printing check in batch runs).
106
+ if(types.isPromise(returned)){Promise.prototype.then.call(returned,()=>{},()=>{});need(false);}
105
107
  }
106
108
  catch{stop('output_capture_failed');return;}
107
109
  }
@@ -35,7 +35,7 @@ import {validateDocumentationPaths} from './host-documentation.mjs';
35
35
  import {verifySpecificationMaterial} from './specification-material.mjs';
36
36
  import {isFinalCmAiTask} from './cm-ai-admission.mjs';
37
37
  import {createHostBootstrap} from './host-bootstrap.mjs';
38
- import {withHostProgress} from './host-progress.mjs';
38
+ import {withHostProgress,recordCheckReuse} from './host-progress.mjs';
39
39
  import {digest,id,json,need,shape,freeze,arrayItems,boundedReason} from './effect-contract.mjs';
40
40
  export const protectedTextInstructions='\nProtected current-host mode: do not write files or run commands. Return {status,value,edits} on success; '
41
41
  +'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content[,mode]}], complete UTF-8 text or null for deletion; '
@@ -190,7 +190,8 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
190
190
  disabledSkills:review?.disabledSkills??[],
191
191
  ...resolveReviewTimeout(review,protection),
192
192
  promptTransport:'stdin',schemaPath:fileURLToPath(new URL('./review-result.schema.json',import.meta.url))};
193
- if(review!==null||provider)need((reviewerRuntime==='codex'?preflightMatches:claudePreflightMatches)(reviewOptions.preflight,reviewOptions),'tool_preflight_missing');
193
+ if((review!==null||provider)&&!(reviewerRuntime==='codex'?preflightMatches:claudePreflightMatches)(reviewOptions.preflight,reviewOptions))
194
+ throw Object.assign(new Error('tool_preflight_missing'),{code:'tool_preflight_missing',reason:preflightMissingReason(reviewerRuntime,reviewOptions)});
194
195
  need(reviewerRuntime!=='claude'||!review||review.disabledSkills.length===0,'invalid_review_config');
195
196
  // Preserve P4a's unauthorizable placeholder bytes for existing unconfigured runs.
196
197
  const reviewProvider=review?reviewerRuntime:'codex', adapterId=`${reviewProvider}-review-adapter`;
@@ -289,6 +290,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
289
290
  const progress=(request,control,stage,run,selectedRuntime=runtime)=>withHostProgress({definition,
290
291
  identity:request.identity,runtime:selectedRuntime,stage,signal:control.signal},run);
291
292
  const execution={configuration,timeoutMs:outerTimeoutMs,excludedContexts:[durableHostContextId],applicableAgentFiles:[],
293
+ onChecksReused:({identity,checkCount})=>recordCheckReuse({definition,identity,runtime,checkCount}),
292
294
  ...(verificationGate?{verificationGate:(request,control)=>progress(request,control,'verifying',()=>verificationGate(request,control))}:{}),
293
295
  ...(bootstrap?{bootstrap}:{}),
294
296
  ...(provider&&!controlPolicy?{developmentAttempt:provider.attempt}:{}),
@@ -424,3 +426,22 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
424
426
  if(externalModels||executionPolicy){freeze(execution);externalConversations.set(execution,digest(definition));}
425
427
  return execution;
426
428
  }
429
+
430
+ // Which side reviews and how to regenerate its diagnostic (2026-12-01 probe: the batch
431
+ // stopped at tool_preflight_missing with neither). Names only facts the host already holds.
432
+ export function preflightMissingReason(reviewerRuntime,{preflight,model,effort}){
433
+ const madeFor=preflight?.provider==='claude'?'claude':typeof preflight?.cli_model==='string'?'codex':null;
434
+ const why=preflight==null?'review-config 里没有预检回执'
435
+ :preflight.passed!==true?'review-config 里的预检没有通过'
436
+ :madeFor&&madeFor!==reviewerRuntime?`review-config 里的预检是给 ${madeFor} 做的`
437
+ :`review-config 里的预检与本次审查条件不一致(审查模型 ${model}、本运行的代码根与审查选项须与预检时相同)`;
438
+ // External-model runs carry an effort and preflight their frozen pair instead of a free model;
439
+ // a pair frozen from a custom file needs that same file, not today's user default.
440
+ const command=effort!==undefined
441
+ ?`--external-provider ${reviewerRuntime} --external-models-config {写着这组值的配置文件}(预检读的是这份文件里 ${reviewerRuntime} 的模型与强度,必须等于本运行冻结的模型 ${model}、强度 ${effort};`
442
+ +'创建时用的那份文件没改过就直接用它,用户默认配置后来改过就另写一份,否则恢复时以 external_model_configuration_conflict 拒绝)'
443
+ :`--review-model ${model==='unconfigured'?'{审查模型}':model} --runtime ${reviewerRuntime}`;
444
+ return `审查端是 ${reviewerRuntime},${why}。用同一代码根的单任务运行定义重新预检:`
445
+ +`cm-ai-host.mjs preflight --config {单任务运行定义.json} ${command},`
446
+ +'把输出原样存为 review-config 后重新启动;另一端的预检不能复用,也不要手改 passed 或指纹';
447
+ }
@@ -66,6 +66,13 @@ export function verifyHostHandoff(raw){
66
66
  // of the same task forever. The receipt names the handoff it reviewed, so the two
67
67
  // cases are distinguishable without guessing from timestamps or run identity.
68
68
  export function reviewConsumedHandoff(parent,name,attempt){
69
+ // A third controlled review's correction handoff is sealed by the correction
70
+ // record that binds its digest; before that record it is a replaceable draft.
71
+ const correction='-controlled-correction-handoff.json';
72
+ if(attempt===2&&name.endsWith(correction)){
73
+ try{fs.lstatSync(path.join(parent,`${name.slice(0,-correction.length)}-controlled-correction.json`));return true;}
74
+ catch(error){if(error.code==='ENOENT')return false;throw error;}
75
+ }
69
76
  const suffix=`-a${attempt}-handoff.json`;
70
77
  if(!name.endsWith(suffix))return true;
71
78
  const receipt=path.join(parent,`${name.slice(0,-suffix.length)}-r${attempt}.md`);
@@ -1,6 +1,7 @@
1
1
  // Event-based operator feedback. Failure here never changes a runner verdict.
2
2
  import path from 'node:path';
3
3
  import {spawnSync} from 'node:child_process';
4
+ import {spawnPythonLogWriter} from '../python-log-writer.mjs';
4
5
  import {randomUUID} from 'node:crypto';
5
6
  import {fileURLToPath} from 'node:url';
6
7
  import {need} from './effect-contract.mjs';
@@ -47,6 +48,23 @@ export function startHostProgress({definition,identity,runtime='codex',stage,sig
47
48
  },
48
49
  });
49
50
  }
51
+ // Completion reused the reviewed command checks instead of running them again.
52
+ // One row per reuse, so analysis can count executed vs reused check batches.
53
+ export function recordCheckReuse({definition,identity,runtime='codex',checkCount}){
54
+ try{
55
+ const result=spawnPythonLogWriter([writer,'--workflow','cm-ai','--event','check_reuse','--phase','reused',
56
+ '--runtime',runtime,'--project-root',definition.codeProject,'--specs-dir',definition.specsDir,
57
+ '--run-id',identity.runId,'--detail','完成前复用已审检查结果','--data-json',JSON.stringify({node:'N5',diagnostic:true,
58
+ feature:definition.feature,task:identity.taskId,attempt:identity.attempt,check_count:checkCount})],
59
+ {timeout:10000,maxBuffer:64*1024,env:{...process.env,
60
+ CM_WORKFLOW_LOG_HOME:path.join(definition.specsDir,'.reviews','host-log-mirror')}});
61
+ need(!result.error&&result.status===0&&result.signal===null,'progress_log_failed');
62
+ }catch{diagnostic();}
63
+ // Same display step a completion check would have claimed (N3 checking): QA
64
+ // and finalization projections only replace N3/N5/N6, never the review's N4.
65
+ try{writeStatusProjection({specsDir:definition.specsDir,feature:definition.feature,identity,node:'N5',state:'approved',
66
+ detail:'审查已通过,复用已审检查完成',claim:true});}catch{diagnostic();}
67
+ }
50
68
  export async function withHostProgress(options,run){
51
69
  const progress=startHostProgress(options);
52
70
  try{const result=await run(progress);progress.complete('returned');return result;}