@aibyzero/cm-workflow 0.16.4 → 0.16.6

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 (283) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +22 -0
  3. package/CHANGELOG.md +57 -0
  4. package/README.md +22 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +48 -7
  17. package/docs/js-workflow-control.md +293 -33
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/runtime-failover.md +1 -1
  21. package/docs/untested-branches.md +27 -4
  22. package/docs/user-guide.md +23 -8
  23. package/install-codex.sh +28 -11
  24. package/package.json +1 -1
  25. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  26. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  27. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  28. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  29. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  30. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  31. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  32. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
  33. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  34. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  35. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
  36. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
  37. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  38. package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
  39. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  40. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  41. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  42. package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
  43. package/runtime/js/cm-ai/drive-core.mjs +47 -9
  44. package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
  45. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  46. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  47. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  48. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  49. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  50. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  51. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  52. package/runtime/js/cm-ai/external-models.mjs +52 -0
  53. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  54. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  55. package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
  56. package/runtime/js/cm-ai/host-check.mjs +30 -4
  57. package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
  58. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  59. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  60. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  61. package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
  62. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
  63. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  64. package/runtime/js/cm-ai/host-session.mjs +12 -4
  65. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  66. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
  67. package/runtime/js/cm-ai/host.mjs +1 -1
  68. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  69. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  70. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  71. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  72. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  73. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  74. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  75. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  76. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  77. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  78. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  79. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  80. package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
  81. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  82. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  83. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  84. package/runtime/js/cm-ai/review-package.mjs +438 -31
  85. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  86. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  87. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  88. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  89. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  90. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  91. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  92. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  93. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  94. package/runtime/js/cm-ai/task-runner.mjs +658 -75
  95. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  96. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  97. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  98. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  99. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  100. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  101. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  102. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  103. package/runtime/js/cm-fix/execution.mjs +279 -52
  104. package/runtime/js/cm-fix/final-review.mjs +18 -10
  105. package/runtime/js/cm-fix/host-review.mjs +32 -9
  106. package/runtime/js/cm-fix/host.mjs +6 -1
  107. package/runtime/js/cm-fix/layout.mjs +1 -1
  108. package/runtime/js/cm-fix/progress.mjs +5 -0
  109. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  110. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  111. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  112. package/runtime/js/cm-prd/analysis.mjs +2 -1
  113. package/runtime/js/cm-prd/change.mjs +28 -10
  114. package/runtime/js/cm-prd/draft.mjs +5 -2
  115. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  116. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  117. package/runtime/js/cm-prd/review-publication.mjs +27 -15
  118. package/runtime/js/cm-prd/review-time.mjs +29 -0
  119. package/runtime/js/cm-prd/self-check.mjs +6 -3
  120. package/runtime/js/cm-prd/session.mjs +53 -6
  121. package/runtime/js/cm-prd/summary.mjs +3 -1
  122. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  123. package/runtime/js/cm-security/finalize.mjs +32 -0
  124. package/runtime/js/spec-task-line.mjs +117 -0
  125. package/runtime/js/specs-status.mjs +10 -3
  126. package/runtime/review.md +5 -0
  127. package/runtime/task-gates.md +6 -0
  128. package/runtime/workflow-config.md +10 -1
  129. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  130. package/scripts/cm-ai-admission.mjs +18 -11
  131. package/scripts/cm-ai-admission.test.mjs +65 -1
  132. package/scripts/cm-ai-batch-drive.mjs +135 -34
  133. package/scripts/cm-ai-batch-drive.test.mjs +209 -3
  134. package/scripts/cm-ai-batch-host.mjs +63 -24
  135. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  136. package/scripts/cm-ai-batch-run.mjs +101 -34
  137. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  138. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  139. package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
  140. package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
  141. package/scripts/cm-ai-bootstrap.test.mjs +174 -89
  142. package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
  143. package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
  144. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  145. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  146. package/scripts/cm-ai-drive.mjs +526 -60
  147. package/scripts/cm-ai-drive.test.mjs +336 -10
  148. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  149. package/scripts/cm-ai-host.mjs +142 -43
  150. package/scripts/cm-ai-host.test.mjs +232 -12
  151. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  152. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  153. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  154. package/scripts/cm-ai-progress.test.mjs +521 -0
  155. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  156. package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
  157. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  158. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  159. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  160. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  161. package/scripts/cm-ai-review-failure.test.mjs +977 -0
  162. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  163. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  164. package/scripts/cm-ai-run.mjs +206 -62
  165. package/scripts/cm-ai-run.test.mjs +6 -4
  166. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  167. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  168. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  169. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  170. package/scripts/cm-ai-supersede.test.mjs +571 -17
  171. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  172. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  173. package/scripts/cm-capability-gate.test.mjs +21 -2
  174. package/scripts/cm-check-drive.test.mjs +2 -1
  175. package/scripts/cm-check-host.test.mjs +1 -1
  176. package/scripts/cm-check-runtime.sh +12 -1
  177. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  178. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  179. package/scripts/cm-claude-probe.test.mjs +10 -2
  180. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  181. package/scripts/cm-claude-worker.test.mjs +11 -4
  182. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  183. package/scripts/cm-codex-plugin-metadata.py +83 -0
  184. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  185. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  186. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  187. package/scripts/cm-efficiency-offline.mjs +35 -0
  188. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  189. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  190. package/scripts/cm-efficiency-response.test.mjs +117 -0
  191. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  192. package/scripts/cm-external-batch-host.test.mjs +157 -0
  193. package/scripts/cm-external-fix-host.test.mjs +281 -0
  194. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  195. package/scripts/cm-external-group-models.test.mjs +60 -0
  196. package/scripts/cm-external-model-host.test.mjs +180 -0
  197. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  198. package/scripts/cm-external-models.test.mjs +89 -0
  199. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  200. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  201. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  202. package/scripts/cm-failover.mjs +8 -8
  203. package/scripts/cm-fix-abandon.test.mjs +123 -5
  204. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  205. package/scripts/cm-fix-drive.mjs +70 -23
  206. package/scripts/cm-fix-drive.test.mjs +36 -1
  207. package/scripts/cm-fix-final-review.test.mjs +11 -6
  208. package/scripts/cm-fix-host.mjs +24 -14
  209. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  210. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  211. package/scripts/cm-fix-review-budget.test.mjs +147 -0
  212. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  213. package/scripts/cm-host-check.test.mjs +6 -3
  214. package/scripts/cm-host-qa-executor.test.mjs +213 -17
  215. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  216. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  217. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  218. package/scripts/cm-live-evidence.test.mjs +64 -0
  219. package/scripts/cm-log-event.mjs +25 -2
  220. package/scripts/cm-log-event.py +15 -0
  221. package/scripts/cm-log-event.test.mjs +31 -0
  222. package/scripts/cm-model-setup.mjs +79 -0
  223. package/scripts/cm-prd-completion.test.mjs +75 -0
  224. package/scripts/cm-prd-draft.test.mjs +14 -0
  225. package/scripts/cm-prd-drive.mjs +32 -11
  226. package/scripts/cm-prd-drive.test.mjs +15 -0
  227. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  228. package/scripts/cm-prd-host.mjs +13 -4
  229. package/scripts/cm-prd-review-gate.mjs +126 -81
  230. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  231. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  232. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  233. package/scripts/cm-prd-self-check.test.mjs +6 -0
  234. package/scripts/cm-prd-summary.test.mjs +9 -0
  235. package/scripts/cm-release-smoke.sh +5 -1
  236. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  237. package/scripts/cm-review-inventory.test.mjs +253 -1
  238. package/scripts/cm-runtime-i18n.mjs +15 -4
  239. package/scripts/cm-runtime-install.mjs +8 -4
  240. package/scripts/cm-runtime.mjs +116 -23
  241. package/scripts/cm-runtime.test.mjs +121 -12
  242. package/scripts/cm-security.test.mjs +32 -0
  243. package/scripts/cm-spec-manifest.mjs +28 -10
  244. package/scripts/cm-spec-manifest.test.mjs +8 -4
  245. package/scripts/cm-spec-task-line.test.mjs +138 -0
  246. package/scripts/cm-specs-status.test.mjs +12 -1
  247. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  248. package/scripts/cm-task-gate.mjs +164 -20
  249. package/scripts/cm-task-gate.py +2 -1
  250. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  251. package/scripts/cm-test-drive.mjs +10 -4
  252. package/scripts/cm-test-drive.test.mjs +14 -1
  253. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  254. package/scripts/cm-usage-report.py +22 -3
  255. package/scripts/cm-workflow-config.mjs +10 -1
  256. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  257. package/scripts/fixtures/claude-review-process.mjs +1 -0
  258. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  259. package/scripts/fixtures/process-cleanup.mjs +101 -0
  260. package/scripts/test-cm-log-event.py +2 -0
  261. package/scripts/test-cm-native-usage.py +62 -0
  262. package/scripts/test-cm-prd-review-gate.py +2 -1
  263. package/scripts/test-external-model-setup.py +91 -0
  264. package/scripts/test-model-configuration-write.py +201 -0
  265. package/scripts/test-npm-install.py +11 -2
  266. package/scripts/test-scan-public-safety.py +1 -1
  267. package/scripts/test-spec-manifest.py +16 -8
  268. package/scripts/test-task-gate.py +2 -2
  269. package/scripts/test-workflow-config.py +1 -0
  270. package/scripts/validate-public-repo.py +1 -0
  271. package/skills/cm-ai/SKILL.md +2 -2
  272. package/skills/cm-ai/references/N1-init.md +1 -1
  273. package/skills/cm-ai/references/N8-finish.md +5 -0
  274. package/skills/cm-ai/references/js-host.md +270 -43
  275. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  276. package/skills/cm-fix/SKILL.md +1 -1
  277. package/skills/cm-fix/references/js-host.md +52 -3
  278. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  279. package/skills/cm-prd/references/js-host.md +6 -0
  280. package/skills/cm-runtime/SKILL.md +29 -6
  281. package/skills/cm-security/SKILL.md +4 -2
  282. package/skills/cm-security/references/scan-contract.md +1 -0
  283. package/templates/cm-workflow.yml +1 -1
@@ -0,0 +1,19 @@
1
+ // Repeating this projection on resume repairs a crash after the journal append.
2
+ import {spawnSync} from 'node:child_process';
3
+ import {fileURLToPath} from 'node:url';
4
+ import {digest,need} from './effect-contract.mjs';
5
+
6
+ const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
7
+ export function recordEffectAbandonment({specsDir,codeProject,feature,identity,record,logHome,runtime='codex'}){
8
+ const p=record.payload;
9
+ const data={node:p.effectKind==='complete'?'N5':p.effectKind==='review'?'N4':'N3',feature,task:identity.taskId,
10
+ effect_id:p.effectId,effect_kind:p.effectKind,intent_digest:p.intentDigest,
11
+ record_digest:record.digest,reason:p.reason};
12
+ const args=[writer,'--workflow','cm-ai','--event','effect_abandoned','--runtime',runtime,
13
+ '--project-root',codeProject,'--specs-dir',specsDir,'--run-id',identity.runId,
14
+ '--at',p.at,'--detail','显式放弃中断且无检查点的任务 effect','--data-json',JSON.stringify(data)];
15
+ const result=spawnSync('python3',args,{timeout:10000,maxBuffer:1024*1024,
16
+ ...(logHome?{env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}}:{})});
17
+ need(!result.error&&result.status===0,'effect_abandon_log_failed');
18
+ return digest(data);
19
+ }
@@ -4,6 +4,45 @@ export { digest };
4
4
  export const need=(ok,code='invalid_input')=>{
5
5
  if(!ok){const e=new Error(code);e.code=code;const at=raisedAt(e);if(at!==null)e.origin=at;throw e;}
6
6
  };
7
+ // One journal record payload (execution-store). Anything a record must carry,
8
+ // such as a review package inside a checkpoint, has to fit this, not only its own limits.
9
+ export const JOURNAL_PAYLOAD_LIMIT=1024*1024;
10
+ // A develop checkpoint must leave room for the later checkpoints of the same
11
+ // attempt, which carry the same package again. Their growth is bounded:
12
+ // - the reviewer result (verdict, digest, findings, summary; examinedPaths are
13
+ // fixed by the package) is truncated to REVIEW_TEXT_LIMIT bytes before any
14
+ // record is written, and the completion checkpoint journals it
15
+ // REVIEW_RESULT_COPIES times (frame receipt, receipts, priorReview, observation
16
+ // and inspection; the review and completion cache entries each repeat
17
+ // receipt, receipts, observation and inspection);
18
+ // - the review and completion cache entries each repeat the receipts, calls and
19
+ // Learning writeback that already exist when the package is made;
20
+ // - everything else (receipt and registration metadata, up to 64 observation
21
+ // events per copy, inspection metadata, the new calls, task commit fields) is
22
+ // bounded by REVIEW_FIXED_RESERVE.
23
+ export const REVIEW_TEXT_LIMIT=12*1024;
24
+ export const REVIEW_RESULT_COPIES=13;
25
+ export const REVIEW_FIXED_RESERVE=96*1024;
26
+ export const developCheckpointReserve=({examinedPathsBytes,receiptsBytes=2,callsBytes=2,writebackBytes=4})=>
27
+ REVIEW_RESULT_COPIES*(examinedPathsBytes+REVIEW_TEXT_LIMIT)+2*(receiptsBytes+callsBytes+writebackBytes)+REVIEW_FIXED_RESERVE;
28
+ // The runner reviews scope plus the project AGENTS.md a Learning writeback may change.
29
+ export const taskReviewScope=scope=>scope.includes('AGENTS.md')?scope:[...scope,'AGENTS.md'];
30
+ // Journaled reasons (checkpoint reason, host diagnostics) are one line of at most
31
+ // this many characters; replay refuses anything longer.
32
+ export const JOURNAL_REASON_LIMIT=8192;
33
+ // The one builder for reasons that name paths or other open-ended lists: every
34
+ // item is shown up to 300 characters (longer ones keep their start and end, so a
35
+ // file name stays visible), as many as fit, then "等 N 个" gives the total.
36
+ // Control characters become spaces. The result always fits the limit.
37
+ export function boundedReason(head,items,tail=''){
38
+ const line=value=>String(value).replace(/[\x00-\x1f\x7f]/g,' ');
39
+ const clip=value=>value.length>300?`${value.slice(0,150)}…${value.slice(-149)}`:value;
40
+ const list=items.map(item=>clip(line(item))),start=line(head),end=line(tail),more=` 等 ${list.length} 个`;
41
+ let shown=list.length;
42
+ const text=count=>`${start}${list.slice(0,count).join(', ')}${count<list.length?more:''}${end}`;
43
+ while(shown>0&&text(shown).length>JOURNAL_REASON_LIMIT)shown--;
44
+ return text(shown).slice(0,JOURNAL_REASON_LIMIT);
45
+ }
7
46
  // Explicit host call budget, shared by live initialization and journal replay.
8
47
  // This is not the short-lived authorization grant expiry.
9
48
  export const validCallTimeout=value=>need(Number.isInteger(value)&&value>=1&&value<=3600000);
@@ -12,7 +51,7 @@ const failureCodes=new Set(['invalid_input','limit_exceeded','call_timeout','can
12
51
  'unregistered_receipt','invalid_receipt','receipt_identity','receipt_package_mismatch','review_not_approved',
13
52
  'checks_not_passed','async_commit','commit_unknown','unsupported_path','unsupported_file','read_failed',
14
53
  'snapshot_changed','spec_drift','invalid_baseline','out_of_scope','empty_changes','invalid_package','package_mismatch',
15
- 'handoff_exists','verification_precheck_failed']);
54
+ 'handoff_exists','verification_precheck_failed','completion_checks_changed','bootstrap_review_mismatch']);
16
55
  // An unlisted code becomes execution_error, which on its own is not actionable.
17
56
  // The EEXIST that blocked every retry of a task in #81 stayed invisible in the
18
57
  // log, the state and stderr until a temporary print was added by hand. Emit one
@@ -154,7 +193,10 @@ export function terminalFor(raw,request) {
154
193
  // Reviewer and unknown terminal contracts remain unchanged.
155
194
  need(request.role==='developer'&&v.accepted===true);
156
195
  shape(v.result,['code','reason',...(Object.hasOwn(v.result,'retryable')?['retryable']:[])]);
157
- need(['invalid_result','protected_edit_stale'].includes(v.result.code));id(v.result.reason);
196
+ // bootstrap_verification_failed is produced only by the host bootstrap
197
+ // capability (never a provider adapter); its reason is the code itself.
198
+ need(['invalid_result','protected_edit_stale','bootstrap_verification_failed'].includes(v.result.code));id(v.result.reason);
199
+ if(v.result.code==='bootstrap_verification_failed')need(v.result.reason===v.result.code);
158
200
  if(Object.hasOwn(v.result,'retryable'))need(v.result.retryable===true
159
201
  &&v.result.code==='invalid_result'&&request.requestedModel==='current-session');
160
202
  }
@@ -0,0 +1,58 @@
1
+ // Explicit, versioned policy for NEW executions. No defaults, migration or budgets.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {digest,json,need,id,shape} from './effect-contract.mjs';
5
+ import {isSupportedExecutionPlatform} from './execution-platform.mjs';
6
+ import {fixArchiveRoot} from '../cm-fix/layout.mjs';
7
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
8
+ import {scanRows} from './log-rows.mjs';
9
+ export const EXECUTION_POLICY_V1=Object.freeze({version:1,responseRecovery:'mechanical-v1',
10
+ checkReuse:'declared-adjacent-v1',reviewPresentation:'utf8-v1',usage:'provider-terminal-v1'});
11
+ export function readExecutionPolicy(raw){
12
+ const value=json(raw);need(digest(value)===digest(EXECUTION_POLICY_V1),'execution_policy_invalid');return value;
13
+ }
14
+ export function readLaunchExecutionPolicy({definition,mode,enabled=false}){
15
+ need(['create','resume'].includes(mode),'invalid_mode');
16
+ if(mode==='create')return enabled?readExecutionPolicy(EXECUTION_POLICY_V1):null;
17
+ let snapshot;
18
+ try{snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,identity:{repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});}
19
+ catch(error){if(error.code!=='ENOENT')throw error;need(!enabled,'execution_policy_legacy_run');return null;}
20
+ const saved=snapshot.records.find(row=>row.payload.type==='init')?.payload.config.executionPolicy??null;
21
+ need(!enabled||saved!==null,'execution_policy_legacy_run');return saved===null?null:readExecutionPolicy(saved);
22
+ }
23
+ const batchRoot=batch=>path.join(batch.specsDir,'.cm-execution-policy-v1');
24
+ const batchIdentity=batch=>{id(batch.batchId);return {repositoryId:batch.repositoryId,runId:'batch-policy-'+digest(batch.batchId).slice(0,32)};};
25
+ export function readBatchExecutionPolicy({batch,started,enabled=false}){
26
+ const identity=batchIdentity(batch),root=batchRoot(batch),file=path.join(root,'.reviews','.execution',identity.runId,'state.json');
27
+ if(fs.existsSync(file)){
28
+ const snapshot=readExecutionSnapshot({specsRoot:root,identity});
29
+ need(snapshot.records.length===1&&snapshot.records[0].id==='batch-policy'&&snapshot.records[0].kind==='result','execution_policy_batch_binding');
30
+ const record=snapshot.records[0].payload;shape(record,['kind','batchId','planDigest','executionPolicy']);
31
+ need(record.kind==='cm-execution-policy-v1'&&record.batchId===batch.batchId&&record.planDigest===digest(batch),'execution_policy_batch_binding');
32
+ return readExecutionPolicy(record.executionPolicy);
33
+ }
34
+ const log=path.join(batch.specsDir,'运行日志.jsonl');
35
+ if(fs.existsSync(log))scanRows(log,row=>{if(row.workflow==='cm-ai'&&row.run_id===batch.batchId&&row.event==='decision'&&row.phase==='batch_start')started=true;});
36
+ need(!started||!enabled,'execution_policy_legacy_run');return enabled&&!started?readExecutionPolicy(EXECUTION_POLICY_V1):null;
37
+ }
38
+ export async function freezeBatchExecutionPolicy(batch,executionPolicy){
39
+ if(executionPolicy===null)return;
40
+ const root=batchRoot(batch),identity=batchIdentity(batch);
41
+ if(fs.existsSync(path.join(root,'.reviews','.execution',identity.runId,'state.json'))){
42
+ need(digest(readBatchExecutionPolicy({batch,started:true}))===digest(executionPolicy),'execution_policy_batch_binding');return;
43
+ }
44
+ need(isSupportedExecutionPlatform(),'unsupported_platform');
45
+ const {openExecutionStore}=await import('./execution-store.mjs');
46
+ try{fs.mkdirSync(root,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
47
+ need(fs.realpathSync(root)===root,'execution_policy_batch_binding');
48
+ const payload={kind:'cm-execution-policy-v1',batchId:batch.batchId,planDigest:digest(batch),executionPolicy:readExecutionPolicy(executionPolicy)};
49
+ const store=openExecutionStore({specsRoot:root,identity,create:true,fingerprints:{workflow:digest(payload.kind),config:digest(batch),inputs:digest(payload)}});
50
+ try{store.append({id:'batch-policy',kind:'result',payload,expectedRevision:store.snapshot().revision});}finally{store.close();}
51
+ }
52
+ export function readFixExecutionPolicy({config,mode,enabled=false}){
53
+ if(mode==='create')return enabled?readExecutionPolicy(EXECUTION_POLICY_V1):null;
54
+ need(mode==='resume','invalid_mode');
55
+ const snapshot=readExecutionSnapshot({specsRoot:fixArchiveRoot(config.specsRoot,config.reproduction.cwd),identity:{repositoryId:config.identity.repositoryId,runId:config.identity.runId}});
56
+ const saved=snapshot.records[0]?.payload.configuration?.executionPolicy??null;
57
+ need(!enabled||saved!==null,'execution_policy_legacy_run');return saved===null?null:readExecutionPolicy(saved);
58
+ }
@@ -0,0 +1,18 @@
1
+ // Size and count limits of the local durable record store, without the store
2
+ // itself (no node:sqlite import), so owners can check an append before making it.
3
+ import { digest } from './effect-contract.mjs';
4
+
5
+ export const MiB=1024*1024,STATE_LIMIT=16*MiB,PHYSICAL_LIMIT=32*MiB,RECORD_LIMIT=1024;
6
+
7
+ // Whether append(input) on this snapshot stays within the store's limits (append
8
+ // input, payload, record count, whole state). Pure: an owner can refuse cleanly
9
+ // before an append that would fail inside its writer. The directory's physical
10
+ // limit (state plus retained temporary files) is not checked here.
11
+ export function appendFits(current,input){
12
+ const bytes=value=>Buffer.byteLength(JSON.stringify(value));
13
+ if(bytes(input)>MiB+1024||bytes(input.payload)>MiB||current.records.length>=RECORD_LIMIT)return false;
14
+ const record={version:1,seq:current.records.length+1,id:input.id,kind:input.kind,payload:input.payload,
15
+ previousDigest:current.records.at(-1)?.digest??null};
16
+ const {revision,...data}=current,next={...data,records:[...current.records,{...record,digest:digest(record)}]};
17
+ return bytes({...next,revision:digest(next)})<=STATE_LIMIT;
18
+ }
@@ -3,10 +3,11 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { randomUUID,createHash } from 'node:crypto';
5
5
  import { DatabaseSync } from 'node:sqlite';
6
- import { need,shape,id,hex,json,digest,freeze } from './effect-contract.mjs';
6
+ import { need,shape,id,hex,json,digest,freeze,JOURNAL_PAYLOAD_LIMIT } from './effect-contract.mjs';
7
7
  import { isSupportedExecutionPlatform } from './execution-platform.mjs';
8
+ import { MiB,STATE_LIMIT,PHYSICAL_LIMIT } from './execution-store-limits.mjs';
8
9
 
9
- const MiB=1024*1024,STATE_LIMIT=16*MiB,PHYSICAL_LIMIT=32*MiB,APP_ID=0x434d5831;
10
+ const APP_ID=0x434d5831;
10
11
  const PROTOCOL_SQL='CREATE TABLE protocol(version INTEGER NOT NULL CHECK(version=1))';
11
12
  const kinds=new Set(['intent','result','cancel','commit-intent','commit-result','finalized']);
12
13
  const seal=value=>freeze({...value,revision:digest(value)});
@@ -53,7 +54,7 @@ function validateState(raw,options) {
53
54
  for(const [index,r] of v.records.entries()) {
54
55
  shape(r,['version','seq','id','kind','payload','previousDigest','digest']);
55
56
  need(r.version===1,'store_version');need(r.seq===index+1 && r.previousDigest===previous,'store_corrupt');
56
- id(r.id);need(!ids.has(r.id) && kinds.has(r.kind),'store_corrupt');ids.add(r.id);json(r.payload,MiB);
57
+ id(r.id);need(!ids.has(r.id) && kinds.has(r.kind),'store_corrupt');ids.add(r.id);json(r.payload,JOURNAL_PAYLOAD_LIMIT);
57
58
  const {digest:checksum,...data}=r;hex(checksum);need(digest(data)===checksum,'store_corrupt');previous=checksum;
58
59
  }
59
60
  const {revision,...data}=v;hex(revision);need(digest(data)===revision,'store_corrupt');return v;
@@ -165,6 +166,7 @@ function acquireWriter(p,create) {
165
166
  return {db,inode:regular(p,64*1024),certificate:current,inspectionFd,release};
166
167
  }catch(error){release();if(error.errcode===5)need(false,'store_busy');throw error;}
167
168
  }
169
+ export { appendFits } from './execution-store-limits.mjs';
168
170
  export function openExecutionStore(input) {
169
171
  const options=json(input);shape(options,['specsRoot','identity','fingerprints','create']);
170
172
  shape(options.identity,['repositoryId','runId']);Object.values(options.identity).forEach(id);
@@ -214,7 +216,7 @@ export function openExecutionStore(input) {
214
216
  const append=input=>{
215
217
  need(!closed,'store_closed');need(!poisoned,'store_poisoned');
216
218
  const v=json(input,MiB+1024);shape(v,['id','kind','payload','expectedRevision']);
217
- id(v.id);hex(v.expectedRevision);need(kinds.has(v.kind));json(v.payload,MiB);
219
+ id(v.id);hex(v.expectedRevision);need(kinds.has(v.kind));json(v.payload,JOURNAL_PAYLOAD_LIMIT);
218
220
  const current=snapshot(),existing=current.records.find(r=>r.id===v.id);
219
221
  if(existing){need(existing.kind===v.kind && digest(existing.payload)===digest(v.payload),'record_conflict');return current;}
220
222
  need(v.expectedRevision===current.revision,'revision_mismatch');
@@ -0,0 +1,53 @@
1
+ // Existing batch/fix owners keep the same provider parser and immutable selection.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {digest,need,id,shape} from './effect-contract.mjs';
5
+ import {loadExternalModels,readExternalModels,selectExternalModels} from './external-models.mjs';
6
+ import {openExecutionStore} from './execution-store.mjs';
7
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
8
+ import {fixArchiveRoot} from '../cm-fix/layout.mjs';
9
+
10
+ export function batchModelsFile(batch){
11
+ id(batch.batchId);return path.join(batch.specsDir,'.cm-external-models-v1','.reviews','.execution','batch-models-'+digest(batch.batchId).slice(0,32),'state.json');
12
+ }
13
+ export function readBatchExternalModels({batch,started,enabled=false,inputFile,providers}){
14
+ const file=batchModelsFile(batch);
15
+ if(fs.existsSync(file)){
16
+ need(inputFile===undefined,'external_model_resume_selection_forbidden');
17
+ const snapshot=readExecutionSnapshot({specsRoot:path.join(batch.specsDir,'.cm-external-models-v1'),identity:{repositoryId:batch.repositoryId,runId:path.basename(path.dirname(file))}});
18
+ need(snapshot.records.length===1&&snapshot.records[0].id==='batch-models'&&snapshot.records[0].kind==='result','external_model_batch_binding');
19
+ const record=snapshot.records[0].payload;
20
+ shape(record,['kind','batchId','planDigest','externalModels']);
21
+ need(record.kind==='cm-external-batch-models-v1'&&record.batchId===batch.batchId
22
+ &&record.planDigest===digest(batch),'external_model_batch_binding');
23
+ return readExternalModels(record.externalModels);
24
+ }
25
+ need(!started||!enabled,'external_model_resume_selection_forbidden');
26
+ need(inputFile===undefined||enabled&&!started,'external_model_feature_required');
27
+ return enabled&&!started?selectExternalModels(loadExternalModels(inputFile),providers):null;
28
+ }
29
+ export function freezeBatchExternalModels(batch,externalModels){
30
+ if(!externalModels)return;
31
+ const value={kind:'cm-external-batch-models-v1',batchId:batch.batchId,planDigest:digest(batch),externalModels:readExternalModels(externalModels)};
32
+ const file=batchModelsFile(batch);
33
+ if(fs.existsSync(file)){need(digest(readBatchExternalModels({batch,started:true,providers:Object.keys(externalModels.providers)}))===digest(externalModels),'external_model_batch_binding');return;}
34
+ const specsRoot=path.join(batch.specsDir,'.cm-external-models-v1');
35
+ try{fs.mkdirSync(specsRoot,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
36
+ need(fs.realpathSync(specsRoot)===specsRoot,'external_model_batch_binding');
37
+ const fingerprint=digest('cm-external-batch-models-v1');
38
+ const store=openExecutionStore({specsRoot,identity:{repositoryId:batch.repositoryId,runId:path.basename(path.dirname(file))},create:true,
39
+ fingerprints:{workflow:fingerprint,config:digest(batch),inputs:digest(value)}});
40
+ try{store.append({id:'batch-models',kind:'result',payload:value,expectedRevision:store.snapshot().revision});}finally{store.close();}
41
+ }
42
+ export function readFixExternalModels({config,mode,enabled=false,inputFile,runtime='codex'}){
43
+ if(mode==='resume'){
44
+ need(inputFile===undefined,'external_model_resume_selection_forbidden');
45
+ const specsRoot=fixArchiveRoot(config.specsRoot,config.reproduction.cwd);
46
+ const saved=readExecutionSnapshot({specsRoot,identity:{repositoryId:config.identity.repositoryId,runId:config.identity.runId}})
47
+ .records[0]?.payload.configuration?.externalModels??null;
48
+ need(!enabled||saved!==null,'external_model_resume_selection_forbidden');
49
+ return saved===null?null:readExternalModels(saved);
50
+ }
51
+ need(inputFile===undefined||enabled,'external_model_feature_required');
52
+ return enabled?selectExternalModels(loadExternalModels(inputFile),[runtime]):null;
53
+ }
@@ -0,0 +1,23 @@
1
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
2
+ import {loadExternalModels,readExternalModels,selectExternalModels} from './external-models.mjs';
3
+ import {need} from './effect-contract.mjs';
4
+ export function readLaunchExternalModels({definition,mode,enabled=false,inputFile,providers}){
5
+ need(['create','resume'].includes(mode),'invalid_mode');
6
+ if(mode==='resume'){
7
+ need(inputFile===undefined,'external_model_resume_selection_forbidden');
8
+ let snapshot;
9
+ try{snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,
10
+ identity:{repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});}
11
+ catch(error){
12
+ if(error.code!=='ENOENT')throw error;
13
+ need(!enabled,'external_model_resume_selection_forbidden');
14
+ // Let the original owner report store_missing, without changing legacy resume diagnostics.
15
+ return null;
16
+ }
17
+ const saved=snapshot.records.find(row=>row.payload.type==='init')?.payload.config.externalModels??null;
18
+ need(!enabled||saved!==null,'external_model_resume_selection_forbidden');
19
+ return saved===null?null:readExternalModels(saved);
20
+ }
21
+ need(inputFile===undefined||enabled,'external_model_feature_required');
22
+ return enabled?selectExternalModels(loadExternalModels(inputFile),providers):null;
23
+ }
@@ -0,0 +1,52 @@
1
+ // One explicit request per external provider; the host session is client-owned.
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import {json,need,shape} from './effect-contract.mjs';
5
+ import {readModelJsonRecord,writeModelJson} from './model-configuration-file.mjs';
6
+
7
+ export const EXTERNAL_MODEL_SCHEMA=1;
8
+ export const EXTERNAL_EFFORTS=Object.freeze({
9
+ codex:Object.freeze(['none','minimal','low','medium','high','xhigh']),
10
+ claude:Object.freeze(['low','medium','high','xhigh','max']),
11
+ });
12
+ export function externalEffort(provider,effort=undefined){
13
+ need(Object.hasOwn(EXTERNAL_EFFORTS,provider),'invalid_external_provider');
14
+ const value=effort===undefined?(provider==='codex'?'high':null):effort;
15
+ need(provider==='claude'&&value===null||EXTERNAL_EFFORTS[provider].includes(value),'unsupported_external_effort');
16
+ return value;
17
+ }
18
+ export function externalPair(provider,raw){
19
+ const value=json(raw);shape(value,['model',...(Object.hasOwn(value,'effort')?['effort']:[])]);
20
+ need(typeof value.model==='string'&&value.model.length<=128&&/^[a-zA-Z0-9._-]+$/.test(value.model)
21
+ &&value.model!=='current-session','external_model_required');
22
+ return {model:value.model,effort:externalEffort(provider,value.effort)};
23
+ }
24
+ export function readExternalModels(raw){
25
+ const value=json(raw,64*1024);shape(value,['schemaVersion','providers']);
26
+ need(value.schemaVersion===EXTERNAL_MODEL_SCHEMA,'external_schema_unsupported');
27
+ shape(value.providers,Object.keys(value.providers));
28
+ return {schemaVersion:EXTERNAL_MODEL_SCHEMA,providers:Object.fromEntries(Object.entries(value.providers)
29
+ .map(([provider,pair])=>[provider,externalPair(provider,pair)]))};
30
+ }
31
+ export const externalModelsPath=()=>path.join(path.resolve(process.env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow')),'external-models-v1.json');
32
+ export function loadExternalModels(file=externalModelsPath()){
33
+ try{return readExternalModels(readModelJsonRecord(file).value);}
34
+ catch(error){if(error.code==='ENOENT')throw Object.assign(new Error('external_model_setup_required'),{code:'external_model_setup_required'});throw error;}
35
+ }
36
+ export function selectExternalModels(raw,providers){
37
+ const value=readExternalModels(raw);
38
+ return {schemaVersion:EXTERNAL_MODEL_SCHEMA,providers:Object.fromEntries([...new Set(providers)].map(provider=>{
39
+ need(Object.hasOwn(value.providers,provider),'external_model_setup_required');return [provider,value.providers[provider]];
40
+ }))};
41
+ }
42
+ export function externalSettingsRecord(file=externalModelsPath()){
43
+ try{return readModelJsonRecord(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}
44
+ }
45
+ export function saveExternalModels(value,{file=externalModelsPath(),expectedSha256,sourceGuard=null}={}){
46
+ writeModelJson(file,readExternalModels(value),{expectedSha256,sourceGuard,createParents:true});
47
+ }
48
+ // This is a requested tuple and adapter capability, never provider confirmation.
49
+ export function describeExternalModels(raw){
50
+ return {host:'current-session (controlled by client)',external:readExternalModels(raw),
51
+ capabilityEvidence:'adapter argument contract',effectiveModel:'unknown',providerConfirmed:false};
52
+ }
@@ -0,0 +1,96 @@
1
+ import {inspectFixExecutionHistory} from '../cm-fix/execution.mjs';
2
+ // Reuse the existing SQLite ownership protocol; never unlock an unknown call.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {openExecutionStore} from './execution-store.mjs';
6
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
7
+ import {fixReviewLedger} from '../cm-fix/review-reconciliation.mjs';
8
+ import {inspectProviderReview,inspectProviderCauseReview} from './provider-review-observation.mjs';
9
+ import {validateReviewDispatchGrant} from './durable-runner-state.mjs';
10
+ import {readRunnerHistory} from './durable-runner-state.mjs';
11
+ import {oldWriterOpen} from './reviewed-evidence-supersede.mjs';
12
+ import {digest,need,shape,id} from './effect-contract.mjs';
13
+ import {readModelJsonRecord,writeModelJson} from './model-configuration-file.mjs';
14
+ function fixCallsResolved(records,configuration){
15
+ const ledger=fixReviewLedger(records,configuration);
16
+ const hosts=[configuration.hostContextId,...records.filter(r=>/^fix-host-joined-/.test(r.id)).map(r=>r.payload.hostContextId)];
17
+ for(const registration of records.filter(r=>/^fix-.*-registered$/.test(r.id))){
18
+ const prefix=registration.id.slice(0,-'-registered'.length),request=registration.payload.request;
19
+ const started=records.find(r=>r.id===prefix+'-started'),result=records.find(r=>r.id===prefix+'-result');
20
+ if(!started||!result)return false;
21
+ const cause=prefix.includes('cause'),reviewer=configuration.causeReview;
22
+ validateReviewDispatchGrant(registration.payload.grant,{request,reviewerId:cause?reviewer.reviewerId:'fix-final-reviewer',adapterId:cause?reviewer.adapterId:`${reviewer.provider}-review-adapter`,packageDigest:request.payload.reviewPackage.packageDigest,hostContextIds:hosts,authorizationAt:registration.payload.authorizationAt,registeredAt:registration.payload.registeredAt});
23
+ need(result.payload.dispatchAt>=registration.payload.registeredAt&&result.payload.dispatchAt<registration.payload.grant.expiresAt,'external_prior_run_unverifiable');
24
+ const proof=ledger.receipts.get(request.invocationId);
25
+ if(proof&&ledger.applied.has(request.invocationId))continue;
26
+ const excluded=[...reviewer.excludedThreadIds,...hosts.slice(1),request.contextId,...records.filter(r=>r.seq<registration.seq&&/-started$/.test(r.id)&&r.payload.providerThreadId).map(r=>r.payload.providerThreadId)];
27
+ const checked=(cause?inspectProviderCauseReview:inspectProviderReview)(JSON.stringify(result.payload.observation),JSON.stringify({request,developerThreadId:hosts[0],excludedThreadIds:[...new Set(excluded)]}));
28
+ if(checked.observationStatus!=='completed'||checked.providerThreadId!==started.payload.providerThreadId)return false;
29
+ }
30
+ return true;
31
+ }
32
+ const codeBinding=codeProject=>path.join(codeProject,'.cm-external-models-v1.json');
33
+ export const externalRunGuardExists=(specsDir,codeProject)=>fs.existsSync(path.join(specsDir,'.cm-external-models-v1'))||fs.existsSync(codeBinding(codeProject));
34
+ export function acquireExternalRunGuard(definition,{strictOnly=false}={}){
35
+ const {specsDir,codeProject,identity,feature}=definition;
36
+ for(const folder of [specsDir,codeProject])need(path.isAbsolute(folder)&&fs.realpathSync(folder)===folder,'external_run_guard_path');
37
+ // A code checkout belongs to one specs root; changing specs cannot hide an attempt.
38
+ const binding={version:1,kind:'cm-external-code-binding',specsDir},file=codeBinding(codeProject);
39
+ if(!fs.existsSync(file))try{writeModelJson(file,binding,{expectedSha256:null,replace:false});}
40
+ catch(error){if(!['model_configuration_exists','model_configuration_changed'].includes(error.code))throw error;}
41
+ need(digest(readModelJsonRecord(file).value)===digest(binding),'external_code_specs_conflict');
42
+ const root=path.join(specsDir,'.cm-external-models-v1');
43
+ try{fs.mkdirSync(root,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
44
+ const stat=fs.lstatSync(root);
45
+ need(stat.isDirectory()&&!stat.isSymbolicLink()&&(stat.mode&0o077)===0,'external_run_guard_path');
46
+ const leaseId='external-provider-'+digest(codeProject).slice(0,32);
47
+ const leaseDir=path.join(root,'.reviews/.execution',leaseId);
48
+ const fingerprint=digest('cm-external-models-serial-lease-v1');
49
+ const lease=openExecutionStore({specsRoot:root,identity:{repositoryId:identity.repositoryId,runId:leaseId},
50
+ fingerprints:{workflow:fingerprint,config:fingerprint,inputs:fingerprint},create:!fs.existsSync(leaseDir)});
51
+ try{
52
+ const execution=path.join(specsDir,'.reviews/.execution');
53
+ if(fs.existsSync(execution))for(const entry of fs.readdirSync(execution,{withFileTypes:true})){
54
+ if(entry.name===identity.runId)continue;
55
+ if(entry.name==='batch.lock'){
56
+ const file=path.join(execution,entry.name),stat=fs.lstatSync(file);
57
+ need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&(stat.mode&0o077)===0&&stat.size<=4096,'external_prior_run_unverifiable');
58
+ const lock=JSON.parse(fs.readFileSync(file,'utf8'));shape(lock,['batchId','pid','at']);id(lock.batchId);
59
+ need(Number.isSafeInteger(lock.pid)&&lock.pid>0&&typeof lock.at==='string','external_prior_run_unverifiable');
60
+ continue;
61
+ }
62
+ need(entry.isDirectory()&&!entry.isSymbolicLink(),'external_prior_run_unverifiable');
63
+ const snapshot=readExecutionSnapshot({specsRoot:specsDir,identity:{repositoryId:identity.repositoryId,runId:entry.name}});
64
+ const init=snapshot.records[0]?.payload,config=init?.config;
65
+ if(init?.workflow==='cm-fix-stages-v1'){
66
+ const fix=init.configuration;need(fix?.reproduction?.cwd,'external_prior_run_unverifiable');
67
+ if(fs.realpathSync(fix.reproduction.cwd)!==codeProject)continue;
68
+ if(strictOnly&&!(fix.externalModels||fix.executionPolicy))continue;
69
+ need(!oldWriterOpen(execution,entry.name),'external_prior_writer_active');
70
+ inspectFixExecutionHistory({specsRoot:specsDir,identity:{repositoryId:identity.repositoryId,runId:entry.name}});
71
+ // A completed parent may reopen read-only between its original serial child steps.
72
+ if(fix.qaSource&&digest(fix.qaSource.identity)===digest(identity))continue;
73
+ need(fixCallsResolved(snapshot.records,fix),'external_prior_attempt_unresolved');
74
+ continue;
75
+ }
76
+ // An unfinished initializer has no task identity and cannot safely be ignored.
77
+ need(config,'external_prior_run_unverifiable');
78
+ if(strictOnly&&!(config.externalModels||config.executionPolicy))continue;
79
+ if(config.root!==codeProject)continue;
80
+ const history=readRunnerHistory(snapshot.records,config,init.version);
81
+ // Unknown external work belongs to the code root, even across tasks/features.
82
+ if(config.externalModels||config.executionPolicy)need(!history.pending&&history.state.state!=='unknown'
83
+ &&history.state.reviewInvocation?.result?.reconciliationRequired!==true
84
+ &&!history.state.calls.some(call=>call.requestedModel!=='current-session'
85
+ &&!['succeeded','not_dispatched'].includes(call.terminal)
86
+ &&!snapshot.records.some(row=>row.payload.type==='review-invocation-reconciled'&&row.payload.invocationId===call.invocationId)),'external_prior_attempt_unresolved');
87
+ need(!oldWriterOpen(execution,entry.name),'external_prior_writer_active');
88
+ if(config.identity.taskId!==identity.taskId
89
+ ||config.completion?.owner?.tasksPath!==path.join(specsDir,feature,'tasks.md'))continue;
90
+ need(!history.pending&&!['unknown','ready','awaiting_review','pending_review','changes_requested','approved'].includes(history.state.state)
91
+ &&history.state.reviewInvocation?.result?.reconciliationRequired!==true,'external_prior_attempt_unresolved');
92
+ need(!oldWriterOpen(execution,entry.name),'external_prior_writer_active');
93
+ }
94
+ return lease;
95
+ }catch(error){lease.close();throw error;}
96
+ }