@moberg_hr/work-tree 2.11.3 → 2.11.5

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 (297) hide show
  1. package/dist/{account-2JVKRIAM.js → account-EAVYWOKR.js} +39 -24
  2. package/dist/account-EAVYWOKR.js.map +1 -0
  3. package/dist/{add-repo-7Y2GWYJX.js → add-repo-3THEK6UG.js} +23 -22
  4. package/dist/{add-repo-7Y2GWYJX.js.map → add-repo-3THEK6UG.js.map} +1 -1
  5. package/dist/{answer-QYFUON2W.js → answer-3CJQWBGY.js} +14 -13
  6. package/dist/{answer-QYFUON2W.js.map → answer-3CJQWBGY.js.map} +1 -1
  7. package/dist/{attach-42GWPK2B.js → attach-FQSBZXI7.js} +20 -19
  8. package/dist/{attach-42GWPK2B.js.map → attach-FQSBZXI7.js.map} +1 -1
  9. package/dist/bin.js +4 -4
  10. package/dist/{block-H23F7WOT.js → block-NGD2KNTU.js} +19 -18
  11. package/dist/{block-H23F7WOT.js.map → block-NGD2KNTU.js.map} +1 -1
  12. package/dist/{broadcast-SVEHWJEJ.js → broadcast-NLASZGWR.js} +10 -9
  13. package/dist/{broadcast-SVEHWJEJ.js.map → broadcast-NLASZGWR.js.map} +1 -1
  14. package/dist/{catchup-IPIOOOFW.js → catchup-WJPWOGVI.js} +17 -16
  15. package/dist/{catchup-IPIOOOFW.js.map → catchup-WJPWOGVI.js.map} +1 -1
  16. package/dist/{chunk-PVTTWADL.js → chunk-3257QPVM.js} +3 -3
  17. package/dist/{chunk-FVENEUOL.js → chunk-3KVOYBM4.js} +6 -6
  18. package/dist/{chunk-XEEF2V22.js → chunk-3O6QFWZ6.js} +2 -2
  19. package/dist/{chunk-P5YSGQBS.js → chunk-45MDVVW7.js} +6 -6
  20. package/dist/{chunk-JAC6X4XN.js → chunk-5LUXNIPA.js} +2 -2
  21. package/dist/{chunk-43EUE5L5.js → chunk-5RAAS4II.js} +9 -7
  22. package/dist/{chunk-43EUE5L5.js.map → chunk-5RAAS4II.js.map} +1 -1
  23. package/dist/{chunk-V3AS6S7C.js → chunk-64M7W2OQ.js} +5 -5
  24. package/dist/{chunk-O36SFV5G.js → chunk-7FNJ6A2U.js} +3 -3
  25. package/dist/{chunk-WN623NAR.js → chunk-7IZVI76D.js} +11 -10
  26. package/dist/chunk-7IZVI76D.js.map +1 -0
  27. package/dist/{chunk-4K4S53KX.js → chunk-7UXV4X2Y.js} +2 -2
  28. package/dist/{chunk-PEGZW3TZ.js → chunk-ACNCTLFO.js} +3 -3
  29. package/dist/{chunk-MQCDFSVF.js → chunk-AGRUEZQX.js} +2 -2
  30. package/dist/{chunk-T5SHUOWM.js → chunk-ANS6OH55.js} +3 -3
  31. package/dist/{chunk-DAKJTB6N.js → chunk-AYHDJMMJ.js} +2 -2
  32. package/dist/{chunk-GKZHWV2R.js → chunk-B2K2I2PQ.js} +26 -8
  33. package/dist/chunk-B2K2I2PQ.js.map +1 -0
  34. package/dist/{chunk-DHNW25TR.js → chunk-BHJ73OPQ.js} +4 -4
  35. package/dist/{chunk-PPZP7CA7.js → chunk-BK73QU45.js} +3 -3
  36. package/dist/{chunk-KMAA4PTG.js → chunk-BW5U6ENJ.js} +4 -4
  37. package/dist/{chunk-7HFSM4SJ.js → chunk-C72Y42VC.js} +6 -6
  38. package/dist/{chunk-SK7MB54C.js → chunk-C7ZKDWPI.js} +4 -4
  39. package/dist/{chunk-OTDYHKRZ.js → chunk-CS2EINZJ.js} +58 -56
  40. package/dist/chunk-CS2EINZJ.js.map +1 -0
  41. package/dist/{chunk-W6SKLTNO.js → chunk-CVMO75V5.js} +4 -4
  42. package/dist/{chunk-BAYVM33J.js → chunk-DHOC2S2L.js} +8 -8
  43. package/dist/{chunk-DMGNJ73M.js → chunk-DROLR3NJ.js} +2 -2
  44. package/dist/{chunk-KJRUC2QY.js → chunk-DS2CKYQ4.js} +2 -2
  45. package/dist/{chunk-E3VBI6BJ.js → chunk-DTFACBDD.js} +182 -94
  46. package/dist/chunk-DTFACBDD.js.map +1 -0
  47. package/dist/chunk-DW245WK4.js +74 -0
  48. package/dist/chunk-DW245WK4.js.map +1 -0
  49. package/dist/{chunk-ILACZ77E.js → chunk-DZ6SLAIZ.js} +2 -2
  50. package/dist/{chunk-KXNYMDIJ.js → chunk-EJSGPLXO.js} +7 -5
  51. package/dist/{chunk-KXNYMDIJ.js.map → chunk-EJSGPLXO.js.map} +1 -1
  52. package/dist/{chunk-BDPRYJL3.js → chunk-EYDGX32Q.js} +2 -2
  53. package/dist/chunk-FC7RECDP.js +9 -0
  54. package/dist/{chunk-NSG3W5ZE.js → chunk-FM6VLU4T.js} +5 -5
  55. package/dist/{chunk-63ZLPXRL.js → chunk-G2V2V5UC.js} +7 -3
  56. package/dist/chunk-G2V2V5UC.js.map +1 -0
  57. package/dist/{chunk-VKJ7XFH2.js → chunk-H4TMS567.js} +7 -7
  58. package/dist/{chunk-NFWSJFYY.js → chunk-HHXVHUGP.js} +2 -2
  59. package/dist/{chunk-7YEACWWO.js → chunk-HORDAO4Z.js} +4 -4
  60. package/dist/{chunk-C72H5FHW.js → chunk-I3FLUAK7.js} +3 -3
  61. package/dist/{chunk-4ZNSMFXT.js → chunk-I7AEQDG7.js} +2 -2
  62. package/dist/{chunk-O5ZJY5BT.js → chunk-INI6TEYT.js} +2 -1
  63. package/dist/chunk-INI6TEYT.js.map +1 -0
  64. package/dist/{chunk-FFTMMZM7.js → chunk-IREGW23T.js} +2 -2
  65. package/dist/{chunk-YKQLHFY4.js → chunk-IUWMT6PF.js} +48 -4
  66. package/dist/chunk-IUWMT6PF.js.map +1 -0
  67. package/dist/{chunk-KEOIM36N.js → chunk-JIWPC53O.js} +9 -9
  68. package/dist/{chunk-UJJDDB6D.js → chunk-JNAYPBAB.js} +7 -7
  69. package/dist/{chunk-IWK733M6.js → chunk-JVRS73M6.js} +6 -6
  70. package/dist/{chunk-DCCC7LEP.js → chunk-K5EAVRXX.js} +5 -3
  71. package/dist/{chunk-DCCC7LEP.js.map → chunk-K5EAVRXX.js.map} +1 -1
  72. package/dist/{chunk-6GBM4B5N.js → chunk-KCWU6HNJ.js} +8 -8
  73. package/dist/{chunk-AHYCZUPI.js → chunk-LSZ6HI3U.js} +2 -2
  74. package/dist/{chunk-KSVYR4G2.js → chunk-MKQ7IA6U.js} +3 -3
  75. package/dist/{chunk-RY6ZLC76.js → chunk-N5PQHNYK.js} +2 -2
  76. package/dist/{chunk-NXUBAXXP.js → chunk-NOB3VR5I.js} +57 -119
  77. package/dist/chunk-NOB3VR5I.js.map +1 -0
  78. package/dist/{chunk-AZPE2HLY.js → chunk-NUPLJJOS.js} +17 -16
  79. package/dist/chunk-NUPLJJOS.js.map +1 -0
  80. package/dist/{chunk-E4O7OZ5G.js → chunk-OIVEYULL.js} +6 -6
  81. package/dist/{chunk-MESE7KI5.js → chunk-OTKWVUGB.js} +3 -3
  82. package/dist/{chunk-4XLB3ARR.js → chunk-PGGNMC34.js} +8 -6
  83. package/dist/{chunk-4XLB3ARR.js.map → chunk-PGGNMC34.js.map} +1 -1
  84. package/dist/{chunk-WH2CGK2A.js → chunk-RPWEOEA3.js} +11 -7
  85. package/dist/chunk-RPWEOEA3.js.map +1 -0
  86. package/dist/{chunk-IV7YIC55.js → chunk-RSCRZGUW.js} +2 -2
  87. package/dist/{chunk-Q5DGDBZL.js → chunk-S36RENUJ.js} +3 -3
  88. package/dist/{chunk-ZBNRIPLQ.js → chunk-SPVVXKDV.js} +6 -3
  89. package/dist/chunk-SPVVXKDV.js.map +1 -0
  90. package/dist/chunk-SQACJQUY.js +37 -0
  91. package/dist/chunk-SQACJQUY.js.map +1 -0
  92. package/dist/{chunk-3ZV77FBH.js → chunk-TFNDOWYP.js} +4 -4
  93. package/dist/{chunk-GT4JUJ76.js → chunk-TL7K3XUY.js} +7 -7
  94. package/dist/{chunk-3MXZNRVH.js → chunk-TMAQASMH.js} +9 -9
  95. package/dist/{chunk-RGLIW45S.js → chunk-TMBO55MM.js} +2 -2
  96. package/dist/{chunk-HIVX3POL.js → chunk-TSFNTMMY.js} +3 -3
  97. package/dist/{chunk-JNBMANFM.js → chunk-TUDDISCX.js} +6 -3
  98. package/dist/{chunk-MSJWQC7H.js → chunk-U2MOKVPZ.js} +2 -2
  99. package/dist/{chunk-J6T75IWG.js → chunk-UQJQZ526.js} +5 -5
  100. package/dist/{chunk-S5YGRCGU.js → chunk-VPFAXLSX.js} +10 -8
  101. package/dist/{chunk-S5YGRCGU.js.map → chunk-VPFAXLSX.js.map} +1 -1
  102. package/dist/{chunk-VJ5XMYXE.js → chunk-VVRSPS67.js} +2 -2
  103. package/dist/{chunk-I6MILNM5.js → chunk-ZIFWZJ7X.js} +2 -2
  104. package/dist/{chunk-EWTW53YY.js → chunk-ZQJKAZRD.js} +10 -10
  105. package/dist/{chunk-EL3XL2OC.js → chunk-ZS7ZXAXB.js} +29 -60
  106. package/dist/chunk-ZS7ZXAXB.js.map +1 -0
  107. package/dist/{cleanup-BOCBMMWE.js → cleanup-GFYEKCJS.js} +41 -40
  108. package/dist/{cleanup-BOCBMMWE.js.map → cleanup-GFYEKCJS.js.map} +1 -1
  109. package/dist/cli-QP3BQXVW.js +20 -0
  110. package/dist/{completion-IAH7WRKJ.js → completion-OEU4UZEA.js} +4 -3
  111. package/dist/{completion-IAH7WRKJ.js.map → completion-OEU4UZEA.js.map} +1 -1
  112. package/dist/{config-77SIIJCR.js → config-W3AEOOUK.js} +16 -15
  113. package/dist/{config-77SIIJCR.js.map → config-W3AEOOUK.js.map} +1 -1
  114. package/dist/{diff-5ASU7NDE.js → diff-G53V34KI.js} +16 -15
  115. package/dist/{diff-5ASU7NDE.js.map → diff-G53V34KI.js.map} +1 -1
  116. package/dist/{digest-4AYCHWBQ.js → digest-W4425I4J.js} +13 -12
  117. package/dist/{digest-4AYCHWBQ.js.map → digest-W4425I4J.js.map} +1 -1
  118. package/dist/{fork-Q2FO4545.js → fork-HTPJML6G.js} +37 -36
  119. package/dist/{fork-Q2FO4545.js.map → fork-HTPJML6G.js.map} +1 -1
  120. package/dist/{history-XWBADBLU.js → history-TYKH3SKB.js} +12 -9
  121. package/dist/{hook-FX44WIXE.js → hook-F7WR5UIQ.js} +19 -18
  122. package/dist/{hook-FX44WIXE.js.map → hook-F7WR5UIQ.js.map} +1 -1
  123. package/dist/{hydrate-OO3AOQGU.js → hydrate-HDZ62YMD.js} +11 -10
  124. package/dist/{hydrate-OO3AOQGU.js.map → hydrate-HDZ62YMD.js.map} +1 -1
  125. package/dist/{init-DVP2F374.js → init-Q5KJ666H.js} +21 -20
  126. package/dist/{init-DVP2F374.js.map → init-Q5KJ666H.js.map} +1 -1
  127. package/dist/install-skills-C46BIZ5O.js +23 -0
  128. package/dist/install-skills-bin.js +9 -8
  129. package/dist/install-skills-bin.js.map +1 -1
  130. package/dist/keep-MYHUCQWD.js +53 -0
  131. package/dist/keep-MYHUCQWD.js.map +1 -0
  132. package/dist/{list-2Y6FB37X.js → list-BGHRHYV6.js} +12 -11
  133. package/dist/{list-2Y6FB37X.js.map → list-BGHRHYV6.js.map} +1 -1
  134. package/dist/{move-2ICBEGSP.js → move-OHV2DC4V.js} +26 -25
  135. package/dist/{move-2ICBEGSP.js.map → move-OHV2DC4V.js.map} +1 -1
  136. package/dist/{note-ADRHPCW3.js → note-2I5WTKED.js} +13 -12
  137. package/dist/{note-ADRHPCW3.js.map → note-2I5WTKED.js.map} +1 -1
  138. package/dist/{overlaps-K4FAJZAY.js → overlaps-PX4BD23H.js} +20 -19
  139. package/dist/{overlaps-K4FAJZAY.js.map → overlaps-PX4BD23H.js.map} +1 -1
  140. package/dist/{pin-FECMJAW3.js → pin-UTMH2XUZ.js} +13 -12
  141. package/dist/{pin-FECMJAW3.js.map → pin-UTMH2XUZ.js.map} +1 -1
  142. package/dist/{pr-PAOI4S4B.js → pr-PZCO36TY.js} +29 -28
  143. package/dist/{pr-PAOI4S4B.js.map → pr-PZCO36TY.js.map} +1 -1
  144. package/dist/{prune-6CGA3L5M.js → prune-APCNVQKK.js} +39 -38
  145. package/dist/{prune-6CGA3L5M.js.map → prune-APCNVQKK.js.map} +1 -1
  146. package/dist/{pty-host-6OG45QCE.js → pty-host-Q5VNQKP2.js} +38 -17
  147. package/dist/pty-host-Q5VNQKP2.js.map +1 -0
  148. package/dist/{read-GOC77JDO.js → read-HSQNG4CA.js} +13 -12
  149. package/dist/{read-GOC77JDO.js.map → read-HSQNG4CA.js.map} +1 -1
  150. package/dist/{recent-YPW7VBOP.js → recent-SNDWYLUH.js} +19 -18
  151. package/dist/{recent-YPW7VBOP.js.map → recent-SNDWYLUH.js.map} +1 -1
  152. package/dist/{remove-24MVWSEL.js → remove-5F5SP5TM.js} +51 -38
  153. package/dist/remove-5F5SP5TM.js.map +1 -0
  154. package/dist/{restart-AG3WNQG5.js → restart-HWSAV22N.js} +14 -13
  155. package/dist/{restart-AG3WNQG5.js.map → restart-HWSAV22N.js.map} +1 -1
  156. package/dist/{resume-H5JKES3P.js → resume-DBO7FTEQ.js} +19 -18
  157. package/dist/{resume-H5JKES3P.js.map → resume-DBO7FTEQ.js.map} +1 -1
  158. package/dist/review-36OJ5EES.js +122 -0
  159. package/dist/review-36OJ5EES.js.map +1 -0
  160. package/dist/{review-now-HHQIBVUS.js → review-now-CZPT7X4K.js} +3 -3
  161. package/dist/{run-IIYIZNQV.js → run-QQARI2AH.js} +10 -9
  162. package/dist/{run-IIYIZNQV.js.map → run-QQARI2AH.js.map} +1 -1
  163. package/dist/{screen-5DDNVXPL.js → screen-SXJEHTUY.js} +14 -13
  164. package/dist/{screen-5DDNVXPL.js.map → screen-SXJEHTUY.js.map} +1 -1
  165. package/dist/{search-JYRJVY4T.js → search-U25QWSX4.js} +10 -9
  166. package/dist/{search-JYRJVY4T.js.map → search-U25QWSX4.js.map} +1 -1
  167. package/dist/{section-KQBSB6LP.js → section-TCH4DXE7.js} +13 -12
  168. package/dist/{section-KQBSB6LP.js.map → section-TCH4DXE7.js.map} +1 -1
  169. package/dist/{send-DHHXAA23.js → send-ZCKMC65W.js} +19 -18
  170. package/dist/{send-DHHXAA23.js.map → send-ZCKMC65W.js.map} +1 -1
  171. package/dist/{sessions-HMXB33GI.js → sessions-7PKZZ4NG.js} +33 -32
  172. package/dist/{sessions-HMXB33GI.js.map → sessions-7PKZZ4NG.js.map} +1 -1
  173. package/dist/{snooze-VGROZWYG.js → snooze-JBPRRYAF.js} +13 -12
  174. package/dist/{snooze-VGROZWYG.js.map → snooze-JBPRRYAF.js.map} +1 -1
  175. package/dist/{start-QKIVUFKV.js → start-L6AWLRVP.js} +14 -13
  176. package/dist/{start-QKIVUFKV.js.map → start-L6AWLRVP.js.map} +1 -1
  177. package/dist/{state-BR43ONIH.js → state-JHCC5CAR.js} +2 -2
  178. package/dist/{status-YD74D27O.js → status-WWRZLDGT.js} +17 -16
  179. package/dist/{status-YD74D27O.js.map → status-WWRZLDGT.js.map} +1 -1
  180. package/dist/{statusline-WKKYCH7O.js → statusline-MIFW47UA.js} +7 -6
  181. package/dist/{statusline-WKKYCH7O.js.map → statusline-MIFW47UA.js.map} +1 -1
  182. package/dist/{statusline-hook-K7KPN2H6.js → statusline-hook-W7KWKWAC.js} +5 -4
  183. package/dist/{statusline-hook-K7KPN2H6.js.map → statusline-hook-W7KWKWAC.js.map} +1 -1
  184. package/dist/{stop-R2LFFUXE.js → stop-WHUBU5JZ.js} +14 -13
  185. package/dist/{stop-R2LFFUXE.js.map → stop-WHUBU5JZ.js.map} +1 -1
  186. package/dist/{sync-FX5C3PVX.js → sync-AVDUHYPQ.js} +39 -38
  187. package/dist/{sync-FX5C3PVX.js.map → sync-AVDUHYPQ.js.map} +1 -1
  188. package/dist/{time-TX7MBFXX.js → time-MIJM6SM6.js} +14 -13
  189. package/dist/{time-TX7MBFXX.js.map → time-MIJM6SM6.js.map} +1 -1
  190. package/dist/{time-actions-YOXF5WC7.js → time-actions-Y5USDGSE.js} +3 -3
  191. package/dist/{timesheet-QBLPQSVX.js → timesheet-AVRH56TG.js} +22 -21
  192. package/dist/{timesheet-QBLPQSVX.js.map → timesheet-AVRH56TG.js.map} +1 -1
  193. package/dist/{todo-TALKJYK6.js → todo-O6Y5MEQR.js} +2 -2
  194. package/dist/{tree-2PSHOP5B.js → tree-7YD6DL3H.js} +46 -40
  195. package/dist/{tree-2PSHOP5B.js.map → tree-7YD6DL3H.js.map} +1 -1
  196. package/dist/{update-4T7FDYHF.js → update-XGT2DFTT.js} +23 -22
  197. package/dist/{update-4T7FDYHF.js.map → update-XGT2DFTT.js.map} +1 -1
  198. package/dist/{usage-QL4CDVAM.js → usage-7NM6L2MR.js} +12 -11
  199. package/dist/{usage-QL4CDVAM.js.map → usage-7NM6L2MR.js.map} +1 -1
  200. package/dist/{version-SW4YGEIY.js → version-V7IM2UL4.js} +11 -9
  201. package/dist/{version-SW4YGEIY.js.map → version-V7IM2UL4.js.map} +1 -1
  202. package/dist/{wait-TDQ4R2P3.js → wait-HCIFDLNX.js} +14 -13
  203. package/dist/{wait-TDQ4R2P3.js.map → wait-HCIFDLNX.js.map} +1 -1
  204. package/dist/wd-bin.js +9 -8
  205. package/dist/wd-bin.js.map +1 -1
  206. package/dist/web/assets/{PtyView-DyDsqsKc.js → PtyView-R0tQXVW8.js} +2 -2
  207. package/dist/web/assets/{PtyView-DyDsqsKc.js.map → PtyView-R0tQXVW8.js.map} +1 -1
  208. package/dist/web/assets/index-Beb-xh6z.js +126 -0
  209. package/dist/web/assets/index-Beb-xh6z.js.map +1 -0
  210. package/dist/web/assets/index-QlOaahcZ.css +1 -0
  211. package/dist/web/index.html +2 -2
  212. package/dist/{web-7FRKYLDS.js → web-AXS3EMZ3.js} +1792 -1117
  213. package/dist/web-AXS3EMZ3.js.map +1 -0
  214. package/npm-shrinkwrap.json +2 -2
  215. package/package.json +1 -1
  216. package/dist/account-2JVKRIAM.js.map +0 -1
  217. package/dist/chunk-63ZLPXRL.js.map +0 -1
  218. package/dist/chunk-AZPE2HLY.js.map +0 -1
  219. package/dist/chunk-E3VBI6BJ.js.map +0 -1
  220. package/dist/chunk-EL3XL2OC.js.map +0 -1
  221. package/dist/chunk-GKZHWV2R.js.map +0 -1
  222. package/dist/chunk-NXUBAXXP.js.map +0 -1
  223. package/dist/chunk-O5ZJY5BT.js.map +0 -1
  224. package/dist/chunk-OTDYHKRZ.js.map +0 -1
  225. package/dist/chunk-P6XBAGSF.js +0 -9
  226. package/dist/chunk-WH2CGK2A.js.map +0 -1
  227. package/dist/chunk-WN623NAR.js.map +0 -1
  228. package/dist/chunk-YKQLHFY4.js.map +0 -1
  229. package/dist/chunk-ZBNRIPLQ.js.map +0 -1
  230. package/dist/cli-X3A7KF2M.js +0 -19
  231. package/dist/install-skills-AKKAAIAK.js +0 -22
  232. package/dist/pty-host-6OG45QCE.js.map +0 -1
  233. package/dist/remove-24MVWSEL.js.map +0 -1
  234. package/dist/web/assets/index-BjNPYCVy.js +0 -126
  235. package/dist/web/assets/index-BjNPYCVy.js.map +0 -1
  236. package/dist/web/assets/index-CpqiTeqj.css +0 -1
  237. package/dist/web-7FRKYLDS.js.map +0 -1
  238. /package/dist/{chunk-PVTTWADL.js.map → chunk-3257QPVM.js.map} +0 -0
  239. /package/dist/{chunk-FVENEUOL.js.map → chunk-3KVOYBM4.js.map} +0 -0
  240. /package/dist/{chunk-XEEF2V22.js.map → chunk-3O6QFWZ6.js.map} +0 -0
  241. /package/dist/{chunk-P5YSGQBS.js.map → chunk-45MDVVW7.js.map} +0 -0
  242. /package/dist/{chunk-JAC6X4XN.js.map → chunk-5LUXNIPA.js.map} +0 -0
  243. /package/dist/{chunk-V3AS6S7C.js.map → chunk-64M7W2OQ.js.map} +0 -0
  244. /package/dist/{chunk-O36SFV5G.js.map → chunk-7FNJ6A2U.js.map} +0 -0
  245. /package/dist/{chunk-4K4S53KX.js.map → chunk-7UXV4X2Y.js.map} +0 -0
  246. /package/dist/{chunk-PEGZW3TZ.js.map → chunk-ACNCTLFO.js.map} +0 -0
  247. /package/dist/{chunk-MQCDFSVF.js.map → chunk-AGRUEZQX.js.map} +0 -0
  248. /package/dist/{chunk-T5SHUOWM.js.map → chunk-ANS6OH55.js.map} +0 -0
  249. /package/dist/{chunk-DAKJTB6N.js.map → chunk-AYHDJMMJ.js.map} +0 -0
  250. /package/dist/{chunk-DHNW25TR.js.map → chunk-BHJ73OPQ.js.map} +0 -0
  251. /package/dist/{chunk-PPZP7CA7.js.map → chunk-BK73QU45.js.map} +0 -0
  252. /package/dist/{chunk-KMAA4PTG.js.map → chunk-BW5U6ENJ.js.map} +0 -0
  253. /package/dist/{chunk-7HFSM4SJ.js.map → chunk-C72Y42VC.js.map} +0 -0
  254. /package/dist/{chunk-SK7MB54C.js.map → chunk-C7ZKDWPI.js.map} +0 -0
  255. /package/dist/{chunk-W6SKLTNO.js.map → chunk-CVMO75V5.js.map} +0 -0
  256. /package/dist/{chunk-BAYVM33J.js.map → chunk-DHOC2S2L.js.map} +0 -0
  257. /package/dist/{chunk-DMGNJ73M.js.map → chunk-DROLR3NJ.js.map} +0 -0
  258. /package/dist/{chunk-KJRUC2QY.js.map → chunk-DS2CKYQ4.js.map} +0 -0
  259. /package/dist/{chunk-ILACZ77E.js.map → chunk-DZ6SLAIZ.js.map} +0 -0
  260. /package/dist/{chunk-BDPRYJL3.js.map → chunk-EYDGX32Q.js.map} +0 -0
  261. /package/dist/{chunk-P6XBAGSF.js.map → chunk-FC7RECDP.js.map} +0 -0
  262. /package/dist/{chunk-NSG3W5ZE.js.map → chunk-FM6VLU4T.js.map} +0 -0
  263. /package/dist/{chunk-VKJ7XFH2.js.map → chunk-H4TMS567.js.map} +0 -0
  264. /package/dist/{chunk-NFWSJFYY.js.map → chunk-HHXVHUGP.js.map} +0 -0
  265. /package/dist/{chunk-7YEACWWO.js.map → chunk-HORDAO4Z.js.map} +0 -0
  266. /package/dist/{chunk-C72H5FHW.js.map → chunk-I3FLUAK7.js.map} +0 -0
  267. /package/dist/{chunk-4ZNSMFXT.js.map → chunk-I7AEQDG7.js.map} +0 -0
  268. /package/dist/{chunk-FFTMMZM7.js.map → chunk-IREGW23T.js.map} +0 -0
  269. /package/dist/{chunk-KEOIM36N.js.map → chunk-JIWPC53O.js.map} +0 -0
  270. /package/dist/{chunk-UJJDDB6D.js.map → chunk-JNAYPBAB.js.map} +0 -0
  271. /package/dist/{chunk-IWK733M6.js.map → chunk-JVRS73M6.js.map} +0 -0
  272. /package/dist/{chunk-6GBM4B5N.js.map → chunk-KCWU6HNJ.js.map} +0 -0
  273. /package/dist/{chunk-AHYCZUPI.js.map → chunk-LSZ6HI3U.js.map} +0 -0
  274. /package/dist/{chunk-KSVYR4G2.js.map → chunk-MKQ7IA6U.js.map} +0 -0
  275. /package/dist/{chunk-RY6ZLC76.js.map → chunk-N5PQHNYK.js.map} +0 -0
  276. /package/dist/{chunk-E4O7OZ5G.js.map → chunk-OIVEYULL.js.map} +0 -0
  277. /package/dist/{chunk-MESE7KI5.js.map → chunk-OTKWVUGB.js.map} +0 -0
  278. /package/dist/{chunk-IV7YIC55.js.map → chunk-RSCRZGUW.js.map} +0 -0
  279. /package/dist/{chunk-Q5DGDBZL.js.map → chunk-S36RENUJ.js.map} +0 -0
  280. /package/dist/{chunk-3ZV77FBH.js.map → chunk-TFNDOWYP.js.map} +0 -0
  281. /package/dist/{chunk-GT4JUJ76.js.map → chunk-TL7K3XUY.js.map} +0 -0
  282. /package/dist/{chunk-3MXZNRVH.js.map → chunk-TMAQASMH.js.map} +0 -0
  283. /package/dist/{chunk-RGLIW45S.js.map → chunk-TMBO55MM.js.map} +0 -0
  284. /package/dist/{chunk-HIVX3POL.js.map → chunk-TSFNTMMY.js.map} +0 -0
  285. /package/dist/{chunk-JNBMANFM.js.map → chunk-TUDDISCX.js.map} +0 -0
  286. /package/dist/{chunk-MSJWQC7H.js.map → chunk-U2MOKVPZ.js.map} +0 -0
  287. /package/dist/{chunk-J6T75IWG.js.map → chunk-UQJQZ526.js.map} +0 -0
  288. /package/dist/{chunk-VJ5XMYXE.js.map → chunk-VVRSPS67.js.map} +0 -0
  289. /package/dist/{chunk-I6MILNM5.js.map → chunk-ZIFWZJ7X.js.map} +0 -0
  290. /package/dist/{chunk-EWTW53YY.js.map → chunk-ZQJKAZRD.js.map} +0 -0
  291. /package/dist/{cli-X3A7KF2M.js.map → cli-QP3BQXVW.js.map} +0 -0
  292. /package/dist/{history-XWBADBLU.js.map → history-TYKH3SKB.js.map} +0 -0
  293. /package/dist/{install-skills-AKKAAIAK.js.map → install-skills-C46BIZ5O.js.map} +0 -0
  294. /package/dist/{review-now-HHQIBVUS.js.map → review-now-CZPT7X4K.js.map} +0 -0
  295. /package/dist/{state-BR43ONIH.js.map → state-JHCC5CAR.js.map} +0 -0
  296. /package/dist/{time-actions-YOXF5WC7.js.map → time-actions-Y5USDGSE.js.map} +0 -0
  297. /package/dist/{todo-TALKJYK6.js.map → todo-O6Y5MEQR.js.map} +0 -0
@@ -2,7 +2,21 @@
2
2
  import {
3
3
  ensureAgentPath,
4
4
  restartHost
5
- } from "./chunk-P5YSGQBS.js";
5
+ } from "./chunk-45MDVVW7.js";
6
+ import {
7
+ createMonthGather,
8
+ defaultTimeDeps,
9
+ fetchIssueDetail,
10
+ fetchJiraPane,
11
+ fetchMyIssues,
12
+ fetchMyIssuesOrThrow,
13
+ finishDeviceLogin,
14
+ graphAccount,
15
+ graphApp,
16
+ graphProblem,
17
+ signOutGraph,
18
+ startDeviceLogin
19
+ } from "./chunk-DHOC2S2L.js";
6
20
  import {
7
21
  addTask,
8
22
  completeTask,
@@ -24,7 +38,7 @@ import {
24
38
  serveSpa,
25
39
  sessionBaseForPath,
26
40
  submitReviewSchema
27
- } from "./chunk-NSG3W5ZE.js";
41
+ } from "./chunk-FM6VLU4T.js";
28
42
  import {
29
43
  announceChange,
30
44
  createArchivedRows,
@@ -39,39 +53,31 @@ import {
39
53
  stageSeenKey,
40
54
  storeHolding,
41
55
  withRestoring
42
- } from "./chunk-WN623NAR.js";
56
+ } from "./chunk-7IZVI76D.js";
43
57
  import {
44
58
  createDigestSource
45
- } from "./chunk-SK7MB54C.js";
59
+ } from "./chunk-C7ZKDWPI.js";
46
60
  import {
47
61
  createBuildFoldersJob,
48
62
  defaultBranchTidyDeps,
49
63
  defaultBuildFoldersDeps,
50
64
  deleteMergedBranches,
51
65
  findMergedBranches
52
- } from "./chunk-KEOIM36N.js";
66
+ } from "./chunk-JIWPC53O.js";
67
+ import {
68
+ defaultCleanupDeps
69
+ } from "./chunk-KCWU6HNJ.js";
53
70
  import {
54
71
  DiffStatCache,
55
72
  findOverlaps,
56
73
  wantsDiffStat
57
- } from "./chunk-C72H5FHW.js";
58
- import {
59
- createMonthGather,
60
- defaultTimeDeps,
61
- fetchIssueDetail,
62
- fetchJiraPane,
63
- fetchMyIssues,
64
- fetchMyIssuesOrThrow,
65
- finishDeviceLogin,
66
- graphAccount,
67
- graphApp,
68
- graphProblem,
69
- signOutGraph,
70
- startDeviceLogin
71
- } from "./chunk-BAYVM33J.js";
74
+ } from "./chunk-I3FLUAK7.js";
72
75
  import {
73
- defaultCleanupDeps
74
- } from "./chunk-6GBM4B5N.js";
76
+ MAX_NOTE_CHARS,
77
+ readNote,
78
+ saveNote,
79
+ sessionsWithNotes
80
+ } from "./chunk-33XSEAHO.js";
75
81
  import {
76
82
  addBlocker,
77
83
  allBlocks,
@@ -83,7 +89,7 @@ import {
83
89
  removeBlocker,
84
90
  sweepBlocks,
85
91
  unblockedPrompt
86
- } from "./chunk-HIVX3POL.js";
92
+ } from "./chunk-TSFNTMMY.js";
87
93
  import {
88
94
  jiraWorklogPoster,
89
95
  logWorkDay,
@@ -101,15 +107,15 @@ import {
101
107
  removeAgentAccount,
102
108
  setDefaultAgentAccount,
103
109
  switchRefusal
104
- } from "./chunk-VKJ7XFH2.js";
110
+ } from "./chunk-H4TMS567.js";
105
111
  import {
106
112
  buildUsage,
107
113
  realUsageDeps,
108
114
  setupAgentUsage
109
- } from "./chunk-DHNW25TR.js";
115
+ } from "./chunk-BHJ73OPQ.js";
110
116
  import {
111
117
  sessionWorkTime
112
- } from "./chunk-MESE7KI5.js";
118
+ } from "./chunk-OTKWVUGB.js";
113
119
  import "./chunk-6UTH3A76.js";
114
120
  import {
115
121
  sendToSession
@@ -118,11 +124,11 @@ import {
118
124
  defaultForkDeps,
119
125
  forkSession,
120
126
  startSessionWithPrompt
121
- } from "./chunk-S5YGRCGU.js";
127
+ } from "./chunk-VPFAXLSX.js";
122
128
  import {
123
129
  addRepoRefusal,
124
130
  addedRepoNote
125
- } from "./chunk-JAC6X4XN.js";
131
+ } from "./chunk-5LUXNIPA.js";
126
132
  import {
127
133
  BehindCache,
128
134
  behindMain,
@@ -138,14 +144,14 @@ import {
138
144
  stackedOn,
139
145
  updateFromBase,
140
146
  updateFromMain
141
- } from "./chunk-E4O7OZ5G.js";
147
+ } from "./chunk-OIVEYULL.js";
142
148
  import {
143
149
  askCatchUp,
144
150
  cachedCatchUp,
145
151
  catchUp,
146
152
  catchUpFacts,
147
153
  forgetCatchUp
148
- } from "./chunk-3ZV77FBH.js";
154
+ } from "./chunk-TFNDOWYP.js";
149
155
  import {
150
156
  applyPlacePatch,
151
157
  applySectionOp,
@@ -155,12 +161,6 @@ import {
155
161
  placeSession,
156
162
  readRailLayout
157
163
  } from "./chunk-DGVCN7HB.js";
158
- import {
159
- MAX_NOTE_CHARS,
160
- readNote,
161
- saveNote,
162
- sessionsWithNotes
163
- } from "./chunk-33XSEAHO.js";
164
164
  import {
165
165
  DEFAULT_CATCH_UP_DAYS,
166
166
  addDays,
@@ -185,7 +185,7 @@ import {
185
185
  tempoSetup,
186
186
  timeRange,
187
187
  updateDay
188
- } from "./chunk-VJ5XMYXE.js";
188
+ } from "./chunk-VVRSPS67.js";
189
189
  import {
190
190
  DISCUSSION_OPEN_MIN_MS,
191
191
  LEFT_OVER_SUBMIT,
@@ -208,7 +208,9 @@ import {
208
208
  leftOverToDoubt,
209
209
  linesWorthReading,
210
210
  markStaleClaim,
211
+ parseAgentPass,
211
212
  preparedOn,
213
+ promptPaths,
212
214
  readReview,
213
215
  refusalStatus,
214
216
  removeDraft,
@@ -225,7 +227,7 @@ import {
225
227
  withClaim,
226
228
  withFixClaim,
227
229
  withoutFixClaim
228
- } from "./chunk-YKQLHFY4.js";
230
+ } from "./chunk-IUWMT6PF.js";
229
231
  import {
230
232
  asData,
231
233
  asDataBlock
@@ -241,12 +243,12 @@ import {
241
243
  readWebUrl,
242
244
  writeDevWebDiscovery,
243
245
  writeWebDiscovery
244
- } from "./chunk-RGLIW45S.js";
246
+ } from "./chunk-TMBO55MM.js";
245
247
  import {
246
248
  checkTools,
247
249
  saveFolders,
248
250
  setupState
249
- } from "./chunk-J6T75IWG.js";
251
+ } from "./chunk-UQJQZ526.js";
250
252
  import {
251
253
  RepoAdminError,
252
254
  deleteGroup,
@@ -258,7 +260,7 @@ import {
258
260
  setRepoIgnored,
259
261
  setReviewMode,
260
262
  setScanRoot
261
- } from "./chunk-KMAA4PTG.js";
263
+ } from "./chunk-BW5U6ENJ.js";
262
264
  import {
263
265
  freeLeftovers,
264
266
  leftoversOf,
@@ -267,37 +269,32 @@ import {
267
269
  parsePrRef,
268
270
  resolvePrToStart,
269
271
  workOnPrPrompt
270
- } from "./chunk-UJJDDB6D.js";
272
+ } from "./chunk-JNAYPBAB.js";
271
273
  import {
272
274
  legacyUnsafeCheck
273
- } from "./chunk-7HFSM4SJ.js";
275
+ } from "./chunk-C72Y42VC.js";
274
276
  import {
275
277
  agentsBySession,
276
278
  summarizeAgents
277
- } from "./chunk-FFTMMZM7.js";
279
+ } from "./chunk-IREGW23T.js";
278
280
  import {
279
281
  howToLift
280
282
  } from "./chunk-FZHFD2AY.js";
281
- import {
282
- childText,
283
- createInChild,
284
- createInProcess,
285
- keyedQueue,
286
- oneAtATime,
287
- runWorkChild
288
- } from "./chunk-WH2CGK2A.js";
289
283
  import {
290
284
  resolveWorkBinPath
291
285
  } from "./chunk-AH5TM3NB.js";
292
286
  import {
293
287
  editorArgs,
294
288
  openUrl
295
- } from "./chunk-FVENEUOL.js";
289
+ } from "./chunk-3KVOYBM4.js";
290
+ import {
291
+ removeWorktreeInChild
292
+ } from "./chunk-SQACJQUY.js";
296
293
  import {
297
294
  archiveMergedSession,
298
295
  archiveWaiting,
299
296
  defaultArchiveDeps
300
- } from "./chunk-AZPE2HLY.js";
297
+ } from "./chunk-NUPLJJOS.js";
301
298
  import {
302
299
  cleanupVerdict,
303
300
  createCleanupJob
@@ -317,7 +314,7 @@ import {
317
314
  retireResolvedReplies,
318
315
  sessionRepoRefs,
319
316
  withThreadContext
320
- } from "./chunk-43EUE5L5.js";
317
+ } from "./chunk-5RAAS4II.js";
321
318
  import {
322
319
  DEFAULT_TRUSTED_BOTS,
323
320
  createCiStore,
@@ -327,27 +324,40 @@ import {
327
324
  openThreadsOf,
328
325
  reviewMessage,
329
326
  subAgentHint
330
- } from "./chunk-T5SHUOWM.js";
327
+ } from "./chunk-ANS6OH55.js";
331
328
  import {
332
329
  sessionStatusView,
333
330
  shownState
334
- } from "./chunk-PEGZW3TZ.js";
331
+ } from "./chunk-ACNCTLFO.js";
335
332
  import {
336
333
  internalReadOnly,
337
334
  runInternal,
338
335
  runInternalReadOnly,
339
336
  summarizeCheckpoint,
340
337
  throttleTrailing
341
- } from "./chunk-GKZHWV2R.js";
338
+ } from "./chunk-B2K2I2PQ.js";
342
339
  import {
343
340
  computeDiff,
344
341
  computeRangeDiff,
345
342
  parseGitDiff
346
- } from "./chunk-W6SKLTNO.js";
343
+ } from "./chunk-CVMO75V5.js";
347
344
  import {
345
+ commandWords,
346
+ describeProcess,
347
+ isPtyHelper,
348
348
  listProcesses,
349
- runningFromNames
350
- } from "./chunk-JNBMANFM.js";
349
+ normDir,
350
+ runningFromNames,
351
+ runsFrom
352
+ } from "./chunk-TUDDISCX.js";
353
+ import {
354
+ childText,
355
+ createInChild,
356
+ createInProcess,
357
+ keyedQueue,
358
+ oneAtATime,
359
+ runWorkChild
360
+ } from "./chunk-RPWEOEA3.js";
351
361
  import {
352
362
  configurePtyPool,
353
363
  detachPtyPool,
@@ -371,43 +381,43 @@ import {
371
381
  syncPtyPool,
372
382
  terminalTicketUrl,
373
383
  writeToPty
374
- } from "./chunk-EWTW53YY.js";
375
- import "./chunk-O36SFV5G.js";
384
+ } from "./chunk-ZQJKAZRD.js";
385
+ import "./chunk-7FNJ6A2U.js";
376
386
  import {
377
387
  disposeAllWatchers,
378
388
  disposeSessionWatcher,
379
389
  findSession as findSession2,
380
390
  subscribeSession
381
- } from "./chunk-XEEF2V22.js";
382
- import "./chunk-KJRUC2QY.js";
383
- import "./chunk-BDPRYJL3.js";
391
+ } from "./chunk-3O6QFWZ6.js";
392
+ import "./chunk-DS2CKYQ4.js";
393
+ import "./chunk-EYDGX32Q.js";
384
394
  import {
385
395
  teardownWorktree,
386
396
  toBaseSpec,
387
397
  wouldRefuseRemoval
388
- } from "./chunk-3MXZNRVH.js";
398
+ } from "./chunk-TMAQASMH.js";
389
399
  import "./chunk-JVHHSKBJ.js";
390
400
  import {
391
401
  isWorktreeFolder
392
- } from "./chunk-AHYCZUPI.js";
402
+ } from "./chunk-LSZ6HI3U.js";
393
403
  import {
394
404
  ASSISTANT_ID,
395
405
  assistantDir,
396
406
  describeView,
397
407
  writeAssistantContext
398
- } from "./chunk-ZBNRIPLQ.js";
408
+ } from "./chunk-SPVVXKDV.js";
399
409
  import "./chunk-7E5XPDKX.js";
400
- import "./chunk-IV7YIC55.js";
410
+ import "./chunk-RSCRZGUW.js";
401
411
  import {
402
412
  NOTE_NUDGE,
403
413
  findSessionForCwd,
404
414
  readPendingForSession,
405
415
  readPendingForWorktree
406
- } from "./chunk-4XLB3ARR.js";
407
- import "./chunk-ZSHWP2VS.js";
416
+ } from "./chunk-PGGNMC34.js";
408
417
  import {
409
418
  getCommentFileStore
410
419
  } from "./chunk-7DUGVGUZ.js";
420
+ import "./chunk-ZSHWP2VS.js";
411
421
  import {
412
422
  createCommentStore
413
423
  } from "./chunk-HUXS3VAI.js";
@@ -423,17 +433,17 @@ import {
423
433
  stageInputOf,
424
434
  withRequiredChecks,
425
435
  workElsewhere
426
- } from "./chunk-GT4JUJ76.js";
436
+ } from "./chunk-TL7K3XUY.js";
427
437
  import {
428
438
  createSessionBranches
429
- } from "./chunk-KXNYMDIJ.js";
439
+ } from "./chunk-EJSGPLXO.js";
430
440
  import {
431
441
  defaultHost,
432
442
  hostById,
433
443
  hostForRepo,
434
444
  hostOfPrUrl,
435
445
  originHostname
436
- } from "./chunk-IWK733M6.js";
446
+ } from "./chunk-JVRS73M6.js";
437
447
  import {
438
448
  MAX_THREAD_BODY
439
449
  } from "./chunk-FGPXMAYU.js";
@@ -446,16 +456,16 @@ import {
446
456
  readSessionBranches,
447
457
  repoNameOf,
448
458
  wasPushed
449
- } from "./chunk-V3AS6S7C.js";
459
+ } from "./chunk-64M7W2OQ.js";
450
460
  import {
451
461
  enrollProblem,
452
462
  groupProblem,
453
463
  suggestAlias
454
- } from "./chunk-MQCDFSVF.js";
455
- import "./chunk-I6MILNM5.js";
464
+ } from "./chunk-AGRUEZQX.js";
465
+ import "./chunk-ZIFWZJ7X.js";
456
466
  import {
457
467
  defaultRunner
458
- } from "./chunk-KSVYR4G2.js";
468
+ } from "./chunk-MKQ7IA6U.js";
459
469
  import {
460
470
  DECISION_MARKER,
461
471
  DEFAULT_HOST,
@@ -466,10 +476,10 @@ import {
466
476
  archiveDirFor,
467
477
  archiveRoot,
468
478
  archiveSession,
479
+ archivedForMerge,
469
480
  bestEffort,
470
481
  bestEffortAsync,
471
482
  buildDigest,
472
- checkedOutBranch,
473
483
  cleanSnoozeRequest,
474
484
  cleanStageRef,
475
485
  clearCheckpoints,
@@ -486,7 +496,6 @@ import {
486
496
  findSession,
487
497
  findSessionById,
488
498
  getScope,
489
- gitDirs,
490
499
  headAdvancedSinceInitial,
491
500
  headBroughtInOtherWork,
492
501
  hostName,
@@ -512,7 +521,6 @@ import {
512
521
  readSnooze,
513
522
  readStatus,
514
523
  recordStatusEvent,
515
- refShaFromFiles,
516
524
  registerScope,
517
525
  removeScope,
518
526
  removeSession,
@@ -530,6 +538,7 @@ import {
530
538
  setCheckpointLabel,
531
539
  setSessionArchived,
532
540
  setSessionBase,
541
+ setSessionKeep,
533
542
  setSessionTitle,
534
543
  snoozeActive,
535
544
  snoozeFor,
@@ -547,9 +556,8 @@ import {
547
556
  turnInProgress,
548
557
  updateCheckpoint,
549
558
  whileRestoring,
550
- workingBranch,
551
559
  writeArchiveRecord
552
- } from "./chunk-NXUBAXXP.js";
560
+ } from "./chunk-NOB3VR5I.js";
553
561
  import {
554
562
  dayKey
555
563
  } from "./chunk-NEJVK5CF.js";
@@ -571,25 +579,30 @@ import {
571
579
  agentFor,
572
580
  agentOf,
573
581
  agentWriteMs,
582
+ checkedOutBranch,
583
+ gitDirs,
574
584
  isOwnCheckout,
575
585
  knownAgents,
576
586
  lineTimeOf,
577
587
  liveAgents,
578
- readJsonlSince
579
- } from "./chunk-E3VBI6BJ.js";
588
+ ownsBranch,
589
+ readJsonlSince,
590
+ refShaFromFiles,
591
+ workingBranch
592
+ } from "./chunk-DTFACBDD.js";
580
593
  import {
581
594
  VERSION
582
- } from "./chunk-P6XBAGSF.js";
595
+ } from "./chunk-FC7RECDP.js";
583
596
  import {
584
597
  resolveProjectTarget
585
- } from "./chunk-4K4S53KX.js";
598
+ } from "./chunk-7UXV4X2Y.js";
586
599
  import {
587
600
  git
588
- } from "./chunk-DCCC7LEP.js";
601
+ } from "./chunk-K5EAVRXX.js";
589
602
  import {
590
603
  usageDir
591
604
  } from "./chunk-CBCOVIXZ.js";
592
- import "./chunk-PPZP7CA7.js";
605
+ import "./chunk-BK73QU45.js";
593
606
  import {
594
607
  QUEUE_RECHECK_MS,
595
608
  busyForRestart,
@@ -597,18 +610,18 @@ import {
597
610
  installedAtCache,
598
611
  outdatedPtys,
599
612
  restartNotesSummary
600
- } from "./chunk-ILACZ77E.js";
613
+ } from "./chunk-DZ6SLAIZ.js";
601
614
  import "./chunk-TNJF7T33.js";
602
615
  import {
603
616
  accountLoginId,
604
617
  accountOfLoginId
605
618
  } from "./chunk-SJBEIYLK.js";
606
- import "./chunk-DAKJTB6N.js";
607
- import "./chunk-DMGNJ73M.js";
619
+ import "./chunk-AYHDJMMJ.js";
620
+ import "./chunk-DROLR3NJ.js";
608
621
  import {
609
622
  DEFAULT_ACCOUNT_NAME,
610
623
  accountNameProblem
611
- } from "./chunk-NFWSJFYY.js";
624
+ } from "./chunk-HHXVHUGP.js";
612
625
  import {
613
626
  DEFAULT_ACCOUNT,
614
627
  DEFAULT_PROMPTS,
@@ -616,19 +629,23 @@ import {
616
629
  getConfigPath,
617
630
  isWorkday,
618
631
  loadConfig
619
- } from "./chunk-O5ZJY5BT.js";
632
+ } from "./chunk-INI6TEYT.js";
620
633
  import {
621
634
  bootTime,
622
635
  detachHere,
623
636
  isPidAlive,
637
+ killTreeAsync,
624
638
  recentProcessTable
625
- } from "./chunk-63ZLPXRL.js";
639
+ } from "./chunk-G2V2V5UC.js";
626
640
  import {
627
- explainNotOnPath,
628
- programPath,
629
641
  shellEnv,
630
642
  spawn_default
631
- } from "./chunk-EL3XL2OC.js";
643
+ } from "./chunk-DW245WK4.js";
644
+ import {
645
+ explainNotOnPath,
646
+ programPath,
647
+ takeSlowestSync
648
+ } from "./chunk-ZS7ZXAXB.js";
632
649
  import {
633
650
  atomicWriteFile
634
651
  } from "./chunk-D2J3AD6L.js";
@@ -756,12 +773,12 @@ function mountSessionControlRoutes(app, opts) {
756
773
  // src/core/stacks/stack-sync.ts
757
774
  var busyWhy = (state) => state === "working" ? "its Claude is working" : state === "needs_input" ? "its Claude is waiting for your answer" : null;
758
775
  async function syncStackChild(child, parentBranch, deps) {
759
- const run = deps.run ?? defaultRunner;
776
+ const run2 = deps.run ?? defaultRunner;
760
777
  const busy = busyWhy(deps.shownState(child));
761
778
  if (busy) return { updated: false, why: busy };
762
779
  const behind = [];
763
780
  for (const p of child.paths) {
764
- const b = await behindMain(p, run, parentBranch);
781
+ const b = await behindMain(p, run2, parentBranch);
765
782
  if (b && b.commits > 0) behind.push({ path: p, b });
766
783
  }
767
784
  if (behind.length === 0) return { updated: false, why: `already on top of ${parentBranch}` };
@@ -769,9 +786,9 @@ async function syncStackChild(child, parentBranch, deps) {
769
786
  return { updated: false, why: `bringing in ${parentBranch} would conflict: left for you (Update from ${parentBranch})` };
770
787
  const heads = /* @__PURE__ */ new Map();
771
788
  for (const { path: p } of behind) {
772
- const st = await run("git", ["-C", p, "status", "--porcelain"], p);
789
+ const st = await run2("git", ["-C", p, "status", "--porcelain"], p);
773
790
  if (st.code !== 0 || st.stdout.trim()) return { updated: false, why: "it has uncommitted changes" };
774
- const head = await run("git", ["-C", p, "rev-parse", "HEAD"], p);
791
+ const head = await run2("git", ["-C", p, "rev-parse", "HEAD"], p);
775
792
  if (head.code !== 0) return { updated: false, why: `${p}: ${head.stderr.trim() || "no HEAD"}` };
776
793
  heads.set(p, head.stdout.trim());
777
794
  }
@@ -780,9 +797,9 @@ async function syncStackChild(child, parentBranch, deps) {
780
797
  const done = [];
781
798
  for (const { path: p } of behind) {
782
799
  const nowBusy = busyWhy(deps.shownState(child));
783
- const r = nowBusy ? null : await updateFromMain(p, run, parentBranch);
800
+ const r = nowBusy ? null : await updateFromMain(p, run2, parentBranch);
784
801
  if (!r || !r.ok) {
785
- for (const q of done) await run("git", ["-C", q, "reset", "--hard", "--quiet", heads.get(q)], q);
802
+ for (const q of done) await run2("git", ["-C", q, "reset", "--hard", "--quiet", heads.get(q)], q);
786
803
  return {
787
804
  updated: false,
788
805
  why: nowBusy ?? `${r.repo}: ${r.reason}${done.length ? " (the others were put back)" : ""}`
@@ -804,15 +821,15 @@ async function syncStackChild(child, parentBranch, deps) {
804
821
  return { updated: true, commits, how, told };
805
822
  }
806
823
  async function retargetIfMerged(child, parent, config, deps) {
807
- const run = deps.run ?? defaultRunner;
824
+ const run2 = deps.run ?? defaultRunner;
808
825
  const busy = busyWhy(deps.shownState(child));
809
826
  if (busy) return { updated: false, why: busy };
810
827
  const tips = /* @__PURE__ */ new Map();
811
- for (const p of child.paths) tips.set(p, await parentTipFor(p, parent, config, run));
828
+ for (const p of child.paths) tips.set(p, await parentTipFor(p, parent, config, run2));
812
829
  for (const p of child.paths) {
813
830
  const tip = tips.get(p);
814
831
  if (!tip) return { updated: false, why: `${parent.branch} merged, but its tip is unknown here: Move onto main by hand` };
815
- const blocker = await retargetBlocker(p, { branch: parent.branch, tip }, run);
832
+ const blocker = await retargetBlocker(p, { branch: parent.branch, tip }, run2);
816
833
  if (blocker?.handOff) {
817
834
  const key = `${sessionIdFor(child)}:${tip}`;
818
835
  if (handedOff.has(key))
@@ -824,7 +841,7 @@ async function retargetIfMerged(child, parent, config, deps) {
824
841
  await deps.tell(child, ontoMainPrompt(parent.branch)).catch((err) => logSwallowed(`asking ${child.branch} to move onto main`, err));
825
842
  return { updated: false, why: `${parent.branch} was rewritten before it merged: its Claude was asked to move this branch onto main` };
826
843
  }
827
- if (!await retargetIsClean(p, { branch: parent.branch, tip }, run)) {
844
+ if (!await retargetIsClean(p, { branch: parent.branch, tip }, run2)) {
828
845
  return {
829
846
  updated: false,
830
847
  why: `${parent.branch} merged; moving onto main isn't sure to go cleanly (a conflict, uncommitted changes, a rewritten parent, or an old git): left for you`
@@ -834,7 +851,7 @@ async function retargetIfMerged(child, parent, config, deps) {
834
851
  const r = await retargetOntoMain(
835
852
  child,
836
853
  async (p) => ({ branch: parent.branch, tip: tips.get(p) ?? null }),
837
- run,
854
+ run2,
838
855
  () => busyWhy(deps.shownState(child))
839
856
  );
840
857
  if (!r.ok)
@@ -865,7 +882,7 @@ async function retargetChildrenOf(parentId, deps) {
865
882
  const stacks = sessionStacks(history, config);
866
883
  const children = history.filter((s) => stacks.mergedParentOf.get(sessionIdFor(s))?.id === parentId);
867
884
  if (children.length === 0) return 0;
868
- const run = deps.startRun();
885
+ const run2 = deps.startRun();
869
886
  let moved = 0;
870
887
  for (const child of children) {
871
888
  const id = sessionIdFor(child);
@@ -876,18 +893,18 @@ async function retargetChildrenOf(parentId, deps) {
876
893
  if (r.updated) {
877
894
  moved++;
878
895
  deps.invalidate(id);
879
- run.note(
896
+ run2.note(
880
897
  `${child.branch}: ${r.how} (its parent merged and was archived)${r.told ? "; its Claude was told" : " \u2014 telling its Claude failed"}`,
881
898
  { sessionId: id, ...r.told ? {} : { level: "warn" } }
882
899
  );
883
- } else run.note(`${child.branch}: left as it is \u2014 ${r.why}`, { sessionId: id });
900
+ } else run2.note(`${child.branch}: left as it is \u2014 ${r.why}`, { sessionId: id });
884
901
  } catch (err) {
885
- run.note(`${child.branch}: ${err.message}`, { sessionId: id, level: "warn" });
902
+ run2.note(`${child.branch}: ${err.message}`, { sessionId: id, level: "warn" });
886
903
  } finally {
887
904
  deps.busy.delete(id);
888
905
  }
889
906
  }
890
- run.done(moved ? `${moved} moved onto main` : "none could move by itself");
907
+ run2.done(moved ? `${moved} moved onto main` : "none could move by itself");
891
908
  return moved;
892
909
  }
893
910
  async function syncStacksAfterTurn(sessionId, deps) {
@@ -900,7 +917,7 @@ async function syncStacksAfterTurn(sessionId, deps) {
900
917
  if (candidates2.length === 0 && !merged) return 0;
901
918
  for (const c of candidates2) deps.invalidate(sessionIdFor(c));
902
919
  if (config?.stacks?.autoUpdate === false) return 0;
903
- const run = deps.startRun();
920
+ const run2 = deps.startRun();
904
921
  let updated = 0;
905
922
  if (self && merged && !deps.busy.has(sessionId)) {
906
923
  deps.busy.add(sessionId);
@@ -909,13 +926,13 @@ async function syncStacksAfterTurn(sessionId, deps) {
909
926
  if (r.updated) {
910
927
  updated++;
911
928
  deps.invalidate(sessionId);
912
- run.note(`${self.branch}: ${r.how} (${merged.branch} merged)${r.told ? "; its Claude was told" : " \u2014 telling its Claude failed"}`, {
929
+ run2.note(`${self.branch}: ${r.how} (${merged.branch} merged)${r.told ? "; its Claude was told" : " \u2014 telling its Claude failed"}`, {
913
930
  sessionId,
914
931
  ...r.told ? {} : { level: "warn" }
915
932
  });
916
- } else run.note(`${self.branch}: left as it is \u2014 ${r.why}`, { sessionId });
933
+ } else run2.note(`${self.branch}: left as it is \u2014 ${r.why}`, { sessionId });
917
934
  } catch (err) {
918
- run.note(`${self.branch}: ${err.message}`, { sessionId, level: "warn" });
935
+ run2.note(`${self.branch}: ${err.message}`, { sessionId, level: "warn" });
919
936
  } finally {
920
937
  deps.busy.delete(sessionId);
921
938
  }
@@ -930,20 +947,20 @@ async function syncStacksAfterTurn(sessionId, deps) {
930
947
  if (r.updated) {
931
948
  updated++;
932
949
  deps.invalidate(childId);
933
- run.note(
950
+ run2.note(
934
951
  `${child.branch}: ${r.commits} commit${r.commits === 1 ? "" : "s"} from ${parent.branch} (${r.how})${r.told ? "; its Claude was told" : "; telling its Claude failed \u2014 it doesn't know yet"}`,
935
952
  { sessionId: childId, ...r.told ? {} : { level: "warn" } }
936
953
  );
937
954
  } else {
938
- run.note(`${child.branch}: left as it is \u2014 ${r.why}`, { sessionId: childId });
955
+ run2.note(`${child.branch}: left as it is \u2014 ${r.why}`, { sessionId: childId });
939
956
  }
940
957
  } catch (err) {
941
- run.note(`${child.branch}: ${err.message}`, { sessionId: childId, level: "warn" });
958
+ run2.note(`${child.branch}: ${err.message}`, { sessionId: childId, level: "warn" });
942
959
  } finally {
943
960
  deps.busy.delete(childId);
944
961
  }
945
962
  }
946
- run.done(updated ? `${updated} brought up to date` : "nothing to bring in");
963
+ run2.done(updated ? `${updated} brought up to date` : "nothing to bring in");
947
964
  return updated;
948
965
  }
949
966
 
@@ -1165,18 +1182,424 @@ function mountNoteRoutes(app, opts) {
1165
1182
  });
1166
1183
  }
1167
1184
 
1185
+ // src/core/sessions/process-view.ts
1186
+ var LEFTOVER_AFTER_MS = 24 * 36e5;
1187
+ function formatBytes(bytes) {
1188
+ const mb = bytes / (1024 * 1024);
1189
+ return mb >= 1024 ? `${(mb / 1024).toFixed(1)} GB` : `${Math.round(mb)} MB`;
1190
+ }
1191
+
1192
+ // src/core/sessions/process-stop.ts
1193
+ function stopRefusal(now, pid, startedAt) {
1194
+ const p = now.processes.find((x) => x.pid === pid);
1195
+ if (!p) return "it is no longer running for this session";
1196
+ if (p.agent) return "that is its agent: stop it from the session instead";
1197
+ if (p.startedAt === null || startedAt === null || Math.abs(p.startedAt - startedAt) > 2e3)
1198
+ return "the process under that number is not the one that was listed";
1199
+ return null;
1200
+ }
1201
+
1202
+ // src/core/sessions/session-processes.ts
1203
+ function descendantsOf(procs, roots) {
1204
+ const children = /* @__PURE__ */ new Map();
1205
+ for (const p of procs) children.set(p.ppid, [...children.get(p.ppid) ?? [], p.pid]);
1206
+ const out = /* @__PURE__ */ new Set();
1207
+ const todo = [...roots].filter((r) => procs.some((p) => p.pid === r));
1208
+ while (todo.length) {
1209
+ const pid = todo.pop();
1210
+ if (out.has(pid)) continue;
1211
+ out.add(pid);
1212
+ todo.push(...children.get(pid) ?? []);
1213
+ }
1214
+ return out;
1215
+ }
1216
+ function sessionProcesses(procs, opts) {
1217
+ const windows = opts.windows ?? process.platform === "win32";
1218
+ const byPid = new Map(procs.map((p) => [p.pid, p]));
1219
+ const real = procs.map((p) => {
1220
+ const parent = byPid.get(p.ppid);
1221
+ const stale = parent && p.startedAt !== null && parent.startedAt !== null && parent.startedAt > p.startedAt + 1e3;
1222
+ return stale ? { ...p, ppid: 0 } : p;
1223
+ });
1224
+ const tree = descendantsOf(real, opts.agentPids);
1225
+ const dirs = opts.dirs.map((d) => normDir(d, windows));
1226
+ const mine = real.filter((p) => !isPtyHelper(p) && (tree.has(p.pid) || dirs.length > 0 && runsFrom(p, dirs, windows)));
1227
+ const rows = mine.map((p) => {
1228
+ const agent = opts.agentPids.has(p.pid);
1229
+ const ageMs = p.startedAt === null ? null : Math.max(0, opts.now - p.startedAt);
1230
+ return {
1231
+ pid: p.pid,
1232
+ // Its name and command with the session's folder shortened, without the pid (it has its own field).
1233
+ what: describeProcess(p, dirs, windows).replace(/ \(PID \d+\)$/, ""),
1234
+ memBytes: p.memBytes,
1235
+ startedAt: p.startedAt,
1236
+ ...agent ? { agent: true } : {},
1237
+ ...!agent && ageMs !== null && ageMs >= LEFTOVER_AFTER_MS ? { leftover: true } : {}
1238
+ };
1239
+ }).sort((a, b) => (b.memBytes ?? 0) - (a.memBytes ?? 0) || a.pid - b.pid);
1240
+ return {
1241
+ at: opts.now,
1242
+ totalBytes: rows.reduce((n, r) => n + (r.memBytes ?? 0), 0),
1243
+ leftovers: rows.filter((r) => r.leftover).length,
1244
+ processes: rows
1245
+ };
1246
+ }
1247
+
1248
+ // src/server/routes/session-process-routes.ts
1249
+ var LIST_FOR_MS = 3e3;
1250
+ function mountSessionProcessRoutes(app, deps) {
1251
+ const now = deps.now ?? Date.now;
1252
+ let kept = null;
1253
+ const listed = (fresh = false) => {
1254
+ if (fresh || !kept || now() - kept.at >= LIST_FOR_MS) kept = { at: now(), list: deps.list() };
1255
+ return kept.list;
1256
+ };
1257
+ const of = async (id, fresh = false) => {
1258
+ const session = findSession2(id);
1259
+ if (!session) return "unknown";
1260
+ const procs = await listed(fresh);
1261
+ if (procs.length === 0) return "unreadable";
1262
+ const pid = deps.agentPid(id);
1263
+ return sessionProcesses(procs, { agentPids: new Set(pid ? [pid] : []), dirs: session.paths, now: now() });
1264
+ };
1265
+ app.get("/api/sessions/:id/processes", async (c) => {
1266
+ const r = await of(c.req.param("id"));
1267
+ if (r === "unknown") return c.json({ error: "unknown session" }, 404);
1268
+ if (r === "unreadable") return c.json({ error: "couldn't read the running processes" }, 502);
1269
+ return c.json(r);
1270
+ });
1271
+ app.post("/api/sessions/:id/processes/stop", async (c) => {
1272
+ const id = c.req.param("id");
1273
+ const body = await c.req.json().catch(() => null);
1274
+ if (typeof body?.pid !== "number" || !Number.isInteger(body.pid) || body.pid <= 0)
1275
+ return c.json({ error: "expected {pid, startedAt}" }, 400);
1276
+ const r = await of(id, true);
1277
+ if (r === "unknown") return c.json({ error: "unknown session" }, 404);
1278
+ if (r === "unreadable") return c.json({ error: "couldn't read the running processes" }, 502);
1279
+ const why = stopRefusal(r, body.pid, typeof body.startedAt === "number" ? body.startedAt : null);
1280
+ if (why) return c.json({ error: `Not stopped: ${why}.` }, 409);
1281
+ if (!await deps.kill(body.pid)) return c.json({ error: "Couldn't stop it." }, 500);
1282
+ const after = await of(id, true);
1283
+ return c.json(typeof after === "string" ? { ...r, processes: r.processes.filter((p) => p.pid !== body.pid) } : after);
1284
+ });
1285
+ }
1286
+
1287
+ // src/core/review/local-review.ts
1288
+ import crypto from "crypto";
1289
+ function diffSignature(files) {
1290
+ const h = crypto.createHash("sha1");
1291
+ for (const f of files) {
1292
+ h.update(`${f.path}\0${f.status}\0${f.added}\0${f.deleted}\0`);
1293
+ for (const hunk2 of f.hunks) for (const l of hunk2.lines) h.update(`${l.kind[0]}${l.content}
1294
+ `);
1295
+ }
1296
+ return h.digest("hex").slice(0, 16);
1297
+ }
1298
+ function localMeta(session, repo, base, signature) {
1299
+ return {
1300
+ repo,
1301
+ number: 0,
1302
+ title: session.title ? `${session.title} (local changes on ${session.branch})` : `Local changes on ${session.branch}`,
1303
+ url: "",
1304
+ author: "you",
1305
+ branch: session.branch,
1306
+ base,
1307
+ headSha: signature
1308
+ };
1309
+ }
1310
+ var REPOS_JOIN = " + ";
1311
+ function inRepo(name, f) {
1312
+ const at = (p) => p === "/dev/null" ? p : `${name}/${p}`;
1313
+ return { ...f, path: at(f.path), oldPath: at(f.oldPath), newPath: at(f.newPath) };
1314
+ }
1315
+ function focusLines(name) {
1316
+ return [
1317
+ `These changes span several repos; each path starts with its repo's name. This pass is about the repo "${name}" alone: another pass writes the stories and reads the other repos.`,
1318
+ `Read every file under "${name}/" closely and add review notes on those files only. The other repos' files are context: use them to answer what "${name}" depends on (an endpoint it calls, a setting or a header the other side sends), and write no note asking what they already show.`,
1319
+ 'Answer with "stories": [], "flows": [], "fileSummaries": {} and "asserts": {} left empty, and no "recommendation": only "notes" is read from this pass.'
1320
+ ];
1321
+ }
1322
+ var SAME_PLACE = 3;
1323
+ function withFocusNotes(main, passes, paths) {
1324
+ if (!main) return null;
1325
+ const start = main.indexOf("{");
1326
+ const end = main.lastIndexOf("}");
1327
+ let raw;
1328
+ try {
1329
+ raw = JSON.parse(main.slice(start, end + 1));
1330
+ } catch {
1331
+ return main;
1332
+ }
1333
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return main;
1334
+ const o = raw;
1335
+ const notes = Array.isArray(o.notes) ? [...o.notes] : [];
1336
+ const taken = (p, line) => notes.some((n) => {
1337
+ const x = n ?? {};
1338
+ return x.path === p && typeof x.line === "number" && Math.abs(x.line - line) <= SAME_PLACE;
1339
+ });
1340
+ let added = 0;
1341
+ for (const pass of passes) {
1342
+ for (const n of parseAgentPass(pass.answer, [...paths])?.notes ?? []) {
1343
+ if (!n.path.startsWith(`${pass.repo}/`) || taken(n.path, n.line)) continue;
1344
+ notes.push(n);
1345
+ added++;
1346
+ }
1347
+ }
1348
+ return added ? JSON.stringify({ ...o, notes }) : main;
1349
+ }
1350
+ async function prepareLocalReview(session, repo, deps) {
1351
+ const diff = deps.diff(session);
1352
+ const changed = diff.repos.filter((r) => r.files.length > 0);
1353
+ const repos = changed.map((r) => r.name);
1354
+ if (repo !== void 0 && !diff.repos.some((r) => r.name === repo)) throw new Error(`${repo} is not one of this session's repos`);
1355
+ const picked = repo === void 0 ? changed : changed.filter((r) => r.name === repo);
1356
+ if (picked.length === 0)
1357
+ throw new Error(
1358
+ repo ? `Nothing has changed in ${repo} since ${diff.resolvedBase}.` : `Nothing has changed on this branch since ${diff.resolvedBase}.`
1359
+ );
1360
+ const together = picked.length > 1;
1361
+ const all = together ? picked.flatMap((r) => r.files.map((f) => inRepo(r.name, f))) : picked[0].files;
1362
+ const { files, ignored } = splitIgnored(all);
1363
+ const extras = { whitespaceOnly: /* @__PURE__ */ new Set(), generated: /* @__PURE__ */ new Set() };
1364
+ const rules = deps.rules?.();
1365
+ const meta = localMeta(session, picked.map((r) => r.name).join(REPOS_JOIN), diff.resolvedBase, diffSignature(all));
1366
+ const kinds = kindsOf(files, extras, rules);
1367
+ const agent = deps.agent;
1368
+ const prompt = agent ? reviewPrompt(meta, files, kinds) : null;
1369
+ const ask = (p) => p && agent ? agent(p).catch(() => null) : Promise.resolve(null);
1370
+ const asked = promptPaths(kinds);
1371
+ const focused = together && prompt ? picked.map((r) => r.name).filter((name) => asked.some((p) => p.startsWith(`${name}/`))) : [];
1372
+ const [main, ...passes] = prompt && agent ? await Promise.all([
1373
+ ask(prompt),
1374
+ ...focused.map(
1375
+ (name) => ask(reviewPrompt(meta, files, kinds, { focus: focusLines(name), first: (p) => p.startsWith(`${name}/`) }))
1376
+ )
1377
+ ]) : [void 0];
1378
+ const answer = main === void 0 ? void 0 : withFocusNotes(
1379
+ main,
1380
+ focused.map((name, i) => ({ repo: name, answer: passes[i] ?? null })),
1381
+ asked
1382
+ );
1383
+ const review = buildReview(meta, files, extras, answer, {
1384
+ ...rules ? { rules } : {},
1385
+ ...deps.now ? { now: deps.now() } : {},
1386
+ ...deps.agent ? {} : { notAskedWhy: "no agent for the AI step: stories are by folder" },
1387
+ ignored
1388
+ });
1389
+ return { review, repo: together ? null : picked[0].name, files, repos };
1390
+ }
1391
+ function createLocalReviews(deps) {
1392
+ const kept = /* @__PURE__ */ new Map();
1393
+ const now = () => (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
1394
+ const wire = (k) => !k ? { status: "none", repo: null, repos: [] } : {
1395
+ status: k.status,
1396
+ repo: k.repo,
1397
+ repos: k.repos,
1398
+ at: k.at,
1399
+ ...k.prepared ? { review: k.prepared.review } : {},
1400
+ ...k.error ? { error: k.error } : {}
1401
+ };
1402
+ return {
1403
+ state: (sessionId) => wire(kept.get(sessionId)),
1404
+ /** The diff the kept review was made of; null when none is ready. */
1405
+ files: (sessionId) => kept.get(sessionId)?.prepared?.files ?? null,
1406
+ start(sessionId, session, repo) {
1407
+ const was = kept.get(sessionId);
1408
+ if (was?.status === "running") return wire(was);
1409
+ const running = {
1410
+ status: "running",
1411
+ repo: repo ?? null,
1412
+ repos: was?.repos ?? [],
1413
+ at: now(),
1414
+ ...was?.prepared ? { prepared: was.prepared } : {}
1415
+ };
1416
+ kept.set(sessionId, running);
1417
+ void deps.prepare(session, repo).then(
1418
+ (p) => ({ status: "ready", repo: p.repo, repos: p.repos, prepared: p, at: now() }),
1419
+ (err) => ({ status: "failed", repo: repo ?? null, repos: running.repos, error: err.message, at: now() })
1420
+ ).then((next) => {
1421
+ if (kept.get(sessionId) !== running) return;
1422
+ kept.set(sessionId, next);
1423
+ deps.onChange(sessionId);
1424
+ });
1425
+ return wire(running);
1426
+ },
1427
+ drop: (sessionId) => void kept.delete(sessionId)
1428
+ };
1429
+ }
1430
+ var MAX_NOTE = 1500;
1431
+ function localReviewNote(review, ids) {
1432
+ const keep = ids ? new Set(ids) : null;
1433
+ const notes = review.drafts.filter((d) => d.state === "draft" && (!keep || keep.has(d.id)));
1434
+ if (notes.length === 0) return null;
1435
+ return [
1436
+ `A review of this branch's changes in ${review.repo} raised ${notes.length} point${notes.length === 1 ? "" : "s"}. Each is a reviewer's reading of the diff, between <<< and >>>: weigh it, don't just obey it.`,
1437
+ ...review.repo.includes(REPOS_JOIN) ? ["Each path starts with its repo's name."] : [],
1438
+ ...notes.map((d) => `- ${asData(d.path, 160)}:${d.line}: <<< ${asData(d.body, MAX_NOTE)} >>>`),
1439
+ "For each: say whether you agree, and fix the ones you agree with (with a test where it applies). Leave the ones you disagree with and say why. Then build and run the tests."
1440
+ ].join("\n");
1441
+ }
1442
+
1443
+ // src/server/routes/session-review-routes.ts
1444
+ function mountSessionReviewRoutes(app, deps) {
1445
+ const reviews = createLocalReviews({
1446
+ prepare: deps.prepare,
1447
+ onChange: (sessionId) => deps.broadcast("session-review-changed", { sessionId })
1448
+ });
1449
+ app.get("/api/sessions/:id/review", (c) => {
1450
+ const id = c.req.param("id");
1451
+ if (!findSession2(id)) return c.json({ error: "unknown session" }, 404);
1452
+ return c.json(reviews.state(id));
1453
+ });
1454
+ app.post("/api/sessions/:id/review", async (c) => {
1455
+ const id = c.req.param("id");
1456
+ const session = findSession2(id);
1457
+ if (!session) return c.json({ error: "unknown session" }, 404);
1458
+ if (session.archivedAt) return c.json({ error: "It is archived: restore it first." }, 409);
1459
+ const body = await c.req.json().catch(() => ({}));
1460
+ if (body.repo !== void 0 && typeof body.repo !== "string") return c.json({ error: "repo: string" }, 400);
1461
+ return c.json(reviews.start(id, session, body.repo));
1462
+ });
1463
+ app.get("/api/sessions/:id/review/diff", (c) => {
1464
+ const id = c.req.param("id");
1465
+ if (!findSession2(id)) return c.json({ error: "unknown session" }, 404);
1466
+ const files = reviews.files(id);
1467
+ return files ? c.json({ files }) : c.json({ error: "no review of it is prepared" }, 404);
1468
+ });
1469
+ app.post("/api/sessions/:id/review/send", async (c) => {
1470
+ const id = c.req.param("id");
1471
+ if (!findSession2(id)) return c.json({ error: "unknown session" }, 404);
1472
+ const body = await c.req.json().catch(() => ({}));
1473
+ const ids = body.ids === void 0 ? void 0 : Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === "string") : null;
1474
+ if (ids === null) return c.json({ error: "ids: string[]" }, 400);
1475
+ const review = reviews.state(id).review;
1476
+ if (!review) return c.json({ error: "no review of it is prepared" }, 409);
1477
+ const note = localReviewNote(review, ids);
1478
+ if (!note) return c.json({ error: "It has no notes to hand over." }, 409);
1479
+ try {
1480
+ await deps.tell(id, note);
1481
+ } catch (err) {
1482
+ return c.json({ error: err.message }, 502);
1483
+ }
1484
+ return c.json({
1485
+ ok: true,
1486
+ sent: ids ? ids.filter((x) => review.drafts.some((d) => d.id === x && d.state === "draft")).length : review.drafts.filter((d) => d.state === "draft").length
1487
+ });
1488
+ });
1489
+ return { drop: reviews.drop };
1490
+ }
1491
+
1492
+ // src/core/platform/process-usage.ts
1493
+ import { execFile } from "child_process";
1494
+ import path2 from "path";
1495
+ var num = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null;
1496
+ function parseCimUsage(json2) {
1497
+ let data;
1498
+ try {
1499
+ data = JSON.parse(json2);
1500
+ } catch {
1501
+ return [];
1502
+ }
1503
+ const rows = Array.isArray(data) ? data : data ? [data] : [];
1504
+ const out = [];
1505
+ for (const r of rows) {
1506
+ if (!r || typeof r !== "object") continue;
1507
+ const o = r;
1508
+ if (typeof o.ProcessId !== "number") continue;
1509
+ const started = num(o.Started);
1510
+ out.push({
1511
+ pid: o.ProcessId,
1512
+ ppid: typeof o.ParentProcessId === "number" ? o.ParentProcessId : 0,
1513
+ name: typeof o.Name === "string" ? o.Name : "",
1514
+ exe: typeof o.ExecutablePath === "string" ? o.ExecutablePath : null,
1515
+ command: typeof o.CommandLine === "string" ? o.CommandLine : "",
1516
+ memBytes: num(o.PrivatePageCount),
1517
+ // 0: a system process with no creation date.
1518
+ startedAt: started ? started : null
1519
+ });
1520
+ }
1521
+ return out;
1522
+ }
1523
+ function elapsedMs(etime) {
1524
+ const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(etime.trim());
1525
+ if (!m) return null;
1526
+ const [days, hours, mins, secs] = [m[1], m[2], m[3], m[4]].map((x) => Number(x ?? 0));
1527
+ return (((days * 24 + hours) * 60 + mins) * 60 + secs) * 1e3;
1528
+ }
1529
+ function parsePsUsage(stdout, now) {
1530
+ const out = [];
1531
+ for (const line of stdout.split(/\r?\n/)) {
1532
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
1533
+ if (!m) continue;
1534
+ const command = m[5].trim();
1535
+ const first = commandWords(command)[0] ?? "";
1536
+ const elapsed = elapsedMs(m[4]);
1537
+ out.push({
1538
+ pid: Number(m[1]),
1539
+ ppid: Number(m[2]),
1540
+ name: path2.posix.basename(first),
1541
+ exe: first.startsWith("/") ? first : null,
1542
+ command,
1543
+ memBytes: Number(m[3]) * 1024,
1544
+ startedAt: elapsed === null ? null : now - elapsed
1545
+ });
1546
+ }
1547
+ return out;
1548
+ }
1549
+ var run = (cmd, args) => new Promise(
1550
+ (resolve) => execFile(
1551
+ programPath(cmd),
1552
+ args,
1553
+ { encoding: "utf-8", windowsHide: true, timeout: 2e4, maxBuffer: 64 * 1024 * 1024 },
1554
+ (_err, stdout) => resolve(stdout ?? "")
1555
+ )
1556
+ );
1557
+ var CIM_USAGE = "[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine,PrivatePageCount,@{n='Started';e={ if ($_.CreationDate) { ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() } else { 0 } }} | ConvertTo-Json -Compress";
1558
+ async function listProcessUsage(now = Date.now()) {
1559
+ if (process.platform === "win32") return parseCimUsage(await run("powershell", ["-NoProfile", "-NonInteractive", "-Command", CIM_USAGE]));
1560
+ return parsePsUsage(await run("ps", ["-A", "-o", "pid=,ppid=,rss=,etime=,args="]), now);
1561
+ }
1562
+
1563
+ // src/core/sessions/leftover-sweep.ts
1564
+ async function sweepLeftovers(deps) {
1565
+ const procs = await deps.list();
1566
+ if (procs.length === 0) return null;
1567
+ const now = (deps.now ?? Date.now)();
1568
+ const found = { sessions: 0, processes: 0, bytes: 0 };
1569
+ for (const s of deps.sessions()) {
1570
+ const pid = deps.agentPid(s.id);
1571
+ const left = sessionProcesses(procs, { agentPids: new Set(pid ? [pid] : []), dirs: s.paths, now }).processes.filter((p) => p.leftover);
1572
+ if (left.length === 0) continue;
1573
+ const bytes = left.reduce((n, p) => n + (p.memBytes ?? 0), 0);
1574
+ found.sessions++;
1575
+ found.processes += left.length;
1576
+ found.bytes += bytes;
1577
+ const names = left.slice(0, 2).map((p) => p.what);
1578
+ deps.note(
1579
+ `${s.name}: ${left.length} process${left.length === 1 ? "" : "es"} left running for over a day (${formatBytes(bytes)}): ${names.join("; ")}${left.length > 2 ? ` and ${left.length - 2} more` : ""} \u2014 its \u22EF menu \u2192 Processes\u2026 stops them`,
1580
+ { level: "warn", sessionId: s.id }
1581
+ );
1582
+ }
1583
+ return found;
1584
+ }
1585
+ function leftoverSummary(found) {
1586
+ if (!found) return "couldn't read the running processes";
1587
+ if (found.processes === 0) return "nothing left running for over a day";
1588
+ return `${found.processes} process${found.processes === 1 ? "" : "es"} left running for over a day in ${found.sessions} session${found.sessions === 1 ? "" : "s"} (${formatBytes(found.bytes)})`;
1589
+ }
1590
+
1168
1591
  // src/core/worktree/code-browse.ts
1169
1592
  import fs3 from "fs";
1170
- import path2 from "path";
1593
+ import path3 from "path";
1171
1594
  var MAX_CODE_FILES = 5e4;
1172
1595
  var MAX_CODE_FILE_BYTES = 2 * 1024 * 1024;
1173
1596
  var LIST_TTL_MS = 3e3;
1174
1597
  function codeRoots(s) {
1175
- return s.paths.map((p) => ({ name: path2.basename(p), root: p }));
1598
+ return s.paths.map((p) => ({ name: path3.basename(p), root: p }));
1176
1599
  }
1177
1600
  function groupRoot(s) {
1178
1601
  if (!s.isGroup || s.paths.length === 0) return null;
1179
- const parents = [...new Set(s.paths.map((p) => path2.dirname(p)))];
1602
+ const parents = [...new Set(s.paths.map((p) => path3.dirname(p)))];
1180
1603
  return parents.length === 1 ? parents[0] : null;
1181
1604
  }
1182
1605
  var realIo = {
@@ -1285,11 +1708,11 @@ async function codeFilePath(s, repo, rel, io = realIo) {
1285
1708
  if (!root) return { error: "unknown repo" };
1286
1709
  if (!allowed) return { error: "not listed" };
1287
1710
  try {
1288
- const full = path2.resolve(root, rel);
1711
+ const full = path3.resolve(root, rel);
1289
1712
  const realRoot = fs3.realpathSync.native(root);
1290
1713
  const real = fs3.realpathSync.native(full);
1291
- const inside2 = path2.relative(realRoot, real);
1292
- if (!inside2 || inside2.startsWith("..") || path2.isAbsolute(inside2)) return { error: "not listed" };
1714
+ const inside2 = path3.relative(realRoot, real);
1715
+ if (!inside2 || inside2.startsWith("..") || path3.isAbsolute(inside2)) return { error: "not listed" };
1293
1716
  const st = fs3.statSync(real);
1294
1717
  if (!st.isFile()) return { error: "unreadable" };
1295
1718
  return { real, size: st.size };
@@ -1383,9 +1806,9 @@ var NOT_NAMES = /* @__PURE__ */ new Set([
1383
1806
  "typeof",
1384
1807
  "await"
1385
1808
  ]);
1386
- function declarationOf(path20, text) {
1809
+ function declarationOf(path21, text) {
1387
1810
  for (const r of RULES) {
1388
- if (!r.ext.test(path20)) continue;
1811
+ if (!r.ext.test(path21)) continue;
1389
1812
  const m = r.re.exec(text);
1390
1813
  if (!m) continue;
1391
1814
  const name = r.name(m);
@@ -1743,7 +2166,7 @@ function mountSetupRoutes(app, opts) {
1743
2166
 
1744
2167
  // src/core/updates/update-source.ts
1745
2168
  import fs4 from "fs";
1746
- import path3 from "path";
2169
+ import path4 from "path";
1747
2170
 
1748
2171
  // src/core/updates/updates.ts
1749
2172
  function parseVersion(v) {
@@ -1828,9 +2251,9 @@ function parseDesktopUpdate(text) {
1828
2251
  var RELEASES_REPO = "moberghr/cli-work-tree-manager";
1829
2252
  var RELEASES_URL = `https://api.github.com/repos/${RELEASES_REPO}/releases?per_page=30`;
1830
2253
  var SEEN_KEY = "ui:seen-version";
1831
- var desktopUpdatePath = () => path3.join(getConfigDir(), "desktop-update.json");
1832
- var desktopRequestPath = () => path3.join(getConfigDir(), "desktop-request.json");
1833
- async function fetchReleases(get = (url) => fetch(url, { headers: { "User-Agent": "work", Accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(15e3) }), run = defaultRunner) {
2254
+ var desktopUpdatePath = () => path4.join(getConfigDir(), "desktop-update.json");
2255
+ var desktopRequestPath = () => path4.join(getConfigDir(), "desktop-request.json");
2256
+ async function fetchReleases(get = (url) => fetch(url, { headers: { "User-Agent": "work", Accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(15e3) }), run2 = defaultRunner) {
1834
2257
  const why = await get(RELEASES_URL).then(
1835
2258
  async (res) => res.ok ? parseReleases(await res.json()) : res.status === 403 ? "GitHub's limit for this address is spent" : `GitHub answered ${res.status}`,
1836
2259
  (err) => err
@@ -1839,7 +2262,7 @@ async function fetchReleases(get = (url) => fetch(url, { headers: { "User-Agent"
1839
2262
  const offline = networkFailure(why);
1840
2263
  if (offline) throw new Error(offline);
1841
2264
  } else if (typeof why !== "string") return why;
1842
- const r = await run("gh", ["api", `repos/${RELEASES_REPO}/releases?per_page=30`], process.cwd());
2265
+ const r = await run2("gh", ["api", `repos/${RELEASES_REPO}/releases?per_page=30`], process.cwd());
1843
2266
  if (r.code === 0) {
1844
2267
  try {
1845
2268
  return parseReleases(JSON.parse(r.stdout));
@@ -1891,7 +2314,7 @@ function markSeenVersion(version) {
1891
2314
  }
1892
2315
  function installKind() {
1893
2316
  const root = packageRoot();
1894
- return installKindOf(root, getConfigDir(), !!root && fs4.existsSync(path3.join(root, ".git")));
2317
+ return installKindOf(root, getConfigDir(), !!root && fs4.existsSync(path4.join(root, ".git")));
1895
2318
  }
1896
2319
  var defaultDeps = () => ({
1897
2320
  fetchReleases: () => fetchReleases(),
@@ -1942,12 +2365,12 @@ function createUpdates(deps = defaultDeps()) {
1942
2365
  checkedAt: () => checkedAt
1943
2366
  };
1944
2367
  }
1945
- async function lookForUpdates(updates, run, changed) {
2368
+ async function lookForUpdates(updates, run2, changed) {
1946
2369
  const before = updates.wire().latest;
1947
2370
  await updates.refresh();
1948
2371
  const w = updates.wire();
1949
- if (w.checkError) run.fail(w.checkError);
1950
- else run.done(w.available ? `work ${w.available.version} is out (this is ${w.running})` : `up to date (${w.running})`);
2372
+ if (w.checkError) run2.fail(w.checkError);
2373
+ else run2.done(w.available ? `work ${w.available.version} is out (this is ${w.running})` : `up to date (${w.running})`);
1951
2374
  if (w.latest !== before) changed();
1952
2375
  }
1953
2376
 
@@ -2086,7 +2509,7 @@ function mountRepoRoutes(app, opts) {
2086
2509
  const regenerate = (name) => {
2087
2510
  const bin = opts.workBin?.();
2088
2511
  if (!bin) return;
2089
- const run = opts.activity?.start("groups", `Writing ${name}'s combined instructions`);
2512
+ const run2 = opts.activity?.start("groups", `Writing ${name}'s combined instructions`);
2090
2513
  const child = spawn_default(
2091
2514
  process.execPath,
2092
2515
  [...process.execArgv.filter((f) => !/^--inspect/.test(f)), bin, "config", "group", "regen", name],
@@ -2096,8 +2519,8 @@ function mountRepoRoutes(app, opts) {
2096
2519
  env: { ...process.env, NO_COLOR: "1" }
2097
2520
  }
2098
2521
  );
2099
- child.on("error", (e) => run?.fail(e.message));
2100
- child.on("close", (code) => code === 0 ? run?.done("written") : run?.fail(`work config group regen exited ${code}`));
2522
+ child.on("error", (e) => run2?.fail(e.message));
2523
+ child.on("close", (code) => code === 0 ? run2?.done("written") : run2?.fail(`work config group regen exited ${code}`));
2101
2524
  };
2102
2525
  app.get("/api/repos", (c) => {
2103
2526
  try {
@@ -2156,8 +2579,8 @@ var SETTING_PATTERNS = {
2156
2579
  agentId: "^[\\w.-]+$",
2157
2580
  envName: "^[A-Za-z_][A-Za-z0-9_]*$"
2158
2581
  };
2159
- var bool = (path20, section, label, help, def, when) => ({
2160
- path: path20,
2582
+ var bool = (path21, section, label, help, def, when) => ({
2583
+ path: path21,
2161
2584
  section,
2162
2585
  label,
2163
2586
  help,
@@ -2270,6 +2693,14 @@ var SETTINGS = [
2270
2693
  false,
2271
2694
  "at the next terminal start"
2272
2695
  ),
2696
+ bool(
2697
+ "agentsLowPriority",
2698
+ "Agents & terminals",
2699
+ "Run agents below normal priority",
2700
+ "What an agent runs (builds, tests) uses the cores nothing else wants and gives way to what you look at. Try it if the computer freezes while sessions build.",
2701
+ false,
2702
+ "at the next agent start (a running one: restart it)"
2703
+ ),
2273
2704
  // ---- Pull requests
2274
2705
  bool(
2275
2706
  "prWatch.autoArchive",
@@ -2515,7 +2946,7 @@ var SETTINGS = [
2515
2946
  "at the next work web start"
2516
2947
  )
2517
2948
  ];
2518
- var settingAt = (path20) => SETTINGS.find((f) => f.path === path20);
2949
+ var settingAt = (path21) => SETTINGS.find((f) => f.path === path21);
2519
2950
  function checkSetting(field, raw) {
2520
2951
  const checked = checkValue(field, raw);
2521
2952
  if (checked.ok && checked.value === null && field.required) return { ok: false, error: "it can\u2019t be left empty" };
@@ -2561,16 +2992,16 @@ function checkValue(field, raw) {
2561
2992
  return typeof raw === "string" && k.options.some((o) => o.value === raw) ? { ok: true, value: raw } : { ok: false, error: `one of ${k.options.map((o) => o.value).join(", ")}` };
2562
2993
  }
2563
2994
  }
2564
- function valueAt(obj, path20) {
2995
+ function valueAt(obj, path21) {
2565
2996
  let cur = obj;
2566
- for (const key of path20.split(".")) {
2997
+ for (const key of path21.split(".")) {
2567
2998
  if (!cur || typeof cur !== "object" || Array.isArray(cur)) return void 0;
2568
2999
  cur = cur[key];
2569
3000
  }
2570
3001
  return cur;
2571
3002
  }
2572
- function setValueAt(obj, path20, value) {
2573
- const keys = path20.split(".");
3003
+ function setValueAt(obj, path21, value) {
3004
+ const keys = path21.split(".");
2574
3005
  const chain = [obj];
2575
3006
  let cur = obj;
2576
3007
  for (const key of keys.slice(0, -1)) {
@@ -2607,8 +3038,8 @@ function checkRepoSetting(key, raw) {
2607
3038
  return raw === "all" || raw === "asked" || raw === "off" ? { ok: true, value: raw } : { ok: false, error: "all, asked or off" };
2608
3039
  }
2609
3040
  function repoSettingsOf(raw, alias) {
2610
- const map = (path20) => {
2611
- const m = valueAt(raw, path20);
3041
+ const map = (path21) => {
3042
+ const m = valueAt(raw, path21);
2612
3043
  return m && typeof m === "object" && !Array.isArray(m) ? m : {};
2613
3044
  };
2614
3045
  const checks = map(REPO_SETTING_PATH.requiredChecks)[alias];
@@ -2664,7 +3095,7 @@ function mountSettingsRoutes(app, opts) {
2664
3095
 
2665
3096
  // src/core/settings/settings-admin.ts
2666
3097
  import fs6 from "fs";
2667
- import path4 from "path";
3098
+ import path5 from "path";
2668
3099
  function rawConfig(file = getConfigPath()) {
2669
3100
  try {
2670
3101
  const raw = JSON.parse(fs6.readFileSync(file, "utf-8"));
@@ -2682,13 +3113,13 @@ function readSettings() {
2682
3113
  }
2683
3114
  return { values, configPath: getConfigPath() };
2684
3115
  }
2685
- async function writeSetting(path20, value) {
2686
- const field = settingAt(path20);
2687
- if (!field) throw new SettingsError(`no setting ${path20}`, 404);
3116
+ async function writeSetting(path21, value) {
3117
+ const field = settingAt(path21);
3118
+ if (!field) throw new SettingsError(`no setting ${path21}`, 404);
2688
3119
  const checked = checkSetting(field, value);
2689
3120
  if (!checked.ok) throw new SettingsError(`${field.label}: ${checked.error}`);
2690
- const toWrite = checkedFolders(path20, checked.value);
2691
- await editConfig((raw) => setValueAt(raw, path20, toWrite)).catch((err) => {
3121
+ const toWrite = checkedFolders(path21, checked.value);
3122
+ await editConfig((raw) => setValueAt(raw, path21, toWrite)).catch((err) => {
2692
3123
  throw err instanceof RepoAdminError ? new SettingsError(err.message) : err;
2693
3124
  });
2694
3125
  return readSettings();
@@ -2702,9 +3133,9 @@ function checkedFolders(at, value) {
2702
3133
  if (at === "scanRoots" && Array.isArray(value))
2703
3134
  return value.map((v) => {
2704
3135
  const p = expandHome(v);
2705
- if (!path4.isAbsolute(p))
3136
+ if (!path5.isAbsolute(p))
2706
3137
  throw new SettingsError(`Folders scanned for repos: ${v} isn't a full path (start it from the drive, / or ~)`);
2707
- const full = path4.resolve(p);
3138
+ const full = path5.resolve(p);
2708
3139
  if (!fs6.statSync(full, { throwIfNoEntry: false })?.isDirectory())
2709
3140
  throw new SettingsError(`Folders scanned for repos: ${full} isn't a folder`);
2710
3141
  return full;
@@ -2755,7 +3186,7 @@ var configSettings = {
2755
3186
  };
2756
3187
 
2757
3188
  // src/core/conversations/timeline-source.ts
2758
- import path5 from "path";
3189
+ import path6 from "path";
2759
3190
 
2760
3191
  // src/core/conversations/timeline.ts
2761
3192
  var SIZE_LABEL = /^(\d+ files? · \+\d+ −\d+|no changes)$/;
@@ -2796,19 +3227,19 @@ function order(k) {
2796
3227
  var DAYS = 30;
2797
3228
  var MAX_TRANSCRIPT_BYTES = 8 << 20;
2798
3229
  var MAX_COMMITS = 100;
2799
- async function commitsOf(repo, since, run) {
2800
- const git3 = (...args) => run("git", ["-C", repo, ...args], repo);
3230
+ async function commitsOf(repo, since, run2) {
3231
+ const git3 = (...args) => run2("git", ["-C", repo, ...args], repo);
2801
3232
  const base = (await git3("merge-base", "HEAD", "origin/HEAD")).stdout.trim();
2802
3233
  const range = base ? [`${base}..HEAD`] : [`--since=${since}`, "HEAD"];
2803
3234
  const log = await git3("log", `--max-count=${MAX_COMMITS}`, "--format=%H%x09%aI%x09%s", ...range);
2804
3235
  if (log.code !== 0) return [];
2805
3236
  return log.stdout.split("\n").filter(Boolean).map((line) => {
2806
3237
  const [sha, at, ...subject] = line.split(" ");
2807
- return { repo: path5.basename(repo), sha, at, subject: subject.join(" ") };
3238
+ return { repo: path6.basename(repo), sha, at, subject: subject.join(" ") };
2808
3239
  });
2809
3240
  }
2810
3241
  async function sessionTimeline(s, deps = {}) {
2811
- const run = deps.run ?? defaultRunner;
3242
+ const run2 = deps.run ?? defaultRunner;
2812
3243
  const since = Math.max(Date.parse(s.createdAt) || 0, (deps.now ?? Date.now()) - DAYS * 864e5);
2813
3244
  const transcripts = [];
2814
3245
  const conv = agentOf(s).conversation;
@@ -2819,7 +3250,7 @@ async function sessionTimeline(s, deps = {}) {
2819
3250
  } catch {
2820
3251
  }
2821
3252
  }
2822
- const commits = s.archivedAt ? [] : (await Promise.all(s.paths.map((p) => commitsOf(p, s.createdAt, run).catch(() => [])))).flat();
3253
+ const commits = s.archivedAt ? [] : (await Promise.all(s.paths.map((p) => commitsOf(p, s.createdAt, run2).catch(() => [])))).flat();
2823
3254
  const prs = (deps.ci?.repos ?? []).filter((r) => r.pr).map((r) => ({
2824
3255
  repo: r.name,
2825
3256
  number: r.pr.number,
@@ -2872,7 +3303,7 @@ function mountBlockRoutes(app, opts) {
2872
3303
 
2873
3304
  // src/server/routes/jira-watch-routes.ts
2874
3305
  import fs7 from "fs";
2875
- import path6 from "path";
3306
+ import path7 from "path";
2876
3307
 
2877
3308
  // src/core/jira/jira-prompt.ts
2878
3309
  var branchFor = (issue) => `feat/${issue.key}`;
@@ -3093,14 +3524,14 @@ async function sweepJira(deps) {
3093
3524
  var EVERY_MS = 5 * 6e4;
3094
3525
  function aboutRepo(dir) {
3095
3526
  try {
3096
- const readme = ["README.md", "readme.md", "README"].map((n) => path6.join(dir, n)).find((f) => fs7.existsSync(f));
3527
+ const readme = ["README.md", "readme.md", "README"].map((n) => path7.join(dir, n)).find((f) => fs7.existsSync(f));
3097
3528
  if (readme) {
3098
3529
  const line = fs7.readFileSync(readme, "utf8").split(/\r?\n/).map(
3099
3530
  (l) => l.replace(/^[#>*\-\s]+/, "").replace(/[`*_[\]]/g, "").trim()
3100
3531
  ).find((l) => l.length > 20 && !/^(!|<|http)/.test(l));
3101
3532
  if (line) return line.slice(0, 160);
3102
3533
  }
3103
- const pkg = path6.join(dir, "package.json");
3534
+ const pkg = path7.join(dir, "package.json");
3104
3535
  if (fs7.existsSync(pkg)) {
3105
3536
  const d = JSON.parse(fs7.readFileSync(pkg, "utf8")).description;
3106
3537
  if (typeof d === "string" && d.trim()) return d.trim().slice(0, 160);
@@ -3114,7 +3545,7 @@ function watchTargets(cfg = loadConfig()) {
3114
3545
  const repos = Object.entries(cfg.repos).map(([alias, dir]) => ({
3115
3546
  name: alias,
3116
3547
  kind: "repo",
3117
- members: [path6.basename(dir)],
3548
+ members: [path7.basename(dir)],
3118
3549
  about: aboutRepo(dir)
3119
3550
  }));
3120
3551
  const groups = Object.entries(cfg.groups).map(([name, aliases]) => ({ name, kind: "group", members: aliases }));
@@ -3146,7 +3577,7 @@ function mountJiraWatchRoutes(app, opts) {
3146
3577
  running ??= (async () => {
3147
3578
  try {
3148
3579
  if (!readSettings2().enabled) return;
3149
- const run = opts.activity?.start("jira-watch", "Looking for newly assigned Jira issues");
3580
+ const run2 = opts.activity?.start("jira-watch", "Looking for newly assigned Jira issues");
3150
3581
  const deps = {
3151
3582
  // Throws when acli can't list them: the sweep fails (said in Activity) rather than reading "none".
3152
3583
  fetchIssues: fetchMyIssuesOrThrow,
@@ -3155,17 +3586,17 @@ function mountJiraWatchRoutes(app, opts) {
3155
3586
  sessions: () => loadHistory(),
3156
3587
  ask: (prompt) => runInternal(prompt, 9e4),
3157
3588
  start: (target, branch, issue) => start(target, branch, issue, true),
3158
- note: (text, level, sessionId) => run?.note(text, { level, ...sessionId ? { sessionId } : {} }),
3589
+ note: (text, level, sessionId) => run2?.note(text, { level, ...sessionId ? { sessionId } : {} }),
3159
3590
  maxPerDay: loadConfig()?.jiraWatch?.maxPerDay
3160
3591
  };
3161
3592
  try {
3162
3593
  const r = await sweepJira(deps);
3163
- run?.done(
3594
+ run2?.done(
3164
3595
  r.started || r.suggested || r.waiting ? `${r.started} started \xB7 ${r.suggested} to start yourself${r.waiting ? ` \xB7 ${r.waiting} waiting` : ""}` : "no new issues"
3165
3596
  );
3166
3597
  if (r.started || r.suggested) changed();
3167
3598
  } catch (err) {
3168
- run?.fail(err.message);
3599
+ run2?.fail(err.message);
3169
3600
  }
3170
3601
  lastRunAt = (/* @__PURE__ */ new Date()).toISOString();
3171
3602
  } finally {
@@ -3258,6 +3689,7 @@ function mountJiraWatchRoutes(app, opts) {
3258
3689
  // src/server/loop-watch.ts
3259
3690
  import { monitorEventLoopDelay } from "perf_hooks";
3260
3691
  function watchLoop(opts) {
3692
+ const ranSince = opts.ran ?? takeSlowestSync;
3261
3693
  const every = opts.everyMs ?? 1e4;
3262
3694
  const threshold = opts.thresholdMs ?? 1e3;
3263
3695
  const h = monitorEventLoopDelay({ resolution: 20 });
@@ -3268,7 +3700,8 @@ function watchLoop(opts) {
3268
3700
  h.reset();
3269
3701
  const s = slowest;
3270
3702
  slowest = null;
3271
- if (blockedMs >= threshold) opts.onStall({ blockedMs, slowest: s });
3703
+ const ran = ranSince();
3704
+ if (blockedMs >= threshold) opts.onStall({ blockedMs, slowest: s, ran });
3272
3705
  }, every);
3273
3706
  timer.unref?.();
3274
3707
  return {
@@ -3284,11 +3717,11 @@ function watchLoop(opts) {
3284
3717
  }
3285
3718
  function describeStall(s) {
3286
3719
  const secs = (s.blockedMs / 1e3).toFixed(1);
3287
- return `the server was blocked for ${secs} s (status updates, terminals and notifications waited)${s.slowest ? `; slowest request: ${s.slowest.what} (${(s.slowest.ms / 1e3).toFixed(1)} s)` : ""}`;
3720
+ return `the server was blocked for ${secs} s (status updates, terminals and notifications waited)${s.slowest ? `; slowest request: ${s.slowest.what} (${(s.slowest.ms / 1e3).toFixed(1)} s)` : ""}${s.ran ? `; it ran: ${s.ran.what} (${(s.ran.ms / 1e3).toFixed(1)} s)` : ""}`;
3288
3721
  }
3289
3722
 
3290
3723
  // src/server/web-server.ts
3291
- import path17 from "path";
3724
+ import path18 from "path";
3292
3725
  import { Hono } from "hono";
3293
3726
  import { streamSSE as streamSSE2 } from "hono/streaming";
3294
3727
 
@@ -3409,7 +3842,8 @@ var realBranchCheckDeps = {
3409
3842
  (prefix) => git(["show-ref", "--verify", "--quiet", `${prefix}${branch}`], repoPath).exitCode === 0
3410
3843
  ),
3411
3844
  validBranch: (name) => !name.startsWith("-") && git(["check-ref-format", "--branch", name], os.tmpdir()).exitCode === 0,
3412
- sessions: loadHistory
3845
+ sessions: loadHistory,
3846
+ ownsBranch: (target, branch, config) => ownsBranch(target, branch, config)
3413
3847
  };
3414
3848
  function checkBranch(target, branch, config, deps = realBranchCheckDeps) {
3415
3849
  const resolved = resolveProjectTarget(target, config);
@@ -3423,7 +3857,8 @@ function checkBranch(target, branch, config, deps = realBranchCheckDeps) {
3423
3857
  valid,
3424
3858
  exists: repoPaths.some((p) => deps.branchExists(p, branch)),
3425
3859
  session: s ? { id: sessionIdFor(s), archived: !!s.archivedAt } : null,
3426
- free: valid ? firstFreeBranch(branch, taken) : null
3860
+ free: valid ? firstFreeBranch(branch, taken) : null,
3861
+ ...deps.ownsBranch(target, branch, config) ? { ownCheckout: true } : {}
3427
3862
  };
3428
3863
  }
3429
3864
 
@@ -3523,19 +3958,19 @@ function mountPanesRoutes(app, opts) {
3523
3958
  const prsFetch = createSharedFetch(async () => {
3524
3959
  const config = loadConfig();
3525
3960
  if (!config) return { prs: [] };
3526
- const run = opts.activity?.start("pr-list", "Listing open pull requests");
3961
+ const run2 = opts.activity?.start("pr-list", "Listing open pull requests");
3527
3962
  try {
3528
3963
  const { map, incomplete } = await fetchAllPullRequests(config.repos);
3529
3964
  const prs = Array.from(map.values()).flat();
3530
3965
  if (incomplete.length)
3531
- run?.note(
3966
+ run2?.note(
3532
3967
  `couldn't list every PR of ${incomplete.join(", ")} (gh failed, or 100+ open): archiving isn't suggested for sessions there`,
3533
3968
  { level: "warn" }
3534
3969
  );
3535
- run?.done(`${prs.length} open PR${prs.length === 1 ? "" : "s"} in ${Object.keys(config.repos).length} repos`);
3970
+ run2?.done(`${prs.length} open PR${prs.length === 1 ? "" : "s"} in ${Object.keys(config.repos).length} repos`);
3536
3971
  return incomplete.length ? { prs, incomplete } : { prs };
3537
3972
  } catch (err) {
3538
- run?.fail(err.message);
3973
+ run2?.fail(err.message);
3539
3974
  throw err;
3540
3975
  }
3541
3976
  }, PRS_TTL_MS);
@@ -3556,14 +3991,14 @@ function mountPanesRoutes(app, opts) {
3556
3991
  app.get("/api/jira", async (c) => {
3557
3992
  if (!jiraInFlight) {
3558
3993
  jiraInFlight = (async () => {
3559
- const run = opts.activity?.start("jira", "Fetching your Jira issues");
3994
+ const run2 = opts.activity?.start("jira", "Fetching your Jira issues");
3560
3995
  try {
3561
3996
  const r = await fetchJiraPane();
3562
- if (!r.available) run?.fail("Jira CLI (acli) not available or not logged in");
3563
- else run?.done(`${r.issues.length} issue${r.issues.length === 1 ? "" : "s"}`);
3997
+ if (!r.available) run2?.fail("Jira CLI (acli) not available or not logged in");
3998
+ else run2?.done(`${r.issues.length} issue${r.issues.length === 1 ? "" : "s"}`);
3564
3999
  return r;
3565
4000
  } catch (err) {
3566
- run?.fail(err.message);
4001
+ run2?.fail(err.message);
3567
4002
  throw err;
3568
4003
  } finally {
3569
4004
  jiraInFlight = null;
@@ -3625,7 +4060,7 @@ function mountPanesRoutes(app, opts) {
3625
4060
 
3626
4061
  // src/server/routes/worktree-routes.ts
3627
4062
  import fs8 from "fs";
3628
- import path7 from "path";
4063
+ import path8 from "path";
3629
4064
  import { spawn } from "child_process";
3630
4065
 
3631
4066
  // src/core/platform/started.ts
@@ -3811,7 +4246,7 @@ function mountWorktreeRoutes(app, opts) {
3811
4246
  const wantsFile = !!body && typeof body === "object" && "path" in body;
3812
4247
  const asked = wantsFile ? openFileSchema.safeParse(body) : null;
3813
4248
  if (asked && !asked.success) return c.json({ error: "repo and path required" }, 400);
3814
- const folder = session.isGroup ? path7.dirname(session.paths[0]) : session.paths[0];
4249
+ const folder = session.isGroup ? path8.dirname(session.paths[0]) : session.paths[0];
3815
4250
  let file;
3816
4251
  if (asked?.success) {
3817
4252
  const at = await codeFilePath(session, asked.data.repo, asked.data.path);
@@ -3880,7 +4315,7 @@ function mountWorktreeRoutes(app, opts) {
3880
4315
  import { zValidator as zValidator6 } from "@hono/zod-validator";
3881
4316
  import { z as z5 } from "zod";
3882
4317
  import { EventEmitter } from "events";
3883
- import path8 from "path";
4318
+ import path9 from "path";
3884
4319
  import { streamSSE } from "hono/streaming";
3885
4320
  function mountScopeRoutes(app, opts) {
3886
4321
  const background = /* @__PURE__ */ new Set();
@@ -4127,7 +4562,7 @@ function mountScopeRoutes(app, opts) {
4127
4562
  const fromSha = fromEntry.repos[p] ?? "HEAD";
4128
4563
  const toSha = toEntry === void 0 ? "working" : toEntry.repos[p] ?? "HEAD";
4129
4564
  return {
4130
- name: path8.basename(p),
4565
+ name: path9.basename(p),
4131
4566
  root: p,
4132
4567
  files: computeRangeDiff({ root: p, fromRef: fromSha, toRef: toSha })
4133
4568
  };
@@ -4144,7 +4579,7 @@ function mountScopeRoutes(app, opts) {
4144
4579
  }
4145
4580
  const resolved = scope.paths.map((p) => resolveRepoDiff(p, base, sessionBaseForPath(p)));
4146
4581
  const repos = scope.paths.map((p, i) => ({
4147
- name: path8.basename(p),
4582
+ name: path9.basename(p),
4148
4583
  root: p,
4149
4584
  resolvedBase: resolved[i].resolvedBase,
4150
4585
  files: computeDiff({ root: p, diffArg: resolved[i].diffArg })
@@ -4175,7 +4610,7 @@ function mountScopeRoutes(app, opts) {
4175
4610
  if (!relPath || !Number.isInteger(start) || !Number.isInteger(end)) {
4176
4611
  return c.json({ error: "bad path/start/end" }, 400);
4177
4612
  }
4178
- const root = scope.paths.length === 1 ? scope.paths[0] : scope.paths.find((p) => path8.basename(p) === repoName);
4613
+ const root = scope.paths.length === 1 ? scope.paths[0] : scope.paths.find((p) => path9.basename(p) === repoName);
4179
4614
  if (!root) return c.json({ error: "unknown repo" }, 404);
4180
4615
  const result = readContextLines({ root, relPath, start, end, ref });
4181
4616
  if (!result) return c.json({ error: "cannot read file" }, 400);
@@ -4356,7 +4791,7 @@ function mountScopeRoutes(app, opts) {
4356
4791
  // src/core/pty/terminal-perf.ts
4357
4792
  var MAX_KEYS = 200;
4358
4793
  var MAX_STALLS = 100;
4359
- var num = (x) => typeof x === "number" && Number.isFinite(x) && x >= 0 && x < 1e13;
4794
+ var num2 = (x) => typeof x === "number" && Number.isFinite(x) && x >= 0 && x < 1e13;
4360
4795
  function cleanPerfReport(x) {
4361
4796
  if (!x || typeof x !== "object") return null;
4362
4797
  const r = x;
@@ -4367,13 +4802,13 @@ function cleanPerfReport(x) {
4367
4802
  const keys = [];
4368
4803
  for (const k of r.keys.slice(0, MAX_KEYS)) {
4369
4804
  const o = k;
4370
- if (!o || !num(o.arrived) || !(o.shown === null || num(o.shown))) return null;
4805
+ if (!o || !num2(o.arrived) || !(o.shown === null || num2(o.shown))) return null;
4371
4806
  keys.push({ arrived: Math.round(o.arrived), shown: o.shown === null ? null : Math.round(o.shown) });
4372
4807
  }
4373
4808
  const stalls = [];
4374
4809
  for (const s of r.stalls.slice(0, MAX_STALLS)) {
4375
4810
  const o = s;
4376
- if (!o || !num(o.at) || !num(o.ms) || !(o.blocking === null || num(o.blocking)) || typeof o.what !== "string") return null;
4811
+ if (!o || !num2(o.at) || !num2(o.ms) || !(o.blocking === null || num2(o.blocking)) || typeof o.what !== "string") return null;
4377
4812
  stalls.push({
4378
4813
  at: o.at,
4379
4814
  ms: Math.round(o.ms),
@@ -4433,7 +4868,7 @@ function mountTerminalRoutes(app, opts) {
4433
4868
  }
4434
4869
 
4435
4870
  // src/server/routes/status-routes.ts
4436
- import path9 from "path";
4871
+ import path10 from "path";
4437
4872
 
4438
4873
  // src/core/status/notifier.ts
4439
4874
  var MESSAGES = {
@@ -4581,7 +5016,7 @@ function mountStatusRoutes(app, opts) {
4581
5016
  const kind = notifyKindForTransition(status.prevState ? { state: status.prevState } : null, status);
4582
5017
  if (kind) {
4583
5018
  const config = loadConfig();
4584
- const launchDir = session.isGroup && session.paths[0] ? path9.dirname(session.paths[0]) : session.paths[0] ?? body.cwd;
5019
+ const launchDir = session.isGroup && session.paths[0] ? path10.dirname(session.paths[0]) : session.paths[0] ?? body.cwd;
4585
5020
  const name = `${session.target} \xB7 ${session.branch}`;
4586
5021
  const snooze = readSnooze(id);
4587
5022
  const route = snooze?.until && snoozeActive(snooze, { attention: status }) ? "none" : presence.route(id);
@@ -4734,6 +5169,7 @@ function conflictMessage(conflicts, isGroup, contextShare) {
4734
5169
  ].join("\n");
4735
5170
  }
4736
5171
  var REENTERED_GRACE_MS = 24 * 36e5;
5172
+ var KEPT_ON_REQUEST = "every PR merged, but kept: you asked to keep it after its PR merges (its right-click menu undoes that)";
4737
5173
  function checkedOutMerged(r) {
4738
5174
  return !r.localSha || !r.pr?.headSha || r.localSha === r.pr.headSha || r.behindMergedHead === true;
4739
5175
  }
@@ -4902,16 +5338,16 @@ function createPrWatch(deps) {
4902
5338
  const me = ci.repos.find((r) => r.name === f.repo)?.viewer ?? ci.viewer;
4903
5339
  return !!me && me.toLowerCase() === author.toLowerCase();
4904
5340
  }
4905
- function check(id, session, act = true, run) {
5341
+ function check(id, session, act = true, run2) {
4906
5342
  const running2 = inflight.get(id);
4907
5343
  if (running2) return running2;
4908
- const p = checkNow(id, session, act, run).finally(() => inflight.delete(id));
5344
+ const p = checkNow(id, session, act, run2).finally(() => inflight.delete(id));
4909
5345
  inflight.set(id, p);
4910
5346
  return p;
4911
5347
  }
4912
- async function checkNow(id, session, act = true, run) {
5348
+ async function checkNow(id, session, act = true, run2) {
4913
5349
  const name = `${session.target} ${session.branch}`;
4914
- const note = (text, level = "info") => run?.note(`${name}: ${text}`, { level, sessionId: id });
5350
+ const note = (text, level = "info") => run2?.note(`${name}: ${text}`, { level, sessionId: id });
4915
5351
  let pre;
4916
5352
  try {
4917
5353
  pre = await deps.preflight(session, { resting });
@@ -5125,7 +5561,8 @@ function createPrWatch(deps) {
5125
5561
  }
5126
5562
  if (opts.autoArchive) {
5127
5563
  const verdict = deps.ownCheckout?.(session) ? null : autoArchiveVerdict(pre, session, now());
5128
- if (verdict?.archive && deps.busy?.(id)) note("every PR merged; archiving once its Claude finishes this turn");
5564
+ if (verdict?.archive && session.keepAfterMerge) note(KEPT_ON_REQUEST);
5565
+ else if (verdict?.archive && deps.busy?.(id)) note("every PR merged; archiving once its Claude finishes this turn");
5129
5566
  else if (verdict?.archive) {
5130
5567
  try {
5131
5568
  const keptWhat = await deps.archive(id);
@@ -5178,20 +5615,20 @@ function createPrWatch(deps) {
5178
5615
  if (!restingNames()) schedule?.resume();
5179
5616
  const queue = due;
5180
5617
  const ids = queue.map((q) => q.id);
5181
- const run = deps.activity?.start("pr-watch", "Checking pull requests");
5618
+ const run2 = deps.activity?.start("pr-watch", "Checking pull requests");
5182
5619
  let done = 0;
5183
- run?.progress(0, ids.length);
5620
+ run2?.progress(0, ids.length);
5184
5621
  const worker = async () => {
5185
5622
  for (let next = queue.shift(); next; next = queue.shift()) {
5186
- await check(next.id, next.session, !deps.lookOnly, run);
5187
- run?.progress(++done, ids.length);
5623
+ await check(next.id, next.session, !deps.lookOnly, run2);
5624
+ run2?.progress(++done, ids.length);
5188
5625
  }
5189
5626
  };
5190
5627
  try {
5191
5628
  await Promise.all(Array.from({ length: CONCURRENCY }, worker));
5192
- run?.done(sweepSummary(ids));
5629
+ run2?.done(sweepSummary(ids));
5193
5630
  } catch (err) {
5194
- run?.fail(err.message);
5631
+ run2?.fail(err.message);
5195
5632
  throw err;
5196
5633
  }
5197
5634
  })().finally(() => {
@@ -5252,7 +5689,7 @@ function repoServer(repoPath) {
5252
5689
  const { origin } = hostForRepo(repoPath);
5253
5690
  return origin ? originHostname(origin) : null;
5254
5691
  }
5255
- function viewerLogin(run, lookup = hostOf, serverOf = repoServer) {
5692
+ function viewerLogin(run2, lookup = hostOf, serverOf = repoServer) {
5256
5693
  const known = /* @__PURE__ */ new Map();
5257
5694
  return async (hostId, repoPath) => {
5258
5695
  const host = lookup(hostId);
@@ -5260,21 +5697,21 @@ function viewerLogin(run, lookup = hostOf, serverOf = repoServer) {
5260
5697
  ${repoPath ? serverOf(repoPath) ?? "" : ""}`;
5261
5698
  const was = known.get(key);
5262
5699
  if (was) return was;
5263
- const login = await host.viewer(run, repoPath ?? process.cwd()).catch(() => null);
5700
+ const login = await host.viewer(run2, repoPath ?? process.cwd()).catch(() => null);
5264
5701
  if (login) known.set(key, login);
5265
5702
  return login || null;
5266
5703
  };
5267
5704
  }
5268
- async function fetchReviewFeedback(repoPath, prNumber, run) {
5269
- return hostForRepo(repoPath).host.reviewFeedback(run, repoPath, prNumber);
5705
+ async function fetchReviewFeedback(repoPath, prNumber, run2) {
5706
+ return hostForRepo(repoPath).host.reviewFeedback(run2, repoPath, prNumber);
5270
5707
  }
5271
5708
  function hostRateLimited(hostId, text) {
5272
5709
  return hostOf(hostId).rateLimited(text);
5273
5710
  }
5274
- function prWatchHostDeps(run) {
5711
+ function prWatchHostDeps(run2) {
5275
5712
  return {
5276
- viewer: viewerLogin(run),
5277
- reviewFeedback: (repoPath, n) => fetchReviewFeedback(repoPath, n, run),
5713
+ viewer: viewerLogin(run2),
5714
+ reviewFeedback: (repoPath, n) => fetchReviewFeedback(repoPath, n, run2),
5278
5715
  rateLimited: hostRateLimited
5279
5716
  };
5280
5717
  }
@@ -5350,7 +5787,7 @@ function branchFactsOf(pre) {
5350
5787
  }))
5351
5788
  );
5352
5789
  }
5353
- function listedPrsIo(run, opts = {}) {
5790
+ function listedPrsIo(run2, opts = {}) {
5354
5791
  return {
5355
5792
  repoIdOf: (repoPath) => {
5356
5793
  const { host, origin } = hostForRepo(repoPath);
@@ -5360,19 +5797,19 @@ function listedPrsIo(run, opts = {}) {
5360
5797
  const h = hostOfPrUrl(url)?.host;
5361
5798
  return h ? h.id === DEFAULT_HOST ? void 0 : h.id : null;
5362
5799
  },
5363
- lookup: (cwd, host, ref) => hostOf(host).prForRef(run, cwd ?? os2.tmpdir(), ref),
5800
+ lookup: (cwd, host, ref) => hostOf(host).prForRef(run2, cwd ?? os2.tmpdir(), ref),
5364
5801
  ...opts
5365
5802
  };
5366
5803
  }
5367
- async function shipPreflightWithListed(session, run, io = {}) {
5368
- const pre = await (io.preflight ?? shipPreflight)(session, run);
5369
- return (await withListedPrs(pre, readSessionPrs(sessionIdFor(session)), io.listed ?? listedPrsIo(run))).pre;
5804
+ async function shipPreflightWithListed(session, run2, io = {}) {
5805
+ const pre = await (io.preflight ?? shipPreflight)(session, run2);
5806
+ return (await withListedPrs(pre, readSessionPrs(sessionIdFor(session)), io.listed ?? listedPrsIo(run2))).pre;
5370
5807
  }
5371
- async function watchPreflight(session, run, opts = {}, io = {}) {
5808
+ async function watchPreflight(session, run2, opts = {}, io = {}) {
5372
5809
  const id = sessionIdFor(session);
5373
5810
  const last = opts.last ?? null;
5374
5811
  const repoOf = (name) => last?.repos.find((x) => x.name === name);
5375
- const pre = await (io.preflight ?? shipPreflight)(session, run, {
5812
+ const pre = await (io.preflight ?? shipPreflight)(session, run2, {
5376
5813
  askGh: watchAskGh(opts.resting, (name) => !!repoOf(name)?.pr),
5377
5814
  ...watchBranchOptions(
5378
5815
  readSessionBranches(id),
@@ -5384,7 +5821,7 @@ async function watchPreflight(session, run, opts = {}, io = {}) {
5384
5821
  const facts = branchFactsOf(pre);
5385
5822
  if (facts.length) bestEffort(`keep the branch facts of ${id}`, () => noteBranchFacts(id, facts));
5386
5823
  const previous = (url) => last ? prsOfCheck(last).find((p) => p.pr.url.toLowerCase() === url.toLowerCase())?.pr : void 0;
5387
- const listed = io.listed ?? listedPrsIo(run, { ...opts.resting ? { resting: opts.resting } : {}, previous });
5824
+ const listed = io.listed ?? listedPrsIo(run2, { ...opts.resting ? { resting: opts.resting } : {}, previous });
5388
5825
  const found = await withListedPrs(pre, readSessionPrs(id), listed);
5389
5826
  const aliases = new Map(sessionRepos(session, loadConfig()).map((r) => [r.path, r.alias]));
5390
5827
  const keys = new Map(pre.repos.map((r) => [r.name, [aliases.get(r.path), listed.repoIdOf(r.path)]]));
@@ -5404,8 +5841,9 @@ function mountShipRoutes(app, opts) {
5404
5841
  if (!session) return { ok: false };
5405
5842
  let ok;
5406
5843
  let warnings = [];
5844
+ const keepOnRestore = !archived && archivedForMerge(id);
5407
5845
  if (archived) {
5408
- const out = await archiveSession(session, defaultArchiveDeps({ release: opts.release }), {
5846
+ const out = await archiveSession(session, defaultArchiveDeps({ release: opts.release, removeWorktree: opts.removeWorktree }), {
5409
5847
  force,
5410
5848
  merged,
5411
5849
  by: merged ? "shipped" : "you"
@@ -5441,6 +5879,7 @@ function mountShipRoutes(app, opts) {
5441
5879
  restoreArchivedTranscripts(session);
5442
5880
  ok = await setSessionArchived(session.target, session.branch, false);
5443
5881
  }
5882
+ if (ok && keepOnRestore) await setSessionKeep(session.target, session.branch, true);
5444
5883
  opts.broadcast("sessions-changed", { ts: Date.now() });
5445
5884
  return warnings.length ? { ok, warnings } : { ok };
5446
5885
  };
@@ -5453,6 +5892,15 @@ function mountShipRoutes(app, opts) {
5453
5892
  opts.broadcast("sessions-changed", { ts: Date.now() });
5454
5893
  return c.json({ ok: true });
5455
5894
  });
5895
+ app.post("/api/sessions/:id/keep", async (c) => {
5896
+ const session = findSession2(c.req.param("id"));
5897
+ if (!session) return c.json({ error: "unknown session" }, 404);
5898
+ const body = await c.req.json().catch(() => null);
5899
+ if (typeof body?.keep !== "boolean") return c.json({ error: "keep: boolean" }, 400);
5900
+ await setSessionKeep(session.target, session.branch, body.keep);
5901
+ opts.broadcast("sessions-changed", { ts: Date.now() });
5902
+ return c.json({ ok: true, keep: body.keep });
5903
+ });
5456
5904
  app.get("/api/sessions/:id/ship", async (c) => {
5457
5905
  const session = findSession2(c.req.param("id"));
5458
5906
  if (!session) return c.json({ error: "unknown session" }, 404);
@@ -5485,11 +5933,11 @@ function mountShipRoutes(app, opts) {
5485
5933
  selection,
5486
5934
  body.method ?? "squash",
5487
5935
  opts.run,
5488
- (s, run) => shipPreflightWithListed(s, run)
5936
+ (s, run2) => shipPreflightWithListed(s, run2)
5489
5937
  );
5490
5938
  opts.onRepoChanged?.(id);
5491
5939
  let archived = false;
5492
- if (outcome.mergedAny && outcome.allDone) {
5940
+ if (outcome.mergedAny && outcome.allDone && !findSession2(id)?.keepAfterMerge) {
5493
5941
  archived = (await archive(id, true, false, true)).ok;
5494
5942
  } else {
5495
5943
  opts.broadcast("sessions-changed", { ts: Date.now() });
@@ -5598,8 +6046,8 @@ function mountRailRoutes(app, opts) {
5598
6046
 
5599
6047
  // src/core/worktree/shared-folders.ts
5600
6048
  import fs9 from "fs";
5601
- import path10 from "path";
5602
- var norm = (p) => path10.resolve(p).replace(/\\/g, "/").toLowerCase();
6049
+ import path11 from "path";
6050
+ var norm = (p) => path11.resolve(p).replace(/\\/g, "/").toLowerCase();
5603
6051
  function shadowedSessions(sessions, branchCheckedOut2) {
5604
6052
  const byFolder = /* @__PURE__ */ new Map();
5605
6053
  for (const s of sessions) {
@@ -5618,14 +6066,14 @@ function shadowedSessions(sessions, branchCheckedOut2) {
5618
6066
  }
5619
6067
  function branchCheckedOut(dir) {
5620
6068
  try {
5621
- const dotGit = path10.join(dir, ".git");
6069
+ const dotGit = path11.join(dir, ".git");
5622
6070
  let gitDir = dotGit;
5623
6071
  if (fs9.statSync(dotGit).isFile()) {
5624
6072
  const m = /^gitdir:\s*(.+)$/m.exec(fs9.readFileSync(dotGit, "utf8"));
5625
6073
  if (!m) return null;
5626
- gitDir = path10.resolve(dir, m[1].trim());
6074
+ gitDir = path11.resolve(dir, m[1].trim());
5627
6075
  }
5628
- const head = fs9.readFileSync(path10.join(gitDir, "HEAD"), "utf8");
6076
+ const head = fs9.readFileSync(path11.join(gitDir, "HEAD"), "utf8");
5629
6077
  const ref = /^ref:\s*refs\/heads\/(.+)$/m.exec(head);
5630
6078
  return ref ? ref[1].trim() : null;
5631
6079
  } catch {
@@ -5719,13 +6167,13 @@ function mountCleanupRoutes(app, opts) {
5719
6167
  app.post("/api/cleanup/branches/scan", (c) => {
5720
6168
  if (!branches.scanning) {
5721
6169
  branches = { ...branches, scanning: true };
5722
- const run = opts.activity?.start("branches", "Looking for merged local branches");
6170
+ const run2 = opts.activity?.start("branches", "Looking for merged local branches");
5723
6171
  void findMergedBranches(branchDeps).then((candidates2) => {
5724
6172
  branches = { scanning: false, scannedAt: (/* @__PURE__ */ new Date()).toISOString(), candidates: candidates2 };
5725
- run?.done(`${candidates2.length} merged local branch${candidates2.length === 1 ? "" : "es"}`);
6173
+ run2?.done(`${candidates2.length} merged local branch${candidates2.length === 1 ? "" : "es"}`);
5726
6174
  }).catch((err) => {
5727
6175
  branches = { ...branches, scanning: false };
5728
- run?.fail(err.message);
6176
+ run2?.fail(err.message);
5729
6177
  });
5730
6178
  }
5731
6179
  return c.json(branches);
@@ -5736,10 +6184,10 @@ function mountCleanupRoutes(app, opts) {
5736
6184
  (i) => !!i && typeof i.repo === "string" && typeof i.branch === "string"
5737
6185
  ).map((i) => ({ repo: i.repo, branch: i.branch, ...typeof i.tip === "string" ? { tip: i.tip } : {} })) : [];
5738
6186
  if (items.length === 0) return c.json({ error: "items: [{repo, branch, tip?}]" }, 400);
5739
- const run = opts.activity?.start("branches", "Deleting merged local branches");
6187
+ const run2 = opts.activity?.start("branches", "Deleting merged local branches");
5740
6188
  const results = await deleteMergedBranches(items, branchDeps);
5741
- for (const r of results) run?.note(`${r.repo} ${r.branch}: ${r.message}`, { level: r.ok ? "action" : "warn" });
5742
- run?.done(`${results.filter((r) => r.ok).length} of ${results.length} deleted`);
6189
+ for (const r of results) run2?.note(`${r.repo} ${r.branch}: ${r.message}`, { level: r.ok ? "action" : "warn" });
6190
+ run2?.done(`${results.filter((r) => r.ok).length} of ${results.length} deleted`);
5743
6191
  const gone = new Set(results.filter((r) => r.ok).map((r) => `${r.repo}\0${r.branch}`));
5744
6192
  branches = { ...branches, candidates: branches.candidates.filter((b) => !gone.has(`${b.repo}\0${b.branch}`)) };
5745
6193
  return c.json({ results, state: branches });
@@ -5789,14 +6237,14 @@ function createActivityLog(opts = {}) {
5789
6237
  let recent = [];
5790
6238
  const lastOk = /* @__PURE__ */ new Map();
5791
6239
  const schedules = /* @__PURE__ */ new Map();
5792
- const finish = (run) => {
5793
- running.delete(run.id);
5794
- recent = [run, ...recent].slice(0, keep);
6240
+ const finish = (run2) => {
6241
+ running.delete(run2.id);
6242
+ recent = [run2, ...recent].slice(0, keep);
5795
6243
  changed();
5796
6244
  };
5797
6245
  return {
5798
6246
  start(kind, label) {
5799
- const run = {
6247
+ const run2 = {
5800
6248
  id: nextId++,
5801
6249
  kind,
5802
6250
  label,
@@ -5807,31 +6255,31 @@ function createActivityLog(opts = {}) {
5807
6255
  summary: null,
5808
6256
  notes: []
5809
6257
  };
5810
- running.set(run.id, run);
6258
+ running.set(run2.id, run2);
5811
6259
  changed();
5812
- const open = () => run.status === "running";
6260
+ const open = () => run2.status === "running";
5813
6261
  return {
5814
6262
  progress(done, total) {
5815
6263
  if (!open()) return;
5816
- run.progress = { done, total };
6264
+ run2.progress = { done, total };
5817
6265
  changed();
5818
6266
  },
5819
6267
  note(text, o = {}) {
5820
6268
  if (!open()) return;
5821
6269
  const n = { at: iso(), text, level: o.level ?? "info", ...o.sessionId ? { sessionId: o.sessionId } : {} };
5822
- run.notes = [...run.notes, n].slice(-KEEP_NOTES);
6270
+ run2.notes = [...run2.notes, n].slice(-KEEP_NOTES);
5823
6271
  changed();
5824
6272
  },
5825
6273
  done(summary) {
5826
6274
  if (!open()) return;
5827
- Object.assign(run, { status: "done", endedAt: iso(), summary });
5828
- lastOk.set(run.kind, run.endedAt);
5829
- finish(run);
6275
+ Object.assign(run2, { status: "done", endedAt: iso(), summary });
6276
+ lastOk.set(run2.kind, run2.endedAt);
6277
+ finish(run2);
5830
6278
  },
5831
6279
  fail(error) {
5832
6280
  if (!open()) return;
5833
- Object.assign(run, { status: "failed", endedAt: iso(), summary: error });
5834
- finish(run);
6281
+ Object.assign(run2, { status: "failed", endedAt: iso(), summary: error });
6282
+ finish(run2);
5835
6283
  }
5836
6284
  };
5837
6285
  },
@@ -5887,7 +6335,7 @@ function threadsWithoutDraft(open, replies) {
5887
6335
  return open.filter((t) => !drafted.has(t.threadId));
5888
6336
  }
5889
6337
  function mountPrReplyRoutes(app, opts) {
5890
- const run = opts.run ?? defaultRunner;
6338
+ const run2 = opts.run ?? defaultRunner;
5891
6339
  const changed = (sessionId) => {
5892
6340
  if (opts.watch) markPostedAnswered(sessionId, opts.watch);
5893
6341
  opts.broadcast("replies-changed", { sessionId });
@@ -5909,7 +6357,7 @@ function mountPrReplyRoutes(app, opts) {
5909
6357
  if (typeof b.body !== "string") return c.json({ error: "body: string" }, 400);
5910
6358
  const r = await draftReply(id, c.req.param("thread"), b.body, {
5911
6359
  repos: () => sessionRepoRefs(session),
5912
- run
6360
+ run: run2
5913
6361
  });
5914
6362
  if (!r.ok) return c.json({ error: r.error }, 400);
5915
6363
  changed(id);
@@ -5932,7 +6380,7 @@ function mountPrReplyRoutes(app, opts) {
5932
6380
  return c.json({ error: "body: the reply text" }, 400);
5933
6381
  const thread = c.req.param("thread");
5934
6382
  const cwd = replyFolder(session, listReplies(id).find((r2) => r2.threadId === thread)?.repo);
5935
- const r = await postReply(id, thread, b.body, { resolve: b.resolve === true, cwd, run });
6383
+ const r = await postReply(id, thread, b.body, { resolve: b.resolve === true, cwd, run: run2 });
5936
6384
  if (!r.ok) return c.json({ error: r.error }, 502);
5937
6385
  const act = opts.activity?.start("pr-watch", "Posting a review reply");
5938
6386
  act?.note(`${session.target} ${session.branch}: posted your reply${r.resolved ? " and resolved the thread" : ""}`, {
@@ -5953,7 +6401,7 @@ function mountPrReplyRoutes(app, opts) {
5953
6401
 
5954
6402
  // src/core/archive/archive-retention.ts
5955
6403
  import fs11 from "fs";
5956
- import path11 from "path";
6404
+ import path12 from "path";
5957
6405
  import zlib from "zlib";
5958
6406
  var DEFAULT_COMPRESS_AFTER_DAYS = 30;
5959
6407
  var DAY_MS = 24 * 36e5;
@@ -5974,14 +6422,14 @@ function applyArchiveRetention(opts) {
5974
6422
  if (!rec) continue;
5975
6423
  const age = now - Date.parse(rec.archivedAt);
5976
6424
  if (!Number.isFinite(age)) continue;
5977
- const ignored = path11.join(archiveDirFor(id, root), "ignored");
6425
+ const ignored = path12.join(archiveDirFor(id, root), "ignored");
5978
6426
  if (compressAfter > 0 && age >= compressAfter * DAY_MS && !rec.ignoredDroppedAt && fs11.existsSync(ignored)) {
5979
6427
  fs11.rmSync(ignored, { recursive: true, force: true });
5980
6428
  rec.ignoredDroppedAt = new Date(now).toISOString();
5981
6429
  writeArchiveRecord(rec, root);
5982
6430
  }
5983
6431
  if (rec.transcriptsDroppedAt) continue;
5984
- const dir = path11.join(archiveDirFor(id, root), "transcripts");
6432
+ const dir = path12.join(archiveDirFor(id, root), "transcripts");
5985
6433
  if (dropAfter > 0 && age >= dropAfter * DAY_MS) {
5986
6434
  out.bytesSaved += dirBytes(dir);
5987
6435
  fs11.rmSync(dir, { recursive: true, force: true });
@@ -5992,7 +6440,7 @@ function applyArchiveRetention(opts) {
5992
6440
  }
5993
6441
  if (compressAfter <= 0 || rec.compressedAt || age < compressAfter * DAY_MS) continue;
5994
6442
  for (const t of rec.transcripts) {
5995
- const plain = path11.join(dir, t.file);
6443
+ const plain = path12.join(dir, t.file);
5996
6444
  if (!fs11.existsSync(plain)) continue;
5997
6445
  const data = fs11.readFileSync(plain);
5998
6446
  const gz = zlib.gzipSync(data);
@@ -6013,7 +6461,7 @@ function applyArchiveRetention(opts) {
6013
6461
  function dirBytes(dir) {
6014
6462
  let n = 0;
6015
6463
  try {
6016
- for (const f of fs11.readdirSync(dir)) n += fs11.statSync(path11.join(dir, f)).size;
6464
+ for (const f of fs11.readdirSync(dir)) n += fs11.statSync(path12.join(dir, f)).size;
6017
6465
  } catch {
6018
6466
  }
6019
6467
  return n;
@@ -6037,7 +6485,7 @@ function createTimeKeeper(deps, opts) {
6037
6485
  if (d === today) return true;
6038
6486
  return needsBuild(d, builtAt.get(d));
6039
6487
  });
6040
- const run2 = opts.activity?.start("time", days.length === 1 ? "Updating today" : `Building ${days.length} days`);
6488
+ const run3 = opts.activity?.start("time", days.length === 1 ? "Updating today" : `Building ${days.length} days`);
6041
6489
  const failed = [];
6042
6490
  let built = 0;
6043
6491
  for (const d of days) {
@@ -6049,11 +6497,11 @@ function createTimeKeeper(deps, opts) {
6049
6497
  }
6050
6498
  }
6051
6499
  if (built) opts.changed();
6052
- if (failed.length) run2?.fail(`${failed.length} of ${days.length} not built \u2014 ${failed.join("; ")}`);
6053
- else run2?.done(days.length === 1 ? "today updated" : `${days.length} days built`);
6500
+ if (failed.length) run3?.fail(`${failed.length} of ${days.length} not built \u2014 ${failed.join("; ")}`);
6501
+ else run3?.done(days.length === 1 ? "today updated" : `${days.length} days built`);
6054
6502
  }
6055
6503
  let again = null;
6056
- const run = (what = "all") => {
6504
+ const run2 = (what = "all") => {
6057
6505
  if (busy) {
6058
6506
  again = again === "all" || what === "all" ? "all" : "local";
6059
6507
  return busy;
@@ -6075,12 +6523,12 @@ function createTimeKeeper(deps, opts) {
6075
6523
  return busy;
6076
6524
  };
6077
6525
  return {
6078
- run,
6526
+ run: run2,
6079
6527
  soon: () => {
6080
6528
  if (timer) return;
6081
6529
  timer = setTimeout(() => {
6082
6530
  timer = null;
6083
- void run("local");
6531
+ void run2("local");
6084
6532
  }, AFTER_TURN_MS);
6085
6533
  timer.unref?.();
6086
6534
  },
@@ -6319,14 +6767,14 @@ function settleLeftOverClaims(deps) {
6319
6767
  function tidyLeftOverSubmits(deps, activity, changed) {
6320
6768
  const done = settleLeftOverClaims(deps);
6321
6769
  if (!done.length) return;
6322
- const run = activity?.start("reviews", "Submits left mid-way");
6770
+ const run2 = activity?.start("reviews", "Submits left mid-way");
6323
6771
  for (const r of done) {
6324
- run?.note(`${r.repo} #${r.number}: work stopped while submitting your review \u2014 look at the PR and say whether it went`, {
6772
+ run2?.note(`${r.repo} #${r.number}: work stopped while submitting your review \u2014 look at the PR and say whether it went`, {
6325
6773
  level: "warn"
6326
6774
  });
6327
6775
  changed(r);
6328
6776
  }
6329
- run?.done(`${done.length} submit${done.length === 1 ? "" : "s"} in doubt`);
6777
+ run2?.done(`${done.length} submit${done.length === 1 ? "" : "s"} in doubt`);
6330
6778
  }
6331
6779
 
6332
6780
  // src/core/review/review-fix.ts
@@ -6405,10 +6853,10 @@ async function fixItMyself(deps, repo, number, input) {
6405
6853
  const no = claimRefused;
6406
6854
  if (no) return { ok: false, ...no };
6407
6855
  const release = () => deps.update(repo, number, (cur) => cur.fixing?.at === claimAt ? withoutFixClaim(cur) : cur);
6408
- const run = deps.activity?.start("reviews", `Fix it myself: ${repo} #${number}`);
6856
+ const run2 = deps.activity?.start("reviews", `Fix it myself: ${repo} #${number}`);
6409
6857
  const fail = (status, error, sessionId) => {
6410
6858
  release();
6411
- run?.fail(error);
6859
+ run2?.fail(error);
6412
6860
  return { ok: false, status, error, ...sessionId ? { sessionId } : {} };
6413
6861
  };
6414
6862
  try {
@@ -6469,13 +6917,13 @@ async function fixItMyself(deps, repo, number, input) {
6469
6917
  `${plural(left.length, "comment")} stayed on the review (posted, or a submit took ${left.length === 1 ? "it" : "them"} meanwhile): the session has ${left.length === 1 ? "it" : "them"} too`
6470
6918
  );
6471
6919
  const said = `${plural(moved, "comment")} on #${number} being fixed in ${label}${created ? " (new session)" : ""}`;
6472
- run?.note(said, { level: "action", sessionId });
6473
- for (const w of warnings) run?.note(`${label}: ${w}`, { level: "warn", sessionId });
6474
- run?.done(said);
6920
+ run2?.note(said, { level: "action", sessionId });
6921
+ for (const w of warnings) run2?.note(`${label}: ${w}`, { level: "warn", sessionId });
6922
+ run2?.done(said);
6475
6923
  return { ok: true, sessionId, created, review: next ?? claimed, ...warnings.length ? { warnings } : {} };
6476
6924
  } catch (err) {
6477
6925
  release();
6478
- run?.fail(err.message);
6926
+ run2?.fail(err.message);
6479
6927
  throw err;
6480
6928
  }
6481
6929
  }
@@ -6491,7 +6939,7 @@ function reviewModeOf(alias, config) {
6491
6939
  return { mode: "all", from: "default" };
6492
6940
  }
6493
6941
  function reviewProjects(config) {
6494
- return Object.entries(config.repos).map(([alias, path20]) => ({ alias, path: path20, mode: reviewModeOf(alias, config).mode }));
6942
+ return Object.entries(config.repos).map(([alias, path21]) => ({ alias, path: path21, mode: reviewModeOf(alias, config).mode }));
6495
6943
  }
6496
6944
  function reviewLimits(config) {
6497
6945
  return {
@@ -6502,7 +6950,7 @@ function reviewLimits(config) {
6502
6950
  var isReviewMode = (v) => v === "all" || v === "asked" || v === "off";
6503
6951
 
6504
6952
  // src/server/routes/review-routes.ts
6505
- var num2 = (s) => /^\d+$/.test(s) ? Number(s) : null;
6953
+ var num3 = (s) => /^\d+$/.test(s) ? Number(s) : null;
6506
6954
  function mountReviewRoutes(app, deps) {
6507
6955
  const changed = (repo, number) => deps.broadcast("reviews-changed", { repo, number });
6508
6956
  app.get("/api/reviews", (c) => {
@@ -6523,13 +6971,13 @@ function mountReviewRoutes(app, deps) {
6523
6971
  return c.json(deps.settings());
6524
6972
  });
6525
6973
  app.get("/api/reviews/:repo/:number", (c) => {
6526
- const n = num2(c.req.param("number"));
6974
+ const n = num3(c.req.param("number"));
6527
6975
  const r = n === null ? null : deps.read(c.req.param("repo"), n);
6528
6976
  return r ? c.json(shownReview(deps, r)) : c.json({ error: "no review of that PR" }, 404);
6529
6977
  });
6530
6978
  app.get("/api/reviews/:repo/:number/diff", async (c) => {
6531
6979
  const repo = c.req.param("repo");
6532
- const n = num2(c.req.param("number"));
6980
+ const n = num3(c.req.param("number"));
6533
6981
  const r = n === null ? null : deps.read(repo, n);
6534
6982
  const at = deps.repoPath(repo);
6535
6983
  if (!r || n === null || !r.mergeBase || !at) return c.json({ error: "no prepared review of that PR" }, 404);
@@ -6538,7 +6986,7 @@ function mountReviewRoutes(app, deps) {
6538
6986
  });
6539
6987
  app.post("/api/reviews/:repo/:number", async (c) => {
6540
6988
  const repo = c.req.param("repo");
6541
- const n = num2(c.req.param("number"));
6989
+ const n = num3(c.req.param("number"));
6542
6990
  if (n === null) return c.json({ error: "not a PR number" }, 400);
6543
6991
  const r = await deps.runNow(repo, n);
6544
6992
  changed(repo, n);
@@ -6546,7 +6994,7 @@ function mountReviewRoutes(app, deps) {
6546
6994
  });
6547
6995
  app.post("/api/reviews/:repo/:number/discussion", async (c) => {
6548
6996
  const repo = c.req.param("repo");
6549
- const n = num2(c.req.param("number"));
6997
+ const n = num3(c.req.param("number"));
6550
6998
  if (n === null || !deps.read(repo, n)) return c.json({ error: "no review of that PR" }, 404);
6551
6999
  const was = deps.read(repo, n)?.discussion?.at;
6552
7000
  const r = await deps.refreshDiscussion(repo, n);
@@ -6556,7 +7004,7 @@ function mountReviewRoutes(app, deps) {
6556
7004
  });
6557
7005
  app.post("/api/reviews/:repo/:number/drafts", async (c) => {
6558
7006
  const repo = c.req.param("repo");
6559
- const n = num2(c.req.param("number"));
7007
+ const n = num3(c.req.param("number"));
6560
7008
  if (n === null || !deps.read(repo, n)) return c.json({ error: "no review of that PR" }, 404);
6561
7009
  const body = await c.req.json().catch(() => null);
6562
7010
  let error = null;
@@ -6574,7 +7022,7 @@ function mountReviewRoutes(app, deps) {
6574
7022
  });
6575
7023
  app.post("/api/reviews/:repo/:number/submit", async (c) => {
6576
7024
  const repo = c.req.param("repo");
6577
- const n = num2(c.req.param("number"));
7025
+ const n = num3(c.req.param("number"));
6578
7026
  if (n === null) return c.json({ error: "no review of that PR" }, 404);
6579
7027
  const input = await c.req.json().catch(() => null);
6580
7028
  const out = await submitPrReview(deps, repo, n, input);
@@ -6584,7 +7032,7 @@ function mountReviewRoutes(app, deps) {
6584
7032
  });
6585
7033
  app.post("/api/reviews/:repo/:number/fix-myself", async (c) => {
6586
7034
  const repo = c.req.param("repo");
6587
- const n = num2(c.req.param("number"));
7035
+ const n = num3(c.req.param("number"));
6588
7036
  if (n === null || !deps.read(repo, n)) return c.json({ error: "no review of that PR" }, 404);
6589
7037
  if (!deps.fixMyself) return c.json({ error: "not available on this server" }, 501);
6590
7038
  const input = await c.req.json().catch(() => null);
@@ -6597,7 +7045,7 @@ function mountReviewRoutes(app, deps) {
6597
7045
  });
6598
7046
  app.post("/api/reviews/:repo/:number/in-doubt", async (c) => {
6599
7047
  const repo = c.req.param("repo");
6600
- const n = num2(c.req.param("number"));
7048
+ const n = num3(c.req.param("number"));
6601
7049
  if (n === null || !deps.read(repo, n)) return c.json({ error: "no review of that PR" }, 404);
6602
7050
  const body = await c.req.json().catch(() => null);
6603
7051
  if (!body || typeof body.went !== "boolean") return c.json({ error: "expected {went: true|false}" }, 400);
@@ -6608,7 +7056,7 @@ function mountReviewRoutes(app, deps) {
6608
7056
  });
6609
7057
  app.delete("/api/reviews/:repo/:number/dropped", (c) => {
6610
7058
  const repo = c.req.param("repo");
6611
- const n = num2(c.req.param("number"));
7059
+ const n = num3(c.req.param("number"));
6612
7060
  const next = n === null ? null : deps.update(repo, n, clearDropped);
6613
7061
  if (!next || n === null) return c.json({ error: "no review of that PR" }, 404);
6614
7062
  changed(repo, n);
@@ -6616,7 +7064,7 @@ function mountReviewRoutes(app, deps) {
6616
7064
  });
6617
7065
  app.delete("/api/reviews/:repo/:number/drafts/:id", (c) => {
6618
7066
  const repo = c.req.param("repo");
6619
- const n = num2(c.req.param("number"));
7067
+ const n = num3(c.req.param("number"));
6620
7068
  if (n === null || !deps.read(repo, n)) return c.json({ error: "no review of that PR" }, 404);
6621
7069
  const id = c.req.param("id");
6622
7070
  let refused = null;
@@ -6639,41 +7087,41 @@ function mountReviewRoutes(app, deps) {
6639
7087
  // src/core/review/review-tree.ts
6640
7088
  import { randomBytes } from "crypto";
6641
7089
  import fs12 from "fs";
6642
- import path12 from "path";
7090
+ import path13 from "path";
6643
7091
 
6644
7092
  // src/core/review/review-source.ts
6645
7093
  var reviewRef = (number) => `refs/work/review/${number}`;
6646
7094
  var ATTR_CHUNK = 200;
6647
- var git2 = (run, cwd, ...args) => run("git", args, cwd);
6648
- async function preparePr(run, repoPath, host, pr) {
7095
+ var git2 = (run2, cwd, ...args) => run2("git", args, cwd);
7096
+ async function preparePr(run2, repoPath, host, pr) {
6649
7097
  const ref = reviewRef(pr.number);
6650
- const head = await git2(run, repoPath, "fetch", "--quiet", "--no-tags", "origin", `+${host.prRef(pr.number)}:${ref}`);
7098
+ const head = await git2(run2, repoPath, "fetch", "--quiet", "--no-tags", "origin", `+${host.prRef(pr.number)}:${ref}`);
6651
7099
  if (head.code !== 0)
6652
7100
  return { ok: false, error: `couldn't fetch the PR's code: ${head.stderr.trim().split("\n")[0] || "git fetch failed"}` };
6653
7101
  if (host.prRefIsMerge) {
6654
- const second = await git2(run, repoPath, "rev-parse", "--verify", "--quiet", `${ref}^2`);
7102
+ const second = await git2(run2, repoPath, "rev-parse", "--verify", "--quiet", `${ref}^2`);
6655
7103
  const tip = second.stdout.trim();
6656
7104
  if (second.code !== 0 || !tip) return { ok: false, error: "the PR's merge ref has no second parent: can't tell its head" };
6657
- const moved = await git2(run, repoPath, "update-ref", ref, tip);
7105
+ const moved = await git2(run2, repoPath, "update-ref", ref, tip);
6658
7106
  if (moved.code !== 0) return { ok: false, error: `couldn't keep the PR's head: ${moved.stderr.trim().split(/\r?\n/)[0]}` };
6659
7107
  }
6660
- if (pr.base) await git2(run, repoPath, "fetch", "--quiet", "--no-tags", "origin", `+refs/heads/${pr.base}:refs/remotes/origin/${pr.base}`);
6661
- const sha = (await git2(run, repoPath, "rev-parse", ref)).stdout.trim();
7108
+ if (pr.base) await git2(run2, repoPath, "fetch", "--quiet", "--no-tags", "origin", `+refs/heads/${pr.base}:refs/remotes/origin/${pr.base}`);
7109
+ const sha = (await git2(run2, repoPath, "rev-parse", ref)).stdout.trim();
6662
7110
  const baseRef = pr.base ? `refs/remotes/origin/${pr.base}` : "origin/HEAD";
6663
- const mb = await git2(run, repoPath, "merge-base", baseRef, ref);
7111
+ const mb = await git2(run2, repoPath, "merge-base", baseRef, ref);
6664
7112
  if (mb.code !== 0 || !mb.stdout.trim()) return { ok: false, error: `no common commit with ${pr.base || "the default branch"}` };
6665
7113
  const mergeBase = mb.stdout.trim();
6666
- const files = await reviewDiff(run, repoPath, mergeBase, ref);
7114
+ const files = await reviewDiff(run2, repoPath, mergeBase, ref);
6667
7115
  if (!files) return { ok: false, error: "git couldn't diff the PR" };
6668
- return { ok: true, files, extras: await diffExtras(run, repoPath, mergeBase, ref, files), mergeBase, headSha: sha };
7116
+ return { ok: true, files, extras: await diffExtras(run2, repoPath, mergeBase, ref, files), mergeBase, headSha: sha };
6669
7117
  }
6670
- async function reviewDiff(run, repoPath, from, to) {
6671
- const d = await git2(run, repoPath, "diff", "--no-color", "--no-ext-diff", "-M", from, to);
7118
+ async function reviewDiff(run2, repoPath, from, to) {
7119
+ const d = await git2(run2, repoPath, "diff", "--no-color", "--no-ext-diff", "-M", from, to);
6672
7120
  return d.code === 0 ? parseGitDiff(d.stdout) : null;
6673
7121
  }
6674
- async function diffExtras(run, repoPath, from, to, files) {
7122
+ async function diffExtras(run2, repoPath, from, to, files) {
6675
7123
  const changed = files.filter((f) => f.added + f.deleted > 0).map((f) => f.path);
6676
- const w = await git2(run, repoPath, "diff", "--no-color", "--no-ext-diff", "-M", "-w", "--name-only", from, to);
7124
+ const w = await git2(run2, repoPath, "diff", "--no-color", "--no-ext-diff", "-M", "-w", "--name-only", from, to);
6677
7125
  const real = new Set(
6678
7126
  w.code === 0 ? w.stdout.split("\n").map((l) => l.trim()).filter(Boolean) : changed
6679
7127
  );
@@ -6681,7 +7129,7 @@ async function diffExtras(run, repoPath, from, to, files) {
6681
7129
  const generated = /* @__PURE__ */ new Set();
6682
7130
  const paths = files.map((f) => f.path);
6683
7131
  for (let i = 0; i < paths.length; i += ATTR_CHUNK) {
6684
- const attr = await git2(run, repoPath, "check-attr", `--source=${to}`, "linguist-generated", "--", ...paths.slice(i, i + ATTR_CHUNK));
7132
+ const attr = await git2(run2, repoPath, "check-attr", `--source=${to}`, "linguist-generated", "--", ...paths.slice(i, i + ATTR_CHUNK));
6685
7133
  if (attr.code !== 0) break;
6686
7134
  for (const line of attr.stdout.split("\n")) {
6687
7135
  const m = /^(.*): linguist-generated: (set|true)$/.exec(line.trim());
@@ -6690,18 +7138,18 @@ async function diffExtras(run, repoPath, from, to, files) {
6690
7138
  }
6691
7139
  return { whitespaceOnly, generated };
6692
7140
  }
6693
- async function dropReviewRef(run, repoPath, number) {
6694
- await git2(run, repoPath, "update-ref", "-d", reviewRef(number));
7141
+ async function dropReviewRef(run2, repoPath, number) {
7142
+ await git2(run2, repoPath, "update-ref", "-d", reviewRef(number));
6695
7143
  }
6696
7144
 
6697
7145
  // src/core/review/review-tree.ts
6698
- var reviewTreesDir = () => path12.join(getConfigDir(), "review-trees");
7146
+ var reviewTreesDir = () => path13.join(getConfigDir(), "review-trees");
6699
7147
  var NO_HOOKS = ".no-hooks";
6700
7148
  var NO_LFS = ["-c", "filter.lfs.smudge=", "-c", "filter.lfs.process=", "-c", "filter.lfs.required=false"];
6701
7149
  var NO_LFS_ENV = { GIT_LFS_SKIP_SMUDGE: "1" };
6702
- function reviewTreeName(alias, number, headSha, run) {
7150
+ function reviewTreeName(alias, number, headSha, run2) {
6703
7151
  const safe = alias.replace(/[^A-Za-z0-9._-]/g, "_").replace(/^\.+/, "_") || "repo";
6704
- const tag = run.replace(/[^A-Za-z0-9]/g, "");
7152
+ const tag = run2.replace(/[^A-Za-z0-9]/g, "");
6705
7153
  return `${safe}-${number}-${headSha.slice(0, 8)}${tag ? `-${tag}` : ""}`;
6706
7154
  }
6707
7155
  var runSuffix = () => `${process.pid.toString(36)}${randomBytes(3).toString("hex")}`;
@@ -6713,13 +7161,13 @@ function rmTree(dir) {
6713
7161
  }
6714
7162
  return !fs12.existsSync(dir);
6715
7163
  }
6716
- async function createReviewTree(run, at, opts) {
7164
+ async function createReviewTree(run2, at, opts) {
6717
7165
  const root = opts.root ?? reviewTreesDir();
6718
- const dir = path12.join(root, reviewTreeName(at.alias, at.number, at.headSha, opts.run ?? runSuffix()));
6719
- const noHooks = path12.join(root, NO_HOOKS);
7166
+ const dir = path13.join(root, reviewTreeName(at.alias, at.number, at.headSha, opts.run ?? runSuffix()));
7167
+ const noHooks = path13.join(root, NO_HOOKS);
6720
7168
  fs12.mkdirSync(noHooks, { recursive: true });
6721
- if (fs12.existsSync(dir)) await removeReviewTree(run, at.repoPath, dir);
6722
- const added = await run(
7169
+ if (fs12.existsSync(dir)) await removeReviewTree(run2, at.repoPath, dir);
7170
+ const added = await run2(
6723
7171
  "git",
6724
7172
  [
6725
7173
  "-c",
@@ -6738,58 +7186,58 @@ async function createReviewTree(run, at, opts) {
6738
7186
  NO_LFS_ENV
6739
7187
  );
6740
7188
  if (added.code !== 0) {
6741
- await removeReviewTree(run, at.repoPath, dir);
7189
+ await removeReviewTree(run2, at.repoPath, dir);
6742
7190
  return { ok: false, error: `couldn't check the PR out: ${firstLine(added.stderr) || "git worktree add failed"}` };
6743
7191
  }
6744
- const head = await run("git", ["rev-parse", "HEAD"], dir);
7192
+ const head = await run2("git", ["rev-parse", "HEAD"], dir);
6745
7193
  if (head.code !== 0 || head.stdout.trim() !== at.headSha) {
6746
- await removeReviewTree(run, at.repoPath, dir);
7194
+ await removeReviewTree(run2, at.repoPath, dir);
6747
7195
  return { ok: false, error: "the checkout isn't at the reviewed commit (the PR moved meanwhile)" };
6748
7196
  }
6749
- const listed = await run("git", ["ls-files", "-z"], dir);
7197
+ const listed = await run2("git", ["ls-files", "-z"], dir);
6750
7198
  if (listed.code !== 0) {
6751
- await removeReviewTree(run, at.repoPath, dir);
7199
+ await removeReviewTree(run2, at.repoPath, dir);
6752
7200
  return { ok: false, error: "couldn't list the checkout's files to remove its settings" };
6753
7201
  }
6754
7202
  const removed = [];
6755
7203
  for (const rel of listed.stdout.split("\0").filter((rel2) => opts.strip(rel2))) {
6756
- const file = path12.join(dir, rel);
7204
+ const file = path13.join(dir, rel);
6757
7205
  fs12.rmSync(file, { recursive: true, force: true });
6758
7206
  if (fs12.existsSync(file)) {
6759
- await removeReviewTree(run, at.repoPath, dir);
7207
+ await removeReviewTree(run2, at.repoPath, dir);
6760
7208
  return { ok: false, error: `couldn't remove ${rel} from the checkout` };
6761
7209
  }
6762
7210
  removed.push(rel);
6763
7211
  }
6764
7212
  return { ok: true, dir, removed };
6765
7213
  }
6766
- async function removeReviewTree(run, repoPath, dir) {
6767
- if (fs12.existsSync(dir)) await run("git", ["worktree", "remove", "--force", "--force", dir], repoPath);
7214
+ async function removeReviewTree(run2, repoPath, dir) {
7215
+ if (fs12.existsSync(dir)) await run2("git", ["worktree", "remove", "--force", "--force", dir], repoPath);
6768
7216
  const gone = rmTree(dir);
6769
- await run("git", ["worktree", "prune"], repoPath);
7217
+ await run2("git", ["worktree", "prune"], repoPath);
6770
7218
  return gone;
6771
7219
  }
6772
- async function withReviewTree(run, at, use, opts) {
6773
- const tree = await createReviewTree(run, at, opts);
7220
+ async function withReviewTree(run2, at, use, opts) {
7221
+ const tree = await createReviewTree(run2, at, opts);
6774
7222
  if (!tree.ok) return tree;
6775
7223
  let value;
6776
7224
  let gone;
6777
7225
  try {
6778
7226
  value = await use(tree.dir, tree.removed);
6779
7227
  } finally {
6780
- gone = await removeReviewTree(run, at.repoPath, tree.dir).catch(() => false);
7228
+ gone = await removeReviewTree(run2, at.repoPath, tree.dir).catch(() => false);
6781
7229
  }
6782
7230
  return { ok: true, value, ...gone ? {} : { left: tree.dir } };
6783
7231
  }
6784
7232
  function gitDirOf(dir) {
6785
7233
  try {
6786
- const m = /^gitdir:\s*(.+)$/m.exec(fs12.readFileSync(path12.join(dir, ".git"), "utf8"));
6787
- return m ? path12.resolve(dir, m[1].trim(), "..", "..") : null;
7234
+ const m = /^gitdir:\s*(.+)$/m.exec(fs12.readFileSync(path13.join(dir, ".git"), "utf8"));
7235
+ return m ? path13.resolve(dir, m[1].trim(), "..", "..") : null;
6788
7236
  } catch {
6789
7237
  return null;
6790
7238
  }
6791
7239
  }
6792
- async function sweepReviewTrees(run, opts = {}) {
7240
+ async function sweepReviewTrees(run2, opts = {}) {
6793
7241
  const root = opts.root ?? reviewTreesDir();
6794
7242
  const now = opts.now?.() ?? Date.now();
6795
7243
  const swept = [];
@@ -6801,14 +7249,14 @@ async function sweepReviewTrees(run, opts = {}) {
6801
7249
  return { swept, failed };
6802
7250
  }
6803
7251
  for (const name of names) {
6804
- const dir = path12.join(root, name);
7252
+ const dir = path13.join(root, name);
6805
7253
  try {
6806
7254
  if (opts.olderThanMs && now - fs12.statSync(dir).mtimeMs < opts.olderThanMs) continue;
6807
7255
  } catch {
6808
7256
  continue;
6809
7257
  }
6810
7258
  const gitDir = gitDirOf(dir);
6811
- const gone = gitDir && fs12.existsSync(gitDir) ? await removeReviewTree(run, gitDir, dir) : rmTree(dir);
7259
+ const gone = gitDir && fs12.existsSync(gitDir) ? await removeReviewTree(run2, gitDir, dir) : rmTree(dir);
6812
7260
  (gone ? swept : failed).push(name);
6813
7261
  }
6814
7262
  return { swept, failed };
@@ -7006,8 +7454,8 @@ function createReviewQueue(deps) {
7006
7454
  }
7007
7455
  }
7008
7456
  async function sweepNow() {
7009
- const run = deps.activity?.start("reviews", "Preparing PR reviews");
7010
- const note = (text, level = "info") => run?.note(text, { level });
7457
+ const run2 = deps.activity?.start("reviews", "Preparing PR reviews");
7458
+ const note = (text, level = "info") => run2?.note(text, { level });
7011
7459
  const { maxPerDay } = deps.limits();
7012
7460
  const asked = [];
7013
7461
  const open = /* @__PURE__ */ new Set();
@@ -7096,9 +7544,9 @@ function createReviewQueue(deps) {
7096
7544
  note(`${talk.length - DISCUSSIONS_PER_SWEEP} more discussions to read again: the next sweep`);
7097
7545
  if (read) note(`read the discussion of ${plural2(read, "PR")} again (moved on the host, or half an hour old)`);
7098
7546
  deps.changed();
7099
- run?.done(todo.length ? `${plural2(todo.length, "PR")} looked at` : read ? `${plural2(read, "discussion")} read again` : "nothing new");
7547
+ run2?.done(todo.length ? `${plural2(todo.length, "PR")} looked at` : read ? `${plural2(read, "discussion")} read again` : "nothing new");
7100
7548
  } catch (err) {
7101
- run?.fail(err.message);
7549
+ run2?.fail(err.message);
7102
7550
  }
7103
7551
  }
7104
7552
  return {
@@ -7116,11 +7564,11 @@ function createReviewQueue(deps) {
7116
7564
  if (!list.ok) return { ok: false, error: list.error };
7117
7565
  const pr = list.prs.find((p) => p.number === number);
7118
7566
  if (!pr) return { ok: false, error: `#${number} isn't an open pull request of ${repo}` };
7119
- const run = deps.activity?.start("reviews", `Preparing the review of ${repo} #${number}`);
7120
- const note = (text, level = "info") => run?.note(text, { level });
7567
+ const run2 = deps.activity?.start("reviews", `Preparing the review of ${repo} #${number}`);
7568
+ const note = (text, level = "info") => run2?.note(text, { level });
7121
7569
  const r = await oneAtATime2(() => prepareOne(project, metaOf(repo, host, pr), pr, false, note));
7122
- if (r.ok) run?.done(`prepared${r.how ? `; ${r.how}` : ""}`);
7123
- else run?.fail(r.error);
7570
+ if (r.ok) run2?.done(`prepared${r.how ? `; ${r.how}` : ""}`);
7571
+ else run2?.fail(r.error);
7124
7572
  return r.ok ? { ok: true, review: r.review } : { ok: false, error: r.error };
7125
7573
  },
7126
7574
  async refreshDiscussion(repo, number) {
@@ -7282,7 +7730,7 @@ function startReviewSweeps(opts) {
7282
7730
  }
7283
7731
 
7284
7732
  // src/core/diff/session-history.ts
7285
- import path13 from "path";
7733
+ import path14 from "path";
7286
7734
 
7287
7735
  // src/core/diff/diff-points.ts
7288
7736
  var SHA = /^[0-9a-f]{7,40}$/;
@@ -7378,12 +7826,12 @@ async function sessionHistory(session, others = []) {
7378
7826
  });
7379
7827
  if (diffArg === "HEAD") continue;
7380
7828
  const log = await g(["log", `-n${MAX_COMMITS2}`, "--format=%H%x1f%cI%x1f%s", `${diffArg}..HEAD`, "--"], root);
7381
- if (log.ok && log.out) commits.push(...parseLog(log.out, path13.basename(root)));
7829
+ if (log.ok && log.out) commits.push(...parseLog(log.out, path14.basename(root)));
7382
7830
  }
7383
7831
  for (const b of others) {
7384
7832
  const tip = await tipOf(b);
7385
7833
  if (!tip) continue;
7386
- const repo = path13.basename(b.path);
7834
+ const repo = path14.basename(b.path);
7387
7835
  const start = liveStart(b) ?? b.start;
7388
7836
  let list = [];
7389
7837
  let base;
@@ -7444,7 +7892,7 @@ function parseLog(stdout, repo) {
7444
7892
  return out;
7445
7893
  }
7446
7894
  function computeSessionRange(session, from, to) {
7447
- const paths = session.paths.map((p) => path13.resolve(p));
7895
+ const paths = session.paths.map((p) => path14.resolve(p));
7448
7896
  const refs = rangeRefs(paths, loadManifest(scopeHashForPaths(paths)).entries, from, to);
7449
7897
  if ("error" in refs) return refs;
7450
7898
  return { repos: refs.map((r) => ({ name: r.name, root: r.root, files: computeRangeDiff(r) })) };
@@ -7463,17 +7911,17 @@ async function sessionHistoryWire(session) {
7463
7911
  }
7464
7912
 
7465
7913
  // src/server/routes/revert-routes.ts
7466
- import path15 from "path";
7914
+ import path16 from "path";
7467
7915
  import { zValidator as zValidator7 } from "@hono/zod-validator";
7468
7916
  import { z as z6 } from "zod";
7469
7917
 
7470
7918
  // src/core/diff/revert.ts
7471
7919
  import fs14 from "fs";
7472
- import path14 from "path";
7920
+ import path15 from "path";
7473
7921
  function inside(root, rel) {
7474
- const abs = path14.resolve(root, rel);
7475
- const back = path14.relative(path14.resolve(root), abs);
7476
- if (!back || back.startsWith("..") || path14.isAbsolute(back)) return null;
7922
+ const abs = path15.resolve(root, rel);
7923
+ const back = path15.relative(path15.resolve(root), abs);
7924
+ if (!back || back.startsWith("..") || path15.isAbsolute(back)) return null;
7477
7925
  return abs;
7478
7926
  }
7479
7927
  function inHead(root, rel) {
@@ -7586,8 +8034,8 @@ function mountRevertRoutes(app, opts) {
7586
8034
  if (!session) return c.json({ error: "unknown session" }, 404);
7587
8035
  const body = c.req.valid("json");
7588
8036
  const repo = opts.uncommitted(session).find((r) => r.name === body.repo);
7589
- const allowed = new Set(session.paths.map((p) => path15.resolve(p).toLowerCase()));
7590
- if (!repo || !allowed.has(path15.resolve(repo.root).toLowerCase())) {
8037
+ const allowed = new Set(session.paths.map((p) => path16.resolve(p).toLowerCase()));
8038
+ if (!repo || !allowed.has(path16.resolve(repo.root).toLowerCase())) {
7591
8039
  return c.json({ error: `unknown repo: ${body.repo}` }, 404);
7592
8040
  }
7593
8041
  const file = repo.files.find((f) => f.path === body.path);
@@ -7745,10 +8193,10 @@ function mountCiRoutes(app, opts) {
7745
8193
 
7746
8194
  // src/core/diff/diffs-sweep.ts
7747
8195
  import fs16 from "fs";
7748
- import path16 from "path";
8196
+ import path17 from "path";
7749
8197
  var SWEEP_AFTER_DAYS = 30;
7750
8198
  var DISPOSABLE = /\.(html|log)$/i;
7751
- function sweepOldDiffArtifacts(now = Date.now(), maxAgeDays = SWEEP_AFTER_DAYS, dir = path16.join(getConfigDir(), "diffs")) {
8199
+ function sweepOldDiffArtifacts(now = Date.now(), maxAgeDays = SWEEP_AFTER_DAYS, dir = path17.join(getConfigDir(), "diffs")) {
7752
8200
  const cutoff = now - maxAgeDays * 24 * 60 * 60 * 1e3;
7753
8201
  let removed = 0;
7754
8202
  let bytes = 0;
@@ -7760,7 +8208,7 @@ function sweepOldDiffArtifacts(now = Date.now(), maxAgeDays = SWEEP_AFTER_DAYS,
7760
8208
  }
7761
8209
  for (const name of names) {
7762
8210
  if (!DISPOSABLE.test(name)) continue;
7763
- const file = path16.join(dir, name);
8211
+ const file = path17.join(dir, name);
7764
8212
  try {
7765
8213
  const st = fs16.statSync(file);
7766
8214
  if (!st.isFile() || st.mtimeMs >= cutoff) continue;
@@ -7974,6 +8422,39 @@ function mountAgentRestartRoutes(app, opts) {
7974
8422
  // src/server/routes/account-routes.ts
7975
8423
  import { zValidator as zValidator8 } from "@hono/zod-validator";
7976
8424
  import { z as z7 } from "zod";
8425
+
8426
+ // src/core/sessions/account-switch-all.ts
8427
+ function sessionsToSwitch(sessions, accountOf, to, from) {
8428
+ return sessions.filter((s) => !s.archivedAt && accountOf(s) !== to && (from === void 0 || accountOf(s) === from));
8429
+ }
8430
+ async function switchAllSessions(deps, to, from) {
8431
+ const rows = [];
8432
+ for (const s of sessionsToSwitch(deps.sessions(), deps.accountOf, to, from)) {
8433
+ const id = deps.idOf(s);
8434
+ const label = `${s.target} \xB7 ${s.branch}`;
8435
+ const r = await deps.switchAccount(id, to).catch((err) => ({
8436
+ ok: false,
8437
+ status: 502,
8438
+ error: err instanceof Error ? err.message : String(err)
8439
+ }));
8440
+ rows.push(r.ok ? { id, label, outcome: r.outcome } : { id, label, error: r.error });
8441
+ }
8442
+ return rows;
8443
+ }
8444
+ function switchAllSummary(rows, to) {
8445
+ if (rows.length === 0) return `No session to move: every one is on ${to} already.`;
8446
+ const n = (o) => rows.filter((r) => r.outcome === o).length;
8447
+ const moved = rows.filter((r) => r.outcome).length;
8448
+ const refused = rows.length - moved;
8449
+ const parts = [
8450
+ n("switched") ? `${n("switched")} restarted on it` : "",
8451
+ n("queued") ? `${n("queued")} when its turn ends` : "",
8452
+ n("recorded") ? `${n("recorded")} on its next start` : ""
8453
+ ].filter(Boolean);
8454
+ return `${moved} session${moved === 1 ? "" : "s"} moved to ${to}${parts.length ? `: ${parts.join(", ")}` : ""}` + (refused ? `; ${refused} refused` : "");
8455
+ }
8456
+
8457
+ // src/server/routes/account-routes.ts
7977
8458
  function mountAccountRoutes(app, opts) {
7978
8459
  const accountsNow = opts.accounts ?? (() => agentFor(loadConfig()).accounts);
7979
8460
  const readings = opts.readings ?? (() => agentFor(loadConfig()).usage?.read() ?? []);
@@ -8078,6 +8559,26 @@ function mountAccountRoutes(app, opts) {
8078
8559
  return c.json({ error: e instanceof Error ? e.message : String(e) }, 502);
8079
8560
  }
8080
8561
  });
8562
+ app.post("/api/accounts/:name/sessions", zValidator8("json", z7.object({ from: z7.string().min(1).max(64).optional() })), async (c) => {
8563
+ if (opts.lookOnly) return c.json({ error: opts.lookOnly }, 409);
8564
+ const to = c.req.param("name");
8565
+ const { from } = c.req.valid("json");
8566
+ const rows = await switchAllSessions(
8567
+ {
8568
+ sessions,
8569
+ accountOf: (s) => s.account ?? DEFAULT_ACCOUNT,
8570
+ idOf: sessionIdFor,
8571
+ switchAccount: (id, name) => opts.switcher.switchAccount(id, name)
8572
+ },
8573
+ to,
8574
+ from
8575
+ );
8576
+ if (rows.length > 0 && rows.every((r) => r.error) && new Set(rows.map((r) => r.error)).size === 1)
8577
+ return c.json({ error: rows[0].error ?? "" }, 409);
8578
+ opts.broadcast("sessions-changed", { ts: Date.now() });
8579
+ changed();
8580
+ return c.json({ ok: true, summary: switchAllSummary(rows, to), sessions: rows });
8581
+ });
8081
8582
  app.post("/api/sessions/:id/account", zValidator8("json", z7.object({ to: z7.string().min(1).max(64) })), async (c) => {
8082
8583
  if (opts.lookOnly) return c.json({ error: opts.lookOnly }, 409);
8083
8584
  const r = await opts.switcher.switchAccount(c.req.param("id"), c.req.valid("json").to).catch((err) => ({
@@ -8101,9 +8602,9 @@ function mountAccountRoutes(app, opts) {
8101
8602
 
8102
8603
  // src/core/sessions/account-skills-child.ts
8103
8604
  var lastLine = (text) => text.split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? "";
8104
- function accountSkillsInChild(workBin, run = runWorkChild) {
8605
+ function accountSkillsInChild(workBin, run2 = runWorkChild) {
8105
8606
  return async (name) => {
8106
- const r = await run(workBin(), ["account", "skills", name], { timeoutMs: 5 * 6e4 });
8607
+ const r = await run2(workBin(), ["account", "skills", name], { timeoutMs: 5 * 6e4 });
8107
8608
  if (r.spawnError) return { ok: false, message: `couldn't start work: ${r.spawnError}` };
8108
8609
  if (r.timedOut) return { ok: false, message: "installing work\u2019s skills took too long" };
8109
8610
  const said = lastLine(r.stdout) || lastLine(r.stderr);
@@ -8263,10 +8764,11 @@ function sleepChecks() {
8263
8764
  }
8264
8765
 
8265
8766
  // src/server/web-server.ts
8767
+ var LEFTOVERS_EVERY_MS = 60 * 6e4;
8266
8768
  function computeSessionDiff(s, base) {
8267
8769
  const resolved = s.paths.map((p) => resolveRepoDiff(p, base, s.baseBranches?.[p] ?? s.baseBranch));
8268
8770
  const repos = s.paths.map((p, i) => ({
8269
- name: path17.basename(p),
8771
+ name: path18.basename(p),
8270
8772
  root: p,
8271
8773
  resolvedBase: resolved[i].resolvedBase,
8272
8774
  files: computeDiff({ root: p, diffArg: resolved[i].diffArg })
@@ -8370,7 +8872,7 @@ async function startWebServer(opts = {}) {
8370
8872
  }, 500);
8371
8873
  }
8372
8874
  });
8373
- const repoNames = (s) => s.isGroup ? s.paths.map((p) => path17.basename(p)) : [s.target];
8875
+ const repoNames = (s) => s.isGroup ? s.paths.map((p) => path18.basename(p)) : [s.target];
8374
8876
  const diffStatFor = (id, s, hasStatus) => wantsDiffStat(s, hasStatus) ? diffStats.get(id, s.paths, repoNames(s)) : null;
8375
8877
  const archivedRow = createArchivedRows();
8376
8878
  app.get("/api/sessions", (c) => {
@@ -8515,7 +9017,11 @@ async function startWebServer(opts = {}) {
8515
9017
  },
8516
9018
  activity,
8517
9019
  // The PR merged: nothing waiting in it holds it up — the archive keeps it.
8518
- archive: (id) => archiveMergedSession(id, defaultArchiveDeps({ release: releaseSession }), () => broadcast("sessions-changed", { ts: Date.now() }))
9020
+ archive: (id) => archiveMergedSession(
9021
+ id,
9022
+ defaultArchiveDeps({ release: releaseSession, removeWorktree: removeWorktreeInChild(getWorkBin) }),
9023
+ () => broadcast("sessions-changed", { ts: Date.now() })
9024
+ )
8519
9025
  });
8520
9026
  const stopPrWatch = lean ? null : prWatch.start(dev ? 10 * 6e4 : 18e4);
8521
9027
  const SLEEP_EVERY_MS = 5 * 6e4;
@@ -8538,12 +9044,12 @@ async function startWebServer(opts = {}) {
8538
9044
  busy: restartBusy,
8539
9045
  running: peekPty,
8540
9046
  report: (notes) => {
8541
- const run = activity.start("agents", "Restarting agents");
9047
+ const run2 = activity.start("agents", "Restarting agents");
8542
9048
  for (const { id, text, level } of notes) {
8543
9049
  const s = findSession2(id);
8544
- run.note(`${s ? `${s.target} ${s.branch}` : id}: ${text}`, { level, sessionId: s ? id : void 0 });
9050
+ run2.note(`${s ? `${s.target} ${s.branch}` : id}: ${text}`, { level, sessionId: s ? id : void 0 });
8545
9051
  }
8546
- run.done(restartNotesSummary(notes));
9052
+ run2.done(restartNotesSummary(notes));
8547
9053
  },
8548
9054
  changed: () => {
8549
9055
  broadcast("agents-changed", { ts: Date.now() });
@@ -8583,7 +9089,7 @@ async function startWebServer(opts = {}) {
8583
9089
  const minutes = loadConfig()?.sleepIdleAfterMinutes ?? DEFAULT_SLEEP_AFTER_MINUTES;
8584
9090
  if (sleepAfterMs(minutes) === 0)
8585
9091
  return activity.skip("idle-sleep", "Looking for idle Claudes", "turned off (sleepIdleAfterMinutes: 0)");
8586
- const run = activity.start("idle-sleep", "Looking for idle Claudes");
9092
+ const run2 = activity.start("idle-sleep", "Looking for idle Claudes");
8587
9093
  const ptys = await listHostPtys().catch(() => []);
8588
9094
  const quiet = new Set(sleepCandidates(ptys, Date.now(), sleepAfterMs(minutes), agentBusy));
8589
9095
  const plan = await sleepPlan(
@@ -8592,7 +9098,7 @@ async function startWebServer(opts = {}) {
8592
9098
  );
8593
9099
  for (const { id, why } of plan.awake) {
8594
9100
  const s = findSession2(id);
8595
- run.note(`${s ? `${s.target} ${s.branch}` : id}: kept awake: ${why}`, { sessionId: s ? id : void 0 });
9101
+ run2.note(`${s ? `${s.target} ${s.branch}` : id}: kept awake: ${why}`, { sessionId: s ? id : void 0 });
8596
9102
  }
8597
9103
  const ids = plan.sleep;
8598
9104
  for (const id of ids) {
@@ -8602,16 +9108,16 @@ async function startWebServer(opts = {}) {
8602
9108
  async () => {
8603
9109
  await markAgentStopped(id).catch(() => {
8604
9110
  });
8605
- run.note(
9111
+ run2.note(
8606
9112
  `${s ? `${s.target} ${s.branch}` : id}: put its Claude to sleep (printed nothing for ${sleepAfterMs(minutes) / 6e4} min, nothing attached; opening it resumes the conversation)`,
8607
9113
  { level: "action", sessionId: id }
8608
9114
  );
8609
9115
  },
8610
- (err) => run.note(`${id}: couldn't stop its Claude: ${err.message}`, { level: "warn", sessionId: id })
9116
+ (err) => run2.note(`${id}: couldn't stop its Claude: ${err.message}`, { level: "warn", sessionId: id })
8611
9117
  );
8612
9118
  }
8613
9119
  const slept = ids.length;
8614
- run.done(`${ptys.length} Claude${ptys.length === 1 ? "" : "s"} running \xB7 ${slept ? `${slept} put to sleep` : "none idle long enough"}`);
9120
+ run2.done(`${ptys.length} Claude${ptys.length === 1 ? "" : "s"} running \xB7 ${slept ? `${slept} put to sleep` : "none idle long enough"}`);
8615
9121
  if (ids.length) broadcast("sessions-changed", { ts: Date.now() });
8616
9122
  };
8617
9123
  sleepSchedule?.next(Date.now() + SLEEP_EVERY_MS);
@@ -8650,15 +9156,15 @@ async function startWebServer(opts = {}) {
8650
9156
  const archiveUpkeep = () => {
8651
9157
  retentionSchedule?.next(Date.now() + RETENTION_EVERY_MS);
8652
9158
  const cfg = loadConfig()?.archive;
8653
- const run = activity.start("archive", "Compressing old archived conversations");
9159
+ const run2 = activity.start("archive", "Compressing old archived conversations");
8654
9160
  try {
8655
9161
  const r = applyArchiveRetention({ compressAfterDays: cfg?.compressAfterDays, dropAfterDays: cfg?.dropTranscriptsAfterDays });
8656
9162
  const mb = Math.round(r.bytesSaved / 1e6);
8657
- run.done(
9163
+ run2.done(
8658
9164
  r.compressed.length || r.dropped.length ? `${r.compressed.length} compressed${r.dropped.length ? `, ${r.dropped.length} conversations deleted (config)` : ""} \xB7 ${mb} MB freed` : "nothing old enough"
8659
9165
  );
8660
9166
  } catch (err) {
8661
- run.fail(err.message);
9167
+ run2.fail(err.message);
8662
9168
  }
8663
9169
  };
8664
9170
  const retentionFirst = !jobs ? null : setTimeout(archiveUpkeep, 3 * 6e4);
@@ -8674,18 +9180,18 @@ async function startWebServer(opts = {}) {
8674
9180
  conversationsSchedule?.next(Date.now() + CONVERSATIONS_EVERY_MS);
8675
9181
  if (conversationsBusy) return;
8676
9182
  conversationsBusy = true;
8677
- const run = activity.start("conversations", "Copying new conversation lines");
9183
+ const run2 = activity.start("conversations", "Copying new conversation lines");
8678
9184
  try {
8679
9185
  const r = await syncConversations(loadHistory().filter((s) => !s.archivedAt));
8680
9186
  const packed = await compressQuietCopies();
8681
- run.done(
9187
+ run2.done(
8682
9188
  [
8683
9189
  r.files ? `${r.sessions} session${r.sessions === 1 ? "" : "s"} \xB7 ${r.files} transcript${r.files === 1 ? "" : "s"} \xB7 ${Math.round(r.bytes / 1e3)} KB copied` : "all up to date",
8684
9190
  packed.files ? `${packed.files} quiet one${packed.files === 1 ? "" : "s"} compressed \xB7 ${Math.round(packed.bytesSaved / 1e6)} MB freed` : ""
8685
9191
  ].filter(Boolean).join(" \xB7 ")
8686
9192
  );
8687
9193
  } catch (err) {
8688
- run.fail(err.message);
9194
+ run2.fail(err.message);
8689
9195
  } finally {
8690
9196
  conversationsBusy = false;
8691
9197
  }
@@ -8751,7 +9257,7 @@ async function startWebServer(opts = {}) {
8751
9257
  blocksSchedule?.next(Date.now() + BLOCKS_EVERY_MS);
8752
9258
  if (blocksBusy || allBlocks().size === 0) return;
8753
9259
  blocksBusy = true;
8754
- const run = activity.start("blocks", "Checking what sessions wait on");
9260
+ const run2 = activity.start("blocks", "Checking what sessions wait on");
8755
9261
  try {
8756
9262
  const history = loadHistory();
8757
9263
  const live = new Set(history.filter((x) => !x.archivedAt).map((x) => sessionIdFor(x)));
@@ -8763,7 +9269,7 @@ async function startWebServer(opts = {}) {
8763
9269
  const r = await blockedPrState(url, defaultRunner);
8764
9270
  if (r && "rateLimited" in r) {
8765
9271
  ghRestUntil = Date.now() + 10 * 6e4;
8766
- run.note(`${r.host} API limit reached: resting 10 minutes`, { level: "warn" });
9272
+ run2.note(`${r.host} API limit reached: resting 10 minutes`, { level: "warn" });
8767
9273
  return null;
8768
9274
  }
8769
9275
  return r?.state ?? null;
@@ -8771,7 +9277,7 @@ async function startWebServer(opts = {}) {
8771
9277
  unblocked: async (id, done) => {
8772
9278
  const s = history.find((x) => sessionIdFor(x) === id);
8773
9279
  const name = s ? `${s.target} \xB7 ${s.branch}` : id;
8774
- run.note(`${name}: no longer waiting (${done.map((b) => b.label).join(", ")})`, { sessionId: id });
9280
+ run2.note(`${name}: no longer waiting (${done.map((b) => b.label).join(", ")})`, { sessionId: id });
8775
9281
  const event = {
8776
9282
  sessionId: id,
8777
9283
  kind: "unblocked",
@@ -8783,14 +9289,40 @@ async function startWebServer(opts = {}) {
8783
9289
  if (s) await stackDeps.tell(s, unblockedPrompt(done)).catch((err) => logSwallowed(`telling ${name} it is unblocked`, err));
8784
9290
  }
8785
9291
  });
8786
- run.done(freed.length ? `${freed.length} unblocked` : "still waiting");
9292
+ run2.done(freed.length ? `${freed.length} unblocked` : "still waiting");
8787
9293
  if (freed.length) broadcast("sessions-changed", { ts: Date.now() });
8788
9294
  } catch (err) {
8789
- run.fail(err.message);
9295
+ run2.fail(err.message);
8790
9296
  } finally {
8791
9297
  blocksBusy = false;
8792
9298
  }
8793
9299
  };
9300
+ const leftoversSchedule = !jobs ? null : activity.schedule("processes", "Processes left running", LEFTOVERS_EVERY_MS);
9301
+ let leftoversBusy = false;
9302
+ const sweepLeftoversNow = async () => {
9303
+ leftoversSchedule?.next(Date.now() + LEFTOVERS_EVERY_MS);
9304
+ if (leftoversBusy) return;
9305
+ leftoversBusy = true;
9306
+ const run2 = activity.start("processes", "Looking for processes left running");
9307
+ try {
9308
+ const found = await sweepLeftovers({
9309
+ sessions: () => loadHistory().filter((x) => !x.archivedAt).map((x) => ({ id: sessionIdFor(x), name: `${x.target} \xB7 ${x.branch}`, paths: x.paths })),
9310
+ list: () => listProcessUsage(),
9311
+ agentPid: ptyPid,
9312
+ note: (text, o) => run2.note(text, o)
9313
+ });
9314
+ if (found) run2.done(leftoverSummary(found));
9315
+ else run2.fail(leftoverSummary(found));
9316
+ } catch (err) {
9317
+ run2.fail(err.message);
9318
+ } finally {
9319
+ leftoversBusy = false;
9320
+ }
9321
+ };
9322
+ const leftoversFirst = !jobs ? null : setTimeout(() => void sweepLeftoversNow(), 10 * 6e4);
9323
+ leftoversFirst?.unref?.();
9324
+ const leftoversTimer = !jobs ? null : setInterval(() => void sweepLeftoversNow(), LEFTOVERS_EVERY_MS);
9325
+ leftoversTimer?.unref?.();
8794
9326
  const blocksTimer = !jobs ? null : setInterval(() => void sweepBlocksNow(), BLOCKS_EVERY_MS);
8795
9327
  blocksTimer?.unref?.();
8796
9328
  const offArchived = lean ? () => {
@@ -8867,7 +9399,13 @@ async function startWebServer(opts = {}) {
8867
9399
  const s = findSession2(id);
8868
9400
  if (s) scopeApi?.releaseSessionScope(s.paths, false);
8869
9401
  };
8870
- mountShipRoutes(app, { broadcast, onRepoChanged: (id) => diffStats.invalidate(id), release: releaseSession, create: makeWorktree });
9402
+ mountShipRoutes(app, {
9403
+ broadcast,
9404
+ onRepoChanged: (id) => diffStats.invalidate(id),
9405
+ release: releaseSession,
9406
+ create: makeWorktree,
9407
+ removeWorktree: removeWorktreeInChild(getWorkBin)
9408
+ });
8871
9409
  mountSessionRepoRoutes(app, {
8872
9410
  broadcast,
8873
9411
  run: addRepoInChild(getWorkBin),
@@ -8885,6 +9423,16 @@ async function startWebServer(opts = {}) {
8885
9423
  mountSessionOrderRoutes(app, { broadcast });
8886
9424
  mountRailRoutes(app, { broadcast });
8887
9425
  mountNoteRoutes(app, { broadcast });
9426
+ mountSessionReviewRoutes(app, {
9427
+ prepare: (session, repo) => prepareLocalReview(session, repo, {
9428
+ diff: (s) => computeSessionDiff(s, "branch"),
9429
+ agent: (prompt) => runInternal(prompt, 24e4, { lane: "localReviews" }),
9430
+ rules: () => rulesWith(loadConfig()?.reviews?.rules)
9431
+ }),
9432
+ tell: noteThroughComments(app),
9433
+ broadcast
9434
+ });
9435
+ mountSessionProcessRoutes(app, { list: () => listProcessUsage(), agentPid: ptyPid, kill: killTreeAsync });
8888
9436
  mountCodeRoutes(app);
8889
9437
  mountDiffSeenRoutes(app);
8890
9438
  mountDiffPageRoutes(app, { ensureScope: sessionScope });
@@ -8970,6 +9518,8 @@ async function startWebServer(opts = {}) {
8970
9518
  offArchived();
8971
9519
  offArchiving();
8972
9520
  if (blocksTimer) clearInterval(blocksTimer);
9521
+ if (leftoversTimer) clearInterval(leftoversTimer);
9522
+ if (leftoversFirst) clearTimeout(leftoversFirst);
8973
9523
  if (hostTick) clearInterval(hostTick);
8974
9524
  loop.stop();
8975
9525
  jiraWatch.stop();
@@ -9042,10 +9592,10 @@ function startAccountSync(deps) {
9042
9592
 
9043
9593
  // src/core/platform/autostart.ts
9044
9594
  import fs18 from "fs";
9045
- import path18 from "path";
9595
+ import path19 from "path";
9046
9596
  function startupScriptPath() {
9047
9597
  if (process.platform !== "win32" || !process.env.APPDATA) return null;
9048
- return path18.join(process.env.APPDATA, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "work-web.vbs");
9598
+ return path19.join(process.env.APPDATA, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "work-web.vbs");
9049
9599
  }
9050
9600
  function vbsQuote(s) {
9051
9601
  return '"' + s.replace(/"/g, '""') + '"';
@@ -9063,7 +9613,7 @@ function setAutostart(enabled, workBin) {
9063
9613
  const file = startupScriptPath();
9064
9614
  if (!file) throw new Error("Autostart is only supported on Windows so far.");
9065
9615
  if (enabled) {
9066
- fs18.mkdirSync(path18.dirname(file), { recursive: true });
9616
+ fs18.mkdirSync(path19.dirname(file), { recursive: true });
9067
9617
  fs18.writeFileSync(file, buildStartupScript(process.execPath, workBin), "utf-8");
9068
9618
  } else {
9069
9619
  try {
@@ -9074,14 +9624,489 @@ function setAutostart(enabled, workBin) {
9074
9624
  return file;
9075
9625
  }
9076
9626
 
9077
- // src/server/demo/demo-server.ts
9078
- import { Hono as Hono2 } from "hono";
9079
- import { streamSSE as streamSSE3 } from "hono/streaming";
9080
- import { WebSocketServer as WebSocketServer2 } from "ws";
9081
-
9082
- // src/server/demo/demo-repos.ts
9083
- var DemoRepoError = class extends Error {
9084
- constructor(message, sessions = []) {
9627
+ // src/server/demo/demo-reviews.ts
9628
+ async function demoHostSubmit(url, review) {
9629
+ if (review.body.includes("#timeout"))
9630
+ return {
9631
+ ok: false,
9632
+ error: "the host timed out (demo)",
9633
+ inDoubt: { comments: review.comments.map((_, i) => i), summary: !!review.body.trim() }
9634
+ };
9635
+ return { ok: true, url: `${url}#pullrequestreview-1` };
9636
+ }
9637
+ var hunk = (path21, lines, status = "modified") => {
9638
+ const added = lines.filter((l) => l.startsWith("+")).length;
9639
+ const deleted = lines.filter((l) => l.startsWith("-")).length;
9640
+ const context = lines.length - added - deleted;
9641
+ return [
9642
+ `diff --git a/${path21} b/${path21}`,
9643
+ ...status === "added" ? ["new file mode 100644", "index 0000000..1111111", "--- /dev/null"] : ["index 1111111..2222222 100644", `--- a/${path21}`],
9644
+ `+++ b/${path21}`,
9645
+ `@@ -${status === "added" ? 0 : 1},${status === "added" ? 0 : context + deleted} +1,${context + added} @@`,
9646
+ ...lines
9647
+ ].join("\n");
9648
+ };
9649
+ var DIFF = [
9650
+ hunk(
9651
+ "src/Shop.Api/Controllers/RefundsController.cs",
9652
+ [
9653
+ "+using System;",
9654
+ "+using Microsoft.AspNetCore.Mvc;",
9655
+ "+using Shop.Orders.Refunds;",
9656
+ "+",
9657
+ "+[ApiController]",
9658
+ '+[Route("orders/{orderId}/refunds")]',
9659
+ "+public class RefundsController(IRefundHandler refunds) : ControllerBase",
9660
+ "+{",
9661
+ "+ [HttpPost]",
9662
+ "+ public async Task<IActionResult> Create(Guid orderId, RefundRequest request)",
9663
+ "+ => Ok(await refunds.Handle(orderId, request));",
9664
+ "+}"
9665
+ ],
9666
+ "added"
9667
+ ),
9668
+ hunk(
9669
+ "src/Shop.Orders/Refunds/RefundHandler.cs",
9670
+ [
9671
+ "+public class RefundHandler(ShopDb db, IPayments payments) : IRefundHandler",
9672
+ "+{",
9673
+ "+ public async Task<RefundResult> Handle(Guid orderId, RefundRequest request)",
9674
+ "+ {",
9675
+ "+ var order = await db.Orders.FindAsync(orderId);",
9676
+ "+ await payments.Refund(order!.PaymentId, request.Amount);",
9677
+ "+ order.Refunded += request.Amount;",
9678
+ "+ await db.SaveChangesAsync();",
9679
+ "+ return new RefundResult(order.Refunded);",
9680
+ "+ }",
9681
+ "+}"
9682
+ ],
9683
+ "added"
9684
+ ),
9685
+ hunk(
9686
+ "src/Shop.Orders/Refunds/RefundValidator.cs",
9687
+ [
9688
+ "+public class RefundValidator : AbstractValidator<RefundRequest>",
9689
+ "+{",
9690
+ "+ public RefundValidator() => RuleFor(x => x.Amount).GreaterThan(0);",
9691
+ "+}"
9692
+ ],
9693
+ "added"
9694
+ ),
9695
+ hunk("src/Shop.Orders/Pricing/Rounding.cs", [
9696
+ " public static class Rounding",
9697
+ " {",
9698
+ "- public static decimal Cents(decimal x) => Math.Round(x, 2);",
9699
+ "+ public static decimal Cents(decimal x) => Math.Round(x, 2, MidpointRounding.AwayFromZero);",
9700
+ " }"
9701
+ ]),
9702
+ hunk(
9703
+ "src/Shop.Data/Migrations/20261102_AddRefunds.cs",
9704
+ [
9705
+ "+public partial class AddRefunds : Migration",
9706
+ "+{",
9707
+ '+ protected override void Up(MigrationBuilder b) => b.AddColumn<decimal>("Refunded", "Orders", nullable: false, defaultValue: 0m);',
9708
+ "+}"
9709
+ ],
9710
+ "added"
9711
+ ),
9712
+ hunk("src/Shop.Data/Migrations/20261102_AddRefunds.Designer.cs", ["+// <auto-generated />", "+partial class AddRefunds { }"], "added"),
9713
+ hunk("src/Shop.Data/Migrations/ShopDbModelSnapshot.cs", [' b.Property<decimal>("Total");', '+ b.Property<decimal>("Refunded");']),
9714
+ hunk("src/Shop.Api/Program.cs", [
9715
+ " builder.Services.AddScoped<IOrders, Orders>();",
9716
+ "+builder.Services.AddScoped<IRefundHandler, RefundHandler>();"
9717
+ ]),
9718
+ hunk("src/Shop.Orders/Shop.Orders.csproj", [
9719
+ '- <PackageReference Include="FluentValidation" Version="11.9.0" />',
9720
+ '+ <PackageReference Include="FluentValidation" Version="11.11.0" />'
9721
+ ]),
9722
+ hunk("src/Shop.Orders/OrderService.cs", ["-using System.Linq;", "+using System.Collections.Generic;", "+using System.Linq;"]),
9723
+ hunk("web/package-lock.json", ['- "version": "1.4.0",', '+ "version": "1.4.1",']),
9724
+ hunk(
9725
+ "tests/Shop.Orders.Tests/RefundHandlerTests.cs",
9726
+ [
9727
+ "+public class RefundHandlerTests",
9728
+ "+{",
9729
+ "+ [Fact]",
9730
+ "+ public async Task Refunds_part_of_an_order()",
9731
+ "+ {",
9732
+ "+ var result = await new RefundHandler(Db(), Payments()).Handle(Order, new(10m));",
9733
+ "+ Assert.Equal(10m, result.Refunded);",
9734
+ "+ }",
9735
+ "+ [Theory]",
9736
+ "+ [InlineData(0)]",
9737
+ "+ [InlineData(-5)]",
9738
+ "+ public void Rejects_amounts_that_are_not_positive(decimal amount) { }",
9739
+ "+}"
9740
+ ],
9741
+ "added"
9742
+ )
9743
+ ].join("\n");
9744
+ var DEMO_ANSWER = JSON.stringify({
9745
+ recommendation: {
9746
+ verdict: "fix-first",
9747
+ text: "Fix the refund limit before this is merged: nothing compares a refund with what the customer paid, so a refund can exceed the order total. Two refunds of one order at the same time can also both pass, which needs a decision on locking. The rounding change is fine on its own but moves amounts by a cent everywhere, so say so in the release notes."
9748
+ },
9749
+ flows: [
9750
+ {
9751
+ change: "added",
9752
+ title: "Support staff refund part of a paid order.",
9753
+ steps: [
9754
+ "A support user posts an amount to the order\u2019s new refund endpoint.",
9755
+ "RefundValidator rejects an amount that is not positive.",
9756
+ "RefundHandler asks the payment provider to refund that amount.",
9757
+ "The handler adds the amount to the order\u2019s new Refunded total and saves the order."
9758
+ ]
9759
+ },
9760
+ {
9761
+ change: "changed",
9762
+ title: "Every price is rounded to cents.",
9763
+ steps: [
9764
+ "A price, total or refund amount is computed with more than two decimals.",
9765
+ "Rounding.Cents rounds it half away from zero; before, it rounded half to the nearest even cent."
9766
+ ]
9767
+ }
9768
+ ],
9769
+ summary: "Adds partial refunds to paid orders: a POST endpoint, a handler that refunds through the payment provider and records the amount on the order, and a validator for the amount. A migration adds the column, and prices now round half away from zero.",
9770
+ stories: [
9771
+ {
9772
+ title: "Support staff can now refund part of a paid order, and the refunded amount is recorded on the order.",
9773
+ what: "A refund request for an order is sent to the payment provider for the requested amount, and the amount is then added to the order\u2019s new Refunded total. The validator only accepts a positive amount. Nothing compares the amount with what the customer paid, so a refund can exceed the order total. Existing orders start with a Refunded total of 0, and no existing caller changes.",
9774
+ why: "The handler moves the money and the validator decides which requests reach it: one cannot be reviewed without the other.",
9775
+ risk: "It moves real money through the payment provider. Two refunds of the same order at once both read the old Refunded total, and nothing stops a refund larger than what was paid.",
9776
+ riskLevel: 5,
9777
+ flags: ["data-loss", "concurrency"],
9778
+ files: ["src/Shop.Orders/Refunds/RefundHandler.cs", "src/Shop.Orders/Refunds/RefundValidator.cs"]
9779
+ },
9780
+ {
9781
+ title: "Prices that end in half a cent now round away from zero instead of to the nearest even cent.",
9782
+ what: "Rounding.Cents now passes MidpointRounding.AwayFromZero, so 2.345 becomes 2.35 where it used to become 2.34. Every price, total and refund goes through this method, so amounts can move by one cent wherever a half cent appears. Invoices already issued keep their stored amounts; new ones may differ from an old calculation of the same order.",
9783
+ why: "It is a one-line change on its own, but every amount the shop computes passes through it.",
9784
+ risk: "A one-cent difference on .5 amounts shows up everywhere at once, including in totals other systems compare against.",
9785
+ riskLevel: 3,
9786
+ flags: ["public-contract"],
9787
+ files: ["src/Shop.Orders/Pricing/Rounding.cs"]
9788
+ }
9789
+ ],
9790
+ fileSummaries: {
9791
+ "src/Shop.Orders/Refunds/RefundHandler.cs": "New handler that loads the order, asks the payment provider to refund the amount, and adds it to the order\u2019s Refunded total before saving. It does not check the order exists or that the amount fits within what was paid.",
9792
+ "src/Shop.Orders/Refunds/RefundValidator.cs": "New validator for refund requests: the amount must be greater than zero. It is the only check a request passes before money moves.",
9793
+ "src/Shop.Orders/Pricing/Rounding.cs": "Cents now rounds half a cent away from zero (MidpointRounding.AwayFromZero) instead of to even. Every amount the shop computes passes through it.",
9794
+ "src/Shop.Api/Controllers/RefundsController.cs": "New endpoint POST /orders/{orderId}/refunds that hands the request to the refund handler and returns the new refunded total. It is a new public route for API clients.",
9795
+ "src/Shop.Data/Migrations/20261102_AddRefunds.cs": "Adds a non-null Refunded column to the Orders table with a default of 0, so existing orders read as not refunded.",
9796
+ "src/Shop.Api/Program.cs": "Registers the refund handler for dependency injection, so the new controller can be constructed."
9797
+ },
9798
+ notes: [
9799
+ {
9800
+ path: "src/Shop.Orders/Refunds/RefundHandler.cs",
9801
+ line: 6,
9802
+ body: "Ivo\u2019s open question about locking the row is still not answered by the code: two refunds at once both read the old `Refunded`. A row version, or a check in the update, would settle it."
9803
+ },
9804
+ { path: "src/Shop.Orders/Refunds/RefundHandler.cs", line: 7, body: "Nothing stops refunding more than the order total." },
9805
+ // A line the diff doesn't show: set aside with its text (the host would refuse the whole review for it).
9806
+ { path: "src/Shop.Orders/Pricing/Rounding.cs", line: 90, body: "Is MidpointRounding used the same way in the invoice export?" }
9807
+ ],
9808
+ asserts: {
9809
+ Refunds_part_of_an_order: "the refunded amount comes back \u2014 not that the payment provider was called",
9810
+ Rejects_amounts_that_are_not_positive: "nothing yet: its body is empty"
9811
+ }
9812
+ });
9813
+ var ALL_FILES = parseGitDiff(DIFF);
9814
+ var SPLIT = splitIgnored(ALL_FILES);
9815
+ var FILES = SPLIT.files;
9816
+ var demoReviewFiles = () => FILES;
9817
+ function demoDiscussion(now = /* @__PURE__ */ new Date()) {
9818
+ const ago = (h) => new Date(now.getTime() - h * 36e5).toISOString();
9819
+ const url = (id) => `https://github.com/example/api/pull/231#discussion_${id}`;
9820
+ return {
9821
+ at: now.toISOString(),
9822
+ updatedAt: ago(2),
9823
+ threads: [
9824
+ {
9825
+ id: "PRRT_demo1",
9826
+ path: "src/Shop.Orders/Refunds/RefundHandler.cs",
9827
+ line: 6,
9828
+ side: "right",
9829
+ outdated: false,
9830
+ resolved: false,
9831
+ url: url("r1"),
9832
+ comments: [
9833
+ {
9834
+ author: "ivo",
9835
+ association: "MEMBER",
9836
+ body: "Is `FindAsync` enough here, or should this lock the order row? Two support agents refunding the same order is not unusual.",
9837
+ at: ago(20),
9838
+ url: url("r1")
9839
+ },
9840
+ {
9841
+ author: "marta",
9842
+ association: "CONTRIBUTOR",
9843
+ body: "Good point. I will look at a row version on Orders.",
9844
+ at: ago(18),
9845
+ url: url("r1b")
9846
+ }
9847
+ ]
9848
+ },
9849
+ {
9850
+ id: "PRRT_demo2",
9851
+ path: "src/Shop.Orders/Refunds/RefundValidator.cs",
9852
+ line: 3,
9853
+ side: "right",
9854
+ outdated: false,
9855
+ resolved: true,
9856
+ url: url("r2"),
9857
+ comments: [
9858
+ { author: "ana", association: "OWNER", body: "Should a refund of 0 be allowed?", at: ago(30), url: url("r2") },
9859
+ { author: "marta", association: "CONTRIBUTOR", body: "No: changed to `GreaterThan(0)`.", at: ago(26), url: url("r2b") }
9860
+ ]
9861
+ },
9862
+ {
9863
+ id: "PRRT_demo3",
9864
+ path: "src/Shop.Orders/Pricing/Rounding.cs",
9865
+ line: null,
9866
+ originalLine: 3,
9867
+ side: "right",
9868
+ outdated: true,
9869
+ resolved: false,
9870
+ url: url("r3"),
9871
+ comments: [
9872
+ {
9873
+ author: "ivo",
9874
+ association: "MEMBER",
9875
+ body: "Why banker\u2019s rounding in the first place? The invoices round half up.",
9876
+ at: ago(40),
9877
+ url: url("r3")
9878
+ }
9879
+ ]
9880
+ }
9881
+ ],
9882
+ reviews: [
9883
+ { author: "ivo", association: "MEMBER", state: "commented", body: "", at: ago(20), url: url("v1") },
9884
+ { author: "ana", association: "OWNER", state: "approved", body: "Fine once the row locking is sorted.", at: ago(25), url: url("v2") }
9885
+ ],
9886
+ comments: [
9887
+ {
9888
+ author: "lea",
9889
+ association: "MEMBER",
9890
+ body: "Can this go in before Friday\u2019s release? Support is waiting for it.",
9891
+ at: ago(6),
9892
+ url: "https://github.com/example/api/pull/231#issuecomment-1"
9893
+ }
9894
+ ]
9895
+ };
9896
+ }
9897
+ function demoReview(now = /* @__PURE__ */ new Date()) {
9898
+ return {
9899
+ ...buildReview(
9900
+ {
9901
+ repo: "api",
9902
+ number: 231,
9903
+ title: "Refunds: partial refunds on paid orders",
9904
+ url: "https://github.com/example/api/pull/231",
9905
+ author: "marta",
9906
+ branch: "feat/refunds",
9907
+ base: "main",
9908
+ headSha: "a1b2c3d"
9909
+ },
9910
+ FILES,
9911
+ { whitespaceOnly: /* @__PURE__ */ new Set(), generated: /* @__PURE__ */ new Set() },
9912
+ DEMO_ANSWER,
9913
+ { now, ignored: SPLIT.ignored }
9914
+ ),
9915
+ mergeBase: "base",
9916
+ preparedAt: now.toISOString(),
9917
+ discussion: demoDiscussion(now)
9918
+ };
9919
+ }
9920
+ function waitingReview(now) {
9921
+ const { discussion: _none, ...prepared } = demoReview(now);
9922
+ return {
9923
+ ...prepared,
9924
+ number: 236,
9925
+ title: "Upgrade to .NET 10",
9926
+ url: "https://github.com/example/api/pull/236",
9927
+ author: "ivo",
9928
+ status: "waiting",
9929
+ why: "4812 changed lines: over the size limit (3000), so it waits for your click",
9930
+ size: { files: 0, added: 4100, deleted: 712 },
9931
+ files: [],
9932
+ stories: [],
9933
+ unstoried: [],
9934
+ drafts: [],
9935
+ tests: { list: [], counts: { added: 0, changed: 0, removed: 0, skipped: 0 }, gaps: [], covers: {}, unitOnlyForSchema: false },
9936
+ asserts: {},
9937
+ aiStep: "none"
9938
+ };
9939
+ }
9940
+ var noSessions = {
9941
+ liveOn: () => null,
9942
+ create: (alias, branch) => ({ id: `${alias}-${branch}`, label: `${alias} \xB7 ${branch}` }),
9943
+ note: () => void 0
9944
+ };
9945
+ function mountDemoReviews(app, broadcast, sessions = noSessions) {
9946
+ const now = /* @__PURE__ */ new Date();
9947
+ const reviews = /* @__PURE__ */ new Map([
9948
+ ["api#231", demoReview(now)],
9949
+ ["api#236", waitingReview(new Date(now.getTime() - 36e5))]
9950
+ ]);
9951
+ const modes = { api: "all", web: "asked", docs: "off" };
9952
+ const settings = () => ({
9953
+ projects: Object.entries(modes).map(([name, mode]) => ({ name, kind: "repo", mode, from: "repo" })),
9954
+ maxPerDay: null,
9955
+ maxLines: 3e3
9956
+ });
9957
+ const key = (repo, n) => `${repo}#${n}`;
9958
+ const store = {
9959
+ read: (rp, num4) => reviews.get(key(rp, String(num4))) ?? null,
9960
+ update: (rp, num4, change) => {
9961
+ const was = reviews.get(key(rp, String(num4)));
9962
+ if (!was) return null;
9963
+ const next = change(was);
9964
+ reviews.set(key(rp, String(num4)), next);
9965
+ return next;
9966
+ },
9967
+ pid: 0,
9968
+ bootedAt: () => 0,
9969
+ alive: () => true
9970
+ };
9971
+ app.get(
9972
+ "/api/reviews",
9973
+ (c) => c.json({
9974
+ reviews: [...reviews.values()].map(summaryOf).sort((a, b) => b.at.localeCompare(a.at)),
9975
+ today: 1,
9976
+ maxPerDay: null
9977
+ })
9978
+ );
9979
+ app.get("/api/reviews/settings", (c) => c.json(settings()));
9980
+ app.put("/api/reviews/settings", async (c) => {
9981
+ const body = await c.req.json().catch(() => null);
9982
+ if (!body || typeof body.project !== "string" || !isReviewMode(body.mode))
9983
+ return c.json({ error: "expected {project, mode: all|asked|off}" }, 400);
9984
+ modes[body.project] = body.mode;
9985
+ broadcast("reviews-changed", { settings: true });
9986
+ return c.json(settings());
9987
+ });
9988
+ app.get("/api/reviews/:repo/:number", (c) => {
9989
+ const r = reviews.get(key(c.req.param("repo"), c.req.param("number")));
9990
+ return r ? c.json(shownReview(store, r)) : c.json({ error: "no review of that PR" }, 404);
9991
+ });
9992
+ app.get("/api/reviews/:repo/:number/diff", (c) => {
9993
+ const r = reviews.get(key(c.req.param("repo"), c.req.param("number")));
9994
+ return r && r.status === "ready" ? c.json({ files: FILES }) : c.json({ error: "no prepared review of that PR" }, 404);
9995
+ });
9996
+ app.post("/api/reviews/:repo/:number", (c) => {
9997
+ const k = key(c.req.param("repo"), c.req.param("number"));
9998
+ const was = reviews.get(k);
9999
+ if (!was) return c.json({ error: "isn't an open pull request" }, 409);
10000
+ const r = { ...demoReview(/* @__PURE__ */ new Date()), number: was.number, title: was.title, url: was.url, author: was.author };
10001
+ reviews.set(k, r);
10002
+ broadcast("reviews-changed", { repo: r.repo, number: r.number });
10003
+ return c.json(r);
10004
+ });
10005
+ app.post("/api/reviews/:repo/:number/discussion", (c) => {
10006
+ const r = reviews.get(key(c.req.param("repo"), c.req.param("number")));
10007
+ return r ? c.json(shownReview(store, r)) : c.json({ error: "no review of that PR" }, 404);
10008
+ });
10009
+ app.post("/api/reviews/:repo/:number/drafts", async (c) => {
10010
+ const k = key(c.req.param("repo"), c.req.param("number"));
10011
+ const r = reviews.get(k);
10012
+ if (!r) return c.json({ error: "no review of that PR" }, 404);
10013
+ const added = addDraft(r, await c.req.json().catch(() => null));
10014
+ if ("error" in added) return c.json({ error: added.error }, 400);
10015
+ reviews.set(k, added.review);
10016
+ broadcast("reviews-changed", { repo: r.repo, number: r.number });
10017
+ return c.json(added.review);
10018
+ });
10019
+ app.post("/api/reviews/:repo/:number/submit", async (c) => {
10020
+ const repo = c.req.param("repo");
10021
+ const n = /^\d+$/.test(c.req.param("number")) ? Number(c.req.param("number")) : null;
10022
+ if (n === null) return c.json({ error: "no review of that PR" }, 404);
10023
+ const input = await c.req.json().catch(() => null);
10024
+ const out = await submitPrReview(
10025
+ {
10026
+ ...store,
10027
+ repoPath: (alias) => alias === "api" ? "/demo/api" : null,
10028
+ submit: async (_at, num4, review) => demoHostSubmit(reviews.get(key(repo, String(num4)))?.url ?? "", review)
10029
+ },
10030
+ repo,
10031
+ n,
10032
+ input
10033
+ );
10034
+ if (out.ok || out.review) broadcast("reviews-changed", { repo, number: n });
10035
+ if (out.ok) return c.json(out.review);
10036
+ return c.json({ error: out.error, ...out.review ? { review: out.review } : {} }, out.status);
10037
+ });
10038
+ app.post("/api/reviews/:repo/:number/fix-myself", async (c) => {
10039
+ const repo = c.req.param("repo");
10040
+ const n = /^\d+$/.test(c.req.param("number")) ? Number(c.req.param("number")) : null;
10041
+ if (n === null || !reviews.get(key(repo, String(n)))) return c.json({ error: "no review of that PR" }, 404);
10042
+ const input = await c.req.json().catch(() => null);
10043
+ const out = await fixItMyself(
10044
+ {
10045
+ read: store.read,
10046
+ update: store.update,
10047
+ lookUp: async (r) => r.fork ? { ok: false, error: "it comes from a fork: its branch isn't on origin" } : {
10048
+ ok: true,
10049
+ pr: { alias: r.repo, number: r.number, title: r.title, url: r.url, branch: r.branch, base: r.base, author: r.author }
10050
+ },
10051
+ liveSessionOn: (alias, branch) => sessions.liveOn(alias, branch),
10052
+ create: async (alias, branch, name) => {
10053
+ const s = sessions.create(alias, branch, name);
10054
+ return { ok: true, sessionId: s.id, label: s.label };
10055
+ },
10056
+ // The demo's agent "starts" on its instruction: a note it answers, as every demo note.
10057
+ start: async (id, prompt) => sessions.note(id, prompt),
10058
+ note: async (id, body) => sessions.note(id, body)
10059
+ },
10060
+ repo,
10061
+ n,
10062
+ input
10063
+ );
10064
+ if (!out.ok) return c.json({ error: out.error }, out.status);
10065
+ broadcast("reviews-changed", { repo, number: n });
10066
+ broadcast("sessions-changed", { ts: Date.now() });
10067
+ const { ok: _ok, ...wire } = out;
10068
+ return c.json(wire);
10069
+ });
10070
+ app.post("/api/reviews/:repo/:number/in-doubt", async (c) => {
10071
+ const k = key(c.req.param("repo"), c.req.param("number"));
10072
+ const r = reviews.get(k);
10073
+ if (!r) return c.json({ error: "no review of that PR" }, 404);
10074
+ const body = await c.req.json().catch(() => null);
10075
+ if (!body || typeof body.went !== "boolean") return c.json({ error: "expected {went: true|false}" }, 400);
10076
+ const out = settlePrReview(store, r.repo, r.number, body.went);
10077
+ if (!out.ok) return c.json({ error: out.error }, out.status);
10078
+ broadcast("reviews-changed", { repo: r.repo, number: r.number });
10079
+ return c.json(out.review);
10080
+ });
10081
+ app.delete("/api/reviews/:repo/:number/dropped", (c) => {
10082
+ const k = key(c.req.param("repo"), c.req.param("number"));
10083
+ const r = reviews.get(k);
10084
+ if (!r) return c.json({ error: "no review of that PR" }, 404);
10085
+ const next = clearDropped(r);
10086
+ reviews.set(k, next);
10087
+ broadcast("reviews-changed", { repo: r.repo, number: r.number });
10088
+ return c.json(next);
10089
+ });
10090
+ app.delete("/api/reviews/:repo/:number/drafts/:id", (c) => {
10091
+ const k = key(c.req.param("repo"), c.req.param("number"));
10092
+ const r = reviews.get(k);
10093
+ if (!r) return c.json({ error: "no review of that PR" }, 404);
10094
+ const out = removeDraft(r, c.req.param("id"));
10095
+ if ("error" in out) return c.json({ error: out.error }, out.status);
10096
+ reviews.set(k, out.review);
10097
+ broadcast("reviews-changed", { repo: r.repo, number: r.number });
10098
+ return c.json(out.review);
10099
+ });
10100
+ }
10101
+
10102
+ // src/server/demo/demo-server.ts
10103
+ import { Hono as Hono2 } from "hono";
10104
+ import { streamSSE as streamSSE3 } from "hono/streaming";
10105
+ import { WebSocketServer as WebSocketServer2 } from "ws";
10106
+
10107
+ // src/server/demo/demo-repos.ts
10108
+ var DemoRepoError = class extends Error {
10109
+ constructor(message, sessions = []) {
9085
10110
  super(message);
9086
10111
  this.sessions = sessions;
9087
10112
  }
@@ -9114,7 +10139,7 @@ function createDemoRepos(liveTargets) {
9114
10139
  /** GET /api/projects: what New worktree offers, as the real one reads config. */
9115
10140
  projects() {
9116
10141
  return {
9117
- singles: Object.entries(repos).map(([name, path20]) => ({ name, kind: "single", path: path20 })),
10142
+ singles: Object.entries(repos).map(([name, path21]) => ({ name, kind: "single", path: path21 })),
9118
10143
  groups: Object.entries(groups).map(([name, members]) => ({ name, kind: "group", members }))
9119
10144
  };
9120
10145
  },
@@ -9156,12 +10181,12 @@ function createDemoRepos(liveTargets) {
9156
10181
  }));
9157
10182
  return { roots: [root], repos: rows, groups: groupRows };
9158
10183
  },
9159
- enroll(alias, path20) {
9160
- if (!found.some((f) => f.path === path20)) throw new DemoRepoError(`${path20} is not the top folder of a git repository`);
9161
- const problem = enrollProblem(alias, path20, config());
10184
+ enroll(alias, path21) {
10185
+ if (!found.some((f) => f.path === path21)) throw new DemoRepoError(`${path21} is not the top folder of a git repository`);
10186
+ const problem = enrollProblem(alias, path21, config());
9162
10187
  if (problem) throw new DemoRepoError(problem);
9163
- repos[alias] = path20;
9164
- ignored.delete(path20);
10188
+ repos[alias] = path21;
10189
+ ignored.delete(path21);
9165
10190
  },
9166
10191
  remove(alias, force) {
9167
10192
  if (!(alias in repos)) throw new DemoRepoError(`no repo \u201C${alias}\u201D`);
@@ -9170,9 +10195,9 @@ function createDemoRepos(liveTargets) {
9170
10195
  delete repos[alias];
9171
10196
  for (const g2 of Object.keys(groups)) groups[g2] = groups[g2].filter((m) => m !== alias);
9172
10197
  },
9173
- ignore(path20, on) {
9174
- if (on) ignored.add(path20);
9175
- else ignored.delete(path20);
10198
+ ignore(path21, on) {
10199
+ if (on) ignored.add(path21);
10200
+ else ignored.delete(path21);
9176
10201
  },
9177
10202
  saveGroup(name, members, creating) {
9178
10203
  const problem = groupProblem(name, members, config(), { creating });
@@ -9572,8 +10597,8 @@ var DemoScenario = class {
9572
10597
  this.pending = this.pending.filter((p) => !ready.includes(p));
9573
10598
  for (const p of ready) p.run();
9574
10599
  }
9575
- after(ms, run) {
9576
- this.pending.push({ at: this.now() + ms * this.speed, run });
10600
+ after(ms, run2) {
10601
+ this.pending.push({ at: this.now() + ms * this.speed, run: run2 });
9577
10602
  }
9578
10603
  // -- seed -----------------------------------------------------------------
9579
10604
  iso(minutesAgo) {
@@ -10412,15 +11437,15 @@ ${reply}\r
10412
11437
  if (refusal || !s) return { ok: false, status: refusal?.status ?? 404, error: refusal?.error ?? "unknown session" };
10413
11438
  s.repos.push({ name: alias, uncommitted: "", sinceBranch: "", published: false, pr: null });
10414
11439
  const from = base || "main";
10415
- const path20 = this.wire(s).paths[s.repos.length - 1];
11440
+ const path21 = this.wire(s).paths[s.repos.length - 1];
10416
11441
  s.comments.post({
10417
11442
  side: "general",
10418
11443
  status: "published",
10419
- body: addedRepoNote({ alias, path: path20, branch: s.branch, from, imported: true })
11444
+ body: addedRepoNote({ alias, path: path21, branch: s.branch, from, imported: true })
10420
11445
  });
10421
11446
  this.emit("comments-changed", { sessionId: id });
10422
11447
  this.changed();
10423
- return { ok: true, wire: { ok: true, path: path20, branch: s.branch, created: true, from, imported: true, warnings: [] } };
11448
+ return { ok: true, wire: { ok: true, path: path21, branch: s.branch, created: true, from, imported: true, warnings: [] } };
10424
11449
  }
10425
11450
  // -- CI (the PR watch, simulated) ------------------------------------------
10426
11451
  /** The Today digest, through the same builder as work web: the demo's
@@ -10990,735 +12015,285 @@ function newSide(f) {
10990
12015
  }
10991
12016
  function demoCodeFiles(repos, group) {
10992
12017
  return {
10993
- group,
10994
- rootFiles: group ? ["CLAUDE.md"] : [],
10995
- repos: repos.map((r) => {
10996
- const changed = r.changed.filter((f) => f.status !== "deleted").map((f) => f.path);
10997
- return { name: r.name, files: [.../* @__PURE__ */ new Set([...Object.keys(COMMON), ...changed])].sort(), changed: changed.sort(), truncated: false };
10998
- })
10999
- };
11000
- }
11001
- function demoCodeFile(repos, group, repo, path20) {
11002
- if (repo === "") {
11003
- if (!group || path20 !== "CLAUDE.md") return null;
11004
- const text2 = `# Group instructions
11005
-
11006
- Repos: ${repos.map((r2) => r2.name).join(", ")}.
11007
- `;
11008
- return { repo, path: path20, size: text2.length, text: text2 };
11009
- }
11010
- const r = repos.find((x) => x.name === repo);
11011
- if (!r) return null;
11012
- const changed = r.changed.find((f) => f.path === path20 && f.status !== "deleted");
11013
- const text = changed ? newSide(changed) : COMMON[path20]?.replace(/\{repo\}/g, repo);
11014
- return text === void 0 ? null : { repo, path: path20, size: text.length, text };
11015
- }
11016
- function demoCodeSearch(repos, group, query) {
11017
- const q = query.trim();
11018
- if (q.length < 2) return { query: q, symbols: [], text: [], truncated: false };
11019
- const symbols = [];
11020
- const text = [];
11021
- const fold = (x) => ignoresCase(q) ? x.toLowerCase() : x;
11022
- for (const r of demoCodeFiles(repos, group).repos) {
11023
- for (const path20 of r.files) {
11024
- const lines = (demoCodeFile(repos, group, r.name, path20)?.text ?? "").split("\n");
11025
- lines.forEach((line, i) => {
11026
- const d = declarationOf(path20, line);
11027
- if (d) symbols.push({ ...d, repo: r.name, path: path20, line: i + 1, text: line.trim() });
11028
- if (fold(line).includes(fold(q))) text.push({ repo: r.name, path: path20, line: i + 1, text: line });
11029
- });
11030
- }
11031
- }
11032
- return { query: q, symbols: matchSymbols(symbols, q), text, truncated: false };
11033
- }
11034
-
11035
- // src/server/demo/demo-activity.ts
11036
- var SWEEP_EVERY_MS = 3e4;
11037
- var STEP_MS = 700;
11038
- function createDemoActivity(scenario, emit) {
11039
- const log = createActivityLog({ onChange: emit });
11040
- const prCheck = log.schedule("pr-watch", "Pull request check", SWEEP_EVERY_MS);
11041
- const idle = log.schedule("idle-sleep", "Idle Claude check", 5 * 6e4);
11042
- idle.next(Date.now() + 4 * 6e4);
11043
- log.start("jira", "Fetching your Jira issues").done(`${scenario.jira().length} issues`);
11044
- log.start("pr-list", "Listing open pull requests").done(`${scenario.prs().length} open PRs in 3 repos`);
11045
- const sleep = log.start("idle-sleep", "Looking for idle Claudes");
11046
- sleep.done(`${scenario.list().length} Claudes running \xB7 none idle long enough`);
11047
- let timers = [];
11048
- const later = (ms, fn) => {
11049
- const t = setTimeout(fn, ms);
11050
- t.unref?.();
11051
- timers.push(t);
11052
- };
11053
- const sweep = () => {
11054
- prCheck.next(Date.now() + SWEEP_EVERY_MS);
11055
- const sessions = scenario.list().filter((s) => !s.archivedAt);
11056
- const run = log.start("pr-watch", "Checking pull requests");
11057
- run.progress(0, sessions.length);
11058
- let prs = 0;
11059
- let threads = 0;
11060
- let failing = 0;
11061
- sessions.forEach((s, i) => {
11062
- later((i + 1) * STEP_MS, () => {
11063
- for (const r of scenario.ci(s.id)?.repos ?? []) {
11064
- if (r.pr?.state !== "OPEN") continue;
11065
- prs++;
11066
- threads += r.openThreads ?? 0;
11067
- if (r.pr.checks === "fail") {
11068
- failing++;
11069
- run.note(
11070
- `${s.target} ${s.branch}: checks fail on #${r.pr.number} (${(r.pr.failing ?? []).map((f) => f.name).join(", ")}): already told its Claude`,
11071
- { sessionId: s.id }
11072
- );
11073
- }
11074
- if (r.openThreads)
11075
- run.note(`${s.target} ${s.branch}: ${r.openThreads} unresolved review threads on #${r.pr.number}`, { sessionId: s.id });
11076
- }
11077
- run.progress(i + 1, sessions.length);
11078
- if (i === sessions.length - 1) {
11079
- const parts = [`${sessions.length} sessions`, `${prs} open PRs`];
11080
- if (threads) parts.push(`${threads} unresolved review threads`);
11081
- if (failing) parts.push(`${failing} failing`);
11082
- run.done(parts.join(" \xB7 "));
11083
- }
11084
- });
11085
- });
11086
- if (sessions.length === 0) run.done("0 sessions");
11087
- };
11088
- later(3e3, sweep);
11089
- prCheck.next(Date.now() + 3e3);
11090
- const every = setInterval(sweep, SWEEP_EVERY_MS);
11091
- every.unref?.();
11092
- return {
11093
- log,
11094
- stop: () => {
11095
- clearInterval(every);
11096
- for (const t of timers) clearTimeout(t);
11097
- timers = [];
11098
- }
11099
- };
11100
- }
11101
-
11102
- // src/server/demo/demo-time.ts
11103
- var SETTINGS2 = { ...DEFAULT_TIME_SETTINGS, gapTicket: "OPS-1", timeOffTicket: "HR-1" };
11104
- var TITLES = {
11105
- "PAY-12": "Export invoices as CSV",
11106
- "PAY-15": "Invoice PDF",
11107
- "SHOP-7": "Checkout in two steps",
11108
- "WEB-3": "Price and brand filters in search",
11109
- "WEB-9": "Login redirect loop",
11110
- "OPS-1": "Meetings, reviews and support",
11111
- "HR-1": "Time off"
11112
- };
11113
- var WORK = [
11114
- { id: "demo-api-feat-invoice-export", label: "api \xB7 feat/invoice-export", key: "PAY-12" },
11115
- { id: "demo-api-feat-invoice-pdf", label: "api \xB7 feat/invoice-pdf", key: "PAY-15" },
11116
- { id: "demo-shop-feat-checkout-v2", label: "shop \xB7 feat/checkout-v2", key: "SHOP-7" },
11117
- { id: "demo-web-feat-search-filters", label: "web \xB7 feat/search-filters", key: "WEB-3" },
11118
- { id: "demo-web-fix-login-redirect", label: "web \xB7 fix/login-redirect", key: "WEB-9" }
11119
- ];
11120
- function evidenceFor(n) {
11121
- const pick = [WORK[n % WORK.length], WORK[(n + 2) % WORK.length]];
11122
- return {
11123
- sessions: [
11124
- { sessionId: pick[0].id, label: pick[0].label, key: pick[0].key, minutes: 25 + n * 7 % 30 },
11125
- { sessionId: pick[1].id, label: pick[1].label, key: pick[1].key, minutes: 8 + n * 5 % 15 },
11126
- ...n % 3 === 0 ? [{ sessionId: "demo-api-chore-deps-update", label: "api \xB7 chore/deps-update", key: null, minutes: 12 }] : []
11127
- ],
11128
- commits: [
11129
- {
11130
- repo: pick[0].id.split("-")[1],
11131
- sha: `c0ffee${n}0`,
11132
- subject: `${pick[0].key}: ${TITLES[pick[0].key].toLowerCase()}, part ${n % 4 + 1}`,
11133
- keys: [pick[0].key]
11134
- }
11135
- ],
11136
- jira: n % 4 === 1 ? [{ key: "WEB-9", summary: TITLES["WEB-9"], what: "moved (now In review)" }] : []
11137
- };
11138
- }
11139
- var DEMO_DAYS = 31;
11140
- function createDemoTime(now) {
11141
- const edits = /* @__PURE__ */ new Map();
11142
- const record = (day) => {
11143
- const today = localDay(now());
11144
- if (day > today) return null;
11145
- const all = daysBetween(addDays(today, -(DEMO_DAYS - 1)), today);
11146
- const n = all.indexOf(day);
11147
- const e = edits.get(day) ?? {};
11148
- if (n < 0 && !e.edited && !e.dayOff) return null;
11149
- return {
11150
- day,
11151
- evidence: n >= 0 && isWorkday(day, SETTINGS2) ? evidenceFor(n) : { sessions: [], commits: [], jira: [] },
11152
- titles: TITLES,
11153
- builtAt: new Date(now()).toISOString(),
11154
- edited: e.edited ?? null,
11155
- dayOff: e.dayOff ?? false,
11156
- posted: e.posted ?? null
11157
- };
11158
- };
11159
- return {
11160
- days: (from, to) => daysWireOf(
11161
- from,
11162
- to,
11163
- SETTINGS2,
11164
- daysBetween(from, to).map(record).filter((r) => !!r)
11165
- ),
11166
- month: (month) => {
11167
- const today = localDay(now());
11168
- const r = monthRange(month, today);
11169
- const records = r ? daysBetween(r.from, r.to).map(record).filter((x) => !!x) : [];
11170
- return { ...monthWireOf(month, today, SETTINGS2, records), gathering: false, gatherError: null, posting: { ready: true, why: null } };
11171
- },
11172
- day: (day) => ({ ...dayWireOf(day, SETTINGS2, record(day)), posting: { ready: true, why: null } }),
11173
- update: (day, change) => {
11174
- edits.set(day, { ...edits.get(day) ?? {}, ...change });
11175
- return { ...dayWireOf(day, SETTINGS2, record(day)), posting: { ready: true, why: null } };
11176
- },
11177
- /** "Posting": what the day shows is now what Tempo has (nothing leaves the demo). */
11178
- post: (day) => {
11179
- const w = dayWireOf(day, SETTINGS2, record(day));
11180
- const before = record(day)?.posted?.entries ?? [];
11181
- const kept = w.entries.filter((e) => before.some((b) => b.key === e.key && b.hours === e.hours)).length;
11182
- edits.set(day, { ...edits.get(day) ?? {}, posted: { at: new Date(now()).toISOString(), entries: w.entries, worklogs: [] } });
11183
- return {
11184
- posted: w.entries.length - kept,
11185
- removed: before.length - kept,
11186
- kept,
11187
- coveredByHand: 0,
11188
- otherByHand: 0,
11189
- failed: [],
11190
- day: { ...dayWireOf(day, SETTINGS2, record(day)), posting: { ready: true, why: null } }
11191
- };
11192
- },
11193
- settings: SETTINGS2
12018
+ group,
12019
+ rootFiles: group ? ["CLAUDE.md"] : [],
12020
+ repos: repos.map((r) => {
12021
+ const changed = r.changed.filter((f) => f.status !== "deleted").map((f) => f.path);
12022
+ return { name: r.name, files: [.../* @__PURE__ */ new Set([...Object.keys(COMMON), ...changed])].sort(), changed: changed.sort(), truncated: false };
12023
+ })
11194
12024
  };
11195
12025
  }
12026
+ function demoCodeFile(repos, group, repo, path21) {
12027
+ if (repo === "") {
12028
+ if (!group || path21 !== "CLAUDE.md") return null;
12029
+ const text2 = `# Group instructions
11196
12030
 
11197
- // src/server/demo/demo-replies.ts
11198
- function mountDemoReplies(app, scenario, emit) {
11199
- const byId = /* @__PURE__ */ new Map();
11200
- const deps = scenario.list().find((s) => s.branch === "chore/deps-update");
11201
- if (deps) {
11202
- const at = new Date(Date.now() - 20 * 6e4).toISOString();
11203
- byId.set(deps.id, [
11204
- {
11205
- threadId: "PRRT_demo_zod",
11206
- repo: "api",
11207
- prNumber: 212,
11208
- url: "https://github.com/example/api/pull/212#discussion_r1",
11209
- where: "src/schema.ts:14",
11210
- reviewer: "dana",
11211
- excerpt: "zod 4 changed `.nonempty()` \u2014 does this still reject empty arrays?",
11212
- body: "zod 4 changed `.nonempty()` \u2014 does this still reject empty arrays?\n\nIf not, this would do it:\n\n```suggestion\n items: z.array(Item).min(1),\n```",
11213
- code: {
11214
- hunk: '@@ -10,6 +10,6 @@ export const Order = z.object({\n id: z.string().uuid(),\n customer: Customer,\n currency: z.enum(["EUR", "USD"]),\n- items: z.array(Item).min(1),\n+ items: z.array(Item).nonempty(),\n note: z.string().optional(),',
11215
- lines: 1
11216
- },
11217
- status: "draft",
11218
- draft: "Yes \u2014 switched to `.min(1)`, which zod 4 keeps, and added a test for the empty case (a1b2c3d).",
11219
- sentAt: at,
11220
- draftedAt: at
11221
- },
11222
- {
11223
- threadId: "PRRT_demo_lock",
11224
- repo: "api",
11225
- prNumber: 212,
11226
- url: "https://github.com/example/api/pull/212#discussion_r2",
11227
- where: "package-lock.json",
11228
- reviewer: "copilot-pull-request-reviewer",
11229
- excerpt: "The lockfile also bumps `express` to a new major version; was that intended?",
11230
- status: "sent",
11231
- draft: null,
11232
- sentAt: at
11233
- }
11234
- ]);
12031
+ Repos: ${repos.map((r2) => r2.name).join(", ")}.
12032
+ `;
12033
+ return { repo, path: path21, size: text2.length, text: text2 };
11235
12034
  }
11236
- const list = (id) => byId.get(id) ?? [];
11237
- const find = (id, thread) => list(id).find((r) => r.threadId === thread);
11238
- app.get("/api/sessions/:id/replies", (c) => c.json({ replies: list(c.req.param("id")), waiting: [] }));
11239
- app.put("/api/sessions/:id/replies/:thread", async (c) => {
11240
- const r = find(c.req.param("id"), c.req.param("thread"));
11241
- const b = await c.req.json().catch(() => ({}));
11242
- if (!r || typeof b.body !== "string" || !b.body.trim()) return c.json({ error: "unknown thread or empty reply" }, 400);
11243
- Object.assign(r, { status: "draft", draft: b.body.trim(), draftedAt: (/* @__PURE__ */ new Date()).toISOString() });
11244
- emit(c.req.param("id"));
11245
- return c.json({ reply: r });
11246
- });
11247
- app.delete("/api/sessions/:id/replies/:thread", (c) => {
11248
- const id = c.req.param("id");
11249
- byId.set(
11250
- id,
11251
- list(id).filter((r) => r.threadId !== c.req.param("thread"))
11252
- );
11253
- emit(id);
11254
- return c.json({ ok: true });
11255
- });
11256
- app.post("/api/sessions/:id/replies/:thread/post", async (c) => {
11257
- const r = find(c.req.param("id"), c.req.param("thread"));
11258
- const b = await c.req.json().catch(() => ({}));
11259
- if (!r || typeof b.body !== "string" || !b.body.trim()) return c.json({ error: "unknown thread or empty reply" }, 400);
11260
- Object.assign(r, {
11261
- status: "posted",
11262
- draft: b.body.trim(),
11263
- postedAt: (/* @__PURE__ */ new Date()).toISOString(),
11264
- postedUrl: r.url,
11265
- resolved: b.resolve === true
11266
- });
11267
- emit(c.req.param("id"));
11268
- return c.json({ ok: true, url: r.url, resolved: b.resolve === true });
11269
- });
11270
- app.post("/api/replies-changed", (c) => c.json({ ok: true }));
11271
- return (id) => list(id).filter((r) => r.status === "draft").length;
12035
+ const r = repos.find((x) => x.name === repo);
12036
+ if (!r) return null;
12037
+ const changed = r.changed.find((f) => f.path === path21 && f.status !== "deleted");
12038
+ const text = changed ? newSide(changed) : COMMON[path21]?.replace(/\{repo\}/g, repo);
12039
+ return text === void 0 ? null : { repo, path: path21, size: text.length, text };
11272
12040
  }
11273
-
11274
- // src/server/demo/demo-reviews.ts
11275
- async function demoHostSubmit(url, review) {
11276
- if (review.body.includes("#timeout"))
11277
- return {
11278
- ok: false,
11279
- error: "the host timed out (demo)",
11280
- inDoubt: { comments: review.comments.map((_, i) => i), summary: !!review.body.trim() }
11281
- };
11282
- return { ok: true, url: `${url}#pullrequestreview-1` };
12041
+ function demoCodeSearch(repos, group, query) {
12042
+ const q = query.trim();
12043
+ if (q.length < 2) return { query: q, symbols: [], text: [], truncated: false };
12044
+ const symbols = [];
12045
+ const text = [];
12046
+ const fold = (x) => ignoresCase(q) ? x.toLowerCase() : x;
12047
+ for (const r of demoCodeFiles(repos, group).repos) {
12048
+ for (const path21 of r.files) {
12049
+ const lines = (demoCodeFile(repos, group, r.name, path21)?.text ?? "").split("\n");
12050
+ lines.forEach((line, i) => {
12051
+ const d = declarationOf(path21, line);
12052
+ if (d) symbols.push({ ...d, repo: r.name, path: path21, line: i + 1, text: line.trim() });
12053
+ if (fold(line).includes(fold(q))) text.push({ repo: r.name, path: path21, line: i + 1, text: line });
12054
+ });
12055
+ }
12056
+ }
12057
+ return { query: q, symbols: matchSymbols(symbols, q), text, truncated: false };
11283
12058
  }
11284
- var hunk = (path20, lines, status = "modified") => {
11285
- const added = lines.filter((l) => l.startsWith("+")).length;
11286
- const deleted = lines.filter((l) => l.startsWith("-")).length;
11287
- const context = lines.length - added - deleted;
11288
- return [
11289
- `diff --git a/${path20} b/${path20}`,
11290
- ...status === "added" ? ["new file mode 100644", "index 0000000..1111111", "--- /dev/null"] : ["index 1111111..2222222 100644", `--- a/${path20}`],
11291
- `+++ b/${path20}`,
11292
- `@@ -${status === "added" ? 0 : 1},${status === "added" ? 0 : context + deleted} +1,${context + added} @@`,
11293
- ...lines
11294
- ].join("\n");
11295
- };
11296
- var DIFF = [
11297
- hunk(
11298
- "src/Shop.Api/Controllers/RefundsController.cs",
11299
- [
11300
- "+using System;",
11301
- "+using Microsoft.AspNetCore.Mvc;",
11302
- "+using Shop.Orders.Refunds;",
11303
- "+",
11304
- "+[ApiController]",
11305
- '+[Route("orders/{orderId}/refunds")]',
11306
- "+public class RefundsController(IRefundHandler refunds) : ControllerBase",
11307
- "+{",
11308
- "+ [HttpPost]",
11309
- "+ public async Task<IActionResult> Create(Guid orderId, RefundRequest request)",
11310
- "+ => Ok(await refunds.Handle(orderId, request));",
11311
- "+}"
11312
- ],
11313
- "added"
11314
- ),
11315
- hunk(
11316
- "src/Shop.Orders/Refunds/RefundHandler.cs",
11317
- [
11318
- "+public class RefundHandler(ShopDb db, IPayments payments) : IRefundHandler",
11319
- "+{",
11320
- "+ public async Task<RefundResult> Handle(Guid orderId, RefundRequest request)",
11321
- "+ {",
11322
- "+ var order = await db.Orders.FindAsync(orderId);",
11323
- "+ await payments.Refund(order!.PaymentId, request.Amount);",
11324
- "+ order.Refunded += request.Amount;",
11325
- "+ await db.SaveChangesAsync();",
11326
- "+ return new RefundResult(order.Refunded);",
11327
- "+ }",
11328
- "+}"
11329
- ],
11330
- "added"
11331
- ),
11332
- hunk(
11333
- "src/Shop.Orders/Refunds/RefundValidator.cs",
11334
- [
11335
- "+public class RefundValidator : AbstractValidator<RefundRequest>",
11336
- "+{",
11337
- "+ public RefundValidator() => RuleFor(x => x.Amount).GreaterThan(0);",
11338
- "+}"
11339
- ],
11340
- "added"
11341
- ),
11342
- hunk("src/Shop.Orders/Pricing/Rounding.cs", [
11343
- " public static class Rounding",
11344
- " {",
11345
- "- public static decimal Cents(decimal x) => Math.Round(x, 2);",
11346
- "+ public static decimal Cents(decimal x) => Math.Round(x, 2, MidpointRounding.AwayFromZero);",
11347
- " }"
11348
- ]),
11349
- hunk(
11350
- "src/Shop.Data/Migrations/20261102_AddRefunds.cs",
11351
- [
11352
- "+public partial class AddRefunds : Migration",
11353
- "+{",
11354
- '+ protected override void Up(MigrationBuilder b) => b.AddColumn<decimal>("Refunded", "Orders", nullable: false, defaultValue: 0m);',
11355
- "+}"
11356
- ],
11357
- "added"
11358
- ),
11359
- hunk("src/Shop.Data/Migrations/20261102_AddRefunds.Designer.cs", ["+// <auto-generated />", "+partial class AddRefunds { }"], "added"),
11360
- hunk("src/Shop.Data/Migrations/ShopDbModelSnapshot.cs", [' b.Property<decimal>("Total");', '+ b.Property<decimal>("Refunded");']),
11361
- hunk("src/Shop.Api/Program.cs", [
11362
- " builder.Services.AddScoped<IOrders, Orders>();",
11363
- "+builder.Services.AddScoped<IRefundHandler, RefundHandler>();"
11364
- ]),
11365
- hunk("src/Shop.Orders/Shop.Orders.csproj", [
11366
- '- <PackageReference Include="FluentValidation" Version="11.9.0" />',
11367
- '+ <PackageReference Include="FluentValidation" Version="11.11.0" />'
11368
- ]),
11369
- hunk("src/Shop.Orders/OrderService.cs", ["-using System.Linq;", "+using System.Collections.Generic;", "+using System.Linq;"]),
11370
- hunk("web/package-lock.json", ['- "version": "1.4.0",', '+ "version": "1.4.1",']),
11371
- hunk(
11372
- "tests/Shop.Orders.Tests/RefundHandlerTests.cs",
11373
- [
11374
- "+public class RefundHandlerTests",
11375
- "+{",
11376
- "+ [Fact]",
11377
- "+ public async Task Refunds_part_of_an_order()",
11378
- "+ {",
11379
- "+ var result = await new RefundHandler(Db(), Payments()).Handle(Order, new(10m));",
11380
- "+ Assert.Equal(10m, result.Refunded);",
11381
- "+ }",
11382
- "+ [Theory]",
11383
- "+ [InlineData(0)]",
11384
- "+ [InlineData(-5)]",
11385
- "+ public void Rejects_amounts_that_are_not_positive(decimal amount) { }",
11386
- "+}"
11387
- ],
11388
- "added"
11389
- )
11390
- ].join("\n");
11391
- var DEMO_ANSWER = JSON.stringify({
11392
- summary: "Adds partial refunds to paid orders: a POST endpoint, a handler that refunds through the payment provider and records the amount on the order, and a validator for the amount. A migration adds the column, and prices now round half away from zero.",
11393
- stories: [
11394
- {
11395
- title: "Support staff can now refund part of a paid order, and the refunded amount is recorded on the order.",
11396
- what: "A refund request for an order is sent to the payment provider for the requested amount, and the amount is then added to the order\u2019s new Refunded total. The validator only accepts a positive amount. Nothing compares the amount with what the customer paid, so a refund can exceed the order total. Existing orders start with a Refunded total of 0, and no existing caller changes.",
11397
- why: "The handler moves the money and the validator decides which requests reach it: one cannot be reviewed without the other.",
11398
- risk: "It moves real money through the payment provider. Two refunds of the same order at once both read the old Refunded total, and nothing stops a refund larger than what was paid.",
11399
- riskLevel: 5,
11400
- flags: ["data-loss", "concurrency"],
11401
- files: ["src/Shop.Orders/Refunds/RefundHandler.cs", "src/Shop.Orders/Refunds/RefundValidator.cs"]
11402
- },
11403
- {
11404
- title: "Prices that end in half a cent now round away from zero instead of to the nearest even cent.",
11405
- what: "Rounding.Cents now passes MidpointRounding.AwayFromZero, so 2.345 becomes 2.35 where it used to become 2.34. Every price, total and refund goes through this method, so amounts can move by one cent wherever a half cent appears. Invoices already issued keep their stored amounts; new ones may differ from an old calculation of the same order.",
11406
- why: "It is a one-line change on its own, but every amount the shop computes passes through it.",
11407
- risk: "A one-cent difference on .5 amounts shows up everywhere at once, including in totals other systems compare against.",
11408
- riskLevel: 3,
11409
- flags: ["public-contract"],
11410
- files: ["src/Shop.Orders/Pricing/Rounding.cs"]
12059
+
12060
+ // src/server/demo/demo-activity.ts
12061
+ var SWEEP_EVERY_MS = 3e4;
12062
+ var STEP_MS = 700;
12063
+ function createDemoActivity(scenario, emit) {
12064
+ const log = createActivityLog({ onChange: emit });
12065
+ const prCheck = log.schedule("pr-watch", "Pull request check", SWEEP_EVERY_MS);
12066
+ const idle = log.schedule("idle-sleep", "Idle Claude check", 5 * 6e4);
12067
+ idle.next(Date.now() + 4 * 6e4);
12068
+ log.start("jira", "Fetching your Jira issues").done(`${scenario.jira().length} issues`);
12069
+ log.start("pr-list", "Listing open pull requests").done(`${scenario.prs().length} open PRs in 3 repos`);
12070
+ const sleep = log.start("idle-sleep", "Looking for idle Claudes");
12071
+ sleep.done(`${scenario.list().length} Claudes running \xB7 none idle long enough`);
12072
+ let timers = [];
12073
+ const later = (ms, fn) => {
12074
+ const t = setTimeout(fn, ms);
12075
+ t.unref?.();
12076
+ timers.push(t);
12077
+ };
12078
+ const sweep = () => {
12079
+ prCheck.next(Date.now() + SWEEP_EVERY_MS);
12080
+ const sessions = scenario.list().filter((s) => !s.archivedAt);
12081
+ const run2 = log.start("pr-watch", "Checking pull requests");
12082
+ run2.progress(0, sessions.length);
12083
+ let prs = 0;
12084
+ let threads = 0;
12085
+ let failing = 0;
12086
+ sessions.forEach((s, i) => {
12087
+ later((i + 1) * STEP_MS, () => {
12088
+ for (const r of scenario.ci(s.id)?.repos ?? []) {
12089
+ if (r.pr?.state !== "OPEN") continue;
12090
+ prs++;
12091
+ threads += r.openThreads ?? 0;
12092
+ if (r.pr.checks === "fail") {
12093
+ failing++;
12094
+ run2.note(
12095
+ `${s.target} ${s.branch}: checks fail on #${r.pr.number} (${(r.pr.failing ?? []).map((f) => f.name).join(", ")}): already told its Claude`,
12096
+ { sessionId: s.id }
12097
+ );
12098
+ }
12099
+ if (r.openThreads)
12100
+ run2.note(`${s.target} ${s.branch}: ${r.openThreads} unresolved review threads on #${r.pr.number}`, { sessionId: s.id });
12101
+ }
12102
+ run2.progress(i + 1, sessions.length);
12103
+ if (i === sessions.length - 1) {
12104
+ const parts = [`${sessions.length} sessions`, `${prs} open PRs`];
12105
+ if (threads) parts.push(`${threads} unresolved review threads`);
12106
+ if (failing) parts.push(`${failing} failing`);
12107
+ run2.done(parts.join(" \xB7 "));
12108
+ }
12109
+ });
12110
+ });
12111
+ if (sessions.length === 0) run2.done("0 sessions");
12112
+ };
12113
+ later(3e3, sweep);
12114
+ prCheck.next(Date.now() + 3e3);
12115
+ const every = setInterval(sweep, SWEEP_EVERY_MS);
12116
+ every.unref?.();
12117
+ return {
12118
+ log,
12119
+ stop: () => {
12120
+ clearInterval(every);
12121
+ for (const t of timers) clearTimeout(t);
12122
+ timers = [];
11411
12123
  }
11412
- ],
11413
- fileSummaries: {
11414
- "src/Shop.Orders/Refunds/RefundHandler.cs": "New handler that loads the order, asks the payment provider to refund the amount, and adds it to the order\u2019s Refunded total before saving. It does not check the order exists or that the amount fits within what was paid.",
11415
- "src/Shop.Orders/Refunds/RefundValidator.cs": "New validator for refund requests: the amount must be greater than zero. It is the only check a request passes before money moves.",
11416
- "src/Shop.Orders/Pricing/Rounding.cs": "Cents now rounds half a cent away from zero (MidpointRounding.AwayFromZero) instead of to even. Every amount the shop computes passes through it.",
11417
- "src/Shop.Api/Controllers/RefundsController.cs": "New endpoint POST /orders/{orderId}/refunds that hands the request to the refund handler and returns the new refunded total. It is a new public route for API clients.",
11418
- "src/Shop.Data/Migrations/20261102_AddRefunds.cs": "Adds a non-null Refunded column to the Orders table with a default of 0, so existing orders read as not refunded.",
11419
- "src/Shop.Api/Program.cs": "Registers the refund handler for dependency injection, so the new controller can be constructed."
11420
- },
11421
- notes: [
11422
- {
11423
- path: "src/Shop.Orders/Refunds/RefundHandler.cs",
11424
- line: 6,
11425
- body: "Ivo\u2019s open question about locking the row is still not answered by the code: two refunds at once both read the old `Refunded`. A row version, or a check in the update, would settle it."
11426
- },
11427
- { path: "src/Shop.Orders/Refunds/RefundHandler.cs", line: 7, body: "Nothing stops refunding more than the order total." },
11428
- // A line the diff doesn't show: set aside with its text (the host would refuse the whole review for it).
11429
- { path: "src/Shop.Orders/Pricing/Rounding.cs", line: 90, body: "Is MidpointRounding used the same way in the invoice export?" }
11430
- ],
11431
- asserts: {
11432
- Refunds_part_of_an_order: "the refunded amount comes back \u2014 not that the payment provider was called",
11433
- Rejects_amounts_that_are_not_positive: "nothing yet: its body is empty"
11434
- }
11435
- });
11436
- var ALL_FILES = parseGitDiff(DIFF);
11437
- var SPLIT = splitIgnored(ALL_FILES);
11438
- var FILES = SPLIT.files;
11439
- function demoDiscussion(now = /* @__PURE__ */ new Date()) {
11440
- const ago = (h) => new Date(now.getTime() - h * 36e5).toISOString();
11441
- const url = (id) => `https://github.com/example/api/pull/231#discussion_${id}`;
12124
+ };
12125
+ }
12126
+
12127
+ // src/server/demo/demo-time.ts
12128
+ var SETTINGS2 = { ...DEFAULT_TIME_SETTINGS, gapTicket: "OPS-1", timeOffTicket: "HR-1" };
12129
+ var TITLES = {
12130
+ "PAY-12": "Export invoices as CSV",
12131
+ "PAY-15": "Invoice PDF",
12132
+ "SHOP-7": "Checkout in two steps",
12133
+ "WEB-3": "Price and brand filters in search",
12134
+ "WEB-9": "Login redirect loop",
12135
+ "OPS-1": "Meetings, reviews and support",
12136
+ "HR-1": "Time off"
12137
+ };
12138
+ var WORK = [
12139
+ { id: "demo-api-feat-invoice-export", label: "api \xB7 feat/invoice-export", key: "PAY-12" },
12140
+ { id: "demo-api-feat-invoice-pdf", label: "api \xB7 feat/invoice-pdf", key: "PAY-15" },
12141
+ { id: "demo-shop-feat-checkout-v2", label: "shop \xB7 feat/checkout-v2", key: "SHOP-7" },
12142
+ { id: "demo-web-feat-search-filters", label: "web \xB7 feat/search-filters", key: "WEB-3" },
12143
+ { id: "demo-web-fix-login-redirect", label: "web \xB7 fix/login-redirect", key: "WEB-9" }
12144
+ ];
12145
+ function evidenceFor(n) {
12146
+ const pick = [WORK[n % WORK.length], WORK[(n + 2) % WORK.length]];
11442
12147
  return {
11443
- at: now.toISOString(),
11444
- updatedAt: ago(2),
11445
- threads: [
11446
- {
11447
- id: "PRRT_demo1",
11448
- path: "src/Shop.Orders/Refunds/RefundHandler.cs",
11449
- line: 6,
11450
- side: "right",
11451
- outdated: false,
11452
- resolved: false,
11453
- url: url("r1"),
11454
- comments: [
11455
- {
11456
- author: "ivo",
11457
- association: "MEMBER",
11458
- body: "Is `FindAsync` enough here, or should this lock the order row? Two support agents refunding the same order is not unusual.",
11459
- at: ago(20),
11460
- url: url("r1")
11461
- },
11462
- {
11463
- author: "marta",
11464
- association: "CONTRIBUTOR",
11465
- body: "Good point. I will look at a row version on Orders.",
11466
- at: ago(18),
11467
- url: url("r1b")
11468
- }
11469
- ]
11470
- },
11471
- {
11472
- id: "PRRT_demo2",
11473
- path: "src/Shop.Orders/Refunds/RefundValidator.cs",
11474
- line: 3,
11475
- side: "right",
11476
- outdated: false,
11477
- resolved: true,
11478
- url: url("r2"),
11479
- comments: [
11480
- { author: "ana", association: "OWNER", body: "Should a refund of 0 be allowed?", at: ago(30), url: url("r2") },
11481
- { author: "marta", association: "CONTRIBUTOR", body: "No: changed to `GreaterThan(0)`.", at: ago(26), url: url("r2b") }
11482
- ]
11483
- },
11484
- {
11485
- id: "PRRT_demo3",
11486
- path: "src/Shop.Orders/Pricing/Rounding.cs",
11487
- line: null,
11488
- originalLine: 3,
11489
- side: "right",
11490
- outdated: true,
11491
- resolved: false,
11492
- url: url("r3"),
11493
- comments: [
11494
- {
11495
- author: "ivo",
11496
- association: "MEMBER",
11497
- body: "Why banker\u2019s rounding in the first place? The invoices round half up.",
11498
- at: ago(40),
11499
- url: url("r3")
11500
- }
11501
- ]
11502
- }
11503
- ],
11504
- reviews: [
11505
- { author: "ivo", association: "MEMBER", state: "commented", body: "", at: ago(20), url: url("v1") },
11506
- { author: "ana", association: "OWNER", state: "approved", body: "Fine once the row locking is sorted.", at: ago(25), url: url("v2") }
12148
+ sessions: [
12149
+ { sessionId: pick[0].id, label: pick[0].label, key: pick[0].key, minutes: 25 + n * 7 % 30 },
12150
+ { sessionId: pick[1].id, label: pick[1].label, key: pick[1].key, minutes: 8 + n * 5 % 15 },
12151
+ ...n % 3 === 0 ? [{ sessionId: "demo-api-chore-deps-update", label: "api \xB7 chore/deps-update", key: null, minutes: 12 }] : []
11507
12152
  ],
11508
- comments: [
12153
+ commits: [
11509
12154
  {
11510
- author: "lea",
11511
- association: "MEMBER",
11512
- body: "Can this go in before Friday\u2019s release? Support is waiting for it.",
11513
- at: ago(6),
11514
- url: "https://github.com/example/api/pull/231#issuecomment-1"
12155
+ repo: pick[0].id.split("-")[1],
12156
+ sha: `c0ffee${n}0`,
12157
+ subject: `${pick[0].key}: ${TITLES[pick[0].key].toLowerCase()}, part ${n % 4 + 1}`,
12158
+ keys: [pick[0].key]
11515
12159
  }
11516
- ]
12160
+ ],
12161
+ jira: n % 4 === 1 ? [{ key: "WEB-9", summary: TITLES["WEB-9"], what: "moved (now In review)" }] : []
11517
12162
  };
11518
12163
  }
11519
- function demoReview(now = /* @__PURE__ */ new Date()) {
11520
- return {
11521
- ...buildReview(
11522
- {
11523
- repo: "api",
11524
- number: 231,
11525
- title: "Refunds: partial refunds on paid orders",
11526
- url: "https://github.com/example/api/pull/231",
11527
- author: "marta",
11528
- branch: "feat/refunds",
11529
- base: "main",
11530
- headSha: "a1b2c3d"
11531
- },
11532
- FILES,
11533
- { whitespaceOnly: /* @__PURE__ */ new Set(), generated: /* @__PURE__ */ new Set() },
11534
- DEMO_ANSWER,
11535
- { now, ignored: SPLIT.ignored }
11536
- ),
11537
- mergeBase: "base",
11538
- preparedAt: now.toISOString(),
11539
- discussion: demoDiscussion(now)
12164
+ var DEMO_DAYS = 31;
12165
+ function createDemoTime(now) {
12166
+ const edits = /* @__PURE__ */ new Map();
12167
+ const record = (day) => {
12168
+ const today = localDay(now());
12169
+ if (day > today) return null;
12170
+ const all = daysBetween(addDays(today, -(DEMO_DAYS - 1)), today);
12171
+ const n = all.indexOf(day);
12172
+ const e = edits.get(day) ?? {};
12173
+ if (n < 0 && !e.edited && !e.dayOff) return null;
12174
+ return {
12175
+ day,
12176
+ evidence: n >= 0 && isWorkday(day, SETTINGS2) ? evidenceFor(n) : { sessions: [], commits: [], jira: [] },
12177
+ titles: TITLES,
12178
+ builtAt: new Date(now()).toISOString(),
12179
+ edited: e.edited ?? null,
12180
+ dayOff: e.dayOff ?? false,
12181
+ posted: e.posted ?? null
12182
+ };
11540
12183
  };
11541
- }
11542
- function waitingReview(now) {
11543
- const { discussion: _none, ...prepared } = demoReview(now);
11544
12184
  return {
11545
- ...prepared,
11546
- number: 236,
11547
- title: "Upgrade to .NET 10",
11548
- url: "https://github.com/example/api/pull/236",
11549
- author: "ivo",
11550
- status: "waiting",
11551
- why: "4812 changed lines: over the size limit (3000), so it waits for your click",
11552
- size: { files: 0, added: 4100, deleted: 712 },
11553
- files: [],
11554
- stories: [],
11555
- unstoried: [],
11556
- drafts: [],
11557
- tests: { list: [], counts: { added: 0, changed: 0, removed: 0, skipped: 0 }, gaps: [], covers: {}, unitOnlyForSchema: false },
11558
- asserts: {},
11559
- aiStep: "none"
11560
- };
11561
- }
11562
- var noSessions = {
11563
- liveOn: () => null,
11564
- create: (alias, branch) => ({ id: `${alias}-${branch}`, label: `${alias} \xB7 ${branch}` }),
11565
- note: () => void 0
11566
- };
11567
- function mountDemoReviews(app, broadcast, sessions = noSessions) {
11568
- const now = /* @__PURE__ */ new Date();
11569
- const reviews = /* @__PURE__ */ new Map([
11570
- ["api#231", demoReview(now)],
11571
- ["api#236", waitingReview(new Date(now.getTime() - 36e5))]
11572
- ]);
11573
- const modes = { api: "all", web: "asked", docs: "off" };
11574
- const settings = () => ({
11575
- projects: Object.entries(modes).map(([name, mode]) => ({ name, kind: "repo", mode, from: "repo" })),
11576
- maxPerDay: null,
11577
- maxLines: 3e3
11578
- });
11579
- const key = (repo, n) => `${repo}#${n}`;
11580
- const store = {
11581
- read: (rp, num3) => reviews.get(key(rp, String(num3))) ?? null,
11582
- update: (rp, num3, change) => {
11583
- const was = reviews.get(key(rp, String(num3)));
11584
- if (!was) return null;
11585
- const next = change(was);
11586
- reviews.set(key(rp, String(num3)), next);
11587
- return next;
12185
+ days: (from, to) => daysWireOf(
12186
+ from,
12187
+ to,
12188
+ SETTINGS2,
12189
+ daysBetween(from, to).map(record).filter((r) => !!r)
12190
+ ),
12191
+ month: (month) => {
12192
+ const today = localDay(now());
12193
+ const r = monthRange(month, today);
12194
+ const records = r ? daysBetween(r.from, r.to).map(record).filter((x) => !!x) : [];
12195
+ return { ...monthWireOf(month, today, SETTINGS2, records), gathering: false, gatherError: null, posting: { ready: true, why: null } };
11588
12196
  },
11589
- pid: 0,
11590
- bootedAt: () => 0,
11591
- alive: () => true
12197
+ day: (day) => ({ ...dayWireOf(day, SETTINGS2, record(day)), posting: { ready: true, why: null } }),
12198
+ update: (day, change) => {
12199
+ edits.set(day, { ...edits.get(day) ?? {}, ...change });
12200
+ return { ...dayWireOf(day, SETTINGS2, record(day)), posting: { ready: true, why: null } };
12201
+ },
12202
+ /** "Posting": what the day shows is now what Tempo has (nothing leaves the demo). */
12203
+ post: (day) => {
12204
+ const w = dayWireOf(day, SETTINGS2, record(day));
12205
+ const before = record(day)?.posted?.entries ?? [];
12206
+ const kept = w.entries.filter((e) => before.some((b) => b.key === e.key && b.hours === e.hours)).length;
12207
+ edits.set(day, { ...edits.get(day) ?? {}, posted: { at: new Date(now()).toISOString(), entries: w.entries, worklogs: [] } });
12208
+ return {
12209
+ posted: w.entries.length - kept,
12210
+ removed: before.length - kept,
12211
+ kept,
12212
+ coveredByHand: 0,
12213
+ otherByHand: 0,
12214
+ failed: [],
12215
+ day: { ...dayWireOf(day, SETTINGS2, record(day)), posting: { ready: true, why: null } }
12216
+ };
12217
+ },
12218
+ settings: SETTINGS2
11592
12219
  };
11593
- app.get(
11594
- "/api/reviews",
11595
- (c) => c.json({
11596
- reviews: [...reviews.values()].map(summaryOf).sort((a, b) => b.at.localeCompare(a.at)),
11597
- today: 1,
11598
- maxPerDay: null
11599
- })
11600
- );
11601
- app.get("/api/reviews/settings", (c) => c.json(settings()));
11602
- app.put("/api/reviews/settings", async (c) => {
11603
- const body = await c.req.json().catch(() => null);
11604
- if (!body || typeof body.project !== "string" || !isReviewMode(body.mode))
11605
- return c.json({ error: "expected {project, mode: all|asked|off}" }, 400);
11606
- modes[body.project] = body.mode;
11607
- broadcast("reviews-changed", { settings: true });
11608
- return c.json(settings());
11609
- });
11610
- app.get("/api/reviews/:repo/:number", (c) => {
11611
- const r = reviews.get(key(c.req.param("repo"), c.req.param("number")));
11612
- return r ? c.json(shownReview(store, r)) : c.json({ error: "no review of that PR" }, 404);
11613
- });
11614
- app.get("/api/reviews/:repo/:number/diff", (c) => {
11615
- const r = reviews.get(key(c.req.param("repo"), c.req.param("number")));
11616
- return r && r.status === "ready" ? c.json({ files: FILES }) : c.json({ error: "no prepared review of that PR" }, 404);
11617
- });
11618
- app.post("/api/reviews/:repo/:number", (c) => {
11619
- const k = key(c.req.param("repo"), c.req.param("number"));
11620
- const was = reviews.get(k);
11621
- if (!was) return c.json({ error: "isn't an open pull request" }, 409);
11622
- const r = { ...demoReview(/* @__PURE__ */ new Date()), number: was.number, title: was.title, url: was.url, author: was.author };
11623
- reviews.set(k, r);
11624
- broadcast("reviews-changed", { repo: r.repo, number: r.number });
11625
- return c.json(r);
11626
- });
11627
- app.post("/api/reviews/:repo/:number/discussion", (c) => {
11628
- const r = reviews.get(key(c.req.param("repo"), c.req.param("number")));
11629
- return r ? c.json(shownReview(store, r)) : c.json({ error: "no review of that PR" }, 404);
11630
- });
11631
- app.post("/api/reviews/:repo/:number/drafts", async (c) => {
11632
- const k = key(c.req.param("repo"), c.req.param("number"));
11633
- const r = reviews.get(k);
11634
- if (!r) return c.json({ error: "no review of that PR" }, 404);
11635
- const added = addDraft(r, await c.req.json().catch(() => null));
11636
- if ("error" in added) return c.json({ error: added.error }, 400);
11637
- reviews.set(k, added.review);
11638
- broadcast("reviews-changed", { repo: r.repo, number: r.number });
11639
- return c.json(added.review);
11640
- });
11641
- app.post("/api/reviews/:repo/:number/submit", async (c) => {
11642
- const repo = c.req.param("repo");
11643
- const n = /^\d+$/.test(c.req.param("number")) ? Number(c.req.param("number")) : null;
11644
- if (n === null) return c.json({ error: "no review of that PR" }, 404);
11645
- const input = await c.req.json().catch(() => null);
11646
- const out = await submitPrReview(
11647
- {
11648
- ...store,
11649
- repoPath: (alias) => alias === "api" ? "/demo/api" : null,
11650
- submit: async (_at, num3, review) => demoHostSubmit(reviews.get(key(repo, String(num3)))?.url ?? "", review)
11651
- },
11652
- repo,
11653
- n,
11654
- input
11655
- );
11656
- if (out.ok || out.review) broadcast("reviews-changed", { repo, number: n });
11657
- if (out.ok) return c.json(out.review);
11658
- return c.json({ error: out.error, ...out.review ? { review: out.review } : {} }, out.status);
11659
- });
11660
- app.post("/api/reviews/:repo/:number/fix-myself", async (c) => {
11661
- const repo = c.req.param("repo");
11662
- const n = /^\d+$/.test(c.req.param("number")) ? Number(c.req.param("number")) : null;
11663
- if (n === null || !reviews.get(key(repo, String(n)))) return c.json({ error: "no review of that PR" }, 404);
11664
- const input = await c.req.json().catch(() => null);
11665
- const out = await fixItMyself(
12220
+ }
12221
+
12222
+ // src/server/demo/demo-replies.ts
12223
+ function mountDemoReplies(app, scenario, emit) {
12224
+ const byId = /* @__PURE__ */ new Map();
12225
+ const deps = scenario.list().find((s) => s.branch === "chore/deps-update");
12226
+ if (deps) {
12227
+ const at = new Date(Date.now() - 20 * 6e4).toISOString();
12228
+ byId.set(deps.id, [
11666
12229
  {
11667
- read: store.read,
11668
- update: store.update,
11669
- lookUp: async (r) => r.fork ? { ok: false, error: "it comes from a fork: its branch isn't on origin" } : {
11670
- ok: true,
11671
- pr: { alias: r.repo, number: r.number, title: r.title, url: r.url, branch: r.branch, base: r.base, author: r.author }
11672
- },
11673
- liveSessionOn: (alias, branch) => sessions.liveOn(alias, branch),
11674
- create: async (alias, branch, name) => {
11675
- const s = sessions.create(alias, branch, name);
11676
- return { ok: true, sessionId: s.id, label: s.label };
12230
+ threadId: "PRRT_demo_zod",
12231
+ repo: "api",
12232
+ prNumber: 212,
12233
+ url: "https://github.com/example/api/pull/212#discussion_r1",
12234
+ where: "src/schema.ts:14",
12235
+ reviewer: "dana",
12236
+ excerpt: "zod 4 changed `.nonempty()` \u2014 does this still reject empty arrays?",
12237
+ body: "zod 4 changed `.nonempty()` \u2014 does this still reject empty arrays?\n\nIf not, this would do it:\n\n```suggestion\n items: z.array(Item).min(1),\n```",
12238
+ code: {
12239
+ hunk: '@@ -10,6 +10,6 @@ export const Order = z.object({\n id: z.string().uuid(),\n customer: Customer,\n currency: z.enum(["EUR", "USD"]),\n- items: z.array(Item).min(1),\n+ items: z.array(Item).nonempty(),\n note: z.string().optional(),',
12240
+ lines: 1
11677
12241
  },
11678
- // The demo's agent "starts" on its instruction: a note it answers, as every demo note.
11679
- start: async (id, prompt) => sessions.note(id, prompt),
11680
- note: async (id, body) => sessions.note(id, body)
12242
+ status: "draft",
12243
+ draft: "Yes \u2014 switched to `.min(1)`, which zod 4 keeps, and added a test for the empty case (a1b2c3d).",
12244
+ sentAt: at,
12245
+ draftedAt: at
11681
12246
  },
11682
- repo,
11683
- n,
11684
- input
11685
- );
11686
- if (!out.ok) return c.json({ error: out.error }, out.status);
11687
- broadcast("reviews-changed", { repo, number: n });
11688
- broadcast("sessions-changed", { ts: Date.now() });
11689
- const { ok: _ok, ...wire } = out;
11690
- return c.json(wire);
11691
- });
11692
- app.post("/api/reviews/:repo/:number/in-doubt", async (c) => {
11693
- const k = key(c.req.param("repo"), c.req.param("number"));
11694
- const r = reviews.get(k);
11695
- if (!r) return c.json({ error: "no review of that PR" }, 404);
11696
- const body = await c.req.json().catch(() => null);
11697
- if (!body || typeof body.went !== "boolean") return c.json({ error: "expected {went: true|false}" }, 400);
11698
- const out = settlePrReview(store, r.repo, r.number, body.went);
11699
- if (!out.ok) return c.json({ error: out.error }, out.status);
11700
- broadcast("reviews-changed", { repo: r.repo, number: r.number });
11701
- return c.json(out.review);
12247
+ {
12248
+ threadId: "PRRT_demo_lock",
12249
+ repo: "api",
12250
+ prNumber: 212,
12251
+ url: "https://github.com/example/api/pull/212#discussion_r2",
12252
+ where: "package-lock.json",
12253
+ reviewer: "copilot-pull-request-reviewer",
12254
+ excerpt: "The lockfile also bumps `express` to a new major version; was that intended?",
12255
+ status: "sent",
12256
+ draft: null,
12257
+ sentAt: at
12258
+ }
12259
+ ]);
12260
+ }
12261
+ const list = (id) => byId.get(id) ?? [];
12262
+ const find = (id, thread) => list(id).find((r) => r.threadId === thread);
12263
+ app.get("/api/sessions/:id/replies", (c) => c.json({ replies: list(c.req.param("id")), waiting: [] }));
12264
+ app.put("/api/sessions/:id/replies/:thread", async (c) => {
12265
+ const r = find(c.req.param("id"), c.req.param("thread"));
12266
+ const b = await c.req.json().catch(() => ({}));
12267
+ if (!r || typeof b.body !== "string" || !b.body.trim()) return c.json({ error: "unknown thread or empty reply" }, 400);
12268
+ Object.assign(r, { status: "draft", draft: b.body.trim(), draftedAt: (/* @__PURE__ */ new Date()).toISOString() });
12269
+ emit(c.req.param("id"));
12270
+ return c.json({ reply: r });
11702
12271
  });
11703
- app.delete("/api/reviews/:repo/:number/dropped", (c) => {
11704
- const k = key(c.req.param("repo"), c.req.param("number"));
11705
- const r = reviews.get(k);
11706
- if (!r) return c.json({ error: "no review of that PR" }, 404);
11707
- const next = clearDropped(r);
11708
- reviews.set(k, next);
11709
- broadcast("reviews-changed", { repo: r.repo, number: r.number });
11710
- return c.json(next);
12272
+ app.delete("/api/sessions/:id/replies/:thread", (c) => {
12273
+ const id = c.req.param("id");
12274
+ byId.set(
12275
+ id,
12276
+ list(id).filter((r) => r.threadId !== c.req.param("thread"))
12277
+ );
12278
+ emit(id);
12279
+ return c.json({ ok: true });
11711
12280
  });
11712
- app.delete("/api/reviews/:repo/:number/drafts/:id", (c) => {
11713
- const k = key(c.req.param("repo"), c.req.param("number"));
11714
- const r = reviews.get(k);
11715
- if (!r) return c.json({ error: "no review of that PR" }, 404);
11716
- const out = removeDraft(r, c.req.param("id"));
11717
- if ("error" in out) return c.json({ error: out.error }, out.status);
11718
- reviews.set(k, out.review);
11719
- broadcast("reviews-changed", { repo: r.repo, number: r.number });
11720
- return c.json(out.review);
12281
+ app.post("/api/sessions/:id/replies/:thread/post", async (c) => {
12282
+ const r = find(c.req.param("id"), c.req.param("thread"));
12283
+ const b = await c.req.json().catch(() => ({}));
12284
+ if (!r || typeof b.body !== "string" || !b.body.trim()) return c.json({ error: "unknown thread or empty reply" }, 400);
12285
+ Object.assign(r, {
12286
+ status: "posted",
12287
+ draft: b.body.trim(),
12288
+ postedAt: (/* @__PURE__ */ new Date()).toISOString(),
12289
+ postedUrl: r.url,
12290
+ resolved: b.resolve === true
12291
+ });
12292
+ emit(c.req.param("id"));
12293
+ return c.json({ ok: true, url: r.url, resolved: b.resolve === true });
11721
12294
  });
12295
+ app.post("/api/replies-changed", (c) => c.json({ ok: true }));
12296
+ return (id) => list(id).filter((r) => r.status === "draft").length;
11722
12297
  }
11723
12298
 
11724
12299
  // src/server/demo/demo-settings.ts
@@ -11746,13 +12321,13 @@ function createDemoSettings(repoPathOf) {
11746
12321
  };
11747
12322
  return {
11748
12323
  read,
11749
- async write(path20, value) {
11750
- const f = settingAt(path20);
11751
- if (!f) throw new SettingsError(`no setting ${path20}`, 404);
12324
+ async write(path21, value) {
12325
+ const f = settingAt(path21);
12326
+ if (!f) throw new SettingsError(`no setting ${path21}`, 404);
11752
12327
  const r = checkSetting(f, value);
11753
12328
  if (!r.ok) throw new SettingsError(`${f.label}: ${r.error}`);
11754
- if (r.value === null) delete values[path20];
11755
- else values[path20] = r.value;
12329
+ if (r.value === null) delete values[path21];
12330
+ else values[path21] = r.value;
11756
12331
  return read();
11757
12332
  },
11758
12333
  readRepo,
@@ -11934,6 +12509,82 @@ async function startDemoServer(opts) {
11934
12509
  });
11935
12510
  return c.json({ events });
11936
12511
  });
12512
+ const localReviews = /* @__PURE__ */ new Set();
12513
+ const demoLocalReview = (w) => {
12514
+ if (!localReviews.has(w.id)) return { status: "none", repo: null, repos: [] };
12515
+ const r = demoReview(new Date(scenario.clockMs()));
12516
+ return {
12517
+ status: "ready",
12518
+ repo: r.repo,
12519
+ repos: [r.repo],
12520
+ at: new Date(scenario.clockMs()).toISOString(),
12521
+ review: { ...r, number: 0, url: "", author: "you", title: `Local changes on ${w.branch}`, branch: w.branch, discussion: void 0 }
12522
+ };
12523
+ };
12524
+ app.get("/api/sessions/:id/review", (c) => {
12525
+ const w = scenario.list().find((x) => x.id === c.req.param("id"));
12526
+ return w ? c.json(demoLocalReview(w)) : notFound(c);
12527
+ });
12528
+ app.post("/api/sessions/:id/review", (c) => {
12529
+ const w = scenario.list().find((x) => x.id === c.req.param("id"));
12530
+ if (!w) return notFound(c);
12531
+ if (w.archivedAt) return c.json({ error: "It is archived: restore it first." }, 409);
12532
+ localReviews.add(w.id);
12533
+ broadcast({ event: "session-review-changed", data: { sessionId: w.id } });
12534
+ return c.json(demoLocalReview(w));
12535
+ });
12536
+ app.get("/api/sessions/:id/review/diff", (c) => {
12537
+ const w = scenario.list().find((x) => x.id === c.req.param("id"));
12538
+ if (!w) return notFound(c);
12539
+ return localReviews.has(w.id) ? c.json({ files: demoReviewFiles() }) : c.json({ error: "no review of it is prepared" }, 404);
12540
+ });
12541
+ app.post("/api/sessions/:id/review/send", async (c) => {
12542
+ const w = scenario.list().find((x) => x.id === c.req.param("id"));
12543
+ if (!w) return notFound(c);
12544
+ const review = demoLocalReview(w).review;
12545
+ if (!review) return c.json({ error: "no review of it is prepared" }, 409);
12546
+ const body = await json2(c);
12547
+ const ids = Array.isArray(body.ids) ? new Set(body.ids) : null;
12548
+ const sent = review.drafts.filter((d) => d.state === "draft" && (!ids || ids.has(d.id))).length;
12549
+ return sent ? c.json({ ok: true, sent }) : c.json({ error: "It has no notes to hand over." }, 409);
12550
+ });
12551
+ const stoppedProcs = /* @__PURE__ */ new Set();
12552
+ const demoProcesses = (id) => {
12553
+ const at = scenario.clockMs();
12554
+ const base = 4e3 + parseInt(id.slice(0, 4), 16) % 3e3;
12555
+ const all = [
12556
+ { pid: base, what: "claude --continue", memBytes: 760 * 1048576, startedAt: at - 3 * 36e5, agent: true },
12557
+ {
12558
+ pid: base + 1,
12559
+ what: "node \u2026/node_modules/vite/bin/vite.js --mode mock",
12560
+ memBytes: 1340 * 1048576,
12561
+ startedAt: at - 50 * 36e5,
12562
+ leftover: true
12563
+ },
12564
+ { pid: base + 2, what: "dotnet test", memBytes: 510 * 1048576, startedAt: at - 12 * 6e4 }
12565
+ ];
12566
+ const processes = all.filter((p) => !stoppedProcs.has(`${id}:${p.pid}`));
12567
+ return {
12568
+ at,
12569
+ totalBytes: processes.reduce((n, p) => n + (p.memBytes ?? 0), 0),
12570
+ leftovers: processes.filter((p) => p.leftover).length,
12571
+ processes
12572
+ };
12573
+ };
12574
+ app.get("/api/sessions/:id/processes", (c) => {
12575
+ const w = scenario.list().find((x) => x.id === c.req.param("id"));
12576
+ return w ? c.json(demoProcesses(w.id)) : notFound(c);
12577
+ });
12578
+ app.post("/api/sessions/:id/processes/stop", async (c) => {
12579
+ const w = scenario.list().find((x) => x.id === c.req.param("id"));
12580
+ if (!w) return notFound(c);
12581
+ const body = await json2(c);
12582
+ if (typeof body.pid !== "number") return c.json({ error: "expected {pid, startedAt}" }, 400);
12583
+ const why = stopRefusal(demoProcesses(w.id), body.pid, typeof body.startedAt === "number" ? body.startedAt : null);
12584
+ if (why) return c.json({ error: `Not stopped: ${why}.` }, 409);
12585
+ stoppedProcs.add(`${w.id}:${body.pid}`);
12586
+ return c.json(demoProcesses(w.id));
12587
+ });
11937
12588
  const notes = /* @__PURE__ */ new Map();
11938
12589
  app.get("/api/sessions/:id/note", (c) => {
11939
12590
  const w = scenario.list().find((x) => x.id === c.req.param("id"));
@@ -11977,6 +12628,7 @@ async function startDemoServer(opts) {
11977
12628
  return c.json({ catchUp: v });
11978
12629
  });
11979
12630
  const snoozes = /* @__PURE__ */ new Map();
12631
+ const kept = /* @__PURE__ */ new Set();
11980
12632
  app.get(
11981
12633
  "/api/sessions",
11982
12634
  (c) => c.json({
@@ -11987,7 +12639,8 @@ async function startDemoServer(opts) {
11987
12639
  (b) => b.kind === "pr" || scenario.list().some((x) => x.id === b.sessionId && !x.archivedAt)
11988
12640
  );
11989
12641
  const withBlocks = waiting.length ? { ...out, blockedBy: waiting } : out;
11990
- const noted = notes.has(w.id) ? { ...withBlocks, hasNote: true } : withBlocks;
12642
+ const withNote = notes.has(w.id) ? { ...withBlocks, hasNote: true } : withBlocks;
12643
+ const noted = kept.has(w.id) && !w.archivedAt ? { ...withNote, keepAfterMerge: true } : withNote;
11991
12644
  return z8 && snoozeActive(z8, noted) ? { ...noted, snoozed: { until: z8.until } } : noted;
11992
12645
  })
11993
12646
  })
@@ -12215,6 +12868,16 @@ async function startDemoServer(opts) {
12215
12868
  demoFolders = demoFolders.filter((f) => !ids.includes(f.sessionId));
12216
12869
  return c.json({ results, state: folderState() });
12217
12870
  });
12871
+ app.post("/api/sessions/:id/keep", async (c) => {
12872
+ const id = c.req.param("id");
12873
+ if (!scenario.list().some((w) => w.id === id)) return c.json({ error: "unknown session" }, 404);
12874
+ const body = await c.req.json().catch(() => null);
12875
+ if (typeof body?.keep !== "boolean") return c.json({ error: "keep: boolean" }, 400);
12876
+ if (body.keep) kept.add(id);
12877
+ else kept.delete(id);
12878
+ broadcast({ event: "sessions-changed", data: { ts: Date.now() } });
12879
+ return c.json({ ok: true, keep: body.keep });
12880
+ });
12218
12881
  app.post("/api/sessions/:id/title", (c) => c.json({ ok: true }));
12219
12882
  let demoBranches = [
12220
12883
  { repo: "api", repoPath: "C:/repos/api", branch: "feat/old-export", tip: "0f3c2a91d4", reason: "squash-merged", prNumber: 41 },
@@ -12562,6 +13225,18 @@ async function startDemoServer(opts) {
12562
13225
  scenario.accountsChanged();
12563
13226
  return c.json({ ok: true, installingSkills: false });
12564
13227
  });
13228
+ app.post("/api/accounts/:name/sessions", async (c) => {
13229
+ const to = c.req.param("name");
13230
+ const from = (await json2(c)).from;
13231
+ const rows = scenario.list().filter((w) => !w.archivedAt && (w.account ?? "default") !== to && (typeof from !== "string" || (w.account ?? "default") === from)).map((w) => {
13232
+ const r = scenario.switchAccount(w.id, to);
13233
+ const label = `${w.target} \xB7 ${w.branch}`;
13234
+ return r?.ok ? { id: w.id, label, outcome: r.body.outcome } : { id: w.id, label, error: r?.error ?? "unknown session" };
13235
+ });
13236
+ if (rows.length > 0 && rows.every((r) => "error" in r)) return c.json({ error: rows[0].error }, 409);
13237
+ scenario.accountsChanged();
13238
+ return c.json({ ok: true, summary: switchAllSummary(rows, to), sessions: rows });
13239
+ });
12565
13240
  app.post("/api/sessions/:id/account", async (c) => {
12566
13241
  const to = (await json2(c)).to;
12567
13242
  if (typeof to !== "string" || !to) return c.json({ error: "to is required" }, 400);
@@ -12764,8 +13439,8 @@ async function startDemoServer(opts) {
12764
13439
 
12765
13440
  // src/core/platform/web-life.ts
12766
13441
  import fs19 from "fs";
12767
- import path19 from "path";
12768
- var lifePath = () => path19.join(getConfigDir(), "web-life.json");
13442
+ import path20 from "path";
13443
+ var lifePath = () => path20.join(getConfigDir(), "web-life.json");
12769
13444
  function isLife(v) {
12770
13445
  const l = v;
12771
13446
  return !!l && typeof l === "object" && typeof l.pid === "number" && typeof l.version === "string" && typeof l.startedAt === "string" && typeof l.lastSeen === "string" && (l.ended === void 0 || typeof l.ended?.at === "string" && typeof l.ended?.how === "string");
@@ -13155,4 +13830,4 @@ export {
13155
13830
  stopExisting,
13156
13831
  webCommand
13157
13832
  };
13158
- //# sourceMappingURL=web-7FRKYLDS.js.map
13833
+ //# sourceMappingURL=web-AXS3EMZ3.js.map