@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
@@ -1,3 +1,6 @@
1
+ import {createNativeUsageLog} from './native-usage-log.mjs';
2
+ import {readExecutionPolicy} from './execution-policy.mjs';
3
+ import {selectExternalModels} from './external-models.mjs';
1
4
  // Fixed current-conversation factory, separate from CLI top-level execution.
2
5
  import fs from 'node:fs';
3
6
  import {spawn} from 'node:child_process';
@@ -26,13 +29,17 @@ import {validateDocumentationPaths} from './host-documentation.mjs';
26
29
  import {verifySpecificationMaterial} from './specification-material.mjs';
27
30
  import {isFinalCmAiTask} from './cm-ai-admission.mjs';
28
31
  import {createHostBootstrap} from './host-bootstrap.mjs';
32
+ import {withHostProgress} from './host-progress.mjs';
29
33
  import {digest,id,hex,json,need,shape,freeze,arrayItems} from './effect-contract.mjs';
30
34
  export const protectedTextInstructions='\nProtected current-host mode: do not write files or run commands. Return {status,value,edits} on success; '
31
- +'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content}], complete UTF-8 text or null for deletion. '
35
+ +'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content[,mode]}], complete UTF-8 text or null for deletion; '
36
+ +'optional mode "0755" or "0644" sets the permission bits of a written file. '
32
37
  +'Only the supplied scope and expected hashes are allowed. The fixed sandbox applies these edits. On failure return {status,code} without edits. '
33
38
  +'status must be exactly "succeeded" on success (with value and edits) or "failed" (with code). Return the object through the structured output schema; never wrap it in markdown fences.';
34
39
  const protectedConversations=new WeakMap();
35
40
  export const conversationProtection=execution=>protectedConversations.get(execution)??null;
41
+ const externalConversations=new WeakMap();
42
+ export const externalConversationDefinition=execution=>externalConversations.get(execution)??null;
36
43
  // An explicit reviewer budget wins over the protected-mode budget: it is the
37
44
  // narrower knob, and raising it must not require switching development mode.
38
45
  // Absent both, the worker default applies. Returns a spread-ready fragment so
@@ -89,23 +96,38 @@ export function deliveredText(codeProject,scope){
89
96
  export function resolveReviewTimeout(review,protection){
90
97
  if(review?.timeoutMs!=null)return {timeoutMs:review.timeoutMs};
91
98
  if(protection)return {timeoutMs:protection.timeoutMs};
92
- return {};
99
+ return {timeoutMs:900000};
93
100
  }
101
+ // The runner races each review against its own timer. That timer must outlast
102
+ // the reviewer's budget, or a budget raised above the runner's journaled call
103
+ // timeout (fixed at 30 minutes here) is still cut at 30 minutes and the attempt's
104
+ // only redispatch is spent. The worker stops its process group about a second
105
+ // after its own deadline; the margin leaves room for that and for close.
106
+ export const REVIEW_BOUND_MARGIN_MS=60000;
107
+ export const reviewRaceTimeout=(outerTimeoutMs,reviewTimeoutMs)=>Math.max(outerTimeoutMs,reviewTimeoutMs+REVIEW_BOUND_MARGIN_MS);
94
108
  export function createConversationExecution(definition,hostContextId,bridge,review=null,allowedAttempt=null,workflow=null,allowQa=false,runtime='codex',options={}){
95
109
  definition=json(definition);workflow=workflow===null?null:json(workflow);options=json(options);
96
- shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
110
+ shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','externalModels','reviewerRuntime','parallelMember','verificationPrecheck','executionPolicy'].filter(key=>Object.hasOwn(options,key))]);
97
111
  need(!Object.hasOwn(options,'verificationPrecheck')||typeof options.verificationPrecheck==='boolean','invalid_input');
112
+ const executionPolicy=options.executionPolicy?readExecutionPolicy(options.executionPolicy):null;
98
113
  const parallelMember=options.parallelMember??false;need(typeof parallelMember==='boolean','invalid_input');
99
114
  const provider=options.providerDevelopment??null;
100
115
  if(provider){
101
- shape(provider,['model','attempt','coderRuntime','reviewerRuntime']);
116
+ shape(provider,['model','attempt','coderRuntime','reviewerRuntime',...(Object.hasOwn(provider,'effort')?['effort']:[])]);
102
117
  need(options.protection&&review!==null,'protected_configuration_required');
103
118
  need([1,2].includes(provider.attempt),'provider_development_authorization_required');
104
119
  need(/^[a-zA-Z0-9._-]+$/.test(provider.model),'invalid_model');
105
120
  need(digest(resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),runtime))
106
121
  ===digest({coderRuntime:provider.coderRuntime,reviewerRuntime:provider.reviewerRuntime}),'runtime_selection_mismatch');
107
122
  }
108
- const coderRuntime=provider?.coderRuntime??runtime,reviewerRuntime=provider?.reviewerRuntime??runtime;
123
+ if(Object.hasOwn(options,'reviewerRuntime'))need(options.externalModels&&['codex','claude'].includes(options.reviewerRuntime)
124
+ &&options.reviewerRuntime===resolveProtectedRuntimes(loadConfig({projectRoot:definition.codeProject}),runtime).reviewerRuntime,'runtime_selection_mismatch');
125
+ const coderRuntime=provider?.coderRuntime??runtime,reviewerRuntime=provider?.reviewerRuntime??options.reviewerRuntime??runtime;
126
+ const externalModels=options.externalModels?selectExternalModels(options.externalModels,provider?[coderRuntime,reviewerRuntime]:[reviewerRuntime]):null;
127
+ if(externalModels){
128
+ const selected=externalModels.providers[reviewerRuntime];need(review!==null&&review.model===selected.model&&review.effort===selected.effort,'external_model_configuration_conflict');
129
+ if(provider){const selected=externalModels.providers[coderRuntime];need(provider.model===selected.model&&provider.effort===selected.effort,'external_model_configuration_conflict');}
130
+ }else need(!Object.hasOwn(provider??{},'effort')&&!Object.hasOwn(review??{},'effort'),'external_model_feature_required');
109
131
  let bootstrap=null;
110
132
  if(options.bootstrap){
111
133
  shape(options.bootstrap,['selection','allowWrite']);
@@ -115,7 +137,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
115
137
  const protection=options.protection??null;
116
138
  if(protection){shape(protection,['checkCommands','timeoutMs']);specsPermissionArgs({cwd:definition.codeProject,specsRoot:definition.specsDir});}
117
139
  need(!definition.codeProjects||protection,'multi_root_protection_required');
118
- const projectExecution=protection?createProjectExecution({definition,protection}):null;
140
+ const projectExecution=protection?createProjectExecution({definition,protection,executionPolicy}):null;
119
141
  const check=projectExecution?.check??null;
120
142
  const documentationPaths=workflow?validateDocumentationPaths(workflow.documentationPaths,definition.scope):[];
121
143
  need(['codex','claude'].includes(runtime),'invalid_runtime');
@@ -132,13 +154,15 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
132
154
  need(protection||!definition.specsDir.startsWith(definition.codeProject+path.sep),'nested_specs_protection_required');
133
155
  const configuration={kind:'cm-current-conversation-v1',...(parallelMember?{parallelMember}:{}),definitionDigest:digest(definition),hostContextId:durableHostContextId,
134
156
  ...(runtime==='claude'?{runtime}:{}),
135
- ...(provider?{providerDevelopment:{model:provider.model,coderRuntime,reviewerRuntime}}:{}),
157
+ ...(executionPolicy?{executionPolicy}:{}),
158
+ ...(externalModels?{externalModels}:{}),
159
+ ...(provider?{providerDevelopment:{model:provider.model,coderRuntime,reviewerRuntime,...(externalModels?{effort:provider.effort}:{})}}:{}),
136
160
  ...(protection?{protection}:{}),
137
161
  ...(bootstrap?{bootstrap:bootstrap.configuration}:{}),
138
162
  ...(options.batchWorkflowsDigest?{batchWorkflowsDigest:options.batchWorkflowsDigest}:{}),
139
- ...(review?{review:{version:1,model:review.model,disabledSkills:review.disabledSkills}}:{}),
163
+ ...(review?{review:{version:1,model:review.model,disabledSkills:review.disabledSkills,...(externalModels?{effort:review.effort}:{})}}:{}),
140
164
  ...(workflow?{workflow}: {})};
141
- const reviewOptions={cwd:definition.codeProject,model:review?.model??'unconfigured',preflight:review?.preflight??null,
165
+ const reviewOptions={cwd:definition.codeProject,model:review?.model??'unconfigured',...(externalModels?{effort:review.effort}:{}),preflight:review?.preflight??null,
142
166
  disabledSkills:review?.disabledSkills??[],
143
167
  ...resolveReviewTimeout(review,protection),
144
168
  promptTransport:'stdin',schemaPath:fileURLToPath(new URL('./review-result.schema.json',import.meta.url))};
@@ -192,8 +216,11 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
192
216
  }catch{/* diagnostics never change the verdict */}
193
217
  return {satisfied:verdict.satisfied};
194
218
  }:null;
195
- const execution={configuration,timeoutMs:provider?protection.timeoutMs:1800000,excludedContexts:[durableHostContextId],hostDecision:null,applicableAgentFiles:[],
196
- ...(verificationGate?{verificationGate}:{}),
219
+ const outerTimeoutMs=provider?protection.timeoutMs:1800000;
220
+ const progress=(request,control,stage,run,selectedRuntime=runtime)=>withHostProgress({definition,
221
+ identity:request.identity,runtime:selectedRuntime,stage,signal:control.signal},run);
222
+ const execution={configuration,timeoutMs:outerTimeoutMs,excludedContexts:[durableHostContextId],hostDecision:null,applicableAgentFiles:[],
223
+ ...(verificationGate?{verificationGate:(request,control)=>progress(request,control,'verifying',()=>verificationGate(request,control))}:{}),
197
224
  ...(bootstrap?{bootstrap}:{}),
198
225
  ...(provider?{developmentAttempt:provider.attempt}:{}),
199
226
  ...(workflow?createHostWorkflowCapabilities({definition,configuration:workflow,bridge,allowQa,runtime,protectedExecution:protection!==null,bootstrap,parallelMember}):{}),
@@ -206,14 +233,18 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
206
233
  need(!used.has(bound.invocationId),'duplicate_dispatch');used.add(bound.invocationId);
207
234
  }
208
235
  const route=provider?null:resolveHostRole({definition,identity:bound.identity,role:'coder',signal:control.signal,runtime});
236
+ let developerUsage=null;const developerLog=executionPolicy&&provider?createNativeUsageLog({definition,request:bound,provider:coderRuntime,role:'developer'}):null;
209
237
  const processWorker=provider?(coderRuntime==='codex'?codexDeveloperWorker:claudeDeveloperWorker)({
210
- cwd:definition.codeProject,model:provider.model,timeoutMs:protection.timeoutMs,
238
+ ...(developerLog?{onUsageClaim:()=>developerLog.claimed(),onUsage:value=>{developerUsage=value;}}:{}),
239
+ cwd:definition.codeProject,model:provider.model,...(externalModels?{effort:provider.effort}:{}),timeoutMs:protection.timeoutMs,
211
240
  ...(coderRuntime==='codex'?{specsRoot:definition.specsDir}:{}),
212
241
  spawnProcess:dispatchSpawn('coder',bound.identity,control.signal)}):null;
213
242
  const worker=async({prompt})=>{
214
243
  if(provider&&coderRuntime==='codex'){
215
244
  if(documentationPaths.length)prompt='Synchronize approved documentation inside this invocation: '+JSON.stringify(documentationPaths)+'\n'+prompt;
216
- return processWorker({prompt},control);
245
+ const response=await processWorker({prompt},control);
246
+ developerLog?.complete(developerUsage??{usage_state:'unavailable'},response.status==='succeeded'?'success':response.status==='cancelled'?'cancelled':'error');
247
+ return response;
217
248
  }
218
249
  const expected=projectExecution?projectExecution.expected(bound.payload.scope):null;
219
250
  if(protection){
@@ -225,6 +256,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
225
256
  ...(definition.codeProjects?{codeProjects:resolveCodeProjects(definition.codeProject,definition.codeProjects),
226
257
  projectInstructions:definition.codeProjects.map(root=>({codeProject:root,files:readProjectInstructionContext(root)}))}:{}),
227
258
  ...(protection?{editMode:'protected-text-v1',expected}: {})},control.signal));
259
+ if(provider)developerLog?.complete(developerUsage??{usage_state:'unavailable'},response.status==='succeeded'?'success':response.status==='cancelled'?'cancelled':'error');
228
260
  if(response.status==='succeeded'){
229
261
  const edits=[];
230
262
  try{
@@ -237,7 +269,8 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
237
269
  if(response.value.outcome==='blocked')need(response.edits.length===0,'protected_edit_invalid');
238
270
  const seen=new Set();
239
271
  for(const edit of response.edits){
240
- shape(edit,['path','beforeSha256','content']);
272
+ shape(edit,['path','beforeSha256','content',...(Object.hasOwn(edit,'mode')?['mode']:[])]);
273
+ need(!Object.hasOwn(edit,'mode')||edit.content!==null&&['0644','0755'].includes(edit.mode),'protected_edit_invalid');
241
274
  need(bound.payload.scope.includes(edit.path)&&!seen.has(edit.path),'out_of_scope');seen.add(edit.path);
242
275
  if(edit.beforeSha256!==null)hex(edit.beforeSha256);
243
276
  need(edit.content===null||typeof edit.content==='string','protected_edit_invalid');
@@ -272,10 +305,11 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
272
305
  if(provider){const {providerThread,...failure}=response;shape(failure,['status','code']);return failure;}
273
306
  shape(response,['status','code']);return response;
274
307
  };
275
- return createDeveloperRun({worker,provider:coderRuntime,requestedModel:provider?.model??'current-session',
276
- protectedCurrentSession:protection!==null&&provider===null})(bound,control);
308
+ return progress(bound,control,'developing',()=>createDeveloperRun({worker,provider:coderRuntime,requestedModel:provider?.model??'current-session',
309
+ protectedCurrentSession:protection!==null&&provider===null})(bound,control),coderRuntime);
277
310
  }},
278
- check:check??((request,control)=>{
311
+ check:(request,control)=>progress(request,control,'checking',()=>{
312
+ if(check)return check(request,control);
279
313
  const route=resolveHostRole({definition,identity:request.identity,role:'tester',signal:control.signal,runtime});
280
314
  return bridge.call('check',{...request,codeProject:definition.codeProject,
281
315
  scope:definition.scope,requirements:definition.requirements,route},control.signal);
@@ -286,11 +320,22 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
286
320
  allowed:true,available:true,contexts:reviewContexts,
287
321
  run:(request,control)=>{
288
322
  need(review!==null,'review_configuration_required');
289
- const selectedOptions={...reviewOptions,...(provider?{spawnProcess:dispatchSpawn('reviewer',request.identity,control.signal)}:{})};
290
- return reviewerRuntime==='codex'?createCodexReviewRun(codexWorker(selectedOptions))(request,control)
291
- :createClaudeReviewRun(claudeWorker(selectedOptions))(request,control);
323
+ let observedUsage=null;const usageLog=executionPolicy?createNativeUsageLog({definition,request,provider:reviewerRuntime,role:'reviewer'}):null;
324
+ const selectedOptions={...reviewOptions,...(usageLog?{onUsageClaim:()=>usageLog.claimed(),onUsage:value=>{observedUsage=value;}}:{}),...(provider?{spawnProcess:dispatchSpawn('reviewer',request.identity,control.signal)}:{})};
325
+ return progress(request,control,'review_starting',async observation=>{
326
+ const observedControl={...control,onEvent:event=>{
327
+ control.onEvent(event);
328
+ if(event.event==='thread.started')observation.reviewStarted();
329
+ }};
330
+ const result=await (reviewerRuntime==='codex'?createCodexReviewRun(codexWorker(selectedOptions),executionPolicy)(request,observedControl)
331
+ :createClaudeReviewRun(claudeWorker(selectedOptions),executionPolicy)(request,observedControl));
332
+ usageLog?.complete(observedUsage??{usage_state:'unavailable'},result.status==='succeeded'?'success':result.status==='cancelled'?'cancelled':'error');
333
+ return result;
334
+ },reviewerRuntime);
292
335
  }}],
293
336
  reviewInvocation:{developerThreadId:author,excludedThreadIds:[durableHostContextId],hostContextId,
337
+ // Not journaled (unlike timeoutMs above), so a resumed run may raise it.
338
+ timeoutMs:reviewRaceTimeout(outerTimeoutMs,reviewOptions.timeoutMs),
294
339
  authorize:authority?.authorize??(()=>({status:'denied',code:'permission_denied'}))},
295
340
  };
296
341
  if(definition.codeProjects)execution.applicableAgentFiles=[...new Set([...execution.applicableAgentFiles,
@@ -298,5 +343,6 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
298
343
  .filter(file=>file!=='AGENTS.md'&&fs.existsSync(path.join(definition.codeProject,file)))])];
299
344
  if(protection){freeze(execution);protectedConversations.set(execution,freeze({codeProject:definition.codeProject,
300
345
  specsRoot:definition.specsDir,definitionDigest:digest(definition)}));}
346
+ if(externalModels||executionPolicy){freeze(execution);externalConversations.set(execution,digest(definition));}
301
347
  return execution;
302
348
  }
@@ -8,7 +8,7 @@ import {implementationSha256,loadHandoff} from '../../../scripts/cm-task-gate.mj
8
8
  import {digest,json,shape,text,need} from './effect-contract.mjs';
9
9
 
10
10
  export const REVIEWED_HANDOFF_HINT='仅 QA 卡住时,配置错误用 --revise-qa-config PREVIOUS.json --qa-config-revision-reason … 恢复原运行,宿主或环境证据不足用 --rerun-blocked-qa。确需重跑任务时,用 --supersede-reviewed-evidence --supersede-reason … 新建运行。';
11
- function reviewedHandoffConflict(){
11
+ export function reviewedHandoffConflict(){
12
12
  const error=new Error('handoff_exists');error.code='handoff_exists';error.reason=REVIEWED_HANDOFF_HINT;throw error;
13
13
  }
14
14
 
@@ -24,11 +24,20 @@ function prepareHostHandoff(raw){
24
24
  const parent=path.dirname(handoffPath);
25
25
  need(fs.realpathSync(parent)===parent&&fs.lstatSync(parent).isDirectory(),'unsupported_path');
26
26
  const reviewPackage=createReviewPackage({root,baseline,checks});
27
+ const changedFiles=reviewPackage.changes.map(change=>change.path);
28
+ const {payload,bytes}=hostHandoffDocument({baseline,checks,reviewPackage,
29
+ implementationSha256:implementationSha256(root,changedFiles),evidence});
30
+ need(bytes.length<=256*1024,'limit_exceeded');
31
+ return {root,baseline,checks,handoffPath,parent,reviewPackage,changedFiles,payload,bytes};
32
+ }
33
+ // Pure: the handoff document for a package and its checks, byte for byte as it is
34
+ // published. The driver builds it for a projected package to size a delivery.
35
+ export function hostHandoffDocument({baseline,checks,reviewPackage,implementationSha256,evidence=[]}){
27
36
  const changedFiles=reviewPackage.changes.map(change=>change.path);
28
37
  const passed=checks.every(check=>check.outcome==='passed');
29
38
  const payload={schema_version:1,task_id:baseline.identity.taskId,attempt:baseline.identity.attempt,
30
39
  status:passed?'ready_for_review':'blocked',changed_files:changedFiles,
31
- implementation_sha256:implementationSha256(root,changedFiles),
40
+ implementation_sha256:implementationSha256,
32
41
  verification:checks.map(check=>({command:check.kind==='visual'
33
42
  ?`Visual inspection (not a shell command): ${check.before.kind} before/after comparison`
34
43
  :JSON.stringify(check.command),
@@ -36,9 +45,7 @@ function prepareHostHandoff(raw){
36
45
  evidence:[`host review package ${reviewPackage.packageDigest}`,...evidence],
37
46
  blockers:passed?[]:checks.filter(check=>check.outcome!=='passed').map(check=>`check ${check.id}: ${check.outcome}`),
38
47
  scope_deviation:[]};
39
- const bytes=Buffer.from(JSON.stringify(payload,null,2)+'\n');
40
- need(bytes.length<=256*1024,'limit_exceeded');
41
- return {root,baseline,checks,handoffPath,parent,reviewPackage,changedFiles,payload,bytes};
48
+ return {payload,bytes:Buffer.from(JSON.stringify(payload,null,2)+'\n')};
42
49
  }
43
50
 
44
51
  // Same serialization as publication, without creating files or registering work.
@@ -57,7 +64,7 @@ export function verifyHostHandoff(raw){
57
64
  // One left by a run that died before review is not: it must not block every retry
58
65
  // of the same task forever. The receipt names the handoff it reviewed, so the two
59
66
  // cases are distinguishable without guessing from timestamps or run identity.
60
- function reviewConsumedHandoff(parent,name,attempt){
67
+ export function reviewConsumedHandoff(parent,name,attempt){
61
68
  const suffix=`-a${attempt}-handoff.json`;
62
69
  if(!name.endsWith(suffix))return true;
63
70
  const receipt=path.join(parent,`${name.slice(0,-suffix.length)}-r${attempt}.md`);
@@ -0,0 +1,80 @@
1
+ // Event-based operator feedback. Failure here never changes a runner verdict.
2
+ import path from 'node:path';
3
+ import {spawnSync} from 'node:child_process';
4
+ import {randomUUID} from 'node:crypto';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {need} from './effect-contract.mjs';
7
+ import {readStatusProjection,writeStatusProjection} from './status-projection.mjs';
8
+
9
+ const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
10
+ const phases={developing:['N3','正在开发'],checking:['N3','正在执行检查'],
11
+ verifying:['N3','正在核对交付要求'],review_starting:['N4','正在启动独立审查'],reviewing:['N4','正在独立审查']};
12
+ const diagnostic=()=>{try{process.stderr.write('{"diagnostic":"progress_projection_failed"}\n');}catch{}};
13
+ function logProgress({definition,identity,runtime,operationId,stage,phase,outcome}){
14
+ const [node,detail]=phases[stage];
15
+ const result=spawnSync('python3',[writer,'--workflow','cm-ai','--event','progress','--phase',phase,
16
+ '--runtime',runtime,'--project-root',definition.codeProject,'--specs-dir',definition.specsDir,
17
+ '--run-id',identity.runId,'--detail',detail+(phase==='complete'?':调用已结束':''),'--data-json',JSON.stringify({node,
18
+ feature:definition.feature,task:identity.taskId,attempt:identity.attempt,operation_id:operationId,
19
+ phase_name:stage,...(outcome?{outcome}:{})})],
20
+ {timeout:10000,maxBuffer:64*1024,env:{...process.env,
21
+ CM_WORKFLOW_LOG_HOME:path.join(definition.specsDir,'.reviews','host-log-mirror')}});
22
+ need(!result.error&&result.status===0&&result.signal===null,'progress_log_failed');
23
+ }
24
+ export function startHostProgress({definition,identity,runtime='codex',stage,signal}){
25
+ need(phases[stage]&&!signal.aborted,'cancelled');
26
+ const operationId=randomUUID();let token=null,closed=false,observedReview=false;
27
+ const record=(phase,outcome)=>{
28
+ try{logProgress({definition,identity,runtime,operationId,stage,phase,outcome});}catch{diagnostic();}
29
+ };
30
+ const project=(selected,claim)=>{
31
+ try{
32
+ const receipt=writeStatusProjection({specsDir:definition.specsDir,feature:definition.feature,identity,
33
+ node:phases[selected][0],state:selected,detail:phases[selected][1],claim,expectedToken:claim?null:token});
34
+ token=receipt.written?receipt.token:null;
35
+ }catch{token=null;diagnostic();}
36
+ };
37
+ record('start');project(stage,true);
38
+ return Object.freeze({
39
+ reviewStarted(){
40
+ if(closed||signal.aborted||observedReview)return;observedReview=true;
41
+ if(token!==null)project('reviewing',false);
42
+ },
43
+ complete(outcome){
44
+ if(closed)return;closed=true;
45
+ record('complete',signal.aborted?'aborted':outcome);
46
+ },
47
+ });
48
+ }
49
+ export async function withHostProgress(options,run){
50
+ const progress=startHostProgress(options);
51
+ try{const result=await run(progress);progress.complete('returned');return result;}
52
+ catch(error){progress.complete('failed');throw error;}
53
+ }
54
+
55
+ const states={awaiting_review:['N4','检查已结束,等待独立审查'],pending_review:['N4','独立审查等待处理'],
56
+ changes_requested:['N4','审查要求修改'],approved:['N5','审查已通过,等待完成检查'],
57
+ fixture_completed:['N5','开发完成检查已通过,等待 QA/收尾'],
58
+ blocked:['N3','运行受阻'],unknown:['N3','执行结果待核对'],cancelled:['N3','运行已取消']};
59
+ export function projectHostResult({specsDir,feature,result,readCurrent}){
60
+ if(!result?.operation||result.operation==='status'||!result.state||!result.identity)return;
61
+ const selected=states[result.state];if(!selected)return;
62
+ // A late control response is not the runner's current state. Derived QA and
63
+ // documentation summaries have their own existing projections.
64
+ try{
65
+ // Read lazily, after eligibility, and keep display-read failures advisory.
66
+ // Eligible results still need fresh state after an asynchronous effect.
67
+ const current=readCurrent();
68
+ if(current.state!==result.state||current.identity.runId!==result.identity.runId
69
+ ||current.identity.taskId!==result.identity.taskId||current.identity.attempt!==result.identity.attempt)return;
70
+ const previous=readStatusProjection(specsDir);
71
+ if(previous===null)return;
72
+ // QA and finalization must never be replaced by an earlier N3/N4 response.
73
+ if(['N6','N7','N8'].includes(previous.node))return;
74
+ const node=['blocked','unknown','cancelled'].includes(result.state)?previous.node:selected[0];
75
+ writeStatusProjection({specsDir,feature,identity:result.identity,node,state:result.state,
76
+ detail:(result.guidance?.summary??selected[1])+(result.code?`(${result.code})`:''),code:result.code,
77
+ ...(result.state==='changes_requested'&&result.identity.attempt>1?{previousAttempt:result.identity.attempt-1}:{}),
78
+ expectedToken:previous.progress_id??null});
79
+ }catch{diagnostic();}
80
+ }
@@ -2,11 +2,11 @@
2
2
  // Root selection is data, not a second scheduler or a task completion authority.
3
3
  import {captureProtectedEdits,commitProtectedEdits} from '../cm-fix/protected-edits.mjs';
4
4
  import {groupCodeProjectPaths,resolveCodeProjects} from './code-projects.mjs';
5
- import {createHostCheck} from './host-check.mjs';
5
+ import {createHostCheck,reportHostCheckProgress} from './host-check.mjs';
6
6
  import {specsPermissionArgs} from './codex-config.mjs';
7
7
  import {digest,json,need,shape,id} from './effect-contract.mjs';
8
8
 
9
- export function createProjectExecution({definition,protection}){
9
+ export function createProjectExecution({definition,protection,executionPolicy=null}){
10
10
  const data=json(definition),config=json(protection);
11
11
  const roots=data.codeProjects?resolveCodeProjects(data.codeProject,data.codeProjects):[data.codeProject];
12
12
  for(const root of roots)specsPermissionArgs({cwd:root,specsRoot:data.specsDir});
@@ -16,15 +16,20 @@ export function createProjectExecution({definition,protection}){
16
16
  const commands=config.checkCommands;
17
17
  need(Array.isArray(commands)&&commands.length>0&&commands.length<=32,'invalid_check_config');
18
18
  const ids=new Set();
19
- const checks=commands.map(command=>{
20
- shape(command,['id','command',...(data.codeProjects?['codeProject']:[])]);id(command.id);
19
+ const plans=[];
20
+ for(const command of commands){
21
+ shape(command,['id','command',...(data.codeProjects?['codeProject']:[]),
22
+ ...(executionPolicy&&Object.hasOwn(command,'sameExecutionAs')?['sameExecutionAs']:[])]);id(command.id);
21
23
  need(!ids.has(command.id),'invalid_check_config');ids.add(command.id);
22
24
  const cwd=data.codeProjects?command.codeProject:data.codeProject;
23
25
  need(roots.includes(cwd),'execution_root_mismatch');
24
- const check=createHostCheck({cwd,specsRoot:data.specsDir,timeoutMs:config.timeoutMs,
25
- commands:[{id:command.id,command:command.command}]});
26
- return {cwd,check};
27
- });
26
+ if(Object.hasOwn(command,'sameExecutionAs'))need(plans.at(-1)?.cwd===cwd,'check_reuse_binding');
27
+ if(plans.at(-1)?.cwd!==cwd)plans.push({cwd,commands:[]});
28
+ const {codeProject,...local}=command;plans.at(-1).commands.push(local);
29
+ }
30
+ const checks=plans.map(plan=>({cwd:plan.cwd,check:createHostCheck({cwd:plan.cwd,specsRoot:data.specsDir,
31
+ timeoutMs:config.timeoutMs,onProgress:reportHostCheckProgress,commands:plan.commands,
32
+ reuseDeclared:executionPolicy?.checkReuse==='declared-adjacent-v1'})}));
28
33
  need(roots.every(root=>checks.some(item=>item.cwd===root)),'code_project_checks_required');
29
34
  const recheck=()=>{if(data.codeProjects)need(digest(resolveCodeProjects(data.codeProject,roots))===digest(roots),'execution_root_mismatch');};
30
35
  return Object.freeze({
@@ -48,9 +53,9 @@ export function createProjectExecution({definition,protection}){
48
53
  async check(request,control){
49
54
  recheck();const result=[];
50
55
  for(const item of checks){
51
- const [row]=await item.check(request,control);
52
- result.push(data.codeProjects?{...row,evidence:`cwd=${item.cwd}; ${row.evidence}`}:row);
53
- if(row.outcome!=='passed')break;
56
+ const rows=await item.check(request,control);
57
+ result.push(...rows.map(row=>data.codeProjects?{...row,evidence:`cwd=${item.cwd}; ${row.evidence}`}:row));
58
+ if(rows.some(row=>row.outcome!=='passed'))break;
54
59
  }
55
60
  return result;
56
61
  },
@@ -6,8 +6,8 @@ import {spawnSync} from 'node:child_process';
6
6
  import {fileURLToPath} from 'node:url';
7
7
  import {loadConfig,resolveRole} from '../../../scripts/cm-workflow-config.mjs';
8
8
  import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
9
- import {inspectCmAiAdmission,inspectCmAiQaTaskContext} from './cm-ai-admission.mjs';
10
- import {createHostCheck} from './host-check.mjs';
9
+ import {inspectCmAiAdmission,inspectCmAiQaTaskContext,identifyApprovedBootstrapFeature} from './cm-ai-admission.mjs';
10
+ import {createHostCheck,reportHostCheckProgress} from './host-check.mjs';
11
11
  import {specsPermissionArgs} from './codex-config.mjs';
12
12
  import {resolveCodeProjects,codeProjectPaths} from './code-projects.mjs';
13
13
  import {findCmAiQaDecision,readCmAiQaRunRound,reportFile} from './cm-ai-qa-log.mjs';
@@ -108,7 +108,8 @@ export function createHostQaExecutor(options) {
108
108
  for(const name of ['specsDir','codeProject'])need(fs.realpathSync(configuration[name])===configuration[name],'unsupported_path');
109
109
  const roots=configuration.codeProjects?resolveCodeProjects(configuration.codeProject,configuration.codeProjects):null;
110
110
  if(configuration.bootstrap){
111
- shape(configuration.bootstrap,['requirements','scope']);need(configuration.feature==='0.bootstrap','bootstrap_task_required');
111
+ shape(configuration.bootstrap,['requirements','scope']);
112
+ need(configuration.feature===identifyApprovedBootstrapFeature(configuration.specsDir),'bootstrap_task_required');
112
113
  }
113
114
  if(Object.hasOwn(configuration,'specsRoot')){
114
115
  need(configuration.specsRoot===configuration.specsDir,'execution_specs_mismatch');
@@ -183,7 +184,7 @@ export function createHostQaExecutor(options) {
183
184
  for(const command of plan.commands){
184
185
  notCancelled();
185
186
  const check=createHostCheck({cwd:roots?command.codeProject:configuration.codeProject,commands:[{id:command.id,command:command.command}],
186
- timeoutMs:configuration.timeoutMs,specsRoot:configuration.specsRoot??null});
187
+ timeoutMs:configuration.timeoutMs,specsRoot:configuration.specsRoot??null,onProgress:reportHostCheckProgress});
187
188
  const resource={resource_id:`qa-command-${digest({testRunId:binding.testRunId,command:command.id}).slice(0,48)}`,
188
189
  resource_kind:'qa_command'};
189
190
  logStep(configuration,binding,'resource','acquired',{...resource,cleanup_required:true},'QA command resource acquired');
@@ -217,10 +218,10 @@ export function createHostQaExecutor(options) {
217
218
  ...(hostRequestTimeout?{hostRequestTimeout:true}:{})});
218
219
  }else{
219
220
  logStep(configuration,binding,'test_run','case_start',{case_id:item.id},'QA browser case started');
220
- let observed,hostRequestTimeout=false;
221
+ let observed,hostRequestTimeout=false,answered=false;
221
222
  if(browser===null||item.expected.some(value=>value.includes('[需确认]')))
222
223
  observed={verdict:'BLOCKED',evidence:[],environment,cleanup:'not_needed'};
223
- else try{observed=json(await browser(request,signal));}
224
+ else try{observed=json(await browser(request,signal));answered=true;}
224
225
  catch(error){
225
226
  if(error.code!=='host_request_timeout')throw error;
226
227
  hostRequestTimeout=true;
@@ -238,11 +239,18 @@ export function createHostQaExecutor(options) {
238
239
  }catch{evidenceProblem='qa_evidence_required';}
239
240
  const verdict=evidenceProblem!==null||digest(observed.environment)!==digest(environment)||observed.cleanup==='failed'
240
241
  ||(item.cleanup.length>0&&observed.cleanup!=='completed')?'BLOCKED':observed.verdict;
242
+ // The session itself answered BLOCKED (for example: simulator
243
+ // unreachable). Unlike [需确认] or a missing capability, a later
244
+ // explicit rerun on the same code can change this outcome.
241
245
  rows.push({id:item.id,kind:'browser',origin:item.origin,blocking:item.blocking,verdict,
242
246
  evidence:observed.evidence,evidenceProblem,environment:observed.environment,cleanup:observed.cleanup,
243
- ...(hostRequestTimeout?{hostRequestTimeout:true}:{})});
247
+ ...(hostRequestTimeout?{hostRequestTimeout:true}:{}),
248
+ ...(answered&&observed.verdict==='BLOCKED'?{hostDeclaredBlocked:true}:{})});
249
+ // The durable log row, appended now through the writer, is the record
250
+ // that the session itself answered BLOCKED; the report only mirrors it.
244
251
  logStep(configuration,binding,'test_run',verdict==='BLOCKED'?'case_blocked':'case_complete',
245
- {case_id:item.id,result:verdict},'QA browser case finished');
252
+ {case_id:item.id,result:verdict,...(answered&&observed.verdict==='BLOCKED'?{host_declared_blocked:true}:{})},
253
+ 'QA browser case finished');
246
254
  }
247
255
  }
248
256
  }
@@ -257,8 +265,14 @@ export function createHostQaExecutor(options) {
257
265
  observed.length>0&&observed.every(item=>item?.outcome==='passed')?'PASS':'BLOCKED';
258
266
  row.commandEvidence=mappings.map(item=>item.id);
259
267
  const item=plan.cases.find(item=>item.id===row.id);
260
- if(item.expected.some(value=>value.includes('[需确认]')))row.verdict='BLOCKED';
268
+ // Record why a logic case is BLOCKED: an unresolved [需确认] expectation
269
+ // stays BLOCKED on every round, while a mapped command that produced no
270
+ // exit code is an environment outcome that an explicit rerun can change.
271
+ const needsConfirmation=item.expected.some(value=>value.includes('[需确认]'));
272
+ if(needsConfirmation){row.verdict='BLOCKED';row.needsConfirmation=true;}
261
273
  if(row.hostRequestTimeout)row.verdict='BLOCKED';
274
+ if(row.verdict==='BLOCKED'&&row.staticVerdict==='SUPPORTED'&&!needsConfirmation
275
+ &&observed.some(result=>result?.outcome==='unavailable'))row.commandUnavailable=true;
262
276
  }
263
277
  if(rows.length===0)rows.push({id:'qa-unavailable',kind:'commands',verdict:'BLOCKED',evidence:['No executable QA contract']});
264
278
  const drift=digest(before.files)!==digest(snapshot().files);
@@ -1,3 +1,5 @@
1
+ import {selectExternalModels} from './external-models.mjs';
2
+ import {readExecutionPolicy} from './execution-policy.mjs';
1
3
  // Serial child host. Existing owners retain lifecycle and action authority.
2
4
  import fs from 'node:fs';
3
5
  import path from 'node:path';
@@ -6,11 +8,11 @@ import {createFixHost} from '../cm-fix/host.mjs';
6
8
  import {bindQaFixDefinition} from './qa-fix-definition.mjs';
7
9
  import {digest,id,json,need,shape,validIdentity,hex} from './effect-contract.mjs';
8
10
 
9
- export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={}}){
11
+ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={},externalModels=null,executionPolicy=null}){
10
12
  id(hostContextId);id(parentHostContextId);
11
13
  need((fix===null)!==(template===null),'invalid_fix_config');
12
14
  let definition=null;
13
- const fixedTemplate=template===null?null:json(template,64*1024);
15
+ let fixedTemplate=template===null?null:json(template,64*1024);
14
16
  if(fixedTemplate){
15
17
  shape(fixedTemplate,['specsRoot','feature','identity','configuration']);validIdentity(fixedTemplate.identity);
16
18
  need(!Object.hasOwn(fixedTemplate.configuration,'qaSource'),'invalid_fix_template');
@@ -18,6 +20,21 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
18
20
  shape(fix,['specsRoot','identity','configuration']);definition=json(fix,64*1024);
19
21
  validIdentity(definition.identity);need(definition.configuration.qaSource,'qa_fix_source_required');
20
22
  }
23
+ if(executionPolicy){
24
+ const selected=readExecutionPolicy(executionPolicy),target=fixedTemplate??definition;
25
+ if(!fixedTemplate&&!target.configuration.executionPolicy)need(false,'execution_policy_legacy_child_inheritance_forbidden');
26
+ if(target.configuration.executionPolicy)need(digest(target.configuration.executionPolicy)===digest(selected),'execution_policy_child_conflict');
27
+ const inherited={...target,configuration:{...target.configuration,executionPolicy:selected}};
28
+ if(fixedTemplate)fixedTemplate=inherited;else definition=inherited;
29
+ }
30
+ if(externalModels){
31
+ const target=fixedTemplate??definition,runtime=target.configuration.runtime??'codex';
32
+ const selected=selectExternalModels(externalModels,[runtime]);
33
+ if(!fixedTemplate&&!target.configuration.externalModels)need(false,'external_model_legacy_child_inheritance_forbidden');
34
+ if(target.configuration.externalModels)need(digest(target.configuration.externalModels)===digest(selected),'external_model_pair_conflict');
35
+ const inherited={...target,configuration:{...target.configuration,externalModels:selected}};
36
+ if(fixedTemplate)fixedTemplate=inherited;else definition=inherited;
37
+ }
21
38
  need(typeof allowStart==='boolean','invalid_input');
22
39
  need(typeof autoFix==='boolean'&&(!autoFix||(allowStart&&fixedTemplate!==null)),'qa_fix_auto_authorization_required');
23
40
  need(typeof reopenParent==='function','invalid_input');
@@ -43,7 +60,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
43
60
  busy=true;try{return await current.host.handle(request);}finally{busy=false;}
44
61
  }
45
62
  const value=json(request);shape(value,['version','requestId','operation','identity','packageDigest','testRunId',
46
- ...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='abandon_step'&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
63
+ ...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='reconcile_review'?['invocationId']:[]),...(['abandon_step','abandon_review'].includes(request.fixOperation)&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
47
64
  need(value.version===1,'invalid_input');id(value.requestId);validIdentity(value.identity);hex(value.packageDigest);id(value.testRunId);
48
65
  if(fixedTemplate)definition=bindQaFixDefinition({template:fixedTemplate,identity:value.identity,
49
66
  packageDigest:value.packageDigest,testRunId:value.testRunId});
@@ -55,7 +72,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
55
72
  const acting=value.operation==='fix_action';
56
73
  if(acting)need(['red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback',
57
74
  'handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression',
58
- 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','abandon_step'].includes(value.fixOperation),'fix_operation_unavailable');
75
+ 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','reconcile_review','abandon_step','abandon_review'].includes(value.fixOperation),'fix_operation_unavailable');
59
76
  need(!(advancing||acting)||allowStart,'qa_fix_start_authorization_required');
60
77
  busy=true;let child=null,released=false,result;
61
78
  try{
@@ -75,7 +92,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
75
92
  runtime:definition.configuration.runtime??'codex',permissions:[...permissions,'--allow-reproduction'],...fixAuthorities});
76
93
  actionResult=running?await host.run(value.requestId)
77
94
  :await host.handle({requestId:value.requestId,operation:advancing?'advance':value.fixOperation,
78
- ...(value.fixOperation==='abandon_step'?{reason:value.reason}:{})});
95
+ ...(value.fixOperation==='reconcile_review'?{invocationId:value.invocationId}:{}),...(['abandon_step','abandon_review'].includes(value.fixOperation)?{reason:value.reason}:{})});
79
96
  }
80
97
  // Original observation/escalation finish intentionally closes its owner. Preserve
81
98
  // that successful incomplete exit without reading a closed store.
@@ -95,7 +112,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
95
112
  // completion evidence uses the existing parent journal contract.
96
113
  if(result.code==='qa_fix_completed'&&typeof current.inspectFixAssociation==='function'){
97
114
  try{
98
- const association=current.inspectFixAssociation(result.evidence.reviewPackage);
115
+ const association=current.inspectFixAssociation(result.evidence.reviewPackage,result.evidence);
99
116
  const accepted=(running||(acting&&value.fixOperation==='finish'))&&typeof current.acceptCompletedFix==='function'
100
117
  ?current.acceptCompletedFix(result.evidence):null;
101
118
  return json({...result,association,...(accepted?{accepted}: {})},12*1024*1024);
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {inspectCmAiQaTaskContext} from './cm-ai-admission.mjs';
5
5
  import {scanRows,readDecision} from './cm-ai-qa-log.mjs';
6
- import {digest,freeze,hex,json,need,shape,validIdentity} from './effect-contract.mjs';
6
+ import {digest,freeze,hex,id,json,need,shape,validIdentity} from './effect-contract.mjs';
7
7
 
8
8
  const key=(feature,task)=>`${feature}/${task}`;
9
9
 
@@ -53,23 +53,32 @@ export function decideHostQaPolicy({assessment,pending,mergeEligible,unassessedT
53
53
  export function createHostQaDecisionProvider({assess,timeoutMs}) {
54
54
  need(typeof assess==='function'&&Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=60000,'qa_assessment_invalid');
55
55
  return Object.freeze({timeoutMs,async decide(raw,signal){
56
- const binding=json(raw);shape(binding,['specsDir','codeProject','feature','identity','packageDigest']);
56
+ const input=json(raw);
57
+ shape(input,['specsDir','codeProject','feature','identity','packageDigest',...(Object.hasOwn(input,'previousDecisionId')?['previousDecisionId']:[])]);
58
+ // previousDecisionId names an older recorded decision that an explicit
59
+ // recovery supersedes; it only derives a distinct id, never the assessment.
60
+ const {previousDecisionId=null,...binding}=input;if(previousDecisionId!==null)id(previousDecisionId);
57
61
  validIdentity(binding.identity);hex(binding.packageDigest);
58
62
  const context=inspectCmAiQaTaskContext({...binding,taskId:binding.identity.taskId});
59
63
  const unassessedTasks=history(binding,context);
60
64
  need(!signal.aborted,'cancelled');
61
- let assessment,timedOut=false;
65
+ let assessment;
62
66
  try{assessment=await assess(freeze({...binding,pending:context.pending,mergeEligible:context.mergeEligible,
63
67
  unassessedTasks}),signal);}
64
- catch(error){if(error.code!=='host_request_timeout')throw error;timedOut=true;}
68
+ catch(error){
69
+ // A missed answer window is a transport outcome, not a QA decision. It is
70
+ // reported like the outer decision timer: retryable, and nothing durable.
71
+ if(error?.code==='host_request_timeout')throw Object.assign(new Error('QA assessment timed out'),{code:'qa_decision_timeout'});
72
+ throw error;
73
+ }
65
74
  need(!signal.aborted,'cancelled');
66
75
  // Assessment is read-only. A task/log change while it was pending requires
67
76
  // another decision; do not bind an answer to different policy inputs.
68
77
  const current=inspectCmAiQaTaskContext({...binding,taskId:binding.identity.taskId});
69
78
  need(digest(current)===digest(context)&&history(binding,current)===unassessedTasks,'stale_qa');
70
- const result=timedOut?{status:'blocked',score:null,reason:'host_request_timeout'}:
71
- decideHostQaPolicy({assessment,pending:context.pending,mergeEligible:context.mergeEligible,unassessedTasks});
72
- return freeze({...result,decisionId:`qa-${digest({identity:binding.identity,packageDigest:binding.packageDigest}).slice(0,48)}`,
79
+ const result=decideHostQaPolicy({assessment,pending:context.pending,mergeEligible:context.mergeEligible,unassessedTasks});
80
+ const bound={identity:binding.identity,packageDigest:binding.packageDigest,...(previousDecisionId===null?{}:{previousDecisionId})};
81
+ return freeze({...result,decisionId:`qa-${digest(bound).slice(0,48)}`,
73
82
  identity:binding.identity,packageDigest:binding.packageDigest,at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')});
74
83
  }});
75
84
  }