@overdeck/core 0.45.10 → 0.45.11

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 (219) hide show
  1. package/dist/{agent-state-KVbJEG5f.js → agent-state-RLhS7ckO.js} +1 -1
  2. package/dist/{agents-pp8FO7Uj.js → agents-By3u_fQ8.js} +1 -1
  3. package/dist/{agents-CQHK0CSA.js → agents-CgVr77Qq.js} +12 -12
  4. package/dist/{agents-CQHK0CSA.js.map → agents-CgVr77Qq.js.map} +1 -1
  5. package/dist/{backlog-auto-trigger-CyuoS0nl.js → backlog-auto-trigger-B_-1tk4e.js} +5 -5
  6. package/dist/{backlog-auto-trigger-CyuoS0nl.js.map → backlog-auto-trigger-B_-1tk4e.js.map} +1 -1
  7. package/dist/cli/index.js +45 -45
  8. package/dist/{cli-Cewlu3yU.js → cli-DGeSW85B.js} +2 -2
  9. package/dist/{cli-Cewlu3yU.js.map → cli-DGeSW85B.js.map} +1 -1
  10. package/dist/cli-MTB9IOoR.js +3 -0
  11. package/dist/{close-issue-BJGX9_z7.js → close-issue-Djajb6Sv.js} +2 -2
  12. package/dist/{close-issue-BJGX9_z7.js.map → close-issue-Djajb6Sv.js.map} +1 -1
  13. package/dist/{concurrency-Ca-fC7tA.js → concurrency-4rzjHAQA.js} +1 -1
  14. package/dist/{conversation-compaction-B_6s9EvM.js → conversation-compaction-BQvZh09I.js} +4 -4
  15. package/dist/{conversation-compaction-B_6s9EvM.js.map → conversation-compaction-BQvZh09I.js.map} +1 -1
  16. package/dist/dashboard/{advancing-selfheal-CMlGznKv.js → advancing-selfheal-BezNfM3P.js} +3 -3
  17. package/dist/dashboard/{advancing-selfheal-CMlGznKv.js.map → advancing-selfheal-BezNfM3P.js.map} +1 -1
  18. package/dist/dashboard/{agent-state-xk_G8t90.js → agent-state-BUANcaA7.js} +1 -1
  19. package/dist/dashboard/{agent-state-service-C1iUF9Ft.js → agent-state-service-DmFpIMbP.js} +1 -1
  20. package/dist/dashboard/{agent-state-service-5ge9xxhx.js → agent-state-service-tXUdp6UF.js} +2 -2
  21. package/dist/dashboard/{agent-state-service-5ge9xxhx.js.map → agent-state-service-tXUdp6UF.js.map} +1 -1
  22. package/dist/dashboard/{agents-BIggLvi_.js → agents-C-vqmKDi.js} +1 -1
  23. package/dist/dashboard/{agents-DHvsjsuP.js → agents-C7V4odQ6.js} +11 -11
  24. package/dist/dashboard/{agents-DHvsjsuP.js.map → agents-C7V4odQ6.js.map} +1 -1
  25. package/dist/dashboard/{backlog-auto-trigger-COm_R96V.js → backlog-auto-trigger-Cb8PR-5w.js} +2 -2
  26. package/dist/dashboard/{backlog-auto-trigger-COm_R96V.js.map → backlog-auto-trigger-Cb8PR-5w.js.map} +1 -1
  27. package/dist/dashboard/{cli-CvK9xuSS.js → cli-BgzbB6h3.js} +2 -2
  28. package/dist/dashboard/{cli-CvK9xuSS.js.map → cli-BgzbB6h3.js.map} +1 -1
  29. package/dist/dashboard/cli-DCqy_wFa.js +3 -0
  30. package/dist/dashboard/{close-issue-BnpErnD1.js → close-issue-BWf3pxn4.js} +2 -2
  31. package/dist/dashboard/{close-issue-BnpErnD1.js.map → close-issue-BWf3pxn4.js.map} +1 -1
  32. package/dist/dashboard/{closed-issue-reaper-DRqK5k39.js → closed-issue-reaper-D7XPq5pY.js} +4 -4
  33. package/dist/dashboard/{closed-issue-reaper-DRqK5k39.js.map → closed-issue-reaper-D7XPq5pY.js.map} +1 -1
  34. package/dist/dashboard/{closed-issue-reaper-BLCQwTpF.js → closed-issue-reaper-VSTSTROK.js} +1 -1
  35. package/dist/dashboard/{conflict-gate-JdFuhKuF.js → conflict-gate-DwOslTij.js} +1 -1
  36. package/dist/dashboard/{conflict-gate-BhKvrPxn.js → conflict-gate-FFEvTDVA.js} +3 -3
  37. package/dist/dashboard/{conflict-gate-BhKvrPxn.js.map → conflict-gate-FFEvTDVA.js.map} +1 -1
  38. package/dist/dashboard/{conversation-compaction-C5o_eKEm.js → conversation-compaction-CCqN4hWk.js} +4 -4
  39. package/dist/dashboard/{conversation-compaction-C5o_eKEm.js.map → conversation-compaction-CCqN4hWk.js.map} +1 -1
  40. package/dist/dashboard/{conversation-compaction-Ba5aZdrb.js → conversation-compaction-CL5Ti4j4.js} +1 -1
  41. package/dist/dashboard/{deacon-j3qSZ7--.js → deacon-CGHl90eC.js} +107 -50
  42. package/dist/dashboard/{deacon-j3qSZ7--.js.map → deacon-CGHl90eC.js.map} +1 -1
  43. package/dist/dashboard/{deacon-Cv2RMfHs.js → deacon-DMPh40Im.js} +2 -2
  44. package/dist/dashboard/deacon-swarm-CVTiNL0N.js +2 -0
  45. package/dist/dashboard/{deacon-swarm-DadWNi5J.js → deacon-swarm-aMMJTq6t.js} +4 -4
  46. package/dist/dashboard/{deacon-swarm-DadWNi5J.js.map → deacon-swarm-aMMJTq6t.js.map} +1 -1
  47. package/dist/dashboard/deacon.js +4 -4
  48. package/dist/dashboard/{feedback-target-oE4-Esxl.js → feedback-target-dJjFfITP.js} +4 -4
  49. package/dist/dashboard/{feedback-target-oE4-Esxl.js.map → feedback-target-dJjFfITP.js.map} +1 -1
  50. package/dist/dashboard/{feedback-target-C4DaDSZ8.js → feedback-target-nQSM6ygL.js} +1 -1
  51. package/dist/dashboard/{flywheel-ClMjGW_u.js → flywheel-BLoVNtJV.js} +6 -6
  52. package/dist/dashboard/{flywheel-ClMjGW_u.js.map → flywheel-BLoVNtJV.js.map} +1 -1
  53. package/dist/dashboard/{flywheel-DefHRzY4.js → flywheel-Cqf8vu7N.js} +6 -6
  54. package/dist/dashboard/{flywheel-DefHRzY4.js.map → flywheel-Cqf8vu7N.js.map} +1 -1
  55. package/dist/dashboard/{flywheel-BqDdGvrQ.js → flywheel-PJsbrXNY.js} +1 -1
  56. package/dist/dashboard/{flywheel-merge-order-CuDcqTRJ.js → flywheel-merge-order-B7BH8mZ3.js} +2 -2
  57. package/dist/dashboard/{flywheel-merge-order-CuDcqTRJ.js.map → flywheel-merge-order-B7BH8mZ3.js.map} +1 -1
  58. package/dist/dashboard/{flywheel-merge-order-B6YDSElh.js → flywheel-merge-order-CCwF60b-.js} +1 -1
  59. package/dist/dashboard/{harness-resolve-DKeSVsJL.js → harness-resolve-B3f9G1Kp.js} +2 -2
  60. package/dist/dashboard/{harness-resolve-DKeSVsJL.js.map → harness-resolve-B3f9G1Kp.js.map} +1 -1
  61. package/dist/dashboard/{inspect-agent-BKKc0XnB.js → inspect-agent-CKF5-SJr.js} +3 -3
  62. package/dist/dashboard/{inspect-agent-BKKc0XnB.js.map → inspect-agent-CKF5-SJr.js.map} +1 -1
  63. package/dist/dashboard/inspect-agent-CqpEWGWy.js +2 -0
  64. package/dist/dashboard/{issue-lifecycle-DnhQgddB.js → issue-lifecycle-5LbOcATP.js} +7 -7
  65. package/dist/dashboard/{issue-lifecycle-DnhQgddB.js.map → issue-lifecycle-5LbOcATP.js.map} +1 -1
  66. package/dist/dashboard/{issue-lifecycle-nY4esZn8.js → issue-lifecycle-CjYqQ669.js} +1 -1
  67. package/dist/dashboard/{issue-service-singleton-Bnqv1uaa.js → issue-service-singleton-B8iu_TKV.js} +1 -1
  68. package/dist/dashboard/{issue-service-singleton-_AquSBTl.js → issue-service-singleton-CDGt__oQ.js} +2 -2
  69. package/dist/dashboard/{issue-service-singleton-_AquSBTl.js.map → issue-service-singleton-CDGt__oQ.js.map} +1 -1
  70. package/dist/dashboard/{lifecycle-CGKm7doE.js → lifecycle-CEg4sHZH.js} +4 -4
  71. package/dist/dashboard/{lifecycle-CGKm7doE.js.map → lifecycle-CEg4sHZH.js.map} +1 -1
  72. package/dist/dashboard/{merge-agent-Dh8Y9PDO.js → merge-agent-7nBiCytp.js} +1 -1
  73. package/dist/dashboard/{merge-agent-BcgAYStl.js → merge-agent-C81xPIGd.js} +6 -6
  74. package/dist/dashboard/{merge-agent-BcgAYStl.js.map → merge-agent-C81xPIGd.js.map} +1 -1
  75. package/dist/dashboard/merge-ops-DE_6CnmZ.js +2 -0
  76. package/dist/dashboard/{merge-train-DmxlYbEo.js → merge-train-D3qzRccL.js} +2 -2
  77. package/dist/dashboard/{merge-train-DmxlYbEo.js.map → merge-train-D3qzRccL.js.map} +1 -1
  78. package/dist/dashboard/{merge-train-deps-DBHsOWt9.js → merge-train-deps-Be5ElC_P.js} +2 -2
  79. package/dist/dashboard/{merge-train-deps-DBHsOWt9.js.map → merge-train-deps-Be5ElC_P.js.map} +1 -1
  80. package/dist/dashboard/{orphan-proposed-reconciler-Db8tUhce.js → orphan-proposed-reconciler-Boq_XaRe.js} +3 -3
  81. package/dist/dashboard/{orphan-proposed-reconciler-Db8tUhce.js.map → orphan-proposed-reconciler-Boq_XaRe.js.map} +1 -1
  82. package/dist/dashboard/{orphan-proposed-reconciler-mXV--tcB.js → orphan-proposed-reconciler-C0sPnDq_.js} +1 -1
  83. package/dist/dashboard/{reconstruct-cache-_tDZ2D72.js → reconstruct-cache-C2pCltOq.js} +3 -3
  84. package/dist/dashboard/{reconstruct-cache-_tDZ2D72.js.map → reconstruct-cache-C2pCltOq.js.map} +1 -1
  85. package/dist/dashboard/{remote-completion-Bklh6loJ.js → remote-completion-BmxD5UMQ.js} +3 -3
  86. package/dist/dashboard/{remote-completion-Bklh6loJ.js.map → remote-completion-BmxD5UMQ.js.map} +1 -1
  87. package/dist/dashboard/resume-C-nxu9Y4.js +3 -0
  88. package/dist/dashboard/{review-agent-phzqNqIs.js → review-agent-D6P6d3pz.js} +26 -17
  89. package/dist/dashboard/review-agent-D6P6d3pz.js.map +1 -0
  90. package/dist/dashboard/review-agent-DTINEffB.js +3 -0
  91. package/dist/dashboard/{review-context-CCq56O_Y.js → review-context-Dyo0tsBa.js} +2 -2
  92. package/dist/dashboard/{review-context-CCq56O_Y.js.map → review-context-Dyo0tsBa.js.map} +1 -1
  93. package/dist/dashboard/{review-status-BQjqQXZG.js → review-status-B5ZASOo4.js} +18 -5
  94. package/dist/dashboard/review-status-B5ZASOo4.js.map +1 -0
  95. package/dist/dashboard/{review-status-bBkqUj5i.js → review-status-h7BXIA4z.js} +1 -1
  96. package/dist/dashboard/{review-verdict-feedback-wqnikhMK.js → review-verdict-feedback-B70VbfRL.js} +4 -4
  97. package/dist/dashboard/{review-verdict-feedback-wqnikhMK.js.map → review-verdict-feedback-B70VbfRL.js.map} +1 -1
  98. package/dist/dashboard/{review-verdict-feedback-cZh9Wi9G.js → review-verdict-feedback-CorgH49f.js} +1 -1
  99. package/dist/dashboard/{sequence-io-B2GmilSI.js → sequence-io-6YP8fVpH.js} +2 -2
  100. package/dist/dashboard/{sequence-io-B2GmilSI.js.map → sequence-io-6YP8fVpH.js.map} +1 -1
  101. package/dist/dashboard/{sequencer-agent-D8pW2aU_.js → sequencer-agent-ja-nkEc1.js} +5 -5
  102. package/dist/dashboard/{sequencer-agent-D8pW2aU_.js.map → sequencer-agent-ja-nkEc1.js.map} +1 -1
  103. package/dist/dashboard/server.js +66 -55
  104. package/dist/dashboard/server.js.map +1 -1
  105. package/dist/dashboard/{service-CILd-uOt.js → service-HKDrIy0h.js} +24 -24
  106. package/dist/dashboard/{service-CILd-uOt.js.map → service-HKDrIy0h.js.map} +1 -1
  107. package/dist/dashboard/{smart-compaction-Bgp_gwcA.js → smart-compaction-L0LSnF0_.js} +1 -1
  108. package/dist/dashboard/{smart-compaction-CrP90OFE.js → smart-compaction-uke1npUz.js} +2 -2
  109. package/dist/dashboard/{smart-compaction-CrP90OFE.js.map → smart-compaction-uke1npUz.js.map} +1 -1
  110. package/dist/dashboard/{spawn-planning-session-D15KbPOy.js → spawn-planning-session-CSMWco8B.js} +1 -1
  111. package/dist/dashboard/{spawn-planning-session-BmJWHSCu.js → spawn-planning-session-CXc0NkwV.js} +3 -3
  112. package/dist/dashboard/{spawn-planning-session-BmJWHSCu.js.map → spawn-planning-session-CXc0NkwV.js.map} +1 -1
  113. package/dist/dashboard/{specialist-context-CwKkcXL9.js → specialist-context-BGCJ24LH.js} +3 -3
  114. package/dist/dashboard/{specialist-context-CwKkcXL9.js.map → specialist-context-BGCJ24LH.js.map} +1 -1
  115. package/dist/dashboard/{specialist-logs-CvDxquV_.js → specialist-logs--Uz-r8ia.js} +2 -2
  116. package/dist/dashboard/{specialist-logs-CvDxquV_.js.map → specialist-logs--Uz-r8ia.js.map} +1 -1
  117. package/dist/dashboard/{specialists-BCjcG4uE.js → specialists-Ca9XSBCS.js} +1 -1
  118. package/dist/dashboard/{specialists-D07ybnam.js → specialists-DEfrAbWs.js} +36 -36
  119. package/dist/dashboard/{specialists-D07ybnam.js.map → specialists-DEfrAbWs.js.map} +1 -1
  120. package/dist/dashboard/{specialists-F2uMO4QS.js → specialists-DeZx9xom.js} +1 -1
  121. package/dist/dashboard/{specialists-BYi0k8CZ.js → specialists-nZ0mRwpZ.js} +12 -12
  122. package/dist/dashboard/{specialists-BYi0k8CZ.js.map → specialists-nZ0mRwpZ.js.map} +1 -1
  123. package/dist/dashboard/{summary-fork-DedqguZb.js → summary-fork-2a1L2DIU.js} +2 -2
  124. package/dist/dashboard/{summary-fork-EjvOkEPl.js → summary-fork-Xn0QUNmb.js} +3 -3
  125. package/dist/dashboard/{summary-fork-EjvOkEPl.js.map → summary-fork-Xn0QUNmb.js.map} +1 -1
  126. package/dist/dashboard/{teardown-workspace-5LCVbjfq.js → teardown-workspace-DhA6oAIK.js} +2 -2
  127. package/dist/dashboard/{teardown-workspace-5LCVbjfq.js.map → teardown-workspace-DhA6oAIK.js.map} +1 -1
  128. package/dist/dashboard/{test-agent-queue-qfsq6uaC.js → test-agent-queue-B_ukPyIK.js} +3 -3
  129. package/dist/dashboard/{test-agent-queue-qfsq6uaC.js.map → test-agent-queue-B_ukPyIK.js.map} +1 -1
  130. package/dist/dashboard/{uat-train-CtNGgXxj.js → uat-train-BLBAbJ8Y.js} +10 -10
  131. package/dist/dashboard/{uat-train-CtNGgXxj.js.map → uat-train-BLBAbJ8Y.js.map} +1 -1
  132. package/dist/dashboard/{uat-train-C3hWXtip.js → uat-train-DPfGR9_I.js} +1 -1
  133. package/dist/dashboard/{verification-runner-DuZRHjPU.js → verification-runner-KTGTNugM.js} +1 -1
  134. package/dist/dashboard/{verification-runner-BPAhPWR7.js → verification-runner-R2-4XgMO.js} +4 -4
  135. package/dist/dashboard/{verification-runner-BPAhPWR7.js.map → verification-runner-R2-4XgMO.js.map} +1 -1
  136. package/dist/dashboard/{workflows-H-COJ84X.js → workflows-CSKX5MhC.js} +7 -7
  137. package/dist/dashboard/{workflows-H-COJ84X.js.map → workflows-CSKX5MhC.js.map} +1 -1
  138. package/dist/dashboard/workflows-DVwXauef.js +2 -0
  139. package/dist/dashboard/{workspaces-CRU9_vRn.js → workspaces-DXLDgXo2.js} +32 -32
  140. package/dist/dashboard/{workspaces-CRU9_vRn.js.map → workspaces-DXLDgXo2.js.map} +1 -1
  141. package/dist/docs-index.sqlite +0 -0
  142. package/dist/{feedback-target-DTGAhFkM.js → feedback-target-BsKN4Tr_.js} +4 -4
  143. package/dist/{feedback-target-DTGAhFkM.js.map → feedback-target-BsKN4Tr_.js.map} +1 -1
  144. package/dist/{feedback-target-DutF088V.js → feedback-target-DM1WzOKy.js} +1 -1
  145. package/dist/{harness-resolve-Bz1prk6B.js → harness-resolve-B-YDNwNW.js} +2 -2
  146. package/dist/{harness-resolve-Bz1prk6B.js.map → harness-resolve-B-YDNwNW.js.map} +1 -1
  147. package/dist/{issue-lifecycle-fVqvCdKM.js → issue-lifecycle-Bc1l3U9f.js} +7 -7
  148. package/dist/{issue-lifecycle-fVqvCdKM.js.map → issue-lifecycle-Bc1l3U9f.js.map} +1 -1
  149. package/dist/{issue-service-singleton-CZm8p6Rj.js → issue-service-singleton-D-8Q6tdT.js} +1 -1
  150. package/dist/{issue-service-singleton-Cr73JAaR.js → issue-service-singleton-D1433I7n.js} +2 -2
  151. package/dist/{issue-service-singleton-Cr73JAaR.js.map → issue-service-singleton-D1433I7n.js.map} +1 -1
  152. package/dist/{lifecycle-CR6tZfl1.js → lifecycle-SmrqysDf.js} +7 -7
  153. package/dist/{lifecycle-CR6tZfl1.js.map → lifecycle-SmrqysDf.js.map} +1 -1
  154. package/dist/{lifecycle-D_EWiUjk.js → lifecycle-mRMyiIXs.js} +2 -2
  155. package/dist/{merge-agent-LM4avOtA.js → merge-agent-B9hIZ6Z0.js} +6 -6
  156. package/dist/{merge-agent-LM4avOtA.js.map → merge-agent-B9hIZ6Z0.js.map} +1 -1
  157. package/dist/{merge-agent-Bj046HE1.js → merge-agent-DUj22cXL.js} +1 -1
  158. package/dist/{merge-fulfillment-DrnC1Kmg.js → merge-fulfillment-__P4WE-T.js} +3 -3
  159. package/dist/{merge-fulfillment-DrnC1Kmg.js.map → merge-fulfillment-__P4WE-T.js.map} +1 -1
  160. package/dist/{reconstruct-cache-NPqoAUg-.js → reconstruct-cache-9SWp82SQ.js} +3 -3
  161. package/dist/{reconstruct-cache-NPqoAUg-.js.map → reconstruct-cache-9SWp82SQ.js.map} +1 -1
  162. package/dist/{records-BIkN1LQ4.js → records-CTmvuRzz.js} +14 -1
  163. package/dist/{records-BIkN1LQ4.js.map → records-CTmvuRzz.js.map} +1 -1
  164. package/dist/records-backfill-BQcmTmwF.js +2 -0
  165. package/dist/{records-backfill-HM0Pln6N.js → records-backfill-BrNsv_zT.js} +2 -2
  166. package/dist/{records-backfill-HM0Pln6N.js.map → records-backfill-BrNsv_zT.js.map} +1 -1
  167. package/dist/resume-Bn4kDk9x.js +3 -0
  168. package/dist/{review-agent-DFosQzCG.js → review-agent-PhqOhpx3.js} +24 -16
  169. package/dist/{review-agent-DFosQzCG.js.map → review-agent-PhqOhpx3.js.map} +1 -1
  170. package/dist/review-agent-hLbRRxZF.js +3 -0
  171. package/dist/{review-status-iJwfEoNX.js → review-status-B_XXomV0.js} +6 -6
  172. package/dist/{review-status-iJwfEoNX.js.map → review-status-B_XXomV0.js.map} +1 -1
  173. package/dist/{review-status-BbNVlXh1.js → review-status-Bo-EFVKh.js} +1 -1
  174. package/dist/{review-verdict-feedback-BGPw3z1X.js → review-verdict-feedback-CXHkoiKZ.js} +1 -1
  175. package/dist/{review-verdict-feedback-CCZ05atV.js → review-verdict-feedback-DGV13LDb.js} +4 -4
  176. package/dist/{review-verdict-feedback-CCZ05atV.js.map → review-verdict-feedback-DGV13LDb.js.map} +1 -1
  177. package/dist/{sequence-io-CcxZNHcD.js → sequence-io-Cg4NHAco.js} +1 -1
  178. package/dist/{sequence-io-Cx1usxG3.js → sequence-io-CyxvNHfA.js} +2 -2
  179. package/dist/{sequence-io-Cx1usxG3.js.map → sequence-io-CyxvNHfA.js.map} +1 -1
  180. package/dist/{smart-compaction-ByUEgQkF.js → smart-compaction-ByKXTQNy.js} +2 -2
  181. package/dist/{smart-compaction-ByUEgQkF.js.map → smart-compaction-ByKXTQNy.js.map} +1 -1
  182. package/dist/{smart-compaction-DfLe_CtH.js → smart-compaction-U6e_uB1E.js} +1 -1
  183. package/dist/{specialist-context-McuGkaeR.js → specialist-context-BUTadO-U.js} +3 -3
  184. package/dist/{specialist-context-McuGkaeR.js.map → specialist-context-BUTadO-U.js.map} +1 -1
  185. package/dist/{specialist-logs-CUUJ4eiB.js → specialist-logs-pEMCTtGZ.js} +2 -2
  186. package/dist/{specialist-logs-CUUJ4eiB.js.map → specialist-logs-pEMCTtGZ.js.map} +1 -1
  187. package/dist/{specialists-BSrylD1S.js → specialists-BGFnrQ8n.js} +1 -1
  188. package/dist/{specialists-B0elgInc.js → specialists-DeTkkp8b.js} +12 -12
  189. package/dist/{specialists-B0elgInc.js.map → specialists-DeTkkp8b.js.map} +1 -1
  190. package/dist/{summary-fork-DskMRnyb.js → summary-fork-CgzThE2-.js} +2 -2
  191. package/dist/{summary-fork-CPUTKcAT.js → summary-fork-Dx1RMuvU.js} +3 -3
  192. package/dist/{summary-fork-CPUTKcAT.js.map → summary-fork-Dx1RMuvU.js.map} +1 -1
  193. package/dist/{sync-BiNVQHBf.js → sync-Bsww9tuj.js} +2 -2
  194. package/dist/{sync-BiNVQHBf.js.map → sync-Bsww9tuj.js.map} +1 -1
  195. package/dist/sync-CylE_SjB.js +2 -0
  196. package/dist/{verdict-restore-DQiV7_fe.js → verdict-restore-DGpX0ZOJ.js} +5 -5
  197. package/dist/{verdict-restore-DQiV7_fe.js.map → verdict-restore-DGpX0ZOJ.js.map} +1 -1
  198. package/dist/{webhook-handlers-DHBSEDEm.js → webhook-handlers-BjsfIL7u.js} +3 -3
  199. package/dist/{webhook-handlers-DHBSEDEm.js.map → webhook-handlers-BjsfIL7u.js.map} +1 -1
  200. package/dist/{workspace-migrate-duUsWNpd.js → workspace-migrate-BBQ8nAnP.js} +2 -2
  201. package/dist/{workspace-migrate-duUsWNpd.js.map → workspace-migrate-BBQ8nAnP.js.map} +1 -1
  202. package/dist/{workspace-reap-DLCIoJmn.js → workspace-reap-12O9354k.js} +2 -2
  203. package/dist/{workspace-reap-DLCIoJmn.js.map → workspace-reap-12O9354k.js.map} +1 -1
  204. package/package.json +1 -1
  205. package/scripts/file-size-baseline.txt +1 -1
  206. package/dist/cli-DBWG12XK.js +0 -3
  207. package/dist/dashboard/cli-CJDWXE_Y.js +0 -3
  208. package/dist/dashboard/deacon-swarm-D1iAUX-P.js +0 -2
  209. package/dist/dashboard/inspect-agent-vm88mLYr.js +0 -2
  210. package/dist/dashboard/merge-ops-QdBiQ8XB.js +0 -2
  211. package/dist/dashboard/resume-DnIsmIgC.js +0 -3
  212. package/dist/dashboard/review-agent-DgySDb-G.js +0 -3
  213. package/dist/dashboard/review-agent-phzqNqIs.js.map +0 -1
  214. package/dist/dashboard/review-status-BQjqQXZG.js.map +0 -1
  215. package/dist/dashboard/workflows-Cz8OtiB4.js +0 -2
  216. package/dist/records-backfill-DEgtRyKL.js +0 -2
  217. package/dist/resume-DGymuXZM.js +0 -3
  218. package/dist/review-agent-DjVadURa.js +0 -3
  219. package/dist/sync-4jqukkxz.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"review-agent-phzqNqIs.js","names":["loadYamlConfig","execAsync","loadYamlConfig"],"sources":["../../src/lib/cloister/review-resume-decision.ts","../../src/lib/cloister/review-rerun-scope.ts","../../src/lib/cloister/review-convoy.ts","../../src/lib/cloister/review-agent.ts"],"sourcesContent":["/**\n * PAN-1862 — the resume-vs-fresh decision for a review agent, as a PURE function so it is locked\n * by tests and shared by both quick review (the parent) and convoy (the sub-reviewers).\n *\n * RESUME (preserve the prior review's context — files read, findings raised — so a re-review\n * checks the fix instead of re-researching the whole diff) when there is a saved, resumable\n * session AND the requested harness/model is unchanged. Fresh-spawn ONLY when the harness or\n * model actually changed (it's a different agent then) or there is no resumable session. A change\n * is detected only when BOTH the requested and saved values are known and differ — an unspecified\n * request (use role default) or an unknown saved value never forces a wipe.\n */\nexport function reviewResumeDecision(params: {\n requestedModel?: string;\n requestedHarness?: string;\n savedModel?: string;\n savedHarness?: string;\n hasSavedState: boolean;\n hasSavedSession: boolean;\n}): boolean {\n const modelChanged =\n !!params.requestedModel && !!params.savedModel && params.requestedModel !== params.savedModel;\n const harnessChanged =\n !!params.requestedHarness && !!params.savedHarness && params.requestedHarness !== params.savedHarness;\n return params.hasSavedState && params.hasSavedSession && !modelChanged && !harnessChanged;\n}\n","/**\n * PAN-1862 (FR-7, NFR-1): pure selection logic for selective re-review.\n *\n * On a re-review cycle (the work agent committed fixes after a BLOCKED verdict),\n * `roles.review.reReviewScope` governs which convoy reviewers actually re-run:\n *\n * - `all` — re-run all four reviewers every cycle (pre-PAN-1862 behavior).\n * - `changed` — (default) re-run reviewers that blocked, PLUS any reviewer whose\n * domain is touched by the files changed since its recorded verdict.\n * - `blockers` — re-run only reviewers that blocked in the prior cycle.\n *\n * Reviewers NOT re-run carry their prior `passed` verdict forward; the dispatch\n * path materializes that as a stub report in the new run directory so synthesis\n * and the deacon fallback see four reports exactly as before.\n *\n * Quality-first bias (NFR-1): whenever the inputs are insufficient to prove a\n * reviewer can be skipped — no prior verdicts, a verdict without a commit anchor,\n * or an unknown changed-file set — the reviewer is INCLUDED. Skipping is only\n * ever an optimization on proven-safe ground.\n */\n\nimport { REVIEW_SUB_ROLES, type ReviewSubRole } from './review-monitor.js';\n\nexport type ReReviewScope = 'all' | 'changed' | 'blockers';\n\nexport interface ReviewerVerdictEntry {\n status: 'passed' | 'blocked';\n /** HEAD sha the verdict was recorded against (anchor for drift invalidation). */\n atCommit?: string;\n /** Path to the reviewer's findings report for that cycle. */\n findingsPath?: string;\n}\n\nexport type ReviewerVerdictsMap = Partial<Record<ReviewSubRole, ReviewerVerdictEntry>>;\n\n/**\n * Domain map for `changed` scope (PRD \"open question\", resolved conservatively):\n * `correctness` and `requirements` are in scope whenever ANY file changed;\n * `security` when a security-sensitive path changed; `performance` when a\n * hot-path-ish file changed. Patterns err toward matching (include the reviewer).\n */\nconst SECURITY_SENSITIVE = /auth|crypt|token|secret|credential|password|session|login|permission|sandbox|escape|inject|input|parse|network|http|request|fetch|socket|proxy|exec|spawn|shell|env|\\.env|package(-lock)?\\.json|bun\\.lock|yarn\\.lock|Dockerfile|docker-compose/i;\nconst PERFORMANCE_SENSITIVE = /query|sql|db|database|cache|index|loop|batch|stream|worker|pool|queue|schedul|poll|interval|timer|migration|perf|bench|concurren|parallel/i;\n\nfunction domainTouched(subRole: ReviewSubRole, changedFiles: readonly string[]): boolean {\n if (changedFiles.length === 0) return false;\n switch (subRole) {\n case 'correctness':\n case 'requirements':\n return true; // every change is in scope for correctness + requirements\n case 'security':\n return changedFiles.some(f => SECURITY_SENSITIVE.test(f));\n case 'performance':\n return changedFiles.some(f => PERFORMANCE_SENSITIVE.test(f));\n default:\n return true; // unknown sub-role → include (fail toward quality)\n }\n}\n\nexport interface ReviewersToRerunInput {\n scope: ReReviewScope;\n /** Prior cycle's per-reviewer verdicts; absent/empty = first cycle → all run. */\n priorVerdicts?: ReviewerVerdictsMap;\n /**\n * Files changed since the prior verdicts' commit anchor. `undefined` means the\n * changed set could NOT be determined — every reviewer runs (fail toward quality).\n */\n changedFiles?: readonly string[];\n}\n\nexport function reviewersToRerun(input: ReviewersToRerunInput): ReviewSubRole[] {\n const all = [...REVIEW_SUB_ROLES];\n if (input.scope === 'all') return all;\n\n const verdicts = input.priorVerdicts ?? {};\n // A reviewer with no recorded verdict, or a verdict with no commit anchor,\n // cannot be proven safe to skip — it always runs.\n const unproven = all.filter(r => !verdicts[r] || !verdicts[r]!.atCommit);\n const blocked = all.filter(r => verdicts[r]?.status === 'blocked');\n\n if (input.scope === 'blockers') {\n return dedupe([...blocked, ...unproven]);\n }\n\n // scope === 'changed'\n if (input.changedFiles === undefined) return all; // unknown drift → everyone runs\n const touched = all.filter(r => verdicts[r]?.status === 'passed' && verdicts[r]!.atCommit && domainTouched(r, input.changedFiles!));\n return dedupe([...blocked, ...unproven, ...touched]);\n}\n\nfunction dedupe(roles: ReviewSubRole[]): ReviewSubRole[] {\n // Preserve the canonical REVIEW_SUB_ROLES ordering for stable prompts/logs.\n const set = new Set(roles);\n return REVIEW_SUB_ROLES.filter(r => set.has(r));\n}\n","/**\n * PAN-1862: the review CONVOY — sub-reviewer prompts and spawning, selective\n * re-review scope, warm-parent fork, and the discovery-ready orchestration.\n *\n * Split out of review-agent.ts (which keeps the review entry point, the\n * synthesis/self-review prompts, mode resolution, and session teardown).\n * This module must NEVER import review-agent.ts — review-agent imports (and\n * re-exports) from here, and a reverse edge would close a cycle.\n *\n * The four convoy sub-roles are security, correctness, performance, and\n * requirements (REVIEW_SUB_ROLES, review-monitor.ts); the synthesis parent is\n * the fifth review role. See docs/REVIEW-AGENT-ARCHITECTURE.md.\n */\n\nimport { exec } from 'child_process';\nimport { mkdir, readFile, rm, writeFile } from 'fs/promises';\nimport { dirname, join } from 'path';\nimport { promisify } from 'util';\nimport { Effect } from 'effect';\nimport { listSessionNames } from '../tmux.js';\nimport { emitActivityEntrySync } from '../activity-logger.js';\nimport { loadConfigSync as loadYamlConfig, resolveModel } from '../config-yaml.js';\nimport { formatTier1Summary, type ReviewContextManifest } from './review-context.js';\nimport { REVIEW_SUB_ROLES, type ReviewSubRole } from './review-monitor.js';\nimport { reviewResumeDecision } from './review-resume-decision.js';\nimport { reviewersToRerun, type ReviewerVerdictsMap, type ReReviewScope } from './review-rerun-scope.js';\nimport { readIssueRecordSync, resolveProjectForIssue } from '../pan-dir/record.js';\nimport { PAN_DIRNAME } from '../pan-dir/types.js';\nimport { AGENTS_DIR, packageRoot, sessionFilePath } from '../paths.js';\nimport type { RuntimeName } from '../runtimes/types.js';\n\nconst execAsync = promisify(exec);\n\n/**\n * Read a convoy sub-role prompt template from the overdeck install.\n *\n * Sub-role prompts are harness-agnostic templates owned by Overdeck. The\n * orchestrator reads them from its own install (packageRoot/roles/) and\n * inlines the body into the spawn message — they never live in the agent's\n * workspace, and they are never loaded via the Claude-specific `--agent` flag.\n * That keeps the same prompt content driving Claude Code, Pi, Codex, or any\n * future harness, and prevents a work agent from ambiently discovering its\n * own reviewer prompts in the workspace tree.\n */\nasync function readConvoySubRoleTemplate(subRole: string): Promise<string> {\n const path = join(packageRoot, 'roles', `review-${subRole}.md`);\n return readFile(path, 'utf-8');\n}\n\n\n\nconst REVIEWER_TIMEOUT_MS = 20 * 60 * 1000;\n\nfunction reviewerAgentId(issueId: string, subRole: ReviewSubRole): string {\n return `agent-${issueId.toLowerCase()}-review-${subRole}`;\n}\n\nfunction reviewerAgentOutputPath(workspace: string, runId: string, subRole: ReviewSubRole): string {\n return join(workspace, PAN_DIRNAME, 'review', runId, `${subRole}.md`);\n}\n\n\n\nasync function buildConvoyPromptPromise(opts: {\n issueId: string;\n subRole: string;\n outputPath: string;\n synthesisAgentId: string;\n contextManifestPath?: string;\n tier1Summary?: string;\n}): Promise<string> {\n const template = await readConvoySubRoleTemplate(opts.subRole);\n const prompt = [\n `REVIEW TASK for ${opts.issueId} — ${opts.subRole.toUpperCase()} REVIEW:`,\n '',\n `Issue: ${opts.issueId}`,\n `Sub-role: ${opts.subRole}`,\n '',\n 'Output file — write your full findings here when done:',\n ` ${opts.outputPath}`,\n '',\n opts.tier1Summary\n ? [\n 'Shared review context (read this first; do not run git diff yourself):',\n '─────────────────────────────────────────────────────────────',\n opts.tier1Summary,\n '─────────────────────────────────────────────────────────────',\n '',\n opts.contextManifestPath\n ? `Full manifest (read on demand for additional detail): ${opts.contextManifestPath}`\n : '',\n ].join('\\n')\n : opts.contextManifestPath\n ? [\n 'Context manifest (read this first; do not run git diff yourself):',\n ` ${opts.contextManifestPath}`,\n 'The manifest contains per-file risk ranking and acceptance criteria.',\n ].join('\\n')\n : 'No context manifest available. Write a blocked reviewer report explaining that the shared review context is missing.',\n '',\n '─────────────────────────────────────────────────────────────',\n 'REVIEW METHODOLOGY (inlined from roles/review-' + opts.subRole + '.md):',\n '─────────────────────────────────────────────────────────────',\n '',\n template.trim(),\n '',\n '─────────────────────────────────────────────────────────────',\n '',\n 'Write exactly one final report to the output file shown above, then stop',\n 'and wait. You do NOT need to signal synthesis or run any pan command —',\n 'when you finish your turn with the report written, Overdeck detects it',\n 'and signals the synthesis agent REVIEWER_READY automatically. Your only',\n 'job is to write the report file, then stop.',\n 'Only the output file is consumed by synthesis; your chat response is not the review report.',\n ].filter(Boolean).join('\\n');\n\n const sizeBytes = Buffer.byteLength(prompt, 'utf-8');\n console.log(`[review-agent] Convoy prompt for ${opts.issueId}/${opts.subRole}: ${sizeBytes} bytes`);\n return prompt;\n}\n\n\n\nasync function spawnReviewSubRoleForIssuePromise(opts: {\n issueId: string;\n workspace: string;\n subRole: ReviewSubRole;\n runId: string;\n outputPath?: string;\n contextManifestPath?: string;\n synthesisAgentId?: string;\n model?: string;\n harness?: RuntimeName;\n allowHost?: boolean;\n /**\n * PAN-1862 Phase A: a session id FORKED from the synthesis parent's discovery\n * session. When set, the reviewer launches with `claude --resume <id>` so its\n * first request replays the parent's byte-identical prefix and reads the warm\n * prompt cache instead of re-reading the diff and files at full price.\n */\n forkedSessionId?: string;\n}): Promise<{ success: boolean; message: string; error?: string; sessionId?: string }> {\n try {\n const { saveAgentState, spawnRun, getAgentStateSync, getLatestSessionIdSync, resumeAgent } = await import('../agents.js');\n const cfg = loadYamlConfig().config;\n const outputPath = opts.outputPath ?? reviewerAgentOutputPath(opts.workspace, opts.runId, opts.subRole);\n const synthesisAgentId = opts.synthesisAgentId ?? `agent-${opts.issueId.toLowerCase()}-review`;\n const model = opts.model ?? resolveModel('review', opts.subRole, cfg, opts.subRole ? undefined : `review:${opts.issueId}`);\n const reviewerDir = join(AGENTS_DIR, reviewerAgentId(opts.issueId, opts.subRole));\n\n await mkdir(dirname(outputPath), { recursive: true });\n await rm(outputPath, { force: true });\n await rm(join(reviewerDir, 'reviewer-signaled'), { force: true });\n await rm(join(reviewerDir, 'reviewer-launcher.pid'), { force: true });\n\n // Build Tier-1 inline summary from manifest when available (PAN-1125)\n let tier1Summary: string | undefined;\n if (opts.contextManifestPath) {\n try {\n const manifestRaw = await readFile(opts.contextManifestPath, 'utf-8');\n const manifest = JSON.parse(manifestRaw) as ReviewContextManifest;\n tier1Summary = formatTier1Summary(manifest);\n } catch (manifestErr) {\n console.warn(`[review-agent] Failed to read manifest for Tier-1 summary (${opts.issueId}/${opts.subRole}):`, manifestErr);\n }\n }\n\n const prompt = await Effect.runPromise(buildConvoyPrompt({\n issueId: opts.issueId,\n subRole: opts.subRole,\n outputPath,\n synthesisAgentId,\n contextManifestPath: opts.contextManifestPath,\n tier1Summary,\n }));\n\n // PAN-1862: convoy sub-reviewers RESUME by default too — same rule as quick review. Each\n // lane keeps its prior round's context so a re-review checks the fix instead of re-reading\n // the whole diff. Fresh-spawn only on a harness/model change or when no session exists.\n // A forked first-cycle spawn (forkedSessionId) bypasses the saved-resume decision entirely:\n // there is no prior lane context, and the fork IS the context.\n const reviewerAgent = reviewerAgentId(opts.issueId, opts.subRole);\n const savedReviewer = opts.forkedSessionId ? null : getAgentStateSync(reviewerAgent);\n const canResumeReviewer = !opts.forkedSessionId && reviewResumeDecision({\n requestedModel: opts.model ?? model,\n requestedHarness: opts.harness,\n savedModel: savedReviewer?.model,\n savedHarness: savedReviewer?.harness,\n hasSavedState: !!savedReviewer,\n hasSavedSession: !!getLatestSessionIdSync(reviewerAgent),\n });\n if (canResumeReviewer) {\n console.log(`[review-agent] Resuming convoy sub-reviewer ${opts.subRole} for ${opts.issueId} — preserving context (PAN-1862)`);\n const resumeResult = await resumeAgent(reviewerAgent, prompt);\n if (resumeResult.success) {\n try {\n const resumed = getAgentStateSync(reviewerAgent);\n if (resumed) {\n resumed.reviewSubRole = opts.subRole;\n resumed.reviewRunId = opts.runId;\n resumed.reviewOutputPath = outputPath;\n resumed.reviewSynthesisAgentId = synthesisAgentId;\n resumed.reviewDeadlineAt = new Date(Date.now() + REVIEWER_TIMEOUT_MS).toISOString();\n await Effect.runPromise(saveAgentState(resumed));\n }\n } catch { /* non-fatal */ }\n return { success: true, message: `Review ${opts.subRole} resumed (session preserved): ${reviewerAgent}`, sessionId: reviewerAgent };\n }\n console.warn(`[review-agent] Convoy sub-reviewer ${opts.subRole} resume failed; falling back to a fresh session: ${resumeResult.error}`);\n }\n\n const forkedPreface = opts.forkedSessionId\n ? [\n 'SHARED DISCOVERY CONTEXT (PAN-1862): this session was forked from the review',\n 'parent AFTER it completed a shared discovery pass — the diff, the high-risk',\n 'changed files, and their surrounding code are already in your history above.',\n 'That pass exists for cost (forked reviewers reuse the warm prompt cache instead',\n 'of four full-price re-reads) and for consistency (every reviewer sees the same',\n 'curated context). BUILD ON IT: do not re-run a broad git diff and do not',\n 're-read the files already shown above; read further code only where your',\n 'sub-role needs deeper detail.',\n '',\n ].join('\\n')\n : '';\n const run = await spawnRun(opts.issueId, 'review', {\n workspace: opts.workspace,\n subRole: opts.subRole,\n prompt: forkedPreface + prompt,\n model,\n harness: opts.harness,\n ...(opts.forkedSessionId ? { resumeSessionId: opts.forkedSessionId } : {}),\n // PAN-977: thread the synthesis wiring up front so the generated launcher\n // owns the REVIEWER_READY/FAILED/TIMEOUT signal deterministically.\n reviewSynthesisAgentId: synthesisAgentId,\n reviewOutputPath: outputPath,\n allowHost: opts.allowHost ?? false,\n });\n run.reviewSubRole = opts.subRole;\n run.reviewRunId = opts.runId;\n run.reviewOutputPath = outputPath;\n run.reviewSynthesisAgentId = synthesisAgentId;\n run.reviewDeadlineAt = new Date(Date.now() + REVIEWER_TIMEOUT_MS).toISOString();\n if (opts.forkedSessionId) run.reviewForkedFromParent = true;\n await Effect.runPromise(saveAgentState(run));\n try {\n const { notifyPipelineSync } = await import('../pipeline-notifier.js');\n notifyPipelineSync({ type: 'reviewer_started', issueId: opts.issueId, role: opts.subRole, sessionName: run.id });\n } catch {\n // Non-fatal\n }\n return { success: true, message: `Review ${opts.subRole} spawned: ${run.id}`, sessionId: run.id };\n } catch (err) {\n return {\n success: false,\n message: `Failed to spawn review ${opts.subRole}`,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n\n/**\n * PAN-1862: selective re-review scope for one dispatch — which convoy reviewers\n * run this cycle and which carry their prior passed verdict forward. Shared by\n * the inline dispatch path and the discovery-ready fork handler.\n */\nexport async function computeConvoyScope(issueId: string, workspace: string): Promise<{\n inScope: ReviewSubRole[];\n carried: Array<{ subRole: ReviewSubRole; atCommit?: string }>;\n scope: ReReviewScope;\n}> {\n let inScope: ReviewSubRole[] = [...REVIEW_SUB_ROLES];\n let carried: Array<{ subRole: ReviewSubRole; atCommit?: string }> = [];\n let scope: ReReviewScope = 'changed';\n try {\n // Dynamic import: review-status.ts reaches back into cloister via review-agent,\n // so a static edge here would close a module cycle (lint:circular).\n const { getReviewStatusSync } = await import('../review-status.js');\n scope = resolveReReviewScope(issueId);\n const priorVerdicts = getReviewStatusSync(issueId)?.reviewerVerdicts as ReviewerVerdictsMap | undefined;\n let changedFiles: string[] | undefined;\n const anchors = new Set(\n Object.values(priorVerdicts ?? {}).map(v => v?.atCommit).filter((c): c is string => !!c),\n );\n if (anchors.size === 1) {\n try {\n const { stdout } = await execAsync(`git diff --name-only ${[...anchors][0]}..HEAD`, {\n cwd: workspace, encoding: 'utf-8', timeout: 15_000,\n });\n changedFiles = stdout.split('\\n').map(l => l.trim()).filter(Boolean);\n } catch { /* anchor unreachable (rebase) -> unknown drift -> all run */ }\n }\n inScope = reviewersToRerun({ scope, priorVerdicts, changedFiles });\n carried = REVIEW_SUB_ROLES\n .filter(r => !inScope.includes(r))\n .map(r => ({ subRole: r, atCommit: priorVerdicts?.[r]?.atCommit }));\n if (carried.length > 0) {\n console.log(`[review-agent] Selective re-review for ${issueId} (scope=${scope}): re-running [${inScope.join(', ')}], carrying forward [${carried.map(c => c.subRole).join(', ')}]`);\n }\n } catch (scopeErr) {\n console.warn(`[review-agent] Selective re-review scope resolution failed for ${issueId} — running the full convoy:`, scopeErr);\n inScope = [...REVIEW_SUB_ROLES];\n carried = [];\n }\n return { inScope, carried, scope };\n}\n\n/**\n * PAN-1862 Phase A: fork the synthesis parent's Claude session JSONL to a fresh\n * session id so a convoy reviewer can `--resume` it and inherit the discovery\n * context (and its warm, content-addressed prompt cache). Returns null when the\n * fork is not possible — caller degrades to a fresh independent spawn (NFR-2).\n * The source JSONL is copied, never modified.\n */\nasync function forkParentSessionForReviewer(parentAgentId: string, workspace: string): Promise<string | null> {\n try {\n const { getLatestSessionIdSync } = await import('../agents.js');\n const parentSessionId = getLatestSessionIdSync(parentAgentId);\n if (!parentSessionId) return null;\n const src = sessionFilePath(workspace, parentSessionId);\n const { existsSync } = await import('fs');\n if (!existsSync(src)) return null;\n const { reserveForkSession, copySessionForFork } = await import('../conversations/session-fork.js');\n const reserved = await reserveForkSession(workspace);\n await copySessionForFork(src, reserved.sessionFile, { fullHistory: true });\n return reserved.sessionId;\n } catch (err) {\n console.warn(`[review-agent] Fork from ${parentAgentId} failed (degrading to independent spawn): ${err instanceof Error ? err.message : String(err)}`);\n return null;\n }\n}\n\nexport interface ConvoyLaunchParams {\n issueId: string;\n workspace: string;\n runId: string;\n synthesisAgentId: string;\n inScope: ReviewSubRole[];\n carried: Array<{ subRole: ReviewSubRole; atCommit?: string }>;\n scope: ReReviewScope;\n contextManifestPath?: string;\n model?: string;\n harness?: RuntimeName;\n allowHost?: boolean;\n /** PAN-1862 Phase A: fork each eligible first-cycle reviewer from the parent's session. */\n forkFromParent?: boolean;\n}\n\n/**\n * Launch the review convoy for one run: write carried-forward stub reports, then\n * spawn (or fork-resume) each in-scope sub-reviewer. Shared by the inline\n * dispatch path (no fork) and the discovery-ready handler (fork).\n */\nexport async function launchConvoyReviewersPromise(params: ConvoyLaunchParams): Promise<Array<{ success: boolean; message: string }>> {\n const reviewDir = join(params.workspace, PAN_DIRNAME, 'review', params.runId);\n // PAN-1862 (FR-8): materialize carried-forward verdicts as stub reports in the\n // NEW run directory so synthesis and the deacon fallback still see one report\n // per sub-role, exactly as when every reviewer runs. Blocking-findings\n // extraction on a stub finds none -> the sub-role reads as passed.\n if (params.carried.length > 0) {\n await mkdir(reviewDir, { recursive: true });\n for (const c of params.carried) {\n const stubPath = reviewerAgentOutputPath(params.workspace, params.runId, c.subRole);\n const anchorNote = c.atCommit ? ` at commit ${c.atCommit.slice(0, 8)}` : '';\n await writeFile(stubPath, [\n `# ${c.subRole} review — VERDICT CARRIED FORWARD`,\n '',\n '## Verdict: APPROVED (carried forward — reviewer not re-run this cycle)',\n '',\n `This reviewer passed the prior cycle${anchorNote} and no files in its domain`,\n `changed since (reReviewScope=${params.scope}, PAN-1862 selective re-review).`,\n 'Its prior findings report remains the report of record for that verdict.',\n '',\n '## Findings',\n '',\n 'None.',\n '',\n ].join('\\n'), 'utf-8');\n }\n }\n\n const cfg = loadYamlConfig().config;\n const { getAgentStateSync } = await import('../agents.js');\n const parentState = getAgentStateSync(params.synthesisAgentId);\n const reviewerResults = await Promise.all(params.inScope.map(async (subRole) => {\n const outputPath = reviewerAgentOutputPath(params.workspace, params.runId, subRole);\n\n // PAN-1862 Phase A fork decision, per reviewer: fork only when (a) fork mode is\n // on, (b) the parent runs claude-code (the fork machinery is Claude's --resume),\n // (c) the reviewer resolves to the SAME model as the parent (the cache is\n // per-model — a mismatched fork would replay the history at full price and the\n // Settings banner is the operator surface for that), and (d) the reviewer has\n // no resumable prior-cycle session of its own (its OWN context beats a re-fork —\n // PRD decision 3). Every failure degrades to today's independent spawn (NFR-2).\n let forkedSessionId: string | undefined;\n if (params.forkFromParent && parentState?.harness === 'claude-code' && !params.harness) {\n try {\n const { getLatestSessionIdSync } = await import('../agents.js');\n const reviewerModel = params.model ?? resolveModel('review', subRole, cfg);\n const hasOwnSession = !!getLatestSessionIdSync(reviewerAgentId(params.issueId, subRole));\n if (!hasOwnSession && reviewerModel === parentState.model) {\n forkedSessionId = (await forkParentSessionForReviewer(params.synthesisAgentId, params.workspace)) ?? undefined;\n if (forkedSessionId) {\n console.log(`[review-agent] Forked ${subRole} reviewer for ${params.issueId} from ${params.synthesisAgentId}'s discovery session (PAN-1862)`);\n }\n }\n } catch { /* degrade to independent spawn */ }\n }\n\n const result = await Effect.runPromise(spawnReviewSubRoleForIssue({\n issueId: params.issueId,\n workspace: params.workspace,\n subRole,\n runId: params.runId,\n outputPath,\n contextManifestPath: params.contextManifestPath,\n synthesisAgentId: params.synthesisAgentId,\n ...(params.model ? { model: params.model } : {}),\n ...(params.harness ? { harness: params.harness } : {}),\n ...(forkedSessionId ? { forkedSessionId } : {}),\n allowHost: params.allowHost ?? false,\n }));\n if (!result.success) {\n try {\n const { messageAgent } = await import('../agents.js');\n await messageAgent(params.synthesisAgentId, `REVIEWER_FAILED ${subRole} ${result.error ?? result.message}`);\n } catch (signalErr) {\n console.warn(`[review-agent] Failed to signal ${subRole} spawn failure to ${params.synthesisAgentId}:`, signalErr);\n }\n }\n return result;\n }));\n\n const failedReviewers = reviewerResults.filter(r => !r.success);\n if (failedReviewers.length > 0) {\n console.warn(`[review-agent] Convoy launched for ${params.issueId}, but ${failedReviewers.length} reviewer(s) failed to spawn`);\n }\n return reviewerResults;\n}\n\n\n\nexport const buildConvoyPrompt = (opts: {\n issueId: string;\n subRole: string;\n outputPath: string;\n synthesisAgentId: string;\n contextManifestPath?: string;\n tier1Summary?: string;\n}): Effect.Effect<string> => Effect.promise(() => buildConvoyPromptPromise(opts));\n\n/**\n * Effect variant of {@link spawnReviewSubRoleForIssue}. The Promise version\n * already aggregates errors into the structured result shape, so the Effect\n * form lifts via `Effect.promise`.\n */\nexport const spawnReviewSubRoleForIssue = (opts: {\n issueId: string;\n workspace: string;\n subRole: ReviewSubRole;\n runId: string;\n outputPath?: string;\n contextManifestPath?: string;\n synthesisAgentId?: string;\n model?: string;\n harness?: RuntimeName;\n allowHost?: boolean;\n}): Effect.Effect<{ success: boolean; message: string; error?: string; sessionId?: string }> =>\n Effect.promise(() => spawnReviewSubRoleForIssuePromise(opts));\n\n/**\n * Effect variant of {@link spawnReviewRoleForIssue}. The Promise version\n * returns a structured result instead of throwing, so the Effect form lifts\n * via `Effect.promise`.\n */\n\n\n/**\n * PAN-1862 Phase A (FR-2/FR-3/FR-4, NFR-5): handle the parent's discovery-ready\n * signal — fork the parent's session into the convoy reviewers and launch them.\n * Idempotent: a repeat signal (or a signal after the convoy already launched)\n * is a no-op. The parent survives unmodified and resumes its synthesis role;\n * the CLI (`pan admin specialists discovery-ready review <id>`) and the deacon\n * stalled-discovery backstop both land here.\n */\nexport async function handleReviewDiscoveryReady(\n issueId: string,\n opts: { source?: string } = {},\n): Promise<{ success: boolean; message: string; launched?: number }> {\n const normalized = issueId.toUpperCase();\n const parentId = `agent-${normalized.toLowerCase()}-review`;\n const { saveAgentState, getAgentStateSync } = await import('../agents.js');\n const parent = getAgentStateSync(parentId);\n if (!parent) {\n return { success: false, message: `No review parent state for ${normalized} — nothing to fork` };\n }\n const workspace = parent.workspace;\n const runId = parent.reviewRunId;\n if (!workspace || !runId) {\n return { success: false, message: `Review parent for ${normalized} is missing workspace/runId state — cannot launch the convoy` };\n }\n\n // PAN-2585: the signal is AUTHORITATIVE. `reviewDiscoveryPending` is persisted only\n // in state.json and is invisible through the DB-backed agent reader, so it must not\n // gate the launch — gating on it left parents standing by forever for reviewers that\n // were never forked. Idempotency comes from evidence instead: a live reviewer\n // session, or a reviewer output already written for the CURRENT run, means the\n // convoy launched — no-op. No evidence means launch, flag or no flag.\n try {\n const sessions = await Effect.runPromise(listSessionNames());\n const reviewerPrefix = `agent-${normalized.toLowerCase()}-review-`;\n if (sessions.some(name => name.startsWith(reviewerPrefix))) {\n parent.reviewDiscoveryPending = false;\n await Effect.runPromise(saveAgentState(parent));\n return { success: true, message: `Convoy already launched for ${normalized} — no-op` };\n }\n } catch { /* liveness probe failure — proceed; spawnRun's own guards hold */ }\n try {\n const { existsSync } = await import('node:fs');\n const hasRunOutput = REVIEW_SUB_ROLES.some(subRole =>\n existsSync(reviewerAgentOutputPath(workspace, runId, subRole)),\n );\n if (hasRunOutput) {\n parent.reviewDiscoveryPending = false;\n await Effect.runPromise(saveAgentState(parent));\n return { success: true, message: `Convoy for ${normalized} run ${runId} already produced reviewer output — no-op` };\n }\n } catch { /* output probe failure — proceed */ }\n\n // Clear the pending flag BEFORE launching so a concurrent duplicate signal\n // short-circuits on the check above / the flag here.\n parent.reviewDiscoveryPending = false;\n parent.reviewDiscoveryReadyAt = new Date().toISOString();\n await Effect.runPromise(saveAgentState(parent));\n\n const { inScope, carried, scope } = await computeConvoyScope(normalized, workspace);\n const results = await launchConvoyReviewersPromise({\n issueId: normalized,\n workspace,\n runId,\n synthesisAgentId: parentId,\n inScope,\n carried,\n scope,\n contextManifestPath: parent.reviewContextManifestPath,\n allowHost: parent.hostOverride ?? false,\n forkFromParent: true,\n });\n\n const refreshed = getAgentStateSync(parentId);\n if (refreshed) {\n refreshed.reviewConvoyForkedAt = new Date().toISOString();\n await Effect.runPromise(saveAgentState(refreshed));\n }\n\n const launched = results.filter(r => r.success).length;\n const message = `Discovery-ready for ${normalized}${opts.source ? ` (${opts.source})` : ''}: launched ${launched}/${inScope.length} convoy reviewer(s)${carried.length ? `, carried [${carried.map(c => c.subRole).join(', ')}]` : ''}`;\n console.log(`[review-agent] ${message}`);\n emitActivityEntrySync({ source: 'review', level: 'info', message, issueId: normalized });\n return { success: launched > 0 || inScope.length === 0, message, launched };\n}\n\n\n\n/** PAN-1862 (FR-7): resolved re-review scope — merged config, default 'changed'. */\nexport function resolveReReviewScope(issueId?: string): ReReviewScope {\n // PAN-1874: per-issue record override beats merged project/global config\n // (same resolution shape as resolveReviewMode in review-agent.ts).\n if (issueId) {\n try {\n const project = resolveProjectForIssue(issueId);\n const issueScope = project ? readIssueRecordSync(project, issueId)?.reReviewScope : undefined;\n if (issueScope === 'all' || issueScope === 'changed' || issueScope === 'blockers') return issueScope;\n } catch { /* fall through to config */ }\n }\n const scope = loadYamlConfig().config.roles?.review?.reReviewScope;\n return scope === 'all' || scope === 'blockers' ? scope : 'changed';\n}\n\n\n","/**\n * Review role entry point.\n *\n * PAN-1048 review feedback 007: every legacy convoy helper has been retired.\n * The bash/tmux coordinator path (dispatchParallelReview /\n * spawnReviewCoordinatorSession / runParallelReview) was deleted in R6, and\n * the round-7 cleanup additionally removed the supporting cast that the\n * coordinator used to drive — spawnSingleReviewer, waitForReviewer,\n * archiveReviewerRound, parseReviewSynthesis, parseAgentOutput,\n * selectCompletedReviewers, getReviewAgents, getFilesChangedFromPR,\n * buildReviewFeedbackBody, parseReviewerTemplate, resolvePromptTemplatePath\n * (and the resolveTemplatePath alias), resolveReviewerModel,\n * reviewResultToReviewStatus, reviewerRetryBackoffMs,\n * isRetryableReviewerFailure, the ReviewContext / ReviewResult /\n * ReviewerTemplate / ReviewerRoundArtifact / ReviewerOutcome /\n * ReviewerWaitResult / ReviewerFailureReason / ReviewHistoryEntry types,\n * and DEFAULT_REVIEW_AGENTS / REVIEW_TIMEOUT_MS / MAX_REVIEWER_TIMEOUT_RETRIES\n * / REVIEWER_TIMEOUT_RETRY_BACKOFF_MS / REVIEW_HISTORY_DIR / REVIEW_HISTORY_FILE\n * / SPECIALISTS_DIR constants. None of these had any production caller after R6;\n * their tests went with them.\n *\n * Every active review surface — POST /api/review/:issueId/trigger, the\n * reactive scheduler review branch, and the dashboard kanban \"Review again\"\n * button — flows through\n * spawnReviewRoleForIssue → spawnRun(issueId, 'review'). The review role\n * launches four isolated review sub-role sessions via `pan review spawn-reviewer`,\n * then writes the report and signals the verdict via Overdeck's CLI inside\n * the role itself (see roles/review.md).\n *\n * Surface area kept:\n * - spawnReviewRoleForIssue — the only review entry point\n * - killAllReviewerSessions — kill the canonical reviewer sessions\n * for one issue (merge-agent +\n * dashboard cancel/abort routes)\n * - killAllReviewSessions — kill ALL review sessions on shutdown\n * (pan down)\n */\n\nimport { exec } from 'child_process';\nimport { mkdir, readFile, rm, writeFile } from 'fs/promises';\nimport { dirname, join } from 'path';\nimport { promisify } from 'util';\nimport { Effect } from 'effect';\nimport { killSession, listSessionNames, isPaneDead } from '../tmux.js';\nimport { emitActivityEntrySync } from '../activity-logger.js';\nimport { removeAgentSync, listAgentIdsByPrefixSync } from '../overdeck/agents.js';\nimport { getReviewStatusSync, setReviewStatusSync } from '../review-status.js';\nimport { loadConfigSync as loadYamlConfig, resolveModel, type ReviewMode } from '../config-yaml.js';\nimport { buildReviewContext, formatTier1Summary, type ReviewContextManifest } from './review-context.js';\nimport { buildRealConflictGateDeps, getCachedConflictGateMergeability, resolveConflictGate } from './conflict-gate.js';\nimport { REVIEW_SUB_ROLES, type ReviewSubRole } from './review-monitor.js';\nimport { reviewResumeDecision } from './review-resume-decision.js';\nimport { type ReReviewScope } from './review-rerun-scope.js';\nimport {\n computeConvoyScope,\n launchConvoyReviewersPromise,\n} from './review-convoy.js';\nimport { shouldSkipDispatchAsMerged } from './merge-verification.js';\nimport { readIssueRecordSync, resolveProjectForIssue } from '../pan-dir/record.js';\nimport { PAN_DIRNAME } from '../pan-dir/types.js';\nimport { AGENTS_DIR, packageRoot, sessionFilePath } from '../paths.js';\nimport { getAgentStateSync } from '../agents.js';\nimport type { RuntimeName } from '../runtimes/types.js';\n\nconst execAsync = promisify(exec);\n// PAN-1531: review-temp stash helpers removed.\n// Review now runs against the committed diff only. The dirty-worktree gate\n// at pan done time (and the same gate added to /api/review/:id/request)\n// guarantees the worktree is clean before specialists see the diff.\n\nfunction buildReviewRolePrompt(opts: {\n issueId: string;\n workspace: string;\n branch: string;\n prUrl?: string;\n runId: string;\n reviewDir: string;\n contextManifestPath?: string;\n tier1Summary?: string;\n /** PAN-1862 (FR-9): sub-roles actually running this cycle (default: all four). */\n inScopeSubRoles?: ReviewSubRole[];\n /** PAN-1862 (FR-9): sub-roles whose passed verdicts are carried forward this cycle. */\n carriedSubRoles?: Array<{ subRole: ReviewSubRole; atCommit?: string }>;\n /**\n * PAN-1862 Phase A: when true, the parent performs SHARED DISCOVERY first and\n * signals `pan admin specialists discovery-ready review <id>`; the server then\n * forks this session into the convoy so the reviewers inherit the warm cache.\n */\n discovery?: boolean;\n}): string {\n const inScope = opts.inScopeSubRoles && opts.inScopeSubRoles.length > 0 ? opts.inScopeSubRoles : [...REVIEW_SUB_ROLES];\n const carried = opts.carriedSubRoles ?? [];\n const subRoleFiles = REVIEW_SUB_ROLES.map(r => ` ${join(opts.reviewDir, `${r}.md`)}`).join('\\n');\n const expectedSignals = inScope.map(r => ` REVIEWER_READY ${r} <outputPath> or REVIEWER_FAILED ${r} <reason> or REVIEWER_TIMEOUT ${r} <reason>`).join('\\n');\n const synthesisPath = join(opts.reviewDir, 'synthesis.md');\n const runningDesc = inScope.length === REVIEW_SUB_ROLES.length\n ? 'the four convoy reviewers (security, correctness, performance, requirements)'\n : `${inScope.length} convoy reviewer(s) this cycle (${inScope.join(', ')})`;\n const carriedSection = carried.length > 0\n ? [\n '',\n `CARRIED-FORWARD VERDICTS (PAN-1862 selective re-review): ${carried.map(c => c.subRole).join(', ')}.`,\n 'These reviewers PASSED the prior cycle and none of their domain files changed',\n 'since, so they were NOT re-run. Their stub reports are already written in the',\n 'review directory — treat each as a passed verdict. Do NOT wait for signals',\n 'from them; they will never arrive.',\n ].join('\\n')\n : '';\n const discoverySection = opts.discovery\n ? [\n `DISCOVERY + SYNTHESIS — REVIEW for ${opts.issueId}`,\n '',\n 'PHASE 1 — SHARED DISCOVERY (do this FIRST):',\n 'Read the code the whole review convoy will need so it lives in THIS',\n \"session's history. WHY: after you signal readiness the server FORKS this\",\n 'session into the convoy reviewers, and because the prompt cache is',\n 'content-addressed, everything you read here becomes a ~90%-discounted',\n 'cache read for every forked reviewer instead of four independent',\n 'full-price re-reads. Reviewers also review better when they all see the',\n 'same curated context and understand the change as a whole.',\n '',\n '1. Read the context manifest (path below): risk ranking + acceptance criteria.',\n '2. Read the committed diff for the branch (git diff against the merge base).',\n '3. Read the FULL contents of the HIGH-risk changed files and the immediately',\n ' surrounding code they depend on. Stay within the manifest scope — this is',\n ' curation for the convoy, not an open-ended crawl.',\n '',\n 'Then signal readiness EXACTLY ONCE (repeat signals are a server-side no-op):',\n ` pan admin specialists discovery-ready review ${opts.issueId}`,\n '',\n 'PHASE 2 — STANDBY (after the signal):',\n `The server forks this session into ${runningDesc}.`,\n 'Your work resumes only once they finish.',\n '',\n ]\n : [\n `STANDBY — REVIEW SYNTHESIS for ${opts.issueId}`,\n '',\n `Do NOT do anything yet. The Overdeck server has already spawned ${runningDesc}`,\n 'and they are running in parallel right now. Your work begins only once they finish.',\n '',\n ];\n const prompt = [\n ...discoverySection,\n `You will receive exactly one \\`pan tell\\` signal per RUNNING sub-role as each`,\n 'reviewer finishes — these are delivered to you as user messages:',\n expectedSignals,\n carriedSection,\n '',\n `Until all ${inScope.length} terminal signal(s) have arrived: do nothing. Do not read the`,\n 'reviewer output files, do not run git, do not inspect tmux sessions, do not',\n 'poll anything. Just wait — the reviewers notify you when they finish, and',\n 'Deacon is the failsafe if one never starts or never completes. Acting early',\n 'wastes tokens reviewing nothing.',\n '',\n `Once you have all ${inScope.length} terminal signal(s), follow roles/review.md exactly to`,\n 'read the reports (including any carried-forward stubs), synthesize the verdict,',\n 'write the synthesis report, and signal the status.',\n '',\n '── Review context ──',\n `Issue: ${opts.issueId}`,\n `Branch: ${opts.branch}`,\n `Workspace: ${opts.workspace}`,\n opts.prUrl ? `PR: ${opts.prUrl}` : `PR: (resolve via: gh pr view ${opts.branch})`,\n `Run ID: ${opts.runId}`,\n `Review directory: ${opts.reviewDir}`,\n `Synthesis output file: ${synthesisPath}`,\n '',\n opts.tier1Summary\n ? [\n 'Shared review context:',\n '─────────────────────────────────────────────────────────────',\n opts.tier1Summary,\n '─────────────────────────────────────────────────────────────',\n '',\n opts.contextManifestPath ? `Full manifest: ${opts.contextManifestPath}` : '',\n ].join('\\n')\n : opts.contextManifestPath\n ? `Context manifest: ${opts.contextManifestPath}`\n : 'Context manifest: (missing — block review per roles/review.md)',\n '',\n 'Convoy reviewer output files (read each one ONLY after its REVIEWER_READY signal):',\n subRoleFiles,\n '',\n 'After writing the synthesis report, signal the verdict with Overdeck CLI,',\n 'including a per-reviewer verdict for each sub-role that RAN this cycle',\n '(PAN-1862 — this is what lets the next re-review skip provably-clean reviewers;',\n 'do NOT list carried-forward sub-roles, their verdicts are already recorded):',\n ` pan admin specialists done review ${opts.issueId} --status passed --notes \"<one-line summary>\" --reviewers \"${inScope.map(r => `${r}=passed`).join(',')}\"`,\n ` pan admin specialists done review ${opts.issueId} --status blocked --notes \"<one-line top blocker>\" --reviewers \"<subRole>=passed|blocked for each of: ${inScope.join(', ')}>\"`,\n '',\n // PAN-2007: do NOT tell the agent to `exit`. The session is kept alive through\n // the pipeline (KEEP_SPECIALIST_SESSIONS_ALIVE) so it can be reused for the next\n // review cycle without a cold re-spawn. Exiting before the signal command is\n // what stranded reviews at reviewStatus=reviewing.\n 'After running the signal command above, STOP and wait — do not exit, do not run',\n 'any further commands. The session stays open for the next review cycle.',\n '',\n 'Reactive Cloister dispatches the test role after review passes. Never queue tests yourself and never edit code.',\n ].filter(Boolean).join('\\n');\n\n const sizeBytes = Buffer.byteLength(prompt, 'utf-8');\n console.log(`[review-agent] Synthesis prompt for ${opts.issueId}: ${sizeBytes} bytes`);\n return prompt;\n}\n\n// PAN-1981 (quick path to production): the review role agent reviews the diff\n// ITSELF — no convoy, no synthesis. `buildReviewRolePrompt` above (the synthesis\n// \"stand by, wait for the convoy\" prompt) is kept for when we restore the convoy\n// as an opt-in (#1982 fast-follow); for now the review agent gets this self-review\n// prompt instead. We will decide convoy-vs-self-review (and better per-harness\n// message transmission) in the fast-follow.\nfunction buildSelfReviewPrompt(opts: {\n issueId: string;\n workspace: string;\n branch: string;\n prUrl?: string;\n runId: string;\n reviewDir: string;\n contextManifestPath?: string;\n tier1Summary?: string;\n}): string {\n const reviewReportPath = join(opts.reviewDir, 'review.md');\n const prompt = [\n `CODE REVIEW for ${opts.issueId} — you are the sole reviewer; review the change yourself.`,\n '',\n 'Review the diff for this branch yourself, across ALL dimensions in one pass:',\n 'correctness/logic, security, requirements/acceptance-criteria, and performance.',\n 'Do NOT spawn or wait for any sub-reviewers — there is no convoy; you do the',\n 'whole review yourself and emit the verdict.',\n '',\n '── Review context ──',\n `Issue: ${opts.issueId}`,\n `Branch: ${opts.branch}`,\n `Workspace: ${opts.workspace}`,\n opts.prUrl ? `PR: ${opts.prUrl}` : `PR: (resolve via: gh pr view ${opts.branch})`,\n `Run ID: ${opts.runId}`,\n `Review directory: ${opts.reviewDir}`,\n `Review output file: ${reviewReportPath}`,\n '',\n opts.tier1Summary\n ? [\n 'Shared review context (risk-ranked changed files + acceptance criteria):',\n '─────────────────────────────────────────────────────────────',\n opts.tier1Summary,\n '─────────────────────────────────────────────────────────────',\n '',\n opts.contextManifestPath ? `Full manifest: ${opts.contextManifestPath}` : '',\n ].join('\\n')\n : opts.contextManifestPath\n ? `Context manifest: ${opts.contextManifestPath}`\n : 'Context manifest: (missing — inspect the diff directly: git diff origin/main...HEAD)',\n '',\n 'How to review:',\n '1. Read the diff — use the manifest risk ranking, `git diff` the high-risk files,',\n ' and read the surrounding code as needed.',\n '2. Evaluate correctness, security, requirements/AC, and performance. Use the',\n ' severity + verdict vocabulary in roles/review.md.',\n `3. Write your findings to ${reviewReportPath}.`,\n '',\n 'Then signal the verdict with the Overdeck CLI (exactly one):',\n ` pan admin specialists done review ${opts.issueId} --status passed --notes \"<one-line summary>\"`,\n ` pan admin specialists done review ${opts.issueId} --status blocked --notes \"<one-line top blocker>\"`,\n '',\n // PAN-2007: do NOT tell the agent to `exit`. The session is kept alive through\n // the pipeline (KEEP_SPECIALIST_SESSIONS_ALIVE) so it can be reused for the next\n // review cycle without a cold re-spawn. Exiting before the signal command is\n // what stranded reviews at reviewStatus=reviewing.\n 'After running the signal command above, STOP and wait — do not exit, do not run',\n 'any further commands. The session stays open for the next review cycle.',\n '',\n 'Reactive Cloister dispatches the test role after review passes. Never queue tests yourself and never edit code.',\n ].filter(Boolean).join('\\n');\n\n const sizeBytes = Buffer.byteLength(prompt, 'utf-8');\n console.log(`[review-agent] Self-review prompt for ${opts.issueId}: ${sizeBytes} bytes`);\n return prompt;\n}\nasync function spawnReviewRoleForIssuePromise(\n opts: { issueId: string; workspace: string; branch: string; prUrl?: string; model?: string; harness?: RuntimeName; force?: boolean; allowHost?: boolean },\n): Promise<{ success: boolean; message: string; error?: string; gated?: boolean }> {\n const reviewSessionName = `agent-${opts.issueId.toLowerCase()}-review`;\n\n // PAN-2420: GitHub-authoritative guard. Do not waste time on conflict-gate\n // checks or context builds for a PR that GitHub already reports merged.\n const mergedGuard = await shouldSkipDispatchAsMerged(opts.issueId);\n if (mergedGuard.skip) {\n const message = `[review-agent] Skipping review dispatch for ${opts.issueId} — ${mergedGuard.reason}`;\n console.log(message);\n emitActivityEntrySync({ source: 'cloister', level: 'info', message, issueId: opts.issueId });\n return { success: false, message };\n }\n\n // PAN-1862 (FR-14): review mode 'none' — skip the AI review entirely. This sits at\n // the single review entry point so the trigger route, host auto-dispatch, and every\n // Deacon re-dispatch site all honor it without per-call-site logic. The pre-review\n // verification gate (typecheck/lint/test floor) has already run by the time any\n // caller reaches here — 'none' skips only the AI review, never the quality floor.\n // reviewSpawnedAt is stamped so the durable reviewRequestedAt intent counts as\n // serviced (otherwise needsReviewDispatch would re-fire this skip every read).\n // Setting reviewStatus 'skipped' advances the lifecycle exactly like an approved\n // review (the setReviewStatusSync write path emits review.approved for it).\n if (resolveReviewMode(opts.issueId) === 'none') {\n setReviewStatusSync(opts.issueId, {\n reviewStatus: 'skipped',\n reviewNotes: 'Review mode: none — AI review skipped by configuration; verification gate still enforced',\n reviewSpawnedAt: new Date().toISOString(),\n });\n const message = `Review skipped for ${opts.issueId} (mode=none) — advancing to test`;\n console.log(`[review-agent] ${message}`);\n emitActivityEntrySync({ source: 'review', level: 'info', message, issueId: opts.issueId });\n return { success: true, message };\n }\n\n // Idempotency: if a review role agent for this issue already has an alive\n // tmux pane, treat the current dispatch as a no-op. spawnRun has its own\n // session-exists check but it throws — we want soft \"already running\"\n // semantics so callers can keep their existing success-path messaging.\n //\n // Force mode (human override from dashboard) kills the old session and\n // respawns so the review runs against current HEAD, not stale state.\n try {\n const sessions = await Effect.runPromise(listSessionNames());\n if (sessions.includes(reviewSessionName)) {\n const paneDead = await Effect.runPromise(isPaneDead(reviewSessionName));\n\n // A synthesis agent that has finished its verdict does NOT terminate:\n // its role prompt tells it to \"exit\", but it runs `Bash(exit)` which\n // only exits a subshell — the Claude process stays idle-alive with a\n // live pane. So \"pane alive\" does NOT mean \"actively reviewing\", and the\n // old guard would skip re-dispatch forever, jamming the issue at\n // review=reviewing with no convoy actually running (PAN-1131).\n //\n // Disambiguate via the run id: every review run is keyed to a HEAD sha\n // (runId = agent-<issue>-review-<head8>). If the existing synthesis\n // session was started for a different HEAD than the one we are about to\n // review, it is a stale leftover — kill the convoy and respawn. Only a\n // session whose runId matches the *current* HEAD is genuinely the\n // review-in-progress we should defer to.\n let staleRunId = false;\n if (!paneDead && !opts.force) {\n try {\n const { stdout } = await execAsync('git rev-parse --short=8 HEAD', {\n cwd: opts.workspace,\n encoding: 'utf-8',\n timeout: 10_000,\n });\n const currentRunId = `agent-${opts.issueId.toLowerCase()}-review-${stdout.trim()}`;\n const synthReviewRunId = getAgentStateSync(reviewSessionName)?.reviewRunId;\n // A missing identity cannot prove that the live pane covers the\n // current obligation, so legacy/unknown sessions are stale too.\n if (!synthReviewRunId || synthReviewRunId !== currentRunId) {\n staleRunId = true;\n console.log(\n `[review-agent] ${reviewSessionName} is stale — runId ${synthReviewRunId ?? 'missing'} != current ${currentRunId}; killing convoy and respawning`,\n );\n }\n } catch (probeErr) {\n console.warn(\n `[review-agent] Could not probe ${reviewSessionName} runId, falling back to pane-alive idempotency:`,\n probeErr,\n );\n }\n }\n\n // PAN-1131 residual + PAN-2579: a runId-matching live pane is only \"actively\n // reviewing\" while this cycle's verdict is UNRECORDED. Once the verdict is\n // terminal, the session is warm-idle (kept alive by the warm-by-default\n // lifecycle) — a re-dispatch request must NOT be swallowed by the guard, or\n // the issue jams at a stale verdict with a live-but-finished reviewer. Fall\n // through to the respawn path below: it kills the convoy tmux and the spawn\n // machinery resumes the saved session with its context intact (warm reuse).\n let finishedIdle = false;\n if (!paneDead && !opts.force && !staleRunId) {\n try {\n const status = getReviewStatusSync(opts.issueId);\n const terminal = status?.reviewStatus === 'passed'\n || status?.reviewStatus === 'blocked'\n || status?.reviewStatus === 'failed';\n // Warm-reuse ONLY for a genuinely un-serviced newer request (same\n // ISO-string comparison as needsReviewDispatch). A terminal verdict\n // with NO newer request means this call is a stale duplicate dispatch\n // racing the verdict (the PAN-399 shape) — skip below and leave the\n // verdict alone rather than re-entering 'reviewing'.\n const newerRequest = !!status?.reviewRequestedAt\n && (!status.reviewSpawnedAt || status.reviewRequestedAt > status.reviewSpawnedAt);\n finishedIdle = terminal && newerRequest;\n if (finishedIdle) {\n console.log(\n `[review-agent] ${reviewSessionName} is finished-idle (verdict ${status?.reviewStatus}, newer request pending) — warm-reusing for the new review cycle`,\n );\n } else if (terminal) {\n console.log(\n `[review-agent] ${reviewSessionName} has a terminal verdict (${status?.reviewStatus}) and no newer request — treating this dispatch as a stale duplicate; leaving the verdict intact`,\n );\n }\n } catch (statusErr) {\n console.warn(`[review-agent] Could not probe review status for finished-idle check on ${opts.issueId}:`, statusErr);\n }\n }\n\n if (!paneDead && !opts.force && !staleRunId && !finishedIdle) {\n console.log(`[review-agent] Idempotency guard: ${reviewSessionName} already running for ${opts.issueId} — skipping spawn`);\n return { success: true, message: `Review already in progress: ${reviewSessionName}` };\n }\n // Session pane is dead, force mode, stale runId, or finished-idle — kill the\n // convoy tmux and respawn (the spawn path resumes the saved session, so a\n // warm reviewer keeps its context).\n const reason = opts.force ? 'force-killed for re-review'\n : paneDead ? 'pane is dead'\n : staleRunId ? 'stale runId'\n : 'finished-idle (warm reuse for new cycle)';\n console.log(`[review-agent] ${reviewSessionName} ${reason} — respawning convoy`);\n await Effect.runPromise(\n killAllReviewerSessions(undefined, opts.issueId).pipe(\n Effect.catch(() => Effect.succeed({ killed: [], failed: [] })),\n ),\n );\n }\n } catch (err) {\n console.warn(`[review-agent] Idempotency check failed for ${opts.issueId}, proceeding:`, err);\n }\n\n // Fast synchronous cache check for the gated case. If the probe cache says\n // the branch has conflicts (or we cannot verify mergeability), fail fast\n // without shelling out to git on the awaited request path.\n const cachedMergeability = getCachedConflictGateMergeability(opts.issueId);\n if (cachedMergeability === 'conflicts' || cachedMergeability === 'unknown') {\n const targetBranch = 'main';\n const reason = cachedMergeability === 'conflicts'\n ? `merge conflict with ${targetBranch} must be resolved before review dispatch`\n : `mergeability against ${targetBranch} could not be verified; deferring review conservatively`;\n const message = `Review dispatch deferred: ${reason}`;\n setReviewStatusSync(opts.issueId, {\n reviewStatus: 'pending',\n reviewNotes: message,\n });\n return { success: false, gated: true, message };\n }\n\n const gate = await resolveConflictGate(\n opts.issueId,\n opts.workspace,\n 'main',\n buildRealConflictGateDeps(),\n );\n if (gate.gated) {\n const message = `Review dispatch deferred: ${gate.reason ?? 'merge conflict must be resolved first'}`;\n setReviewStatusSync(opts.issueId, {\n reviewStatus: 'pending',\n reviewNotes: message,\n });\n return { success: false, gated: true, message };\n }\n\n // Clear feedback from any previous review cycle so the work agent only\n // sees current-cycle feedback when it reads .pan/feedback/.\n try {\n const { archiveFeedbackFiles } = await import('./feedback-writer.js');\n await Effect.runPromise(archiveFeedbackFiles(opts.workspace));\n } catch {\n // Non-fatal: archiving is best-effort\n }\n\n // PAN-1531: review-temp stash machinery removed. Reviewers see only the\n // committed diff because the dirty-worktree gate refuses pan done /\n // pan review request before reaching here. If callers somehow bypass the\n // gate, uncommitted scratch becomes visible in the review — that's the\n // correct fail-loud behavior, not a reason to silently stash.\n try {\n setReviewStatusSync(opts.issueId, {\n reviewStatus: 'reviewing',\n reviewSpawnedAt: new Date().toISOString(),\n });\n } catch (err) {\n console.error(`[review-agent] Failed to set reviewing status for ${opts.issueId}:`, err);\n return {\n success: false,\n message: 'Failed to initialize review status',\n error: err instanceof Error ? err.message : String(err),\n };\n }\n\n try {\n const { notifyPipelineSync } = await import('../pipeline-notifier.js');\n notifyPipelineSync({ type: 'task_queued', specialist: 'review-agent', issueId: opts.issueId });\n } catch {\n // Non-fatal\n }\n\n try {\n const { spawnRun, saveAgentState, getAgentState, getAgentStateSync, getLatestSessionIdSync, resumeAgent, wipeAgentStateDirs } = await import('../agents.js');\n const workAgentState = await Effect.runPromise(getAgentState(`agent-${opts.issueId.toLowerCase()}`));\n const allowHost = opts.allowHost === true || workAgentState?.hostOverride === true;\n\n // Build the shared context manifest before spawning so all reviewers\n // read one pre-built diff+AC object instead of each running git diff\n // independently (PAN-1059).\n //\n // Include HEAD SHA in runId so re-reviews of the same issue get their own\n // directory and don't overwrite round-1 files (collision prevention).\n let headSha = 'unknown';\n try {\n const { stdout } = await execAsync('git rev-parse --short=8 HEAD', { cwd: opts.workspace, encoding: 'utf-8', timeout: 10_000 });\n headSha = stdout.trim();\n } catch { /* non-fatal — fall back to static runId */ }\n const runId = headSha !== 'unknown'\n ? `agent-${opts.issueId.toLowerCase()}-review-${headSha}`\n : `agent-${opts.issueId.toLowerCase()}-review`;\n const reviewDir = join(opts.workspace, PAN_DIRNAME, 'review', runId);\n let contextManifestPath: string | undefined;\n let tier1Summary: string | undefined;\n try {\n const manifest = await Effect.runPromise(buildReviewContext({\n runId,\n issueId: opts.issueId,\n workspace: opts.workspace,\n branch: opts.branch,\n }));\n contextManifestPath = manifest.manifestPath;\n tier1Summary = formatTier1Summary(manifest);\n console.log(`[review-agent] Context manifest built: ${contextManifestPath} (${manifest.changedFiles.length} files)`);\n } catch (ctxErr) {\n console.warn(`[review-agent] Context manifest build failed for ${opts.issueId} — reviewers will block on missing shared context:`, ctxErr);\n }\n\n const fullReview = isExtendedReviewEnabled(opts.issueId);\n\n // PAN-1862 (FR-7/FR-8/NFR-1): selective re-review — which convoy reviewers run\n // this cycle vs carry their prior passed verdict forward (computeConvoyScope).\n const { inScope: inScopeSubRoles, carried: carriedSubRoles, scope: reReviewScope } = fullReview\n ? await computeConvoyScope(opts.issueId, opts.workspace)\n : { inScope: [...REVIEW_SUB_ROLES], carried: [], scope: 'changed' as ReReviewScope };\n\n // PAN-1862 Phase A: discovery-then-fork mode. When the full-convoy review will\n // run on claude-code, the parent does the shared discovery reads FIRST, signals\n // `pan admin specialists discovery-ready review <id>`, and the server forks its\n // session into the convoy — the reviewers replay the discovery prefix as warm\n // cache reads instead of four independent full-price re-reads. Any other\n // harness keeps the inline convoy spawn (the fork machinery is Claude Code's\n // --resume; NFR-2 explicitly degrades to independent reads there). Per-reviewer\n // model mismatches are handled at fork time, not here — a mismatched reviewer\n // simply spawns fresh while the rest fork.\n const cfgReviewHarness = loadYamlConfig().config.roles?.review?.harness;\n // PAN-2585: decide from the harness that will ACTUALLY run — the saved review\n // agent is the resume target, and model routing (not config) usually picks the\n // harness. Falling through to the 'claude-code' literal put codex parents into\n // discovery mode, where they stand by forever for a fork that can never happen.\n const savedReviewHarness = getAgentStateSync(`agent-${opts.issueId.toLowerCase()}-review`)?.harness;\n const discoveryForkMode = fullReview\n && (opts.harness ?? savedReviewHarness ?? cfgReviewHarness ?? 'claude-code') === 'claude-code';\n\n const prompt = fullReview\n ? buildReviewRolePrompt({ ...opts, runId, reviewDir, contextManifestPath, tier1Summary, inScopeSubRoles, carriedSubRoles, discovery: discoveryForkMode })\n : buildSelfReviewPrompt({ ...opts, runId, reviewDir, contextManifestPath, tier1Summary });\n\n // PAN-1862: in discovery-fork mode the convoy is NOT spawned here — the parent\n // signals discovery-ready and handleReviewDiscoveryReady launches (and forks)\n // the convoy. markDiscoveryPending records what the handler needs on the\n // parent's state; the deacon's stalled-discovery backstop covers a parent that\n // never signals.\n const markDiscoveryPending = async (synthesisAgentId: string) => {\n try {\n const parent = getAgentStateSync(synthesisAgentId);\n if (parent) {\n parent.reviewDiscoveryPending = true;\n parent.reviewContextManifestPath = contextManifestPath;\n parent.reviewDiscoveryReadyAt = undefined;\n parent.reviewConvoyForkedAt = undefined;\n parent.reviewForkCacheChecked = undefined;\n await Effect.runPromise(saveAgentState(parent));\n }\n } catch (stateErr) {\n console.warn(`[review-agent] Could not mark discovery pending on ${synthesisAgentId}:`, stateErr);\n }\n };\n const spawnConvoyReviewers = async (synthesisAgentId: string) => {\n if (discoveryForkMode) {\n await markDiscoveryPending(synthesisAgentId);\n console.log(`[review-agent] ${opts.issueId}: parent spawned in discovery mode — convoy defers to the discovery-ready signal (PAN-1862)`);\n return [];\n }\n return launchConvoyReviewersPromise({\n issueId: opts.issueId,\n workspace: opts.workspace,\n runId,\n synthesisAgentId,\n inScope: inScopeSubRoles,\n carried: carriedSubRoles,\n scope: reReviewScope,\n contextManifestPath,\n ...(opts.model ? { model: opts.model } : {}),\n ...(opts.harness ? { harness: opts.harness } : {}),\n allowHost,\n });\n };\n\n // PAN-1862: RESUME the saved review session by default. The review agent keeps the prior\n // review's context (the files it read, the findings it raised), so a re-review checks the\n // fix instead of re-researching the entire diff from scratch — the token-cost problem this\n // was set out to fix. Fresh-spawn ONLY when the harness/model actually changed (it's a\n // different agent then) or there is no resumable saved session. The resume delivery is\n // resilient (supervisor → tmux fallback, PAN-1988).\n const reviewAgentId = `agent-${opts.issueId.toLowerCase()}-review`;\n const savedReview = getAgentStateSync(reviewAgentId);\n const canResumeReview = reviewResumeDecision({\n requestedModel: opts.model,\n requestedHarness: opts.harness,\n savedModel: savedReview?.model,\n savedHarness: savedReview?.harness,\n hasSavedState: !!savedReview,\n hasSavedSession: !!getLatestSessionIdSync(reviewAgentId),\n });\n if (canResumeReview) {\n console.log(`[review-agent] Resuming saved review session for ${opts.issueId} — model/harness unchanged, preserving context (PAN-1862)`);\n const resumeResult = await resumeAgent(reviewAgentId, prompt);\n if (resumeResult.success) {\n try {\n // Keep the idempotency guard's HEAD-staleness detection honest for the resumed run.\n const resumed = getAgentStateSync(reviewAgentId);\n if (resumed) { resumed.reviewRunId = runId; await Effect.runPromise(saveAgentState(resumed)); }\n } catch { /* non-fatal */ }\n if (fullReview) {\n await spawnConvoyReviewers(reviewAgentId);\n return { success: true, message: `Convoy review resumed (session preserved): ${reviewAgentId}` };\n }\n return { success: true, message: `Review resumed (session preserved): ${reviewAgentId}` };\n }\n console.warn(`[review-agent] Review resume failed for ${reviewAgentId}; falling back to a fresh session: ${resumeResult.error}`);\n }\n // Fresh review: wipe any stale review state (harness/model changed, or the resume above\n // failed) so the new session does not inherit a mismatched saved session id.\n if (savedReview || getLatestSessionIdSync(reviewAgentId)) {\n try { await wipeAgentStateDirs(opts.issueId, { rolePrefix: 'review' }); }\n catch (wipeErr) { console.warn(`[review-agent] review state wipe before fresh spawn failed (non-fatal): ${wipeErr instanceof Error ? wipeErr.message : String(wipeErr)}`); }\n }\n const run = await spawnRun(opts.issueId, 'review', {\n workspace: opts.workspace,\n prompt,\n ...(opts.model ? { model: opts.model } : {}),\n ...(opts.harness ? { harness: opts.harness } : {}),\n ...(allowHost ? { allowHost: true } : {}),\n });\n // Persist the runId on the synthesis agent's own state so the idempotency\n // guard above can tell a genuinely-running review (runId matches current\n // HEAD) from a finished-but-idle leftover (runId from an older HEAD) — see\n // PAN-1131. Sub-reviewers already persist this; the synthesis agent did not.\n run.reviewRunId = runId;\n try {\n await Effect.runPromise(saveAgentState(run));\n } catch (saveErr) {\n console.warn(`[review-agent] Could not persist reviewRunId on ${run.id}:`, saveErr);\n }\n if (fullReview) {\n await spawnConvoyReviewers(run.id);\n console.log(`[review-agent] Review role (convoy synthesis) spawned for ${opts.issueId}: ${run.id}`);\n emitActivityEntrySync({ source: 'review', level: 'info', message: `Convoy review spawned for ${opts.issueId}: ${run.id}`, issueId: opts.issueId });\n return {\n success: true,\n message: `Convoy review spawned: ${run.id}`,\n };\n }\n\n console.log(`[review-agent] Review role (self-review) spawned for ${opts.issueId}: ${run.id}`);\n emitActivityEntrySync({ source: 'review', level: 'info', message: `Self-review spawned for ${opts.issueId}: ${run.id}`, issueId: opts.issueId });\n\n return {\n success: true,\n message: `Self-review spawned: ${run.id}`,\n };\n } catch (err) {\n console.error(`[review-agent] Failed to spawn review role for ${opts.issueId}:`, err);\n setReviewStatusSync(opts.issueId, {\n reviewStatus: 'failed',\n reviewNotes: `Review role spawn failed: ${err instanceof Error ? err.message : String(err)}`,\n });\n return {\n success: false,\n message: 'Failed to spawn review role',\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n/**\n * Kill all canonical reviewer sessions for one issue.\n *\n * PAN-915: this is no longer called per-round. Canonical reviewer sessions\n * persist across review rounds via PAN-830's `remain-on-exit on` so each\n * round resumes the same Claude process via `sendKeysAsync` — preserving\n * the reviewer's accumulated context (codebase patterns, prior findings,\n * decisions made during earlier rounds). This function is now invoked from\n * terminal lifecycle events: merge complete, reset, cancel, deep-wipe, and\n * explicit `pan review abort`.\n *\n * Matches the parent review role, convoy children, and legacy coordinator\n * sessions so callers do not need to know which review phase has started.\n */\nexport function isReviewSessionForIssue(sessionName: string, projectKey: string | undefined, issueId: string): boolean {\n const session = sessionName.toLowerCase();\n const issue = issueId.toLowerCase();\n const project = projectKey?.toLowerCase();\n\n // Belt-and-suspenders: a user conversation session (`conv-*`) must never be\n // classified as a reviewer session and swept into reviewer cleanup/kill.\n if (session.startsWith('conv-')) return false;\n\n if (session === `agent-${issue}-review` || session.startsWith(`agent-${issue}-review-`)) return true;\n if (session.startsWith(`review-${issue}-`) || session.startsWith(`review-coordinator-${issue}-`)) return true;\n if (!project) return false;\n if (session === `specialist-${project}-${issue}-review-agent`) return true;\n return session.startsWith(`specialist-${project}-${issue}-review-`);\n}async function killAllReviewerSessionsPromise(\n projectKey: string | undefined,\n issueId: string,\n): Promise<{ killed: string[]; failed: string[] }> {\n const killed: string[] = [];\n const failed: string[] = [];\n let allSessions: readonly string[];\n\n try {\n allSessions = await Effect.runPromise(listSessionNames());\n } catch (err) {\n console.warn('[review-agent] Failed to list tmux sessions during reviewer cleanup:', err instanceof Error ? err.message : String(err));\n return { killed, failed };\n }\n\n const sessionsToKill = allSessions.filter(s => isReviewSessionForIssue(s, projectKey, issueId));\n await Promise.all(\n sessionsToKill.map(async (sessionName) => {\n try {\n await Effect.runPromise(killSession(sessionName));\n console.log(`[review-agent] Killed reviewer session ${sessionName}`);\n killed.push(sessionName);\n } catch (err) {\n console.log(`[review-agent] Session ${sessionName} already gone or failed to kill: ${err instanceof Error ? err.message : String(err)}`);\n failed.push(sessionName);\n }\n }),\n );\n return { killed, failed };\n}async function killAllReviewSessionsPromise(): Promise<{ killed: string[]; failed: string[] }> {\n const killed: string[] = [];\n const failed: string[] = [];\n\n let allSessions: readonly string[];\n try {\n allSessions = await Effect.runPromise(listSessionNames());\n } catch (err) {\n console.warn('[review-agent] Failed to list tmux sessions during review cleanup:', err instanceof Error ? err.message : String(err));\n return { killed, failed };\n }\n\n const reviewPatterns = [\n /^agent-[a-z0-9-]+-review(?:-(?:security|correctness|performance|requirements))?$/i,\n /^review-coordinator-/,\n /^specialist-.+-review-/,\n /^review-[A-Z0-9]+-\\d+-\\d+/, // legacy: review-PAN-999-1713456789000-correctness\n ];\n\n const sessionsToKill = allSessions.filter(s => reviewPatterns.some(p => p.test(s)));\n if (sessionsToKill.length === 0) {\n return { killed, failed };\n }\n\n console.log(`[review-agent] Killing ${sessionsToKill.length} review session(s) during shutdown`);\n\n await Promise.all(\n sessionsToKill.map(async (sessionName) => {\n try {\n await Effect.runPromise(killSession(sessionName));\n console.log(`[review-agent] Killed review session ${sessionName}`);\n killed.push(sessionName);\n } catch (err) {\n console.log(`[review-agent] Session ${sessionName} already gone or failed to kill: ${err instanceof Error ? err.message : String(err)}`);\n failed.push(sessionName);\n }\n }),\n );\n\n return { killed, failed };\n}\n\n// ─── Effect variants (PAN-1249) ──────────────────────────────────────────────\n\n/**\n * Effect variant of {@link buildConvoyPrompt}. Template reads are the only\n * fallible step; any failure here is fatal and propagates via Effect's defect\n * channel through `Effect.promise`.\n */\nexport const spawnReviewRoleForIssue = (\n opts: { issueId: string; workspace: string; branch: string; prUrl?: string; model?: string; harness?: RuntimeName; force?: boolean; allowHost?: boolean },\n): Effect.Effect<{ success: boolean; message: string; error?: string; gated?: boolean }> =>\n Effect.promise(() => spawnReviewRoleForIssuePromise(opts));\n\n/**\n * Effect variant of {@link killAllReviewerSessions}. Session-kill failures are\n * already aggregated into the `failed` array — this wrapper preserves that\n * contract.\n */\nexport const killAllReviewerSessions = (\n projectKey: string | undefined,\n issueId: string,\n): Effect.Effect<{ killed: string[]; failed: string[] }> =>\n Effect.promise(() => killAllReviewerSessionsPromise(projectKey, issueId));\n\n/**\n * Effect variant of {@link killAllReviewSessions}. Same aggregation semantics\n * as the Promise version.\n */\nexport const killAllReviewSessions = (): Effect.Effect<{ killed: string[]; failed: string[] }> =>\n Effect.promise(() => killAllReviewSessionsPromise());\n\n// PAN-1862 resume-vs-fresh decision lives in its own pure module (review-resume-decision.ts) so\n// it is unit-testable without importing this heavy file. Re-exported for external callers.\nexport { reviewResumeDecision } from './review-resume-decision.js';\n// PAN-1862: convoy machinery lives in review-convoy.ts; re-exported here so the\n// deacon modules, tests, and the CLI keep one stable import surface.\nexport {\n buildConvoyPrompt,\n spawnReviewSubRoleForIssue,\n handleReviewDiscoveryReady,\n resolveReReviewScope,\n} from './review-convoy.js';\n\n/**\n * Is the issue carrying leftover EXTENDED-review (convoy) sub-reviewer agents from a\n * prior cycle? Quick-review — the current hardcoded mode — only ever creates the single\n * `agent-<id>-review` parent, so any `agent-<id>-review-<subRole>` is a stale ghost\n * (e.g. PAN-1866's `-correctness/-security/-performance/-requirements` from an old run).\n *\n * Seam for when extended review returns: this becomes a reviewRunId-mismatch check — a\n * sub-reviewer is stale only when its run differs from the active review run.\n */\nexport function isReviewStaleSync(issueId: string): boolean {\n return listAgentIdsByPrefixSync(`agent-${issueId.toLowerCase()}-review-`).length > 0;\n}\n\nexport function resolveReviewMode(issueId?: string): ReviewMode {\n if (issueId) {\n const project = resolveProjectForIssue(issueId);\n const issueMode = project ? readIssueRecordSync(project, issueId)?.reviewMode : undefined;\n if (issueMode === 'quick' || issueMode === 'full' || issueMode === 'none') {\n return issueMode;\n }\n }\n\n const configMode = loadYamlConfig().config.roles?.review?.mode;\n return configMode === 'full' || configMode === 'none' ? configMode : 'quick';\n}\n\n/**\n * Is EXTENDED (convoy) review enabled for this issue?\n *\n * `resolveReviewMode` is the single source of truth: per-issue record override\n * beats merged project/global config, and quick remains the default.\n */\nexport function isExtendedReviewEnabled(issueId?: string): boolean {\n return resolveReviewMode(issueId) === 'full';\n}\n\n/**\n * Tear down an issue's entire review fleet — the `agent-<id>-review` parent plus any\n * extended-mode sub-reviewers. Kills every review tmux session, then removes each agent\n * via the canonical removeAgentSync (overdeck.db row + state dir, never the JSONL\n * transcript). Does NOT reset review_status — the caller composes that (see the\n * POST /api/review/:id/purge route). Returns what was killed and removed.\n */\nexport async function purgeReviewAgentsForIssue(\n projectKey: string | undefined,\n issueId: string,\n): Promise<{ killed: string[]; removed: string[] }> {\n const killResult = await killAllReviewerSessionsPromise(projectKey, issueId);\n const removed: string[] = [];\n for (const agentId of listAgentIdsByPrefixSync(`agent-${issueId.toLowerCase()}-review`)) {\n removeAgentSync(agentId);\n removed.push(agentId);\n }\n return { killed: killResult.killed, removed };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAgB,qBAAqB,QAOzB;CACV,MAAM,eACJ,CAAC,CAAC,OAAO,kBAAkB,CAAC,CAAC,OAAO,cAAc,OAAO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,CAAC;AAM9D,+BACX,OAAO,cAAc,8BAA8B,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"review-status-BQjqQXZG.js","names":["join","fsp","join","dirname"],"sources":["../../src/lib/overdeck/agent-state-sync.ts","../../src/lib/cloister/review-status-source.ts","../../src/lib/pan-dir/record-lock.ts","../../src/lib/pan-dir/records.ts","../../src/lib/overdeck/review-status-record-sync.ts","../../src/lib/review-dispatch-decision.ts","../../src/lib/review-status.ts"],"sourcesContent":["import type { AgentState, Role } from '../agents.js';\nimport type { RuntimeName } from '../runtimes/types.js';\nimport { getOverdeckDatabaseSync } from './infra.js';\n\ntype OverdeckAgentRow = {\n id: string;\n issue_id: string;\n role: string;\n status: string;\n workspace: string;\n session_id: string | null;\n harness: string | null;\n model: string | null;\n host_override: string | null;\n delivery_method: string | null;\n started_at: number | null;\n last_resume_at: number | null;\n stopped_by_user: number | null;\n stopped_by_pause: number | null;\n kickoff_delivered: number | null;\n paused: number | null;\n paused_reason: string | null;\n yielded_by_scheduler: number | null;\n yielded_at: number | null;\n last_yield_resume_at: number | null;\n troubled: number | null;\n channels_enabled: number | null;\n consecutive_failures: number | null;\n first_failure_in_run_at: number | null;\n last_failure_next_retry_at: number | null;\n stopped_at: number | null;\n paused_at: number | null;\n troubled_at: number | null;\n last_activity: number | null;\n last_failure_reason: string | null;\n phase: string | null;\n role_run_head: string | null;\n flywheel_run_id: string | null;\n cost_so_far: number | null;\n review_sub_role: string | null;\n review_run_id: string | null;\n review_synthesis_agent_id: string | null;\n review_output_path: string | null;\n review_deadline_at: number | null;\n review_monitor_signaled: string | null;\n review_retry_attempt: number | null;\n updated_at: number;\n};\n\n/** Exported for agent-projection.ts transactional writes. */\nexport const AGENT_COLUMNS_FOR_DB = [\n 'id',\n 'issue_id',\n 'role',\n 'status',\n 'workspace',\n 'session_id',\n 'harness',\n 'model',\n 'host_override',\n 'delivery_method',\n 'started_at',\n 'last_resume_at',\n 'stopped_by_user',\n 'stopped_by_pause',\n 'kickoff_delivered',\n 'paused',\n 'paused_reason',\n 'yielded_by_scheduler',\n 'yielded_at',\n 'last_yield_resume_at',\n 'troubled',\n 'channels_enabled',\n 'consecutive_failures',\n 'first_failure_in_run_at',\n 'last_failure_next_retry_at',\n 'stopped_at',\n 'paused_at',\n 'troubled_at',\n 'last_activity',\n 'last_failure_reason',\n 'phase',\n 'role_run_head',\n 'flywheel_run_id',\n 'cost_so_far',\n 'review_sub_role',\n 'review_run_id',\n 'review_synthesis_agent_id',\n 'review_output_path',\n 'review_deadline_at',\n 'review_monitor_signaled',\n 'review_retry_attempt',\n 'updated_at',\n] as const;\n\nconst SELECT_AGENT_SQL = `SELECT ${AGENT_COLUMNS_FOR_DB.join(', ')} FROM agents`;\n\nfunction isoFromMillis(value: number | null | undefined): string | undefined {\n return value == null ? undefined : new Date(value).toISOString();\n}\n\nfunction millisFromIso(value: string | null | undefined): number | null {\n if (!value) return null;\n const millis = Date.parse(value);\n return Number.isFinite(millis) ? millis : null;\n}\n\nfunction boolFromInteger(value: number | null | undefined): boolean | undefined {\n return value == null ? undefined : Boolean(value);\n}\n\nfunction hostOverrideFromRow(value: string | null | undefined): boolean | undefined {\n if (value == null) return undefined;\n return value === '1' || value === 'true' || value === 'yes';\n}\n\nfunction hostOverrideToRow(value: boolean | undefined): string | null {\n return value === true ? 'true' : null;\n}\n\nfunction overdeckRowToAgentState(row: OverdeckAgentRow): AgentState {\n const deliveryMethod = row.delivery_method as AgentState['deliveryMethod'] | null;\n return {\n id: row.id,\n issueId: row.issue_id,\n workspace: row.workspace,\n role: row.role as Role,\n model: row.model ?? '',\n status: row.status as AgentState['status'],\n startedAt: isoFromMillis(row.started_at) ?? isoFromMillis(row.updated_at) ?? new Date().toISOString(),\n harness: row.harness ? (row.harness as RuntimeName) : undefined,\n lastResumeAt: isoFromMillis(row.last_resume_at),\n stoppedByUser: boolFromInteger(row.stopped_by_user),\n stoppedByPause: boolFromInteger(row.stopped_by_pause),\n kickoffDelivered: boolFromInteger(row.kickoff_delivered),\n paused: boolFromInteger(row.paused),\n pausedReason: row.paused_reason ?? undefined,\n yieldedByScheduler: boolFromInteger(row.yielded_by_scheduler),\n yieldedAt: isoFromMillis(row.yielded_at),\n lastYieldResumeAt: isoFromMillis(row.last_yield_resume_at),\n troubled: boolFromInteger(row.troubled),\n consecutiveFailures: row.consecutive_failures ?? undefined,\n firstFailureInRunAt: isoFromMillis(row.first_failure_in_run_at),\n lastFailureNextRetryAt: isoFromMillis(row.last_failure_next_retry_at),\n sessionId: row.session_id ?? undefined,\n channelsEnabled: boolFromInteger(row.channels_enabled),\n supervisorEnabled: deliveryMethod === 'supervisor' ? true : undefined,\n deliveryMethod: deliveryMethod ?? undefined,\n hostOverride: hostOverrideFromRow(row.host_override),\n stoppedAt: isoFromMillis(row.stopped_at),\n pausedAt: isoFromMillis(row.paused_at),\n troubledAt: isoFromMillis(row.troubled_at),\n lastActivity: isoFromMillis(row.last_activity),\n lastFailureReason: row.last_failure_reason ?? undefined,\n phase: row.phase == null ? undefined : (row.phase as AgentState['phase']),\n roleRunHead: row.role_run_head ?? undefined,\n flywheelRunId: row.flywheel_run_id ?? undefined,\n costSoFar: row.cost_so_far ?? undefined,\n reviewSubRole: row.review_sub_role ?? undefined,\n reviewRunId: row.review_run_id ?? undefined,\n reviewSynthesisAgentId: row.review_synthesis_agent_id ?? undefined,\n reviewOutputPath: row.review_output_path ?? undefined,\n reviewDeadlineAt: isoFromMillis(row.review_deadline_at),\n reviewMonitorSignaled: (row.review_monitor_signaled ?? undefined) as AgentState['reviewMonitorSignaled'],\n reviewRetryAttempt: row.review_retry_attempt ?? undefined,\n };\n}\n\n/** Exported for agent-projection.ts transactional writes. */\nexport function stateToOverdeckParamsForDb(state: AgentState, updatedAt: number): unknown[] {\n const deliveryMethod = state.deliveryMethod ?? (state.supervisorEnabled === true ? 'supervisor' : null);\n return [\n state.id,\n state.issueId,\n state.role,\n state.status,\n state.workspace,\n state.sessionId ?? null,\n state.harness ?? '',\n state.model ?? '',\n hostOverrideToRow(state.hostOverride),\n deliveryMethod,\n millisFromIso(state.startedAt),\n millisFromIso(state.lastResumeAt),\n state.stoppedByUser == null ? null : (state.stoppedByUser ? 1 : 0),\n state.stoppedByPause == null ? null : (state.stoppedByPause ? 1 : 0),\n state.kickoffDelivered == null ? null : (state.kickoffDelivered ? 1 : 0),\n state.paused == null ? null : (state.paused ? 1 : 0),\n state.pausedReason ?? null,\n state.yieldedByScheduler == null ? null : (state.yieldedByScheduler ? 1 : 0),\n millisFromIso(state.yieldedAt),\n millisFromIso(state.lastYieldResumeAt),\n state.troubled == null ? null : (state.troubled ? 1 : 0),\n state.channelsEnabled == null ? null : (state.channelsEnabled ? 1 : 0),\n state.consecutiveFailures ?? null,\n millisFromIso(state.firstFailureInRunAt),\n millisFromIso(state.lastFailureNextRetryAt),\n millisFromIso(state.stoppedAt),\n millisFromIso(state.pausedAt),\n millisFromIso(state.troubledAt),\n millisFromIso(state.lastActivity),\n state.lastFailureReason ?? null,\n state.phase ?? null,\n state.roleRunHead ?? null,\n state.flywheelRunId ?? null,\n state.costSoFar ?? null,\n state.reviewSubRole ?? null,\n state.reviewRunId ?? null,\n state.reviewSynthesisAgentId ?? null,\n state.reviewOutputPath ?? null,\n millisFromIso(state.reviewDeadlineAt),\n state.reviewMonitorSignaled ?? null,\n state.reviewRetryAttempt ?? null,\n updatedAt,\n ];\n}\n\nexport function getOverdeckAgentStateSync(agentId: string): AgentState | null {\n const row = getOverdeckDatabaseSync()\n .prepare(`${SELECT_AGENT_SQL} WHERE id = ?`)\n .get(agentId) as OverdeckAgentRow | undefined;\n return row ? overdeckRowToAgentState(row) : null;\n}\n\nexport function listOverdeckAgentStatesSync(): AgentState[] {\n const rows = getOverdeckDatabaseSync()\n .prepare(SELECT_AGENT_SQL)\n .all() as OverdeckAgentRow[];\n return rows.map(overdeckRowToAgentState);\n}\n\nexport function saveOverdeckAgentStateSync(state: AgentState): void {\n const db = getOverdeckDatabaseSync();\n const updatedAt = Date.now();\n db.prepare(\n `INSERT OR IGNORE INTO issues (id, stage, updated_at) VALUES (?, 'working', ?)`,\n ).run(state.issueId, updatedAt);\n db.prepare(\n `INSERT OR REPLACE INTO agents (${AGENT_COLUMNS_FOR_DB.join(', ')}) VALUES (${AGENT_COLUMNS_FOR_DB.map(() => '?').join(', ')})`,\n ).run(...stateToOverdeckParamsForDb(state, updatedAt));\n}\n","/**\n * PAN-2579: synchronous access to the review-status map for warm-idle advancing\n * classification in concurrency.ts, WITHOUT importing review-status-sync.ts —\n * that module transitively reaches agents/spawn.ts -> concurrency.ts\n * (review-status-sync -> review-status-normalize -> review-status -> agents),\n * so a direct concurrency.ts import closes a real cycle (caught by\n * scripts/lint-circular-deps.sh). Same shape as memory-verdict-cache.ts: this\n * module has no imports of its own, so it cannot be part of any cycle.\n *\n * review-status.ts registers the reader at module load. Before registration\n * (or if the read throws) callers get null and treat NOTHING as warm-idle —\n * the ceiling stays conservative.\n */\n\n/** Minimal status shape needed for warm-idle classification (mirrors ReapableStatus). */\nexport interface WarmIdleStatusShape {\n reviewStatus?: string;\n testStatus?: string;\n readyForMerge?: boolean;\n mergeStatus?: string;\n}\n\ntype StatusMapReader = () => Record<string, WarmIdleStatusShape>;\n\nlet reader: StatusMapReader | null = null;\n\nexport function registerReviewStatusMapReader(fn: StatusMapReader): void {\n reader = fn;\n}\n\nexport function readReviewStatusMap(): Record<string, WarmIdleStatusShape> | null {\n if (!reader) return null;\n try {\n return reader();\n } catch {\n return null;\n }\n}\n","const issueRecordLocks = new Map<string, Promise<void>>();\n\n/**\n * Serialize async read-modify-write rebuilds for a single issue record.\n *\n * Synchronous record writers remain synchronous; async flows that read, await,\n * then write the whole record must use this lock so same-issue rebuilds cannot\n * overwrite each other's final re-read.\n */\nexport async function withIssueRecordLock<T>(\n issueId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n const key = issueId.toUpperCase();\n const previous = issueRecordLocks.get(key) ?? Promise.resolve();\n let release: () => void = () => {};\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const chain = previous.catch(() => undefined).then(() => current);\n issueRecordLocks.set(key, chain);\n\n await previous.catch(() => undefined);\n\n try {\n return await fn();\n } finally {\n release();\n if (issueRecordLocks.get(key) === chain) {\n issueRecordLocks.delete(key);\n }\n }\n}\n","/**\n * PAN-1908 / PAN-1919: per-issue permanent-record builder.\n *\n * Builds a single JSON record per issue from SQLite (pipeline verdicts, usage,\n * merges) plus the legacy project-side continue file. The actual read/write/path\n * helpers live in `record.ts` (PAN-1919 single-writer module) and write the\n * record onto the feature branch at `<workspace>/.pan/records/<issue>.json`.\n */\n\nimport { hostname } from 'node:os';\nimport { join } from 'node:path';\nimport { existsSync, promises as fsp } from 'node:fs';\nimport { PAN_CONTINUES_DIRNAME, PAN_DIRNAME } from './types.js';\n\n// ─── Types ────────────────────────────────────────────────────────────────────\nimport {\n getCostBreakdownByStageAndModelSync,\n getCostForIssueSync,\n} from '../overdeck/cost-sync.js';\nimport { getMergeSetSync } from '../merge-set.js';\nimport {\n getProjectSync,\n resolveProjectFromIssueSync,\n type ProjectConfig,\n} from '../projects.js';\nimport type { ReviewStatus } from '../review-status.js';\nimport type { RuntimeName } from '../runtimes/types.js';\nimport type {\n ContinueBeadsMapping,\n ContinueDecision,\n ContinueFeedbackEntry,\n ContinueHazard,\n ContinueResumePoint,\n ContinueSessionEntry,\n ScopeDriftRecord,\n} from '../vbrief/continue-state.js';\nimport { listOverdeckAgentStatesSync } from '../overdeck/agent-state-sync.js';\nimport {\n getIssueWorkspacePath,\n queueIssueRecordCommit,\n RECORD_SCHEMA_VERSION,\n readIssueRecord,\n readIssueRecordSync,\n writeIssueRecordSync,\n type PanIssueRecord,\n type PanIssuePipelineRecord,\n type PanIssueUsageRecord,\n} from './record.js';\nimport { withIssueRecordLock } from './record-lock.js';\n\nexport type {\n PanIssueRecord,\n PanIssueCloseOutRecord,\n PanIssuePipelineRecord,\n PanIssueUsageRecord,\n} from './record.js';\n\n// ─── Continue projection ──────────────────────────────────────────────────────\n\ninterface ContinueFile {\n issueId?: string;\n gitState?: { branch?: string };\n decisions?: ContinueDecision[];\n hazards?: ContinueHazard[];\n resumePoint?: ContinueResumePoint | null;\n beadsMapping?: ContinueBeadsMapping;\n sessionHistory?: ContinueSessionEntry[];\n feedback?: ContinueFeedbackEntry[];\n agentModel?: string;\n scopeDrift?: ScopeDriftRecord;\n}\n\nfunction projectContinue(raw: ContinueFile | null): Pick<PanIssueRecord, 'decisions' | 'hazards' | 'resumePoint' | 'beadsMapping' | 'sessionHistory' | 'feedback' | 'scopeDrift'> {\n return {\n decisions: raw?.decisions,\n hazards: raw?.hazards,\n resumePoint: raw?.resumePoint,\n beadsMapping: raw?.beadsMapping,\n sessionHistory: raw?.sessionHistory,\n feedback: raw?.feedback ?? [],\n scopeDrift: raw?.scopeDrift,\n };\n}\n\n// ─── Pipeline projection ──────────────────────────────────────────────────────\n\nfunction projectPipeline(\n issueId: string,\n status: ReviewStatus | null,\n existing?: PanIssuePipelineRecord,\n): PanIssuePipelineRecord {\n const base: PanIssuePipelineRecord = {\n issueId,\n reviewStatus: status?.reviewStatus ?? 'pending',\n testStatus: status?.testStatus ?? 'pending',\n verificationStatus: status?.verificationStatus,\n inspectStatus: status?.inspectStatus,\n mergeStatus: status?.mergeStatus,\n readyForMerge: status?.readyForMerge ?? false,\n closedOut: existing?.closedOut,\n closedOutAt: existing?.closedOutAt,\n updatedAt: status?.updatedAt ?? new Date().toISOString(),\n };\n\n if (!status) return base;\n\n return {\n ...base,\n reviewNotes: status.reviewNotes,\n testNotes: status.testNotes,\n verificationNotes: status.verificationNotes,\n inspectNotes: status.inspectNotes,\n mergeNotes: status.mergeNotes,\n blockerReasons: status.blockerReasons,\n prUrl: status.prUrl,\n prNumber: status.prNumber,\n prHeadSha: status.prHeadSha,\n reviewedAtCommit: status.reviewedAtCommit,\n lastVerifiedCommit: status.lastVerifiedCommit,\n reviewRequestedAt: status.reviewRequestedAt,\n scopeDrift: status.scopeDrift,\n autoMerge: status.autoMerge,\n deaconIgnored: status.deaconIgnored,\n deaconIgnoredAt: status.deaconIgnoredAt,\n deaconIgnoredReason: status.deaconIgnoredReason,\n reviewerVerdicts: (status as { reviewerVerdicts?: unknown }).reviewerVerdicts,\n };\n}\n\n// ─── Usage projection ─────────────────────────────────────────────────────────\n\nfunction projectUsage(issueId: string): PanIssueUsageRecord {\n const { byStage, totals } = getCostBreakdownByStageAndModelSync(issueId);\n const aggregate = getCostForIssueSync(issueId);\n\n return {\n byStage,\n totals,\n costAtCloseOut: {\n usd: aggregate?.totalCost ?? 0,\n pricingAsOf: new Date().toISOString(),\n },\n };\n}\n\n// ─── Merge projection ─────────────────────────────────────────────────────────\n\nfunction projectMerges(issueId: string): string[] {\n const mergeSet = getMergeSetSync(issueId);\n if (!mergeSet) return [];\n return mergeSet.repos\n .map(r => r.artifactUrl)\n .filter((url): url is string => typeof url === 'string' && url.length > 0);\n}\n\n// ─── Record builder ───────────────────────────────────────────────────────────\n\nasync function readLegacyContinueText(projectRoot: string, issueId: string): Promise<string | null> {\n const path = join(projectRoot, PAN_DIRNAME, PAN_CONTINUES_DIRNAME, `${issueId.toLowerCase()}.vbrief.json`);\n try {\n return await fsp.readFile(path, 'utf-8');\n } catch {\n return null;\n }\n}\n\n/** Read workspace continue.json and return its statusOverrides (if any). */\nasync function readWorkspaceContinueStatusOverrides(issueId: string): Promise<Record<string, string> | undefined> {\n const workspacePath = getIssueWorkspacePath(issueId);\n if (!workspacePath || !existsSync(workspacePath)) return undefined;\n const continuePath = join(workspacePath, '.pan', 'continue.json');\n try {\n const text = await fsp.readFile(continuePath, 'utf-8');\n const parsed = JSON.parse(text) as { statusOverrides?: Record<string, string> };\n return parsed.statusOverrides ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Read harness/model for an issue from the overdeck agents table (most recent work agent). */\nfunction projectAgentHarnessModel(issueId: string): { harness?: RuntimeName; model?: string } {\n try {\n const agents = listOverdeckAgentStatesSync().filter(\n (a) => a.issueId?.toUpperCase() === issueId.toUpperCase(),\n );\n const workAgent =\n agents\n .filter((a) => a.role === 'work')\n .sort((a, b) => (b.startedAt ?? '').localeCompare(a.startedAt ?? ''))[0]\n ?? agents[agents.length - 1];\n return {\n harness: workAgent?.harness,\n model: workAgent?.model ?? undefined,\n };\n } catch {\n return {};\n }\n}\n\nexport interface BuildIssueRecordOptions {\n closedAt?: string;\n owner?: string;\n reviewStatus?: ReviewStatus | null;\n}\n\nexport async function buildIssueRecord(\n project: ProjectConfig,\n issueId: string,\n opts: BuildIssueRecordOptions = {},\n): Promise<PanIssueRecord> {\n const existing = await readIssueRecord(project, issueId);\n const legacyContinueText = await readLegacyContinueText(project.path, issueId);\n const continueSubset = projectContinue(legacyContinueText ? (JSON.parse(legacyContinueText) as ContinueFile) : null);\n const pipelineRecord = projectPipeline(issueId, opts.reviewStatus ?? null, existing?.pipeline);\n const usageRecord = projectUsage(issueId);\n const merges = projectMerges(issueId);\n\n // PAN-1919: fold workspace continue statusOverrides; fall back to existing.\n const workspaceStatusOverrides = await readWorkspaceContinueStatusOverrides(issueId);\n const mergedStatusOverrides = workspaceStatusOverrides\n ? { ...(existing?.statusOverrides ?? {}), ...workspaceStatusOverrides }\n : existing?.statusOverrides;\n\n // PAN-1919: harness/model from existing record, then agents table as fallback.\n const agentHM = existing?.harness || existing?.model\n ? { harness: existing.harness, model: existing.model }\n : projectAgentHarnessModel(issueId);\n\n return {\n issueId: issueId.toUpperCase(),\n schemaVersion: RECORD_SCHEMA_VERSION,\n ...continueSubset,\n ...existing,\n harness: agentHM.harness,\n model: agentHM.model,\n statusOverrides: mergedStatusOverrides,\n pipeline: pipelineRecord,\n closeOut: {\n usage: usageRecord,\n merges,\n ranOn: hostname(),\n closedAt: opts.closedAt,\n },\n owner: opts.owner ?? existing?.owner,\n };\n}\n\n// Re-export core record I/O from the PAN-1919 single-writer module.\nexport {\n getIssueRecordPath,\n markRecordPipelineClosedOutSync,\n writeIssueRecordSync,\n readIssueRecord,\n queueIssueRecordCommit,\n} from './record.js';\n\n// ─── Owner-URI lease (PAN-1908, CP-3) ─────────────────────────────────────────\n\nexport {\n buildOwnUri,\n claimIssueOwner,\n clearIssueOwner,\n type ClaimResult,\n} from './record.js';\n\n/**\n * PAN-1908 / PAN-1919: rebuild and queue the per-issue permanent record for a\n * given issue. Fire-and-forget: failures are logged, never thrown, so\n * review-status writes stay synchronous and fast.\n *\n * PAN-2583: returns whether the durable write actually landed, so the caller\n * can fall back to a sandbox-writable verdict drop when it did not (a sandboxed\n * reviewer cannot write ${OVERDECK_HOME}/state, and swallowing that here was\n * how blocked review verdicts silently vanished).\n */\nexport async function updateIssueRecordForIssue(\n issueId: string,\n reviewStatus?: ReviewStatus | null,\n): Promise<boolean> {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return false;\n const project = getProjectSync(resolved.projectKey);\n if (!project) return false;\n\n await withIssueRecordLock(issueId, async () => {\n const record = await buildIssueRecord(project, issueId, { reviewStatus });\n // buildIssueRecord's `existing` snapshot is read at the top of several awaits;\n // anything written to the record during that window would be erased by this\n // whole-record write (lost update). Observed twice on PAN-1791: wiped swarm\n // slot assignments during the runaway, then wiped item statusOverrides right\n // after `pan done` — which made every completed item dispatchable again and\n // re-spawned slots for finished work. Re-read both blocks synchronously\n // immediately before writing so the freshest values survive the rebuild.\n const fresh = readIssueRecordSync(project, issueId);\n if (fresh?.swarm) record.swarm = fresh.swarm;\n if (fresh?.statusOverrides && Object.keys(fresh.statusOverrides).length > 0) {\n record.statusOverrides = { ...record.statusOverrides, ...fresh.statusOverrides };\n }\n const recordPath = writeIssueRecordSync(project, issueId, record);\n queueIssueRecordCommit(project, issueId, recordPath);\n });\n return true;\n } catch (err) {\n console.warn(`[pan-dir/records] Failed to update record for ${issueId}: ${(err as Error).message}`);\n return false;\n }\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { ReviewStatus } from '../review-status.js';\nimport { updateIssueRecordForIssue, type PanIssuePipelineRecord } from '../pan-dir/records.js';\nimport { readIssueRecordSync } from '../pan-dir/record.js';\nimport { resolveProjectFromIssueSync, getProjectSync } from '../projects.js';\n\nexport function updateIssueRecordForReviewStatusSync(issueId: string, status: ReviewStatus): void {\n // PAN-2583: the state-dir journal is the durable home, but a sandboxed reviewer\n // (codex workspace-write) cannot write ${OVERDECK_HOME}/state — and swallowing that\n // failure here is how blocked review verdicts silently vanished for hours. When the\n // journal write does not land, drop the durable verdict into the workspace runtime\n // dir (the one place a sandboxed agent can always write); readJournalStatusSync\n // overlays it on the next host-side read.\n void Promise.resolve(updateIssueRecordForIssue(issueId, status))\n .then((landed) => {\n // Only an explicit `false` means the durable write failed — undefined\n // (e.g. a test double) is \"unknown\", not \"failed\".\n if (landed === false) writeWorkspaceVerdictFallbackSync(issueId, status);\n })\n .catch(() => writeWorkspaceVerdictFallbackSync(issueId, status));\n}\n\n/** Resolve and read the per-issue journal record's pipeline block, or null. Best-effort. */\nfunction readPipelineSync(issueId: string): PanIssuePipelineRecord | null {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return null;\n const project = getProjectSync(resolved.projectKey);\n if (!project) return null;\n const record = readIssueRecordSync(project, issueId);\n return record?.pipeline ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * PAN-1988: feedback TEXT (review / test / merge / inspect / verification notes) is durable\n * JOURNAL state, not DB-cache state. The SQLite row holds only the queryable status flags;\n * the human-readable notes live in the per-issue git record (`<workspace>/.pan/records/<issue>.json`,\n * PAN-1908). This overlays those notes onto a DB-sourced status so every reader (deacon\n * CI-failure detection, dashboard panels) stays transparent while the DB stops storing them.\n */\nexport function enrichReviewNotesFromRecordSync(issueId: string, status: ReviewStatus): ReviewStatus {\n const pipeline = readPipelineSync(issueId);\n if (!pipeline) return status;\n return {\n ...status,\n reviewNotes: pipeline.reviewNotes ?? status.reviewNotes,\n testNotes: pipeline.testNotes ?? status.testNotes,\n mergeNotes: pipeline.mergeNotes ?? status.mergeNotes,\n inspectNotes: pipeline.inspectNotes ?? status.inspectNotes,\n verificationNotes: pipeline.verificationNotes ?? status.verificationNotes,\n scopeDrift: pipeline.scopeDrift ?? status.scopeDrift,\n // PAN-1988 auto-heal: the durable review-request intent is journal-only — overlay it on every\n // read so the merge base preserves it through partial updates and the dispatch reconcile sees it.\n reviewRequestedAt: pipeline.reviewRequestedAt ?? status.reviewRequestedAt,\n };\n}\n\ntype DurableStatusFields = Partial<ReviewStatus> & { closedOut?: boolean; closedOutAt?: string };\n\n/**\n * The durable field subset shared by the journal record's pipeline block and the\n * workspace verdict fallback (PAN-2583). Derived/live columns (readyForMerge,\n * blockerReasons) are intentionally omitted — the reader recomputes them.\n */\nfunction durableSubset(p: PanIssuePipelineRecord): DurableStatusFields {\n return {\n reviewStatus: p.reviewStatus as ReviewStatus['reviewStatus'],\n testStatus: p.testStatus as ReviewStatus['testStatus'],\n mergeStatus: (p.mergeStatus as ReviewStatus['mergeStatus']) ?? undefined,\n inspectStatus: (p.inspectStatus as ReviewStatus['inspectStatus']) ?? undefined,\n verificationStatus: (p.verificationStatus as ReviewStatus['verificationStatus']) ?? undefined,\n reviewNotes: p.reviewNotes,\n testNotes: p.testNotes,\n mergeNotes: p.mergeNotes,\n inspectNotes: p.inspectNotes,\n verificationNotes: p.verificationNotes,\n scopeDrift: p.scopeDrift,\n prUrl: p.prUrl,\n prNumber: p.prNumber,\n prHeadSha: p.prHeadSha,\n reviewedAtCommit: p.reviewedAtCommit,\n lastVerifiedCommit: p.lastVerifiedCommit,\n reviewRequestedAt: p.reviewRequestedAt,\n reviewerVerdicts: p.reviewerVerdicts as ReviewStatus['reviewerVerdicts'],\n autoMerge: p.autoMerge,\n deaconIgnored: p.deaconIgnored,\n deaconIgnoredAt: p.deaconIgnoredAt,\n deaconIgnoredReason: p.deaconIgnoredReason,\n closedOut: p.closedOut,\n closedOutAt: p.closedOutAt,\n };\n}\n\n/**\n * PAN-2583: sandbox-writable emergency drop for a verdict whose state-dir journal\n * write failed. Lives in the workspace runtime dir (gitignored), swept by\n * readJournalStatusSync on the next host-side read.\n */\ninterface WorkspaceVerdictFallback {\n issueId: string;\n updatedAt: string;\n pipeline: DurableStatusFields;\n}\n\nexport function workspaceVerdictFallbackPath(issueId: string): string | null {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return null;\n return join(\n resolved.projectPath,\n 'workspaces',\n `feature-${issueId.toLowerCase()}`,\n '.overdeck',\n 'pipeline-verdict.json',\n );\n } catch {\n return null;\n }\n}\n\nfunction writeWorkspaceVerdictFallbackSync(issueId: string, status: ReviewStatus): void {\n try {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) {\n console.error(\n `[review-status] PAN-2583: journal write failed for ${issueId} and no workspace could be resolved — the verdict is NOT durable`,\n );\n return;\n }\n mkdirSync(dirname(path), { recursive: true });\n const payload: WorkspaceVerdictFallback = {\n issueId: issueId.toUpperCase(),\n updatedAt: status.updatedAt ?? new Date().toISOString(),\n pipeline: durableSubset(status as unknown as PanIssuePipelineRecord),\n };\n writeFileSync(path, JSON.stringify(payload, null, 2));\n console.warn(\n `[review-status] journal write failed for ${issueId} — durable verdict written to workspace fallback ${path}; the host sweeps it on the next status read (PAN-2583)`,\n );\n } catch (err) {\n console.error(\n `[review-status] PAN-2583: could not persist verdict for ${issueId} anywhere durable: ${(err as Error).message}`,\n );\n }\n}\n\nfunction readWorkspaceVerdictFallbackSync(issueId: string): WorkspaceVerdictFallback | null {\n try {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path || !existsSync(path)) return null;\n const parsed = JSON.parse(readFileSync(path, 'utf-8')) as WorkspaceVerdictFallback;\n if (!parsed?.updatedAt || !parsed.pipeline) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\n/**\n * PAN-1988: read the journal record's durable verdict for an issue — the SOURCE OF TRUTH.\n * Returns the record `updatedAt` (used to decide whether the journal is newer than the DB\n * cache) plus the durable status fields (flags + feedback notes). Derived/live columns\n * (readyForMerge, blockerReasons) are intentionally omitted — the reader recomputes them.\n *\n * This is what makes verdict writes host-owned: a sandboxed agent can always write the journal\n * (workspace-local) even when it cannot write `~/.overdeck/overdeck.db`. The host reconciles\n * the cache from this on read, so no agent has to escalate out of its sandbox to record a verdict.\n *\n * PAN-2583: since the records migration (PAN-2541) the journal itself lives in\n * ${OVERDECK_HOME}/state, which a sandboxed reviewer cannot write either. When such a\n * writer dropped its verdict into the workspace fallback instead, overlay it here —\n * a strictly newer fallback wins over the record, and the host's own next journal\n * write folds it back into the canonical record.\n */\nexport function readJournalStatusSync(\n issueId: string,\n): { updatedAt: string; durable: DurableStatusFields } | null {\n const p = readPipelineSync(issueId);\n const fallback = readWorkspaceVerdictFallbackSync(issueId);\n const fallbackNewer = !!fallback && (!p || (p.updatedAt ?? '') < fallback.updatedAt);\n if (fallback && fallbackNewer) {\n const base = p ? durableSubset(p) : {};\n const overlay = Object.fromEntries(\n Object.entries(fallback.pipeline).filter(([, value]) => value !== undefined),\n ) as DurableStatusFields;\n return { updatedAt: fallback.updatedAt, durable: { ...base, ...overlay } };\n }\n if (!p) return null;\n return { updatedAt: p.updatedAt, durable: durableSubset(p) };\n}\n","/**\n * PAN-1988 auto-heal — decide whether a review needs to be (re-)dispatched from the durable\n * journal intent, as a PURE function so it is locked by tests.\n *\n * The work agent's `pan done` writes a durable `reviewRequestedAt` into the journal/record (always\n * writable, even sandboxed) BEFORE it tries to reach the dashboard. If that reactive trigger is\n * dropped — the dashboard was mid-reload, the network blipped, the deacon is frozen — the intent\n * survives in the journal. The host reconciles on read: when a request is newer than the last\n * dispatch and nothing is currently reviewing, it dispatches review. This heals with NO deacon and\n * NO live dashboard event, on the next status read.\n *\n * Returns true when a review dispatch is owed:\n * - a request exists (`reviewRequestedAt` set), AND\n * - it is newer than the last spawn (or there was never a spawn) — i.e. a genuinely un-serviced\n * request, not the request that produced the current review, AND\n * - a review is not already in progress (`reviewing`), AND\n * - the issue is not already merged.\n */\nexport function needsReviewDispatch(params: {\n reviewRequestedAt?: string;\n reviewSpawnedAt?: string;\n reviewStatus?: string;\n mergeStatus?: string;\n}): boolean {\n if (!params.reviewRequestedAt) return false;\n if (params.reviewStatus === 'reviewing') return false;\n if (params.mergeStatus === 'merged') return false;\n return !params.reviewSpawnedAt || params.reviewRequestedAt > params.reviewSpawnedAt;\n}\n","import { join } from 'path';\nimport { homedir } from 'os';\nimport { Data, Effect } from 'effect';\nimport { notifyPipelineSync } from './pipeline-notifier.js';\nimport { emitActivityEntrySync, emitActivityTtsSync } from './activity-logger.js';\nimport {\n upsertReviewStatusSync as dbUpsert,\n deleteReviewStatus as dbDelete,\n getReviewStatusFromDbSync,\n getAllReviewStatusesFromDb,\n getReviewStatusesFromDb,\n markWorkspaceStuck as dbMarkStuck,\n clearWorkspaceStuck as dbClearStuck,\n} from './overdeck/review-status-sync.js';\nimport { registerReviewStatusMapReader } from './cloister/review-status-source.js';\nimport { normalizeReviewStatusSync } from './review-status-normalize.js';\nimport { updateIssueRecordForReviewStatusSync, enrichReviewNotesFromRecordSync, readJournalStatusSync } from './overdeck/review-status-record-sync.js';\nimport { needsReviewDispatch } from './review-dispatch-decision.js';\nimport type { ScopeDriftRecord } from './vbrief/continue-state.js';\n\nfunction emitReactiveLifecycleEvent(type: 'review.approved' | 'test.passed', issueId: string): void {\n try {\n notifyPipelineSync({ type, issueId });\n } catch (error) {\n console.warn(`[review-status] Failed to emit ${type} for ${issueId}:`, error);\n }\n}\n\nexport interface StatusHistoryEntry {\n type: 'review' | 'test' | 'merge' | 'inspect' | 'uat';\n status: string;\n timestamp: string;\n notes?: string;\n}\n\nexport interface BlockerReason {\n type: 'failing_checks' | 'merge_conflict' | 'unresolved_conversations' | 'changes_requested' | 'draft_pr' | 'not_mergeable';\n summary: string;\n details?: string;\n detectedAt: string;\n}\n\nexport interface ReviewStatus {\n issueId: string;\n reviewStatus: 'pending' | 'reviewing' | 'passed' | 'failed' | 'blocked' | 'skipped';\n testStatus: 'pending' | 'testing' | 'passed' | 'failed' | 'skipped' | 'dispatch_failed';\n mergeStatus?: 'pending' | 'queued' | 'merging' | 'verifying' | 'merged' | 'failed';\n inspectStatus?: 'pending' | 'inspecting' | 'passed' | 'failed' | 'error';\n inspectNotes?: string;\n inspectStartedAt?: string;\n inspectBeadId?: string;\n uatStatus?: 'pending' | 'testing' | 'passed' | 'failed';\n uatNotes?: string;\n verificationStatus?: 'pending' | 'running' | 'passed' | 'failed' | 'skipped';\n verificationNotes?: string;\n verificationCycleCount?: number;\n verificationMaxCycles?: number;\n reviewNotes?: string;\n testNotes?: string;\n mergeNotes?: string;\n updatedAt: string;\n readyForMerge: boolean;\n /**\n * PAN-1691: per-issue merge-train routing key.\n * `undefined` = follow the project default; `true` = auto-merge (fast lane,\n * rides the train and ships when green); `false` = hold for UAT (manual lane,\n * waits for human batch review). The merge-train engine reads this to decide\n * whether a ready issue auto-advances or is held for the UAT candidate.\n */\n autoMerge?: boolean;\n autoRequeueCount?: number;\n mergeRetryCount?: number;\n prUrl?: string;\n /** PAN-905: HEAD commit SHA of the tracked PR for webhook identity validation */\n prHeadSha?: string;\n /** PAN-905: GitHub PR number of the tracked PR for webhook identity validation */\n prNumber?: number;\n history?: StatusHistoryEntry[];\n /** PAN-905: GitHub-native merge blocker reasons */\n blockerReasons?: BlockerReason[];\n /** HEAD commit SHA at the time review passed — used to detect new commits after review */\n reviewedAtCommit?: string;\n /** HEAD commit SHA at the time the pre-review verification gate passed — used to skip redundant test-agent */\n lastVerifiedCommit?: string;\n /** Current merge pipeline step for granular merge progress tracking */\n mergeStep?: string;\n /** PAN-653: workspace is stuck (e.g. main diverged mid-approve) — Deacon skips it */\n stuck?: boolean;\n /** PAN-653: reason workspace is stuck (e.g. 'main_diverged') */\n stuckReason?: string;\n /** PAN-653: ISO timestamp when workspace was marked stuck */\n stuckAt?: string;\n /** PAN-653: JSON details about the stuck event (e.g. {localSha, remoteSha}) */\n stuckDetails?: string;\n /** PAN-699: timestamp when review agents were dispatched (deacon timeout detection) */\n reviewSpawnedAt?: string;\n /**\n * PAN-1988 auto-heal: durable JOURNAL intent set by `pan done` BEFORE it reaches the dashboard.\n * \"The work agent finished and wants review.\" When this is newer than {@link reviewSpawnedAt}\n * and nothing is reviewing, the host reconciles on read and dispatches review — surviving a\n * dashboard reload, a dropped event, or a frozen deacon. Journal-only (not a DB column).\n */\n reviewRequestedAt?: string;\n /** PAN-1765: timestamp when a conflict-resolution work agent was dispatched. */\n conflictResolutionDispatchedAt?: string;\n /** PAN-699: number of test-agent dispatch retries (circuit breaker) */\n testRetryCount?: number;\n /** PAN-794: number of consecutive parallel-review re-dispatch attempts within the current cycle */\n reviewRetryCount?: number;\n /** PAN-794: ISO timestamp when deacon began the current recovery cycle — acts as the history cutoff for the breaker */\n recoveryStartedAt?: string;\n /** Human-requested ignore flag: when true, Deacon patrol skips this issue entirely (distinct from `stuck`, which is a system-set failure marker). */\n deaconIgnored?: boolean;\n /** ISO timestamp when the ignore flag was set. */\n deaconIgnoredAt?: string;\n /** Optional free-form reason shown alongside the ignore toggle. */\n deaconIgnoredReason?: string;\n /** PAN-1762: advisory files_scope drift recorded at pan done and surfaced to review. */\n scopeDrift?: ScopeDriftRecord;\n /**\n * PAN-1862 (FR-6): per-convoy-reviewer verdicts from the latest full-review cycle,\n * keyed by sub-role (security/correctness/performance/requirements). Journal-durable\n * (not a DB column — overlaid on read like reviewRequestedAt). `atCommit` anchors\n * drift invalidation for selective re-review (reviewersToRerun).\n */\n reviewerVerdicts?: Partial<Record<string, { status: 'passed' | 'blocked'; atCommit?: string; findingsPath?: string }>>;\n // PAN-1531: reviewTempStashRef / reviewTempStashMessage / reviewTempStashSequence\n // removed. The review pipeline no longer stashes uncommitted work — the\n // dirty-worktree gate refuses pan done / pan review request before review\n // is dispatched.\n}\n\nexport function verificationSatisfied(status: Pick<ReviewStatus, 'verificationStatus'>): boolean {\n // Only block readyForMerge if verification explicitly FAILED.\n // 'pending' means \"scheduled but not yet run this cycle\" — not a failure signal.\n // request-review resets verificationStatus to 'pending' as part of its cycle reset,\n // but subsequent review+test passing should still yield readyForMerge=true.\n // The post-rebase gate in triggerMerge() is the authoritative quality gate (PAN-XXX).\n return status.verificationStatus !== 'failed';\n}\n\n/**\n * PAN-1988: the merge-gate predicate (review passed, test passed/skipped, verification not\n * failed, UAT ok, merge not started). Extracted so both setReviewStatusSync and the\n * journal→DB reconcile in getReviewStatusSync derive readyForMerge identically.\n */\nexport function reviewGatesPassedSync(\n s: Pick<ReviewStatus, 'reviewStatus' | 'testStatus' | 'verificationStatus' | 'uatStatus' | 'mergeStatus'>,\n): boolean {\n return (\n (s.reviewStatus === 'passed' || s.reviewStatus === 'skipped') &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n verificationSatisfied(s) &&\n (s.uatStatus === undefined || s.uatStatus === 'passed') &&\n (s.mergeStatus === 'pending' ||\n s.mergeStatus === 'queued' ||\n s.mergeStatus === undefined ||\n s.mergeStatus === null)\n );\n}\n\nexport interface MergeGateEligibility {\n eligible: boolean;\n reason?: string;\n}\n\n/**\n * Authoritative \"allowed to merge\" predicate (PAN-1759). The flywheel\n * orchestrator's pipeline verb says it INTENDS to merge an issue; this record\n * says the pipeline ALLOWS it. Both must hold before an issue enters the merge\n * queue or a UAT batch — RUN-20 tagged a mid-review issue with a merge verb\n * and it rode into a promotable batch. Same criteria as the\n * fixStuckReadyForMerge repair sweep: review passed, test passed/skipped,\n * verification not failed, not already merged.\n */\nexport function mergeGateEligibility(\n status: Pick<ReviewStatus, 'reviewStatus' | 'testStatus' | 'verificationStatus' | 'mergeStatus'> | null,\n): MergeGateEligibility {\n if (!status) return { eligible: false, reason: 'no review record' };\n if (status.reviewStatus !== 'passed' && status.reviewStatus !== 'skipped') {\n return { eligible: false, reason: `review is ${status.reviewStatus}` };\n }\n if (status.testStatus !== 'passed' && status.testStatus !== 'skipped') {\n return { eligible: false, reason: `test is ${status.testStatus}` };\n }\n if (!verificationSatisfied(status)) return { eligible: false, reason: 'verification failed' };\n if (status.mergeStatus === 'merged') return { eligible: false, reason: 'already merged' };\n return { eligible: true };\n}\n// PAN-2579: register the cycle-free status-map reader used by concurrency.ts for\n// warm-idle advancing classification (see cloister/review-status-source.ts).\nregisterReviewStatusMapReader(() => getAllReviewStatusesFromDb());\n\nconst DEFAULT_STATUS_FILE = join(homedir(), '.overdeck', 'review-status.json');\n\nexport function loadReviewStatuses(filePath = DEFAULT_STATUS_FILE): Record<string, ReviewStatus> {\n // SQLite is the authoritative store for the default (server) path.\n // Non-default JSON paths have been moved to review-status-json.ts so that\n // dashboard-reachable code never imports sync FS operations.\n if (filePath !== DEFAULT_STATUS_FILE) {\n throw new Error(\n `Non-default review-status paths are not supported in review-status.ts. ` +\n `Import from review-status-json.ts for JSON file operations.`\n );\n }\n return getAllReviewStatusesFromDb();\n}\n\nexport function loadReviewStatusesForIssues(issueIds: string[]): Record<string, ReviewStatus> {\n return getReviewStatusesFromDb(issueIds);\n}\n\nexport function loadReadyForMergeFlags(issueIds: string[]): Map<string, boolean> {\n const normalizedIds = [...new Set(issueIds.map((id) => id.toUpperCase()).filter(Boolean))];\n const dbStatuses = loadReviewStatusesForIssues(normalizedIds);\n const flags = new Map<string, boolean>();\n\n for (const issueId of normalizedIds) {\n const dbStatus = dbStatuses[issueId] ?? null;\n const journal = readJournalStatusSync(issueId);\n let status = dbStatus;\n\n if (journal) {\n if ((journal.durable as { closedOut?: boolean }).closedOut === true) {\n flags.set(issueId, false);\n continue;\n }\n\n if (!dbStatus || (dbStatus.updatedAt ?? '') < journal.updatedAt) {\n const merged: ReviewStatus = {\n ...(dbStatus ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: journal.updatedAt,\n readyForMerge: false,\n }),\n };\n for (const [key, value] of Object.entries(journal.durable)) {\n if (value !== undefined) (merged as unknown as Record<string, unknown>)[key] = value;\n }\n merged.issueId = issueId;\n merged.updatedAt = journal.updatedAt;\n const hasBlockers = (merged.blockerReasons?.length ?? 0) > 0;\n merged.readyForMerge = hasBlockers ? false : reviewGatesPassedSync(merged);\n status = normalizeReviewStatusSync(merged);\n }\n }\n\n flags.set(issueId, status?.readyForMerge ?? false);\n }\n\n return flags;\n}\n\nexport function saveReviewStatuses(statuses: Record<string, ReviewStatus>, filePath = DEFAULT_STATUS_FILE): void {\n // SQLite is the authoritative store for the default (server) path.\n // Mirrors the old JSON overwrite semantics: upsert every entry in the map and\n // delete any SQLite rows whose keys are absent from the map (replace-all).\n if (filePath !== DEFAULT_STATUS_FILE) {\n throw new Error(\n `Non-default review-status paths are not supported in review-status.ts. ` +\n `Import from review-status-json.ts for JSON file operations.`\n );\n }\n const incoming = new Set(Object.keys(statuses));\n const existing = getAllReviewStatusesFromDb();\n for (const id of Object.keys(existing)) {\n if (!incoming.has(id)) {\n dbDelete(id);\n }\n }\n for (const status of Object.values(statuses)) {\n dbUpsert(status);\n }\n}\n\nexport function setReviewStatusSync(\n issueId: string,\n update: Partial<ReviewStatus>,\n existing?: ReviewStatus,\n): ReviewStatus {\n // Guard: bare numeric IDs (no alphabetic prefix) must never reach the DB.\n // They would create orphaned rows that pollute pending lists and metrics.\n if (/^\\d+$/.test(issueId)) {\n console.warn(\n `[review-status] Rejecting setReviewStatus for bare numeric ID \"${issueId}\" — ` +\n `issue IDs must include a project prefix (e.g. PAN-${issueId}).`\n );\n return {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: new Date().toISOString(),\n readyForMerge: false,\n };\n }\n\n issueId = issueId.toUpperCase();\n\n // Read only the single row we're updating (avoids TOCTOU: bulk read-modify-write\n // races when two concurrent calls for different issue IDs run concurrently).\n // If `existing` is provided (e.g. from mutateBlockers), skip the read to\n // avoid double-read on the webhook ingestion path (PAN-905).\n // PAN-1988: the merge base goes through getReviewStatusSync (journal-reconciled +\n // notes-enriched), NOT the raw DB read. Otherwise a partial update (e.g. a testStatus\n // change carrying no review notes) would merge against a DB row whose notes/flags lag\n // the journal and silently erase the journal's feedback. The reconcile inside\n // getReviewStatusSync never re-enters setReviewStatusSync, so there is no recursion.\n const status: ReviewStatus = existing ?? getReviewStatusSync(issueId) ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: new Date().toISOString(),\n readyForMerge: false,\n };\n\n // Guard: reject reviewStatus regression from 'passed' to 'reviewing' unless the caller\n // is explicitly resetting the merge lifecycle (update includes mergeStatus).\n // This is belt-and-suspenders — endpoint-level guards should catch this first.\n if (update.reviewStatus === 'reviewing' && status.reviewStatus === 'passed' && update.mergeStatus === undefined) {\n console.warn(`[review-status] Rejecting reviewStatus regression from 'passed' to 'reviewing' for ${issueId} (mergeStatus not being reset)`);\n notifyPipelineSync({ type: 'status_changed', issueId, status: status as ReviewStatus });\n return status as ReviewStatus;\n }\n\n // PAN-2578: a bare 'reviewing' write must never clobber a terminal blocked/failed verdict.\n // A review agent can finish FASTER than the dispatch path that spawned it (PAN-399: the\n // verification gate completed 2 minutes after the agent recorded BLOCKED, and the dispatch\n // route's redundant `{ reviewStatus: 'reviewing' }` write destroyed the verdict in both the\n // DB and the journal). Blocked/failed → reviewing is legal ONLY when the caller explicitly\n // starts a NEW review cycle by carrying reviewSpawnedAt (spawnReviewRoleForIssue does).\n if (\n update.reviewStatus === 'reviewing' &&\n (status.reviewStatus === 'blocked' || status.reviewStatus === 'failed') &&\n update.reviewSpawnedAt === undefined\n ) {\n console.warn(\n `[review-status] Rejecting stale 'reviewing' write for ${issueId} — a terminal ` +\n `'${status.reviewStatus}' verdict is already recorded for this review cycle. Only a ` +\n `new dispatch (carrying reviewSpawnedAt) may re-enter 'reviewing'.`\n );\n notifyPipelineSync({ type: 'status_changed', issueId, status: status as ReviewStatus });\n return status as ReviewStatus;\n }\n\n // PAN-424: Reject testStatus regression from 'passed' to 'dispatch_failed' or 'failed'.\n // Once tests pass, duplicate dispatch failures must not overwrite the result.\n if (\n (update.testStatus === 'dispatch_failed' || update.testStatus === 'failed') &&\n status.testStatus === 'passed'\n ) {\n console.warn(`[review-status] Rejecting testStatus regression from 'passed' to '${update.testStatus}' for ${issueId}`);\n delete update.testStatus;\n delete update.testNotes;\n }\n\n const merged = { ...status, ...update };\n\n // PAN-1862 (FR-6): reviewerVerdicts is a per-sub-role MAP — a partial update\n // (synthesis reporting only the reviewers that re-ran this cycle) must merge\n // with, not replace, the carried-forward entries from prior cycles.\n if (update.reviewerVerdicts && status.reviewerVerdicts) {\n merged.reviewerVerdicts = { ...status.reviewerVerdicts, ...update.reviewerVerdicts };\n }\n\n // Track status transitions in history (last 10 entries)\n const history = [...(status.history || [])];\n const now = new Date().toISOString();\n if (update.reviewStatus && update.reviewStatus !== status.reviewStatus) {\n history.push({ type: 'review', status: update.reviewStatus, timestamp: now, notes: update.reviewNotes });\n }\n if (update.testStatus && update.testStatus !== status.testStatus) {\n history.push({ type: 'test', status: update.testStatus, timestamp: now, notes: update.testNotes });\n }\n if (update.uatStatus && update.uatStatus !== status.uatStatus) {\n history.push({ type: 'uat', status: update.uatStatus, timestamp: now, notes: update.uatNotes });\n }\n if (update.mergeStatus && update.mergeStatus !== status.mergeStatus) {\n history.push({ type: 'merge', status: update.mergeStatus, timestamp: now });\n }\n while (history.length > 10) history.shift();\n\n // PAN-1650: readyForMerge is EVENT-DRIVEN — derived from the gate state on every\n // write, so it flips the instant review+test+verification pass instead of waiting\n // for a deacon patrol or a startup `fixStuckReadyForMerge` reconcile (those become\n // redundant safety nets). This supersedes the PAN-1048 explicit-only model.\n //\n // Deriving from gates here does NOT bypass the \"rebased onto main + verified\"\n // guarantee: `triggerMerge()` performs the authoritative post-rebase quality gate\n // before it actually merges (see verificationSatisfied's note). The gate predicate\n // mirrors `fixStuckReadyForMerge` so behaviour is identical — just immediate.\n //\n // Explicit caller intent still wins (the merge flow sets readyForMerge=false when a\n // merge starts; mergeStatus then leaves pending/queued so the derive agrees).\n // PAN-905: GitHub-native blockers always override readyForMerge to false.\n const hasBlockers = (merged.blockerReasons?.length ?? 0) > 0;\n const readyForMerge = hasBlockers\n ? false\n : (update.readyForMerge !== undefined\n ? update.readyForMerge\n : reviewGatesPassedSync(merged));\n\n const updated: ReviewStatus = normalizeReviewStatusSync({\n ...merged,\n issueId,\n updatedAt: now,\n readyForMerge,\n history,\n });\n\n // Report commit statuses to GitHub when readyForMerge transitions to true (PAN-536)\n if (readyForMerge && !status.readyForMerge && updated.prUrl) {\n (async () => {\n try {\n const { isGitHubAppConfigured, reportCommitStatus } = await import('./github-app.js');\n if (!isGitHubAppConfigured()) return;\n const prMatch = updated.prUrl!.match(/github\\.com\\/([^/]+)\\/([^/]+)\\/pull/);\n if (!prMatch) return;\n const [, owner, repo] = prMatch;\n // Get HEAD SHA of the PR branch\n const { exec } = await import('child_process');\n const { promisify } = await import('util');\n const execAsync = promisify(exec);\n const { stdout } = await execAsync(\n `gh pr view ${updated.prUrl!.match(/\\/pull\\/(\\d+)/)?.[1]} --json headRefOid --jq .headRefOid`,\n { encoding: 'utf-8', timeout: 10000 }\n );\n const sha = stdout.trim();\n if (sha) {\n // overdeck/review is honest here — review just transitioned to readyForMerge.\n // The overdeck/tests status is posted separately at the actual test-completion\n // site (verification-runner success, test-agent POST in workspaces routes) so it\n // accurately reflects which commit was tested.\n await reportCommitStatus(owner, repo, sha, 'success', 'overdeck/review', 'Review passed');\n console.log(`[review-status] Reported overdeck/review for ${issueId} (${sha.slice(0, 8)})`);\n }\n } catch (err: any) {\n console.warn(`[review-status] Failed to report commit status: ${err.message}`);\n }\n })();\n }\n\n // PAN-1908 + PAN-1988: the journal record is the SOURCE OF TRUTH for the verdict; the\n // SQLite row is a rebuildable cache. Write the journal FIRST — it is workspace-local\n // (<workspace>/.pan/records/<issue>.json), so it succeeds even for a sandboxed agent\n // (codex workspace-write) that cannot reach ~/.overdeck. Fire-and-forget; queueAutoCommit\n // debounces bursts into one commit. Do NOT mirror into canonical vBRIEF specs (PAN-1124).\n updateIssueRecordForReviewStatusSync(issueId, updated);\n\n // The DB cache write is best-effort. A sandboxed agent's write throws SQLITE_READONLY, but\n // the verdict is already durable in the journal above, and the host reconciles the cache on\n // read (getReviewStatusSync's journal→DB reconcile). Tolerating this is what removes the\n // sandbox-escalation \"smoke and mirrors\" — the agent never has to break out of its jail to\n // record a verdict.\n try {\n dbUpsert(updated);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[review-status] DB cache write skipped for ${issueId} (${msg}); journal holds the verdict, host will reconcile on read.`);\n }\n\n notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n\n // Emit activity log entries for meaningful pipeline state transitions.\n // Each transition produces one entry so the ActivityPanel shows live pipeline progress.\n if (update.verificationStatus && update.verificationStatus !== status.verificationStatus) {\n const vMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n running: { level: 'info', msg: `${issueId} — verification running`, tts: `${issueId} verification running` },\n passed: { level: 'success', msg: `${issueId} — verification passed`, tts: `${issueId} verification passed` },\n failed: { level: 'error', msg: `${issueId} — verification failed`, tts: `${issueId} verification failed` },\n skipped: { level: 'info', msg: `${issueId} — verification skipped`, tts: `${issueId} verification skipped`, ttsPriority: 2 },\n };\n const entry = vMap[update.verificationStatus];\n if (entry) emitActivityEntrySync({ source: 'cloister', level: entry.level, message: entry.msg, details: update.verificationNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'cloister',\n eventType: `verificationStatus.${update.verificationStatus}`,\n });\n }\n if (update.reviewStatus && update.reviewStatus !== status.reviewStatus) {\n let reviewMsg = `${issueId} — review started`;\n if (update.reviewStatus === 'reviewing') {\n const retryCount = updated.reviewRetryCount ?? 0;\n reviewMsg = retryCount > 0\n ? `${issueId} — review re-dispatched (retry ${retryCount})`\n : `${issueId} — review started`;\n }\n const rMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string }> = {\n reviewing: { level: 'info', msg: reviewMsg, tts: `${issueId} review started` },\n passed: { level: 'success', msg: `${issueId} — review passed`, tts: `${issueId} review passed` },\n failed: { level: 'error', msg: `${issueId} — review failed`, tts: `${issueId} review failed` },\n blocked: { level: 'warn', msg: `${issueId} — review blocked (changes requested)`, tts: `${issueId} review blocked` },\n };\n const entry = rMap[update.reviewStatus];\n if (entry) emitActivityEntrySync({ source: 'review', level: entry.level, message: entry.msg, details: update.reviewNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.level === 'error' ? 0 : 1,\n issueId,\n source: 'review-specialist',\n eventType: `reviewStatus.${update.reviewStatus}`,\n });\n }\n if (update.testStatus && update.testStatus !== status.testStatus) {\n const tMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n testing: { level: 'info', msg: `${issueId} — tests running`, tts: `${issueId} tests running`, ttsPriority: 2 },\n passed: { level: 'success', msg: `${issueId} — tests passed`, tts: `${issueId} tests passed` },\n failed: { level: 'error', msg: `${issueId} — tests failed`, tts: `${issueId} tests failed` },\n skipped: { level: 'info', msg: `${issueId} — tests skipped`, tts: `${issueId} tests skipped`, ttsPriority: 2 },\n dispatch_failed: { level: 'warn', msg: `${issueId} — test dispatch failed`, tts: `${issueId} test dispatch failed`, ttsPriority: 1 },\n };\n const entry = tMap[update.testStatus];\n if (entry) emitActivityEntrySync({ source: 'test', level: entry.level, message: entry.msg, details: update.testNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'test-specialist',\n eventType: `testStatus.${update.testStatus}`,\n });\n }\n if (update.mergeStatus && update.mergeStatus !== status.mergeStatus) {\n const mMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n queued: { level: 'info', msg: `${issueId} — queued for merge`, tts: `${issueId} queued for merge`, ttsPriority: 2 },\n merging: { level: 'info', msg: `${issueId} — merge in progress`, tts: `${issueId} merge in progress`, ttsPriority: 2 },\n verifying: { level: 'info', msg: `${issueId} — post-merge verification`, tts: `${issueId} post-merge verification running`, ttsPriority: 2 },\n merged: { level: 'success', msg: `${issueId} — merged`, tts: `${issueId} merged to main` },\n failed: { level: 'error', msg: `${issueId} — merge failed`, tts: `${issueId} merge failed` },\n };\n const entry = mMap[update.mergeStatus];\n if (entry) emitActivityEntrySync({ source: 'ship', level: entry.level, message: entry.msg, details: update.mergeNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'merge-agent',\n eventType: `mergeStatus.${update.mergeStatus}`,\n });\n }\n if (update.readyForMerge === true && !status.readyForMerge) {\n emitActivityEntrySync({ source: 'cloister', level: 'success', message: `${issueId} — ready for merge`, issueId });\n emitActivityTtsSync({\n utterance: `${issueId} ready for merge`,\n priority: 1,\n issueId,\n source: 'cloister',\n eventType: 'readyForMerge',\n });\n }\n\n // Reactive Cloister owns review→test and test→ship scheduling. setReviewStatus\n // emits the lifecycle event here so API and direct-import callers share one path.\n // PAN-1862 (FR-14): reviewStatus 'skipped' (review mode none) advances the\n // lifecycle exactly like an approved review — same event, same downstream.\n if (\n (update.reviewStatus === 'passed' || update.reviewStatus === 'skipped') &&\n status.reviewStatus !== 'passed' && status.reviewStatus !== 'skipped' &&\n updated.testStatus === 'pending'\n ) {\n const canSkipTests =\n updated.reviewedAtCommit &&\n updated.lastVerifiedCommit &&\n updated.reviewedAtCommit === updated.lastVerifiedCommit;\n\n if (canSkipTests) {\n console.log(`[review-status] Skipping test role for ${issueId} — no code drift since verification (HEAD=${updated.reviewedAtCommit!.slice(0, 8)})`);\n emitActivityEntrySync({ source: 'cloister', level: 'info', message: `${issueId} — tests skipped (no code change since verification gate)`, issueId });\n setReviewStatusSync(issueId, {\n testStatus: 'passed',\n testNotes: 'Skipped: no code changed since pre-review verification gate',\n verificationStatus: 'passed',\n verificationNotes: 'Pre-review verification already covered the reviewed commit',\n });\n void emitReactiveLifecycleEvent('test.passed', issueId);\n } else {\n void emitReactiveLifecycleEvent('review.approved', issueId);\n }\n }\n\n if (update.testStatus === 'passed' && status.testStatus !== 'passed') {\n void emitReactiveLifecycleEvent('test.passed', issueId);\n }\n\n // PAN-1988: test FAILED → hand it straight back to the work agent (host-side). The dead-end\n // requeue that does this is deacon-only, so without this a failure strands until the (possibly\n // frozen) deacon nudges. Fires once per transition into failed — both the agent's direct POST and\n // the host's .pan/test/result.json recovery flow through this same transition.\n if (\n (update.testStatus === 'failed' || update.testStatus === 'dispatch_failed') &&\n status.testStatus !== 'failed' && status.testStatus !== 'dispatch_failed'\n ) {\n void deliverTestFailureToWorkAgentHostSide(issueId, updated);\n }\n\n return updated;\n}\n\nexport function resetPipelineVerdictsForWorkStartSync(issueId: string): ReviewStatus | null {\n const status = getReviewStatusSync(issueId);\n if (!status) return null;\n\n const isPending =\n status.reviewStatus === 'pending' &&\n status.testStatus === 'pending' &&\n (status.mergeStatus === undefined || status.mergeStatus === 'pending') &&\n (status.verificationStatus === undefined || status.verificationStatus === 'pending') &&\n !status.readyForMerge &&\n status.autoRequeueCount === 0 &&\n status.verificationCycleCount === 0 &&\n status.reviewRetryCount === 0 &&\n status.testRetryCount === 0 &&\n status.mergeRetryCount === 0 &&\n status.recoveryStartedAt === undefined &&\n status.reviewedAtCommit === undefined &&\n status.lastVerifiedCommit === undefined;\n\n if (isPending) return null;\n\n return setReviewStatusSync(issueId, {\n reviewStatus: 'pending',\n testStatus: 'pending',\n mergeStatus: 'pending',\n reviewNotes: undefined,\n testNotes: undefined,\n mergeNotes: undefined,\n readyForMerge: false,\n autoRequeueCount: 0,\n verificationStatus: 'pending',\n verificationNotes: undefined,\n verificationCycleCount: 0,\n stuck: false,\n stuckReason: undefined,\n stuckAt: undefined,\n stuckDetails: undefined,\n reviewRetryCount: 0,\n testRetryCount: 0,\n mergeRetryCount: 0,\n recoveryStartedAt: undefined,\n reviewedAtCommit: undefined,\n lastVerifiedCommit: undefined,\n });\n}\n\n/**\n * PAN-1988 — deliver review feedback to the work agent from the HOST when a blocked/failed\n * verdict is reconciled from the journal. Dynamic import to avoid a static import cycle\n * (review-verdict-feedback → review-status). Fully best-effort: in a sandboxed agent process the\n * delivery fails (host paths blocked) and is swallowed; the host process performs the real\n * notification. Never throws into the read path.\n */\nasync function deliverReviewVerdictFeedbackHostSide(issueId: string, status: ReviewStatus): Promise<void> {\n try {\n const { deliverReviewVerdictFeedback } = await import('./cloister/review-verdict-feedback.js');\n const result = await Effect.runPromise(deliverReviewVerdictFeedback({\n issueId,\n verdict: status.reviewStatus === 'failed' ? 'failed' : 'blocked',\n notes: status.reviewNotes,\n prUrl: status.prUrl,\n }));\n if (result.agentMessageSent) {\n console.log(`[review-status] delivered review feedback to the work agent for ${issueId} (host-side)`);\n }\n } catch (err) {\n console.warn(`[review-status] host-side review feedback delivery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n// PAN-1988 auto-heal — throttle so the reconcile-on-read does not spam dispatch attempts for a\n// genuinely-gated issue (one whose dispatch keeps deferring on a merge conflict). Date.now() is\n// available in normal lib code (only workflow scripts forbid it).\nconst reviewDispatchAttemptAt = new Map<string, number>();\nconst REVIEW_AUTO_DISPATCH_THROTTLE_MS = 30_000;\n\n/**\n * PAN-1988 auto-heal — the host re-dispatches review from the durable journal intent. When the\n * work agent's `pan done` recorded a `reviewRequestedAt` but the reactive dashboard trigger never\n * landed (dashboard reloading, dropped event, frozen deacon), the next status read notices the\n * un-serviced request and dispatches review here. {@link needsReviewDispatch} gates it,\n * spawnReviewRoleForIssue is idempotent (it skips a live review), and a 30s throttle bounds retries\n * for a gated issue. Fire-and-forget; in a sandboxed reader the dispatch is a best-effort no-op.\n */\nfunction maybeAutoDispatchReviewHostSide(issueId: string, status: ReviewStatus): void {\n if (!needsReviewDispatch({\n reviewRequestedAt: status.reviewRequestedAt,\n reviewSpawnedAt: status.reviewSpawnedAt,\n reviewStatus: status.reviewStatus,\n mergeStatus: status.mergeStatus,\n })) return;\n const last = reviewDispatchAttemptAt.get(issueId) ?? 0;\n if (Date.now() - last < REVIEW_AUTO_DISPATCH_THROTTLE_MS) return;\n reviewDispatchAttemptAt.set(issueId, Date.now());\n void dispatchReviewHostSide(issueId, status.prUrl);\n}\n\nasync function dispatchReviewHostSide(issueId: string, prUrl?: string): Promise<void> {\n try {\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return;\n const { existsSync } = await import('fs');\n const workspace = join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`);\n if (!existsSync(workspace)) return;\n let branch = `feature/${issueId.toLowerCase()}`;\n try {\n const { promisify } = await import('util');\n const { exec } = await import('child_process');\n const execAsync = promisify(exec);\n const { stdout } = await execAsync('git branch --show-current', { cwd: workspace, encoding: 'utf-8' });\n branch = stdout.trim() || branch;\n } catch { /* non-fatal — fall back to the conventional branch name */ }\n const { spawnReviewRoleForIssue } = await import('./cloister/review-agent.js');\n const result = await Effect.runPromise(spawnReviewRoleForIssue({ issueId, workspace, branch, ...(prUrl ? { prUrl } : {}) }));\n if (result.success) {\n console.log(`[review-status] auto-dispatched review for ${issueId} from durable journal intent (host-side)`);\n }\n } catch (err) {\n console.warn(`[review-status] host-side review auto-dispatch for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n// ── PAN-1988 host-owned TEST-stage recovery ───────────────────────────────────\n// The test stage had NO reactive path. Recovering an unsignaled verdict (the agent — often Haiku —\n// writes .pan/test/result.json then idles without POSTing) AND the test=failed → work-agent requeue\n// both lived ONLY in deacon patrols (checkCompletedButUnsignaledTests + the dead-end requeue). With\n// the deacon frozen, a finished test agent stranded the issue at test=testing forever. The host now\n// (a) recovers the written verdict on read and (b) hands a failure back to the work agent — symmetric\n// with the review stage. Recovery only acts on a WRITTEN artifact; it never guesses pass/fail.\nconst testVerdictRecoveryAt = new Map<string, number>();\nconst TEST_VERDICT_RECOVERY_THROTTLE_MS = 60_000;\n\nfunction maybeRecoverTestVerdictHostSide(issueId: string, status: ReviewStatus): void {\n if (status.reviewStatus !== 'passed') return; // tests only run after review approves\n if (status.mergeStatus === 'merged' || status.readyForMerge) return;\n // Only act while the verdict is UNSIGNALED — once test resolves (passed/failed) the write path\n // owns the transition (test.passed → ship; test failed → deliverTestFailureToWorkAgentHostSide).\n if (status.testStatus !== 'testing' && status.testStatus !== 'pending' && status.testStatus !== 'dispatch_failed') return;\n const last = testVerdictRecoveryAt.get(issueId) ?? 0;\n if (Date.now() - last < TEST_VERDICT_RECOVERY_THROTTLE_MS) return;\n testVerdictRecoveryAt.set(issueId, Date.now());\n void recoverTestVerdictHostSide(issueId);\n}\n\nasync function recoverTestVerdictHostSide(issueId: string): Promise<void> {\n try {\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return;\n const { existsSync } = await import('fs');\n const workspace = join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`);\n if (!existsSync(workspace)) return;\n const { readTestVerdictArtifact } = await import('./cloister/test-verdict.js');\n const artifact = readTestVerdictArtifact(workspace);\n if (!artifact) return; // no WRITTEN verdict — never guess; the agent/deacon owns the write-nudge\n // Record the recovered verdict. setReviewStatusSync emits test.passed (→ ship) for a pass and\n // fires the work-agent handoff (below) on a fail, via its test-transition logic.\n setReviewStatusSync(issueId, {\n testStatus: artifact.status,\n testNotes: artifact.notes ?? `Recovered from .pan/test/result.json (${artifact.status}) — the test agent wrote the verdict but never signaled`,\n });\n console.log(`[review-status] recovered unsignaled test verdict for ${issueId}: ${artifact.status} (host-side, from .pan/test/result.json)`);\n } catch (err) {\n console.warn(`[review-status] host-side test verdict recovery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nasync function deliverTestFailureToWorkAgentHostSide(issueId: string, status: ReviewStatus): Promise<void> {\n try {\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n const workspace = resolved ? join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`) : undefined;\n const notes = status.testNotes; let feedbackPath: string | undefined;\n try {\n const { writeFeedbackFile } = await import('./cloister/feedback-writer.js');\n const r = await Effect.runPromise(writeFeedbackFile({\n issueId, workspacePath: workspace, specialist: 'test-agent', outcome: 'failed', summary: `Tests FAILED for ${issueId}`,\n markdownBody: `# Test failure\\n\\n${notes ?? 'The test gate reported failures. See .pan/test/result.json and re-run the project test suite.'}\\n\\n## Required\\nFix the failing tests, commit and push, then re-run \\`pan done ${issueId}\\`.`,\n }));\n if (r.success) feedbackPath = r.filePath;\n } catch { /* non-fatal — the message below still carries the summary */ }\n\n const message = `SPECIALIST FEEDBACK: test-agent reported FAILED for ${issueId}.\\n\\n${feedbackPath ? `MUST READ: ${feedbackPath}\\n\\n` : ''}${notes ? `${notes.slice(0, 400)}\\n\\n` : ''}Fix the failing tests, commit and push, then re-run pan done ${issueId}. Do NOT stop at the prompt.`;\n const { resolveIssueFeedbackTarget, surfaceIssueFeedbackNeedsYou } = await import('./cloister/feedback-target.js');\n const target = await resolveIssueFeedbackTarget(issueId);\n if ('agentId' in target) {\n const { messageAgent } = await import('./agents.js');\n await messageAgent(target.agentId, message);\n console.log(`[review-status] delivered test failure to ${target.agentId} for ${issueId} (host-side)`);\n } else {\n await surfaceIssueFeedbackNeedsYou(issueId, target.reason, { specialist: 'test-agent', feedbackPath });\n }\n } catch (err) {\n console.warn(`[review-status] host-side test-failure delivery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nexport function getReviewStatusSync(issueId: string): ReviewStatus | null {\n const dbStatus = getReviewStatusFromDbSync(issueId);\n const journal = readJournalStatusSync(issueId);\n\n // No journal record → the DB is all we have. (Pre-PAN-1908 issues, or issues whose\n // workspace/record hasn't been created yet.)\n if (!journal) return dbStatus ?? null;\n\n if ((journal.durable as { closedOut?: boolean }).closedOut === true) {\n // PAN-2054: closed-out journal records are terminal; stale active DB rows are cache residue.\n try {\n dbDelete(issueId);\n } catch {\n // Read-only DB (a sandboxed reader) — the host clears residue when it reads. Non-fatal.\n }\n return null;\n }\n\n // PAN-1988 — journal is the source of truth; DB is a rebuildable cache. If the journal is\n // NEWER than the DB row, an agent recorded its verdict to the journal but the DB write\n // lagged or was blocked (a sandboxed agent that can't write ~/.overdeck). Reconcile the\n // cache from the journal. Whatever process reads next performs this; the host (non-sandboxed)\n // write succeeds, a sandboxed reader's reconcile is a best-effort no-op.\n const journalNewer = !dbStatus || (dbStatus.updatedAt ?? '') < journal.updatedAt;\n if (journalNewer) {\n const merged: ReviewStatus = {\n ...(dbStatus ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: journal.updatedAt,\n readyForMerge: false,\n }),\n };\n // Apply ONLY the journal fields that are actually present. The journal carries the durable\n // verdict; DB-only/ephemeral fields it does not store (stuck/stuckReason, transient counters)\n // must NOT be clobbered with `undefined`. This keeps every reconcile a strict overlay.\n for (const [key, value] of Object.entries(journal.durable)) {\n if (value !== undefined) (merged as unknown as Record<string, unknown>)[key] = value;\n }\n merged.issueId = issueId;\n merged.updatedAt = journal.updatedAt;\n const hasBlockers = (merged.blockerReasons?.length ?? 0) > 0;\n merged.readyForMerge = hasBlockers ? false : reviewGatesPassedSync(merged);\n const reconciled = normalizeReviewStatusSync(merged);\n try {\n dbUpsert(reconciled);\n } catch {\n // Read-only DB (a sandboxed reader) — the host reconciles when it reads. Non-fatal.\n }\n\n // PAN-1988 — host-owned review FEEDBACK delivery. A sandboxed review agent records its\n // verdict to the journal but cannot notify the work agent (the work agent's tmux/mail and\n // the network are outside its jail — \"side effects failed due restricted network / readonly\n // host paths\"). When the HOST reconciles a NEW blocked/failed review verdict, it delivers the\n // feedback here. Fires exactly once per verdict: the reconcile only runs while the journal is\n // newer than the DB, and the dbUpsert above makes the DB catch up, so the next read does not\n // re-fire. In a sandboxed agent process the delivery is a best-effort no-op (host paths\n // blocked); the host's read performs the real delivery. Fire-and-forget.\n const wasBlocked = dbStatus?.reviewStatus === 'blocked' || dbStatus?.reviewStatus === 'failed';\n const nowBlocked = reconciled.reviewStatus === 'blocked' || reconciled.reviewStatus === 'failed';\n if (nowBlocked && !wasBlocked) {\n void deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n }\n\n // PAN-1988 — host-owned review→test and test→ship HANDOFF. setReviewStatusSync emits these\n // lifecycle events on the write path, but a sandboxed agent (codex/pi) records its verdict to\n // the JOURNAL only and the host picks it up HERE via reconcile — which bypasses\n // setReviewStatusSync. Without re-emitting, a passed verdict strands at review=passed/test=pending\n // (and a passed test strands before ship) until the deacon patrol nudges it — and the deacon may\n // be frozen. Re-emit the same transitions the write path would, so reactive Cloister advances.\n const wasReviewPassed = dbStatus?.reviewStatus === 'passed';\n const nowReviewPassed = reconciled.reviewStatus === 'passed';\n if (nowReviewPassed && !wasReviewPassed && reconciled.testStatus === 'pending') {\n console.log(`[review-status] reconcile: review.approved for ${issueId} (host-owned handoff — sandboxed agent verdict from journal)`);\n void emitReactiveLifecycleEvent('review.approved', issueId);\n }\n const wasTestPassed = dbStatus?.testStatus === 'passed';\n const nowTestPassed = reconciled.testStatus === 'passed';\n if (nowTestPassed && !wasTestPassed) {\n console.log(`[review-status] reconcile: test.passed for ${issueId} (host-owned handoff — sandboxed agent verdict from journal)`);\n void emitReactiveLifecycleEvent('test.passed', issueId);\n }\n\n maybeAutoDispatchReviewHostSide(issueId, reconciled);\n maybeRecoverTestVerdictHostSide(issueId, reconciled);\n return reconciled;\n }\n\n // DB is current → overlay the feedback TEXT from the journal (it is no longer stored in the\n // DB; the row holds only the queryable status flags).\n const enriched = enrichReviewNotesFromRecordSync(issueId, dbStatus!);\n maybeAutoDispatchReviewHostSide(issueId, enriched);\n maybeRecoverTestVerdictHostSide(issueId, enriched);\n return enriched;\n}\n\n/**\n * On server startup, clear any mergeStatus stuck at 'merging'.\n * Pending merge operations are in-memory only — they don't survive a restart.\n * Any 'merging' status after boot is definitionally stuck (PAN-490).\n */\nexport function clearStuckMergeStatuses(): void {\n const statuses = loadReviewStatuses();\n // Don't clear 'queued' — the SQLite merge queue handles that (PAN-632).\n // Only clear truly stuck transient states.\n const stuck = Object.values(statuses).filter(s =>\n s.mergeStatus === 'merging' || s.mergeStatus === 'verifying'\n );\n if (stuck.length === 0) return;\n console.log(`[review-status] Clearing ${stuck.length} stuck merge status(es) on startup (merging/verifying)`);\n for (const s of stuck) {\n // Reset to pending so MERGE button reappears — the in-memory queue was lost on restart.\n // Preserve readyForMerge if review+test both passed — the merge just needs to be retried.\n const shouldBeReady =\n s.reviewStatus === 'passed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n verificationSatisfied(s) &&\n (s.uatStatus === undefined || s.uatStatus === 'passed');\n setReviewStatusSync(s.issueId, {\n mergeStatus: 'pending',\n ...(shouldBeReady ? { readyForMerge: true } : {}),\n });\n }\n}\n\n/**\n * On server startup, fix any issues where review+test both passed and\n * verificationStatus is not 'failed', but readyForMerge is stuck at false.\n *\n * This happens when:\n * 1. A merge attempt was made (merging → verifying)\n * 2. The server restarted while verifying — clearStuckMergeStatuses reset mergeStatus to 'pending'\n * 3. At restart time, verificationStatus was 'pending' (reset by the request-review cycle)\n * 4. The old verificationSatisfied check blocked readyForMerge because of 'pending' status\n *\n * With verificationSatisfied now only blocking on 'failed', these issues should be\n * re-evaluated and readyForMerge restored so they reappear on the Awaiting Merge page.\n */\nexport function fixStuckReadyForMerge(): void {\n const statuses = loadReviewStatuses();\n const stuck = Object.values(statuses).filter(s =>\n s.readyForMerge === false &&\n s.reviewStatus === 'passed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n verificationSatisfied(s) &&\n // Only fix 'pending'/'queued' merge states — not 'failed' ones.\n // 'failed' means the merge actually attempted and broke; those need human review,\n // not automatic restoration. 'merged' is done. Only pending/queued are stuck-but-valid.\n (s.mergeStatus === 'pending' || s.mergeStatus === 'queued' || s.mergeStatus === undefined || s.mergeStatus === null) &&\n (s.uatStatus === undefined || s.uatStatus === 'passed')\n );\n if (stuck.length === 0) return;\n console.log(`[review-status] Restoring readyForMerge for ${stuck.length} issue(s) with passed review+test`);\n for (const s of stuck) {\n console.log(`[review-status] Restoring readyForMerge=true for ${s.issueId} (verif=${s.verificationStatus}, merge=${s.mergeStatus})`);\n setReviewStatusSync(s.issueId, { readyForMerge: true });\n }\n}\n\n/**\n * PAN-869: On server startup, fix any issues where reviewStatus was incorrectly\n * set to 'failed' due to the old COMMENTED → 'failed' mapping bug.\n *\n * This identifies records where:\n * - reviewStatus = 'failed'\n * - testStatus = 'passed' (CI green, so review wasn't genuinely bad)\n * - mergeStatus is not terminal ('merged', 'failed')\n * - readyForMerge = false\n * - The last review history entry is type='review', status='failed'\n *\n * The old reviewResultToReviewStatus() mapped COMMENTED (regardless of success)\n * to 'failed', so the history stores 'failed' for old COMMENTED reviews.\n * We use testStatus='passed' as the signal that this was a successful review\n * (CI was green), distinguishing it from genuinely failed reviews.\n */\nexport function fixStuckCommentedReviews(): void {\n const statuses = loadReviewStatuses();\n const candidates = Object.values(statuses).filter(s =>\n s.reviewStatus === 'failed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n s.mergeStatus !== 'merged' &&\n s.mergeStatus !== 'failed' &&\n s.readyForMerge === false &&\n s.verificationStatus !== 'failed'\n );\n\n if (candidates.length === 0) return;\n\n const toFix: string[] = [];\n for (const s of candidates) {\n // Check if the last review history entry is 'failed' (the old COMMENTED mapping\n // stored 'failed' in history). testStatus='passed' signals CI was green,\n // so this was a successful review incorrectly stored as 'failed'.\n const lastReviewEntry = [...(s.history || [])]\n .reverse()\n .find(h => h.type === 'review');\n if (lastReviewEntry?.status === 'failed') {\n toFix.push(s.issueId);\n }\n }\n\n if (toFix.length === 0) return;\n console.log(`[review-status] Restoring reviewStatus='passed' for ${toFix.length} issue(s) with COMMENTED reviews (PAN-869 backfill)`);\n for (const issueId of toFix) {\n console.log(`[review-status] Restoring reviewStatus='passed' for ${issueId}`);\n // reviewStatus='passed' will trigger readyForMerge recomputation in setReviewStatus\n setReviewStatusSync(issueId, { reviewStatus: 'passed' });\n }\n}\n\nexport function clearReviewStatus(issueId: string): void {\n try {\n dbDelete(issueId);\n } catch (err) {\n console.error('[review-status] SQLite delete failed:', err);\n }\n}\n\n// ============== Stuck state helpers (PAN-653) ==============\n\n/**\n * Mark a workspace as stuck with a reason and optional JSON details.\n * Persists across dashboard restarts. Deacon will skip stuck workspaces.\n *\n * @param issueId - Issue ID (e.g. \"PAN-653\")\n * @param reason - Short reason code (e.g. \"main_diverged\")\n * @param details - Optional structured details (e.g. {localSha, remoteSha})\n */\n// PAN-1988: `stuck` is EPHEMERAL runtime state (set when patrol detects a wedged workspace),\n// NOT a durable verdict — projectPipeline deliberately does not journal it, and it is rebuilt\n// from runtime on a cache rebuild. So markWorkspaceStuck/clearWorkspaceStuck write the DB cache\n// directly and do not go through the journal door. The getReviewStatusSync journal→DB reconcile\n// preserves it (a strict overlay that never clobbers DB-only fields the journal doesn't carry).\nexport function markWorkspaceStuck(\n issueId: string,\n reason: string,\n details?: Record<string, unknown>,\n): void {\n try {\n dbMarkStuck(issueId, reason, details);\n console.log(`[review-status] Marked ${issueId} as stuck: ${reason}`);\n const updated = getReviewStatusSync(issueId);\n if (updated) notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n } catch (err) {\n console.error(`[review-status] Failed to mark ${issueId} as stuck:`, err);\n }\n}\n\n/**\n * Clear the stuck flag for a workspace.\n * Called when the human clicks \"Unstick\" in the dashboard.\n * Re-enables Deacon patrol for this workspace.\n */\nexport function clearWorkspaceStuck(issueId: string): void {\n try {\n dbClearStuck(issueId);\n console.log(`[review-status] Cleared stuck state for ${issueId}`);\n const updated = getReviewStatusSync(issueId);\n if (updated) notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n } catch (err) {\n console.error(`[review-status] Failed to clear stuck state for ${issueId}:`, err);\n }\n}\n\n/**\n * Set or clear the operator-requested deacon-ignore flag. When set, Deacon\n * patrol skips the issue entirely on every cycle. Distinct from `stuck`, which\n * is a system-set failure marker that also suppresses patrol.\n */\nexport function setDeaconIgnored(\n issueId: string,\n ignored: boolean,\n reason?: string,\n): void {\n try {\n // PAN-1988: route through the single write door. deaconIgnored is a DURABLE field that\n // projectPipeline journals — a DB-only write (the old dbSetDeaconIgnored) lands in the\n // cache but not the journal, so it vanishes on a cache rebuild. setReviewStatusSync writes\n // both (and emits the status_changed event), keeping DB and journal in sync.\n setReviewStatusSync(issueId, {\n deaconIgnored: ignored,\n deaconIgnoredAt: ignored ? new Date().toISOString() : undefined,\n deaconIgnoredReason: ignored ? reason : undefined,\n });\n console.log(`[review-status] deaconIgnored=${ignored} for ${issueId}${reason ? ` (${reason})` : ''}`);\n } catch (err) {\n console.error(`[review-status] Failed to set deaconIgnored for ${issueId}:`, err);\n }\n}\n\n/**\n * PAN-1691: set the per-issue auto-merge routing key and broadcast the change.\n * `autoMerge === null` clears it back to the project default. Emits a\n * status_changed pipeline event so open dashboards reflect the toggle live.\n */\nexport function setAutoMerge(issueId: string, autoMerge: boolean | null): void {\n try {\n // PAN-1988: route through the single write door. autoMerge is a DURABLE field journaled by\n // projectPipeline; a DB-only write would be lost on cache rebuild. `null` clears it back to\n // the project default (stored as undefined). setReviewStatusSync writes DB + journal and\n // emits the status_changed event.\n setReviewStatusSync(issueId, { autoMerge: autoMerge === null ? undefined : autoMerge });\n console.log(`[review-status] autoMerge=${autoMerge === null ? 'default' : autoMerge} for ${issueId}`);\n } catch (err) {\n console.error(`[review-status] Failed to set autoMerge for ${issueId}:`, err);\n }\n}\n\n/** Tagged error for review-status Effect variants. */\nexport class ReviewStatusError extends Data.TaggedError('ReviewStatusError')<{\n readonly issueId: string;\n readonly operation: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\nexport const setReviewStatus = (\n issueId: string,\n update: Partial<ReviewStatus>,\n existing?: ReviewStatus,\n): Effect.Effect<ReviewStatus, ReviewStatusError> =>\n Effect.tryPromise({\n try: () => new Promise<ReviewStatus>((resolve, reject) => {\n setImmediate(() => {\n try {\n resolve(setReviewStatusSync(issueId, update, existing));\n } catch (err) {\n reject(err);\n }\n });\n }),\n catch: (cause) =>\n new ReviewStatusError({\n issueId,\n operation: 'setReviewStatus',\n message: cause instanceof Error ? cause.message : String(cause),\n cause,\n }),\n });\n\nexport const getReviewStatus = (\n issueId: string,\n): Effect.Effect<ReviewStatus | null, ReviewStatusError> =>\n Effect.try({\n try: () => getReviewStatusFromDbSync(issueId),\n catch: (cause) =>\n new ReviewStatusError({\n issueId,\n operation: 'getReviewStatus',\n message: cause instanceof Error ? cause.message : String(cause),\n cause,\n }),\n });\n"],"mappings":";;;;;;;;;;;;;;;;AAiGA,SAAS,cAAc,OAAsD;AAC3E,QAAO,SAAS,OAAO,KAAA,IAAY,IAAI,KAAK,MAAM,CAAC,aAAa;;AAGlE,SAAS,cAAc,OAAiD;AACtE,KAAI,CAAC,MAAO,QAAO;CACnB,MAAM,SAAS,KAAK,MAAM,MAAM;AAChC,QAAO,OAAO,SAAS,OAAO,GAAG,SAAS;;AAG5C,SAAS,gBAAgB,OAAuD;AAC9E,QAAO,SAAS,OAAO,KAAA,IAAY,QAAQ,MAAM;;AAGnD,SAAS,oBAAoB,OAAuD;AAClF,KAAI,SAAS,KAAM,QAAO,KAAA;AAC1B,QAAO,UAAU,OAAO,UAAU,UAAU,UAAU;;AAGxD,SAAS,kBAAkB,OAA2C;AACpE,QAAO,UAAU,OAAO,SAAS;;AAGnC,SAAS,wBAAwB,KAAmC;CAClE,MAAM,iBAAiB,IAAI;AAC3B,QAAO;EACL,IAAI,IAAI;EACR,SAAS,IAAI;EACb,WAAW,IAAI;EACf,MAAM,IAAI;EACV,OAAO,IAAI,SAAS;EACpB,QAAQ,IAA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UAAQ,MAAM,+CAA+C,QAAQ,IAAI,IAAI;;;;;yBA7kCrB;uBACsB;0BASxC;4BACyC;+BACV;iCAC8E;gCACnF;AA8KpE,qCAAoC,4BAA4B,CAAC;AAE3D,uBAAsB,KAAK,SAAS,EAAE,aAAa,qBAAqB;AAiexE,2CAA0B,IAAI,KAAqB;AACnD,oCAAmC;AAwDnC,yCAAwB,IAAI,KAAqB;AACjD,qCAAoC;AAyX7B,qBAAb,cAAuC,KAAK,YAAY,oBAAoB,CAKzE;AAEU,oBACX,SACA,QACA,aAEA,OAAO,WAAW;EAChB,WAAW,IAAI,SAAuB,SAAS,WAAW;AACxD,sBAAmB;AACjB,QAAI;AACF,aAAQ,oBAAoB,SAAS,QAAQ,SAAS,CAAC;aAChD,KAAK;AACZ,YAAO,IAAI;;KAEb;IACF;EACF,QAAQ,UACN,IAAI,kBAAkB;GACpB;GACA,WAAW;GACX,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D;GACD,CAAC;EACL,CAAC;AAES,oBACX,YAEA,OAAO,IAAI;EACT,WAAW,0BAA0B,QAAQ;EAC7C,QAAQ,UACN,IAAI,kBAAkB;GACpB;GACA,WAAW;GACX,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D;GACD,CAAC;EACL,CAAC"}
@@ -1,2 +0,0 @@
1
- import { a as deepWipe, i as closeOut } from "./workflows-H-COJ84X.js";
2
- export { closeOut, deepWipe };
@@ -1,2 +0,0 @@
1
- import { t as backfillIssueRecords } from "./records-backfill-HM0Pln6N.js";
2
- export { backfillIssueRecords };
@@ -1,3 +0,0 @@
1
- import { S as resumeAgent, x as init_resume } from "./agents-CQHK0CSA.js";
2
- init_resume();
3
- export { resumeAgent };
@@ -1,3 +0,0 @@
1
- import { a as killAllReviewerSessions, i as killAllReviewSessions, l as handleReviewDiscoveryReady, s as spawnReviewRoleForIssue, t as init_review_agent } from "./review-agent-DFosQzCG.js";
2
- init_review_agent();
3
- export { handleReviewDiscoveryReady, killAllReviewSessions, killAllReviewerSessions, spawnReviewRoleForIssue };
@@ -1,2 +0,0 @@
1
- import { t as syncCommand } from "./sync-BiNVQHBf.js";
2
- export { syncCommand };