@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
@@ -9,17 +9,22 @@ import {reviewResult,reviewReceipt} from './review-runner.mjs';
9
9
  import {checkCompletion} from './gate-bridge.mjs';
10
10
  import path from 'node:path';
11
11
  import {readCommitIntent,readCommitResult} from './task-commit-codec.mjs';
12
- import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure,inspectProviderReviewReconciliation,REVIEWER_PROVIDER_FAILURES} from './provider-review-observation.mjs';
12
+ import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure,inspectProviderReviewReconciliation,REVIEWER_PROVIDER_FAILURES,abandonableReviewerExit,reviewerGoneWithoutResult} from './provider-review-observation.mjs';
13
13
  import {readReconciliationReceipt} from './review-reconciliation.mjs';
14
14
  import {readCmAiProjectLearningWriteback} from './cm-ai-learning-writer.mjs';
15
15
  import {readCmAiTaskLearningApplication} from './cm-ai-context-refresh.mjs';
16
16
  import {reviewExclusions} from './effect-contract.mjs';
17
17
  import {validateAcceptedFix} from './accepted-fix.mjs';
18
18
  import {readBootstrapEvidence,validateBootstrapReviewPackage} from './host-bootstrap.mjs';
19
- import {validateCodeProjectPaths,assertCodeProjectSelections} from './code-projects.mjs';
19
+ import {validateCodeProjectPaths,assertCodeProjectSelections,MAX_CODE_PROJECTS} from './code-projects.mjs';
20
20
  import {identifyApprovedBootstrapFeature} from './bootstrap-feature.mjs';
21
21
  import {readSpecificationRebind} from './specification-material.mjs';
22
22
  import {protectedScopePaths} from './developer-adapter.mjs';
23
+ import {validWorkerPid,validStartTime} from './worker-process-identity.mjs';
24
+ import {MAX_REVIEW_NOT_DISPATCHED_RETRIES,MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS,REVIEW_NOT_DISPATCHED_LIMIT_CODE,MAX_REVIEW_DENIAL_CONFIRMATIONS,
25
+ REVIEW_DENIAL_LIMIT_CODE,REVIEW_NEVER_STARTED_MANUAL_STEP} from './review-dispatch-limits.mjs';
26
+ export {MAX_REVIEW_NOT_DISPATCHED_RETRIES,MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS,REVIEW_NOT_DISPATCHED_LIMIT_CODE,MAX_REVIEW_DENIAL_CONFIRMATIONS,
27
+ REVIEW_DENIAL_LIMIT_CODE,REVIEW_NEVER_STARTED_MANUAL_STEP};
23
28
 
24
29
  const LIMIT=16*1024*1024;
25
30
  // The developer adapter refuses a protected scope on every dispatch, before any
@@ -35,9 +40,10 @@ const prefix=(a,b)=>{need(b.length>=a.length,'runner_history_mismatch');same(a,b
35
40
  const uuid=s=>need(typeof s==='string' && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(s),'runner_session');
36
41
  const states=['ready','awaiting_review','approved','changes_requested','fixture_completed','blocked','unknown','cancelled','pending_review'];
37
42
  export const stageAllowed=(kind,state,code=null,reviewVerdict=null)=>
38
- kind==='develop'&&state==='blocked'&&['developer_result_invalid','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(code)
39
- ||kind==='review'&&state==='pending_review'&&REVIEW_RETRY_CODES.includes(code)
40
- ||kind==='complete'&&state==='blocked'&&(['completion_checks_changed','completion_package_changed'].includes(code)
43
+ kind==='develop'&&state==='blocked'&&['developer_result_invalid','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','develop_answer_invalid',...RECHECK_CODES,DEVELOP_REDO_CODE,DISPATCH_RETRY_CODE,DEVELOP_INTERRUPTED_CODE,...DOCUMENTATION_SYNC_CODES].includes(code)
44
+ ||kind==='review'&&state==='pending_review'&&(REVIEW_RETRY_CODES.includes(code)||REVIEW_NOT_DISPATCHED_CODES.includes(code)
45
+ ||code===REVIEW_DENIAL_CONFIRMED_CODE)
46
+ ||kind==='complete'&&state==='blocked'&&(['completion_checks_changed','completion_package_changed',COMPLETE_RECHECK_CODE].includes(code)
41
47
  ||code==='review_package_changed'&&reviewVerdict==='approved')
42
48
  ||kind==='develop'&&state==='blocked'&&code==='review_package_changed'&&reviewVerdict==='changes_requested'
43
49
  ||({develop:['ready','changes_requested'],review:['awaiting_review'],complete:['approved']})[kind]?.includes(state)===true;
@@ -55,10 +61,111 @@ export const reviewerFailure=result=>result?.outcome==='failed'&&result.reconcil
55
61
  export const reviewRetryCode=result=>reviewTransportTimeout(result)?'review_transport_timeout'
56
62
  :reviewerFailure(result)?(result.inspection.category==='verdict'?'review_verdict_invalid':'review_provider_failed'):null;
57
63
  export const REVIEW_RETRY_CODES=Object.freeze(['review_transport_timeout','review_abandoned','review_provider_failed','review_verdict_invalid']);
64
+ // A review registered but never handed to the reviewer: the dispatch grant had
65
+ // expired, or the dispatch clock ran backwards (task-runner, outcome not_dispatched,
66
+ // call started:false). No reviewer process ran and no verdict exists, so nothing has
67
+ // to be proven stopped: the round may dispatch again under a fresh grant (new effect
68
+ // id, same review round). Such an effect holds no call or effect slot. Only the
69
+ // runner's not_dispatched halt yields pending_review with these codes.
70
+ export const REVIEW_NOT_DISPATCHED_CODES=Object.freeze(['grant_expired','clock_invalid']);
71
+ const notDispatchedEffect=entry=>entry.effect.kind==='review'&&entry.result.state==='pending_review'
72
+ &&REVIEW_NOT_DISPATCHED_CODES.includes(entry.result.code)&&entry.result.reviewInvocation?.result?.outcome==='not_dispatched';
73
+ // Bounded on its own (it holds no call or effect slot): at most two such redispatches
74
+ // per review round, like the no-result ones. The count is the round's not-dispatched
75
+ // effects in the checkpointed cache, so live and replay read the same number; once the
76
+ // round's latest end is the third, no review effect is admitted (live and replay) and
77
+ // status shows the explicit limit block. The limit has one audited exit: the operator's
78
+ // confirmation (abandon_review + reason, journaled as review-dispatch-confirmed) grants
79
+ // MAX_REVIEW_NOT_DISPATCHED_RETRIES more, at most MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS
80
+ // per round, so the retry cap (R2) is never defeated, only extended on the record.
81
+ export const reviewNotDispatchedCount=(cache,attempt)=>cache.filter(entry=>entry.effect.identity.attempt===attempt&&notDispatchedEffect(entry)).length;
82
+ export const reviewNotDispatchedExhausted=(s,extended=0)=>s.state==='pending_review'&&REVIEW_NOT_DISPATCHED_CODES.includes(s.code)
83
+ &&reviewNotDispatchedCount(s.cache,s.attempt)>MAX_REVIEW_NOT_DISPATCHED_RETRIES*(1+extended);
84
+ export const reviewNotDispatchedExtendable=(s,confirmed)=>reviewNotDispatchedExhausted(s,confirmed.extended)
85
+ &&confirmed.extended<MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS
86
+ &&s.cache.at(-1)!==undefined&&notDispatchedEffect(s.cache.at(-1))&&s.cache.at(-1).effect.identity.attempt===s.attempt;
87
+ export const reviewNotDispatchedLimitReason=(code,extended=0)=>`${REVIEW_NOT_DISPATCHED_LIMIT_CODE}: 本轮独立审查已登记 ${MAX_REVIEW_NOT_DISPATCHED_RETRIES*(1+extended)+1} 次,每次都在派发前作废(最近一次 pending_review/${code}:授权过期或派发时钟倒退),审查进程从未启动、没有写入。`
88
+ +(extended<MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS
89
+ ?'本运行不再自动重派。先查清宿主从授权到派发为何超过授权有效期(60 秒内)或本机时钟为何倒退,并修好;'
90
+ +`然后用 --mode resume 加 --allow-abandon-review 启动并发送 abandon_review(单行 reason 写明修好了什么)登记确认,本轮再多重派 ${MAX_REVIEW_NOT_DISPATCHED_RETRIES} 次(每轮只能确认 ${MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS} 次,用满后不再有这个出口)。`
91
+ :`已确认延长 ${extended} 次(用满),不再提供继续重派的操作。先查清宿主从授权到派发为何超过授权有效期(60 秒内)或本机时钟为何倒退。${REVIEW_NEVER_STARTED_MANUAL_STEP}`);
92
+ // A review whose authorization was refused before any registration (the runner's
93
+ // permission_denied halt): no call, no grant, no reviewer, so nothing can be writing.
94
+ // It is a decision, not a timing failure: only an explicit operator confirmation
95
+ // (abandon_review, journaled as review-dispatch-confirmed with its reason) lets the same
96
+ // round ask for a fresh authorization, once per denial, at most
97
+ // MAX_REVIEW_DENIAL_CONFIRMATIONS per round; a host or a standing approval never does.
98
+ export const REVIEW_DENIED_CODE='permission_denied';
99
+ export const REVIEW_DENIAL_CONFIRMED_CODE='permission_denied_confirmed';
100
+ export const REVIEW_DISPATCH_CONFIRM_REQUIRED_CODE='review_dispatch_confirmation_required';
101
+ const deniedEffect=entry=>entry.effect.kind==='review'&&entry.result.state==='pending_review'&&entry.result.code===REVIEW_DENIED_CODE;
102
+ export const reviewDenialUnconfirmed=s=>s.state==='pending_review'&&s.code===REVIEW_DENIED_CODE;
103
+ export const reviewDenialExhausted=(s,confirmed)=>reviewDenialUnconfirmed(s)&&confirmed.denied>=MAX_REVIEW_DENIAL_CONFIRMATIONS;
104
+ export const reviewDenialConfirmable=(s,confirmed)=>reviewDenialUnconfirmed(s)&&confirmed.denied<MAX_REVIEW_DENIAL_CONFIRMATIONS
105
+ &&deniedEffect(s.cache.at(-1)??{effect:{},result:{}})&&s.cache.at(-1).effect.identity.attempt===s.attempt;
106
+ // Confirmations of a review round, read the same way live (journal payloads) and in
107
+ // replay (the running tally in answerGaps.reviewDispatchConfirmed).
108
+ export const noReviewDispatchConfirmations=()=>({denied:0,extended:0});
109
+ export const countReviewDispatchConfirmations=(payloads,attempt)=>{
110
+ const count=noReviewDispatchConfirmations();
111
+ for(const p of payloads)if(p.type==='review-dispatch-confirmed'&&p.attempt===attempt)
112
+ count[p.code===REVIEW_DENIED_CODE?'denied':'extended']++;
113
+ return count;
114
+ };
115
+ export const reviewDenialConfirmReason=confirmed=>`${REVIEW_DENIED_CODE}: 本轮独立审查的授权没有取得(被拒绝,或授权已超过有效期),审查没有登记、没有派发、审查进程从未启动,不会有任何写入。`
116
+ +'宿主不会自动重试,也不会因为留着的审查授权而重派:先查清是谁拒绝、为什么,确认现在可以授权后,用 --mode resume 加 --allow-abandon-review 启动并发送 abandon_review(单行 reason 写明依据)登记确认,'
117
+ +`再按原方式重新取得本轮审查授权后 advance。每轮最多这样确认 ${MAX_REVIEW_DENIAL_CONFIRMATIONS} 次(本轮已确认 ${confirmed.denied} 次),之后为 ${REVIEW_DENIAL_LIMIT_CODE}。`;
118
+ export const reviewDenialLimitReason=()=>`${REVIEW_DENIAL_LIMIT_CODE}: 本轮独立审查的授权已被拒绝 ${MAX_REVIEW_DENIAL_CONFIRMATIONS+1} 次,已确认重新授权 ${MAX_REVIEW_DENIAL_CONFIRMATIONS} 次(用满),审查进程从未启动,也没有写入。`
119
+ +`本运行不再提供重新授权的操作。先查清授权为何一直被拒绝(宿主是否配了审查权限、授权是否在 60 秒内用完)。${REVIEW_NEVER_STARTED_MANUAL_STEP}`;
120
+ // Status-only overlay for a review round that ended without ever starting a reviewer,
121
+ // read by the live runner and by replay (projectedRunnerStatus) alike; never journaled.
122
+ export function reviewNeverStartedStatus(s,confirmed){
123
+ if(reviewDenialExhausted(s,confirmed))return {state:'blocked',code:REVIEW_DENIAL_LIMIT_CODE,reason:reviewDenialLimitReason()};
124
+ if(reviewDenialUnconfirmed(s))return {reviewDispatchConfirmRequired:true,reason:reviewDenialConfirmReason(confirmed)};
125
+ if(reviewNotDispatchedExhausted(s,confirmed.extended))
126
+ return {state:'blocked',code:REVIEW_NOT_DISPATCHED_LIMIT_CODE,reason:reviewNotDispatchedLimitReason(s.code,confirmed.extended),
127
+ ...(confirmed.extended<MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS?{reviewDispatchConfirmRequired:true}:{})};
128
+ return null;
129
+ }
58
130
  const timeoutEffect=entry=>entry.effect.kind==='review'&&reviewRetryCode(entry.result.reviewInvocation?.result)!==null
59
131
  &&entry.result.code===reviewRetryCode(entry.result.reviewInvocation.result);
60
132
  export const reviewRetrySpent=(cache,calls,attempt,contextId)=>cache.some(entry=>entry.effect.identity.attempt===attempt&&timeoutEffect(entry))
61
133
  ||calls.some(call=>call.terminal==='abandoned'&&call.contextId===contextId);
134
+ // V5 (A34/A36): no-result redispatches of one review round (attempt), counted
135
+ // apart from the two review rounds: the automatic one (a retryable end that went
136
+ // back to pending_review), operator abandonments (abandoned calls), and the
137
+ // review-redispatch records an operator writes (abandon_review) from a spent
138
+ // retryable block. The automatic transition still grants only the first
139
+ // (reviewTimeoutTransition, unchanged so older journals replay as written); the
140
+ // second needs that record, which carries the operator's confirmation that the
141
+ // original call's reviewer process stopped: a timeout only aborted it and the
142
+ // host never waited for its exit, so nothing else proves it gone.
143
+ // Never a third verdict: a redispatch exists only because the round accepted none.
144
+ export const MAX_REVIEW_REDISPATCHES=2;
145
+ export const reviewRedispatchCount=(cache,calls,attempt,contextId,records=0)=>
146
+ cache.filter(entry=>entry.effect.identity.attempt===attempt&&timeoutEffect(entry)&&entry.result.state==='pending_review').length
147
+ +calls.filter(call=>call.terminal==='abandoned'&&call.contextId===contextId).length+records;
148
+ // The spent retryable block of this round (reviewTimeoutTransition gave blocked).
149
+ const spentRetryBlock=s=>{
150
+ const entry=s.cache.at(-1);
151
+ // An end whose worker could not confirm its process-group cleanup never qualifies.
152
+ return s.state==='blocked'&&REVIEW_RETRY_CODES.includes(s.code)&&entry?.effect.kind==='review'
153
+ &&s.reviewInvocation?.result?.observation?.result?.code!=='process_cleanup_unknown'
154
+ &&entry.effect.identity.attempt===s.attempt&&timeoutEffect(entry)&&entry.result.state==='blocked'&&entry.result.code===s.code
155
+ &&s.reviewInvocation?.registration?.grant?.invocationId!=null
156
+ &&entry.result.reviewInvocation?.registration?.grant?.invocationId===s.reviewInvocation.registration.grant.invocationId;
157
+ };
158
+ export const reviewRedispatchable=(s,contextId,records=0)=>spentRetryBlock(s)
159
+ &&reviewRedispatchCount(s.cache,s.calls,s.attempt,contextId,records)<MAX_REVIEW_REDISPATCHES;
160
+ export const reviewRedispatchExhausted=(s,contextId,records=0)=>spentRetryBlock(s)
161
+ &&reviewRedispatchCount(s.cache,s.calls,s.attempt,contextId,records)>=MAX_REVIEW_REDISPATCHES;
162
+ export const REVIEW_REDISPATCH_LIMIT_CODE='review_redispatch_limit';
163
+ export const reviewRedispatchLimitReason=code=>`${REVIEW_REDISPATCH_LIMIT_CODE}: 本轮独立审查已无结论重派 ${MAX_REVIEW_REDISPATCHES} 次(原记录 blocked/${code}),`
164
+ +'不再自动重派,也不计为审查轮次。先查清审查进程为何一直没有结论(登录、额度、网络或审查答复格式),'
165
+ +'修好后用 --supersede-reviewed-evidence 新建运行重做;本运行记录保留不改写。';
166
+ export const reviewRedispatchStopReason=code=>`review_redispatch_stop_required: 本轮独立审查第二次没有结论(blocked/${code}),本轮还剩 1 次无结论重派。`
167
+ +'宿主只中止了原调用、没有等到审查进程退出,不能证明它已停止:先确认原审查进程(含子进程)已退出,'
168
+ +'再用 --allow-abandon-review 发送 abandon_review(单行 reason)登记确认,之后 advance 重新取得授权并重派;不算审查轮次。';
62
169
  export const reviewTimeoutTransition=(result,cache,attempt,calls=[],contextId=null)=>{
63
170
  const code=reviewRetryCode(result);
64
171
  return code===null?null:{state:reviewRetrySpent(cache,calls,attempt,contextId)?'blocked':'pending_review',code};
@@ -66,8 +173,367 @@ export const reviewTimeoutTransition=(result,cache,attempt,calls=[],contextId=nu
66
173
  // Six counted provider calls per run. Locally rejected developer values,
67
174
  // automatic review retries and abandoned invocations hold no slot.
68
175
  export const MAX_RUNNER_CALLS=6;
176
+ // A develop the host answer limit cut off (call_timeout, call terminal unknown).
177
+ // It produced nothing the runner accepted. Only while the code root still equals
178
+ // where it started (checked live, see developTimeoutBasis) can the run go on, so
179
+ // it holds no call or effect slot; MAX_DEVELOP_TIMEOUT_RETRIES bounds the redos.
180
+ export const developTimeoutEffect=entry=>entry.effect.kind==='develop'&&entry.result.state==='unknown'
181
+ &&entry.result.code==='call_timeout';
182
+ export const MAX_DEVELOP_TIMEOUT_RETRIES=2;
183
+ export const DEVELOP_CALL_TIMEOUT_REASON='develop_call_timeout: 开发应答超过宿主请求上限(默认 30 分钟),代码根仍与本轮开发开始时一致;'
184
+ +'在原运行 advance 重发本轮开发(新 effect id,审查轮次不变)。迟到的应答仍被拒绝。';
185
+ // The tree a timed-out develop started from, when the journal pins it: the
186
+ // reviewed attempt-1 package (attempt 2) or the original baseline (attempt 1,
187
+ // nothing delivered yet). A develop redone from a blocked delivery left
188
+ // unrecorded edits on disk, so its start cannot be proven: null, stays unknown.
189
+ // The binding outlives the develop-timeout-retry record (blocked/develop_call_timeout):
190
+ // the redo re-verifies the same start right before dispatch.
191
+ export const developTimeoutState=s=>s.state==='unknown'&&s.code==='call_timeout'
192
+ ||s.state==='blocked'&&s.code==='develop_call_timeout';
193
+ export function developTimeoutBasis(s,configuration=null) {
194
+ if(configuration?.mode==='instructions')return null;
195
+ const last=s.cache.at(-1),call=s.calls.at(-1);
196
+ if(!(developTimeoutState(s)&&last&&developTimeoutEffect(last)
197
+ &&last.effect.identity.attempt===s.attempt&&call?.terminal==='unknown'&&call.channel==='fixture'))return null;
198
+ if(s.cache.filter(developTimeoutEffect).length>MAX_DEVELOP_TIMEOUT_RETRIES)return null;
199
+ return pinnedDevelopStart(s,developTimeoutEffect);
200
+ }
201
+ // The tree the round's develop effects all started from, when the journal pins
202
+ // it: the reviewed attempt-1 package (attempt 2) or the original baseline
203
+ // (attempt 1, nothing delivered yet). Earlier develops of this attempt that
204
+ // produced nothing the runner accepted (skip) are passed over; any other entry
205
+ // means unrecorded edits may exist, so the start cannot be proven (null). The
206
+ // caller still compares the live code root with it.
207
+ function pinnedDevelopStart(s,skip,from=s.cache.length-2){
208
+ for(let i=from;i>=0;i--){
209
+ const entry=s.cache[i];
210
+ if(skip(entry)&&entry.effect.identity.attempt===s.attempt)continue;
211
+ return s.attempt===2&&entry.effect.kind==='review'&&entry.result.state==='changes_requested'
212
+ &&s.reviewPackage?.identity.attempt===1&&s.priorReview?.verdict==='changes_requested'?'reviewed_package':null;
213
+ }
214
+ return s.attempt===1&&s.reviewPackage===null?'baseline':null;
215
+ }
216
+ // A current-session answer the host rejected locally (invalid_result without the
217
+ // protected retryable flag: e.g. application.note over 512 characters). It was
218
+ // journaled as blocked/failed. Like a protected invalid value it holds no call
219
+ // or effect slot; MAX_DEVELOP_ANSWER_RETRIES bounds the redos. Edits the session
220
+ // already wrote stay on disk and are part of the redone delivery, which is
221
+ // built from the round's start and reviewed like any other.
222
+ export const developAnswerInvalidEffect=entry=>{
223
+ const call=entry.result.calls?.at(-1);
224
+ return entry.effect.kind==='develop'&&entry.result.state==='blocked'&&entry.result.code==='failed'
225
+ &&call?.terminal==='failed'&&call.requestedModel==='current-session'&&call.failureResult?.code==='invalid_result'
226
+ &&!Object.hasOwn(call.failureResult,'retryable');
227
+ };
228
+ export const MAX_DEVELOP_ANSWER_RETRIES=2;
229
+ export const DEVELOP_ANSWER_LIMITS='application.note 为单行且不超过 512 个字符(no_relevant_lesson 时为 null);'
230
+ +'retrospective 的 reason 与每个候选的 trigger、action 为单行且不超过 240 个字符;候选 1–3 个,每个 1–8 条相对路径证据(单行、不超过 512 个字符)';
231
+ const answerReasons={application_note_limit:'application.note 超过 512 个字符或含换行'};
232
+ export const developAnswerInvalidReason=failure=>`develop_answer_invalid: 开发应答未通过交付合同校验(${answerReasons[failure?.reason]??failure?.reason??'invalid_input'});`
233
+ +`上限:${DEVELOP_ANSWER_LIMITS}。会话已写的代码保留,在原运行 advance 重发本轮开发(新 effect id,审查轮次不变),按上限重新应答。`;
234
+ // The journaled blocked/failed develop is the last effect and the cap is not spent.
235
+ export function developAnswerRetryable(s,configuration=null) {
236
+ if(configuration?.mode==='instructions')return false;
237
+ const last=s.cache.at(-1);
238
+ return s.state==='blocked'&&['failed','develop_answer_invalid'].includes(s.code)&&last!==undefined
239
+ &&developAnswerInvalidEffect(last)&&last.effect.identity.attempt===s.attempt
240
+ &&s.cache.filter(developAnswerInvalidEffect).length<=MAX_DEVELOP_ANSWER_RETRIES;
241
+ }
242
+ // V3 answer gaps: the delivery already reached the disk (the developer call
243
+ // succeeded and its Learning was written back), but a later step never got a
244
+ // usable answer: the task checks or the verification precheck (timed out,
245
+ // disconnected, late, or malformed), or the completion re-check before any
246
+ // task-commit-intent. The developer is never dispatched again: advance journals
247
+ // develop-recheck (or complete-recheck) and re-runs only those later steps.
248
+ // Neither the source effect nor its re-check holds a call or effect slot;
249
+ // MAX_ANSWER_GAP_RETRIES bounds each kind per run. Old journals are projected
250
+ // the same way on replay; their records are never rewritten.
251
+ export const MAX_ANSWER_GAP_RETRIES=2;
252
+ const CHECK_ANSWER_MISSING=['call_timeout','execution_error','host_disconnected','host_request_timeout','role_log_failed'];
253
+ // limit_exceeded is left out: it is also how older runtimes recorded package and
254
+ // journal size limits, which a re-check does not resolve. An oversized check
255
+ // answer is refused by the bridge and times out (check_answer_missing).
256
+ const CHECK_ANSWER_INVALID=['invalid_input','invalid_result','verification_precheck_invalid'];
257
+ // A53: the delivery touched paths outside the task scope (not only files the
258
+ // checks created). The paths are named; once the operator moved or restored
259
+ // them, a re-check rebuilds the handoff and package without a new develop.
260
+ export const OUT_OF_SCOPE_RECHECK_CODE='develop_out_of_scope';
261
+ export const RECHECK_CODES=Object.freeze(['check_answer_missing','check_answer_invalid',OUT_OF_SCOPE_RECHECK_CODE]);
262
+ export const COMPLETE_RECHECK_CODE='complete_recheck_failed';
263
+ // learningWriteback mirrors the checkpointed Learning result, which the journal
264
+ // grammar only accepts after this effect's own developer call succeeded (or on a
265
+ // re-check that kept it unchanged).
266
+ export const developRecheckSource=entry=>{
267
+ const result=entry.result,call=result.calls?.at(-1);
268
+ return entry.effect.kind==='develop'&&result.state==='unknown'
269
+ &&[...CHECK_ANSWER_MISSING,...CHECK_ANSWER_INVALID,'out_of_scope'].includes(result.code)
270
+ &&call?.terminal==='succeeded'&&call.channel==='fixture'
271
+ &&result.learningWriteback!=null&&result.learningWriteback.outcome!=='writeback_pending';
272
+ };
273
+ export function developRecheckCode(s,config,recorded=0){
274
+ if(config.bootstrap?.mode==='instructions'||config.taskLearning?.hostHandoff!==true)return null;
275
+ const last=s.cache.at(-1);
276
+ if(!last||last.effect.identity.attempt!==s.attempt||!developRecheckSource(last)
277
+ ||s.learningResult==null||s.receipt!==null)return null;
278
+ if(s.state==='blocked'&&RECHECK_CODES.includes(s.code))return s.code;
279
+ if(!(s.state==='unknown'&&s.code===last.result.code)||recorded>=MAX_ANSWER_GAP_RETRIES)return null;
280
+ return last.result.code==='out_of_scope'?OUT_OF_SCOPE_RECHECK_CODE
281
+ :CHECK_ANSWER_INVALID.includes(last.result.code)?'check_answer_invalid':'check_answer_missing';
282
+ }
283
+ // detail: the source checkpoint's reason, which names the out-of-scope paths.
284
+ const outOfScopePaths=detail=>typeof detail==='string'&&/^out_of_scope:/.test(detail)
285
+ ?detail.replace(/^out_of_scope:\s*/,'').split(/,\s*/).filter(Boolean).slice(0,20):[];
286
+ export const developRecheckReason=(code,source,detail=null)=>code===OUT_OF_SCOPE_RECHECK_CODE
287
+ ?boundedReason(`${code}: 开发已交付并写回 Learning,但改动超出任务 scope(原记录 unknown/${source}):`,(paths=>paths.length?paths:['见原记录'])(outOfScopePaths(detail)),
288
+ '。这些路径可能是会话越界写的,也可能是你自己的改动:移走或还原它们(确需改动就先走规格变更扩大 scope)后,在原运行 advance 只重跑检查、验证预检、handoff 与审查包,不重发开发、不占名额(每运行最多 2 次)。')
289
+ :`${code}: 开发已交付并写回 Learning,但之后的检查或验证预检没有拿到可用应答(原记录 unknown/${source})。`
290
+ +'先确认上一次检查命令已经停止;在原运行 advance 只重跑检查、验证预检、handoff 与审查包,不重发开发,不占开发调用与 effect 名额(每运行最多 2 次)。';
291
+ export const completeRecheckSource=entry=>entry.effect.kind==='complete'&&entry.result.state==='unknown'
292
+ &&[...CHECK_ANSWER_MISSING,'invalid_input'].includes(entry.result.code)
293
+ &&entry.result.taskCommit===null;
294
+ export function completeRecheckable(s,recorded=0){
295
+ const last=s.cache.at(-1);
296
+ if(!last||last.effect.identity.attempt!==s.attempt||!completeRecheckSource(last)||s.taskCommit!=null)return false;
297
+ if(s.state==='blocked'&&s.code===COMPLETE_RECHECK_CODE)return true;
298
+ return s.state==='unknown'&&s.code===last.result.code&&recorded<MAX_ANSWER_GAP_RETRIES;
299
+ }
300
+ export const completeRecheckReason=source=>`${COMPLETE_RECHECK_CODE}: 完成前复查没有正常结束(检查应答缺失、断开,或宿主在写入提交意图前出错;原记录 unknown/${source}),task-commit-intent 尚未写入,tasks.md 未改动。`
301
+ +'先按宿主 stderr 的 diagnostic 修好原因(如缺失的 handoff 或检查环境);'
302
+ +'在原运行发送 complete 重新复查并完成,不重新开发或审查(每运行最多 2 次)。';
303
+ // V2 + R3: a current-session develop whose answer never arrived (timed out with
304
+ // the code root changed or its start not pinned, disconnected, late) or came back
305
+ // as a bare failure. The session may still be writing and the host cannot see
306
+ // it, so nothing is redispatched until the operator confirms it stopped:
307
+ // develop_redo with a reason, journaled as develop-answer-redo. The redo sends
308
+ // the same round under a new effect id. Edits already on disk stay and are part
309
+ // of the redone delivery, whose review package is built against the task
310
+ // baseline captured when the run was created (never re-captured), so no edit
311
+ // skips the checks and the independent review. Provider development and
312
+ // instruction bootstrap are excluded (their writers or half-writes need their
313
+ // own reconciliation); the host also excludes protected current-session mode,
314
+ // where a changed root can only be a partially applied proposal.
315
+ export const DEVELOP_REDO_CODE='develop_answer_missing';
316
+ export const MAX_DEVELOP_REDOS=2;
317
+ export const developAnswerMissingEffect=entry=>{
318
+ const result=entry.result,call=result.calls?.at(-1);
319
+ if(entry.effect.kind!=='develop'||call?.requestedModel!=='current-session'||call.channel!=='fixture')return false;
320
+ return result.state==='unknown'&&result.code==='unknown'&&call.terminal==='unknown'
321
+ ||result.state==='blocked'&&result.code==='failed'&&call.terminal==='failed'
322
+ &&!Object.hasOwn(call,'failureResult')&&!Object.hasOwn(call,'blockedReason');
323
+ };
324
+ // V9: a provider develop (Codex writes in its sandbox, Claude proposes and the
325
+ // host applies) that ended without a usable result. Its worker may outlive the
326
+ // call, so a redo is offered only for an effect whose worker identity this
327
+ // runtime journaled (workerJournal intent marker): the host then proves the
328
+ // recorded process group gone before the redo record is written.
329
+ export const providerStuckCause=entry=>{
330
+ const result=entry.result,call=result.calls?.at(-1);
331
+ if(entry.effect.kind!=='develop'||!call||call.requestedModel==='current-session'||call.channel!=='fixture')return null;
332
+ if(result.state==='unknown'&&call.terminal==='unknown')return result.code==='call_timeout'?'provider_call_timeout':'provider_unknown';
333
+ // Only an explicit invalid proposal: a bare failure may be a legitimate
334
+ // blocked answer without a reason, which stays terminal (A11).
335
+ if(result.state==='blocked'&&result.code==='failed'&&call.terminal==='failed'&&!Object.hasOwn(call,'blockedReason')
336
+ &&call.failureResult?.code==='invalid_result'&&call.failureResult.retryable!==true)return 'provider_failed';
337
+ if(result.state==='blocked'&&result.code==='unavailable'&&call.terminal==='unavailable')return 'provider_unavailable';
338
+ return null;
339
+ };
340
+ // What the stuck develop was ('call_timeout', 'unknown', 'execution_error',
341
+ // 'failed' or a provider_* cause), or null when this exit does not apply.
342
+ // workers: the journaled worker records by effect id (readRunnerHistory).
343
+ export function developRedoCause(s,config,recorded=0,workers=null){
344
+ if(config.bootstrap?.mode==='instructions'||recorded>=MAX_DEVELOP_REDOS)return null;
345
+ if(config.developer.requestedModel!=='current-session'){
346
+ const last=s.cache.at(-1);
347
+ if(!last||last.effect.identity.attempt!==s.attempt||s.receipt!==null)return null;
348
+ const cause=providerStuckCause(last);
349
+ if(cause===null||s.state!==last.result.state||s.code!==last.result.code)return null;
350
+ return workers?.[last.effect.id]?.journal===true?cause:null;
351
+ }
352
+ const last=s.cache.at(-1);
353
+ if(!last||last.effect.identity.attempt!==s.attempt||s.receipt!==null)return null;
354
+ if(developTimeoutEffect(last)&&s.calls.at(-1)?.terminal==='unknown'
355
+ &&(s.state==='unknown'&&s.code==='call_timeout'||s.state==='blocked'&&s.code==='develop_call_timeout'))return 'call_timeout';
356
+ if(developAnswerMissingEffect(last)&&s.state===last.result.state&&s.code===last.result.code)return last.result.code;
357
+ // A dispatch failure whose round start cannot be proven unchanged (legacy
358
+ // execution_error, a start the journal does not pin, or a root that changed,
359
+ // also after its develop-dispatch-retry record) needs the same confirmation.
360
+ if(developDispatchFailedEffect(last)&&(s.state==='unknown'&&s.code===last.result.code
361
+ ||s.state==='blocked'&&s.code===DISPATCH_RETRY_CODE))return last.result.code;
362
+ return null;
363
+ }
364
+ // V1/V3 (P1-3): the current-session developer run failed before the session was
365
+ // asked anything: the host's own role routing (its run-log write or the workflow
366
+ // role configuration) threw, the call never returned (terminal unknown, no
367
+ // result). Those codes are raised only before the bridge request, so nothing
368
+ // was dispatched and nothing written: develop_dispatch_failed, redone like any
369
+ // retryable develop block after a develop-dispatch-retry record. Older runtimes
370
+ // collapsed the same failure into execution_error, which a failure after the
371
+ // answer can also produce; such a journal gets this exit only while the code
372
+ // root still equals the round's pinned start (checked live, like #198), and
373
+ // otherwise the operator-confirmed develop_redo.
374
+ export const DISPATCH_RETRY_CODE='develop_dispatch_failed';
375
+ export const DISPATCH_FAILURE_CODES=Object.freeze(['role_log_failed','invalid_workflow_config']);
376
+ export const developDispatchFailedEffect=entry=>{
377
+ const result=entry.result,call=result.calls?.at(-1);
378
+ return entry.effect.kind==='develop'&&result.state==='unknown'
379
+ &&[...DISPATCH_FAILURE_CODES,'execution_error'].includes(result.code)
380
+ &&call?.terminal==='unknown'&&call.resultDigest===null&&call.requestedModel==='current-session'&&call.channel==='fixture';
381
+ };
382
+ // The round start the journal pins ('baseline' or 'reviewed_package'), or null.
383
+ // Like #198 the binding outlives the develop-dispatch-retry record
384
+ // (blocked/develop_dispatch_failed): the host compares the live code root with
385
+ // this start before every redispatch, the first one and any after a restart.
386
+ export function developDispatchBasis(s,config,recorded=0){
387
+ if(config.bootstrap?.mode==='instructions'||config.developer.requestedModel!=='current-session')return null;
388
+ const last=s.cache.at(-1);
389
+ if(!last||last.effect.identity.attempt!==s.attempt||s.receipt!==null||!developDispatchFailedEffect(last))return null;
390
+ if(!(s.state==='unknown'&&s.code===last.result.code&&recorded<MAX_DEVELOP_REDOS
391
+ ||s.state==='blocked'&&s.code===DISPATCH_RETRY_CODE))return null;
392
+ return pinnedDevelopStart(s,entry=>developDispatchFailedEffect(entry)||developTimeoutEffect(entry));
393
+ }
394
+ // Q16/Q17 (V2): documentation_sync runs inside the final task's develop, after
395
+ // the session already answered the develop. This runtime journals that answer
396
+ // and the documentation start (documentation-sync-started) right before it asks
397
+ // the sync, and marks the developer call with that record's digest
398
+ // (call.documentationSync). A sync that then ends without a usable answer is
399
+ // checkpointed unknown with one of these codes; only documentation_sync is
400
+ // asked again, by a develop intent whose adapter reuses the journaled answer.
401
+ // The developer is never dispatched again, and the review package still
402
+ // compares with the task baseline captured at create. The source holds no call
403
+ // or effect slot; MAX_DOCUMENTATION_SYNC_RETRIES bounds the retries per run.
404
+ // Journals without the record keep their old projection.
405
+ //
406
+ // R3: nothing the host observes proves the documentation writer stopped. A
407
+ // lost answer may simply not have written yet, and an accepted answer only ends
408
+ // the host's wait, not the session's writes. So every retry first needs the
409
+ // operator's stop confirmation for that exact source call (develop_redo with a
410
+ // reason, journaled as documentation-sync-retry), or the effect-interrupted
411
+ // record of a host that died during the sync (the same confirmation, given
412
+ // through abandon_effect). The disk is a separate gate, checked right before
413
+ // every redispatch (also after a restart): the code root outside the
414
+ // documentation paths still equals the documentation start, and the
415
+ // documentation paths still equal what they were when the stop was confirmed.
416
+ export const DOCUMENTATION_SYNC_INTERRUPTED_CODE='documentation_sync_interrupted';
417
+ export const DOCUMENTATION_SYNC_CODES=Object.freeze(['documentation_sync_answer_missing','documentation_sync_answer_invalid',
418
+ 'documentation_sync_answer_blocked','documentation_sync_out_of_scope',DOCUMENTATION_SYNC_INTERRUPTED_CODE]);
419
+ export const MAX_DOCUMENTATION_SYNC_RETRIES=2;
420
+ // The workflow configuration accepts up to 256 documentation paths
421
+ // (host-workflow-capabilities.mjs); the record accepts every one of them.
422
+ export const MAX_DOCUMENTATION_PATHS=256;
423
+ // The documentation paths and their sha256 (null: absent) a record names: in
424
+ // the task scope, distinct, 1..MAX_DOCUMENTATION_PATHS of them.
425
+ export function validDocumentationStates(documents,scope){
426
+ need(Array.isArray(documents)&&documents.length>0&&documents.length<=MAX_DOCUMENTATION_PATHS,'runner_documentation');
427
+ const seen=new Set();
428
+ for(const item of documents){
429
+ shape(item,['path','sha256']);
430
+ need(typeof item.path==='string'&&scope.includes(item.path)&&!seen.has(item.path),'runner_documentation');
431
+ seen.add(item.path);if(item.sha256!==null)hex(item.sha256);
432
+ }
433
+ return documents;
434
+ }
435
+ export const DOCUMENTATION_SYNC_LIMIT_CODE='documentation_sync_retry_limit';
436
+ export const documentationSyncSource=entry=>{
437
+ const result=entry.result,call=result.calls?.at(-1);
438
+ return entry.effect.kind==='develop'&&result.state==='unknown'&&DOCUMENTATION_SYNC_CODES.includes(result.code)
439
+ &&call?.terminal==='unknown'&&call.resultDigest===null&&typeof call.documentationSync==='string'
440
+ &&call.channel==='fixture'&&result.learningWriteback==null;
441
+ };
442
+ // The checkpointed failure (state unknown, last effect) still waiting for its
443
+ // stop confirmation, while the run has a retry left; its code, or null.
444
+ export function documentationSyncRetryCode(s,config,recorded=0){
445
+ if(config.bootstrap)return null;
446
+ const last=s.cache.at(-1);
447
+ if(!last||last.effect.identity.attempt!==s.attempt||!documentationSyncSource(last))return null;
448
+ return s.state==='unknown'&&s.code===last.result.code&&recorded<MAX_DOCUMENTATION_SYNC_RETRIES?s.code:null;
449
+ }
450
+ const documentationSyncCauses={
451
+ documentation_sync_answer_missing:'文档同步没有拿到应答(超时、断开、迟到被拒或宿主核对时出错)',
452
+ documentation_sync_answer_invalid:'文档同步的应答格式不合格(只接受 {"status":"completed"} 或 {"status":"blocked"})',
453
+ documentation_sync_answer_blocked:'文档同步答复 blocked,文档没有同步完',
454
+ documentation_sync_out_of_scope:'文档同步改了文档路径以外的文件',
455
+ documentation_sync_interrupted:'宿主在文档同步中途退出'};
456
+ const documentationDetail=(code,detail)=>{
457
+ if(typeof detail!=='string'||!detail)return '';
458
+ if(code==='documentation_sync_out_of_scope'){
459
+ const paths=detail.replace(/^out_of_scope:\s*/,'').split(/,\s*/).filter(Boolean).slice(0,20);
460
+ return paths.length?`:${paths.join(', ')}`:'';
461
+ }
462
+ return code==='documentation_sync_answer_missing'&&/^[a-z_]{1,64}$/.test(detail)?`(${detail})`:'';
463
+ };
464
+ const DOCUMENTATION_SYNC_TAIL='只重发文档同步,复用运行存档里已记录的开发应答,不重发开发;盘上的开发与文档改动保留,审查包仍对照本运行创建时的任务基线,经检查与独立审查;不占调用与 effect 名额(每运行最多 2 次)。';
465
+ const documentationSyncFixes={
466
+ documentation_sync_answer_blocked:'按会话说明补齐或修正文档、解决阻碍;',
467
+ documentation_sync_out_of_scope:'把这些文件还原到文档同步开始时的内容(宿主按运行存档里的摘要核对,没还原就拒绝;确需修改先走规格变更);'};
468
+ const documentationSyncGate='重发前宿主再核对:文档路径以外的文件与文档同步开始时一致,文档路径与确认停写时一致,任一不符就拒绝、不写记录。';
469
+ // Before the confirmation: shown as blocked with pendingAction develop_redo.
470
+ export const documentationSyncStopReason=(code,detail=null)=>`${code}: 开发已应答并写入运行存档,但${documentationSyncCauses[code]}${documentationDetail(code,detail)}。`
471
+ +'宿主无法证明会话已停止修改文档(没应答可能只是还没写,已应答也只结束了宿主的等待);'
472
+ +`先确认会话已停止修改文档,${documentationSyncFixes[code]??''}再以 --mode resume --allow-develop-redo 启动并发送 develop_redo(单行 reason,写入运行存档);之后 advance `
473
+ +DOCUMENTATION_SYNC_TAIL+documentationSyncGate;
474
+ // After the confirmation (documentation-sync-retry or effect-interrupted).
475
+ export const documentationSyncRetryReason=(code,detail=null)=>`${code}: ${documentationSyncCauses[code]}${documentationDetail(code,detail)};`
476
+ +(code===DOCUMENTATION_SYNC_INTERRUPTED_CODE?'操作员已确认旧宿主与会话停止写入(effect-interrupted)。':'操作员已确认会话停止修改文档(documentation-sync-retry)。')
477
+ +'在原运行 advance '+DOCUMENTATION_SYNC_TAIL+documentationSyncGate+'确认之后若你又改了文档,再发送一次 develop_redo 重新确认(不另占次数)。';
478
+ export const documentationSyncLimitReason=source=>`${DOCUMENTATION_SYNC_LIMIT_CODE}: 文档同步重发(原记录 ${source})已在本运行用满 ${MAX_DOCUMENTATION_SYNC_RETRIES} 次,不再重发。`
479
+ +'先查清会话为何一直不应答、答复 blocked 或越界写文件;修好后用 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做,'
480
+ +'本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift 作为已有代码记录。';
481
+ export const developDispatchReason=source=>`${DISPATCH_RETRY_CODE}: 开发请求在派发给会话之前失败(原记录 unknown/${source})`
482
+ +(DISPATCH_FAILURE_CODES.includes(source)?',宿主自己的角色路由出错,未派发':'')+',代码根仍与本轮开发起点一致(每次重发前再核对)'
483
+ +'。修好 reason 指出的宿主环境(运行日志写入、工作流角色配置)后在原运行 advance 用新 effect id 重发本轮开发;不占调用与 effect 名额(每运行最多 2 次)。';
484
+ const redoCauses={call_timeout:'开发应答超时且代码根已变化或本轮起点无法核对',
485
+ role_log_failed:'开发请求派发前宿主运行日志写入失败,但代码根已变化或本轮起点无法核对',
486
+ invalid_workflow_config:'开发请求派发前工作流角色配置无效,但代码根已变化或本轮起点无法核对',unknown:'开发应答中断(会话断开、应答形状错或结果不明)',
487
+ execution_error:'开发调用以 execution_error 结束、结果不明',failed:'开发应答只回了 failed、没有可用结果',
488
+ provider_call_timeout:'provider 开发进程超时、结果不明',provider_unknown:'provider 开发进程中断或输出无法解析、结果不明',
489
+ provider_failed:'provider 开发提案未通过本地校验',provider_unavailable:'provider 开发进程启动失败或报告失败'};
490
+ const providerCause=cause=>String(cause).startsWith('provider_');
491
+ export const developRedoRequiredReason=cause=>providerCause(cause)
492
+ ?`${DEVELOP_REDO_CODE}: ${redoCauses[cause]??cause}。provider 进程组可能仍在写文件;以 --mode resume --allow-develop-redo 启动并发送 develop_redo(单行 reason),`
493
+ +'宿主先按运行存档里记下的进程身份(pid、启动时间)核对进程组已退出,核对不了(Windows、无权限、读不到启动时间)就拒绝。'
494
+ +'之后 advance 用新 effect id 重发本轮开发:盘上改动保留,审查包仍对照本运行创建时的任务基线,经检查与独立审查;不占调用与 effect 名额(每运行最多 2 次)。'
495
+ :`${DEVELOP_REDO_CODE}: ${redoCauses[cause]??cause}。会话可能仍在写文件,宿主看不到;`
496
+ +'先确认会话已停止修改代码,再以 --mode resume --allow-develop-redo 启动并发送 develop_redo(单行 reason,写入运行存档)。'
497
+ +'之后 advance 用新 effect id 重发本轮开发:盘上改动保留,审查包仍对照本运行创建时的任务基线,经检查与独立审查;不占调用与 effect 名额(每运行最多 2 次)。';
498
+ export const developRedoReason=cause=>`${DEVELOP_REDO_CODE}: ${redoCauses[cause]??cause};`
499
+ +(providerCause(cause)?'宿主已核对 provider 进程组退出(develop-answer-redo)。':'操作员已确认会话停写(develop-answer-redo)。')
500
+ +'在原运行 advance 用新 effect id 重发本轮开发;盘上改动保留并经检查与独立审查,审查轮次不变。';
501
+ // V8: the host died with an effect intent and no checkpoint. abandon_effect
502
+ // journals effect-interrupted instead of voiding the run: the pending effect is
503
+ // retired (it never got a slot) and the run continues from the step's own
504
+ // retryable block. A develop becomes blocked/develop_interrupted and is redone
505
+ // under a new effect id; edits already on disk stay and are reviewed against
506
+ // the task baseline captured at create (never re-captured). A review that was
507
+ // never registered returns to awaiting_review. A completion without a
508
+ // task-commit-intent returns to the state it started from. Old journals keep
509
+ // their records; their effect-abandoned records still end the run.
510
+ export const DEVELOP_INTERRUPTED_CODE='develop_interrupted';
511
+ export const developInterruptedReason=provider=>`${DEVELOP_INTERRUPTED_CODE}: 宿主在本轮开发中途退出,开发意图已登记但结果没写入;`
512
+ +(provider?'宿主已核对 provider 进程组退出(或进程从未启动)。':'操作员已确认会话停写。')
513
+ +'在原运行 advance 用新 effect id 重发本轮开发:盘上改动保留,审查包仍对照本运行创建时的任务基线,经检查与独立审查;不占调用与 effect 名额。';
514
+ // A45: the host died after task-commit-intent and before its result. Shown
515
+ // instead of unknown/reconciliation_required; complete then follows only the
516
+ // journaled commit plan (tasks.md before or after, never a redone completion).
517
+ export const COMMIT_INTERRUPTED_CODE='complete_commit_interrupted';
518
+ export const COMMIT_INTERRUPTED_REASON=`${COMMIT_INTERRUPTED_CODE}: 宿主在写入任务完成的提交意图之后、提交结果之前退出,tasks.md 可能已勾选也可能未勾选。`
519
+ +'发送 complete:宿主只按运行存档里的提交计划核对 tasks.md——已是提交后的内容就补记结果;仍是提交前的内容且证据文件未变、代码仍等于审查通过的交付,就按原计划写完;其余情况拒绝并保留现场。不重新复查、不重新开发。';
520
+ export const REVIEW_INTERRUPTED_REASON='review_interrupted: 宿主在审查登记前退出,审查没有派发;在原运行 advance 重新取得本轮审查授权并派发,不占重派次数。';
521
+ // A pending develop's round start as the journal pins it (see pinnedDevelopStart):
522
+ // nothing of this attempt may have been accepted or left unrecorded edits.
523
+ export const pendingDevelopStart=s=>pinnedDevelopStart(s,entry=>developDispatchFailedEffect(entry)||developTimeoutEffect(entry),s.cache.length-1);
524
+ // The same start for a checkpointed provider develop being redone (it is the
525
+ // last cache entry; earlier redo sources of this attempt produced nothing accepted).
526
+ export const redoDevelopStart=s=>pinnedDevelopStart(s,entry=>developDispatchFailedEffect(entry)||developTimeoutEffect(entry)||developRedoSource(entry));
527
+ // What may sit between a pending intent and an effect-interrupted record.
528
+ // documentation-sync-started (Q16) keeps a host death during the sync interruptible as before.
529
+ const INTERRUPTIBLE_TRAILERS={develop:['control','develop-worker','documentation-sync-started'],review:['control','host-joined'],complete:['control']};
530
+ // A provider develop that ended without a usable result is, like a current-session
531
+ // one, a redo source (developRedoCause): it holds no call or effect slot either.
532
+ export const developRedoSource=entry=>developAnswerMissingEffect(entry)||providerStuckCause(entry)!==null;
69
533
  export const countedCalls=(calls,cache)=>calls.filter(call=>!invalidDeveloperCall(call)&&call.terminal!=='abandoned').length
70
- -cache.filter(timeoutEffect).length;
534
+ -cache.filter(timeoutEffect).length-cache.filter(developTimeoutEffect).length-cache.filter(developAnswerInvalidEffect).length
535
+ -cache.filter(developRedoSource).length-cache.filter(developDispatchFailedEffect).length-cache.filter(notDispatchedEffect).length
536
+ -cache.filter(documentationSyncSource).length;
71
537
  // A review effect whose journaled result the operator abandoned (below) no
72
538
  // longer holds one of the six effect slots; its retry does.
73
539
  const abandonedResult=(entry,calls)=>entry.effect.kind==='review'&&entry.result.state==='unknown'
@@ -83,7 +549,9 @@ const completionBlock=entry=>entry.effect.kind==='complete'&&entry.result.state=
83
549
  export const completionBlockCount=cache=>cache.filter(completionBlock).length;
84
550
  export const completedEffectCount=(cache,calls=[])=>cache.filter(entry=>!(entry.effect.kind==='develop'
85
551
  &&entry.result.state==='blocked'&&['developer_result_invalid','check_output_out_of_scope'].includes(entry.result.code))
86
- &&!timeoutEffect(entry)&&!abandonedResult(entry,calls)&&entry.effect.kind!=='complete').length;
552
+ &&!timeoutEffect(entry)&&!developTimeoutEffect(entry)&&!developAnswerInvalidEffect(entry)&&!developRecheckSource(entry)
553
+ &&!developRedoSource(entry)&&!developDispatchFailedEffect(entry)&&!notDispatchedEffect(entry)&&!deniedEffect(entry)&&!documentationSyncSource(entry)
554
+ &&!abandonedResult(entry,calls)&&entry.effect.kind!=='complete').length;
87
555
  // The six-effect cap counts develop and review effects only; completion (above),
88
556
  // QA, documentation and finalization hold no slot.
89
557
  export const MAX_RUNNER_EFFECTS=6;
@@ -99,8 +567,9 @@ export const effectSlotFree=(kind,cache,calls)=>kind==='complete'||completedEffe
99
567
  export const developBudget=s=>({calls:countedCalls(s.calls,s.cache),effects:completedEffectCount(s.cache,s.calls)});
100
568
  export const developBudgetExhausted=s=>{
101
569
  if(!stageAllowed('develop',s.state,s.code,s.priorReview?.verdict))return false;
102
- const used=developBudget(s);
103
- return used.calls+2>MAX_RUNNER_CALLS||used.effects+2>MAX_RUNNER_EFFECTS;
570
+ // A re-check makes no developer call: only its review needs one.
571
+ const used=developBudget(s),calls=RECHECK_CODES.includes(s.code)?1:2;
572
+ return used.calls+calls>MAX_RUNNER_CALLS||used.effects+2>MAX_RUNNER_EFFECTS;
104
573
  };
105
574
  // At most this many re-checks after a blocked completion. Each re-runs only the
106
575
  // local checks and the commit gate, so a small fixed bound keeps the journal
@@ -120,16 +589,40 @@ export const developRetryLimitReason=({countedCalls:calls,countedEffects:effects
120
589
  // failure of a class that is now retried automatically but was recorded as
121
590
  // unknown (older versions, or after a final message). Nothing ever accepted its
122
591
  // verdict, so, exactly like an interrupted registered review, the operator may
123
- // abandon it and spend the attempt's one redispatch. Tool, context and output
124
- // limit breaks, observation_invalid and legacy timed_out without inspection stay out.
125
- export function abandonableReviewResult(s,contextId){
592
+ // abandon it and spend one of the round's MAX_REVIEW_REDISPATCHES. A Claude reviewer stopped
593
+ // at its boundary (unexpected_tool_or_content) qualifies only under
594
+ // abandonableReviewerExit: process closed, nothing received, and a rejection
595
+ // that cannot have run a tool. Other tool, context and output limit breaks,
596
+ // observation_invalid and legacy timed_out without inspection stay out.
597
+ // A journaled review end with no accepted verdict that the operator may abandon:
598
+ // a timeout, a fixed provider failure, a Claude boundary exit that cannot have
599
+ // run a tool (abandonableReviewerExit), or (V5, A33) an end whose reviewer
600
+ // process the worker proved gone without a final message (reviewerGoneWithoutResult).
601
+ export const abandonableReviewOutcome=result=>result?.inspection!=null&&result.reconciliationRequired===true
602
+ &&(result.outcome==='timed_out'||result.outcome==='unknown'
603
+ &&(Object.hasOwn(REVIEWER_PROVIDER_FAILURES,result.observation?.result?.code)
604
+ ||result.inspection.provider==='claude'&&abandonableReviewerExit(result.observation)
605
+ ||reviewerGoneWithoutResult(result.observation)));
606
+ export function abandonableReviewResult(s,contextId,records=0){
126
607
  const entry=s.cache.at(-1),result=s.reviewInvocation?.result;
127
608
  return s.state==='unknown'&&entry?.effect.kind==='review'&&entry.effect.identity.attempt===s.attempt
128
- &&entry.result.state==='unknown'&&result?.inspection!=null&&result.reconciliationRequired===true
129
- &&(result.outcome==='timed_out'||result.outcome==='unknown'
130
- &&Object.hasOwn(REVIEWER_PROVIDER_FAILURES,result.observation?.result?.code))
609
+ &&entry.result.state==='unknown'&&abandonableReviewOutcome(result)
131
610
  &&entry.result.reviewInvocation?.registration?.grant?.invocationId===s.reviewInvocation.registration?.grant?.invocationId
132
- &&!reviewRetrySpent(s.cache,s.calls,s.attempt,contextId);
611
+ &&reviewRedispatchCount(s.cache,s.calls,s.attempt,contextId,records)<MAX_REVIEW_REDISPATCHES;
612
+ }
613
+ // R4: why a no-verdict review end cannot be abandoned, with its real exit.
614
+ export function reviewAbandonRefusal(s,contextId,records=0){
615
+ const entry=s.cache.at(-1),result=s.reviewInvocation?.result;
616
+ if(s.state!=='unknown'||entry?.effect.kind!=='review'||entry.effect.identity.attempt!==s.attempt||!result||result.outcome==='observed')return null;
617
+ if(reviewRedispatchCount(s.cache,s.calls,s.attempt,contextId,records)>=MAX_REVIEW_REDISPATCHES)
618
+ return {code:'review_abandon_budget_exhausted',reason:`本轮独立审查已无结论重派 ${MAX_REVIEW_REDISPATCHES} 次,不能再放弃重派;查清原因后用 --supersede-reviewed-evidence 新建运行重做。`};
619
+ if(result.observation?.result?.code==='process_cleanup_unknown')
620
+ return {code:'review_process_unverified',reason:'审查 worker 报告进程组清理结果不明(process_cleanup_unknown),宿主无法证明旧审查进程已退出,不放行重派;手工确认该进程组已不存在后,用 --supersede-reviewed-evidence 新建运行重做。'};
621
+ if(result.inspection==null)
622
+ return {code:'review_observation_invalid',reason:'审查事件流本身不合法(observation_invalid),宿主无法判断审查进程是否给出过结论,不放行重派;核对原审查证据后用 --supersede-reviewed-evidence 新建运行重做。'};
623
+ if(!abandonableReviewOutcome(result))
624
+ return {code:'review_boundary_unverified',reason:'审查进程越界(工具或内容边界)后退出,或退出时可能已收到结论,宿主不能证明重派安全;核对原审查证据与磁盘后用 --supersede-reviewed-evidence 新建运行重做。'};
625
+ return null;
133
626
  }
134
627
  export function validateTaskLearningReviewPackage(rawPackage,writeback,learningInput,bootstrap=null,configuration=null) {
135
628
  validTaskLearningInput(learningInput,learningInput.identity,learningInput.feature);
@@ -224,7 +717,10 @@ function callRequest(call,adapter,contextId,role,payload,identity,session,index)
224
717
  shape(call,['invocationId','contextId','provider','requestedModel','effectiveModel','channel','started','terminal','requestDigest','resultDigest',
225
718
  ...(Object.hasOwn(call,'providerThreadId')?['providerThreadId']:[]),
226
719
  ...(Object.hasOwn(call,'failureResult')?['failureResult']:[]),
227
- ...(Object.hasOwn(call,'blockedReason')?['blockedReason']:[])]);
720
+ ...(Object.hasOwn(call,'blockedReason')?['blockedReason']:[]),
721
+ ...(Object.hasOwn(call,'documentationSync')?['documentationSync']:[])]);
722
+ // Q16: the documentation-sync-started record this developer call journaled.
723
+ if(Object.hasOwn(call,'documentationSync')){need(role==='developer','runner_call');hex(call.documentationSync);}
228
724
  if(Object.hasOwn(call,'blockedReason')){
229
725
  need(role==='developer'&&call.terminal==='failed'&&!Object.hasOwn(call,'failureResult'),'runner_call');
230
726
  validBlockedReason(call.blockedReason);
@@ -357,7 +853,7 @@ function invocationCall(call,registration,started,result,before) {
357
853
  &&call.resultDigest===digest(result.outcome==='observed'?result.inspection.review:result)
358
854
  &&before.sequence+1===Number(request.invocationId.split('.').at(-1)),'runner_call');
359
855
  }
360
- function checkpoint(before,raw,effect,config,original,session,controls,version=1,taskCommit=null,invocation=null,carried=null) {
856
+ function checkpoint(before,raw,effect,config,original,session,controls,version=1,taskCommit=null,invocation=null,carried=null,documentation=null) {
361
857
  const s=json(raw,LIMIT);
362
858
  shape(s,['state','code','attempt','session','sequence','reviewPackage','currentChecks','receipt','receipts','calls','cache',
363
859
  ...(Object.hasOwn(s,'reason')?['reason']:[]),
@@ -391,12 +887,28 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
391
887
  if(effect.kind!=='develop'&&Object.hasOwn(config,'taskLearning'))same(s.learningResult,before.learningResult);
392
888
  if(effect.kind==='develop') {
393
889
  need(added.length<=1 && s.receipts.length===before.receipts.length,'runner_develop');same(s.receipt,null);same(s.priorReview,before.priorReview);
890
+ // A re-check (develop-recheck) dispatches no developer: it keeps the Learning
891
+ // result and stands on the developer call that already succeeded.
892
+ const recheck=before.state==='blocked'&&RECHECK_CODES.includes(before.code);
893
+ if(recheck){need(added.length===0&&before.learningResult!=null&&before.calls.at(-1)?.terminal==='succeeded','runner_develop');
894
+ same(s.learningResult,before.learningResult);}
895
+ const developerCall=recheck?before.calls.at(-1):added[0];
394
896
  if(added.length)callRequest(added[0],config.developer,config.developer.contextId,'developer',{
395
897
  scope:config.scope,requirements:original.files.filter(f=>config.requirements.includes(f.path)),priorReview:before.priorReview,
396
898
  ...supersededReviewPayload(carried,before.attempt),
397
899
  ...(Object.hasOwn(original,'specification')?{specification:original.specification}:{}),
398
900
  ...(Object.hasOwn(effect,'learningInput')?{learningInput:effect.learningInput}:{})
399
901
  },identity,session,before.calls.length+1);
902
+ // Q16: a developer call carries the documentation-sync-started record it
903
+ // journaled (exactly that one), and a delivery is the answer it recorded.
904
+ need((added[0]?.documentationSync??null)===(documentation?.digest??null),'runner_documentation');
905
+ if(documentation&&added[0].terminal==='succeeded')
906
+ need(added[0].resultDigest===digest(documentation.payload.result),'runner_documentation');
907
+ if(s.state==='unknown'&&DOCUMENTATION_SYNC_CODES.includes(s.code))
908
+ need(documentation!==null&&added[0].terminal==='unknown'&&added[0].resultDigest===null,'runner_documentation');
909
+ // A documentation-only redo of the final task's develop journals a sync again.
910
+ if(before.state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(before.code)&&added[0]?.terminal==='succeeded')
911
+ need(documentation!==null,'runner_documentation');
400
912
  // A live-session init_verify that did not pass: the host wrote nothing, and
401
913
  // the develop keeps exactly the Learning/bootstrap evidence it started from.
402
914
  const verificationFailed=added[0]?.terminal==='failed'&&added[0].failureResult?.code==='bootstrap_verification_failed';
@@ -431,8 +943,8 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
431
943
  same(application.identity,effect.learningInput.identity);}
432
944
  const writeback=readCmAiProjectLearningWriteback(s.learningResult.writeback,
433
945
  {learningInput:effect.learningInput,retrospective:s.learningResult.retrospective});
434
- need(added.length===1&&added[0].terminal==='succeeded','runner_learning');
435
- same(added[0].resultDigest,digest({outcome:'implemented',...(hasApplication?{application}:{}),
946
+ need((recheck||added.length===1)&&developerCall?.terminal==='succeeded','runner_learning');
947
+ same(developerCall.resultDigest,digest({outcome:'implemented',...(hasApplication?{application}:{}),
436
948
  retrospective:s.learningResult.retrospective,...(hasBootstrap?{bootstrap:s.learningResult.bootstrap}:{})}));
437
949
  if(writeback.outcome==='writeback_pending'){
438
950
  expectedState='blocked';expectedCode='learning_writeback_pending';
@@ -450,7 +962,7 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
450
962
  ?{outcome:'implemented',...(s.learningResult&&Object.hasOwn(s.learningResult,'application')
451
963
  ?{application:s.learningResult.application}:{}),retrospective:s.learningResult?.retrospective,
452
964
  ...(s.learningResult?.bootstrap?{bootstrap:s.learningResult.bootstrap}:{})}:{outcome:'implemented'};
453
- need(added.length===1 && added[0].terminal==='succeeded' && added[0].resultDigest===digest(developerResult),'runner_develop');
965
+ need((recheck||added.length===1) && developerCall?.terminal==='succeeded' && developerCall.resultDigest===digest(developerResult),'runner_develop');
454
966
  if(Object.hasOwn(config,'taskLearning'))need(s.learningResult!==null
455
967
  &&s.learningResult.writeback.outcome!=='writeback_pending','runner_learning');
456
968
  packageLink(s.reviewPackage,original,before.attempt,s.currentChecks);
@@ -462,7 +974,7 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
462
974
  // between the checks and the review package. No package exists, so no review
463
975
  // round was spent; the attempt counter does not move either.
464
976
  // develop_unchanged_after_review: attempt 2 matched the rejected attempt-1 artifact.
465
- if(added[0]?.terminal==='succeeded'&&['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'].includes(s.code)) {
977
+ if(developerCall?.terminal==='succeeded'&&['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'].includes(s.code)) {
466
978
  // s.receipt is null for every develop checkpoint (above); at attempt 2 the
467
979
  // state before still holds the attempt-1 receipt, so only receipts compare.
468
980
  need(digest(s.reviewPackage)===digest(before.reviewPackage),'runner_develop');
@@ -570,7 +1082,7 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
570
1082
  expectedState='blocked';
571
1083
  if(['completion_checks_changed','completion_package_changed'].includes(s.code)){
572
1084
  need(effect.kind==='complete'&&['approved','blocked'].includes(before.state)
573
- &&(before.state==='approved'||['completion_checks_changed','completion_package_changed','review_package_changed'].includes(before.code)),'runner_transition');
1085
+ &&(before.state==='approved'||['completion_checks_changed','completion_package_changed','review_package_changed',COMPLETE_RECHECK_CODE].includes(before.code)),'runner_transition');
574
1086
  expectedCode=s.code;
575
1087
  if(s.code==='completion_package_changed')need(typeof s.reason==='string'&&s.reason.length>0,'runner_diagnostic');
576
1088
  }
@@ -610,6 +1122,23 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
610
1122
  recovered.cache.at(-1).result=runnerStatus(recovered,config);
611
1123
  return recovered;
612
1124
  }
1125
+ // A42: since #160 a completion re-check whose check list (ids or commands)
1126
+ // or visual carriers differed from the reviewed package ended in a terminal
1127
+ // package_mismatch whose reason is the bare code; nothing else produced that
1128
+ // reason, and the reviewed code had matched. A retried complete re-verifies
1129
+ // everything. A reason naming changed paths, and the older no-reason shape
1130
+ // (it also covered a Learning handoff mismatch and pre-#160 code drift, so
1131
+ // the journal cannot prove it was only checks), stay terminal.
1132
+ if(effect.kind==='complete'&&s.state==='blocked'&&s.code==='package_mismatch'
1133
+ &&s.reason==='package_mismatch'&&s.taskCommit==null
1134
+ &&(before.state==='approved'||before.state==='blocked'
1135
+ &&[...COMPLETION_RETRY_CODES,'review_package_changed',COMPLETE_RECHECK_CODE].includes(before.code))){
1136
+ const recovered=structuredClone(s);
1137
+ recovered.code='completion_checks_changed';
1138
+ recovered.reason='completion_checks_changed: 旧版本把完成复查与审查包的检查清单或检查证据差异记成了 package_mismatch(代码未变);发送 complete 按审查包的检查清单重新复查并完成。';
1139
+ recovered.cache.at(-1).result=runnerStatus(recovered,config);
1140
+ return recovered;
1141
+ }
613
1142
  // Runners before the create-time scope gate dispatched a protected scope and
614
1143
  // journaled the adapter's pre-dispatch refusal as unknown/execution_error,
615
1144
  // with no exit. Reproject only that exact shape: one developer call that never
@@ -686,6 +1215,29 @@ function completionConfig(config,version){
686
1215
  }
687
1216
  return c;
688
1217
  }
1218
+ const workerSummary=w=>({journal:w.journal===true,spawned:w.spawning!==null,started:w.started,
1219
+ applies:w.applies.map(item=>({started:item.started}))});
1220
+ // What a redo, interruption or void record names when the host proved every
1221
+ // started writer's process group gone: the provider worker and each sandbox
1222
+ // subprocess that applied a protected proposal (the exact develop-worker
1223
+ // records it checked). null: nothing was started, so there is nothing to prove.
1224
+ export const workerGoneBinding=summary=>{
1225
+ const worker=summary?.started??null,applies=(summary?.applies??[]).filter(item=>item.started).map(item=>item.started);
1226
+ if(worker===null&&!applies.length)return null;
1227
+ return {worker:worker&&{recordDigest:worker.digest,pid:worker.pid},
1228
+ applies:applies.map(item=>({recordDigest:item.digest,pid:item.pid})),verdict:'gone'};
1229
+ };
1230
+ // Every writer the journal shows as about to start also journaled its pid.
1231
+ // A pending effect with a spawning record and no pid is unprovable.
1232
+ const writersComplete=w=>(w.spawning===null||w.started!==null)&&w.applies.every(item=>item.started!==null);
1233
+ const bindingMatches=(p,expected)=>expected===null?!Object.hasOwn(p,'worker')
1234
+ :Object.hasOwn(p,'worker')&&digest(p.worker)===digest(expected);
1235
+ // R2: an interrupted step of the same kind is retired at most this many times
1236
+ // per run; afterwards abandon_effect only voids the run (effect-abandoned).
1237
+ export const MAX_EFFECT_INTERRUPTIONS=2;
1238
+ export const EFFECT_INTERRUPT_LIMIT_CODE='effect_interrupt_limit';
1239
+ export const effectInterruptLimitReason=kind=>`${EFFECT_INTERRUPT_LIMIT_CODE}: 宿主中途退出后在原运行内恢复 ${kind} 已用满 ${MAX_EFFECT_INTERRUPTIONS} 次。`
1240
+ +'先查清宿主为何反复中断;确认旧宿主与写入方已退出后,abandon_effect 只能作废本运行(effect-abandoned),再用 --supersede-reviewed-evidence 新建运行。';
689
1241
  function fullEnvelope(r,index,previousDigest){
690
1242
  shape(r,['version','seq','id','kind','payload','previousDigest','digest']);hex(r.digest);
691
1243
  need(r.version===1&&r.seq===index+1&&r.previousDigest===previousDigest,'runner_chain');
@@ -700,12 +1252,58 @@ export function readRunnerHistory(raw,config,version=1) {
700
1252
  let original,session,state,pending=null,beforeIntent=null,controlCount=0,controls={},completeIntentDigest=null,transaction=null;
701
1253
  let invocation={registration:null,started:null,result:null};let registrationRecord=null,startedRecord=null,resultRecord=null,lastReview=null;
702
1254
  const acceptedFixes=[],joinedHosts=[],reviewerThreads=[];let qaAttachment=null,qaRevision=null,joinedForInvocation=false,supersession=null;
1255
+ const answerGaps={developRecheck:0,completeRecheck:0,developRedo:0,developDispatch:0,documentationSync:0,reviewRedispatch:{1:0,2:0},
1256
+ reviewDispatchConfirmed:{1:noReviewDispatchConfirmations(),2:noReviewDispatchConfirmations()}};
1257
+ // Q16: documentation-sync-started records by digest, and the pending develop's.
1258
+ const documentationRecords=new Map();let pendingDocumentation=null,documentationStop=null;
1259
+ // V8/V9: interrupted intents (their ids are never reused) and the provider
1260
+ // worker records of the pending develop and of every checkpointed develop.
1261
+ const interrupted=[],workers={};let pendingWorker=null;
703
1262
  const reviewConfig=(calls=[])=>({...config,reviewInvocation:{...config.reviewInvocation,
704
1263
  excludedThreadIds:reviewExclusions({excludedThreadIds:[...config.reviewInvocation.excludedThreadIds,...joinedHosts]},
705
1264
  calls,config.developer.contextId)}});
706
1265
  const reconciliationBinding=()=>({effectId:lastReview.effect.id,invocationId:lastReview.request.invocationId,
707
1266
  registeredDigest:lastReview.registrationRecord.digest,startedDigest:lastReview.startedRecord?.digest??null,
708
1267
  resultDigest:lastReview.resultRecord.digest});
1268
+ // A pending effect that effect-interrupted may retire: no task-commit-intent,
1269
+ // not cancelled, a review never registered, and after the intent only the
1270
+ // records its kind may leave behind (controls, a join, worker records).
1271
+ // Q16: the documentation start a pending develop belongs to. Its own once
1272
+ // documentation_sync was asked; before that (a documentation-only redo whose
1273
+ // host died between its intent and its new start record) the start of the
1274
+ // failure the redo was confirmed for, which the intent's prior state names.
1275
+ const documentationOrigin=()=>{
1276
+ if(pending?.kind!=='develop')return null;
1277
+ if(pendingDocumentation!==null)return pendingDocumentation;
1278
+ if(beforeIntent?.state!=='blocked'||!DOCUMENTATION_SYNC_CODES.includes(beforeIntent.code))return null;
1279
+ const digest=beforeIntent.calls.at(-1)?.documentationSync,payload=documentationRecords.get(digest);
1280
+ return payload===undefined?null:{digest,payload};
1281
+ };
1282
+ const pendingInterruptible=(effect,intentIndex,end)=>version===3&&!(config.externalModels||config.executionPolicy)
1283
+ &&effect!==null&&Object.hasOwn(INTERRUPTIBLE_TRAILERS,effect.kind)&&transaction===null&&state.taskCommit?.intentDigest==null
1284
+ &&!controls.cancelled&&!controls.workflowError&&(effect.kind!=='review'||!invocation.registration)
1285
+ &&interrupted.filter(item=>item.kind===effect.kind).length<MAX_EFFECT_INTERRUPTIONS
1286
+ // Q16: one that died during documentation_sync is a documentation retry and
1287
+ // shares that cap; once spent, abandon_effect only voids the run.
1288
+ &&(documentationOrigin()===null||answerGaps.documentationSync<MAX_DOCUMENTATION_SYNC_RETRIES)
1289
+ &&records.slice(intentIndex+1,end).every(row=>INTERRUPTIBLE_TRAILERS[effect.kind].includes(row.payload.type));
1290
+ // A pending develop whose only trailers are controls and worker records may
1291
+ // still be voided (effect-abandoned) once the interruption cap is spent.
1292
+ const pendingWorkerVoidable=(effect,intentIndex,end)=>version===3&&!(config.externalModels||config.executionPolicy)
1293
+ &&effect?.kind==='develop'&&transaction===null&&state.taskCommit?.intentDigest==null
1294
+ &&records.slice(intentIndex+1,end).some(row=>row.payload.type==='develop-worker')
1295
+ &&records.slice(intentIndex+1,end).every(row=>['control','develop-worker'].includes(row.payload.type));
1296
+ const roundRedispatches=()=>reviewRedispatchCount(state.cache,state.calls,state.attempt,
1297
+ config.reviewers[0].contexts[state.attempt-1],answerGaps.reviewRedispatch[state.attempt]);
1298
+ const pendingReviewExhausted=()=>pending?.kind==='review'&&invocation.registration!==null
1299
+ &&(invocation.result===null||invocation.result.outcome!=='observed')&&roundRedispatches()>=MAX_REVIEW_REDISPATCHES;
1300
+ // A38: a pending review whose result reached the journal but whose checkpoint
1301
+ // did not, and the result is a no-verdict end the operator could abandon.
1302
+ const pendingResultAbandonable=()=>!(config.externalModels||config.executionPolicy)&&version===3&&pending?.kind==='review'
1303
+ &&invocation.registration!==null&&invocation.result!==null&&invocation.result.outcome!=='observed'
1304
+ &&!controls.cancelled&&!controls.workflowError
1305
+ &&(abandonableReviewOutcome(invocation.result)||reviewRetryCode(invocation.result)!==null)
1306
+ &&roundRedispatches()<MAX_REVIEW_REDISPATCHES;
709
1307
  for(const [index,r] of records.entries()) {
710
1308
  if(index>0)need(records[index-1].payload.type!=='effect-abandoned','runner_abandon');
711
1309
  boundRunnerRecord(r,index+1);
@@ -756,15 +1354,23 @@ export function readRunnerHistory(raw,config,version=1) {
756
1354
  state.reviewPackage=readReviewPackage(p.reviewPackage);
757
1355
  state.state='awaiting_review';state.code=null;state.reason=null;
758
1356
  } else if(p.type==='effect-intent') {
759
- shape(p,[...common,'effect']);need(r.kind==='intent' && pending===null,'runner_intent');
1357
+ shape(p,[...common,'effect',...(Object.hasOwn(p,'workerJournal')?['workerJournal']:[])]);need(r.kind==='intent' && pending===null,'runner_intent');
760
1358
  const e=p.effect;shape(e,['version','id','identity','kind',...(Object.hasOwn(e,'learningInput')?['learningInput']:[])]);
761
1359
  validIdentity(e.identity);id(e.id);
1360
+ // The marker says this runtime journals the provider worker's identity
1361
+ // (develop-worker) for this effect; only provider development carries it.
1362
+ // Current-session development carries it when protected proposals are
1363
+ // applied by a sandbox subprocess (apply records only).
1364
+ if(Object.hasOwn(p,'workerJournal'))need(version===3&&p.workerJournal===true&&e.kind==='develop','runner_worker');
1365
+ need(!interrupted.some(item=>item.effectId===e.id),'runner_cache');
1366
+ pendingWorker={journal:p.workerJournal===true,spawning:null,started:null,applies:[]};
762
1367
  if(e.kind==='develop'&&Object.hasOwn(config,'taskLearning'))need(Object.hasOwn(e,'learningInput'),'runner_learning');
763
1368
  if(Object.hasOwn(e,'learningInput')){need(e.kind==='develop'&&Object.hasOwn(config,'taskLearning'),'runner_learning');
764
1369
  validTaskLearningInput(e.learningInput,e.identity,config.taskLearning.feature);}
765
1370
  same(e.identity,{...config.identity,attempt:state.attempt});need(e.version===1 && stageAllowed(e.kind,state.state,state.code,state.priorReview?.verdict),'runner_stage');
1371
+ need(!(e.kind==='review'&&reviewNotDispatchedExhausted(state,answerGaps.reviewDispatchConfirmed[state.attempt].extended)),'runner_stage');
766
1372
  need(effectSlotFree(e.kind,state.cache,state.calls) && !state.cache.some(c=>c.effect.id===e.id),'runner_cache');
767
- pending=e;beforeIntent=structuredClone(state);controls={};completeIntentDigest=e.kind==='complete'?r.digest:null;
1373
+ pending=e;beforeIntent=structuredClone(state);controls={};completeIntentDigest=e.kind==='complete'?r.digest:null;pendingDocumentation=null;documentationStop=null;
768
1374
  invocation={registration:null,started:null,result:null};registrationRecord=null;startedRecord=null;resultRecord=null;
769
1375
  joinedForInvocation=false;lastReview=null;
770
1376
  } else if(version===3&&p.type==='host-joined') {
@@ -830,6 +1436,142 @@ export function readRunnerHistory(raw,config,version=1) {
830
1436
  &&p.fromCode===state.code&&p.countedCalls===used.calls&&p.countedEffects===used.effects,'runner_retry_limit');
831
1437
  state.state='blocked';state.code='develop_retry_limit';
832
1438
  state.reason=developRetryLimitReason(p);lastReview=null;
1439
+ } else if(version===3&&p.type==='develop-answer-retry') {
1440
+ // Written by advance for a current-session answer the host rejected as
1441
+ // invalid; replay re-derives the whole condition from the journal.
1442
+ shape(p,[...common,'effectId','invocationId']);
1443
+ need(r.kind==='result'&&pending===null&&state.code==='failed'&&developAnswerRetryable(state,config.bootstrap)
1444
+ &&p.effectId===state.cache.at(-1).effect.id&&p.invocationId===state.calls.at(-1).invocationId,'runner_develop_answer');
1445
+ state.code='develop_answer_invalid';state.reason=developAnswerInvalidReason(state.calls.at(-1).failureResult);lastReview=null;
1446
+ } else if(version===3&&p.type==='develop-timeout-retry') {
1447
+ // Written by advance after it found the code root unchanged since the
1448
+ // timed-out develop started; replay re-derives everything but the disk.
1449
+ shape(p,[...common,'effectId','invocationId','basis']);
1450
+ const basis=developTimeoutBasis(state,config.bootstrap);
1451
+ need(r.kind==='result'&&pending===null&&state.state==='unknown'&&basis!==null&&p.basis===basis
1452
+ &&p.effectId===state.cache.at(-1).effect.id&&p.invocationId===state.calls.at(-1).invocationId,'runner_develop_timeout');
1453
+ state.state='blocked';state.code='develop_call_timeout';state.reason=DEVELOP_CALL_TIMEOUT_REASON;lastReview=null;
1454
+ } else if(version===3&&p.type==='develop-recheck') {
1455
+ // Written by advance for a delivered develop whose later checks never got
1456
+ // a usable answer; everything is re-derived from the replayed journal.
1457
+ shape(p,[...common,'effectId','invocationId','code']);
1458
+ const code=developRecheckCode(state,config,answerGaps.developRecheck);
1459
+ need(r.kind==='result'&&pending===null&&state.state==='unknown'&&code!==null&&p.code===code
1460
+ &&p.effectId===state.cache.at(-1).effect.id&&p.invocationId===state.calls.at(-1).invocationId,'runner_develop_recheck');
1461
+ answerGaps.developRecheck++;
1462
+ state.state='blocked';state.code=code;state.reason=developRecheckReason(code,state.cache.at(-1).result.code,state.cache.at(-1).result.reason);lastReview=null;
1463
+ } else if(version===3&&p.type==='develop-answer-redo') {
1464
+ // The operator confirmed the session stopped writing (R3); the redo itself
1465
+ // is the next develop intent. Re-derived from the journal, never the disk.
1466
+ const cause=developRedoCause(state,config,answerGaps.developRedo,workers);
1467
+ need(r.kind==='result'&&pending===null&&cause!==null&&p.cause===cause
1468
+ &&p.effectId===state.cache.at(-1).effect.id&&p.invocationId===state.calls.at(-1).invocationId,'runner_develop_redo');
1469
+ // Every started provider writer must have been proven gone by the host;
1470
+ // a Claude proposal also needs the live root at the round start (basis).
1471
+ const provider=cause.startsWith('provider_');
1472
+ shape(p,[...common,'effectId','invocationId','cause','reason','at',...['worker','basis'].filter(key=>Object.hasOwn(p,key))]);
1473
+ need(bindingMatches(p,provider?workerGoneBinding(workers[p.effectId]):null),'runner_develop_redo');
1474
+ if(provider&&config.developer.provider==='claude')need(p.basis!=null&&p.basis===redoDevelopStart(state),'runner_develop_redo');
1475
+ else need(!Object.hasOwn(p,'basis'),'runner_develop_redo');
1476
+ need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
1477
+ &&!/[\r\n\0]/.test(p.reason),'runner_develop_redo');
1478
+ need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_develop_redo');
1479
+ answerGaps.developRedo++;
1480
+ state.state='blocked';state.code=DEVELOP_REDO_CODE;state.reason=developRedoReason(cause);lastReview=null;
1481
+ } else if(version===3&&p.type==='develop-dispatch-retry') {
1482
+ // Written by advance when the develop failed before dispatch; a legacy
1483
+ // execution_error is admitted only on a journal-pinned start (the live
1484
+ // host compared the code root with it before writing this record).
1485
+ shape(p,[...common,'effectId','invocationId','basis']);
1486
+ const basis=developDispatchBasis(state,config,answerGaps.developDispatch);
1487
+ need(r.kind==='result'&&pending===null&&state.state==='unknown'&&basis!==null&&p.basis===basis
1488
+ &&p.effectId===state.cache.at(-1).effect.id&&p.invocationId===state.calls.at(-1).invocationId,'runner_develop_dispatch');
1489
+ answerGaps.developDispatch++;
1490
+ state.reason=developDispatchReason(state.code);
1491
+ state.state='blocked';state.code=DISPATCH_RETRY_CODE;lastReview=null;
1492
+ } else if(version===3&&p.type==='documentation-sync-started') {
1493
+ // Q16: written by the final task's develop right before it asks
1494
+ // documentation_sync: the developer answer it already accepted and the
1495
+ // documentation start. Bound to the pending develop's own developer call.
1496
+ shape(p,[...common,'effectId','invocationId','result','effectiveModel','documents','othersDigest']);
1497
+ need(r.kind==='result'&&pending?.kind==='develop'&&p.effectId===pending.id&&pendingDocumentation===null
1498
+ &&!config.bootstrap&&p.invocationId===`${session}.${beforeIntent.calls.length+1}`
1499
+ &&!controls.cancelled&&!controls.workflowError,'runner_documentation');
1500
+ text(p.effectiveModel);hex(p.othersDigest);json(p.result,256*1024);
1501
+ need(p.result!==null&&typeof p.result==='object'&&!Array.isArray(p.result),'runner_documentation');
1502
+ validDocumentationStates(p.documents,config.scope);
1503
+ // A documentation-only redo carries exactly the answer its source journaled.
1504
+ if(beforeIntent.state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(beforeIntent.code)){
1505
+ const source=documentationRecords.get(beforeIntent.calls.at(-1)?.documentationSync);
1506
+ need(source&&digest(source.result)===digest(p.result)&&source.effectiveModel===p.effectiveModel
1507
+ &&digest(source.documents.map(item=>item.path))===digest(p.documents.map(item=>item.path)),'runner_documentation');
1508
+ }
1509
+ pendingDocumentation={digest:r.digest,payload:p};documentationRecords.set(r.digest,p);
1510
+ } else if(version===3&&p.type==='documentation-sync-retry') {
1511
+ // Q16/Q17 (R3): develop_redo's stop confirmation for one failed
1512
+ // documentation_sync, bound to its developer call and start record, with
1513
+ // the documentation paths as they were at the confirmation. From the
1514
+ // checkpointed failure (unknown) it spends one of the run's retries; from
1515
+ // an already confirmed block (a re-confirmation after the operator's own
1516
+ // edits) it only replaces the confirmed documentation state.
1517
+ shape(p,[...common,'effectId','invocationId','startDigest','code','documents','reason','at']);
1518
+ need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
1519
+ &&!/[\r\n\0]/.test(p.reason),'runner_documentation_retry');
1520
+ need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_documentation_retry');
1521
+ need(r.kind==='result'&&pending===null,'runner_documentation_retry');
1522
+ const call=state.calls.at(-1),start=documentationRecords.get(call?.documentationSync);
1523
+ need(start!==undefined&&p.invocationId===call.invocationId&&p.startDigest===call.documentationSync,'runner_documentation_retry');
1524
+ validDocumentationStates(p.documents,config.scope);
1525
+ same(p.documents.map(item=>item.path),start.documents.map(item=>item.path));
1526
+ if(state.state==='unknown'){
1527
+ const code=documentationSyncRetryCode(state,config,answerGaps.documentationSync);
1528
+ need(code!==null&&p.code===code&&p.effectId===state.cache.at(-1).effect.id,'runner_documentation_retry');
1529
+ answerGaps.documentationSync++;
1530
+ documentationStop={effectId:p.effectId,invocationId:p.invocationId,startDigest:p.startDigest,
1531
+ detail:state.cache.at(-1).result.reason??null};
1532
+ }else need(state.state==='blocked'&&DOCUMENTATION_SYNC_CODES.includes(state.code)&&p.code===state.code
1533
+ &&documentationStop!==null&&p.effectId===documentationStop.effectId&&p.invocationId===documentationStop.invocationId
1534
+ &&p.startDigest===documentationStop.startDigest,'runner_documentation_retry');
1535
+ state.state='blocked';state.code=p.code;state.reason=documentationSyncRetryReason(p.code,documentationStop.detail);lastReview=null;
1536
+ } else if(version===3&&p.type==='complete-recheck') {
1537
+ shape(p,[...common,'effectId','source']);
1538
+ need(r.kind==='result'&&pending===null&&state.state==='unknown'&&completeRecheckable(state,answerGaps.completeRecheck)
1539
+ &&p.effectId===state.cache.at(-1).effect.id&&p.source===state.code,'runner_complete_recheck');
1540
+ answerGaps.completeRecheck++;
1541
+ state.state='blocked';state.code=COMPLETE_RECHECK_CODE;state.reason=completeRecheckReason(p.source);lastReview=null;
1542
+ } else if(version===3&&p.type==='review-redispatch') {
1543
+ // V5 (A34): written by abandon_review from this round's spent retryable
1544
+ // review block while the round has a no-result redispatch left: the
1545
+ // operator confirmed (reason) the original call's reviewer stopped. The
1546
+ // redispatch itself is the next review intent. Re-derived from the journal.
1547
+ need(!(config.externalModels||config.executionPolicy),'external_review_reconciliation_required');
1548
+ shape(p,[...common,'effectId','invocationId','attempt','code','reason','at']);
1549
+ need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
1550
+ &&!/[\r\n\0]/.test(p.reason),'runner_review_redispatch');
1551
+ need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_review_redispatch');
1552
+ const contextId=config.reviewers[0].contexts[state.attempt-1];
1553
+ need(r.kind==='result'&&pending===null&&p.attempt===state.attempt
1554
+ &&reviewRedispatchable(state,contextId,answerGaps.reviewRedispatch[state.attempt])
1555
+ &&p.code===state.code&&p.effectId===state.cache.at(-1).effect.id
1556
+ &&p.invocationId===state.reviewInvocation.registration.grant.invocationId,'runner_review_redispatch');
1557
+ answerGaps.reviewRedispatch[state.attempt]++;
1558
+ state.state='pending_review';lastReview=null;
1559
+ } else if(version===3&&p.type==='review-dispatch-confirmed') {
1560
+ // The operator's confirmation (abandon_review + reason) for a review that never
1561
+ // started: a refused authorization (once per denial) or the spent not-dispatched
1562
+ // redispatch bound (once per round). Nothing ran, so there is no process to prove
1563
+ // stopped (unlike review-redispatch). Re-derived from the journal.
1564
+ shape(p,[...common,'effectId','attempt','code','reason','at']);
1565
+ need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
1566
+ &&!/[\r\n\0]/.test(p.reason),'runner_review_dispatch_confirm');
1567
+ need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_review_dispatch_confirm');
1568
+ const confirmed=answerGaps.reviewDispatchConfirmed[state.attempt];
1569
+ need(r.kind==='result'&&pending===null&&p.attempt===state.attempt&&p.code===state.code
1570
+ &&p.effectId===state.cache.at(-1)?.effect.id
1571
+ &&(reviewDenialConfirmable(state,confirmed)||reviewNotDispatchedExtendable(state,confirmed)),'runner_review_dispatch_confirm');
1572
+ if(p.code===REVIEW_DENIED_CODE){confirmed.denied++;state.code=REVIEW_DENIAL_CONFIRMED_CODE;}
1573
+ else confirmed.extended++;
1574
+ lastReview=null;
833
1575
  } else if(version===3&&p.type==='completion-retry-limit') {
834
1576
  // Terminal: written instead of a complete intent once the re-check bound
835
1577
  // is spent. Every field is recomputed from the replayed state.
@@ -837,12 +1579,12 @@ export function readRunnerHistory(raw,config,version=1) {
837
1579
  need(r.kind==='result'&&pending===null&&completionRetriesExhausted(state)&&p.fromCode===state.code
838
1580
  &&p.completionBlocks===completionBlockCount(state.cache),'runner_retry_limit');
839
1581
  state.state='blocked';state.code='completion_retry_limit';state.reason=completionRetryLimitReason(p);lastReview=null;
840
- } else if(version===3&&p.type==='review-invocation-abandoned'&&Object.hasOwn(p,'resultDigest')) {
1582
+ } else if(version===3&&p.type==='review-invocation-abandoned'&&Object.hasOwn(p,'resultDigest')&&pending===null) {
841
1583
  need(!(config.externalModels||config.executionPolicy),'external_review_reconciliation_required');
842
1584
  // Abandoning a checkpointed review whose journaled result was never accepted.
843
1585
  shape(p,[...common,'effectId','invocationId','registeredDigest','startedDigest','resultDigest','reason','at']);
844
1586
  need(r.kind==='result'&&pending===null&&lastReview!==null
845
- &&abandonableReviewResult(state,config.reviewers[0].contexts[state.attempt-1]),'runner_abandon');
1587
+ &&abandonableReviewResult(state,config.reviewers[0].contexts[state.attempt-1],answerGaps.reviewRedispatch[state.attempt]),'runner_abandon');
846
1588
  need(p.effectId===lastReview.effect.id&&state.cache.at(-1).effect.id===lastReview.effect.id
847
1589
  &&p.invocationId===lastReview.request.invocationId&&p.registeredDigest===lastReview.registrationRecord.digest
848
1590
  &&p.startedDigest===(lastReview.startedRecord?.digest??null)&&p.resultDigest===lastReview.resultRecord.digest,'runner_abandon');
@@ -860,18 +1602,23 @@ export function readRunnerHistory(raw,config,version=1) {
860
1602
  lastReview=null;
861
1603
  } else if(version===3&&p.type==='review-invocation-abandoned') {
862
1604
  need(!(config.externalModels||config.executionPolicy),'external_review_reconciliation_required');
863
- shape(p,[...common,'effectId','invocationId','registeredDigest','startedDigest','reason','at']);
864
- need(r.kind==='result'&&pending?.kind==='review'&&invocation.registration&&!invocation.result
865
- &&!controls.cancelled&&!controls.workflowError&&state.state==='awaiting_review','runner_abandon');
1605
+ // A38: a pending review whose no-verdict result reached the journal right
1606
+ // before the host died (no checkpoint) is abandoned like a pending one,
1607
+ // bound to that result record, which must be the record just before.
1608
+ const withResult=Object.hasOwn(p,'resultDigest');
1609
+ shape(p,[...common,'effectId','invocationId','registeredDigest','startedDigest',...(withResult?['resultDigest']:[]),'reason','at']);
1610
+ need(r.kind==='result'&&pending?.kind==='review'&&invocation.registration
1611
+ &&(withResult?pendingResultAbandonable()&&records[index-1]===resultRecord&&p.resultDigest===resultRecord.digest:!invocation.result)
1612
+ &&!controls.cancelled&&!controls.workflowError
1613
+ // A redispatch's intent was issued from pending_review (V5: up to two per round).
1614
+ &&(state.state==='awaiting_review'||state.state==='pending_review'&&REVIEW_RETRY_CODES.includes(state.code)),'runner_abandon');
866
1615
  need(p.effectId===pending.id&&p.invocationId===invocation.registration.request.invocationId
867
1616
  &&p.registeredDigest===registrationRecord.digest
868
1617
  &&p.startedDigest===(startedRecord?.digest??null),'runner_abandon');
869
1618
  need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
870
1619
  &&!/[\r\n\0]/.test(p.reason),'runner_abandon');
871
1620
  need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_abandon');
872
- need(!state.cache.some(entry=>entry.effect.identity.attempt===state.attempt&&timeoutEffect(entry))
873
- &&!state.calls.some(call=>call.terminal==='abandoned'
874
- &&call.contextId===config.reviewers[0].contexts[state.attempt-1]),'runner_abandon_budget');
1621
+ need(roundRedispatches()<MAX_REVIEW_REDISPATCHES,'runner_abandon_budget');
875
1622
  const request=invocation.registration.request;
876
1623
  state.calls.push({invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
877
1624
  requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-authorized',
@@ -882,12 +1629,103 @@ export function readRunnerHistory(raw,config,version=1) {
882
1629
  state.reviewInvocation={registration:invocation.registration.record,started:invocation.started,
883
1630
  result:{outcome:'abandoned',reason:p.reason,at:p.at,recordDigest:r.digest}};
884
1631
  pending=null;beforeIntent=null;invocation={registration:null,started:null,result:null};
1632
+ } else if(version===3&&p.type==='develop-worker') {
1633
+ // V9: the writers of the pending develop, journaled by the host right
1634
+ // before (…spawning) and right after (…started: pid = process group,
1635
+ // start time) each spawns: the provider worker once, and each sandbox
1636
+ // subprocess that applies a protected proposal (one per root, at most
1637
+ // MAX_CODE_PROJECTS). Bound to the
1638
+ // develop's invocation; never after a cancel or workflow error.
1639
+ const started=['started','apply_started'].includes(p.phase);
1640
+ shape(p,[...common,'effectId','invocationId','phase',...(started?['pid','startTime']:[])]);
1641
+ need(r.kind==='result'&&pending?.kind==='develop'&&p.effectId===pending.id&&pendingWorker?.journal===true
1642
+ &&p.invocationId===`${session}.${beforeIntent.calls.length+1}`&&!controls.cancelled&&!controls.workflowError,'runner_worker');
1643
+ if(started)need(validWorkerPid(p.pid)&&validStartTime(p.startTime),'runner_worker');
1644
+ const identity={digest:r.digest,pid:p.pid,startTime:p.startTime};
1645
+ const provider=config.developer.requestedModel!=='current-session',open=pendingWorker.applies.at(-1);
1646
+ if(p.phase==='spawning'){need(provider&&pendingWorker.spawning===null&&!pendingWorker.applies.length,'runner_worker');pendingWorker.spawning=r.digest;}
1647
+ else if(p.phase==='started'){need(provider&&pendingWorker.spawning!==null&&pendingWorker.started===null&&!pendingWorker.applies.length,'runner_worker');pendingWorker.started=identity;}
1648
+ else if(p.phase==='apply_spawning'){need((!open||open.started!==null)&&pendingWorker.applies.length<MAX_CODE_PROJECTS,'runner_worker');pendingWorker.applies.push({started:null});}
1649
+ else{need(p.phase==='apply_started'&&open&&open.started===null,'runner_worker');open.started=identity;}
1650
+ } else if(version===3&&p.type==='effect-interrupted') {
1651
+ need(!(config.externalModels||config.executionPolicy),'external_review_reconciliation_required');
1652
+ shape(p,[...common,'effectId','effectKind','intentDigest','lastRecordDigest','reason','at',
1653
+ ...['basis','worker','startDigest','documents'].filter(key=>Object.hasOwn(p,key))]);
1654
+ const intentIndex=records.slice(0,index).findLastIndex(row=>row.payload.type==='effect-intent');
1655
+ // Q16: a develop that died during documentation_sync names its start record
1656
+ // and the documentation paths as they were when the operator confirmed
1657
+ // the old host and session stopped (this record); exactly then.
1658
+ const origin=documentationOrigin(),documentationInterrupted=origin!==null;
1659
+ need(documentationInterrupted===Object.hasOwn(p,'startDigest')&&documentationInterrupted===Object.hasOwn(p,'documents'),'runner_interrupt');
1660
+ if(documentationInterrupted){
1661
+ need(p.startDigest===origin.digest,'runner_interrupt');
1662
+ validDocumentationStates(p.documents,config.scope);
1663
+ same(p.documents.map(item=>item.path),origin.payload.documents.map(item=>item.path));
1664
+ }
1665
+ need(r.kind==='result'&&pending&&intentIndex>=0&&pendingInterruptible(pending,intentIndex,index),'runner_interrupt');
1666
+ need(p.effectId===pending.id&&p.effectKind===pending.kind&&p.intentDigest===records[intentIndex].digest
1667
+ &&p.lastRecordDigest===records[index-1].digest,'runner_interrupt');
1668
+ need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
1669
+ &&!/[\r\n\0]/.test(p.reason),'runner_interrupt');
1670
+ need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_interrupt');
1671
+ const provider=config.developer.requestedModel!=='current-session';
1672
+ if(pending.kind==='develop'){
1673
+ // A provider worker that may have started is retired only with the
1674
+ // host's proof that its process group is gone; no record, no proof.
1675
+ if(provider)need(pendingWorker.journal===true,'runner_interrupt');
1676
+ need(writersComplete(pendingWorker)&&bindingMatches(p,workerGoneBinding(pendingWorker)),'runner_interrupt');
1677
+ // basis: the live host proved the code root still equals the pinned round
1678
+ // start where every write is an applied proposal (protected current-session
1679
+ // development, Claude provider development): a partial apply is restored
1680
+ // by a person first, never sent to review as a new delivery (V6).
1681
+ const proposalApply=provider&&config.developer.provider==='claude';
1682
+ if(proposalApply)need(p.basis!=null&&p.basis===pendingDevelopStart(state),'runner_interrupt');
1683
+ else if(Object.hasOwn(p,'basis'))need(!provider&&p.basis===pendingDevelopStart(state),'runner_interrupt');
1684
+ const request=requestFor({invocationId:`${session}.${state.calls.length+1}`,identity:{...config.identity,attempt:state.attempt},
1685
+ role:'developer',provider:config.developer.provider,requestedModel:config.developer.requestedModel,
1686
+ contextId:config.developer.contextId,payload:{scope:config.scope,
1687
+ requirements:original.files.filter(f=>config.requirements.includes(f.path)),priorReview:state.priorReview,
1688
+ ...supersededReviewPayload(supersession?.carriedReview??null,state.attempt),
1689
+ ...(Object.hasOwn(original,'specification')?{specification:original.specification}:{}),
1690
+ ...(Object.hasOwn(pending,'learningInput')?{learningInput:pending.learningInput}:{})}});
1691
+ state.calls.push({invocationId:request.invocationId,contextId:config.developer.contextId,provider:config.developer.provider,
1692
+ requestedModel:config.developer.requestedModel,effectiveModel:'unknown',channel:'fixture',started:true,
1693
+ terminal:'abandoned',requestDigest:request.requestDigest,resultDigest:r.digest,
1694
+ ...(documentationInterrupted?{documentationSync:origin.digest}:{})});
1695
+ state.sequence++;
1696
+ if(documentationInterrupted){
1697
+ // The developer had answered (journaled): redo only documentation_sync.
1698
+ answerGaps.documentationSync++;
1699
+ documentationStop={effectId:pending.id,invocationId:request.invocationId,startDigest:p.startDigest,detail:null};
1700
+ state.state='blocked';state.code=DOCUMENTATION_SYNC_INTERRUPTED_CODE;
1701
+ state.reason=documentationSyncRetryReason(DOCUMENTATION_SYNC_INTERRUPTED_CODE);
1702
+ }else{state.state='blocked';state.code=DEVELOP_INTERRUPTED_CODE;state.reason=developInterruptedReason(provider);}
1703
+ }else{
1704
+ need(!Object.hasOwn(p,'basis')&&!Object.hasOwn(p,'worker'),'runner_interrupt');
1705
+ if(pending.kind==='review'){state.state='awaiting_review';state.code=null;state.reason=REVIEW_INTERRUPTED_REASON;}
1706
+ else {state.state=beforeIntent.state;state.code=beforeIntent.code;state.reason=beforeIntent.reason??null;}
1707
+ }
1708
+ interrupted.push({effectId:pending.id,kind:pending.kind});
1709
+ pending=null;beforeIntent=null;invocation={registration:null,started:null,result:null};pendingWorker=null;pendingDocumentation=null;
1710
+ joinedForInvocation=false;lastReview=null;
885
1711
  } else if(version===3&&p.type==='effect-abandoned') {
886
1712
  need(!(config.externalModels||config.executionPolicy),'external_review_reconciliation_required');
887
1713
  shape(p,[...common,'effectId','effectKind','intentDigest','reason','at',
888
- ...(Object.hasOwn(p,'lastRecordDigest')?['lastRecordDigest']:[])]);
1714
+ ...['lastRecordDigest','worker'].filter(key=>Object.hasOwn(p,key))]);
889
1715
  let intentIndex=index-1;
890
- while(intentIndex>=0&&records[intentIndex].payload.type==='control')intentIndex--;
1716
+ while(intentIndex>=0&&(records[intentIndex].payload.type==='control'
1717
+ ||pending?.kind==='develop'&&records[intentIndex].payload.type==='documentation-sync-started'))intentIndex--;
1718
+ // A36: a registered review whose no-result redispatches this round
1719
+ // (MAX_REVIEW_REDISPATCHES) are spent can no longer be abandoned with abandon_review. Voiding the run
1720
+ // (then superseding it) is its only exit; it must name the last record.
1721
+ const exhaustedReview=pendingReviewExhausted();
1722
+ const lastIntent=records.slice(0,index).findLastIndex(row=>row.payload.type==='effect-intent');
1723
+ // A develop with journaled writers is voided only with their gone-proof.
1724
+ const workerVoid=pendingWorkerVoidable(pending,lastIntent,index);
1725
+ if(exhaustedReview||workerVoid)intentIndex=lastIntent;
1726
+ if(workerVoid)need(writersComplete(pendingWorker)&&bindingMatches(p,workerGoneBinding(pendingWorker))
1727
+ &&Object.hasOwn(p,'lastRecordDigest'),'runner_abandon');
1728
+ else need(!Object.hasOwn(p,'worker'),'runner_abandon');
891
1729
  const intent=records[intentIndex];
892
1730
  need(r.kind==='result'&&pending&&['develop','complete','review'].includes(pending.kind)
893
1731
  &&intent?.payload.type==='effect-intent'&&transaction===null
@@ -895,8 +1733,8 @@ export function readRunnerHistory(raw,config,version=1) {
895
1733
  need(p.effectId===pending.id&&p.effectKind===pending.kind
896
1734
  &&p.intentDigest===intent.digest
897
1735
  &&(Object.hasOwn(p,'lastRecordDigest')
898
- ?p.lastRecordDigest===records[index-1].digest:intentIndex===index-1)
899
- &&(pending.kind!=='review'||!invocation.registration&&!joinedForInvocation),'runner_abandon');
1736
+ ?p.lastRecordDigest===records[index-1].digest:intentIndex===index-1&&!exhaustedReview&&!workerVoid)
1737
+ &&(pending.kind!=='review'||!invocation.registration&&!joinedForInvocation||exhaustedReview),'runner_abandon');
900
1738
  need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
901
1739
  &&!/[\r\n\0]/.test(p.reason),'runner_abandon');
902
1740
  need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_abandon');
@@ -905,17 +1743,18 @@ export function readRunnerHistory(raw,config,version=1) {
905
1743
  } else if(p.type==='effect-checkpoint') {
906
1744
  shape(p,[...common,'effectId','checkpoint']);need(r.kind==='result' && pending && p.effectId===pending.id,'runner_checkpoint');
907
1745
  state=checkpoint(beforeIntent,p.checkpoint,pending,config,original,session,controls,version,state.taskCommit??null,invocation,
908
- supersession?.carriedReview??null);
1746
+ supersession?.carriedReview??null,pendingDocumentation);pendingDocumentation=null;
909
1747
  lastReview=version===3&&pending.kind==='review'&&invocation.result?{effect:pending,request:invocation.registration.request,
910
1748
  registrationRecord,startedRecord,resultRecord,before:beforeIntent,controls,invocation}:null;
911
- pending=null;beforeIntent=null;invocation={registration:null,started:null,result:null};
1749
+ if(pending.kind==='develop'&&pendingWorker?.journal)workers[pending.id]=workerSummary(pendingWorker);
1750
+ pending=null;beforeIntent=null;invocation={registration:null,started:null,result:null};pendingWorker=null;
912
1751
  } else if(version>=2 && ['task-commit-intent','task-commit-result'].includes(p.type)){
913
1752
  shape(p,[...common,'effectId','completeIntentDigest','commit']);
914
1753
  need(pending?.kind==='complete'&&p.effectId===pending.id&&p.completeIntentDigest===completeIntentDigest&&!controls.cancelled,'runner_commit');
915
1754
  if(p.type==='task-commit-intent'){
916
1755
  need(r.kind==='commit-intent'&&transaction===null
917
1756
  &&(beforeIntent.state==='approved'||beforeIntent.state==='blocked'
918
- &&['completion_checks_changed','completion_package_changed','review_package_changed'].includes(beforeIntent.code)),'runner_commit');
1757
+ &&['completion_checks_changed','completion_package_changed','review_package_changed',COMPLETE_RECHECK_CODE].includes(beforeIntent.code)),'runner_commit');
919
1758
  const c=readCommitIntent(p.commit,{owner:completion.owner,identity:pending.identity,fingerprints:completion.fingerprints});
920
1759
  const base=attemptBaseline(original,pending.identity.attempt),s=beforeIntent;
921
1760
  checkCompletion({receipt:s.receipt,registered:s.receipts.find(x=>x.id===s.receipt?.id),
@@ -973,14 +1812,24 @@ export function readRunnerHistory(raw,config,version=1) {
973
1812
  &&!transaction&&state.taskCommit?.intentDigest==null
974
1813
  &&(pending.kind!=='review'||!invocation.registration&&!joinedForInvocation)
975
1814
  &&records.slice(records.findLastIndex(row=>row.payload.type==='effect-intent')+1)
976
- .every(row=>row.payload.type==='control');
1815
+ .every(row=>row.payload.type==='control'||pending.kind==='develop'&&row.payload.type==='documentation-sync-started');
977
1816
  const reviewResultAbandon=!(config.externalModels||config.executionPolicy)&&version===3&&pending===null&&lastReview!==null
978
- &&abandonableReviewResult(state,config.reviewers[0].contexts[state.attempt-1])
1817
+ &&abandonableReviewResult(state,config.reviewers[0].contexts[state.attempt-1],answerGaps.reviewRedispatch[state.attempt])
979
1818
  ?{effectId:lastReview.effect.id,invocationId:lastReview.request.invocationId,
980
1819
  registeredDigest:lastReview.registrationRecord.digest,startedDigest:lastReview.startedRecord?.digest??null,
981
1820
  resultDigest:lastReview.resultRecord.digest}:null;
982
- return {original,session,state,pending,acceptedFixes,qaAttachment,
1821
+ const lastIntentIndex=records.findLastIndex(row=>row.payload.type==='effect-intent');
1822
+ const interruptible=pending!==null&&pendingInterruptible(pending,lastIntentIndex,records.length);
1823
+ const interruptLimit=pending!==null&&!interruptible
1824
+ &&interrupted.filter(item=>item.kind===pending.kind).length>=MAX_EFFECT_INTERRUPTIONS;
1825
+ const workerVoidable=pending!==null&&pendingWorkerVoidable(pending,lastIntentIndex,records.length);
1826
+ return {original,session,state,pending,acceptedFixes,qaAttachment,answerGaps,
983
1827
  ...(version===3?{joinedHosts,reviewerThreads,supersession,pendingAbandonable,reviewResultAbandon,
1828
+ interrupted,workers,pendingInterruptible:interruptible,pendingReviewExhausted:pendingReviewExhausted(),
1829
+ pendingResultAbandonable:pending!==null&&pendingResultAbandonable(),
1830
+ pendingInterruptLimit:interruptLimit,pendingWorkerVoidable:workerVoidable,
1831
+ pendingWorker:pending?.kind==='develop'&&pendingWorker?workerSummary(pendingWorker):null,
1832
+ pendingDocumentation:documentationOrigin(),
984
1833
  reviewReconciliation:lastReview?.reconciliation&&['unknown','pending_review'].includes(state.state)?{...reconciliationBinding(),
985
1834
  ...lastReview.reconciliation,request:lastReview.request,effect:lastReview.effect,before:lastReview.before}:null,
986
1835
  pendingObservedReview:pending?.kind==='review'&&invocation.result?.outcome==='observed'
@@ -988,6 +1837,65 @@ export function readRunnerHistory(raw,config,version=1) {
988
1837
  started:invocation.started,result:invocation.result}:null}:{}),
989
1838
  ...(version>=2?{transaction}:{})};
990
1839
  }
1840
+ // R2: each answer-gap exit has two uses per run. Once spent, the same stuck shape
1841
+ // is shown as an explicit limit block instead of falling back to an exit-less
1842
+ // unknown/reconcile: its code names the spent exit and its reason names what is
1843
+ // left (fix the root cause, then a superseding run). Derived from the journal
1844
+ // on every read, never journaled itself, so replay shows the same block.
1845
+ // A spent develop_dispatch_failed exit falls to the confirmed develop_redo, so it
1846
+ // has no limit code of its own.
1847
+ export const ANSWER_GAP_LIMIT_CODES=Object.freeze(['check_answer_retry_limit','complete_recheck_limit','develop_redo_limit',DOCUMENTATION_SYNC_LIMIT_CODE]);
1848
+ const gapLimitReason=(code,what,source)=>`${code}: ${what}(原记录 ${source})已在本运行用满 ${MAX_ANSWER_GAP_RETRIES} 次,不再自动重做。`
1849
+ +'先查清根因(会话为何一直不应答或答复不合格、宿主环境为何失败);修好后用 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做,'
1850
+ +'本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift 作为已有代码记录。';
1851
+ export function answerGapLimit(s,config,gaps={}){
1852
+ if(!['unknown','blocked'].includes(s.state))return null;
1853
+ const source=`${s.state}/${s.code}`;
1854
+ if(s.state==='unknown'&&(gaps.developRecheck??0)>=MAX_ANSWER_GAP_RETRIES&&developRecheckCode(s,config,0)!==null)
1855
+ return {code:'check_answer_retry_limit',reason:gapLimitReason('check_answer_retry_limit','开发后的检查或验证预检重跑',source)};
1856
+ if(s.state==='unknown'&&(gaps.completeRecheck??0)>=MAX_ANSWER_GAP_RETRIES&&completeRecheckable(s,0))
1857
+ return {code:'complete_recheck_limit',reason:gapLimitReason('complete_recheck_limit','完成前复查重跑',source)};
1858
+ if(s.state==='unknown'&&(gaps.documentationSync??0)>=MAX_DOCUMENTATION_SYNC_RETRIES&&documentationSyncRetryCode(s,config,0)!==null)
1859
+ return {code:DOCUMENTATION_SYNC_LIMIT_CODE,reason:documentationSyncLimitReason(source)};
1860
+ if((gaps.developRedo??0)>=MAX_DEVELOP_REDOS&&developRedoCause(s,config,0,gaps.workers??null)!==null)
1861
+ return {code:'develop_redo_limit',reason:gapLimitReason('develop_redo_limit','确认停写后的开发重发',source)};
1862
+ return null;
1863
+ }
1864
+ // Q28: the status a host would show for a replayed journal, as far as the
1865
+ // journal alone decides it. Drivers prepare answers from this (never from the
1866
+ // raw replay state, which still reads unknown/call_timeout or blocked/failed
1867
+ // for the retryable answer-gap blocks). Exits that also need a live disk check
1868
+ // (#198 develop_call_timeout, a legacy pinned dispatch failure) are projected
1869
+ // as available: preparing an answer that ends up unused is harmless, while a
1870
+ // missing one ends a real redo in host_close. Exits that need an operator
1871
+ // confirmation first (develop_redo) are not projected as retryable.
1872
+ export function projectedRunnerStatus(history,config){
1873
+ const s=history.state,gaps=history.answerGaps??{};
1874
+ const project=code=>({...s,state:'blocked',code});
1875
+ if(s.state==='blocked'&&s.code==='failed'&&developAnswerRetryable(s,config.bootstrap))return project('develop_answer_invalid');
1876
+ if(s.state==='blocked'&&s.code==='failed'){const limit=answerGapLimit(s,config,gaps);
1877
+ return limit?{...s,state:'blocked',code:limit.code,reason:limit.reason}:s;}
1878
+ // V5: a spent retryable review block with a no-result redispatch left waits
1879
+ // for the operator's stop confirmation (abandon_review → review-redispatch);
1880
+ // a fully spent one is a limit.
1881
+ if(s.state==='blocked'&&!(config.externalModels||config.executionPolicy)&&Array.isArray(config.reviewers)){
1882
+ const contextId=config.reviewers[0].contexts[s.attempt-1],records=gaps.reviewRedispatch?.[s.attempt]??0;
1883
+ if(reviewRedispatchable(s,contextId,records))return {...s,reviewRedispatchStopRequired:true,reason:reviewRedispatchStopReason(s.code)};
1884
+ if(reviewRedispatchExhausted(s,contextId,records))return {...s,code:REVIEW_REDISPATCH_LIMIT_CODE,reason:reviewRedispatchLimitReason(s.code)};
1885
+ }
1886
+ const never=reviewNeverStartedStatus(s,gaps.reviewDispatchConfirmed?.[s.attempt]??noReviewDispatchConfirmations());
1887
+ if(never!==null)return {...s,...never};
1888
+ if(s.state!=='unknown')return s;
1889
+ const recheck=developRecheckCode(s,config,gaps.developRecheck??0);
1890
+ if(recheck!==null)return project(recheck);
1891
+ if(completeRecheckable(s,gaps.completeRecheck??0))return project(COMPLETE_RECHECK_CODE);
1892
+ // Q16/Q17: a failed documentation_sync needs the operator's stop
1893
+ // confirmation (develop_redo) first, so it is not projected as retryable.
1894
+ if(s.code==='call_timeout'&&developTimeoutBasis(s,config.bootstrap)!==null)return project('develop_call_timeout');
1895
+ if(developDispatchBasis(s,config,gaps.developDispatch??0)!==null)return project(DISPATCH_RETRY_CODE);
1896
+ const limit=answerGapLimit(s,config,gaps);
1897
+ return limit?{...s,state:'blocked',code:limit.code,reason:limit.reason}:s;
1898
+ }
991
1899
  // Baseline rootDigest uses bytes of the canonical root, not JSON string encoding.
992
1900
  import {createHash} from 'node:crypto';
993
1901
  import {readQaAttachment} from './qa-attachment.mjs';