@aibyzero/cm-workflow 0.17.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (357) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +23 -0
  3. package/CHANGELOG.md +242 -0
  4. package/README.md +20 -3
  5. package/THIRD_PARTY_NOTICES.md +13 -0
  6. package/VERSION +1 -1
  7. package/compat/claude-commands/cm-challenge.md +3 -0
  8. package/docs/architecture.md +11 -0
  9. package/docs/cm-control-policy-v2.md +127 -9
  10. package/docs/installation.md +310 -4
  11. package/docs/js-workflow-control.md +150 -15
  12. package/docs/live-evidence-drivers.md +28 -4
  13. package/docs/out-of-scope/README.md +25 -0
  14. package/docs/out-of-scope/background-supervisor.md +32 -0
  15. package/docs/reviewed-integration.md +48 -0
  16. package/docs/user-guide.md +50 -21
  17. package/install-codex.sh +331 -18
  18. package/install.ps1 +28 -2
  19. package/install.sh +321 -17
  20. package/package.json +2 -1
  21. package/runtime/js/autonomy.mjs +152 -0
  22. package/runtime/js/cm-ai/batch-location.mjs +55 -0
  23. package/runtime/js/cm-ai/batch-plan.mjs +242 -0
  24. package/runtime/js/cm-ai/checkpoint-package-material.mjs +162 -0
  25. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +55 -1
  26. package/runtime/js/cm-ai/claude-review-stream.mjs +83 -14
  27. package/runtime/js/cm-ai/claude-tool-preview.mjs +11 -9
  28. package/runtime/js/cm-ai/cm-ai-admission.mjs +56 -17
  29. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +91 -6
  30. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +5 -1
  31. package/runtime/js/cm-ai/codex-config.mjs +6 -2
  32. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +3 -2
  33. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  34. package/runtime/js/cm-ai/codex-reconnect-notice.mjs +6 -0
  35. package/runtime/js/cm-ai/codex-review-adapter.mjs +27 -7
  36. package/runtime/js/cm-ai/control-policy.mjs +21 -4
  37. package/runtime/js/cm-ai/developer-adapter.mjs +19 -5
  38. package/runtime/js/cm-ai/drive-core.mjs +115 -11
  39. package/runtime/js/cm-ai/drive-rate-limit.mjs +105 -0
  40. package/runtime/js/cm-ai/durable-runner-state.mjs +234 -33
  41. package/runtime/js/cm-ai/effect-contract.mjs +11 -2
  42. package/runtime/js/cm-ai/execution-policy.mjs +3 -1
  43. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -2
  44. package/runtime/js/cm-ai/execution-store-limits.mjs +14 -7
  45. package/runtime/js/cm-ai/execution-store.mjs +60 -17
  46. package/runtime/js/cm-ai/fix-code-association.mjs +73 -2
  47. package/runtime/js/cm-ai/host-check.mjs +11 -5
  48. package/runtime/js/cm-ai/host-conversation-execution.mjs +70 -28
  49. package/runtime/js/cm-ai/host-qa-executor.mjs +38 -5
  50. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +2 -2
  51. package/runtime/js/cm-ai/host-qa-policy.mjs +19 -2
  52. package/runtime/js/cm-ai/host-replay.mjs +148 -0
  53. package/runtime/js/cm-ai/host-session.mjs +1 -1
  54. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +19 -2
  55. package/runtime/js/cm-ai/host.mjs +1 -1
  56. package/runtime/js/cm-ai/implicit-qa-decision.mjs +5 -0
  57. package/runtime/js/cm-ai/integration-snapshots.mjs +50 -0
  58. package/runtime/js/cm-ai/live-evidence.mjs +28 -6
  59. package/runtime/js/cm-ai/operator-guidance.mjs +9 -2
  60. package/runtime/js/cm-ai/owned-process-cleanup.mjs +27 -9
  61. package/runtime/js/cm-ai/process-group-exit.mjs +46 -0
  62. package/runtime/js/cm-ai/provider-review-observation.mjs +3 -2
  63. package/runtime/js/cm-ai/qa-attachment.mjs +22 -0
  64. package/runtime/js/cm-ai/qa-config-revision.mjs +7 -2
  65. package/runtime/js/cm-ai/requirement-evidence.mjs +102 -0
  66. package/runtime/js/cm-ai/review-package.mjs +79 -7
  67. package/runtime/js/cm-ai/review-presentation-delta.mjs +166 -0
  68. package/runtime/js/cm-ai/review-presentation.mjs +177 -8
  69. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +70 -2
  70. package/runtime/js/cm-ai/reviewed-integration.mjs +260 -0
  71. package/runtime/js/cm-ai/scope-revision.mjs +38 -0
  72. package/runtime/js/cm-ai/specification-material.mjs +2 -2
  73. package/runtime/js/cm-ai/task-runner.mjs +242 -39
  74. package/runtime/js/cm-ai/verification-auto.mjs +38 -0
  75. package/runtime/js/cm-ai/worker-claude-developer.mjs +39 -15
  76. package/runtime/js/cm-ai/worker-claude.mjs +35 -13
  77. package/runtime/js/cm-ai/worker-codex-developer.mjs +43 -17
  78. package/runtime/js/cm-ai/worker-codex.mjs +41 -7
  79. package/runtime/js/cm-fix/cause-invocation.mjs +16 -2
  80. package/runtime/js/cm-fix/cause-package.mjs +46 -1
  81. package/runtime/js/cm-fix/command-correction.mjs +37 -0
  82. package/runtime/js/cm-fix/cooperative.mjs +12 -0
  83. package/runtime/js/cm-fix/dossier.mjs +8 -2
  84. package/runtime/js/cm-fix/execution.mjs +578 -100
  85. package/runtime/js/cm-fix/final-review.mjs +39 -8
  86. package/runtime/js/cm-fix/finish.mjs +15 -11
  87. package/runtime/js/cm-fix/host-review.mjs +65 -10
  88. package/runtime/js/cm-fix/host.mjs +35 -12
  89. package/runtime/js/cm-fix/jest-command-correction.mjs +69 -0
  90. package/runtime/js/cm-fix/metrics.mjs +18 -5
  91. package/runtime/js/cm-fix/regression-evidence.mjs +3 -2
  92. package/runtime/js/cm-fix/regression.mjs +16 -7
  93. package/runtime/js/cm-fix/repair.mjs +29 -8
  94. package/runtime/js/cm-fix/review-verification-command.mjs +135 -0
  95. package/runtime/js/cm-fix/review-verification-contract.mjs +54 -0
  96. package/runtime/js/cm-fix/review-verification-diagnostic.mjs +75 -0
  97. package/runtime/js/cm-fix/review-verification-recovery.mjs +44 -0
  98. package/runtime/js/cm-fix/review-verification-server.mjs +38 -0
  99. package/runtime/js/cm-fix/review-verification.mjs +214 -0
  100. package/runtime/js/cm-fix/source-correction-recovery.mjs +65 -0
  101. package/runtime/js/cm-fix/start.mjs +6 -3
  102. package/runtime/js/cm-fix/test-type-correction.mjs +86 -0
  103. package/runtime/js/cm-fix/test-type-recovery.mjs +51 -0
  104. package/runtime/js/cm-fix/type-import-correction.mjs +89 -0
  105. package/runtime/js/cm-prd/accepted-design.mjs +8 -0
  106. package/runtime/js/cm-prd/analysis.mjs +13 -9
  107. package/runtime/js/cm-prd/change.mjs +37 -16
  108. package/runtime/js/cm-prd/draft-save.mjs +13 -6
  109. package/runtime/js/cm-prd/draft.mjs +31 -3
  110. package/runtime/js/cm-prd/failed-correction.mjs +19 -3
  111. package/runtime/js/cm-prd/inputs-replaced.mjs +3 -0
  112. package/runtime/js/cm-prd/review-correction.mjs +6 -4
  113. package/runtime/js/cm-prd/review-disposition.mjs +7 -1
  114. package/runtime/js/cm-prd/self-check-revision.mjs +2 -2
  115. package/runtime/js/cm-prd/self-check.mjs +125 -6
  116. package/runtime/js/cm-prd/session.mjs +30 -1
  117. package/runtime/js/cm-prd/summary.mjs +11 -5
  118. package/runtime/js/cm-prd/task-scope-record.mjs +97 -0
  119. package/runtime/js/cm-prd/tree-digest.mjs +34 -0
  120. package/runtime/js/cm-prd/validation-reason.mjs +8 -4
  121. package/runtime/js/cm-security/scan.mjs +1 -1
  122. package/runtime/js/commander/decision.mjs +44 -0
  123. package/runtime/js/commander/dispatch-registry.mjs +110 -0
  124. package/runtime/js/commander/ledger.mjs +265 -0
  125. package/runtime/js/commander/preflight.mjs +107 -0
  126. package/runtime/js/notify-later.mjs +13 -0
  127. package/runtime/js/notify-send.mjs +6 -2
  128. package/runtime/js/notify.mjs +581 -65
  129. package/runtime/js/review-findings.mjs +38 -0
  130. package/runtime/js/session-boundary.mjs +56 -0
  131. package/runtime/js/session-handoff.mjs +68 -0
  132. package/runtime/js/spec-task-line.mjs +27 -13
  133. package/runtime/js/specs-status.mjs +5 -4
  134. package/runtime/js/task-scope.mjs +197 -0
  135. package/runtime/logging.md +6 -1
  136. package/runtime/model-efficiency.md +69 -10
  137. package/runtime/orchestration.md +3 -1
  138. package/runtime/project-learning.md +2 -0
  139. package/runtime/review.md +3 -2
  140. package/runtime/test-contract.md +1 -0
  141. package/scripts/ci-test-weights.json +3 -0
  142. package/scripts/cm-ai-admission.mjs +21 -7
  143. package/scripts/cm-ai-admission.test.mjs +171 -3
  144. package/scripts/cm-ai-batch-drive.mjs +79 -18
  145. package/scripts/cm-ai-batch-drive.test.mjs +169 -3
  146. package/scripts/cm-ai-batch-host.mjs +38 -9
  147. package/scripts/cm-ai-batch-host.test.mjs +6 -5
  148. package/scripts/cm-ai-batch-learning-merge.test.mjs +36 -0
  149. package/scripts/cm-ai-batch-location.test.mjs +57 -0
  150. package/scripts/cm-ai-batch-plan.mjs +52 -0
  151. package/scripts/cm-ai-batch-plan.test.mjs +397 -0
  152. package/scripts/cm-ai-batch-run-fixture.mjs +446 -35
  153. package/scripts/cm-ai-batch-run-member-stops.test.mjs +16 -0
  154. package/scripts/cm-ai-batch-run-parallel.test.mjs +28 -1
  155. package/scripts/cm-ai-batch-run.mjs +471 -57
  156. package/scripts/cm-ai-batch-run.test.mjs +23 -4
  157. package/scripts/cm-ai-batch-session-e2e.test.mjs +235 -0
  158. package/scripts/cm-ai-batch-session-member.test.mjs +293 -0
  159. package/scripts/cm-ai-batch-session-recovery.test.mjs +423 -0
  160. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +247 -0
  161. package/scripts/cm-ai-checklist-coverage.test.mjs +4 -2
  162. package/scripts/cm-ai-checkpoint-package-material.test.mjs +221 -0
  163. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +193 -0
  164. package/scripts/cm-ai-control-launch.test.mjs +21 -0
  165. package/scripts/cm-ai-control-policy.test.mjs +14 -0
  166. package/scripts/cm-ai-control-v2-drive.test.mjs +398 -3
  167. package/scripts/cm-ai-control-v2-supersede-race.mjs +25 -0
  168. package/scripts/cm-ai-control-v2-supersede.test.mjs +318 -0
  169. package/scripts/cm-ai-develop-driver-gaps.test.mjs +163 -0
  170. package/scripts/cm-ai-development-rework.test.mjs +423 -0
  171. package/scripts/cm-ai-drive.mjs +73 -17
  172. package/scripts/cm-ai-drive.test.mjs +34 -2
  173. package/scripts/cm-ai-execution-store-legacy-probe.test.mjs +84 -0
  174. package/scripts/cm-ai-host.mjs +60 -19
  175. package/scripts/cm-ai-integration-adoption.test.mjs +223 -0
  176. package/scripts/cm-ai-integration-independence.test.mjs +23 -0
  177. package/scripts/cm-ai-integration-launch.test.mjs +240 -0
  178. package/scripts/cm-ai-integration-preview.mjs +41 -0
  179. package/scripts/cm-ai-integration-snapshots.test.mjs +197 -0
  180. package/scripts/cm-ai-nested-execution.test.mjs +29 -1
  181. package/scripts/cm-ai-operator-guidance.test.mjs +16 -1
  182. package/scripts/cm-ai-prefinal-delivery.test.mjs +278 -0
  183. package/scripts/cm-ai-project-qa-gate.test.mjs +56 -0
  184. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +28 -0
  185. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +36 -2
  186. package/scripts/cm-ai-requirement-evidence.test.mjs +65 -0
  187. package/scripts/cm-ai-review-failure.test.mjs +150 -5
  188. package/scripts/cm-ai-run.mjs +88 -21
  189. package/scripts/cm-ai-scope-revision.test.mjs +341 -0
  190. package/scripts/cm-ai-spec-rebind.test.mjs +13 -0
  191. package/scripts/cm-ai-supersede.test.mjs +28 -0
  192. package/scripts/cm-ai-verification-auto.test.mjs +99 -0
  193. package/scripts/cm-announce-hook.mjs +35 -8
  194. package/scripts/cm-announce-hook.test.mjs +25 -0
  195. package/scripts/cm-autonomy.mjs +94 -0
  196. package/scripts/cm-autonomy.test.mjs +162 -0
  197. package/scripts/cm-challenge.test.mjs +61 -0
  198. package/scripts/cm-check-drive-files.mjs +1 -1
  199. package/scripts/cm-check-runtime.sh +60 -1
  200. package/scripts/cm-claude-developer-worker.test.mjs +56 -7
  201. package/scripts/cm-claude-install-layout.test.mjs +1 -1
  202. package/scripts/cm-claude-review-diagnostics.test.mjs +235 -0
  203. package/scripts/cm-claude-review-stream.test.mjs +13 -0
  204. package/scripts/cm-codex-developer-reconnect-notice.test.mjs +98 -0
  205. package/scripts/cm-codex-developer-worker.test.mjs +120 -0
  206. package/scripts/cm-codex-install-local-edit-guard.test.mjs +436 -0
  207. package/scripts/cm-codex-prompt-input.test.mjs +153 -0
  208. package/scripts/cm-codex-reconnect-notice.test.mjs +167 -0
  209. package/scripts/cm-commander-ledger.test.mjs +260 -0
  210. package/scripts/cm-commander-p2.test.mjs +295 -0
  211. package/scripts/cm-commander-preflight.mjs +84 -0
  212. package/scripts/cm-commander.mjs +116 -0
  213. package/scripts/cm-config-lock.mjs +35 -0
  214. package/scripts/cm-controlled-correction.test.mjs +10 -1
  215. package/scripts/cm-developer-failure-code.test.mjs +62 -0
  216. package/scripts/cm-display-task-id.test.mjs +41 -0
  217. package/scripts/cm-efficiency-presentation-delta.test.mjs +218 -0
  218. package/scripts/cm-execution-snapshot-reuse.test.mjs +115 -0
  219. package/scripts/cm-external-batch-host.test.mjs +4 -3
  220. package/scripts/cm-external-process-cleanup.test.mjs +128 -0
  221. package/scripts/cm-external-qa-fix.test.mjs +89 -7
  222. package/scripts/cm-external-review-reconciliation.test.mjs +11 -0
  223. package/scripts/cm-failover.mjs +48 -10
  224. package/scripts/cm-failover.test.mjs +46 -0
  225. package/scripts/cm-fix-cause-invocation.test.mjs +19 -4
  226. package/scripts/cm-fix-command-correction.mjs +17 -0
  227. package/scripts/cm-fix-command-correction.test.mjs +211 -0
  228. package/scripts/cm-fix-cooperative-closeout.test.mjs +87 -0
  229. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +217 -0
  230. package/scripts/cm-fix-drive.mjs +33 -5
  231. package/scripts/cm-fix-drive.test.mjs +49 -0
  232. package/scripts/cm-fix-host-review-assembly.test.mjs +197 -1
  233. package/scripts/cm-fix-host-review.test.mjs +21 -9
  234. package/scripts/cm-fix-host.mjs +26 -8
  235. package/scripts/cm-fix-monorepo-map.test.mjs +92 -0
  236. package/scripts/cm-fix-observation-task-id.test.mjs +122 -0
  237. package/scripts/cm-fix-regression-input-budget.test.mjs +111 -0
  238. package/scripts/cm-fix-repair-input-budget.test.mjs +119 -0
  239. package/scripts/cm-fix-review-file-paging.test.mjs +91 -0
  240. package/scripts/cm-fix-review-preflight.mjs +24 -0
  241. package/scripts/cm-fix-review-storage.test.mjs +233 -0
  242. package/scripts/cm-fix-review-verification-command.test.mjs +242 -0
  243. package/scripts/cm-fix-review-verification-evidence.test.mjs +218 -0
  244. package/scripts/cm-fix-review-verification-integration.test.mjs +81 -0
  245. package/scripts/cm-fix-review-verification-recovery.test.mjs +198 -0
  246. package/scripts/cm-fix-review-verification.test.mjs +146 -0
  247. package/scripts/cm-fix-revision-transport.test.mjs +81 -0
  248. package/scripts/cm-fix-source-correction.test.mjs +296 -0
  249. package/scripts/cm-fix-test-type-correction.mjs +18 -0
  250. package/scripts/cm-fix-test-type-correction.test.mjs +123 -0
  251. package/scripts/cm-fix-test-type-owner.test.mjs +208 -0
  252. package/scripts/cm-fix-test-type-verification-cost.test.mjs +66 -0
  253. package/scripts/cm-fix-type-import-correction.test.mjs +95 -0
  254. package/scripts/cm-fix-verification-diagnostic.test.mjs +200 -0
  255. package/scripts/cm-fix-verification-recovery.mjs +33 -0
  256. package/scripts/cm-host-qa-executor.test.mjs +77 -0
  257. package/scripts/cm-host-replay.test.mjs +176 -0
  258. package/scripts/cm-install-local-edit-guard.test.mjs +621 -0
  259. package/scripts/cm-install-manifest.sh +351 -0
  260. package/scripts/cm-live-evidence.test.mjs +59 -1
  261. package/scripts/cm-log-event.mjs +61 -10
  262. package/scripts/cm-log-event.test.mjs +121 -1
  263. package/scripts/cm-matt-skills.mjs +576 -0
  264. package/scripts/cm-matt-skills.test.mjs +550 -0
  265. package/scripts/cm-notify-command.test.mjs +42 -10
  266. package/scripts/cm-notify.mjs +14 -10
  267. package/scripts/cm-notify.test.mjs +581 -59
  268. package/scripts/cm-patrol.mjs +4 -1
  269. package/scripts/cm-patrol.test.mjs +23 -5
  270. package/scripts/cm-prd-answer-gaps.test.mjs +2 -2
  271. package/scripts/cm-prd-completion.test.mjs +56 -13
  272. package/scripts/cm-prd-design-phase.test.mjs +78 -8
  273. package/scripts/cm-prd-draft-save.test.mjs +12 -0
  274. package/scripts/cm-prd-draft.test.mjs +1 -1
  275. package/scripts/cm-prd-drive.mjs +13 -6
  276. package/scripts/cm-prd-drive.test.mjs +45 -1
  277. package/scripts/cm-prd-gate-diagnostic.test.mjs +2 -2
  278. package/scripts/cm-prd-host.mjs +10 -5
  279. package/scripts/cm-prd-host.test.mjs +4 -2
  280. package/scripts/cm-prd-inputs-replaced.test.mjs +1 -1
  281. package/scripts/cm-prd-review-disposition.test.mjs +124 -8
  282. package/scripts/cm-prd-revision.test.mjs +1 -1
  283. package/scripts/cm-prd-self-check-revision.test.mjs +1 -1
  284. package/scripts/cm-prd-self-check-rules.test.mjs +239 -0
  285. package/scripts/cm-prd-self-check.test.mjs +105 -5
  286. package/scripts/cm-prd-summary.test.mjs +24 -3
  287. package/scripts/cm-prd-task-grouping.test.mjs +6 -6
  288. package/scripts/cm-prd-tree-digest.test.mjs +74 -0
  289. package/scripts/cm-refactor-drive.mjs +2 -1
  290. package/scripts/cm-refactor-drive.test.mjs +9 -0
  291. package/scripts/cm-release-smoke.sh +1 -1
  292. package/scripts/cm-skill-hints-autowire.test.mjs +394 -0
  293. package/scripts/cm-skill-hints-exam.mjs +149 -0
  294. package/scripts/cm-skill-hints-install.test.mjs +168 -0
  295. package/scripts/cm-skill-hints.exam.json +706 -0
  296. package/scripts/cm-skill-hints.json +119 -0
  297. package/scripts/cm-skill-hints.mjs +669 -0
  298. package/scripts/cm-skill-hints.test.mjs +831 -0
  299. package/scripts/cm-skill-judge.mjs +181 -0
  300. package/scripts/cm-skill-judge.test.mjs +255 -0
  301. package/scripts/cm-specs-status.test.mjs +4 -2
  302. package/scripts/cm-start-check.mjs +323 -0
  303. package/scripts/cm-start-check.test.mjs +406 -0
  304. package/scripts/cm-task-gate.mjs +150 -29
  305. package/scripts/cm-task-gate.test.mjs +73 -1
  306. package/scripts/cm-task-id-grammar.test.mjs +66 -0
  307. package/scripts/cm-task-scope.test.mjs +308 -0
  308. package/scripts/cm-upgrade-compat-batch.test.mjs +172 -0
  309. package/scripts/cm-upgrade-compat.test.mjs +239 -0
  310. package/scripts/cm-workflow-config.mjs +12 -2
  311. package/scripts/fixtures/fix-verification-claude.mjs +44 -0
  312. package/scripts/fixtures/reviewed-integration.mjs +202 -0
  313. package/scripts/scan-public-safety.py +1 -0
  314. package/scripts/session-boundary.test.mjs +170 -0
  315. package/scripts/test-npm-install.py +14 -3
  316. package/scripts/test-shell-compat.sh +2 -0
  317. package/scripts/validate-public-repo.py +4 -0
  318. package/scripts/validate-test-cases.mjs +3 -2
  319. package/skills/cm-ai/SKILL.md +5 -2
  320. package/skills/cm-ai/references/N3-execute-task.md +1 -1
  321. package/skills/cm-ai/references/N4-review.md +2 -1
  322. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  323. package/skills/cm-ai/references/N8-finish.md +22 -0
  324. package/skills/cm-ai/references/js-host-qa-recovery.md +1 -1
  325. package/skills/cm-ai/references/js-host-recovery.md +79 -3
  326. package/skills/cm-ai/references/js-host.md +82 -16
  327. package/skills/cm-challenge/SKILL.md +65 -0
  328. package/skills/cm-challenge/evals/README.md +18 -0
  329. package/skills/cm-challenge/evals/trigger-cases.json +20 -0
  330. package/skills/cm-challenge/evals/trigger-config.json +28 -0
  331. package/skills/cm-challenge/references/examples.md +15 -0
  332. package/skills/cm-check/SKILL.md +5 -0
  333. package/skills/cm-check/references/js-host.md +2 -0
  334. package/skills/cm-fix/SKILL.md +12 -3
  335. package/skills/cm-fix/references/command-correction.md +67 -0
  336. package/skills/cm-fix/references/isolated-review.md +54 -0
  337. package/skills/cm-fix/references/js-host.md +62 -2
  338. package/skills/cm-fix/references/test-type-correction.md +72 -0
  339. package/skills/cm-fix/references/verification-recovery.md +114 -0
  340. package/skills/cm-idea/SKILL.md +2 -0
  341. package/skills/cm-idea/references/js-host.md +2 -0
  342. package/skills/cm-notify/SKILL.md +2 -0
  343. package/skills/cm-prd/SKILL.md +14 -9
  344. package/skills/cm-prd/references/brownfield.md +8 -1
  345. package/skills/cm-prd/references/change-mode.md +8 -1
  346. package/skills/cm-prd/references/greenfield.md +4 -0
  347. package/skills/cm-prd/references/js-change-recovery.md +14 -0
  348. package/skills/cm-prd/references/js-host.md +4 -2
  349. package/skills/cm-prd/references/spec-self-check.md +5 -1
  350. package/skills/cm-refactor/SKILL.md +8 -0
  351. package/skills/cm-refactor/references/js-host.md +2 -0
  352. package/skills/cm-test/SKILL.md +4 -0
  353. package/templates/dashboard/dashboard.html +2 -2
  354. package/templates/pixel/cm-pixel.html +1 -1
  355. package/templates/pixel/cm-pixel.sh +1 -1
  356. package/templates/pixel/dev/template.html +1 -1
  357. package/templates/statusline/cm-statusline.sh +1 -1
@@ -5,17 +5,24 @@ import {digest,json,need,shape,validIdentity,hex,id} from './effect-contract.mjs
5
5
  import {parseModelJson} from './model-configuration-file.mjs';
6
6
 
7
7
  export const CONTROL_RECOVERY_OPERATIONS=Object.freeze(['abandon_review','abandon_effect','develop_redo',
8
- 'bootstrap_review_recover','reconcile_review']);
8
+ 'bootstrap_review_recover','completion_rework','development_rework','revise_scope','reconcile_review']);
9
9
  export const CONTROL_FIX_RECOVERY_OPERATIONS=Object.freeze(['abandon_step','abandon_review','rediagnose',
10
10
  'rerun_blocked_step','recover_final_review','reconcile_review']);
11
+ // verification is optional so policies saved before it existed keep their exact
12
+ // digest; absent means the same as disabled. precheck enables the delivery
13
+ // verification gate for every launch of the run it is saved into; auto enables
14
+ // the same gate answered by the host (verification-auto.mjs), for unattended runs.
11
15
  export function readControlPolicy(raw){
12
- const value=json(raw);shape(value,['version','development','bootstrap','qa','qaFix']);
16
+ const value=json(raw);
17
+ shape(value,['version','development','bootstrap','qa','qaFix',...(Object.hasOwn(value,'verification')?['verification']:[])]);
13
18
  need(value.version===2&&['conversation','provider'].includes(value.development)
14
19
  &&['disabled','write'].includes(value.bootstrap)&&['disabled','run'].includes(value.qa)
15
20
  &&['disabled','manual','auto'].includes(value.qaFix),'invalid_input');
21
+ need(!Object.hasOwn(value,'verification')||['disabled','precheck','auto'].includes(value.verification),'invalid_input');
16
22
  need(value.qaFix==='disabled'||value.qa==='run','invalid_input');
17
23
  return value;
18
24
  }
25
+ export const policyVerificationPrecheck=policy=>policy?.verification==='precheck';
19
26
  export function readControlPolicyFile(file){
20
27
  const before=fs.lstatSync(file);
21
28
  need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1&&before.size<=65536,'invalid_input');
@@ -31,10 +38,20 @@ export function readControlPolicyFile(file){
31
38
  export function controlPolicyFromSnapshot(snapshot){
32
39
  return snapshot.records.find(row=>row.payload.type==='init')?.payload.config?.controlPolicy??null;
33
40
  }
34
- export function assertControlEntry(snapshot,policy){
41
+ // A run created with qa:"disabled" may turn QA on once after it completed: the
42
+ // launch policy equals the saved one except qa:"run". Everything else about the
43
+ // run stays bound to the saved policy (qa-attachment.mjs, cm-ai-run.mjs).
44
+ export function isControlQaUpgrade(saved,policy){
45
+ if(saved===null||policy===null)return false;
46
+ const before=readControlPolicy(saved),after=readControlPolicy(policy);
47
+ return before.qa==='disabled'&&after.qa==='run'&&digest({...before,qa:'run'})===digest(after);
48
+ }
49
+ export function assertControlEntry(snapshot,policy,{allowQaUpgrade=false}={}){
35
50
  const saved=controlPolicyFromSnapshot(snapshot);
36
51
  need((saved===null)===(policy===null),'fingerprint_mismatch');
37
- if(saved!==null)need(digest(readControlPolicy(saved))===digest(readControlPolicy(policy)),'fingerprint_mismatch');
52
+ if(saved===null||digest(readControlPolicy(saved))===digest(readControlPolicy(policy)))return null;
53
+ need(allowQaUpgrade&&isControlQaUpgrade(saved,policy),'fingerprint_mismatch');
54
+ return readControlPolicy(saved);
38
55
  }
39
56
  export function readControlTarget(raw){
40
57
  const v=json(raw);shape(v,['version','identity','state','code','packageDigest','effectId','invocationId','revision',
@@ -5,6 +5,7 @@ import {createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective} f
5
5
 
6
6
  import {readSpecificationMaterial} from './specification-material.mjs';
7
7
  import {readCarriedReview} from './reviewed-evidence-supersession-record.mjs';
8
+ import {splitRequirementReport} from './requirement-evidence.mjs';
8
9
 
9
10
  const LIMIT=10*1024*1024;
10
11
  const INSTRUCTIONS=`Implement the single task described by the JSON data below in the host-selected workspace.
@@ -26,6 +27,12 @@ retrospective reason and each candidate trigger and action are one line of at mo
26
27
  Without learningInput, return only outcome and reason. A blocked result may include reason explaining why implementation is impossible (string, at most 1000 UTF-8 bytes, no NUL); application and retrospective are optional when blocked.
27
28
  The top-level reason explains blocked outcomes; otherwise it must be null. Use null when no explanation is available.
28
29
  Use outcome blocked when implementation is not possible. Do not claim implementation if no implementation was made.
30
+ Always also return requirements: one item {requirement, satisfied, evidence, run, result} for each requirement written in the
31
+ task's description and verification (specification), evidence naming where it is met (file, test name, expected command result).
32
+ Use null when the task states none. The host runs the task's checks itself before development (baseline) and with only the
33
+ task's test files delivered (red), and checks tagged items against those runs: set run "red" on an item stating that a new
34
+ test fails before the implementation; set run "baseline" on an item stating the result before development, with result
35
+ "passed" or "failed" when the item states it; result is read only on a baseline item; otherwise run and result are null. Never claim a run you have not reasoned about.
29
36
  When supersededReview exists, it is read-only context: the last review of an earlier, superseded run of this task, not a verdict on this run. Avoid repeating its problems, but implement only the supplied task and scope.`;
30
37
 
31
38
  // The host owns instructions and workflow evidence. Reject contradictory
@@ -99,8 +106,9 @@ export function validateDeveloperValue(value,request) {
99
106
  retrospective:createCmAiTaskLearningRetrospective({...binding,...value.retrospective})};
100
107
  }
101
108
 
102
- export function createDeveloperRun({worker,requestedModel,provider,protectedCurrentSession=false}) {
109
+ export function createDeveloperRun({worker,requestedModel,provider,protectedCurrentSession=false,onRequirements=null}) {
103
110
  need(['codex','claude'].includes(provider),'invalid_provider');
111
+ need(onRequirements===null||typeof onRequirements==='function','invalid_input');
104
112
  need(typeof worker==='function');text(requestedModel);
105
113
  need(typeof protectedCurrentSession==='boolean'&&(!protectedCurrentSession||requestedModel==='current-session'));
106
114
  return async (raw,control)=>{
@@ -108,10 +116,13 @@ export function createDeveloperRun({worker,requestedModel,provider,protectedCurr
108
116
  need(r.requestedModel===requestedModel,'invalid_input');
109
117
  need(control?.signal&&typeof control.signal.aborted==='boolean','invalid_input');
110
118
  let providerThreadId;
111
- const envelope=(status,result=null,blockedReason=undefined)=>terminalFor({version:1,invocationId:r.invocationId,
119
+ const envelope=(status,result=null,blockedReason=undefined,failureCode=undefined)=>terminalFor({version:1,invocationId:r.invocationId,
112
120
  contextId:r.contextId,provider,effectiveModel:'unknown',status,
113
121
  accepted:!['unavailable','auth_required','permission_denied'].includes(status),result,
114
122
  ...(blockedReason===undefined?{}:{blockedReason}),
123
+ // Kept only when it is a plain code for a failed/unknown call without a result.
124
+ ...(failureCode!==undefined&&['failed','unknown'].includes(status)&&result===null&&blockedReason===undefined
125
+ &&typeof failureCode==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(failureCode)?{failureCode}:{}),
115
126
  ...(providerThreadId===undefined?{}:{providerThreadId})},r);
116
127
  const failed=(code,reason)=>envelope('failed',{code,reason,
117
128
  ...(protectedCurrentSession&&code==='invalid_result'?{retryable:true}:{})});
@@ -119,7 +130,7 @@ export function createDeveloperRun({worker,requestedModel,provider,protectedCurr
119
130
  need(!control.signal.aborted,'cancelled');
120
131
  let response;
121
132
  try{response=await worker({prompt:buildDeveloperPrompt(r,provider)},control);}
122
- catch{return envelope('unknown');}
133
+ catch(error){return envelope('unknown',null,undefined,error?.code);}
123
134
  if(control.signal.aborted||!response||typeof response!=='object'||Array.isArray(response))return envelope('unknown');
124
135
  try{response=json(response);}
125
136
  catch(error){
@@ -130,7 +141,10 @@ export function createDeveloperRun({worker,requestedModel,provider,protectedCurr
130
141
  if(response.status==='succeeded'){
131
142
  try{
132
143
  if(Object.hasOwn(response,'providerThread')){id(response.providerThread);providerThreadId=response.providerThread;}
133
- const result=validateDeveloperValue(response.value,r);
144
+ // The report goes to the host's gate; the journaled value keeps its contract.
145
+ const split=splitRequirementReport(response.value);
146
+ try{onRequirements?.(r.identity,split.items);}catch{/* a consumer never changes the terminal */}
147
+ const result=validateDeveloperValue(split.value,r);
134
148
  // Preserve the null failure result; the explanation is diagnostic only.
135
149
  return result.outcome==='blocked'?envelope('failed',null,result.reason):envelope('succeeded',result);
136
150
  }catch(error){return failed('invalid_result',error.code??'invalid_input');}
@@ -139,6 +153,6 @@ export function createDeveloperRun({worker,requestedModel,provider,protectedCurr
139
153
  return failed(response.code,response.reason??response.code);
140
154
  // A missing/ambiguous terminal may have performed writes. Never retry here.
141
155
  return envelope(['failed','unavailable','auth_required','permission_denied'].includes(response.status)
142
- ?response.status:'unknown');
156
+ ?response.status:'unknown',null,undefined,response.code);
143
157
  };
144
158
  }
@@ -4,8 +4,11 @@ import path from 'node:path';
4
4
  import {spawn} from 'node:child_process';
5
5
  import readline from 'node:readline';
6
6
  import {guidanceText} from './operator-guidance.mjs';
7
+ import {applyRateLimitResume,nextRateLimitRetry,rateLimitedReview,rateLimitRetriesDone,RATE_LIMIT_RETRY_ENV,RATE_LIMIT_EXPECTED_ENV,
8
+ RATE_LIMIT_PLAN_DIGEST_ENV,planFileFromArgv,planDigest,digestBytes,expectedReviewStop,readExpectedReviewStop} from './drive-rate-limit.mjs';
7
9
 
8
10
  export const stderr=line=>process.stderr.write(`[drive] ${line}\n`);
11
+ const waitWords=ms=>ms<60000?`${Math.max(1,Math.ceil(ms/1000))} 秒`:`${Math.round(ms/60000)} 分钟`;
9
12
  export const stop=(code,line)=>{stderr(line);process.exit(code);};
10
13
  export function planCheckTimeout(plan,item=null){
11
14
  const valid=value=>Number.isInteger(value)&&value>=1&&value<=3600000;
@@ -25,9 +28,23 @@ export function loadPlanFile({argv=process.argv.slice(2),name,known}){
25
28
  if(at===-1||!argv[at+1]||!operation)stop(2,`用法: ${name} --plan PLAN.json <operation>`);
26
29
  if(!known.has(operation))stop(2,`不认识的步骤 ${operation};宿主支持的见 ${name.replace('-drive','-host')} --help`);
27
30
  const planPath=path.resolve(argv[at+1]),base=path.dirname(planPath);
28
- let plan;
29
- try{plan=JSON.parse(fs.readFileSync(planPath,'utf8'));}
31
+ let plan,bytes;
32
+ try{bytes=fs.readFileSync(planPath);plan=JSON.parse(bytes.toString('utf8'));}
30
33
  catch(error){stop(2,`读不了 ${planPath}: ${error.code??error.message}`);}
34
+ // A rate-limit check or re-run is bound to the PLAN bytes the waiting driver started from.
35
+ const bound=process.env[RATE_LIMIT_PLAN_DIGEST_ENV];
36
+ if(bound&&digestBytes(bytes)!==bound)stop(2,'状态已变,未自动重试:PLAN 文件在限流等待期间被改过');
37
+ // A rate-limit re-run (driveHost below) resumes the run its first command created,
38
+ // and is only ever a decision bound to the frozen review stop it waited for.
39
+ if(plan&&typeof plan==='object')applyRateLimitResume(plan);
40
+ const expected=rateLimitRetriesDone()>0?readExpectedReviewStop():null;
41
+ if(rateLimitRetriesDone()>0){
42
+ // The single-task driver retries with a bound decision, the batch driver with retry_review.
43
+ const retryOperation=known.has('decision')?'decision':'retry_review';
44
+ if(!expected||retryOperation==='retry_review'&&!expected.batch)stop(2,'状态已变,未自动重试:缺少等待时冻结的审查限流前置条件');
45
+ plan.packageDigest=expected.packageDigest;
46
+ return {operation:retryOperation,plan,base,expectedReviewStop:expected};
47
+ }
31
48
  return {operation,plan,base};
32
49
  }
33
50
 
@@ -65,25 +82,107 @@ export function deliberatelyUnanswered(message){
65
82
  // The long fallback covers hosts that cannot advertise individual phase budgets.
66
83
  export const DRIVE_LIVENESS_DEFAULTS=Object.freeze({startupMs:60000,operationMs:21600000,
67
84
  heartbeatMs:30000,graceMs:30000,closeMs:5000,killMs:1000,pollMs:250});
68
- export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null,liveness={}}){
85
+ // rateLimitRetry (cm-ai drivers only, drive-rate-limit.mjs; 'batch' for the batch driver): a review the provider
86
+ // rate limited is redispatched by re-running this same driver command after a
87
+ // wait, without printing the interim result or notifying; the re-run's result is
88
+ // the one printed. Only the runner's automatic pending_review state qualifies.
89
+ export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null,liveness={},sessionBoundary=null,rateLimitRetry=false}){
69
90
  const budget={...DRIVE_LIVENESS_DEFAULTS,...liveness};
70
91
  for(const value of Object.values(budget))if(!Number.isSafeInteger(value)||value<1)throw Error('driver_liveness_invalid');
71
92
  const ownGroup=process.platform!=='win32';
93
+ // Notices on: name the project and session they will show, so a notice can be matched to this session.
94
+ import('../notify.mjs').then(({notifyIdentityLine})=>{const line=notifyIdentityLine({cwd,args});if(line)stderr(line);}).catch(()=>{});
72
95
  const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe'],detached:ownGroup,
73
96
  env:{...process.env,CM_HOST_HEARTBEAT:'1'}});
74
97
  const control=new AbortController();
75
98
  child.stderr.on('data',chunk=>process.stderr.write(chunk));
76
- let done=false,refused=false,rejected=null,unanswered=false,finalRow=null,noticed=false,failureCode=null;
99
+ let done=false,refused=false,rejected=null,unanswered=false,finalRow=null,finalAt=null,noticed=false,failureCode=null,retry=null;
100
+ const retriesDone=rateLimitRetriesDone();
77
101
  let sessionId=null,ready=false,heartbeat=false,lastBeat=0,waitingFor='drive',stopping=false,closed=false;
78
102
  let deadline=Date.now()+budget.startupMs,phase='startup',closeDeadline=null,killTimer=null,forceTimer=null;
79
103
  // Optional notices never change the result or make watchdog failures successful.
104
+ // A stop that is not a person's decision waits waitMinutes and is dropped if
105
+ // the session moves on (notifyLater); a rate limit after this driver's own
106
+ // retries is sent at once and says how many were tried.
107
+ const sendNotice=(fields,mod)=>{
108
+ // Under the standing authorization the session retries on its own: the stop still waits.
109
+ if(!failureCode&&rateLimitedReview(finalRow)&&retriesDone>0)fields={...fields,rateLimitRetries:retriesDone,...(fields.autonomous?{}:{delivery:'now'})};
110
+ if(fields.delivery!=='later')return mod.notify(fields);
111
+ // An unsafe pending directory already produced its once-a-day fault notice
112
+ // and the stop is not sent; any other failure to schedule (state busy, write
113
+ // failed) sends the stop at once rather than losing it.
114
+ return mod.notifyLater(fields).then(result=>result.scheduled||['off','sent_now','invalid_key','pending_dir_unsafe'].includes(result.reason)?result:mod.notify(fields));
115
+ };
80
116
  const notice=failure=>{
81
117
  if(noticed)return;noticed=true;
118
+ // A timed retry the host refused as stale dispatched nothing: the run moved
119
+ // on without it, so there is nothing new to tell the person.
120
+ if(!failure&&retriesDone>0&&finalRow?.result?.staleRetry===true)return;
121
+ if(retry!==null&&!failure){waitAndRetry();return;}
122
+ if(retry!==null)releaseRetry();
82
123
  if(rejected!==null)failure='host_response_rejected';else if(!failure&&unanswered&&!finalRow)failure='host_request_unanswered';
83
- import('../notify.mjs').then(({driveNotice,notify})=>{
124
+ import('../notify.mjs').then(mod=>{
125
+ const {driveNotice,driveProgressKey,clearAttention}=mod;
84
126
  const fields=driveNotice({host,cwd,args,operation,row:finalRow,failure});
85
- return fields?notify(fields):null;
127
+ if(fields)return sendNotice(fields,mod);
128
+ const progress=driveProgressKey({host,cwd,args,operation,row:finalRow,failure});
129
+ // The step moved on when its final result arrived, not when the host closed later.
130
+ return progress&&finalAt!==null?clearAttention(progress,{before:finalAt}):null;
131
+ }).catch(()=>{});
132
+ };
133
+ // The interim rate-limited result is printed only if the re-run cannot start.
134
+ const printFinal=row=>{
135
+ process.stdout.write(JSON.stringify(row,null,2)+'\n');
136
+ // The driver prints the session-boundary verdict itself so the model only relays it;
137
+ if(typeof sessionBoundary==='function'&&!row.error){let block=null;try{block=sessionBoundary(row.result,operation);}catch{stderr('会话边界结论生成失败;请按技能输出模板手写三行结论(业务结果不受影响)');}
138
+ // stderr, not stdout: callers parse stdout as one JSON result.
139
+ if(typeof block==='string'&&block)process.stderr.write(block+'\n');}
140
+ const guidance=guidanceText(row.result);if(guidance)stderr(guidance);
141
+ if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
142
+ if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
143
+ };
144
+ // A host failure after the result was chosen for a retry: show it as usual.
145
+ const releaseRetry=()=>{printFinal(finalRow);retry=null;};
146
+ // The timed re-run: after the wait, the same driver command is run again as a
147
+ // decision carrying the frozen stop (round identity, reviewed package, failed
148
+ // invocation). The host checks it under the run's writer lock and either
149
+ // redispatches exactly that review or answers staleRetry without any effect.
150
+ const planFile=planFileFromArgv();
151
+ // The PLAN bytes are frozen when the rate-limited result arrives, not when the host closes.
152
+ let retryPlanDigest=null;
153
+ const waitAndRetry=()=>{
154
+ const pending=retry,frozenPlan=retryPlanDigest,expected=expectedReviewStop(finalRow);
155
+ // Backstop: if this waiting driver is killed, the stop is still sent once
156
+ // the wait and waitMinutes have passed; the re-run's start cancels it.
157
+ import('../notify.mjs').then(mod=>{
158
+ const fields=mod.driveNotice({host,cwd,args,operation,row:finalRow,failure:null});
159
+ return fields?mod.notifyLater({...fields,rateLimitWaiting:true},{extraDelayMs:pending.delayMs}):null;
86
160
  }).catch(()=>{});
161
+ // Not retried: show the original result and decide its notice as usual.
162
+ const giveUp=reason=>{
163
+ stderr(`状态已变,未自动重试:${reason};下面是限流时的原结果`);
164
+ printFinal(finalRow);process.exitCode=hostResponseFailed(finalRow)?1:0;
165
+ import('../notify.mjs').then(mod=>{const fields=mod.driveNotice({host,cwd,args,operation,row:finalRow,failure:null});
166
+ return fields?sendNotice(fields,mod):null;}).catch(()=>{});
167
+ };
168
+ setTimeout(()=>{
169
+ if(!frozenPlan||!expected||planDigest(planFile)!==frozenPlan){giveUp('PLAN 文件在等待期间被改过或读不了');return;}
170
+ stderr(`审查限流等待结束,按等待时那次限流重派这一次审查(第 ${pending.attempt}/${pending.max} 次);运行已变时宿主不派发任何操作`);
171
+ let child;
172
+ try{child=spawn(process.execPath,[...process.execArgv,process.argv[1],...process.argv.slice(2)],{cwd:process.cwd(),stdio:'inherit',
173
+ env:{...process.env,[RATE_LIMIT_PLAN_DIGEST_ENV]:frozenPlan,[RATE_LIMIT_EXPECTED_ENV]:JSON.stringify(expected),
174
+ [RATE_LIMIT_RETRY_ENV]:String(pending.attempt)}});}
175
+ catch{child=null;}
176
+ const failed=()=>{
177
+ stderr('自动重派没能启动:下面是限流时的原结果,请回到会话说「继续」');
178
+ printFinal(finalRow);process.exitCode=hostResponseFailed(finalRow)?1:0;
179
+ import('../notify.mjs').then(mod=>{const fields=mod.driveNotice({host,cwd,args,operation,row:finalRow,failure:null});
180
+ return fields?mod.notify({...fields,rateLimitWaiting:true}):null;}).catch(()=>{});
181
+ };
182
+ if(!child){failed();return;}
183
+ child.once('error',failed);
184
+ child.once('exit',(code,signal)=>{process.exitCode=code??(signal?1:0);});
185
+ },pending.delayMs);
87
186
  };
88
187
  const signalOwnHost=(signal,cleanup=false)=>{
89
188
  if((closed&&!cleanup)||!child.pid)return;
@@ -156,6 +255,10 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
156
255
  if(row.type==='host_ready'){
157
256
  if(ready)return;
158
257
  ready=true;sessionId=row.sessionId;heartbeat=Boolean(row.heartbeat);lastBeat=Date.now();
258
+ // The host accepted a new step of this session: a deferred stop from before is no longer news.
259
+ const startedAt=Date.now();
260
+ import('../notify.mjs').then(({driveAttentionKey,cancelPendingNotice})=>{
261
+ const key=driveAttentionKey({host,cwd,args,operation});return key?cancelPendingNotice(key,{before:startedAt}):null;}).catch(()=>{});
159
262
  phase='operation';deadline=Date.now()+budget.operationMs;
160
263
  if(beforeRequest){
161
264
  let refusal;
@@ -197,11 +300,12 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
197
300
  if(typeof inFlight?.requestId==='string')waitingFor=inFlight.requestId;
198
301
  phaseBudget(inFlight);stderr(`host_busy:上一步仍在执行,继续等待 ${waitingFor} 的结果`);return;
199
302
  }
200
- done=true;finalRow=row;control.abort();
201
- process.stdout.write(JSON.stringify(row,null,2)+'\n');
202
- const guidance=guidanceText(row.result);if(guidance)stderr(guidance);
203
- if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
204
- if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
303
+ done=true;finalRow=row;finalAt=Date.now();control.abort();
304
+ retry=rateLimitRetry&&!deliberateStop&&!refused&&!unanswered&&rejected===null?nextRateLimitRetry(row,process.env,rateLimitRetry==='batch'?'batch':'single'):null;
305
+ if(retry)retryPlanDigest=planFile?planDigest(planFile):null;
306
+ if(retriesDone>0&&row.result?.staleRetry===true)stderr('状态已变,未自动重试:宿主核对运行已不停在等待时那次审查限流,没有派发任何操作');
307
+ if(retry)stderr(`审查被限流(reviewer_rate_limited),${waitWords(retry.delayMs)}后在原运行自动重派审查(第 ${retry.attempt}/${retry.max} 次);等待期间不推送,也不用你处理`);
308
+ else printFinal(row);
205
309
  process.exitCode=deliberateStop||refused?2:hostResponseFailed(row)||rejected!==null||unanswered?1:0;
206
310
  // Normal EOF follows a final result. The explicit force compatibility
207
311
  // path for a legacy host is separately logged by closeHost above.
@@ -0,0 +1,105 @@
1
+ // Driver-side wait-and-redispatch for a review the provider rate limited
2
+ // (reviewFailure reviewer_rate_limited, 2026-10-26: Codex 429 stopped a batch
3
+ // while the weekly quota was at 3%). It only re-runs the same driver command in
4
+ // resume mode, i.e. what a person does by saying "继续": the runner's own rules
5
+ // decide whether that dispatches a review. It never sends abandon_review, never
6
+ // spends a review round and needs no extra permission: the runner grants one
7
+ // automatic no-verdict redispatch per review round (pending_review), and a
8
+ // second rate limit in the same round comes back as blocked, which stops here.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import {createHash} from 'node:crypto';
12
+
13
+ export const RATE_LIMIT_RETRY_ENV='CM_DRIVE_RATE_LIMIT_RETRY';
14
+ // SHA-256 of the PLAN bytes the waiting driver started from; a re-run reading
15
+ // other bytes stops before launching anything.
16
+ export const RATE_LIMIT_PLAN_DIGEST_ENV='CM_DRIVE_RATE_LIMIT_PLAN_DIGEST';
17
+ export const RATE_LIMIT_DELAYS_ENV='CM_DRIVE_RATE_LIMIT_DELAYS_MS';
18
+ // At most three waits, 15, 10 and 5 minutes, 30 minutes in all. The first is the
19
+ // longest: on 2026-10-26 the review succeeded when resumed about 15 minutes after
20
+ // the 429, and a round has only one automatic redispatch, so it should not be spent
21
+ // too early.
22
+ export const RATE_LIMIT_DEFAULT_DELAYS_MS=Object.freeze([900000,600000,300000]);
23
+ export const RATE_LIMIT_MAX_TOTAL_MS=1800000;
24
+ // Operations whose rate-limited stop is retried (cm-ai-conversation-entry.mjs: advance and
25
+ // decision dispatch the review; resume only reports the state and never dispatches).
26
+ // The single-task retry is a bound decision; the batch retry is the batch host's
27
+ // retry_review, checked under batch.lock and the member's writer lock.
28
+ // The retry itself is always a decision bound to the frozen stop (never the
29
+ // original advance), so it can only redispatch that one review.
30
+ export const RATE_LIMIT_RETRY_OPERATIONS=Object.freeze(['advance','decision']);
31
+
32
+ const obj=value=>value&&typeof value==='object'&&!Array.isArray(value)?value:{};
33
+ // Overridable (tests use milliseconds); anything out of range keeps the default.
34
+ export function rateLimitDelays(env=process.env){
35
+ const raw=env[RATE_LIMIT_DELAYS_ENV];
36
+ if(typeof raw!=='string'||!raw)return [...RATE_LIMIT_DEFAULT_DELAYS_MS];
37
+ const values=raw.split(',').map(item=>Number(item.trim()));
38
+ const valid=values.length>=1&&values.length<=3&&values.every(value=>Number.isSafeInteger(value)&&value>=1)
39
+ &&values.reduce((sum,value)=>sum+value,0)<=RATE_LIMIT_MAX_TOTAL_MS;
40
+ return valid?values:[...RATE_LIMIT_DEFAULT_DELAYS_MS];
41
+ }
42
+ export function rateLimitRetriesDone(env=process.env){
43
+ const value=Number(env[RATE_LIMIT_RETRY_ENV]);
44
+ return Number.isSafeInteger(value)&&value>=1&&value<=RATE_LIMIT_DEFAULT_DELAYS_MS.length?value:0;
45
+ }
46
+ // A rate-limited review end, whatever state the runner put it in.
47
+ export const rateLimitedReview=row=>!row?.error&&obj(row?.result).reviewFailure==='reviewer_rate_limited';
48
+ // Only the runner's own automatic redispatch state qualifies.
49
+ export const rateLimitRetryable=row=>{
50
+ const result=obj(row?.result);
51
+ // A refused (e.g. stale) request dispatched nothing and is never retried.
52
+ return rateLimitedReview(row)&&result.outcome!=='rejected'&&result.staleRetry!==true
53
+ &&result.state==='pending_review'&&result.code==='review_provider_failed'&&result.pendingAction==='resume';
54
+ };
55
+ // {attempt,max,delayMs} for the next wait, or null.
56
+ // kind 'batch': the batch driver, whose retry_review also needs the batch target.
57
+ export function nextRateLimitRetry(row,env=process.env,kind='single'){
58
+ const expected=expectedReviewStop(row);
59
+ if(!rateLimitRetryable(row)||expected===null||kind==='batch'&&!expected.batch)return null;
60
+ const delays=rateLimitDelays(env),done=rateLimitRetriesDone(env);
61
+ return done<delays.length?{attempt:done+1,max:delays.length,delayMs:delays[done]}:null;
62
+ }
63
+ // The re-run resumes the run the first command created (same session).
64
+ export function applyRateLimitResume(plan,env=process.env){
65
+ if(rateLimitRetriesDone(env)===0||plan?.mode!=='create')return plan;
66
+ plan.mode='resume';plan.originalHostContext=plan.hostContext;
67
+ return plan;
68
+ }
69
+ // Driver eligibility: an operation that can dispatch the review, and a plan the
70
+ // resume re-run accepts unchanged (create-only supersede flags are left alone).
71
+ export function rateLimitRetryEligible(operation,plan){
72
+ const permissions=Array.isArray(plan?.permissions)?plan.permissions:[];
73
+ return RATE_LIMIT_RETRY_OPERATIONS.includes(operation)
74
+ &&!permissions.some(flag=>typeof flag==='string'&&(flag.startsWith('--supersede')||flag==='--accept-superseded-code-drift'));
75
+ }
76
+
77
+ export const digestBytes=bytes=>createHash('sha256').update(bytes).digest('hex');
78
+ // The PLAN file a driver command names (--plan <file>), as the driver resolves it.
79
+ export function planFileFromArgv(argv=process.argv.slice(2),cwd=process.cwd()){
80
+ const at=argv.indexOf('--plan');
81
+ return at!==-1&&typeof argv[at+1]==='string'&&argv[at+1]?path.resolve(cwd,argv[at+1]):null;
82
+ }
83
+ export function planDigest(file){try{return digestBytes(fs.readFileSync(file));}catch{return null;}}
84
+ const text=value=>typeof value==='string'&&value?value:null;
85
+ // The frozen precondition a timed retry sends with its decision (the cm-ai host
86
+ // checks it under the run's writer lock, cm-ai-conversation-entry.mjs
87
+ // rateLimitStopMatches): the round's identity, the reviewed package and the
88
+ // failed review invocation. null when the result does not carry all of them.
89
+ export const RATE_LIMIT_EXPECTED_ENV='CM_DRIVE_RATE_LIMIT_EXPECTED';
90
+ // A batch stop (cm-ai-batch-run.mjs withReviewRetryTarget) also carries its batch
91
+ // target: the member taskKey and the digest of the batch log when it stopped.
92
+ export function expectedReviewStop(row){
93
+ const result=obj(row?.result),identity=obj(result.identity),target=obj(result.reviewRetryTarget);
94
+ if(!['repositoryId','runId','taskId'].every(key=>text(identity[key]))||!Number.isSafeInteger(identity.attempt)
95
+ ||!/^[a-f0-9]{64}$/.test(result.packageDigest??'')||!text(result.reviewInvocationId))return null;
96
+ const batch=text(target.taskKey)&&/^[a-f0-9]{64}$/.test(target.batchDigest??'')?{taskKey:target.taskKey,batchDigest:target.batchDigest}:null;
97
+ return {identity:{repositoryId:identity.repositoryId,runId:identity.runId,taskId:identity.taskId,attempt:identity.attempt},
98
+ packageDigest:result.packageDigest,invocationId:result.reviewInvocationId,...(batch?{batch}:{})};
99
+ }
100
+ export function readExpectedReviewStop(env=process.env){
101
+ const raw=env[RATE_LIMIT_EXPECTED_ENV];if(typeof raw!=='string'||!raw)return null;
102
+ let value;try{value=JSON.parse(raw);}catch{return null;}
103
+ return expectedReviewStop({result:{identity:value?.identity,packageDigest:value?.packageDigest,reviewInvocationId:value?.invocationId,
104
+ ...(value?.batch?{reviewRetryTarget:value.batch}:{})}});
105
+ }