@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,4 +1,7 @@
1
- import {readQaConfigRevision} from './qa-config-revision.mjs';
1
+ import {readExecutionPolicy} from './execution-policy.mjs';
2
+ import {readExternalModels} from './external-models.mjs';
3
+ import {beforeFirstQaRound,readQaConfigRevision} from './qa-config-revision.mjs';
4
+ import {readCloseoutPolicy} from './knowledge-closeout.mjs';
2
5
  import {readQaAttachment} from './qa-attachment.mjs';
3
6
  // Trusted synthetic fixture host; explicit V2 supports isolated task-file writes.
4
7
  import { randomUUID } from 'node:crypto';
@@ -6,22 +9,29 @@ import { types } from 'node:util';
6
9
  import fs from 'node:fs';
7
10
  import path from 'node:path';
8
11
  import {createRequire} from 'node:module';
9
- import {verifySpecificationMaterial} from './specification-material.mjs';
10
- import { captureReviewBaseline, createReviewPackage, verifyReviewPackage } from './review-package.mjs';
11
- import { digest,need,shape,id,text,json,freeze,arrayItems,validIdentity,validTaskLearningInput,validCallTimeout,requestFor,terminalFor,failureCode } from './effect-contract.mjs';
12
- import { reviewResult,reviewReceipt } from './review-runner.mjs';
12
+ import {verifySpecificationMaterial,boundSpecificationMaterial,inspectSpecificationDrift,describeSpecificationDrift,
13
+ readSpecificationRebind} from './specification-material.mjs';
14
+ import { captureReviewBaseline, captureReviewInventory, compareReviewBaseline, createReviewPackage, verifyReviewPackage, verifyCompletionReviewPackage, validChecks, readReviewSourceFiles } from './review-package.mjs';
15
+ import { digest,need,shape,id,text,json,freeze,arrayItems,validIdentity,validTaskLearningInput,validCallTimeout,requestFor,terminalFor,failureCode,
16
+ JOURNAL_PAYLOAD_LIMIT,developCheckpointReserve,taskReviewScope,boundedReason } from './effect-contract.mjs';
17
+ import { reviewResult,reviewReceipt,boundReviewText,reviewPaths } from './review-runner.mjs';
13
18
  import { checkCompletion } from './gate-bridge.mjs';
14
19
  import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
15
- MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,completedEffectCount,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage } from './durable-runner-state.mjs';
20
+ MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage,
21
+ reviewRetrySpent,abandonableReviewResult,developBudget,developBudgetExhausted,
22
+ completionBlockCount,completionRetriesExhausted,supersededReviewPayload,bootstrapReviewRecoverable } from './durable-runner-state.mjs';
16
23
  import {commitRunnerFixture} from './task-commit.mjs';
17
- import {inspectProviderReview,hasProviderReviewResult} from './provider-review-observation.mjs';
24
+ import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure} from './provider-review-observation.mjs';
18
25
  import {attachCmAiTaskLearningApplicationEvidence,attachCmAiTaskLearningEvidence,
19
26
  readCmAiTaskLearningApplication} from './cm-ai-context-refresh.mjs';
20
27
  import {readCmAiProjectLearningWriteback,writeCmAiProjectLearning} from './cm-ai-learning-writer.mjs';
21
28
  import {verifyCmAiTaskLearningHandoff,writeCmAiTaskLearningHandoff} from './cm-ai-learning-handoff-writer.mjs';
29
+ import {implementationSha256,loadHandoff} from '../../../scripts/cm-task-gate.mjs';
22
30
  import {createHostHandoff} from './host-handoff.mjs';
23
- import {inspectFixCodeAssociation} from './fix-code-association.mjs';
31
+ import {inspectFixCodeAssociation,explainCompletedDelivery} from './fix-code-association.mjs';
32
+ import {approvedReviewAt,completedReviewedDeliveries,fixReviewedAt,resolveDeliverySteps} from './reviewed-deliveries.mjs';
24
33
  import {validateAcceptedFix} from './accepted-fix.mjs';
34
+ import {appendFits} from './execution-store-limits.mjs';
25
35
  import {inspectCmAiQaFailure} from './cm-ai-qa-log.mjs';
26
36
  import {readHostQaFixHistory} from './host-qa-fix.mjs';
27
37
  import {publishHostReview} from './host-review-file.mjs';
@@ -29,6 +39,7 @@ import {reviewExclusions} from './effect-contract.mjs';
29
39
  import {bootstrapConfiguration,readBootstrapEvidence} from './host-bootstrap.mjs';
30
40
  import {validateCodeProjectPaths,assertCodeProjectSelections} from './code-projects.mjs';
31
41
  import {readEvidenceSupersession} from './reviewed-evidence-supersession-record.mjs';
42
+ import {readReconciliationReceipt} from './review-reconciliation.mjs';
32
43
 
33
44
  // Keep default V1 imports free of SQLite initialization/warnings. Native ownership
34
45
  // is loaded synchronously only at the explicit V2 boundary (Node24.14+).
@@ -82,6 +93,38 @@ function observePromise(value,onFulfilled,onRejected) {
82
93
  }
83
94
  }
84
95
  const ignorePromiseResult=()=>{};
96
+ // Reviewer budgets go up to 3,600,000 ms; the host adds its cleanup margin.
97
+ export const MAX_REVIEW_BOUND_MS=3600000+60000;
98
+ // What the user does next for each retryable reviewer failure class. The class
99
+ // itself is also journaled in reviewInvocation.result.inspection.failure.
100
+ const REVIEW_FAILURE_HINTS=Object.freeze({
101
+ reviewer_auth_failed:'审查 CLI 未登录或凭证失效;先在本机重新登录审查 CLI,再恢复原 run 重派本轮审查',
102
+ reviewer_billing_error:'审查账号额度或计费不可用;恢复额度后再恢复原 run 重派本轮审查',
103
+ reviewer_rate_limited:'审查请求被限流或额度用尽;等额度恢复后再恢复原 run 重派本轮审查',
104
+ reviewer_server_error:'审查服务端错误或过载;稍后恢复原 run 重派本轮审查',
105
+ reviewer_model_not_found:'审查模型不存在或当前账号不可用;模型已绑定原 run 配置,确认账号可用该模型后恢复,换模型需新建运行',
106
+ reviewer_api_error:'审查 API 返回错误且没有结论;核对审查 CLI 账号与网络后恢复原 run 重派本轮审查',
107
+ reviewer_provider_failed:'审查进程报告失败且没有结论;核对审查 CLI 后恢复原 run 重派本轮审查',
108
+ reviewer_exited:'审查进程没有给出结论就退出;核对审查 CLI 能否正常运行后恢复原 run 重派本轮审查',
109
+ reviewer_stream_unrecognized:'审查 CLI 输出了无法识别的事件(常见于 CLI 升级);核对 CLI 版本后恢复原 run 重派本轮审查',
110
+ contradictory_verdict:'审查结论与 finding 等级矛盾:approved 不能带 P0–P2,changes_requested 至少要有一条 P0–P2;本轮结论作废并重派',
111
+ invalid_finding_path:'审查 finding 的 path 不在 examinedPaths 或 handoff 路径内;本轮结论作废并重派',
112
+ missing_material:'审查没有原样复制 examinedPaths;本轮结论作废并重派',
113
+ review_package_mismatch:'审查没有原样复制 packageDigest;本轮结论作废并重派',
114
+ invalid_finding_severity:'审查 finding 的 severity 不是 P0–P3;本轮结论作废并重派',
115
+ invalid_finding_id:'审查 finding 的 id 不合格式;本轮结论作废并重派',
116
+ invalid_finding_shape:'审查 finding 字段不全或重复;本轮结论作废并重派'});
117
+ const reviewFailureReason=failure=>`${failure}: ${REVIEW_FAILURE_HINTS[failure]??'审查失败且没有可用结论'}`;
118
+ // A verdict the review round ends on names why, instead of a bare code.
119
+ const verdictReason=(prefix,summary)=>`${prefix}:${String(summary).replace(/[\x00-\x1f\x7f]/g,' ').slice(0,300)}`;
120
+ const HALTED_SPEC_DRIFT='规格在本运行执行中途变化,运行已停在 blocked/spec_drift,不能继续或换绑。'
121
+ +'出口:用 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做;本运行改动的代码需还原,或加 --accept-superseded-code-drift 作为已有代码记录。';
122
+ const safeReason=error=>{
123
+ if(error===null||typeof error!=='object'||types.isProxy(error))return null;
124
+ const descriptor=Object.getOwnPropertyDescriptor(error,'message');
125
+ return descriptor&&Object.hasOwn(descriptor,'value')&&typeof descriptor.value==='string'
126
+ &&descriptor.value.length<=8192&&!/[\r\n\0]/.test(descriptor.value)?descriptor.value:null;
127
+ };
85
128
 
86
129
  export function createTaskRunner(options) {
87
130
  const taskMode=options && Object.hasOwn(options,'taskCompletion');
@@ -95,8 +138,13 @@ export function createTaskRunner(options) {
95
138
  if(options && Object.hasOwn(options,'bootstrap'))optionKeys.push('bootstrap');
96
139
  if(options && Object.hasOwn(options,'codeProjectPaths'))optionKeys.push('codeProjectPaths');
97
140
  if(options && Object.hasOwn(options,'verificationGate'))optionKeys.push('verificationGate');
141
+ if(options && Object.hasOwn(options,'providerDevelopment'))optionKeys.push('providerDevelopment');
142
+ if(options && Object.hasOwn(options,'knowledgeCloseout'))optionKeys.push('knowledgeCloseout');
143
+ if(options && Object.hasOwn(options,'executionPolicy'))optionKeys.push('executionPolicy');
144
+ if(options && Object.hasOwn(options,'externalModels'))optionKeys.push('externalModels');
98
145
  if(invocationMode)optionKeys.push('reviewInvocation');
99
146
  shape(options,optionKeys);
147
+ need(options.providerDevelopment===undefined||typeof options.providerDevelopment==='boolean','invalid_input');
100
148
  const {check,commit}=options;need(typeof check==='function' && (taskMode||typeof commit==='function'));
101
149
  // Opt-in gate between the task's own checks and the independent review. It may
102
150
  // only block: passing it grants nothing and never substitutes for that review.
@@ -126,12 +174,18 @@ export function createTaskRunner(options) {
126
174
  if(invocationMode)id(r.adapterId);
127
175
  return {...v,...(invocationMode?{adapterId:r.adapterId}:{}),run};
128
176
  });
129
- let invocationConfig=null,authorize=null,liveHostContextId=null;
177
+ let invocationConfig=null,authorize=null,liveHostContextId=null,reviewTimeoutMs=null;
130
178
  if(invocationMode){
131
179
  need(reviewers.length===1&&['codex','claude'].includes(reviewers[0].provider)&&reviewers[0].allowed&&reviewers[0].available,'runner_invocation');
132
180
  shape(options.reviewInvocation,['developerThreadId','excludedThreadIds','authorize',
133
- ...(Object.hasOwn(options.reviewInvocation,'hostContextId')?['hostContextId']:[])]);
181
+ ...['hostContextId','timeoutMs'].filter(key=>Object.hasOwn(options.reviewInvocation,key))]);
134
182
  liveHostContextId=options.reviewInvocation.hostContextId??null;
183
+ // Transient like hostContextId, never journaled: the host sizes the review
184
+ // race above its reviewer's own budget, which a resumed run may raise.
185
+ if(Object.hasOwn(options.reviewInvocation,'timeoutMs')){
186
+ reviewTimeoutMs=options.reviewInvocation.timeoutMs;
187
+ need(Number.isSafeInteger(reviewTimeoutMs)&&reviewTimeoutMs>=1&&reviewTimeoutMs<=MAX_REVIEW_BOUND_MS,'runner_invocation');
188
+ }
135
189
  if(liveHostContextId!==null){id(liveHostContextId);
136
190
  need(![developer.contextId,...reviewers.flatMap(r=>r.contexts)].includes(liveHostContextId),'not_independent');}
137
191
  authorize=options.reviewInvocation.authorize;need(typeof authorize==='function','runner_invocation');
@@ -144,7 +198,10 @@ export function createTaskRunner(options) {
144
198
  }
145
199
  let metadata=json({...config,developer:{provider:developer.provider,requestedModel:developer.requestedModel,contextId:developer.contextId},
146
200
  reviewers:reviewers.map(({run,...r})=>r),...(invocationMode?{reviewInvocation:invocationConfig}:{}),
147
- ...(Object.hasOwn(options,'taskLearning')?{taskLearning:json(options.taskLearning)}:{})});
201
+ ...(Object.hasOwn(options,'taskLearning')?{taskLearning:json(options.taskLearning)}:{}),
202
+ ...(Object.hasOwn(options,'knowledgeCloseout')?{knowledgeCloseout:readCloseoutPolicy(options.knowledgeCloseout)}:{}),
203
+ ...(Object.hasOwn(options,'executionPolicy')?{executionPolicy:readExecutionPolicy(options.executionPolicy)}:{}),
204
+ ...(Object.hasOwn(options,'externalModels')?{externalModels:readExternalModels(options.externalModels)}:{})});
148
205
  const taskLearning=metadata.taskLearning??null;
149
206
  if(taskLearning!==null){need(taskMode,'runner_learning');
150
207
  shape(taskLearning,['feature',...(Object.hasOwn(taskLearning,'hostHandoff')?['hostHandoff']:[])]);
@@ -201,10 +258,20 @@ export function createTaskRunner(options) {
201
258
  const controller=new AbortController(),calls=[],cache=new Map(),session=restored?.session??randomUUID(),registered=new Map(),receipts=[];
202
259
  let state=reviewers.some(r=>r.allowed&&r.available)?'ready':'pending_review',code=null,attempt=1;
203
260
  let busy=false,pending=null,sequence=0,base=original,reviewPackage=null,currentChecks=null,workflowRunning=false;
261
+ let reason=null,checkNewPaths=null;
204
262
  let receipt=null,priorReview=null,cancelAfterCommit=false,workflowError=null,cancellationRequested=false,reviewInvocation=null;
205
263
  let learningResult=null;
264
+ // Journaled supersession context: shown, never counted as a review verdict.
265
+ let carriedReview=restored?.supersession?.carriedReview??null;
206
266
  const acceptedFixes=structuredClone(restored?.acceptedFixes??[]);
207
267
  let qaAttachment=restored?.qaAttachment??null;
268
+ // A fresh ready-state capture carries the current material; represent an
269
+ // accepted (identical or explicitly rebound) one by the bound material.
270
+ const withBoundSpecification=fresh=>{
271
+ if(!Object.hasOwn(fresh,'specification'))return fresh;
272
+ const {baselineDigest,...data}={...fresh,specification:boundSpecificationMaterial(original,fresh.specification)};
273
+ return {...data,baselineDigest:digest(data)};
274
+ };
208
275
  const handoffBinding=(pkg=reviewPackage)=>pkg&&Object.hasOwn(pkg,'handoff')
209
276
  ?{handoffPath:completion.handoffs[pkg.identity.attempt-1]}:{};
210
277
  function publishRegisteredReview(inspectOnly=false){
@@ -219,15 +286,85 @@ export function createTaskRunner(options) {
219
286
  // the blocked result back out of the cache. Counting them here keeps that
220
287
  // derivation in one place, next to the cache it is derived from.
221
288
  const verificationBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='develop'
222
- &&entry.result?.state==='blocked'&&entry.result?.code==='verification_precheck_failed').length;
223
- const privateStatus=()=>json({state,code,identity:{...config.identity,attempt},packageDigest:reviewPackage?.packageDigest??null,
289
+ &&entry.result?.state==='blocked'
290
+ &&['verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed','bootstrap_instruction_conflict'].includes(entry.result?.code)).length;
291
+ const completionBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='complete'
292
+ &&entry.result?.state==='blocked'&&['completion_checks_changed','completion_package_changed'].includes(entry.result?.code)).length;
293
+ const privateStatus=()=>json({state,code,...(reason?{reason}:{}),
294
+ ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pendingAbandonable
295
+ ?{pendingEffectKind:restored.pending.kind}:{}),
296
+ ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pending?.kind==='review'
297
+ &&restored.state.reviewInvocation?.registration&&restored.state.reviewInvocation.result===null
298
+ ?{pendingReviewInvocation:true}:{}),
299
+ identity:{...config.identity,attempt},packageDigest:reviewPackage?.packageDigest??null,
224
300
  receipt,receipts,calls,cancelAfterCommit,workflowError,...(store?{cancellationRequested}:{}),...(taskMode?{taskCommit}:{}),
225
301
  ...(invocationMode?{reviewInvocation}:{}),...(taskLearning!==null?{learningWriteback:learningResult?.writeback??null}:{})},16*1024*1024);
302
+ // Other task runs' committed, reviewed deliveries in this specs root, only
303
+ // those reviewed after this run's own approving review, and the live proof
304
+ // that recorded interleaving steps are exactly such deliveries.
305
+ const laterDeliveries=()=>completedReviewedDeliveries({specsRoot:completion.owner.specsRoot,root:config.root,identity:config.identity});
306
+ const reviewedAt=()=>approvedReviewAt({reviewInvocation,reviewPackage});
307
+ const resolveSteps=(steps,allowAbsent=false)=>resolveDeliverySteps({specsRoot:completion.owner.specsRoot,root:config.root,
308
+ identity:config.identity,after:reviewedAt(),steps,allowAbsent});
309
+ // This run's own QA fixes take their place in the same order at the final
310
+ // review time their completion evidence cites (evidence: a fix not yet accepted).
311
+ const fixTime=(evidence=null)=>fix=>{
312
+ const cited=[...acceptedFixes.map(item=>item.evidence),...(evidence?[evidence]:[])]
313
+ .find(item=>item.reviewPackage.packageDigest===fix.packageDigest);
314
+ return cited?fixReviewedAt(completion.owner.specsRoot,cited):null;
315
+ };
316
+ const laterOptions=(evidence=null)=>({deliveries:laterDeliveries,after:reviewedAt(),fixTime:fixTime(evidence)});
226
317
  let publication;
318
+ let pendingReconciliation=null;
319
+ // Replay decides; this only reports an exit abandonReview would accept.
320
+ function reviewResultAbandonable(){
321
+ return !(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned&&state==='unknown'&&!restored?.pending
322
+ &&abandonableReviewResult({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1]);
323
+ }
227
324
  const status=()=>{
228
- const current=store?publication:privateStatus();
325
+ let current=store?publication:privateStatus();
326
+ if(!busy&&!poisoned&&bootstrapReviewRecoverable(frame(),restored?.pending??null,metadata.bootstrap))
327
+ current=freeze({...current,bootstrapReviewRecovery:true});
328
+ // Status only; never part of a cached result or checkpoint.
329
+ if(current.state==='unknown'&&reviewResultAbandonable())current=freeze({...current,abandonableReviewResult:true});
330
+ const available=Boolean((metadata.externalModels||metadata.executionPolicy))&&!busy&&!poisoned&&invocationMode&&store&&['unknown','pending_review'].includes(current.state)
331
+ &&readRunnerHistory(journal,metadata,3).reviewReconciliation!==null;
332
+ if((metadata.externalModels||metadata.executionPolicy)&&!busy&&!poisoned&&invocationMode&&store&&reviewInvocation?.registration
333
+ &&(available||current.state==='unknown'&&reviewInvocation.result?.reconciliationRequired!==false)){
334
+ const grant=reviewInvocation.registration.grant;
335
+ current=freeze({...current,reviewReconciliation:{invocationId:grant.invocationId,requestDigest:grant.requestDigest,
336
+ provider:reviewers[0].provider,providerThreadId:reviewInvocation.started,available},
337
+ reason:available?'原调用的终态与本地清理收据已保存;使用 reconcile_review 接纳证据,此操作不派发模型。'
338
+ :'缺少原调用的可信终态或本地清理证据。保留本 run、attempt、journal 和快照;按 invocationId / providerThreadId 向原宿主或 provider 核对结果及终止状态,并确认本地后代已退出。当前适配器没有远端状态查询入口,人工说明、PID 消失或重启均不能解锁;不要删 journal、换 runId 或重派。'});
339
+ }
229
340
  if(!busy&&!poisoned)try{publishRegisteredReview(true);}
230
341
  catch{return freeze({...current,code:'review_publication_required'});}
342
+ // Every next effect re-verifies the bound specification. When it no longer
343
+ // verifies, report that and its real exits instead of the refused action.
344
+ if(!busy&&!poisoned&&specificationLive(current.state,current.code)){
345
+ const drift=inspectSpecificationDrift(original);
346
+ if(drift)return freeze({...current,code:'spec_drift',reason:describeSpecificationDrift(drift),
347
+ specificationRebind:drift.rebindable?'available':'unavailable'});
348
+ }
349
+ if(current.state==='blocked'&&current.code==='spec_drift'&&!current.reason)
350
+ return freeze({...current,reason:HALTED_SPEC_DRIFT});
351
+ if(!busy&&reviewPackage&&(['awaiting_review','approved','changes_requested'].includes(current.state)
352
+ ||current.state==='blocked'&&['review_package_changed','completion_package_changed'].includes(current.code))){
353
+ try{
354
+ verifyReviewPackage({root:config.root,baseline:attemptBaseline(original,reviewPackage.identity.attempt),
355
+ checks:currentChecks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
356
+ if(current.state==='blocked'&&current.code==='review_package_changed'){
357
+ const {reason:oldReason,...rest}=current;
358
+ if(priorReview?.verdict==='approved')return freeze({...rest,state:'approved',code:null});
359
+ if(priorReview?.verdict==='changes_requested'&&attempt===2&&reviewPackage.identity.attempt===1)
360
+ return freeze({...rest,state:'changes_requested',code:null});
361
+ return freeze({...rest,state:'blocked',code:priorReview?.verdict==='changes_requested'?'review_limit':'review_blocked'});
362
+ }
363
+ if(current.code==='completion_package_changed')return freeze({...current,retryReady:true});
364
+ }catch(error){return freeze({...current,state:'blocked',
365
+ code:current.code==='completion_package_changed'?'completion_package_changed':'review_package_changed',
366
+ ...(current.code==='completion_package_changed'?{retryReady:false}:{}),reason:error.message});}
367
+ }
231
368
  if(current.state!=='fixture_completed')return current;
232
369
  try {
233
370
  if(acceptedFixes.length){
@@ -237,18 +374,35 @@ export function createTaskRunner(options) {
237
374
  need(history.handoffDigest===handoffDigest,'fix_qa_source_changed');
238
375
  }
239
376
  inspectFixCodeAssociation({root:config.root,specsRoot:completion.owner.specsRoot,baseline:base,
240
- parentPackage:reviewPackage,fixPackages:acceptedFixes.map(item=>item.evidence.reviewPackage)});
377
+ parentPackage:reviewPackage,fixPackages:acceptedFixes.map(item=>item.evidence.reviewPackage),
378
+ steps:acceptedFixes.at(-1).association.laterDeliveries??[],...laterOptions()});
241
379
  const last=acceptedFixes.at(-1);
242
380
  return freeze({...current,acceptedQaFix:{qaRound:last.qaRound,testRunId:last.evidence.qaSource.testRunId,
243
381
  evidenceDigest:digest(last)}});
244
382
  }
245
- verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
246
- reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
383
+ try{verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
384
+ reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});}
385
+ catch(error){
386
+ // The exact reviewed tree no longer holds. A committed task may still be
387
+ // intact under later, separately reviewed deliveries of other runs.
388
+ if(!completion)throw error;
389
+ if(reviewPackage.handoff){
390
+ const handoff=handoffBinding().handoffPath;
391
+ need(digest(readReviewSourceFiles(path.dirname(handoff),[path.basename(handoff)])[0])===digest(reviewPackage.handoff),'package_mismatch');
392
+ }
393
+ explainCompletedDelivery({root:config.root,baseline:base,parentPackage:reviewPackage,deliveries:laterDeliveries(),after:reviewedAt()});
394
+ }
247
395
  return current;
248
- } catch {return freeze({...current,code:'correction_review_required'});}
396
+ } catch(error){
397
+ return freeze({...current,code:'correction_review_required',...(error?.code==='fix_current_code_unexplained'
398
+ ?{reason:`未经审查的改动:${error.paths.slice(0,20).join(', ')}${error.paths.length>20?` 等 ${error.paths.length} 个路径`:''}`}
399
+ :error?.code==='fix_association_unverified'?{reason:'已登记 QA 修复所接续的后续交付无法按其运行存档核实(存档缺失、未完成或内容不符)'}:{})});
400
+ }
249
401
  };
250
- const halt=(next,why)=>{state=next;code=why;};
251
- function frame(){return {state,code,attempt,session,sequence,reviewPackage,currentChecks,receipt,receipts,calls,
402
+ const halt=(next,why,detail=null)=>{state=next;code=why;reason=detail;};
403
+ const specificationLive=(currentState,currentCode)=>Object.hasOwn(original,'specification')
404
+ &&['develop','review','complete'].some(kind=>stageAllowed(kind,currentState,currentCode,priorReview?.verdict));
405
+ function frame(){return {state,code,reason,attempt,session,sequence,reviewPackage,currentChecks,receipt,receipts,calls,
252
406
  cache:[...cache.values()],priorReview,cancelAfterCommit,workflowError,cancellationRequested,...(taskMode?{taskCommit}:{}),
253
407
  ...(invocationMode?{reviewInvocation}:{}),...(taskLearning!==null?{learningResult}:{})};}
254
408
  const same=(a,b,why)=>need(digest(a)===digest(b),why);
@@ -269,13 +423,23 @@ export function createTaskRunner(options) {
269
423
  kind:{init:'result','effect-intent':'intent','effect-checkpoint':'result',control:'cancel',
270
424
  'task-commit-intent':'commit-intent','task-commit-result':'commit-result',
271
425
  'review-invocation-registered':'intent','review-invocation-started':'result','review-invocation-result':'result',
426
+ 'review-invocation-abandoned':'result','review-invocation-receipt':'result','review-invocation-reconciled':'result','effect-abandoned':'result',
272
427
  'host-joined':'result','qa-fix-accepted':'result','qa-attached':'result','qa-config-revised':'result',
273
- 'evidence-superseded':'result'}[type],
428
+ 'evidence-superseded':'result','develop-retry-limit':'result','completion-retry-limit':'result','specification-rebound':'result',
429
+ 'bootstrap-review-recovered':'result'}[type],
274
430
  payload:version===3?runnerPayloadV3(type,fields):runnerPayload(type,fields,version)};
275
431
  const body={version:1,seq:journal.length+1,...basic,previousDigest:journal.at(-1)?.digest??null};
276
432
  const record={...body,digest:digest(body)};boundRunnerRecord(record,body.seq);
277
433
  return {record,parsed:readRunnerHistory([...journal,record],metadata,version)};
278
434
  }
435
+ // The exact record the store would append must fit its limits (payload, append
436
+ // input, record count, whole state). Refusing here leaves the store usable,
437
+ // where an over-limit append inside persist would poison it.
438
+ function assertJournalFits(type,fields,why){
439
+ if(!store||!taskMode)return;
440
+ const {record}=candidate(type,fields);
441
+ need(appendFits(currentStore(),{id:record.id,kind:record.kind,payload:record.payload,expectedRevision:storeRevision}),why);
442
+ }
279
443
  function persist(type,fields) {
280
444
  if(!store)return;
281
445
  if(taskMode)return storeOperation(()=>{
@@ -329,15 +493,35 @@ export function createTaskRunner(options) {
329
493
  same(result,{outcome:'fixture_committed',intentDigest:taskCommit.intentDigest,planDigest:taskCommit.planDigest},'commit_unknown');
330
494
  }finally{revoke();}
331
495
  }
496
+ // Exact byte count of the payload the store validates for this record, built by
497
+ // the same record builder; an oversized record is measured, never written.
498
+ const payloadBytes=(type,fields)=>Buffer.byteLength(JSON.stringify(version===3
499
+ ?runnerPayloadV3(type,fields,Infinity):runnerPayload(type,fields,version,Infinity)));
500
+ const largestFiles=files=>files.slice().sort((a,b)=>b.size-a.size).slice(0,3)
501
+ .map(file=>`${file.path} ${file.size} bytes`);
332
502
  if(restored) {
333
503
  const s=structuredClone(restored.state);
334
504
  ({state,code,attempt,sequence,reviewPackage,currentChecks,receipt,priorReview,cancelAfterCommit,workflowError,cancellationRequested}=s);
505
+ reason=s.reason??null;
335
506
  if(taskLearning!==null)learningResult=s.learningResult;
336
507
  if(taskMode)taskCommit=s.taskCommit;
337
508
  if(invocationMode)reviewInvocation=s.reviewInvocation;
338
509
  calls.push(...s.calls);receipts.push(...s.receipts);s.cache.forEach(c=>cache.set(c.effect.id,c));
339
510
  receipts.forEach(r=>registered.set(r.id,r));base=attemptBaseline(original,attempt);
340
- } else persist('init',{config:metadata,baseline:original,session});
511
+ // Replay re-proves each version 2 record (its steps and the composition they
512
+ // give) against the referenced stores when they all still exist; a missing
513
+ // store is left to the live checks, which refuse it.
514
+ for(const [index,item] of acceptedFixes.entries())if(item.association.version===2)
515
+ validateAcceptedFix({record:item,previous:acceptedFixes.slice(0,index),baseline:base,parentPackage:reviewPackage,
516
+ feature:taskLearning?.feature,resolveSteps:steps=>resolveSteps(steps,true)});
517
+ } else {
518
+ // A baseline too large for its record is refused before anything is appended.
519
+ const bytes=store?payloadBytes('init',{config:metadata,baseline:original,session}):0;
520
+ if(bytes>JOURNAL_PAYLOAD_LIMIT)throw Object.assign(new Error(boundedReason(`limit_exceeded: the task baseline journal record would be ${bytes} bytes, `
521
+ +`above the journal record limit ${JOURNAL_PAYLOAD_LIMIT}; largest baseline material: `,
522
+ largestFiles(original.files.filter(file=>Object.hasOwn(file,'contentBase64'))))),{code:'limit_exceeded'});
523
+ persist('init',{config:metadata,baseline:original,session});
524
+ }
341
525
  publication=privateStatus();
342
526
  function control(event) {
343
527
  if(poisoned)return false;
@@ -402,8 +586,13 @@ export function createTaskRunner(options) {
402
586
  }
403
587
  function acceptReview(request,call,rawResult,fallbackReasons=[]) {
404
588
  const result=reviewResult(rawResult,reviewPackage);
405
- verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
406
- reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
589
+ let drift=null;
590
+ try{verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
591
+ reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});}
592
+ catch(error){drift=error;}
593
+ // Changed approved specs invalidate the verdict itself. Do not register a
594
+ // receipt that the code-root cleanup path could later reuse.
595
+ if(drift?.code==='spec_drift'){halt('blocked','spec_drift');return;}
407
596
  receipt=reviewReceipt({request,call,result,reviewPackage,developerProvider:developer.provider,fallbackReasons});
408
597
  registered.set(receipt.id,receipt);receipts.push(receipt);priorReview=result;
409
598
  if(result.verdict==='approved'){state='approved';code=null;}
@@ -411,7 +600,10 @@ export function createTaskRunner(options) {
411
600
  state='changes_requested';code=null;attempt=2;
412
601
  const {baselineDigest:old,...data}=original,newData={...data,identity:{...config.identity,attempt}};
413
602
  base=freeze({...newData,baselineDigest:digest(newData)});
414
- } else halt('blocked',result.verdict==='changes_requested'?'review_limit':'review_blocked');
603
+ } else halt('blocked',result.verdict==='changes_requested'?'review_limit':'review_blocked',
604
+ verdictReason(result.verdict==='changes_requested'?'review_limit: 第 2 轮审查仍要求修改,本运行两轮已用完'
605
+ :'review_blocked: 审查判定 blocked,无法靠修改批准范围内的代码解决',result.summary));
606
+ if(drift)halt('blocked','review_package_changed',drift.message);
415
607
  }
416
608
  const clock=Date.now.bind(Date);
417
609
  const safeTime=()=>{const value=clock();need(Number.isSafeInteger(value),'clock_invalid');return value;};
@@ -479,6 +671,21 @@ export function createTaskRunner(options) {
479
671
  const expectation={request,developerThreadId:invocationConfig.developerThreadId,
480
672
  excludedThreadIds:reviewExclusions(liveInvocation(),calls,developer.contextId)};
481
673
  const events=[];let started=null,sealed=false,invalid=false,invalidReject;
674
+ let capturedReceipt=null,receiptConflict=false,captureOpen=true,adapterDone;
675
+ const adapterFinished=new Promise(resolve=>{adapterDone=resolve;});
676
+ const onReconciliation=raw=>{
677
+ if(!captureOpen||invalid)return false;
678
+ try{
679
+ let value=readReconciliationReceipt(raw);
680
+ if(value.result?.status==='succeeded'){
681
+ const bounded=boundReviewText(value.result.value);need(bounded!==null,'observation_invalid');
682
+ value={...value,result:{status:'succeeded',value:bounded}};
683
+ }
684
+ if(capturedReceipt&&digest(value)!==digest(capturedReceipt))receiptConflict=true;
685
+ else capturedReceipt=value;
686
+ return !receiptConflict;
687
+ }catch{receiptConflict=true;return false;}
688
+ };
482
689
  const localController=new AbortController();
483
690
  const abort=()=>localController.abort();controller.signal.addEventListener('abort',abort,{once:true});
484
691
  const observation=result=>json({version:1,kind:'cm-provider-review-observation',requestDigest:request.requestDigest,
@@ -517,17 +724,18 @@ export function createTaskRunner(options) {
517
724
  new Promise((resolve,reject)=>queueMicrotask(()=>{
518
725
  try{
519
726
  need(!localController.signal.aborted,'cancelled');
520
- const returned=adapter.run(request,{signal:localController.signal,onEvent});
727
+ const returned=adapter.run(request,{signal:localController.signal,onEvent,...((metadata.externalModels||metadata.executionPolicy)?{onReconciliation}:{})});
521
728
  if(types.isPromise(returned)){
522
729
  const supported=Object.getPrototypeOf(returned)===promisePrototype&&!Object.hasOwn(returned,'constructor');
523
- const observed=observePromise(returned,supported?resolve:ignorePromiseResult,supported?reject:ignorePromiseResult);
730
+ const observed=observePromise(returned,supported?value=>{adapterDone();resolve(value);}:ignorePromiseResult,
731
+ supported?error=>{adapterDone();reject(error);}:ignorePromiseResult);
524
732
  need(supported&&observed);
525
- }else resolve(returned);
526
- }catch(error){reject(error);}
733
+ }else {adapterDone();resolve(returned);}
734
+ }catch(error){adapterDone();reject(error);}
527
735
  })),
528
736
  invalidPromise,
529
737
  new Promise((_,reject)=>{timer=setTimeout(()=>{timedOut=true;localController.abort();
530
- reject(Object.assign(new Error('call_timeout'),{code:'call_timeout'}));},config.timeoutMs);}),
738
+ reject(Object.assign(new Error('call_timeout'),{code:'call_timeout'}));},reviewTimeoutMs??config.timeoutMs);}),
531
739
  new Promise((_,reject)=>{cancelReject=()=>reject(Object.assign(new Error('cancelled'),{code:'cancelled'}));
532
740
  controller.signal.addEventListener('abort',cancelReject,{once:true});})
533
741
  ]);
@@ -539,7 +747,7 @@ export function createTaskRunner(options) {
539
747
  const recorded=observation({status:'failed',code:'timeout'});
540
748
  fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'timed_out',
541
749
  observation:recorded,inspection:inspectProviderReview(JSON.stringify(recorded),JSON.stringify(expectation)),
542
- reconciliationRequired:hasProviderReviewResult(recorded.events)};
750
+ reconciliationRequired:Boolean((metadata.externalModels||metadata.executionPolicy))||hasProviderReviewResult(recorded.events)};
543
751
  }
544
752
  else if(state==='cancelled'){fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'cancelled',
545
753
  observation:observation({status:'cancelled',code:'cancelled'}),inspection:null,reconciliationRequired:true};}
@@ -548,12 +756,17 @@ export function createTaskRunner(options) {
548
756
  fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'unknown',observation:recorded,inspection,reconciliationRequired:true};
549
757
  }
550
758
  persist('review-invocation-result',fields);const result=resultView(fields);
551
- const retry=reviewTimeoutTransition(result,[...cache.values()],attempt);
759
+ const retry=reviewTimeoutTransition(result,[...cache.values()],attempt,calls.slice(0,-1),contextId);
552
760
  Object.assign(call,{terminal:fields.outcome==='cancelled'?'cancelled':retry?'failed':'unknown',resultDigest:digest(result)});
553
761
  reviewInvocation=json({registration,started,result});
554
762
  if(fields.outcome==='cancelled')halt('cancelled','cancelled');
555
763
  else if(retry)halt(retry.state,retry.code);
556
- else halt('unknown',fields.reason??fields.inspection?.code??'reconciliation_required');return;
764
+ else halt('unknown',fields.reason??fields.inspection?.code??'reconciliation_required');
765
+ // Bound cleanup draining; never wait indefinitely or dispatch again.
766
+ // The original unknown is already journaled and remains unchanged.
767
+ if((metadata.externalModels||metadata.executionPolicy)&&timedOut&&!invalid){let drainTimer;await Promise.race([adapterFinished,
768
+ new Promise(resolve=>{drainTimer=setTimeout(resolve,2500);})]);clearTimeout(drainTimer);}
769
+ return;
557
770
  }
558
771
  sealed=true;
559
772
  let providerResult;
@@ -569,28 +782,71 @@ export function createTaskRunner(options) {
569
782
  Object.assign(call,{terminal:'unknown',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
570
783
  halt('unknown',inspection.code??'reconciliation_required');return;
571
784
  }
785
+ // A reviewer that failed without a verdict, or whose complete answer breaks
786
+ // the verdict contract, ends in a new explicit retryable result.
787
+ const reviewerFailed=(recorded,failure)=>{
788
+ const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'failed',observation:recorded,
789
+ inspection:failure,reconciliationRequired:Boolean((metadata.externalModels||metadata.executionPolicy))};
790
+ persist('review-invocation-result',fields);const result=resultView(fields);
791
+ const retry=reviewTimeoutTransition(result,[...cache.values()],attempt,calls.slice(0,-1),contextId);
792
+ Object.assign(call,{terminal:retry?'failed':'unknown',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
793
+ halt(retry?.state??'unknown',retry?.code??failure.code??'reconciliation_required',reviewFailureReason(failure.failure));
794
+ };
795
+ // Bound the reviewer text before it is observed, inspected or journaled.
796
+ if(providerResult.status==='succeeded'){
797
+ const bounded=boundReviewText(providerResult.value);
798
+ if(bounded===null){
799
+ const fields=invalidFields();persist('review-invocation-result',fields);const result=resultView(fields);
800
+ Object.assign(call,{terminal:'unknown',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
801
+ halt('unknown','observation_invalid');return;
802
+ }
803
+ providerResult=json({status:'succeeded',value:bounded});
804
+ }
572
805
  let recorded,inspection;
573
806
  try{recorded=observation(providerResult);inspection=inspectProviderReview(JSON.stringify(recorded),JSON.stringify(expectation));}
574
807
  catch{
808
+ const failure=recorded===undefined?null:inspectProviderReviewFailure(JSON.stringify(recorded),JSON.stringify(expectation));
809
+ if(failure){reviewerFailed(recorded,failure);return;}
575
810
  const fields=invalidFields();persist('review-invocation-result',fields);const result=resultView(fields);
576
811
  Object.assign(call,{terminal:'unknown',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
577
812
  halt('unknown','observation_invalid');return;
578
813
  }
579
814
  const observed=inspection.observationStatus==='completed';
815
+ const failure=!observed&&inspection.code==='transport_incomplete'
816
+ ?inspectProviderReviewFailure(JSON.stringify(recorded),JSON.stringify(expectation)):null;
817
+ if(failure){reviewerFailed(recorded,failure);return;}
580
818
  const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:observed?'observed':inspection.code==='transport_timeout'?'timed_out':'unknown',
581
819
  observation:recorded,inspection,reconciliationRequired:!observed
582
- &&(inspection.code!=='transport_timeout'||hasProviderReviewResult(recorded.events))};
820
+ &&(Boolean((metadata.externalModels||metadata.executionPolicy))||inspection.code!=='transport_timeout'||hasProviderReviewResult(recorded.events))};
583
821
  persist('review-invocation-result',fields);const result=resultView(fields);
584
- const retry=reviewTimeoutTransition(result,[...cache.values()],attempt);
822
+ const retry=reviewTimeoutTransition(result,[...cache.values()],attempt,calls.slice(0,-1),contextId);
585
823
  Object.assign(call,{terminal:observed?'succeeded':retry?'failed':'unknown',resultDigest:digest(observed?inspection.review:result)});
586
824
  reviewInvocation=json({registration,started,result});
587
825
  if(observed)acceptReview(request,call,inspection.review);
588
826
  else if(retry)halt(retry.state,retry.code);
589
827
  else halt('unknown',inspection.code??'reconciliation_required');
590
- }finally{sealed=true;clearTimeout(timer);controller.signal.removeEventListener('abort',abort);
828
+ }finally{
829
+ captureOpen=false;
830
+ if((metadata.externalModels||metadata.executionPolicy)&&(state==='unknown'||state==='pending_review'&&code==='review_transport_timeout')
831
+ &&started!==null&&!invalid&&!receiptConflict&&capturedReceipt)
832
+ pendingReconciliation={effectId,invocationId:request.invocationId,receipt:capturedReceipt};
833
+ sealed=true;clearTimeout(timer);controller.signal.removeEventListener('abort',abort);
591
834
  if(cancelReject)controller.signal.removeEventListener('abort',cancelReject);}
592
835
  }
593
- async function collectChecks(){return json(await bounded(check,json({identity:{...config.identity,attempt}})));}
836
+ async function collectChecks(){
837
+ const before=new Map(captureReviewInventory(config.root,base).map(file=>[file.path,file.sha256]));
838
+ const results=json(await bounded(check,json({identity:{...config.identity,attempt}})));
839
+ validChecks(results);
840
+ const after=captureReviewInventory(config.root,base);
841
+ checkNewPaths=new Set(after.filter(file=>!before.has(file.path)).map(file=>file.path));
842
+ return results;
843
+ }
844
+ const failedChecks=checks=>checks.filter(item=>item.outcome!=='passed'||item.kind!=='visual'&&item.exitCode!==0);
845
+ const checkFailureReason=(checks,code='checks_not_passed')=>{
846
+ const details=failedChecks(checks).map(item=>
847
+ `${item.id}: ${item.outcome}; ${item.evidence.replace(/[\x00-\x1f]/g,' ').slice(0,60)}`);
848
+ return `${code}: ${details.join(' | ')}`;
849
+ };
594
850
  // Runs on the checks just collected, before any handoff or review package is
595
851
  // built, so a deliverable that does not satisfy the task's own written
596
852
  // verification never spends an independent review round.
@@ -612,21 +868,82 @@ export function createTaskRunner(options) {
612
868
  shape(verdict,['satisfied']);need(typeof verdict.satisfied==='boolean','invalid_result');
613
869
  return verdict.satisfied;
614
870
  }
871
+ // Attempt 2 exists to answer the findings that rejected attempt 1. Code
872
+ // byte-identical to that rejected artifact cannot, so it never spends the
873
+ // last review round; the same attempt may deliver again under a new effect id.
874
+ function unchangedSinceRejection(){
875
+ if(attempt!==2||priorReview?.verdict!=='changes_requested')return null;
876
+ const rejected=receipts.findLast(item=>item.identity.attempt===1&&item.result.verdict==='changes_requested');
877
+ if(!rejected)return null;
878
+ const candidate=createReviewPackage({root:config.root,baseline:base,checks:currentChecks});
879
+ return candidate.artifactDigest===rejected.artifactDigest
880
+ ?`develop_unchanged_after_review: 第 2 轮交付与第 1 轮被要求修改的代码逐字节相同(artifactDigest ${rejected.artifactDigest.slice(0,12)});按审查 findings 修改后重新交付`:null;
881
+ }
882
+ // A delivery that changes nothing in scope has no review package to build. It
883
+ // is the delivery that must be redone, exactly like failed checks, not an
884
+ // unknown effect: nothing was dispatched to a reviewer and no round was spent.
885
+ const EMPTY_DELIVERY='develop_empty_changes: the delivery changes nothing in scope relative to the task baseline; '
886
+ +'write the actual change and resume to redo this attempt';
887
+ // Scope may overlap requirements. A delivery that removed such a file cannot be
888
+ // packaged (every requirement must exist), which is again a delivery to redo.
889
+ // Only in-scope requirements qualify: touching any other file stays out_of_scope,
890
+ // which the package builder reports before it ever reads the requirements.
891
+ const missingScopeRequirements=()=>config.scope.filter(p=>config.requirements.includes(p)).filter(p=>{
892
+ try{const stat=fs.lstatSync(path.join(config.root,p));return !stat.isFile()||stat.isSymbolicLink();}
893
+ catch(error){if(error.code==='ENOENT'||error.code==='ENOTDIR')return true;throw error;}
894
+ });
895
+ const emptyDelivery=error=>{
896
+ if(error?.code==='empty_changes'){halt('blocked','develop_empty_changes',EMPTY_DELIVERY);return;}
897
+ // Instruction bootstrap has its own no-redispatch recovery contract once
898
+ // rule evidence starts being written. Keep its size failures on that
899
+ // conservative path instead of granting a fresh developer effect.
900
+ if(error?.code==='limit_exceeded'&&metadata.bootstrap?.mode!=='instructions'){
901
+ halt('blocked','develop_package_too_large',boundedReason('develop_package_too_large: ',
902
+ [safeReason(error)??'review material exceeds its bounded size'],
903
+ '; shrink the changed files or move generated artifacts out of scope, then resume to redo this attempt'));
904
+ return;
905
+ }
906
+ const missing=error?.code==='read_failed'?missingScopeRequirements():[];
907
+ if(!missing.length)throw error;
908
+ halt('blocked','develop_requirement_missing',boundedReason('develop_requirement_missing: ',missing,
909
+ ' are requirement files and must exist in the review package; restore them and resume to redo this attempt'));
910
+ };
615
911
  async function perform(v) {
616
912
  if(v.kind==='develop') {
617
- need(stageAllowed('develop',state,code),'stage_mismatch');state='developing';code=null;receipt=null;
913
+ need(stageAllowed('develop',state,code,priorReview?.verdict),'stage_mismatch');state='developing';code=null;reason=null;checkNewPaths=null;receipt=null;
914
+ const previousLearning=learningResult;
618
915
  const previousBootstrap=learningResult?.bootstrap??null;
619
916
  const previousWriteback=learningResult?.writeback??null;
917
+ if(bootstrap!==null&&metadata.bootstrap?.mode==='instructions'){
918
+ try{bootstrap.assertInstructionBaseline({identity:v.identity,previous:previousBootstrap,
919
+ previousWriteback});}
920
+ catch(error){if(error.code!=='bootstrap_instruction_conflict')throw error;
921
+ halt('blocked','bootstrap_instruction_conflict',boundedReason(
922
+ 'bootstrap_instruction_conflict: 规则文件与本运行绑定的基准不一致:',error.paths??[],
923
+ '。本轮未派发或写入。请还原这些文件后在原 run resume;若要采用新的提交,使用新 runId 重建。'));
924
+ return;}
925
+ }
620
926
  if(taskLearning!==null)learningResult=null;
927
+ let verificationReason=null;
621
928
  const adapter=bootstrap===null?developer:{...developer,run:(request,control)=>
622
- bootstrap.run(request,control,developer.run,{previous:previousBootstrap,previousWriteback,baseline:original})};
929
+ bootstrap.run(request,control,developer.run,{previous:previousBootstrap,previousWriteback,baseline:original,
930
+ verificationFailed:detail=>{verificationReason=detail;}})};
623
931
  const result=await invoke(adapter,'developer',developer.contextId,{scope:config.scope,
624
932
  requirements:original.files.filter(f=>config.requirements.includes(f.path)),priorReview,
933
+ ...supersededReviewPayload(carriedReview,attempt),
625
934
  ...(Object.hasOwn(original,'specification')?{specification:verifySpecificationMaterial(original)}:{}),
626
935
  ...(Object.hasOwn(v,'learningInput')?{learningInput:v.learningInput}:{})});
627
936
  if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
628
937
  if(result.response.status!=='succeeded'){
629
938
  const failure=result.response.result?.code;
939
+ // The live session's init_verify did not pass, before any rule write.
940
+ // Keep the Learning/bootstrap evidence this develop started from, so the
941
+ // retry of the same attempt binds to exactly the files still on disk.
942
+ if(failure==='bootstrap_verification_failed'){
943
+ need(metadata.bootstrap?.mode==='instructions'&&typeof verificationReason==='string','invalid_result');
944
+ learningResult=previousLearning;
945
+ halt('blocked','bootstrap_verification_failed',verificationReason);return;
946
+ }
630
947
  halt(result.response.status==='unknown'?'unknown':'blocked',
631
948
  failure==='invalid_result'&&result.response.result.retryable===true?'developer_result_invalid':
632
949
  failure==='protected_edit_stale'?failure:result.response.status);return;
@@ -645,16 +962,25 @@ export function createTaskRunner(options) {
645
962
  &&application.learningDigest===v.learningInput.learningDigest,'identity_mismatch');
646
963
  const retrospective=json(result.response.result.retrospective,16*1024);
647
964
  const writeback=readCmAiProjectLearningWriteback(writeCmAiProjectLearning({codeProject:config.root,
648
- learningInput:v.learningInput,retrospective},instructionEvidence?.files.find(file=>file.path==='AGENTS.md').afterSha256??null),
965
+ learningInput:v.learningInput,retrospective},instructionEvidence?.files.find(file=>file.path==='AGENTS.md').afterSha256??null,
966
+ metadata.bootstrap?.feature??null),
649
967
  {learningInput:v.learningInput,retrospective});
650
968
  learningResult=freeze({application,retrospective,writeback,...(instructionEvidence?{bootstrap:instructionEvidence}:{})});
651
969
  if(writeback.outcome==='writeback_pending'){halt('blocked','learning_writeback_pending');return;}
652
970
  if(taskLearning.hostHandoff===true){
653
971
  currentChecks=await collectChecks();active();
972
+ if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return;}
654
973
  if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return;}
655
974
  active();
656
- createHostHandoff({root:config.root,baseline:base,checks:currentChecks,
657
- handoffPath:completion.handoffs[attempt-1]});
975
+ // unchangedSinceRejection builds a package too, so an empty delivery or a
976
+ // deleted in-scope requirement surfaces there first and takes the same
977
+ // retryable block (emptyDelivery).
978
+ let unchanged;
979
+ try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return;}
980
+ if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return;}
981
+ try{createHostHandoff({root:config.root,baseline:base,checks:currentChecks,
982
+ handoffPath:completion.handoffs[attempt-1]});}
983
+ catch(error){emptyDelivery(error);return;}
658
984
  }
659
985
  writeCmAiTaskLearningHandoff({handoffPath:completion.handoffs[attempt-1],feature:taskLearning.feature,
660
986
  identity:{...config.identity,attempt},learningInput:v.learningInput,application,retrospective,writeback});
@@ -662,11 +988,18 @@ export function createTaskRunner(options) {
662
988
  need(result.response.result.outcome==='implemented','invalid_result');
663
989
  if(taskLearning?.hostHandoff!==true){
664
990
  currentChecks=await collectChecks();active();
991
+ if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return;}
665
992
  if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return;}
993
+ active();
994
+ let unchanged;
995
+ try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return;}
996
+ if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return;}
666
997
  }
667
998
  active();
668
- const nextPackage=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,
669
- ...(taskLearning?.hostHandoff===true?{handoffPath:completion.handoffs[attempt-1]}:{})});
999
+ let nextPackage;
1000
+ try{nextPackage=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,
1001
+ ...(taskLearning?.hostHandoff===true?{handoffPath:completion.handoffs[attempt-1]}:{})});}
1002
+ catch(error){emptyDelivery(error);return;}
670
1003
  if(taskLearning!==null)validateTaskLearningReviewPackage(nextPackage,learningResult.writeback,v.learningInput,
671
1004
  learningResult.bootstrap??null,metadata.bootstrap??null);
672
1005
  reviewPackage=nextPackage;
@@ -675,12 +1008,14 @@ export function createTaskRunner(options) {
675
1008
  if(v.kind==='review') {
676
1009
  state='reviewing';verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
677
1010
  reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
678
- if(invocationMode){await invokeObserved(reviewers[0],reviewers[0].contexts[attempt-1],{reviewPackage,priorReview},v.id);return;}
1011
+ if(invocationMode){await invokeObserved(reviewers[0],reviewers[0].contexts[attempt-1],{reviewPackage,priorReview,
1012
+ ...supersededReviewPayload(carriedReview,attempt)},v.id);return;}
679
1013
  const fallbackReasons=[];
680
1014
  for(const candidate of reviewers) {
681
1015
  active();
682
1016
  if(!candidate.allowed || !candidate.available){fallbackReasons.push({id:candidate.id,reason:!candidate.allowed?'not_authorized':'unavailable'});continue;}
683
- const {request,response,call}=await invoke(candidate,'reviewer',candidate.contexts[attempt-1],{reviewPackage,priorReview});
1017
+ const {request,response,call}=await invoke(candidate,'reviewer',candidate.contexts[attempt-1],{reviewPackage,priorReview,
1018
+ ...supersededReviewPayload(carriedReview,attempt)});
684
1019
  if(['unavailable','auth_required','permission_denied'].includes(response.status)) {
685
1020
  fallbackReasons.push({id:candidate.id,reason:response.status});continue;
686
1021
  }
@@ -693,8 +1028,14 @@ export function createTaskRunner(options) {
693
1028
  if(v.kind==='complete') {
694
1029
  const fresh=await collectChecks();active();
695
1030
  try {
696
- verifyReviewPackage({root:config.root,baseline:base,checks:fresh,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
697
- } catch(error){halt('blocked',failureCode(error));return;}
1031
+ verifyCompletionReviewPackage({root:config.root,baseline:base,checks:fresh,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
1032
+ } catch(error){
1033
+ const duringCheck=error.code==='out_of_scope'&&Array.isArray(error.violations)
1034
+ &&error.violations.length>0&&error.violations.every(item=>item.newFile);
1035
+ const blockedCode=duringCheck?'completion_package_changed':failureCode(error);
1036
+ halt('blocked',blockedCode,blockedCode==='completion_checks_changed'&&failedChecks(fresh).length
1037
+ ?checkFailureReason(fresh):safeReason(error));return;
1038
+ }
698
1039
  if(taskLearning!==null)try {
699
1040
  const learningInput=currentLearningInput();
700
1041
  verifyCmAiTaskLearningHandoff({handoffPath:completion.handoffs[attempt-1],feature:taskLearning.feature,
@@ -717,6 +1058,25 @@ export function createTaskRunner(options) {
717
1058
  state='fixture_completed';return;
718
1059
  }
719
1060
  }
1061
+ // No delivery can still be reviewed: journal the terminal limit instead of an
1062
+ // intent, so no developer call runs (see developBudgetExhausted).
1063
+ const retryLimitDue=()=>invocationMode&&store&&!poisoned
1064
+ &&developBudgetExhausted({state,code,priorReview,calls,cache:[...cache.values()]});
1065
+ function recordRetryLimit(){
1066
+ const used=developBudget({calls,cache:[...cache.values()]});
1067
+ persist('develop-retry-limit',{fromState:state,fromCode:code,countedCalls:used.calls,countedEffects:used.effects});
1068
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1069
+ ({state,code}=recovered);reason=recovered.reason??null;publication=privateStatus();return publication;
1070
+ }
1071
+ // The completion re-check bound is spent: journal the terminal limit instead
1072
+ // of another complete intent (see completionRetriesExhausted).
1073
+ const completionLimitDue=()=>invocationMode&&store&&!poisoned&&completionRetriesExhausted({state,code,cache:[...cache.values()]});
1074
+ function recordCompletionLimit(){
1075
+ persist('completion-retry-limit',{fromCode:code,completionBlocks:completionBlockCount([...cache.values()])});
1076
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1077
+ ({state,code}=recovered);reason=recovered.reason??null;publication=privateStatus();return publication;
1078
+ }
1079
+ const limitDue=()=>retryLimitDue()?recordRetryLimit:completionLimitDue()?recordCompletionLimit:null;
720
1080
  function executeEffect(raw) {
721
1081
  let v;
722
1082
  try {
@@ -737,36 +1097,89 @@ export function createTaskRunner(options) {
737
1097
  if(old){need(old.digest===digest(v),'intent_conflict');return Promise.resolve(old.result);}
738
1098
  if(restored?.pending?.id===v.id){need(digest(restored.pending)===digest(v),'intent_conflict');return Promise.resolve(status());}
739
1099
  need(!busy,'busy');need(v.identity.attempt===attempt,'attempt_mismatch');
740
- need(stageAllowed(v.kind,state,code),'stage_mismatch');need(completedEffectCount([...cache.values()])<6,'limit_exceeded');
1100
+ need(stageAllowed(v.kind,state,code,priorReview?.verdict),'stage_mismatch');need(effectSlotFree(v.kind,[...cache.values()],calls),'limit_exceeded');
741
1101
  if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
742
1102
  if(v.kind==='develop'&&bootstrap!==null)bootstrap.assertWriteAuthorized();
743
1103
  } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:error.code??'invalid_input'}));}
1104
+ if(v.kind==='develop'&&retryLimitDue()){try{return Promise.resolve(recordRetryLimit());}catch{return Promise.resolve(poison());}}
1105
+ if(v.kind==='complete'&&completionLimitDue()){try{return Promise.resolve(recordCompletionLimit());}catch{return Promise.resolve(poison());}}
744
1106
  if(store) {
745
1107
  try {
746
- if(state==='ready')need(digest(captureReviewBaseline({...configToBaseline(metadata),version:original.version,
747
- ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})}))===digest(original),'package_mismatch');
748
- // A develop restarted from a locally rejected delivery has no review package
749
- // to verify yet: the invalid result never built one, and the host gate blocks
750
- // before one is built.
751
- else if(!(v.kind==='develop'&&stageAllowed('develop',state,code)))verifyReviewPackage({root:config.root,baseline:state==='changes_requested'?attemptBaseline(original,attempt-1):base,
1108
+ if(state==='ready')compareReviewBaseline(withBoundSpecification(captureReviewBaseline({...configToBaseline(metadata),version:original.version,
1109
+ ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
1110
+ !Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
1111
+ original.ignorePolicy?.version===2?original.ignorePolicy:null)),original);
1112
+ // A rejected first delivery has no review package yet. Every later
1113
+ // developer effect must recheck the reviewed tree before dispatch,
1114
+ // except one that redoes a delivery this attempt already made: that
1115
+ // delivery changed the tree on purpose and never became a package, so
1116
+ // it is compared against the baseline when the new package is built,
1117
+ // exactly as a redo at attempt 1 is.
1118
+ else if(reviewPackage!==null&&!(v.kind==='develop'&&state==='blocked'&&code!=='review_package_changed'
1119
+ &&stageAllowed('develop',state,code,priorReview?.verdict)))verifyReviewPackage({root:config.root,baseline:reviewPackage.identity.attempt===attempt?base:attemptBaseline(original,reviewPackage.identity.attempt),
752
1120
  checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
753
- } catch {return Promise.resolve(freeze({outcome:'rejected',code:'package_mismatch'}));}
1121
+ } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:failureCode(error),
1122
+ ...(safeReason(error)?{reason:safeReason(error)}:{})}));}
754
1123
  try{const record=persist('effect-intent',{effect:v});
755
1124
  if(taskMode&&v.kind==='complete')completeEffect={effect:v,digest:record.digest};
756
1125
  }catch{return Promise.resolve(poison());}
757
1126
  }
758
1127
  busy=true;if(v.kind!=='develop')code=null;
1128
+ const packageBefore=reviewPackage;
759
1129
  pending=(async()=>{
760
1130
  try {await perform(v);}
761
- catch(error){if(state!=='cancelled'){const code=failureCode(error);halt(code==='spec_drift'?'blocked':'unknown',code);}}
1131
+ catch(error){if(state!=='cancelled'){
1132
+ const failure=failureCode(error);
1133
+ const checkOnly=failure==='out_of_scope'&&Array.isArray(error.violations)&&error.violations.length>0
1134
+ &&error.violations.every(item=>item.newFile&&checkNewPaths?.has(item.path));
1135
+ halt(checkOnly||failure==='spec_drift'||failure==='bootstrap_review_mismatch'?'blocked':'unknown',
1136
+ checkOnly?'check_output_out_of_scope':failure,
1137
+ failure==='bootstrap_review_mismatch'
1138
+ ?'规则审查包与六项目标证据不符;核对当前文件及 handoff 后,在原 run 使用 bootstrap_review_recover 恢复审查包。'
1139
+ :['out_of_scope','unsupported_file','limit_exceeded','package_mismatch','snapshot_changed'].includes(failure)
1140
+ ?safeReason(error):null);
1141
+ }}
762
1142
  if(poisoned)return status();
763
- const result=privateStatus();cache.set(v.id,{effect:v,digest:digest(v),result});
764
- try{persist('effect-checkpoint',{effectId:v.id,checkpoint:frame()});publication=result;return result;}
1143
+ let result=privateStatus();cache.set(v.id,{effect:v,digest:digest(v),result});
1144
+ // A package the journal cannot hold would poison the store after the delivery
1145
+ // was written. Measure the exact checkpoint first; if it (plus room for the
1146
+ // review and completion checkpoints) does not fit, the delivery is redone.
1147
+ if(store&&v.kind==='develop'&&state==='awaiting_review'&&reviewPackage!==packageBefore){
1148
+ const bytes=payloadBytes('effect-checkpoint',{effectId:v.id,checkpoint:frame()});
1149
+ const size=value=>Buffer.byteLength(JSON.stringify(value??null));
1150
+ const reserve=developCheckpointReserve({examinedPathsBytes:size(reviewPaths(reviewPackage)),
1151
+ receiptsBytes:size(receipts),callsBytes:size(calls),writebackBytes:size(learningResult?.writeback)});
1152
+ const budget=JOURNAL_PAYLOAD_LIMIT-reserve;
1153
+ if(bytes>budget){
1154
+ const changed=reviewPackage.changes.filter(change=>change.after).map(change=>change.after);
1155
+ reviewPackage=packageBefore;
1156
+ halt('blocked','develop_package_too_large',boundedReason(`develop_package_too_large: the review checkpoint would be ${bytes} bytes, `
1157
+ +`above ${budget} (journal record limit ${JOURNAL_PAYLOAD_LIMIT} minus ${reserve} kept for the bounded review `
1158
+ +'and completion records); largest changed files: ',largestFiles(changed),
1159
+ '; shrink them or move them out of scope, then resume to redo this attempt'));
1160
+ result=privateStatus();cache.set(v.id,{effect:v,digest:digest(v),result});
1161
+ }
1162
+ }
1163
+ try{persist('effect-checkpoint',{effectId:v.id,checkpoint:frame()});publication=result;}
765
1164
  catch{return poison();}
1165
+ if(pendingReconciliation){
1166
+ const saved=pendingReconciliation;pendingReconciliation=null;
1167
+ const registration=journal.findLast(row=>row.payload.type==='review-invocation-registered'&&row.payload.effectId===saved.effectId);
1168
+ const startedRecord=journal.findLast(row=>row.payload.type==='review-invocation-started'&&row.payload.effectId===saved.effectId);
1169
+ const resultRecord=journal.findLast(row=>row.payload.type==='review-invocation-result'&&row.payload.effectId===saved.effectId);
1170
+ const fields={...saved,registeredDigest:registration.digest,startedDigest:startedRecord?.digest??null,resultDigest:resultRecord.digest};
1171
+ // Invalid/unusable evidence never mutates the journal or poisons a run.
1172
+ let usable=false;try{assertJournalFits('review-invocation-receipt',fields,'review_reconciliation_limit');usable=true;}catch{}
1173
+ if(usable)try{persist('review-invocation-receipt',fields);}catch{return poison();}
1174
+ }
1175
+ // A block or verdict that leaves no reviewable delivery ends the run now,
1176
+ // so status never invites a resume that could not finish.
1177
+ try{const record=limitDue();return record?record():result;}catch{return poison();}
766
1178
  })().finally(()=>{busy=false;pending=null;completeEffect=null;}).then(result=>{
767
1179
  if(poisoned)return result;
768
- try{publishRegisteredReview();return result;}
1180
+ try{publishRegisteredReview();}
769
1181
  catch{return freeze({...result,code:'review_publication_required'});}
1182
+ return ['unknown','pending_review'].includes(result.state)?status():result;
770
1183
  });
771
1184
  return pending;
772
1185
  }
@@ -782,8 +1195,11 @@ export function createTaskRunner(options) {
782
1195
  }
783
1196
  function currentLearningInput() {
784
1197
  const currentIdentity={...config.identity,attempt};
1198
+ const recovered=journal?.some(row=>row.payload.type==='bootstrap-review-recovered'
1199
+ &&row.payload.reviewPackage.packageDigest===reviewPackage?.packageDigest)??false;
785
1200
  const develop=[...cache.values()].filter(entry=>entry.effect.kind==='develop'
786
- &&digest(entry.effect.identity)===digest(currentIdentity)&&entry.result.state==='awaiting_review');
1201
+ &&digest(entry.effect.identity)===digest(currentIdentity)
1202
+ &&(entry.result.state==='awaiting_review'||recovered&&['unknown','blocked'].includes(entry.result.state)));
787
1203
  need(develop.length===1&&Object.hasOwn(develop[0].effect,'learningInput'),'runner_learning');
788
1204
  return develop[0].effect.learningInput;
789
1205
  }
@@ -806,8 +1222,9 @@ export function createTaskRunner(options) {
806
1222
  catch {
807
1223
  if(workflowError===null && control('workflow-error')) {
808
1224
  const next=controlledState(frame(),'workflow-error',busy||restored?.pending!=null,version);
809
- ({state,code,workflowError}=next);
810
- publication=json({...publication,workflowError,...(!busy?{state,code}:{})},16*1024*1024);
1225
+ ({state,code,workflowError}=next);reason=next.reason??null;
1226
+ const {reason:oldReason,...currentPublication}=publication;
1227
+ publication=json({...currentPublication,workflowError,...(!busy?{state,code,...(reason?{reason}:{})}:{})},16*1024*1024);
811
1228
  }
812
1229
  }
813
1230
  finally {
@@ -818,27 +1235,28 @@ export function createTaskRunner(options) {
818
1235
  return status();
819
1236
  }
820
1237
  // Read-only content comparison, not completion authority or a JSON operation.
821
- const inspectFixAssociation=fixPackage=>{
1238
+ const inspectFixAssociation=(fixPackage,evidence=null)=>{
822
1239
  need(!busy&&!poisoned,'host_busy');
823
1240
  const current=status();
824
1241
  need(current.state==='fixture_completed'&&current.code!=='review_publication_required','qa_fix_parent_not_completed');
1242
+ const known=acceptedFixes.some(item=>item.evidence.reviewPackage.packageDigest===fixPackage.packageDigest);
825
1243
  return inspectFixCodeAssociation({root:config.root,
826
- ...(completion?{specsRoot:completion.owner.specsRoot}:{}),
827
- baseline:base,parentPackage:reviewPackage,
828
- fixPackages:acceptedFixes.some(item=>item.evidence.reviewPackage.packageDigest===fixPackage.packageDigest)
829
- ?acceptedFixes.map(item=>item.evidence.reviewPackage)
1244
+ ...(completion?{specsRoot:completion.owner.specsRoot,...laterOptions(evidence)}:{}),
1245
+ baseline:base,parentPackage:reviewPackage,steps:acceptedFixes.at(-1)?.association.laterDeliveries??[],extend:!known,
1246
+ fixPackages:known?acceptedFixes.map(item=>item.evidence.reviewPackage)
830
1247
  :[...acceptedFixes.map(item=>item.evidence.reviewPackage),fixPackage]});
831
1248
  };
832
1249
  const acceptCompletedFix=raw=>{
833
1250
  need(invocationMode&&store&&!busy&&!poisoned,'fix_accept_unavailable');
834
- const evidence=json(raw,12*1024*1024),association=inspectFixAssociation(evidence.reviewPackage);
1251
+ const evidence=json(raw,12*1024*1024),association=inspectFixAssociation(evidence.reviewPackage,evidence);
835
1252
  const existing=acceptedFixes.find(item=>item.evidence.qaSource.testRunId===evidence.qaSource.testRunId);
836
1253
  if(existing){need(digest(existing.evidence)===digest(evidence),'fix_evidence_changed');return json(existing,12*1024*1024);}
837
1254
  const source=evidence.qaSource;
838
1255
  const failure=inspectCmAiQaFailure({specsDir:completion.owner.specsRoot,feature:source.feature,
839
1256
  identity:source.identity,packageDigest:source.packageDigest,testRunId:source.testRunId});
840
1257
  const record=validateAcceptedFix({record:{evidence,association,qaRound:failure.qaRound},previous:acceptedFixes,
841
- baseline:base,parentPackage:reviewPackage,feature:taskLearning?.feature});
1258
+ baseline:base,parentPackage:reviewPackage,feature:taskLearning?.feature,resolveSteps:steps=>resolveSteps(steps)});
1259
+ assertJournalFits('qa-fix-accepted',{record},'fix_record_too_large');
842
1260
  persist('qa-fix-accepted',{record});acceptedFixes.push(record);
843
1261
  return json(record,12*1024*1024);
844
1262
  };
@@ -852,25 +1270,190 @@ export function createTaskRunner(options) {
852
1270
  const reviseQa=raw=>{
853
1271
  need(invocationMode&&store&&!busy&&!poisoned,'qa_revision_unavailable');
854
1272
  const record=readQaConfigRevision(raw),current=status();
855
- need(current.state==='fixture_completed'&&current.code===null,'qa_revision_not_completed');
856
- need(current.packageDigest===record.packageDigest,'package_mismatch');
1273
+ // Before the first QA round (the caller checks the QA log) development may
1274
+ // still be in progress, but never with an unresolved effect, after
1275
+ // cancellation, or over completed code that no longer matches its review.
1276
+ if(beforeFirstQaRound(record))need(!['unknown','cancelled'].includes(current.state)
1277
+ &&!(current.state==='fixture_completed'&&current.code!==null),'qa_revision_not_completed');
1278
+ else need(current.state==='fixture_completed'&&current.code===null,'qa_revision_not_completed');
1279
+ need((current.packageDigest??null)===record.packageDigest,'package_mismatch');
857
1280
  persist('qa-config-revised',{record});return json(record);
858
1281
  };
1282
+ // Explicit, journaled continuation after a proper re-approval. Refused unless
1283
+ // everything this run's developer and reviewer see is unchanged; the record
1284
+ // then lets the bound material verify against the re-approved hashes only.
1285
+ const rebindSpecification=raw=>{
1286
+ const refuse=(code,why)=>{throw Object.assign(new Error(code),{code,reason:why});};
1287
+ need(invocationMode&&store&&!busy&&!poisoned,'spec_rebind_unavailable');
1288
+ const value=json(raw);shape(value,['version','reason','at']);need(value.version===1,'invalid_input');
1289
+ if(!Object.hasOwn(original,'specification'))refuse('spec_rebind_unavailable','本运行没有绑定规格材料(旧版运行),无需换绑');
1290
+ const drift=inspectSpecificationDrift(original);
1291
+ if(drift===null)return freeze({outcome:'unchanged'});
1292
+ if(restored?.pending||!specificationLive(state,code))
1293
+ refuse('spec_rebind_unavailable',`运行当前为 ${state}${code?`/${code}`:''},没有待执行的开发、审查或完成,不能换绑`);
1294
+ if(!drift.rebindable)refuse('spec_rebind_refused',describeSpecificationDrift(drift));
1295
+ const record=readSpecificationRebind({version:1,taskId:config.identity.taskId,boundDigest:digest(original.specification),
1296
+ sources:drift.sources,files:drift.files,reason:value.reason,reboundAt:value.at});
1297
+ persist('specification-rebound',{record});
1298
+ return json({outcome:'rebound',record});
1299
+ };
859
1300
  const supersedeEvidence=raw=>{
860
1301
  need(invocationMode&&store&&!busy&&!poisoned,'supersede_unavailable');
861
1302
  const record=readEvidenceSupersession(raw,{feature:taskLearning.feature,
862
1303
  taskId:config.identity.taskId,newRunId:config.identity.runId});
863
1304
  if(restored?.supersession){need(digest(restored.supersession)===digest(record),'supersede_record_invalid');return json(record);}
864
1305
  need(journal.length===1&&state==='ready','supersede_unavailable');
865
- persist('evidence-superseded',{record});return json(record);
1306
+ persist('evidence-superseded',{record});carriedReview=record.carriedReview??null;return json(record);
866
1307
  };
867
- const api={reviseQa,supersedeEvidence,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks};
1308
+ const abandonReview=raw=>{
1309
+ try{
1310
+ need(!(metadata.externalModels||metadata.executionPolicy),'external_review_reconciliation_required');
1311
+ need(invocationMode&&store&&!busy&&!poisoned&&state==='unknown'
1312
+ &&(restored?.pending?.kind==='review'||reviewResultAbandonable()),'review_abandon_unavailable');
1313
+ const value=json(raw);shape(value,['allowed','reason']);
1314
+ need(value.allowed===true,'review_abandon_authorization_required');
1315
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1316
+ &&!/[\r\n\0]/.test(value.reason),'review_abandon_reason_required');
1317
+ if(!restored?.pending){
1318
+ // A checkpointed review whose journaled result was never accepted.
1319
+ const binding=readRunnerHistory(journal,metadata,3).reviewResultAbandon;
1320
+ need(binding!==null,'review_abandon_unavailable');
1321
+ persist('review-invocation-abandoned',{...binding,reason:value.reason,at:new Date().toISOString()});
1322
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1323
+ ({state,code,sequence,reviewInvocation}=recovered);reason=recovered.reason??null;
1324
+ calls.splice(0,calls.length,...recovered.calls);
1325
+ publication=privateStatus();return status();
1326
+ }
1327
+ const history=readRunnerHistory(journal,metadata,3),last=journal.at(-1);
1328
+ need(history.pending?.id===restored.pending.id&&history.state.state==='unknown'
1329
+ &&history.state.code==='reconciliation_required'
1330
+ &&['review-invocation-registered','review-invocation-started'].includes(last?.payload?.type)
1331
+ &&history.state.reviewInvocation?.registration&&history.state.reviewInvocation.result===null,
1332
+ 'review_abandon_unavailable');
1333
+ const registration=journal.findLast(row=>row.payload.type==='review-invocation-registered'
1334
+ &&row.payload.effectId===history.pending.id);
1335
+ const started=last.payload.type==='review-invocation-started'?last:null;
1336
+ need(registration,'review_abandon_unavailable');
1337
+ const contextId=reviewers[0].contexts[attempt-1];
1338
+ need(!reviewRetrySpent(history.state.cache,history.state.calls,attempt,contextId),'review_abandon_budget_exhausted');
1339
+ const fields={effectId:history.pending.id,
1340
+ invocationId:history.state.reviewInvocation.registration.grant.invocationId,
1341
+ registeredDigest:registration.digest,startedDigest:started?.digest??null,
1342
+ reason:value.reason,at:new Date().toISOString()};
1343
+ persist('review-invocation-abandoned',fields);
1344
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1345
+ ({state,code,sequence,reviewInvocation}=recovered);calls.push(...recovered.calls.slice(calls.length));
1346
+ publication=privateStatus();return status();
1347
+ }catch(error){return freeze({outcome:'rejected',code:error.code??'review_abandon_unavailable'});}
1348
+ };
1349
+ const reconcileReview=raw=>{
1350
+ try{
1351
+ need((metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned,'review_reconciliation_unavailable');
1352
+ const value=json(raw);shape(value,['invocationId']);id(value.invocationId);
1353
+ const prior=journal.findLast(row=>row.payload.type==='review-invocation-reconciled');
1354
+ if(prior?.payload.invocationId===value.invocationId&&state!=='unknown')return status();
1355
+ const history=readRunnerHistory(journal,metadata,3),proof=history.reviewReconciliation;
1356
+ need(['unknown','pending_review'].includes(state)&&!history.pending&&proof!==null,'review_reconciliation_evidence_required');
1357
+ need(proof.invocationId===value.invocationId,'review_reconciliation_binding');
1358
+ const {request,effect,before,result,...binding}=proof;
1359
+ const call=calls.find(item=>item.invocationId===value.invocationId);
1360
+ need(['unknown','failed'].includes(call?.terminal),'review_reconciliation_unavailable');
1361
+ // Same call, same grant and same effect. The journal retains the original
1362
+ // unknown and receipt; one atomic record contains the validated transition.
1363
+ Object.assign(call,{terminal:result.outcome==='observed'?'succeeded':'failed',
1364
+ resultDigest:digest(result.outcome==='observed'?result.inspection.review:result)});
1365
+ reviewInvocation=json({...reviewInvocation,result});reason=null;
1366
+ if(result.outcome==='observed')acceptReview(request,call,result.inspection.review);
1367
+ else {const retry=reviewTimeoutTransition(result,before.cache,before.attempt,before.calls,call.contextId);
1368
+ halt(retry.state,retry.code,reviewFailureReason(result.inspection.failure));}
1369
+ const response=privateStatus();cache.set(effect.id,{effect,digest:digest(effect),result:response});
1370
+ try{persist('review-invocation-reconciled',{...binding,checkpoint:frame()});publication=response;}
1371
+ catch{return poison();}
1372
+ try{limitDue()?.();}catch{return poison();}
1373
+ return status();
1374
+ }catch(error){return freeze({outcome:'rejected',code:error.code??'review_reconciliation_unavailable'});}
1375
+ };
1376
+ const abandonEffect=raw=>{
1377
+ try{
1378
+ need(!(metadata.externalModels||metadata.executionPolicy),'external_review_reconciliation_required');
1379
+ need(invocationMode&&store&&!busy&&!poisoned&&options.persistence.mode==='resume','effect_abandon_unavailable');
1380
+ const value=json(raw);shape(value,['allowed','reason']);
1381
+ need(value.allowed===true,'effect_abandon_authorization_required');
1382
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1383
+ &&!/[\r\n\0]/.test(value.reason),'effect_abandon_reason_required');
1384
+ const history=readRunnerHistory(journal,metadata,3),effect=history.pending;
1385
+ need(effect!==null,'effect_abandon_no_pending');
1386
+ need(effect.kind!=='review'||history.pendingAbandonable,'effect_abandon_review_pending');
1387
+ need(['develop','complete','review'].includes(effect.kind),'effect_abandon_unavailable');
1388
+ need(effect.kind!=='develop'||options.providerDevelopment!==true,'effect_abandon_provider_development');
1389
+ need(history.transaction===null&&history.state.taskCommit?.intentDigest==null,'effect_abandon_commit_pending');
1390
+ need(history.state.state==='unknown'&&history.state.code==='reconciliation_required'
1391
+ &&history.pendingAbandonable,'effect_abandon_unavailable');
1392
+ const intent=journal.findLast(row=>row.payload.type==='effect-intent');
1393
+ persist('effect-abandoned',{effectId:effect.id,effectKind:effect.kind,intentDigest:intent.digest,
1394
+ lastRecordDigest:journal.at(-1).digest,reason:value.reason,at:new Date().toISOString()});
1395
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1396
+ ({state,code,sequence}=recovered);reason=recovered.reason;restored.pending=null;
1397
+ publication=privateStatus();return status();
1398
+ }catch(error){return freeze({outcome:'rejected',code:error.code??'effect_abandon_unavailable',
1399
+ ...(error.code==='effect_abandon_commit_pending'?{reason:'task-commit-intent 已写入,tasks.md 可能已改名或勾选;请核对 tasks.md、提交回执和旧进程后按原提交恢复路径处理。'}:{})});}
1400
+ };
1401
+ const recoverBootstrapReview=raw=>{
1402
+ try{
1403
+ need(invocationMode&&store&&!busy&&!poisoned&&options.persistence.mode==='resume',
1404
+ 'bootstrap_review_recovery_unavailable');
1405
+ const value=json(raw);shape(value,['allowed','reason']);
1406
+ need(value.allowed===true,'bootstrap_review_recovery_authorization_required');
1407
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1408
+ &&!/[\r\n\0]/.test(value.reason),'bootstrap_review_recovery_reason_required');
1409
+ const history=readRunnerHistory(journal,metadata,3);
1410
+ need(bootstrapReviewRecoverable(history.state,history.pending,metadata.bootstrap),
1411
+ 'bootstrap_review_recovery_unavailable');
1412
+ const input=history.state.cache.at(-1).effect.learningInput;
1413
+ const handoffPath=completion.handoffs[attempt-1];
1414
+ verifyCmAiTaskLearningHandoff({handoffPath,feature:taskLearning.feature,
1415
+ identity:{...config.identity,attempt},learningInput:input,
1416
+ ...(Object.hasOwn(learningResult,'application')?{application:learningResult.application}:{}),
1417
+ retrospective:learningResult.retrospective,writeback:learningResult.writeback});
1418
+ const pkg=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,handoffPath});
1419
+ validateTaskLearningReviewPackage(pkg,learningResult.writeback,input,learningResult.bootstrap,metadata.bootstrap);
1420
+ const handoff=loadHandoff(handoffPath,{task:config.identity.taskId,attempt});
1421
+ const paths=pkg.changes.map(item=>item.path);
1422
+ need(digest([...handoff.changed_files].sort())===digest([...paths].sort())
1423
+ &&handoff.implementation_sha256===implementationSha256(config.root,handoff.changed_files),
1424
+ 'bootstrap_review_recovery_mismatch');
1425
+ verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
1426
+ reviewPackage:pkg,expectedDigest:pkg.packageDigest,handoffPath});
1427
+ persist('bootstrap-review-recovered',{fromDigest:journal.at(-1).digest,reviewPackage:pkg,
1428
+ reason:value.reason,at:new Date().toISOString()});
1429
+ reviewPackage=pkg;state='awaiting_review';code=null;reason=null;
1430
+ publication=privateStatus();return status();
1431
+ }catch(error){return freeze({outcome:'rejected',code:error.code??'bootstrap_review_recovery_mismatch',
1432
+ reason:'原运行的文件、handoff 或证据无法精确核对;请保留现场并检查差异,不要重新派发开发。'});}
1433
+ };
1434
+ const api={reviseQa,supersedeEvidence,rebindSpecification,abandonReview,reconcileReview,abandonEffect,recoverBootstrapReview,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks};
868
1435
  if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
869
1436
  if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
1437
+ // A terminal reviewer observation is durable even if the host died before
1438
+ // the checkpoint. Finish that same effect from its validated journal bytes.
1439
+ if(restored?.pendingObservedReview){
1440
+ const observed=restored.pendingObservedReview,request=observed.request,result=observed.result;
1441
+ const call={invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
1442
+ requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-authorized',
1443
+ started:true,terminal:'succeeded',requestDigest:request.requestDigest,
1444
+ resultDigest:digest(result.inspection.review),providerThreadId:observed.started};
1445
+ sequence++;calls.push(call);
1446
+ reviewInvocation=json({registration:observed.registration,started:observed.started,result});
1447
+ acceptReview(request,call,result.inspection.review);
1448
+ const effect=restored.pending,response=privateStatus();
1449
+ cache.set(effect.id,{effect,digest:digest(effect),result:response});
1450
+ persist('effect-checkpoint',{effectId:effect.id,checkpoint:frame()});
1451
+ restored.pending=null;publication=response;
1452
+ }
870
1453
  return Object.freeze(api);
871
1454
  }
872
1455
  function configToBaseline(c){
873
- const scope=Object.hasOwn(c,'taskLearning')&&!c.scope.includes('AGENTS.md')?[...c.scope,'AGENTS.md']:c.scope;
1456
+ const scope=Object.hasOwn(c,'taskLearning')?taskReviewScope(c.scope):c.scope;
874
1457
  return {root:c.root,identity:c.identity,scope,requirements:c.requirements,
875
1458
  ...(c.codeProjectPaths?{codeProjectPaths:c.codeProjectPaths}:{}),
876
1459
  ...(c.bootstrap?{bootstrapRequirements:c.bootstrap.bootstrapRequirements}:{}),