@straiffi/archon 1.12.0 → 1.12.2

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 (220) hide show
  1. package/dist/client/assets/{ActivityView-jw3H-NeG.js → ActivityView-CQlCQBZ3.js} +1 -1
  2. package/dist/client/assets/{GitHubActionsDialog-cUxcoLqx.js → GitHubActionsDialog-CMGwf-3c.js} +1 -1
  3. package/dist/client/assets/{VerificationDialog-DP8d6ddQ.js → VerificationDialog-pDAR02Iu.js} +1 -1
  4. package/dist/client/assets/{architectureDiagram-3BPJPVTR-BhWOZPeu.js → architectureDiagram-3BPJPVTR-tZWwIvJD.js} +1 -1
  5. package/dist/client/assets/{blockDiagram-GPEHLZMM-BJjjnCa4.js → blockDiagram-GPEHLZMM-9cPPW98U.js} +1 -1
  6. package/dist/client/assets/{c4Diagram-AAUBKEIU-CQldjeAF.js → c4Diagram-AAUBKEIU-Q4v6QN9V.js} +1 -1
  7. package/dist/client/assets/channel-CZJ2ieVb.js +1 -0
  8. package/dist/client/assets/{chunk-2J33WTMH-D3ULHOwT.js → chunk-2J33WTMH-DyMC2JRY.js} +1 -1
  9. package/dist/client/assets/{chunk-3OPIFGDE-zDE6O-L_.js → chunk-3OPIFGDE-BAlOU7jJ.js} +1 -1
  10. package/dist/client/assets/{chunk-5ZQYHXKU-C7W7qahQ.js → chunk-5ZQYHXKU-BMG9ktCF.js} +1 -1
  11. package/dist/client/assets/{chunk-727SXJPM-ChrtCiX1.js → chunk-727SXJPM-E2iP203L.js} +1 -1
  12. package/dist/client/assets/{chunk-AQP2D5EJ-BJcMYTJ-.js → chunk-AQP2D5EJ-HLLgiAtB.js} +1 -1
  13. package/dist/client/assets/{chunk-CSCIHK7Q-uFhZVkuh.js → chunk-CSCIHK7Q-DCUzpxPC.js} +1 -1
  14. package/dist/client/assets/{chunk-KSCS5N6A-DNE-cIoY.js → chunk-KSCS5N6A-DKHH2w_a.js} +1 -1
  15. package/dist/client/assets/{chunk-L5ZTLDWV-B1hsOai3.js → chunk-L5ZTLDWV-DxCOPCTA.js} +1 -1
  16. package/dist/client/assets/{chunk-LZXEDZCA-BFcJgF2j.js → chunk-LZXEDZCA-BbdU5fBK.js} +2 -2
  17. package/dist/client/assets/{chunk-ND2GUHAM-oXJD3VO7.js → chunk-ND2GUHAM-BIoT8VFe.js} +1 -1
  18. package/dist/client/assets/{chunk-NZK2D7GU-DRK-yrm5.js → chunk-NZK2D7GU-gAjhuVrw.js} +1 -1
  19. package/dist/client/assets/{chunk-O5CBEL6O-LQ2Eqsqb.js → chunk-O5CBEL6O-DiStlVZA.js} +1 -1
  20. package/dist/client/assets/{chunk-WU5MYG2G-DW1hrICF.js → chunk-WU5MYG2G-DaNpjUtw.js} +1 -1
  21. package/dist/client/assets/classDiagram-4FO5ZUOK-Nzi9uSR0.js +1 -0
  22. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-BDxta1PA.js +1 -0
  23. package/dist/client/assets/{dagre-BM42HDAG-DAOujANI.js → dagre-BM42HDAG-D2p3lyn5.js} +1 -1
  24. package/dist/client/assets/{diagram-2AECGRRQ-CQoEIHep.js → diagram-2AECGRRQ-BNYaTw7l.js} +1 -1
  25. package/dist/client/assets/{diagram-5GNKFQAL-ChV233vS.js → diagram-5GNKFQAL-CB7v21FT.js} +1 -1
  26. package/dist/client/assets/{diagram-KO2AKTUF-CIkpG_DX.js → diagram-KO2AKTUF-BpicXA0x.js} +1 -1
  27. package/dist/client/assets/{diagram-LMA3HP47-kxcYwQT7.js → diagram-LMA3HP47-jgdcYx5Q.js} +1 -1
  28. package/dist/client/assets/{diagram-OG6HWLK6-J5YY8urL.js → diagram-OG6HWLK6-CLexqY2c.js} +1 -1
  29. package/dist/client/assets/{erDiagram-TEJ5UH35-B5WiaYY1.js → erDiagram-TEJ5UH35-Bou1hM2V.js} +1 -1
  30. package/dist/client/assets/{flowDiagram-I6XJVG4X-BuQ2YOAf.js → flowDiagram-I6XJVG4X-BGvzcmP9.js} +1 -1
  31. package/dist/client/assets/{ganttDiagram-6RSMTGT7-BKgtiOWd.js → ganttDiagram-6RSMTGT7-ROKfHlv_.js} +1 -1
  32. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-ZT89EFiT.js → gitGraphDiagram-PVQCEYII-DUrAZKBx.js} +1 -1
  33. package/dist/client/assets/{index-X4XsGor3.js → index-7_pHbYnC.js} +117 -117
  34. package/dist/client/assets/index-BjtfHzEk.css +2 -0
  35. package/dist/client/assets/{infoDiagram-5YYISTIA-gSvPZVHC.js → infoDiagram-5YYISTIA-C5hJjVRq.js} +1 -1
  36. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-B4t29USy.js → ishikawaDiagram-YF4QCWOH-CM-aRegu.js} +1 -1
  37. package/dist/client/assets/{journeyDiagram-JHISSGLW-CVmQq2kB.js → journeyDiagram-JHISSGLW-CYoegl--.js} +1 -1
  38. package/dist/client/assets/{kanban-definition-UN3LZRKU-b5O5VKrr.js → kanban-definition-UN3LZRKU-Bfpw046h.js} +1 -1
  39. package/dist/client/assets/{line-D6RHOz5K.js → line-CTs-0Pcn.js} +1 -1
  40. package/dist/client/assets/{mermaid-parser.core-Cwq8hOlE.js → mermaid-parser.core--Hdz1E5S.js} +1 -1
  41. package/dist/client/assets/{mermaid.core-D6EV8_i4.js → mermaid.core-B7_vS1v6.js} +3 -3
  42. package/dist/client/assets/{mindmap-definition-RKZ34NQL-DivmXvOE.js → mindmap-definition-RKZ34NQL-BXNBNJ-i.js} +1 -1
  43. package/dist/client/assets/{pieDiagram-4H26LBE5-Bfemol_L.js → pieDiagram-4H26LBE5-DH5p-UpG.js} +1 -1
  44. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-Cas_rlHH.js → quadrantDiagram-W4KKPZXB-DCSiXMJI.js} +1 -1
  45. package/dist/client/assets/{requirementDiagram-4Y6WPE33-BM8zTE_j.js → requirementDiagram-4Y6WPE33-DLK6MoZE.js} +1 -1
  46. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-B6mxh_XP.js → sankeyDiagram-5OEKKPKP-2drxgiMr.js} +1 -1
  47. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-CYnnYFdz.js → sequenceDiagram-3UESZ5HK-Cy0uD8Yt.js} +1 -1
  48. package/dist/client/assets/{stateDiagram-AJRCARHV-DzYqaPIm.js → stateDiagram-AJRCARHV-Cs9IOXLg.js} +1 -1
  49. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-DqucoZIy.js +1 -0
  50. package/dist/client/assets/{timeline-definition-PNZ67QCA-IsLLwa3b.js → timeline-definition-PNZ67QCA-B_edXdC-.js} +1 -1
  51. package/dist/client/assets/{vennDiagram-CIIHVFJN-Dq0WBBOy.js → vennDiagram-CIIHVFJN-CATf-LeJ.js} +1 -1
  52. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-DD_3WNIO.js → wardleyDiagram-YWT4CUSO-BHhpeDY_.js} +1 -1
  53. package/dist/client/assets/{xychartDiagram-2RQKCTM6-Ds-PWhnZ.js → xychartDiagram-2RQKCTM6-99Q3NPyF.js} +1 -1
  54. package/dist/client/index.html +2 -2
  55. package/dist/server/db.js +6 -1
  56. package/dist/server/db.js.map +1 -1
  57. package/dist/server/epicRoutes.js +2 -1
  58. package/dist/server/epicRoutes.js.map +1 -1
  59. package/dist/server/index.js +10 -7
  60. package/dist/server/index.js.map +1 -1
  61. package/dist/server/lib/agent.js +9 -1
  62. package/dist/server/lib/agent.js.map +1 -1
  63. package/dist/server/lib/automationProgression.js +12 -2
  64. package/dist/server/lib/automationProgression.js.map +1 -1
  65. package/dist/server/lib/buildCompletionContinuation.js +20 -7
  66. package/dist/server/lib/buildCompletionContinuation.js.map +1 -1
  67. package/dist/server/lib/buildCompletionEvidence.js +62 -0
  68. package/dist/server/lib/buildCompletionEvidence.js.map +1 -0
  69. package/dist/server/lib/buildCompletionEvidenceReader.js +38 -0
  70. package/dist/server/lib/buildCompletionEvidenceReader.js.map +1 -0
  71. package/dist/server/lib/buildFlow.js +4 -3
  72. package/dist/server/lib/buildFlow.js.map +1 -1
  73. package/dist/server/lib/buildTicketCommit.js +52 -1
  74. package/dist/server/lib/buildTicketCommit.js.map +1 -1
  75. package/dist/server/lib/bundleBranchNames.js +9 -0
  76. package/dist/server/lib/bundleBranchNames.js.map +1 -0
  77. package/dist/server/lib/bundleContextControls.js +205 -0
  78. package/dist/server/lib/bundleContextControls.js.map +1 -0
  79. package/dist/server/lib/bundleContextEnrollments.js +216 -0
  80. package/dist/server/lib/bundleContextEnrollments.js.map +1 -0
  81. package/dist/server/lib/bundleContextPublication.js +467 -0
  82. package/dist/server/lib/bundleContextPublication.js.map +1 -0
  83. package/dist/server/lib/bundleContextRecoveryStore.js +199 -0
  84. package/dist/server/lib/bundleContextRecoveryStore.js.map +1 -0
  85. package/dist/server/lib/bundleContextSchema.js +359 -0
  86. package/dist/server/lib/bundleContextSchema.js.map +1 -0
  87. package/dist/server/lib/bundleContextSources.js +206 -0
  88. package/dist/server/lib/bundleContextSources.js.map +1 -0
  89. package/dist/server/lib/bundleFollowUpRequest.js +19 -0
  90. package/dist/server/lib/bundleFollowUpRequest.js.map +1 -0
  91. package/dist/server/lib/checkRunner.js +1 -1
  92. package/dist/server/lib/checkRunner.js.map +1 -1
  93. package/dist/server/lib/checkpointExecution.js +30 -0
  94. package/dist/server/lib/checkpointExecution.js.map +1 -0
  95. package/dist/server/lib/epicAdmission.js +41 -30
  96. package/dist/server/lib/epicAdmission.js.map +1 -1
  97. package/dist/server/lib/epicAttemptBuildRecovery.js +16 -8
  98. package/dist/server/lib/epicAttemptBuildRecovery.js.map +1 -1
  99. package/dist/server/lib/epicAttemptReconciliation.js +91 -1
  100. package/dist/server/lib/epicAttemptReconciliation.js.map +1 -1
  101. package/dist/server/lib/epicAutomation.js +1 -1
  102. package/dist/server/lib/epicAutomation.js.map +1 -1
  103. package/dist/server/lib/epicCheckpointAdmission.js +5 -2
  104. package/dist/server/lib/epicCheckpointAdmission.js.map +1 -1
  105. package/dist/server/lib/epicCheckpointAutomationIntegration.js +31 -2
  106. package/dist/server/lib/epicCheckpointAutomationIntegration.js.map +1 -1
  107. package/dist/server/lib/epicCheckpointSourceIdentity.js +67 -0
  108. package/dist/server/lib/epicCheckpointSourceIdentity.js.map +1 -0
  109. package/dist/server/lib/epicCheckpointTicketIntegration.js +12 -1
  110. package/dist/server/lib/epicCheckpointTicketIntegration.js.map +1 -1
  111. package/dist/server/lib/epicExecutionPlans.js +7 -0
  112. package/dist/server/lib/epicExecutionPlans.js.map +1 -1
  113. package/dist/server/lib/epicExecutionRecovery.js +436 -31
  114. package/dist/server/lib/epicExecutionRecovery.js.map +1 -1
  115. package/dist/server/lib/epicMaterialization.js +49 -17
  116. package/dist/server/lib/epicMaterialization.js.map +1 -1
  117. package/dist/server/lib/epicMergedDelivery.js +21 -0
  118. package/dist/server/lib/epicMergedDelivery.js.map +1 -0
  119. package/dist/server/lib/epicOperations.js +23 -7
  120. package/dist/server/lib/epicOperations.js.map +1 -1
  121. package/dist/server/lib/epicOrchestration.js +74 -60
  122. package/dist/server/lib/epicOrchestration.js.map +1 -1
  123. package/dist/server/lib/epicPlanningRestartRecovery.js +101 -0
  124. package/dist/server/lib/epicPlanningRestartRecovery.js.map +1 -0
  125. package/dist/server/lib/epicPlanningStartupRecovery.js +28 -0
  126. package/dist/server/lib/epicPlanningStartupRecovery.js.map +1 -0
  127. package/dist/server/lib/epicPlanningStore.js +3 -7
  128. package/dist/server/lib/epicPlanningStore.js.map +1 -1
  129. package/dist/server/lib/epicPlanningWorkspace.js +303 -0
  130. package/dist/server/lib/epicPlanningWorkspace.js.map +1 -0
  131. package/dist/server/lib/epicPostMergeEvidence.js +4 -6
  132. package/dist/server/lib/epicPostMergeEvidence.js.map +1 -1
  133. package/dist/server/lib/epicPullRequestExternalOwnership.js +10 -2
  134. package/dist/server/lib/epicPullRequestExternalOwnership.js.map +1 -1
  135. package/dist/server/lib/epicReconciliation.js +15 -13
  136. package/dist/server/lib/epicReconciliation.js.map +1 -1
  137. package/dist/server/lib/epicRecovery.js +2 -0
  138. package/dist/server/lib/epicRecovery.js.map +1 -1
  139. package/dist/server/lib/epicReferences.js +24 -3
  140. package/dist/server/lib/epicReferences.js.map +1 -1
  141. package/dist/server/lib/epicSchema.js +11 -1
  142. package/dist/server/lib/epicSchema.js.map +1 -1
  143. package/dist/server/lib/epicSettings.js +73 -0
  144. package/dist/server/lib/epicSettings.js.map +1 -0
  145. package/dist/server/lib/epicStartState.js +16 -0
  146. package/dist/server/lib/epicStartState.js.map +1 -0
  147. package/dist/server/lib/epicStartStateSchema.js +84 -0
  148. package/dist/server/lib/epicStartStateSchema.js.map +1 -0
  149. package/dist/server/lib/epicTicketBuilders.js +60 -0
  150. package/dist/server/lib/epicTicketBuilders.js.map +1 -0
  151. package/dist/server/lib/epics.js +12 -29
  152. package/dist/server/lib/epics.js.map +1 -1
  153. package/dist/server/lib/executionRunAuthority.js +1 -43
  154. package/dist/server/lib/executionRunAuthority.js.map +1 -1
  155. package/dist/server/lib/followUpExecutionLineage.js +25 -0
  156. package/dist/server/lib/followUpExecutionLineage.js.map +1 -0
  157. package/dist/server/lib/httpError.js +3 -1
  158. package/dist/server/lib/httpError.js.map +1 -1
  159. package/dist/server/lib/i18n/epicExecution.js +29 -0
  160. package/dist/server/lib/i18n/epicExecution.js.map +1 -1
  161. package/dist/server/lib/i18n/epicPlanning.js +12 -0
  162. package/dist/server/lib/i18n/epicPlanning.js.map +1 -1
  163. package/dist/server/lib/i18n/resources.js +5 -0
  164. package/dist/server/lib/i18n/resources.js.map +1 -1
  165. package/dist/server/lib/opencodeApprovalTransport.js +4 -1
  166. package/dist/server/lib/opencodeApprovalTransport.js.map +1 -1
  167. package/dist/server/lib/planningSessionAuthority.js +38 -0
  168. package/dist/server/lib/planningSessionAuthority.js.map +1 -0
  169. package/dist/server/lib/projects.js +12 -5
  170. package/dist/server/lib/projects.js.map +1 -1
  171. package/dist/server/lib/providerSessionAuthority.js +87 -0
  172. package/dist/server/lib/providerSessionAuthority.js.map +1 -0
  173. package/dist/server/lib/providerSessionIdentity.js +41 -0
  174. package/dist/server/lib/providerSessionIdentity.js.map +1 -0
  175. package/dist/server/lib/reviewCompletionContinuation.js +115 -0
  176. package/dist/server/lib/reviewCompletionContinuation.js.map +1 -0
  177. package/dist/server/lib/reviewRepairCompletion.js +16 -1
  178. package/dist/server/lib/reviewRepairCompletion.js.map +1 -1
  179. package/dist/server/lib/reviewRepairReconciliation.js +4 -1
  180. package/dist/server/lib/reviewRepairReconciliation.js.map +1 -1
  181. package/dist/server/lib/specBundleGroups.js +3 -3
  182. package/dist/server/lib/specBundleGroups.js.map +1 -1
  183. package/dist/server/lib/ticketAutomationCommit.js +1 -0
  184. package/dist/server/lib/ticketAutomationCommit.js.map +1 -1
  185. package/dist/server/lib/ticketFollowUpOperations.js +16 -4
  186. package/dist/server/lib/ticketFollowUpOperations.js.map +1 -1
  187. package/dist/server/lib/tickets.js +14 -2
  188. package/dist/server/lib/tickets.js.map +1 -1
  189. package/dist/server/workers/build.js +17 -2
  190. package/dist/server/workers/build.js.map +1 -1
  191. package/dist/server/workers/epicArtifactContract.js +2 -1
  192. package/dist/server/workers/epicArtifactContract.js.map +1 -1
  193. package/dist/server/workers/epicConversation.js +1 -0
  194. package/dist/server/workers/epicConversation.js.map +1 -1
  195. package/dist/server/workers/epicPlanning.js +32 -10
  196. package/dist/server/workers/epicPlanning.js.map +1 -1
  197. package/dist/server/workers/epicSpecArtifactContract.js +1 -0
  198. package/dist/server/workers/epicSpecArtifactContract.js.map +1 -1
  199. package/dist/server/workers/followUp.js +15 -2
  200. package/dist/server/workers/followUp.js.map +1 -1
  201. package/dist/server/workers/plan.js +8 -2
  202. package/dist/server/workers/plan.js.map +1 -1
  203. package/dist/server/workers/planFollowUp.js +4 -0
  204. package/dist/server/workers/planFollowUp.js.map +1 -1
  205. package/dist/server/workers/review.js +5 -0
  206. package/dist/server/workers/review.js.map +1 -1
  207. package/dist/server/workers/specArtifactContract.js +2 -0
  208. package/dist/server/workers/specArtifactContract.js.map +1 -1
  209. package/dist/shared/bundleContext.js +72 -0
  210. package/dist/shared/bundleContext.js.map +1 -0
  211. package/dist/shared/epics.js +1 -0
  212. package/dist/shared/epics.js.map +1 -1
  213. package/package.json +1 -1
  214. package/dist/client/assets/channel-2Q4_MKqQ.js +0 -1
  215. package/dist/client/assets/classDiagram-4FO5ZUOK-DlhYAzjF.js +0 -1
  216. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DZsqIDkO.js +0 -1
  217. package/dist/client/assets/index-DTsS9gs9.css +0 -2
  218. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-BDRmC9KJ.js +0 -1
  219. package/dist/server/lib/epicStepCheckApplicability.js +0 -19
  220. package/dist/server/lib/epicStepCheckApplicability.js.map +0 -1
@@ -1,11 +1,12 @@
1
1
  import db from '../db.js';
2
2
  import { resolveBuildCheckpointSuccessor } from './buildCheckpointSuccessor.js';
3
- import { getEpic } from './epics.js';
4
- import { getExecutionRun, listExecutionRunLinks, appendLifecycleEvent } from './executionRuns.js';
3
+ import { getEpic, getEpicAttempt } from './epics.js';
4
+ import { getExecutionRun, listExecutionRunLinks, appendLifecycleEvent, transitionExecutionRun } from './executionRuns.js';
5
5
  import { getEpicCheckpointContinuation } from './epicCheckpointContinuations.js';
6
6
  import { assertEpicCheckpointPlanOwnership } from './epicCheckpointContinuations.js';
7
- import { assertEpicBuildAdmission } from './epicAdmission.js';
8
- import { resolveBuildTicketCommitCheckpointLineage } from './buildTicketCommit.js';
7
+ import { assertEpicBuildAdmission, resolveEpicAdmission } from './epicAdmission.js';
8
+ import { resolveBuildTicketCommitCheckpointLineage, resolveCanonicalCheckpointBuildRunId } from './buildTicketCommit.js';
9
+ import { withCheckpointExecution } from './checkpointExecution.js';
9
10
  import { recoverProjectEpicCheckpoints } from './epicRecovery.js';
10
11
  import { getTicket, resolveTicketWorkerKey } from './tickets.js';
11
12
  import { getEffectiveProject } from './projects.js';
@@ -15,9 +16,13 @@ import { isLatestTicketBuildSource, finalizePostBuildCheckTicket, markPostBuildC
15
16
  import { getCheckBatchDetails } from './checkRuns.js';
16
17
  import { normalizeProjectMemorySuggestions } from './projectMemorySuggestions.js';
17
18
  import { validateWorkflowContext } from './types.js';
18
- import { completeAutomationProgression, interruptAutomationProgression, runAutomationProgression, waitAutomationProgression } from './automationProgression.js';
19
+ import { completeAutomationProgression, interruptAutomationProgression, resolveProgressionForChild, runAutomationProgression, waitAutomationProgression } from './automationProgression.js';
19
20
  import { getActiveAutomationChild } from './activeAutomationChild.js';
20
21
  import { listEpicOwnedRuns } from './epicOwnedRuns.js';
22
+ import { getActiveReviewRepairIteration, getReviewRepairIterationByVerification } from './reviewRepairIterations.js';
23
+ import { epicExecutionMessage } from './i18n/epicExecution.js';
24
+ import { readEpicMergedDelivery } from './epicMergedDelivery.js';
25
+ import { getReviewCompletionContinuation, resumeReviewCompletionContinuation } from './reviewCompletionContinuation.js';
21
26
  const recoveringSources = new Set();
22
27
  const busy = new Map();
23
28
  const ownRecovery = (projectId, epicId) => {
@@ -45,20 +50,316 @@ const independentlyPaused = (projectId, bundleId) => {
45
50
  const state = bundleId ? getBundleAutomationState(projectId, bundleId) : null;
46
51
  return state?.automation_pause_reason_code === 'manual_transition' || state?.automation_paused_code === 'open_questions';
47
52
  };
53
+ const canFinalizeSource = (projectId, epicId, source) => {
54
+ if (eligible(projectId, epicId)) {
55
+ return true;
56
+ }
57
+ const ticketId = listExecutionRunLinks(projectId, source.id).find(link => link.entity_type === 'ticket' && link.relationship === 'primary')?.entity_id;
58
+ const ticket = ticketId ? getTicket(ticketId) : null;
59
+ const admission = ticket?.worktree_bundle_id ? resolveEpicAdmission({ projectId, bundleId: ticket.worktree_bundle_id,
60
+ kind: 'finalization', executionRunId: source.id }) : null;
61
+ return admission?.allowed === true && admission.epicId === epicId;
62
+ };
63
+ const latestTicketBuild = (projectId, ticketId) => db.prepare(`SELECT run.id FROM execution_runs run
64
+ JOIN execution_run_links link ON link.execution_run_id = run.id AND link.project_id = run.project_id
65
+ WHERE run.project_id = ? AND link.entity_type = 'ticket' AND link.entity_id = ? AND link.relationship = 'primary'
66
+ AND run.kind IN ('build', 'build_follow_up') ORDER BY run.rowid DESC LIMIT 1`)
67
+ .get(projectId, ticketId);
68
+ const recoveredWorkflowContext = (source) => validateWorkflowContext(Object.fromEntries(Object.entries(source.metadata ?? {}).filter((entry) => typeof entry[1] === 'string')));
69
+ // Follow actual execution ancestry, rather than bundle or contextual Epic links.
70
+ // A completed attempt root is also the admission fence for queued recovery work.
71
+ const belongsToCompletedAttempt = (projectId, epicId, runId) => {
72
+ const roots = db.prepare(`WITH RECURSIVE ancestors(id, parent_run_id, status) AS (
73
+ SELECT id, parent_run_id, status FROM execution_runs WHERE project_id = ? AND id = ?
74
+ UNION SELECT parent.id, parent.parent_run_id, parent.status FROM execution_runs parent
75
+ JOIN ancestors child ON child.parent_run_id = parent.id WHERE parent.project_id = ?
76
+ ) SELECT id, status FROM ancestors WHERE id LIKE 'epic-attempt:%'`)
77
+ .all(projectId, runId, projectId);
78
+ return roots.some(root => {
79
+ const attempt = getEpicAttempt(root.id.slice('epic-attempt:'.length), epicId, projectId);
80
+ // Resume routes may run recovery before orchestration consumes the receipt.
81
+ // Already-observed delivery must never restart its historical workers.
82
+ return root.status === 'completed' || Boolean(attempt && readEpicMergedDelivery(attempt));
83
+ });
84
+ };
85
+ const deferInterruptedRecovery = (projectId, epicId, source, reason, io) => {
86
+ if (!db.prepare(`SELECT 1 FROM lifecycle_events WHERE project_id = ? AND execution_run_id = ?
87
+ AND event_type = 'epic_execution_recovery_deferred' AND json_extract(metadata_json, '$.reason') = ?`)
88
+ .get(projectId, source.id, reason)) {
89
+ appendLifecycleEvent({ projectId, runId: source.id, eventType: 'epic_execution_recovery_deferred',
90
+ message: reason, metadata: { epic_id: epicId, reason } }, io);
91
+ }
92
+ };
93
+ const resumeInterruptedBuild = async (projectId, epicId, source, io) => {
94
+ const ticketId = listExecutionRunLinks(projectId, source.id).find(link => link.entity_type === 'ticket' && link.relationship === 'primary')?.entity_id;
95
+ const ticket = ticketId ? getTicket(ticketId) : null;
96
+ const key = ticket ? resolveTicketWorkerKey(ticket, 'build') : null;
97
+ const state = ticket?.worktree_bundle_id ? getBundleAutomationState(projectId, ticket.worktree_bundle_id) : null;
98
+ const neverStarted = source.started_at === null && source.kind === 'build';
99
+ const recoverableTicket = (candidate) => neverStarted
100
+ ? candidate.state === 'build' && candidate.agent_status !== 'stopped'
101
+ : ['build', 'review'].includes(candidate.state) && ['error', 'running'].includes(candidate.agent_status ?? '');
102
+ if (!ticket || ticket.project_id !== projectId || !key || !['build', 'review'].includes(ticket.state)
103
+ || !recoverableTicket(ticket) || independentlyPaused(projectId, ticket.worktree_bundle_id)
104
+ || (state?.automation_pause_reason_code && state.automation_pause_reason_code !== 'server_restart')
105
+ || latestTicketBuild(projectId, ticket.id)?.id !== source.id) {
106
+ return { dispatched: 0, busy: 0 };
107
+ }
108
+ if (!ticket.session_id && !neverStarted) {
109
+ deferInterruptedRecovery(projectId, epicId, source, epicExecutionMessage('recoveryBuildSessionMissing'), io);
110
+ return { dispatched: 0, busy: 0 };
111
+ }
112
+ const recoveryKey = `${projectId}:${source.id}`;
113
+ if (isRunning(key) || recoveringSources.has(recoveryKey)) {
114
+ return { dispatched: 0, busy: 1 };
115
+ }
116
+ recoveringSources.add(recoveryKey);
117
+ try {
118
+ const buildWorker = await import('../workers/build.js');
119
+ const { getBuildSequenceIdForTicket } = await import('./buildSequences.js');
120
+ if (!eligible(projectId, epicId) || belongsToCompletedAttempt(projectId, epicId, source.id)) {
121
+ return { dispatched: 0, busy: 0 };
122
+ }
123
+ // Failed startup sequence ownership can be restored only from its exact
124
+ // accepted activation; never adopt another sequence or revive completed items.
125
+ const retained = db.prepare(`SELECT sequence.id, sequence.status, item.status AS item_status FROM build_sequences sequence
126
+ JOIN build_sequence_tickets item ON item.build_sequence_id = sequence.id
127
+ WHERE sequence.project_id = ? AND sequence.worktree_bundle_id = ? AND item.ticket_id = ?
128
+ AND item.activation_execution_run_id = ? AND sequence.status IN ('active', 'failed')`)
129
+ .get(projectId, ticket.worktree_bundle_id, ticket.id, source.id);
130
+ const sequenceId = retained?.id ?? getBuildSequenceIdForTicket(ticket.id);
131
+ if (!retained && ticket.worktree_bundle_id) {
132
+ const activeItem = sequenceId ? db.prepare(`SELECT status, activation_execution_run_id FROM build_sequence_tickets
133
+ WHERE build_sequence_id = ? AND ticket_id = ?`).get(sequenceId, ticket.id) : undefined;
134
+ if (activeItem?.status !== 'active' || (activeItem.activation_execution_run_id
135
+ && !listEpicOwnedRuns(projectId, epicId).some(run => run.id === activeItem.activation_execution_run_id))) {
136
+ return { dispatched: 0, busy: 0 };
137
+ }
138
+ }
139
+ if (retained && ((retained.status === 'active' && retained.item_status !== 'active')
140
+ || (retained.status === 'failed' && retained.item_status !== 'failed'))) {
141
+ return { dispatched: 0, busy: 0 };
142
+ }
143
+ const schedule = neverStarted ? buildWorker.startBuild : buildWorker.resumeBuild;
144
+ const scheduling = schedule(ticket, io, {
145
+ sequenceId, initiation: { initiator: 'automation', causalParentRunId: source.id, workflowContext: recoveredWorkflowContext(source) },
146
+ accept: () => {
147
+ const live = getTicket(ticket.id);
148
+ const pause = live?.worktree_bundle_id ? getBundleAutomationState(projectId, live.worktree_bundle_id) : null;
149
+ const liveSource = getExecutionRun(projectId, source.id);
150
+ if (!eligible(projectId, epicId) || belongsToCompletedAttempt(projectId, epicId, source.id) || !live || live.project_id !== projectId || (!neverStarted && !live.session_id)
151
+ || independentlyPaused(projectId, live.worktree_bundle_id)
152
+ || !recoverableTicket(live)
153
+ || (pause?.automation_pause_reason_code && pause.automation_pause_reason_code !== 'server_restart')
154
+ || latestTicketBuild(projectId, ticket.id)?.id !== source.id
155
+ || liveSource?.status !== 'interrupted' || liveSource.failure?.code !== 'server_restarted'
156
+ || (neverStarted && liveSource.started_at !== null)
157
+ || !listEpicOwnedRuns(projectId, epicId).some(run => run.id === source.id)) {
158
+ throw new Error(epicExecutionMessage('recoveryBuildUnavailable'));
159
+ }
160
+ if (retained) {
161
+ const owned = db.prepare(`SELECT sequence.status, item.status AS item_status, item.activation_execution_run_id
162
+ FROM build_sequences sequence JOIN build_sequence_tickets item ON item.build_sequence_id = sequence.id
163
+ WHERE sequence.id = ? AND sequence.project_id = ? AND sequence.worktree_bundle_id = ? AND item.ticket_id = ?`)
164
+ .get(retained.id, projectId, live.worktree_bundle_id, live.id);
165
+ if (owned?.status !== retained.status || owned.item_status !== retained.item_status || owned.activation_execution_run_id !== source.id) {
166
+ throw new Error(epicExecutionMessage('recoveryBuildSequenceOwnershipChanged'));
167
+ }
168
+ }
169
+ else if (live.worktree_bundle_id) {
170
+ const owned = db.prepare(`SELECT sequence.status, item.status AS item_status, item.activation_execution_run_id
171
+ FROM build_sequences sequence JOIN build_sequence_tickets item ON item.build_sequence_id = sequence.id
172
+ WHERE sequence.id = ? AND sequence.project_id = ? AND sequence.worktree_bundle_id = ? AND item.ticket_id = ?`)
173
+ .get(sequenceId, projectId, live.worktree_bundle_id, live.id);
174
+ if (owned?.status !== 'active' || owned.item_status !== 'active' || (owned.activation_execution_run_id
175
+ && !listEpicOwnedRuns(projectId, epicId).some(run => run.id === owned.activation_execution_run_id))) {
176
+ throw new Error(epicExecutionMessage('recoveryBuildSequenceOwnershipChanged'));
177
+ }
178
+ }
179
+ let compensate;
180
+ if (retained?.status === 'failed') {
181
+ if (retained.item_status !== 'failed' || db.prepare(`SELECT 1 FROM build_sequences WHERE project_id = ?
182
+ AND worktree_bundle_id = ? AND status = 'active' AND id <> ?`).get(projectId, live.worktree_bundle_id, retained.id)) {
183
+ throw new Error(epicExecutionMessage('recoveryBuildSequenceManual'));
184
+ }
185
+ const sequence = db.prepare('SELECT updated_at FROM build_sequences WHERE id = ?').get(retained.id);
186
+ const items = db.prepare(`SELECT ticket_id, status, finished_at FROM build_sequence_tickets WHERE build_sequence_id = ?
187
+ AND (ticket_id = ? OR (status = 'cancelled' AND activation_execution_run_id IS NULL
188
+ AND finished_at = (SELECT finished_at FROM build_sequence_tickets WHERE build_sequence_id = ? AND ticket_id = ?)
189
+ AND position > (SELECT position FROM build_sequence_tickets WHERE build_sequence_id = ? AND ticket_id = ?)))`)
190
+ .all(retained.id, live.id, retained.id, live.id, retained.id, live.id);
191
+ // Only the startup-cancelled tail with the same interruption timestamp
192
+ // is eligible; independently cancelled items retain their authority.
193
+ db.prepare(`UPDATE build_sequence_tickets SET status = 'queued', finished_at = NULL
194
+ WHERE build_sequence_id = ? AND ticket_id IN (${items.filter(item => item.ticket_id !== live.id).map(() => '?').join(', ') || 'NULL'})`)
195
+ .run(retained.id, ...items.filter(item => item.ticket_id !== live.id).map(item => item.ticket_id));
196
+ db.prepare("UPDATE build_sequences SET status = 'active', updated_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'failed'").run(retained.id);
197
+ db.prepare("UPDATE build_sequence_tickets SET status = 'active', finished_at = NULL WHERE build_sequence_id = ? AND ticket_id = ? AND status = 'failed'").run(retained.id, live.id);
198
+ compensate = () => {
199
+ db.prepare("UPDATE build_sequences SET status = 'failed', updated_at = ? WHERE id = ?").run(sequence.updated_at, retained.id);
200
+ for (const item of items) {
201
+ db.prepare('UPDATE build_sequence_tickets SET status = ?, finished_at = ? WHERE build_sequence_id = ? AND ticket_id = ?')
202
+ .run(item.status, item.finished_at, retained.id, item.ticket_id);
203
+ }
204
+ };
205
+ }
206
+ if (neverStarted && sequenceId) {
207
+ const binding = db.prepare(`SELECT activation_execution_run_id FROM build_sequence_tickets
208
+ WHERE build_sequence_id = ? AND ticket_id = ? AND status = 'active'`)
209
+ .get(sequenceId, live.id);
210
+ if (!binding || (binding.activation_execution_run_id && binding.activation_execution_run_id !== source.id)) {
211
+ throw new Error(epicExecutionMessage('recoveryBuildActivationMismatch'));
212
+ }
213
+ // Fresh admission binds a new run; release only the proven never-started
214
+ // activation inside that same admission transaction, retaining its history.
215
+ const changed = db.prepare(`UPDATE build_sequence_tickets SET activation_execution_run_id = NULL
216
+ WHERE build_sequence_id = ? AND ticket_id = ? AND status = 'active' AND activation_execution_run_id IS ?`)
217
+ .run(sequenceId, live.id, binding.activation_execution_run_id);
218
+ if (changed.changes !== 1) {
219
+ throw new Error(epicExecutionMessage('recoveryBuildActivationChanged'));
220
+ }
221
+ const compensateSequence = compensate;
222
+ compensate = () => {
223
+ db.prepare('UPDATE build_sequence_tickets SET activation_execution_run_id = ? WHERE build_sequence_id = ? AND ticket_id = ?')
224
+ .run(binding.activation_execution_run_id, sequenceId, live.id);
225
+ compensateSequence?.();
226
+ };
227
+ }
228
+ return { ticket: live, sequenceId, compensate };
229
+ },
230
+ });
231
+ if (!scheduling.accepted && scheduling.reason !== 'busy') {
232
+ deferInterruptedRecovery(projectId, epicId, source, epicExecutionMessage('recoveryBuildSchedulingFailed', { error: scheduling.error }), io);
233
+ }
234
+ return { dispatched: scheduling.accepted ? 1 : 0, busy: 0 };
235
+ }
236
+ catch (error) {
237
+ deferInterruptedRecovery(projectId, epicId, source, epicExecutionMessage('recoveryBuildAttentionRequired', {
238
+ error: error instanceof Error ? error.message : String(error),
239
+ }), io);
240
+ return { dispatched: 0, busy: 0 };
241
+ }
242
+ finally {
243
+ recoveringSources.delete(recoveryKey);
244
+ }
245
+ };
246
+ const resumeInterruptedReview = async (projectId, epicId, source, io) => {
247
+ const ticketId = listExecutionRunLinks(projectId, source.id).find(link => link.entity_type === 'ticket' && link.relationship === 'primary')?.entity_id;
248
+ const ticket = ticketId ? getTicket(ticketId) : null;
249
+ const latest = () => db.prepare(`SELECT run.id FROM execution_runs run JOIN execution_run_links link
250
+ ON link.execution_run_id = run.id AND link.project_id = run.project_id WHERE run.project_id = ?
251
+ AND link.entity_type = 'ticket' AND link.entity_id = ? AND link.relationship = 'primary'
252
+ AND run.kind IN ('review', 'build', 'build_follow_up') ORDER BY run.rowid DESC LIMIT 1`).get(projectId, ticketId);
253
+ if (!ticket || ticket.project_id !== projectId || latest()?.id !== source.id
254
+ || independentlyPaused(projectId, ticket.worktree_bundle_id)) {
255
+ return { dispatched: 0, busy: 0 };
256
+ }
257
+ const key = resolveTicketWorkerKey(ticket, 'review');
258
+ const recoveryKey = `${projectId}:${source.id}`;
259
+ if (key && (isRunning(key) || recoveringSources.has(recoveryKey))) {
260
+ return { dispatched: 0, busy: 1 };
261
+ }
262
+ recoveringSources.add(recoveryKey);
263
+ try {
264
+ const { startReview, resolveReviewContinuation } = await import('../workers/review.js');
265
+ if (!eligible(projectId, epicId)) {
266
+ return { dispatched: 0, busy: 0 };
267
+ }
268
+ const assertRecoverable = () => {
269
+ const live = getTicket(ticket.id);
270
+ const liveSource = getExecutionRun(projectId, source.id);
271
+ const state = live?.worktree_bundle_id ? getBundleAutomationState(projectId, live.worktree_bundle_id) : null;
272
+ if (!eligible(projectId, epicId) || belongsToCompletedAttempt(projectId, epicId, source.id) || !live || live.project_id !== projectId || live.state !== 'review'
273
+ || live.review_follow_up_active || !['error', 'running'].includes(live.agent_status ?? '')
274
+ || !live.worktree_bundle_id || independentlyPaused(projectId, live.worktree_bundle_id)
275
+ || (state?.automation_pause_reason_code && !['server_restart'].includes(state.automation_pause_reason_code))
276
+ || latest()?.id !== source.id || liveSource?.status !== 'interrupted' || liveSource.failure?.code !== 'server_restarted'
277
+ || !listEpicOwnedRuns(projectId, epicId).some(run => run.id === source.id)) {
278
+ throw new Error(epicExecutionMessage('recoveryReviewContextChanged'));
279
+ }
280
+ const progression = resolveProgressionForChild({ projectId, bundleId: live.worktree_bundle_id, childRunId: source.id });
281
+ if (getActiveAutomationChild(projectId, progression.id)) {
282
+ throw new Error(epicExecutionMessage('recoveryReviewProgressionBusy'));
283
+ }
284
+ // Verification carries gate/workspace evidence and a durable iteration pointer.
285
+ // Generic Review scheduling must not bypass ledger reconciliation or create a second loop.
286
+ if (getReviewRepairIterationByVerification(projectId, source.id) || getActiveReviewRepairIteration(projectId, progression.id)
287
+ || state?.fix_loop_active) {
288
+ throw new Error(epicExecutionMessage('recoveryReviewVerificationReconciliation'));
289
+ }
290
+ return { live, progression };
291
+ };
292
+ const { progression } = assertRecoverable();
293
+ const scheduling = startReview(ticket, io, {
294
+ initiation: { initiator: 'automation', causalParentRunId: progression.id, retrySourceRunId: source.id,
295
+ workflowContext: recoveredWorkflowContext(source) },
296
+ continuation: resolveReviewContinuation(source.id),
297
+ accept: () => {
298
+ const current = assertRecoverable();
299
+ if (current.progression.id !== progression.id) {
300
+ throw new Error(epicExecutionMessage('recoveryReviewProgressionOwnershipChanged'));
301
+ }
302
+ const wasWaiting = current.progression.status === 'waiting';
303
+ if (wasWaiting) {
304
+ runAutomationProgression({ projectId, bundleId: current.live.worktree_bundle_id, progressionRunId: progression.id });
305
+ }
306
+ else if (current.progression.status !== 'running') {
307
+ throw new Error(epicExecutionMessage('recoveryReviewProgressionUnavailable'));
308
+ }
309
+ return { ticket: current.live, compensate: wasWaiting ? () => {
310
+ waitAutomationProgression({ projectId, bundleId: current.live.worktree_bundle_id, progressionRunId: progression.id,
311
+ pauseCode: 'review', pauseReason: epicExecutionMessage('recoveryReviewSchedulingPause'),
312
+ reasonCode: 'server_restart', pausedStageRunId: source.id, broadcaster: io });
313
+ } : undefined };
314
+ },
315
+ });
316
+ if (!scheduling.accepted) {
317
+ if (scheduling.reason !== 'busy') {
318
+ deferInterruptedRecovery(projectId, epicId, source, epicExecutionMessage('recoveryReviewSchedulingFailed', { error: scheduling.error }), io);
319
+ }
320
+ return { dispatched: 0, busy: scheduling.reason === 'busy' ? 1 : 0 };
321
+ }
322
+ return { dispatched: 1, busy: 0 };
323
+ }
324
+ catch (error) {
325
+ deferInterruptedRecovery(projectId, epicId, source, epicExecutionMessage('recoveryReviewAttentionRequired', {
326
+ reason: error instanceof Error ? error.message : String(error),
327
+ }), io);
328
+ return { dispatched: 0, busy: 0 };
329
+ }
330
+ finally {
331
+ recoveringSources.delete(recoveryKey);
332
+ }
333
+ };
48
334
  const resolveReceiptSuccessor = (projectId, epicId, checkpoint) => {
49
335
  assertEpicCheckpointPlanOwnership(checkpoint);
50
336
  return checkpoint.projectId === projectId && checkpoint.epic?.epicId === epicId
51
337
  ? resolveBuildCheckpointSuccessor(checkpoint) : { state: 'unavailable' };
52
338
  };
53
339
  const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQueue) => {
54
- if (!eligible(projectId, epicId)) {
340
+ const ticketId = listExecutionRunLinks(projectId, source.id).find(link => link.entity_type === 'ticket' && link.relationship === 'primary')?.entity_id;
341
+ const ticket = ticketId ? getTicket(ticketId) : null;
342
+ if (!ticket?.worktree_bundle_id) {
343
+ return;
344
+ }
345
+ return withCheckpointExecution(projectId, ticket.worktree_bundle_id, async () => {
346
+ const canonicalId = resolveCanonicalCheckpointBuildRunId(projectId, ticket.worktree_bundle_id, ticket.id, source.id);
347
+ const canonical = getExecutionRun(projectId, canonicalId);
348
+ if (canonical) {
349
+ await resumeCanonicalCompletedBuild(projectId, epicId, canonical, io, releaseOwnerQueue);
350
+ }
351
+ });
352
+ };
353
+ const resumeCanonicalCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQueue) => {
354
+ const canResume = () => canFinalizeSource(projectId, epicId, source) && !belongsToCompletedAttempt(projectId, epicId, source.id);
355
+ if (!canResume()) {
55
356
  return;
56
357
  }
57
358
  const ticketId = listExecutionRunLinks(projectId, source.id).find(link => link.entity_type === 'ticket' && link.relationship === 'primary')?.entity_id;
58
359
  const ticket = ticketId ? getTicket(ticketId) : null;
59
360
  const project = ticket ? getEffectiveProject(ticket) : null;
60
361
  if (!ticket || !project || independentlyPaused(projectId, ticket.worktree_bundle_id)
61
- || !isLatestTicketBuildSource(projectId, source.id, ticket.id)) {
362
+ || !isCanonicalLatestBuild(projectId, ticket, source.id)) {
62
363
  return;
63
364
  }
64
365
  const metadata = getExecutionRun(projectId, source.id)?.metadata ?? {};
@@ -96,14 +397,14 @@ const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQ
96
397
  }
97
398
  }
98
399
  const { runPostBuildChecks } = await import('./postBuildChecks.js');
99
- if (!eligible(projectId, epicId)) {
400
+ if (!canResume()) {
100
401
  return;
101
402
  }
102
403
  const checks = needsChecks && finalization.check_admission !== 'skipped'
103
404
  ? await runPostBuildChecks({ project, sourceRunId: source.id, owner: { kind: 'ticket', ticket },
104
405
  emitter: io, onStatusChange: () => emitUpdatedTickets([ticket.id]), releaseOwnerQueue })
105
406
  : { batch, error: null };
106
- if (!eligible(projectId, epicId)) {
407
+ if (!canResume()) {
107
408
  return;
108
409
  }
109
410
  const finalized = finalizePostBuildCheckTicket({ projectId, sourceRunId: source.id,
@@ -112,7 +413,7 @@ const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQ
112
413
  return;
113
414
  }
114
415
  }
115
- if (!eligible(projectId, epicId)) {
416
+ if (!canResume()) {
116
417
  return;
117
418
  }
118
419
  const checkpoint = getEpicCheckpointContinuation(projectId, source.id);
@@ -134,7 +435,7 @@ const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQ
134
435
  }
135
436
  }
136
437
  const { completeSuccessfulBuildPostFinalization } = await import('./buildCompletionContinuation.js');
137
- if (!eligible(projectId, epicId)) {
438
+ if (!canResume()) {
138
439
  return;
139
440
  }
140
441
  let result;
@@ -145,7 +446,7 @@ const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQ
145
446
  }
146
447
  finally {
147
448
  const retained = getEpicCheckpointContinuation(projectId, source.id);
148
- if (retained?.nextStage && ticket.worktree_bundle_id
449
+ if (eligible(projectId, epicId) && canResume() && retained?.nextStage && ticket.worktree_bundle_id
149
450
  && getExecutionRun(projectId, retained.progressionRunId)?.status === 'running'
150
451
  && !getActiveAutomationChild(projectId, retained.progressionRunId)) {
151
452
  waitAutomationProgression({ projectId, bundleId: ticket.worktree_bundle_id,
@@ -153,7 +454,7 @@ const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQ
153
454
  pauseReason: retained.deferralReason.message, reasonCode: 'reconciliation_failed', pausedStageRunId: null, broadcaster: io });
154
455
  }
155
456
  }
156
- if (result.deferred || !eligible(projectId, epicId)) {
457
+ if (result.deferred || !canResume() || !eligible(projectId, epicId)) {
157
458
  return;
158
459
  }
159
460
  if (checkpoint && ticket.worktree_bundle_id && getEpicCheckpointContinuation(projectId, source.id)?.nextStage === null
@@ -183,13 +484,13 @@ const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQ
183
484
  const scheduling = startBuild(next, io, { sequenceId,
184
485
  initiation: { initiator: 'automation', causalParentRunId: source.id, workflowContext },
185
486
  accept: () => {
186
- if (!eligible(projectId, epicId) || independentlyPaused(projectId, next.worktree_bundle_id)) {
187
- throw new Error('Epic execution is no longer available');
487
+ if (!eligible(projectId, epicId) || !canResume() || independentlyPaused(projectId, next.worktree_bundle_id)) {
488
+ throw new Error(epicExecutionMessage('recoveryExecutionUnavailable'));
188
489
  }
189
490
  if (receiptSuccessor && completedCheckpoint) {
190
491
  const live = resolveReceiptSuccessor(projectId, epicId, completedCheckpoint);
191
492
  if (live.state !== 'queued' || live.ticket.id !== next.id || live.sequenceId !== sequenceId) {
192
- throw new Error('Checkpoint successor is no longer the owned queued item');
493
+ throw new Error(epicExecutionMessage('recoveryCheckpointSuccessorOwnershipChanged'));
193
494
  }
194
495
  }
195
496
  if (next.worktree_bundle_id) {
@@ -197,7 +498,7 @@ const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQ
197
498
  }
198
499
  const transition = prepareTicketForBuild(next.id, { ignoredBlockerTicketIds: result.ignoredBlockerTicketIds });
199
500
  if (!transition.ok || !sequenceId) {
200
- throw new Error(transition.ok ? 'Build sequence no longer exists' : transition.error);
501
+ throw new Error(transition.ok ? epicExecutionMessage('recoveryBuildSequenceMissing') : transition.error);
201
502
  }
202
503
  activateQueuedBuildSequenceTicket(sequenceId, transition.ticket.id);
203
504
  return { ticket: transition.ticket, sequenceId, compensate: () => compensateBuildSequenceTicketActivation(sequenceId, transition.ticket.id) };
@@ -208,17 +509,78 @@ const resumeCompletedBuild = async (projectId, epicId, source, io, releaseOwnerQ
208
509
  }
209
510
  markPostBuildCheckFinalizationComplete(projectId, source.id);
210
511
  };
512
+ const isCanonicalLatestBuild = (projectId, ticket, sourceRunId) => {
513
+ if (isLatestTicketBuildSource(projectId, sourceRunId, ticket.id)) {
514
+ return true;
515
+ }
516
+ const latest = latestTicketBuild(projectId, ticket.id);
517
+ return Boolean(latest && ticket.worktree_bundle_id
518
+ && resolveCanonicalCheckpointBuildRunId(projectId, ticket.worktree_bundle_id, ticket.id, latest.id) === sourceRunId);
519
+ };
211
520
  /** Same worker queue as Build recovery, but the completed Build is never invoked.
212
521
  * Check admission/finalization precedes every checkpoint replay. */
213
522
  const resumeExecution = async (projectId, epicId, io, options) => {
214
523
  const result = { dispatched: 0, busy: 0 };
215
- if (!eligible(projectId, epicId)) {
524
+ const pausedDrain = !eligible(projectId, epicId) && getEpic(epicId, projectId)?.execution_intent === 'paused';
525
+ if (!eligible(projectId, epicId) && !pausedDrain) {
216
526
  return result;
217
527
  }
218
- recoverProjectEpicCheckpoints(projectId, epicId);
528
+ if (!pausedDrain) {
529
+ recoverProjectEpicCheckpoints(projectId, epicId);
530
+ }
219
531
  for (const row of listEpicOwnedRuns(projectId, epicId)) {
220
- const source = getExecutionRun(projectId, row.id);
532
+ if (belongsToCompletedAttempt(projectId, epicId, row.id)) {
533
+ continue;
534
+ }
535
+ let source = getExecutionRun(projectId, row.id);
536
+ if (!pausedDrain && source?.kind === 'review' && source.status === 'completed'
537
+ && getReviewCompletionContinuation(projectId, source.id)?.status === 'pending') {
538
+ const ticketId = listExecutionRunLinks(projectId, source.id).find(link => link.entity_type === 'ticket' && link.relationship === 'primary')?.entity_id;
539
+ const ticket = ticketId ? getTicket(ticketId) : null;
540
+ const key = ticket ? resolveTicketWorkerKey(ticket, 'review') : null;
541
+ if (key && ticket?.worktree_bundle_id && canFinalizeSource(projectId, epicId, source)
542
+ && resolveEpicAdmission({ projectId, bundleId: ticket.worktree_bundle_id, kind: 'finalization', executionRunId: source.id }).allowed) {
543
+ if (isRunning(key)) {
544
+ result.busy += 1;
545
+ }
546
+ else {
547
+ const release = ownRecovery(projectId, epicId);
548
+ const runId = source.id;
549
+ const reviewSource = source;
550
+ void enqueue(key, () => resumeReviewCompletionContinuation(projectId, runId, io))
551
+ .catch(error => deferInterruptedRecovery(projectId, epicId, reviewSource, error instanceof Error ? error.message : String(error), io)).finally(release);
552
+ result.dispatched += 1;
553
+ }
554
+ }
555
+ continue;
556
+ }
557
+ if (pausedDrain) {
558
+ const finalization = source?.metadata?.post_build_finalization;
559
+ if (!source || source.status !== 'completed' || !['build', 'build_follow_up'].includes(source.kind)
560
+ || !(['pending', 'finalized'].includes(finalization?.status ?? '')
561
+ || (finalization?.status === 'blocked' && finalization.check_admission === 'pending'))
562
+ || (finalization?.status === 'finalized' && getEpicCheckpointContinuation(projectId, source.id))
563
+ || !canFinalizeSource(projectId, epicId, source)) {
564
+ continue;
565
+ }
566
+ }
567
+ if (source?.status === 'interrupted' && source.failure?.code === 'server_restarted' && source.kind === 'review') {
568
+ const resumed = await resumeInterruptedReview(projectId, epicId, source, io);
569
+ result.dispatched += resumed.dispatched;
570
+ result.busy += resumed.busy;
571
+ continue;
572
+ }
573
+ if (source?.status === 'interrupted' && source.failure?.code === 'server_restarted'
574
+ && ['build', 'build_follow_up'].includes(source.kind)) {
575
+ const resumed = await resumeInterruptedBuild(projectId, epicId, source, io);
576
+ result.dispatched += resumed.dispatched;
577
+ result.busy += resumed.busy;
578
+ continue;
579
+ }
221
580
  if (source?.status === 'cancelled' && source.domain_status === 'stopped' && ['build', 'build_follow_up'].includes(source.kind)) {
581
+ if (!options.explicit) {
582
+ continue;
583
+ }
222
584
  const ticketId = listExecutionRunLinks(projectId, source.id).find(link => link.entity_type === 'ticket' && link.relationship === 'primary')?.entity_id;
223
585
  const ticket = ticketId ? getTicket(ticketId) : null;
224
586
  const latest = ticket && db.prepare(`SELECT run.id FROM execution_runs run JOIN execution_run_links link
@@ -228,7 +590,7 @@ const resumeExecution = async (projectId, epicId, io, options) => {
228
590
  if (ticket?.agent_status === 'stopped' && latest?.id === source.id && !independentlyPaused(projectId, ticket.worktree_bundle_id)) {
229
591
  const { resumeBuildTicketRun } = await import('./ticketRunOperations.js');
230
592
  const { getBuildSequenceIdForTicket } = await import('./buildSequences.js');
231
- if (!eligible(projectId, epicId)) {
593
+ if (!eligible(projectId, epicId) || belongsToCompletedAttempt(projectId, epicId, source.id)) {
232
594
  return result;
233
595
  }
234
596
  const resumed = resumeBuildTicketRun({ ticketId: ticket.id, requestedProjectId: projectId, broadcaster: io,
@@ -242,6 +604,15 @@ const resumeExecution = async (projectId, epicId, io, options) => {
242
604
  if (!source || source.status !== 'completed' || !['build', 'build_follow_up'].includes(source.kind)) {
243
605
  continue;
244
606
  }
607
+ const sourceTicketId = listExecutionRunLinks(projectId, source.id).find(link => link.entity_type === 'ticket' && link.relationship === 'primary')?.entity_id;
608
+ const sourceTicket = sourceTicketId ? getTicket(sourceTicketId) : null;
609
+ if (sourceTicket?.worktree_bundle_id) {
610
+ const canonicalId = resolveCanonicalCheckpointBuildRunId(projectId, sourceTicket.worktree_bundle_id, sourceTicket.id, source.id);
611
+ source = getExecutionRun(projectId, canonicalId);
612
+ if (!source || belongsToCompletedAttempt(projectId, epicId, source.id)) {
613
+ continue;
614
+ }
615
+ }
245
616
  const continuation = getEpicCheckpointContinuation(projectId, source.id);
246
617
  const finalization = source.metadata?.post_build_finalization;
247
618
  const unadmittedAtRestart = finalization?.status === 'blocked' && finalization.check_admission === 'pending' && continuation
@@ -258,7 +629,7 @@ const resumeExecution = async (projectId, epicId, io, options) => {
258
629
  const ticket = ticketId ? getTicket(ticketId) : null;
259
630
  const key = ticket ? resolveTicketWorkerKey(ticket, 'build') : null;
260
631
  if (!key || !ticket || independentlyPaused(projectId, ticket.worktree_bundle_id)
261
- || !isLatestTicketBuildSource(projectId, source.id, ticket.id)) {
632
+ || !isCanonicalLatestBuild(projectId, ticket, source.id)) {
262
633
  continue;
263
634
  }
264
635
  const automationState = ticket.worktree_bundle_id ? getBundleAutomationState(projectId, ticket.worktree_bundle_id) : null;
@@ -284,8 +655,9 @@ const resumeExecution = async (projectId, epicId, io, options) => {
284
655
  recoveringSources.add(recoveryKey);
285
656
  const releaseOwnership = ownRecovery(projectId, epicId);
286
657
  let completion;
658
+ const recoverySource = source;
287
659
  try {
288
- completion = enqueue(key, release => resumeCompletedBuild(projectId, epicId, source, io, release));
660
+ completion = enqueue(key, release => resumeCompletedBuild(projectId, epicId, recoverySource, io, release));
289
661
  }
290
662
  catch (error) {
291
663
  recoveringSources.delete(recoveryKey);
@@ -293,9 +665,11 @@ const resumeExecution = async (projectId, epicId, io, options) => {
293
665
  throw error;
294
666
  }
295
667
  void completion.catch(error => {
296
- if (getExecutionRun(projectId, source.id)) {
297
- appendLifecycleEvent({ projectId, runId: source.id, eventType: 'epic_execution_recovery_deferred',
298
- metadata: { epic_id: epicId, reason: error instanceof Error ? error.message : String(error) } }, io);
668
+ if (getExecutionRun(projectId, recoverySource.id)) {
669
+ appendLifecycleEvent({ projectId, runId: recoverySource.id, eventType: 'epic_execution_recovery_deferred',
670
+ metadata: { epic_id: epicId, reason: epicExecutionMessage('recoveryDeferredReason', {
671
+ reason: error instanceof Error ? error.message : String(error),
672
+ }) } }, io);
299
673
  }
300
674
  }).finally(() => {
301
675
  recoveringSources.delete(recoveryKey);
@@ -307,17 +681,27 @@ const resumeExecution = async (projectId, epicId, io, options) => {
307
681
  };
308
682
  /** Intent has already been committed. Interrupt only this epic's owned work;
309
683
  * do not retire progression, clean workspace, or stop a Build sequence. */
310
- const stopExecution = async (projectId, epicId, io) => {
684
+ const stopExecution = async (projectId, epicId, io, attemptId) => {
311
685
  const { stopBuildAgent, stopReviewAgent, interruptExecutionProcesses, stopSpecAgent } = await import('./agent.js');
312
686
  const { getSpecAgentProcessKey } = await import('./specAgentRuntime.js');
313
687
  if (!getEpic(epicId, projectId)) {
314
688
  return;
315
689
  }
316
- await stopSpecAgent(getSpecAgentProcessKey(epicId, 'epic'));
690
+ if (!attemptId) {
691
+ await stopSpecAgent(getSpecAgentProcessKey(epicId, 'epic'));
692
+ }
693
+ const owned = attemptId ? db.prepare(`WITH RECURSIVE descendants(id) AS (
694
+ SELECT id FROM execution_runs WHERE project_id = ? AND parent_run_id = ?
695
+ UNION SELECT child.id FROM execution_runs child JOIN descendants parent ON child.parent_run_id = parent.id
696
+ WHERE child.project_id = ?
697
+ ) SELECT id FROM descendants WHERE id <> ?`)
698
+ .all(projectId, `epic-attempt:${attemptId}`, projectId, `epic-attempt:${attemptId}`)
699
+ : listEpicOwnedRuns(projectId, epicId);
700
+ const ownedIds = new Set(owned.map(run => run.id));
317
701
  const bundles = new Set();
318
702
  const interrupted = new Set();
319
703
  const stopOwnedRun = async (run) => {
320
- if (interrupted.has(run.id)) {
704
+ if (interrupted.has(run.id) || (attemptId && !ownedIds.has(run.id))) {
321
705
  return;
322
706
  }
323
707
  interrupted.add(run.id);
@@ -334,8 +718,11 @@ const stopExecution = async (projectId, epicId, io) => {
334
718
  await stopCheckBatch(projectId, run.id, io);
335
719
  }
336
720
  await interruptExecutionProcesses(projectId, run.id);
721
+ if (attemptId && ['queued', 'running', 'waiting'].includes(getExecutionRun(projectId, run.id)?.status ?? '')) {
722
+ transitionExecutionRun({ projectId, runId: run.id, status: 'interrupted' }, io);
723
+ }
337
724
  };
338
- for (const row of listEpicOwnedRuns(projectId, epicId)) {
725
+ for (const row of owned) {
339
726
  const run = getExecutionRun(projectId, row.id);
340
727
  if (!run || !['queued', 'running', 'waiting'].includes(run.status)) {
341
728
  continue;
@@ -343,10 +730,14 @@ const stopExecution = async (projectId, epicId, io) => {
343
730
  const links = listExecutionRunLinks(projectId, run.id);
344
731
  if (run.kind === 'automation_progression') {
345
732
  const bundleId = links.find(link => link.entity_type === 'bundle' && link.relationship === 'primary')?.entity_id;
346
- if (bundleId && !bundles.has(bundleId)) {
733
+ if (bundleId && !bundles.has(bundleId) && (!attemptId
734
+ || getBundleAutomationState(projectId, bundleId)?.automation_progression_run_id === run.id)) {
347
735
  bundles.add(bundleId);
348
736
  await interruptAutomationProgression({ projectId, bundleId, broadcaster: io, stopChild: stopOwnedRun });
349
737
  }
738
+ if (attemptId) {
739
+ await stopOwnedRun(run);
740
+ }
350
741
  continue;
351
742
  }
352
743
  await stopOwnedRun(run);
@@ -373,4 +764,18 @@ export const stopEpicExecution = async (projectId, epicId, io) => {
373
764
  release();
374
765
  }
375
766
  };
767
+ /** The authoritative merge has completed the root before invoking cleanup. */
768
+ export const stopMergedEpicAttemptExecution = async (projectId, epicId, attemptId, io) => {
769
+ if (!getEpicAttempt(attemptId, epicId, projectId)
770
+ || getExecutionRun(projectId, `epic-attempt:${attemptId}`)?.status !== 'completed') {
771
+ return;
772
+ }
773
+ const release = ownRecovery(projectId, epicId);
774
+ try {
775
+ await stopExecution(projectId, epicId, io, attemptId);
776
+ }
777
+ finally {
778
+ release();
779
+ }
780
+ };
376
781
  //# sourceMappingURL=epicExecutionRecovery.js.map