@aibyzero/cm-workflow 0.16.8 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +22 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/cm-control-policy-v2.md +331 -0
  7. package/docs/execution-optimizations.md +1 -1
  8. package/docs/external-models.md +3 -3
  9. package/docs/human-correction.md +5 -5
  10. package/docs/installation.md +1 -1
  11. package/docs/js-workflow-control.md +119 -78
  12. package/docs/next-steps.md +19 -2
  13. package/docs/untested-branches.md +2 -3
  14. package/docs/user-guide.md +105 -5
  15. package/package.json +2 -1
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  17. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +103 -68
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +79 -27
  19. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  20. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  21. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  22. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  23. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +883 -69
  25. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  26. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  27. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  28. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  29. package/runtime/js/cm-ai/host-check.mjs +4 -1
  30. package/runtime/js/cm-ai/host-conversation-execution.mjs +33 -24
  31. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  32. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  33. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  34. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +53 -9
  35. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  36. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  37. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +43 -3
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  41. package/runtime/js/cm-ai/host.mjs +1 -2
  42. package/runtime/js/cm-ai/operator-guidance.mjs +89 -3
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  44. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  45. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  46. package/runtime/js/cm-ai/review-package.mjs +26 -5
  47. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  48. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  49. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  50. package/runtime/js/cm-ai/task-runner.mjs +629 -121
  51. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  52. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  53. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  54. package/runtime/js/cm-fix/execution.mjs +176 -48
  55. package/runtime/js/cm-fix/host.mjs +2 -1
  56. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  57. package/runtime/js/cm-fix/progress.mjs +13 -3
  58. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  59. package/runtime/js/cm-fix/repair.mjs +11 -3
  60. package/runtime/js/cm-fix/test-author.mjs +10 -3
  61. package/runtime/js/cm-idea/session.mjs +67 -4
  62. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  63. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  64. package/runtime/js/cm-prd/review-host.mjs +1 -1
  65. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  66. package/runtime/js/cm-prd/session.mjs +43 -0
  67. package/runtime/js/cm-refactor/records.mjs +98 -8
  68. package/runtime/js/cm-refactor/workflow.mjs +80 -10
  69. package/runtime/js/cm-test/host.mjs +10 -3
  70. package/runtime/js/cm-test/session.mjs +45 -6
  71. package/runtime/js/notify-safe-read.mjs +49 -0
  72. package/runtime/js/notify-send.mjs +313 -0
  73. package/runtime/js/notify.mjs +164 -37
  74. package/runtime/js/policy-binding-compat.mjs +55 -0
  75. package/runtime/review.md +52 -7
  76. package/runtime/task-gates.md +107 -9
  77. package/scripts/ci-test-shards.mjs +67 -0
  78. package/scripts/ci-test-shards.test.mjs +64 -0
  79. package/scripts/ci-test-weights.json +222 -0
  80. package/scripts/cm-ai-abandon-effect-position.test.mjs +71 -10
  81. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  82. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  83. package/scripts/cm-ai-answer-gap-fixture.mjs +89 -0
  84. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  85. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  86. package/scripts/cm-ai-batch-drive.mjs +98 -34
  87. package/scripts/cm-ai-batch-drive.test.mjs +124 -16
  88. package/scripts/cm-ai-batch-host.mjs +167 -29
  89. package/scripts/cm-ai-batch-host.test.mjs +303 -31
  90. package/scripts/cm-ai-batch-run-fixture.mjs +452 -0
  91. package/scripts/cm-ai-batch-run-member-stops.test.mjs +26 -0
  92. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  93. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  94. package/scripts/cm-ai-batch-run.mjs +213 -25
  95. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  96. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  97. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  98. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  99. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  100. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  101. package/scripts/cm-ai-develop-answer-invalid.test.mjs +97 -0
  102. package/scripts/cm-ai-develop-call-timeout.test.mjs +146 -0
  103. package/scripts/cm-ai-develop-driver-gaps.test.mjs +37 -23
  104. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  105. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  106. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  107. package/scripts/cm-ai-drive.mjs +142 -58
  108. package/scripts/cm-ai-drive.test.mjs +70 -84
  109. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  110. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  111. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +267 -0
  113. package/scripts/cm-ai-host-fixture.mjs +296 -0
  114. package/scripts/cm-ai-host-protected.test.mjs +253 -0
  115. package/scripts/cm-ai-host.mjs +122 -100
  116. package/scripts/cm-ai-host.test.mjs +35 -776
  117. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  118. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  119. package/scripts/cm-ai-light-modules.test.mjs +54 -0
  120. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  121. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  122. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  123. package/scripts/cm-ai-progress.test.mjs +10 -8
  124. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  125. package/scripts/cm-ai-protected-scope.test.mjs +8 -5
  126. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  127. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  128. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  129. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +95 -13
  130. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  131. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  132. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +59 -14
  133. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  134. package/scripts/cm-ai-review-failure.test.mjs +137 -32
  135. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  136. package/scripts/cm-ai-review-timeout.test.mjs +132 -67
  137. package/scripts/cm-ai-run.mjs +91 -28
  138. package/scripts/cm-ai-run.test.mjs +11 -38
  139. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  140. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  141. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  142. package/scripts/cm-ai-supersede.test.mjs +489 -51
  143. package/scripts/cm-blocked-reason.test.mjs +2 -3
  144. package/scripts/cm-capability-gate.test.mjs +33 -1
  145. package/scripts/cm-check-drive-files.mjs +8 -0
  146. package/scripts/cm-check-drive.test.mjs +2 -5
  147. package/scripts/cm-check-runtime.sh +4 -2
  148. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  149. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  150. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  151. package/scripts/cm-claude-worker.test.mjs +23 -5
  152. package/scripts/cm-controlled-correction.test.mjs +469 -0
  153. package/scripts/cm-external-batch-host.test.mjs +30 -11
  154. package/scripts/cm-external-model-host.test.mjs +1 -1
  155. package/scripts/cm-external-model-recovery.test.mjs +32 -12
  156. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  157. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  158. package/scripts/cm-fix-abandon.test.mjs +163 -10
  159. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  160. package/scripts/cm-fix-drive.mjs +25 -7
  161. package/scripts/cm-fix-host.mjs +8 -7
  162. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  163. package/scripts/cm-fix-review-recovery.test.mjs +36 -1
  164. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  165. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  166. package/scripts/cm-host-documentation.test.mjs +49 -0
  167. package/scripts/cm-host-qa-executor.test.mjs +23 -12
  168. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  169. package/scripts/cm-host-review-authority.test.mjs +0 -31
  170. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  171. package/scripts/cm-idea-drive.mjs +49 -11
  172. package/scripts/cm-idea-drive.test.mjs +66 -0
  173. package/scripts/cm-idea-host.mjs +106 -16
  174. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  175. package/scripts/cm-init-drive.mjs +41 -7
  176. package/scripts/cm-init-host.mjs +61 -12
  177. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  178. package/scripts/cm-log-event.mjs +21 -10
  179. package/scripts/cm-notify-command.test.mjs +936 -0
  180. package/scripts/cm-notify-read-drift.test.mjs +270 -0
  181. package/scripts/cm-notify.mjs +481 -0
  182. package/scripts/cm-notify.test.mjs +312 -23
  183. package/scripts/cm-patrol.test.mjs +3 -2
  184. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  185. package/scripts/cm-prd-drive.mjs +18 -5
  186. package/scripts/cm-prd-drive.test.mjs +15 -0
  187. package/scripts/cm-prd-host.mjs +37 -4
  188. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  189. package/scripts/cm-prd-review-gate.mjs +56 -0
  190. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  191. package/scripts/cm-refactor-drive.mjs +52 -8
  192. package/scripts/cm-refactor-drive.test.mjs +44 -0
  193. package/scripts/cm-refactor-host.test.mjs +10 -6
  194. package/scripts/cm-release-smoke.sh +2 -0
  195. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  196. package/scripts/cm-task-gate.mjs +368 -34
  197. package/scripts/cm-task-gate.py +2 -0
  198. package/scripts/cm-task-gate.test.mjs +252 -4
  199. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  200. package/scripts/cm-test-drive.mjs +21 -5
  201. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  202. package/scripts/fixtures/claude-review-process.mjs +1 -1
  203. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  204. package/scripts/policy-binding-compat.test.mjs +103 -0
  205. package/scripts/scan-public-safety.py +4 -0
  206. package/scripts/validate-public-repo.py +4 -0
  207. package/skills/cm-ai/SKILL.md +8 -6
  208. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  209. package/skills/cm-ai/references/N4-review.md +11 -21
  210. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  211. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  212. package/skills/cm-ai/references/js-host-modes.md +35 -14
  213. package/skills/cm-ai/references/js-host-qa-recovery.md +85 -11
  214. package/skills/cm-ai/references/js-host-recovery.md +181 -21
  215. package/skills/cm-ai/references/js-host.md +76 -32
  216. package/skills/cm-check/SKILL.md +3 -3
  217. package/skills/cm-fix/SKILL.md +12 -0
  218. package/skills/cm-fix/references/js-host.md +44 -5
  219. package/skills/cm-idea/references/js-host.md +27 -2
  220. package/skills/cm-init/references/js-host.md +17 -4
  221. package/skills/cm-notify/SKILL.md +34 -0
  222. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  223. package/skills/cm-prd/references/js-host.md +1 -1
  224. package/skills/cm-refactor/SKILL.md +12 -0
  225. package/skills/cm-refactor/references/js-host.md +17 -0
  226. package/skills/cm-test/references/js-host.md +14 -1
@@ -17,9 +17,22 @@ import { digest,need,shape,id,text,json,freeze,arrayItems,validIdentity,validTas
17
17
  import { reviewResult,reviewReceipt,boundReviewText,reviewPaths } from './review-runner.mjs';
18
18
  import { checkCompletion } from './gate-bridge.mjs';
19
19
  import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
20
- MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage,
20
+ MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateTaskLearningReviewPackage,
21
21
  reviewRetrySpent,abandonableReviewResult,developBudget,developBudgetExhausted,
22
- completionBlockCount,completionRetriesExhausted,supersededReviewPayload,bootstrapReviewRecoverable,protectedDevelopScope,protectedScopeBlockReason } from './durable-runner-state.mjs';
22
+ MAX_REVIEW_REDISPATCHES,REVIEW_RETRY_CODES,reviewRedispatchCount,reviewRedispatchable,reviewRedispatchExhausted,REVIEW_REDISPATCH_LIMIT_CODE,reviewRedispatchLimitReason,reviewRedispatchStopReason,reviewAbandonRefusal,
23
+ completionBlockCount,completionRetriesExhausted,supersededReviewPayload,bootstrapReviewRecoverable,protectedDevelopScope,protectedScopeBlockReason,
24
+ developTimeoutBasis,developTimeoutEffect,developTimeoutState,DEVELOP_CALL_TIMEOUT_REASON,
25
+ developAnswerInvalidEffect,developAnswerRetryable,developAnswerInvalidReason,
26
+ RECHECK_CODES,COMPLETE_RECHECK_CODE,developRecheckSource,developRecheckCode,developRecheckReason,
27
+ completeRecheckSource,completeRecheckable,completeRecheckReason,
28
+ DEVELOP_REDO_CODE,developAnswerMissingEffect,developRedoCause,developRedoRequiredReason,developRedoReason,
29
+ DISPATCH_RETRY_CODE,developDispatchFailedEffect,developDispatchBasis,developDispatchReason,answerGapLimit,
30
+ pendingDevelopStart,redoDevelopStart,workerGoneBinding,EFFECT_INTERRUPT_LIMIT_CODE,effectInterruptLimitReason,developRedoSource,COMMIT_INTERRUPTED_CODE,COMMIT_INTERRUPTED_REASON,
31
+ DOCUMENTATION_SYNC_CODES,documentationSyncSource,documentationSyncRetryCode,documentationSyncStopReason } from './durable-runner-state.mjs';
32
+ import {splitDocumentationState} from './host-documentation.mjs';
33
+ import {readControlPolicy} from './control-policy.mjs';
34
+ import {readProcessStartTime,inspectWorkerGroup} from './worker-process-identity.mjs';
35
+ import {recoverRunnerCommitImage} from './task-commit.mjs';
23
36
  import {commitRunnerFixture} from './task-commit.mjs';
24
37
  import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure} from './provider-review-observation.mjs';
25
38
  import {attachCmAiTaskLearningApplicationEvidence,attachCmAiTaskLearningEvidence,
@@ -139,12 +152,18 @@ export function createTaskRunner(options) {
139
152
  if(options && Object.hasOwn(options,'codeProjectPaths'))optionKeys.push('codeProjectPaths');
140
153
  if(options && Object.hasOwn(options,'verificationGate'))optionKeys.push('verificationGate');
141
154
  if(options && Object.hasOwn(options,'providerDevelopment'))optionKeys.push('providerDevelopment');
155
+ if(options && Object.hasOwn(options,'protectedDevelopment'))optionKeys.push('protectedDevelopment');
142
156
  if(options && Object.hasOwn(options,'knowledgeCloseout'))optionKeys.push('knowledgeCloseout');
143
157
  if(options && Object.hasOwn(options,'executionPolicy'))optionKeys.push('executionPolicy');
144
158
  if(options && Object.hasOwn(options,'externalModels'))optionKeys.push('externalModels');
159
+ if(options && Object.hasOwn(options,'controlPolicy'))optionKeys.push('controlPolicy');
145
160
  if(invocationMode)optionKeys.push('reviewInvocation');
146
161
  shape(options,optionKeys);
147
162
  need(options.providerDevelopment===undefined||typeof options.providerDevelopment==='boolean','invalid_input');
163
+ // Transient like providerDevelopment, never journaled: protected current-session
164
+ // development applies proposals in a sandbox, so a stuck develop there may be a
165
+ // partial write and gets no develop_redo exit (durable-runner-state.mjs).
166
+ need(options.protectedDevelopment===undefined||typeof options.protectedDevelopment==='boolean','invalid_input');
148
167
  const {check,commit}=options;need(typeof check==='function' && (taskMode||typeof commit==='function'));
149
168
  // Opt-in gate between the task's own checks and the independent review. It may
150
169
  // only block: passing it grants nothing and never substitutes for that review.
@@ -174,10 +193,10 @@ export function createTaskRunner(options) {
174
193
  if(invocationMode)id(r.adapterId);
175
194
  return {...v,...(invocationMode?{adapterId:r.adapterId}:{}),run};
176
195
  });
177
- let invocationConfig=null,authorize=null,liveHostContextId=null,reviewTimeoutMs=null;
196
+ let invocationConfig=null,liveHostContextId=null,reviewTimeoutMs=null;
178
197
  if(invocationMode){
179
198
  need(reviewers.length===1&&['codex','claude'].includes(reviewers[0].provider)&&reviewers[0].allowed&&reviewers[0].available,'runner_invocation');
180
- shape(options.reviewInvocation,['developerThreadId','excludedThreadIds','authorize',
199
+ shape(options.reviewInvocation,['developerThreadId','excludedThreadIds',
181
200
  ...['hostContextId','timeoutMs'].filter(key=>Object.hasOwn(options.reviewInvocation,key))]);
182
201
  liveHostContextId=options.reviewInvocation.hostContextId??null;
183
202
  // Transient like hostContextId, never journaled: the host sizes the review
@@ -188,7 +207,6 @@ export function createTaskRunner(options) {
188
207
  }
189
208
  if(liveHostContextId!==null){id(liveHostContextId);
190
209
  need(![developer.contextId,...reviewers.flatMap(r=>r.contexts)].includes(liveHostContextId),'not_independent');}
191
- authorize=options.reviewInvocation.authorize;need(typeof authorize==='function','runner_invocation');
192
210
  invocationConfig=json({developerThreadId:options.reviewInvocation.developerThreadId,
193
211
  excludedThreadIds:options.reviewInvocation.excludedThreadIds});
194
212
  id(invocationConfig.developerThreadId);need(Array.isArray(invocationConfig.excludedThreadIds)
@@ -201,7 +219,8 @@ export function createTaskRunner(options) {
201
219
  ...(Object.hasOwn(options,'taskLearning')?{taskLearning:json(options.taskLearning)}:{}),
202
220
  ...(Object.hasOwn(options,'knowledgeCloseout')?{knowledgeCloseout:readCloseoutPolicy(options.knowledgeCloseout)}:{}),
203
221
  ...(Object.hasOwn(options,'executionPolicy')?{executionPolicy:readExecutionPolicy(options.executionPolicy)}:{}),
204
- ...(Object.hasOwn(options,'externalModels')?{externalModels:readExternalModels(options.externalModels)}:{})});
222
+ ...(Object.hasOwn(options,'externalModels')?{externalModels:readExternalModels(options.externalModels)}:{}),
223
+ ...(Object.hasOwn(options,'controlPolicy')?{controlPolicy:readControlPolicy(options.controlPolicy)}:{})});
205
224
  const taskLearning=metadata.taskLearning??null;
206
225
  if(taskLearning!==null){need(taskMode,'runner_learning');
207
226
  shape(taskLearning,['feature',...(Object.hasOwn(taskLearning,'hostHandoff')?['hostHandoff']:[])]);
@@ -212,7 +231,7 @@ export function createTaskRunner(options) {
212
231
  metadata=json({...metadata,bootstrap:bootstrapConfiguration(bootstrap,{root:config.root,identity:config.identity,
213
232
  scope:config.scope,feature:taskLearning.feature})});
214
233
  }
215
- let store=null,journal=null,restored=null,storeRevision=null,poisoned=false;
234
+ let store=null,journal=null,restored=null,storeRevision=null,poisoned=false,parsedHistory=null;
216
235
  let completion=null,storeIdentity=null,storeOperating=false,liveToken=null,completeEffect=null,taskCommit=null;
217
236
  const version=taskMode?(invocationMode?3:2):1;
218
237
  if(Object.hasOwn(options,'persistence')) {
@@ -238,7 +257,7 @@ export function createTaskRunner(options) {
238
257
  completion=json({version:1,mode:'fixture-task',owner:completion.owner,fingerprints:saved.fingerprints,...selection});
239
258
  storeIdentity=saved.identity;metadata=json({...metadata,completion});
240
259
  }
241
- if(options.persistence.mode==='resume')restored=readRunnerHistory(journal,metadata,version);
260
+ if(options.persistence.mode==='resume')parsedHistory=restored=readRunnerHistory(journal,metadata,version);
242
261
  else need(journal.length===0,'runner_exists');
243
262
  }
244
263
  // Transient live identity is deliberately absent from metadata/init bytes.
@@ -287,14 +306,24 @@ export function createTaskRunner(options) {
287
306
  // derivation in one place, next to the cache it is derived from.
288
307
  const verificationBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='develop'
289
308
  &&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;
309
+ &&['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','develop_call_timeout'].includes(entry.result?.code)
310
+ ||developTimeoutEffect(entry)||developAnswerInvalidEffect(entry)||developRecheckSource(entry)||developRedoSource(entry)||developDispatchFailedEffect(entry)
311
+ ||documentationSyncSource(entry)).length;
291
312
  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;
313
+ &&entry.result?.state==='blocked'&&['completion_checks_changed','completion_package_changed'].includes(entry.result?.code)
314
+ ||completeRecheckSource(entry)).length;
293
315
  const privateStatus=()=>json({state,code,...(reason?{reason}:{}),
294
- ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pendingAbandonable
316
+ ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pending
317
+ &&(restored.pendingAbandonable||restored.pendingInterruptible||restored.pendingReviewExhausted||restored.pendingWorkerVoidable)
295
318
  ?{pendingEffectKind:restored.pending.kind}:{}),
319
+ // Q16: this interruption is a documentation retry; abandon_effect resends only documentation_sync.
320
+ ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pending?.kind==='develop'
321
+ &&restored.pendingInterruptible&&restored.pendingDocumentation!=null?{documentationSyncPending:true}:{}),
322
+ // R2: the interruption cap is spent; abandon_effect now only voids the run.
323
+ ...(state==='unknown'&&restored?.pending&&restored.pendingInterruptLimit
324
+ ?{code:EFFECT_INTERRUPT_LIMIT_CODE,reason:effectInterruptLimitReason(restored.pending.kind)}:{}),
296
325
  ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pending?.kind==='review'
297
- &&restored.state.reviewInvocation?.registration&&restored.state.reviewInvocation.result===null
326
+ &&restored.state.reviewInvocation?.registration&&(restored.state.reviewInvocation.result===null||restored.pendingResultAbandonable)
298
327
  ?{pendingReviewInvocation:true}:{}),
299
328
  identity:{...config.identity,attempt},packageDigest:reviewPackage?.packageDigest??null,
300
329
  receipt,receipts,calls,cancelAfterCommit,workflowError,...(store?{cancellationRequested}:{}),...(taskMode?{taskCommit}:{}),
@@ -319,20 +348,283 @@ export function createTaskRunner(options) {
319
348
  // Replay decides; this only reports an exit abandonReview would accept.
320
349
  function reviewResultAbandonable(){
321
350
  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]);
351
+ &&abandonableReviewResult({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1],reviewRedispatchRecords());
323
352
  }
353
+ // V5 (A34): review-redispatch records of this round (written by abandon_review).
354
+ function reviewRedispatchRecords(){
355
+ return journal?.filter(row=>row.payload.type==='review-redispatch'&&row.payload.attempt===attempt).length??0;
356
+ }
357
+ // The entry derives each redispatch id from the current round's durable effects,
358
+ // so an id cannot repeat one the cache already holds.
359
+ const reviewEffectIds=()=>[...cache.values()].filter(entry=>entry.effect.kind==='review'
360
+ &&entry.effect.identity.attempt===attempt).map(entry=>entry.effect.id);
361
+ // A spent retryable review block this round may still redispatch (advance).
362
+ const reviewRedispatchLive=()=>Boolean(!(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned
363
+ &&!restored?.pending&&reviewRedispatchable({state,code,attempt,cache:[...cache.values()],calls,reviewInvocation},
364
+ reviewers[0].contexts[attempt-1],reviewRedispatchRecords()));
365
+ const reviewRedispatchSpent=()=>Boolean(!(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned
366
+ &&!restored?.pending&&reviewRedispatchExhausted({state,code,attempt,cache:[...cache.values()],calls,reviewInvocation},
367
+ reviewers[0].contexts[attempt-1],reviewRedispatchRecords()));
368
+ // A develop cut off by the host answer limit (unknown/call_timeout) whose
369
+ // start the journal pins, checked against the code root now: true only when
370
+ // nothing of it reached the disk. Never journaled by status; advance records
371
+ // develop-timeout-retry before redoing the round (see executeEffect).
372
+ function developTimeoutRetryBasis(){
373
+ if(!store||!taskMode||busy||poisoned||!developTimeoutState({state,code})||restored?.pending&&!cache.has(restored.pending.id))return null;
374
+ const basis=developTimeoutBasis({state,code,attempt,cache:[...cache.values()],calls,reviewPackage,priorReview},metadata.bootstrap);
375
+ if(basis===null)return null;
376
+ try{
377
+ if(basis==='reviewed_package')verifyReviewPackage({root:config.root,baseline:attemptBaseline(original,reviewPackage.identity.attempt),
378
+ checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
379
+ else assertReadyBaseline();
380
+ }catch{return null;}
381
+ return basis;
382
+ }
383
+ // A journaled blocked/failed develop whose current-session answer failed local
384
+ // validation: shown as the retryable block; advance journals develop-answer-retry.
385
+ const answerRetryable=()=>Boolean(store&&taskMode&&!busy&&!poisoned&&!(restored?.pending&&!cache.has(restored.pending.id))
386
+ &&developAnswerRetryable({state,code,attempt,cache:[...cache.values()]},metadata.bootstrap));
387
+ // V3 answer gaps (durable-runner-state.mjs): a delivered develop or a complete
388
+ // whose later re-check never got a usable answer. Status shows the retryable
389
+ // block; advance journals develop-recheck / complete-recheck first.
390
+ const answerGapCount=type=>journal?.filter(row=>row.payload.type===type).length??0;
391
+ const gapsLive=()=>Boolean(store&&taskMode&&invocationMode&&!busy&&!poisoned&&!(restored?.pending&&!cache.has(restored.pending.id)));
392
+ const developRecheck=()=>gapsLive()?developRecheckCode({state,code,attempt,cache:[...cache.values()],learningResult,receipt},
393
+ metadata,answerGapCount('develop-recheck')):null;
394
+ const completeRecheck=()=>gapsLive()&&completeRecheckable({state,code,attempt,cache:[...cache.values()],taskCommit},
395
+ answerGapCount('complete-recheck'));
396
+ // V2 + R3: a stuck current-session develop that only an operator confirmation
397
+ // (develop_redo) may redo. Returns the cause or null.
398
+ // Provider development (V9) qualifies only with its worker identity journaled.
399
+ const providerRun=developer.requestedModel!=='current-session';
400
+ const developRedoRequired=()=>{
401
+ if(!gapsLive()||!providerRun&&(options.protectedDevelopment===true||options.providerDevelopment===true))return null;
402
+ return developRedoCause({state,code,attempt,cache:[...cache.values()],calls,receipt},metadata,
403
+ answerGapCount('develop-answer-redo'),parsedHistory?.workers??null);
404
+ };
405
+ // Q16/Q17: the final task's develop journals the developer answer it accepted
406
+ // and the documentation start (documentation-sync-started) right before the
407
+ // adapter asks documentation_sync, and marks its developer call with the
408
+ // record. A sync that then fails is redone alone, from that record.
409
+ const documentationJournaling=()=>Boolean(invocationMode&&store&&taskMode&&bootstrap===null&&!metadata.bootstrap);
410
+ function journalDocumentationSync(effectId,raw){
411
+ const event=json(raw,512*1024);shape(event,['result','effectiveModel','documents','othersDigest']);
412
+ const call=calls.at(-1);need(call?.terminal==='running'&&!Object.hasOwn(call,'documentationSync'),'invalid_input');
413
+ const record=persist('documentation-sync-started',{effectId,invocationId:call.invocationId,...event});
414
+ call.documentationSync=record.digest;
415
+ }
416
+ const documentationRecord=value=>journal?.find(row=>row.digest===value&&row.payload.type==='documentation-sync-started')?.payload??null;
417
+ // The run's documentation-sync retries so far, as the journal counts them.
418
+ const documentationRetries=()=>parsedHistory?.answerGaps?.documentationSync??0;
419
+ // The checkpointed documentation_sync failure the last develop left, still
420
+ // waiting for its stop confirmation, with its start record; or null.
421
+ function documentationSyncRetry(){
422
+ if(!gapsLive()||!documentationJournaling()||options.providerDevelopment===true)return null;
423
+ const retry=documentationSyncRetryCode({state,code,attempt,cache:[...cache.values()]},metadata,documentationRetries());
424
+ const source=retry===null?null:documentationRecord(calls.at(-1)?.documentationSync);
425
+ return source?{code:retry,source,detail:[...cache.values()].at(-1).result.reason??null}:null;
426
+ }
427
+ // The latest stop confirmation for the source call: documentation-sync-retry
428
+ // (develop_redo) or effect-interrupted (abandon_effect), bound to its start.
429
+ const documentationStopRecord=start=>journal?.findLast(row=>['documentation-sync-retry','effect-interrupted'].includes(row.payload.type)
430
+ &&row.payload.startDigest===start)?.payload??null;
431
+ // A confirmed documentation block: what the redo reuses and is checked against.
432
+ function documentationRedoSource(){
433
+ if(!gapsLive()||!documentationJournaling()||state!=='blocked'||!DOCUMENTATION_SYNC_CODES.includes(code))return null;
434
+ const start=calls.at(-1)?.documentationSync,source=documentationRecord(start),stop=documentationStopRecord(start);
435
+ return source&&stop?{code,source,stop}:null;
436
+ }
437
+ // The Learning input of the develop effect whose sync is redone (checkpointed
438
+ // or interrupted): the redo reuses its developer answer, so it binds the same.
439
+ const documentationRedoLearningInput=()=>{
440
+ const stop=documentationRedoSource()?.stop;
441
+ return journal.findLast(row=>row.payload.type==='effect-intent'&&row.payload.effect.id===stop?.effectId)?.payload.effect.learningInput;
442
+ };
443
+ // The code root under the task's own fixed snapshot rules (the full develop
444
+ // scope and the ignore policy bound at create, as the task baseline), split
445
+ // at the documentation paths. The adapter takes its start and end with it too.
446
+ function documentationSnapshot(paths){
447
+ const baseline=captureReviewBaseline({...configToBaseline(metadata),version:original.version,
448
+ ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
449
+ !Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
450
+ original.ignorePolicy?.version===2?original.ignorePolicy:null);
451
+ return splitDocumentationState(baseline.files,paths);
452
+ }
453
+ const documentationRefusal=(refusal,detail)=>Object.assign(new Error(refusal),{code:refusal,reason:{
454
+ documentation_sync_out_of_scope:`documentation_sync_out_of_scope: 文档路径以外的文件已不等于文档同步开始时的内容${detail?`(${detail.replace(/^out_of_scope:\s*/,'')})`:''},`
455
+ +'可能是文档同步越界写的,也可能是之后的改动。先把它们还原到文档同步开始时的内容(git diff 查看差异;确需修改先走规格变更),再 advance 只重发文档同步。',
456
+ documentation_sync_stop_required:'documentation_sync_stop_required: 宿主无法证明文档同步的写入方已停止;先确认会话已停止修改文档,再以 --mode resume --allow-develop-redo 发送 develop_redo,之后 advance 只重发文档同步。',
457
+ documentation_sync_changed_after_stop:'documentation_sync_changed_after_stop: 文档路径在确认停写之后又变了,旧的文档同步可能仍在写。若是你自己的修改,确认会话已停后再发送一次 develop_redo 重新确认(不另占次数),再 advance;否则先让会话停下。',
458
+ documentation_sync_capture_failed:`documentation_sync_capture_failed: 宿主无法读取代码根来核对文档同步的起点(${detail});修好后再试。`}[refusal]});
459
+ // The live documentation state, or the refusal when the code root cannot be read.
460
+ function documentationLive(paths){
461
+ try{return documentationSnapshot(paths);}
462
+ catch(error){throw documentationRefusal('documentation_sync_capture_failed',failureCode(error));}
463
+ }
464
+ // The disk gate before every documentation-only redo (also after a restart):
465
+ // the rest of the code root equals the documentation start, and the
466
+ // documentation paths equal what they were when the stop was confirmed.
467
+ function assertDocumentationRedo(redo){
468
+ const live=documentationLive(redo.source.documents.map(item=>item.path));
469
+ if(live.othersDigest!==redo.source.othersDigest)throw documentationRefusal('documentation_sync_out_of_scope',
470
+ redo.code==='documentation_sync_out_of_scope'?[...cache.values()].at(-1)?.result.reason??null:null);
471
+ if(digest(live.documents)!==digest(redo.stop.documents))throw documentationRefusal('documentation_sync_changed_after_stop');
472
+ }
473
+ // V9: provider development journals its worker's identity (develop-worker):
474
+ // spawning right before the spawn, started (pid = process group, start time)
475
+ // right after. A throw here makes the spawn wrapper kill the new group.
476
+ // Protected development also journals each sandbox subprocess that applies a
477
+ // proposal (apply_spawning / apply_started): it may outlive a dead host too.
478
+ const workerJournaling=()=>Boolean(invocationMode&&store&&taskMode
479
+ &&(developer.requestedModel!=='current-session'||options.protectedDevelopment===true));
480
+ function journalWorker(effectId,raw){
481
+ const event=json(raw),started=['started','apply_started'].includes(event?.phase);
482
+ shape(event,['phase',...(started?['pid']:[])]);
483
+ need(['spawning','started','apply_spawning','apply_started'].includes(event.phase),'invalid_input');
484
+ persist('develop-worker',{effectId,invocationId:calls.at(-1).invocationId,phase:event.phase,
485
+ ...(started?{pid:event.pid,startTime:readProcessStartTime(event.pid)}:{})});
486
+ }
487
+ // The host's proof for a provider develop: 'none' (never spawned), 'gone',
488
+ // or a refusal code. Windows, permission errors and unreadable start times
489
+ // are unknown, never gone.
490
+ // checkpointed: the host was alive after the spawn, so a spawned child with a
491
+ // pid was journaled in the same tick; spawning alone then means no process.
492
+ // Every started writer is checked: the provider worker and each proposal
493
+ // apply subprocess.
494
+ function workerProof(worker,{checkpointed=false}={}){
495
+ if(worker?.journal!==true)return {code:'worker_identity_unrecorded'};
496
+ if(!checkpointed&&(worker.spawned&&worker.started===null||worker.applies.some(item=>item.started===null)))
497
+ return {code:'worker_identity_incomplete'};
498
+ const binding=workerGoneBinding(worker);
499
+ if(binding===null)return {proof:'none'};
500
+ for(const started of [worker.started,...worker.applies.map(item=>item.started)].filter(Boolean)){
501
+ const verdict=inspectWorkerGroup(started);
502
+ if(verdict!=='gone')return {code:verdict==='alive'?'worker_process_alive':'worker_process_unknown',pid:started.pid};
503
+ }
504
+ return {proof:'gone',binding};
505
+ }
506
+ // V6: where writes are applied proposals, the live root must still equal the
507
+ // journal-pinned round start (no partial apply is sent to review).
508
+ function verifyRoundStart(basis,prefix,what){
509
+ const refuse=(code,detail)=>{throw Object.assign(new Error(code),{code,reason:detail});};
510
+ if(basis===null)refuse(`${prefix}_root_unpinned`,`${what}的本轮起点无法从运行存档确定(本轮之前已有被拦下的交付),宿主不能证明中途没有写到一半;核对后用新建运行替代。`);
511
+ try{
512
+ if(basis==='reviewed_package')verifyReviewPackage({root:config.root,baseline:attemptBaseline(original,reviewPackage.identity.attempt),
513
+ checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
514
+ else assertReadyBaseline();
515
+ }catch(error){refuse(`${prefix}_root_changed`,boundedReason(`${what}中途退出后代码根已不等于本轮起点(可能是应用到一半的提案):`,
516
+ [safeReason(error)??error?.code??'changed'],'。把这些文件还原到本轮起点后重试;半成品不会被当成新交付送审。'));}
517
+ return basis;
518
+ }
519
+ const workerRefusal=(prefix,result)=>({code:`${prefix}_${result.code}`,reason:{
520
+ worker_identity_unrecorded:'这次 provider 开发没有在运行存档里记下 worker 进程身份(旧版本建的 effect,或未配置 provider 模型),宿主无法证明进程已退出;按 reason 手工核对后只能新建运行替代。',
521
+ worker_identity_incomplete:'运行存档只记到 worker 即将启动,没有记下 pid,宿主无法证明进程已退出;请手工确认该 provider 进程已不存在后,用新建运行替代。',
522
+ worker_process_alive:`provider worker 或提案应用子进程的进程组(pid ${result.pid})仍在运行,可能还在写文件;等它退出或手工结束该进程组后再试。`,
523
+ worker_process_unknown:`宿主无法核对进程组(pid ${result.pid})是否已退出(Windows、无权限或读不到启动时间),不放行;确认进程已退出后在能核对的环境重试。`}[result.code]});
524
+ // P1-3: a develop that failed before dispatch. A legacy execution_error also
525
+ // needs the live code root to still equal the journal-pinned round start.
526
+ function developDispatchRetry(){
527
+ if(!gapsLive()||options.providerDevelopment===true)return null;
528
+ const basis=developDispatchBasis({state,code,attempt,cache:[...cache.values()],calls,receipt,reviewPackage,priorReview},
529
+ metadata,answerGapCount('develop-dispatch-retry'));
530
+ if(basis===null)return null;
531
+ try{
532
+ if(basis==='reviewed_package')verifyReviewPackage({root:config.root,baseline:attemptBaseline(original,reviewPackage.identity.attempt),
533
+ checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
534
+ else assertReadyBaseline();
535
+ }catch{return null;}
536
+ return basis;
537
+ }
538
+ // A45: the host died between task-commit-intent and task-commit-result. Only
539
+ // the journaled commit plan is followed (recoverCommit); complete is never redone.
540
+ // A result already journaled (a recovery that died before its checkpoint)
541
+ // closes the same effect with the checkpoint only.
542
+ const commitRecoveryTransaction=()=>!invocationMode||!store||busy||poisoned||restored?.pending?.kind!=='complete'
543
+ ||!restored.transaction?null:restored.transaction;
544
+ // The Learning input a re-check must carry: exactly the delivered develop's.
545
+ // A documentation-only redo reuses that develop's answer, so it carries the
546
+ // input bound to it too (a LESSONS.md edited meanwhile changes a fresh read).
547
+ const recheckLearningInput=()=>{
548
+ if(RECHECK_CODES.includes(status().code))return json([...cache.values()].at(-1).effect.learningInput);
549
+ const bound=documentationRedoSource()===null?undefined:documentationRedoLearningInput();
550
+ return bound===undefined?null:json(bound);
551
+ };
324
552
  const status=()=>{
325
553
  let current=store?publication:privateStatus();
554
+ if(current.state==='unknown'&&commitRecoveryTransaction()!==null){
555
+ const {reason:discard,...rest}=current;
556
+ current=freeze({...rest,state:'blocked',code:COMMIT_INTERRUPTED_CODE,reason:COMMIT_INTERRUPTED_REASON});
557
+ }
558
+ if(current.state==='unknown'){
559
+ const recheck=developRecheck();
560
+ if(recheck!==null)current=freeze({...current,state:'blocked',code:recheck,reason:developRecheckReason(recheck,current.code,current.reason)});
561
+ else if(completeRecheck())current=freeze({...current,state:'blocked',code:COMPLETE_RECHECK_CODE,reason:completeRecheckReason(current.code)});
562
+ }
563
+ if(current.state==='blocked'&&current.code==='failed'&&answerRetryable())
564
+ current=freeze({...current,code:'develop_answer_invalid',reason:developAnswerInvalidReason(calls.at(-1).failureResult)});
565
+ if(developTimeoutState(current)){
566
+ const {reason:discard,...rest}=current;
567
+ current=developTimeoutRetryBasis()!==null
568
+ ?freeze({...rest,state:'blocked',code:'develop_call_timeout',reason:DEVELOP_CALL_TIMEOUT_REASON})
569
+ :freeze({...rest,state:'unknown',code:'call_timeout',...(current.state==='blocked'
570
+ ?{reason:'develop_call_timeout: 代码根已不等于本轮开发起点(超时后有写入),不能重发;按 unknown 只读核对。'}:{})});
571
+ }
572
+ if(current.state==='unknown'){
573
+ const basis=developDispatchRetry();
574
+ if(basis!==null){const {reason:discard,...rest}=current;
575
+ current=freeze({...rest,state:'blocked',code:DISPATCH_RETRY_CODE,reason:developDispatchReason(current.code)});}
576
+ }
577
+ // The journaled block keeps its start binding: a changed root falls to develop_redo below.
578
+ if(current.state==='blocked'&&current.code===DISPATCH_RETRY_CODE&&developDispatchRetry()===null){
579
+ const {reason:discard,...rest}=current;current=freeze({...rest,state:'unknown',code:[...cache.values()].at(-1).result.code});
580
+ }
581
+ // Q16/Q17: a failed documentation_sync of the final task (never develop_redo).
582
+ if(current.state==='unknown'){
583
+ const retry=documentationSyncRetry();
584
+ if(retry!==null){
585
+ const {reason:discard,...rest}=current;
586
+ current=freeze({...rest,state:'blocked',code:retry.code,reason:documentationSyncStopReason(retry.code,retry.detail),developRedoRequired:true});
587
+ }
588
+ }
589
+ if(current.state==='unknown'||current.state==='blocked'&&['failed','unavailable'].includes(current.code)){
590
+ const cause=developRedoRequired();
591
+ if(cause!==null){const {reason:discard,...rest}=current;
592
+ current=freeze({...rest,state:'blocked',code:DEVELOP_REDO_CODE,reason:developRedoRequiredReason(cause),developRedoRequired:true});}
593
+ }
594
+ // R2: a spent exit is an explicit limit block, never an exit-less unknown.
595
+ if((current.state==='unknown'||current.state==='blocked'&&['failed','unavailable'].includes(current.code))&&gapsLive()
596
+ &&(options.providerDevelopment!==true||providerRun)){
597
+ const limit=answerGapLimit({state,code,attempt,cache:[...cache.values()],calls,receipt,learningResult,taskCommit,reviewPackage,priorReview},
598
+ metadata,{developRecheck:answerGapCount('develop-recheck'),completeRecheck:answerGapCount('complete-recheck'),
599
+ developRedo:answerGapCount('develop-answer-redo'),developDispatch:answerGapCount('develop-dispatch-retry'),
600
+ documentationSync:documentationRetries(),
601
+ workers:parsedHistory?.workers??null});
602
+ if(limit!==null&&(options.providerDevelopment===true?limit.code==='develop_redo_limit'
603
+ :!(options.protectedDevelopment===true&&limit.code==='develop_redo_limit'))){
604
+ const {reason:discard,...rest}=current;current=freeze({...rest,state:'blocked',code:limit.code,reason:limit.reason});}
605
+ }
326
606
  if(!busy&&!poisoned&&bootstrapReviewRecoverable(frame(),restored?.pending??null,metadata.bootstrap))
327
607
  current=freeze({...current,bootstrapReviewRecovery:true});
608
+ // V5: a spent retryable review block with a no-result redispatch left stays
609
+ // blocked until the operator confirms the original reviewer stopped
610
+ // (abandon_review journals review-redispatch); a fully spent round is an
611
+ // explicit limit block.
612
+ if(current.state==='blocked'&&reviewRedispatchLive())
613
+ current=freeze({...current,reviewRedispatchStopRequired:true,reason:reviewRedispatchStopReason(current.code)});
614
+ else if(current.state==='blocked'&&reviewRedispatchSpent())
615
+ current=freeze({...current,code:REVIEW_REDISPATCH_LIMIT_CODE,reason:reviewRedispatchLimitReason(current.code)});
328
616
  // Status only; never part of a cached result or checkpoint.
329
617
  if(current.state==='unknown'&&reviewResultAbandonable())current=freeze({...current,abandonableReviewResult:true});
618
+ else if(current.state==='unknown'&&!(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned&&!restored?.pending){
619
+ const refusal=reviewAbandonRefusal({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1],reviewRedispatchRecords());
620
+ if(refusal)current=freeze({...current,reason:`${refusal.code}: ${refusal.reason}`,reviewAbandonRefusal:refusal.code});
621
+ }
330
622
  const available=Boolean((metadata.externalModels||metadata.executionPolicy))&&!busy&&!poisoned&&invocationMode&&store&&['unknown','pending_review'].includes(current.state)
331
623
  &&readRunnerHistory(journal,metadata,3).reviewReconciliation!==null;
332
624
  if((metadata.externalModels||metadata.executionPolicy)&&!busy&&!poisoned&&invocationMode&&store&&reviewInvocation?.registration
333
625
  &&(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,
626
+ const binding=reviewInvocation.registration.binding;
627
+ current=freeze({...current,reviewReconciliation:{invocationId:binding.invocationId,requestDigest:binding.requestDigest,
336
628
  provider:reviewers[0].provider,providerThreadId:reviewInvocation.started,available},
337
629
  reason:available?'原调用的终态与本地清理收据已保存;使用 reconcile_review 接纳证据,此操作不派发模型。'
338
630
  :'缺少原调用的可信终态或本地清理证据。保留本 run、attempt、journal 和快照;按 invocationId / providerThreadId 向原宿主或 provider 核对结果及终止状态,并确认本地后代已退出。当前适配器没有远端状态查询入口,人工说明、PID 消失或重启均不能解锁;不要删 journal、换 runId 或重派。'});
@@ -400,6 +692,12 @@ export function createTaskRunner(options) {
400
692
  }
401
693
  };
402
694
  const halt=(next,why,detail=null)=>{state=next;code=why;reason=detail;};
695
+ function assertReadyBaseline(){
696
+ compareReviewBaseline(withBoundSpecification(captureReviewBaseline({...configToBaseline(metadata),version:original.version,
697
+ ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
698
+ !Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
699
+ original.ignorePolicy?.version===2?original.ignorePolicy:null)),original);
700
+ }
403
701
  const specificationLive=(currentState,currentCode)=>Object.hasOwn(original,'specification')
404
702
  &&['develop','review','complete'].some(kind=>stageAllowed(kind,currentState,currentCode,priorReview?.verdict));
405
703
  function frame(){return {state,code,reason,attempt,session,sequence,reviewPackage,currentChecks,receipt,receipts,calls,
@@ -425,7 +723,7 @@ export function createTaskRunner(options) {
425
723
  'review-invocation-registered':'intent','review-invocation-started':'result','review-invocation-result':'result',
426
724
  'review-invocation-abandoned':'result','review-invocation-receipt':'result','review-invocation-reconciled':'result','effect-abandoned':'result',
427
725
  'host-joined':'result','qa-fix-accepted':'result','qa-attached':'result','qa-config-revised':'result',
428
- 'evidence-superseded':'result','develop-retry-limit':'result','completion-retry-limit':'result','specification-rebound':'result',
726
+ 'evidence-superseded':'result','develop-retry-limit':'result','develop-worker':'result','effect-interrupted':'result','develop-timeout-retry':'result','develop-answer-retry':'result','develop-recheck':'result','complete-recheck':'result','develop-answer-redo':'result','develop-dispatch-retry':'result','review-redispatch':'result','review-dispatch-confirmed':'result','completion-retry-limit':'result','specification-rebound':'result','documentation-sync-started':'result','documentation-sync-retry':'result',
429
727
  'bootstrap-review-recovered':'result'}[type],
430
728
  payload:version===3?runnerPayloadV3(type,fields):runnerPayload(type,fields,version)};
431
729
  const body={version:1,seq:journal.length+1,...basic,previousDigest:journal.at(-1)?.digest??null};
@@ -449,7 +747,7 @@ export function createTaskRunner(options) {
449
747
  const saved=store.snapshot();need(!poisoned,'store_failure');
450
748
  const {revision:old,...body}=current,expected={...body,records:[...journal,record]};
451
749
  same(saved,{...expected,revision:digest(expected)},'runner_store_changed');
452
- need(!poisoned,'store_failure');journal=saved.records;storeRevision=saved.revision;
750
+ need(!poisoned,'store_failure');journal=saved.records;storeRevision=saved.revision;parsedHistory=parsed;
453
751
  if(type.startsWith('task-commit-'))taskCommit=parsed.state.taskCommit;
454
752
  return record;
455
753
  });
@@ -540,7 +838,7 @@ export function createTaskRunner(options) {
540
838
  return status();
541
839
  }
542
840
  function active(){need(!poisoned,'store_failure');need(state!=='cancelled','cancelled');}
543
- async function bounded(fn,request) {
841
+ async function bounded(fn,request,extraControl=null) {
544
842
  active();let timer,abort;
545
843
  try {
546
844
  const boxed=await Promise.race([
@@ -549,7 +847,7 @@ export function createTaskRunner(options) {
549
847
  const accept=value=>{try {resolve({value:json(value)});}catch(error){reject(error);}};
550
848
  queueMicrotask(()=>{
551
849
  try {
552
- active();const returned=fn(request,{signal:controller.signal});
850
+ active();const returned=fn(request,{signal:controller.signal,...(extraControl??{})});
553
851
  if(types.isPromise(returned)) {
554
852
  const supported=Object.getPrototypeOf(returned)===promisePrototype
555
853
  && !Object.hasOwn(returned,'constructor');
@@ -569,14 +867,14 @@ export function createTaskRunner(options) {
569
867
  return boxed.value;
570
868
  } finally {clearTimeout(timer);controller.signal.removeEventListener('abort',abort);}
571
869
  }
572
- async function invoke(adapter,role,contextId,payload) {
870
+ async function invoke(adapter,role,contextId,payload,extraControl=null) {
573
871
  const request=requestFor({invocationId:`${session}.${++sequence}`,identity:{...config.identity,attempt},
574
872
  role,provider:adapter.provider,requestedModel:adapter.requestedModel,contextId,payload});
575
873
  const call={invocationId:request.invocationId,contextId,provider:adapter.provider,requestedModel:adapter.requestedModel,
576
874
  effectiveModel:'unknown',channel:'fixture',started:true,terminal:'running',requestDigest:request.requestDigest,resultDigest:null};
577
875
  calls.push(call);
578
876
  try {
579
- const response=terminalFor(await bounded(adapter.run,request),request);active();
877
+ const response=terminalFor(await bounded(adapter.run,request,extraControl),request);active();
580
878
  call.terminal=response.status;call.effectiveModel=response.effectiveModel;call.resultDigest=digest(response.result);
581
879
  if(role==='developer'&&response.status==='failed'&&response.result!==null)call.failureResult=response.result;
582
880
  if(role==='developer'&&Object.hasOwn(response,'blockedReason'))call.blockedReason=response.blockedReason;
@@ -613,60 +911,26 @@ export function createTaskRunner(options) {
613
911
  const nextSequence=sequence+1,request=requestFor({invocationId:`${session}.${nextSequence}`,
614
912
  identity:{...config.identity,attempt},role:'reviewer',provider:adapter.provider,
615
913
  requestedModel:adapter.requestedModel,contextId,payload});
616
- let authorizationAt;
617
- try{authorizationAt=safeTime();}catch{halt('unknown','clock_invalid');return;}
618
- let grant;
619
- try{
620
- const returned=authorize(request,Object.freeze({authorizationAt}));
621
- if(types.isPromise(returned)){
622
- observePromise(returned,ignorePromiseResult,ignorePromiseResult);
623
- if(state==='cancelled'||controller.signal.aborted)return;
624
- need(false,'authorization_invalid');
625
- }
626
- if(state==='cancelled'||controller.signal.aborted)return;
627
- grant=json(returned);
628
- if(digest(grant)===digest({status:'denied',code:'permission_denied'})){
629
- halt('pending_review','permission_denied');return;
630
- }
631
- }catch(error){
632
- if(state==='cancelled'||controller.signal.aborted)return;
633
- halt('unknown',failureCode(error)==='clock_invalid'?'clock_invalid':'authorization_invalid');return;
634
- }
635
- if(state==='cancelled'||controller.signal.aborted)return;
636
914
  let registeredAt;
637
915
  try{registeredAt=safeTime();}catch{halt('unknown','clock_invalid');return;}
638
- if(registeredAt<authorizationAt){halt('unknown','clock_invalid');return;}
639
- try{grant=validateReviewDispatchGrant(grant,{request,reviewerId:adapter.id,adapterId:adapter.adapterId,
640
- packageDigest:reviewPackage.packageDigest,hostContextIds:[invocationConfig.developerThreadId,...liveInvocation().excludedThreadIds],
641
- authorizationAt,registeredAt});}
642
- catch{halt('unknown','authorization_invalid');return;}
643
- const registrationFields={effectId,reviewerId:adapter.id,adapterId:adapter.adapterId,requestDigest:request.requestDigest,
644
- authorizationAt,registeredAt,grant};
645
- // Validate first, then journal the signer immediately before registration.
646
- // Durable host lists and prior joiners already have replayable authority.
647
- if(![invocationConfig.developerThreadId,...invocationConfig.excludedThreadIds,...joinedHosts].includes(grant.hostContextId)){
916
+ if(state==='cancelled'||controller.signal.aborted)return;
917
+ const hostContextId=liveHostContextId??invocationConfig.developerThreadId;
918
+ const binding=json({adapterId:adapter.adapterId,invocationId:request.invocationId,requestDigest:request.requestDigest,
919
+ identity:request.identity,reviewerId:adapter.id,logicalContextId:request.contextId,
920
+ packageDigest:reviewPackage.packageDigest,hostContextId});
921
+ if(![invocationConfig.developerThreadId,...invocationConfig.excludedThreadIds,...joinedHosts].includes(hostContextId)){
648
922
  need(joinedHosts.length<MAX_AI_JOINED_HOSTS,'host_limit');
649
- persist('host-joined',{hostContextId:grant.hostContextId});joinedHosts.push(grant.hostContextId);
923
+ persist('host-joined',{hostContextId});joinedHosts.push(hostContextId);
650
924
  }
651
- persist('review-invocation-registered',registrationFields);
652
- sequence=nextSequence;
653
925
  const registration=json({reviewerId:adapter.id,adapterId:adapter.adapterId,requestDigest:request.requestDigest,
654
- authorizationAt,registeredAt,grant});
926
+ registeredAt,binding});
927
+ persist('review-invocation-registered',{effectId,...registration});
928
+ sequence=nextSequence;
655
929
  const call={invocationId:request.invocationId,contextId,provider:request.provider,requestedModel:adapter.requestedModel,
656
- effectiveModel:'unknown',channel:'host-authorized',started:false,terminal:'running',requestDigest:request.requestDigest,
930
+ effectiveModel:'unknown',channel:'host-review',started:false,terminal:'running',requestDigest:request.requestDigest,
657
931
  resultDigest:null,providerThreadId:null};
658
932
  calls.push(call);
659
- let dispatchAt=null,notDispatched=null;
660
- try{dispatchAt=safeTime();if(dispatchAt<registeredAt)notDispatched='clock_invalid';
661
- else if(dispatchAt>=grant.expiresAt)notDispatched='grant_expired';}
662
- catch{notDispatched='clock_invalid';}
663
- if(notDispatched){
664
- const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'not_dispatched',observation:null,inspection:null,
665
- reconciliationRequired:true,reason:notDispatched};
666
- persist('review-invocation-result',fields);const result=resultView(fields);
667
- Object.assign(call,{terminal:'not_dispatched',resultDigest:digest(result)});
668
- reviewInvocation=json({registration,started:null,result});halt('pending_review',notDispatched);return;
669
- }
933
+ const dispatchAt=registeredAt;
670
934
  call.started=true;
671
935
  const expectation={request,developerThreadId:invocationConfig.developerThreadId,
672
936
  excludedThreadIds:reviewExclusions(liveInvocation(),calls,developer.contextId)};
@@ -908,14 +1172,80 @@ export function createTaskRunner(options) {
908
1172
  halt('blocked','develop_requirement_missing',boundedReason('develop_requirement_missing: ',missing,
909
1173
  ' are requirement files and must exist in the review package; restore them and resume to redo this attempt'));
910
1174
  };
1175
+ // After a delivered develop: the task checks, the verification precheck, the
1176
+ // unchanged-after-review guard and the host handoff. False when it halted.
1177
+ async function hostDeliveryChecks(){
1178
+ currentChecks=await collectChecks();active();
1179
+ if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return false;}
1180
+ if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return false;}
1181
+ active();
1182
+ // unchangedSinceRejection builds a package too, so an empty delivery or a
1183
+ // deleted in-scope requirement surfaces there first and takes the same
1184
+ // retryable block (emptyDelivery).
1185
+ let unchanged;
1186
+ try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return false;}
1187
+ if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return false;}
1188
+ try{createHostHandoff({root:config.root,baseline:base,checks:currentChecks,
1189
+ handoffPath:completion.handoffs[attempt-1]});}
1190
+ catch(error){emptyDelivery(error);return false;}
1191
+ return true;
1192
+ }
1193
+ async function packageDelivery(v){
1194
+ active();
1195
+ let nextPackage;
1196
+ try{nextPackage=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,
1197
+ ...(taskLearning?.hostHandoff===true?{handoffPath:completion.handoffs[attempt-1]}:{})});}
1198
+ catch(error){emptyDelivery(error);return;}
1199
+ if(taskLearning!==null)validateTaskLearningReviewPackage(nextPackage,learningResult.writeback,v.learningInput,
1200
+ learningResult.bootstrap??null,metadata.bootstrap??null);
1201
+ reviewPackage=nextPackage;
1202
+ state='awaiting_review';
1203
+ }
1204
+ function developControl(effectId,documentationRedo){
1205
+ const control={...(workerJournaling()?{onWorker:event=>journalWorker(effectId,event)}:{}),
1206
+ ...(documentationJournaling()?{onDocumentationSync:event=>journalDocumentationSync(effectId,event),
1207
+ documentationSnapshot:paths=>documentationSnapshot(json(paths))}:{}),
1208
+ ...(documentationRedo?{documentationRedo}:{})};
1209
+ return Object.keys(control).length?control:null;
1210
+ }
1211
+ // Q16/Q17: a develop whose documentation_sync started (its call carries the
1212
+ // record) and then failed: the code its checkpoint shows, and the detail
1213
+ // (out-of-scope paths, or the transport code of a lost answer).
1214
+ function documentationFailure(v,error){
1215
+ const call=calls.at(-1);
1216
+ if(v.kind!=='develop'||call?.terminal!=='unknown'||typeof call.documentationSync!=='string')return null;
1217
+ let raw=null;
1218
+ try{const d=Object.getOwnPropertyDescriptor(error,'code');if(d&&Object.hasOwn(d,'value')&&typeof d.value==='string')raw=d.value;}catch{}
1219
+ if(raw==='documentation_sync_blocked')return {code:'documentation_sync_answer_blocked',detail:null};
1220
+ if(['documentation_sync_answer_invalid','invalid_input','invalid_result'].includes(raw))return {code:'documentation_sync_answer_invalid',detail:null};
1221
+ if(raw==='out_of_scope')return {code:'documentation_sync_out_of_scope',detail:safeReason(error)};
1222
+ return {code:'documentation_sync_answer_missing',detail:typeof raw==='string'&&/^[a-z_]{1,64}$/.test(raw)?raw:'execution_error'};
1223
+ }
911
1224
  async function perform(v) {
912
1225
  if(v.kind==='develop') {
913
- need(stageAllowed('develop',state,code,priorReview?.verdict),'stage_mismatch');state='developing';code=null;reason=null;checkNewPaths=null;receipt=null;
1226
+ need(stageAllowed('develop',state,code,priorReview?.verdict),'stage_mismatch');
1227
+ const recheck=state==='blocked'&&RECHECK_CODES.includes(code);
1228
+ // Q16/Q17: a documentation-only redo reuses the journaled developer answer.
1229
+ let documentationRedo=null;
1230
+ if(state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(code)){
1231
+ const source=documentationRecord(calls.at(-1)?.documentationSync);need(source!==null,'documentation_sync_unavailable');
1232
+ documentationRedo={result:source.result,effectiveModel:source.effectiveModel};
1233
+ }
1234
+ state='developing';code=null;reason=null;checkNewPaths=null;receipt=null;
914
1235
  // The adapter would refuse this scope before any provider runs. Block it
915
1236
  // here instead: no call starts, nothing is written, and the outcome is
916
1237
  // definite rather than unknown (create refuses such runs already).
917
1238
  const refusedScope=protectedDevelopScope(metadata);
918
1239
  if(refusedScope.length){halt('blocked','protected_scope',protectedScopeBlockReason(refusedScope));return;}
1240
+ // The delivery and its Learning writeback are already on disk: re-run only
1241
+ // the checks, the precheck, the handoff and the package. No developer call.
1242
+ if(recheck){
1243
+ if(!await hostDeliveryChecks())return;
1244
+ writeCmAiTaskLearningHandoff({handoffPath:completion.handoffs[attempt-1],feature:taskLearning.feature,
1245
+ identity:{...config.identity,attempt},learningInput:v.learningInput,application:learningResult.application,
1246
+ retrospective:learningResult.retrospective,writeback:learningResult.writeback});
1247
+ await packageDelivery(v);return;
1248
+ }
919
1249
  const previousLearning=learningResult;
920
1250
  const previousBootstrap=learningResult?.bootstrap??null;
921
1251
  const previousWriteback=learningResult?.writeback??null;
@@ -937,7 +1267,8 @@ export function createTaskRunner(options) {
937
1267
  requirements:original.files.filter(f=>config.requirements.includes(f.path)),priorReview,
938
1268
  ...supersededReviewPayload(carriedReview,attempt),
939
1269
  ...(Object.hasOwn(original,'specification')?{specification:verifySpecificationMaterial(original)}:{}),
940
- ...(Object.hasOwn(v,'learningInput')?{learningInput:v.learningInput}:{})});
1270
+ ...(Object.hasOwn(v,'learningInput')?{learningInput:v.learningInput}:{})},
1271
+ developControl(v.id,documentationRedo));
941
1272
  if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
942
1273
  if(result.response.status!=='succeeded'){
943
1274
  const failure=result.response.result?.code;
@@ -972,21 +1303,7 @@ export function createTaskRunner(options) {
972
1303
  {learningInput:v.learningInput,retrospective});
973
1304
  learningResult=freeze({application,retrospective,writeback,...(instructionEvidence?{bootstrap:instructionEvidence}:{})});
974
1305
  if(writeback.outcome==='writeback_pending'){halt('blocked','learning_writeback_pending');return;}
975
- if(taskLearning.hostHandoff===true){
976
- currentChecks=await collectChecks();active();
977
- if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return;}
978
- if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return;}
979
- active();
980
- // unchangedSinceRejection builds a package too, so an empty delivery or a
981
- // deleted in-scope requirement surfaces there first and takes the same
982
- // retryable block (emptyDelivery).
983
- let unchanged;
984
- try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return;}
985
- if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return;}
986
- try{createHostHandoff({root:config.root,baseline:base,checks:currentChecks,
987
- handoffPath:completion.handoffs[attempt-1]});}
988
- catch(error){emptyDelivery(error);return;}
989
- }
1306
+ if(taskLearning.hostHandoff===true&&!await hostDeliveryChecks())return;
990
1307
  writeCmAiTaskLearningHandoff({handoffPath:completion.handoffs[attempt-1],feature:taskLearning.feature,
991
1308
  identity:{...config.identity,attempt},learningInput:v.learningInput,application,retrospective,writeback});
992
1309
  }
@@ -1000,15 +1317,7 @@ export function createTaskRunner(options) {
1000
1317
  try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return;}
1001
1318
  if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return;}
1002
1319
  }
1003
- active();
1004
- let nextPackage;
1005
- try{nextPackage=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,
1006
- ...(taskLearning?.hostHandoff===true?{handoffPath:completion.handoffs[attempt-1]}:{})});}
1007
- catch(error){emptyDelivery(error);return;}
1008
- if(taskLearning!==null)validateTaskLearningReviewPackage(nextPackage,learningResult.writeback,v.learningInput,
1009
- learningResult.bootstrap??null,metadata.bootstrap??null);
1010
- reviewPackage=nextPackage;
1011
- state='awaiting_review';return;
1320
+ await packageDelivery(v);return;
1012
1321
  }
1013
1322
  if(v.kind==='review') {
1014
1323
  state='reviewing';verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
@@ -1048,7 +1357,7 @@ export function createTaskRunner(options) {
1048
1357
  ...(Object.hasOwn(learningResult,'application')?{application:learningResult.application}:{}),
1049
1358
  retrospective:learningResult.retrospective,
1050
1359
  writeback:learningResult.writeback});
1051
- } catch {halt('blocked','package_mismatch');return;}
1360
+ } catch {halt('blocked','package_mismatch','package_mismatch: 完成前核对 Learning handoff 与已审交付不一致(handoff 文件或 Learning 记录被改动);保留现场核对 .reviews 下的 handoff,不能直接重试。');return;}
1052
1361
  try {
1053
1362
  checkCompletion({receipt,registered:registered.get(receipt?.id),execution:calls.find(c=>c.invocationId===receipt?.id),
1054
1363
  reviewPackage,identity:{...config.identity,attempt}});
@@ -1083,7 +1392,7 @@ export function createTaskRunner(options) {
1083
1392
  }
1084
1393
  const limitDue=()=>retryLimitDue()?recordRetryLimit:completionLimitDue()?recordCompletionLimit:null;
1085
1394
  function executeEffect(raw) {
1086
- let v;
1395
+ let v,timeoutBasis=null,answerRetry=false,recheck=null,completeSource=null,dispatchBasis=null;
1087
1396
  try {
1088
1397
  need(!poisoned,'store_failure');v=json(raw);
1089
1398
  shape(v,['version','id','identity','kind',...(Object.hasOwn(v,'learningInput')?['learningInput']:[])]);id(v.id);validIdentity(v.identity);
@@ -1102,30 +1411,87 @@ export function createTaskRunner(options) {
1102
1411
  if(old){need(old.digest===digest(v),'intent_conflict');return Promise.resolve(old.result);}
1103
1412
  if(restored?.pending?.id===v.id){need(digest(restored.pending)===digest(v),'intent_conflict');return Promise.resolve(status());}
1104
1413
  need(!busy,'busy');need(v.identity.attempt===attempt,'attempt_mismatch');
1105
- need(stageAllowed(v.kind,state,code,priorReview?.verdict),'stage_mismatch');need(effectSlotFree(v.kind,[...cache.values()],calls),'limit_exceeded');
1414
+ // A timed-out develop (journaled or already released) is redone only while
1415
+ // the code root still equals its start, verified here in the dispatch tick.
1416
+ // A delivered develop whose later checks lost their answer is re-checked,
1417
+ // never redeveloped; the re-check carries the delivered Learning input.
1418
+ if(v.kind==='develop'&&state==='unknown')recheck=developRecheck();
1419
+ if(v.kind==='develop'&&(recheck!==null||state==='blocked'&&RECHECK_CODES.includes(code)))
1420
+ need(digest(v.learningInput)===digest([...cache.values()].at(-1).effect.learningInput),'runner_learning');
1421
+ if(v.kind==='complete'&&state==='unknown'&&completeRecheck())completeSource=code;
1422
+ if(v.kind==='develop'&&state==='unknown'&&recheck===null)dispatchBasis=developDispatchRetry();
1423
+ // Q16/Q17: re-ask only documentation_sync; refused (nothing journaled)
1424
+ // while the code root outside the documentation paths changed, or while a
1425
+ // writer that never answered may still be writing the documentation.
1426
+ // Q16/Q17: never redispatched before the operator confirmed the writer stopped.
1427
+ if(v.kind==='develop'&&state==='unknown'&&recheck===null&&documentationSyncRetry()!==null)
1428
+ throw documentationRefusal('documentation_sync_stop_required');
1429
+ if(v.kind==='develop'&&state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(code)){
1430
+ const redo=documentationRedoSource();need(redo!==null,'documentation_sync_unavailable');
1431
+ if(taskLearning!==null)need(digest(v.learningInput)===digest(documentationRedoLearningInput()),'runner_learning');
1432
+ assertDocumentationRedo(redo);
1433
+ }
1434
+ // A journaled develop_dispatch_failed (also after a restart between its
1435
+ // record and the develop intent) re-verifies the round start right here.
1436
+ if(v.kind==='develop'&&state==='blocked'&&code===DISPATCH_RETRY_CODE)
1437
+ need(developDispatchRetry()!==null,'develop_dispatch_root_changed');
1438
+ if(v.kind==='develop'&&recheck===null&&developTimeoutState({state,code})){
1439
+ timeoutBasis=developTimeoutRetryBasis();need(timeoutBasis!==null,'develop_timeout_root_changed');
1440
+ if(state==='blocked')timeoutBasis=null;
1441
+ }
1442
+ answerRetry=v.kind==='develop'&&state==='blocked'&&code==='failed'&&answerRetryable();
1443
+ need(timeoutBasis!==null||answerRetry||recheck!==null||completeSource!==null||dispatchBasis!==null
1444
+ ||stageAllowed(v.kind,state,code,priorReview?.verdict),'stage_mismatch');need(effectSlotFree(v.kind,[...cache.values()],calls),'limit_exceeded');
1106
1445
  if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
1107
1446
  if(v.kind==='develop'&&bootstrap!==null)bootstrap.assertWriteAuthorized();
1108
- } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:error.code??'invalid_input'}));}
1447
+ } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:error.code??'invalid_input',
1448
+ ...(String(error.code).startsWith('documentation_sync_')&&typeof error.reason==='string'?{reason:error.reason}:{})}));}
1449
+ // The timed-out develop left the code root as it started: journal that
1450
+ // finding, then redo the round like any retryable develop block.
1451
+ if(timeoutBasis!==null){
1452
+ try{persist('develop-timeout-retry',{effectId:[...cache.values()].at(-1).effect.id,invocationId:calls.at(-1).invocationId,basis:timeoutBasis});}
1453
+ catch{return Promise.resolve(poison());}
1454
+ halt('blocked','develop_call_timeout',DEVELOP_CALL_TIMEOUT_REASON);publication=privateStatus();
1455
+ }
1456
+ if(recheck!==null){
1457
+ const source=code;
1458
+ try{persist('develop-recheck',{effectId:[...cache.values()].at(-1).effect.id,invocationId:calls.at(-1).invocationId,code:recheck});}
1459
+ catch{return Promise.resolve(poison());}
1460
+ halt('blocked',recheck,developRecheckReason(recheck,source,reason));publication=privateStatus();
1461
+ }
1462
+ if(dispatchBasis!==null){
1463
+ const source=code;
1464
+ try{persist('develop-dispatch-retry',{effectId:[...cache.values()].at(-1).effect.id,invocationId:calls.at(-1).invocationId,basis:dispatchBasis});}
1465
+ catch{return Promise.resolve(poison());}
1466
+ halt('blocked',DISPATCH_RETRY_CODE,developDispatchReason(source));publication=privateStatus();
1467
+ }
1468
+ if(completeSource!==null){
1469
+ try{persist('complete-recheck',{effectId:[...cache.values()].at(-1).effect.id,source:completeSource});}
1470
+ catch{return Promise.resolve(poison());}
1471
+ halt('blocked',COMPLETE_RECHECK_CODE,completeRecheckReason(completeSource));publication=privateStatus();
1472
+ }
1473
+ if(answerRetry){
1474
+ try{persist('develop-answer-retry',{effectId:[...cache.values()].at(-1).effect.id,invocationId:calls.at(-1).invocationId});}
1475
+ catch{return Promise.resolve(poison());}
1476
+ halt('blocked','develop_answer_invalid',developAnswerInvalidReason(calls.at(-1).failureResult));publication=privateStatus();
1477
+ }
1109
1478
  if(v.kind==='develop'&&retryLimitDue()){try{return Promise.resolve(recordRetryLimit());}catch{return Promise.resolve(poison());}}
1110
1479
  if(v.kind==='complete'&&completionLimitDue()){try{return Promise.resolve(recordCompletionLimit());}catch{return Promise.resolve(poison());}}
1111
1480
  if(store) {
1112
1481
  try {
1113
- if(state==='ready')compareReviewBaseline(withBoundSpecification(captureReviewBaseline({...configToBaseline(metadata),version:original.version,
1114
- ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
1115
- !Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
1116
- original.ignorePolicy?.version===2?original.ignorePolicy:null)),original);
1482
+ if(state==='ready')assertReadyBaseline();
1117
1483
  // A rejected first delivery has no review package yet. Every later
1118
1484
  // developer effect must recheck the reviewed tree before dispatch,
1119
1485
  // except one that redoes a delivery this attempt already made: that
1120
1486
  // delivery changed the tree on purpose and never became a package, so
1121
1487
  // it is compared against the baseline when the new package is built,
1122
1488
  // exactly as a redo at attempt 1 is.
1123
- else if(reviewPackage!==null&&!(v.kind==='develop'&&state==='blocked'&&code!=='review_package_changed'
1489
+ else if(reviewPackage!==null&&!(v.kind==='develop'&&state==='blocked'&&!['review_package_changed','develop_call_timeout'].includes(code)
1124
1490
  &&stageAllowed('develop',state,code,priorReview?.verdict)))verifyReviewPackage({root:config.root,baseline:reviewPackage.identity.attempt===attempt?base:attemptBaseline(original,reviewPackage.identity.attempt),
1125
1491
  checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
1126
1492
  } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:failureCode(error),
1127
1493
  ...(safeReason(error)?{reason:safeReason(error)}:{})}));}
1128
- try{const record=persist('effect-intent',{effect:v});
1494
+ try{const record=persist('effect-intent',{effect:v,...(v.kind==='develop'&&workerJournaling()?{workerJournal:true}:{})});
1129
1495
  if(taskMode&&v.kind==='complete')completeEffect={effect:v,digest:record.digest};
1130
1496
  }catch{return Promise.resolve(poison());}
1131
1497
  }
@@ -1133,7 +1499,9 @@ export function createTaskRunner(options) {
1133
1499
  const packageBefore=reviewPackage;
1134
1500
  pending=(async()=>{
1135
1501
  try {await perform(v);}
1136
- catch(error){if(state!=='cancelled'){
1502
+ catch(error){if(state!=='cancelled'&&!poisoned&&documentationFailure(v,error)){
1503
+ const {code:failed,detail}=documentationFailure(v,error);halt('unknown',failed,detail);
1504
+ }else if(state!=='cancelled'){
1137
1505
  const failure=failureCode(error);
1138
1506
  const checkOnly=failure==='out_of_scope'&&Array.isArray(error.violations)&&error.violations.length>0
1139
1507
  &&error.violations.every(item=>item.newFile&&checkNewPaths?.has(item.path));
@@ -1184,7 +1552,10 @@ export function createTaskRunner(options) {
1184
1552
  if(poisoned)return result;
1185
1553
  try{publishRegisteredReview();}
1186
1554
  catch{return freeze({...result,code:'review_publication_required'});}
1187
- return ['unknown','pending_review'].includes(result.state)?status():result;
1555
+ // A spent retryable review block reads through status: its V5 redispatch
1556
+ // (pending_review) or the round's explicit limit.
1557
+ return ['unknown','pending_review'].includes(result.state)
1558
+ ||result.state==='blocked'&&REVIEW_RETRY_CODES.includes(result.code)?status():result;
1188
1559
  });
1189
1560
  return pending;
1190
1561
  }
@@ -1313,6 +1684,22 @@ export function createTaskRunner(options) {
1313
1684
  const abandonReview=raw=>{
1314
1685
  try{
1315
1686
  need(!(metadata.externalModels||metadata.executionPolicy),'external_review_reconciliation_required');
1687
+ // V5 (A34): the operator confirms the spent block's reviewer stopped; this
1688
+ // journals the round's second no-result redispatch (no dispatch here).
1689
+ if(state==='blocked'&&reviewRedispatchLive()){
1690
+ const value=json(raw);shape(value,['allowed','reason']);
1691
+ need(value.allowed===true,'review_abandon_authorization_required');
1692
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1693
+ &&!/[\r\n\0]/.test(value.reason),'review_abandon_reason_required');
1694
+ persist('review-redispatch',{effectId:[...cache.values()].at(-1).effect.id,
1695
+ invocationId:reviewInvocation.registration.binding.invocationId,attempt,code,reason:value.reason,at:new Date().toISOString()});
1696
+ state='pending_review';publication=privateStatus();return status();
1697
+ }
1698
+ if(state==='blocked'&&reviewRedispatchSpent())throw Object.assign(new Error('review_abandon_budget_exhausted'),{code:'review_abandon_budget_exhausted'});
1699
+ if(invocationMode&&store&&!busy&&!poisoned&&state==='unknown'&&!restored?.pending&&!reviewResultAbandonable()){
1700
+ const refusal=reviewAbandonRefusal({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1],reviewRedispatchRecords());
1701
+ if(refusal)throw Object.assign(new Error(refusal.code),refusal);
1702
+ }
1316
1703
  need(invocationMode&&store&&!busy&&!poisoned&&state==='unknown'
1317
1704
  &&(restored?.pending?.kind==='review'||reviewResultAbandonable()),'review_abandon_unavailable');
1318
1705
  const value=json(raw);shape(value,['allowed','reason']);
@@ -1330,26 +1717,34 @@ export function createTaskRunner(options) {
1330
1717
  publication=privateStatus();return status();
1331
1718
  }
1332
1719
  const history=readRunnerHistory(journal,metadata,3),last=journal.at(-1);
1720
+ // A38: the no-verdict result of the pending review reached the journal, its checkpoint did not.
1721
+ const withResult=last?.payload?.type==='review-invocation-result'&&history.pendingResultAbandonable===true;
1333
1722
  need(history.pending?.id===restored.pending.id&&history.state.state==='unknown'
1334
1723
  &&history.state.code==='reconciliation_required'
1335
- &&['review-invocation-registered','review-invocation-started'].includes(last?.payload?.type)
1336
- &&history.state.reviewInvocation?.registration&&history.state.reviewInvocation.result===null,
1724
+ &&(['review-invocation-registered','review-invocation-started'].includes(last?.payload?.type)
1725
+ &&history.state.reviewInvocation?.result===null||withResult)
1726
+ &&history.state.reviewInvocation?.registration,
1337
1727
  'review_abandon_unavailable');
1338
1728
  const registration=journal.findLast(row=>row.payload.type==='review-invocation-registered'
1339
1729
  &&row.payload.effectId===history.pending.id);
1340
- const started=last.payload.type==='review-invocation-started'?last:null;
1730
+ const started=journal.findLast(row=>row.payload.type==='review-invocation-started'&&row.payload.effectId===history.pending.id
1731
+ &&journal.indexOf(row)>journal.indexOf(registration))??null;
1341
1732
  need(registration,'review_abandon_unavailable');
1342
1733
  const contextId=reviewers[0].contexts[attempt-1];
1343
- need(!reviewRetrySpent(history.state.cache,history.state.calls,attempt,contextId),'review_abandon_budget_exhausted');
1734
+ need(reviewRedispatchCount(history.state.cache,history.state.calls,attempt,contextId,reviewRedispatchRecords())<MAX_REVIEW_REDISPATCHES,
1735
+ 'review_abandon_budget_exhausted');
1344
1736
  const fields={effectId:history.pending.id,
1345
- invocationId:history.state.reviewInvocation.registration.grant.invocationId,
1737
+ invocationId:history.state.reviewInvocation.registration.binding.invocationId,
1346
1738
  registeredDigest:registration.digest,startedDigest:started?.digest??null,
1739
+ ...(withResult?{resultDigest:last.digest}:{}),
1347
1740
  reason:value.reason,at:new Date().toISOString()};
1348
1741
  persist('review-invocation-abandoned',fields);
1349
1742
  const recovered=readRunnerHistory(journal,metadata,3).state;
1350
1743
  ({state,code,sequence,reviewInvocation}=recovered);calls.push(...recovered.calls.slice(calls.length));
1351
1744
  publication=privateStatus();return status();
1352
- }catch(error){return freeze({outcome:'rejected',code:error.code??'review_abandon_unavailable'});}
1745
+ }catch(error){return freeze({outcome:'rejected',code:error.code??'review_abandon_unavailable',
1746
+ ...(error.code==='review_abandon_budget_exhausted'?{reason:`本轮独立审查已无结论重派 ${MAX_REVIEW_REDISPATCHES} 次,不能再放弃重派;在途审查可用 abandon_effect 作废本运行后 --supersede-reviewed-evidence 新建运行。`}
1747
+ :typeof error.reason==='string'?{reason:error.reason}:{})});}
1353
1748
  };
1354
1749
  const reconcileReview=raw=>{
1355
1750
  try{
@@ -1363,7 +1758,7 @@ export function createTaskRunner(options) {
1363
1758
  const {request,effect,before,result,...binding}=proof;
1364
1759
  const call=calls.find(item=>item.invocationId===value.invocationId);
1365
1760
  need(['unknown','failed'].includes(call?.terminal),'review_reconciliation_unavailable');
1366
- // Same call, same grant and same effect. The journal retains the original
1761
+ // Same call, same binding and same effect. The journal retains the original
1367
1762
  // unknown and receipt; one atomic record contains the validated transition.
1368
1763
  Object.assign(call,{terminal:result.outcome==='observed'?'succeeded':'failed',
1369
1764
  resultDigest:digest(result.outcome==='observed'?result.inspection.review:result)});
@@ -1388,20 +1783,124 @@ export function createTaskRunner(options) {
1388
1783
  &&!/[\r\n\0]/.test(value.reason),'effect_abandon_reason_required');
1389
1784
  const history=readRunnerHistory(journal,metadata,3),effect=history.pending;
1390
1785
  need(effect!==null,'effect_abandon_no_pending');
1391
- need(effect.kind!=='review'||history.pendingAbandonable,'effect_abandon_review_pending');
1392
- need(['develop','complete','review'].includes(effect.kind),'effect_abandon_unavailable');
1393
- need(effect.kind!=='develop'||options.providerDevelopment!==true,'effect_abandon_provider_development');
1394
1786
  need(history.transaction===null&&history.state.taskCommit?.intentDigest==null,'effect_abandon_commit_pending');
1787
+ // V8: retire the interrupted step and continue the run from its retryable block.
1788
+ if(history.pendingInterruptible)return interruptEffect(history,effect,value.reason);
1789
+ need(effect.kind!=='review'||history.pendingAbandonable||history.pendingReviewExhausted,'effect_abandon_review_pending');
1790
+ need(['develop','complete','review'].includes(effect.kind),'effect_abandon_unavailable');
1791
+ // A develop whose writers are journaled is voided only with their gone-proof.
1792
+ let worker=null;
1793
+ if(effect.kind==='develop'&&history.pendingWorkerVoidable){
1794
+ const proof=workerProof(history.pendingWorker);
1795
+ if(proof.code){const refusal=workerRefusal('effect_abandon',proof);throw Object.assign(new Error(refusal.code),refusal);}
1796
+ worker=proof.binding??null;
1797
+ }else need(effect.kind!=='develop'||options.providerDevelopment!==true||history.pendingWorker?.journal===true,'effect_abandon_provider_development');
1395
1798
  need(history.state.state==='unknown'&&history.state.code==='reconciliation_required'
1396
- &&history.pendingAbandonable,'effect_abandon_unavailable');
1799
+ &&(history.pendingAbandonable||history.pendingReviewExhausted||history.pendingWorkerVoidable),'effect_abandon_unavailable');
1397
1800
  const intent=journal.findLast(row=>row.payload.type==='effect-intent');
1398
1801
  persist('effect-abandoned',{effectId:effect.id,effectKind:effect.kind,intentDigest:intent.digest,
1399
- lastRecordDigest:journal.at(-1).digest,reason:value.reason,at:new Date().toISOString()});
1802
+ lastRecordDigest:journal.at(-1).digest,reason:value.reason,at:new Date().toISOString(),...(worker?{worker}:{})});
1400
1803
  const recovered=readRunnerHistory(journal,metadata,3).state;
1401
1804
  ({state,code,sequence}=recovered);reason=recovered.reason;restored.pending=null;
1402
1805
  publication=privateStatus();return status();
1403
- }catch(error){return freeze({outcome:'rejected',code:error.code??'effect_abandon_unavailable',
1404
- ...(error.code==='effect_abandon_commit_pending'?{reason:'task-commit-intent 已写入,tasks.md 可能已改名或勾选;请核对 tasks.md、提交回执和旧进程后按原提交恢复路径处理。'}:{})});}
1806
+ }catch(error){return freeze({outcome:'rejected',code:poisoned?'store_failure':error.code??'effect_abandon_unavailable',
1807
+ ...(error.code==='effect_abandon_commit_pending'?{reason:'task-commit-intent 已写入,tasks.md 可能已改名或勾选;不能放弃或重做完成。发送 complete,宿主只按运行存档里的提交计划核对 tasks.md 并收尾。'}
1808
+ :!poisoned&&error.reason?{reason:error.reason}:{})});}
1809
+ };
1810
+ function interruptEffect(history,effect,why){
1811
+ const refuse=(code,detail)=>{throw Object.assign(new Error(code),{code,reason:detail});};
1812
+ const extra={};
1813
+ if(effect.kind==='develop'){
1814
+ if(options.providerDevelopment===true&&!providerRun)refuse('effect_interrupt_worker_identity_unrecorded',
1815
+ '这次 provider 开发没有配置 provider 模型,运行存档无法记下 worker 进程身份,宿主无法证明进程已退出;请手工确认进程已退出后用新建运行替代。');
1816
+ // Every journaled writer (provider worker, proposal apply subprocess) must be gone.
1817
+ if(providerRun||history.pendingWorker?.journal===true){
1818
+ const proof=workerProof(history.pendingWorker);
1819
+ if(proof.code){const refusal=workerRefusal('effect_interrupt',proof);refuse(refusal.code,refusal.reason);}
1820
+ if(proof.proof==='gone')extra.worker=proof.binding;
1821
+ }
1822
+ // A Claude provider and protected current-session development write by
1823
+ // applying proposals: a changed root can only be a partly applied one.
1824
+ if(providerRun?developer.provider==='claude':options.protectedDevelopment===true)
1825
+ extra.basis=verifyRoundStart(pendingDevelopStart(history.state),'effect_interrupt',providerRun?'Claude provider 开发':'受保护开发');
1826
+ // Q16: the host died during documentation_sync, after the developer
1827
+ // answered: bind the start record and the documentation as confirmed now,
1828
+ // so the run redoes only documentation_sync.
1829
+ if(history.pendingDocumentation){
1830
+ extra.startDigest=history.pendingDocumentation.digest;
1831
+ extra.documents=documentationLive(history.pendingDocumentation.payload.documents.map(item=>item.path)).documents;
1832
+ }
1833
+ }
1834
+ const intent=journal.findLast(row=>row.payload.type==='effect-intent');
1835
+ persist('effect-interrupted',{effectId:effect.id,effectKind:effect.kind,intentDigest:intent.digest,
1836
+ lastRecordDigest:journal.at(-1).digest,reason:why,at:new Date().toISOString(),...extra});
1837
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1838
+ ({state,code,sequence}=recovered);reason=recovered.reason??null;
1839
+ calls.splice(0,calls.length,...recovered.calls);
1840
+ restored.pending=null;publication=privateStatus();return status();
1841
+ }
1842
+ // A45: finish the interrupted task commit from its journaled plan only.
1843
+ const recoverCommit=()=>{
1844
+ try{
1845
+ const transaction=commitRecoveryTransaction();need(transaction!==null,'commit_recovery_unavailable');
1846
+ const effect=restored.pending,intent=transaction.intentRecord.payload.commit;
1847
+ // tasks.md is never touched again and no second result is appended once
1848
+ // the journal holds the commit result; only the checkpoint is missing.
1849
+ if(transaction.resultRecord===null){
1850
+ recoverRunnerCommitImage(completion.owner,intent,()=>verifyReviewPackage({root:config.root,baseline:base,
1851
+ checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()}));
1852
+ persist('task-commit-result',{effectId:effect.id,completeIntentDigest:transaction.completeIntentDigest,
1853
+ commit:{version:1,protocol:'cm-task-commit',type:'result',intentDigest:transaction.intentRecord.digest,
1854
+ planDigest:intent.plan.planDigest,outcome:'fixture_committed'}});
1855
+ }
1856
+ state='fixture_completed';code=null;reason=null;
1857
+ const response=privateStatus();cache.set(effect.id,{effect,digest:digest(effect),result:response});
1858
+ persist('effect-checkpoint',{effectId:effect.id,checkpoint:frame()});
1859
+ restored.pending=null;publication=response;return status();
1860
+ }catch(error){
1861
+ if(poisoned)return freeze({outcome:'rejected',code:'store_failure'});
1862
+ return freeze({outcome:'rejected',code:error.code??'commit_recovery_unavailable',reason:error.code==='commit_recovery_conflict'
1863
+ ?'tasks.md 或提交计划引用的证据文件既不是提交前也不是提交后的样子(或已被改动);宿主不改写。请核对 tasks.md 与 .reviews 下的 handoff/审查文件,还原后重试 complete。'
1864
+ :error.code==='commit_recovery_code_changed'?'代码已不等于审查通过的交付,宿主不勾选任务;还原到审查通过的交付后重试 complete。'
1865
+ :'完成提交无法按运行存档的提交计划收尾;保留现场核对 tasks.md 与提交记录。'});
1866
+ }
1867
+ };
1868
+ // The operator's confirmation that the stuck current-session develop stopped
1869
+ // writing (R3). Journals develop-answer-redo; the next advance redoes the round.
1870
+ const redoDevelop=raw=>{
1871
+ try{
1872
+ need(invocationMode&&store&&!busy&&!poisoned&&options.persistence.mode==='resume','develop_redo_unavailable');
1873
+ const value=json(raw);shape(value,['allowed','reason']);
1874
+ need(value.allowed===true,'develop_redo_authorization_required');
1875
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1876
+ &&!/[\r\n\0]/.test(value.reason),'develop_redo_reason_required');
1877
+ // Q16: the confirmation for a documentation_sync that never answered after
1878
+ // it changed the documentation paths; only documentation_sync is redone.
1879
+ // A re-confirmation (blocked) keeps the confirmed source and spends no retry.
1880
+ const documentation=state==='unknown'?documentationSyncRetry():null,confirmed=state==='blocked'?documentationRedoSource():null;
1881
+ if(documentation!==null||confirmed!==null){
1882
+ const source=documentation?.source??confirmed.source,start=calls.at(-1).documentationSync;
1883
+ const live=documentationLive(source.documents.map(item=>item.path));
1884
+ persist('documentation-sync-retry',{effectId:documentation?[...cache.values()].at(-1).effect.id:confirmed.stop.effectId,
1885
+ invocationId:calls.at(-1).invocationId,startDigest:start,code:documentation?.code??confirmed.code,documents:live.documents,
1886
+ reason:value.reason,at:new Date().toISOString()});
1887
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1888
+ halt('blocked',recovered.code,recovered.reason);publication=privateStatus();return status();
1889
+ }
1890
+ const cause=developRedoRequired();need(cause!==null,'develop_redo_unavailable');
1891
+ const effectId=[...cache.values()].at(-1).effect.id;let worker=null,basis=null;
1892
+ if(cause.startsWith('provider_')){
1893
+ const proof=workerProof(parsedHistory?.workers?.[effectId],{checkpointed:true});
1894
+ if(proof.code){const refusal=workerRefusal('develop_redo',proof);throw Object.assign(new Error(refusal.code),refusal);}
1895
+ if(proof.proof==='gone')worker=proof.binding;
1896
+ if(developer.provider==='claude')basis=verifyRoundStart(redoDevelopStart({state,code,attempt,cache:[...cache.values()],
1897
+ reviewPackage,priorReview}),'develop_redo','Claude provider 开发');
1898
+ }
1899
+ persist('develop-answer-redo',{effectId,invocationId:calls.at(-1).invocationId,
1900
+ cause,reason:value.reason,at:new Date().toISOString(),...(worker?{worker}:{}),...(basis?{basis}:{})});
1901
+ halt('blocked',DEVELOP_REDO_CODE,developRedoReason(cause));publication=privateStatus();return status();
1902
+ }catch(error){return freeze({outcome:'rejected',code:poisoned?'store_failure':error.code??'develop_redo_unavailable',
1903
+ ...(!poisoned&&error.reason?{reason:error.reason}:{})});}
1405
1904
  };
1406
1905
  const recoverBootstrapReview=raw=>{
1407
1906
  try{
@@ -1436,7 +1935,16 @@ export function createTaskRunner(options) {
1436
1935
  }catch(error){return freeze({outcome:'rejected',code:error.code??'bootstrap_review_recovery_mismatch',
1437
1936
  reason:'原运行的文件、handoff 或证据无法精确核对;请保留现场并检查差异,不要重新派发开发。'});}
1438
1937
  };
1439
- const api={reviseQa,supersedeEvidence,rebindSpecification,abandonReview,reconcileReview,abandonEffect,recoverBootstrapReview,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks};
1938
+ // Interrupted intents keep their ids; the entry derives fresh ones from this count.
1939
+ const interruptions=kind=>parsedHistory?.interrupted?.filter(item=>item.kind===kind).length??0;
1940
+ // Read-only projection of the baseline-derived reviewed change inventory.
1941
+ // Entry checks current status before/after the call; do not rebuild a baseline
1942
+ // from the author's handoff or change any completion/correction authority.
1943
+ const qaChangedFiles=packageDigest=>{
1944
+ need(state==='fixture_completed'&&reviewPackage?.packageDigest===packageDigest,'stale_qa');
1945
+ return freeze({paths:reviewPackage.changes.map(change=>change.path),source:'review_package'});
1946
+ };
1947
+ const api={qaChangedFiles,reviseQa,supersedeEvidence,rebindSpecification,abandonReview,reconcileReview,abandonEffect,recoverBootstrapReview,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks,reviewEffectIds,recheckLearningInput,redoDevelop,recoverCommit,interruptions};
1440
1948
  if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
1441
1949
  if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
1442
1950
  // A terminal reviewer observation is durable even if the host died before
@@ -1444,7 +1952,7 @@ export function createTaskRunner(options) {
1444
1952
  if(restored?.pendingObservedReview){
1445
1953
  const observed=restored.pendingObservedReview,request=observed.request,result=observed.result;
1446
1954
  const call={invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
1447
- requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-authorized',
1955
+ requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-review',
1448
1956
  started:true,terminal:'succeeded',requestDigest:request.requestDigest,
1449
1957
  resultDigest:digest(result.inspection.review),providerThreadId:observed.started};
1450
1958
  sequence++;calls.push(call);