@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
@@ -11,8 +11,8 @@ import {inspectFixWalkthrough,readFixWalkthrough,fixWalkthroughBinding} from '..
11
11
  import {inspectFixRegressionFailure} from '../runtime/js/cm-fix/regression-evidence.mjs';
12
12
  import {taskDeclarations,approvedTaskGrammar,LEGACY_TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
13
13
  import {statesZeroBlockingFindings,ZERO_BLOCKING_PHRASES,REVIEWER_SOURCES} from '../runtime/js/review-findings.mjs';
14
- import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
15
14
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
15
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
16
16
  import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
17
17
  import {resolveCheckpointPackage} from '../runtime/js/cm-ai/checkpoint-package-material.mjs';
18
18
  import {publishHostReview} from '../runtime/js/cm-ai/host-review-file.mjs';
@@ -718,10 +718,14 @@ function correctionHistory({reviewsDir,feature,task,projectRoot}){
718
718
  return {payload,revisions,history:revisions.map(item=>({file:path.basename(item.path),
719
719
  sha256:createHash('sha256').update(item.bytes).digest('hex')}))};
720
720
  }
721
- function boundCorrectionHandoff(handoff,task,projectRoot){
721
+ // A runner-owned correction handoff carries the runner's structured Learning,
722
+ // which the owning runner verifies itself before its native completion.
723
+ function boundCorrectionHandoff(handoff,task,projectRoot,{runnerOwned=false,allowSymlinks=false}={}){
722
724
  const payload=loadHandoff(handoff,{task,attempt:2});
723
725
  if(payload.status!=='ready_for_review')throw new GateError('human correction requires ready_for_review');
724
- verifyLearningRecord(payload,projectRoot);verifyImplementationBinding(payload,{projectRoot});
726
+ if(runnerOwned!==true)verifyLearningRecord(payload,projectRoot);
727
+ // Only a runner-owned correction inherits the run's symlink-capable baseline.
728
+ verifyImplementationBinding(payload,{projectRoot,allowSymlinks:runnerOwned===true&&allowSymlinks===true});
725
729
  return payload;
726
730
  }
727
731
  export function prepareHumanCorrection(selectors){
@@ -818,6 +822,35 @@ function checkHumanCorrection(selectors,stage){
818
822
 
819
823
  // Provenance is a declaration of who selected this bounded continuation. It is
820
824
  // neither authenticated identity nor authorization, and never a review verdict.
825
+ // Exclusive and all-or-nothing: bytes are written and synced to a private temp,
826
+ // then hard-linked into place, so a crash never leaves a partial evidence file.
827
+ function writeExclusiveAtomic(file,bytes){
828
+ const temp=path.join(path.dirname(file),`.cm-gate-${randomUUID()}`);
829
+ const fd=fs.openSync(temp,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL,0o600);
830
+ try{fs.writeFileSync(fd,bytes);fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
831
+ try{fs.linkSync(temp,file);}finally{fs.unlinkSync(temp);}
832
+ }
833
+ // A crash between the link and the temp unlink leaves the evidence with a second
834
+ // link. Only the caller's own fixed evidence files are healed, and only a temp
835
+ // named exactly like writeExclusiveAtomic's (random v4 UUID) sharing their inode.
836
+ const ATOMIC_TEMP=/^\.cm-gate-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
837
+ export function healAtomicTempLinks(dir,files){
838
+ // A listed temp may vanish before it is read (its own writer finished, or this
839
+ // loop removed it for an earlier file): that name is skipped, never fatal.
840
+ const temps=new Set(fs.readdirSync(dir).filter(name=>ATOMIC_TEMP.test(name)));
841
+ const gone=error=>{if(error.code!=='ENOENT')throw error;};
842
+ for(const file of files){
843
+ let target;try{target=fs.lstatSync(file);}catch(error){gone(error);continue;}
844
+ if(path.dirname(file)!==dir||!target.isFile()||target.nlink!==2)continue;
845
+ for(const name of [...temps]){
846
+ let temp;try{temp=fs.lstatSync(path.join(dir,name));}catch(error){gone(error);temps.delete(name);continue;}
847
+ if(temp.isFile()&&temp.dev===target.dev&&temp.ino===target.ino){
848
+ try{fs.unlinkSync(path.join(dir,name));}catch(error){gone(error);}
849
+ temps.delete(name);break;
850
+ }
851
+ }
852
+ }
853
+ }
821
854
  function controlledCorrectionPaths(reviewsDir,feature,task){
822
855
  const root=path.dirname(correctionPaths(reviewsDir,feature,task).record);
823
856
  const prefix=path.join(root,`${feature}-${task}-controlled-correction`);
@@ -852,8 +885,8 @@ function withCorrectionPreparation(selectors,action){
852
885
  }finally{fs.closeSync(descriptor);}
853
886
  }
854
887
  }
855
- function controlledCorrectionPayload(handoff,task,projectRoot,original){
856
- const payload=boundCorrectionHandoff(handoff,task,projectRoot);
888
+ function controlledCorrectionPayload(handoff,task,projectRoot,original,runnerOwned=false,allowSymlinks=false){
889
+ const payload=boundCorrectionHandoff(handoff,task,projectRoot,{runnerOwned,allowSymlinks});
857
890
  if(!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
858
891
  throw new GateError('controlled correction must retain the full original reviewed file scope');
859
892
  if(payload.implementation_sha256===original.payload.implementation_sha256)
@@ -912,6 +945,41 @@ function assertCompatibilityCorrectionOwner(reviewsDir){
912
945
  }
913
946
  }
914
947
  }
948
+ // A cm-ai run that journaled its own third controlled review owns exactly this
949
+ // one correction (library callers only; the CLI cannot set runnerOwned). It must
950
+ // show the run's continuation marker instead of the compatibility writer.
951
+ export const REVIEW_CONTINUATION_MARKER_PROTOCOL='cm-ai-review-continuation';
952
+ export const reviewContinuationMarkerPath=(reviewsDir,feature,task)=>
953
+ path.join(path.dirname(correctionPaths(reviewsDir,feature,task).record),`${feature}-${task}-review-continuation.json`);
954
+ function assertCorrectionOwner(selectors){
955
+ if(selectors.runnerOwned!==true)return assertCompatibilityCorrectionOwner(selectors.reviewsDir);
956
+ let marker,markerBytes;
957
+ try{markerBytes=fileRevision(reviewContinuationMarkerPath(selectors.reviewsDir,selectors.feature,selectors.task),16384).bytes;
958
+ marker=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(markerBytes));}
959
+ catch{throw new GateError('runner-owned correction requires a valid run continuation marker');}
960
+ exactFields(marker,['version','protocol','feature','task','repositoryId','runId','fromDigest','at'],'run continuation marker');
961
+ const safeId=value=>typeof value==='string'&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value)&&!value.includes('..');
962
+ if(marker.version!==1n||marker.protocol!==REVIEW_CONTINUATION_MARKER_PROTOCOL||marker.feature!==selectors.feature||marker.task!==selectors.task
963
+ ||!safeId(marker.runId)||!safeId(marker.repositoryId)||!/^[0-9a-f]{64}$/.test(marker.fromDigest??'')||typeof marker.at!=='string')
964
+ throw new GateError('runner-owned correction requires the run continuation marker for this task');
965
+ // The named run's own journal is the authority: it must be this task's v2 run
966
+ // and hold the authorization bound to these exact marker bytes.
967
+ const reviews=fs.realpathSync(selectors.reviewsDir);
968
+ let snapshot;
969
+ try{snapshot=readExecutionSnapshot({specsRoot:path.dirname(reviews),identity:{repositoryId:marker.repositoryId,runId:marker.runId}});}
970
+ catch{throw new GateError('runner-owned correction requires the marker to name a retained JS run');}
971
+ const config=snapshot.records[0]?.payload?.config;
972
+ const markerSha=createHash('sha256').update(markerBytes).digest('hex');
973
+ // Replay the whole journal with the runner's own validator, so only an
974
+ // authorization that legally follows its recorded review_limit counts.
975
+ let history=null;
976
+ try{history=readRunnerHistory(snapshot.records,config,snapshot.records[0].payload.version);}catch{history=null;}
977
+ if(config?.controlPolicy?.version!==2||config.identity?.taskId!==selectors.task
978
+ ||config.completion?.owner?.feature!==selectors.feature||config.completion?.reviewsDir!==reviews
979
+ ||history?.reviewContinuation?.markerSha256!==markerSha||history.reviewContinuation.fromDigest!==marker.fromDigest
980
+ ||history.reviewContinuation.at!==marker.at)
981
+ throw new GateError('runner-owned correction requires the run journal to hold this continuation authorization');
982
+ }
915
983
  export function prepareControlledCorrection(selectors){
916
984
  const {reviewsDir,feature,task,handoff,projectRoot,decisionSource,reason}=selectors;
917
985
  if(!['operator','model'].includes(decisionSource))
@@ -919,15 +987,15 @@ export function prepareControlledCorrection(selectors){
919
987
  if(typeof reason!=='string'||!reason.trim()||reason.length>2000)
920
988
  throw new GateError('controlled correction requires a concrete bounded reason');
921
989
  return withCorrectionPreparation(selectors,()=>{
922
- assertCompatibilityCorrectionOwner(reviewsDir);
990
+ assertCorrectionOwner(selectors);
923
991
  const paths=controlledCorrectionPaths(reviewsDir,feature,task);
924
992
  noCorrectionEvidence(correctionPaths(reviewsDir,feature,task),{includeOrphan:false});
925
993
  absent(paths.record);absent(paths.review);absent(paths.receipt);
926
994
  const original=correctionHistory(selectors),draft=fileRevision(handoff,PREPARATION_FILE_LIMIT);
927
- controlledCorrectionPayload(handoff,task,projectRoot,original);
995
+ controlledCorrectionPayload(handoff,task,projectRoot,original,selectors.runnerOwned===true,selectors.allowSymlinks===true);
928
996
  requireRevisions([...original.revisions,draft]);
929
997
  // The only recoverable orphan is the exact handoff written before the record.
930
- try{absent(paths.handoff);fs.writeFileSync(paths.handoff,draft.bytes,{flag:'wx',mode:0o600});}
998
+ try{absent(paths.handoff);writeExclusiveAtomic(paths.handoff,draft.bytes);}
931
999
  catch(error){
932
1000
  if(error instanceof GateError&&!fs.existsSync(paths.record)&&fileRevision(paths.handoff,PREPARATION_FILE_LIMIT).bytes.equals(draft.bytes)){}
933
1001
  else throw error;
@@ -936,17 +1004,17 @@ export function prepareControlledCorrection(selectors){
936
1004
  decision_source:decisionSource,source_semantics:'provenance-only',at:new Date().toISOString(),reason:reason.trim(),
937
1005
  history:original.history,handoff_sha256:sha256(paths.handoff)};
938
1006
  requireRevisions(original.revisions);
939
- controlledCorrectionPayload(paths.handoff,task,projectRoot,original);
940
- assertCompatibilityCorrectionOwner(reviewsDir);
1007
+ controlledCorrectionPayload(paths.handoff,task,projectRoot,original,selectors.runnerOwned===true,selectors.allowSymlinks===true);
1008
+ assertCorrectionOwner(selectors);
941
1009
  noCorrectionEvidence(correctionPaths(reviewsDir,feature,task),{includeOrphan:false});
942
- fs.writeFileSync(paths.record,JSON.stringify(record,null,2)+'\n',{flag:'wx',mode:0o600});
1010
+ writeExclusiveAtomic(paths.record,Buffer.from(JSON.stringify(record,null,2)+'\n'));
943
1011
  return {outcome:'ready_for_correction_review',correction:paths.record,handoff:paths.handoff,
944
1012
  review:paths.review,correction_sha256:sha256(paths.record),attempt:2,continuation:1};
945
1013
  });
946
1014
  }
947
1015
  function inspectControlledCorrection(selectors){
948
1016
  const {reviewsDir,feature,task,correction,handoff,projectRoot}=selectors;
949
- assertCompatibilityCorrectionOwner(reviewsDir);
1017
+ assertCorrectionOwner(selectors);
950
1018
  const paths=controlledCorrectionPaths(reviewsDir,feature,task);
951
1019
  if(typeof correction!=='string'||typeof handoff!=='string'||path.resolve(correction)!==paths.record||path.resolve(handoff)!==paths.handoff)
952
1020
  throw new GateError('controlled correction must use its fixed evidence paths');
@@ -965,7 +1033,7 @@ function inspectControlledCorrection(selectors){
965
1033
  const original=correctionHistory(selectors);
966
1034
  if(canonical(record.history)!==canonical(original.history))throw new GateError('controlled correction history changed');
967
1035
  const handoffRevision=fileRevision(paths.handoff,PREPARATION_FILE_LIMIT);
968
- const payload=controlledCorrectionPayload(paths.handoff,task,projectRoot,original);
1036
+ const payload=controlledCorrectionPayload(paths.handoff,task,projectRoot,original,selectors.runnerOwned===true,selectors.allowSymlinks===true);
969
1037
  if(record.handoff_sha256!==createHash('sha256').update(handoffRevision.bytes).digest('hex'))
970
1038
  throw new GateError('controlled correction handoff changed');
971
1039
  requireRevisions([pinned,handoffRevision,...original.revisions]);
@@ -1010,7 +1078,7 @@ export function publishControlledCorrectionReview(selectors){
1010
1078
  inspectControlledCorrection(selectors);
1011
1079
  const receipt={version:2,protocol:'cm-controlled-correction-review',correction_sha256:correctionDigest,
1012
1080
  review_sha256:createHash('sha256').update(pinned.bytes).digest('hex'),verdict:header.verdict};
1013
- fs.writeFileSync(paths.receipt,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
1081
+ writeExclusiveAtomic(paths.receipt,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
1014
1082
  return {outcome:header.verdict,receipt:paths.receipt};
1015
1083
  }
1016
1084
  function checkControlledCorrection(selectors,stage){
@@ -1048,8 +1116,9 @@ function checkCorrection(selectors,stage){
1048
1116
 
1049
1117
  // Only compatibility CLI entries opt into inventory validation. Library callers
1050
1118
  // retain the original content-binding contract and exact result shape.
1051
- export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null,allowSymlinks=false}){
1052
- if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory},'n4');
1119
+ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null,allowSymlinks=false,runnerOwned=false}){
1120
+ if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory,
1121
+ ...(runnerOwned===true?{runnerOwned:true,allowSymlinks}:{})},'n4');
1053
1122
  requireTaskId(task,'task');
1054
1123
  const payload=loadHandoff(handoff,{task});
1055
1124
  if(payload.status!=='ready_for_review')throw new GateError('N4 requires a ready_for_review handoff');
@@ -1062,8 +1131,9 @@ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowL
1062
1131
  return {gate:'n4',task,attempt,outcome:'ready_for_review',handoff_sha256:sha256(handoff),content_bound:contentBound,...inventoryResult};
1063
1132
  }
1064
1133
 
1065
- export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null,allowSymlinks=false}){
1066
- if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory},'n5');
1134
+ export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null,inventory=null,allowSymlinks=false,runnerOwned=false}){
1135
+ if(correction!==null)return checkCorrection({handoff,reviewsDir,feature,task,projectRoot,correction,allowLegacyUnbound,inventory,
1136
+ ...(runnerOwned===true?{runnerOwned:true,allowSymlinks}:{})},'n5');
1067
1137
  requireTaskId(task,'task');
1068
1138
  const payload=loadHandoff(handoff,{task});
1069
1139
  if(payload.status!=='ready_for_review')throw new GateError('N5 requires a ready_for_review handoff');
@@ -174,7 +174,7 @@ const draft=(tasks)=>({draftDigest:'d',features:[{directory:'1.sample',name:'sam
174
174
  const codes=report=>report.findings.map(item=>item.code);
175
175
 
176
176
  test('rule 3: every task of a new draft must declare its files; earlier rules do not ask',()=>{
177
- assert.equal(PRD_SELF_CHECK_RULES,5,'rules 4 and 5 keep the rule-3 scope check');
177
+ assert.equal(PRD_SELF_CHECK_RULES,8,'rules 4, 5, 7 and 8 keep the rule-3 scope check');
178
178
  const without=draft('- [ ] T-001: a\n- [ ] T-002: b\n - 范围: `b.js`\n');
179
179
  const report=checkPrdDraftMechanics(without,{rules:3});
180
180
  assert.deepEqual(codes(report),['task_scope_missing']);
@@ -23,8 +23,9 @@ import {readSourceFiles,snapshotSource,selectReportDirectory,checkSourceEvidence
23
23
  import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
24
24
  import {inspectDeclaredTestCommand} from '../runtime/js/cm-test/declared-command.mjs';
25
25
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
26
- import {effectDigest} from '../runtime/js/cm-refactor/records.mjs';
27
- import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
26
+ import {effectDigest,journalCreatedBy} from '../runtime/js/cm-refactor/records.mjs';
27
+ import {assertResumable,executorRelease} from '../runtime/js/executor-version.mjs';
28
+ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,errorLine} from '../runtime/js/cm-ai/drive-core.mjs';
28
29
 
29
30
  import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
30
31
 
@@ -49,10 +50,10 @@ function main(){
49
50
  valid(config.skillDir===path.join(root,'skills/cm-test'),'config.skillDir 必须指向当前 checkout');
50
51
  let admission;
51
52
  try{admission=inspectCmTestAdmission({...config.arguments,skillDir:config.skillDir,project:config.project});}
52
- catch(error){stop(2,`宿主配置准入失败: ${error.code??error.message}`);}
53
+ catch(error){stop(2,`宿主配置准入失败: ${errorLine(error)}`);}
53
54
  valid(admission.status==='ready','宿主配置准入');
54
55
  try{createCmTestHost(config,{call:()=>{throw Error('preflight must not call host')}});}
55
- catch(error){stop(2,`宿主配置无效: ${error.code??error.message}`);}
56
+ catch(error){stop(2,`宿主配置无效: ${errorLine(error)}`);}
56
57
  valid(['codex','claude'].includes(config.runtime)&&Array.isArray(config.sources)&&Array.isArray(config.commands)
57
58
  &&config.commands.length<=32&&path.isAbsolute(config.logHome),'config.runtime/sources/commands/logHome');
58
59
  if(admission.operation==='impact')valid(config.commands.length===0&&config.environment===null,'impact 只读配置');
@@ -67,6 +68,9 @@ function main(){
67
68
  const session=path.resolve(base,plan.sessionDir);
68
69
  if(!safeFile(path.join(session,'execution.jsonl')))stop(2,`恢复记录不存在: ${path.join(session,'execution.jsonl')}`);
69
70
  const rows=fs.readFileSync(path.join(session,'execution.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
71
+ // Same gate the host applies before writing: a newer journal is refused with its reason.
72
+ try{const createdBy=journalCreatedBy(rows);if(createdBy)assertResumable(createdBy);}
73
+ catch(error){stop(2,errorLine(error));}
70
74
  const context=rows.find(row=>row.type==='context')?.value;
71
75
  valid(context?.workflow==='cm-test'&&context.configDigest===digest(config),'resume 配置绑定不匹配');
72
76
  const pending=new Map(),inputs=new Map();let last=null;
@@ -84,6 +88,7 @@ function main(){
84
88
  }else if(operation==='start'&&plan.sessionDir){
85
89
  const session=path.resolve(base,plan.sessionDir);
86
90
  valid(!fs.existsSync(path.join(session,'execution.jsonl')),'start 的 sessionDir 已有记录,请用 resume');
91
+ try{executorRelease();}catch(error){stop(2,errorLine(error));}
87
92
  }
88
93
  const existingSession=plan.sessionDir&&safeFile(path.join(path.resolve(base,plan.sessionDir),'execution.jsonl'));
89
94
  const answerRoot=plan.answers?path.resolve(base,plan.answers):null;
@@ -91,12 +96,12 @@ function main(){
91
96
  if(['start','resume'].includes(operation)){
92
97
  if(admission.operation==='impact'){
93
98
  try{impact=collectBranchImpact(admission.project,admission.comparison,config.sources,config.mapPaths??[]);}
94
- catch(error){stop(2,`impact 定义无效: ${error.code??error.message}`);}
99
+ catch(error){stop(2,`impact 定义无效: ${errorLine(error)}`);}
95
100
  if(impact.changes.length)asks.push('change_impact');
96
101
  }else{
97
102
  const runId='test-drive-preflight';
98
103
  let snapshot;try{snapshot=snapshotSource(admission.project,selectReportDirectory(admission,runId));
99
- sources=readSourceFiles(admission.project,config.sources,snapshot);}catch(error){stop(2,`sources 定义无效: ${error.code??error.message}`);}
104
+ sources=readSourceFiles(admission.project,config.sources,snapshot);}catch(error){stop(2,`sources 定义无效: ${errorLine(error)}`);}
100
105
  const caseFile=admission.cases??(admission.specs&&admission.feature?path.join(admission.specs,admission.feature,'test-cases.json'):null);
101
106
  if(caseFile&&safeFile(caseFile)){
102
107
  if(path.extname(caseFile)==='.json'){
@@ -107,7 +112,7 @@ function main(){
107
112
  if(admission.operation==='generate_cases'||contract===null)asks.push('test_cases');
108
113
  for(const item of config.commands){
109
114
  try{inspectDeclaredTestCommand(item,sources);createHostCheck({cwd:admission.project,commands:[{id:item.id,command:item.command}]});}
110
- catch(error){stop(2,`声明命令无效 ${item?.id??'?'}: ${error.code??error.message}`);}
115
+ catch(error){stop(2,`声明命令无效 ${item?.id??'?'}: ${errorLine(error)}`);}
111
116
  }
112
117
  }
113
118
  }
@@ -131,7 +136,7 @@ function main(){
131
136
  valid(value.contractDigest===digest(selected),'qa_logic.contractDigest');
132
137
  checkSourceEvidence(value.results,sources);
133
138
  }
134
- }catch(error){stop(2,`答案格式错误:${kind}: ${error.code??error.message}`);}
139
+ }catch(error){stop(2,`答案格式错误:${kind}: ${errorLine(error)}`);}
135
140
  return value;
136
141
  };
137
142
  const answers=preflightAnswers(asks,loadAnswer);
@@ -3,6 +3,8 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {fileURLToPath} from 'node:url';
5
5
  import {inspectBranchComparison} from '../runtime/js/cm-test/branch-impact.mjs';
6
+ import {executorRelease} from '../runtime/js/executor-version.mjs';
7
+ import {diagnosticReason} from '../runtime/js/cm-ai/diagnostic-reason.mjs';
6
8
 
7
9
  const FEATURE=/^(\d+)\.(.+)$/;
8
10
  const OPTIONAL=new Set(['description','specs','feature','cases','reportDir','generateCases',
@@ -82,7 +84,8 @@ function workflowRoot(skillDir) {
82
84
  ownedFile(root,'VERSION','skill_path_invalid');layout='plugin';
83
85
  }else if(fs.existsSync(path.join(root,'templates','cm-VERSION'))){
84
86
  ownedFile(root,'templates/cm-VERSION','skill_path_invalid');layout='claude-compat';
85
- }else reject('skill_path_invalid');
87
+ // No release marker at all: a broken install, reported with its reinstall hint.
88
+ }else{executorRelease(root);reject('skill_path_invalid');}
86
89
  ownedFile(root,'skills/cm-test/SKILL.md','skill_path_invalid');
87
90
  ownedFile(root,'runtime/test-contract.md','skill_path_invalid');
88
91
  ownedFile(root,'scripts/cm-test-entry.mjs','skill_path_invalid');
@@ -230,7 +233,7 @@ if(isMainModule(process.argv[1])){
230
233
  process.stdout.write(`${JSON.stringify(result)}\n`);
231
234
  } catch(error) {
232
235
  process.stderr.write(`${JSON.stringify({schemaVersion:1,workflow:'cm-test',status:'blocked',
233
- reason:error?.code??'admission_failed'})}\n`);
236
+ reason:error?.code??'admission_failed',...(diagnosticReason(error)?{detail:diagnosticReason(error)}:{})})}\n`);
234
237
  process.exitCode=2;
235
238
  }
236
239
  }
@@ -10,6 +10,7 @@ import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
10
10
  import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
11
11
  import {need} from '../runtime/js/cm-ai/effect-contract.mjs';
12
12
  import {openTestSession} from '../runtime/js/cm-test/session.mjs';
13
+ import {diagnosticReason} from '../runtime/js/cm-ai/diagnostic-reason.mjs';
13
14
 
14
15
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
15
16
  let bridge,session;
@@ -34,7 +35,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
34
35
  const rawMode=input.isTTY&&typeof input.setRawMode==='function';if(rawMode)input.setRawMode(true);
35
36
  try{await serveCmAiHost({host,input,output,toolBridge:bridge});}finally{if(rawMode)input.setRawMode(false);}
36
37
  return 0;
37
- }catch(cause){error.write(JSON.stringify({error:{code:cause?.code??'cm_test_host_failed'}})+'\n');return 1;}
38
+ }catch(cause){const reason=cause instanceof Error?diagnosticReason(cause):null;
39
+ error.write(JSON.stringify({error:{code:cause?.code??'cm_test_host_failed',...(reason?{reason}:{})}})+'\n');return 1;}
38
40
  finally{bridge?.close();session?.close();}
39
41
  }
40
42
  if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=await main();
@@ -18,10 +18,11 @@ import os from 'node:os';
18
18
  import path from 'node:path';
19
19
  import {createHash,randomUUID} from 'node:crypto';
20
20
  import {spawnSync} from 'node:child_process';
21
- import {fileURLToPath} from 'node:url';
21
+ import {fileURLToPath,pathToFileURL} from 'node:url';
22
22
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
23
23
  import {buildManifest} from './cm-spec-manifest.mjs';
24
24
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
25
+ import {executorRelease} from '../runtime/js/executor-version.mjs';
25
26
 
26
27
  const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
27
28
  const LEGACY_COMMIT='f73402d';
@@ -57,8 +58,10 @@ function fixture(t){
57
58
  workflows:{'1.work/T-001':workflow,'1.work/T-002':workflow}};
58
59
  fs.writeFileSync(path.join(root,'run.json'),JSON.stringify(bundle));
59
60
  fs.writeFileSync(path.join(root,'control.json'),JSON.stringify(policy));
60
- fs.writeFileSync(path.join(root,'review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,cli_model:'fixture',
61
- prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture'})}}));
61
+ // Preflight receipt bound to a code version's reviewer arguments (default: the current code).
62
+ const writeReview=(fingerprint=configFingerprint)=>fs.writeFileSync(path.join(root,'review.json'),JSON.stringify({model:'fixture',
63
+ preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',config_fingerprint:fingerprint({cwd:codeProject,model:'fixture'})}}));
64
+ writeReview();
62
65
  // Fixture Codex reviewer: approves, except T-002 while the reject marker exists.
63
66
  fs.writeFileSync(path.join(bin,'codex'),`#!${process.execPath}
64
67
  const fs=require('node:fs');let prompt='';process.stdin.on('data',part=>prompt+=part);process.stdin.on('end',()=>{
@@ -87,11 +90,19 @@ const fs=require('node:fs');let prompt='';process.stdin.on('data',part=>prompt+=
87
90
  const drive=(workflowRoot=repo)=>spawnSync(process.execPath,[path.join(workflowRoot,'scripts/cm-ai-batch-drive.mjs'),'--plan',plan,'advance'],
88
91
  {encoding:'utf8',timeout:120000,env:{...process.env,PATH:bin+path.delimiter+process.env.PATH,
89
92
  CM_WORKFLOW_HOME:path.join(root,'home'),CM_WORKFLOW_LOG_HOME:path.join(root,'logs')}});
90
- return {root,specsDir,codeProject,bundle,reject,writePlan,drive,log:path.join(specsDir,'运行日志.jsonl')};
93
+ return {root,specsDir,codeProject,bundle,reject,writePlan,writeReview,drive,log:path.join(specsDir,'运行日志.jsonl')};
91
94
  }
92
95
  // The plan digest and worktree segment exactly as f73402d computed them.
93
96
  const legacyPlanDigest=bundle=>digest({...bundle.batch,controlPolicy:policy});
94
97
  const legacySegment=id=>`${id.slice(0,8).replace(/\./g,'-')}-${createHash('sha256').update(id).digest('hex').slice(0,12)}`;
98
+ // The log is append-only: the pre-upgrade text must stay the exact prefix, byte for byte
99
+ // (comparing parsed rows would miss a rewrite that only changes spacing or key order).
100
+ // Raw bytes, not decoded text: decoding maps invalid UTF-8 and U+FFFD to the same character.
101
+ const assertLogPrefix=(f,before,message)=>{
102
+ const bytes=fs.readFileSync(f.log);
103
+ assert.ok(bytes.length>before.length,'the upgraded run appended rows');
104
+ assert.deepEqual(bytes.subarray(0,before.length),before,message);
105
+ };
95
106
  const batchRows=f=>fs.readFileSync(f.log,'utf8').trim().split('\n').map(line=>JSON.parse(line))
96
107
  .filter(row=>row.run_id===batchId&&row.event==='decision'&&row.phase.startsWith('batch_'));
97
108
  const memberStates=f=>{
@@ -134,21 +145,27 @@ test('a batch whose pre-upgrade host wrote batch_start and stopped before its fi
134
145
  const result=resumeToDone(f);
135
146
  assert.equal(result.state,'run_done',JSON.stringify(result).slice(0,800));
136
147
  assertLegacyCompletion(f,planDigest);
137
- assert.equal(batchRows(f)[0].event_id,row.event_id,'the original batch_start row is kept, not rewritten');
148
+ assertLogPrefix(f,Buffer.from(JSON.stringify(row)+'\n'),'the original batch_start row is kept byte for byte, not rewritten');
149
+ // Review q1: members created after the upgrade keep the QA count the batch was approved by.
150
+ for(const [runId,state] of Object.entries(memberStates(f)))
151
+ assert.equal(Object.hasOwn(state.records[0].payload.config,'qaCadence'),false,`${runId} keeps the historical QA cadence`);
138
152
  });
139
153
 
140
154
  const legacyAvailable=spawnSync('git',['-C',repo,'cat-file','-e',`${LEGACY_COMMIT}^{commit}`]).status===0;
141
155
  test('a batch the f73402d code really ran to mid-member resumes on the new code with unchanged fingerprints to run_done',
142
- {skip:legacyAvailable?false:`${LEGACY_COMMIT} 不在本地历史(浅克隆),跳过真实旧代码运行`,timeout:300000},t=>{
156
+ {skip:legacyAvailable?false:`${LEGACY_COMMIT} 不在本地历史(浅克隆),跳过真实旧代码运行`,timeout:300000},async t=>{
143
157
  const old=fs.mkdtempSync(path.join(os.tmpdir(),'cm-upgrade-old-'));t.after(()=>fs.rmSync(old,{recursive:true,force:true}));
144
158
  const archive=spawnSync('sh',['-c',`git -C "$1" archive ${LEGACY_COMMIT} | tar -x -C "$2"`,'archive',repo,old],{encoding:'utf8'});
145
159
  assert.equal(archive.status,0,archive.stderr);
146
160
  const f=fixture(t);fs.writeFileSync(f.reject,'');
161
+ // The pre-upgrade host only accepts a receipt for its own reviewer arguments; 813b9d0 later
162
+ // changed them, so the receipt is the one f73402d's preflight would have written.
163
+ f.writeReview((await import(pathToFileURL(path.join(old,'runtime/js/cm-ai/codex-config.mjs')).href)).configFingerprint);
147
164
  // Pre-upgrade run: T-001 done and handed off, T-002 stopped after a changes_requested review.
148
165
  const first=f.drive(old);assert.equal(first.status,0,first.stderr);
149
166
  const stopped=lastResult(first);
150
- assert.deepEqual([stopped.state,stopped.code,stopped.identity.taskId],['changes_requested','revision_answer_required','T-002']);
151
- const before=batchRows(f),states=memberStates(f);
167
+ assert.deepEqual([stopped.state,stopped.code,stopped.identity?.taskId],['changes_requested','revision_answer_required','T-002']);
168
+ const before=batchRows(f),beforeLog=fs.readFileSync(f.log),states=memberStates(f);
152
169
  assert.deepEqual(before.map(row=>row.phase),['batch_start','batch_task_committed','batch_handoff']);
153
170
  // The hand-written archive above matches the real one: same row keys, same digest formula.
154
171
  assert.deepEqual(Object.keys(before[0]).sort(),LEGACY_START_KEYS);
@@ -158,15 +175,51 @@ test('a batch the f73402d code really ran to mid-member resumes on the new code
158
175
  for(const state of Object.values(states))assert.deepEqual(Object.keys(state.fingerprints).sort(),['config','inputs','workflow']);
159
176
  // Upgrade: the T-002 author answers the review; the reviewer now approves.
160
177
  fs.rmSync(f.reject);
178
+ // Documented upgrade step (CHANGELOG, 813b9d0): re-run the preflight with the same config.
179
+ f.writeReview();
161
180
  const answers=path.join(f.root,'answers/1.work/T-002');
162
181
  fs.writeFileSync(path.join(answers,'develop-a2.json'),JSON.stringify({...develop,edits:{'other.mjs':'second.txt'}}));
163
182
  fs.writeFileSync(path.join(answers,'second.txt'),'export const other = 2;\n');
164
183
  const result=resumeToDone(f);
165
184
  assert.equal(result.state,'run_done',JSON.stringify(result).slice(0,800));
166
185
  assertLegacyCompletion(f,before[0].plan_digest);
167
- assert.deepEqual(batchRows(f).slice(0,3),before,'the pre-upgrade rows are kept byte for byte');
186
+ assertLogPrefix(f,beforeLog,'the pre-upgrade log rows are kept byte for byte');
168
187
  const after=memberStates(f);
169
188
  for(const [runId,state] of Object.entries(states))
170
189
  assert.deepEqual(after[runId].fingerprints,state.fingerprints,`${runId} keeps its pre-upgrade fingerprints`);
171
190
  assert.equal(fs.readFileSync(path.join(f.codeProject,'other.mjs'),'utf8'),'export const other = 2;\n');
172
191
  });
192
+
193
+ // Executor release (0.22.0): a batch started by this release folds its createdBy into
194
+ // the plan digest, so the real 0.21.7 code reads batch_plan_mismatch and writes nothing.
195
+ const RELEASE_0_21_7='034d460';
196
+ const release0217Available=spawnSync('git',['-C',repo,'cat-file','-e',`${RELEASE_0_21_7}^{commit}`]).status===0;
197
+ test('the real 0.21.7 code refuses a batch this release started before writing anything',
198
+ {skip:release0217Available?false:`${RELEASE_0_21_7} 不在本地历史(浅克隆),跳过真实旧代码运行`,timeout:300000},t=>{
199
+ const old=fs.mkdtempSync(path.join(os.tmpdir(),'cm-release-0217-'));t.after(()=>fs.rmSync(old,{recursive:true,force:true}));
200
+ const archive=spawnSync('sh',['-c',`git -C "$1" archive ${RELEASE_0_21_7} | tar -x -C "$2"`,'archive',repo,old],{encoding:'utf8'});
201
+ assert.equal(archive.status,0,archive.stderr);
202
+ const f=fixture(t);
203
+ const first=f.drive();assert.equal(first.status,0,first.stderr);
204
+ const start=batchRows(f)[0];
205
+ assert.equal(start.phase,'batch_start');assert.deepEqual(start.created_by,{version:1,release:executorRelease()});
206
+ assert.notEqual(start.plan_digest,legacyPlanDigest(f.bundle),'the release is part of the plan digest');
207
+ const before={log:fs.readFileSync(f.log),stores:memberStates(f)};
208
+ f.writePlan('resume');
209
+ // With a member store on disk 0.21.7 already stops at its read-only member check.
210
+ const downgraded=f.drive(old);
211
+ assert.notEqual(downgraded.status,0);assert.match(downgraded.stderr,/invalid_input/,downgraded.stderr);
212
+ assert.deepEqual({log:fs.readFileSync(f.log),stores:memberStates(f)},before,'0.21.7 wrote nothing');
213
+ // Only batch_start on disk (stopped before its first member): the plan digest stops it.
214
+ const execution=path.join(f.specsDir,'.reviews/.execution');
215
+ for(const name of Object.keys(memberStates(f)))fs.rmSync(path.join(execution,name),{recursive:true,force:true});
216
+ fs.writeFileSync(f.log,JSON.stringify(start)+'\n');
217
+ const onlyStart=fs.readFileSync(f.log),batchOnly=f.drive(old);
218
+ assert.match(batchOnly.stdout+batchOnly.stderr,/batch_plan_mismatch/,batchOnly.stdout+batchOnly.stderr);
219
+ assert.deepEqual(fs.readFileSync(f.log),onlyStart,'0.21.7 appended nothing');assert.deepEqual(memberStates(f),{});
220
+ // A row stripped of created_by is not read as a pre-0.22.0 batch either.
221
+ const rows=fs.readFileSync(f.log,'utf8').trim().split('\n').map(line=>JSON.parse(line));
222
+ fs.writeFileSync(f.log,rows.map(row=>JSON.stringify(row.phase==='batch_start'?(({created_by,...rest})=>rest)(row):row)).join('\n')+'\n');
223
+ const stripped=f.drive();
224
+ assert.match(stripped.stdout+stripped.stderr,/batch_plan_mismatch/,stripped.stdout+stripped.stderr);
225
+ });
@@ -0,0 +1,8 @@
1
+ // Test helper: create runs with the completion-check reuse escape hatch set
2
+ // (CM_AI_COMPLETION_CHECK_REUSE=off), so tests of the fresh completion re-check
3
+ // machinery (retries, limits, rework) keep exercising it. Restores the variable.
4
+ export async function withFreshCompletionChecks(run){
5
+ const old=process.env.CM_AI_COMPLETION_CHECK_REUSE;process.env.CM_AI_COMPLETION_CHECK_REUSE='off';
6
+ try{return await run();}
7
+ finally{if(old===undefined)delete process.env.CM_AI_COMPLETION_CHECK_REUSE;else process.env.CM_AI_COMPLETION_CHECK_REUSE=old;}
8
+ }
@@ -155,8 +155,17 @@ def load_receipt(path: Path, *, stage: str, feature: str, evidence: Path) -> dic
155
155
  "artifacts",
156
156
  "at",
157
157
  }
158
+ if isinstance(value, dict) and "narrow_user_decision_sha256" in value:
159
+ # Design only: the user's accept-risks decision this receipt released on (mirrors the JS gate).
160
+ required = required | {"narrow_user_decision_sha256"}
158
161
  if not isinstance(value, dict) or set(value) != required:
159
162
  raise GateError("PRD review receipt fields do not match the contract")
163
+ if "narrow_user_decision_sha256" in value and (
164
+ value["stage"] != "design"
165
+ or not isinstance(value["narrow_user_decision_sha256"], str)
166
+ or not re.fullmatch(r"[0-9a-f]{64}", value["narrow_user_decision_sha256"])
167
+ ):
168
+ raise GateError("PRD review receipt narrow decision binding is invalid")
160
169
  if (
161
170
  value["schema_version"] != 1
162
171
  or value["stage"] != stage
@@ -90,8 +90,9 @@ test('real cm-test host: a journal bound by 0b3040e opens and replays; another p
90
90
  if(message.type==='host_request')child.kill('SIGKILL');});
91
91
  await closed;
92
92
  const journal=path.join(session,'execution.jsonl');
93
- const rebind=policy=>{let previous=null;const rows=fs.readFileSync(journal,'utf8').trimEnd().split('\n').map(line=>JSON.parse(line)).map(({hash,...row})=>{
94
- const body={...row,...(row.type==='context'?{value:{...row.value,binding:{...row.value.binding,policy}}}:{}),previous};
93
+ // The first row keeps its own previous (a format-2 journal starts from its format seed).
94
+ const rebind=policy=>{let previous=null;const rows=fs.readFileSync(journal,'utf8').trimEnd().split('\n').map(line=>JSON.parse(line)).map(({hash,...row},index)=>{
95
+ const body={...row,...(row.type==='context'?{value:{...row.value,binding:{...row.value.binding,policy}}}:{}),previous:index===0?row.previous:previous};
95
96
  previous=digest(body);return {...body,hash:previous};});
96
97
  fs.writeFileSync(journal,rows.map(row=>JSON.stringify(row)).join('\n')+'\n',{mode:0o600});};
97
98
  rebind(legacyTest.policy);
@@ -75,6 +75,30 @@ def runtime_mark_fixtures(root: Path) -> None:
75
75
  assert "changed after disposition" in invoke("inspect", *flags, expected_exit=1)["stderr"]
76
76
  (root / name).write_bytes(saved)
77
77
  assert receipt.read_bytes() == receipt_bytes
78
+ # Review (todo r1): the user-decision binding is design-only; a split receipt carrying it is rejected by both.
79
+ narrow_decision_binding_fixtures(receipt, ["inspect", *flags], accept_valid=False)
80
+
81
+
82
+ def narrow_decision_binding_fixtures(receipt: Path, inspect_args: list[str], *, accept_valid: bool = True) -> None:
83
+ """Both implementations read the optional design-only user-decision binding alike."""
84
+ saved = receipt.read_bytes()
85
+ base = json.loads(saved)
86
+ impls = [ROOT / "scripts" / "cm-prd-review-gate.mjs",
87
+ ROOT / "scripts" / "fixtures" / "prd-review-gate-python-oracle.py"]
88
+ cases = [("a" * 64, True), ("A" * 64, False), ("a" * 63, False), (7, False), (["a" * 64], False), (None, False)]
89
+ try:
90
+ for value, accepted in cases:
91
+ accepted = accepted and accept_valid
92
+ receipt.write_text(json.dumps({**base, "narrow_user_decision_sha256": value}) + "\n", encoding="utf-8")
93
+ for impl in impls:
94
+ runner = sys.executable if impl.suffix == ".py" else os.environ.get("CM_NODE_BIN", "node")
95
+ done = subprocess.run([runner, str(impl), *inspect_args], cwd=ROOT, text=True,
96
+ encoding="utf-8", capture_output=True, check=False)
97
+ ok = done.returncode == 0 and json.loads(done.stdout).get("outcome") == "completed"
98
+ if ok != accepted:
99
+ raise AssertionError(f"{impl.name} narrow binding {value!r}: expected accepted={accepted}\n{done.stderr}")
100
+ finally:
101
+ receipt.write_bytes(saved)
78
102
 
79
103
 
80
104
  def main() -> int:
@@ -221,6 +245,7 @@ def main() -> int:
221
245
  str(receipt),
222
246
  )
223
247
  assert completed["outcome"] == "completed"
248
+ narrow_decision_binding_fixtures(receipt, inspect_args)
224
249
 
225
250
  artifact.write_text("# changed after disposition\n", encoding="utf-8")
226
251
  artifact_mismatch = invoke(
@@ -99,7 +99,7 @@ START
99
99
 
100
100
  **暂停(仅灾难级):** 不可逆破坏(删数据、动线上、不可回滚迁移)、资金/密钥/合规风险、交付形态级架构错向、环境阻塞到无法继续。
101
101
  **不暂停(多方案自主决策):** 执行中出现多个可选方案时——技术选型、实现路径、库/工具选择、审查意见分歧——**自己分析利弊选最优解直接执行,不询问**。代价是留痕义务:把「选了什么 / 为什么 / 放弃了什么」写进任务汇报,方向性取舍追记 LESSONS.md——人可以事后翻案,但流程不为选择题停车。业务逻辑歧义按需求文档最合理解释执行并显式记录所做假设,仅当触及灾难级清单才暂停。
102
- **节点间不停车:** 除上述灾难级与各节点显式卡点(入口闸/降级知情/形态确认/涉合规走查)外,任何节点完成后**直接进入下一节点**——不得以"我将要…是否继续?"、"完成了 X,需要我继续吗?"这类问句收尾等待。阶段性汇报写在输出里照常可见,但回合不能停在等确认上(实跑反馈:执行器习惯性在节点末尾问一句,用户被迫每阶段点头,自动化名存实亡)。
102
+ **节点间不停车:** 除上述灾难级与各节点显式卡点(入口闸/降级知情/形态确认/涉合规走查)外,任何节点完成后**直接进入下一节点**——不得以"我将要…是否继续?"、"完成了 X,需要我继续吗?"这类问句收尾等待。阶段性汇报写在输出里照常可见,但回合不能停在等确认上(实跑反馈:执行器习惯性在节点末尾问一句,用户被迫每阶段点头,自动化名存实亡)。驾驶员最后一行 `[drive] 下一步:` 为 `继续` 时不得结束本轮;后台驾驶员与 Monitor 的配合见 `references/js-host.md` 第 7 条。
103
103
  **度量:** 每次暂停问人,恢复后在当前任务的 METRICS.md 记录里人工介入计 1 次并注明原因(见 N5)。
104
104
  **状态落盘(供状态条/看板实时点亮节点):** 每进入一个节点(N1–N8),覆盖写入 `{SPECS_DIR}/.cm-status.json` 单行 JSON:
105
105
  `{"node":"N4","feature":"1.xxx","task":"T-005","detail":"一句话当前动作","state":"running","at":"HH:MM:SS"}`
@@ -44,7 +44,7 @@
44
44
  以 JS admission 的结果为准;模型不得自行拼写或修改 `.cm-specs-status`:
45
45
 
46
46
  - `ready` / `complete` → 沿用现有准入结果;旧版无 `specFiles` 的文件仍可读取,不在本节点自行补造批准证据。
47
- - `awaiting_spec_approval` → 展示规格摘要卡(无卡时可现场汇总,但不得据此生成或替换 `summaryDigest`),请用户明确回复“开始”。JS 仅接受“开始”“开始吧”“可以开始”“确认开始”“开始执行”“现在开始”“可以,请开始开发”,可带尾部中英文句末标点和空白;泛化授权语(“继续”“可以”“好”“好的”“OK”“按最优解处理”“你看着办”“行”)仍不构成审批,未命中时明确提示回复“开始”(实跑失守:泛化授权曾被误视为审批通过)。
47
+ - `awaiting_spec_approval` → 展示规格摘要卡(无卡时可现场汇总,但不得据此生成或替换 `summaryDigest`),请用户明确回复“开始”。JS 仅接受“开始”“开始吧”“可以开始”“确认开始”“开始执行”“现在开始”“可以,请开始开发”“开工”“开工吧”“批准开工”“同意开工”“批准开始”“同意开始”,可带尾部中英文句末标点和空白;泛化授权语(“继续”“可以”“好”“好的”“OK”“按最优解处理”“你看着办”“行”)仍不构成审批,未命中时明确提示回复“开始”(实跑失守:泛化授权曾被误视为审批通过)。
48
48
  - 取得明确回复后运行以下写入口,`--approval-response` 传用户原话;多个代码项目全部传入:
49
49
 
50
50
  ```bash
@@ -94,11 +94,12 @@ node "{CM_WORKFLOW_ROOT}/scripts/cm-spec-amend.mjs" inspect --specs-dir "{SPECS_
94
94
 
95
95
  开工前按 `runtime/review.md` 探测能否建立**与实现者不同上下文**的审查通道,而不是检查当前进程是否叫 Codex:
96
96
 
97
- - 可创建 fresh Codex 子代理/独立线程 → 作为主通道
97
+ - 项目声明审查者为 `claude-cli`(含 `claude-only`)→ 只探测全新 Claude CLI 审查进程,不探测 Codex;不可用即暂停
98
+ - 其余情况:可创建 fresh Codex 子代理/独立线程 → 作为主通道
98
99
  - 子代理不可用,但可以安全启动隔离的 `codex` CLI 审查会话 → 作为备用通道
99
100
  - 两者都不可用 → 暂停新开发,已有实现保持待审并说明通道失败原因;不论任务风险高低,都不能用 `self-degraded` 诊断代替独立审查或进入成功收尾
100
101
 
101
- 当前 gate 支持的是上述 Codex 通道;未来 Claude-native 适配须单独验证,不能把
102
+ Codex 与 Claude 两条通道都由 protected host 实际启动并回收 V3 凭证;凭证标明实际审查端,不能把
102
103
  Claude 结果标成 Codex 通过门禁。通道不可用不算代码 finding,不消耗实现审查轮次。
103
104
 
104
105
  ## Git 前置检查(字段优先,询问兜底)
@@ -17,7 +17,10 @@ N3 保留开发期 lint 与测试;这些正常检查不构成作者自审前
17
17
 
18
18
  ## 1. 独立审查(强制)
19
19
 
20
- 按以下顺序选择一个**新上下文**的审查者:
20
+ 按以下顺序选择一个**新上下文**的审查者。**先看项目声明的 `roles.reviewer.adapter`**(含 `claude-only` 预设):
21
+ 声明为 `claude-cli` → 直接用第 3 项,不再尝试 Codex(实跑教训:声明 claude-only 后仍总被派去 Codex 审,因为旧顺序固定先试 Codex);
22
+ 声明为 `codex-cli`,或未声明 → 按下列顺序。
23
+ 本条只约束兼容流程;JS 宿主按 `--review-runtime` 显式选择审查端(声明与实际不符时需人工核对),不在此处自动改选。
21
24
 
22
25
  1. `codex-subagent`:用当前运行时的 no-history/fresh-context 选项(如 `fork_turns: none`)新建独立 Codex 子代理/线程,只接收任务范围、验收标准、diff 和验证结果
23
26
  2. `codex-cli`:子代理不可用时,启动隔离的非交互 Codex CLI 审查会话;禁止它修改文件
@@ -29,9 +32,9 @@ N3 保留开发期 lint 与测试;这些正常检查不构成作者自审前
29
32
 
30
33
  审查输入只包含**本 task 的 diff**,不得将整个未分类 working tree 当作任务 diff。审查者必须:
31
34
 
32
- - 假设这个 diff 有害,优先寻找可复现的失败场景
35
+ - 假设这个 diff 有害,优先寻找**可复现、可达的失败场景**
33
36
  - 对照 requirements/design/task 验收,检查超范围变更
34
- - 按严重度排序;每条必须说明「输入/状态 → 错误结果」
37
+ - 按严重度排序;每条阻断项(P0/P1/P2)必须说明「可达输入/状态 → 错误结果」;纯命名/措辞/文档润色、范围外重构建议或无可达触发路径的理论担忧一律归为 P3(只记录不阻断)
35
38
  - 找不到真实问题时明确写「零发现」,不凑数
36
39
 
37
40
  该 feature 存在 `test-cases.json` 时,把 `taskIds` 命中当前 task 的 logic cases