@moberg_hr/work-tree 2.11.4 → 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 (292) hide show
  1. package/dist/{account-JOKEFQ46.js → account-EAVYWOKR.js} +38 -24
  2. package/dist/account-EAVYWOKR.js.map +1 -0
  3. package/dist/{add-repo-JKVHNRWU.js → add-repo-3THEK6UG.js} +22 -22
  4. package/dist/{answer-PDCLL5Z2.js → answer-3CJQWBGY.js} +13 -13
  5. package/dist/{attach-BIFQP5OY.js → attach-FQSBZXI7.js} +19 -19
  6. package/dist/bin.js +4 -4
  7. package/dist/{block-EI3OQVDM.js → block-NGD2KNTU.js} +18 -18
  8. package/dist/{broadcast-ZSA3L5FY.js → broadcast-NLASZGWR.js} +10 -10
  9. package/dist/{catchup-SNMGWNRX.js → catchup-WJPWOGVI.js} +16 -16
  10. package/dist/{chunk-2R6EHVZG.js → chunk-3257QPVM.js} +3 -3
  11. package/dist/{chunk-IYWNDEXA.js → chunk-3KVOYBM4.js} +6 -6
  12. package/dist/{chunk-HJ2RKMBI.js → chunk-3O6QFWZ6.js} +2 -2
  13. package/dist/{chunk-MGNJPBZU.js → chunk-45MDVVW7.js} +6 -6
  14. package/dist/{chunk-K7Y7YTN3.js → chunk-5LUXNIPA.js} +2 -2
  15. package/dist/{chunk-M7FX37Z2.js → chunk-5RAAS4II.js} +9 -7
  16. package/dist/{chunk-M7FX37Z2.js.map → chunk-5RAAS4II.js.map} +1 -1
  17. package/dist/{chunk-73MGZAGV.js → chunk-64M7W2OQ.js} +5 -5
  18. package/dist/{chunk-AU7XGTJZ.js → chunk-7FNJ6A2U.js} +3 -3
  19. package/dist/{chunk-WQN7HJK6.js → chunk-7IZVI76D.js} +10 -10
  20. package/dist/{chunk-PMEOGFGV.js → chunk-7UXV4X2Y.js} +2 -2
  21. package/dist/{chunk-RH4BGTER.js → chunk-ACNCTLFO.js} +3 -3
  22. package/dist/{chunk-BLOV7ECI.js → chunk-AGRUEZQX.js} +2 -2
  23. package/dist/{chunk-2VYWTBC6.js → chunk-ANS6OH55.js} +3 -3
  24. package/dist/{chunk-HRUKMBF3.js → chunk-AYHDJMMJ.js} +2 -2
  25. package/dist/{chunk-F7IOGLKV.js → chunk-B2K2I2PQ.js} +26 -8
  26. package/dist/chunk-B2K2I2PQ.js.map +1 -0
  27. package/dist/{chunk-ZJBVZ4OJ.js → chunk-BHJ73OPQ.js} +4 -4
  28. package/dist/{chunk-7HQM5NYN.js → chunk-BK73QU45.js} +3 -3
  29. package/dist/{chunk-BENY64FW.js → chunk-BW5U6ENJ.js} +4 -4
  30. package/dist/{chunk-VADGWMXL.js → chunk-C72Y42VC.js} +6 -6
  31. package/dist/{chunk-7OZZUQDW.js → chunk-C7ZKDWPI.js} +4 -4
  32. package/dist/{chunk-PHHBZDO2.js → chunk-CS2EINZJ.js} +58 -58
  33. package/dist/{chunk-ZX2VBM2F.js → chunk-CVMO75V5.js} +4 -4
  34. package/dist/{chunk-QRYZAY7R.js → chunk-DHOC2S2L.js} +8 -8
  35. package/dist/{chunk-DMGNJ73M.js → chunk-DROLR3NJ.js} +2 -2
  36. package/dist/{chunk-KJRUC2QY.js → chunk-DS2CKYQ4.js} +2 -2
  37. package/dist/{chunk-KCDHOW22.js → chunk-DTFACBDD.js} +182 -94
  38. package/dist/chunk-DTFACBDD.js.map +1 -0
  39. package/dist/{chunk-VQACXAFX.js → chunk-DW245WK4.js} +9 -4
  40. package/dist/chunk-DW245WK4.js.map +1 -0
  41. package/dist/{chunk-MBSCZQ2C.js → chunk-DZ6SLAIZ.js} +2 -2
  42. package/dist/{chunk-XZKQHQBB.js → chunk-EJSGPLXO.js} +7 -5
  43. package/dist/{chunk-XZKQHQBB.js.map → chunk-EJSGPLXO.js.map} +1 -1
  44. package/dist/{chunk-BDPRYJL3.js → chunk-EYDGX32Q.js} +2 -2
  45. package/dist/chunk-FC7RECDP.js +9 -0
  46. package/dist/{chunk-SC2FQ6BR.js → chunk-FM6VLU4T.js} +5 -5
  47. package/dist/{chunk-WYQD44Y4.js → chunk-G2V2V5UC.js} +7 -3
  48. package/dist/chunk-G2V2V5UC.js.map +1 -0
  49. package/dist/{chunk-6MMXVHPL.js → chunk-H4TMS567.js} +7 -7
  50. package/dist/{chunk-NFWSJFYY.js → chunk-HHXVHUGP.js} +2 -2
  51. package/dist/{chunk-3QEDOZMA.js → chunk-HORDAO4Z.js} +4 -4
  52. package/dist/{chunk-E6WVQXF4.js → chunk-I3FLUAK7.js} +3 -3
  53. package/dist/{chunk-RIEBQWQC.js → chunk-I7AEQDG7.js} +2 -2
  54. package/dist/{chunk-O5ZJY5BT.js → chunk-INI6TEYT.js} +2 -1
  55. package/dist/chunk-INI6TEYT.js.map +1 -0
  56. package/dist/{chunk-CL3SSNBC.js → chunk-IREGW23T.js} +2 -2
  57. package/dist/{chunk-YKQLHFY4.js → chunk-IUWMT6PF.js} +48 -4
  58. package/dist/chunk-IUWMT6PF.js.map +1 -0
  59. package/dist/{chunk-GAE3NB3G.js → chunk-JIWPC53O.js} +9 -9
  60. package/dist/{chunk-U3RRXU6W.js → chunk-JNAYPBAB.js} +7 -7
  61. package/dist/{chunk-TW44C7CG.js → chunk-JVRS73M6.js} +6 -6
  62. package/dist/{chunk-CSTPOCV2.js → chunk-K5EAVRXX.js} +3 -3
  63. package/dist/{chunk-WV5U4S5N.js → chunk-KCWU6HNJ.js} +8 -8
  64. package/dist/{chunk-KKVWDMSM.js → chunk-LSZ6HI3U.js} +2 -2
  65. package/dist/{chunk-253Q6TOC.js → chunk-MKQ7IA6U.js} +3 -3
  66. package/dist/{chunk-3XU7Y2MV.js → chunk-N5PQHNYK.js} +2 -2
  67. package/dist/{chunk-3PXA5RJ2.js → chunk-NOB3VR5I.js} +37 -118
  68. package/dist/chunk-NOB3VR5I.js.map +1 -0
  69. package/dist/{chunk-BTR2E5WD.js → chunk-NUPLJJOS.js} +17 -16
  70. package/dist/chunk-NUPLJJOS.js.map +1 -0
  71. package/dist/{chunk-FFL7ETBY.js → chunk-OIVEYULL.js} +6 -6
  72. package/dist/{chunk-2YKV6MNQ.js → chunk-OTKWVUGB.js} +3 -3
  73. package/dist/{chunk-LPHYUNMD.js → chunk-PGGNMC34.js} +5 -3
  74. package/dist/{chunk-LPHYUNMD.js.map → chunk-PGGNMC34.js.map} +1 -1
  75. package/dist/{chunk-DMA3XCMF.js → chunk-RPWEOEA3.js} +11 -7
  76. package/dist/chunk-RPWEOEA3.js.map +1 -0
  77. package/dist/{chunk-CJ2QTQHG.js → chunk-RSCRZGUW.js} +2 -2
  78. package/dist/{chunk-N75AJ3ZR.js → chunk-S36RENUJ.js} +3 -3
  79. package/dist/{chunk-SQ4ZGEZY.js → chunk-SPVVXKDV.js} +2 -2
  80. package/dist/chunk-SQACJQUY.js +37 -0
  81. package/dist/chunk-SQACJQUY.js.map +1 -0
  82. package/dist/{chunk-KP2CI5QU.js → chunk-TFNDOWYP.js} +4 -4
  83. package/dist/{chunk-SMXRY653.js → chunk-TL7K3XUY.js} +7 -7
  84. package/dist/{chunk-HECIDNBU.js → chunk-TMAQASMH.js} +9 -9
  85. package/dist/{chunk-6C7CR2W2.js → chunk-TMBO55MM.js} +2 -2
  86. package/dist/{chunk-GV3KXHF3.js → chunk-TSFNTMMY.js} +3 -3
  87. package/dist/{chunk-5DUKO7WC.js → chunk-TUDDISCX.js} +6 -3
  88. package/dist/{chunk-3UI35AFZ.js → chunk-U2MOKVPZ.js} +2 -2
  89. package/dist/{chunk-RXZKYHSW.js → chunk-UQJQZ526.js} +5 -5
  90. package/dist/{chunk-RUUEZSQY.js → chunk-VPFAXLSX.js} +10 -8
  91. package/dist/{chunk-RUUEZSQY.js.map → chunk-VPFAXLSX.js.map} +1 -1
  92. package/dist/{chunk-VJ5XMYXE.js → chunk-VVRSPS67.js} +2 -2
  93. package/dist/{chunk-5ZU6H62F.js → chunk-ZIFWZJ7X.js} +2 -2
  94. package/dist/{chunk-3LDQPUJ6.js → chunk-ZQJKAZRD.js} +10 -10
  95. package/dist/{chunk-3QKH7JNR.js → chunk-ZS7ZXAXB.js} +33 -2
  96. package/dist/chunk-ZS7ZXAXB.js.map +1 -0
  97. package/dist/{cleanup-5CPX253G.js → cleanup-GFYEKCJS.js} +40 -40
  98. package/dist/cli-QP3BQXVW.js +20 -0
  99. package/dist/{completion-QCB7PKKT.js → completion-OEU4UZEA.js} +4 -4
  100. package/dist/{config-EQFAXBMQ.js → config-W3AEOOUK.js} +16 -16
  101. package/dist/{diff-MLCUMIYC.js → diff-G53V34KI.js} +16 -16
  102. package/dist/{digest-KSAGLQND.js → digest-W4425I4J.js} +13 -13
  103. package/dist/{fork-RCTVMUYI.js → fork-HTPJML6G.js} +36 -36
  104. package/dist/{history-N4ZURR4F.js → history-TYKH3SKB.js} +10 -10
  105. package/dist/{hook-DRZVYLJB.js → hook-F7WR5UIQ.js} +18 -18
  106. package/dist/{hydrate-NVJZZAFT.js → hydrate-HDZ62YMD.js} +11 -11
  107. package/dist/{init-RF6YC4BQ.js → init-Q5KJ666H.js} +21 -21
  108. package/dist/install-skills-C46BIZ5O.js +23 -0
  109. package/dist/install-skills-bin.js +9 -9
  110. package/dist/{keep-7Q3B6QT5.js → keep-MYHUCQWD.js} +12 -12
  111. package/dist/{list-PIJ4ROHR.js → list-BGHRHYV6.js} +12 -12
  112. package/dist/{move-XAZG3MJT.js → move-OHV2DC4V.js} +26 -26
  113. package/dist/{note-JJXIQ4QK.js → note-2I5WTKED.js} +12 -12
  114. package/dist/{overlaps-3YN4UQWC.js → overlaps-PX4BD23H.js} +20 -20
  115. package/dist/{pin-OOCB6DFR.js → pin-UTMH2XUZ.js} +12 -12
  116. package/dist/{pr-LCG4W65A.js → pr-PZCO36TY.js} +28 -28
  117. package/dist/{prune-2NGAUOPI.js → prune-APCNVQKK.js} +38 -38
  118. package/dist/{pty-host-XRXRI6UL.js → pty-host-Q5VNQKP2.js} +38 -18
  119. package/dist/pty-host-Q5VNQKP2.js.map +1 -0
  120. package/dist/{read-FJDDCX4D.js → read-HSQNG4CA.js} +12 -12
  121. package/dist/{recent-AAXLCQUF.js → recent-SNDWYLUH.js} +18 -18
  122. package/dist/{remove-VO5V45IJ.js → remove-5F5SP5TM.js} +50 -38
  123. package/dist/remove-5F5SP5TM.js.map +1 -0
  124. package/dist/{restart-AP763LE2.js → restart-HWSAV22N.js} +13 -13
  125. package/dist/{resume-SPO5XNDT.js → resume-DBO7FTEQ.js} +18 -18
  126. package/dist/{review-5IGFQF2T.js → review-36OJ5EES.js} +11 -9
  127. package/dist/{review-5IGFQF2T.js.map → review-36OJ5EES.js.map} +1 -1
  128. package/dist/{review-now-HHQIBVUS.js → review-now-CZPT7X4K.js} +3 -3
  129. package/dist/{run-JZWZHJOE.js → run-QQARI2AH.js} +10 -10
  130. package/dist/{screen-JRMMYVHB.js → screen-SXJEHTUY.js} +13 -13
  131. package/dist/{search-XOWMVFP2.js → search-U25QWSX4.js} +10 -10
  132. package/dist/{section-7WO7IHG6.js → section-TCH4DXE7.js} +12 -12
  133. package/dist/{send-OCSMOCUE.js → send-ZCKMC65W.js} +14 -14
  134. package/dist/{sessions-UAZALGGH.js → sessions-7PKZZ4NG.js} +32 -32
  135. package/dist/{snooze-UDJ5UDCS.js → snooze-JBPRRYAF.js} +12 -12
  136. package/dist/{start-OEG3T2SW.js → start-L6AWLRVP.js} +13 -13
  137. package/dist/{state-BR43ONIH.js → state-JHCC5CAR.js} +2 -2
  138. package/dist/{status-R4T2EHG5.js → status-WWRZLDGT.js} +17 -17
  139. package/dist/{statusline-3H3HAPCZ.js → statusline-MIFW47UA.js} +7 -7
  140. package/dist/{statusline-hook-FILOARNM.js → statusline-hook-W7KWKWAC.js} +5 -5
  141. package/dist/{stop-D3LRCCJS.js → stop-WHUBU5JZ.js} +13 -13
  142. package/dist/{sync-FWC2EWLW.js → sync-AVDUHYPQ.js} +38 -38
  143. package/dist/{time-AMAMIDWD.js → time-MIJM6SM6.js} +13 -13
  144. package/dist/{time-actions-YOXF5WC7.js → time-actions-Y5USDGSE.js} +3 -3
  145. package/dist/{timesheet-QFBA2Z2A.js → timesheet-AVRH56TG.js} +22 -22
  146. package/dist/{todo-TALKJYK6.js → todo-O6Y5MEQR.js} +2 -2
  147. package/dist/{tree-PJM2R2VA.js → tree-7YD6DL3H.js} +45 -40
  148. package/dist/{tree-PJM2R2VA.js.map → tree-7YD6DL3H.js.map} +1 -1
  149. package/dist/{update-RVZMM54Z.js → update-XGT2DFTT.js} +22 -22
  150. package/dist/{usage-W4UXQUPD.js → usage-7NM6L2MR.js} +12 -12
  151. package/dist/{version-WPF664CL.js → version-V7IM2UL4.js} +9 -9
  152. package/dist/{wait-C3S7Q6FA.js → wait-HCIFDLNX.js} +13 -13
  153. package/dist/wd-bin.js +7 -7
  154. package/dist/web/assets/{PtyView-Bq8MHIjd.js → PtyView-R0tQXVW8.js} +2 -2
  155. package/dist/web/assets/{PtyView-Bq8MHIjd.js.map → PtyView-R0tQXVW8.js.map} +1 -1
  156. package/dist/web/assets/index-Beb-xh6z.js +126 -0
  157. package/dist/web/assets/index-Beb-xh6z.js.map +1 -0
  158. package/dist/web/assets/{index-vHIk7hQs.css → index-QlOaahcZ.css} +1 -1
  159. package/dist/web/index.html +2 -2
  160. package/dist/{web-MPSYOYQ2.js → web-AXS3EMZ3.js} +1862 -1216
  161. package/dist/web-AXS3EMZ3.js.map +1 -0
  162. package/npm-shrinkwrap.json +2 -2
  163. package/package.json +1 -1
  164. package/dist/account-JOKEFQ46.js.map +0 -1
  165. package/dist/chunk-3PXA5RJ2.js.map +0 -1
  166. package/dist/chunk-3QKH7JNR.js.map +0 -1
  167. package/dist/chunk-AWY2HWAQ.js +0 -9
  168. package/dist/chunk-BTR2E5WD.js.map +0 -1
  169. package/dist/chunk-DMA3XCMF.js.map +0 -1
  170. package/dist/chunk-F7IOGLKV.js.map +0 -1
  171. package/dist/chunk-KCDHOW22.js.map +0 -1
  172. package/dist/chunk-O5ZJY5BT.js.map +0 -1
  173. package/dist/chunk-VQACXAFX.js.map +0 -1
  174. package/dist/chunk-WYQD44Y4.js.map +0 -1
  175. package/dist/chunk-YKQLHFY4.js.map +0 -1
  176. package/dist/cli-D2RPZWWM.js +0 -20
  177. package/dist/install-skills-DV7JBW56.js +0 -23
  178. package/dist/pty-host-XRXRI6UL.js.map +0 -1
  179. package/dist/remove-VO5V45IJ.js.map +0 -1
  180. package/dist/web/assets/index-DkVQmwkZ.js +0 -126
  181. package/dist/web/assets/index-DkVQmwkZ.js.map +0 -1
  182. package/dist/web-MPSYOYQ2.js.map +0 -1
  183. /package/dist/{add-repo-JKVHNRWU.js.map → add-repo-3THEK6UG.js.map} +0 -0
  184. /package/dist/{answer-PDCLL5Z2.js.map → answer-3CJQWBGY.js.map} +0 -0
  185. /package/dist/{attach-BIFQP5OY.js.map → attach-FQSBZXI7.js.map} +0 -0
  186. /package/dist/{block-EI3OQVDM.js.map → block-NGD2KNTU.js.map} +0 -0
  187. /package/dist/{broadcast-ZSA3L5FY.js.map → broadcast-NLASZGWR.js.map} +0 -0
  188. /package/dist/{catchup-SNMGWNRX.js.map → catchup-WJPWOGVI.js.map} +0 -0
  189. /package/dist/{chunk-2R6EHVZG.js.map → chunk-3257QPVM.js.map} +0 -0
  190. /package/dist/{chunk-IYWNDEXA.js.map → chunk-3KVOYBM4.js.map} +0 -0
  191. /package/dist/{chunk-HJ2RKMBI.js.map → chunk-3O6QFWZ6.js.map} +0 -0
  192. /package/dist/{chunk-MGNJPBZU.js.map → chunk-45MDVVW7.js.map} +0 -0
  193. /package/dist/{chunk-K7Y7YTN3.js.map → chunk-5LUXNIPA.js.map} +0 -0
  194. /package/dist/{chunk-73MGZAGV.js.map → chunk-64M7W2OQ.js.map} +0 -0
  195. /package/dist/{chunk-AU7XGTJZ.js.map → chunk-7FNJ6A2U.js.map} +0 -0
  196. /package/dist/{chunk-WQN7HJK6.js.map → chunk-7IZVI76D.js.map} +0 -0
  197. /package/dist/{chunk-PMEOGFGV.js.map → chunk-7UXV4X2Y.js.map} +0 -0
  198. /package/dist/{chunk-RH4BGTER.js.map → chunk-ACNCTLFO.js.map} +0 -0
  199. /package/dist/{chunk-BLOV7ECI.js.map → chunk-AGRUEZQX.js.map} +0 -0
  200. /package/dist/{chunk-2VYWTBC6.js.map → chunk-ANS6OH55.js.map} +0 -0
  201. /package/dist/{chunk-HRUKMBF3.js.map → chunk-AYHDJMMJ.js.map} +0 -0
  202. /package/dist/{chunk-ZJBVZ4OJ.js.map → chunk-BHJ73OPQ.js.map} +0 -0
  203. /package/dist/{chunk-7HQM5NYN.js.map → chunk-BK73QU45.js.map} +0 -0
  204. /package/dist/{chunk-BENY64FW.js.map → chunk-BW5U6ENJ.js.map} +0 -0
  205. /package/dist/{chunk-VADGWMXL.js.map → chunk-C72Y42VC.js.map} +0 -0
  206. /package/dist/{chunk-7OZZUQDW.js.map → chunk-C7ZKDWPI.js.map} +0 -0
  207. /package/dist/{chunk-PHHBZDO2.js.map → chunk-CS2EINZJ.js.map} +0 -0
  208. /package/dist/{chunk-ZX2VBM2F.js.map → chunk-CVMO75V5.js.map} +0 -0
  209. /package/dist/{chunk-QRYZAY7R.js.map → chunk-DHOC2S2L.js.map} +0 -0
  210. /package/dist/{chunk-DMGNJ73M.js.map → chunk-DROLR3NJ.js.map} +0 -0
  211. /package/dist/{chunk-KJRUC2QY.js.map → chunk-DS2CKYQ4.js.map} +0 -0
  212. /package/dist/{chunk-MBSCZQ2C.js.map → chunk-DZ6SLAIZ.js.map} +0 -0
  213. /package/dist/{chunk-BDPRYJL3.js.map → chunk-EYDGX32Q.js.map} +0 -0
  214. /package/dist/{chunk-AWY2HWAQ.js.map → chunk-FC7RECDP.js.map} +0 -0
  215. /package/dist/{chunk-SC2FQ6BR.js.map → chunk-FM6VLU4T.js.map} +0 -0
  216. /package/dist/{chunk-6MMXVHPL.js.map → chunk-H4TMS567.js.map} +0 -0
  217. /package/dist/{chunk-NFWSJFYY.js.map → chunk-HHXVHUGP.js.map} +0 -0
  218. /package/dist/{chunk-3QEDOZMA.js.map → chunk-HORDAO4Z.js.map} +0 -0
  219. /package/dist/{chunk-E6WVQXF4.js.map → chunk-I3FLUAK7.js.map} +0 -0
  220. /package/dist/{chunk-RIEBQWQC.js.map → chunk-I7AEQDG7.js.map} +0 -0
  221. /package/dist/{chunk-CL3SSNBC.js.map → chunk-IREGW23T.js.map} +0 -0
  222. /package/dist/{chunk-GAE3NB3G.js.map → chunk-JIWPC53O.js.map} +0 -0
  223. /package/dist/{chunk-U3RRXU6W.js.map → chunk-JNAYPBAB.js.map} +0 -0
  224. /package/dist/{chunk-TW44C7CG.js.map → chunk-JVRS73M6.js.map} +0 -0
  225. /package/dist/{chunk-CSTPOCV2.js.map → chunk-K5EAVRXX.js.map} +0 -0
  226. /package/dist/{chunk-WV5U4S5N.js.map → chunk-KCWU6HNJ.js.map} +0 -0
  227. /package/dist/{chunk-KKVWDMSM.js.map → chunk-LSZ6HI3U.js.map} +0 -0
  228. /package/dist/{chunk-253Q6TOC.js.map → chunk-MKQ7IA6U.js.map} +0 -0
  229. /package/dist/{chunk-3XU7Y2MV.js.map → chunk-N5PQHNYK.js.map} +0 -0
  230. /package/dist/{chunk-FFL7ETBY.js.map → chunk-OIVEYULL.js.map} +0 -0
  231. /package/dist/{chunk-2YKV6MNQ.js.map → chunk-OTKWVUGB.js.map} +0 -0
  232. /package/dist/{chunk-CJ2QTQHG.js.map → chunk-RSCRZGUW.js.map} +0 -0
  233. /package/dist/{chunk-N75AJ3ZR.js.map → chunk-S36RENUJ.js.map} +0 -0
  234. /package/dist/{chunk-SQ4ZGEZY.js.map → chunk-SPVVXKDV.js.map} +0 -0
  235. /package/dist/{chunk-KP2CI5QU.js.map → chunk-TFNDOWYP.js.map} +0 -0
  236. /package/dist/{chunk-SMXRY653.js.map → chunk-TL7K3XUY.js.map} +0 -0
  237. /package/dist/{chunk-HECIDNBU.js.map → chunk-TMAQASMH.js.map} +0 -0
  238. /package/dist/{chunk-6C7CR2W2.js.map → chunk-TMBO55MM.js.map} +0 -0
  239. /package/dist/{chunk-GV3KXHF3.js.map → chunk-TSFNTMMY.js.map} +0 -0
  240. /package/dist/{chunk-5DUKO7WC.js.map → chunk-TUDDISCX.js.map} +0 -0
  241. /package/dist/{chunk-3UI35AFZ.js.map → chunk-U2MOKVPZ.js.map} +0 -0
  242. /package/dist/{chunk-RXZKYHSW.js.map → chunk-UQJQZ526.js.map} +0 -0
  243. /package/dist/{chunk-VJ5XMYXE.js.map → chunk-VVRSPS67.js.map} +0 -0
  244. /package/dist/{chunk-5ZU6H62F.js.map → chunk-ZIFWZJ7X.js.map} +0 -0
  245. /package/dist/{chunk-3LDQPUJ6.js.map → chunk-ZQJKAZRD.js.map} +0 -0
  246. /package/dist/{cleanup-5CPX253G.js.map → cleanup-GFYEKCJS.js.map} +0 -0
  247. /package/dist/{cli-D2RPZWWM.js.map → cli-QP3BQXVW.js.map} +0 -0
  248. /package/dist/{completion-QCB7PKKT.js.map → completion-OEU4UZEA.js.map} +0 -0
  249. /package/dist/{config-EQFAXBMQ.js.map → config-W3AEOOUK.js.map} +0 -0
  250. /package/dist/{diff-MLCUMIYC.js.map → diff-G53V34KI.js.map} +0 -0
  251. /package/dist/{digest-KSAGLQND.js.map → digest-W4425I4J.js.map} +0 -0
  252. /package/dist/{fork-RCTVMUYI.js.map → fork-HTPJML6G.js.map} +0 -0
  253. /package/dist/{history-N4ZURR4F.js.map → history-TYKH3SKB.js.map} +0 -0
  254. /package/dist/{hook-DRZVYLJB.js.map → hook-F7WR5UIQ.js.map} +0 -0
  255. /package/dist/{hydrate-NVJZZAFT.js.map → hydrate-HDZ62YMD.js.map} +0 -0
  256. /package/dist/{init-RF6YC4BQ.js.map → init-Q5KJ666H.js.map} +0 -0
  257. /package/dist/{install-skills-DV7JBW56.js.map → install-skills-C46BIZ5O.js.map} +0 -0
  258. /package/dist/{keep-7Q3B6QT5.js.map → keep-MYHUCQWD.js.map} +0 -0
  259. /package/dist/{list-PIJ4ROHR.js.map → list-BGHRHYV6.js.map} +0 -0
  260. /package/dist/{move-XAZG3MJT.js.map → move-OHV2DC4V.js.map} +0 -0
  261. /package/dist/{note-JJXIQ4QK.js.map → note-2I5WTKED.js.map} +0 -0
  262. /package/dist/{overlaps-3YN4UQWC.js.map → overlaps-PX4BD23H.js.map} +0 -0
  263. /package/dist/{pin-OOCB6DFR.js.map → pin-UTMH2XUZ.js.map} +0 -0
  264. /package/dist/{pr-LCG4W65A.js.map → pr-PZCO36TY.js.map} +0 -0
  265. /package/dist/{prune-2NGAUOPI.js.map → prune-APCNVQKK.js.map} +0 -0
  266. /package/dist/{read-FJDDCX4D.js.map → read-HSQNG4CA.js.map} +0 -0
  267. /package/dist/{recent-AAXLCQUF.js.map → recent-SNDWYLUH.js.map} +0 -0
  268. /package/dist/{restart-AP763LE2.js.map → restart-HWSAV22N.js.map} +0 -0
  269. /package/dist/{resume-SPO5XNDT.js.map → resume-DBO7FTEQ.js.map} +0 -0
  270. /package/dist/{review-now-HHQIBVUS.js.map → review-now-CZPT7X4K.js.map} +0 -0
  271. /package/dist/{run-JZWZHJOE.js.map → run-QQARI2AH.js.map} +0 -0
  272. /package/dist/{screen-JRMMYVHB.js.map → screen-SXJEHTUY.js.map} +0 -0
  273. /package/dist/{search-XOWMVFP2.js.map → search-U25QWSX4.js.map} +0 -0
  274. /package/dist/{section-7WO7IHG6.js.map → section-TCH4DXE7.js.map} +0 -0
  275. /package/dist/{send-OCSMOCUE.js.map → send-ZCKMC65W.js.map} +0 -0
  276. /package/dist/{sessions-UAZALGGH.js.map → sessions-7PKZZ4NG.js.map} +0 -0
  277. /package/dist/{snooze-UDJ5UDCS.js.map → snooze-JBPRRYAF.js.map} +0 -0
  278. /package/dist/{start-OEG3T2SW.js.map → start-L6AWLRVP.js.map} +0 -0
  279. /package/dist/{state-BR43ONIH.js.map → state-JHCC5CAR.js.map} +0 -0
  280. /package/dist/{status-R4T2EHG5.js.map → status-WWRZLDGT.js.map} +0 -0
  281. /package/dist/{statusline-3H3HAPCZ.js.map → statusline-MIFW47UA.js.map} +0 -0
  282. /package/dist/{statusline-hook-FILOARNM.js.map → statusline-hook-W7KWKWAC.js.map} +0 -0
  283. /package/dist/{stop-D3LRCCJS.js.map → stop-WHUBU5JZ.js.map} +0 -0
  284. /package/dist/{sync-FWC2EWLW.js.map → sync-AVDUHYPQ.js.map} +0 -0
  285. /package/dist/{time-AMAMIDWD.js.map → time-MIJM6SM6.js.map} +0 -0
  286. /package/dist/{time-actions-YOXF5WC7.js.map → time-actions-Y5USDGSE.js.map} +0 -0
  287. /package/dist/{timesheet-QFBA2Z2A.js.map → timesheet-AVRH56TG.js.map} +0 -0
  288. /package/dist/{todo-TALKJYK6.js.map → todo-O6Y5MEQR.js.map} +0 -0
  289. /package/dist/{update-RVZMM54Z.js.map → update-XGT2DFTT.js.map} +0 -0
  290. /package/dist/{usage-W4UXQUPD.js.map → usage-7NM6L2MR.js.map} +0 -0
  291. /package/dist/{version-WPF664CL.js.map → version-V7IM2UL4.js.map} +0 -0
  292. /package/dist/{wait-C3S7Q6FA.js.map → wait-HCIFDLNX.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/sessions/history.ts","../src/core/sessions/session-activity.ts","../src/core/worktree/port-allocator.ts","../src/core/sessions/session-store.ts","../src/core/api-types.ts","../src/core/archive/session-archive.ts","../src/core/archive/archive-uncommitted.ts","../src/core/diff/git-tree-snapshot.ts","../src/core/platform/best-effort.ts","../src/core/pr/pr-stage.ts","../src/core/rail/snooze.ts","../src/core/status/attention.ts","../src/core/status/session-status.ts","../src/core/rail/snooze-store.ts","../src/core/archive/archiving.ts","../src/core/conversations/work-time.ts","../src/core/conversations/digest.ts","../src/core/conversations/conversation-store.ts","../src/core/archive/archive-search.ts","../src/core/hosts/github/origin.ts","../src/core/hosts/azure/origin.ts","../src/core/hosts/github/commands.ts","../src/core/hosts/azure/commands.ts","../src/core/hosts/commands.ts","../src/core/hosts/links.ts","../src/core/pr/session-prs.ts","../src/core/worktree/dev-server.ts","../src/core/sessions/session-repos.ts","../src/core/diff/checkpoint.ts","../src/core/diff/scope-manager.ts","../src/core/platform/fs-watcher.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { WorkConfig } from '../platform/config.js';\nimport { getConfigDir, loadConfig } from '../platform/config.js';\nimport { agentFor, agentToRecord } from '../agents/index.js';\n\n/**\n * What a new session records about its agent: the configured one when work has an adapter for it (agents/), and — for\n * an agent with accounts (its adapter's `accounts` part) — the account it runs on: the one asked for, else that agent's\n * default, so a later change of the default never moves it. An agent without accounts records none.\n */\nconst recordAgent = (account?: string): { agent?: string; account?: string } => {\n const config = loadConfig();\n const agent = agentToRecord(config);\n const accounts = agentFor(config).accounts;\n return { ...(agent ? { agent } : {}), ...(accounts ? { account: account || accounts.defaultName() } : {}) };\n};\nimport { json, purgeSessionRows, tx, withDb, type Db } from '../platform/db.js';\nimport { sessionIdFor } from './session-id.js';\nimport { effectiveLastAccessedAt } from './session-activity.js';\nimport { allocateFreePort } from '../worktree/port-allocator.js';\nimport { removeSessionFiles, stopSessionDevServer, clearSessionCheckpoints } from './session-store.js';\n\nexport type { WorktreeSession } from './session-types.js';\nimport type { SessionInstructions, WorktreeSession } from './session-types.js';\nimport { recordedRepos, sessionRepos } from './session-repos.js';\n\n/**\n * Worktree sessions, in the `sessions` table of ~/.work/state.db (db.ts):\n * one row per target:branch, the record as JSON. Writes are transactions,\n * so concurrent `work tree` / `remove` / work web can't clobber each other\n * (the old history.json needed a file lock for that — and once lost 60+\n * sessions without it).\n */\n\n/** The pre-SQLite history file. Only the one-time import (db-import.ts)\n * reads it now. */\nexport function getHistoryPath(): string {\n return path.join(getConfigDir(), 'history.json');\n}\n\nfunction valid(s: unknown): s is WorktreeSession {\n const x = s as WorktreeSession | null;\n return !!x && typeof x.target === 'string' && typeof x.branch === 'string' && Array.isArray(x.paths);\n}\n\nfunction rows(d: Db): WorktreeSession[] {\n return (d.prepare('SELECT data FROM sessions ORDER BY rowid').all() as Array<{ data: string }>)\n .map((r) => json.parse(r.data))\n .filter(valid);\n}\n\nfunction getRow(d: Db, target: string, branch: string): WorktreeSession | undefined {\n const r = d.prepare('SELECT data FROM sessions WHERE id = ?').get(sessionIdFor({ target, branch })) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return valid(s) ? s : undefined;\n}\n\nfunction putRow(d: Db, s: WorktreeSession): void {\n d.prepare(\n 'INSERT INTO sessions (id, target, branch, data) VALUES (?, ?, ?, ?) ' + 'ON CONFLICT(id) DO UPDATE SET data = excluded.data',\n ).run(sessionIdFor(s), s.target, s.branch, JSON.stringify(s));\n}\n\n/**\n * A repo added to a session (add-repo.ts): its worktree appended to the\n * session's paths, its alias to its repos (a row from before gets its list\n * recorded first, as derived), and its base — in one transaction over the row\n * as it is now. `before` is the paths it had, read in that transaction (the\n * scope its turns move from). Already there: unchanged. Null when the session\n * is gone. Throws, writing nothing, when a folder of a row from before can't\n * be matched to a repo of its group (it would be recorded under a made-up alias).\n *\n * The base: one `baseBranch` stands for every repo only when every repo has it\n * (as a group's is recorded). An added repo made from it keeps that; one made\n * from another, or checked out on a branch it had (no base known), gets its own\n * entry or none, and the others keep theirs — each in `baseBranches`.\n */\nexport function appendSessionRepo(\n id: string,\n alias: string,\n worktree: string,\n from: string | undefined,\n config: WorkConfig,\n /** Its folder's file gets the repo's import (an agent that can import): recorded on the\n * session when it has no mode yet — a group's copied summary keeps it, the block after it. */\n imports = false,\n): { before: string[]; session: WorktreeSession } | null {\n return tx((d) => {\n const r = d.prepare('SELECT data FROM sessions WHERE id = ?').get(id) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n if (!valid(s)) return null;\n const own = sessionRepos(s, config);\n const unknown = own.filter((x) => x.guessed).map((x) => path.basename(x.path));\n if (unknown.length) throw new Error(`no repo of its group is in ${unknown.join(', ')}, so its repos can't be recorded`);\n const repos = own.map((x) => x.alias);\n const before = [...s.paths];\n if (repos.includes(alias)) return { before, session: s };\n if (s.baseBranch && from !== s.baseBranch) {\n const perRepo = { ...(s.baseBranches ?? {}) };\n for (const p of s.paths) perRepo[p] ??= s.baseBranch;\n s.baseBranches = perRepo;\n delete s.baseBranch;\n }\n s.paths = [...s.paths, worktree];\n s.repos = [...repos, alias];\n if (imports && !s.instructions) s.instructions = config.groups?.[s.target] ? 'summary+imports' : 'imports';\n if (from) s.baseBranches = { ...(s.baseBranches ?? {}), [worktree]: from };\n putRow(d, s);\n return { before, session: s };\n });\n}\n\n/** One session by its id (the `sessions` primary key). */\nexport function findSessionById(id: string): WorktreeSession | null {\n return withDb((d) => {\n const r = d.prepare('SELECT data FROM sessions WHERE id = ?').get(id) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return valid(s) ? s : null;\n });\n}\n\n/** Every session, in the order they were first recorded. */\nexport function loadHistory(): WorktreeSession[] {\n return withDb(rows);\n}\n\n/** Replace the whole history (bulk rewrites, tests). */\nexport function saveHistory(sessions: WorktreeSession[]): void {\n tx((d) => {\n d.prepare('DELETE FROM sessions').run();\n const seen = new Set<string>();\n for (const s of sessions) {\n if (!valid(s)) continue;\n const id = sessionIdFor(s);\n if (seen.has(id)) continue; // first entry wins, as findSession does\n seen.add(id);\n putRow(d, s);\n }\n });\n}\n\nfunction sessionKey(target: string, branch: string): string {\n return `${target}:${branch}`;\n}\n\nexport function findSession(sessions: WorktreeSession[], target: string, branch: string): WorktreeSession | undefined {\n return sessions.find((s) => s.target === target && s.branch === branch);\n}\n\n/**\n * A session's folders as a writer gives them (`paths`, and `repos` when it knows\n * them), over the row as it is NOW (inside the writer's transaction). A row that\n * records its repos never loses one the writer didn't know of — a repo added to\n * it (add-repo.ts) after the writer read the row, seconds of git work earlier —:\n * those pairs are kept, after the writer's. A row from before (no list) takes\n * what it's given, as it always did. Mutates `existing`.\n */\nexport function setOwnRepos(existing: WorktreeSession, paths: string[], repos?: string[]): void {\n const recorded = recordedRepos(existing);\n if (!recorded) {\n existing.paths = paths;\n if (repos) existing.repos = [...repos];\n return;\n }\n // The writer's pairs: its own list, else (it knows only the folders) the recorded aliases by place.\n const given =\n repos && repos.length === paths.length\n ? repos.map((alias, i) => ({ alias, path: paths[i] }))\n : paths.length === recorded.length\n ? recorded.map((r, i) => ({ alias: r.alias, path: paths[i] }))\n : recorded;\n const kept = recorded.filter((r) => !given.some((g) => g.alias === r.alias));\n const all = [...given, ...kept];\n existing.paths = all.map((r) => r.path);\n existing.repos = all.map((r) => r.alias);\n}\n\n/**\n * Coming back to a session without changing what it holds (`work resume`,\n * `work recent`): its last access, and un-archived, in one write over the row\n * as it is now — never a copy of its folders read before a picker waited on you.\n */\nexport function touchSession(target: string, branch: string): void {\n tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return;\n s.lastAccessedAt = new Date().toISOString();\n delete s.archivedAt;\n putRow(d, s);\n });\n}\n\n/**\n * Drops the row's `launchedUnsafe` from before `--unsafe` was retired. Called through `clearLaunchedUnsafeWhenIdle`\n * (legacy-unsafe-io.ts), which leaves it while an agent of the session still runs anywhere. REMOVE IN THE NEXT RELEASE.\n */\nexport function clearLaunchedUnsafe(target: string, branch: string): void {\n tx((d) => {\n const s = getRow(d, target, branch);\n if (!s || s.launchedUnsafe === undefined) return;\n delete s.launchedUnsafe;\n putRow(d, s);\n });\n}\n\nexport async function upsertSession(\n target: string,\n isGroup: boolean,\n branch: string,\n paths: string[],\n jiraKey?: string,\n baseBranch?: string,\n port?: number,\n /** The repo alias of each of `paths` (WorktreeSession.repos); omitted keeps what the row has. */\n repos?: string[],\n /** The Claude account a NEW session runs on (default: the configured one); an existing session keeps its own. */\n account?: string,\n): Promise<void> {\n tx((d) => {\n const existing = getRow(d, target, branch);\n const now = new Date().toISOString();\n\n if (existing) {\n setOwnRepos(existing, paths, repos);\n existing.lastAccessedAt = now;\n delete existing.archivedAt; // coming back to it un-archives it\n if (jiraKey) existing.jiraKey = jiraKey;\n if (baseBranch && !existing.baseBranch) existing.baseBranch = baseBranch;\n if (port !== undefined) existing.port = port;\n putRow(d, existing);\n } else {\n const session: WorktreeSession = {\n target,\n isGroup,\n branch,\n paths,\n createdAt: now,\n lastAccessedAt: now,\n ...recordAgent(account),\n };\n if (jiraKey) session.jiraKey = jiraKey;\n if (baseBranch) session.baseBranch = baseBranch;\n if (port !== undefined) session.port = port;\n if (repos) session.repos = [...repos];\n putRow(d, session);\n }\n });\n}\n\n/**\n * Allocate a stable dev-server port AND persist the session, without two\n * concurrent `work tree` runs picking the same port.\n *\n * Allocation probes ports (async) and a transaction can't span an await,\n * so it is optimistic: pick a port against a snapshot, then in one write\n * transaction re-check that no other live session took it meanwhile — and\n * if one did, pick again.\n *\n * Port allocation is best-effort: if it fails (range exhausted, etc.) the\n * session is still persisted, just without a port, and `port` comes back\n * undefined. An already-allocated port on an existing session is preserved\n * (idempotent re-runs keep their port).\n *\n * The allocation seed is `target:branch` (unique per worktree) so two repos\n * that share a branch name don't collide on the same deterministic base offset.\n */\nexport async function upsertSessionWithPort(\n target: string,\n isGroup: boolean,\n branch: string,\n paths: string[],\n config: Pick<WorkConfig, 'portRange'>,\n jiraKey?: string,\n baseBranch?: string,\n baseBranches?: Record<string, string>,\n /** What the session owns: the repo alias of each of `paths` (WorktreeSession.repos) and how\n * its instructions file is made (`instructions`). Each omitted keeps what the row has. `account`: the Claude\n * account a NEW session records (default: the configured one) — an existing row keeps its own, never overwritten. */\n own: { repos?: string[]; instructions?: SessionInstructions; account?: string } = {},\n): Promise<{ port?: number }> {\n const { repos, instructions, account } = own;\n const hasPerRepo = baseBranches && Object.keys(baseBranches).length > 0;\n const id = sessionIdFor({ target, branch });\n\n const write = (d: Db, port: number | undefined): number | undefined => {\n const existing = getRow(d, target, branch);\n const now = new Date().toISOString();\n if (existing) {\n setOwnRepos(existing, paths, repos);\n existing.lastAccessedAt = now;\n delete existing.archivedAt; // coming back to it un-archives it\n if (jiraKey) existing.jiraKey = jiraKey;\n if (baseBranch && !existing.baseBranch) existing.baseBranch = baseBranch;\n if (hasPerRepo && !existing.baseBranches) existing.baseBranches = baseBranches;\n if (existing.port === undefined && port !== undefined) existing.port = port;\n if (instructions) existing.instructions = instructions;\n putRow(d, existing);\n return existing.port;\n }\n const session: WorktreeSession = { target, isGroup, branch, paths, createdAt: now, lastAccessedAt: now, ...recordAgent(account) };\n if (jiraKey) session.jiraKey = jiraKey;\n if (baseBranch) session.baseBranch = baseBranch;\n if (hasPerRepo) session.baseBranches = baseBranches;\n if (port !== undefined) session.port = port;\n if (repos) session.repos = [...repos];\n if (instructions) session.instructions = instructions;\n putRow(d, session);\n return port;\n };\n\n for (let attempt = 0; attempt < 5; attempt++) {\n const sessions = loadHistory();\n const existing = findSession(sessions, target, branch);\n let port = existing?.port;\n if (port === undefined) {\n try {\n port = await allocateFreePort(sessionKey(target, branch), config, sessions);\n } catch {\n port = undefined;\n }\n }\n const done = tx((d) => {\n // Another `work tree` may have taken this port since the snapshot:\n // only a port no other live session holds may be kept.\n if (port !== undefined && getRow(d, target, branch)?.port === undefined) {\n const taken = rows(d).some((s) => sessionIdFor(s) !== id && s.port === port && s.paths.some((p) => fs.existsSync(p)));\n if (taken) return null;\n }\n return { port: write(d, port) };\n });\n if (done) return done;\n }\n // Could not get an uncontested port: record the session without one.\n return tx((d) => ({ port: write(d, undefined) }));\n}\n\n/** Archive / un-archive a session. Returns false when it doesn't exist. */\nexport async function setSessionArchived(target: string, branch: string, archived: boolean): Promise<boolean> {\n return tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return false;\n if (archived) s.archivedAt = new Date().toISOString();\n else {\n // A Restore is entering it: the PR watch's \"merged after you last entered\" must not read it as left since\n // before the merge (reported: a restored session was archived again by the next sweep).\n delete s.archivedAt;\n s.lastAccessedAt = new Date().toISOString();\n }\n putRow(d, s);\n return true;\n });\n}\n\n/** Name a session (an empty title goes back to the automatic name). */\nexport async function setSessionTitle(target: string, branch: string, title: string): Promise<boolean> {\n return tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return false;\n const t = title.trim().slice(0, 120);\n if (t) s.title = t;\n else delete s.title;\n putRow(d, s);\n return true;\n });\n}\n\n/** Keep a session once its PR merges, or go back to archiving it then: in one transaction. False for an unknown session. */\nexport async function setSessionKeep(target: string, branch: string, keep: boolean): Promise<boolean> {\n return tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return false;\n if (keep) s.keepAfterMerge = true;\n else delete s.keepAfterMerge;\n putRow(d, s);\n return true;\n });\n}\n\n/** Record the Claude account a session runs on (a switch of account): in one transaction. False for an unknown session. */\nexport async function setSessionAccount(target: string, branch: string, account: string): Promise<boolean> {\n return tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return false;\n s.account = account;\n putRow(d, s);\n return true;\n });\n}\n\n/**\n * Record the branches it is now based on (a stacked session moved onto\n * main): by checkout path. One name for every repo is `baseBranch` alone;\n * repos with different mainlines (main and master) keep `baseBranches` too.\n */\nexport async function setSessionBase(target: string, branch: string, bases: Record<string, string>): Promise<boolean> {\n const names = [...new Set(Object.values(bases))];\n if (names.length === 0) return false;\n return tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return false;\n s.baseBranch = names[0];\n if (names.length === 1) delete s.baseBranches;\n else s.baseBranches = { ...bases };\n putRow(d, s);\n return true;\n });\n}\n\nexport async function removeSession(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch });\n if (!withDb((d) => getRow(d, target, branch))) return; // nothing to remove: touch nothing\n const session = findSession(loadHistory(), target, branch);\n // The session's other state (status, comments, saved PTY entry, …) goes\n // with it — in the SAME transaction, so a crash can't leave state behind\n // for a re-created session to inherit (see session-store.ts).\n stopSessionDevServer(id);\n const removed = tx((d) => {\n const gone = d.prepare('DELETE FROM sessions WHERE id = ?').run(id).changes > 0;\n if (gone) purgeSessionRows(d, id);\n return gone;\n });\n if (removed) {\n removeSessionFiles(id);\n if (session) clearSessionCheckpoints(session);\n }\n}\n\nexport function getSessionsForTarget(sessions: WorktreeSession[], target: string): WorktreeSession[] {\n return sessions.filter((s) => s.target === target);\n}\n\nexport function getRecentSessions(sessions: WorktreeSession[], count: number): WorktreeSession[] {\n return [...sessions]\n .sort((a, b) => new Date(effectiveLastAccessedAt(b)).getTime() - new Date(effectiveLastAccessedAt(a)).getTime())\n .slice(0, count);\n}\n\nexport function pruneStaleEntries(sessions: WorktreeSession[]): {\n kept: WorktreeSession[];\n pruned: number;\n} {\n const kept: WorktreeSession[] = [];\n let pruned = 0;\n\n for (const session of sessions) {\n const anyPathExists = session.paths.some((p) => fs.existsSync(p));\n if (anyPathExists) {\n kept.push(session);\n } else {\n pruned++;\n }\n }\n\n return { kept, pruned };\n}\n\n/** Persisted prune for `status --prune` callers. */\nexport async function prunePersistedStaleEntries(): Promise<{ pruned: number }> {\n const stale = pruneStaleEntries(loadHistory()).kept;\n const keep = new Set(stale.map((s) => sessionIdFor(s)));\n for (const s of loadHistory()) if (!keep.has(sessionIdFor(s))) stopSessionDevServer(sessionIdFor(s));\n const gone = tx((d) => {\n const drop = rows(d).filter((s) => !keep.has(sessionIdFor(s)));\n const del = d.prepare('DELETE FROM sessions WHERE id = ?');\n for (const s of drop) {\n del.run(sessionIdFor(s));\n purgeSessionRows(d, sessionIdFor(s));\n }\n return drop;\n });\n for (const s of gone) removeSessionFiles(sessionIdFor(s));\n return { pruned: gone.length };\n}\n\n/**\n * Merge hydrated sessions into history without clobbering existing entries.\n * For each incoming session: if a matching target+branch exists, refresh its\n * paths (if different) but keep original timestamps. Otherwise insert.\n * A session that records its repos (`repos`) owns its list: its paths keep\n * their order and none is dropped; a folder found on disk that it lacks is\n * added at the end, with its repo.\n */\nexport async function mergeHydratedSessions(incoming: WorktreeSession[]): Promise<{ added: number; updated: number }> {\n return tx((d) => {\n let added = 0;\n let updated = 0;\n\n for (const inc of incoming) {\n const existing = getRow(d, inc.target, inc.branch);\n const own = existing ? recordedRepos(existing) : null;\n if (existing && own) {\n const extra = inc.paths\n .map((p, i) => ({ path: p, alias: inc.repos?.[i] }))\n .filter((x) => !own.some((r) => samePath(r.path, x.path)));\n // Without its repo a new folder can't be recorded beside the others: the list stays as it is.\n if (extra.length && extra.every((x) => typeof x.alias === 'string')) {\n existing.paths = [...existing.paths, ...extra.map((x) => x.path)];\n existing.repos = [...own.map((r) => r.alias), ...extra.map((x) => x.alias as string)];\n putRow(d, existing);\n updated++;\n }\n } else if (existing) {\n const sortedA = [...existing.paths].sort();\n const sortedB = [...inc.paths].sort();\n const same = sortedA.length === sortedB.length && sortedA.every((p, i) => p === sortedB[i]);\n if (!same) {\n existing.paths = inc.paths;\n putRow(d, existing);\n updated++;\n }\n } else {\n putRow(d, inc);\n added++;\n }\n }\n return { added, updated };\n });\n}\n\nconst samePath = (a: string, b: string) => {\n const n = (p: string) => path.resolve(p).split(path.sep).join('/').toLowerCase();\n return n(a) === n(b);\n};\n\n/**\n * A base checkout (`work tree <target>` with no branch) is recorded under the\n * branch it had checked out at the time. Run it again after switching that\n * checkout to another branch and a second entry appeared for the SAME folder\n * — then a third… — each showing the folder's activity as its own (three\n * \"Active\" rows for one busy checkout). Keep one: the entry just recorded.\n * Returns the branches of the entries removed.\n */\nexport async function forgetOtherBaseCheckoutEntries(target: string, keepBranch: string, repoPath: string): Promise<string[]> {\n const others = loadHistory().filter(\n (s) => s.target === target && !s.isGroup && s.branch !== keepBranch && s.paths.length === 1 && samePath(s.paths[0], repoPath),\n );\n for (const s of others) await removeSession(s.target, s.branch);\n return others.map((s) => s.branch);\n}\n","import { agentOf } from '../agents/index.js';\nimport type { ActivityState } from '../api-types.js';\nimport type { WorktreeSession } from './session-types.js';\n\n/**\n * How recently a session's agent wrote: the newest of its conversation files\n * (agents/: `conversation.files`). Works however the agent was started — by\n * `work tree`, `work attach`, a plain terminal or the PTY host — since they\n * all write the same files. An agent work can't read gives no activity (the\n * other signals — hooks, the PTY host's output — still do).\n */\n\n/** Active: it wrote in the last 30 s — mid-turn. */\nconst ACTIVE_MS = 30_000;\n/** Open: it wrote within 5 min — likely still at its prompt. After that, stale. */\nconst OPEN_MS = 5 * 60_000;\n\nexport interface SessionActivity {\n /** ms since epoch of its newest conversation write, or null when there is none. */\n lastActivity: number | null;\n state: ActivityState;\n}\n\n/** The newest write to any of the session's conversation files, ms (0: none). */\nexport function lastConversationWriteMs(session: WorktreeSession): number {\n let latest = 0;\n for (const f of agentOf(session).conversation?.files(session) ?? []) if (f.mtimeMs > latest) latest = f.mtimeMs;\n return latest;\n}\n\nexport function readSessionActivity(session: WorktreeSession, now = Date.now()): SessionActivity {\n const latest = lastConversationWriteMs(session);\n if (latest === 0) return { lastActivity: null, state: 'stale' };\n const age = now - latest;\n return { lastActivity: latest, state: age <= ACTIVE_MS ? 'active' : age <= OPEN_MS ? 'open' : 'stale' };\n}\n\n/**\n * True when an agent wrote within `windowMs` of `nowMs` (0: never). The\n * scope auto-snapshot timer uses it to stay out of the way while an agent is\n * at work (its turn-end hook owns checkpoints then); the timer only fires for\n * hand edits when none is.\n */\nexport function activeWithin(activityMs: number, nowMs: number, windowMs: number): boolean {\n return activityMs > 0 && nowMs - activityMs < windowMs;\n}\n\n/** When it was last used: the newer of its recorded entry and its agent's last write. */\nexport function effectiveLastAccessedAt(session: WorktreeSession): string {\n const recorded = Date.parse(session.lastAccessedAt);\n return new Date(Math.max(Number.isFinite(recorded) ? recorded : 0, lastConversationWriteMs(session))).toISOString();\n}\n","import fs from 'node:fs';\nimport net from 'node:net';\nimport type { WorkConfig } from '../platform/config.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\n\n/** Default dev-server port range when none is configured. */\nexport const DEFAULT_PORT_RANGE = { start: 3000, end: 3099 };\n\n/**\n * Thrown when every port in the configured range is occupied. Distinct class so\n * callers can tell \"range exhausted\" apart from any other allocation failure.\n */\nexport class PortRangeExhaustedError extends Error {\n readonly start: number;\n readonly end: number;\n constructor(start: number, end: number) {\n super(\n `No free dev-server port available in range ${start}-${end} ` +\n `(all ${end - start + 1} in use). Widen \"portRange\" in ~/.work/config.json.`,\n );\n this.name = 'PortRangeExhaustedError';\n this.start = start;\n this.end = end;\n }\n}\n\n/**\n * Deterministic, stable string hash (FNV-1a 32-bit). Same input always yields\n * the same non-negative integer, so a worktree's seed key maps to the same base\n * offset across processes and machines.\n */\nfunction hashString(input: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\nfunction normalizeRange(config: Pick<WorkConfig, 'portRange'>): {\n start: number;\n end: number;\n rangeSize: number;\n} {\n const range = config.portRange ?? DEFAULT_PORT_RANGE;\n const start = Math.min(range.start, range.end);\n const end = Math.max(range.start, range.end);\n const rangeSize = end - start + 1;\n if (rangeSize <= 0) {\n throw new Error(`Invalid port range: ${range.start}-${range.end}`);\n }\n return { start, end, rangeSize };\n}\n\nfunction portsHeldByActiveSessions(sessions: WorktreeSession[]): Set<number> {\n const inUse = new Set<number>();\n for (const session of sessions) {\n if (session.port === undefined) continue;\n const active = session.paths.some((p) => fs.existsSync(p));\n if (active) inUse.add(session.port);\n }\n return inUse;\n}\n\n/**\n * Allocate a stable dev-server port for a worktree.\n *\n * Pure and testable: the caller passes the current `sessions` array (e.g.\n * `loadHistory()`) rather than this function reading state itself.\n *\n * - The range comes from `config.portRange` (falling back to 3000–3099).\n * - A deterministic base offset is derived from `hash(seedKey) % rangeSize`,\n * so the same worktree prefers the same port. The seed key MUST be unique per\n * worktree (e.g. `target:branch` or the full worktree path) — using only a\n * branch name would let two repos sharing a branch collide deterministically.\n * - Ports already held by *active* sessions (at least one path still exists)\n * are considered in use and skipped.\n * - Walks forward from the base offset (wrapping around the range) to the first\n * free port. Throws `PortRangeExhaustedError` if every port is occupied.\n *\n * NOTE: this checks only our own history, not host liveness. Use\n * `allocateFreePort` when you also want to skip ports occupied by unrelated\n * processes on the machine.\n */\nexport function allocatePort(seedKey: string, config: Pick<WorkConfig, 'portRange'>, sessions: WorktreeSession[]): number {\n const { start, end, rangeSize } = normalizeRange(config);\n const inUse = portsHeldByActiveSessions(sessions);\n const baseOffset = hashString(seedKey) % rangeSize;\n\n for (let i = 0; i < rangeSize; i++) {\n const candidate = start + ((baseOffset + i) % rangeSize);\n if (!inUse.has(candidate)) {\n return candidate;\n }\n }\n\n throw new PortRangeExhaustedError(start, end);\n}\n\n/**\n * Probe whether a TCP port is free to bind on localhost. Resolves false on\n * EADDRINUSE (something is already listening), true otherwise. Best-effort: any\n * non-EADDRINUSE error resolves true so a quirky host can't block allocation.\n */\nexport function isPortFree(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once('error', (err: NodeJS.ErrnoException) => {\n resolve(err.code !== 'EADDRINUSE');\n });\n server.once('listening', () => {\n server.close(() => resolve(true));\n });\n server.listen(port, '127.0.0.1');\n });\n}\n\n/**\n * Like `allocatePort`, but additionally probes host liveness: candidates that\n * are already bound by some other process on localhost (EADDRINUSE) are skipped\n * even when our history doesn't know about them. This is what actually prevents\n * collisions with non-work processes.\n *\n * Walks the same deterministic order as `allocatePort` and returns the first\n * candidate that is both free in history and bindable on the host. Throws\n * `PortRangeExhaustedError` if every candidate is taken.\n */\nexport async function allocateFreePort(\n seedKey: string,\n config: Pick<WorkConfig, 'portRange'>,\n sessions: WorktreeSession[],\n probe: (port: number) => Promise<boolean> = isPortFree,\n): Promise<number> {\n const { start, end, rangeSize } = normalizeRange(config);\n const inUse = portsHeldByActiveSessions(sessions);\n const baseOffset = hashString(seedKey) % rangeSize;\n\n for (let i = 0; i < rangeSize; i++) {\n const candidate = start + ((baseOffset + i) % rangeSize);\n if (inUse.has(candidate)) continue;\n if (await probe(candidate)) {\n return candidate;\n }\n }\n\n throw new PortRangeExhaustedError(start, end);\n}\n","import fs from 'node:fs';\nimport { archiveDirFor } from '../archive/session-archive.js';\nimport { conversationDirFor } from '../conversations/conversation-store.js';\nimport { sessionIdFor } from './session-id.js';\nimport { purgeSessionRows, tx } from '../platform/db.js';\nimport { logSwallowed } from '../platform/best-effort.js';\nimport { devLogFile, stopDev } from '../worktree/dev-server.js';\nimport { clearCheckpoints } from '../diff/checkpoint.js';\nimport { dropSessionSaves } from '../archive/archive-uncommitted.js';\nimport { scopeHashForPaths } from '../diff/scope-manager.js';\nimport { loadConfig } from '../platform/config.js';\nimport type { WorktreeSession } from './session-types.js';\nimport { sessionAliases } from './session-repos.js';\n\n/**\n * Owner of a session's state beyond its `sessions` row. Everything\n * per-session is keyed by sessionIdFor(target, branch) and lives in\n * state.db (db.ts):\n *\n * session_status attention status (hooks)\n * comments [store=id] review comments\n * comment_deliveries which comments reached Claude\n * pty_sessions restore-after-reboot entry\n * pr_watch_seen PR watch: comments / CI failures acted on\n * dev_runs dev server pid (the server is stopped first)\n *\n * plus one file, ~/.work/dev/<id>.log (the dev server's output).\n *\n * plus its diff scope's checkpoints: refs/wd/<hash>/* in its repos and the\n * manifest, keyed by the hash of its paths (clearSessionCheckpoints) — the\n * refs keep their commits (untracked files `add -A` captured included) from\n * git's garbage collection.\n *\n * § WHEN adding per-session state, add its table to `purgeSessionRows`\n * (db.ts), or its file here — so removing a session removes it. Before\n * this, deleted sessions left their state behind and a re-created session\n * with the same target:branch inherited it.\n */\n\n/** Per-session files that live outside the database. */\nexport function sessionStatePaths(id: string): string[] {\n // Its archive (kept conversation + summary) and work's copy of its\n // conversations go when the session is deleted for good; archiving keeps\n // the session, so they stay then.\n return [devLogFile(id), archiveDirFor(id), conversationDirFor(id)];\n}\n\n/** Before the session's rows go: stop its dev server (needs the dev_runs\n * row). Best-effort, logged. */\nexport function stopSessionDevServer(id: string): void {\n try {\n stopDev(id);\n } catch (err) {\n logSwallowed(`stop dev server ${id}`, err);\n }\n}\n\n/**\n * A removed session's checkpoints: the refs in its repos' shared git dir\n * (from the base checkouts: the worktree may already be gone) and the\n * manifest. Best-effort, logged.\n */\nexport function clearSessionCheckpoints(s: Pick<WorktreeSession, 'target' | 'isGroup' | 'paths' | 'repos'> & { branch?: string }): void {\n try {\n const cfg = loadConfig();\n const aliases = sessionAliases(s, cfg);\n const roots = aliases.map((a) => cfg?.repos[a]).filter((r): r is string => !!r && fs.existsSync(r));\n clearCheckpoints(scopeHashForPaths(s.paths), roots);\n // Uncommitted work an archive saved (archive-uncommitted.ts): its refs go like the checkpoints'.\n if (s.branch !== undefined) for (const r of roots) dropSessionSaves(r, sessionIdFor({ target: s.target, branch: s.branch }));\n } catch (err) {\n logSwallowed(`clear checkpoints of ${s.target}`, err);\n }\n}\n\n/** After the session's rows are gone: its files. Best-effort per file. */\nexport function removeSessionFiles(id: string): void {\n for (const p of sessionStatePaths(id)) {\n try {\n fs.rmSync(p, { force: true, recursive: true });\n } catch (err) {\n logSwallowed(`purge ${p}`, err);\n }\n }\n}\n\n/**\n * Remove every piece of per-session state for a session that has no\n * `sessions` row (any more). history.ts removes a session's row and its\n * state in ONE transaction (`purgeSessionRows`); this is the standalone\n * form for state left behind. Best-effort per step (logged), never throws.\n */\nexport async function purgeSessionState(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch });\n stopSessionDevServer(id);\n try {\n tx((d) => purgeSessionRows(d, id));\n } catch (err) {\n logSwallowed(`purge state rows ${id}`, err);\n }\n removeSessionFiles(id);\n}\n","import type { AttentionLike } from './status/attention.js';\nimport type { AgentUsage, UsageAccount } from './usage/usage.js';\n\n/**\n * Wire types shared by the server (core) and the browser SPA — ONE\n * definition each, so the two can't drift (they did: fields added on one\n * side had to be remembered on the other). Types only, no runtime imports:\n * the SPA imports this file directly (architecture allowlist), so it must\n * never pull in Node.\n */\n\n// ---- session list ---------------------------------------------------------\n\n/** Derived from Claude's last transcript write: ≤30 s active, ≤5 min open. */\nexport type ActivityState = 'active' | 'open' | 'stale';\n\n/** Whether work web's pool knows of a live PTY for the session. */\nexport type PtyStatus = 'running' | 'idle';\n\n/** `+N −M` for a session's working tree vs HEAD, across its repos. */\nexport interface DiffStat {\n added: number;\n deleted: number;\n /** Changed tracked files + untracked files. */\n files: number;\n}\n\n/** The tool call a permission prompt is about (from the transcript). */\nexport interface PermissionRequest {\n /** Tool name as Claude Code calls it (Bash, Edit, WebFetch, mcp__…). */\n tool: string;\n /** What it wants to do: the command, the file, the URL. One line. */\n detail: string;\n}\n\n/** POST /api/sessions/:id/answer — answer the permission prompt shown. */\nexport interface AnswerRequest {\n answer: 'allow' | 'deny';\n /** The request the user was shown; refused if the prompt moved on. */\n request: PermissionRequest;\n}\n\n/** A session's agent on the wire: who, and which of its adapter's capabilities exist (agents/types.ts). */\nexport interface SessionAgentWire {\n /** Its binary name (`claude`). */\n id: string;\n /** How to name it to you (\"Claude Code\"). */\n name: string;\n can: {\n /** Its conversation can be read (context %, digest, search, `work read`…). */\n read: boolean;\n /** Its turns are heard through hooks (working / done / needs input). */\n hooks: boolean;\n /** Its running processes are seen outside work's own terminals. */\n live: boolean;\n /** Its permission prompts can be answered from the dashboard. */\n answer: boolean;\n /** It runs on one of several logins, and a session can be moved between them (absent: a server from before accounts). */\n accounts?: boolean;\n };\n}\n\n/** Hook-driven agent status as sent to the dashboard (attention inbox). */\nexport interface SessionAttention extends AttentionLike {\n /** One line: prompt while working, last message when done, the\n * permission request when blocked. */\n summary?: string;\n updatedAt: string;\n /** A \"working\" that went quiet for 15 min, shown as idle. */\n stale: boolean;\n /** needs_input on a permission prompt: what it wants to run. */\n request?: PermissionRequest;\n /** Working because a background agent its turn started is still at it: its turn ended, its prompt is free. `what`:\n * the agent's own description (\"/mtk:code-review-and-quality Re-review…\"), when it gives one. With `command`: idle,\n * with a background command it started (a build, tests, a dev server) still running — `what` names it.\n * Absent: an older server. */\n background?: { what: string | null; command?: boolean };\n}\n\n/** Who archived a session: you (Archive, its key, the bulk bar), Ship's merge, the PR watch once its PR merged, or Clean up. */\nexport const ARCHIVED_BY = ['you', 'shipped', 'pr-merged', 'cleanup'] as const;\nexport type ArchivedBy = (typeof ARCHIVED_BY)[number];\n\n/** An archived session: whether its folder went, and what it was about. */\nexport interface SessionArchiveInfo {\n /** Who archived it (none: archived before work recorded it). */\n by?: ArchivedBy;\n worktreeRemoved: boolean;\n keptBecause: string | null;\n promptCount: number;\n /** Its prompts (first and latest), for recall and search. */\n prompts: string[];\n lastSummary: string | null;\n /** What was done and why, written after archiving (null until then). */\n written?: string | null;\n /** Build output cleared from its kept worktree. */\n buildFolders?: { folders: number; bytes: number };\n /** Uncommitted files saved when its worktree was removed, waiting for Restore to put them back. */\n savedUncommitted?: number;\n /** What was waiting in it when archived, kept with it (\"2 reply drafts, 1 note for its Claude\"). */\n kept?: string;\n}\n\n/** A session's running Claudes: in your terminal, or run by the app. */\nexport interface SessionClaudes {\n inTerminal: number;\n inApp: number;\n /** One of them is in the middle of a turn. */\n busy: boolean;\n /** Two or more on one conversation (they would both write to it). */\n duplicate: boolean;\n /** What Claude Code itself says (~/.claude/sessions/<pid>.json): mid-turn, at its prompt, waiting on you, or\n * (`shell`) at its prompt with a background command it started still running. */\n state?: 'busy' | 'idle' | 'waiting' | 'shell';\n /** When that last changed (ms). */\n stateAt?: number;\n /** While waiting: what for. */\n waitingFor?: string;\n}\n\n// ---- merged local branches (Clean up) ---------------------------------------\n\nexport interface BranchCandidate {\n /** Repo alias. */\n repo: string;\n repoPath: string;\n branch: string;\n tip: string;\n /** merged: git says so; squash-merged: a merged PR's head is its tip. */\n reason: 'merged' | 'squash-merged';\n prNumber?: number;\n /** An archived session uses it: its Restore needs the branch. */\n archivedSession?: string;\n}\n\n/** GET /api/cleanup/branches */\nexport interface BranchesState {\n scanning: boolean;\n scannedAt: string | null;\n candidates: BranchCandidate[];\n}\n\n// ---- build folders (Clean up: space without archiving) ---------------------\n\nexport interface BuildFolder {\n path: string;\n bytes: number;\n}\n\nexport interface BuildFolderCandidate {\n sessionId: string;\n target: string;\n branch: string;\n /** A repo's own checkout (not a worktree `work` made). */\n baseCheckout?: boolean;\n lastActive: string;\n folders: BuildFolder[];\n bytes: number;\n}\n\n/** GET /api/cleanup/build-folders */\nexport interface BuildFoldersState {\n scanning: boolean;\n checked: number;\n total: number;\n scannedAt: string | null;\n candidates: BuildFolderCandidate[];\n}\n\nexport interface BuildFoldersApplyResult {\n sessionId: string;\n ok: boolean;\n removed: number;\n message: string;\n}\n\n// ---- Repos and groups (repo-admin.ts; the Repos page) ----------------------\n\n/** A repo the Repos page lists: enrolled (by alias), found in a scanned folder and not yet, or ignored. */\nexport interface RepoRow {\n path: string;\n folder: string;\n /** `owner/name` of its origin, when it has one. */\n origin: string | null;\n /** missing: enrolled, but the folder is gone. */\n status: 'enrolled' | 'new' | 'ignored' | 'missing';\n /** Its alias, when enrolled. */\n alias: string | null;\n /** For a new one: the alias it would get. */\n suggestedAlias?: string;\n /** For a new one: why it can't be enrolled as suggested (pick another alias, or it can't be at all). */\n problem?: string | null;\n /** Other aliases on the same folder (an old duplicate). */\n sharedWith?: string[];\n /** Groups it is in. */\n groups: string[];\n /** Live sessions on it. */\n sessions: number;\n}\n\nexport interface GroupRow {\n name: string;\n members: string[];\n /** Members that are no longer enrolled. */\n missing: string[];\n /** Live sessions on the group. */\n sessions: number;\n /** What's wrong with it as it is (fewer than two repos, …); null when fine. */\n problem: string | null;\n}\n\n/** GET /api/repos */\nexport interface ReposWire {\n /** The folders scanned (config `scanRoots`, else the worktrees root's). */\n roots: string[];\n repos: RepoRow[];\n groups: GroupRow[];\n}\n\n// ---- Updates and release notes (core/updates/) --------------------------------\n\nexport type { ReleaseNote, InstallKind, DesktopUpdate, AvailableUpdate } from './updates/updates.js';\n\n/** GET /api/updates */\nexport interface UpdateWire {\n /** This work's version (\"dev\" for an unbuilt run). */\n running: string;\n install: import('./updates/updates.js').InstallKind;\n /** The newest published release, when the list was read. */\n latest: string | null;\n checkedAt: string | null;\n /** Why the release list couldn't be read, the last time. */\n checkError: string | null;\n /** The desktop app's updater, while the app runs. */\n desktop: import('./updates/updates.js').DesktopUpdate | null;\n /** An update to offer, and how it's had. */\n available: import('./updates/updates.js').AvailableUpdate | null;\n /** The version whose notes to open by themselves (once after an upgrade), or null. */\n whatsNew: string | null;\n}\n\n// ---- First run (first-run.ts, the Welcome page) -----------------------------\n\n/** A tool work leans on, and whether it answers here. */\nexport interface ToolCheck {\n /** The tool's command: git, claude, each git host's CLI (gh, az), acli. */\n id: string;\n label: string;\n /** work can't do without it (git, Claude Code); the others add features. */\n needed: boolean;\n ok: boolean;\n /** Its version when it answers; what to do when it doesn't. */\n detail: string;\n}\n\n/** GET /api/setup */\nexport interface SetupWire {\n /** config.json exists, with a worktrees folder. */\n configured: boolean;\n worktreesRoot: string | null;\n /** The folder scanned for repos (config scanRoots[0], else the one holding the worktrees). */\n reposFolder: string | null;\n repos: number;\n /** Live sessions. */\n sessions: number;\n /** Folders to offer when none are set. */\n suggested: { reposFolder: string | null; worktreesRoot: string };\n tools: ToolCheck[];\n}\n\n// ---- Diff: since you last looked (diff-seen.ts) -----------------------------\n\n/** GET/POST /api/sessions/:id/diff-seen: the newest turn (checkpoint id) on screen the last time you looked at its diff. */\nexport interface DiffSeen {\n checkpointId: number;\n at: string;\n /** That turn's own time (its checkpoint's `ts`): a re-baselined scope counts turns from 1 again, and the time\n * tells a reused number from the turn you saw. Absent on a mark from before. */\n ts?: string;\n /** Your looks, oldest first (diff-looks.ts): what \"Since you looked\" showed each time, to see again. */\n looks?: DiffLook[];\n}\n\n/** One look at a session's diff: the turns (checkpoint ids) it went from and to, and when (started, last grew). */\nexport interface DiffLook {\n from: number;\n to: number;\n /** The two turns' own times (see DiffSeen.ts): a look whose numbers now name other turns isn't shown. */\n fromTs?: string;\n toTs?: string;\n startedAt: string;\n at: string;\n}\n\n/** A commit of one of the session's repos since its branch left its base: the Diff tab's picker lists them with the turns. */\nexport interface SessionCommit {\n /** The repo's tab name (its folder). */\n repo: string;\n sha: string;\n subject: string;\n /** Committer date, ISO: commits and turns are listed in time order. */\n at: string;\n /** Another branch the session worked on (session-branches.ts): its commits since its base, listed under it.\n * Absent: the checked-out branch's. */\n branch?: string;\n}\n\n/** GET /api/sessions/:id/checkpoints: its turns, and (additive) its commits since the branch's base. */\nexport interface SessionHistoryWire {\n scopeHash: string;\n /** `branches`: each repo's checked-out branch when the turn was taken (by repo root; absent on turns from before) —\n * a turn whose branch differs from the one before it crossed a switch. */\n entries: Array<{\n id: number;\n ts: string;\n label?: string;\n repos: Record<string, string | null>;\n branches?: Record<string, string | null>;\n }>;\n commits?: SessionCommit[];\n /** (additive) Each other branch's whole work: its base and its tip, to diff between (`c:<repo>:<base>` to `c:<repo>:<tip>`). */\n branchSpans?: SessionBranchSpan[];\n}\n\n/** Another branch the session worked on, as one span: from the last base it took in (or where it was made) to its tip. */\nexport interface SessionBranchSpan {\n /** The repo's tab name (its folder). */\n repo: string;\n branch: string;\n base: string;\n tip: string;\n}\n\n/**\n * One branch a session's repo has been on (session-branches.ts), with what the background look found\n * (branch-facts.ts) and its PR (the PR watch's last check). The session header's Branches line, the Diff\n * picker's groups, `work sessions --json`.\n */\nexport interface SessionBranchWire {\n /** The repo as the session names it (a group's folder, a single repo's target). */\n repo: string;\n name: string;\n /** Checked out in that repo now. */\n current: boolean;\n firstSeen: string;\n lastSeen: string;\n /** What it was made from (`origin/dev`), when the reflog said. */\n from?: string;\n /** The facts: absent until the background look has been. */\n exists?: boolean;\n /** `origin/<name>` exists. */\n pushed?: boolean;\n /** Commits on it its base (origin/HEAD) doesn't have; null: unknown. */\n commits?: number | null;\n /** Commits on it origin doesn't have (all of them when it was never pushed); null: unknown. */\n unpushed?: number | null;\n /** Its work is in main (its commits, or its PR merged). */\n merged?: boolean;\n /** Its newest PR, as the PR watch last saw it. */\n pr?: { number: number; url: string; state: 'OPEN' | 'MERGED' | 'CLOSED'; kind: import('./pr/pr-stage.js').PrStageKind };\n}\n\n// ---- New worktree: is the branch new? (branch-check.ts) -------------------\n\n/** GET /api/branch-check?target=&branch= */\nexport interface BranchCheck {\n branch: string;\n /** git takes it as a branch name. */\n valid: boolean;\n /** A branch of that name in one of the project's repos (local or origin): Create checks it out. */\n exists: boolean;\n /** The session already on it: Create reuses it (an archived one is restored). */\n session: { id: string; archived: boolean } | null;\n /** The first free name from it (`branch`, `branch-2`, …); null when none is, or it isn't valid. */\n free: string | null;\n /** It is the branch the repo's own folder is on: Create opens that folder (no new worktree). */\n ownCheckout?: true;\n}\n\n// ---- assistant (Ctrl+K) ---------------------------------------------------\n\n/** POST /api/assistant/context — what the dashboard shows right now, so the\n * assistant knows what \"this\" means. */\nexport interface AssistantView {\n /** The top tab or view: inbox, today, sessions, cleanup, prs, jira, tasks, session. */\n tab: string;\n /** Sub-view (a session's diff / term / comments). */\n sub?: string;\n /** The session on screen, if any. */\n sessionId?: string | null;\n /** Anything else worth saying (e.g. \"12 cleanup candidates listed\"). */\n note?: string;\n /** The Time tab's day on screen (`YYYY-MM-DD`). */\n day?: string;\n /** The Time tab's Month view on screen (`YYYY-MM`): described in place of a day. */\n month?: string;\n /** The Reviews tab's PR on screen: its prepared review is described (#64). */\n review?: { repo: string; number: number };\n}\n\n// ---- cleanup --------------------------------------------------------------\n\n/** What cleanup found: `merged` — safe to delete; `work`/`dirty` — has\n * something of its own (offered for archiving once a week quiet); `gone` —\n * folder missing; `keep` — not a candidate. */\nexport type CleanupVerdict = 'merged' | 'work' | 'dirty' | 'gone' | 'keep';\nexport type CleanupAction = 'delete' | 'archive' | 'forget';\n\nexport interface CleanupRepo {\n name: string;\n path: string;\n exists: boolean;\n /** git could read it. */\n readable: boolean;\n /** Uncommitted + untracked files. */\n dirty: number | null;\n /** Commits not in `base`. */\n ahead: number | null;\n /** 'contained' — nothing of its own; 'squash' — squash-merged; null — has work. */\n merged: 'contained' | 'squash' | null;\n /** The ref compared with (origin/HEAD, origin/main…). */\n base: string | null;\n /** The configured repo itself, not a worktree: never removed. */\n baseCheckout: boolean;\n}\n\nexport interface CleanupCandidate {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n lastActive: string;\n archivedAt: string | null;\n verdict: CleanupVerdict;\n /** What the view pre-selects; null — shown for information only. */\n suggested: CleanupAction | null;\n reason: string;\n repos: CleanupRepo[];\n}\n\n/** GET /api/cleanup — the scan / apply job, polled by the Clean up view. */\nexport interface CleanupState {\n phase: 'idle' | 'fetching' | 'scanning' | 'applying';\n done: number;\n total: number;\n candidates: CleanupCandidate[];\n results: Array<{ sessionId: string; action: CleanupAction; ok: boolean; message: string }>;\n startedAt?: string;\n finishedAt?: string;\n error?: string;\n}\n\n/** POST /api/cleanup/apply */\nexport interface CleanupApplyRequest {\n items: Array<{ sessionId: string; action: CleanupAction }>;\n}\n\n/** Terminal WebSocket control frame: the session's Claude is running in\n * a plain terminal (not the PTY host), so nothing was spawned — a second\n * Claude would share its conversation. Reconnect with `?force=1` to\n * spawn anyway. */\n/**\n * `POST /api/terminals/:id/ticket`: where the Terminal tab connects. `url`: straight to the PTY host, with a one-time\n * ticket (terminal-tickets.ts); `fallback`: through work web's relay (`/ws/sessions/:id/terminal`) as before — a host\n * from before tickets, the demo; `elsewhere`: its Claude runs in another terminal, nothing was started; `error`: it\n * couldn't be started (archived, the host won't start), said over the pane.\n */\n/** `POST /api/terminal-perf`: what a Terminal tab measured since it last sent (core/pty/terminal-perf.ts). */\nexport interface TerminalPerfWire {\n sessionId: string;\n route: 'direct' | 'relay' | null;\n renderer: 'webgl' | 'retrying' | 'dom';\n /** Each keystroke: ms to its echo, and to the first frame drawn after it (null: none before the next key). */\n keys: { arrived: number; shown: number | null }[];\n /** Each time the window froze: when (epoch ms), how long, the part that blocked input, what ran. */\n stalls: { at: number; ms: number; blocking: number | null; what: string }[];\n}\n\nexport type TerminalTicketWire = { url: string } | { fallback: true } | { elsewhere: TerminalElsewhere } | { error: string };\n\nexport interface TerminalElsewhere {\n type: 'elsewhere';\n /** Claude's last transcript write (ms since epoch), or null. */\n lastActivity: number | null;\n state: 'working' | 'needs_input' | 'idle' | null;\n /** A Claude process is known to run on this conversation (Claude's own\n * process files), not inferred from activity: the tab then offers no way\n * to start a second one. */\n confirmed?: boolean;\n}\n\n/** GET /api/digest — what each session did since a point in time. */\nexport interface DigestResponse {\n since: string;\n generatedAt: string;\n sessions: DigestSession[];\n}\n\nexport interface DigestSession {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n /** Where it stands now. */\n state: 'working' | 'needs_input' | 'idle' | null;\n summary?: string;\n /** What you asked it in the window, oldest first (capped). */\n prompts: Array<{ ts: string; text: string }>;\n /** More prompts than listed. */\n morePrompts: number;\n /** Finished turns (checkpoints) in the window, and the names already given to them. */\n turns: number;\n turnLabels: string[];\n /** A transcript was too large to read back to the window's start, so\n * earlier prompts are missing. */\n partial?: boolean;\n diffStat: DiffStat | null;\n prs: Array<{ repo: string; number: number; url: string; state: 'OPEN' | 'MERGED' | 'CLOSED'; mergedAt?: string }>;\n archivedAt: string | null;\n /** Newest activity in the window (ISO). */\n lastActivity: string;\n /** How long its Claude worked in the window (work-time.ts; approximate). */\n workedMs?: number;\n}\n\n/** A one-click instruction for a session (config `prompts`, or defaults). */\nexport interface SavedPrompt {\n label: string;\n prompt: string;\n /** Only for these repo aliases / group names; all when absent. */\n repos?: string[];\n}\n\n/** GET /api/prompts */\nexport interface PromptsResponse {\n prompts: SavedPrompt[];\n /** False when these are the built-in defaults (no `prompts` in config). */\n configured: boolean;\n}\n\n/** How full the session's Claude conversation is (tokens). */\nexport interface ContextUsage {\n /** Tokens the conversation holds now (last request's prompt + reply). */\n used: number;\n /** The model's context window. */\n window: number;\n model?: string;\n}\n\n/** Another live session that changes some of the same files (same repo,\n * same path): the two will conflict when both merge. */\nexport interface SessionOverlap {\n sessionId: string;\n target: string;\n branch: string;\n /** How many files both change. */\n count: number;\n /** The first of them (capped), repo alias + root-relative path. */\n files: Array<{ repo: string; path: string }>;\n}\n\n/** One row of GET /api/sessions — what every dashboard server (the real\n * work web and the demo) sends. */\nexport interface SessionWire {\n id: string;\n /** Being archived right now (archiving.ts: the button, Ship, the PR watch, cleanup): shown as Archiving until it's gone. */\n archiving?: true;\n /** Its Claude was stopped by work while idle (idle sleep, `work stop`) and hasn't run since: Asleep —\n * opening the session starts it again, conversation and all (session-wire.ts `isAsleep`). */\n asleep?: true;\n /** Being restored right now (archiving.ts): listed with the live sessions meanwhile, still `archivedAt` until it's done. */\n restoring?: true;\n /** Snoozed out of the Inbox right now (snooze.ts): until when, or null for \"until it changes\". */\n snoozed?: { until: string | null };\n /** Behind its main branch (behind-main.ts, as of the last fetch) — or, when stacked, behind the\n * session it is stacked on (`stacked`, its local branch): absent when level or unknown. */\n behind?: { base: string; commits: number; conflicts: boolean; stacked?: true };\n /** The live session it is stacked on (stack.ts): made from that session's branch. */\n stackedOn?: { id: string; branch: string; title?: string };\n /** How many live sessions are stacked on this one. */\n stackedChildren?: number;\n /** You have notes on it (session-notes.ts; GET /api/sessions/:id/note). */\n hasNote?: boolean;\n /** You asked to keep it once its PR merges: neither the PR watch nor Ship's merge archives it. Absent: archived then, as usual. */\n keepAfterMerge?: true;\n /** What it waits on that isn't done yet (session-blocks.ts): out of the Inbox meanwhile. */\n blockedBy?: BlockerWire[];\n /** It was stacked on a session that merged and is archived: it should move onto main (POST …/retarget). */\n stackParentMerged?: { id: string; branch: string };\n target: string;\n /** The branch it was started on: with target, the session's identity (and its folder's name). */\n branch: string;\n /** Every branch it worked on (session-branches.ts), the checked-out ones first: present only when some repo\n * has been on more than one (merged ones deleted a while ago left out). Absent from a server before this. */\n branches?: SessionBranchWire[];\n /** Repos whose checkout is on another branch now (Claude switched, or you did); null = detached HEAD. */\n /** `noGit`: its folder has no git left in it (a removal that stopped halfway): `work tree` makes it again. */\n onOtherBranch?: Array<{ repo: string; branch: string | null; noGit?: true }>;\n isGroup: boolean;\n paths: string[];\n /** Its repos' aliases, one per path in the same order (session-repos.ts `sessionRepos`: the recorded list,\n * else a group's config members by folder name, a single repo's target). Absent from a server before this. */\n repos?: string[];\n /** A session folder (a group's, or one made with `sessionFolders`): its agent runs in the folder and a repo\n * can be added to it (POST …/repos). Absent from a server before this. */\n folder?: boolean;\n baseBranch?: string;\n jiraKey?: string;\n createdAt: string;\n lastAccessedAt: string;\n draftCount: number;\n /** Open comment threads (top-level, not resolved): the Diff tab's badge. */\n commentCount: number;\n claudeCount: number;\n ptyStatus: PtyStatus;\n lastActivity: number | null;\n activityState: ActivityState;\n pendingForClaudeCount: number;\n attention: SessionAttention | null;\n diffStat: DiffStat | null;\n archivedAt: string | null;\n /** This worktree's dev-server port ($PORT), when it has one. */\n port: number | null;\n /** Its agent processes running right now (agents/: `live`, grouped by core/live-claudes.ts);\n * absent when none. */\n agents?: SessionClaudes;\n /** @deprecated The same as `agents` (its old name; kept for `work sessions --json` readers for one version). */\n claudes?: SessionClaudes;\n /** The agent it runs, and what work can do with it (a feature it can't is hidden, not shown broken). */\n agent?: SessionAgentWire;\n /** The account (login) its agent runs on, by its config name; absent = the default account. */\n account?: string;\n /** The account a switch waiting for its turn to end will move it to (kept in work web's memory). */\n accountPending?: string;\n /** What its archive kept (archived sessions; session-archive.ts). */\n archive?: SessionArchiveInfo;\n /** Its name: the one you gave it, else its first prompt, else its Jira key. */\n title?: string | null;\n /** The title is one you gave it (not the automatic one). */\n titleIsYours?: boolean;\n /** Other sessions changing the same files; absent when there are none. */\n overlaps?: SessionOverlap[];\n /** Context used by its Claude conversation; null before the first reply. */\n context?: ContextUsage | null;\n /** Unresolved review threads on its open PRs whose last word isn't\n * yours (the PR watch's count, pr-review.ts); absent when none or not\n * checked yet. Makes it \"Review comments\" (session-view.ts). */\n openReviewThreads?: number;\n /** Replies its Claude drafted for you to post on those threads (pr-replies.ts). */\n replyDrafts?: number;\n /** Where its pull request stands (pr-stage.ts, the PR watch's last check); `seen` once you\n * opened the session at this stage. Absent with no PR or before the first check. */\n prStage?: PrStageWire;\n}\n\n/** A session's PR stage, as the dashboard gets it. */\nexport type PrStageWire = import('./pr/pr-stage.js').PrStage & { seen?: boolean };\n\n// ---- time (the Time tab: a day's hours per ticket) -------------------------\n\nexport interface TimeEntryWire {\n key: string;\n hours: number;\n}\n\n/** A session that worked that day: its Claude's minutes, and the ticket it is for (null: none known). */\nexport interface TimeSessionEvidence {\n sessionId: string;\n label: string;\n key: string | null;\n minutes: number;\n /** Its ticket is the AI step's guess (classify.ts), not its branch or Jira key. */\n guessed?: true;\n}\n\nexport interface TimeCommitEvidence {\n repo: string;\n sha: string;\n subject: string;\n keys: string[];\n guessed?: true;\n}\n\n/** A meeting from Outlook that day (Graph): it goes to its ticket when the AI step places it, else to the gap ticket. */\nexport interface TimeMeetingEvidence {\n /** Outlook's id for it (what the AI step's answer is kept by; absent in days gathered before). */\n id?: string;\n subject: string;\n /** Local `HH:MM`. */\n start: string;\n end: string;\n minutes: number;\n key?: string | null;\n guessed?: true;\n}\n\n/** A Teams chat you wrote in that day: how many of your messages, a few of them shortened (what the AI step reads). */\nexport interface TimeChatEvidence {\n /** Issue keys anyone in the chat named that day (only the keys are read from others' messages). */\n mentions?: string[];\n /** Teams' id for the chat: untitled ones share a name (\"a one-on-one chat\"). */\n id?: string;\n chat: string;\n messages: number;\n sample: string[];\n key?: string | null;\n guessed?: true;\n}\n\n/** An issue you did something to that day in Jira (moved it). */\nexport interface TimeJiraEvidence {\n key: string;\n summary: string;\n what: string;\n}\n\nexport interface TimeEvidence {\n sessions: TimeSessionEvidence[];\n commits: TimeCommitEvidence[];\n jira: TimeJiraEvidence[];\n meetings?: TimeMeetingEvidence[];\n chats?: TimeChatEvidence[];\n /** What the AI step last placed (a hash of the unplaced items): it isn't asked again until they change. */\n classifiedFor?: string;\n}\n\n/** empty: nothing built yet; draft: the suggestion; edited: your rows; off: a day off; not-workday: a weekend or holiday;\n * posted: in Tempo as it stands; changed: posted, then changed (post again). */\nexport type TimeDayStatus = 'empty' | 'draft' | 'edited' | 'off' | 'not-workday' | 'posted' | 'changed';\n\nexport interface TimeSettingsWire {\n dayHours: number;\n multiplier: number;\n capHours: number;\n stepHours: number;\n minHours: number;\n gapTicket: string | null;\n timeOffTicket: string | null;\n /** Hours as measured (Claude minutes 1:1), not scaled. */\n effort: boolean;\n}\n\n/** POST /api/sessions/:id/diff-page: where the session's diff has a page of its own (the one `wd` opens). */\nexport interface DiffPageWire {\n url: string;\n}\n\n/** GET /api/time/:day */\nexport interface TimeDayWire {\n day: string;\n status: TimeDayStatus;\n workday: boolean;\n dayOff: boolean;\n /** What work suggests from the evidence. */\n suggested: TimeEntryWire[];\n /** What will be posted: your rows when you edited, else the suggestion. */\n entries: TimeEntryWire[];\n edited: boolean;\n /** Hours of the day no ticket has (no gap ticket set). */\n unallocated: number;\n total: number;\n evidence: TimeEvidence;\n /** Issue titles, by key. */\n titles: Record<string, string>;\n builtAt: string | null;\n settings: TimeSettingsWire;\n /** When work last posted the day to Tempo, and what. */\n posted: { at: string; entries: TimeEntryWire[] } | null;\n /** A vacation day (config `time.vacation`): a day off whatever was ticked. */\n vacation: boolean;\n /** How each row got its hours, by key: the suggestion's arithmetic and what it came from, or \"your hours\". */\n why: Record<string, string>;\n /** Rows whose ticket Jira had as done when the day was gathered. */\n resolved: string[];\n /** Rows whose ticket is a placeholder (`time.hints`): create it in Jira before posting. */\n placeholders: string[];\n /** Whether it can post (a Tempo token and your account id), or why not. Set by the server. */\n posting?: { ready: boolean; why: string | null };\n}\n\n/** GET /api/time/graph: Outlook and Teams for the Time tab (Microsoft Graph). */\nexport interface TimeGraphWire {\n /** Can it sign in at all (an app registration), or why not. */\n ready: boolean;\n why: string | null;\n /** Signed in as. */\n account: string | null;\n /** Signed in, but it stopped working (expired or revoked, another app registration): connect again. */\n problem: string | null;\n /** A sign-in under way: the code to enter at the address. */\n login: { userCode: string; verificationUri: string; expiresAt: string } | null;\n /** How the last sign-in went wrong. */\n error: string | null;\n}\n\n/** POST /api/time/:day/post */\nexport interface TimePostWire {\n posted: number;\n removed: number;\n kept: number;\n /** Rows a worklog you made by hand in Tempo already covered (not posted again). */\n coveredByHand: number;\n /** Your own worklogs that day that no row matches: left alone. */\n otherByHand: number;\n failed: Array<{ key: string; error: string }>;\n day: TimeDayWire;\n}\n\nexport interface TimeDaySummary {\n day: string;\n status: TimeDayStatus;\n workday: boolean;\n total: number;\n tickets: number;\n}\n\n/** GET /api/time?from=&to= */\nexport interface TimeDaysWire {\n days: TimeDaySummary[];\n settings: TimeSettingsWire;\n}\n\n/** A day of the Month view: what will be posted for it. */\nexport interface TimeMonthDay {\n day: string;\n status: TimeDayStatus;\n workday: boolean;\n dayOff: boolean;\n /** Today: still going, never posted with the month. */\n today: boolean;\n /** Your rows, not the suggestion. */\n edited: boolean;\n /** How each row got its hours (TimeDayWire.why). */\n why: Record<string, string>;\n entries: TimeEntryWire[];\n total: number;\n /** Its rows whose ticket is a placeholder (`time.hints`): it can't be posted until they're made in Jira. */\n placeholders: string[];\n}\n\n/** Why a day of the month isn't posted with it. */\nexport type TimeMonthLeftOut = 'today' | 'placeholder' | 'posted' | 'empty' | 'not-gathered' | 'not-workday';\n\n/** A ticket's hours across days. */\nexport interface TimeMonthTicket {\n key: string;\n title: string;\n hours: number;\n /** On how many days. */\n days: number;\n placeholder: boolean;\n}\n\n/** GET /api/time/month/:month (YYYY-MM): the month up to today as a grid, and what \"Post the month\" would do. */\nexport interface TimeMonthWire {\n month: string;\n /** Oldest first: every workday, and a weekend or holiday when something happened on it. */\n days: TimeMonthDay[];\n /** The month's tickets with their totals: most hours first, time off and the gap ticket last. */\n tickets: TimeMonthTicket[];\n /** Posting the month: the days that go, oldest first, and the rest with why. */\n plan: {\n days: string[];\n leftOut: Array<{ day: string; why: TimeMonthLeftOut }>;\n /** What goes, per ticket. */\n tickets: TimeMonthTicket[];\n total: number;\n /** Days that go with less or more than the day's hours. */\n short: Array<{ day: string; total: number }>;\n };\n /** Past days never gathered, or gathered before they ended (Gather these days). */\n missing: number;\n settings: TimeSettingsWire;\n /** Set by the server: a gather of the month under way, and how the last one failed. */\n gathering?: boolean;\n gatherError?: string | null;\n /** Set by the server: whether it can post (a Tempo token and your account id), or why not. */\n posting?: { ready: boolean; why: string | null };\n}\n\n// ---- start on a PR ---------------------------------------------------------\n\n/** The PR a session is started on, as the lookup found it (core/pr/pr-start.ts). */\nexport interface PrToStart {\n /** The repo alias it belongs to (a group's repo: the session is that repo's alone). */\n alias: string;\n number: number;\n title: string;\n url: string;\n /** Its head branch: on origin, so the session's pushes reach the PR. */\n branch: string;\n /** Where it merges into. */\n base: string;\n author: string;\n /** The host it's on; absent for GitHub (and from a server before hosts). */\n host?: string;\n}\n\n/** GET /api/pr-start?ref=&target=: the PR, or (400) why not — a fork, closed, not one of your repos. */\nexport type PrStartWire = { pr: PrToStart } | { error: string };\n\n// ---- ship -----------------------------------------------------------------\n\nexport type ChecksState = 'pass' | 'fail' | 'pending' | 'none';\n\nexport interface ShipPr {\n number: number;\n url: string;\n state: 'OPEN' | 'MERGED' | 'CLOSED';\n isDraft: boolean;\n /** GitHub mergeStateStatus: CLEAN | DIRTY | BLOCKED | BEHIND | UNSTABLE | HAS_HOOKS | DRAFT | UNKNOWN */\n mergeStateStatus: string;\n checks: ChecksState;\n headSha: string;\n /** When it was merged (ISO), for a MERGED PR. */\n mergedAt?: string;\n /** When anything on it last changed (a push, a comment, a review): the\n * PR watch re-reads review threads only when this moved. */\n updatedAt?: string;\n /** Checks that failed (name + link), when `checks` is 'fail'. */\n failing?: FailingCheck[];\n /** Checks that failed but aren't required: the host merges it all the same, so they don't make `checks` fail —\n * shown quietly, never red, never asked of Claude. */\n optionalFailing?: FailingCheck[];\n /** The host said which checks are required (GitHub's branch protection or rulesets, Azure DevOps' blocking\n * policies), and `checks` counts only those: a repo's list in config (`prWatch.requiredChecks`) isn't applied. */\n checksRequiredByHost?: boolean;\n /** `checks` is 'fail' and another check was still running then: once the failures turn out not to count (a repo's\n * list in config), the PR's checks are running, not passing. */\n checksRunning?: true;\n /** APPROVED | CHANGES_REQUESTED | REVIEW_REQUIRED, or '' when the repo requires no review (gh's reviewDecision). */\n reviewDecision?: string;\n /** Its author's login: a session on someone else's PR (work on it, review it) isn't handed its threads or CI notes. */\n author?: string;\n /** The branch it merges into (gh's baseRefName): what a conflict is resolved against. */\n baseBranch?: string;\n /** Its own branch (gh's headRefName), when the host said: a session's PR on a branch it isn't on now is named by it. */\n headBranch?: string;\n}\n\nexport interface FailingCheck {\n name: string;\n url?: string;\n}\n\nexport interface RepoShipState {\n /** Repo alias (group sub-repo folder, or the target for a single repo). */\n name: string;\n /** The host its PRs are on (`github`, `azure`; absent from a server before hosts: GitHub). */\n host?: string;\n path: string;\n branch: string;\n /** Local HEAD commit. */\n localSha: string;\n /** Its PR is merged at a later commit that contains HEAD — commits added on GitHub (a bot's\n * \"Update branch\") the worktree never pulled — so everything checked out is in the merge. */\n behindMergedHead?: boolean;\n /** Uncommitted (incl. untracked) files — shipping needs a clean tree. */\n dirtyFiles: number;\n /** git couldn't read the working tree (a timeout under load): its facts are unknown, so it's never done. */\n gitError?: string;\n /** The branch exists on origin (`origin/<branch>`), whatever the local\n * tracking config says — `work tree` often leaves it tracking the base. */\n hasUpstream: boolean;\n /** Local tracking is set to `origin/<branch>` (a plain `git push` works). */\n tracksRemote: boolean;\n /** vs `origin/<branch>`; null when the branch isn't on origin. */\n ahead: number | null;\n behind: number | null;\n pr: ShipPr | null;\n /** Nothing left to do here: PR merged with nothing since, or the repo\n * was never touched. Never blocks the other repos of a group. */\n done: boolean;\n doneReason?: 'merged' | 'untouched';\n /** Why \"merge\" isn't available right now ([] = go). Empty when done. */\n mergeBlockers: string[];\n /** gh missing / not authenticated / no GitHub remote. */\n ghError?: string;\n /** Commits the remote's default branch doesn't have (null = unknown). */\n commitsVsBase?: number | null;\n /** The other branches this repo worked on (session-branches.ts), as they stand: a session isn't done\n * while one has work that isn't pushed or a PR still open (`workElsewhere`). Absent: none recorded. */\n otherBranches?: OtherBranchState[];\n /** PRs on the session's list (session-prs.ts) in this repo that neither the checked-out branch nor `otherBranches`\n * found — a branch made and left within one turn, or one past the branches looked at — each looked up by its link. */\n listedPrs?: Array<{ branch: string; pr: ShipPr }>;\n}\n\n/** A PR on the session's list in a repo the session doesn't have (Claude opened one on the docs repo too). */\nexport interface ElsewherePr {\n /** The host's name for the repo (`owner/name`). */\n repo: string;\n /** Its host (absent: GitHub). */\n host?: string;\n /** Its branch, when the host said. */\n branch?: string;\n pr: ShipPr;\n}\n\n/** Another branch a repo of the session worked on: the facts (branch-facts.ts) and its PR. */\nexport interface OtherBranchState {\n name: string;\n exists: boolean;\n /** Its tip, when it exists: a merged PR at it leaves nothing unpushed, its origin branch deleted or not. */\n sha?: string | null;\n pushed: boolean;\n commits: number | null;\n unpushed: number | null;\n merged: boolean;\n pr: ShipPr | null;\n /** The host couldn't say (its PR unknown: never read as none). */\n ghError?: string;\n}\n\nexport interface ShipPreflight {\n repos: RepoShipState[];\n /** The session's listed PRs in repos it doesn't have (session-prs.ts). */\n elsewhere?: ElsewherePr[];\n /** Listed PRs still open as far as work knows that the host couldn't be asked about this time (`<repo>#<n>: why`):\n * never read as gone — the session isn't archived meanwhile. */\n unknownPrs?: string[];\n}\n\nexport type ShipAction = 'push' | 'create-pr' | 'merge';\nexport type MergeMethod = 'squash' | 'merge' | 'rebase';\n\n/** A repo the user chose to merge, with the PR head they were shown. */\nexport interface MergeSelection {\n name: string;\n headSha: string;\n}\n\nexport interface ShipResult {\n repo: string;\n ok: boolean;\n message: string;\n url?: string;\n /** For merge: whether this repo's PR was merged by this call. */\n merged?: boolean;\n}\n\n/** POST /api/sessions/:id/ship body. */\nexport type ShipRequest =\n { action: 'push' | 'create-pr'; draft?: boolean } | { action: 'merge'; method?: MergeMethod; repos: MergeSelection[] };\n\nexport interface ShipResponse {\n results: ShipResult[];\n archived?: boolean;\n allDone?: boolean;\n}\n\n/** POST /api/sessions/:id/revert — undo an uncommitted file, or the lines\n * of one hunk (new-side range), back to HEAD. */\nexport interface RevertRequest {\n repo: string;\n path: string;\n lines?: { start: number; end: number };\n /** Leave Claude a note about it (default true). */\n tell?: boolean;\n}\nexport interface RevertResponse {\n ok: true;\n description: string;\n}\n\n/** POST /api/presence — one dashboard tab says what it is showing. Sent on\n * every change and as a heartbeat; `gone` when the tab closes. */\nexport interface PresenceReport {\n /** Random per tab. */\n clientId: string;\n /** The session the tab shows, or null (Inbox, Sessions table, …). */\n sessionId: string | null;\n visible: boolean;\n focused: boolean;\n /** The tab may show browser notifications (permission granted). */\n canNotify: boolean;\n gone?: boolean;\n}\n\n/** SSE `notify` — a session wants the user and nobody is looking at it. */\nexport interface NotifyEvent {\n sessionId: string;\n kind: 'idle' | 'needs_input' | 'unblocked' | 'pr';\n title: string;\n body?: string;\n}\n\n/** GET /api/sessions/:id/dev — the worktree's port and dev server. */\nexport interface DevServerState {\n port: number | null;\n /** Something is serving on the port (whoever started it). */\n listening: boolean;\n url: string | null;\n /** The configured dev command for this session, if any. */\n command: string | null;\n repo: string | null;\n /** Started from the dashboard and still alive. */\n running: { pid: number; startedAt: string } | null;\n}\n\n/** GET /api/sessions/:id/ci — what GitHub says about the session's PRs. */\nexport interface SessionCi {\n checkedAt: string;\n /**\n * Who gh is signed in as, when the watch knew it: tells your PRs from others' (the PR tab's \"by @…\"). One\n * repo's (a github.com one's first): each repo's own is `repos[].viewer`; kept for older readers.\n */\n viewer?: string;\n repos: Array<{\n name: string;\n /** The host its PR is on (absent: GitHub). */\n host?: string;\n /** Who you are on its host and server (a GitHub Enterprise login isn't github.com's). Absent: unknown, or an older server. */\n viewer?: string;\n pr: ShipPr | null;\n /** The branch `pr` is for: the one checked out (absent from a check before this). */\n branch?: string;\n /** PRs of the other branches this repo worked on (session-branches.ts), newest first: the stage\n * prefers the newest open one across them (pr-stage.ts `stageRepos`). */\n otherPrs?: Array<{ branch: string; pr: ShipPr }>;\n done: boolean;\n /** Unresolved review threads waiting on the author (open PRs). */\n openThreads?: number;\n /** Those threads (the PR watch's last read). */\n threads?: OpenReviewThread[];\n }>;\n /** The session's PRs in repos it doesn't have (session-prs.ts): shown beside its own, newest first. */\n elsewhere?: ElsewherePr[];\n}\n\n/** An unresolved review thread waiting on you (the PR watch's last read). */\nexport interface OpenReviewThread {\n threadId: string;\n repo: string;\n prNumber: number;\n url: string;\n where: string | null;\n reviewer: string;\n excerpt: string;\n /** Its text is from someone with write access or a trusted review bot (the PR watch's rule); only\n * such threads go to Claude in one \"Ask Claude about all\". Missing (an older server): not known. */\n trusted?: boolean;\n /** The reviewer's whole comment, Markdown (`excerpt` is its start, for notes). Absent from an older server. */\n body?: string;\n /** The code it's on. Absent for a comment on no line, or from an older server. */\n code?: ThreadCode;\n}\n\n/** The code a review thread is on: the end of the diff hunk GitHub keeps with it, and how many of its last lines the comment covers. */\nexport interface ThreadCode {\n /** Unified-diff lines from its `@@ … @@` header to the commented line (GitHub's `diffHunk`). */\n hunk: string;\n /** How many of the hunk's last lines are commented on (1 for a single line). */\n lines: number;\n /** The code has changed since: the comment is on an older version. */\n outdated?: boolean;\n}\n\n/** GET /api/sessions/:id/replies: the threads handed to its Claude and its drafts, and the open threads that have no draft. */\nexport interface RepliesWire {\n replies: PrReply[];\n /** Unresolved threads with no reply drafted: nothing to post yet (ask its Claude, or answer on GitHub). */\n waiting: OpenReviewThread[];\n}\n\n// ---- the rail's pins and sections (rail-layout.ts) -------------------------------\n\n/** GET /api/rail (and every rail write's answer). */\nexport type { RailLayout, RailSection, RailPlace, PlacePatch, SectionOp } from './rail/rail-layout.js';\n\n// ---- the PTY host's heartbeat (host-health.ts) ----------------------------------------\n\nexport type { HostHealth, HostState } from './pty/host-health.js';\n\n// ---- a session's timeline (timeline.ts) ---------------------------------------------\n\nexport type { TimelineEvent, TimelineKind } from './conversations/timeline.js';\n\n/** GET /api/sessions/:id/timeline: newest first. */\nexport interface TimelineWire {\n events: import('./conversations/timeline.js').TimelineEvent[];\n}\n\n// ---- blocked by (session-blocks.ts) -------------------------------------------------\n\n/** One thing a session waits on. */\nexport interface BlockerWire {\n key: string;\n kind: 'session' | 'pr';\n label: string;\n sessionId?: string;\n url?: string;\n state?: 'OPEN' | 'MERGED' | 'CLOSED';\n}\n\n// ---- your notes on a session (session-notes.ts) ------------------------------------\n\n/** GET / PUT /api/sessions/:id/note */\nexport interface NoteWire {\n note: { text: string; updatedAt: string } | null;\n}\n\n// ---- the Code tab: a session's files, read only (code-browse.ts) ------------------\n\n/** One repo of a session: its files as git lists them (tracked, and new ones not ignored). */\nexport interface CodeRepoWire {\n /** Its folder's name (a group's repos are folders of the group's). */\n name: string;\n /** Paths relative to the repo, `/`-separated, sorted. */\n files: string[];\n /** Changed on this branch: committed since it left its base, or not committed. */\n changed: string[];\n /** More files than are listed (MAX_CODE_FILES). */\n truncated: boolean;\n}\n\n/** GET /api/sessions/:id/files */\nexport interface CodeFilesWire {\n /** A group: its repos are folders, beside the group folder's own files (`rootFiles`, its CLAUDE.md…). */\n group: boolean;\n rootFiles: string[];\n repos: CodeRepoWire[];\n}\n\n/** A line with what was searched for in it (code-search.ts). */\nexport interface CodeTextHit {\n repo: string;\n path: string;\n line: number;\n text: string;\n}\n\nexport type CodeSymbolKind = 'class' | 'interface' | 'record' | 'struct' | 'enum' | 'type' | 'function' | 'method' | 'property' | 'const';\n\n/** A declaration: a type or member, where it is. */\nexport interface CodeSymbol {\n name: string;\n kind: CodeSymbolKind;\n repo: string;\n path: string;\n line: number;\n /** Its line, trimmed. */\n text: string;\n}\n\n/** GET /api/sessions/:id/code-search?q= — by name and inside the files. */\nexport interface CodeSearchWire {\n query: string;\n symbols: CodeSymbol[];\n text: CodeTextHit[];\n /** More lines matched than came back. */\n truncated: boolean;\n}\n\n/** GET /api/sessions/:id/file?repo=&path= — one file as it is in the worktree now. */\nexport interface CodeFileWire {\n repo: string;\n path: string;\n size: number;\n /** null with `reason`: not shown as text. */\n text: string | null;\n reason?: 'binary' | 'too-large';\n}\n\n// ---- agent usage (core/usage/) -----------------------------------------------------\n\n/** Tokens, with what was read from the prompt cache apart: `input` is the rest of the prompt. */\nexport interface TokenTotals {\n input: number;\n cached: number;\n output: number;\n}\n\n/** One agent in GET /api/usage: its readings, one `UsageAccount` per account, aged to the answer's time. */\nexport type UsageAgentWire = AgentUsage;\n\n/** GET /api/usage: each agent's plan limits as last read, and the tokens work saw in the sessions' transcripts. */\nexport interface UsageWire {\n agents: UsageAgentWire[];\n tokens: {\n today: TokenTotals;\n /** The last 7 local days, today included. */\n week: TokenTotals;\n byModel: Array<{ model: string; today: TokenTotals; week: TokenTotals }>;\n topSessions: Array<{ id: string; label: string; week: TokenTotals }>;\n };\n at: string;\n}\n\n// ---- time per session (work-time.ts) ---------------------------------------------\n\n/** GET /api/sessions/:id/time: how long its Claude worked (approximate: see work-time.ts). */\nexport interface WorkTimeWire {\n workedMs: number;\n /** Prompts you gave it, in all its transcripts. */\n prompts: number;\n /** The last two weeks, per local day, newest first; days without work left out. */\n byDay: Array<{ day: string; ms: number }>;\n firstAt: string | null;\n lastAt: string | null;\n}\n\n/** GET /api/sessions/:id/worklog: can it write Jira worklogs, to which issue, and what was logged per day (seconds). */\nexport interface WorklogWire {\n configured: boolean;\n issueKey: string | null;\n logged: Record<string, number>;\n}\n\n// ---- fork (fork.ts) ---------------------------------------------------------------\n\n/** POST /api/sessions/:id/fork: the new session. */\nexport interface ForkWire {\n sessionId: string;\n paths: string[];\n /** Its Claude was given a summary of the original's conversation. */\n summarized: boolean;\n /** The worktree exists, but its Claude didn't start (the Terminal tab can). */\n startError?: string;\n}\n\n// ---- add a repo to a session folder (add-repo.ts) ----------------------------------\n\n/** POST /api/sessions/:id/repos: the repo was checked out into the session folder. */\nexport interface AddRepoWire {\n ok: true;\n /** The new checkout: `<session folder>/<repo folder>`. */\n path: string;\n branch: string;\n /** Its branch was made for it (false: the repo's existing branch of that name). */\n created: boolean;\n /** The branch a new one was made from. */\n from?: string;\n /** The session folder's instructions file imports the repo's own now (absent from an older server). */\n imported?: boolean;\n /** What didn't go as it should once the repo was in (the turns, the instructions file, telling its Claude): it stands. */\n warnings?: string[];\n}\n\n// ---- behind main (behind-main.ts) -------------------------------------------------\n\n/** POST /api/sessions/:id/update-from-main: per repo. */\nexport interface UpdateFromMainWire {\n results: Array<\n | { ok: true; repo: string; how: 'rebase' | 'merge' | 'nothing'; base: string; commits: number }\n | {\n ok: false;\n repo: string;\n reason: string;\n conflicts?: boolean;\n base?: string;\n /** Not for a button: hand it to the session's Claude. */ handOff?: boolean;\n }\n >;\n}\n\n// ---- catch me up (catch-up.ts) -------------------------------------------------------\n\n/** GET / POST /api/sessions/:id/catch-up */\nexport interface CatchUpWire {\n catchUp: { text: string; at: string } | null;\n}\n\n// ---- the Jira watch (jira-watch.ts) -----------------------------------------------\n\n/** What the Jira watch did with an issue assigned to you. */\nexport interface JiraDecision {\n key: string;\n summary: string;\n url: string;\n at: string;\n /** baseline: there when it was turned on · started: worktree + Claude · suggested: not sure, start it yourself · skipped: has a session · failed · dismissed: you said no. */\n action: 'baseline' | 'started' | 'suggested' | 'skipped' | 'failed' | 'dismissed';\n target?: string;\n branch?: string;\n sessionId?: string;\n reason: string;\n}\n\n/** GET /api/jira/watch */\nexport interface JiraWatchState {\n settings: { enabled: boolean; since: string | null };\n /** Newest first; baseline entries left out. */\n decisions: JiraDecision[];\n /** The projects an issue can be started in (for \"Start in …\"). */\n targets: string[];\n lastRunAt: string | null;\n nextRunAt: string | null;\n}\n\n/** What work does in the background (core/activity.ts), for the Activity panel. */\nexport type ActivityKind =\n | 'pr-watch'\n | 'reviews'\n | 'pr-list'\n | 'jira'\n | 'idle-sleep'\n | 'cleanup'\n | 'build-folders'\n | 'branches'\n | 'archive'\n | 'conversations'\n | 'server'\n | 'jira-watch'\n | 'stacks'\n | 'blocks'\n | 'groups'\n | 'updates'\n | 'time'\n | 'agents'\n | 'accounts'\n | 'processes';\n\n/** One thing a run decided or noticed (\"archived …\", \"kept … because …\"). */\nexport interface ActivityNote {\n at: string;\n text: string;\n /** action: it did something; warn: something stopped it; info: why it didn't. */\n level: 'info' | 'action' | 'warn';\n /** The session it is about (click to open). */\n sessionId?: string;\n}\n\nexport interface ActivityRun {\n id: number;\n kind: ActivityKind;\n label: string;\n startedAt: string;\n endedAt: string | null;\n status: 'running' | 'done' | 'failed' | 'skipped';\n progress: { done: number; total: number } | null;\n /** One line on how it ended (or why it was skipped / failed). */\n summary: string | null;\n notes: ActivityNote[];\n /** The same skip, repeated this many more times (collapsed). */\n repeats?: number;\n}\n\n/** A job that runs on its own, and when it runs next. */\nexport interface ActivitySchedule {\n kind: ActivityKind;\n label: string;\n everyMs: number;\n nextAt: string | null;\n pausedUntil: string | null;\n pausedWhy: string | null;\n}\n\n/** GET /api/activity */\nexport interface ActivityWire {\n running: ActivityRun[];\n /** Finished runs, newest first. */\n recent: ActivityRun[];\n schedules: ActivitySchedule[];\n /** When each job last finished well (absent from a server before this): a failing job that worked once needs you. */\n lastOk?: Partial<Record<ActivityKind, string>>;\n}\n\n/**\n * A review thread handed to a session's Claude, and the reply it drafted\n * for you (pr-replies.ts). GET /api/sessions/:id/replies.\n */\nexport interface PrReply {\n /** GitHub's thread id (PRRT_…). */\n threadId: string;\n repo: string;\n prNumber: number;\n /** The reviewer comment it answers. */\n url: string;\n where: string | null;\n reviewer: string;\n excerpt: string;\n /** The reviewer's whole comment, Markdown. Absent from a row from before. */\n body?: string;\n /** The code the thread is on. */\n code?: ThreadCode;\n /** sent: Claude has it; draft: Claude wrote a reply; posted: on GitHub (your click, or `work pr post` on your yes). */\n status: 'sent' | 'draft' | 'posted';\n draft: string | null;\n sentAt: string;\n draftedAt?: string;\n postedAt?: string;\n postedUrl?: string;\n resolved?: boolean;\n}\n\n/** GET /api/conversations/search: a session whose kept conversation mentions the query (conversation-store.ts). */\nexport interface ConversationHit {\n sessionId: string;\n target: string;\n branch: string;\n /** Archived now (Restore brings it back). */\n archived: boolean;\n archivedAt: string | null;\n worktreeRemoved: boolean;\n /** When its conversation was last written (the newest transcript). */\n lastAt: string | null;\n snippets: Array<{ role: 'you' | 'claude' | 'summary'; text: string; at: string | null }>;\n}\n\n// ---- driving a session from outside (session-control.ts) ----------------------------\n\n/** How a message reaches a session: typed in now (idle in the PTY host), on its next turn (busy, or a terminal outside work), or by starting its Claude. */\nexport type SendHow = 'typed' | 'next-turn' | 'outside' | 'started';\n\n/** POST /api/sessions/:id/send. */\nexport interface SendWire {\n how: SendHow;\n sentAt: string;\n}\n\n/** POST /api/sessions/:id/agent/start | stop. */\nexport interface AgentControlWire {\n how: 'started' | 'running' | 'stopped' | 'not-running';\n}\n\n/** One account of the agent new sessions run (accounts.ts): a login with its own folder. */\nexport interface AccountWire {\n name: string;\n /** Its config folder. */\n dir: string;\n /** The one new sessions use. */\n isDefault: boolean;\n /** Logged in; null: unknown (the keychain on macOS). */\n loggedIn: boolean | null;\n /** The live sessions on it (\"target · branch\"); absent from an older server. */\n liveSessions?: string[];\n /** The archived sessions on it (their Restore would need it); absent from an older server. */\n archivedSessions?: string[];\n /** Its last usage reading as recorded (windows not aged: the page ages them); null: none yet. Absent from an older server. */\n usage?: UsageAccount | null;\n}\n\n/** GET /api/accounts. */\nexport interface AccountsWire {\n accounts: AccountWire[];\n /** The name new sessions use. */\n default: string;\n /** Accounts can be added, removed and logged in to from the dashboard (the agent's accounts are managed by work, and\n * this server acts: not the dev server). Absent from an older server: the page then only lists them. */\n canManage?: boolean;\n /** Why they can't (the dev server's, or the agent's), when `canManage` is false. */\n manageNote?: string;\n}\n\n/** POST /api/accounts {name, folder?}: the account recorded, its folder made. */\nexport interface AccountAddWire {\n ok: true;\n name: string;\n dir: string;\n}\n\n/** POST /api/accounts/:name/login: its login terminal runs in the PTY host under `id` (`/ws/sessions/<id>/terminal`). */\nexport interface AccountLoginWire {\n ok: true;\n id: string;\n}\n\n/** A refused account change (400 / 409): the reason, and for a removal the sessions on it — `kind: 'archived'` can be\n * forced (`?force=1`), `live` never. */\nexport interface AccountRefusalWire {\n error: string;\n sessions?: string[];\n kind?: 'live' | 'archived';\n}\n\n/** POST /api/sessions/:id/account {to}: `switched` (its Claude restarted on it), `queued` (when its turn ends), `recorded` (not running: its next start). */\nexport interface AccountSwitchWire {\n ok: true;\n outcome: 'switched' | 'queued' | 'recorded';\n /** How many conversation entries went across to the new account's folders. */\n moved?: number;\n}\n\n/** POST /api/accounts/:name/sessions {from?}: every session moved to that account, each with how it went (account-switch-all.ts). */\nexport interface AccountSwitchAllWire {\n ok: true;\n /** What happened, in a line. */\n summary: string;\n sessions: import('./sessions/account-switch-all.js').SwitchAllRow[];\n}\n\n/** GET /api/agents: the agents in the PTY host still running a version from before their tool was updated (agent-restart.ts). */\nexport interface AgentsWire {\n /** When the newest of their tools was installed (ISO): what a \"Later\" is for. Null when none is on PATH. */\n installedAt: string | null;\n outdated: Array<{\n id: string;\n tool: string;\n startedAt: string;\n /** Working or waiting on you: restarts after its turn. */ busy: boolean;\n }>;\n /** Asked to restart, waiting for their turn to end. */\n queued: string[];\n}\n\n/** POST /api/agents/restart {ids} | {outdated: true} | {all: true}: restarted now, after their turn, or not (why). */\nexport interface RestartWire {\n now: string[];\n later: string[];\n failed: Array<{ id: string; error: string }>;\n}\n\n/** GET /api/sessions/:id/screen: its terminal as plain text (null: no terminal in the PTY host). */\nexport interface ScreenWire {\n text: string | null;\n}\n\n/** GET /api/sessions/:id/last-reply: its agent's newest message as written (last-reply.ts); null when there is none. */\nexport interface LastReplyWire {\n text: string | null;\n}\n\n/** POST /api/pty-host/restart: the host was stopped (or none ran) and a new one started; it restores the sessions. */\nexport interface PtyHostRestartWire {\n outcome: 'stopped' | 'not-running' | 'stale-file';\n pid: number;\n}\n\n// ---- Reviews (#64: PR reviews prepared in the background, core/review/) ----\n\n/** Where a PR's prepared review stands. */\nexport type ReviewStatus = 'queued' | 'running' | 'ready' | 'waiting' | 'failed';\n\n/** A file of the PR: its kind of change and why (change-kinds.ts). */\nexport interface ReviewFileWire {\n path: string;\n oldPath?: string;\n status: string;\n added: number;\n deleted: number;\n kind: import('./review/change-kinds.js').ChangeKind;\n why: string;\n by: 'rule' | 'git';\n /**\n * The lines of the new side a review comment can go on (the diff's added and context lines), as [first, last]\n * ranges. Absent on a review prepared before they were recorded: then nothing is checked.\n */\n lines?: Array<[number, number]>;\n /**\n * What changed in it and why it matters, in a few sentences (the AI step's, for a schema, API, logic or wiring file).\n * Absent: none given, a review without the AI step, or one from before.\n */\n summary?: string;\n}\n\n/** A draft that couldn't stay on the review (its line isn't in the diff any more, or never was), kept so its text isn't lost. */\nexport interface ReviewDroppedWire {\n path: string;\n line: number;\n body: string;\n by: 'ai' | 'you';\n why: string;\n}\n\n/** A submit whose outcome isn't known (the host's call timed out): what may have gone out. Nothing is sent again until you say. */\nexport interface ReviewInDoubtWire {\n at: string;\n event: ReviewEvent;\n /** The drafts that may have gone out, with the text sent. */\n drafts: Array<{ id: string; body: string }>;\n /** The summary that may have gone out; null when it wasn't part of it. */\n summary: string | null;\n error: string;\n /**\n * The steps after the doubtful one weren't tried (Azure DevOps: the comments after it, the summary, the vote): if it\n * went out, the review went out only in part. Absent: the doubtful call was the whole rest of it.\n */\n partial?: boolean;\n}\n\n/**\n * A submit under way (the durable claim in the `pr_reviews` row): a second submit — another window, the dev server on\n * the same state.db — is refused while it stands. One left by a work web that stopped is taken as in doubt.\n */\nexport interface ReviewSubmittingWire {\n at: string;\n /** The process submitting it. */\n pid: number;\n event: ReviewEvent;\n /** The drafts it sends, with the text sent. */\n drafts: Array<{ id: string; body: string }>;\n /** The summary it sends; null when none. */\n summary: string | null;\n /**\n * Left over by a work web that stopped while submitting (said on read, never stored): it may have gone out — shown\n * as in doubt, and saying whether it went settles it (`POST …/in-doubt`).\n */\n stale?: true;\n}\n\n/** Fix it myself under way (the durable claim in the `pr_reviews` row): its drafts are spoken for until it ends. */\nexport interface ReviewFixingWire {\n at: string;\n /** The drafts it takes off. */\n drafts: string[];\n}\n\n/** A draft review comment — the AI step's note (`by: 'ai'`) or yours — on a line of the PR's new side; it goes out only in a review you submit. */\nexport interface ReviewDraftWire {\n id: string;\n path: string;\n line: number;\n body: string;\n state: 'draft' | 'posted';\n url?: string;\n /** Who wrote it: the AI step, or you (added on the diff). Absent: the AI step (from before). */\n by?: 'ai' | 'you';\n}\n\n/** One comment of a PR's existing discussion on its host: someone else's words (or yours), read only. */\nexport interface PrDiscussionCommentWire {\n author: string;\n /** How the host relates them to the repo (GitHub's authorAssociation: OWNER, MEMBER, CONTRIBUTOR…); absent: it doesn't say. */\n association?: string;\n /** Markdown, as written (cut at `MAX_DISCUSSION_BODY`). */\n body: string;\n /** When (ISO); '' when the host doesn't say. */\n at: string;\n /** Its link on the host. */\n url?: string;\n}\n\n/** A review thread already on the PR (the host's), on a line of a file — read only here. */\nexport interface PrDiscussionThreadWire {\n /** The host's id. */\n id: string;\n path: string | null;\n /** The line it's on now (null: outdated, its line gone, or a thread on the whole file). */\n line: number | null;\n /** The line it was written on (an outdated one's place, said beside it). */\n originalLine?: number | null;\n /** The side of the diff: the new code (right) or the old (left). */\n side: 'right' | 'left';\n /** The code moved on under it since: its line may be gone. */\n outdated: boolean;\n resolved: boolean;\n /** Its first comment's link on the host. */\n url?: string;\n comments: PrDiscussionCommentWire[];\n}\n\n/** A review someone submitted on the PR: their verdict. */\nexport interface PrDiscussionReviewWire extends PrDiscussionCommentWire {\n state: 'approved' | 'changes-requested' | 'commented' | 'dismissed';\n}\n\n/**\n * The PR's discussion as its host has it (#64): the review threads on its lines, the submitted reviews, the\n * conversation comments. Read when the review is prepared, refreshed when the PR moves (`updatedAt`) or on open;\n * shown read only, given to the AI step as data. work never answers or resolves anything here.\n */\nexport interface PrDiscussionWire {\n /** When it was read (ISO). */\n at: string;\n /** The PR's `updatedAt` on the host when it was read (absent: the host's list doesn't say — Azure DevOps). */\n updatedAt?: string;\n threads: PrDiscussionThreadWire[];\n reviews: PrDiscussionReviewWire[];\n comments: PrDiscussionCommentWire[];\n /** The host's lists stopped at their limits: there is more on the host. */\n more?: true;\n}\n\n/** How a submitted review is cast. */\nexport type ReviewEvent = 'comment' | 'approve' | 'request-changes';\n\n/** POST /api/reviews/:repo/:number/submit — the drafts to send (each with its body as you left it), the verdict, a summary. */\nexport interface ReviewSubmitInput {\n event: ReviewEvent;\n body: string;\n drafts: Array<{ id: string; body: string }>;\n}\n\n/** GET /api/reviews/:repo/:number — a PR's review, as prepared for its head. */\nexport interface PrReviewWire {\n repo: string;\n number: number;\n title: string;\n url: string;\n author: string;\n branch: string;\n base: string;\n headSha: string;\n /**\n * The head the host's PR list named when this was written: what a sweep compares (a fetch can land on a newer\n * push, and an Azure DevOps merge ref is another commit). Absent: `headSha`.\n */\n listedHead?: string;\n /** The host it's on (absent: GitHub). */\n host?: string;\n status: ReviewStatus;\n /** Why it waits: today's cap (picked up when the day allows), or its size (only your click). */\n held?: 'cap' | 'size';\n /** Why it waits, failed, or was prepared without the AI step. */\n why: string | null;\n /** When the status last changed (ISO). */\n at: string;\n size: { files: number; added: number; deleted: number };\n files: ReviewFileWire[];\n /** Files left out of the review altogether (`ignoredInReview`: designer files) — never diffed or read, only named. */\n ignored?: Array<{ path: string; why: string; added: number; deleted: number }>;\n tests: {\n list: import('./review/test-breakdown.js').FoundTest[];\n counts: Record<import('./review/test-breakdown.js').TestChange, number>;\n /** Production files (logic, schema, API) no test of the PR touches. */\n gaps: string[];\n /** A test file → the production files it covers. */\n covers: Record<string, string[]>;\n unitOnlyForSchema: boolean;\n };\n /** What the PR does in two or three sentences (the AI step's; absent: none ran, or a review from before). */\n summary?: string;\n /** What the AI step advises doing with the change as it is, and why (absent: none ran, or a review from before). Advice: you decide. */\n recommendation?: import('./review/review-plan.js').Recommendation;\n /** The flows the change adds, changes or removes, each as its steps (the AI step's; absent: none named, or a review from before). */\n flows?: import('./review/review-plan.js').Flow[];\n stories: import('./review/review-plan.js').Story[];\n /** Logic files no story names (never hidden). */\n unstoried: string[];\n drafts: ReviewDraftWire[];\n /** A test's name → what it actually asserts (the AI step's word). */\n asserts: Record<string, string>;\n /** The AI step: ran, none (no agent, or too big), or failed (stories by folder then). */\n aiStep: 'done' | 'none' | 'failed';\n /** The commit its diff starts from (the merge-base with its base branch), for the diff view. */\n mergeBase?: string;\n /** When it was prepared (counts against the day's cap). */\n preparedAt?: string;\n /**\n * Your submitted review: when, how, and its link. `partial`: it stopped part way (some comments went out, the rest\n * are still drafts); `summary`: the summary that went out, not sent again.\n */\n submitted?: { at: string; event: ReviewEvent; url?: string; partial?: boolean; summary?: string };\n /** Drafts that couldn't stay (off the diff's lines, or on a file the new push no longer changes): their text, and why. */\n dropped?: ReviewDroppedWire[];\n /** A submit that may or may not have gone out: you say which (POST …/in-doubt) before anything is sent again. */\n inDoubt?: ReviewInDoubtWire;\n /** A submit under way: nothing else is sent until it ends. */\n submitting?: ReviewSubmittingWire;\n /**\n * The highest number a draft id (`d<n>`, `u<n>`) of this review has had: ids are never handed out twice, so an id a\n * submit in doubt names is never a newer draft's. Absent: the highest id it holds.\n */\n lastDraft?: number;\n /** The PR comes from a fork: its branch isn't on origin, so Fix it myself can't open a session on it. */\n fork?: true;\n /** Drafts you took off the review to fix yourself (Fix it myself), each batch with the session it went to. */\n fixingMyself?: ReviewFixWire[];\n /** Fix it myself making its session: a submit, and a second Fix it myself, wait (stale after `FIX_CLAIM_STALE_MS`). */\n fixing?: ReviewFixingWire;\n /** What's already discussed on the PR (its host's threads, reviews and comments); absent: not read yet, or from before. */\n discussion?: PrDiscussionWire;\n}\n\n/** Draft comments you took off a review to fix yourself, in a session on the PR's branch. */\nexport interface ReviewFixWire {\n /** When (ISO). */\n at: string;\n /** The session they went to (made for them, or one already on the branch). */\n sessionId: string;\n /** The PR's branch the session is on. */\n branch: string;\n comments: Array<{ path: string; line: number; body: string; by?: 'ai' | 'you' }>;\n}\n\n/** POST /api/reviews/:repo/:number/fix-myself — the drafts (ids) to fix yourself instead of posting them. */\nexport interface ReviewFixInput {\n drafts: string[];\n}\n\n/** What Fix it myself did: the session the comments went to (`created`: made for them), and the review now. */\nexport interface ReviewFixResultWire {\n sessionId: string;\n created: boolean;\n review: PrReviewWire;\n /** Something that went wrong after the session had the instruction (a draft that couldn't be taken off, a start that fell back to a note). */\n warnings?: string[];\n}\n\n/** One row of the Reviews list. */\nexport interface ReviewSummaryWire {\n repo: string;\n number: number;\n title: string;\n url: string;\n author: string;\n host?: string;\n status: ReviewStatus;\n why: string | null;\n at: string;\n size: { files: number; added: number; deleted: number };\n stories: number;\n /** Flags across its stories (no tests, a public contract changed, …). */\n flags: number;\n /** Production changes no test touches. */\n gaps: number;\n}\n\n/** GET /api/reviews */\nexport interface ReviewsWire {\n reviews: ReviewSummaryWire[];\n /** Reviews prepared today, against the day's cap (null: none). */\n today: number;\n maxPerDay: number | null;\n}\n\n/** A project's setting for automatic reviews: every open PR, only those asking you, or none. */\nexport type ReviewMode = 'all' | 'asked' | 'off';\n\n/** GET /api/reviews/settings — each repo and group, its automatic-review mode, and the limits. PUT {project, mode} sets one. */\nexport interface ReviewSettingsWire {\n projects: Array<{ name: string; kind: 'repo' | 'group'; mode: ReviewMode; from: 'repo' | 'group' | 'default'; group?: string }>;\n /** null: no daily cap. */\n maxPerDay: number | null;\n maxLines: number;\n}\n\n// ---- settings (core/settings) ---------------------------------------------\n\n/** GET /api/settings: each setting of the Settings page written in config.json, by its path (settings-schema.ts\n * `SETTINGS`; the rest are their defaults). Nothing else of config.json is in it. */\nexport interface SettingsWire {\n values: Record<string, unknown>;\n /** Where config.json is, for what isn't on the page. */\n configPath: string;\n}\n\n/** GET /api/repos/:alias/settings: a repo's settings and what is known of it. */\nexport interface RepoSettingsWire {\n alias: string;\n path: string;\n origin: string | null;\n /** Its host's name (\"GitHub\", \"Azure DevOps\"); null when it can't be told. */\n host: string | null;\n requiredChecks: string[] | null;\n devCommand: string | null;\n reviews: 'all' | 'asked' | 'off' | null;\n}\n\n/** One process of a session: its agent, something the agent started, or something running from its folder. */\nexport interface SessionProcessWire {\n pid: number;\n /** Its name and command, the session's folder shortened to \"…\". */\n what: string;\n /** The memory it holds for itself; null when the system didn't say. */\n memBytes: number | null;\n /** When it started (ms); null when the system didn't say. Sent back with a stop, to tell it from a reused pid. */\n startedAt: number | null;\n /** The session's agent itself (stopped from the session, never here). */\n agent?: true;\n /** Not the agent, and running for over a day: likely a forgotten dev server or watcher. */\n leftover?: true;\n}\n\n/** GET /api/sessions/:id/processes — what a session holds in memory right now, most first. */\nexport interface SessionProcessesWire {\n /** When it was looked at (ms). */\n at: number;\n totalBytes: number;\n leftovers: number;\n processes: SessionProcessWire[];\n}\n\n/**\n * GET /api/sessions/:id/review — a session's own changes read as a review, before there is a pull request\n * (local-review.ts). `review` is a `PrReviewWire` with no number, link or host: nothing of it goes anywhere.\n */\nexport interface SessionReviewWire {\n /** none: never prepared (or work web restarted since: they are kept in memory). */\n status: 'none' | 'running' | 'ready' | 'failed';\n /** The one repo it is of; null: all the session's repos with changes, in one review (paths start with the repo's name). */\n repo: string | null;\n /** The session's repos that had changes when it was prepared. */\n repos: string[];\n /** When the status last changed (ISO). */\n at?: string;\n /** The last one prepared — still there while another is being prepared. */\n review?: PrReviewWire;\n error?: string;\n}\n","import { ARCHIVED_BY, type ArchivedBy } from '../api-types.js';\nimport fs from 'node:fs';\nimport { isSavedUncommitted, type SavedUncommitted } from './archive-uncommitted.js';\nimport { logSwallowed } from '../platform/best-effort.js';\nimport { clearSnooze } from '../rail/snooze-store.js';\nimport { whileArchiving } from './archiving.js';\nimport path from 'node:path';\nimport zlib from 'node:zlib';\nimport { getConfigDir } from '../platform/config.js';\nimport { promptsSince } from '../conversations/digest.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { readJsonlTail } from '../conversations/jsonl.js';\nimport { agentOf } from '../agents/index.js';\nimport type { ConversationEntry } from '../agents/types.js';\n\n/**\n * Archiving a session: out of the way, its disk space back, its history kept.\n *\n * 0. unless forced, nothing is waiting in it: replies Claude drafted for\n * you to post, notes not yet delivered to its Claude, a Claude mid-turn\n * or waiting for your answer (`waiting`);\n * 1. its Claude and its dev server are stopped;\n * 2. its conversation (every transcript) is copied to\n * ~/.work/archive/<id>/transcripts — Claude Code deletes old transcripts\n * by itself, and this is what \"recall what we did\" reads;\n * 3. a summary is written next to it: your prompts, its PRs, how it ended,\n * the branch tips — and, in the background, a few sentences on what was\n * done and why (`writeArchiveSummary`, an internal `claude -p`);\n * 4. the worktree is removed — only when cleanup's own check says nothing\n * would be lost (merged, clean) — and then its checkpoint refs go, and a\n * branch already merged into the main branch is deleted (its tip is\n * recorded; Restore recreates it). Otherwise the worktree stays, the\n * reason is recorded, and its build output (node_modules, bin/obj, …)\n * is cleared to give the disk back anyway;\n * 5. the session is marked archived.\n *\n * Restoring (`work tree` into it, or Restore in the dashboard) recreates the\n * branch if archiving deleted it, the worktree from the branch, and puts the\n * transcripts back where Claude looks for them, so it continues the\n * conversation. Old archives are compressed (archive-retention.ts).\n */\n\nexport interface ArchivedPr {\n repo: string;\n number: number;\n url: string;\n state: string;\n}\n\n/** A repo's git-ignored files archiving copied (archive-ignored.ts). */\nexport interface SavedIgnored {\n files: number;\n bytes: number;\n /** Left out: over a cap. */\n skipped: number;\n /** It stopped looking at MAX_IGNORED_FILES files: more were there. */\n partial?: true;\n /** Put back by a Restore (then not again). */\n restoredAt?: string;\n /** A Restore that couldn't put them back: why (not tried again). */\n restoreError?: string;\n}\n\nexport interface ArchiveRecord {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n paths: string[];\n archivedAt: string;\n /** Who archived it (ArchiveOptions.by); none in an archive from before it was recorded. */\n archivedBy?: ArchivedBy;\n /** The worktree folder(s) were removed (false: kept, see keptBecause). */\n worktreeRemoved: boolean;\n keptBecause: string | null;\n /** Removed only in part: git stopped at a file in use, leaving these folders with no git in\n * them. The save is kept; Restore makes the worktree again and copies them back (leftover.ts). */\n leftovers?: string[];\n /** Transcript file names under transcripts/, by the folder they belong to\n * (on disk `<file>` or, once compressed, `<file>.gz`). */\n transcripts: Array<{ file: string; projectDir: string }>;\n summary: {\n prompts: Array<{ ts: string; text: string }>;\n promptCount: number;\n lastSummary: string | null;\n prs: ArchivedPr[];\n jiraKey: string | null;\n /** What was done and why, in a few sentences (written after archiving). */\n written?: string | null;\n };\n /** Each repo's branch tip when archived (repo alias → commit): of the branch checked out (`heads`), else the session's. */\n tips?: Record<string, string>;\n /** Repos checked out on another branch than the session's when archived (alias → branch): Restore brings that branch back. */\n heads?: Record<string, string>;\n /** Repos whose local branch was deleted (merged): Restore recreates it at its tip. */\n branchesDeleted?: string[];\n /** Build output cleared from a kept worktree. */\n buildFolders?: { folders: number; bytes: number };\n /** Uncommitted work saved because the worktree was removed (repo alias → where it is): Restore puts it back (archive-uncommitted.ts). */\n uncommitted?: Record<string, SavedUncommitted>;\n /** Git-ignored files that aren't build output (local settings, the editor's state), copied because the\n * worktree was removed (repo alias → how many): Restore puts them back (archive-ignored.ts). */\n ignored?: Record<string, SavedIgnored>;\n /** What was still waiting in it when archived (a merged session isn't held up by these): they stay in\n * state.db with the session, so Restore brings them back — drafts in the header, notes delivered on\n * its next turn. Listed here so the archive says what it holds. */\n kept?: ArchiveKept;\n /** Saved work an earlier Restore couldn't put back, carried over when archived again (still in its ref and patch). */\n unrestored?: SavedUncommitted[];\n /** When the copied git-ignored files were deleted for retention (ISO): they can hold secrets. */\n ignoredDroppedAt?: string;\n /** When the transcripts were compressed / deleted for retention (ISO). */\n compressedAt?: string;\n transcriptsDroppedAt?: string;\n}\n\n/**\n * It was archived because its PR merged (the PR watch, or Ship's merge) — so a Restore is you saying you still want\n * it, and it is kept after its merge from then on (`keepAfterMerge`), not archived again a day later.\n */\nexport function archivedForMerge(id: string): boolean {\n const by = archivedByOf(readArchive(id) ?? {});\n return by === 'pr-merged' || by === 'shipped';\n}\n\n/** Who archived it, as stored (archive.json is read back as JSON): only a value work writes. */\nexport function archivedByOf(rec: { archivedBy?: unknown }): ArchivedBy | undefined {\n return ARCHIVED_BY.find((b) => b === rec.archivedBy);\n}\n\nexport interface ArchiveKept {\n replyDrafts: Array<{ threadId: string; url: string; reviewer: string; draft: string }>;\n notes: Array<{ id: string; text: string }>;\n /** Its Claude was waiting for your answer: what it asked. */\n askingYou?: string;\n}\n\nexport interface ArchiveDeps {\n stopClaude: (id: string) => Promise<void>;\n /** Would removing its worktree lose anything? (cleanup's verdict). With\n * `uncommittedSaved`, uncommitted files don't count: they were saved. */\n removable: (s: WorktreeSession, opts?: { uncommittedSaved?: boolean }) => Promise<{ ok: boolean; reason: string }>;\n /** Save each repo's uncommitted work (archive-uncommitted.ts) before the worktree may go. */\n saveUncommitted?: (\n s: WorktreeSession,\n archiveDir: string,\n stamp: number,\n ) => Promise<{ saved: Record<string, SavedUncommitted>; error: string | null }>;\n /** Drop saves that weren't needed (the worktree stayed). */\n dropSaved?: (s: WorktreeSession, saved: Record<string, SavedUncommitted>, archiveDir: string) => Promise<void>;\n /** Copy each repo's git-ignored files that aren't build output into `<archiveDir>/ignored/<repo>` (archive-ignored.ts). */\n saveIgnored?: (s: WorktreeSession, archiveDir: string) => Promise<Record<string, SavedIgnored>>;\n removeWorktree: (s: WorktreeSession) => Promise<boolean>;\n /** After a removal git refused: the session's folders left with no git in them (it stopped halfway). */\n halfRemoved?: (s: WorktreeSession) => string[];\n setArchived: (s: WorktreeSession) => Promise<boolean>;\n /** The session's transcript files. */\n transcripts: (s: WorktreeSession) => string[];\n prs?: (id: string) => ArchivedPr[];\n lastSummary?: (id: string) => string | null;\n /** What archiving now would leave behind unfinished (empty: nothing). */\n waiting?: (id: string) => string[];\n /** Its Claude is in the middle of a turn (stopping it would cut the turn off). */\n working?: (id: string) => boolean;\n /** What waits in it, to list in the record (drafts, notes, a question). */\n kept?: (id: string) => ArchiveKept;\n stopDev?: (id: string) => void;\n /** Stop what still runs from its folders (a dev server or watcher its Claude started in the background,\n * running-from.ts) and say what: otherwise it holds files, and the worktree is removed only in part. */\n stopRunningFrom?: (s: WorktreeSession) => Promise<string[]>;\n /** What runs from its folders, by name, stopping nothing (an unattended archive keeps the worktree then).\n * Rejects when it can't tell, which keeps it too. */\n runningFrom?: (s: WorktreeSession) => Promise<string[]>;\n /** Repos checked out on another branch than the session's (alias → branch). */\n heads?: (s: WorktreeSession) => Record<string, string>;\n /** Each repo's branch tip (alias → commit): of `heads[alias]`, else the session's branch. */\n tips?: (s: WorktreeSession, heads: Record<string, string>) => Promise<Record<string, string>>;\n /** A kept worktree: clear its git-ignored build output. */\n clearBuildFolders?: (s: WorktreeSession) => Promise<{ folders: number; bytes: number }>;\n /** A removed worktree: its checkpoint refs, and merged local branches — the session's and the one checked out (returns the repos whose checked-out branch went). */\n tidy?: (s: WorktreeSession, heads: Record<string, string>) => Promise<string[]>;\n /** A few sentences on what was done (background; null: none). */\n summarize?: (rec: ArchiveRecord) => Promise<string | null>;\n archiveRoot?: string;\n now?: () => number;\n}\n\nexport interface ArchiveOutcome {\n ok: boolean;\n worktreeRemoved: boolean;\n keptBecause: string | null;\n transcripts: number;\n message: string;\n /** Not archived: these were waiting (archive with force to go ahead). */\n blocked?: string[];\n /** What waited in it and was kept with it (\"2 reply drafts, 1 note for its Claude\"). */\n kept?: string;\n}\n\n/** Most prompts kept in the summary: the first ones (what it was about) and the latest. */\nconst SUMMARY_PROMPTS = 40;\n\nexport const archiveRoot = (): string => path.join(getConfigDir(), 'archive');\nexport const archiveDirFor = (id: string, root = archiveRoot()): string => path.join(root, id);\n\n/** Told after each archive that went through (work web: stacked sessions move onto main). */\nconst afterArchive = new Set<(s: WorktreeSession) => void | Promise<unknown>>();\n\n/** Listen for archives (every path: the button, Ship, the PR watch, cleanup); returns the unsubscribe. A listener may be async: its failure is logged, never the archive's. */\nexport function onArchived(listener: (s: WorktreeSession) => void | Promise<unknown>): () => void {\n afterArchive.add(listener);\n return () => afterArchive.delete(listener);\n}\n\n/**\n * `merged`: the session's PR merged (the PR watch, Ship). That decides it:\n * reply drafts, undelivered notes and a question for you don't hold it up —\n * they stay with the session and are listed in the record — and only a\n * Claude in the middle of a turn does (the caller tries again later).\n */\nexport interface ArchiveOptions {\n /** Who asked: kept in the record, and shown with the archived session. */\n by?: ArchivedBy;\n force?: boolean;\n merged?: boolean;\n /** No one asked (the PR watch, a merged PR): nothing running from the worktree is stopped — it keeps it. */\n unattended?: boolean;\n}\n\nexport async function archiveSession(s: WorktreeSession, deps: ArchiveDeps, opts: ArchiveOptions = {}): Promise<ArchiveOutcome> {\n // Nothing starts its Claude again while this runs (archiving.ts).\n const out = await whileArchiving(sessionIdFor(s), () => archiveSteps(s, deps, opts));\n if (out.ok)\n for (const l of afterArchive) {\n // Sync throws and async rejections alike: a listener's trouble isn't the archive's.\n void Promise.resolve()\n .then(() => l(s))\n .catch((err) => logSwallowed('after archiving', err));\n }\n return out;\n}\n\nasync function archiveSteps(s: WorktreeSession, deps: ArchiveDeps, opts: ArchiveOptions): Promise<ArchiveOutcome> {\n const id = sessionIdFor(s);\n const root = deps.archiveRoot ?? archiveRoot();\n const dir = archiveDirFor(id, root);\n const now = deps.now ?? Date.now;\n\n // 0. Work still waiting in it would vanish from view with it.\n const waiting = opts.force\n ? []\n : opts.merged\n ? deps.working?.(id)\n ? ['its Claude is in the middle of a turn']\n : []\n : (deps.waiting?.(id) ?? []);\n if (waiting.length) {\n return {\n ok: false,\n worktreeRemoved: false,\n keptBecause: null,\n transcripts: 0,\n blocked: waiting,\n message: `Not archived: ${waiting.join('; ')}.`,\n };\n }\n\n await deps.stopClaude(id);\n try {\n deps.stopDev?.(id);\n } catch {\n /* not running */\n }\n // Which branch each repo is on: Claude may have switched from the session's.\n let heads: Record<string, string> = {};\n try {\n heads = deps.heads?.(s) ?? {};\n } catch {\n /* unreadable: the session's branch, as before */\n }\n const tips = (await deps.tips?.(s, heads).catch(() => ({}))) ?? {};\n\n // 2. The conversation. Copied before anything is removed; a copy that fails\n // stops the archive (nothing removed, nothing marked).\n const copied: ArchiveRecord['transcripts'] = [];\n // Read as its agent writes them (none when work can't read that agent's conversations).\n const toEntries = agentOf(s).conversation?.entries ?? (() => []);\n const entries: ConversationEntry[][] = [];\n try {\n fs.mkdirSync(path.join(dir, 'transcripts'), { recursive: true });\n for (const file of deps.transcripts(s)) {\n const name = path.basename(file);\n fs.copyFileSync(file, path.join(dir, 'transcripts', name));\n copied.push({ file: name, projectDir: path.basename(path.dirname(file)) });\n entries.push(toEntries(readJsonlTail(file, 64 * 1024 * 1024)));\n }\n } catch (err) {\n return {\n ok: false,\n worktreeRemoved: false,\n keptBecause: null,\n transcripts: copied.length,\n message: `Not archived: could not copy its conversation (${(err as Error).message}).`,\n };\n }\n\n // 3. Uncommitted work is saved (a snapshot commit + a patch), so it\n // doesn't keep the worktree: Restore puts it back. A save that fails\n // keeps the worktree, as before.\n const saving = deps.saveUncommitted\n ? await deps.saveUncommitted(s, dir, now()).catch((err: Error) => ({ saved: {}, error: err.message }))\n : { saved: {}, error: null };\n let saved: Record<string, SavedUncommitted> = saving.error ? {} : saving.saved;\n if (saving.error) await deps.dropSaved?.(s, saving.saved, dir).catch(() => {});\n\n // 4. The folder goes only if nothing would be lost.\n const verdict = await deps.removable(s, { uncommittedSaved: !saving.error });\n let worktreeRemoved = false;\n let keptBecause: string | null = null;\n let leftovers: string[] = [];\n let ignored: Record<string, SavedIgnored> = {};\n const ignoredDir = path.join(dir, 'ignored');\n let stopped: string[] = [];\n // Unasked (the PR watch): what runs from the folder is yours — it keeps the worktree rather than stop it, and\n // stops nothing (not even what started after this look). Processes it can't read keep it too: no guess.\n const runningThere =\n verdict.ok && opts.unattended\n ? ((await deps.runningFrom?.(s).catch(() => [\"(couldn't tell: the process list didn't answer)\"])) ?? [])\n : [];\n if (verdict.ok && runningThere.length === 0) {\n // Only for a folder that goes (never a repo's own checkout, never a kept worktree: what runs there is\n // yours), and only when you asked: what still runs from it holds its files, and git would remove it only in part.\n if (!opts.unattended) stopped = (await deps.stopRunningFrom?.(s).catch(() => [])) ?? [];\n // Local settings and the editor's state go with the folder: kept, so Restore brings them back.\n fs.rmSync(ignoredDir, { recursive: true, force: true });\n ignored = deps.saveIgnored ? await deps.saveIgnored(s, dir).catch(() => ({})) : {};\n worktreeRemoved = await deps.removeWorktree(s);\n // git deletes the files first and stops at one in use (Visual Studio's): the folder\n // that's left is no worktree any more. That's removed — and its save is the copy.\n leftovers = worktreeRemoved ? [] : (deps.halfRemoved?.(s) ?? []);\n // Removed only when every folder is gone or half-removed: a repo of a group whose\n // removal failed outright is still a worktree, and the session keeps it.\n if (leftovers.length && s.paths.every((p) => leftovers.includes(p) || !fs.existsSync(p))) worktreeRemoved = true;\n else if (!worktreeRemoved)\n keptBecause = leftovers.length\n ? `git removed ${leftovers.join(', ')} only in part (a file in use) and kept the rest`\n : 'git refused to remove the worktree';\n } else {\n keptBecause = runningThere.length\n ? `still running from it: ${runningThere.join(', ')}`\n : saving.error && !verdict.reason.includes(saving.error)\n ? `${verdict.reason} (${saving.error})`\n : verdict.reason;\n }\n // Kept: the changes are still in it, so the saves aren't needed.\n // (Not when part of it is gone: the saves are the only copy of that.)\n if (!worktreeRemoved && !leftovers.length && Object.keys(saved).length) {\n await deps.dropSaved?.(s, saved, dir).catch(() => {});\n saved = {};\n }\n if (!worktreeRemoved && !leftovers.length && Object.keys(ignored).length) {\n fs.rmSync(ignoredDir, { recursive: true, force: true });\n ignored = {};\n }\n // What waits in it (kept with the session in state.db), listed in the record.\n const kept = deps.kept?.(id);\n // Work an earlier Restore couldn't put back stays known (its ref and patch are still there).\n const earlier = readArchive(id, root);\n const unrestored = [...(earlier?.unrestored ?? []), ...Object.values(earlier?.uncommitted ?? {}).filter((u) => !u.restoredAt)];\n let branchesDeleted: string[] = [];\n let buildFolders: ArchiveRecord['buildFolders'];\n if (worktreeRemoved) branchesDeleted = (await deps.tidy?.(s, heads).catch(() => [])) ?? [];\n // Not under what still runs from it (a dev server's node_modules): kept so as to leave it alone.\n else if (keptBecause !== \"it is the repo's own checkout\" && runningThere.length === 0 && deps.clearBuildFolders) {\n buildFolders = await deps.clearBuildFolders(s).catch(() => undefined);\n }\n\n const all = promptsSince(entries, 0);\n const prompts = all.length > SUMMARY_PROMPTS ? [...all.slice(0, SUMMARY_PROMPTS / 2), ...all.slice(-SUMMARY_PROMPTS / 2)] : all;\n const record: ArchiveRecord = {\n sessionId: id,\n target: s.target,\n branch: s.branch,\n isGroup: s.isGroup,\n paths: s.paths,\n archivedAt: new Date(now()).toISOString(),\n ...(opts.by ? { archivedBy: opts.by } : {}),\n worktreeRemoved,\n keptBecause,\n ...(leftovers.length ? { leftovers } : {}),\n transcripts: copied,\n summary: {\n prompts,\n promptCount: all.length,\n lastSummary: deps.lastSummary?.(id) ?? null,\n prs: deps.prs?.(id) ?? [],\n jiraKey: s.jiraKey ?? null,\n },\n ...(Object.keys(tips).length ? { tips } : {}),\n ...(Object.keys(heads).length ? { heads } : {}),\n ...(branchesDeleted.length ? { branchesDeleted } : {}),\n ...(buildFolders && buildFolders.folders ? { buildFolders } : {}),\n ...(Object.keys(saved).length ? { uncommitted: saved } : {}),\n ...(Object.keys(ignored).length ? { ignored } : {}),\n ...(unrestored.length ? { unrestored } : {}),\n ...(keptAny(kept) ? { kept } : {}),\n };\n fs.writeFileSync(path.join(dir, 'archive.json'), JSON.stringify(record, null, 2));\n\n await deps.setArchived(s);\n // A snooze doesn't outlive the archive: Restore brings it back as it is now.\n try {\n clearSnooze(id);\n } catch {\n /* best effort */\n }\n if (deps.summarize) void writeArchiveSummary(id, deps.summarize, root).catch(() => {});\n return {\n ok: true,\n worktreeRemoved,\n keptBecause,\n transcripts: copied.length,\n message:\n (worktreeRemoved\n ? `Archived; worktree removed, conversation kept${savedFiles(saved) ? `, ${savedFiles(saved)} uncommitted file${savedFiles(saved) === 1 ? '' : 's'} saved for Restore` : ''}${leftovers.length ? `; git stopped at a file in use, so part of the folder is left (${leftovers.join(', ')}): close what holds it and delete it, or Restore puts it back` : ''}`\n : `Archived; worktree kept (${keptBecause})`) +\n (keptList(kept) ? `; kept for Restore: ${keptList(kept)}` : '') +\n (stopped.length ? `; stopped what still ran from it: ${stopped.join(', ')}` : ''),\n ...(keptList(kept) ? { kept: keptList(kept) } : {}),\n };\n}\n\nconst savedFiles = (saved: Record<string, SavedUncommitted>): number => Object.values(saved).reduce((n, u) => n + u.files, 0);\nconst keptAny = (k: ArchiveKept | undefined): k is ArchiveKept => !!k && (k.replyDrafts.length > 0 || k.notes.length > 0 || !!k.askingYou);\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;\n/** \"2 reply drafts, 1 note for its Claude, its question to you\" (empty: nothing kept). */\nexport function keptList(k: ArchiveKept | undefined): string {\n if (!keptAny(k)) return '';\n return [\n ...(k.replyDrafts.length ? [plural(k.replyDrafts.length, 'reply draft', 'reply drafts')] : []),\n ...(k.notes.length ? [plural(k.notes.length, 'note for its Claude', 'notes for its Claude')] : []),\n ...(k.askingYou ? ['its question to you'] : []),\n ].join(', ');\n}\n\n/** Ask for the written summary and store it in the record (background, after archiving). */\nexport async function writeArchiveSummary(\n id: string,\n summarize: (rec: ArchiveRecord) => Promise<string | null>,\n root = archiveRoot(),\n): Promise<string | null> {\n const rec = readArchive(id, root);\n if (!rec || rec.summary.written) return rec?.summary.written ?? null;\n const text = (await summarize(rec))?.trim() || null;\n if (!text) return null;\n const now = readArchive(id, root); // re-read: it may have changed meanwhile\n if (!now) return null;\n now.summary.written = text;\n writeArchiveRecord(now, root);\n return text;\n}\n\nexport function writeArchiveRecord(rec: ArchiveRecord, root = archiveRoot()): void {\n const file = path.join(archiveDirFor(rec.sessionId, root), 'archive.json');\n const tmp = `${file}.tmp-${process.pid}`;\n fs.writeFileSync(tmp, JSON.stringify(rec, null, 2));\n fs.renameSync(tmp, file);\n}\n\n/** An archived transcript's text, compressed or not (null: gone). */\nexport function readArchivedTranscript(id: string, file: string, root = archiveRoot()): string | null {\n const plain = path.join(archiveDirFor(id, root), 'transcripts', file);\n try {\n return fs.readFileSync(plain, 'utf8');\n } catch {\n /* compressed, or gone */\n }\n try {\n return zlib.gunzipSync(fs.readFileSync(`${plain}.gz`)).toString('utf8');\n } catch {\n return null;\n }\n}\n\n/** The archive record, or null (never archived with a copy, or unreadable). */\nexport function readArchive(id: string, root = archiveRoot()): ArchiveRecord | null {\n try {\n const raw: unknown = JSON.parse(fs.readFileSync(path.join(archiveDirFor(id, root), 'archive.json'), 'utf8'));\n return isArchiveRecord(raw) ? withValidSaves(raw) : null;\n } catch {\n return null;\n }\n}\n\nfunction isSavedIgnored(v: unknown): v is SavedIgnored {\n if (!v || typeof v !== 'object') return false;\n const o = v as Record<string, unknown>;\n return typeof o.files === 'number' && typeof o.bytes === 'number' && typeof o.skipped === 'number';\n}\n\n/** Saved work comes back only in its known shape (stored JSON); anything else is dropped from the record read. */\nfunction withValidSaves(r: ArchiveRecord): ArchiveRecord {\n const out = { ...r };\n if (r.uncommitted !== undefined) {\n const valid =\n typeof r.uncommitted === 'object' && r.uncommitted ? Object.entries(r.uncommitted).filter(([, v]) => isSavedUncommitted(v)) : [];\n if (valid.length) out.uncommitted = Object.fromEntries(valid);\n else delete out.uncommitted;\n }\n if (r.unrestored !== undefined) {\n const valid = Array.isArray(r.unrestored) ? r.unrestored.filter(isSavedUncommitted) : [];\n if (valid.length) out.unrestored = valid;\n else delete out.unrestored;\n }\n if (r.ignored !== undefined) {\n const valid = typeof r.ignored === 'object' && r.ignored ? Object.entries(r.ignored).filter(([, v]) => isSavedIgnored(v)) : [];\n if (valid.length) out.ignored = Object.fromEntries(valid);\n else delete out.ignored;\n }\n return out;\n}\n\nfunction isArchiveRecord(x: unknown): x is ArchiveRecord {\n const r = x as ArchiveRecord | null;\n return (\n !!r &&\n typeof r === 'object' &&\n typeof r.sessionId === 'string' &&\n typeof r.worktreeRemoved === 'boolean' &&\n Array.isArray(r.transcripts) &&\n !!r.summary &&\n Array.isArray(r.summary.prompts)\n );\n}\n\n/** How far back the newest restored transcript is dated: past the Terminal tab's 5 minutes of \"written just now\". */\nexport const RESTORED_AGE_MS = 10 * 60_000;\n\n/**\n * When a conversation file's last entry was written, as its agent reads it (`conversation.entries` over its\n * tail), or 0 — no time in it (an empty file, a summary only).\n */\nexport function lastEntryTime(file: string, entries: (lines: readonly unknown[]) => ConversationEntry[]): number {\n // 64 KB back almost always has a time; up to 4 MB when it doesn't (a last line can be a big tool result).\n for (const bytes of [64 * 1024, 4 * 1024 * 1024]) {\n let t = 0;\n for (const e of entries(readJsonlTail(file, bytes))) {\n const at = Date.parse(e.at);\n if (Number.isFinite(at) && at > t) t = at;\n }\n if (t || fileSize(file) <= bytes) return t;\n }\n return 0;\n}\n\nfunction fileSize(file: string): number {\n try {\n return fs.statSync(file).size;\n } catch {\n return 0;\n }\n}\n\n/**\n * Put an archived conversation back where Claude looks for it (the project\n * folder of the session's worktree), so `--continue` picks it up. Files that\n * are already there are left alone. Returns how many were restored.\n *\n * Then every conversation in that folder — restored, and kept by Claude Code (it deletes the old ones first) —\n * is dated in the order it was written (by its last entry; one with no time first), a second apart, the newest\n * a few minutes back: --continue and every \"its newest conversation\" reader take the newest, whichever were kept;\n * none reads as written just now (the Terminal tab's \"running in another terminal\"); none lands near Claude\n * Code's 30 days (cleanupPeriodDays), which would delete it.\n */\nexport function restoreArchivedTranscripts(\n s: WorktreeSession,\n root = archiveRoot(),\n /** Where its agent looks for them (agents/: `conversation.restoreDir`; none: it starts fresh, the archive keeps them). */\n restoreDir: (s: WorktreeSession) => string | null = (x) => agentOf(x).conversation?.restoreDir?.(x) ?? null,\n): number {\n const id = sessionIdFor(s);\n const rec = readArchive(id, root);\n if (!rec) return 0;\n const dest = restoreDir(s);\n if (!dest) return 0;\n const written = new Set<string>();\n for (const t of rec.transcripts) {\n const to = path.join(dest, t.file);\n if (fs.existsSync(to)) continue;\n const text = readArchivedTranscript(id, t.file, root);\n if (text === null) continue;\n fs.mkdirSync(dest, { recursive: true });\n fs.writeFileSync(to, text);\n written.add(to);\n }\n if (written.size === 0) return 0;\n // Only this session's own conversations (the archive's list): another conversation in the same folder — you\n // ran Claude there yourself — keeps its date.\n const entries = agentOf(s).conversation?.entries ?? (() => []);\n const files: Array<{ file: string; last: number }> = [];\n for (const t of rec.transcripts) {\n const file = path.join(dest, t.file);\n try {\n // Its last entry's time; with none readable (none at all, or a last line past the tail read), its own\n // date — but not for one just written, whose date is now: that one goes first, never the one resumed.\n files.push({ file, last: lastEntryTime(file, entries) || (written.has(file) ? 0 : fs.statSync(file).mtimeMs) });\n } catch {\n /* gone: nothing to date */\n }\n }\n files.sort((a, b) => a.last - b.last);\n const newest = Date.now() - RESTORED_AGE_MS;\n for (const [i, { file }] of files.entries()) {\n const at = new Date(newest - (files.length - 1 - i) * 1000);\n try {\n fs.utimesSync(file, at, at);\n } catch {\n /* dated as it is */\n }\n }\n return written.size;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { runGitAsync, runGitSync, writeTempTreeAsync } from '../diff/git-tree-snapshot.js';\n\n/**\n * A worktree's uncommitted work, kept when archiving removes the worktree\n * and put back when the session is restored. Modified, deleted and new\n * (untracked, not git-ignored) files are snapshotted into a commit on top of\n * HEAD, the way checkpoints are (a temp index: the real one is untouched),\n * kept alive by a ref in the repo (`refs/work/archive/<session>/<repo>`,\n * shared by its worktrees, so it outlives this one), and written as a binary\n * patch into the archive folder — the copy Restore applies, readable by hand.\n * Git-ignored files aren't included (build output, local settings that\n * `copyFiles` copies again); staged and unstaged come back alike, unstaged.\n */\n\n/** A bigger patch isn't kept: the worktree stays instead (a stray dump file shouldn't land in ~/.work). */\nexport const MAX_SAVED_PATCH_BYTES = 50 * 1024 * 1024;\n\nexport interface SavedUncommitted {\n /** The snapshot commit (its parent is `base`). */\n commit: string;\n /** HEAD when it was saved. */\n base: string;\n ref: string;\n files: number;\n /** The patch's file name in the archive's `uncommitted/` folder. */\n patch: string;\n /** Put back by a Restore (then not again). */\n restoredAt?: string;\n /** A Restore that couldn't put it back: why (the ref and patch stay). */\n restoreError?: string;\n}\n\nexport type SaveResult = { clean: true } | { saved: SavedUncommitted } | { error: string };\n\nconst safeName = (s: string): string => s.replace(/[^A-Za-z0-9._-]/g, '_');\n/** Where a save is kept: per session, repo and archive time, so a later archive never overwrites one a Restore couldn't put back. */\nexport const archiveRefFor = (sessionId: string, repo: string, stamp: number): string =>\n `refs/work/archive/${safeName(sessionId)}/${safeName(repo)}/${stamp}`;\n/** Every save of a session lives under this (deleted with the session). */\nexport const archiveRefsPrefix = (sessionId: string): string => `refs/work/archive/${safeName(sessionId)}/`;\nexport const uncommittedDir = (archiveDir: string): string => path.join(archiveDir, 'uncommitted');\n\nconst COMMIT_ENV = {\n GIT_AUTHOR_NAME: 'work',\n GIT_AUTHOR_EMAIL: 'work@local',\n GIT_COMMITTER_NAME: 'work',\n GIT_COMMITTER_EMAIL: 'work@local',\n};\n\n/** Save `worktree`'s uncommitted work under `ref` and as `<archiveDir>/uncommitted/<patchName>.patch`. */\nexport async function saveUncommitted(\n worktree: string,\n repo: string,\n ref: string,\n archiveDir: string,\n patchName = repo,\n maxBytes = MAX_SAVED_PATCH_BYTES,\n): Promise<SaveResult> {\n const status = await runGitAsync(worktree, { args: ['status', '--porcelain', '--untracked-files=all'] });\n if (status.status !== 0) return { error: `git can't read ${repo}` };\n const files = status.stdout.split('\\n').filter((l) => l.trim()).length;\n if (files === 0) return { clean: true };\n\n const tree = await writeTempTreeAsync(worktree, { includeWorkingTree: true });\n if (!tree?.headSha) return { error: `git couldn't snapshot ${repo}` };\n const commit = await runGitAsync(worktree, {\n args: ['commit-tree', tree.treeSha, '-p', tree.headSha, '-m', 'work archive: uncommitted changes'],\n env: { ...process.env, ...COMMIT_ENV },\n });\n const sha = commit.stdout.trim();\n if (commit.status !== 0 || !sha) return { error: `git couldn't snapshot ${repo}` };\n\n const dir = uncommittedDir(archiveDir);\n fs.mkdirSync(dir, { recursive: true });\n const patch = `${safeName(patchName)}.patch`;\n const patchPath = path.join(dir, patch);\n const diff = await runGitAsync(worktree, {\n args: ['diff', '--binary', '--no-color', '--no-ext-diff', `--output=${patchPath}`, tree.headSha, sha],\n });\n const size = fs.existsSync(patchPath) ? fs.statSync(patchPath).size : 0;\n if (diff.status !== 0 || size === 0) {\n fs.rmSync(patchPath, { force: true });\n return { error: `git couldn't write ${repo}'s changes as a patch` };\n }\n if (size > maxBytes) {\n fs.rmSync(patchPath, { force: true });\n return { error: `${repo}'s uncommitted changes are too large to keep (${Math.round(size / 1024 / 1024)} MB)` };\n }\n const pinned = await runGitAsync(worktree, { args: ['update-ref', ref, sha] });\n if (pinned.status !== 0) {\n fs.rmSync(patchPath, { force: true });\n return { error: `git couldn't keep ${repo}'s changes (update-ref)` };\n }\n return { saved: { commit: sha, base: tree.headSha, ref, files, patch } };\n}\n\n/** Undo a save that wasn't needed after all (the worktree stayed): its ref and patch go. */\nexport async function dropSaved(repoRoot: string, saved: SavedUncommitted, archiveDir: string): Promise<void> {\n await runGitAsync(repoRoot, { args: ['update-ref', '-d', saved.ref] });\n fs.rmSync(path.join(uncommittedDir(archiveDir), saved.patch), { force: true });\n}\n\n/**\n * Put saved work back into a recreated worktree: the patch applied to the\n * working tree (nothing staged). Refuses rather than mixes: when the\n * worktree already has changes of its own, or the patch doesn't apply\n * (the branch moved on) — the ref and the patch stay for doing it by hand.\n * On success the ref goes (the patch stays in the archive).\n */\nexport async function restoreUncommitted(\n worktree: string,\n saved: SavedUncommitted,\n archiveDir: string,\n): Promise<{ ok: true } | { ok: false; error: string }> {\n const patchPath = path.join(uncommittedDir(archiveDir), saved.patch);\n const byHand = `the changes are kept in ${saved.ref} and ${patchPath}`;\n if (!fs.existsSync(patchPath)) return { ok: false, error: `its saved patch is missing (${patchPath})` };\n const status = await runGitAsync(worktree, { args: ['status', '--porcelain', '--untracked-files=all'] });\n if (status.status !== 0) return { ok: false, error: `git can't read the worktree; ${byHand}` };\n if (status.stdout.trim()) return { ok: false, error: `the worktree already has changes, so they weren't mixed in; ${byHand}` };\n const check = await runGitAsync(worktree, { args: ['apply', '--binary', '--check', patchPath] });\n if (check.status !== 0) return { ok: false, error: `they no longer apply (the branch moved on); ${byHand}` };\n const apply = await runGitAsync(worktree, { args: ['apply', '--binary', patchPath] });\n if (apply.status !== 0) return { ok: false, error: `git apply failed; ${byHand}` };\n await runGitAsync(worktree, { args: ['update-ref', '-d', saved.ref] });\n return { ok: true };\n}\n\n/** Delete every saved ref of a session in a repo (the session is deleted; its archive folder goes too). */\nexport function dropSessionSaves(repoRoot: string, sessionId: string): void {\n const refs = runGitSync(repoRoot, { args: ['for-each-ref', '--format=%(refname)', archiveRefsPrefix(sessionId)] });\n for (const ref of refs.stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean))\n runGitSync(repoRoot, { args: ['update-ref', '-d', ref] });\n}\n\n/** Shape guard for the archive record's `uncommitted` map (stored JSON). */\nexport function isSavedUncommitted(x: unknown): x is SavedUncommitted {\n const v = x as SavedUncommitted | null;\n return (\n !!v &&\n typeof v === 'object' &&\n typeof v.commit === 'string' &&\n typeof v.base === 'string' &&\n typeof v.ref === 'string' &&\n typeof v.patch === 'string' &&\n typeof v.files === 'number'\n );\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport spawn from '../platform/spawn.js';\n\nexport interface TempTreeResult {\n /** Tree sha written from the temp index. */\n treeSha: string;\n /** HEAD commit sha, or null when the repo has no commits yet. Callers that\n * build a commit from `treeSha` use this as the parent. */\n headSha: string | null;\n}\n\n/**\n * Build a git tree sha for a repo WITHOUT disturbing the real index, using a\n * throwaway `GIT_INDEX_FILE`. Shared by `checkpoint.ts` (which commits the\n * tree and pins it behind a ref) and `diff-pipeline.ts` (which diffs the tree\n * against a checkpoint commit) — both previously hand-rolled this same\n * read-tree / add / write-tree dance.\n *\n * cp .git/index <tmp> (when includeWorkingTree)\n * GIT_INDEX_FILE=<tmp> git read-tree HEAD (otherwise / on copy failure)\n * GIT_INDEX_FILE=<tmp> git add -A (when includeWorkingTree)\n * GIT_INDEX_FILE=<tmp> git write-tree → treeSha\n *\n * Why the copy: an index built by `read-tree` carries no stat cache, so the\n * following `add -A` has to re-hash EVERY file in the worktree — 3.3s on a\n * mid-size repo, paid on every checkpoint and every `to=working` range diff\n * (twice over for a two-repo group). Seeding from the real index inherits its\n * stat cache, so git only hashes what actually changed: same tree sha, ~0.2s.\n * `add -A` overwrites every entry from the worktree, so staged-but-uncommitted\n * state in the copied index can't leak into the tree — the one exception is a\n * force-added ignored file, which stays (it is staged content, so keeping it\n * is the better answer anyway). An index with assume-unchanged/skip-worktree\n * entries is NOT used as a seed (see `seedFromRealIndex`).\n *\n * With `includeWorkingTree` (default), `add -A` promotes every working-tree\n * change including untracked files (honoring `.gitignore`), so the tree is a\n * full snapshot of the working tree. Without it, the tree is HEAD's tree\n * verbatim (the empty tree on a repo with no commits) — used for the\n * \"Initial\" checkpoint baseline so a diff of Initial→working reproduces the\n * full uncommitted diff instead of hiding pre-existing changes.\n *\n * Returns null on any git failure (caller should skip this repo). The temp\n * index file is always unlinked.\n */\nexport function writeTempTree(repoRoot: string, opts: { includeWorkingTree?: boolean } = {}): TempTreeResult | null {\n const steps = tempTreeSteps(repoRoot, opts.includeWorkingTree ?? true);\n let next = steps.next();\n while (!next.done) next = steps.next(runGitSync(repoRoot, next.value));\n return next.value;\n}\n\n/**\n * writeTempTree without blocking the event loop — for checkpoints, which run\n * on every Claude turn of every session (a synchronous `git add -A` on a big\n * repo froze the server for seconds, once per finishing turn). One snapshot\n * per repo at a time: turns ending together queue rather than run several\n * `add -A` over the same tree at once.\n */\nexport function writeTempTreeAsync(repoRoot: string, opts: { includeWorkingTree?: boolean } = {}): Promise<TempTreeResult | null> {\n return inRepoQueue(repoRoot, async () => {\n const steps = tempTreeSteps(repoRoot, opts.includeWorkingTree ?? true);\n let next = steps.next();\n while (!next.done) next = steps.next(await runGitAsync(repoRoot, next.value));\n return next.value;\n });\n}\n\n/** One git command of the snapshot: its args, and the env it runs with. */\nexport interface GitStep {\n args: string[];\n env?: NodeJS.ProcessEnv;\n}\nexport interface GitResult {\n status: number | null;\n stdout: string;\n}\n\n/**\n * The snapshot's steps, once, for both drivers: yields each git command and\n * gets its result back; returns the tree. (fs work in between — copying the\n * index, removing the temp file — is quick and stays synchronous.)\n */\nfunction* tempTreeSteps(repoRoot: string, includeWorkingTree: boolean): Generator<GitStep, TempTreeResult | null, GitResult> {\n const tmpIndex = path.join(os.tmpdir(), `wd-tree-${process.pid}-${crypto.randomBytes(6).toString('hex')}.idx`);\n const env: NodeJS.ProcessEnv = { ...process.env, GIT_INDEX_FILE: tmpIndex };\n try {\n const headSha = ((yield { args: ['rev-parse', '--verify', 'HEAD'] }).stdout ?? '').trim() || null;\n\n // The working-tree snapshot only needs a starting point that `add -A`\n // will overwrite, so prefer the warm real index (its stat cache: git\n // re-hashes only what changed); HEAD's tree is the fallback. A HEAD-only\n // snapshot must read HEAD verbatim.\n let seeded = false;\n if (includeWorkingTree) {\n const out = (yield { args: ['rev-parse', '--git-path', 'index'] }).stdout;\n if (seedIndexCopy(repoRoot, out, tmpIndex)) {\n // assume-unchanged / skip-worktree bits ride along in the copy, and\n // `add -A` trusts them and never re-reads those files — an edit to a\n // locally-tweaked config would silently vanish from the snapshot. The\n // read-tree index has no such bits, so fall back to it when any exist.\n // `ls-files -v` tags assume-unchanged with a lowercase letter and\n // skip-worktree with S.\n const listed = yield { args: ['ls-files', '-v'], env };\n const flagged =\n listed.status !== 0 ||\n (listed.stdout ?? '').split('\\n').some((line) => {\n const tag = line.charAt(0);\n return tag === 'S' || (tag >= 'a' && tag <= 'z');\n });\n if (flagged) removeQuietly(tmpIndex);\n else seeded = true;\n }\n }\n if (!seeded && headSha) {\n if ((yield { args: ['read-tree', 'HEAD'], env }).status !== 0) return null;\n }\n if (includeWorkingTree) {\n // `-A` against a temp index seeded from HEAD (or empty) captures the\n // full working-tree state, subject to .gitignore.\n if ((yield { args: ['add', '-A'], env }).status !== 0) return null;\n }\n const wt = yield { args: ['write-tree'], env };\n if (wt.status !== 0 || !wt.stdout) return null;\n return { treeSha: wt.stdout.trim(), headSha };\n } finally {\n removeQuietly(tmpIndex);\n }\n}\n\n/** Copy the repo's real index (`git rev-parse --git-path index` output,\n * relative to the repo root in a linked worktree) to `tmpIndex`, keeping\n * its mtime. False when there's nothing to copy (fresh repo). */\nfunction seedIndexCopy(repoRoot: string, gitPathOut: string, tmpIndex: string): boolean {\n try {\n if (!gitPathOut) return false;\n const realIndex = path.resolve(repoRoot, gitPathOut.trim());\n if (!fs.existsSync(realIndex)) return false;\n fs.copyFileSync(realIndex, tmpIndex);\n // Carry the real index's mtime over. Git re-hashes \"racily clean\"\n // entries — file mtime >= the index file's own mtime — rather than\n // trusting their cached stat. A copy stamped \"now\" would make those\n // entries look safely clean, and a same-size edit landing in the same\n // timestamp tick as an index refresh would be missed. copyFileSync\n // preserves times on Windows (CopyFileW) but not on Linux/macOS.\n const st = fs.statSync(realIndex);\n fs.utimesSync(tmpIndex, st.atime, st.mtime);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction removeQuietly(file: string): void {\n try {\n if (fs.existsSync(file)) fs.unlinkSync(file);\n } catch {\n // Temp-file leftover isn't fatal — the OS cleans it eventually.\n }\n}\n\nconst GIT_MAX_BUFFER = 64 * 1024 * 1024;\n\nexport function runGitSync(cwd: string, step: GitStep): GitResult {\n const r = spawn.sync('git', step.args, {\n cwd,\n encoding: 'utf-8',\n env: step.env ?? process.env,\n windowsHide: true,\n maxBuffer: GIT_MAX_BUFFER,\n });\n return { status: r.status, stdout: r.stdout ?? '' };\n}\n\n/** A git command off the event loop (argv only, no shell). */\nexport function runGitAsync(cwd: string, step: GitStep): Promise<GitResult> {\n return new Promise((resolve) => {\n let stdout = '';\n let size = 0;\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn('git', step.args, { cwd, env: step.env ?? process.env, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });\n } catch {\n resolve({ status: null, stdout: '' });\n return;\n }\n child.stdout?.setEncoding('utf-8');\n child.stdout?.on('data', (d: string) => {\n size += d.length;\n if (size <= GIT_MAX_BUFFER) stdout += d;\n });\n child.on('error', () => resolve({ status: null, stdout: '' }));\n child.on('close', (code) => resolve({ status: code, stdout }));\n });\n}\n\nconst repoQueues = new Map<string, Promise<unknown>>();\n\n/** Run `fn` after whatever is queued for this repo; the queue empties itself. */\nexport function inRepoQueue<T>(repoRoot: string, fn: () => Promise<T>): Promise<T> {\n const key = path.resolve(repoRoot).toLowerCase();\n const prev = repoQueues.get(key) ?? Promise.resolve();\n const run = prev.then(fn, fn);\n const tail = run.catch(() => {});\n repoQueues.set(key, tail);\n void tail.then(() => {\n if (repoQueues.get(key) === tail) repoQueues.delete(key);\n });\n return run;\n}\n","import { debugLog } from './logger.js';\n\n/**\n * \"Best effort\" without flying blind. Plenty of work's side paths must never\n * break the main one — a Claude hook must not block the turn, a failed\n * status write must not fail a request — so errors are swallowed. But a\n * silent `catch {}` makes those failures invisible when someone asks \"why\n * didn't my session show up / get restored / get a status?\". These helpers\n * swallow AND record to ~/.work/debug.log (rotated), labelled.\n *\n * Use for failures that would explain a symptom. Plain noise — unlinking a\n * file that's already gone, writing to a socket that just closed — can stay\n * a bare catch.\n */\n\nexport function logSwallowed(label: string, err: unknown): void {\n const e = err as { code?: string; message?: string } | null;\n const detail = e?.message ?? String(err);\n debugLog('WARN', `[best-effort] ${label}: ${e?.code ? `${e.code} ` : ''}${detail}`);\n}\n\n/** Run `fn`; on throw, log it and return `fallback`. */\nexport function bestEffort<T>(label: string, fn: () => T, fallback?: T): T | undefined {\n try {\n return fn();\n } catch (err) {\n logSwallowed(label, err);\n return fallback;\n }\n}\n\n/** Async variant; also catches rejections. */\nexport async function bestEffortAsync<T>(label: string, fn: () => Promise<T>, fallback?: T): Promise<T | undefined> {\n try {\n return await fn();\n } catch (err) {\n logSwallowed(label, err);\n return fallback;\n }\n}\n\n/** For promise chains: `.catch(swallow('label'))`. */\nexport function swallow(label: string): (err: unknown) => undefined {\n return (err) => {\n logSwallowed(label, err);\n return undefined;\n };\n}\n","/**\n * Where a session's pull request stands, in one word and one line — the\n * session header, the rail's tooltip, the Inbox and `work sessions` say\n * the same. Pure and import-free: the SPA and the demo import it.\n *\n * A PR waiting on others (reviewers, checks) keeps the session out of the\n * Inbox (\"In review\"); it comes back when the PR wants you again: approved\n * with checks passing (ready to merge), a merge conflict, or failing checks.\n * Review comments come back on their own (`openReviewThreads`).\n */\n\n/** What the stage reads of a PR (ShipPr, the PR watch's last check). */\nexport interface StagePr {\n number: number;\n url: string;\n state: 'OPEN' | 'MERGED' | 'CLOSED';\n isDraft: boolean;\n mergeStateStatus: string;\n checks: 'pass' | 'fail' | 'pending' | 'none';\n headSha: string;\n /** APPROVED | CHANGES_REQUESTED | REVIEW_REQUIRED, or '' when the repo requires no review. */\n reviewDecision?: string;\n /** When it merged (ISO), when it did. */\n mergedAt?: string;\n}\n\n/** How long another branch's merged PR goes on showing under a session (the PR tab's \"earlier\"). */\nexport const EARLIER_SHOWN_MS = 30 * 24 * 3600_000;\n\nexport type PrStageKind =\n 'draft' | 'in_review' | 'checks_running' | 'checks_failing' | 'changes' | 'conflict' | 'approved' | 'ready' | 'merged' | 'closed';\n\nexport interface PrStage {\n kind: PrStageKind;\n /** \"PR #212 · approved, ready to merge\" */\n text: string;\n /** Each PR with its own stage: a group's are shown (and opened) one by one. Its\n * checks too (additive): a draft's stage is \"draft\" whatever its checks say. */\n prs: Array<{ repo: string; number: number; url: string; kind: PrStageKind; checks?: StagePr['checks'] }>;\n /** Changes when the stage or a PR's head does: what \"seen\" and a snooze compare. */\n key: string;\n}\n\n/** The stages that bring a session back to the Inbox (until you've looked). */\nexport const STAGE_WANTS_YOU: ReadonlySet<PrStageKind> = new Set(['ready', 'conflict', 'checks_failing']);\n/** The stages where it waits on others: \"In review\", out of the Inbox. */\nexport const STAGE_WAITING: ReadonlySet<PrStageKind> = new Set(['in_review', 'checks_running', 'approved', 'changes']);\n\nconst PHRASE: Record<PrStageKind, string> = {\n draft: 'draft',\n in_review: 'waiting for review',\n checks_running: 'checks running',\n checks_failing: 'checks failing',\n changes: 'changes requested',\n conflict: 'merge conflict',\n approved: 'approved',\n ready: 'approved, ready to merge',\n merged: 'merged',\n closed: 'closed',\n};\n\n/** One open PR's stage. Most pressing first: a conflict or failing checks outweigh a review. */\nexport function stageOfPr(pr: StagePr): PrStageKind {\n if (pr.state === 'MERGED') return 'merged';\n if (pr.state === 'CLOSED') return 'closed';\n if (pr.isDraft) return 'draft';\n if (pr.mergeStateStatus === 'DIRTY') return 'conflict';\n if (pr.checks === 'fail') return 'checks_failing';\n if (pr.reviewDecision === 'CHANGES_REQUESTED') return 'changes';\n if (pr.reviewDecision === 'APPROVED') {\n if (pr.checks === 'pending') return 'checks_running';\n // Behind its base or blocked by a rule: approved, not mergeable yet.\n return pr.mergeStateStatus === 'BEHIND' || pr.mergeStateStatus === 'BLOCKED' ? 'approved' : 'ready';\n }\n if (pr.checks === 'pending' && pr.reviewDecision !== 'REVIEW_REQUIRED') return 'checks_running';\n return 'in_review';\n}\n\n/** How pressing a stage is, across a group's repos (the session shows its most pressing). */\nconst RANK: Record<PrStageKind, number> = {\n conflict: 0,\n checks_failing: 1,\n changes: 2,\n draft: 3,\n in_review: 4,\n checks_running: 5,\n approved: 6,\n ready: 7,\n merged: 8,\n closed: 9,\n};\n\n/**\n * A session's stage from its repos' PRs: the most pressing open one; `ready`\n * only when every open PR is. Merged when every PR merged; null with no PR.\n */\nexport function prStageOf(\n repos: ReadonlyArray<{ name: string; pr: StagePr | null; also?: ReadonlyArray<{ pr: StagePr }> }>,\n): PrStage | null {\n // A repo's other open PRs (stageRepos' `also`: other branches it worked on) count as its own.\n const withPr = repos.flatMap((r) =>\n r.pr ? [{ name: r.name, pr: r.pr }, ...(r.also ?? []).map((a) => ({ name: r.name, pr: a.pr }))] : [],\n );\n if (!withPr.length) return null;\n const open = withPr.filter((r) => r.pr.state === 'OPEN');\n const shown = open.length ? open : withPr;\n let kind: PrStageKind = 'closed';\n for (const r of shown) {\n const k = stageOfPr(r.pr);\n if (RANK[k] < RANK[kind]) kind = k;\n }\n // `ready` is the least pressing open stage, so the loop above already\n // picked anything less ready that another repo has.\n if (!open.length && withPr.some((r) => r.pr.state === 'MERGED')) kind = 'merged';\n const pr = (r: { name: string; pr: StagePr }) => ({\n repo: r.name,\n number: r.pr.number,\n url: r.pr.url,\n kind: stageOfPr(r.pr),\n checks: r.pr.checks,\n });\n const named = shown.map(pr);\n // Its merged PRs too, after the open ones: a group whose backend merged while\n // its frontend is in review shows both pills, so you know it had (and merged)\n // one. The stage, its text and its key are still the open ones'.\n const prs = [...named, ...withPr.filter((r) => r.pr.state === 'MERGED' && !shown.includes(r)).map(pr)];\n const which = named.length === 1 ? `PR #${named[0].number}` : `PRs ${named.map((p) => `${p.repo} #${p.number}`).join(', ')}`;\n return {\n kind,\n text: kind === 'draft' ? `Draft ${which}` : `${which} · ${PHRASE[kind]}`,\n prs,\n key: `${kind}:${shown.map((r) => `${r.name}@${r.pr.headSha}`).join(',')}`,\n };\n}\n\n/**\n * Per repo, the PRs its stage reads, across the branches it worked on (session-branches.ts: Claude may have\n * moved on after a PR merged, to a new branch and a new PR): `pr` the newest open one, else the checked-out\n * branch's own whatever its state — never another branch's merged or closed one (reported: a repo's own checkout on\n * main read \"PR #55 · merged\", from a branch it was on a month before); `also` every other open one, newest first — a\n * session that opened PRs from two branches of one repo shows both. `earlier`: the merged and closed rest, newest\n * first, those merged over `EARLIER_SHOWN_MS` ago left out — the PR tab folds them under it (\"earlier: #3592\n * merged\"), and they drop out of the stage's pills. Pure.\n */\nexport function stageRepos<P extends StagePr>(\n repos: ReadonlyArray<{ name: string; pr: P | null; branch?: string; otherPrs?: ReadonlyArray<{ branch: string; pr: P }> }>,\n now: number = Date.now(),\n): Array<{\n name: string;\n pr: P | null;\n branch?: string;\n also: Array<{ branch?: string; pr: P }>;\n earlier: Array<{ branch?: string; pr: P }>;\n}> {\n return repos.map((r) => {\n const all: Array<{ branch?: string; pr: P }> = [\n ...(r.pr ? [{ ...(r.branch ? { branch: r.branch } : {}), pr: r.pr }] : []),\n ...(r.otherPrs ?? []).filter((o) => !r.pr || o.pr.url !== r.pr.url),\n ];\n const open = all.filter((x) => x.pr.state === 'OPEN').sort((a, b) => b.pr.number - a.pr.number);\n const chosen = open[0] ?? all.find((x) => x.pr === r.pr) ?? null;\n const recent = (x: { pr: P }) => !x.pr.mergedAt || now - Date.parse(x.pr.mergedAt) < EARLIER_SHOWN_MS;\n return {\n name: r.name,\n pr: chosen?.pr ?? null,\n ...(chosen?.branch ? { branch: chosen.branch } : {}),\n also: open.filter((x) => x !== chosen),\n earlier: all.filter((x) => x !== chosen && x.pr.state !== 'OPEN' && recent(x)).sort((a, b) => b.pr.number - a.pr.number),\n };\n });\n}\n\n/** A stage in a word or two, for one PR's pill: \"waiting for review\", \"ready to merge\"… */\nexport const stagePhrase = (kind: PrStageKind): string => (kind === 'ready' ? 'ready to merge' : PHRASE[kind]);\n\n/** How a stage reads at a glance: good (ready), bad (a conflict, failing checks, changes asked), draft, merged, or plain. */\nexport function stageTone(kind: PrStageKind): 'good' | 'bad' | 'draft' | 'merged' | 'plain' {\n if (kind === 'ready') return 'good';\n if (kind === 'merged') return 'merged';\n if (kind === 'conflict' || kind === 'checks_failing' || kind === 'changes') return 'bad';\n return kind === 'draft' ? 'draft' : 'plain';\n}\n\n/** It wants you: a stage that brings it back, not looked at since it got there. */\nexport function stageWantsYou(stage: (Pick<PrStage, 'kind'> & { seen?: boolean }) | null | undefined): boolean {\n return !!stage && STAGE_WANTS_YOU.has(stage.kind) && !stage.seen;\n}\n\n/** A stage as a client sent it back (the snooze and seen routes): its kind and key, or null. */\nexport function cleanStageRef(raw: unknown): { kind: PrStageKind; key: string } | null {\n const o = raw as { kind?: unknown; key?: unknown } | null;\n if (!o || typeof o !== 'object' || typeof o.key !== 'string' || !o.key || o.key.length > 2000) return null;\n return typeof o.kind === 'string' && Object.hasOwn(PHRASE, o.kind) ? { kind: o.kind as PrStageKind, key: o.key } : null;\n}\n\n/**\n * What a new check says against the stage shown before (its key, '' for\n * none, undefined before the first check): nothing new, a change to show,\n * or one that wants you — to tell you about. The first sight after a start\n * is only shown, never told.\n */\nexport function stageNews(prevKey: string | undefined, next: PrStage | null): 'none' | 'changed' | 'notify' {\n const key = next?.key ?? '';\n if (key === prevKey) return 'none';\n if (prevKey === undefined || !next) return 'changed';\n return STAGE_WANTS_YOU.has(next.kind) ? 'notify' : 'changed';\n}\n\n/** It waits on others: in review. */\nexport function stageWaiting(stage: Pick<PrStage, 'kind'> | null | undefined): boolean {\n return !!stage && STAGE_WAITING.has(stage.kind);\n}\n\n/** Per session, what each new check says against the last one (stageNews), remembering it. */\nexport function createStageTracker(): (sessionId: string, stage: PrStage | null) => 'none' | 'changed' | 'notify' {\n const shown = new Map<string, string>();\n return (sessionId, stage) => {\n const news = stageNews(shown.get(sessionId), stage);\n shown.set(sessionId, stage?.key ?? '');\n return news;\n };\n}\n\n/**\n * The session's open PRs the stage doesn't hold. The PR watch knows one PR\n * per repo (`gh pr view <branch>`), and a branch may have more — one into\n * main and one into dev — which the dashboard's PR list still has: those are\n * shown beside the stage's pills, as plainly open (or draft).\n */\nexport function prsBeyondStage<T extends { url: string }>(stage: Pick<PrStage, 'prs'> | null | undefined, prs: T[]): T[] {\n if (!stage) return prs;\n const known = new Set(stage.prs.map((p) => p.url));\n return prs.filter((p) => !known.has(p.url));\n}\n","/**\n * Snooze: \"not now\" for a session that wants you. While snoozed it leaves the\n * Inbox (and its count, `n`, Review all) for a section of its own, and a\n * snooze for a while holds its notifications. Three kinds:\n *\n * 2h — two hours\n * tomorrow — tomorrow 9:00 (today 9:00 when it is still early morning)\n * change — until its status changes (a new turn, a new question, a\n * reviewer's new comment): it notifies then, as usual\n *\n * Pure (the SPA's labels and the server's checks both use it); stored per\n * session by snooze-store.ts.\n */\n\nimport { STAGE_WANTS_YOU, type PrStageKind } from '../pr/pr-stage.js';\n\nexport type SnoozeFor = '2h' | 'tomorrow' | 'change';\n/** One of the choices, or until a time (ISO). */\nexport type SnoozeChoice = SnoozeFor | { until: string };\n\nexport interface Snooze {\n /** Until then (ISO); null for \"until it changes\". */\n until: string | null;\n /** For \"until it changes\": the status it was snoozed in (statusKey). */\n statusKey?: string;\n at: string;\n}\n\n/**\n * What \"its status changed\" compares: Claude's state and since, the review\n * threads waiting, and a PR stage that wants you (only then, so a snooze\n * taken before stages existed still holds).\n */\nexport function statusKey(s: {\n attention?: { state: string; since: string } | null;\n openReviewThreads?: number;\n prStage?: { kind: PrStageKind; key: string } | null;\n}): string {\n const base = `${s.attention?.state ?? '-'}@${s.attention?.since ?? '-'}#${s.openReviewThreads ?? 0}`;\n const pr = s.prStage && STAGE_WANTS_YOU.has(s.prStage.kind);\n return pr ? `${base}|${s.prStage!.key}` : base;\n}\n\n/** The snooze to store for a choice, made at `now` (local time for \"tomorrow\"). */\nexport function snoozeFor(choice: SnoozeFor, subject: Parameters<typeof statusKey>[0], now = new Date()): Snooze {\n const at = now.toISOString();\n if (choice === 'change') return { until: null, statusKey: statusKey(subject), at };\n if (choice === '2h') return { until: new Date(now.getTime() + 2 * 3600_000).toISOString(), at };\n const morning = new Date(now);\n morning.setHours(9, 0, 0, 0);\n // Before 6 in the morning, \"tomorrow\" means the coming morning.\n if (now.getHours() >= 6) morning.setDate(morning.getDate() + 1);\n return { until: morning.toISOString(), at };\n}\n\n/** The longest a snooze for a set time may run. */\nexport const MAX_SNOOZE_MS = 30 * 24 * 3600_000;\n\n/**\n * Snoozed until a time you chose (\"until Friday 14:00\"). Null when that time\n * isn't one: not a date, already past, or more than 30 days away (a session\n * forgotten that long belongs archived, not snoozed).\n */\nexport function snoozeUntil(until: string | Date, now = new Date()): Snooze | null {\n const t = until instanceof Date ? until.getTime() : Date.parse(until);\n if (!Number.isFinite(t) || t <= now.getTime() || t - now.getTime() > MAX_SNOOZE_MS) return null;\n return { until: new Date(t).toISOString(), at: now.toISOString() };\n}\n\nconst WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];\n\n/**\n * A time typed for `work snooze --until`, local: \"14:00\" (today, or\n * tomorrow when that has passed), \"fri\" / \"fri 14:00\" (the coming one, 9:00\n * by default), \"+3h\" / \"+2d\", or a date (\"2026-10-03\", \"2026-10-03 14:00\").\n * Null when it isn't one.\n */\nexport function parseWhen(text: string, now = new Date()): Date | null {\n const t = text.trim().toLowerCase();\n const rel = /^\\+(\\d+)\\s*([hmd])$/.exec(t);\n if (rel && rel[2] === 'd') {\n // Days: the same clock time that many days on (across a DST change too, unlike 24 h steps).\n const d = new Date(now);\n d.setDate(d.getDate() + Number(rel[1]));\n return d;\n }\n if (rel) return new Date(now.getTime() + Number(rel[1]) * (rel[2] === 'h' ? 3_600_000 : 60_000));\n const clock = (h: string, m: string | undefined, base: Date) => {\n const d = new Date(base);\n d.setHours(Number(h), Number(m ?? 0), 0, 0);\n return Number(h) < 24 && Number(m ?? 0) < 60 ? d : null;\n };\n const hm = /^(\\d{1,2}):(\\d{2})$/.exec(t);\n if (hm) {\n const d = clock(hm[1], hm[2], now);\n if (d && d <= now) d.setDate(d.getDate() + 1);\n return d;\n }\n const wd = /^([a-z]{3})[a-z]*(?:\\s+(\\d{1,2})(?::(\\d{2}))?)?$/.exec(t);\n if (wd && WEEKDAYS.includes(wd[1])) {\n const d = new Date(now);\n const ahead = (WEEKDAYS.indexOf(wd[1]) - now.getDay() + 7) % 7 || 7;\n d.setDate(d.getDate() + ahead);\n return clock(wd[2] ?? '9', wd[3], d);\n }\n const date = /^(\\d{4})-(\\d{2})-(\\d{2})(?:[ t](\\d{1,2}):(\\d{2}))?$/.exec(t);\n if (date) {\n const d = new Date(Number(date[1]), Number(date[2]) - 1, Number(date[3]));\n return clock(date[4] ?? '9', date[5], d);\n }\n return null;\n}\n\n/** Is it still snoozed: before its time, or (until it changes) still in the status it was snoozed in. */\nexport function snoozeActive(snooze: Snooze | null | undefined, subject: Parameters<typeof statusKey>[0], now = Date.now()): boolean {\n if (!snooze) return false;\n if (snooze.until !== null) return (Date.parse(snooze.until) || 0) > now;\n return snooze.statusKey === statusKey(subject);\n}\n\n/** For the Inbox's Snoozed section: \"until 17:30\", \"until tomorrow 9:00\", \"until it changes\". */\nexport function snoozeLabel(snooze: Pick<Snooze, 'until'>, now = new Date()): string {\n if (snooze.until === null) return 'until it changes';\n const t = new Date(snooze.until);\n const time = t.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });\n const tomorrow = new Date(now);\n tomorrow.setDate(tomorrow.getDate() + 1);\n if (t.toDateString() === now.toDateString()) return `until ${time}`;\n if (t.toDateString() === tomorrow.toDateString()) return `until tomorrow ${time}`;\n return `until ${t.toLocaleDateString([], { weekday: 'short' })} ${time}`;\n}\n","/**\n * Attention-inbox ordering, shared by the server (session-status.ts) and the\n * browser SPA. Pure and dependency-free on purpose: the SPA may import it\n * (see the architecture test's allowlist), so it must never pull in Node.\n */\n\nexport type AgentState = 'working' | 'needs_input' | 'idle';\n\nexport interface AttentionLike {\n state: AgentState;\n seen: boolean;\n /** When the session entered `state` (ISO). */\n since: string;\n}\n\n/**\n * Inbox order: who needs you next.\n * 0 needs input — blocked on you; longest-waiting first\n * 1 done, unseen — finished a turn you haven't looked at; oldest first\n * 2 working — most recently started first\n * 3 idle, seen — nothing to do\n * 4 no status yet\n */\nexport function attentionRank(s: Pick<AttentionLike, 'state' | 'seen'> | null | undefined): number {\n if (!s) return 4;\n if (s.state === 'needs_input') return 0;\n if (s.state === 'idle' && !s.seen) return 1;\n if (s.state === 'working') return 2;\n return 3;\n}\n\nexport function compareAttention(a: AttentionLike | null | undefined, b: AttentionLike | null | undefined): number {\n const ra = attentionRank(a);\n const rb = attentionRank(b);\n if (ra !== rb) return ra - rb;\n if (!a || !b) return 0;\n const ta = Date.parse(a.since) || 0;\n const tb = Date.parse(b.since) || 0;\n // Waiting on you: oldest first. Working / idle-seen: newest first.\n return ra <= 1 ? ta - tb : tb - ta;\n}\n\n/** Wants the user now — what the inbox count counts. */\nexport function needsAttention(s: Pick<AttentionLike, 'state' | 'seen'> | null | undefined): boolean {\n return attentionRank(s) <= 1;\n}\n\n/** What the inbox ranks: Claude's status plus reviewers waiting on the session's PRs. */\nexport interface InboxSubject {\n attention?: AttentionLike | null;\n /** Snoozed out of the Inbox (snooze.ts): a section of its own, last; it doesn't want you meanwhile. */\n snoozed?: unknown;\n /** Unresolved review threads on its open PRs whose last word isn't yours. */\n openReviewThreads?: number;\n /** What it waits on that isn't done yet (session-blocks.ts): out of the Inbox meanwhile. */\n blockedBy?: readonly unknown[];\n /** Replies to PR review threads drafted and waiting for your Post (pr-replies.ts). */\n replyDrafts?: number;\n /** Where its pull request stands (pr-stage.ts); `seen` once you looked at it there. */\n prStage?: { kind: string; seen?: boolean; prs?: ReadonlyArray<{ kind: string; checks?: string }> } | null;\n}\n\n/**\n * What waits on YOU about a session, apart from what its Claude is doing —\n * the second of a session's two signals (its status icon is the first, and\n * says only what Claude is doing). Most pressing first:\n * turn — its Claude finished a turn you haven't looked at (to review)\n * reply — replies drafted to its PR's review threads, waiting for your Post\n * thread — review threads on its open PRs whose last word isn't yours\n * conflict — a PR of it conflicts with its base\n * checks — a PR of it fails its checks\n * merge — its PRs are approved with checks passing: ready to merge\n * Every view reads this one list (the rail's badge, the header's Needs you\n * line, the Sessions table, the Inbox), so they can't disagree.\n */\nexport type OwedKind = 'turn' | 'reply' | 'thread' | 'conflict' | 'checks' | 'merge';\nexport interface Owed {\n kind: OwedKind;\n count: number;\n}\n\nconst OPEN_PR = (k: string) => k !== 'merged' && k !== 'closed';\n\nexport function owedToYou(s: Pick<InboxSubject, 'attention' | 'openReviewThreads' | 'replyDrafts' | 'prStage'>): Owed[] {\n const out: Owed[] = [];\n // Finished, and you haven't looked: yours to review — not something its Claude is doing (reported: it took the icon).\n if (s.attention?.state === 'idle' && !s.attention.seen) out.push({ kind: 'turn', count: 1 });\n if ((s.replyDrafts ?? 0) > 0) out.push({ kind: 'reply', count: s.replyDrafts! });\n if ((s.openReviewThreads ?? 0) > 0) out.push({ kind: 'thread', count: s.openReviewThreads! });\n const stage = s.prStage;\n if (!stage) return out;\n // Each PR's own stage when the row has them (a group: one conflicts, another fails); else the stage's.\n const prs = stage.prs?.length ? stage.prs : [{ kind: stage.kind }];\n const conflicts = prs.filter((p) => p.kind === 'conflict').length;\n const failing = prs.filter(\n (p) => p.kind !== 'conflict' && OPEN_PR(p.kind) && (p.kind === 'checks_failing' || p.checks === 'fail'),\n ).length;\n if (conflicts) out.push({ kind: 'conflict', count: conflicts });\n if (failing) out.push({ kind: 'checks', count: failing });\n if (stage.kind === 'ready') out.push({ kind: 'merge', count: Math.max(1, prs.filter((p) => p.kind === 'ready').length) });\n return out;\n}\n\n/**\n * It wants you in the Inbox for what it owes you: replies to post and\n * unanswered threads until they're done; its PR's state (ready, conflict,\n * failing) until you've looked at that stage (`prWantsYou`).\n */\nexport function owedInInbox(s: InboxSubject): boolean {\n return (s.replyDrafts ?? 0) > 0 || (s.openReviewThreads ?? 0) > 0 || prWantsYou(s);\n}\n\n/**\n * The PR stages that bring a session back (pr-stage.ts STAGE_WANTS_YOU; a\n * test keeps the two equal — this module imports nothing).\n */\nexport const PR_STAGES_WANTING = ['ready', 'conflict', 'checks_failing'] as const;\n\n/** Its PR wants you and you haven't looked since: ready to merge, a conflict, failing checks. */\nexport function prWantsYou(s: Pick<InboxSubject, 'prStage'>): boolean {\n return !!s.prStage && !s.prStage.seen && (PR_STAGES_WANTING as readonly string[]).includes(s.prStage.kind);\n}\n\n/**\n * The inbox's sections, with review feedback — the same order the status\n * vocabulary colours by (session-view.ts `displayStatus`):\n * 0 needs input — blocked on you\n * 1 done, unseen — finished a turn you haven't looked at\n * 2 needs you — something on its PRs waits on you (`owedInInbox`:\n * replies to post, unanswered review threads, a PR\n * ready to merge, conflicting or failing — unseen),\n * whatever its Claude is doing\n * 3 working\n * 4 quiet\n * 5 no status, no review comments\n * 6 snoozed\n * 7 waiting on other work (blocked by) — unless its Claude asks you something\n */\nexport function inboxRank(s: InboxSubject): number {\n if (s.snoozed) return 6;\n const a = s.attention;\n if (s.blockedBy?.length && a?.state !== 'needs_input') return 7;\n if (a?.state === 'needs_input') return 0;\n if (a?.state === 'idle' && !a.seen) return 1;\n if (owedInInbox(s)) return 2;\n if (a?.state === 'working') return 3;\n return a ? 4 : 5;\n}\n\n/** Inbox order: by section; waiting on you (0–2) oldest first, the rest newest first. */\nexport function compareInbox(a: InboxSubject, b: InboxSubject): number {\n const ra = inboxRank(a);\n const rb = inboxRank(b);\n if (ra !== rb) return ra - rb;\n const ta = (a.attention && Date.parse(a.attention.since)) || 0;\n const tb = (b.attention && Date.parse(b.attention.since)) || 0;\n return ra <= 2 ? ta - tb : tb - ta;\n}\n\n/** It waits on your answer, as the Inbox's first section has it (not snoozed): what flashes the desktop app's taskbar. */\nexport function waitsOnYou(s: InboxSubject): boolean {\n return inboxRank(s) === 0;\n}\n\n/** Wants you now — what the Inbox badge counts: needs input, done unseen, what it owes you (`owedInInbox`). */\nexport function wantsYou(s: InboxSubject): boolean {\n return inboxRank(s) <= 2;\n}\n\n/** The line Claude starts when it stops to ask you something (the PR\n * watch's CI / review notes ask for it). A finished turn carrying it is\n * \"needs input\", not \"done\": top of the Inbox, and it notifies as such. */\nexport const DECISION_MARKER = 'DECISION NEEDED:';\n","import { json, tx, withDb, type Db } from '../platform/db.js';\nimport type { ConversationEntry } from '../agents/types.js';\n\n/**\n * Per-session agent status, driven by Claude Code's own hooks (installed by\n * `work web`): UserPromptSubmit → working, Stop → idle (done, review me),\n * Notification with a permission/approval message → needs_input. Hooks are\n * the source of truth — no screen scraping — the approach Emdash uses.\n *\n * Stored one row per session in state.db (see persistence below).\n */\n\nimport type { AgentState } from './attention.js';\nimport type { PermissionRequest } from '../api-types.js';\n\nexport type { AgentState } from './attention.js';\nexport { attentionRank, compareAttention, needsAttention } from './attention.js';\n\nexport interface SessionStatus {\n state: AgentState;\n /** When the session entered `state` (ISO). */\n since: string;\n /** One line: the prompt while working, Claude's last message when idle,\n * the permission request when it needs input. */\n summary?: string;\n /** False from the moment the session wants attention until the user looks\n * at it (opens it in the dashboard, or answers it). */\n seen: boolean;\n updatedAt: string;\n /** State before the latest hook event (null for the first). Lets the\n * server, which is only told \"status changed\", decide whether the\n * transition deserves a notification. */\n prevState?: AgentState | null;\n /** While needs_input on a permission prompt: the tool call it is about\n * (from the transcript), so the inbox can show it and answer it. */\n request?: PermissionRequest;\n /** When the last turn ended (the Stop hook). `since` doesn't move on an\n * idle → idle stop, and `updatedAt` moves on seen and on the idle nudge;\n * this is what transcript activity is compared with (effectiveStatus). */\n turnEndedAt?: string;\n /** When work itself last stopped its Claude (idle sleep, `work stop`, `markAgentStopped`): signs of a\n * Claude from before then are that one's, and it's gone — not one open in another terminal. */\n stoppedAt?: string;\n}\n\nexport type { StatusEvent } from './status-event.js';\nimport type { StatusEvent } from './status-event.js';\n\n/** Claude's Notification hook fires both for permission prompts and for the\n * \"waiting for your input\" nudge after ~60 s idle; only the former means\n * it's blocked on you. (Same regex Emdash settled on.) */\nconst NEEDS_INPUT_RE = /permission|approval|approve|needs your input|needs network access/i;\n\n/** `notification_type`s that mean Claude waits on you (vs idle_prompt, auth_success). */\nconst WAITS_ON_YOU = new Set(['permission_prompt', 'elicitation_dialog']);\n\n/** A finished turn whose message has a DECISION_MARKER line (attention.ts). */\nconst DECISION_RE = /^[\\W_]*DECISION NEEDED\\b[:\\s-]*(.*)$/im;\n\n/** Squash a prompt / message to one readable line. */\nexport function oneLine(text: string | undefined, max = 140): string | undefined {\n if (!text) return undefined;\n const line = text\n .split(/\\r?\\n/)\n .map((l) =>\n l\n .replace(/^[#>*\\-\\s]+/, '')\n .replace(/[`*_]/g, '')\n .trim(),\n )\n .find((l) => l.length > 0);\n if (!line) return undefined;\n return line.length > max ? line.slice(0, max - 1).trimEnd() + '…' : line;\n}\n\n/** Pure transition. `prev` is null for a session never seen before. */\nexport function applyStatusEvent(prev: SessionStatus | null, event: StatusEvent, now: Date = new Date()): SessionStatus {\n const ts = now.toISOString();\n const enter = (state: AgentState, summary: string | undefined, seen: boolean): SessionStatus => ({\n state,\n since: prev?.state === state ? prev.since : ts,\n summary: summary ?? prev?.summary,\n seen,\n updatedAt: ts,\n });\n switch (event.kind) {\n case 'prompt':\n // The user just typed into it — by definition they've seen it.\n return enter('working', oneLine(event.prompt), true);\n case 'stop': {\n // A turn ended now: `since` is now even when no prompt hook marked it\n // working (a `!` command, a background task's result) — \"finished 2m ago\".\n const ask = event.lastMessage?.match(DECISION_RE);\n if (ask) return { ...enter('needs_input', oneLine(ask[1]) ?? 'Claude needs a decision', false), since: ts, turnEndedAt: ts };\n return { ...enter('idle', oneLine(event.lastMessage), false), since: ts, turnEndedAt: ts };\n }\n case 'notification': {\n // Claude Code says what kind (`notification_type`): a permission prompt\n // or a question / dialog for you, or \"idle at its prompt\" (a minute\n // after it stopped). The message text is the fallback for older\n // versions: it missed \"Claude needs your input\" and the like.\n const blocks = event.type ? WAITS_ON_YOU.has(event.type) : !!event.message && NEEDS_INPUT_RE.test(event.message);\n if (event.type === 'idle_prompt' && prev && (prev.state === 'working' || prev.state === 'needs_input')) {\n // Waiting at its prompt with no Stop: the turn was interrupted (Esc,\n // a denied permission) — by you, so nothing to flag.\n return { ...enter('idle', prev.summary, true), turnEndedAt: ts };\n }\n if (blocks) {\n const next = enter('needs_input', oneLine(event.message), false);\n return event.request ? { ...next, request: event.request } : next;\n }\n // The idle nudge: nothing new happened, don't re-flag it as unseen.\n if (prev) return { ...prev, updatedAt: ts };\n return enter('idle', undefined, false);\n }\n case 'continue':\n return enter('working', oneLine(event.what) ?? prev?.summary, prev?.seen ?? true);\n case 'answered': {\n // Allowed: the tool runs, the turn goes on. Denied: Claude stops and\n // waits for you to say what to do instead.\n const what = prev?.request ? `${prev.request.tool}: ${prev.request.detail}` : 'the request';\n return event.answer === 'allow'\n ? enter('working', oneLine(`Allowed ${what}`), true)\n : enter('idle', oneLine(`Denied ${what} — tell Claude what to do instead`), true);\n }\n }\n}\n\n/** A \"working\" status with no Claude activity for this long is treated as\n * idle: the Claude died, was killed, or the Stop hook never fired. */\nexport const STALE_WORKING_MS = 15 * 60_000;\n\nexport interface EffectiveStatus extends SessionStatus {\n /** True when `state` was downgraded from a stale \"working\". */\n stale: boolean;\n /**\n * Its turn ended and its prompt is free, but something it started is still at it: a background agent (the state\n * reads working), or — `command` — a background command (a build, tests, a dev server: the state stays idle, so a\n * finished turn you haven't looked at still says so). What it is, when it says.\n */\n background?: { what: string | null; command?: boolean };\n}\n\n/** Transcript activity this long after a needs-input notification means\n * the question was answered. */\nexport const ANSWERED_AFTER_MS = 3_000;\n\nexport function effectiveStatus(\n status: SessionStatus,\n lastActivityMs: number,\n now: number = Date.now(),\n /** The newest transcript entry that is a turn's work (yours or Claude's:\n * `lastTurnEntryMs`), when the caller read it; 0 = unknown. */\n lastTurnEntryMs = 0,\n): EffectiveStatus {\n const last = Math.max(lastActivityMs, Date.parse(status.updatedAt) || 0);\n if (status.state === 'working' && now - last > STALE_WORKING_MS) {\n return { ...status, state: 'idle', seen: true, stale: true };\n }\n // Approving a permission prompt fires no hook until the turn ends, so a\n // blocked session would look blocked while it's working again. Claude\n // writing its transcript after the question is the tell.\n // Answered in its terminal: Claude wrote a turn's message (a tool result,\n // its reply) after the question. Its own lines — the away summary a few\n // minutes after every turn, the last-prompt / cost lines on exit — are no\n // answer, so only turn entries count (`lastTurnEntryMs`, when the caller\n // read them; the bare transcript time otherwise). Quiet 15 min: idle.\n const since = Date.parse(status.since) || 0;\n const answeredAt = lastTurnEntryMs || lastActivityMs;\n if (status.state === 'needs_input' && answeredAt > since + ANSWERED_AFTER_MS) {\n if (now - answeredAt > STALE_WORKING_MS) return { ...status, state: 'idle', seen: true, stale: true };\n return { ...status, state: 'working', seen: true, stale: false };\n }\n // Some turns fire no prompt hook: a `!` shell command and Claude's turn on\n // its output, or any turn while work's hooks were being reinstalled (a work\n // web restart). The session read \"idle\" while it worked. A message in its\n // transcript after the last turn ended is the tell; quiet for 15 min, it\n // decays like a working status.\n if (status.state === 'idle' && lastTurnEntryMs > idleFrom(status) + ANSWERED_AFTER_MS && now - lastTurnEntryMs <= STALE_WORKING_MS) {\n return { ...status, state: 'working', seen: true, stale: false };\n }\n return { ...status, stale: false };\n}\n\n/**\n * Claude Code's own word on a running Claude (~/.claude/sessions/<pid>.json,\n * via SessionClaudes) over what the hooks recorded, when it is newer: the\n * hooks miss turns (a work web restart, an interrupt, a Stop that handed\n * Claude more work), Claude Code's file doesn't. Busy → working, waiting →\n * needs input, idle → a working / needs-input record is over.\n *\n * And with nothing running for the session anywhere (`known`: the process\n * list was read; `hosted`: no PTY of ours either), it can't be working\n * or waiting: idle at once, not after 15 quiet minutes.\n */\nexport function withLiveClaude(\n status: EffectiveStatus,\n live: { state?: 'busy' | 'idle' | 'waiting' | 'shell'; stateAt?: number; waitingFor?: string } | null,\n opts: {\n known: boolean;\n hosted: boolean;\n /** A background agent its conversation started is still at it since its turn ended (asked only when it matters). */\n background?: () => { what: string | null } | null;\n /** The background commands its conversation has running, newest first, each in a line (asked only when it matters). */\n commands?: () => string[];\n },\n): EffectiveStatus {\n const recorded = Date.parse(status.updatedAt) || 0;\n // Claude Code's `shell`: no turn, its prompt free, a background command it started still running (reported: two\n // sessions running tests in the background read Idle). Newer than a working / needs-input record, that turn is over.\n // The state stays idle — Done and \"review\" still work — and the icon says In background, with what runs.\n if (live?.state === 'shell') {\n const over = (live.stateAt ?? 0) > recorded && (status.state === 'working' || status.state === 'needs_input');\n const base: EffectiveStatus = over ? { ...status, state: 'idle', seen: true, stale: true } : status;\n if (base.state !== 'idle') return base;\n const names = opts.commands?.() ?? [];\n const what = names.length > 1 ? `${names[0]} and ${names.length - 1} more` : (names[0] ?? null);\n return { ...base, background: { what, command: true } };\n }\n if (live?.state && (live.stateAt ?? 0) > recorded) {\n if (live.state === 'busy' && status.state !== 'working') return { ...status, state: 'working', seen: true, stale: false };\n if (live.state === 'waiting' && status.state !== 'needs_input') {\n return {\n ...status,\n state: 'needs_input',\n seen: false,\n stale: false,\n summary: live.waitingFor ? `Waiting for you: ${live.waitingFor}` : 'Waiting for you',\n };\n }\n if (live.state === 'idle' && (status.state === 'working' || status.state === 'needs_input'))\n return { ...status, state: 'idle', seen: true, stale: true };\n }\n // Its turn ended, but Claude Code is still busy (said before that end, so older than the hook) and a background\n // agent it started has written since: the turn handed its work to that agent, which is still at it (reported:\n // \"handing it to a background agent\" read Idle). Its end comes back as a new turn, and Claude Code says idle then.\n if (live?.state === 'busy' && status.state === 'idle') {\n const work = opts.background?.();\n // Working, but not on a turn of yours: its prompt is free (the dashboard says \"In background\", what it is).\n if (work) return { ...status, state: 'working', seen: true, stale: false, background: { what: work.what } };\n }\n if (!live && opts.known && !opts.hosted && (status.state === 'working' || status.state === 'needs_input')) {\n return { ...status, state: 'idle', seen: true, stale: true };\n }\n return status;\n}\n\n/** When an idle session's last turn ended: the Stop hook's time, else (a row from before it was kept) `since`. */\nexport function idleFrom(status: SessionStatus): number {\n return Date.parse(status.turnEndedAt ?? '') || Date.parse(status.since) || 0;\n}\n\n/**\n * The newest entry that is a turn's work: your prompt or `!` command and its\n * output, the agent's message or tool call, a tool's result, a background\n * task's result. Not what the agent writes around a turn (durations, hook\n * summaries, away summaries, PR links, titles), slash commands, compaction\n * or meta lines (the agent's mapping marks those: `meta`, no `turn`). Pure;\n * 0 when there is none.\n */\nexport function lastTurnEntryMs(entries: readonly ConversationEntry[]): number {\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i];\n if (e.meta) continue;\n if (e.role === 'other' && !e.turn) continue;\n const ms = Date.parse(e.at);\n if (ms) return ms;\n }\n return 0;\n}\n\n// ---- persistence ----------------------------------------------------------\n\n// One row per session in state.db's `session_status` (db.ts). Hooks for\n// different sessions touch different rows; same-session updates are\n// transactions, so two hooks racing can't lose an event.\n\nfunction isStatus(x: unknown): x is SessionStatus {\n const s = x as SessionStatus | null;\n return !!s && typeof s === 'object' && typeof s.state === 'string' && typeof s.updatedAt === 'string';\n}\n\nfunction readRow(d: Db, sessionId: string): SessionStatus | null {\n const r = d.prepare('SELECT data FROM session_status WHERE session_id = ?').get(sessionId) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return isStatus(s) ? s : null;\n}\n\nexport function readStatus(sessionId: string): SessionStatus | null {\n return withDb((d) => readRow(d, sessionId));\n}\n\nasync function updateStatus(\n sessionId: string,\n fn: (prev: SessionStatus | null) => SessionStatus | null,\n): Promise<{ prev: SessionStatus | null; next: SessionStatus | null }> {\n return tx((d) => {\n const prev = readRow(d, sessionId);\n const next = fn(prev);\n if (next) {\n d.prepare('INSERT OR REPLACE INTO session_status (session_id, data) VALUES (?, ?)').run(sessionId, JSON.stringify(next));\n }\n return { prev, next };\n });\n}\n\n/**\n * Apply a hook event and persist it, keeping the pre-event state in\n * `prevState` for the server's notification decision.\n */\nexport function recordStatusEvent(\n sessionId: string,\n event: StatusEvent,\n now: Date = new Date(),\n): Promise<{ prev: SessionStatus | null; next: SessionStatus | null }> {\n return updateStatus(sessionId, (prev) => ({\n ...applyStatusEvent(prev, event, now),\n // A Stop ends a turn even when no prompt hook said one began (a `!`\n // command, a background task's result): as far as notifying goes, it\n // was working — so you hear that it finished.\n prevState: event.kind === 'stop' && prev?.state === 'idle' ? 'working' : (prev?.state ?? null),\n }));\n}\n\n/**\n * Its Claude is in the middle of a turn: working, or stopped mid-turn at a\n * dialog for you (a permission prompt, a question) — a needs-input state\n * entered after the last turn ended. A finished turn that asks you something\n * (DECISION NEEDED, recorded by the Stop) is not: its turn is over. Stopping\n * a Claude mid-turn cuts the turn off (a pending tool call is lost), so the\n * merged-work archive waits for this, and only this.\n */\nexport function turnInProgress(s: Pick<SessionStatus, 'state' | 'since' | 'turnEndedAt'> | null): boolean {\n if (!s) return false;\n if (s.state === 'working') return true;\n if (s.state !== 'needs_input') return false;\n const ended = s.turnEndedAt ? Date.parse(s.turnEndedAt) : NaN;\n return !(ended >= Date.parse(s.since));\n}\n\n/**\n * Work stopped the session's Claude itself (idle sleep, `work stop`): the\n * Terminal tab's \"running in another terminal\" check (`claudeElsewhere`)\n * then ignores the turn that ended just before, and starts it again. A\n * session with no status yet has nothing that check could misread.\n */\nexport async function markAgentStopped(sessionId: string, now: Date = new Date()): Promise<void> {\n await updateStatus(sessionId, (prev) => (prev ? { ...prev, stoppedAt: now.toISOString() } : prev));\n}\n\n/** The user looked at it (opened it in the dashboard). */\nexport async function markSeen(sessionId: string): Promise<SessionStatus | null> {\n const { next } = await updateStatus(sessionId, (prev) =>\n prev && !prev.seen ? { ...prev, seen: true, updatedAt: new Date().toISOString() } : prev,\n );\n return next;\n}\n\n/**\n * Whether a status change deserves a desktop notification / status hook:\n * only on entering a state that wants the user — needs_input from anything\n * else, or idle out of a turn (a finished turn). Repeat events (a second\n * Stop, the 60 s idle nudge) stay silent.\n *\n * \"Out of a turn\" includes needs_input: approving a permission prompt fires\n * no hook, so a turn that paused for one is still stored as needs_input\n * when its Stop arrives — and that finish must notify like any other.\n */\nexport function notifyKindForTransition(\n prev: Pick<SessionStatus, 'state'> | null,\n next: Pick<SessionStatus, 'state'> | null,\n): 'idle' | 'needs_input' | null {\n if (!next) return null;\n if (next.state === 'needs_input' && prev?.state !== 'needs_input') return 'needs_input';\n if (next.state === 'idle' && (prev?.state === 'working' || prev?.state === 'needs_input')) return 'idle';\n return null;\n}\n","import { json, withDb } from '../platform/db.js';\nimport type { PrStageKind } from '../pr/pr-stage.js';\nimport { snoozeFor, snoozeUntil, type Snooze } from './snooze.js';\nimport { readStatus } from '../status/session-status.js';\n\n/** Snoozes, one per session, in state.db `session_snooze` (gone with the session: purgeSessionRows). */\n\nfunction isSnooze(v: unknown): v is Snooze {\n const o = v as Snooze | null;\n return !!o && typeof o === 'object' && (o.until === null || typeof o.until === 'string') && typeof o.at === 'string';\n}\n\nexport function readSnooze(sessionId: string): Snooze | null {\n const row = withDb(\n (d) => d.prepare('SELECT data FROM session_snooze WHERE session_id = ?').get(sessionId) as { data: string } | undefined,\n );\n const v = row ? json.parse(row.data) : null;\n return isSnooze(v) ? v : null;\n}\n\n/** Every session's snooze (one query for the whole session list). */\nexport function allSnoozes(): Map<string, Snooze> {\n const rows = withDb((d) => d.prepare('SELECT session_id, data FROM session_snooze').all() as Array<{ session_id: string; data: string }>);\n const out = new Map<string, Snooze>();\n for (const r of rows) {\n const v = json.parse(r.data);\n if (isSnooze(v)) out.set(r.session_id, v);\n }\n return out;\n}\n\nexport function saveSnooze(sessionId: string, snooze: Snooze): void {\n withDb((d) => d.prepare('INSERT OR REPLACE INTO session_snooze (session_id, data) VALUES (?, ?)').run(sessionId, JSON.stringify(snooze)));\n}\n\nexport function clearSnooze(sessionId: string): boolean {\n return withDb((d) => d.prepare('DELETE FROM session_snooze WHERE session_id = ?').run(sessionId).changes > 0);\n}\n\n/** A snooze asked for: one of the choices, or until a time. */\nexport type SnoozeRequest = { for: '2h' | 'tomorrow' | 'change' } | { until: string };\n\n/** Validate a request body as one; null when it isn't. */\nexport function cleanSnoozeRequest(raw: unknown): SnoozeRequest | null {\n const o = raw as Record<string, unknown> | null;\n if (!o || typeof o !== 'object') return null;\n if (o.for === '2h' || o.for === 'tomorrow' || o.for === 'change') return { for: o.for };\n if (typeof o.until === 'string' && o.until) return { until: o.until };\n return null;\n}\n\n/**\n * Snooze a session — the dashboard's menu and `work snooze` both. \"Until it\n * changes\" is taken against the status the hooks recorded (and the review\n * threads the caller knows of), as the check that ends it compares.\n */\nexport function requestSnooze(\n sessionId: string,\n req: SnoozeRequest,\n shown: { openReviewThreads?: number; prStage?: { kind: PrStageKind; key: string } | null } = {},\n now = new Date(),\n): { ok: true; snooze: Snooze } | { ok: false; error: string } {\n const snooze =\n 'until' in req\n ? snoozeUntil(req.until, now)\n : snoozeFor(\n req.for,\n { attention: readStatus(sessionId), openReviewThreads: shown.openReviewThreads ?? 0, prStage: shown.prStage },\n now,\n );\n if (!snooze) return { ok: false, error: 'not a time to snooze until: give one in the next 30 days' };\n saveSnooze(sessionId, snooze);\n return { ok: true, snooze };\n}\n","/**\n * Sessions being archived right now (archiveSession, from its first step to\n * its last). Nothing may start their Claude meanwhile: archiving stops it\n * first, and a Terminal tab still open on the session would otherwise start\n * it again a moment later — an archived session with a live Claude, put back\n * by the PTY host after every restart. ensurePty refuses them, and archived\n * ones (pty-pool.ts).\n *\n * In memory, per process: archiving runs in work web, which is also what\n * starts session Claudes.\n */\n\nconst inProgress = new Set<string>();\n/** Restores running now: every view lists the session again at once, as Restoring. */\nconst restoring = new Set<string>();\ntype Change = (sessionId: string, what: 'archiving' | 'restoring', on: boolean) => void;\nconst listeners = new Set<Change>();\n\n/** Told when a session starts and stops being archived or restored (work web broadcasts it: the rail shows it). Returns the unsubscribe. */\nexport function onArchivingChange(listener: Change): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n}\n\nfunction tell(sessionId: string, what: 'archiving' | 'restoring', on: boolean): void {\n for (const l of listeners) {\n try {\n l(sessionId, what, on);\n } catch {\n // A listener's trouble is never the archive's.\n }\n }\n}\n\nexport function isRestoring(sessionId: string): boolean {\n return restoring.has(sessionId);\n}\n\n/** Run `fn` (a Restore) with the session marked as being restored. */\nexport async function whileRestoring<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {\n restoring.add(sessionId);\n tell(sessionId, 'restoring', true);\n try {\n return await fn();\n } finally {\n restoring.delete(sessionId);\n tell(sessionId, 'restoring', false);\n }\n}\n\nexport function isArchiving(sessionId: string): boolean {\n return inProgress.has(sessionId);\n}\n\n/** Run `fn` with the session marked as being archived. */\nexport async function whileArchiving<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {\n inProgress.add(sessionId);\n tell(sessionId, 'archiving', true);\n try {\n return await fn();\n } finally {\n inProgress.delete(sessionId);\n tell(sessionId, 'archiving', false);\n }\n}\n\n/** Why a session's Claude can't be started now, or null. */\nexport function noClaudeBecause(session: { archivedAt?: string | null } | null, sessionId: string): string | null {\n if (isArchiving(sessionId)) return 'This session is being archived.';\n if (session?.archivedAt) return 'This session is archived. Restore it to continue the conversation.';\n return null;\n}\n","import type { ConversationEntry } from '../agents/types.js';\nimport { dayKey } from './work-time-view.js';\n\n/**\n * How long a session's Claude worked, from its transcripts — for a worklog,\n * or to see where the time went. Approximate by design: the time between\n * two transcript lines counts when the later one is Claude's own (its reply,\n * a tool's result), each gap at most STEP_CAP_MS — so your time reading and\n * typing isn't counted, and a permission prompt left an hour isn't an hour of\n * work. Pure: entries in, steps out.\n */\n\n/** The most one step counts for (a long test run still counts; a prompt waiting all afternoon doesn't). */\nexport const STEP_CAP_MS = 15 * 60_000;\n\n/** One step of Claude's: when it ended (ms) and how long it counted for. */\nexport type WorkStep = readonly [endMs: number, ms: number];\n\n/** The agent's own line: its message or tool call, or a tool's result coming back to it.\n * A subagent's lines count too (unlike the digest's prompts): its work is\n * the agent's work, and the steps of one file never overlap, so nothing is\n * counted twice. */\nfunction isAgents(e: ConversationEntry): boolean {\n return e.role === 'agent' || e.role === 'tool' || e.role === 'tool-result';\n}\n\n/**\n * The steps in `entries` (in file order), continuing from `prevMs` — the\n * time of the line before them, when they continue a file already read.\n * Returns the steps and the time of the last line, to continue from.\n */\nexport function workSteps(\n entries: readonly ConversationEntry[],\n prevMs: number | null = null,\n): { steps: WorkStep[]; lastMs: number | null } {\n const steps: WorkStep[] = [];\n let prev = prevMs;\n for (const e of entries) {\n const ts = Date.parse(e.at);\n if (!Number.isFinite(ts)) continue;\n if (prev !== null && isAgents(e)) {\n const gap = ts - prev;\n if (gap > 0) steps.push([ts, Math.min(gap, STEP_CAP_MS)]);\n }\n // Lines can arrive a little out of order (a subagent's): never step back.\n prev = prev === null ? ts : Math.max(prev, ts);\n }\n return { steps, lastMs: prev };\n}\n\n/**\n * Steps from several transcripts of one session (two Claudes on one folder\n * at once, a conversation resumed beside another) as one timeline: time\n * covered by both counts once. Pure.\n */\nexport function mergeSteps(steps: readonly WorkStep[]): WorkStep[] {\n const spans = steps.map(([end, ms]) => [end - ms, end] as [number, number]).sort((a, b) => a[0] - b[0]);\n const out: WorkStep[] = [];\n let cur: [number, number] | null = null;\n for (const [start, end] of spans) {\n if (cur && start <= cur[1]) cur[1] = Math.max(cur[1], end);\n else {\n if (cur) out.push([cur[1], cur[1] - cur[0]]);\n cur = [start, end];\n }\n }\n if (cur) out.push([cur[1], cur[1] - cur[0]]);\n return out;\n}\n\n/** Time worked in steps ending at or after `sinceMs` (and before `untilMs`). */\nexport function workedBetween(steps: readonly WorkStep[], sinceMs = 0, untilMs = Infinity): number {\n let ms = 0;\n for (const [end, d] of steps) if (end >= sinceMs && end < untilMs) ms += d;\n return ms;\n}\n\n/** Time worked per local day (`YYYY-MM-DD`), newest first, for the days after `sinceMs`. */\nexport function workedByDay(steps: readonly WorkStep[], sinceMs = 0): Array<{ day: string; ms: number }> {\n const by = new Map<string, number>();\n for (const [end, d] of steps) {\n if (end < sinceMs) continue;\n const k = dayKey(end);\n by.set(k, (by.get(k) ?? 0) + d);\n }\n return [...by].map(([day, ms]) => ({ day, ms })).sort((a, b) => b.day.localeCompare(a.day));\n}\n","import type { ConversationEntry } from '../agents/types.js';\nimport { workedBetween, type WorkStep } from './work-time.js';\nimport type { DiffStat, DigestSession, SessionCi } from '../api-types.js';\n\n/**\n * \"What did each session do today?\" — for a standup, or for coming back\n * after a weekend. Built from what's already on disk: the prompts you gave\n * (the transcripts), the turns it finished (checkpoints, named when a name\n * was already made — the digest never runs Claude), where it stands now,\n * its diff and its PRs. The assembly is pure; web-server.ts feeds it.\n */\n\nexport const MAX_PROMPTS = 12;\nconst MAX_PROMPT_CHARS = 240;\n\n/** What `checkpoint-summary.ts` names a turn when Claude was unavailable:\n * \"3 files · +52 −8\" or \"no changes\". A size, not what the turn did. */\nexport const HEURISTIC_LABEL_RE = /^(\\d+ files? · \\+\\d+ −\\d+|no changes)$/;\n\n/** One line of at most MAX_PROMPT_CHARS. */\nfunction clip(text: string): string {\n const line = text.replace(/\\s+/g, ' ').trim();\n return line.length > MAX_PROMPT_CHARS ? line.slice(0, MAX_PROMPT_CHARS - 1).trimEnd() + '…' : line;\n}\n\n/**\n * Of a conversation's entries, only what the digest reads — your prompts.\n * A day's conversations hold tool output too (megabytes per session); the\n * digest kept all of it in memory for every session in the window, for the\n * sake of a few lines.\n */\nexport function promptEntries(entries: readonly ConversationEntry[]): ConversationEntry[] {\n return entries.filter((e) => e.role === 'you' && !e.sidechain && e.text !== '');\n}\n\n/** Your prompts after `sinceMs`, oldest first. The same entry seen twice\n * (by its id, else time + text) counts once; typing \"commit\" three times\n * is three prompts. */\nexport function promptsSince(transcripts: readonly (readonly ConversationEntry[])[], sinceMs: number): Array<{ ts: string; text: string }> {\n const out: Array<{ ts: string; text: string }> = [];\n const seen = new Set<string>();\n for (const entries of transcripts) {\n for (const e of entries) {\n const ts = Date.parse(e.at);\n if (!(ts >= sinceMs)) continue;\n if (e.role !== 'you' || e.sidechain || !e.text) continue;\n const line = clip(e.text);\n const key = e.id ? e.id : `${ts}|${line}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push({ ts: new Date(ts).toISOString(), text: line });\n }\n }\n return out.sort((a, b) => a.ts.localeCompare(b.ts));\n}\n\nexport interface DigestInput {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n lastAccessedAt: string;\n archivedAt: string | null;\n status: { state: 'working' | 'needs_input' | 'idle'; summary?: string; updatedAt: string } | null;\n /** Entries of the transcripts written to since the window opened. */\n transcripts: ConversationEntry[][];\n /** A transcript was too large to read back to the window's start. */\n transcriptsPartial?: boolean;\n /** Claude's work steps in those transcripts (work-time.ts). */\n work?: WorkStep[][];\n /** The session scope's checkpoints (id 0 is the baseline, not a turn). */\n checkpoints: Array<{ id: number; ts: string; label?: string }>;\n diffStat: DiffStat | null;\n ci: SessionCi | null;\n}\n\n/** One digest row, or null when the session did nothing in the window. */\nexport function digestSession(s: DigestInput, sinceMs: number): DigestSession | null {\n const prompts = promptsSince(s.transcripts, sinceMs);\n const turns = s.checkpoints.filter((c) => c.id > 0 && Date.parse(c.ts) >= sinceMs);\n const archivedInWindow = !!s.archivedAt && Date.parse(s.archivedAt) >= sinceMs;\n const prs = (s.ci?.repos ?? [])\n .filter((r) => r.pr)\n .map((r) => ({\n repo: r.name,\n number: r.pr!.number,\n url: r.pr!.url,\n state: r.pr!.state,\n ...(r.pr!.mergedAt ? { mergedAt: r.pr!.mergedAt } : {}),\n }));\n const mergedInWindow = prs.some((p) => p.mergedAt && Date.parse(p.mergedAt) >= sinceMs);\n if (prompts.length === 0 && turns.length === 0 && !archivedInWindow && !mergedInWindow) return null;\n\n const times = [\n ...prompts.map((p) => Date.parse(p.ts)),\n ...turns.map((t) => Date.parse(t.ts)),\n ...prs.map((p) => (p.mergedAt && Date.parse(p.mergedAt) >= sinceMs ? Date.parse(p.mergedAt) : 0)),\n archivedInWindow ? Date.parse(s.archivedAt!) : 0,\n s.status ? Date.parse(s.status.updatedAt) || 0 : 0,\n ];\n return {\n sessionId: s.sessionId,\n target: s.target,\n branch: s.branch,\n isGroup: s.isGroup,\n state: s.status?.state ?? null,\n ...(s.status?.summary ? { summary: s.status.summary } : {}),\n prompts: prompts.slice(-MAX_PROMPTS),\n morePrompts: Math.max(0, prompts.length - MAX_PROMPTS),\n turns: turns.length,\n turnLabels: turns.map((t) => t.label?.trim()).filter((l): l is string => !!l && l !== 'Initial' && !HEURISTIC_LABEL_RE.test(l)),\n ...(s.transcriptsPartial ? { partial: true } : {}),\n diffStat: s.diffStat,\n prs,\n archivedAt: s.archivedAt,\n lastActivity: new Date(Math.max(...times)).toISOString(),\n ...(() => {\n const ms = (s.work ?? []).reduce((n, steps) => n + workedBetween(steps, sinceMs), 0);\n return ms > 0 ? { workedMs: ms } : {};\n })(),\n };\n}\n\n/** Rows for every session that did something, most recent first. */\nexport function buildDigest(inputs: DigestInput[], sinceMs: number): DigestSession[] {\n return inputs\n .map((s) => digestSession(s, sinceMs))\n .filter((d): d is DigestSession => d !== null)\n .sort((a, b) => b.lastActivity.localeCompare(a.lastActivity));\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport zlib from 'node:zlib';\nimport { promisify } from 'node:util';\nimport { getConfigDir } from '../platform/config.js';\nimport { agentOf } from '../agents/index.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { archiveRoot, readArchive, readArchivedTranscript } from '../archive/session-archive.js';\nimport { matchingLines, queryWords, snippet } from '../archive/archive-search.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport type { ConversationHit } from '../api-types.js';\nimport type { ConversationPrLink } from '../agents/types.js';\nimport { noteSessionPrs, readSessionPrs } from '../pr/session-prs.js';\nimport { report } from '../platform/report.js';\n\n/**\n * work's own copy of every session's Claude conversations, at\n * ~/.work/conversations/<session id>/<transcript>.jsonl. Claude Code\n * deletes its transcripts after a while (`cleanupPeriodDays`, 30 days by\n * default); this copy stays as long as the session, so a session's whole\n * history can be searched (`searchConversations`, GET\n * /api/conversations/search, `work search`). Disk is cheap here; nothing of\n * it is held in memory.\n *\n * Synced incrementally: a transcript only ever grows, so only its new bytes\n * are appended (a source that got smaller was replaced: copied whole). Run\n * after each Claude turn (the status hook) and by a sweep at start and every\n * 30 minutes. Removing the session removes it (sessionStatePaths).\n */\n\nconst gunzip = promisify(zlib.gunzip);\n\nexport const conversationRoot = (): string => path.join(getConfigDir(), 'conversations');\nexport const conversationDirFor = (id: string, root = conversationRoot()): string => path.join(root, id);\n\nexport interface SyncResult {\n files: number;\n bytes: number;\n /** PRs its agent's new lines name as the session's (`AgentConversation.prLinks`), put on its list (session-prs.ts). */\n prs?: number;\n}\n\n/**\n * Bring a session's copy up to date with its transcripts. The new lines are read for the PRs they name as the\n * session's (`prLinks`) on the way, and those go on the session's PR list; a session whose list was never filled\n * from its whole conversation has its copy read once for them (`scanned`).\n */\nexport async function syncConversation(\n s: WorktreeSession,\n root = conversationRoot(),\n sources = agentOf(s).conversation?.files(s) ?? [],\n prLinks: ((text: string) => ConversationPrLink[]) | null | undefined = agentOf(s).conversation?.prLinks,\n): Promise<SyncResult> {\n const id = sessionIdFor(s);\n const dir = conversationDirFor(id, root);\n const out: SyncResult = { files: 0, bytes: 0 };\n const found: ConversationPrLink[] = [];\n const scan = prLinks ? lineScanner((text) => found.push(...prLinks(text))) : null;\n for (const src of sources) {\n const dest = path.join(dir, path.basename(src.file));\n // Packed while it was quiet (compressQuietCopies): unchanged since, it\n // stays packed; the conversation went on, so unpack it and copy the rest.\n const packed = await packedState(dest, src.mtimeMs);\n if (packed === 'current') continue;\n if (packed === 'stale') await unpack(dest);\n let have = 0;\n let haveMtime = 0;\n try {\n const st = await fs.promises.stat(dest);\n [have, haveMtime] = [st.size, st.mtimeMs];\n } catch {\n /* not copied yet */\n }\n if (have === src.size) {\n // Complete; only its time may be off (a copy from before times were kept).\n if (Math.abs(haveMtime - src.mtimeMs) > 1000)\n await fs.promises.utimes(dest, new Date(), new Date(src.mtimeMs)).catch(() => undefined);\n continue;\n }\n await fs.promises.mkdir(dir, { recursive: true });\n if (have > src.size) {\n // Smaller than our copy: the file was replaced. Copy it whole (its lines are read by the scan below, or were).\n await fs.promises.copyFile(src.file, dest);\n out.bytes += src.size;\n } else {\n const feed = scan?.file();\n out.bytes += await appendRange(src.file, dest, have, src.size, feed);\n feed?.end();\n }\n // The copy's time is the conversation's last write, not when we copied\n // it: search orders by it, and shows it.\n await fs.promises.utimes(dest, new Date(), new Date(src.mtimeMs)).catch(() => undefined);\n out.files++;\n }\n if (prLinks) {\n const prs = await notePrLinks(s, id, dir, found, prLinks);\n if (prs) out.prs = prs;\n }\n return out;\n}\n\n/**\n * Feeds text in pieces to `onLines` as whole lines: a line cut at a piece's end waits for the rest. The first line of\n * a range that started mid-line is cut at its start — whatever reads it skips a line that doesn't parse.\n */\nfunction lineScanner(onLines: (text: string) => void) {\n return {\n file() {\n let carry = '';\n return {\n push(buf: Buffer) {\n const text = carry + buf.toString('utf8');\n const nl = text.lastIndexOf('\\n');\n if (nl < 0) {\n carry = text.length > 1_000_000 ? '' : text; // a line this long isn't one of the short lines read here\n return;\n }\n onLines(text.slice(0, nl));\n carry = text.slice(nl + 1);\n },\n end() {\n if (carry) onLines(carry);\n carry = '';\n },\n };\n },\n };\n}\n\n/** The new lines' PRs onto the session's list; the first time, every PR its whole kept copy names. Returns how many it named. */\nasync function notePrLinks(\n s: WorktreeSession,\n id: string,\n dir: string,\n found: ConversationPrLink[],\n prLinks: (text: string) => ConversationPrLink[],\n): Promise<number> {\n if (s.archivedAt) return 0;\n const whole = rescanPrLinks.has(id) || !readSessionPrs(id)?.scanned;\n const links = [...found];\n // Scanned only when every file of the copy was read: one that couldn't be is read again next time.\n let readAll = true;\n if (whole) {\n // Read off the event loop, one file at a time (a long session's copy is tens of megabytes).\n const names = await fs.promises.readdir(dir).catch((err: NodeJS.ErrnoException) => {\n if (err.code !== 'ENOENT') readAll = false;\n return [] as string[];\n });\n for (const n of names.filter((x) => x.endsWith('.jsonl') || x.endsWith('.jsonl.gz'))) {\n try {\n const buf = await fs.promises.readFile(path.join(dir, n));\n links.push(...prLinks((n.endsWith('.gz') ? await gunzip(buf) : buf).toString('utf8')));\n } catch (err) {\n // Vanished (packed meanwhile, or gone): its lines are in the other file or nowhere. Anything else: again.\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') readAll = false;\n }\n }\n }\n if (!links.length && !whole) return 0;\n try {\n notedPrLinks(id, links, whole && readAll);\n } catch (err) {\n // The new lines are copied already, so the next sync won't see them again: it reads the whole copy instead.\n rescanPrLinks.add(id);\n report('warn', `couldn't keep the PRs named in ${id}'s conversation (${(err as Error).message}); read again at the next sync`);\n return 0;\n }\n if (whole && readAll) rescanPrLinks.delete(id);\n return new Set(links.map((l) => l.url)).size;\n}\n\n/** Sessions whose PR links couldn't be kept: their whole copy is read again at the next sync (this process's memory). */\nconst rescanPrLinks = new Set<string>();\n\nfunction notedPrLinks(id: string, links: ConversationPrLink[], scanned: boolean): void {\n noteSessionPrs(\n id,\n links.map((l) => ({\n url: l.url,\n number: l.number,\n ...(l.repo ? { repoId: l.repo.toLowerCase() } : {}),\n source: 'agent' as const,\n ...(l.at ? { at: l.at } : {}),\n })),\n new Date(),\n scanned ? { scanned: true } : {},\n );\n}\n\n/** A copy kept gzipped: its time is the conversation's last write, so a newer source means it went on. */\nasync function packedState(dest: string, srcMtimeMs: number): Promise<'none' | 'current' | 'stale'> {\n try {\n const st = await fs.promises.stat(`${dest}.gz`);\n return srcMtimeMs <= st.mtimeMs + 1000 ? 'current' : 'stale';\n } catch {\n return 'none';\n }\n}\n\n/** Back to a plain copy (the conversation went on): written beside it, then put in place. */\nasync function unpack(dest: string): Promise<void> {\n const gz = `${dest}.gz`;\n const tmp = `${dest}.unpack-${process.pid}`;\n await fs.promises.writeFile(tmp, zlib.gunzipSync(await fs.promises.readFile(gz)));\n await fs.promises.rename(tmp, dest);\n await fs.promises.rm(gz, { force: true });\n}\n\n/** How long a conversation stays untouched before its copy is gzipped. */\nexport const PACK_QUIET_MS = 2 * 24 * 3600_000;\n\n/**\n * Gzip the copies of conversations nobody has written to for a while\n * (JSON lines shrink about tenfold). Lossless: search reads `.gz`, and a\n * sync unpacks one whose conversation goes on. Written beside it and\n * renamed, so a reader never sees half a file; its time stays the\n * conversation's last write.\n */\nexport async function compressQuietCopies(\n root = conversationRoot(),\n now = Date.now(),\n quietMs = PACK_QUIET_MS,\n): Promise<{ files: number; bytesSaved: number }> {\n const out = { files: 0, bytesSaved: 0 };\n let dirs: string[];\n try {\n dirs = await fs.promises.readdir(root);\n } catch {\n return out;\n }\n for (const d of dirs) {\n const dir = path.join(root, d);\n let names: string[];\n try {\n names = (await fs.promises.readdir(dir)).filter((n) => n.endsWith('.jsonl'));\n } catch {\n continue;\n }\n for (const n of names) {\n const file = path.join(dir, n);\n try {\n const st = await fs.promises.stat(file);\n if (now - st.mtimeMs < quietMs) continue;\n const packed = zlib.gzipSync(await fs.promises.readFile(file));\n const tmp = `${file}.gz.tmp-${process.pid}`;\n await fs.promises.writeFile(tmp, packed);\n await fs.promises.utimes(tmp, new Date(), new Date(st.mtimeMs));\n await fs.promises.rename(tmp, `${file}.gz`);\n await fs.promises.rm(file, { force: true });\n out.files++;\n out.bytesSaved += st.size - packed.length;\n } catch {\n /* busy or gone: next sweep */\n }\n }\n }\n return out;\n}\n\n/**\n * Copy bytes [from, to) of `src` to the same offsets of `dest`; returns how\n * many. Written at the source's offsets, not appended: two syncs of one\n * session at once (a turn's and the sweep's, or `work search` beside work\n * web) write the same bytes to the same place instead of doubling lines.\n */\nasync function appendRange(src: string, dest: string, from: number, to: number, feed?: { push(buf: Buffer): void }): Promise<number> {\n await (await fs.promises.open(dest, 'a')).close(); // create it if new\n const [inp, out] = [await fs.promises.open(src, 'r'), await fs.promises.open(dest, 'r+')];\n try {\n const chunk = 4 * 1024 * 1024;\n let done = 0;\n for (let pos = from; pos < to; pos += chunk) {\n const buf = Buffer.alloc(Math.min(chunk, to - pos));\n const { bytesRead } = await inp.read(buf, 0, buf.length, pos);\n if (bytesRead === 0) break;\n await out.write(buf, 0, bytesRead, pos);\n feed?.push(buf.subarray(0, bytesRead));\n done += bytesRead;\n }\n return done;\n } finally {\n await inp.close();\n await out.close();\n }\n}\n\n/** Sync many sessions, a few at a time. */\nexport async function syncConversations(\n sessions: WorktreeSession[],\n root = conversationRoot(),\n concurrency = 3,\n): Promise<SyncResult & { sessions: number }> {\n const total = { files: 0, bytes: 0, sessions: 0 };\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, sessions.length) }, async () => {\n for (let i = next++; i < sessions.length; i = next++) {\n const r = await syncConversation(sessions[i], root).catch(() => ({ files: 0, bytes: 0 }));\n total.files += r.files;\n total.bytes += r.bytes;\n if (r.files) total.sessions++;\n }\n }),\n );\n return total;\n}\n\nconst MAX_SESSIONS = 20;\nconst SNIPPETS_PER_SESSION = 3;\n\n/** A session's transcript texts from its copy (plain or gzipped), newest first. */\nfunction storedTranscripts(dir: string): Array<{ mtimeMs: number; read: () => string | null }> {\n let names: string[];\n try {\n names = fs.readdirSync(dir).filter((n) => n.endsWith('.jsonl') || n.endsWith('.jsonl.gz'));\n } catch {\n return [];\n }\n return names\n .map((n) => {\n const file = path.join(dir, n);\n let mtimeMs = 0;\n try {\n mtimeMs = fs.statSync(file).mtimeMs;\n } catch {\n /* vanished */\n }\n const read = () => {\n try {\n const buf = fs.readFileSync(file);\n return (n.endsWith('.gz') ? zlib.gunzipSync(buf) : buf).toString('utf8');\n } catch {\n return null;\n }\n };\n return { mtimeMs, read };\n })\n .sort((a, b) => b.mtimeMs - a.mtimeMs);\n}\n\n/**\n * \"What did we do about X?\" across every session's kept conversation — live\n * and archived (an archive made before this store existed is read from its\n * archive copy). Every word must appear in one message (yours or Claude's)\n * or in an archive's written summary. Most recently active sessions first,\n * up to 20.\n */\nexport async function searchConversations(\n query: string,\n opts: { sessions: WorktreeSession[]; root?: string; archive?: string },\n): Promise<ConversationHit[]> {\n const { words, jsonWords } = queryWords(query);\n if (words.length === 0) return [];\n const root = opts.root ?? conversationRoot();\n const archive = opts.archive ?? archiveRoot();\n const candidates = opts.sessions.map((s) => {\n const id = sessionIdFor(s);\n const stored = storedTranscripts(conversationDirFor(id, root));\n const rec = readArchive(id, archive);\n const lastMs = Math.max(0, ...stored.map((t) => t.mtimeMs), rec ? Date.parse(rec.archivedAt) || 0 : 0);\n // Its lines read as its agent writes them; none when work can't read that agent's conversations.\n const entries = agentOf(s).conversation?.entries ?? (() => []);\n return { s, id, stored, rec, lastMs, entries };\n });\n candidates.sort((a, b) => b.lastMs - a.lastMs);\n const hits: ConversationHit[] = [];\n for (const c of candidates) {\n if (hits.length >= MAX_SESSIONS) break;\n const snippets: ConversationHit['snippets'] = [];\n const written = c.rec?.summary.written;\n if (written && words.every((w) => written.toLowerCase().includes(w))) {\n snippets.push({ role: 'summary', text: snippet(written, words), at: c.rec!.archivedAt });\n }\n // An archived session reads its archive (complete as of archiving; from\n // before this store existed too), a live one its own copy. Each falls\n // back to the other when it has nothing readable (archive transcripts\n // dropped by config, no sync yet).\n const fromArchive = (c.rec?.transcripts ?? []).map((t) => () => readArchivedTranscript(c.id, t.file, archive));\n const fromStore = c.stored.map((t) => t.read);\n const [first, second] = c.s.archivedAt ? [fromArchive, fromStore] : [fromStore, fromArchive];\n for (const texts of [first, second]) {\n let readAny = false;\n for (const read of texts) {\n if (snippets.length >= SNIPPETS_PER_SESSION) break;\n const raw = read();\n if (raw === null) continue;\n readAny = true;\n await new Promise((r) => setImmediate(r)); // a big history doesn't hold up the server\n snippets.push(...matchingLines(raw, words, jsonWords, SNIPPETS_PER_SESSION - snippets.length, c.entries));\n }\n if (readAny) break;\n }\n if (!snippets.length) continue;\n hits.push({\n sessionId: c.id,\n target: c.s.target,\n branch: c.s.branch,\n archived: !!c.s.archivedAt,\n archivedAt: c.s.archivedAt ?? null,\n worktreeRemoved: !!c.rec?.worktreeRemoved && !!c.s.archivedAt,\n lastAt: c.lastMs ? new Date(c.lastMs).toISOString() : null,\n snippets,\n });\n }\n return hits;\n}\n","import type { ConversationEntry } from '../agents/types.js';\n\n/**\n * Matching a query in a conversation: every word of the query must appear\n * in one message (yours or its agent's). Used by the conversation search\n * (conversation-store.ts) over kept and archived conversations; the lines\n * are read through the session's agent (agents/: `entries`).\n */\n\nconst SNIPPET_CHARS = 220;\n\n/** A readable message: your prompt, or the agent's text — not tool calls, results, a subagent's lines or tagged echoes. */\nexport function messageOf(e: ConversationEntry): { role: 'you' | 'claude'; text: string } | null {\n if (e.sidechain || (e.role !== 'you' && e.role !== 'agent')) return null;\n const text = e.text.trim();\n if (!text || text.startsWith('<')) return null; // tagged command echoes, reminders\n return { role: e.role === 'you' ? 'you' : 'claude', text };\n}\n\n/** The part of `text` around the first query word, one line. */\nexport function snippet(text: string, words: string[]): string {\n const flat = text.replace(/\\s+/g, ' ');\n const lower = flat.toLowerCase();\n const at = Math.max(0, lower.indexOf(words[0]));\n const start = Math.max(0, at - 60);\n const cut = flat.slice(start, start + SNIPPET_CHARS);\n return (start > 0 ? '…' : '') + cut + (start + SNIPPET_CHARS < flat.length ? '…' : '');\n}\n\n/** A query's words, lower case, and as JSON writes them (`\\` and `\"` escaped) for the raw-line pre-filter. */\nexport function queryWords(query: string): { words: string[]; jsonWords: string[] } {\n const words = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((w) => w.length > 0);\n return { words, jsonWords: words.map((w) => JSON.stringify(w).slice(1, -1)) };\n}\n\n/** Up to `max` messages of a transcript's text in which every word appears (yours or Claude's). */\nexport function matchingLines(\n raw: string,\n words: string[],\n jsonWords: string[],\n max: number,\n entries: (lines: readonly unknown[]) => ConversationEntry[],\n): Array<{ role: 'you' | 'claude'; text: string; at: string | null }> {\n const out: Array<{ role: 'you' | 'claude'; text: string; at: string | null }> = [];\n if (max <= 0) return out;\n for (const line of raw.split('\\n')) {\n if (out.length >= max) break;\n if (!line) continue;\n const lower = line.toLowerCase();\n if (!jsonWords.every((w) => lower.includes(w))) continue; // cheap pre-filter on the raw JSON line\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n continue;\n }\n for (const e of entries([parsed])) {\n const m = messageOf(e);\n if (!m || !words.every((w) => m.text.toLowerCase().includes(w))) continue;\n out.push({ role: m.role, text: snippet(m.text, words), at: e.at || null });\n break; // one hit per line\n }\n }\n return out;\n}\n","import type { PrLink } from '../types.js';\n\n/**\n * GitHub origins and pull request links. Pure and import-free (types only):\n * the SPA reads PR links with it too (`core/hosts/links.ts`).\n */\n\n/** GitHub review-thread node ids. Checked before a thread id reaches gh or the database. */\nexport const GITHUB_THREAD_ID = /^PRRT_[A-Za-z0-9_-]{4,120}$/;\n\n/** An origin on github.com (https, ssh or git@ form). */\nexport function onGithub(origin: string): boolean {\n return /(^|[@/.])github\\.com[:/]/i.test(origin);\n}\n\n/** `owner/name` (lower case) of an origin on github.com; null for another host. */\nexport function githubRepoId(origin: string): string | null {\n if (!onGithub(origin)) return null;\n const m = /[:/]([^/:]+)\\/([^/]+?)(?:\\.git)?\\/?$/.exec(origin.trim());\n return m ? `${m[1]}/${m[2]}`.toLowerCase() : null;\n}\n\n/** A GitHub pull request link (`https://github.com/owner/repo/pull/123`, any tail, scheme optional); null for anything else. */\nexport function parseGithubPrUrl(text: string): PrLink | null {\n const m = /^(?:https?:\\/\\/)?(?:www\\.)?github\\.com\\/([\\w.-]+)\\/([\\w.-]+)\\/pull\\/(\\d+)(?:[/?#].*)?$/i.exec(text.trim());\n if (!m) return null;\n const number = Number(m[3]);\n return {\n repoId: `${m[1]}/${m[2]}`.toLowerCase(),\n number,\n url: `https://github.com/${m[1]}/${m[2]}/pull/${number}`,\n label: `${m[2]}#${number}`,\n };\n}\n","import type { PrLink } from '../types.js';\n\n/**\n * Azure DevOps origins, pull request links and review-thread ids. Pure and\n * import-free (types only): the SPA reads links and thread ids with it too\n * (`core/hosts/links.ts`).\n *\n * A repo is `org/project/repo` (lower case: its id here). Origins:\n * https://dev.azure.com/{org}/{project}/_git/{repo} (also `{user}@dev.azure.com`)\n * https://{org}.visualstudio.com/[DefaultCollection/]{project}/_git/{repo}\n * git@ssh.dev.azure.com:v3/{org}/{project}/{repo}\n * {org}@vs-ssh.visualstudio.com:v3/{org}/{project}/{repo}\n */\n\nexport interface AzureRepo {\n org: string;\n project: string;\n repo: string;\n /** The org's URL, as `az --org` takes it. */\n orgUrl: string;\n}\n\nconst dec = (s: string) => {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n};\nconst strip = (s: string) => s.replace(/\\.git$/, '').replace(/\\/+$/, '');\n\n/**\n * What an org, a project and a repo may be called: Azure DevOps' own rules (an org: letters, digits and\n * hyphens; a project or repo: none of `\\ / : * ? \" ' < > ; # $ { } , + = [ ] |`, nor a control character),\n * plus none of `% & ^ !`. These names reach `az`'s argv and its REST routes, so anything else isn't a repo here.\n */\nconst ORG_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,49}$/;\nconst PART_NAME = /^[^\\\\/:*?\"'<>;#$*{},+=[\\]|%&^!\\x00-\\x1f\\x7f]{1,128}$/;\nexport const azureNameOk = (org: string, project: string, repo: string): boolean =>\n ORG_NAME.test(org) && PART_NAME.test(project) && PART_NAME.test(repo) && project.trim() === project && repo.trim() === repo;\n\n/** The org of an org URL `az --org` takes, only in the forms Azure DevOps has: `https://dev.azure.com/<org>`, `https://<org>.visualstudio.com`. */\nexport function azureOrgOf(orgUrl: string): string | null {\n const m = /^https:\\/\\/dev\\.azure\\.com\\/([^/]+)$/.exec(orgUrl) ?? /^https:\\/\\/([^./]+)\\.visualstudio\\.com$/.exec(orgUrl);\n return m && ORG_NAME.test(m[1]) ? m[1] : null;\n}\n\nfunction repoOf(org: string, project: string, repo: string, orgUrl: string): AzureRepo | null {\n const r = { org: dec(org), project: dec(project), repo: dec(strip(repo)), orgUrl };\n return azureNameOk(r.org, r.project, r.repo) && azureOrgOf(orgUrl) === r.org ? r : null;\n}\n\n/** An origin on Azure DevOps, read; null for anything else (and for names Azure DevOps wouldn't have). */\nexport function parseAzureOrigin(origin: string): AzureRepo | null {\n const o = origin.trim();\n let m = /^https?:\\/\\/(?:[^@/]+@)?dev\\.azure\\.com\\/([^/]+)\\/([^/]+)\\/_git\\/([^/?#]+)/i.exec(o);\n if (m) return repoOf(m[1], m[2], m[3], `https://dev.azure.com/${m[1]}`);\n m = /^https?:\\/\\/(?:[^@/]+@)?([^./]+)\\.visualstudio\\.com\\/(?:DefaultCollection\\/)?([^/]+)\\/_git\\/([^/?#]+)/i.exec(o);\n if (m) return repoOf(m[1], m[2], m[3], `https://${m[1]}.visualstudio.com`);\n m = /^(?:ssh:\\/\\/)?[^@]+@ssh\\.dev\\.azure\\.com[:/]v3\\/([^/]+)\\/([^/]+)\\/([^/]+)$/i.exec(o);\n if (m) return repoOf(m[1], m[2], m[3], `https://dev.azure.com/${m[1]}`);\n m = /^(?:ssh:\\/\\/)?[^@]+@vs-ssh\\.visualstudio\\.com[:/]v3\\/([^/]+)\\/([^/]+)\\/([^/]+)$/i.exec(o);\n if (m) return repoOf(m[1], m[2], m[3], `https://${m[1]}.visualstudio.com`);\n return null;\n}\n\n/** An origin on Azure DevOps. */\nexport const onAzure = (origin: string) => parseAzureOrigin(origin) !== null;\n\n/** `org/project/repo` (lower case) of an Azure DevOps origin; null for another host. */\nexport function azureRepoId(origin: string): string | null {\n const r = parseAzureOrigin(origin);\n return r ? `${r.org}/${r.project}/${r.repo}`.toLowerCase() : null;\n}\n\n/** The repo's web address (its PRs live under `/pullrequest/<id>`). */\nexport function azureWebUrl(r: Pick<AzureRepo, 'orgUrl' | 'project' | 'repo'>): string {\n return `${r.orgUrl}/${encodeURIComponent(r.project)}/_git/${encodeURIComponent(r.repo)}`;\n}\n\n/** An Azure DevOps pull request link (any tail); null for anything else. */\nexport function parseAzurePrUrl(text: string): (PrLink & { repo: AzureRepo }) | null {\n const t = text.trim();\n const m = /^(https?:\\/\\/[^?#]+\\/_git\\/[^/?#]+)\\/pullrequest\\/(\\d+)(?:[/?#].*)?$/i.exec(t);\n if (!m) return null;\n const repo = parseAzureOrigin(m[1]);\n if (!repo) return null;\n const number = Number(m[2]);\n return {\n repoId: `${repo.org}/${repo.project}/${repo.repo}`.toLowerCase(),\n number,\n url: `${azureWebUrl(repo)}/pullrequest/${number}`,\n label: `${repo.repo}!${number}`,\n repo,\n };\n}\n\n/**\n * A review thread's id here: Azure DevOps numbers threads per pull request,\n * so the id carries where it is — `AZT_<org/project/repo, base64url>_<pr>_<thread>` —\n * and any thread can be answered from any folder, like GitHub's global ids.\n */\nexport const AZURE_THREAD_ID = /^AZT_[A-Za-z0-9_-]{2,400}_\\d{1,9}_\\d{1,9}$/;\n\nconst b64url = (s: string) => {\n const bytes = new TextEncoder().encode(s);\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n};\nconst unb64url = (s: string) => {\n const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'));\n return new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));\n};\n\n/** The `org/project/repo` id (lower case) of the repo a thread id is on; null when it isn't a valid one. */\nexport function azureThreadRepoId(id: string): string | null {\n const t = parseAzureThreadId(id);\n const org = t ? azureOrgOf(t.repo.orgUrl) : null;\n return t && org ? `${org}/${t.repo.project}/${t.repo.repo}`.toLowerCase() : null;\n}\n\nexport function azureThreadId(r: Pick<AzureRepo, 'orgUrl' | 'project' | 'repo'>, pr: number, thread: number): string {\n return `AZT_${b64url(JSON.stringify([r.orgUrl, r.project, r.repo]))}_${pr}_${thread}`;\n}\n\n/** A thread id read back: its repo, PR and thread; null when it isn't one. */\nexport function parseAzureThreadId(\n id: string,\n): { repo: Pick<AzureRepo, 'orgUrl' | 'project' | 'repo'>; pr: number; thread: number } | null {\n if (!AZURE_THREAD_ID.test(id)) return null;\n const m = /^AZT_(.+)_(\\d+)_(\\d+)$/.exec(id);\n if (!m) return null;\n try {\n const v: unknown = JSON.parse(unb64url(m[1]));\n if (!Array.isArray(v) || v.length !== 3 || !v.every((x) => typeof x === 'string')) return null;\n const [orgUrl, project, repo] = v as [string, string, string];\n // Only an org URL Azure DevOps has, and names it would have: the id is text anyone can hand `work pr reply`,\n // and its org URL is where `az` would connect, signed in as you. It must read back as the same repo.\n const back = parseAzureOrigin(azureWebUrl({ orgUrl, project, repo }));\n if (!back || back.orgUrl !== orgUrl || back.project !== project || back.repo !== repo) return null;\n return { repo: { orgUrl, project, repo }, pr: Number(m[2]), thread: Number(m[3]) };\n } catch {\n return null;\n }\n}\n","import type { PrCommands } from '../command-types.js';\n\n/** The `gh` commands a prompt tells an agent to run for a GitHub PR. Pure, import-free (the SPA builds prompts with it). */\nexport const githubCommands: PrCommands = {\n host: 'GitHub',\n cli: 'gh',\n view: (n) => `gh pr view ${n}`,\n comments: (n) => `gh pr view ${n} --comments`,\n diff: (n) => `gh pr diff ${n}`,\n checks: (n) => `gh pr checks ${n}`,\n failedLog: 'gh run view <run-id> --log-failed',\n checkout: (n, detach) => `gh pr checkout ${n}${detach ? ' --detach' : ''}`,\n create: 'gh pr create',\n};\n","import type { PrCommands } from '../command-types.js';\n\n/**\n * The commands a prompt tells an agent to run for an Azure DevOps PR: the\n * `az repos` commands (the azure-devops extension), and git for the diff —\n * Azure DevOps keeps a PR's code at `refs/pull/<id>/merge`, whose first\n * parent is its target. Pure, import-free (the SPA builds prompts with it).\n */\nexport const azureCommands: PrCommands = {\n host: 'Azure DevOps',\n cli: 'az',\n view: (n) => `az repos pr show --id ${n}`,\n comments: (n) => `az repos pr show --id ${n} (and its threads: az devops invoke --area git --resource pullRequestThreads)`,\n diff: (n) => `git fetch origin refs/pull/${n}/merge && git diff FETCH_HEAD^1 FETCH_HEAD`,\n checks: (n) => `az repos pr policy list --id ${n}`,\n failedLog: 'az pipelines runs show --id <run-id>',\n checkout: (n) => `az repos pr checkout --id ${n}`,\n create: 'az repos pr create',\n};\n","import { githubCommands } from './github/commands.js';\nimport { azureCommands } from './azure/commands.js';\n\nexport type { PrCommands } from './command-types.js';\nimport type { PrCommands } from './command-types.js';\n\nconst TABLE: Record<string, PrCommands> = { github: githubCommands, azure: azureCommands };\n\n/** The default host: a repo no adapter claims is asked as GitHub (as before hosts existed; `gh` decides). */\nexport const DEFAULT_HOST = 'github';\n\n/** A host's prompt commands; the default host's for an unknown or missing id (a row from an older server). */\nexport function commandsFor(hostId?: string | null): PrCommands {\n return TABLE[hostId ?? DEFAULT_HOST] ?? TABLE[DEFAULT_HOST];\n}\n\n/** Add a host's commands (registerHost does, for a host added at run time). Returns its removal. */\nexport function addCommands(hostId: string, commands: PrCommands): () => void {\n TABLE[hostId] = commands;\n return () => {\n if (TABLE[hostId] === commands) delete TABLE[hostId];\n };\n}\n\n/** How the UI names a host (\"GitHub\"), from its id on the wire. */\nexport function hostName(hostId?: string | null): string {\n return commandsFor(hostId).host;\n}\n","import { GITHUB_THREAD_ID, parseGithubPrUrl } from './github/origin.js';\nimport { AZURE_THREAD_ID, parseAzurePrUrl } from './azure/origin.js';\nimport { DEFAULT_HOST } from './commands.js';\nimport type { PrLink } from './types.js';\n\n/**\n * Pull request links of the built-in hosts, read without the registry (which\n * reads git config from disk): pure, so the SPA, the demo and the pure\n * modules (`pr-ref.ts`, `blocks.ts`) share it. A host registered at run time\n * (a test's fake) is read by the registry's `hostOfPrUrl` instead.\n */\nconst PARSERS: Array<{ host: string; parse: (text: string) => PrLink | null }> = [\n { host: 'github', parse: parseGithubPrUrl },\n {\n host: 'azure',\n parse: (t) => {\n const l = parseAzurePrUrl(t);\n return l ? { repoId: l.repoId, number: l.number, url: l.url, label: l.label } : null;\n },\n },\n];\n\n/** A pull request link of a built-in host, read, with the host's id; null for anything else. */\nexport function parsePrLink(text: string): (PrLink & { host: string }) | null {\n for (const p of PARSERS) {\n const link = p.parse(text);\n if (link) return { ...link, host: p.host };\n }\n return null;\n}\n\nconst THREAD_IDS: Array<{ host: string; re: RegExp }> = [\n { host: 'github', re: GITHUB_THREAD_ID },\n { host: 'azure', re: AZURE_THREAD_ID },\n];\n\n/** The built-in host a review-thread id is shaped for (the UI names it); the default host's for anything else. */\nexport function threadHostId(id: string): string {\n return THREAD_IDS.find((t) => t.re.test(id))?.host ?? DEFAULT_HOST;\n}\n","import { json, tx, withDb } from '../platform/db.js';\nimport type { ShipPr } from '../api-types.js';\nimport { parsePrLink } from '../hosts/links.js';\n\n/**\n * Every pull request a session made or worked on, kept as it goes — the session's own list, so its PRs no longer\n * depend on guessing from branches. A PR was found only through a branch the session was seen on (session-branches.ts),\n * and a branch made, pushed and left within one turn was never seen: its PR (and a PR in a repo the session doesn't\n * have — Claude opening one on the docs repo too) never showed, and the PR watch never fixed its failing CI.\n *\n * Sources: what the agent's conversation says (`AgentConversation.prLinks`: Claude Code writes a line for each PR its\n * session makes or works on), read as work copies the new lines of a conversation (conversation-store.ts) and once\n * over the whole conversation for a session from before (`scanned`); and every PR the PR watch finds on a branch of\n * the session. A PR stays on the list once it is there; the PR watch looks each one up by its link\n * (`GitHost.prForRef`) until it is merged or closed, then keeps its last look (`final`) and asks no more.\n *\n * Per session in state.db `session_prs` (schema v13, gone with the session: purgeSessionRows).\n */\n\nexport type SessionPrSource = 'agent' | 'branch';\n\nexport interface SessionPrRecord {\n /** The PR's link, as its host writes it: the key. */\n url: string;\n number: number;\n /** The host's name for its repo (`owner/name`), from the link; '' when it can't be told. */\n repoId: string;\n /** Its head branch, once known (its host's look, or the branch it was found on). */\n branch?: string;\n /** How work learned of it. */\n sources: SessionPrSource[];\n /** ISO. */\n firstSeen: string;\n /** Its last look once merged or closed: shown as it was, never asked again. */\n final?: ShipPr;\n}\n\nexport interface SessionPrs {\n prs: SessionPrRecord[];\n /** When its whole conversation was read for PRs (once per session; later lines are read as they are copied). */\n scanned?: string;\n}\n\n/** A PR to put on a session's list. */\nexport interface PrSighting {\n url: string;\n number: number;\n /** `owner/name`; taken from the link when it parses. */\n repoId?: string;\n branch?: string;\n source: SessionPrSource;\n /** ISO; default now. */\n at?: string;\n}\n\n/** Most PRs kept per session: the oldest finished ones go first. */\nexport const MAX_SESSION_PRS = 100;\n\nconst isIso = (v: unknown): v is string => typeof v === 'string' && Number.isFinite(Date.parse(v));\nconst SOURCES: readonly SessionPrSource[] = ['agent', 'branch'];\n\nfunction isShipPr(v: unknown): v is ShipPr {\n const p = v as Partial<ShipPr> | null;\n return (\n !!p &&\n typeof p === 'object' &&\n typeof p.number === 'number' &&\n typeof p.url === 'string' &&\n (p.state === 'OPEN' || p.state === 'MERGED' || p.state === 'CLOSED') &&\n typeof p.isDraft === 'boolean' &&\n typeof p.mergeStateStatus === 'string' &&\n (p.checks === 'pass' || p.checks === 'fail' || p.checks === 'pending' || p.checks === 'none') &&\n typeof p.headSha === 'string'\n );\n}\n\n/** A stored record, shape-checked; entries that don't hold up are dropped, not the record. Pure. */\nexport function cleanSessionPrs(raw: unknown): SessionPrs | null {\n const o = raw as { prs?: unknown; scanned?: unknown } | null;\n if (!o || typeof o !== 'object' || !Array.isArray(o.prs)) return null;\n const prs: SessionPrRecord[] = [];\n for (const x of o.prs as unknown[]) {\n const r = x as Partial<Record<keyof SessionPrRecord, unknown>> | null;\n if (!r || typeof r !== 'object' || typeof r.url !== 'string' || !r.url) continue;\n if (typeof r.number !== 'number' || !Number.isInteger(r.number) || r.number <= 0) continue;\n if (typeof r.repoId !== 'string' || !isIso(r.firstSeen) || !Array.isArray(r.sources)) continue;\n const sources = (r.sources as unknown[]).filter((s): s is SessionPrSource => SOURCES.includes(s as SessionPrSource));\n if (!sources.length) continue;\n prs.push({\n url: r.url,\n number: r.number,\n repoId: r.repoId,\n ...(typeof r.branch === 'string' && r.branch ? { branch: r.branch } : {}),\n sources,\n firstSeen: r.firstSeen,\n ...(isShipPr(r.final) && r.final.state !== 'OPEN' ? { final: r.final } : {}),\n });\n }\n return { prs, ...(isIso(o.scanned) ? { scanned: o.scanned } : {}) };\n}\n\n/** The link as its host writes it, and its repo (the key two sightings of one PR share). */\nfunction normal(s: Pick<PrSighting, 'url' | 'number' | 'repoId'>): { url: string; repoId: string } {\n const link = parsePrLink(s.url);\n if (link && link.number === s.number) return { url: link.url, repoId: link.repoId };\n return { url: s.url, repoId: s.repoId ?? '' };\n}\n\n/**\n * The record with these sightings: a new PR appended, a known one's sources and branch filled in. Returns the record\n * unchanged (the same object) when nothing moved, so a caller writes only a change. Pure.\n */\nexport function withPrSightings(rec: SessionPrs | null, seen: PrSighting[], now: Date, opts: { scanned?: boolean } = {}): SessionPrs {\n const base: SessionPrs = rec ?? { prs: [] };\n let changed = !rec || (opts.scanned === true && !base.scanned);\n const prs = base.prs.map((p) => ({ ...p, sources: [...p.sources] }));\n for (const s of seen) {\n if (!Number.isInteger(s.number) || s.number <= 0 || !s.url) continue;\n const { url, repoId } = normal(s);\n const p = prs.find((x) => x.url === url);\n if (!p) {\n prs.push({\n url,\n number: s.number,\n repoId,\n ...(s.branch ? { branch: s.branch } : {}),\n sources: [s.source],\n firstSeen: isIso(s.at) ? s.at : now.toISOString(),\n });\n changed = true;\n continue;\n }\n if (!p.sources.includes(s.source)) {\n p.sources.push(s.source);\n changed = true;\n }\n if (s.branch && !p.branch) {\n p.branch = s.branch;\n changed = true;\n }\n if (!p.repoId && repoId) {\n p.repoId = repoId;\n changed = true;\n }\n if (isIso(s.at) && Date.parse(s.at) < Date.parse(p.firstSeen)) {\n p.firstSeen = s.at;\n changed = true;\n }\n }\n if (!changed) return base;\n return { prs: trim(prs), ...(base.scanned ? { scanned: base.scanned } : opts.scanned ? { scanned: now.toISOString() } : {}) };\n}\n\n/** At most MAX_SESSION_PRS: open ones are all kept; of the finished, the newest. */\nfunction trim(prs: SessionPrRecord[]): SessionPrRecord[] {\n if (prs.length <= MAX_SESSION_PRS) return prs;\n const finished = prs.filter((p) => p.final).sort((a, b) => Date.parse(b.firstSeen) - Date.parse(a.firstSeen));\n const drop = new Set(finished.slice(Math.max(0, MAX_SESSION_PRS - (prs.length - finished.length))));\n return prs.filter((p) => !drop.has(p));\n}\n\n/**\n * The record with what the host said of its PRs: a merged or closed one keeps that last look (`final`) and is asked\n * no more; every look fills in its branch. Unchanged (the same object) when nothing moved. Pure.\n */\nexport function withPrLooks(rec: SessionPrs, looks: Array<{ url: string; pr: ShipPr; branch?: string }>): SessionPrs {\n let changed = false;\n const prs = rec.prs.map((p) => {\n const look = looks.find((l) => l.url === p.url || l.pr.url === p.url);\n if (!look) return p;\n const next = { ...p };\n if (look.branch && !p.branch) {\n next.branch = look.branch;\n changed = true;\n }\n if (look.pr.state !== 'OPEN' && !p.final) {\n next.final = look.pr;\n changed = true;\n }\n return next;\n });\n return changed ? { ...rec, prs } : rec;\n}\n\nfunction readRow(d: Parameters<Parameters<typeof withDb>[0]>[0], sessionId: string): SessionPrs | null {\n const row = d.prepare('SELECT data FROM session_prs WHERE session_id = ?').get(sessionId) as { data: string } | undefined;\n return row ? cleanSessionPrs(json.parse(row.data)) : null;\n}\n\nfunction writeRow(d: Parameters<Parameters<typeof withDb>[0]>[0], sessionId: string, rec: SessionPrs): void {\n d.prepare('INSERT OR REPLACE INTO session_prs (session_id, data) VALUES (?, ?)').run(sessionId, JSON.stringify(rec));\n}\n\nexport function readSessionPrs(sessionId: string): SessionPrs | null {\n return withDb((d) => readRow(d, sessionId));\n}\n\n/** Put PRs on a session's list, in one transaction over the row as it is now; writes only a change. Returns the record after. */\nexport function noteSessionPrs(sessionId: string, seen: PrSighting[], now = new Date(), opts: { scanned?: boolean } = {}): SessionPrs {\n return tx((d) => {\n const old = readRow(d, sessionId);\n const next = withPrSightings(old, seen, now, opts);\n if (next !== old) writeRow(d, sessionId, next);\n return next;\n });\n}\n\n/** Record what the host said of a session's listed PRs (withPrLooks), in one transaction; writes only a change. */\nexport function notePrLooks(sessionId: string, looks: Array<{ url: string; pr: ShipPr; branch?: string }>): void {\n if (!looks.length) return;\n tx((d) => {\n const old = readRow(d, sessionId);\n if (!old) return;\n const next = withPrLooks(old, looks);\n if (next !== old) writeRow(d, sessionId, next);\n });\n}\n","import fs from 'node:fs';\nimport net from 'node:net';\nimport path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { getConfigDir, type WorkConfig } from '../platform/config.js';\nimport { shellEnv } from '../platform/shell-env.js';\nimport { bootTime, isPidAlive, killTree, processName } from '../platform/process.js';\nimport { json, withDb } from '../platform/db.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport { sessionRepos } from '../sessions/session-repos.js';\nimport type { DevServerState } from '../api-types.js';\n\n/**\n * Per-worktree dev server + preview.\n *\n * Every worktree already owns a stable port ($PORT, see port-allocator.ts)\n * that its Claude and anything it runs inherit. This module answers \"is\n * something serving on it?\" and can run the repo's dev command there —\n * `devCommands` in config.json, keyed by repo alias, e.g.\n * `{ \"web\": \"npm run dev -- --port $PORT\" }`. In a group the first repo\n * (in the session's order) with a command gets the port.\n *\n * The command comes from the user's own config and runs with `shell: true`\n * (like statusHooks); the worktree path is the spawn cwd, never part of\n * the command string. It runs in the background, its output in\n * ~/.work/dev/<session>.log, its pid in state.db (`dev_runs`) — so a\n * `work web` restart still knows it and can stop it.\n */\n\nfunction devDir(): string {\n const dir = path.join(getConfigDir(), 'dev');\n fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\nexport const devLogFile = (id: string) => path.join(devDir(), `${id}.log`);\n\ninterface RunRecord {\n pid: number;\n command: string;\n cwd: string;\n startedAt: string;\n /** Executable at that pid when we started it (the shell), if known.\n * Records from before this field (imported from the JSON files) have\n * none, and are trusted on pid + boot alone. */\n image?: string | null;\n}\n\n/** A run started this close to a boot can't be told from one started\n * before it, if the clock was stepped meanwhile (NTP after sleep). */\nconst REBOOT_SLACK_MS = 5 * 60_000;\n\nfunction isRunRecord(x: unknown): x is RunRecord {\n const r = x as RunRecord | null;\n return !!r && typeof r === 'object' && typeof r.pid === 'number' && typeof r.command === 'string' && typeof r.startedAt === 'string';\n}\n\n/** The machine has rebooted since this run started, so its pid — if alive —\n * belongs to someone else (Windows reuses pids quickly). Compares the boot\n * time with the run's own start time, both on the wall clock, so a clock\n * step of a few minutes doesn't turn a live run into \"another boot\". */\nfunction rebootedSince(r: RunRecord): boolean {\n const started = Date.parse(r.startedAt);\n if (!Number.isFinite(started)) return true; // unknown start: don't trust it\n return bootTime() - started > REBOOT_SLACK_MS;\n}\n\n/**\n * The live run for a session, or null. A saved pid is trusted only while\n * it is alive and from this boot: after a reboot the row survives but the\n * number may belong to an unrelated process — which the header would show\n * as \"running\" and Stop would kill.\n */\nfunction readRun(id: string): RunRecord | null {\n const row = withDb((d) => d.prepare('SELECT data FROM dev_runs WHERE session_id = ?').get(id) as { data: string } | undefined);\n if (!row) return null;\n const r = json.parse(row.data);\n if (isRunRecord(r) && !rebootedSince(r) && isPidAlive(r.pid)) return r;\n forgetRun(id); // it died on its own, or the machine rebooted\n return null;\n}\n\nfunction forgetRun(id: string): void {\n withDb((d) => d.prepare('DELETE FROM dev_runs WHERE session_id = ?').run(id));\n}\n\n/** The dev command for this session and where it runs, or null. */\nexport function devCommandFor(\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): { command: string; cwd: string; repo: string } | null {\n const commands = config?.devCommands ?? {};\n // Each folder's repo: recorded on the session, else (a row from before) the group\n // member named like the folder (resolve.ts names a worktree folder after its repo's).\n // A folder no member matches has no dev command, as before.\n for (const { alias, path: p, guessed } of sessionRepos(session, config)) {\n if (guessed) continue;\n const command = commands[alias];\n if (typeof command === 'string' && command.trim()) return { command, cwd: p, repo: alias };\n }\n return null;\n}\n\n/** Something accepts TCP connections on localhost:port (IPv4 or IPv6). */\nexport function isListening(port: number, timeoutMs = 400): Promise<boolean> {\n const probe = (host: string) =>\n new Promise<boolean>((resolve) => {\n const sock = net.connect({ host, port });\n const done = (ok: boolean) => {\n sock.destroy();\n resolve(ok);\n };\n sock.setTimeout(timeoutMs, () => done(false));\n sock.once('connect', () => done(true));\n sock.once('error', () => done(false));\n });\n return probe('127.0.0.1').then((ok) => ok || probe('::1'));\n}\n\nexport async function devState(\n id: string,\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): Promise<DevServerState> {\n const port = session.port ?? null;\n const cmd = devCommandFor(session, config);\n const run = readRun(id);\n return {\n port,\n listening: port !== null ? await isListening(port) : false,\n url: port !== null ? `http://localhost:${port}/` : null,\n command: cmd?.command ?? null,\n repo: cmd?.repo ?? null,\n running: run ? { pid: run.pid, startedAt: run.startedAt } : null,\n };\n}\n\nexport type DevStartOutcome = { ok: true; pid: number } | { ok: false; status: 400 | 409; error: string };\n\nexport function startDev(\n id: string,\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): DevStartOutcome {\n if (session.port === undefined) return { ok: false, status: 400, error: 'this worktree has no port — recreate it with work tree' };\n const cmd = devCommandFor(session, config);\n if (!cmd) return { ok: false, status: 400, error: 'no dev command — set devCommands in ~/.work/config.json' };\n if (!fs.existsSync(cmd.cwd)) return { ok: false, status: 400, error: `worktree is gone: ${cmd.cwd}` };\n const running = readRun(id);\n if (running) return { ok: false, status: 409, error: `already running (pid ${running.pid})` };\n\n const log = fs.openSync(devLogFile(id), 'w');\n try {\n fs.writeSync(log, `$ ${cmd.command} (PORT=${session.port}, in ${cmd.cwd})\\n`);\n const child = spawn(cmd.command, {\n cwd: cmd.cwd,\n shell: true,\n // POSIX: its own process group, so Stop can signal the whole tree.\n // Windows: NOT detached — a DETACHED_PROCESS cmd.exe drops its\n // children's output — and taskkill /T stops the tree instead.\n detached: process.platform !== 'win32',\n windowsHide: true,\n stdio: ['ignore', log, log],\n // Windows: a bare name in the command is PATH's, never the worktree's (a branch's script runs by its path: shell-env.ts).\n env: shellEnv({ ...process.env, PORT: String(session.port) }),\n });\n child.on('error', () => {});\n if (child.pid === undefined) return { ok: false, status: 400, error: 'could not start the dev command' };\n child.unref();\n const rec: RunRecord = {\n pid: child.pid,\n command: cmd.command,\n cwd: cmd.cwd,\n startedAt: new Date().toISOString(),\n image: processName(child.pid),\n };\n withDb((d) => d.prepare('INSERT OR REPLACE INTO dev_runs (session_id, data) VALUES (?, ?)').run(id, JSON.stringify(rec)));\n return { ok: true, pid: child.pid };\n } finally {\n fs.closeSync(log);\n }\n}\n\n/** Stop this session's dev server (the whole process tree). `name` looks\n * up a live pid's executable (injectable for tests). */\nexport function stopDev(id: string, name: (pid: number) => string | null = processName): boolean {\n const run = readRun(id);\n if (!run) return false;\n // Last check before killing a whole tree: the pid must still be the shell\n // we started. A DIFFERENT program at that number means the dev server is\n // long gone and the pid was reused — forget it, kill nothing. An\n // unreadable name (tasklist/ps slow or missing) proves nothing: the pid\n // is alive and from this boot, so go ahead.\n const now = name(run.pid);\n if (run.image && now !== null && now.toLowerCase() !== run.image.toLowerCase()) {\n forgetRun(id);\n return false;\n }\n // Detached on POSIX = its own process group: signal the group, so the\n // shell's children (npm → vite) go too. Windows: taskkill /T.\n let killed = false;\n if (process.platform !== 'win32') {\n try {\n process.kill(-run.pid, 'SIGTERM');\n killed = true;\n } catch {\n /* fall through */\n }\n }\n if (!killed) killed = killTree(run.pid);\n forgetRun(id);\n return killed;\n}\n\n/** The tail of the dev server's log. */\nexport function devLogTail(id: string, maxBytes = 64 * 1024): string {\n try {\n const file = devLogFile(id);\n const size = fs.statSync(file).size;\n const fd = fs.openSync(file, 'r');\n try {\n const len = Math.min(size, maxBytes);\n const buf = Buffer.alloc(len);\n fs.readSync(fd, buf, 0, len, size - len);\n return buf.toString('utf-8');\n } finally {\n fs.closeSync(fd);\n }\n } catch {\n return '';\n }\n}\n","import path from 'node:path';\nimport type { WorkConfig } from '../platform/config.js';\nimport type { WorktreeSession } from './session-types.js';\n\n/**\n * A session's repos: which repo alias each of its folders is a checkout of.\n * The session owns that list (`WorktreeSession.repos`, recorded when it is\n * made), so a session can hold a repo its group's config doesn't name, and\n * keep one its group lost. Rows from before it was recorded are read as they\n * always were: a group's from the config, a single repo's by its target.\n * Pure: the config is passed in.\n */\n\ntype SessionShape = Pick<WorktreeSession, 'target' | 'isGroup' | 'paths' | 'repos'>;\n\nexport interface SessionRepo {\n alias: string;\n path: string;\n /** Legacy only: no repo of the group's config has this folder's name, so the\n * alias is just the folder's name (readers that used to find no repo there skip it). */\n guessed?: true;\n}\n\n/** Its recorded list, zipped with its paths — null on a row from before (or one whose list doesn't match its paths). */\nexport function recordedRepos(s: Pick<WorktreeSession, 'paths' | 'repos'>): SessionRepo[] | null {\n if (!Array.isArray(s.repos) || s.repos.length !== s.paths.length || s.repos.length === 0) return null;\n if (!s.repos.every((a) => typeof a === 'string' && a)) return null;\n return s.repos.map((alias, i) => ({ alias, path: s.paths[i] }));\n}\n\nconst sameName = (a: string, b: string) => path.basename(a).toLowerCase() === path.basename(b).toLowerCase();\n\n/**\n * Each of its folders with the repo it is a checkout of. Recorded: as\n * recorded. Legacy: a group's folder is named after its repo's folder, so\n * the group's member (config) with that folder name, else the folder's own\n * name (`guessed`); a single repo's is its target.\n */\nexport function sessionRepos(s: SessionShape, config: Partial<Pick<WorkConfig, 'repos' | 'groups'>> | null | undefined): SessionRepo[] {\n const recorded = recordedRepos(s);\n if (recorded) return recorded;\n if (!s.isGroup) return s.paths.length ? [{ alias: s.target, path: s.paths[0] }] : [];\n // A list that is there but doesn't match its paths (a damaged row): each folder is matched\n // by name among the recorded aliases first — never read as a row from before, whose group\n // config may name none of them (a repo's session folder has no group at all).\n const listed = Array.isArray(s.repos) ? s.repos.filter((a): a is string => typeof a === 'string' && !!a) : [];\n const members = [...new Set([...listed, ...(config?.groups?.[s.target] ?? [])])];\n return s.paths.map((p) => {\n const alias = members.find((a) => {\n const repo = config?.repos?.[a];\n return repo !== undefined && sameName(repo, p);\n });\n return alias ? { alias, path: p } : { alias: path.basename(p), path: p, guessed: true as const };\n });\n}\n\n/**\n * The repo aliases a session acts over (archive, clean-up, checkpoints…).\n * Recorded: its own. Legacy, as before: a group's config members, a single\n * repo's target.\n */\nexport function sessionAliases(s: SessionShape, config: Partial<Pick<WorkConfig, 'repos' | 'groups'>> | null | undefined): string[] {\n const recorded = recordedRepos(s);\n if (recorded) return recorded.map((r) => r.alias);\n // A damaged list: what its folders are matched to, never the group's config alone.\n // (Without the repos' folders to match by, what it lists.)\n if (Array.isArray(s.repos) && s.isGroup)\n return config?.repos\n ? sessionRepos(s, config)\n .filter((r) => !r.guessed)\n .map((r) => r.alias)\n : s.repos.filter((a): a is string => typeof a === 'string' && !!a);\n return s.isGroup ? (config?.groups?.[s.target] ?? []) : [s.target];\n}\n\n/**\n * A session that is a folder of repos (a group's, or a repo's made with\n * `sessionFolders`): Claude runs in the folder, and a repo can be added to it.\n */\nexport function isFolderSession(s: Pick<WorktreeSession, 'isGroup'>): boolean {\n return s.isGroup;\n}\n","/**\n * Per-scope diff checkpoints.\n *\n * A \"checkpoint\" is a snapshot of every repo in a scope's working tree\n * (including untracked files) captured as a real git commit and held alive\n * by `refs/wd/<scope-hash>/<n>` in each repo. A small JSON manifest at\n * `~/.work/diffs/<scope-hash>.checkpoints.json` records the per-checkpoint\n * timestamp + repo→sha mapping so the SPA can list checkpoints and ask for\n * a diff between any two (or between one and the live working tree).\n *\n * Snapshots are taken automatically:\n * - once when a scope is first registered (the \"Initial\" point). This\n * baseline captures HEAD's tree, NOT the working tree — so a range of\n * \"Initial → working\" equals the full uncommitted diff (`git diff HEAD`\n * plus untracked), and any pre-existing uncommitted work the user\n * already had when `wd` launched stays visible instead of being baked\n * into an invisible baseline.\n * - again whenever the scope's fs-watch debounce fires AND the working\n * tree differs from the previous snapshot (the dedup keeps idle saves\n * from spawning empty checkpoints)\n *\n * The capture mechanism uses a temp git index file so the real index is\n * never disturbed:\n *\n * GIT_INDEX_FILE=<tmp> git read-tree HEAD\n * GIT_INDEX_FILE=<tmp> git add -A\n * GIT_INDEX_FILE=<tmp> git write-tree → <tree-sha>\n * git commit-tree <tree-sha> -p HEAD -m \"wd checkpoint\" → <commit-sha>\n * git update-ref refs/wd/<hash>/<n> <commit-sha>\n *\n * Untracked files end up in the snapshot because `git add -A` against the\n * temp index promotes them. `.gitignore` is honoured (same as the diff\n * pipeline's untracked detection).\n */\n\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport spawn from '../platform/spawn.js';\nimport { atomicWriteFile, ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { runGitAsync, writeTempTreeAsync } from './git-tree-snapshot.js';\nimport { workingBranch } from '../git/git-head.js';\n\nexport interface CheckpointEntry {\n /** Monotonic per-scope sequence id, starting at 0 for the initial\n * snapshot. */\n id: number;\n /** ISO timestamp of capture. */\n ts: string;\n /** Human label — \"Initial\" for id 0, otherwise empty (the SPA shows\n * \"#1\", \"#2\", ...). Reserved for future user-labelled checkpoints. */\n label?: string;\n /** Per-repo commit sha captured. Keyed by repo name (the same `name`\n * used in `RepoData`). When a repo has no head yet (fresh repo, no\n * commits), the value is null — diff ranges that touch it on the\n * \"from\" side fall back to the empty tree. */\n repos: Record<string, string | null>;\n /** Per repo (keyed as `repos`), the branch checked out when it was taken (null: detached). A turn whose\n * branch differs from the one before it crossed a branch switch: its diff is the switch, not a revert.\n * Absent on entries from before. */\n branches?: Record<string, string | null>;\n}\n\n/** Each repo's checked-out branch now (HEAD files, no git). */\nexport function branchesOf(repos: ScopeRepo[]): Record<string, string | null> {\n // In the middle of a rebase, the branch being rebased: a turn that ends on a conflict is still on it.\n return Object.fromEntries(repos.map((r) => [r.name, workingBranch(r.root)]));\n}\n\nexport interface CheckpointManifest {\n version: 1;\n scopeHash: string;\n entries: CheckpointEntry[];\n}\n\n/** Where this scope's manifest lives on disk. */\nexport function manifestPath(scopeHash: string): string {\n const dir = path.join(os.homedir(), '.work', 'diffs');\n fs.mkdirSync(dir, { recursive: true });\n return path.join(dir, `${scopeHash}.checkpoints.json`);\n}\n\nfunction emptyManifest(scopeHash: string): CheckpointManifest {\n return { version: 1, scopeHash, entries: [] };\n}\n\n/** Read manifest from disk (returns an empty one if the file is missing\n * or unparseable). Never throws. */\nexport function loadManifest(scopeHash: string): CheckpointManifest {\n const file = manifestPath(scopeHash);\n if (!fs.existsSync(file)) return emptyManifest(scopeHash);\n try {\n const raw = fs.readFileSync(file, 'utf-8');\n const parsed = JSON.parse(raw) as Partial<CheckpointManifest>;\n if (parsed.version !== 1 || !Array.isArray(parsed.entries)) {\n return emptyManifest(scopeHash);\n }\n return {\n version: 1,\n scopeHash,\n entries: parsed.entries as CheckpointEntry[],\n };\n } catch {\n return emptyManifest(scopeHash);\n }\n}\n\n// (Previously a separate `appendCheckpoint` lived here. It was folded\n// into `takeCheckpoint` so id assignment + snapshot + ref write + manifest\n// append all happen under a single lock — concurrent fs-watch fires across\n// the same scope must not race on `nextId`.)\n\n/**\n * Capture a single repo as a commit and return its sha. Updates\n * `refs/wd/<scopeHash>/<id>` to point at the commit so git GC can't\n * reclaim it. Returns null on failure (caller should skip this repo).\n *\n * `includeWorkingTree` (default true) controls what tree is captured:\n * - true — the working tree, incl. untracked files (subject to\n * .gitignore). This is the normal per-change snapshot.\n * - false — HEAD's tree verbatim (no `git add -A`). Used for the\n * \"Initial\" baseline so a diff of Initial → working reproduces\n * the full uncommitted diff rather than hiding pre-existing\n * changes inside the baseline. On a repo with no commits this\n * yields the empty tree (everything shows as added).\n *\n * Internally uses a temp `GIT_INDEX_FILE` so the user's real index is\n * untouched. The temp file is unlinked on success and on most failures.\n */\n/** A commit's (or rev's) tree, off the event loop; null when git can't say. */\nasync function treeOfAsync(root: string, rev: string | null): Promise<string | null> {\n if (!rev) return null;\n const r = await runGitAsync(root, { args: ['rev-parse', `${rev}^{tree}`] });\n return r.status === 0 ? r.stdout.trim() || null : null;\n}\n\n/** Every repo's tree of `a` equals its tree of `b` (each known). */\nasync function sameTrees(repos: ScopeRepo[], a: (r: ScopeRepo) => string | null, b: (r: ScopeRepo) => string | null): Promise<boolean> {\n for (const repo of repos) {\n const cur = await treeOfAsync(repo.root, a(repo));\n if (cur === null || cur !== (await treeOfAsync(repo.root, b(repo)))) return false;\n }\n return true;\n}\n\nexport async function snapshotRepo(repoRoot: string, scopeHash: string, id: number, includeWorkingTree = true): Promise<string | null> {\n // Build the tree (HEAD baseline, or full working tree) via the shared\n // temp-index helper — same dance `diff-pipeline.ts` uses to diff against\n // a checkpoint.\n // Off the event loop, one per repo at a time (writeTempTreeAsync): this\n // runs on every Claude turn of every session.\n const tree = await writeTempTreeAsync(repoRoot, { includeWorkingTree });\n if (!tree) return null;\n const { treeSha, headSha } = tree;\n\n // commit-tree doesn't need the temp index. Use a fixed author/committer +\n // date so two snapshots of identical content produce the SAME commit sha\n // (the tree sha is already identical; matching commit shas help dedup).\n // The dedup path in `takeCheckpoint` relies on this: when nothing changed\n // between captures, every repo's recomputed sha matches the previous entry\n // and the new manifest row is discarded. (The id isn't in the message; it\n // lives in the ref name + manifest entry.)\n const commitArgs = ['commit-tree', treeSha, '-m', 'wd checkpoint'];\n if (headSha) commitArgs.push('-p', headSha);\n const commitEnv = {\n ...process.env,\n GIT_AUTHOR_NAME: 'wd',\n GIT_AUTHOR_EMAIL: 'wd@local',\n GIT_AUTHOR_DATE: '2000-01-01T00:00:00Z',\n GIT_COMMITTER_NAME: 'wd',\n GIT_COMMITTER_EMAIL: 'wd@local',\n GIT_COMMITTER_DATE: '2000-01-01T00:00:00Z',\n };\n const commit = await runGitAsync(repoRoot, { args: commitArgs, env: commitEnv });\n if (commit.status !== 0 || !commit.stdout) return null;\n const commitSha = commit.stdout.trim();\n\n const refName = `refs/wd/${scopeHash}/${id}`;\n const updateRef = await runGitAsync(repoRoot, { args: ['update-ref', refName, commitSha] });\n if (updateRef.status !== 0) return null;\n\n return commitSha;\n}\n\nexport interface ScopeRepo {\n name: string;\n root: string;\n}\n\n/**\n * Take one checkpoint across every repo in a scope. Returns the appended\n * entry, or null when the snapshot is identical to the previous entry's\n * (every repo's commit sha matches — i.e. nothing changed). The caller\n * uses the null return to skip the SSE broadcast.\n *\n * When this is the first checkpoint for the scope, `label` defaults to\n * \"Initial\" so the SPA can render it specially.\n */\nexport async function takeCheckpoint(\n scopeHash: string,\n repos: ScopeRepo[],\n opts: { force?: boolean; label?: string } = {},\n): Promise<CheckpointEntry | null> {\n // Entire flow runs under one file lock so concurrent fs-watch fires\n // (or a register-handler racing with a debounced auto-snapshot) can't\n // assign duplicate ids or interleave manifest writes. Snapshot work\n // itself is git-side-effect-safe to concurrent — git's index/ref\n // locking handles same-repo overlap, and our temp `GIT_INDEX_FILE`\n // means the user's real index is untouched either way. We only need\n // the file lock to serialise the *id assignment + ref write + append*\n // triple, which has to be atomic across processes.\n const file = manifestPath(scopeHash);\n ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));\n return withFileLock(file, async () => {\n const manifest = loadManifest(scopeHash);\n const isFirst = manifest.entries.length === 0;\n const nextId = isFirst ? 0 : manifest.entries[manifest.entries.length - 1].id + 1;\n\n // The first checkpoint baselines HEAD (not the working tree) so\n // pre-existing uncommitted work stays visible in an \"Initial → working\"\n // range. Every subsequent checkpoint captures the working tree.\n const captured: Record<string, string | null> = {};\n for (const repo of repos) {\n captured[repo.name] = await snapshotRepo(repo.root, scopeHash, nextId, !isFirst);\n }\n\n // Delete `refs/wd/<hash>/<id>` in every listed repo. Used by both\n // the partial-failure bailout and the dedup-cancel path —\n // `update-ref -d` is a no-op on a missing ref, so the same helper\n // covers \"rollback what we wrote\" and \"rollback what we might\n // have written\" without needing per-repo state.\n const rollbackRefs = async () => {\n const refName = `refs/wd/${scopeHash}/${nextId}`;\n for (const repo of repos) await runGitAsync(repo.root, { args: ['update-ref', '-d', refName] });\n };\n\n // If any repo snapshot failed (returned null), bail — a partial\n // entry would let range diffs against this id silently produce\n // empty diffs for the failed repos (via the `?? 'HEAD'` fallback\n // in scope-routes) instead of surfacing the problem. The next\n // fs-event will retry.\n if (repos.some((r) => captured[r.name] === null)) {\n await rollbackRefs();\n return null;\n }\n\n // Dedup: when not forced, compare against the previous entry by\n // TREE sha rather than commit sha. Two captures of the same working\n // tree produce identical trees but can have different commit shas\n // (different parent because HEAD moved, different `-p` argument\n // when one capture saw an empty HEAD). Compare-by-tree means we\n // drop checkpoints that didn't actually change any content —\n // exactly what the user expects from \"no changes since last snapshot\".\n if (!opts.force && !isFirst) {\n const prev = manifest.entries[manifest.entries.length - 1];\n const allTreesMatch = await sameTrees(\n repos,\n (r) => captured[r.name],\n (r) => prev.repos[r.name] ?? null,\n );\n if (allTreesMatch) {\n await rollbackRefs();\n return null;\n }\n }\n\n const entry: CheckpointEntry = {\n id: nextId,\n ts: new Date().toISOString(),\n repos: captured,\n branches: branchesOf(repos),\n };\n const label = opts.label ?? (isFirst ? 'Initial' : undefined);\n if (label) entry.label = label;\n manifest.entries.push(entry);\n // At most MAX_CHECKPOINTS per scope: the oldest steps go (never the\n // Initial baseline), refs and all — each ref keeps a full snapshot's\n // objects from git's garbage collection.\n const dropped = checkpointsOverCap(manifest.entries);\n if (dropped.length) {\n const gone = new Set(dropped.map((e) => e.id));\n manifest.entries = manifest.entries.filter((e) => !gone.has(e.id));\n }\n atomicWriteFile(file, JSON.stringify(manifest, null, 2));\n for (const e of dropped) {\n for (const repo of repos) await runGitAsync(repo.root, { args: ['update-ref', '-d', `refs/wd/${scopeHash}/${e.id}`] });\n }\n return entry;\n });\n}\n\n/** How many checkpoints a scope keeps (Initial included). */\nexport const MAX_CHECKPOINTS = 200;\n\n/** The entries to drop to get back to `max`: the oldest after the Initial one. */\nexport function checkpointsOverCap<T extends { id: number }>(entries: T[], max = MAX_CHECKPOINTS): T[] {\n if (entries.length <= max) return [];\n return entries.slice(1, 1 + (entries.length - max));\n}\n\nexport type UpdateCheckpointResult = { status: 'updated'; entry: CheckpointEntry } | { status: 'unchanged' } | { status: 'missing' };\n\n/**\n * Re-snapshot every repo into an EXISTING checkpoint `id`, replacing its\n * captured shas + timestamp in place. This is the \"one step per instruction\"\n * primitive: while a Claude instruction is in progress, each turn refreshes\n * the same (live) checkpoint instead of appending a brand-new step, so all\n * the turns answering one prompt collapse into a single entry. The label is\n * cleared on a real change so the caller re-summarises the new content.\n *\n * Returns:\n * - { status:'updated', entry } — content changed and was written\n * - { status:'unchanged' } — the refreshed tree matches what's stored\n * - { status:'missing' } — no entry with `id`, or a repo snapshot\n * failed (caller should append instead)\n *\n * Ref/manifest consistency: `snapshotRepo` overwrites `refs/wd/<hash>/<id>`.\n * On both the 'missing' (partial-failure) and 'unchanged' paths we restore\n * each ref to the entry's recorded sha so a moved ref can't orphan the commit\n * the manifest still points at.\n */\nexport async function updateCheckpoint(scopeHash: string, repos: ScopeRepo[], id: number): Promise<UpdateCheckpointResult> {\n const file = manifestPath(scopeHash);\n ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));\n return withFileLock(file, async () => {\n const manifest = loadManifest(scopeHash);\n const entry = manifest.entries.find((e) => e.id === id);\n if (!entry) return { status: 'missing' as const };\n\n const refName = `refs/wd/${scopeHash}/${id}`;\n const restoreRefs = async () => {\n for (const repo of repos) {\n const old = entry.repos[repo.name] ?? null;\n await runGitAsync(repo.root, { args: old ? ['update-ref', refName, old] : ['update-ref', '-d', refName] });\n }\n };\n\n // Capture the current working tree into the SAME ref id (overwrites the\n // previous commit for this id).\n const captured: Record<string, string | null> = {};\n for (const repo of repos) {\n captured[repo.name] = await snapshotRepo(repo.root, scopeHash, id, true);\n }\n if (repos.some((r) => captured[r.name] === null)) {\n await restoreRefs();\n return { status: 'missing' as const };\n }\n\n const unchanged = await sameTrees(\n repos,\n (r) => captured[r.name],\n (r) => entry.repos[r.name] ?? null,\n );\n if (unchanged) {\n await restoreRefs();\n return { status: 'unchanged' as const };\n }\n\n entry.repos = captured;\n entry.branches = branchesOf(repos);\n entry.ts = new Date().toISOString();\n delete entry.label; // content changed → re-summarise\n atomicWriteFile(file, JSON.stringify(manifest, null, 2));\n return { status: 'updated' as const, entry };\n });\n}\n\n/**\n * Atomically re-baseline a scope at the current HEAD: under a SINGLE file\n * lock, capture a fresh \"Initial\" snapshot (HEAD's tree, not the working\n * tree) for every repo into id 0, delete the refs of all previous steps, and\n * replace the manifest with just that Initial entry.\n *\n * This is the locked, all-or-nothing form of \"clearCheckpoints +\n * takeCheckpoint\": doing those as two separate (and, for clearCheckpoints,\n * unlocked) steps let a concurrent checkpoint write interleave between the\n * clear and the new Initial — leaving a dangling ref or a dropped entry.\n * Holding one lock across the whole reset closes that window.\n *\n * Returns the new Initial entry, or null if any repo's snapshot failed (the\n * manifest is left untouched in that case; the partial id-0 ref is undone).\n */\nexport async function resetBaseline(scopeHash: string, repos: ScopeRepo[]): Promise<CheckpointEntry | null> {\n const file = manifestPath(scopeHash);\n ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));\n return withFileLock(file, async () => {\n const prevIds = loadManifest(scopeHash).entries.map((e) => e.id);\n\n // Fresh Initial baselines HEAD (includeWorkingTree=false). snapshotRepo\n // overwrites refs/wd/<hash>/0 in place.\n const captured: Record<string, string | null> = {};\n for (const repo of repos) {\n captured[repo.name] = await snapshotRepo(repo.root, scopeHash, 0, false);\n }\n\n const delRef = async (id: number) => {\n for (const repo of repos) await runGitAsync(repo.root, { args: ['update-ref', '-d', `refs/wd/${scopeHash}/${id}`] });\n };\n\n // Any repo failed → undo the partial id-0 write, leave the old manifest.\n if (repos.some((r) => captured[r.name] === null)) {\n await delRef(0);\n return null;\n }\n\n // Drop every previous step's ref except id 0 (just overwritten with the\n // fresh Initial). These are the now-orphaned snapshots being discarded.\n for (const id of prevIds) {\n if (id !== 0) await delRef(id);\n }\n\n const entry: CheckpointEntry = {\n id: 0,\n ts: new Date().toISOString(),\n label: 'Initial',\n repos: captured,\n branches: branchesOf(repos),\n };\n const manifest: CheckpointManifest = {\n version: 1,\n scopeHash,\n entries: [entry],\n };\n atomicWriteFile(file, JSON.stringify(manifest, null, 2));\n return entry;\n });\n}\n\n/**\n * Set (cache) a checkpoint's human label. Runs under the same file lock as\n * `takeCheckpoint` so a concurrent auto-snapshot can't clobber the write.\n * No-op when the id isn't found. Idempotent.\n */\nexport async function setCheckpointLabel(scopeHash: string, id: number, label: string): Promise<void> {\n const file = manifestPath(scopeHash);\n ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));\n await withFileLock(file, () => {\n const manifest = loadManifest(scopeHash);\n const entry = manifest.entries.find((e) => e.id === id);\n if (!entry || entry.label === label) return;\n entry.label = label;\n atomicWriteFile(file, JSON.stringify(manifest, null, 2));\n });\n}\n\n/**\n * True when the branch has advanced (pull / merge / new commit) since the\n * Initial (id 0) checkpoint was captured — i.e. any repo's current HEAD tree\n * differs from the tree the Initial baseline recorded.\n *\n * The Initial checkpoint commits HEAD's tree verbatim (`snapshotRepo` with\n * `includeWorkingTree=false`), so its tree equals HEAD-at-capture's tree. When\n * that no longer matches the live HEAD's tree the baseline is stale, and an\n * \"Initial → working\" range silently absorbs every commit pulled in since\n * (e.g. a `git pull`/merge of an upstream branch) — ballooning the diff far\n * beyond the user's own work. Callers re-baseline when this returns true.\n *\n * Returns false when there's no Initial entry, when HEAD can't be resolved, or\n * when every recorded tree still matches (uncommitted edits don't move HEAD's\n * tree, so a dirty-but-not-advanced worktree is correctly left alone).\n */\nexport async function headAdvancedSinceInitial(scopeHash: string, repos: ScopeRepo[]): Promise<boolean> {\n const manifest = loadManifest(scopeHash);\n const initial = manifest.entries.find((e) => e.id === 0);\n if (!initial) return false;\n // Off the event loop: this runs on every turn of every session.\n for (const repo of repos) {\n const headTree = await treeOfAsync(repo.root, 'HEAD');\n if (headTree === null) continue; // can't resolve HEAD → don't reset\n const baselineSha = initial.repos[repo.name];\n if (!baselineSha) return true; // baseline had no commit, HEAD exists now\n const baselineTree = await treeOfAsync(repo.root, baselineSha);\n if (baselineTree === null) continue; // baseline ref gone → leave it\n if (baselineTree !== headTree) return true;\n }\n return false;\n}\n\n/**\n * Whether the repo is on another branch than when the turn was taken (the turn recorded its branches; one from\n * before didn't: not known, false). A detached HEAD on either side isn't a switch (a rebase is read as its branch,\n * `workingBranch`; anything else detached can't be told): only branch to branch is, so a rebase onto main still\n * re-baselines. HEAD files only.\n */\nexport function switchedBranch(turn: Pick<CheckpointEntry, 'branches'>, repo: ScopeRepo): boolean {\n if (!turn.branches || !(repo.name in turn.branches)) return false;\n const was = turn.branches[repo.name];\n const now = workingBranch(repo.root);\n return !!was && !!now && was !== now;\n}\n\n/**\n * A session's scope keeps its turns across its own commits, but not across\n * a HEAD move that brought in work the session didn't do: the next turn,\n * diffed against the one before, would show all of it as Claude's. Since the\n * newest checkpoint (whose snapshot commit's parent is the HEAD then): a\n * rebase or reset (that HEAD is no longer underneath), a merge (Update from\n * main, a pull that merged), or commits already on the main branch\n * (`origin/HEAD`: a fast-forward pull, a rebase onto main) — true; only new\n * commits of its own on top — false. Can't tell (git failed): false.\n */\nexport async function headBroughtInOtherWork(scopeHash: string, repos: ScopeRepo[]): Promise<boolean> {\n const entries = loadManifest(scopeHash).entries;\n if (entries.length === 0) return false;\n const newest = entries.reduce((a, b) => (b.id > a.id ? b : a));\n // Off the event loop: this runs on every turn of every session, up to seven git calls a repo.\n const run = async (root: string, args: string[]) => {\n const r = await runGitAsync(root, { args });\n return { ok: r.status === 0, out: r.stdout.trim() };\n };\n const count = async (root: string, args: string[]) => {\n const r = await run(root, ['rev-list', '--count', ...args]);\n return r.ok && /^\\d+$/.test(r.out) ? Number(r.out) : null;\n };\n const broughtIn = async (repo: ScopeRepo): Promise<boolean> => {\n const snap = newest.repos[repo.name];\n if (!snap) return false;\n // Another branch checked out since (Claude moved on to a new branch, or back to an old one): the session's\n // own history goes on — the next turn is marked as the switch (`branchSwitch`), never taken for Claude's work.\n // Starting over here wiped every turn of a session that worked on more than one branch.\n if (switchedBranch(newest, repo)) return false;\n const was = await run(repo.root, ['rev-parse', '--verify', '--quiet', `${snap}^`]);\n const now = await run(repo.root, ['rev-parse', '--verify', '--quiet', 'HEAD']);\n if (!was.ok || !now.ok || !was.out || was.out === now.out) return false;\n if (!(await run(repo.root, ['merge-base', '--is-ancestor', was.out, now.out])).ok) return true;\n const range = `${was.out}..${now.out}`;\n if (((await count(repo.root, ['--merges', range])) ?? 0) > 0) return true;\n const main = await run(repo.root, ['rev-parse', '--verify', '--quiet', 'origin/HEAD']);\n if (!main.ok) return false;\n const all = await count(repo.root, [range]);\n const own = await count(repo.root, [range, '^origin/HEAD']);\n return all !== null && own !== null && own < all;\n };\n for (const repo of repos) if (await broughtIn(repo)) return true;\n return false;\n}\n\n/** Remove the manifest + every ref for this scope. Called when a scope\n * is explicitly torn down. Best-effort — partial failure leaves orphaned\n * refs but doesn't otherwise corrupt state. */\nexport function clearCheckpoints(scopeHash: string, repoRoots: string[]): void {\n const manifest = loadManifest(scopeHash);\n for (const root of repoRoots) {\n for (const entry of manifest.entries) {\n const refName = `refs/wd/${scopeHash}/${entry.id}`;\n spawn.sync('git', ['update-ref', '-d', refName], {\n cwd: root,\n encoding: 'utf-8',\n windowsHide: true,\n });\n }\n }\n const file = manifestPath(scopeHash);\n if (fs.existsSync(file)) {\n try {\n fs.unlinkSync(file);\n } catch {\n // Leave it — next register will overwrite.\n }\n }\n}\n","/**\n * Stage 1 of the migration to \"one server per machine.\"\n *\n * A scope is an ad-hoc registration from a `wd` (or `wd -c`) invocation:\n * a label and a list of repo roots. Identified by the same sha1-of-roots\n * hash that `stableDiffPath` produces, so the same directory always gets\n * the same scope id across CLI invocations.\n *\n * Scopes are in-memory only — registering one doesn't touch disk. The\n * file watcher and comment store are per-scope, lazily started on first\n * access and reused thereafter.\n *\n * This module is mounted into `work web` so multiple `wd` invocations\n * share a single server process. Eventually `wd` itself will become a\n * thin client that registers a scope and opens a URL.\n */\n\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport { createFsWatcher, type FsWatcher } from '../platform/fs-watcher.js';\nimport { loadConfig } from '../platform/config.js';\n\nexport interface Scope {\n /** Stable hash — same as `stableDiffPath` would emit. */\n hash: string;\n /** Repo roots this scope covers. One for a single-repo worktree,\n * many for a group. */\n paths: string[];\n /** Optional human label (e.g. \"work-tree · feat/x\"). */\n label: string;\n /** When the scope was first registered. */\n createdAt: string;\n /** Set when the user clicks \"End Review\" in the browser. The scope\n * itself stays alive (browser tab still works) — this is just a\n * signal so the `wd -c` CLI proxy knows to emit\n * `--- review done ---` and exit. */\n ended: boolean;\n}\n\ninterface ScopeEntry {\n scope: Scope;\n watcher: FsWatcher | null;\n subscribers: Set<() => void>;\n /** ms-since-epoch until which fs-watch events for this scope are ignored.\n * The diff server sets a short window right after it computes a diff so\n * the `.git` churn from its OWN git commands (e.g. the `to=working`\n * range diff's `git add -A` / `write-tree`) doesn't fire a reload — which\n * would refetch the diff, churn `.git` again, and loop. Real user edits\n * land outside this window and still reload. */\n suppressWatchUntil: number;\n}\n\nconst scopes = new Map<string, ScopeEntry>();\n\nfunction hashFor(paths: string[]): string {\n const key = paths.slice().sort().join('|');\n return crypto.createHash('sha1').update(key).digest('hex').slice(0, 12);\n}\n\n/** Thrown by registerScope when the requested paths aren't inside any\n * configured repo or under the configured worktrees root. */\nexport class ScopePathRejectedError extends Error {\n constructor(public rejected: string[]) {\n super(`paths not allowed: ${rejected.join(', ')} (must be inside a configured repo or worktreesRoot)`);\n this.name = 'ScopePathRejectedError';\n }\n}\n\nfunction normaliseForCompare(p: string): string {\n return path.resolve(p).replace(/\\\\/g, '/').toLowerCase();\n}\n\n/**\n * Reject paths that aren't inside any configured repo or under the\n * configured `worktreesRoot`. The work web server binds to 127.0.0.1\n * only, but any local process can still POST `/api/scopes` with an\n * arbitrary filesystem path — without this check a malicious npm\n * package could cause `git` and chokidar to operate on\n * `C:\\Windows\\System32` or the user's home root.\n *\n * Returns the rejected subset (empty array when everything's allowed).\n */\nfunction rejectedPaths(normalised: string[]): string[] {\n const config = loadConfig();\n if (!config) {\n // No config means no allowlist to check against. Fall back to\n // permissive — `work init` hasn't been run yet, and rejecting\n // everything would break first-run flows.\n return [];\n }\n const allowed = [...Object.values(config.repos), ...(config.worktreesRoot ? [config.worktreesRoot] : [])].map(normaliseForCompare);\n if (allowed.length === 0) return [];\n return normalised.filter((p) => {\n const np = normaliseForCompare(p);\n return !allowed.some((a) => np === a || np.startsWith(a + '/'));\n });\n}\n\n/** Register a scope (idempotent). Returns the resolved entry — same call\n * twice with the same paths gets the same hash and the same entry.\n * Throws `ScopePathRejectedError` when any path is outside the configured\n * repos / worktrees root. */\nexport function registerScope(paths: string[], label?: string): Scope {\n const normalised = paths.map((p) => path.resolve(p));\n const rejected = rejectedPaths(normalised);\n if (rejected.length > 0) throw new ScopePathRejectedError(rejected);\n const hash = hashFor(normalised);\n const existing = scopes.get(hash);\n if (existing) {\n if (label && existing.scope.label !== label) {\n existing.scope.label = label;\n }\n return existing.scope;\n }\n const scope: Scope = {\n hash,\n paths: normalised,\n label: label ?? path.basename(normalised[0]),\n createdAt: new Date().toISOString(),\n ended: false,\n };\n scopes.set(hash, {\n scope,\n watcher: null,\n subscribers: new Set(),\n suppressWatchUntil: 0,\n });\n return scope;\n}\n\n/** Mark a scope as ended (the user clicked \"End Review\"). Idempotent.\n * Does NOT remove the scope — the URL stays viewable. */\nexport function markScopeEnded(hash: string): boolean {\n const entry = scopes.get(hash);\n if (!entry) return false;\n if (entry.scope.ended) return false;\n entry.scope.ended = true;\n return true;\n}\n\n/**\n * Clear a scope's `ended` flag. Called when a scope is re-registered —\n * a new `wd -c` run on the same paths is a fresh review, not a replay of\n * the finished one. Returns true when the flag was actually set (so the\n * caller knows to also reset the previous run's comments).\n */\nexport function reviveScope(hash: string): boolean {\n const entry = scopes.get(hash);\n if (!entry || !entry.scope.ended) return false;\n entry.scope.ended = false;\n return true;\n}\n\n/**\n * Which scopes a work web shutdown may sweep (checkpoint refs + manifest):\n * only ones no session owns. A session's scope holds its turn history\n * (\"Last turn\"), which must survive a restart; sweeping it on every clean\n * shutdown erased every session's turns. What's left are `wd` scopes for\n * paths outside any session (or one sub-repo of a group).\n */\nexport function scopesToSweep(scopes: Scope[], sessionPaths: string[][]): Scope[] {\n const owned = new Set(sessionPaths.map((paths) => hashFor(paths.map((p) => path.resolve(p)))));\n return scopes.filter((s) => !owned.has(s.hash));\n}\n\n/**\n * Is this scope a session's (its paths are a session's paths)? A session's\n * turns are its history: the Diff tab lists them beside its commits, so a\n * commit must not wipe them (wd's own scopes re-baseline at each commit).\n */\nexport function sessionOwnsScope(hash: string, sessionPaths: string[][]): boolean {\n return sessionPaths.some((paths) => hashFor(paths.map((p) => path.resolve(p))) === hash);\n}\n\n/** The registered scope for exactly these paths, or null — no side effects\n * (unlike registerScope, which relabels). */\nexport function findScope(paths: string[]): Scope | null {\n return getScope(scopeHashForPaths(paths));\n}\n\n/** The scope hash for these paths, registered or not (its checkpoint\n * manifest on disk is keyed by it). */\nexport function scopeHashForPaths(paths: string[]): string {\n return hashFor(paths.map((p) => path.resolve(p)));\n}\n\nexport function getScope(hash: string): Scope | null {\n return scopes.get(hash)?.scope ?? null;\n}\n\n/** Ignore this scope's fs-watch events for the next `ms`. The diff server\n * calls this right after computing a diff so its own `.git` churn doesn't\n * trigger a reload (which would recompute → churn → loop). */\nexport function suppressScopeWatch(hash: string, ms: number): void {\n const entry = scopes.get(hash);\n if (entry) entry.suppressWatchUntil = Date.now() + ms;\n}\n\n/**\n * Pure predicate: does a scope with these repo roots cover `cwd`? True when\n * cwd equals a root, sits inside one, or contains one (the group-root case,\n * where Claude runs in the parent of the sub-repos). Exported for testing\n * without the registry / config allowlist.\n */\nexport function scopeCoversCwd(paths: string[], cwd: string): boolean {\n const nc = normaliseForCompare(cwd);\n return paths.some((p) => {\n const np = normaliseForCompare(p);\n return np === nc || np.startsWith(nc + '/') || nc.startsWith(np + '/');\n });\n}\n\n/**\n * Scopes relevant to `cwd` — used by the `work hook checkpoint` bridge to\n * snapshot the right scope when a Claude turn ends.\n */\nexport function scopesForCwd(cwd: string): Scope[] {\n return Array.from(scopes.values())\n .map((e) => e.scope)\n .filter((s) => scopeCoversCwd(s.paths, cwd));\n}\n\nexport function listScopes(): Scope[] {\n return Array.from(scopes.values()).map((e) => e.scope);\n}\n\nexport function removeScope(hash: string): boolean {\n const entry = scopes.get(hash);\n if (!entry) return false;\n entry.watcher?.stop();\n entry.subscribers.clear();\n scopes.delete(hash);\n return true;\n}\n\n/**\n * Subscribe to file-change events for a scope. Lazy-starts the\n * chokidar watcher on first subscribe; tears it down when the last\n * subscriber unsubscribes. Same lifecycle as `web-state.subscribeSession`.\n *\n * The callback fires once per debounced fs event burst.\n */\nexport function subscribeScope(hash: string, cb: () => void): (() => void) | null {\n const entry = scopes.get(hash);\n if (!entry) return null;\n entry.subscribers.add(cb);\n if (!entry.watcher) {\n entry.watcher = createFsWatcher({\n roots: entry.scope.paths,\n debounceMs: 150,\n onChange: () => {\n // Ignore the burst of `.git` churn our own diff computation just\n // produced (see suppressWatchUntil) — firing here would loop the\n // live-reload. Real edits arrive outside the window.\n if (Date.now() < entry.suppressWatchUntil) return;\n for (const sub of entry.subscribers) {\n try {\n sub();\n } catch {\n /* */\n }\n }\n },\n });\n }\n return () => {\n entry.subscribers.delete(cb);\n if (entry.subscribers.size === 0 && entry.watcher) {\n entry.watcher.stop();\n entry.watcher = null;\n }\n };\n}\n\n/** Shut down every scope's watcher. Web server shutdown hook. */\nexport function disposeAllScopes(): void {\n for (const e of scopes.values()) {\n e.watcher?.stop();\n e.subscribers.clear();\n }\n scopes.clear();\n}\n\n/** Build a comment-store id for a scope. Distinguishes from session\n * ids so the two namespaces can't collide on disk. */\nexport function commentStoreIdForScope(hash: string): string {\n return `scope-${hash}`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { report } from './report.js';\n\n/** chokidar, loaded when a watch starts (Linux only uses it): every `work` process\n * that imports this module — a hook, on each Claude turn — would otherwise load it too. */\nconst loadChokidar = () => createRequire(import.meta.url)('chokidar') as typeof import('chokidar');\n\nexport interface FsWatcherOptions {\n /** Working-tree roots to watch. .git/ subdirs are filtered out. */\n roots: string[];\n /** Debounce window for fs events before firing `onChange`. */\n debounceMs?: number;\n /** Fires once per debounce window when anything under `roots` changed. */\n onChange: () => void;\n}\n\nexport interface FsWatcher {\n stop(): void;\n}\n\n/**\n * Directory names the watcher must never descend into. chokidar (v4+, no\n * fsevents) opens one OS watch per directory, so recursively watching a\n * dependency install or build-output tree exhausts the process's file\n * descriptors (EMFILE) and wedges the server. These are all git-ignored in\n * practice, so changes there never affect the diff — at worst a manual\n * browser refresh is needed for an edit inside one.\n */\nconst IGNORED_DIRS = new Set([\n '.git',\n 'node_modules',\n 'bin', // .NET build output\n 'obj', // .NET build output\n 'dist',\n 'build',\n 'out',\n 'target', // Rust / JVM\n '.next',\n '.nuxt',\n '.svelte-kit',\n '.turbo',\n '.gradle',\n 'coverage',\n '.vs',\n '.idea',\n]);\n\n/**\n * Whether chokidar should skip a path. A path is ignored when any segment\n * *below one of the watched roots* is in {@link IGNORED_DIRS}. Matching\n * relative to the root (not the absolute path) avoids false positives when an\n * ancestor directory happens to be named e.g. `build`.\n */\nexport function isIgnoredWatchPath(roots: string[], filePath: string): boolean {\n for (const root of roots) {\n const rel = path.relative(root, filePath).replace(/\\\\/g, '/');\n if (rel === '' || rel.startsWith('../')) continue; // not under this root\n if (rel.split('/').some((seg) => IGNORED_DIRS.has(seg))) return true;\n }\n return false;\n}\n\n// macOS and Windows support recursive fs.watch (backed by FSEvents /\n// ReadDirectoryChangesW) — a single OS handle covers the whole tree with\n// O(1) file descriptors. Linux has no recursive fs.watch, so we keep\n// chokidar there.\nconst SUPPORTS_RECURSIVE_WATCH = process.platform === 'darwin' || process.platform === 'win32';\n\nfunction logWatchError(err: unknown): void {\n report('warn', `[watcher] fs error: ${(err as Error).message}`);\n}\n\n/**\n * Debounced recursive watcher over one-or-more repo roots, filtering out\n * `.git/`, `node_modules/`, and build output. Shared between `wd` (the diff\n * server's reload trigger) and any other live file-watcher need.\n *\n * On macOS/Windows this uses one recursive `fs.watch` per root: O(1) fds no\n * matter how big the tree. chokidar (v4 — no bundled fsevents) instead opens\n * one watch per directory, which on a large repo exhausts the process's file\n * descriptors and starves the `git` subprocesses the diff server spawns\n * (branch detection then silently returns nothing). Linux keeps chokidar.\n */\nexport function createFsWatcher(opts: FsWatcherOptions): FsWatcher {\n const debounceMs = opts.debounceMs ?? 150;\n let debounceTimer: NodeJS.Timeout | null = null;\n\n const fire = (): void => {\n if (debounceTimer) clearTimeout(debounceTimer);\n debounceTimer = setTimeout(() => {\n debounceTimer = null;\n opts.onChange();\n }, debounceMs);\n };\n\n if (SUPPORTS_RECURSIVE_WATCH) {\n const watchers = opts.roots.map((root) => {\n const w = fs.watch(root, { recursive: true }, (_event, filename) => {\n // `filename` is relative to `root` (and may be null on some events).\n // The single FSEvents handle still reports ignored dirs, so filter\n // here to avoid spurious reloads from node_modules / build churn.\n if (filename && isIgnoredWatchPath([root], path.join(root, filename.toString()))) {\n return;\n }\n fire();\n });\n w.on('error', logWatchError);\n return w;\n });\n return {\n stop() {\n if (debounceTimer) clearTimeout(debounceTimer);\n for (const w of watchers) {\n try {\n w.close();\n } catch {\n /* already closed */\n }\n }\n },\n };\n }\n\n const watcher = loadChokidar().watch(opts.roots, {\n ignored: (filePath) => isIgnoredWatchPath(opts.roots, filePath),\n ignoreInitial: true,\n persistent: true,\n awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 20 },\n });\n watcher.on('all', fire);\n watcher.on('error', logWatchError);\n\n return {\n stop() {\n if (debounceTimer) clearTimeout(debounceTimer);\n watcher.close().catch(() => {\n /* */\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,UAAQ;AACf,OAAOC,YAAU;;;ACYjB,IAAM,YAAY;AAElB,IAAM,UAAU,IAAI;AASb,SAAS,wBAAwB,SAAkC;AACxE,MAAI,SAAS;AACb,aAAW,KAAK,QAAQ,OAAO,EAAE,cAAc,MAAM,OAAO,KAAK,CAAC,EAAG,KAAI,EAAE,UA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AC,GAAG,IAAI,IAAI,CAAC,MAAM,EAAE,KAAK,GAAG,GAAG,MAAM,IAAI,CAAC,MAAM,EAAE,KAAe,CAAC;AACpF,iBAAO,GAAG,QAAQ;AAClB;AAAA,QACF;AAAA,MACF,WAAW,UAAU;AACnB,cAAM,UAAU,CAAC,GAAG,SAAS,KAAK,EAAE,KAAK;AACzC,cAAM,UAAU,CAAC,GAAG,IAAI,KAAK,EAAE,KAAK;AACpC,cAAM,OAAO,QAAQ,WAAW,QAAQ,UAAU,QAAQ,MAAM,CAAC,GAAG,MAAM,MAAM,QAAQ,CAAC,CAAC;AAC1F,YAAI,CAAC,MAAM;AACT,mBAAS,QAAQ,IAAI;AACrB,iBAAO,GAAG,QAAQ;AAClB;AAAA,QACF;AAAA,MACF,OAAO;AACL,eAAO,GAAG,GAAG;AACb;AAAA,MACF;AAAA,IACF;AACA,WAAO,EAAE,OAAO,QAAQ;AAAA,EAC1B,CAAC;AACH;AAEA,IAAM,WAAW,CAAC,GAAW,MAAc;AACzC,QAAM,IAAI,CAAC,MAAcD,OAAK,QAAQ,CAAC,EAAE,MAAMA,OAAK,GAAG,EAAE,KAAK,GAAG,EAAE,YAAY;AAC/E,SAAO,EAAE,CAAC,MAAM,EAAE,CAAC;AACrB;AAUA,eAAsB,+BAA+B,QAAgB,YAAoB,UAAqC;AAC5H,QAAM,SAAS,YAAY,EAAE;AAAA,IAC3B,CAAC,MAAM,EAAE,WAAW,UAAU,CAAC,EAAE,WAAW,EAAE,WAAW,cAAc,EAAE,MAAM,WAAW,KAAK,SAAS,EAAE,MAAM,CAAC,GAAG,QAAQ;AAAA,EAC9H;AACA,aAAW,KAAK,OAAQ,OAAM,cAAc,EAAE,QAAQ,EAAE,MAAM;AAC9D,SAAO,OAAO,IAAI,CAAC,MAAM,EAAE,MAAM;AACnC;","names":["fs","path","fs","fs","fs","path","fs","fs","path","fs","lastTurnEntryMs","rows","path","path","fs","valid","fs","path","zlib","readRow","zlib","path","fs","fs","net","path","path","path","fs","net","fs","os","path","path","os","fs","path","crypto","fs","path","path","fs","crypto","path","scopes","fs","path","fs"]}