@aibyzero/cm-workflow 0.21.7 → 0.25.1

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 (227) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +64 -0
  3. package/README.md +15 -1
  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 +63 -19
  12. package/docs/js-workflow-control.md +67 -31
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +2 -2
  15. package/docs/user-guide.md +1 -1
  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/claude-probe-diagnosis.mjs +21 -0
  20. package/runtime/js/cm-ai/claude-review-stream.mjs +20 -7
  21. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -2
  22. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  23. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  24. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  25. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  27. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  28. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  29. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  30. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  32. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  33. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  34. package/runtime/js/cm-ai/host-check.mjs +4 -2
  35. package/runtime/js/cm-ai/host-conversation-execution.mjs +29 -2
  36. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  37. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  38. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  39. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  40. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  41. package/runtime/js/cm-ai/host-session.mjs +1 -1
  42. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  43. package/runtime/js/cm-ai/host.mjs +1 -1
  44. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  45. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  46. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  47. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  48. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  49. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  50. package/runtime/js/cm-ai/review-package.mjs +25 -4
  51. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  52. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  53. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  54. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  55. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  56. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  57. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  58. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  59. package/runtime/js/cm-ai/worker-claude-developer.mjs +3 -1
  60. package/runtime/js/cm-ai/worker-claude.mjs +5 -1
  61. package/runtime/js/cm-check/host.mjs +13 -3
  62. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  63. package/runtime/js/cm-fix/execution.mjs +47 -9
  64. package/runtime/js/cm-fix/finish.mjs +9 -1
  65. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  66. package/runtime/js/cm-idea/session.mjs +22 -3
  67. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  68. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  69. package/runtime/js/cm-prd/analysis.mjs +27 -9
  70. package/runtime/js/cm-prd/change.mjs +29 -8
  71. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  72. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  73. package/runtime/js/cm-prd/review-channels.mjs +5 -0
  74. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  75. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  76. package/runtime/js/cm-prd/review-publication.mjs +2 -1
  77. package/runtime/js/cm-prd/self-check.mjs +121 -9
  78. package/runtime/js/cm-prd/session.mjs +55 -13
  79. package/runtime/js/cm-prd/summary.mjs +34 -6
  80. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  81. package/runtime/js/cm-refactor/records.mjs +82 -11
  82. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  83. package/runtime/js/executor-version.mjs +81 -0
  84. package/runtime/js/python-log-writer.mjs +15 -0
  85. package/runtime/js/run-analysis.mjs +136 -11
  86. package/runtime/logging.md +6 -0
  87. package/runtime/review.md +2 -1
  88. package/scripts/ci-test-weights.json +1 -0
  89. package/scripts/cm-ai-admission.mjs +27 -1
  90. package/scripts/cm-ai-admission.test.mjs +34 -2
  91. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  92. package/scripts/cm-ai-batch-drive.mjs +54 -17
  93. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  94. package/scripts/cm-ai-batch-host.mjs +64 -11
  95. package/scripts/cm-ai-batch-host.test.mjs +23 -3
  96. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  97. package/scripts/cm-ai-batch-merge.mjs +102 -0
  98. package/scripts/cm-ai-batch-plan.mjs +55 -2
  99. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  100. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  101. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  102. package/scripts/cm-ai-batch-run.mjs +437 -34
  103. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  104. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  105. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  106. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  107. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  108. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  109. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  110. package/scripts/cm-ai-drive.mjs +66 -14
  111. package/scripts/cm-ai-drive.test.mjs +13 -3
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  113. package/scripts/cm-ai-host.mjs +20 -9
  114. package/scripts/cm-ai-host.test.mjs +12 -0
  115. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  116. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  117. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  118. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  119. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  120. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  121. package/scripts/cm-ai-run.mjs +42 -11
  122. package/scripts/cm-ai-run.test.mjs +26 -0
  123. package/scripts/cm-ai-supersede.test.mjs +10 -2
  124. package/scripts/cm-capability-gate.test.mjs +1 -1
  125. package/scripts/cm-check-host.test.mjs +54 -0
  126. package/scripts/cm-check-runtime.sh +27 -15
  127. package/scripts/cm-check-update.mjs +83 -8
  128. package/scripts/cm-check-update.test.mjs +114 -1
  129. package/scripts/cm-claude-developer-worker.test.mjs +29 -1
  130. package/scripts/cm-claude-managed-preflight.test.mjs +126 -0
  131. package/scripts/cm-claude-probe.test.mjs +5 -0
  132. package/scripts/cm-claude-review-stream.test.mjs +4 -1
  133. package/scripts/cm-claude-worker.test.mjs +29 -0
  134. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  135. package/scripts/cm-developer-self-review.test.mjs +27 -0
  136. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  137. package/scripts/cm-efficiency-response.test.mjs +2 -1
  138. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  139. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  140. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  141. package/scripts/cm-executor-version-records.test.mjs +256 -0
  142. package/scripts/cm-executor-version.test.mjs +250 -0
  143. package/scripts/cm-external-model-host.test.mjs +6 -1
  144. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  145. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  146. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  147. package/scripts/cm-fix-drive.mjs +7 -2
  148. package/scripts/cm-fix-drive.test.mjs +45 -0
  149. package/scripts/cm-fix-entry.mjs +5 -2
  150. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  151. package/scripts/cm-fix-host.mjs +9 -2
  152. package/scripts/cm-fix-review-preflight.mjs +2 -0
  153. package/scripts/cm-fix-review-verification-integration.test.mjs +19 -0
  154. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  155. package/scripts/cm-host-check.test.mjs +12 -0
  156. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  157. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  158. package/scripts/cm-idea-drive.mjs +5 -2
  159. package/scripts/cm-idea-entry.mjs +5 -2
  160. package/scripts/cm-idea-host.mjs +3 -1
  161. package/scripts/cm-init-drive.mjs +8 -5
  162. package/scripts/cm-init-entry.mjs +5 -2
  163. package/scripts/cm-init-host.mjs +6 -2
  164. package/scripts/cm-log-event.mjs +10 -2
  165. package/scripts/cm-log-event.test.mjs +29 -0
  166. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  167. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  168. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  169. package/scripts/cm-prd-completion.test.mjs +67 -4
  170. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  171. package/scripts/cm-prd-drive.mjs +91 -21
  172. package/scripts/cm-prd-drive.test.mjs +126 -4
  173. package/scripts/cm-prd-entry.mjs +5 -2
  174. package/scripts/cm-prd-host.mjs +89 -20
  175. package/scripts/cm-prd-host.test.mjs +17 -8
  176. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  177. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  178. package/scripts/cm-prd-review-gate.mjs +13 -5
  179. package/scripts/cm-prd-review-publication.test.mjs +34 -0
  180. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  181. package/scripts/cm-prd-self-check.test.mjs +1 -1
  182. package/scripts/cm-refactor-drive.mjs +10 -4
  183. package/scripts/cm-refactor-entry.mjs +5 -2
  184. package/scripts/cm-refactor-host.mjs +3 -1
  185. package/scripts/cm-release-smoke.sh +3 -2
  186. package/scripts/cm-run-analysis.test.mjs +373 -1
  187. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  188. package/scripts/cm-skill-hints-exam.mjs +3 -1
  189. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  190. package/scripts/cm-skill-hints.mjs +106 -10
  191. package/scripts/cm-skill-hints.test.mjs +162 -6
  192. package/scripts/cm-skill-judge.mjs +2 -1
  193. package/scripts/cm-task-gate.mjs +88 -18
  194. package/scripts/cm-task-scope.test.mjs +1 -1
  195. package/scripts/cm-test-drive.mjs +13 -8
  196. package/scripts/cm-test-entry.mjs +5 -2
  197. package/scripts/cm-test-host.mjs +3 -1
  198. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  199. package/scripts/cm-workflow-config.test.mjs +8 -3
  200. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  201. package/scripts/fixtures/prd-review-gate-python-oracle.py +10 -1
  202. package/scripts/policy-binding-compat.test.mjs +3 -2
  203. package/scripts/scan-public-safety.py +1 -0
  204. package/scripts/shell-pipe-early-exit.test.mjs +96 -0
  205. package/scripts/test-cm-prd-review-gate.py +55 -0
  206. package/scripts/test-shell-compat.sh +7 -5
  207. package/skills/cm-ai/SKILL.md +1 -1
  208. package/skills/cm-ai/references/N1-init.md +1 -1
  209. package/skills/cm-ai/references/N4-review.md +2 -2
  210. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  211. package/skills/cm-ai/references/js-host-recovery.md +5 -1
  212. package/skills/cm-ai/references/js-host.md +17 -8
  213. package/skills/cm-check/SKILL.md +3 -0
  214. package/skills/cm-fix/references/isolated-review.md +1 -1
  215. package/skills/cm-fix/references/js-host.md +20 -0
  216. package/skills/cm-fix/references/test-extension.md +1 -1
  217. package/skills/cm-prd/SKILL.md +8 -6
  218. package/skills/cm-prd/references/ai-draft.md +81 -0
  219. package/skills/cm-prd/references/change-mode.md +2 -0
  220. package/skills/cm-prd/references/greenfield.md +2 -0
  221. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  222. package/skills/cm-prd/references/js-host.md +9 -6
  223. package/skills/cm-prd/references/light-mode.md +19 -0
  224. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  225. package/skills/cm-prd/references/spec-self-check.md +1 -0
  226. package/skills/cm-prd/references/summary-card.md +1 -0
  227. package/templates/auto-update/cm-update.sh +2 -2
@@ -0,0 +1,106 @@
1
+ // Plain-language QA notes for runs that froze qaCadence 'feature-v1' (new runs only):
2
+ // which acceptance criteria this round covers, and what a BLOCKED round is missing.
3
+ // Both are read-only explanations beside the verdicts; they never change a verdict.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import {acceptanceDeclarations} from './cm-ai-admission.mjs';
7
+ import {digest} from './effect-contract.mjs';
8
+
9
+ // Every acceptance criterion the feature declares (requirements, design, tasks: the
10
+ // same files admission accepts acIds from), with the cases bound to it at QA start.
11
+ // planned: a case runs this round; later: an applicable case waits (deferred task or
12
+ // periodic browser); not_selected: its cases are neither blocking nor a kind the project's
13
+ // tests policy runs; dropped: its only cases are bound only to [DROPPED] tasks (the
14
+ // report lists them NOT_APPLICABLE); no_case: no case names it at all.
15
+ // A criterion is skipped only when every declaration of it says NOT_APPLICABLE: one
16
+ // plain declaration anywhere keeps it (as the spec self-check rules it).
17
+ export function acceptanceCoverage({featureRoot,cases,selectedIds,applicableIds,droppedIds}){
18
+ const declared=new Map();
19
+ for(const file of ['requirements.md','design.md','tasks.md']){
20
+ const target=path.join(featureRoot,file);
21
+ if(!fs.existsSync(target))continue;
22
+ for(const item of acceptanceDeclarations(fs.readFileSync(target,'utf8')))
23
+ declared.set(item.id,(declared.get(item.id)??true)&&item.inapplicable);
24
+ }
25
+ return [...declared].filter(([,inapplicable])=>!inapplicable).map(([id])=>{
26
+ const named=cases.filter(item=>item.acIds.includes(id)).map(item=>item.id);
27
+ const bound=named.filter(caseId=>!droppedIds.has(caseId));
28
+ const status=named.length===0?'no_case':bound.length===0?'dropped':bound.some(caseId=>selectedIds.has(caseId))?'planned'
29
+ :bound.some(caseId=>applicableIds.has(caseId))?'later':'not_selected';
30
+ return {id,status,cases:named};
31
+ });
32
+ }
33
+
34
+ const MESSAGES={
35
+ source_changed:'QA 进行中代码被改动,需要重跑 QA',
36
+ host_timeout:'执行方超时没有回答;确认设备或会话空闲后重跑',
37
+ confirmation:'用例预期带 [需确认],需要负责人确认预期',
38
+ test_command_missing:'没有声明项目测试命令;在 workflow 配置的 QA commands 里补上',
39
+ qa_contract_missing:'没有可执行的 QA 合同(test-cases.json 或测试命令)',
40
+ no_applicable_cases:'本轮没有可执行的用例(相关任务还没完成)',
41
+ command_unavailable:'测试命令没能运行(命令或依赖不可用)',
42
+ command_timeout:'测试命令超时没有跑完',
43
+ capability_missing:'没有接入浏览器或设备执行方,这类用例跑不了',
44
+ command_no_result:'对应的测试命令没有跑出结果',
45
+ logic_command_mapping:'逻辑用例没有对应的测试命令;在 QA commands 的 caseIds 里映射',
46
+ evidence:'浏览器或设备用例缺少有效的证据文件',
47
+ cleanup:'用例要求的清理没有完成',
48
+ unclassified:'原因未归类,请看 QA 报告里的这一行',
49
+ };
50
+ // One line: a report section starts at a line beginning with `## `.
51
+ const clip=value=>{const chars=[...String(value).replace(/\s+/g,' ').trim()];return chars.length>120?`${chars.slice(0,120).join('')}…`:chars.join('');};
52
+ function need(row,environment,reason){
53
+ if(row.sourceChanged)return {need:'source_changed'};
54
+ if(row.hostRequestTimeout)return {need:'host_timeout'};
55
+ if(row.needsConfirmation)return {need:'confirmation'};
56
+ if(row.kind==='commands'){
57
+ // The host's own placeholder rows carry no exitCode; a declared command always does,
58
+ // so a command that happens to share one of these names is judged as a command.
59
+ if(!Object.hasOwn(row,'exitCode')){
60
+ if(row.id==='commands-unavailable')return {need:'test_command_missing'};
61
+ if(row.id==='qa-unavailable')return {need:'qa_contract_missing'};
62
+ if(row.id==='no-applicable-cases')return {need:'no_applicable_cases'};
63
+ }
64
+ if(Array.isArray(row.evidence)&&row.evidence.includes('host check: timeout'))return {need:'command_timeout'};
65
+ return {need:'command_unavailable'};
66
+ }
67
+ if(row.kind==='logic'){
68
+ if(row.commandUnavailable)return {need:'command_no_result'};
69
+ if(!row.commandEvidence?.length)return {need:'logic_command_mapping'};
70
+ return {need:'unclassified'};
71
+ }
72
+ // The executor's own reason for a browser case (feature-v1 runs) decides first.
73
+ if(reason==='unavailable')return {need:'capability_missing'};
74
+ if(reason==='needs_confirmation')return {need:'confirmation'};
75
+ if(row.hostDeclaredBlocked){
76
+ const said=Array.isArray(row.evidence)&&typeof row.evidence[0]==='string'?clip(row.evidence[0]):'';
77
+ return {need:'host_declared',detail:said?`执行方报告环境不可用:${said}`:'执行方报告环境不可用,没有说明原因'};
78
+ }
79
+ if(row.evidenceProblem)return {need:'evidence'};
80
+ if(row.environment&&digest(row.environment)!==digest(environment))return {need:'environment_mismatch',
81
+ detail:`实际环境与登记的不一致;需要 ${environment.kind}/${environment.carrier}(${clip(environment.target)})`};
82
+ if(reason==='evidence')return {need:'evidence'};
83
+ if(row.cleanup==='failed'||reason==='cleanup')return {need:'cleanup'};
84
+ return {need:'unclassified'};
85
+ }
86
+ // One entry per distinct need (and detail), listing the BLOCKED rows behind it.
87
+ // reasons: case id -> the executor's own blocked reason, kept beside the rows.
88
+ export function qaBlockedNeeds(rows,environment,reasons=new Map()){
89
+ const grouped=new Map();
90
+ for(const row of rows.filter(item=>item.verdict==='BLOCKED')){
91
+ const found=need(row,environment,reasons.get(row.id)??null),detail=found.detail??MESSAGES[found.need],key=`${found.need}\n${detail}`;
92
+ if(!grouped.has(key))grouped.set(key,{need:found.need,detail,cases:[]});
93
+ grouped.get(key).cases.push(row.id);
94
+ }
95
+ return [...grouped.values()];
96
+ }
97
+
98
+ // The notes are explanations: they join the report only when what they would cost
99
+ // still fits the limit, so they never cost a QA round its result.
100
+ export const QA_NOTES_OMITTED='QA notes omitted: report size limit\n\n';
101
+ export function composeQaReport({head,notes,tail,limit=1024*1024}){
102
+ const full=Buffer.from(head+notes+tail);
103
+ if(notes===''||full.length<=limit)return full;
104
+ const shorter=Buffer.from(head+QA_NOTES_OMITTED+tail);
105
+ return shorter.length<=limit?shorter:Buffer.from(head+tail);
106
+ }
@@ -0,0 +1,102 @@
1
+ // Third controlled review pilot (review-continuation-authorized). The owning
2
+ // runner journals the authorization; these helpers only project it onto the
3
+ // task's fixed evidence files and the existing controlled-correction protocol.
4
+ // Nothing here grants a review, a completion or another continuation.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import {createHash} from 'node:crypto';
8
+ import {digest,need,id} from './effect-contract.mjs';
9
+ import {readReviewPackage} from './review-package.mjs';
10
+ import {reviewResult} from './review-runner.mjs';
11
+ import {writeImmutableWorkflowFile} from './review-evidence-file.mjs';
12
+ import {loadHandoff,checkN4,prepareControlledCorrection,publishControlledCorrectionReview,healAtomicTempLinks,
13
+ REVIEW_CONTINUATION_MARKER_PROTOCOL} from '../../../scripts/cm-task-gate.mjs';
14
+
15
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
16
+ const present=file=>{try{fs.lstatSync(file);return true;}catch(error){if(error.code==='ENOENT')return false;throw error;}};
17
+ export function continuationPaths(reviewsDir,feature,task){
18
+ const prefix=path.join(reviewsDir,`${feature}-${task}`);
19
+ return {marker:`${prefix}-review-continuation.json`,record:`${prefix}-controlled-correction.json`,
20
+ handoff:`${prefix}-controlled-correction-handoff.json`,review:`${prefix}-controlled-correction.md`,
21
+ receipt:`${prefix}-controlled-correction-receipt.json`};
22
+ }
23
+ // Deterministic from the journaled authorization, so a crash between the
24
+ // journal append and the marker write is repaired with the identical bytes.
25
+ export function continuationMarkerBytes({feature,task,repositoryId,runId,fromDigest,at}){
26
+ return Buffer.from(JSON.stringify({version:1,protocol:REVIEW_CONTINUATION_MARKER_PROTOCOL,feature,task,repositoryId,runId,fromDigest,at},null,2)+'\n');
27
+ }
28
+ // At most one continuation per task, across runs: this run's marker, a peer
29
+ // run's marker, any human or controlled correction, live or archived, refuses.
30
+ export function continuationUsedElsewhere(reviewsDir,feature,task){
31
+ const p=continuationPaths(reviewsDir,feature,task),prefix=`${feature}-${task}-`;
32
+ const live=[p.marker,p.record,p.handoff,p.review,p.receipt,
33
+ ...['','-handoff','-receipt'].map(suffix=>path.join(reviewsDir,`${prefix}human-correction${suffix}.json`)),
34
+ path.join(reviewsDir,`${prefix}human-correction.md`)];
35
+ if(live.some(present))return true;
36
+ const archive=path.join(reviewsDir,'.superseded');
37
+ let names=[];try{names=fs.readdirSync(archive);}catch(error){if(error.code!=='ENOENT')throw error;}
38
+ return names.some(name=>name.startsWith(`${prefix}review-continuation.json.`)||name.startsWith(`${prefix}controlled-correction`)
39
+ ||name.startsWith(`${prefix}human-correction`));
40
+ }
41
+ export function writeContinuationMarker(reviewsDir,feature,task,bytes,{inspectOnly=false,exclusive=false}={}){
42
+ try{return writeImmutableWorkflowFile({reviewsDir,name:path.basename(continuationPaths(reviewsDir,feature,task).marker),bytes,inspectOnly,exclusive});}
43
+ catch(error){if(exclusive&&error.code==='review_file_conflict')need(false,'review_continuation_used');throw error;}
44
+ }
45
+ // The gate's controlled correction keeps the reviewed file set and needs a real
46
+ // revision. Checked at delivery, before any record exists, so the developer can
47
+ // still redo; null when the correction handoff satisfies both.
48
+ export function continuationDeliveryProblem({reviewedHandoff,correctionHandoff,task}){
49
+ const reviewed=loadHandoff(reviewedHandoff,{task}),next=loadHandoff(correctionHandoff,{task});
50
+ const before=new Set(reviewed.changed_files),after=new Set(next.changed_files);
51
+ const missing=[...before].filter(file=>!after.has(file)).sort(),extra=[...after].filter(file=>!before.has(file)).sort();
52
+ if(missing.length||extra.length)return {code:'develop_continuation_scope_mismatch',
53
+ paths:[...missing.map(file=>`-${file}`),...extra.map(file=>`+${file}`)]};
54
+ if(next.implementation_sha256===reviewed.implementation_sha256)return {code:'develop_unchanged_after_review',paths:[]};
55
+ return null;
56
+ }
57
+ // Idempotent: an existing record must still bind this handoff (checkN4 with the
58
+ // correction); otherwise the one controlled correction record is prepared.
59
+ export function prepareContinuationCorrection({reviewsDir,feature,task,projectRoot,reason,allowSymlinks=false}){
60
+ const p=continuationPaths(reviewsDir,feature,task),selectors={reviewsDir,feature,task,projectRoot,runnerOwned:true,allowSymlinks};
61
+ healAtomicTempLinks(reviewsDir,[p.handoff,p.record,p.receipt]);
62
+ if(present(p.record))return checkN4({...selectors,handoff:p.handoff,correction:p.record});
63
+ return prepareControlledCorrection({...selectors,handoff:p.handoff,decisionSource:'operator',reason});
64
+ }
65
+ const reviewerSource=provider=>`${provider}-cli`;
66
+ // Projection of the runner's registered continuation receipt into the strict
67
+ // controlled-correction review and its sealed receipt. Approved maps to zero
68
+ // active findings; any other verdict seals a blocked review that cannot complete.
69
+ export function publishContinuationReview({reviewsDir,feature,projectRoot,reviewPackage,receipt,registered,at,inspectOnly=false,allowSymlinks=false}){
70
+ id(feature);
71
+ const pkg=readReviewPackage(reviewPackage),r=receipt;
72
+ need(r&&registered&&digest(r)===digest(registered),'unregistered_review');
73
+ const {receiptDigest,...body}=r;
74
+ need(receiptDigest===digest(body)&&r.packageDigest===pkg.packageDigest&&digest(r.identity)===digest(pkg.identity)
75
+ &&pkg.identity.attempt===2,'review_package_mismatch');
76
+ need(['host-review','host-authorized'].includes(r.execution.channel)&&r.execution.started===true
77
+ &&r.execution.terminal==='succeeded'&&['codex','claude'].includes(r.execution.provider),'execution_mismatch');
78
+ const result=reviewResult(r.result,pkg);need(r.execution.resultDigest===digest(result),'execution_mismatch');
79
+ need(Number.isSafeInteger(at)&&at>=0,'clock_invalid');
80
+ const p=continuationPaths(reviewsDir,feature,pkg.identity.taskId);
81
+ need(pkg.handoff?.path===path.basename(p.handoff),'unsupported_path');
82
+ const correctionDigest=sha(fs.readFileSync(p.record));
83
+ const approved=result.verdict==='approved';
84
+ const active=approved?[]:result.findings.filter(f=>f.severity!=='P3').map(f=>({id:f.id,priority:f.severity,
85
+ evidence:`${f.path}: ${f.message} — ${f.evidence}`}));
86
+ // A blocked verdict may cite missing material rather than a code finding.
87
+ if(!approved&&!active.length)active.push({id:'review-not-approved',priority:'P1',evidence:result.summary});
88
+ const reviewBytes=Buffer.from(['---',`at: ${new Date(at).toISOString()}`,`reviewer: ${reviewerSource(r.execution.provider)}`,
89
+ 'independent: true',`task: ${pkg.identity.taskId}`,'attempt: 2','round: 2',`verdict: ${approved?'approved':'blocked'}`,
90
+ `blocking_findings: ${active.length}`,`handoff: ${pkg.handoff.path}`,`handoff_sha256: ${pkg.handoff.sha256}`,
91
+ `correction_sha256: ${correctionDigest}`,'scope:',...pkg.changes.map(c=>` - ${c.path}`),'---',
92
+ JSON.stringify({conclusion:approved?'Zero findings.':'Blocking findings.',findings:active,resolved_findings:[]}),''].join('\n'));
93
+ need(reviewBytes.length<=256*1024,'limit_exceeded');
94
+ if(!inspectOnly)healAtomicTempLinks(reviewsDir,[p.handoff,p.record,p.receipt]);
95
+ writeImmutableWorkflowFile({reviewsDir,name:path.basename(p.review),bytes:reviewBytes,inspectOnly});
96
+ const receiptBytes=Buffer.from(JSON.stringify({version:2,protocol:'cm-controlled-correction-review',correction_sha256:correctionDigest,
97
+ review_sha256:sha(reviewBytes),verdict:approved?'approved':'blocked'},null,2)+'\n');
98
+ if(!inspectOnly&&!present(p.receipt))publishControlledCorrectionReview({reviewsDir,feature,task:pkg.identity.taskId,
99
+ projectRoot,correction:p.record,handoff:p.handoff,runnerOwned:true,allowSymlinks});
100
+ need(fs.readFileSync(p.receipt).equals(receiptBytes),'review_file_conflict');
101
+ return {outcome:'published',path:p.review};
102
+ }
@@ -22,6 +22,17 @@ export function writeImmutableWorkflowFile({reviewsDir,name,bytes,validate=()=>{
22
22
  need(fs.readFileSync(target).equals(bytes),'review_file_conflict');validate(target);
23
23
  };
24
24
  if(inspectOnly){verify();return {outcome:'published',path:target};}
25
+ // A crash between linking the target and unlinking its own temp leaves the
26
+ // target with a second link. Only that exact temp (same inode, our prefix) is
27
+ // removed; anything else keeps refusing as a conflict.
28
+ try{
29
+ const stat=fs.lstatSync(target);
30
+ if(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===2)for(const name of fs.readdirSync(reviewsDir)){
31
+ if(!/^\.cm-review-[0-9a-f-]{36}$/.test(name))continue;
32
+ const peer=fs.lstatSync(path.join(reviewsDir,name));
33
+ if(peer.isFile()&&peer.dev===stat.dev&&peer.ino===stat.ino){fs.unlinkSync(path.join(reviewsDir,name));break;}
34
+ }
35
+ }catch(error){if(error.code!=='ENOENT')throw error;}
25
36
  const temp=path.join(reviewsDir,`.cm-review-${randomUUID()}`);let fd;
26
37
  try{
27
38
  fd=fs.openSync(temp,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL,0o600);
@@ -443,14 +443,15 @@ export function captureReviewInventory(root,baseline,{withMode=false}={}){
443
443
  // file record. The default keeps the historical content-only comparison.
444
444
  // probe: one path also reported from this same scan, changed or not, flagged
445
445
  // probe:true (sha256 null when the current inventory does not contain it).
446
- export function compareReviewInventoryToBaseline(root,baseline,{withMode=false,probe=null}={}){
446
+ export function compareReviewInventoryToBaseline(root,baseline,{withMode=false,probe=null,protectScope=false}={}){
447
447
  validBaseline(baseline);
448
448
  const stable=baseline.ignorePolicy?.version===2;
449
449
  const policy=stable?stableSnapshotPolicy(root,baseline.ignorePolicy)
450
450
  :Object.hasOwn(baseline,'ignorePolicy')?ignorePolicy(root):null;
451
- const before=stable?comparableFiles(baseline.files,policy,new Set([...baseline.scope,...baseline.requirements])):baseline.files;
451
+ const protectedPaths=new Set([...baseline.scope,...baseline.requirements]);
452
+ const before=stable?comparableFiles(baseline.files,policy,protectedPaths):baseline.files;
452
453
  const after=snapshot(root,baseline.specsPath??null,baseline.codeProjectPaths??null,
453
- stable?[]:baseline.files.map(file=>file.path),new Set(),policy,false,baseline.version===SYMLINK_BASELINE_VERSION);
454
+ stable?[]:baseline.files.map(file=>file.path),protectScope?protectedPaths:new Set(),policy,false,baseline.version===SYMLINK_BASELINE_VERSION);
454
455
  const key=file=>withMode?`${file.sha256}:${file.mode??null}`:file.sha256;
455
456
  const previous=new Map(before.map(file=>[file.path,key(file)]));
456
457
  const current=new Map(after.map(file=>[file.path,key(file)]));
@@ -484,6 +485,18 @@ const sealed = (data,key) => {
484
485
  need(Buffer.byteLength(JSON.stringify(result))<=8*1024*1024,'limit_exceeded');
485
486
  return freeze(result);
486
487
  };
488
+ // The path rules captureReviewBaseline applies to one selection list before it
489
+ // reads anything (shape, case-insensitive duplicates, dependency/Pods trees, specs
490
+ // files inside the project). Reads no file content, so a caller can refuse a
491
+ // configuration at creation that a later baseline would certainly reject.
492
+ export function checkReviewSelection({root,specsRoot=null,files}){
493
+ const selected=paths(files),real=rootPath(root);
494
+ need(!selected.some(p=>inDependencyDirectory(p)||inCocoaPodsTree(real,p)),'excluded_snapshot_path');
495
+ // Specs outside the project (the usual layout) have no in-project path to protect.
496
+ const specsPath=specsRoot===null?null:reviewSpecsPath(real,specsRoot);
497
+ if(specsPath!==null)validateSpecsSelection(specsPath,selected);
498
+ return selected;
499
+ }
487
500
  export function captureReviewBaseline(options,legacy=false,policyVersion=2,baselinePolicy=null,acceptance=true) {
488
501
  const v=plain(options); keys(v,['root','identity','scope','requirements',
489
502
  ...['specsRoot','codeProjectPaths','bootstrapRequirements','specification','version','scopeRevisionPaths'].filter(key=>Object.hasOwn(v,key))]); identityCheck(v.identity);
@@ -800,6 +813,14 @@ function packageSnapshot(root,b,policy){
800
813
  ...b.files.filter(f=>Object.hasOwn(f,'contentBase64')).map(f=>f.path)]);
801
814
  return snapshot(root,b.specsPath??null,b.codeProjectPaths??null,b.ignorePolicy?.version===2?[]:b.files.map(f=>f.path),selected,policy,false,b.version===SYMLINK_BASELINE_VERSION);
802
815
  }
816
+ // Read-only: the identity (path, type, mode, content or link target) of every
817
+ // file a package built from the current tree would hold, from the very same
818
+ // selection, so callers can tell whether that package's files changed.
819
+ export function reviewPackageFileIdentities(options){
820
+ const v=plain(options);keys(v,['root','baseline']);const b=v.baseline;validBaseline(b);
821
+ const root=rootPath(v.root);need(sha(root)===b.rootDigest,'invalid_baseline');
822
+ return freeze(packageSnapshot(root,b,packagePolicy(root,b)).map(({contentBase64,size,...identity})=>identity));
823
+ }
803
824
  // Read-only: path and size of every material body a package built from the
804
825
  // current tree would carry. Callers use it to refuse a delivery before writing it.
805
826
  export function reviewMaterialSizes(options){
@@ -1089,4 +1110,4 @@ export function readReviewPackage(raw) {
1089
1110
  // Reuse the same bounded scanner and two-sided stable policy for compatibility
1090
1111
  // inventories; the default snapshot mode above is unchanged for JS callers.
1091
1112
  export {snapshot,rootPath,stableIgnorePolicy,stablePublicPolicy,stableSnapshotPolicy,
1092
- comparableFiles,validateStablePolicy,filePath,INVENTORY_COUNT,INVENTORY_LIMIT};
1113
+ comparableFiles,validateStablePolicy,filePath,readHandoffSnapshot,INVENTORY_COUNT,INVENTORY_LIMIT};
@@ -1,13 +1,14 @@
1
1
  // Lossless presentation inside the same no-tools prompt. Canonical evidence stays unchanged.
2
2
  import {createHash} from 'node:crypto';
3
3
  import {json,need,shape,hex,digest,validIdentity,JOURNAL_PAYLOAD_LIMIT} from './effect-contract.mjs';
4
- import {readReviewPackage} from './review-package.mjs';
4
+ import {readReviewBaseline,readReviewPackage} from './review-package.mjs';
5
+ import {storeStateKeys} from '../executor-version.mjs';
5
6
  export function compactReviewData(raw){
6
7
  const input=json(raw,10*1024*1024);
7
8
  need(!Object.hasOwn(input,'presentation')&&!Object.hasOwn(input,'contents')&&input.reviewPackage?.packageDigest,'review_presentation_invalid');
8
9
  return compactInlineContent(input,input.reviewPackage.packageDigest);
9
10
  }
10
- function compactInlineContent(input,packageDigest,selected=null){
11
+ function compactInlineContent(input,packageDigest,selected=null,preferSmallerEncoding=false){
11
12
  const contents={},keys=new Map();
12
13
  const visit=(value,route=[])=>{
13
14
  if(Array.isArray(value))return value.map((item,i)=>visit(item,[...route,String(i)]));
@@ -26,7 +27,10 @@ function compactInlineContent(input,packageDigest,selected=null){
26
27
  ref='content-'+(keys.size+1);keys.set(key,ref);
27
28
  let text;try{text=new TextDecoder('utf8',{fatal:true}).decode(bytes);}catch{}
28
29
  // Byte-exact decoding: BOM or invalid UTF-8 retains the original base64.
29
- const utf8=text!==undefined&&Buffer.from(text,'utf8').equals(bytes);
30
+ // Existing review packages must keep their canonical representation on replay.
31
+ // For new baseline records, include JSON escaping in the storage cost.
32
+ const utf8=text!==undefined&&Buffer.from(text,'utf8').equals(bytes)
33
+ &&(!preferSmallerEncoding||sizeOf(['utf8',text])<=sizeOf(['base64',value.contentBase64]));
30
34
  contents[ref]={sha256:hash,size:bytes.length,encoding:utf8?'utf8':'base64',content:utf8?text:value.contentBase64};
31
35
  }
32
36
  delete out.contentBase64;out.contentRef=ref;return out;
@@ -68,7 +72,22 @@ export function fixJournalWorkflow(state){
68
72
  const inPackage=(route,paths)=>paths.some(p=>route.length>=p.length&&p.every((part,i)=>route[i]===part));
69
73
  // These are the actual durable fix-owner payload forms. This is not an arbitrary
70
74
  // recursive search for a token package hidden inside unrelated application data.
71
- function packageLocations(value,{validate=true}={}){
75
+ function storageMaterial(value,{validate=true}={}){
76
+ // The first test-author intent is a bare baseline. Its revision and both
77
+ // repair intents wrap it with digests binding the owner's earlier evidence.
78
+ if(value?.kind==='cm-review-baseline'||value?.baseline?.kind==='cm-review-baseline'){
79
+ const wrapped=Object.hasOwn(value,'baseline');
80
+ const baseline=wrapped?value.baseline:value;
81
+ if(wrapped){
82
+ const bindings=Object.hasOwn(value,'redDigest')?['redDigest','testBaselineDigest']:[];
83
+ if(Object.hasOwn(value,'revisionDigest'))bindings.push('revisionDigest');
84
+ need(bindings.length>0,storageCode);
85
+ shape(value,['baseline',...bindings]);
86
+ bindings.forEach(key=>hex(value[key]));
87
+ }
88
+ if(validate)readReviewBaseline(baseline);
89
+ return {paths:[wrapped?['baseline','files']:['files']],anchorDigest:baseline.baselineDigest,preferSmallerEncoding:true};
90
+ }
72
91
  need(object(value),storageCode);let locations;
73
92
  if(value.kind==='cm-review-package')locations=[[]];
74
93
  else if(Object.hasOwn(value,'writeback')&&Object.hasOwn(value,'reviewPackage')){
@@ -100,17 +119,15 @@ function packageLocations(value,{validate=true}={}){
100
119
  const identity=value.request?.identity??value.writeback?.identity;
101
120
  if(identity)need(packages.every(pkg=>digest(pkg.identity)===digest(identity)),storageCode);
102
121
  }
103
- return {paths:locations,packages};
122
+ return {paths:locations,anchorDigest:packages[0].packageDigest};
104
123
  }
105
124
  export function packFixJournalPayload(raw,{workflow}={}){
106
125
  const value=json(raw,INPUT_LIMIT),logicalBytes=sizeOf(value);
107
- // 只有 cm-fix 的审查载荷在超过 1 MiB 时压缩;其他运行原样存,大小由存储层的记录上限
126
+ // 只有 cm-fix 的审查包及冻结基线在超过 1 MiB 时压缩;其他运行原样存,大小由存储层的记录上限
108
127
  // (JOURNAL_PAYLOAD_LIMIT)把关——这里再按 1 MiB 拒绝,会让放大后的记录上限形同虚设
109
128
  if(logicalBytes<=PAYLOAD_LIMIT||workflow!==FIX_WORKFLOW){need(logicalBytes<=JOURNAL_PAYLOAD_LIMIT,'limit_exceeded');return value;}
110
- const {paths,packages}=packageLocations(value);
111
- // No duplicated anchor package in the temporary input: the canonical package
112
- // already inside payload supplies the presentation digest to the same visitor.
113
- const data=compactInlineContent({payload:value},packages[0].packageDigest,paths.map(p=>['payload',...p]));
129
+ const {paths,anchorDigest,preferSmallerEncoding}=storageMaterial(value);
130
+ const data=compactInlineContent({payload:value},anchorDigest,paths.map(p=>['payload',...p]),preferSmallerEncoding);
114
131
  const packed={version:1,kind:PAYLOAD_KIND,logicalBytes,logicalDigest:digest(value),data};
115
132
  return json(packed,PAYLOAD_LIMIT);
116
133
  }
@@ -124,7 +141,7 @@ function payloadPlan(raw,{workflow}={}){
124
141
  shape(data.presentation,['version','kind','packageDigest']);
125
142
  need(data.presentation.version===1&&data.presentation.kind==='complete-inline-content-table',storageCode);hex(data.presentation.packageDigest);
126
143
  need(object(data.contents),storageCode);
127
- const {paths}=packageLocations(data.payload,{validate:false});
144
+ const {paths}=storageMaterial(data.payload,{validate:false});
128
145
  const names=Object.keys(data.contents),lengths=new Map(),used=new Set();
129
146
  for(const [index,name] of names.entries()){
130
147
  need(name==='content-'+(index+1),storageCode);
@@ -170,9 +187,9 @@ export function unpackFixJournalPayload(raw,{workflow}={}){
170
187
  }
171
188
  return out;
172
189
  };
173
- const payload=json(visit(value.data.payload),INPUT_LIMIT),{packages}=packageLocations(payload);
190
+ const payload=json(visit(value.data.payload),INPUT_LIMIT),{anchorDigest}=storageMaterial(payload);
174
191
  need(sizeOf(payload)===value.logicalBytes&&digest(payload)===value.logicalDigest
175
- &&packages[0].packageDigest===value.data.presentation.packageDigest,storageCode);
192
+ &&anchorDigest===value.data.presentation.packageDigest,storageCode);
176
193
  // Exact fixed point rejects alternate encodings, extra tables and collisions.
177
194
  need(sameBytes(packFixJournalPayload(payload,{workflow}),value),storageCode);return payload;
178
195
  }
@@ -197,7 +214,7 @@ export function unpackFixJournalState(raw){
197
214
  physical.records.forEach(record=>json(record.payload,limit));
198
215
  return physical;
199
216
  }
200
- shape(physical,['version','identity','fingerprints','records','revision','storageEncoding']);
217
+ shape(physical,storeStateKeys(physical,['storageEncoding']));
201
218
  const workflow=fixJournalWorkflow(physical);need(workflow===FIX_WORKFLOW,storageCode);
202
219
  const marker=physical.storageEncoding;shape(marker,['version','kind','records']);
203
220
  need(marker.version===1&&marker.kind===STORAGE_KIND&&Array.isArray(physical.records)
@@ -9,10 +9,10 @@ export function reviewPaths(pkg) {
9
9
  export function allowedFindingPaths(pkg,paths=reviewPaths(pkg)) {
10
10
  return [...paths,pkg.handoff?.path].filter(Boolean);
11
11
  }
12
- export function reviewResult(raw,pkg) {
13
- return reviewResultForPaths(raw,pkg,reviewPaths(pkg));
12
+ export function reviewResult(raw,pkg,options={}) {
13
+ return reviewResultForPaths(raw,pkg,reviewPaths(pkg),options);
14
14
  }
15
- export function reviewResultForPaths(raw,pkg,paths) {
15
+ export function reviewResultForPaths(raw,pkg,paths,{strictBlocked=false}={}) {
16
16
  const r=json(raw);shape(r,['verdict','packageDigest','examinedPaths','findings','summary']);
17
17
  need(['approved','changes_requested','blocked'].includes(r.verdict));text(r.summary);
18
18
  need(r.packageDigest===pkg.packageDigest,'review_package_mismatch');
@@ -32,7 +32,8 @@ export function reviewResultForPaths(raw,pkg,paths) {
32
32
  }
33
33
  const blocking=r.findings.filter(f=>f.severity!=='P3').length;
34
34
  need(r.verdict!=='approved'||blocking===0,'contradictory_verdict');
35
- need(r.verdict!=='changes_requested'||blocking>0,'contradictory_verdict');return r;
35
+ need(r.verdict!=='changes_requested'||blocking>0,'contradictory_verdict');
36
+ need(!strictBlocked||r.verdict!=='blocked'||r.findings.length===0||blocking>0,'contradictory_verdict');return r;
36
37
  }
37
38
  // A reviewer result is journaled many times (see developCheckpointReserve), so its
38
39
  // text is bounded before any record is written. Rule, applied only when the result
@@ -0,0 +1,7 @@
1
+ // The reviewer's verdict rules: one source for the review prompt and the
2
+ // developer's self-review (a leaf module, so no import cycle can leave it unset).
3
+ export const VERDICT_RULES=`Verdict rules; a reply that breaks them cannot authorize completion:
4
+ - Severity: P0 = security hole, data loss, or crash or wrong result on a main path; P1 = incorrect behaviour or an unmet acceptance criterion a user will hit; P2 = a real defect in an edge case, error handling, contract or test with a concrete reachable input/state and wrong outcome that must be fixed before merge; P3 = optional improvement, naming/wording/doc polish, style preference, or theoretical concern without a concrete reachable failure path (must not block).
5
+ - Every P0, P1 and P2 finding must cite a concrete reachable input/state and the wrong outcome it causes; never use P2 for out-of-scope redesign, wording nits, or speculative edge cases.
6
+ - approved requires zero P0, P1 and P2 findings; P3 notes are allowed with approved.
7
+ - changes_requested requires at least one P0, P1 or P2 finding; never use it for P3-only notes.`;
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {createHash} from 'node:crypto';
6
6
  import {spawnSync} from 'node:child_process';
7
+ import {spawnPythonLogWriter} from '../python-log-writer.mjs';
7
8
  import {fileURLToPath} from 'node:url';
8
9
  import {readExecutionSnapshot} from './execution-snapshot.mjs';
9
10
  import {openExecutionStore} from './execution-store.mjs';
@@ -293,6 +294,24 @@ export function archiveReviewedEvidence(reviewsDir,raw){
293
294
  return record;
294
295
  }
295
296
 
297
+ // Diagnostic only: how the superseded runs ended, counted by cause (review limit,
298
+ // blocked checks, QA BLOCKED) instead of read from the free-text reason.
299
+ // Read-only snapshots; an unreadable run counts as such. At most 16 causes.
300
+ function predecessorCauses(specsDir,identity,taskId,runIds){
301
+ const causes={};
302
+ for(const runId of runIds){
303
+ let cause='unreadable';
304
+ try{
305
+ const snapshot=readExecutionSnapshot({specsRoot:specsDir,identity:{repositoryId:identity.repositoryId,runId}});
306
+ const first=snapshot.records[0]?.payload,{state}=readRunnerHistory(snapshot.records,first.config,first.version);
307
+ cause=state.state==='fixture_completed'?`qa/${qaTerminal(specsDir,runId,taskId)}`:[state.state,state.code].filter(Boolean).join('/');
308
+ }catch{}
309
+ cause=String(cause).replace(/[^A-Za-z0-9_./-]/g,'_').slice(0,64);
310
+ if(Object.hasOwn(causes,cause)||Object.keys(causes).length<16)causes[cause]=(causes[cause]??0)+1;
311
+ else causes.other=(causes.other??0)+1;
312
+ }
313
+ return causes;
314
+ }
296
315
  export function recordEvidenceSupersession({specsDir,codeProject,identity,record,logHome}){
297
316
  const data={node:'N3',feature:record.feature,task:record.taskId,
298
317
  previous_run_count:record.previousRunIds.length,file_count:record.files.length,
@@ -300,7 +319,17 @@ export function recordEvidenceSupersession({specsDir,codeProject,identity,record
300
319
  const args=[writer,'--workflow','cm-ai','--event','supersede','--runtime','codex',
301
320
  '--project-root',codeProject,'--specs-dir',specsDir,'--run-id',identity.runId,
302
321
  '--at',record.authorizedAt,'--detail','显式归档旧任务证据','--data-json',JSON.stringify(data)];
303
- const result=spawnSync('python3',args,{timeout:10000,maxBuffer:1024*1024,
322
+ // Same interpreter choice as the diagnostic row below (only-`python` platforms).
323
+ const result=spawnPythonLogWriter(args,{timeout:10000,maxBuffer:1024*1024,
304
324
  ...(logHome?{env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}}:{})});
305
325
  need(!result.error&&result.status===0,'supersede_log_failed');
326
+ // Separate, best-effort diagnostic row: the restart event above keeps its exact
327
+ // historical content (and event id), and a failure here never fails the restart.
328
+ try{
329
+ spawnPythonLogWriter([writer,'--workflow','cm-ai','--event','supersede_cause','--runtime','codex',
330
+ '--project-root',codeProject,'--specs-dir',specsDir,'--run-id',identity.runId,'--at',record.authorizedAt,
331
+ '--detail','重开前旧运行的结束原因','--data-json',JSON.stringify({diagnostic:true,feature:record.feature,task:record.taskId,
332
+ record_digest:data.record_digest,causes:predecessorCauses(specsDir,identity,record.taskId,record.previousRunIds)})],
333
+ {timeout:10000,maxBuffer:1024*1024,...(logHome?{env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}}:{})});
334
+ }catch{/* diagnostics never change the restart */}
306
335
  }
@@ -18,10 +18,20 @@ export function planBytes(raw){
18
18
  validIdentity({repositoryId:'plan',runId:'plan',taskId:p.taskId,attempt:p.attempt});absolute(p.tasksPath);
19
19
  need(Number.isInteger(p.mode)&&p.mode>=0&&p.mode<=0o7777,'invalid_plan');
20
20
  for(const k of ['beforeDigest','afterDigest','taskRevision','planDigest'])hex(p[k]);
21
- need(Array.isArray(p.evidence)&&p.evidence.length>0&&p.evidence.length<=4,'invalid_plan');
21
+ // The gate pins at most 4 files, or 8 for a correction continuation (cm-task-gate
22
+ // prepareMarkDone); a third controlled review completes through the latter.
23
+ need(Array.isArray(p.evidence)&&p.evidence.length>0&&p.evidence.length<=8,'invalid_plan');
22
24
  let previous;
23
25
  for(const e of p.evidence){shape(e,['path','revision']);absolute(e.path);hex(e.revision);
24
26
  need(previous===undefined||Buffer.compare(Buffer.from(previous),Buffer.from(e.path))<0,'invalid_plan');previous=e.path;}
27
+ // More than the ordinary four only for a controlled-correction completion, and
28
+ // then exactly its eight files: both original rounds plus the correction set.
29
+ if(p.evidence.length>4){
30
+ const names=['-a1-handoff.json','-r1.md','-a2-handoff.json','-r2.md','-controlled-correction.json',
31
+ '-controlled-correction-handoff.json','-controlled-correction.md','-controlled-correction-receipt.json']
32
+ .map(suffix=>`${p.feature}-${p.taskId}${suffix}`).sort();
33
+ need(p.attempt===2&&p.evidence.length===8&&digest(p.evidence.map(e=>path.basename(e.path)).sort())===digest(names),'invalid_plan');
34
+ }
25
35
  const {planDigest,...body}=p;need(digest(body)===planDigest,'invalid_plan');
26
36
  const before=base64(p.beforeBase64),after=base64(p.afterBase64);
27
37
  need(sha(before)===p.beforeDigest&&sha(after)===p.afterDigest,'invalid_plan');
@@ -64,7 +64,9 @@ function readFile(p) {
64
64
  }
65
65
  function nativeRevision(p,f) {return digest({path:p,stat:statFields(f.stat),sha256:sha(f.bytes)});}
66
66
  function completionSelectors(selectors,identity,projectRoot,baseline){
67
- return {...selectors,task:identity.taskId,projectRoot,allowSymlinks:baseline.version===SYMLINK_BASELINE_VERSION};
67
+ // A correction selector exists only for a run's own third controlled review.
68
+ return {...selectors,task:identity.taskId,projectRoot,allowSymlinks:baseline.version===SYMLINK_BASELINE_VERSION,
69
+ ...(Object.hasOwn(selectors,'correction')?{runnerOwned:true}:{})};
68
70
  }
69
71
  function verifyProof(v) {
70
72
  verifyCompletionReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,reviewPackage:v.reviewPackage,expectedDigest:v.reviewPackage.packageDigest,
@@ -120,13 +122,14 @@ export function commitRunnerFixture(token,store,input,signal) {
120
122
  function commitCore(input,signal,owner,initial,guard,appendIntent,appendResult) {
121
123
  cancellation(signal);const v=json(input,16*MiB);
122
124
  shape(v,['selectors','root','identity','baseline','reviewPackage','checks','receipt','registered','execution']);
123
- shape(v.selectors,['handoff','reviewsDir','tasksPath','feature']);validIdentity(v.identity);
125
+ shape(v.selectors,['handoff','reviewsDir','tasksPath','feature',...(Object.hasOwn(v.selectors??{},'correction')?['correction']:[])]);validIdentity(v.identity);
124
126
  need(equal(initial.identity,{repositoryId:v.identity.repositoryId,runId:v.identity.runId}),'identity_mismatch');
125
127
  const selectors=v.selectors;
126
128
  need(selectors.tasksPath===owner.tasksPath && selectors.feature===owner.feature,'task_owner_mismatch');
127
- for(const p of [v.root,selectors.tasksPath,selectors.reviewsDir,selectors.handoff])canonicalPath(p);
129
+ for(const p of [v.root,selectors.tasksPath,selectors.reviewsDir,selectors.handoff,...(selectors.correction?[selectors.correction]:[])])canonicalPath(p);
128
130
  need([path.join(owner.specsRoot,'.reviews'),path.join(path.dirname(owner.tasksPath),'.reviews')].includes(selectors.reviewsDir)
129
- && path.dirname(selectors.handoff)===selectors.reviewsDir,'unsupported_path');
131
+ && path.dirname(selectors.handoff)===selectors.reviewsDir
132
+ && (!Object.hasOwn(selectors,'correction')||path.dirname(selectors.correction)===selectors.reviewsDir),'unsupported_path');
130
133
  need((v.baseline.specsPath??null)===reviewSpecsPath(v.root,owner.specsRoot),'overlapping_roots');
131
134
  const parent=parentRevision(path.dirname(owner.tasksPath));
132
135
  let plan;
@@ -2,7 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { need,shape,id,hex,json } from './effect-contract.mjs';
5
- import { openExecutionStore } from './execution-store.mjs';
5
+ import { openExecutionStore,assertExecutorMayOpen } from './execution-store.mjs';
6
6
  import { isSupportedExecutionPlatform } from './execution-platform.mjs';
7
7
 
8
8
  const same=(a,b)=>a.dev===b.dev && a.ino===b.ino;
@@ -67,7 +67,10 @@ function bind(v) {
67
67
  return {p,stat,bytes};
68
68
  }
69
69
  export function openTaskExecutionStore(input) {
70
- const v=validate(input),binding=bind(v),{tasksPath,feature,...options}=v;
70
+ const v=validate(input);
71
+ // Before the owner binding below is written.
72
+ assertExecutorMayOpen({specsRoot:v.specsRoot,identity:v.identity,create:v.create});
73
+ const binding=bind(v),{tasksPath,feature,...options}=v;
71
74
  const execution=path.join(v.specsRoot,'.reviews','.execution');
72
75
  try {
73
76
  directory(execution);