@aibyzero/cm-workflow 0.16.7 → 0.16.9

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 (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. package/skills/cm-test/references/js-host.md +14 -1
@@ -19,7 +19,20 @@ import { checkCompletion } from './gate-bridge.mjs';
19
19
  import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
20
20
  MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateReviewDispatchGrant,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,reviewNotDispatchedExhausted,REVIEW_NOT_DISPATCHED_LIMIT_CODE,reviewNeverStartedStatus,reviewNotDispatchedLimitReason,reviewNotDispatchedExtendable,reviewDenialUnconfirmed,reviewDenialExhausted,reviewDenialConfirmable,reviewDenialLimitReason,
23
+ REVIEW_DENIAL_LIMIT_CODE,REVIEW_DISPATCH_CONFIRM_REQUIRED_CODE,countReviewDispatchConfirmations,reviewRedispatchCount,reviewRedispatchable,reviewRedispatchExhausted,REVIEW_REDISPATCH_LIMIT_CODE,reviewRedispatchLimitReason,reviewRedispatchStopReason,reviewAbandonRefusal,
24
+ completionBlockCount,completionRetriesExhausted,supersededReviewPayload,bootstrapReviewRecoverable,protectedDevelopScope,protectedScopeBlockReason,
25
+ developTimeoutBasis,developTimeoutEffect,developTimeoutState,DEVELOP_CALL_TIMEOUT_REASON,
26
+ developAnswerInvalidEffect,developAnswerRetryable,developAnswerInvalidReason,
27
+ RECHECK_CODES,COMPLETE_RECHECK_CODE,developRecheckSource,developRecheckCode,developRecheckReason,
28
+ completeRecheckSource,completeRecheckable,completeRecheckReason,
29
+ DEVELOP_REDO_CODE,developAnswerMissingEffect,developRedoCause,developRedoRequiredReason,developRedoReason,
30
+ DISPATCH_RETRY_CODE,developDispatchFailedEffect,developDispatchBasis,developDispatchReason,answerGapLimit,
31
+ pendingDevelopStart,redoDevelopStart,workerGoneBinding,EFFECT_INTERRUPT_LIMIT_CODE,effectInterruptLimitReason,developRedoSource,COMMIT_INTERRUPTED_CODE,COMMIT_INTERRUPTED_REASON,
32
+ DOCUMENTATION_SYNC_CODES,documentationSyncSource,documentationSyncRetryCode,documentationSyncStopReason } from './durable-runner-state.mjs';
33
+ import {splitDocumentationState} from './host-documentation.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,17 @@ 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');
145
159
  if(invocationMode)optionKeys.push('reviewInvocation');
146
160
  shape(options,optionKeys);
147
161
  need(options.providerDevelopment===undefined||typeof options.providerDevelopment==='boolean','invalid_input');
162
+ // Transient like providerDevelopment, never journaled: protected current-session
163
+ // development applies proposals in a sandbox, so a stuck develop there may be a
164
+ // partial write and gets no develop_redo exit (durable-runner-state.mjs).
165
+ need(options.protectedDevelopment===undefined||typeof options.protectedDevelopment==='boolean','invalid_input');
148
166
  const {check,commit}=options;need(typeof check==='function' && (taskMode||typeof commit==='function'));
149
167
  // Opt-in gate between the task's own checks and the independent review. It may
150
168
  // only block: passing it grants nothing and never substitutes for that review.
@@ -212,7 +230,7 @@ export function createTaskRunner(options) {
212
230
  metadata=json({...metadata,bootstrap:bootstrapConfiguration(bootstrap,{root:config.root,identity:config.identity,
213
231
  scope:config.scope,feature:taskLearning.feature})});
214
232
  }
215
- let store=null,journal=null,restored=null,storeRevision=null,poisoned=false;
233
+ let store=null,journal=null,restored=null,storeRevision=null,poisoned=false,parsedHistory=null;
216
234
  let completion=null,storeIdentity=null,storeOperating=false,liveToken=null,completeEffect=null,taskCommit=null;
217
235
  const version=taskMode?(invocationMode?3:2):1;
218
236
  if(Object.hasOwn(options,'persistence')) {
@@ -238,7 +256,7 @@ export function createTaskRunner(options) {
238
256
  completion=json({version:1,mode:'fixture-task',owner:completion.owner,fingerprints:saved.fingerprints,...selection});
239
257
  storeIdentity=saved.identity;metadata=json({...metadata,completion});
240
258
  }
241
- if(options.persistence.mode==='resume')restored=readRunnerHistory(journal,metadata,version);
259
+ if(options.persistence.mode==='resume')parsedHistory=restored=readRunnerHistory(journal,metadata,version);
242
260
  else need(journal.length===0,'runner_exists');
243
261
  }
244
262
  // Transient live identity is deliberately absent from metadata/init bytes.
@@ -287,14 +305,24 @@ export function createTaskRunner(options) {
287
305
  // derivation in one place, next to the cache it is derived from.
288
306
  const verificationBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='develop'
289
307
  &&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;
308
+ &&['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)
309
+ ||developTimeoutEffect(entry)||developAnswerInvalidEffect(entry)||developRecheckSource(entry)||developRedoSource(entry)||developDispatchFailedEffect(entry)
310
+ ||documentationSyncSource(entry)).length;
291
311
  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;
312
+ &&entry.result?.state==='blocked'&&['completion_checks_changed','completion_package_changed'].includes(entry.result?.code)
313
+ ||completeRecheckSource(entry)).length;
293
314
  const privateStatus=()=>json({state,code,...(reason?{reason}:{}),
294
- ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pendingAbandonable
315
+ ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pending
316
+ &&(restored.pendingAbandonable||restored.pendingInterruptible||restored.pendingReviewExhausted||restored.pendingWorkerVoidable)
295
317
  ?{pendingEffectKind:restored.pending.kind}:{}),
318
+ // Q16: this interruption is a documentation retry; abandon_effect resends only documentation_sync.
319
+ ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pending?.kind==='develop'
320
+ &&restored.pendingInterruptible&&restored.pendingDocumentation!=null?{documentationSyncPending:true}:{}),
321
+ // R2: the interruption cap is spent; abandon_effect now only voids the run.
322
+ ...(state==='unknown'&&restored?.pending&&restored.pendingInterruptLimit
323
+ ?{code:EFFECT_INTERRUPT_LIMIT_CODE,reason:effectInterruptLimitReason(restored.pending.kind)}:{}),
296
324
  ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pending?.kind==='review'
297
- &&restored.state.reviewInvocation?.registration&&restored.state.reviewInvocation.result===null
325
+ &&restored.state.reviewInvocation?.registration&&(restored.state.reviewInvocation.result===null||restored.pendingResultAbandonable)
298
326
  ?{pendingReviewInvocation:true}:{}),
299
327
  identity:{...config.identity,attempt},packageDigest:reviewPackage?.packageDigest??null,
300
328
  receipt,receipts,calls,cancelAfterCommit,workflowError,...(store?{cancellationRequested}:{}),...(taskMode?{taskCommit}:{}),
@@ -319,14 +347,286 @@ export function createTaskRunner(options) {
319
347
  // Replay decides; this only reports an exit abandonReview would accept.
320
348
  function reviewResultAbandonable(){
321
349
  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]);
350
+ &&abandonableReviewResult({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1],reviewRedispatchRecords());
323
351
  }
352
+ // V5 (A34): review-redispatch records of this round (written by abandon_review).
353
+ function reviewRedispatchRecords(){
354
+ return journal?.filter(row=>row.payload.type==='review-redispatch'&&row.payload.attempt===attempt).length??0;
355
+ }
356
+ // The review effect ids of the current round: the entry derives the next redispatch id from
357
+ // them, never from reviewInvocation (a refused authorization leaves it at the previous round's
358
+ // value), so an id can never repeat one the cache holds.
359
+ const reviewEffectIds=()=>[...cache.values()].filter(entry=>entry.effect.kind==='review'
360
+ &&entry.effect.identity.attempt===attempt).map(entry=>entry.effect.id);
361
+ // Confirmations of this round (abandon_review on a review that never started).
362
+ const reviewDispatchConfirmations=()=>countReviewDispatchConfirmations((journal??[]).map(row=>row.payload),attempt);
363
+ // A spent retryable review block this round may still redispatch (advance).
364
+ const reviewRedispatchLive=()=>Boolean(!(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned
365
+ &&!restored?.pending&&reviewRedispatchable({state,code,attempt,cache:[...cache.values()],calls,reviewInvocation},
366
+ reviewers[0].contexts[attempt-1],reviewRedispatchRecords()));
367
+ const reviewRedispatchSpent=()=>Boolean(!(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned
368
+ &&!restored?.pending&&reviewRedispatchExhausted({state,code,attempt,cache:[...cache.values()],calls,reviewInvocation},
369
+ reviewers[0].contexts[attempt-1],reviewRedispatchRecords()));
370
+ // A develop cut off by the host answer limit (unknown/call_timeout) whose
371
+ // start the journal pins, checked against the code root now: true only when
372
+ // nothing of it reached the disk. Never journaled by status; advance records
373
+ // develop-timeout-retry before redoing the round (see executeEffect).
374
+ function developTimeoutRetryBasis(){
375
+ if(!store||!taskMode||busy||poisoned||!developTimeoutState({state,code})||restored?.pending&&!cache.has(restored.pending.id))return null;
376
+ const basis=developTimeoutBasis({state,code,attempt,cache:[...cache.values()],calls,reviewPackage,priorReview},metadata.bootstrap);
377
+ if(basis===null)return null;
378
+ try{
379
+ if(basis==='reviewed_package')verifyReviewPackage({root:config.root,baseline:attemptBaseline(original,reviewPackage.identity.attempt),
380
+ checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
381
+ else assertReadyBaseline();
382
+ }catch{return null;}
383
+ return basis;
384
+ }
385
+ // A journaled blocked/failed develop whose current-session answer failed local
386
+ // validation: shown as the retryable block; advance journals develop-answer-retry.
387
+ const answerRetryable=()=>Boolean(store&&taskMode&&!busy&&!poisoned&&!(restored?.pending&&!cache.has(restored.pending.id))
388
+ &&developAnswerRetryable({state,code,attempt,cache:[...cache.values()]},metadata.bootstrap));
389
+ // V3 answer gaps (durable-runner-state.mjs): a delivered develop or a complete
390
+ // whose later re-check never got a usable answer. Status shows the retryable
391
+ // block; advance journals develop-recheck / complete-recheck first.
392
+ const answerGapCount=type=>journal?.filter(row=>row.payload.type===type).length??0;
393
+ const gapsLive=()=>Boolean(store&&taskMode&&invocationMode&&!busy&&!poisoned&&!(restored?.pending&&!cache.has(restored.pending.id)));
394
+ const developRecheck=()=>gapsLive()?developRecheckCode({state,code,attempt,cache:[...cache.values()],learningResult,receipt},
395
+ metadata,answerGapCount('develop-recheck')):null;
396
+ const completeRecheck=()=>gapsLive()&&completeRecheckable({state,code,attempt,cache:[...cache.values()],taskCommit},
397
+ answerGapCount('complete-recheck'));
398
+ // V2 + R3: a stuck current-session develop that only an operator confirmation
399
+ // (develop_redo) may redo. Returns the cause or null.
400
+ // Provider development (V9) qualifies only with its worker identity journaled.
401
+ const providerRun=developer.requestedModel!=='current-session';
402
+ const developRedoRequired=()=>{
403
+ if(!gapsLive()||!providerRun&&(options.protectedDevelopment===true||options.providerDevelopment===true))return null;
404
+ return developRedoCause({state,code,attempt,cache:[...cache.values()],calls,receipt},metadata,
405
+ answerGapCount('develop-answer-redo'),parsedHistory?.workers??null);
406
+ };
407
+ // Q16/Q17: the final task's develop journals the developer answer it accepted
408
+ // and the documentation start (documentation-sync-started) right before the
409
+ // adapter asks documentation_sync, and marks its developer call with the
410
+ // record. A sync that then fails is redone alone, from that record.
411
+ const documentationJournaling=()=>Boolean(invocationMode&&store&&taskMode&&bootstrap===null&&!metadata.bootstrap);
412
+ function journalDocumentationSync(effectId,raw){
413
+ const event=json(raw,512*1024);shape(event,['result','effectiveModel','documents','othersDigest']);
414
+ const call=calls.at(-1);need(call?.terminal==='running'&&!Object.hasOwn(call,'documentationSync'),'invalid_input');
415
+ const record=persist('documentation-sync-started',{effectId,invocationId:call.invocationId,...event});
416
+ call.documentationSync=record.digest;
417
+ }
418
+ const documentationRecord=value=>journal?.find(row=>row.digest===value&&row.payload.type==='documentation-sync-started')?.payload??null;
419
+ // The run's documentation-sync retries so far, as the journal counts them.
420
+ const documentationRetries=()=>parsedHistory?.answerGaps?.documentationSync??0;
421
+ // The checkpointed documentation_sync failure the last develop left, still
422
+ // waiting for its stop confirmation, with its start record; or null.
423
+ function documentationSyncRetry(){
424
+ if(!gapsLive()||!documentationJournaling()||options.providerDevelopment===true)return null;
425
+ const retry=documentationSyncRetryCode({state,code,attempt,cache:[...cache.values()]},metadata,documentationRetries());
426
+ const source=retry===null?null:documentationRecord(calls.at(-1)?.documentationSync);
427
+ return source?{code:retry,source,detail:[...cache.values()].at(-1).result.reason??null}:null;
428
+ }
429
+ // The latest stop confirmation for the source call: documentation-sync-retry
430
+ // (develop_redo) or effect-interrupted (abandon_effect), bound to its start.
431
+ const documentationStopRecord=start=>journal?.findLast(row=>['documentation-sync-retry','effect-interrupted'].includes(row.payload.type)
432
+ &&row.payload.startDigest===start)?.payload??null;
433
+ // A confirmed documentation block: what the redo reuses and is checked against.
434
+ function documentationRedoSource(){
435
+ if(!gapsLive()||!documentationJournaling()||state!=='blocked'||!DOCUMENTATION_SYNC_CODES.includes(code))return null;
436
+ const start=calls.at(-1)?.documentationSync,source=documentationRecord(start),stop=documentationStopRecord(start);
437
+ return source&&stop?{code,source,stop}:null;
438
+ }
439
+ // The Learning input of the develop effect whose sync is redone (checkpointed
440
+ // or interrupted): the redo reuses its developer answer, so it binds the same.
441
+ const documentationRedoLearningInput=()=>{
442
+ const stop=documentationRedoSource()?.stop;
443
+ return journal.findLast(row=>row.payload.type==='effect-intent'&&row.payload.effect.id===stop?.effectId)?.payload.effect.learningInput;
444
+ };
445
+ // The code root under the task's own fixed snapshot rules (the full develop
446
+ // scope and the ignore policy bound at create, as the task baseline), split
447
+ // at the documentation paths. The adapter takes its start and end with it too.
448
+ function documentationSnapshot(paths){
449
+ const baseline=captureReviewBaseline({...configToBaseline(metadata),version:original.version,
450
+ ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
451
+ !Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
452
+ original.ignorePolicy?.version===2?original.ignorePolicy:null);
453
+ return splitDocumentationState(baseline.files,paths);
454
+ }
455
+ const documentationRefusal=(refusal,detail)=>Object.assign(new Error(refusal),{code:refusal,reason:{
456
+ documentation_sync_out_of_scope:`documentation_sync_out_of_scope: 文档路径以外的文件已不等于文档同步开始时的内容${detail?`(${detail.replace(/^out_of_scope:\s*/,'')})`:''},`
457
+ +'可能是文档同步越界写的,也可能是之后的改动。先把它们还原到文档同步开始时的内容(git diff 查看差异;确需修改先走规格变更),再 advance 只重发文档同步。',
458
+ documentation_sync_stop_required:'documentation_sync_stop_required: 宿主无法证明文档同步的写入方已停止;先确认会话已停止修改文档,再以 --mode resume --allow-develop-redo 发送 develop_redo,之后 advance 只重发文档同步。',
459
+ documentation_sync_changed_after_stop:'documentation_sync_changed_after_stop: 文档路径在确认停写之后又变了,旧的文档同步可能仍在写。若是你自己的修改,确认会话已停后再发送一次 develop_redo 重新确认(不另占次数),再 advance;否则先让会话停下。',
460
+ documentation_sync_capture_failed:`documentation_sync_capture_failed: 宿主无法读取代码根来核对文档同步的起点(${detail});修好后再试。`}[refusal]});
461
+ // The live documentation state, or the refusal when the code root cannot be read.
462
+ function documentationLive(paths){
463
+ try{return documentationSnapshot(paths);}
464
+ catch(error){throw documentationRefusal('documentation_sync_capture_failed',failureCode(error));}
465
+ }
466
+ // The disk gate before every documentation-only redo (also after a restart):
467
+ // the rest of the code root equals the documentation start, and the
468
+ // documentation paths equal what they were when the stop was confirmed.
469
+ function assertDocumentationRedo(redo){
470
+ const live=documentationLive(redo.source.documents.map(item=>item.path));
471
+ if(live.othersDigest!==redo.source.othersDigest)throw documentationRefusal('documentation_sync_out_of_scope',
472
+ redo.code==='documentation_sync_out_of_scope'?[...cache.values()].at(-1)?.result.reason??null:null);
473
+ if(digest(live.documents)!==digest(redo.stop.documents))throw documentationRefusal('documentation_sync_changed_after_stop');
474
+ }
475
+ // V9: provider development journals its worker's identity (develop-worker):
476
+ // spawning right before the spawn, started (pid = process group, start time)
477
+ // right after. A throw here makes the spawn wrapper kill the new group.
478
+ // Protected development also journals each sandbox subprocess that applies a
479
+ // proposal (apply_spawning / apply_started): it may outlive a dead host too.
480
+ const workerJournaling=()=>Boolean(invocationMode&&store&&taskMode
481
+ &&(developer.requestedModel!=='current-session'||options.protectedDevelopment===true));
482
+ function journalWorker(effectId,raw){
483
+ const event=json(raw),started=['started','apply_started'].includes(event?.phase);
484
+ shape(event,['phase',...(started?['pid']:[])]);
485
+ need(['spawning','started','apply_spawning','apply_started'].includes(event.phase),'invalid_input');
486
+ persist('develop-worker',{effectId,invocationId:calls.at(-1).invocationId,phase:event.phase,
487
+ ...(started?{pid:event.pid,startTime:readProcessStartTime(event.pid)}:{})});
488
+ }
489
+ // The host's proof for a provider develop: 'none' (never spawned), 'gone',
490
+ // or a refusal code. Windows, permission errors and unreadable start times
491
+ // are unknown, never gone.
492
+ // checkpointed: the host was alive after the spawn, so a spawned child with a
493
+ // pid was journaled in the same tick; spawning alone then means no process.
494
+ // Every started writer is checked: the provider worker and each proposal
495
+ // apply subprocess.
496
+ function workerProof(worker,{checkpointed=false}={}){
497
+ if(worker?.journal!==true)return {code:'worker_identity_unrecorded'};
498
+ if(!checkpointed&&(worker.spawned&&worker.started===null||worker.applies.some(item=>item.started===null)))
499
+ return {code:'worker_identity_incomplete'};
500
+ const binding=workerGoneBinding(worker);
501
+ if(binding===null)return {proof:'none'};
502
+ for(const started of [worker.started,...worker.applies.map(item=>item.started)].filter(Boolean)){
503
+ const verdict=inspectWorkerGroup(started);
504
+ if(verdict!=='gone')return {code:verdict==='alive'?'worker_process_alive':'worker_process_unknown',pid:started.pid};
505
+ }
506
+ return {proof:'gone',binding};
507
+ }
508
+ // V6: where writes are applied proposals, the live root must still equal the
509
+ // journal-pinned round start (no partial apply is sent to review).
510
+ function verifyRoundStart(basis,prefix,what){
511
+ const refuse=(code,detail)=>{throw Object.assign(new Error(code),{code,reason:detail});};
512
+ if(basis===null)refuse(`${prefix}_root_unpinned`,`${what}的本轮起点无法从运行存档确定(本轮之前已有被拦下的交付),宿主不能证明中途没有写到一半;核对后用新建运行替代。`);
513
+ try{
514
+ if(basis==='reviewed_package')verifyReviewPackage({root:config.root,baseline:attemptBaseline(original,reviewPackage.identity.attempt),
515
+ checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
516
+ else assertReadyBaseline();
517
+ }catch(error){refuse(`${prefix}_root_changed`,boundedReason(`${what}中途退出后代码根已不等于本轮起点(可能是应用到一半的提案):`,
518
+ [safeReason(error)??error?.code??'changed'],'。把这些文件还原到本轮起点后重试;半成品不会被当成新交付送审。'));}
519
+ return basis;
520
+ }
521
+ const workerRefusal=(prefix,result)=>({code:`${prefix}_${result.code}`,reason:{
522
+ worker_identity_unrecorded:'这次 provider 开发没有在运行存档里记下 worker 进程身份(旧版本建的 effect,或未配置 provider 模型),宿主无法证明进程已退出;按 reason 手工核对后只能新建运行替代。',
523
+ worker_identity_incomplete:'运行存档只记到 worker 即将启动,没有记下 pid,宿主无法证明进程已退出;请手工确认该 provider 进程已不存在后,用新建运行替代。',
524
+ worker_process_alive:`provider worker 或提案应用子进程的进程组(pid ${result.pid})仍在运行,可能还在写文件;等它退出或手工结束该进程组后再试。`,
525
+ worker_process_unknown:`宿主无法核对进程组(pid ${result.pid})是否已退出(Windows、无权限或读不到启动时间),不放行;确认进程已退出后在能核对的环境重试。`}[result.code]});
526
+ // P1-3: a develop that failed before dispatch. A legacy execution_error also
527
+ // needs the live code root to still equal the journal-pinned round start.
528
+ function developDispatchRetry(){
529
+ if(!gapsLive()||options.providerDevelopment===true)return null;
530
+ const basis=developDispatchBasis({state,code,attempt,cache:[...cache.values()],calls,receipt,reviewPackage,priorReview},
531
+ metadata,answerGapCount('develop-dispatch-retry'));
532
+ if(basis===null)return null;
533
+ try{
534
+ if(basis==='reviewed_package')verifyReviewPackage({root:config.root,baseline:attemptBaseline(original,reviewPackage.identity.attempt),
535
+ checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
536
+ else assertReadyBaseline();
537
+ }catch{return null;}
538
+ return basis;
539
+ }
540
+ // A45: the host died between task-commit-intent and task-commit-result. Only
541
+ // the journaled commit plan is followed (recoverCommit); complete is never redone.
542
+ // A result already journaled (a recovery that died before its checkpoint)
543
+ // closes the same effect with the checkpoint only.
544
+ const commitRecoveryTransaction=()=>!invocationMode||!store||busy||poisoned||restored?.pending?.kind!=='complete'
545
+ ||!restored.transaction?null:restored.transaction;
546
+ // The Learning input a re-check must carry: exactly the delivered develop's.
547
+ // A documentation-only redo reuses that develop's answer, so it carries the
548
+ // input bound to it too (a LESSONS.md edited meanwhile changes a fresh read).
549
+ const recheckLearningInput=()=>{
550
+ if(RECHECK_CODES.includes(status().code))return json([...cache.values()].at(-1).effect.learningInput);
551
+ const bound=documentationRedoSource()===null?undefined:documentationRedoLearningInput();
552
+ return bound===undefined?null:json(bound);
553
+ };
324
554
  const status=()=>{
325
555
  let current=store?publication:privateStatus();
556
+ if(current.state==='unknown'&&commitRecoveryTransaction()!==null){
557
+ const {reason:discard,...rest}=current;
558
+ current=freeze({...rest,state:'blocked',code:COMMIT_INTERRUPTED_CODE,reason:COMMIT_INTERRUPTED_REASON});
559
+ }
560
+ if(current.state==='unknown'){
561
+ const recheck=developRecheck();
562
+ if(recheck!==null)current=freeze({...current,state:'blocked',code:recheck,reason:developRecheckReason(recheck,current.code,current.reason)});
563
+ else if(completeRecheck())current=freeze({...current,state:'blocked',code:COMPLETE_RECHECK_CODE,reason:completeRecheckReason(current.code)});
564
+ }
565
+ if(current.state==='blocked'&&current.code==='failed'&&answerRetryable())
566
+ current=freeze({...current,code:'develop_answer_invalid',reason:developAnswerInvalidReason(calls.at(-1).failureResult)});
567
+ if(developTimeoutState(current)){
568
+ const {reason:discard,...rest}=current;
569
+ current=developTimeoutRetryBasis()!==null
570
+ ?freeze({...rest,state:'blocked',code:'develop_call_timeout',reason:DEVELOP_CALL_TIMEOUT_REASON})
571
+ :freeze({...rest,state:'unknown',code:'call_timeout',...(current.state==='blocked'
572
+ ?{reason:'develop_call_timeout: 代码根已不等于本轮开发起点(超时后有写入),不能重发;按 unknown 只读核对。'}:{})});
573
+ }
574
+ if(current.state==='unknown'){
575
+ const basis=developDispatchRetry();
576
+ if(basis!==null){const {reason:discard,...rest}=current;
577
+ current=freeze({...rest,state:'blocked',code:DISPATCH_RETRY_CODE,reason:developDispatchReason(current.code)});}
578
+ }
579
+ // The journaled block keeps its start binding: a changed root falls to develop_redo below.
580
+ if(current.state==='blocked'&&current.code===DISPATCH_RETRY_CODE&&developDispatchRetry()===null){
581
+ const {reason:discard,...rest}=current;current=freeze({...rest,state:'unknown',code:[...cache.values()].at(-1).result.code});
582
+ }
583
+ // Q16/Q17: a failed documentation_sync of the final task (never develop_redo).
584
+ if(current.state==='unknown'){
585
+ const retry=documentationSyncRetry();
586
+ if(retry!==null){
587
+ const {reason:discard,...rest}=current;
588
+ current=freeze({...rest,state:'blocked',code:retry.code,reason:documentationSyncStopReason(retry.code,retry.detail),developRedoRequired:true});
589
+ }
590
+ }
591
+ if(current.state==='unknown'||current.state==='blocked'&&['failed','unavailable'].includes(current.code)){
592
+ const cause=developRedoRequired();
593
+ if(cause!==null){const {reason:discard,...rest}=current;
594
+ current=freeze({...rest,state:'blocked',code:DEVELOP_REDO_CODE,reason:developRedoRequiredReason(cause),developRedoRequired:true});}
595
+ }
596
+ // R2: a spent exit is an explicit limit block, never an exit-less unknown.
597
+ if((current.state==='unknown'||current.state==='blocked'&&['failed','unavailable'].includes(current.code))&&gapsLive()
598
+ &&(options.providerDevelopment!==true||providerRun)){
599
+ const limit=answerGapLimit({state,code,attempt,cache:[...cache.values()],calls,receipt,learningResult,taskCommit,reviewPackage,priorReview},
600
+ metadata,{developRecheck:answerGapCount('develop-recheck'),completeRecheck:answerGapCount('complete-recheck'),
601
+ developRedo:answerGapCount('develop-answer-redo'),developDispatch:answerGapCount('develop-dispatch-retry'),
602
+ documentationSync:documentationRetries(),
603
+ workers:parsedHistory?.workers??null});
604
+ if(limit!==null&&(options.providerDevelopment===true?limit.code==='develop_redo_limit'
605
+ :!(options.protectedDevelopment===true&&limit.code==='develop_redo_limit'))){
606
+ const {reason:discard,...rest}=current;current=freeze({...rest,state:'blocked',code:limit.code,reason:limit.reason});}
607
+ }
326
608
  if(!busy&&!poisoned&&bootstrapReviewRecoverable(frame(),restored?.pending??null,metadata.bootstrap))
327
609
  current=freeze({...current,bootstrapReviewRecovery:true});
610
+ // V5: a spent retryable review block with a no-result redispatch left stays
611
+ // blocked until the operator confirms the original reviewer stopped
612
+ // (abandon_review journals review-redispatch); a fully spent round is an
613
+ // explicit limit block.
614
+ if(current.state==='blocked'&&reviewRedispatchLive())
615
+ current=freeze({...current,reviewRedispatchStopRequired:true,reason:reviewRedispatchStopReason(current.code)});
616
+ else if(current.state==='blocked'&&reviewRedispatchSpent())
617
+ current=freeze({...current,code:REVIEW_REDISPATCH_LIMIT_CODE,reason:reviewRedispatchLimitReason(current.code)});
618
+ // A round whose review never started: a refused authorization (explicit confirmation
619
+ // needed) or registrations voided before dispatch three times. Shared with replay.
620
+ if(!busy&&current.state==='pending_review'){
621
+ const never=reviewNeverStartedStatus({state,code,attempt,cache:[...cache.values()]},reviewDispatchConfirmations());
622
+ if(never!==null)current=freeze({...current,...never});
623
+ }
328
624
  // Status only; never part of a cached result or checkpoint.
329
625
  if(current.state==='unknown'&&reviewResultAbandonable())current=freeze({...current,abandonableReviewResult:true});
626
+ else if(current.state==='unknown'&&!(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned&&!restored?.pending){
627
+ const refusal=reviewAbandonRefusal({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1],reviewRedispatchRecords());
628
+ if(refusal)current=freeze({...current,reason:`${refusal.code}: ${refusal.reason}`,reviewAbandonRefusal:refusal.code});
629
+ }
330
630
  const available=Boolean((metadata.externalModels||metadata.executionPolicy))&&!busy&&!poisoned&&invocationMode&&store&&['unknown','pending_review'].includes(current.state)
331
631
  &&readRunnerHistory(journal,metadata,3).reviewReconciliation!==null;
332
632
  if((metadata.externalModels||metadata.executionPolicy)&&!busy&&!poisoned&&invocationMode&&store&&reviewInvocation?.registration
@@ -400,6 +700,12 @@ export function createTaskRunner(options) {
400
700
  }
401
701
  };
402
702
  const halt=(next,why,detail=null)=>{state=next;code=why;reason=detail;};
703
+ function assertReadyBaseline(){
704
+ compareReviewBaseline(withBoundSpecification(captureReviewBaseline({...configToBaseline(metadata),version:original.version,
705
+ ...(Object.hasOwn(original,'specification')?{specification:{specsRoot:original.specificationRoot,feature:original.specification.feature}}:{})},
706
+ !Object.hasOwn(original,'ignorePolicy'),original.ignorePolicy?.version??2,
707
+ original.ignorePolicy?.version===2?original.ignorePolicy:null)),original);
708
+ }
403
709
  const specificationLive=(currentState,currentCode)=>Object.hasOwn(original,'specification')
404
710
  &&['develop','review','complete'].some(kind=>stageAllowed(kind,currentState,currentCode,priorReview?.verdict));
405
711
  function frame(){return {state,code,reason,attempt,session,sequence,reviewPackage,currentChecks,receipt,receipts,calls,
@@ -425,7 +731,7 @@ export function createTaskRunner(options) {
425
731
  'review-invocation-registered':'intent','review-invocation-started':'result','review-invocation-result':'result',
426
732
  'review-invocation-abandoned':'result','review-invocation-receipt':'result','review-invocation-reconciled':'result','effect-abandoned':'result',
427
733
  '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',
734
+ '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
735
  'bootstrap-review-recovered':'result'}[type],
430
736
  payload:version===3?runnerPayloadV3(type,fields):runnerPayload(type,fields,version)};
431
737
  const body={version:1,seq:journal.length+1,...basic,previousDigest:journal.at(-1)?.digest??null};
@@ -449,7 +755,7 @@ export function createTaskRunner(options) {
449
755
  const saved=store.snapshot();need(!poisoned,'store_failure');
450
756
  const {revision:old,...body}=current,expected={...body,records:[...journal,record]};
451
757
  same(saved,{...expected,revision:digest(expected)},'runner_store_changed');
452
- need(!poisoned,'store_failure');journal=saved.records;storeRevision=saved.revision;
758
+ need(!poisoned,'store_failure');journal=saved.records;storeRevision=saved.revision;parsedHistory=parsed;
453
759
  if(type.startsWith('task-commit-'))taskCommit=parsed.state.taskCommit;
454
760
  return record;
455
761
  });
@@ -540,7 +846,7 @@ export function createTaskRunner(options) {
540
846
  return status();
541
847
  }
542
848
  function active(){need(!poisoned,'store_failure');need(state!=='cancelled','cancelled');}
543
- async function bounded(fn,request) {
849
+ async function bounded(fn,request,extraControl=null) {
544
850
  active();let timer,abort;
545
851
  try {
546
852
  const boxed=await Promise.race([
@@ -549,7 +855,7 @@ export function createTaskRunner(options) {
549
855
  const accept=value=>{try {resolve({value:json(value)});}catch(error){reject(error);}};
550
856
  queueMicrotask(()=>{
551
857
  try {
552
- active();const returned=fn(request,{signal:controller.signal});
858
+ active();const returned=fn(request,{signal:controller.signal,...(extraControl??{})});
553
859
  if(types.isPromise(returned)) {
554
860
  const supported=Object.getPrototypeOf(returned)===promisePrototype
555
861
  && !Object.hasOwn(returned,'constructor');
@@ -569,14 +875,14 @@ export function createTaskRunner(options) {
569
875
  return boxed.value;
570
876
  } finally {clearTimeout(timer);controller.signal.removeEventListener('abort',abort);}
571
877
  }
572
- async function invoke(adapter,role,contextId,payload) {
878
+ async function invoke(adapter,role,contextId,payload,extraControl=null) {
573
879
  const request=requestFor({invocationId:`${session}.${++sequence}`,identity:{...config.identity,attempt},
574
880
  role,provider:adapter.provider,requestedModel:adapter.requestedModel,contextId,payload});
575
881
  const call={invocationId:request.invocationId,contextId,provider:adapter.provider,requestedModel:adapter.requestedModel,
576
882
  effectiveModel:'unknown',channel:'fixture',started:true,terminal:'running',requestDigest:request.requestDigest,resultDigest:null};
577
883
  calls.push(call);
578
884
  try {
579
- const response=terminalFor(await bounded(adapter.run,request),request);active();
885
+ const response=terminalFor(await bounded(adapter.run,request,extraControl),request);active();
580
886
  call.terminal=response.status;call.effectiveModel=response.effectiveModel;call.resultDigest=digest(response.result);
581
887
  if(role==='developer'&&response.status==='failed'&&response.result!==null)call.failureResult=response.result;
582
888
  if(role==='developer'&&Object.hasOwn(response,'blockedReason'))call.blockedReason=response.blockedReason;
@@ -908,14 +1214,80 @@ export function createTaskRunner(options) {
908
1214
  halt('blocked','develop_requirement_missing',boundedReason('develop_requirement_missing: ',missing,
909
1215
  ' are requirement files and must exist in the review package; restore them and resume to redo this attempt'));
910
1216
  };
1217
+ // After a delivered develop: the task checks, the verification precheck, the
1218
+ // unchanged-after-review guard and the host handoff. False when it halted.
1219
+ async function hostDeliveryChecks(){
1220
+ currentChecks=await collectChecks();active();
1221
+ if(failedChecks(currentChecks).length){halt('blocked','develop_checks_not_passed',checkFailureReason(currentChecks,'develop_checks_not_passed'));return false;}
1222
+ if(!await verificationSatisfied(currentChecks)){halt('blocked','verification_precheck_failed');return false;}
1223
+ active();
1224
+ // unchangedSinceRejection builds a package too, so an empty delivery or a
1225
+ // deleted in-scope requirement surfaces there first and takes the same
1226
+ // retryable block (emptyDelivery).
1227
+ let unchanged;
1228
+ try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return false;}
1229
+ if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return false;}
1230
+ try{createHostHandoff({root:config.root,baseline:base,checks:currentChecks,
1231
+ handoffPath:completion.handoffs[attempt-1]});}
1232
+ catch(error){emptyDelivery(error);return false;}
1233
+ return true;
1234
+ }
1235
+ async function packageDelivery(v){
1236
+ active();
1237
+ let nextPackage;
1238
+ try{nextPackage=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,
1239
+ ...(taskLearning?.hostHandoff===true?{handoffPath:completion.handoffs[attempt-1]}:{})});}
1240
+ catch(error){emptyDelivery(error);return;}
1241
+ if(taskLearning!==null)validateTaskLearningReviewPackage(nextPackage,learningResult.writeback,v.learningInput,
1242
+ learningResult.bootstrap??null,metadata.bootstrap??null);
1243
+ reviewPackage=nextPackage;
1244
+ state='awaiting_review';
1245
+ }
1246
+ function developControl(effectId,documentationRedo){
1247
+ const control={...(workerJournaling()?{onWorker:event=>journalWorker(effectId,event)}:{}),
1248
+ ...(documentationJournaling()?{onDocumentationSync:event=>journalDocumentationSync(effectId,event),
1249
+ documentationSnapshot:paths=>documentationSnapshot(json(paths))}:{}),
1250
+ ...(documentationRedo?{documentationRedo}:{})};
1251
+ return Object.keys(control).length?control:null;
1252
+ }
1253
+ // Q16/Q17: a develop whose documentation_sync started (its call carries the
1254
+ // record) and then failed: the code its checkpoint shows, and the detail
1255
+ // (out-of-scope paths, or the transport code of a lost answer).
1256
+ function documentationFailure(v,error){
1257
+ const call=calls.at(-1);
1258
+ if(v.kind!=='develop'||call?.terminal!=='unknown'||typeof call.documentationSync!=='string')return null;
1259
+ let raw=null;
1260
+ try{const d=Object.getOwnPropertyDescriptor(error,'code');if(d&&Object.hasOwn(d,'value')&&typeof d.value==='string')raw=d.value;}catch{}
1261
+ if(raw==='documentation_sync_blocked')return {code:'documentation_sync_answer_blocked',detail:null};
1262
+ if(['documentation_sync_answer_invalid','invalid_input','invalid_result'].includes(raw))return {code:'documentation_sync_answer_invalid',detail:null};
1263
+ if(raw==='out_of_scope')return {code:'documentation_sync_out_of_scope',detail:safeReason(error)};
1264
+ return {code:'documentation_sync_answer_missing',detail:typeof raw==='string'&&/^[a-z_]{1,64}$/.test(raw)?raw:'execution_error'};
1265
+ }
911
1266
  async function perform(v) {
912
1267
  if(v.kind==='develop') {
913
- need(stageAllowed('develop',state,code,priorReview?.verdict),'stage_mismatch');state='developing';code=null;reason=null;checkNewPaths=null;receipt=null;
1268
+ need(stageAllowed('develop',state,code,priorReview?.verdict),'stage_mismatch');
1269
+ const recheck=state==='blocked'&&RECHECK_CODES.includes(code);
1270
+ // Q16/Q17: a documentation-only redo reuses the journaled developer answer.
1271
+ let documentationRedo=null;
1272
+ if(state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(code)){
1273
+ const source=documentationRecord(calls.at(-1)?.documentationSync);need(source!==null,'documentation_sync_unavailable');
1274
+ documentationRedo={result:source.result,effectiveModel:source.effectiveModel};
1275
+ }
1276
+ state='developing';code=null;reason=null;checkNewPaths=null;receipt=null;
914
1277
  // The adapter would refuse this scope before any provider runs. Block it
915
1278
  // here instead: no call starts, nothing is written, and the outcome is
916
1279
  // definite rather than unknown (create refuses such runs already).
917
1280
  const refusedScope=protectedDevelopScope(metadata);
918
1281
  if(refusedScope.length){halt('blocked','protected_scope',protectedScopeBlockReason(refusedScope));return;}
1282
+ // The delivery and its Learning writeback are already on disk: re-run only
1283
+ // the checks, the precheck, the handoff and the package. No developer call.
1284
+ if(recheck){
1285
+ if(!await hostDeliveryChecks())return;
1286
+ writeCmAiTaskLearningHandoff({handoffPath:completion.handoffs[attempt-1],feature:taskLearning.feature,
1287
+ identity:{...config.identity,attempt},learningInput:v.learningInput,application:learningResult.application,
1288
+ retrospective:learningResult.retrospective,writeback:learningResult.writeback});
1289
+ await packageDelivery(v);return;
1290
+ }
919
1291
  const previousLearning=learningResult;
920
1292
  const previousBootstrap=learningResult?.bootstrap??null;
921
1293
  const previousWriteback=learningResult?.writeback??null;
@@ -937,7 +1309,8 @@ export function createTaskRunner(options) {
937
1309
  requirements:original.files.filter(f=>config.requirements.includes(f.path)),priorReview,
938
1310
  ...supersededReviewPayload(carriedReview,attempt),
939
1311
  ...(Object.hasOwn(original,'specification')?{specification:verifySpecificationMaterial(original)}:{}),
940
- ...(Object.hasOwn(v,'learningInput')?{learningInput:v.learningInput}:{})});
1312
+ ...(Object.hasOwn(v,'learningInput')?{learningInput:v.learningInput}:{})},
1313
+ developControl(v.id,documentationRedo));
941
1314
  if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
942
1315
  if(result.response.status!=='succeeded'){
943
1316
  const failure=result.response.result?.code;
@@ -972,21 +1345,7 @@ export function createTaskRunner(options) {
972
1345
  {learningInput:v.learningInput,retrospective});
973
1346
  learningResult=freeze({application,retrospective,writeback,...(instructionEvidence?{bootstrap:instructionEvidence}:{})});
974
1347
  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
- }
1348
+ if(taskLearning.hostHandoff===true&&!await hostDeliveryChecks())return;
990
1349
  writeCmAiTaskLearningHandoff({handoffPath:completion.handoffs[attempt-1],feature:taskLearning.feature,
991
1350
  identity:{...config.identity,attempt},learningInput:v.learningInput,application,retrospective,writeback});
992
1351
  }
@@ -1000,15 +1359,7 @@ export function createTaskRunner(options) {
1000
1359
  try{unchanged=unchangedSinceRejection();}catch(error){emptyDelivery(error);return;}
1001
1360
  if(unchanged){halt('blocked','develop_unchanged_after_review',unchanged);return;}
1002
1361
  }
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;
1362
+ await packageDelivery(v);return;
1012
1363
  }
1013
1364
  if(v.kind==='review') {
1014
1365
  state='reviewing';verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
@@ -1048,7 +1399,7 @@ export function createTaskRunner(options) {
1048
1399
  ...(Object.hasOwn(learningResult,'application')?{application:learningResult.application}:{}),
1049
1400
  retrospective:learningResult.retrospective,
1050
1401
  writeback:learningResult.writeback});
1051
- } catch {halt('blocked','package_mismatch');return;}
1402
+ } catch {halt('blocked','package_mismatch','package_mismatch: 完成前核对 Learning handoff 与已审交付不一致(handoff 文件或 Learning 记录被改动);保留现场核对 .reviews 下的 handoff,不能直接重试。');return;}
1052
1403
  try {
1053
1404
  checkCompletion({receipt,registered:registered.get(receipt?.id),execution:calls.find(c=>c.invocationId===receipt?.id),
1054
1405
  reviewPackage,identity:{...config.identity,attempt}});
@@ -1083,7 +1434,7 @@ export function createTaskRunner(options) {
1083
1434
  }
1084
1435
  const limitDue=()=>retryLimitDue()?recordRetryLimit:completionLimitDue()?recordCompletionLimit:null;
1085
1436
  function executeEffect(raw) {
1086
- let v;
1437
+ let v,timeoutBasis=null,answerRetry=false,recheck=null,completeSource=null,dispatchBasis=null;
1087
1438
  try {
1088
1439
  need(!poisoned,'store_failure');v=json(raw);
1089
1440
  shape(v,['version','id','identity','kind',...(Object.hasOwn(v,'learningInput')?['learningInput']:[])]);id(v.id);validIdentity(v.identity);
@@ -1102,30 +1453,92 @@ export function createTaskRunner(options) {
1102
1453
  if(old){need(old.digest===digest(v),'intent_conflict');return Promise.resolve(old.result);}
1103
1454
  if(restored?.pending?.id===v.id){need(digest(restored.pending)===digest(v),'intent_conflict');return Promise.resolve(status());}
1104
1455
  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');
1456
+ // A timed-out develop (journaled or already released) is redone only while
1457
+ // the code root still equals its start, verified here in the dispatch tick.
1458
+ // A delivered develop whose later checks lost their answer is re-checked,
1459
+ // never redeveloped; the re-check carries the delivered Learning input.
1460
+ if(v.kind==='develop'&&state==='unknown')recheck=developRecheck();
1461
+ if(v.kind==='develop'&&(recheck!==null||state==='blocked'&&RECHECK_CODES.includes(code)))
1462
+ need(digest(v.learningInput)===digest([...cache.values()].at(-1).effect.learningInput),'runner_learning');
1463
+ if(v.kind==='complete'&&state==='unknown'&&completeRecheck())completeSource=code;
1464
+ if(v.kind==='develop'&&state==='unknown'&&recheck===null)dispatchBasis=developDispatchRetry();
1465
+ // Q16/Q17: re-ask only documentation_sync; refused (nothing journaled)
1466
+ // while the code root outside the documentation paths changed, or while a
1467
+ // writer that never answered may still be writing the documentation.
1468
+ // Q16/Q17: never redispatched before the operator confirmed the writer stopped.
1469
+ if(v.kind==='develop'&&state==='unknown'&&recheck===null&&documentationSyncRetry()!==null)
1470
+ throw documentationRefusal('documentation_sync_stop_required');
1471
+ if(v.kind==='develop'&&state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(code)){
1472
+ const redo=documentationRedoSource();need(redo!==null,'documentation_sync_unavailable');
1473
+ if(taskLearning!==null)need(digest(v.learningInput)===digest(documentationRedoLearningInput()),'runner_learning');
1474
+ assertDocumentationRedo(redo);
1475
+ }
1476
+ // A journaled develop_dispatch_failed (also after a restart between its
1477
+ // record and the develop intent) re-verifies the round start right here.
1478
+ if(v.kind==='develop'&&state==='blocked'&&code===DISPATCH_RETRY_CODE)
1479
+ need(developDispatchRetry()!==null,'develop_dispatch_root_changed');
1480
+ if(v.kind==='develop'&&recheck===null&&developTimeoutState({state,code})){
1481
+ timeoutBasis=developTimeoutRetryBasis();need(timeoutBasis!==null,'develop_timeout_root_changed');
1482
+ if(state==='blocked')timeoutBasis=null;
1483
+ }
1484
+ // A refused authorization is a decision: a review is admitted again only after the
1485
+ // operator's journaled confirmation (abandon_review), bounded per round.
1486
+ if(v.kind==='review'&&reviewDenialUnconfirmed({state,code}))
1487
+ need(false,reviewDenialExhausted({state,code},reviewDispatchConfirmations())?REVIEW_DENIAL_LIMIT_CODE:REVIEW_DISPATCH_CONFIRM_REQUIRED_CODE);
1488
+ answerRetry=v.kind==='develop'&&state==='blocked'&&code==='failed'&&answerRetryable();
1489
+ need(timeoutBasis!==null||answerRetry||recheck!==null||completeSource!==null||dispatchBasis!==null
1490
+ ||stageAllowed(v.kind,state,code,priorReview?.verdict),'stage_mismatch');need(effectSlotFree(v.kind,[...cache.values()],calls),'limit_exceeded');
1491
+ need(!(v.kind==='review'&&reviewNotDispatchedExhausted({state,code,attempt,cache:[...cache.values()]},reviewDispatchConfirmations().extended)),REVIEW_NOT_DISPATCHED_LIMIT_CODE);
1106
1492
  if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
1107
1493
  if(v.kind==='develop'&&bootstrap!==null)bootstrap.assertWriteAuthorized();
1108
- } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:error.code??'invalid_input'}));}
1494
+ } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:error.code??'invalid_input',
1495
+ ...(String(error.code).startsWith('documentation_sync_')&&typeof error.reason==='string'?{reason:error.reason}:{})}));}
1496
+ // The timed-out develop left the code root as it started: journal that
1497
+ // finding, then redo the round like any retryable develop block.
1498
+ if(timeoutBasis!==null){
1499
+ try{persist('develop-timeout-retry',{effectId:[...cache.values()].at(-1).effect.id,invocationId:calls.at(-1).invocationId,basis:timeoutBasis});}
1500
+ catch{return Promise.resolve(poison());}
1501
+ halt('blocked','develop_call_timeout',DEVELOP_CALL_TIMEOUT_REASON);publication=privateStatus();
1502
+ }
1503
+ if(recheck!==null){
1504
+ const source=code;
1505
+ try{persist('develop-recheck',{effectId:[...cache.values()].at(-1).effect.id,invocationId:calls.at(-1).invocationId,code:recheck});}
1506
+ catch{return Promise.resolve(poison());}
1507
+ halt('blocked',recheck,developRecheckReason(recheck,source,reason));publication=privateStatus();
1508
+ }
1509
+ if(dispatchBasis!==null){
1510
+ const source=code;
1511
+ try{persist('develop-dispatch-retry',{effectId:[...cache.values()].at(-1).effect.id,invocationId:calls.at(-1).invocationId,basis:dispatchBasis});}
1512
+ catch{return Promise.resolve(poison());}
1513
+ halt('blocked',DISPATCH_RETRY_CODE,developDispatchReason(source));publication=privateStatus();
1514
+ }
1515
+ if(completeSource!==null){
1516
+ try{persist('complete-recheck',{effectId:[...cache.values()].at(-1).effect.id,source:completeSource});}
1517
+ catch{return Promise.resolve(poison());}
1518
+ halt('blocked',COMPLETE_RECHECK_CODE,completeRecheckReason(completeSource));publication=privateStatus();
1519
+ }
1520
+ if(answerRetry){
1521
+ try{persist('develop-answer-retry',{effectId:[...cache.values()].at(-1).effect.id,invocationId:calls.at(-1).invocationId});}
1522
+ catch{return Promise.resolve(poison());}
1523
+ halt('blocked','develop_answer_invalid',developAnswerInvalidReason(calls.at(-1).failureResult));publication=privateStatus();
1524
+ }
1109
1525
  if(v.kind==='develop'&&retryLimitDue()){try{return Promise.resolve(recordRetryLimit());}catch{return Promise.resolve(poison());}}
1110
1526
  if(v.kind==='complete'&&completionLimitDue()){try{return Promise.resolve(recordCompletionLimit());}catch{return Promise.resolve(poison());}}
1111
1527
  if(store) {
1112
1528
  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);
1529
+ if(state==='ready')assertReadyBaseline();
1117
1530
  // A rejected first delivery has no review package yet. Every later
1118
1531
  // developer effect must recheck the reviewed tree before dispatch,
1119
1532
  // except one that redoes a delivery this attempt already made: that
1120
1533
  // delivery changed the tree on purpose and never became a package, so
1121
1534
  // it is compared against the baseline when the new package is built,
1122
1535
  // exactly as a redo at attempt 1 is.
1123
- else if(reviewPackage!==null&&!(v.kind==='develop'&&state==='blocked'&&code!=='review_package_changed'
1536
+ else if(reviewPackage!==null&&!(v.kind==='develop'&&state==='blocked'&&!['review_package_changed','develop_call_timeout'].includes(code)
1124
1537
  &&stageAllowed('develop',state,code,priorReview?.verdict)))verifyReviewPackage({root:config.root,baseline:reviewPackage.identity.attempt===attempt?base:attemptBaseline(original,reviewPackage.identity.attempt),
1125
1538
  checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()});
1126
1539
  } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:failureCode(error),
1127
1540
  ...(safeReason(error)?{reason:safeReason(error)}:{})}));}
1128
- try{const record=persist('effect-intent',{effect:v});
1541
+ try{const record=persist('effect-intent',{effect:v,...(v.kind==='develop'&&workerJournaling()?{workerJournal:true}:{})});
1129
1542
  if(taskMode&&v.kind==='complete')completeEffect={effect:v,digest:record.digest};
1130
1543
  }catch{return Promise.resolve(poison());}
1131
1544
  }
@@ -1133,7 +1546,9 @@ export function createTaskRunner(options) {
1133
1546
  const packageBefore=reviewPackage;
1134
1547
  pending=(async()=>{
1135
1548
  try {await perform(v);}
1136
- catch(error){if(state!=='cancelled'){
1549
+ catch(error){if(state!=='cancelled'&&!poisoned&&documentationFailure(v,error)){
1550
+ const {code:failed,detail}=documentationFailure(v,error);halt('unknown',failed,detail);
1551
+ }else if(state!=='cancelled'){
1137
1552
  const failure=failureCode(error);
1138
1553
  const checkOnly=failure==='out_of_scope'&&Array.isArray(error.violations)&&error.violations.length>0
1139
1554
  &&error.violations.every(item=>item.newFile&&checkNewPaths?.has(item.path));
@@ -1184,7 +1599,10 @@ export function createTaskRunner(options) {
1184
1599
  if(poisoned)return result;
1185
1600
  try{publishRegisteredReview();}
1186
1601
  catch{return freeze({...result,code:'review_publication_required'});}
1187
- return ['unknown','pending_review'].includes(result.state)?status():result;
1602
+ // A spent retryable review block reads through status: its V5 redispatch
1603
+ // (pending_review) or the round's explicit limit.
1604
+ return ['unknown','pending_review'].includes(result.state)
1605
+ ||result.state==='blocked'&&REVIEW_RETRY_CODES.includes(result.code)?status():result;
1188
1606
  });
1189
1607
  return pending;
1190
1608
  }
@@ -1312,7 +1730,46 @@ export function createTaskRunner(options) {
1312
1730
  };
1313
1731
  const abandonReview=raw=>{
1314
1732
  try{
1733
+ // A review that never started (a refused authorization, or the spent not-dispatched
1734
+ // redispatch bound): nothing ran, so no process needs proving stopped, even for
1735
+ // external-model runs. Only this explicit, audited confirmation leaves those ends.
1736
+ if(invocationMode&&store&&!busy&&!poisoned&&!restored?.pending&&state==='pending_review'){
1737
+ const confirmed=reviewDispatchConfirmations(),ended={state,code,attempt,cache:[...cache.values()]};
1738
+ const denied=reviewDenialUnconfirmed(ended),voided=reviewNotDispatchedExhausted(ended,confirmed.extended);
1739
+ if(denied||voided){
1740
+ if(denied&&reviewDenialExhausted(ended,confirmed))
1741
+ throw Object.assign(new Error(REVIEW_DENIAL_LIMIT_CODE),{code:REVIEW_DENIAL_LIMIT_CODE,reason:reviewDenialLimitReason()});
1742
+ if(voided&&!reviewNotDispatchedExtendable(ended,confirmed))
1743
+ throw Object.assign(new Error(REVIEW_NOT_DISPATCHED_LIMIT_CODE),
1744
+ {code:REVIEW_NOT_DISPATCHED_LIMIT_CODE,reason:reviewNotDispatchedLimitReason(code,confirmed.extended)});
1745
+ need(denied?reviewDenialConfirmable(ended,confirmed):true,'review_abandon_unavailable');
1746
+ const value=json(raw);shape(value,['allowed','reason']);
1747
+ need(value.allowed===true,'review_abandon_authorization_required');
1748
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1749
+ &&!/[\r\n\0]/.test(value.reason),'review_abandon_reason_required');
1750
+ persist('review-dispatch-confirmed',{effectId:[...cache.values()].at(-1).effect.id,attempt,code,reason:value.reason,
1751
+ at:new Date().toISOString()});
1752
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1753
+ ({state,code}=recovered);reason=recovered.reason??null;publication=privateStatus();return status();
1754
+ }
1755
+ }
1315
1756
  need(!(metadata.externalModels||metadata.executionPolicy),'external_review_reconciliation_required');
1757
+ // V5 (A34): the operator confirms the spent block's reviewer stopped; this
1758
+ // journals the round's second no-result redispatch (no dispatch here).
1759
+ if(state==='blocked'&&reviewRedispatchLive()){
1760
+ const value=json(raw);shape(value,['allowed','reason']);
1761
+ need(value.allowed===true,'review_abandon_authorization_required');
1762
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1763
+ &&!/[\r\n\0]/.test(value.reason),'review_abandon_reason_required');
1764
+ persist('review-redispatch',{effectId:[...cache.values()].at(-1).effect.id,
1765
+ invocationId:reviewInvocation.registration.grant.invocationId,attempt,code,reason:value.reason,at:new Date().toISOString()});
1766
+ state='pending_review';publication=privateStatus();return status();
1767
+ }
1768
+ if(state==='blocked'&&reviewRedispatchSpent())throw Object.assign(new Error('review_abandon_budget_exhausted'),{code:'review_abandon_budget_exhausted'});
1769
+ if(invocationMode&&store&&!busy&&!poisoned&&state==='unknown'&&!restored?.pending&&!reviewResultAbandonable()){
1770
+ const refusal=reviewAbandonRefusal({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1],reviewRedispatchRecords());
1771
+ if(refusal)throw Object.assign(new Error(refusal.code),refusal);
1772
+ }
1316
1773
  need(invocationMode&&store&&!busy&&!poisoned&&state==='unknown'
1317
1774
  &&(restored?.pending?.kind==='review'||reviewResultAbandonable()),'review_abandon_unavailable');
1318
1775
  const value=json(raw);shape(value,['allowed','reason']);
@@ -1330,26 +1787,34 @@ export function createTaskRunner(options) {
1330
1787
  publication=privateStatus();return status();
1331
1788
  }
1332
1789
  const history=readRunnerHistory(journal,metadata,3),last=journal.at(-1);
1790
+ // A38: the no-verdict result of the pending review reached the journal, its checkpoint did not.
1791
+ const withResult=last?.payload?.type==='review-invocation-result'&&history.pendingResultAbandonable===true;
1333
1792
  need(history.pending?.id===restored.pending.id&&history.state.state==='unknown'
1334
1793
  &&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,
1794
+ &&(['review-invocation-registered','review-invocation-started'].includes(last?.payload?.type)
1795
+ &&history.state.reviewInvocation?.result===null||withResult)
1796
+ &&history.state.reviewInvocation?.registration,
1337
1797
  'review_abandon_unavailable');
1338
1798
  const registration=journal.findLast(row=>row.payload.type==='review-invocation-registered'
1339
1799
  &&row.payload.effectId===history.pending.id);
1340
- const started=last.payload.type==='review-invocation-started'?last:null;
1800
+ const started=journal.findLast(row=>row.payload.type==='review-invocation-started'&&row.payload.effectId===history.pending.id
1801
+ &&journal.indexOf(row)>journal.indexOf(registration))??null;
1341
1802
  need(registration,'review_abandon_unavailable');
1342
1803
  const contextId=reviewers[0].contexts[attempt-1];
1343
- need(!reviewRetrySpent(history.state.cache,history.state.calls,attempt,contextId),'review_abandon_budget_exhausted');
1804
+ need(reviewRedispatchCount(history.state.cache,history.state.calls,attempt,contextId,reviewRedispatchRecords())<MAX_REVIEW_REDISPATCHES,
1805
+ 'review_abandon_budget_exhausted');
1344
1806
  const fields={effectId:history.pending.id,
1345
1807
  invocationId:history.state.reviewInvocation.registration.grant.invocationId,
1346
1808
  registeredDigest:registration.digest,startedDigest:started?.digest??null,
1809
+ ...(withResult?{resultDigest:last.digest}:{}),
1347
1810
  reason:value.reason,at:new Date().toISOString()};
1348
1811
  persist('review-invocation-abandoned',fields);
1349
1812
  const recovered=readRunnerHistory(journal,metadata,3).state;
1350
1813
  ({state,code,sequence,reviewInvocation}=recovered);calls.push(...recovered.calls.slice(calls.length));
1351
1814
  publication=privateStatus();return status();
1352
- }catch(error){return freeze({outcome:'rejected',code:error.code??'review_abandon_unavailable'});}
1815
+ }catch(error){return freeze({outcome:'rejected',code:error.code??'review_abandon_unavailable',
1816
+ ...(error.code==='review_abandon_budget_exhausted'?{reason:`本轮独立审查已无结论重派 ${MAX_REVIEW_REDISPATCHES} 次,不能再放弃重派;在途审查可用 abandon_effect 作废本运行后 --supersede-reviewed-evidence 新建运行。`}
1817
+ :typeof error.reason==='string'?{reason:error.reason}:{})});}
1353
1818
  };
1354
1819
  const reconcileReview=raw=>{
1355
1820
  try{
@@ -1388,20 +1853,124 @@ export function createTaskRunner(options) {
1388
1853
  &&!/[\r\n\0]/.test(value.reason),'effect_abandon_reason_required');
1389
1854
  const history=readRunnerHistory(journal,metadata,3),effect=history.pending;
1390
1855
  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
1856
  need(history.transaction===null&&history.state.taskCommit?.intentDigest==null,'effect_abandon_commit_pending');
1857
+ // V8: retire the interrupted step and continue the run from its retryable block.
1858
+ if(history.pendingInterruptible)return interruptEffect(history,effect,value.reason);
1859
+ need(effect.kind!=='review'||history.pendingAbandonable||history.pendingReviewExhausted,'effect_abandon_review_pending');
1860
+ need(['develop','complete','review'].includes(effect.kind),'effect_abandon_unavailable');
1861
+ // A develop whose writers are journaled is voided only with their gone-proof.
1862
+ let worker=null;
1863
+ if(effect.kind==='develop'&&history.pendingWorkerVoidable){
1864
+ const proof=workerProof(history.pendingWorker);
1865
+ if(proof.code){const refusal=workerRefusal('effect_abandon',proof);throw Object.assign(new Error(refusal.code),refusal);}
1866
+ worker=proof.binding??null;
1867
+ }else need(effect.kind!=='develop'||options.providerDevelopment!==true||history.pendingWorker?.journal===true,'effect_abandon_provider_development');
1395
1868
  need(history.state.state==='unknown'&&history.state.code==='reconciliation_required'
1396
- &&history.pendingAbandonable,'effect_abandon_unavailable');
1869
+ &&(history.pendingAbandonable||history.pendingReviewExhausted||history.pendingWorkerVoidable),'effect_abandon_unavailable');
1397
1870
  const intent=journal.findLast(row=>row.payload.type==='effect-intent');
1398
1871
  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()});
1872
+ lastRecordDigest:journal.at(-1).digest,reason:value.reason,at:new Date().toISOString(),...(worker?{worker}:{})});
1400
1873
  const recovered=readRunnerHistory(journal,metadata,3).state;
1401
1874
  ({state,code,sequence}=recovered);reason=recovered.reason;restored.pending=null;
1402
1875
  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、提交回执和旧进程后按原提交恢复路径处理。'}:{})});}
1876
+ }catch(error){return freeze({outcome:'rejected',code:poisoned?'store_failure':error.code??'effect_abandon_unavailable',
1877
+ ...(error.code==='effect_abandon_commit_pending'?{reason:'task-commit-intent 已写入,tasks.md 可能已改名或勾选;不能放弃或重做完成。发送 complete,宿主只按运行存档里的提交计划核对 tasks.md 并收尾。'}
1878
+ :!poisoned&&error.reason?{reason:error.reason}:{})});}
1879
+ };
1880
+ function interruptEffect(history,effect,why){
1881
+ const refuse=(code,detail)=>{throw Object.assign(new Error(code),{code,reason:detail});};
1882
+ const extra={};
1883
+ if(effect.kind==='develop'){
1884
+ if(options.providerDevelopment===true&&!providerRun)refuse('effect_interrupt_worker_identity_unrecorded',
1885
+ '这次 provider 开发没有配置 provider 模型,运行存档无法记下 worker 进程身份,宿主无法证明进程已退出;请手工确认进程已退出后用新建运行替代。');
1886
+ // Every journaled writer (provider worker, proposal apply subprocess) must be gone.
1887
+ if(providerRun||history.pendingWorker?.journal===true){
1888
+ const proof=workerProof(history.pendingWorker);
1889
+ if(proof.code){const refusal=workerRefusal('effect_interrupt',proof);refuse(refusal.code,refusal.reason);}
1890
+ if(proof.proof==='gone')extra.worker=proof.binding;
1891
+ }
1892
+ // A Claude provider and protected current-session development write by
1893
+ // applying proposals: a changed root can only be a partly applied one.
1894
+ if(providerRun?developer.provider==='claude':options.protectedDevelopment===true)
1895
+ extra.basis=verifyRoundStart(pendingDevelopStart(history.state),'effect_interrupt',providerRun?'Claude provider 开发':'受保护开发');
1896
+ // Q16: the host died during documentation_sync, after the developer
1897
+ // answered: bind the start record and the documentation as confirmed now,
1898
+ // so the run redoes only documentation_sync.
1899
+ if(history.pendingDocumentation){
1900
+ extra.startDigest=history.pendingDocumentation.digest;
1901
+ extra.documents=documentationLive(history.pendingDocumentation.payload.documents.map(item=>item.path)).documents;
1902
+ }
1903
+ }
1904
+ const intent=journal.findLast(row=>row.payload.type==='effect-intent');
1905
+ persist('effect-interrupted',{effectId:effect.id,effectKind:effect.kind,intentDigest:intent.digest,
1906
+ lastRecordDigest:journal.at(-1).digest,reason:why,at:new Date().toISOString(),...extra});
1907
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1908
+ ({state,code,sequence}=recovered);reason=recovered.reason??null;
1909
+ calls.splice(0,calls.length,...recovered.calls);
1910
+ restored.pending=null;publication=privateStatus();return status();
1911
+ }
1912
+ // A45: finish the interrupted task commit from its journaled plan only.
1913
+ const recoverCommit=()=>{
1914
+ try{
1915
+ const transaction=commitRecoveryTransaction();need(transaction!==null,'commit_recovery_unavailable');
1916
+ const effect=restored.pending,intent=transaction.intentRecord.payload.commit;
1917
+ // tasks.md is never touched again and no second result is appended once
1918
+ // the journal holds the commit result; only the checkpoint is missing.
1919
+ if(transaction.resultRecord===null){
1920
+ recoverRunnerCommitImage(completion.owner,intent,()=>verifyReviewPackage({root:config.root,baseline:base,
1921
+ checks:reviewPackage.checks,reviewPackage,expectedDigest:reviewPackage.packageDigest,...handoffBinding()}));
1922
+ persist('task-commit-result',{effectId:effect.id,completeIntentDigest:transaction.completeIntentDigest,
1923
+ commit:{version:1,protocol:'cm-task-commit',type:'result',intentDigest:transaction.intentRecord.digest,
1924
+ planDigest:intent.plan.planDigest,outcome:'fixture_committed'}});
1925
+ }
1926
+ state='fixture_completed';code=null;reason=null;
1927
+ const response=privateStatus();cache.set(effect.id,{effect,digest:digest(effect),result:response});
1928
+ persist('effect-checkpoint',{effectId:effect.id,checkpoint:frame()});
1929
+ restored.pending=null;publication=response;return status();
1930
+ }catch(error){
1931
+ if(poisoned)return freeze({outcome:'rejected',code:'store_failure'});
1932
+ return freeze({outcome:'rejected',code:error.code??'commit_recovery_unavailable',reason:error.code==='commit_recovery_conflict'
1933
+ ?'tasks.md 或提交计划引用的证据文件既不是提交前也不是提交后的样子(或已被改动);宿主不改写。请核对 tasks.md 与 .reviews 下的 handoff/审查文件,还原后重试 complete。'
1934
+ :error.code==='commit_recovery_code_changed'?'代码已不等于审查通过的交付,宿主不勾选任务;还原到审查通过的交付后重试 complete。'
1935
+ :'完成提交无法按运行存档的提交计划收尾;保留现场核对 tasks.md 与提交记录。'});
1936
+ }
1937
+ };
1938
+ // The operator's confirmation that the stuck current-session develop stopped
1939
+ // writing (R3). Journals develop-answer-redo; the next advance redoes the round.
1940
+ const redoDevelop=raw=>{
1941
+ try{
1942
+ need(invocationMode&&store&&!busy&&!poisoned&&options.persistence.mode==='resume','develop_redo_unavailable');
1943
+ const value=json(raw);shape(value,['allowed','reason']);
1944
+ need(value.allowed===true,'develop_redo_authorization_required');
1945
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1946
+ &&!/[\r\n\0]/.test(value.reason),'develop_redo_reason_required');
1947
+ // Q16: the confirmation for a documentation_sync that never answered after
1948
+ // it changed the documentation paths; only documentation_sync is redone.
1949
+ // A re-confirmation (blocked) keeps the confirmed source and spends no retry.
1950
+ const documentation=state==='unknown'?documentationSyncRetry():null,confirmed=state==='blocked'?documentationRedoSource():null;
1951
+ if(documentation!==null||confirmed!==null){
1952
+ const source=documentation?.source??confirmed.source,start=calls.at(-1).documentationSync;
1953
+ const live=documentationLive(source.documents.map(item=>item.path));
1954
+ persist('documentation-sync-retry',{effectId:documentation?[...cache.values()].at(-1).effect.id:confirmed.stop.effectId,
1955
+ invocationId:calls.at(-1).invocationId,startDigest:start,code:documentation?.code??confirmed.code,documents:live.documents,
1956
+ reason:value.reason,at:new Date().toISOString()});
1957
+ const recovered=readRunnerHistory(journal,metadata,3).state;
1958
+ halt('blocked',recovered.code,recovered.reason);publication=privateStatus();return status();
1959
+ }
1960
+ const cause=developRedoRequired();need(cause!==null,'develop_redo_unavailable');
1961
+ const effectId=[...cache.values()].at(-1).effect.id;let worker=null,basis=null;
1962
+ if(cause.startsWith('provider_')){
1963
+ const proof=workerProof(parsedHistory?.workers?.[effectId],{checkpointed:true});
1964
+ if(proof.code){const refusal=workerRefusal('develop_redo',proof);throw Object.assign(new Error(refusal.code),refusal);}
1965
+ if(proof.proof==='gone')worker=proof.binding;
1966
+ if(developer.provider==='claude')basis=verifyRoundStart(redoDevelopStart({state,code,attempt,cache:[...cache.values()],
1967
+ reviewPackage,priorReview}),'develop_redo','Claude provider 开发');
1968
+ }
1969
+ persist('develop-answer-redo',{effectId,invocationId:calls.at(-1).invocationId,
1970
+ cause,reason:value.reason,at:new Date().toISOString(),...(worker?{worker}:{}),...(basis?{basis}:{})});
1971
+ halt('blocked',DEVELOP_REDO_CODE,developRedoReason(cause));publication=privateStatus();return status();
1972
+ }catch(error){return freeze({outcome:'rejected',code:poisoned?'store_failure':error.code??'develop_redo_unavailable',
1973
+ ...(!poisoned&&error.reason?{reason:error.reason}:{})});}
1405
1974
  };
1406
1975
  const recoverBootstrapReview=raw=>{
1407
1976
  try{
@@ -1436,7 +2005,9 @@ export function createTaskRunner(options) {
1436
2005
  }catch(error){return freeze({outcome:'rejected',code:error.code??'bootstrap_review_recovery_mismatch',
1437
2006
  reason:'原运行的文件、handoff 或证据无法精确核对;请保留现场并检查差异,不要重新派发开发。'});}
1438
2007
  };
1439
- const api={reviseQa,supersedeEvidence,rebindSpecification,abandonReview,reconcileReview,abandonEffect,recoverBootstrapReview,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks};
2008
+ // Interrupted intents keep their ids; the entry derives fresh ones from this count.
2009
+ const interruptions=kind=>parsedHistory?.interrupted?.filter(item=>item.kind===kind).length??0;
2010
+ const api={reviseQa,supersedeEvidence,rebindSpecification,abandonReview,reconcileReview,abandonEffect,recoverBootstrapReview,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks,reviewEffectIds,recheckLearningInput,redoDevelop,recoverCommit,interruptions};
1440
2011
  if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
1441
2012
  if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
1442
2013
  // A terminal reviewer observation is durable even if the host died before