@moberg_hr/work-tree 2.9.1 → 2.9.3
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.
- package/dist/{account-RTOXCLE6.js → account-NG75VLRU.js} +14 -13
- package/dist/{account-RTOXCLE6.js.map → account-NG75VLRU.js.map} +1 -1
- package/dist/{add-repo-AA3XTOZT.js → add-repo-EDU3QEYI.js} +9 -9
- package/dist/{answer-NT62U5MY.js → answer-MHOJ2J6S.js} +7 -7
- package/dist/{attach-HKVFNOOK.js → attach-37JOJ4C3.js} +12 -11
- package/dist/{attach-HKVFNOOK.js.map → attach-37JOJ4C3.js.map} +1 -1
- package/dist/bin.js +3 -3
- package/dist/{block-YZQGJMLI.js → block-D5CAR53T.js} +8 -8
- package/dist/{broadcast-2NOVIUZI.js → broadcast-LLYHUWXA.js} +5 -5
- package/dist/{catchup-LZ5FMXEO.js → catchup-2SL3JGA7.js} +10 -10
- package/dist/{chunk-ODBA4PVE.js → chunk-26OVU2AE.js} +4 -4
- package/dist/{chunk-PDWEPIL6.js → chunk-2JNW2AQ2.js} +2 -1
- package/dist/chunk-2JNW2AQ2.js.map +1 -0
- package/dist/{chunk-RVT4435Z.js → chunk-37XQIG7F.js} +63 -97
- package/dist/chunk-37XQIG7F.js.map +1 -0
- package/dist/{chunk-GEGRI67Z.js → chunk-3C3BKZ3H.js} +3 -3
- package/dist/{chunk-BDFAIHTM.js → chunk-63VY4YJM.js} +4 -4
- package/dist/{chunk-VNNAKJZA.js → chunk-6E2I2FBJ.js} +10 -10
- package/dist/{chunk-FK2ZZUR5.js → chunk-6FVYSW3E.js} +4 -73
- package/dist/chunk-6FVYSW3E.js.map +1 -0
- package/dist/{chunk-BNGX2JGD.js → chunk-72IBYKIY.js} +2 -2
- package/dist/{chunk-SXPC4FQM.js → chunk-7OUIZ2YQ.js} +53 -53
- package/dist/{chunk-3NXRBRRJ.js → chunk-AAYWHIIT.js} +11 -4
- package/dist/chunk-AAYWHIIT.js.map +1 -0
- package/dist/{chunk-BGKHI4FC.js → chunk-ATED7SAH.js} +3 -3
- package/dist/{chunk-T6BX6B5B.js → chunk-BSP2Z7B7.js} +2 -2
- package/dist/{chunk-PGZMPB2Q.js → chunk-CCTALU3C.js} +2 -2
- package/dist/{chunk-N7EHLEYG.js → chunk-CLBQ7ZC4.js} +2 -2
- package/dist/{chunk-4GVXOUVN.js → chunk-CMO5YUZR.js} +2 -2
- package/dist/{chunk-JAU62YN5.js → chunk-CYWI3ZW7.js} +4 -4
- package/dist/{chunk-QNH6ZRFV.js → chunk-DQCUYCMX.js} +2 -2
- package/dist/{chunk-ZJSEDIFT.js → chunk-GRLKPVTP.js} +11 -8
- package/dist/chunk-GRLKPVTP.js.map +1 -0
- package/dist/{chunk-IGC64EGV.js → chunk-HCVONKJI.js} +6 -6
- package/dist/{chunk-4OK2WJ2B.js → chunk-HEPBANFJ.js} +5 -5
- package/dist/{chunk-AHA65ZCO.js → chunk-INQQGV2G.js} +3 -3
- package/dist/{chunk-AQJSY4CI.js → chunk-IPGH7TXJ.js} +2 -2
- package/dist/{chunk-HJZSMSP4.js → chunk-IWJXFNM4.js} +6 -6
- package/dist/{chunk-JFN67PRA.js → chunk-KSUOVFO3.js} +2 -2
- package/dist/{chunk-7NSQVIIK.js → chunk-MG5TTLYZ.js} +2 -2
- package/dist/chunk-NWIVXGSL.js +9 -0
- package/dist/chunk-OTAZOIXK.js +78 -0
- package/dist/chunk-OTAZOIXK.js.map +1 -0
- package/dist/{chunk-HKK3WUPZ.js → chunk-P6BHOAQG.js} +2 -2
- package/dist/{chunk-RCZZAQFN.js → chunk-PRDRRU2B.js} +4 -4
- package/dist/{chunk-CYXMVMVO.js → chunk-PTWVOT7A.js} +223 -9
- package/dist/chunk-PTWVOT7A.js.map +1 -0
- package/dist/{chunk-6KOJSRML.js → chunk-QEVYCCKD.js} +2 -2
- package/dist/{chunk-7NZC7EAP.js → chunk-QHTXLCG7.js} +7 -7
- package/dist/{chunk-A633PJUP.js → chunk-QL36KN7X.js} +3 -3
- package/dist/{chunk-7POCHRUP.js → chunk-QSOEMCWQ.js} +6 -6
- package/dist/{chunk-J4Y7DKQN.js → chunk-RFINYWID.js} +3 -3
- package/dist/{chunk-4WG66W6U.js → chunk-S3FMTEFR.js} +4 -4
- package/dist/{chunk-MVMLNEHM.js → chunk-T7AFYEQ7.js} +4 -4
- package/dist/{chunk-JT5AR7PO.js → chunk-TPSFJSO7.js} +72 -3
- package/dist/chunk-TPSFJSO7.js.map +1 -0
- package/dist/{chunk-MPY2ZQBL.js → chunk-VUAVPBFR.js} +4 -4
- package/dist/{chunk-T22E35FV.js → chunk-WC534PXU.js} +5 -5
- package/dist/{chunk-T22E35FV.js.map → chunk-WC534PXU.js.map} +1 -1
- package/dist/{chunk-UJWMBDFX.js → chunk-WTQ2QCAG.js} +3 -3
- package/dist/{chunk-7OTYC7T5.js → chunk-WXE7D44E.js} +3 -3
- package/dist/{chunk-IJSW2U6U.js → chunk-WXMWZRBH.js} +2 -2
- package/dist/{chunk-FXWY22ZP.js → chunk-XVNRP7XE.js} +6 -6
- package/dist/{chunk-2Z2O5LEA.js → chunk-ZI2KXTKM.js} +2 -2
- package/dist/{cleanup-6NOT6VTS.js → cleanup-5PSLKZLF.js} +20 -19
- package/dist/{cleanup-6NOT6VTS.js.map → cleanup-5PSLKZLF.js.map} +1 -1
- package/dist/{cli-PAICDKJT.js → cli-AF7636FA.js} +4 -4
- package/dist/{config-U4SGJ7RB.js → config-6MSITKGB.js} +7 -7
- package/dist/{diff-CYXW5YWD.js → diff-Q7MV6YGJ.js} +8 -8
- package/dist/{digest-KRIBJHII.js → digest-KUMVYXKZ.js} +7 -7
- package/dist/{fork-LQYEB4A4.js → fork-OFENISEM.js} +18 -17
- package/dist/{fork-LQYEB4A4.js.map → fork-OFENISEM.js.map} +1 -1
- package/dist/{history-DCALTZMM.js → history-5WKRWARZ.js} +5 -5
- package/dist/{hook-MDFVVCD2.js → hook-ARS32DG2.js} +9 -8
- package/dist/{hook-MDFVVCD2.js.map → hook-ARS32DG2.js.map} +1 -1
- package/dist/{hydrate-KBWZSSBL.js → hydrate-LCT6DVB3.js} +5 -5
- package/dist/{init-R47WGD62.js → init-FJKPEY5N.js} +6 -6
- package/dist/{install-skills-IIMTRQ4K.js → install-skills-UYAFVJBA.js} +5 -5
- package/dist/install-skills-bin.js +4 -4
- package/dist/{list-X5YB4JRL.js → list-GTKP5FAW.js} +5 -5
- package/dist/{move-WSK5UU5T.js → move-GOCLEFGZ.js} +8 -8
- package/dist/{note-VMO2PKYX.js → note-B7TQBXQF.js} +7 -7
- package/dist/{overlaps-ZNZTQHU7.js → overlaps-UKQHIJMU.js} +7 -7
- package/dist/{pin-RGRNNJUL.js → pin-UZZCDK7M.js} +7 -7
- package/dist/{pr-B2V3N3SV.js → pr-NU2ME2XW.js} +8 -7
- package/dist/{pr-B2V3N3SV.js.map → pr-NU2ME2XW.js.map} +1 -1
- package/dist/{prune-M2MYPNI6.js → prune-IZGEYTSB.js} +18 -17
- package/dist/{prune-M2MYPNI6.js.map → prune-IZGEYTSB.js.map} +1 -1
- package/dist/{pty-host-I2I7SVOL.js → pty-host-AWDIKPQN.js} +46 -41
- package/dist/pty-host-AWDIKPQN.js.map +1 -0
- package/dist/{read-E22APCUR.js → read-U6GBGA5E.js} +7 -7
- package/dist/{recent-F3Z3JXFX.js → recent-2DUMLUDG.js} +6 -6
- package/dist/{remove-YGVUESDY.js → remove-OXUP4O33.js} +17 -16
- package/dist/{remove-YGVUESDY.js.map → remove-OXUP4O33.js.map} +1 -1
- package/dist/{restart-BAGGJDD2.js → restart-QEW4DJC3.js} +7 -7
- package/dist/{resume-PIFCI727.js → resume-K45IT4QO.js} +6 -6
- package/dist/{run-MW3QTOXU.js → run-42LORGPS.js} +5 -5
- package/dist/{screen-UILBPWSR.js → screen-2TLIUH3G.js} +7 -7
- package/dist/{search-DLZEPI4I.js → search-7E4B2KX6.js} +5 -5
- package/dist/{section-A5JKTX4J.js → section-OVA5VD7L.js} +7 -7
- package/dist/{send-EPPQKYOK.js → send-BJY5CYLO.js} +8 -8
- package/dist/{sessions-3HLVK6HG.js → sessions-4A24ZORW.js} +15 -14
- package/dist/{sessions-3HLVK6HG.js.map → sessions-4A24ZORW.js.map} +1 -1
- package/dist/{snooze-GA46Z56G.js → snooze-WIVKB3GH.js} +7 -7
- package/dist/{start-L6G3NC2J.js → start-G6GR533S.js} +7 -7
- package/dist/{state-OZF4S7PG.js → state-S3DGLT4J.js} +2 -2
- package/dist/{status-H5S3DZBI.js → status-BTAWY6JQ.js} +5 -5
- package/dist/{statusline-RSQMMCRN.js → statusline-WLXEU5DM.js} +3 -3
- package/dist/{stop-HQLHTY5V.js → stop-FN6EPFJ4.js} +7 -7
- package/dist/{sync-N2CDSJA4.js → sync-T3BSHX6Q.js} +18 -17
- package/dist/{sync-N2CDSJA4.js.map → sync-T3BSHX6Q.js.map} +1 -1
- package/dist/{time-H54NH62B.js → time-5CH5O5MZ.js} +8 -8
- package/dist/{time-actions-DB7OQ2IS.js → time-actions-XEUQ3UF7.js} +3 -3
- package/dist/{timesheet-PAS5SHPD.js → timesheet-FMQKPS5S.js} +10 -10
- package/dist/{todo-ODF7RI27.js → todo-23COLGR2.js} +2 -2
- package/dist/{tree-7EBS7PVA.js → tree-T33VU473.js} +14 -13
- package/dist/{tree-7EBS7PVA.js.map → tree-T33VU473.js.map} +1 -1
- package/dist/{update-M7ECF7UE.js → update-PJRSKQZ2.js} +9 -9
- package/dist/{usage-IFKUY6LC.js → usage-TL66LWO4.js} +7 -7
- package/dist/{wait-K3NSSNFR.js → wait-YIEJO6YM.js} +8 -8
- package/dist/wd-bin.js +3 -3
- package/dist/web/assets/PtyView-DnDd6jLI.js +96 -0
- package/dist/web/assets/PtyView-DnDd6jLI.js.map +1 -0
- package/dist/web/assets/index-DxozAoUO.css +1 -0
- package/dist/web/assets/index-InmdAx6g.js +120 -0
- package/dist/web/assets/index-InmdAx6g.js.map +1 -0
- package/dist/web/index.html +2 -2
- package/dist/{web-U34XTVBA.js → web-IYUNJMQD.js} +241 -263
- package/dist/web-IYUNJMQD.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/chunk-3NXRBRRJ.js.map +0 -1
- package/dist/chunk-CYXMVMVO.js.map +0 -1
- package/dist/chunk-FK2ZZUR5.js.map +0 -1
- package/dist/chunk-JT5AR7PO.js.map +0 -1
- package/dist/chunk-MYXLQMF7.js +0 -9
- package/dist/chunk-PDWEPIL6.js.map +0 -1
- package/dist/chunk-RVT4435Z.js.map +0 -1
- package/dist/chunk-ZJSEDIFT.js.map +0 -1
- package/dist/pty-host-I2I7SVOL.js.map +0 -1
- package/dist/web/assets/PtyView-Cg5gjgaQ.js +0 -96
- package/dist/web/assets/PtyView-Cg5gjgaQ.js.map +0 -1
- package/dist/web/assets/index-BOyg0f4L.css +0 -1
- package/dist/web/assets/index-CBK3PI8Y.js +0 -119
- package/dist/web/assets/index-CBK3PI8Y.js.map +0 -1
- package/dist/web-U34XTVBA.js.map +0 -1
- /package/dist/{add-repo-AA3XTOZT.js.map → add-repo-EDU3QEYI.js.map} +0 -0
- /package/dist/{answer-NT62U5MY.js.map → answer-MHOJ2J6S.js.map} +0 -0
- /package/dist/{block-YZQGJMLI.js.map → block-D5CAR53T.js.map} +0 -0
- /package/dist/{broadcast-2NOVIUZI.js.map → broadcast-LLYHUWXA.js.map} +0 -0
- /package/dist/{catchup-LZ5FMXEO.js.map → catchup-2SL3JGA7.js.map} +0 -0
- /package/dist/{chunk-ODBA4PVE.js.map → chunk-26OVU2AE.js.map} +0 -0
- /package/dist/{chunk-GEGRI67Z.js.map → chunk-3C3BKZ3H.js.map} +0 -0
- /package/dist/{chunk-BDFAIHTM.js.map → chunk-63VY4YJM.js.map} +0 -0
- /package/dist/{chunk-VNNAKJZA.js.map → chunk-6E2I2FBJ.js.map} +0 -0
- /package/dist/{chunk-BNGX2JGD.js.map → chunk-72IBYKIY.js.map} +0 -0
- /package/dist/{chunk-SXPC4FQM.js.map → chunk-7OUIZ2YQ.js.map} +0 -0
- /package/dist/{chunk-BGKHI4FC.js.map → chunk-ATED7SAH.js.map} +0 -0
- /package/dist/{chunk-T6BX6B5B.js.map → chunk-BSP2Z7B7.js.map} +0 -0
- /package/dist/{chunk-PGZMPB2Q.js.map → chunk-CCTALU3C.js.map} +0 -0
- /package/dist/{chunk-N7EHLEYG.js.map → chunk-CLBQ7ZC4.js.map} +0 -0
- /package/dist/{chunk-4GVXOUVN.js.map → chunk-CMO5YUZR.js.map} +0 -0
- /package/dist/{chunk-JAU62YN5.js.map → chunk-CYWI3ZW7.js.map} +0 -0
- /package/dist/{chunk-QNH6ZRFV.js.map → chunk-DQCUYCMX.js.map} +0 -0
- /package/dist/{chunk-IGC64EGV.js.map → chunk-HCVONKJI.js.map} +0 -0
- /package/dist/{chunk-4OK2WJ2B.js.map → chunk-HEPBANFJ.js.map} +0 -0
- /package/dist/{chunk-AHA65ZCO.js.map → chunk-INQQGV2G.js.map} +0 -0
- /package/dist/{chunk-AQJSY4CI.js.map → chunk-IPGH7TXJ.js.map} +0 -0
- /package/dist/{chunk-HJZSMSP4.js.map → chunk-IWJXFNM4.js.map} +0 -0
- /package/dist/{chunk-JFN67PRA.js.map → chunk-KSUOVFO3.js.map} +0 -0
- /package/dist/{chunk-7NSQVIIK.js.map → chunk-MG5TTLYZ.js.map} +0 -0
- /package/dist/{chunk-MYXLQMF7.js.map → chunk-NWIVXGSL.js.map} +0 -0
- /package/dist/{chunk-HKK3WUPZ.js.map → chunk-P6BHOAQG.js.map} +0 -0
- /package/dist/{chunk-RCZZAQFN.js.map → chunk-PRDRRU2B.js.map} +0 -0
- /package/dist/{chunk-6KOJSRML.js.map → chunk-QEVYCCKD.js.map} +0 -0
- /package/dist/{chunk-7NZC7EAP.js.map → chunk-QHTXLCG7.js.map} +0 -0
- /package/dist/{chunk-A633PJUP.js.map → chunk-QL36KN7X.js.map} +0 -0
- /package/dist/{chunk-7POCHRUP.js.map → chunk-QSOEMCWQ.js.map} +0 -0
- /package/dist/{chunk-J4Y7DKQN.js.map → chunk-RFINYWID.js.map} +0 -0
- /package/dist/{chunk-4WG66W6U.js.map → chunk-S3FMTEFR.js.map} +0 -0
- /package/dist/{chunk-MVMLNEHM.js.map → chunk-T7AFYEQ7.js.map} +0 -0
- /package/dist/{chunk-MPY2ZQBL.js.map → chunk-VUAVPBFR.js.map} +0 -0
- /package/dist/{chunk-UJWMBDFX.js.map → chunk-WTQ2QCAG.js.map} +0 -0
- /package/dist/{chunk-7OTYC7T5.js.map → chunk-WXE7D44E.js.map} +0 -0
- /package/dist/{chunk-IJSW2U6U.js.map → chunk-WXMWZRBH.js.map} +0 -0
- /package/dist/{chunk-FXWY22ZP.js.map → chunk-XVNRP7XE.js.map} +0 -0
- /package/dist/{chunk-2Z2O5LEA.js.map → chunk-ZI2KXTKM.js.map} +0 -0
- /package/dist/{cli-PAICDKJT.js.map → cli-AF7636FA.js.map} +0 -0
- /package/dist/{config-U4SGJ7RB.js.map → config-6MSITKGB.js.map} +0 -0
- /package/dist/{diff-CYXW5YWD.js.map → diff-Q7MV6YGJ.js.map} +0 -0
- /package/dist/{digest-KRIBJHII.js.map → digest-KUMVYXKZ.js.map} +0 -0
- /package/dist/{history-DCALTZMM.js.map → history-5WKRWARZ.js.map} +0 -0
- /package/dist/{hydrate-KBWZSSBL.js.map → hydrate-LCT6DVB3.js.map} +0 -0
- /package/dist/{init-R47WGD62.js.map → init-FJKPEY5N.js.map} +0 -0
- /package/dist/{install-skills-IIMTRQ4K.js.map → install-skills-UYAFVJBA.js.map} +0 -0
- /package/dist/{list-X5YB4JRL.js.map → list-GTKP5FAW.js.map} +0 -0
- /package/dist/{move-WSK5UU5T.js.map → move-GOCLEFGZ.js.map} +0 -0
- /package/dist/{note-VMO2PKYX.js.map → note-B7TQBXQF.js.map} +0 -0
- /package/dist/{overlaps-ZNZTQHU7.js.map → overlaps-UKQHIJMU.js.map} +0 -0
- /package/dist/{pin-RGRNNJUL.js.map → pin-UZZCDK7M.js.map} +0 -0
- /package/dist/{read-E22APCUR.js.map → read-U6GBGA5E.js.map} +0 -0
- /package/dist/{recent-F3Z3JXFX.js.map → recent-2DUMLUDG.js.map} +0 -0
- /package/dist/{restart-BAGGJDD2.js.map → restart-QEW4DJC3.js.map} +0 -0
- /package/dist/{resume-PIFCI727.js.map → resume-K45IT4QO.js.map} +0 -0
- /package/dist/{run-MW3QTOXU.js.map → run-42LORGPS.js.map} +0 -0
- /package/dist/{screen-UILBPWSR.js.map → screen-2TLIUH3G.js.map} +0 -0
- /package/dist/{search-DLZEPI4I.js.map → search-7E4B2KX6.js.map} +0 -0
- /package/dist/{section-A5JKTX4J.js.map → section-OVA5VD7L.js.map} +0 -0
- /package/dist/{send-EPPQKYOK.js.map → send-BJY5CYLO.js.map} +0 -0
- /package/dist/{snooze-GA46Z56G.js.map → snooze-WIVKB3GH.js.map} +0 -0
- /package/dist/{start-L6G3NC2J.js.map → start-G6GR533S.js.map} +0 -0
- /package/dist/{state-OZF4S7PG.js.map → state-S3DGLT4J.js.map} +0 -0
- /package/dist/{status-H5S3DZBI.js.map → status-BTAWY6JQ.js.map} +0 -0
- /package/dist/{statusline-RSQMMCRN.js.map → statusline-WLXEU5DM.js.map} +0 -0
- /package/dist/{stop-HQLHTY5V.js.map → stop-FN6EPFJ4.js.map} +0 -0
- /package/dist/{time-H54NH62B.js.map → time-5CH5O5MZ.js.map} +0 -0
- /package/dist/{time-actions-DB7OQ2IS.js.map → time-actions-XEUQ3UF7.js.map} +0 -0
- /package/dist/{timesheet-PAS5SHPD.js.map → timesheet-FMQKPS5S.js.map} +0 -0
- /package/dist/{todo-ODF7RI27.js.map → todo-23COLGR2.js.map} +0 -0
- /package/dist/{update-M7ECF7UE.js.map → update-PJRSKQZ2.js.map} +0 -0
- /package/dist/{usage-IFKUY6LC.js.map → usage-TL66LWO4.js.map} +0 -0
- /package/dist/{wait-K3NSSNFR.js.map → wait-YIEJO6YM.js.map} +0 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@moberg_hr/work-tree",
|
|
3
|
-
"version": "2.9.
|
|
3
|
+
"version": "2.9.3",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@moberg_hr/work-tree",
|
|
9
|
-
"version": "2.9.
|
|
9
|
+
"version": "2.9.3",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "MIT",
|
|
12
12
|
"dependencies": {
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/pty/pty-host-protocol.ts","../src/core/pty/pty-host-client.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { getConfigDir } from '../platform/config.js';\nimport type { AiToolSpec } from '../platform/ai-launcher.js';\nimport { isEnvDelta, type EnvDelta } from '../platform/env-delta.js';\n\n/**\n * Wire contract between the PTY host (`work pty-host`, the long-lived\n * process that owns every Claude PTY) and its clients (`work web`,\n * `work attach`). Bump PROTOCOL_VERSION on any incompatible change: a\n * client that finds an older host running tells the user to restart it\n * (`work pty-host --restart`) instead of silently misbehaving — the host\n * outlives rebuilds by design.\n *\n * 2: the restore list moved from pty-sessions.json into state.db. A v1 host\n * still writes the file, which a v2 host adopts on start\n * (adoptLegacyRestoreList).\n */\nexport const PROTOCOL_VERSION = 2;\n\n/**\n * What this host can do beyond PROTOCOL_VERSION, answered by `/health` (additive: a host from before answers none).\n * `agentEnv`: it applies a spawn's / restart's / resume's `agentEnv` (a session's Claude account); `halt`: halt / resume.\n * A client asks before sending something an older host would silently drop (pty-pool.ts).\n */\nexport const HOST_FEATURES = ['agentEnv', 'halt'] as const;\nexport type HostFeature = (typeof HOST_FEATURES)[number];\n\n/** Discovery file: where the running host listens and its auth token. */\nexport interface HostInfo {\n pid: number;\n port: number;\n token: string;\n version: number;\n}\n\n/** What a client asks the host to spawn. The host decides `--continue`\n * itself (see `hasClaudeConversation`) so restores after a reboot make\n * the same call a fresh spawn would. */\nexport interface SpawnSpec {\n cwd: string;\n tool: AiToolSpec;\n port?: number;\n cols?: number;\n rows?: number;\n /** `--unsafe`: the tool's skip-permissions flag. Persisted, so a restore\n * comes back with the same permission mode. */\n unsafe?: boolean;\n /** `--fresh`: start a new conversation even if one exists. First spawn\n * only — a restore always continues. */\n fresh?: boolean;\n /** `--prompt` / `--prompt-file` contents. First spawn only. */\n initialPrompt?: string;\n /** The launching shell's environment. First spawn only and never\n * persisted — it can hold secrets; a restore after reboot uses the\n * host's own environment. */\n env?: Record<string, string>;\n /**\n * What the agent's environment differs by for this session (its account's `CLAUDE_CONFIG_DIR`: set, or `null` = taken\n * out), applied over whatever environment the process starts with — the shell's, or the host's own. Persisted (a\n * folder path is no secret), so a restore keeps it. Additive, no PROTOCOL_VERSION bump: a host from before ignores\n * it and starts the agent on the environment it inherits (`work pty-host --restart` after upgrading).\n */\n agentEnv?: EnvDelta;\n}\n\n/** One entry of the host's restore list: how to respawn a session. The\n * spec as launched, minus `env` (never persisted: it can hold secrets) —\n * except the variables config `hostEnv` names (`keptEnv`), which a restore\n * after a reboot puts back over the host's own environment. */\nexport interface PersistedPty extends SpawnSpec {\n startedAt: string;\n keptEnv?: Record<string, string>;\n}\n\n/** Names that look like secrets (or carry them, as a connection string does): never kept on disk, whatever `hostEnv` says. */\nconst SECRET_NAME =\n /TOKEN|SECRET|PASS|PWD|CREDENTIAL|PRIVATE|KEY|AUTH|BEARER|COOKIE|SESSION|CERT|SIGN|SALT|(^|_)PAT($|_)|DSN|CONN|DATABASE_URL|_URI$|_URL$/i;\n/** Values that carry a password whatever their name: `scheme://user:pass@host`. */\nconst SECRET_VALUE = /:\\/\\/[^/\\s:@]+:[^/\\s@]+@/;\n\n/** Always kept for a restore, whatever `hostEnv` says: the agent's account folder (a path, not a secret — SECRET_VALUE still applies). */\nexport const ALWAYS_KEPT_ENV = ['CLAUDE_CONFIG_DIR'] as const;\n\n/** The variables of `env` to keep for a restore: the ones named (and `ALWAYS_KEPT_ENV`), that exist, and look like neither a secret nor a URL with a password in it. Pure. */\nexport function keepEnv(env: Record<string, string> | undefined, names: readonly string[]): Record<string, string> | undefined {\n if (!env) return undefined;\n const kept = Object.fromEntries(\n [...new Set([...names, ...ALWAYS_KEPT_ENV])]\n .filter((n) => !SECRET_NAME.test(n) && typeof env[n] === 'string' && !SECRET_VALUE.test(env[n]))\n .map((n) => [n, env[n]]),\n );\n return Object.keys(kept).length ? kept : undefined;\n}\nexport type PersistedPtys = Record<string, PersistedPty>;\n\n/** Shape check for a restore-list entry read back from storage. */\nexport function isPersistedPty(x: unknown): x is PersistedPty {\n const e = x as PersistedPty | null;\n return (\n !!e &&\n typeof e === 'object' &&\n typeof e.cwd === 'string' &&\n !!e.tool &&\n typeof e.tool === 'object' &&\n (e.agentEnv === undefined || isEnvDelta(e.agentEnv)) &&\n (e.keptEnv === undefined ||\n (!!e.keptEnv && typeof e.keptEnv === 'object' && Object.values(e.keptEnv).every((v) => typeof v === 'string')))\n );\n}\n\nexport interface PtyInfo {\n id: string;\n cwd: string;\n pid: number;\n exited: boolean;\n cols: number;\n rows: number;\n startedAt: string;\n /** Respawned by the host on startup from the persisted session list\n * (after a crash, `--restart` or reboot), not by a client. */\n restored: boolean;\n /** Clients attached right now (dashboard Terminal tabs, `work attach`).\n * Additive: a host from before it sends none. */\n clients?: number;\n /** When the PTY last printed anything (ISO). Additive, like clients. */\n lastOutputAt?: string;\n /** The tool's binary (`claude`, `opencode`…). Additive, like clients. */\n tool?: string;\n}\n\n/** Client → host frames on the attach WebSocket (text, JSON). Host →\n * client PTY output is sent as binary frames; control frames as text. */\nexport type ClientFrame = { type: 'input'; data: string } | { type: 'resize'; cols: number; rows: number };\n\nexport type HostControlFrame =\n /** Sent once, first, on attach: the serialized screen and the grid it was\n * drawn for. Clients draw it at exactly cols×rows, then resize to their\n * own size (which makes Claude redraw), and only then send input. */\n { type: 'replay'; data: string; cols: number; rows: number } | { type: 'exit'; code: number } | { type: 'error'; message: string };\n\nexport function hostInfoPath(): string {\n return path.join(getConfigDir(), 'pty-host.json');\n}\n\n/** Held by a starting host from \"is one running?\" through writing its\n * discovery file AND restoring the saved sessions — so two hosts can't\n * both start, and a `work remove` racing a start waits for the restore\n * instead of slipping between it (see stopSessionPty). */\nexport function hostStartLockPath(): string {\n return path.join(getConfigDir(), 'pty-host.start.lock');\n}\n\n/** The pre-SQLite restore list. Only the one-time import reads it now. */\nexport function ptySessionsPath(): string {\n return path.join(getConfigDir(), 'pty-sessions.json');\n}\n\nexport function readHostInfo(): HostInfo | null {\n try {\n const raw = JSON.parse(fs.readFileSync(hostInfoPath(), 'utf-8')) as HostInfo;\n if (typeof raw.port === 'number' && typeof raw.token === 'string' && typeof raw.pid === 'number') {\n return raw;\n }\n return null;\n } catch {\n return null;\n }\n}\n","import path from 'node:path';\nimport { spawnDetachedWork } from '../platform/process.js';\nimport { getConfigDir } from '../platform/config.js';\nimport { isPidAlive } from '../platform/process.js';\nimport { ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport type { EnvDelta } from '../platform/env-delta.js';\nimport { PROTOCOL_VERSION, readHostInfo, type HostInfo, type PtyInfo, type SpawnSpec } from './pty-host-protocol.js';\n\nexport class PtyHostVersionError extends Error {\n constructor(readonly hostVersion: number) {\n super(\n `A PTY host from an older build (protocol v${hostVersion}, need v${PROTOCOL_VERSION}) ` +\n 'is running. Restart it with `work pty-host --restart` — sessions come back via --continue.',\n );\n }\n}\n\n/**\n * Ask whoever listens on the discovery file's port whether it's our host:\n * it must answer /health with our token. Returns what it reports (its\n * protocol version and pid), or null if nothing answers / the token is\n * wrong — i.e. the discovery file is stale.\n */\nexport async function probeHost(info: HostInfo, timeoutMs = 800): Promise<{ version: number; pid: number } | null> {\n const r = await probeHostDetailed(info, timeoutMs);\n return r.kind === 'host' ? { version: r.version, pid: r.pid } : null;\n}\n\nexport type ProbeResult =\n | { kind: 'host'; version: number; pid: number }\n /** Nothing listens on the port (connection refused): definitely gone. */\n | { kind: 'refused' }\n /** Something answered, but not as our host (wrong token, bad body). */\n | { kind: 'not-ours' }\n /** No answer in time — could be a BUSY host (e.g. restoring many\n * sessions). Never treat this as proof the host is gone. */\n | { kind: 'timeout' };\n\nexport async function probeHostDetailed(info: HostInfo, timeoutMs = 800): Promise<ProbeResult> {\n try {\n const res = await fetch(`http://127.0.0.1:${info.port}/health`, {\n headers: { 'x-work-token': info.token },\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return { kind: 'not-ours' };\n const body = (await res.json()) as { version?: number; pid?: number };\n if (typeof body.version !== 'number' || typeof body.pid !== 'number') return { kind: 'not-ours' };\n return { kind: 'host', version: body.version, pid: body.pid };\n } catch (err) {\n const e = err as { name?: string; cause?: { code?: string } };\n if (e.cause?.code === 'ECONNREFUSED') return { kind: 'refused' };\n if (e.name === 'TimeoutError' || e.name === 'AbortError') return { kind: 'timeout' };\n return { kind: 'refused' };\n }\n}\n\n/** A host is there but didn't answer in time (event loop busy: a ConPTY\n * spawn, restoring many sessions). It is RUNNING — never start another. */\nexport class PtyHostBusyError extends Error {\n constructor() {\n super('The PTY host is running but not answering (busy?). Try again in a moment.');\n this.name = 'PtyHostBusyError';\n }\n}\n\n/**\n * The running host, or null when there is none. Throws PtyHostVersionError\n * on a mismatch, and PtyHostBusyError when a host holds the port but\n * doesn't answer even a patient second probe — treating that as \"no host\"\n * would start a second one, which restores every session again (two\n * Claudes per conversation).\n */\nexport async function findHost(timeoutsMs: number[] = [800, 5000]): Promise<HostInfo | null> {\n const info = readHostInfo();\n if (!info) return null;\n let probe: ProbeResult = { kind: 'timeout' };\n for (const t of timeoutsMs) {\n probe = await probeHostDetailed(info, t);\n if (probe.kind !== 'timeout') break;\n }\n if (probe.kind === 'timeout') {\n // No answer: a host whose process is alive is busy — but a dead one\n // (crashed, killed) left a stale file, and whatever now holds that port\n // is not our host. Calling THAT busy would make the host unstartable.\n if (!isPidAlive(info.pid)) return null;\n throw new PtyHostBusyError();\n }\n if (probe.kind !== 'host' || probe.pid !== info.pid) return null;\n if (probe.version !== PROTOCOL_VERSION) throw new PtyHostVersionError(probe.version);\n return info;\n}\n\n/**\n * findHost that waits out a busy host: retries until it answers or\n * `timeoutMs` passes, then throws PtyHostBusyError. For callers that must\n * reach the host (stopping a session before its worktree is deleted).\n */\nexport async function findHostPatient(timeoutMs = 20_000): Promise<HostInfo | null> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n return await findHost();\n } catch (err) {\n if (!(err instanceof PtyHostBusyError) || Date.now() >= deadline) throw err;\n await new Promise((r) => setTimeout(r, 250));\n }\n }\n}\n\n/** findHost for \"should I start one?\": a busy host counts as running. */\nasync function findHostOrBusy(): Promise<HostInfo | 'busy' | null> {\n try {\n return await findHost();\n } catch (err) {\n if (err instanceof PtyHostBusyError) return 'busy';\n throw err;\n }\n}\n\n/** Serializes host spawning across `work` processes (see ensureHost). */\nexport function hostSpawnLockPath(): string {\n return path.join(getConfigDir(), 'pty-host.spawn.lock');\n}\n\nlet inFlight: Promise<HostInfo> | null = null;\n\n/**\n * Return the running host, spawning a detached one if none is. `workBin` is\n * the path to the `work` binary (dist/bin.js) — passed in rather than\n * derived because core can't reach the commands layer's resolver (§2.1).\n *\n * Exactly one host may start: two hosts would each restore every saved\n * session — two Claudes on one conversation. So spawning is single-flight\n * within this process (concurrent callers share one attempt) and serialized\n * across processes by a file lock held from \"is one running?\" until the new\n * host answers; a caller that waited on the lock re-checks and finds it.\n */\n// A cold host start loads the whole `work` bundle; on a busy machine (right\n// after login with autostart, or a loaded test run) that can pass 8 s.\nexport function ensureHost(workBin: string, timeoutMs = 20_000): Promise<HostInfo> {\n if (!inFlight) {\n inFlight = ensureHostLocked(workBin, timeoutMs).finally(() => {\n inFlight = null;\n });\n }\n return inFlight;\n}\n\nasync function ensureHostLocked(workBin: string, timeoutMs: number): Promise<HostInfo> {\n const existing = await findHostOrBusy();\n if (existing === 'busy') return waitForHost(timeoutMs); // it's there; wait for it to answer\n if (existing) return existing;\n const lock = hostSpawnLockPath();\n ensureFile(lock, '');\n try {\n return await withFileLock(lock, async () => {\n // Another process may have started it while we waited for the lock.\n const started = await findHostOrBusy();\n if (started === 'busy') return waitForHost(timeoutMs);\n if (started) return started;\n spawnHost(workBin);\n return waitForHost(timeoutMs);\n });\n } catch (err) {\n // Couldn't get the lock in time (another process is mid-spawn and slow):\n // don't spawn a second one — wait for theirs.\n if ((err as { code?: string }).code === 'ELOCKED') return waitForHost(timeoutMs);\n throw err;\n }\n}\n\nfunction spawnHost(workBin: string): void {\n spawnDetachedWork(workBin, ['pty-host'], path.join(getConfigDir(), 'pty-host.log'));\n}\n\nasync function waitForHost(timeoutMs: number): Promise<HostInfo> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const found = await findHost().catch(() => null);\n if (found) return found;\n await new Promise((r) => setTimeout(r, 100));\n }\n throw new Error('PTY host did not start (see ~/.work/pty-host.log)');\n}\n\nexport class PtyHostClient {\n constructor(readonly info: HostInfo) {}\n\n /** What the host said it supports (`/health`'s `features`), asked once per host (a client is one host). */\n private featureList: readonly string[] | null = null;\n\n /**\n * The host's features (HOST_FEATURES): [] for a host from before they were answered. Null when it couldn't be asked\n * (not answering in time): unknown, asked again next time.\n */\n async features(): Promise<readonly string[] | null> {\n if (this.featureList) return this.featureList;\n try {\n const res = await fetch(`http://127.0.0.1:${this.info.port}/health`, {\n headers: { 'x-work-token': this.info.token },\n signal: AbortSignal.timeout(5000),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { features?: unknown };\n const list = Array.isArray(body.features) ? body.features.filter((f): f is string => typeof f === 'string') : [];\n this.featureList = list;\n return list;\n } catch {\n return null;\n }\n }\n\n private async call<T>(method: string, p: string, body?: unknown): Promise<T> {\n const res = await fetch(`http://127.0.0.1:${this.info.port}${p}`, {\n method,\n headers: {\n 'x-work-token': this.info.token,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: AbortSignal.timeout(5000),\n });\n const json = (await res.json().catch(() => ({}))) as T & { error?: string };\n if (!res.ok) throw new Error(json.error ?? `PTY host ${method} ${p}: ${res.status}`);\n return json;\n }\n\n list(): Promise<PtyInfo[]> {\n return this.call('GET', '/ptys');\n }\n\n get(id: string): Promise<PtyInfo | null> {\n return this.call<PtyInfo>('GET', `/ptys/${encodeURIComponent(id)}`).catch(() => null);\n }\n\n spawn(id: string, spec: SpawnSpec): Promise<PtyInfo> {\n return this.call('POST', `/ptys/${encodeURIComponent(id)}`, spec);\n }\n\n /** The session's visible screen as text; null when it has none — or the\n * host predates this call (404 either way: nothing to answer by key). */\n async screen(id: string): Promise<string | null> {\n try {\n const r = await this.call<{ text?: unknown }>('GET', `/ptys/${encodeURIComponent(id)}/screen`);\n return typeof r.text === 'string' ? r.text : null;\n } catch {\n return null;\n }\n }\n\n async write(id: string, data: string): Promise<boolean> {\n try {\n await this.call('POST', `/ptys/${encodeURIComponent(id)}/write`, { data });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Its agent restarted in place, the attached terminals kept (registry.restart).\n * `unsupported`: a host from before the call (404) — stop and start it instead. With `agentEnv` (a session moved to\n * another account) a host that restarted it without taking the environment (one from before it) is `unsupported` too:\n * what runs now is on the old account, and the caller starts it again.\n */\n async restart(id: string, opts: { agentEnv?: EnvDelta } = {}): Promise<'restarted' | 'not-running' | 'unsupported'> {\n const res = await fetch(`http://127.0.0.1:${this.info.port}/ptys/${encodeURIComponent(id)}/restart`, {\n method: 'POST',\n headers: { 'x-work-token': this.info.token, ...(opts.agentEnv ? { 'content-type': 'application/json' } : {}) },\n ...(opts.agentEnv ? { body: JSON.stringify({ agentEnv: opts.agentEnv }) } : {}),\n // Waits for the old process to exit (up to 3 s) before the new one starts.\n signal: AbortSignal.timeout(15_000),\n });\n if (res.ok) {\n if (!opts.agentEnv) return 'restarted';\n const json = (await res.json().catch(() => null)) as { agentEnvApplied?: unknown } | null;\n return json?.agentEnvApplied === true ? 'restarted' : 'unsupported';\n }\n if (res.status === 409) return 'not-running';\n if (res.status === 404) return 'unsupported';\n const json = (await res.json().catch(() => ({}))) as { error?: string };\n throw new Error(json.error ?? `PTY host restart ${id}: ${res.status}`);\n }\n\n /**\n * Stop its agent and keep the session (entry, terminals) until `resume`. `unsupported`: a host from before the call (404):\n * nothing was stopped — the caller stops it the old way.\n */\n async halt(id: string): Promise<'halted' | 'not-running' | 'unsupported'> {\n const res = await fetch(`http://127.0.0.1:${this.info.port}/ptys/${encodeURIComponent(id)}/halt`, {\n method: 'POST',\n headers: { 'x-work-token': this.info.token },\n signal: AbortSignal.timeout(15_000),\n });\n if (res.ok) return 'halted';\n if (res.status === 409) return 'not-running';\n if (res.status === 404) return 'unsupported';\n const json = (await res.json().catch(() => ({}))) as { error?: string };\n throw new Error(json.error ?? `PTY host halt ${id}: ${res.status}`);\n }\n\n /** Start a halted agent again in place (`--continue`), on `agentEnv` when given. `not-halted`: it isn't halted (resumed already, or gone). */\n async resume(id: string, opts: { agentEnv?: EnvDelta } = {}): Promise<'resumed' | 'not-halted'> {\n const res = await fetch(`http://127.0.0.1:${this.info.port}/ptys/${encodeURIComponent(id)}/resume`, {\n method: 'POST',\n headers: { 'x-work-token': this.info.token, 'content-type': 'application/json' },\n body: JSON.stringify(opts.agentEnv ? { agentEnv: opts.agentEnv } : {}),\n signal: AbortSignal.timeout(15_000),\n });\n if (res.ok) return 'resumed';\n if (res.status === 409) return 'not-halted';\n const json = (await res.json().catch(() => ({}))) as { error?: string };\n throw new Error(json.error ?? `PTY host resume ${id}: ${res.status}`);\n }\n\n async kill(id: string): Promise<void> {\n await this.call('DELETE', `/ptys/${encodeURIComponent(id)}`);\n }\n\n attachUrl(id: string): string {\n return `ws://127.0.0.1:${this.info.port}/ptys/${encodeURIComponent(id)}/attach?token=${this.info.token}`;\n }\n}\n"],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B,EAAE,CAAC,iBAAiB,KAAK,KAAK,KAAK;AAAA,EACxG;AACF;","names":["path","path","json"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/pr/pr-watch-store.ts","../src/core/pr/pr-replies.ts"],"sourcesContent":["import { json, withDb } from '../platform/db.js';\nimport type { SessionCi } from '../api-types.js';\n\n/**\n * What the PR watch has already acted on, per session: state.db's\n * `pr_watch_seen` (session_id, key). Keys are review-comment ids, per-PR\n * baselines, and CI head commits already reported (see pr-watch.ts /\n * pr-review.ts). Removed with the session (db.ts purgeSessionRows); no cap.\n *\n * No in-memory cache: each check is one primary-key lookup, and a cache\n * outlived the session it belonged to — a session removed and re-created\n * with the same target:branch inherited the old keys and had its review\n * comments and CI failures suppressed.\n */\n\n/** A per-session seen-store. (Structurally the SeenStore of pr-review.ts —\n * not imported, to keep the ship/history types out of an import cycle.) */\nexport function createSeenStores(): (sessionId: string) => { has: (k: string) => boolean; add: (k: string) => void } {\n return (sessionId) => ({\n has: (k) => withDb((d) => d.prepare('SELECT 1 FROM pr_watch_seen WHERE session_id = ? AND key = ?').get(sessionId, k)) !== undefined,\n add: (k) => {\n try {\n withDb((d) => d.prepare('INSERT OR IGNORE INTO pr_watch_seen (session_id, key) VALUES (?, ?)').run(sessionId, k));\n } catch {\n /* best-effort: worst case something is reported twice */\n }\n },\n });\n}\n\n/**\n * The PR watch's last check of each session: state.db's `pr_watch_state`\n * (session_id, data), removed with the session. Kept so a restarted work web\n * shows each session's PRs at once rather than after its first sweep reaches\n * it (a minute or two with many sessions); that sweep then replaces it.\n */\nexport interface CiStore {\n load(): Array<[string, SessionCi]>;\n save(sessionId: string, ci: SessionCi): void;\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\nconst PR_STATES = new Set(['OPEN', 'MERGED', 'CLOSED']);\n\n/** A stored open thread as the watch wrote it (`OpenReviewThread`). */\nfunction isOpenThread(t: unknown): boolean {\n return (\n isObject(t) &&\n ['threadId', 'repo', 'url', 'reviewer', 'excerpt'].every((k) => typeof t[k] === 'string') &&\n typeof t.prNumber === 'number' &&\n (t.where === null || typeof t.where === 'string') &&\n (t.trusted === undefined || typeof t.trusted === 'boolean')\n );\n}\n\n/** A stored check as the watch wrote it (the fields its readers rely on, its open threads' too); anything else is dropped. */\nexport function isSessionCi(v: unknown): v is SessionCi {\n if (!isObject(v) || typeof v.checkedAt !== 'string' || !Array.isArray(v.repos)) return false;\n return v.repos.every(\n (r) =>\n isObject(r) &&\n typeof r.name === 'string' &&\n typeof r.done === 'boolean' &&\n (r.pr === null ||\n (isObject(r.pr) &&\n typeof r.pr.number === 'number' &&\n typeof r.pr.url === 'string' &&\n typeof r.pr.state === 'string' &&\n PR_STATES.has(r.pr.state) &&\n typeof r.pr.headSha === 'string')) &&\n (r.openThreads === undefined || typeof r.openThreads === 'number') &&\n (r.threads === undefined || (Array.isArray(r.threads) && r.threads.every(isOpenThread))),\n );\n}\n\nexport function createCiStore(): CiStore {\n return {\n load() {\n let rows: Array<{ session_id: string; data: string }>;\n try {\n rows = withDb((d) => d.prepare('SELECT session_id, data FROM pr_watch_state').all() as Array<{ session_id: string; data: string }>);\n } catch {\n return []; // best-effort, as saving is: the sweep fills it in\n }\n const out: Array<[string, SessionCi]> = [];\n for (const r of rows) {\n const ci = json.parse(r.data);\n if (isSessionCi(ci)) out.push([r.session_id, ci]);\n }\n return out;\n },\n save(sessionId, ci) {\n try {\n withDb((d) =>\n d.prepare('INSERT OR REPLACE INTO pr_watch_state (session_id, data) VALUES (?, ?)').run(sessionId, JSON.stringify(ci)),\n );\n } catch {\n /* best-effort: a restart then waits for the sweep, as before */\n }\n },\n };\n}\n","import { json, tx, withDb, type Db } from '../platform/db.js';\nimport type { PrReply, SessionCi } from '../api-types.js';\nimport type { CommandRunner } from './ship.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { isSessionCi } from './pr-watch-store.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport { sessionRepos } from '../sessions/session-repos.js';\nimport { loadConfig } from '../platform/config.js';\nimport { readGitConfig } from '../worktree/repo-scan.js';\nimport { githubRepoOf } from './pr.js';\nimport { checkedOutBranch } from '../git/git-head.js';\n\n/**\n * Replies to PR review threads, drafted by the session's Claude and posted\n * with your yes. The PR watch records each thread it hands over\n * (`rememberSent`); Claude drafts an answer with `work pr reply <thread id>\n * \"<text>\"` (`saveDraft`) and shows you; the dashboard shows the drafts too,\n * editable. What appears on GitHub is in your name, so a draft goes out\n * only once you've said yes: your Post click, or Claude running `work pr\n * post` after you agreed in the conversation (`postDrafts`; never on the\n * assistant's allow list, so Claude Code asks you as well).\n *\n * Rows live in state.db `pr_replies`, keyed by session + thread, and go\n * with the session (purgeSessionRows). A thread the PR watch lists as open\n * for the session (its last check, `pr_watch_state`) can be drafted too:\n * \"Ask Claude to reply\" hands one over as a plain note, with no row here.\n */\n\n/** GitHub review-thread node ids. Checked before a thread id reaches gh or the database. */\nexport const THREAD_ID = /^PRRT_[A-Za-z0-9_-]{4,120}$/;\nexport const MAX_REPLY_CHARS = 20_000;\n\nfunction parseRow(data: string): PrReply | null {\n const v = json.parse(data);\n if (!v || typeof v !== 'object') return null;\n const r = v as Record<string, unknown>;\n const str = (k: string) => typeof r[k] === 'string';\n if (\n !str('threadId') ||\n !str('repo') ||\n typeof r.prNumber !== 'number' ||\n !str('url') ||\n !str('reviewer') ||\n !str('excerpt') ||\n !str('sentAt')\n )\n return null;\n if (r.status !== 'sent' && r.status !== 'draft' && r.status !== 'posted') return null;\n return v as PrReply;\n}\n\nfunction read(sessionId: string, threadId: string): PrReply | null {\n const row = withDb(\n (d) =>\n d.prepare('SELECT data FROM pr_replies WHERE session_id = ? AND thread_id = ?').get(sessionId, threadId) as\n { data: string } | undefined,\n );\n return row ? parseRow(row.data) : null;\n}\n\nexport function listReplies(sessionId: string): PrReply[] {\n const rows = withDb((d) => d.prepare('SELECT data FROM pr_replies WHERE session_id = ?').all(sessionId) as Array<{ data: string }>);\n return rows\n .map((r) => parseRow(r.data))\n .filter((r): r is PrReply => r !== null)\n .sort((a, b) => a.sentAt.localeCompare(b.sentAt));\n}\n\n/** Drafts waiting for you, per session (one query for the whole session list). */\nexport function draftCounts(): Map<string, number> {\n const rows = withDb((d) => d.prepare('SELECT session_id, data FROM pr_replies').all() as Array<{ session_id: string; data: string }>);\n const out = new Map<string, number>();\n for (const r of rows) if (parseRow(r.data)?.status === 'draft') out.set(r.session_id, (out.get(r.session_id) ?? 0) + 1);\n return out;\n}\n\n/**\n * The threads just handed to the session's Claude. A thread seen again —\n * a reviewer answered in it — starts over: the old draft answered\n * something else.\n */\nexport function rememberSent(\n sessionId: string,\n threads: Array<Pick<PrReply, 'threadId' | 'repo' | 'prNumber' | 'url' | 'where' | 'reviewer' | 'excerpt'>>,\n now = new Date(),\n): void {\n tx((d) => {\n const put = d.prepare('INSERT OR REPLACE INTO pr_replies (session_id, thread_id, data) VALUES (?, ?, ?)');\n for (const t of threads) {\n if (!THREAD_ID.test(t.threadId)) continue;\n const row: PrReply = { ...t, status: 'sent', draft: null, sentAt: now.toISOString() };\n put.run(sessionId, t.threadId, JSON.stringify(row));\n }\n });\n}\n\nexport type DraftResult = { ok: true; reply: PrReply } | { ok: false; error: string };\n\n/**\n * The thread as the PR watch's last check of the session lists it, open (as of `checkedAt`): a reply's row is\n * made from it, never from what the drafter typed.\n */\nfunction openThreadOf(d: Db, sessionId: string, threadId: string, now: Date): { reply: PrReply; checkedAt: string } | null {\n const row = d.prepare('SELECT data FROM pr_watch_state WHERE session_id = ?').get(sessionId) as { data: string } | undefined;\n const ci = row ? json.parse(row.data) : null;\n if (!isSessionCi(ci)) return null;\n for (const r of ci.repos) {\n const t = r.threads?.find((x) => x.threadId === threadId);\n if (!t) continue;\n const { repo, prNumber, url, where, reviewer, excerpt } = t;\n const reply: PrReply = {\n threadId,\n repo,\n prNumber,\n url,\n where,\n reviewer,\n excerpt,\n status: 'sent',\n draft: null,\n sentAt: now.toISOString(),\n };\n return { reply, checkedAt: ci.checkedAt };\n }\n return null;\n}\n\n/**\n * Claude's (or your edited) answer to a thread it was handed, or one the PR watch lists as open for the session.\n * A thread answered before and listed open again since (the reviewer answered) starts over, as `rememberSent` does.\n * A session launched `--unsafe` (`opts.unsafe`) drafts only what the watch handed it: review text never reaches it.\n */\nexport function saveDraft(\n sessionId: string,\n threadId: string,\n body: string,\n now = new Date(),\n opts: { unsafe?: boolean; live?: PrReply } = {},\n): DraftResult {\n if (!THREAD_ID.test(threadId)) return { ok: false, error: `not a review thread id: ${threadId}` };\n const text = body.trim();\n if (!text) return { ok: false, error: 'the reply is empty' };\n if (text.length > MAX_REPLY_CHARS) return { ok: false, error: `the reply is over ${MAX_REPLY_CHARS} characters` };\n return tx((d) => {\n const row = d.prepare('SELECT data FROM pr_replies WHERE session_id = ? AND thread_id = ?').get(sessionId, threadId) as\n { data: string } | undefined;\n const handed = row ? parseRow(row.data) : null;\n const listed = opts.unsafe ? null : openThreadOf(d, sessionId, threadId, now);\n const raisedAgain =\n handed?.status === 'posted' && listed && Date.parse(listed.checkedAt) > Date.parse(handed.postedAt ?? '') ? listed.reply : null;\n // `live`: read from GitHub just now (draftReply), when work's last check hadn't it.\n const cur = raisedAgain ?? (handed?.status === 'posted' && opts.live ? opts.live : (handed ?? listed?.reply ?? opts.live ?? null));\n if (!cur)\n return {\n ok: false,\n error: `thread ${threadId} isn't an open review thread of this session's pull requests (as work last checked them)`,\n } as const;\n if (cur.status === 'posted') return { ok: false, error: 'a reply to this thread was already posted' } as const;\n const next: PrReply = { ...cur, status: 'draft', draft: text, draftedAt: now.toISOString() };\n d.prepare('INSERT OR REPLACE INTO pr_replies (session_id, thread_id, data) VALUES (?, ?, ?)').run(\n sessionId,\n threadId,\n JSON.stringify(next),\n );\n return { ok: true, reply: next } as const;\n });\n}\n\nexport function discardReply(sessionId: string, threadId: string): boolean {\n return withDb((d) => d.prepare('DELETE FROM pr_replies WHERE session_id = ? AND thread_id = ?').run(sessionId, threadId).changes > 0);\n}\n\nfunction markPosted(sessionId: string, threadId: string, body: string, postedUrl: string, resolved: boolean): void {\n tx((d) => {\n const row = d.prepare('SELECT data FROM pr_replies WHERE session_id = ? AND thread_id = ?').get(sessionId, threadId) as\n { data: string } | undefined;\n const cur = row ? parseRow(row.data) : null;\n if (!cur) return;\n const next: PrReply = { ...cur, status: 'posted', draft: body, postedAt: new Date().toISOString(), postedUrl, resolved };\n d.prepare('UPDATE pr_replies SET data = ? WHERE session_id = ? AND thread_id = ?').run(JSON.stringify(next), sessionId, threadId);\n });\n}\n\nconst ADD_REPLY = `mutation($threadId: ID!, $body: String!) {\n addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { url } }\n}`;\nconst RESOLVE = `mutation($threadId: ID!) { resolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } } }`;\n/** The thread as it is now, and who you are: the last check before a reply goes out. */\nconst THREAD_NOW = `query($threadId: ID!) {\n viewer { login }\n node(id: $threadId) { ... on PullRequestReviewThread { isResolved comments(last: 1) { nodes { author { login } } } } }\n}`;\n\n/**\n * Why a reply mustn't go out now, from the thread as GitHub has it: the last\n * word in it is already yours (you'd be answering yourself — a PR author's\n * own comment, handed over as if a reviewer's), or it was resolved since.\n * Null to go ahead. When gh can't say, it isn't posted (it'd be in your name). Exported for tests.\n */\nexport async function threadRefusal(threadId: string, cwd: string, run: CommandRunner): Promise<string | null> {\n const r = await run('gh', ['api', 'graphql', '-f', `query=${THREAD_NOW}`, '-f', `threadId=${threadId}`], cwd);\n if (r.code !== 0) return `couldn't read the thread on GitHub first: ${r.stderr.trim() || 'gh failed'}`;\n const j = json.parse(r.stdout) as {\n data?: {\n viewer?: { login?: unknown };\n node?: { isResolved?: unknown; comments?: { nodes?: Array<{ author?: { login?: unknown } | null } | null> } } | null;\n };\n } | null;\n const me = j?.data?.viewer?.login;\n const node = j?.data?.node;\n if (typeof me !== 'string' || !me || !node) return \"couldn't read the thread on GitHub first\";\n if (node.isResolved === true) return 'the thread was resolved on GitHub since: nothing to answer';\n const last = node.comments?.nodes?.at(-1)?.author?.login;\n if (typeof last === 'string' && last.toLowerCase() === me.toLowerCase())\n return 'the last word in this thread is already yours (@' + me + '): a reply would answer yourself';\n return null;\n}\n\nexport type PostResult = { ok: true; url: string; resolved: boolean } | { ok: false; error: string };\n\n/**\n * Post the reply from your GitHub account (gh), then resolve the thread if\n * asked. Run on your yes: the Post route (a POST behind the local-origin\n * guard) or `work pr post`. It re-reads the row first.\n */\nexport async function postReply(\n sessionId: string,\n threadId: string,\n body: string,\n opts: { resolve: boolean; cwd: string; run: CommandRunner },\n): Promise<PostResult> {\n if (!THREAD_ID.test(threadId)) return { ok: false, error: 'not a review thread id' };\n const text = body.trim();\n if (!text || text.length > MAX_REPLY_CHARS) return { ok: false, error: 'the reply is empty or too long' };\n const cur = read(sessionId, threadId);\n if (!cur) return { ok: false, error: 'no such thread for this session' };\n if (cur.status === 'posted') return { ok: false, error: 'already posted' };\n // Whatever handed it over, a reply never answers your own last word (reported: a PR author's\n // Claude answered his own comment, as if a reviewer's), nor a thread resolved meanwhile.\n const refusal = await threadRefusal(threadId, opts.cwd, opts.run);\n if (refusal) return { ok: false, error: refusal };\n // -f: raw strings (never @file / number parsing), argv only (no shell).\n const add = await opts.run(\n 'gh',\n ['api', 'graphql', '-f', `query=${ADD_REPLY}`, '-f', `threadId=${threadId}`, '-f', `body=${text}`],\n opts.cwd,\n );\n if (add.code !== 0) return { ok: false, error: add.stderr.trim() || 'gh could not post the reply' };\n let url = cur.url;\n const parsed = json.parse(add.stdout) as { data?: { addPullRequestReviewThreadReply?: { comment?: { url?: unknown } } } } | null;\n const got = parsed?.data?.addPullRequestReviewThreadReply?.comment?.url;\n if (typeof got === 'string') url = got;\n let resolved = false;\n if (opts.resolve) {\n const r = await opts.run('gh', ['api', 'graphql', '-f', `query=${RESOLVE}`, '-f', `threadId=${threadId}`], opts.cwd);\n resolved = r.code === 0;\n }\n markPosted(sessionId, threadId, text, url, resolved);\n return { ok: true, url, resolved };\n}\n\n/**\n * Post saved drafts as they stand (your edits in the dashboard included):\n * `work pr post`, which a session's Claude runs once you've said yes to\n * them in the conversation. One at a time, each re-checked by postReply.\n */\nexport async function postDrafts(\n session: { target: string; branch: string; paths: string[] },\n drafts: PrReply[],\n resolve: boolean,\n run: CommandRunner,\n): Promise<{ posted: Array<PrReply & { url: string; resolved: boolean }>; failed: Array<{ threadId: string; error: string }> }> {\n const id = sessionIdFor(session);\n const cwd = session.paths.find((p) => p) ?? process.cwd();\n const posted: Array<PrReply & { url: string; resolved: boolean }> = [];\n const failed: Array<{ threadId: string; error: string }> = [];\n for (const d of drafts) {\n const r = await postReply(id, d.threadId, d.draft ?? '', { resolve, cwd, run });\n if (r.ok) posted.push({ ...d, url: r.url, resolved: r.resolved });\n else failed.push({ threadId: d.threadId, error: r.error });\n }\n return { posted, failed };\n}\n\n/**\n * The replies posted after the PR watch last read GitHub (`checkedAt`): the\n * threads they answer still look unanswered in its check. Pure.\n */\nexport function postedSince(replies: PrReply[], checkedAt: string | null | undefined): string[] {\n const since = checkedAt ? Date.parse(checkedAt) : 0;\n return replies.filter((r) => r.status === 'posted' && r.postedAt && Date.parse(r.postedAt) > since).map((r) => r.threadId);\n}\n\n/**\n * A reply went out (your Post, or `work pr post` from the session's\n * Claude): take the threads it answered out of the PR watch's last check,\n * so the session stops saying a thread waits on you before the watch reads\n * GitHub again. Read from what was posted, not from the request.\n */\nexport function markPostedAnswered(\n sessionId: string,\n watch: { state(id: string): SessionCi | null; answered(id: string, threadId: string): void },\n): string[] {\n const threads = postedSince(listReplies(sessionId), watch.state(sessionId)?.checkedAt);\n for (const t of threads) watch.answered(sessionId, t);\n return threads;\n}\n\n/** A thread as GitHub has it now, with its pull request: what a draft can be made from when work's last check hasn't it. */\nconst THREAD_LIVE = `query($threadId: ID!) {\n viewer { login }\n node(id: $threadId) { ... on PullRequestReviewThread {\n isResolved path line\n first: comments(first: 1) { nodes { author { login } body url } }\n last: comments(last: 1) { nodes { author { login } url } }\n pullRequest { number url headRefName repository { nameWithOwner } }\n } }\n}`;\n\n/** The session's repos with what the live lookup matches a thread against: their GitHub name and checked-out branch. */\nexport function sessionRepoRefs(s: WorktreeSession): SessionRepoRef[] {\n return sessionRepos(s, loadConfig()).map((r) => {\n const config = readGitConfig(r.path);\n return { name: r.alias, path: r.path, github: config ? githubRepoOf(config) : null, branch: checkedOutBranch(r.path) };\n });\n}\n\n/** One of the session's repos, as the live lookup matches a thread's pull request against it. */\nexport interface SessionRepoRef {\n /** Its alias (what the PR watch names the repo by). */\n name: string;\n path: string;\n /** owner/name on github.com, lower case (`githubRepoOf`); null when not on GitHub. */\n github: string | null;\n /** The branch checked out there now. */\n branch: string | null;\n}\n\n/**\n * The thread read from GitHub now, accepted as the PR watch would list it:\n * on an open pull request of this session (its repo, from the branch one of\n * the session's checkouts has), not resolved, and its last word not yours.\n * What `work pr reply` falls back to when work's last check hasn't the\n * thread — a new one since, or a watch that missed the session — so a\n * reply is never stuck on stale state, and never looser than the watch.\n */\nexport async function liveOpenThread(\n threadId: string,\n repos: SessionRepoRef[],\n run: CommandRunner,\n now = new Date(),\n): Promise<{ reply: PrReply } | { error: string }> {\n if (!THREAD_ID.test(threadId)) return { error: `not a review thread id: ${threadId}` };\n const cwd = repos[0]?.path;\n if (!cwd) return { error: 'the session has no repo to ask GitHub from' };\n const r = await run('gh', ['api', 'graphql', '-f', `query=${THREAD_LIVE}`, '-f', `threadId=${threadId}`], cwd);\n if (r.code !== 0) return { error: `couldn't read the thread on GitHub: ${r.stderr.trim() || 'gh failed'}` };\n type Who = { author?: { login?: unknown } | null; body?: unknown; url?: unknown } | null;\n const j = json.parse(r.stdout) as {\n data?: {\n viewer?: { login?: unknown };\n node?: {\n isResolved?: unknown;\n path?: unknown;\n line?: unknown;\n first?: { nodes?: Who[] };\n last?: { nodes?: Who[] };\n pullRequest?: { number?: unknown; url?: unknown; headRefName?: unknown; repository?: { nameWithOwner?: unknown } };\n } | null;\n };\n } | null;\n const me = j?.data?.viewer?.login;\n const t = j?.data?.node;\n const pr = t?.pullRequest;\n if (typeof me !== 'string' || !me || !t || !pr || typeof pr.number !== 'number')\n return { error: `${threadId} isn't a review thread GitHub knows` };\n const nameWithOwner = typeof pr.repository?.nameWithOwner === 'string' ? pr.repository.nameWithOwner.toLowerCase() : '';\n const repo = repos.find((x) => x.github === nameWithOwner && !!x.branch && x.branch === pr.headRefName);\n if (!repo) return { error: `${threadId} is on ${nameWithOwner || 'a repo'} #${pr.number}, not a pull request of this session` };\n if (t.isResolved === true) return { error: 'the thread is resolved on GitHub: nothing to answer' };\n const first = t.first?.nodes?.[0];\n const last = t.last?.nodes?.at(-1);\n const lastBy = typeof last?.author?.login === 'string' ? last.author.login : '';\n if (lastBy.toLowerCase() === me.toLowerCase()) return { error: `the last word in this thread is already yours (@${me})` };\n const str = (v: unknown) => (typeof v === 'string' ? v : '');\n const path = str(t.path);\n return {\n reply: {\n threadId,\n repo: repo.name,\n prNumber: pr.number,\n url: str(last?.url) || str(pr.url),\n where: path ? `${path}${typeof t.line === 'number' ? `:${t.line}` : ''}` : null,\n reviewer: str(first?.author?.login),\n excerpt: str(first?.body).slice(0, 400),\n status: 'sent',\n draft: null,\n sentAt: now.toISOString(),\n },\n };\n}\n\n/** What `saveDraft` refuses that GitHub may know better: a thread it can't find, or one answered before\n * that the reviewer may have answered since (work's last check not having seen it yet). */\nconst ASK_GITHUB = /isn't an open review thread of this session|already posted/;\n\n/**\n * Draft a reply — what `work pr reply` and the dashboard's PUT do: from\n * what work knows (`saveDraft`), else from the thread as GitHub has it now\n * (`liveOpenThread`), never for a session launched `--unsafe` (it drafts\n * only what the watch handed it).\n */\nexport async function draftReply(\n sessionId: string,\n threadId: string,\n body: string,\n io: { unsafe: boolean; repos: () => SessionRepoRef[]; run: CommandRunner },\n now = new Date(),\n): Promise<DraftResult> {\n const known = saveDraft(sessionId, threadId, body, now, { unsafe: io.unsafe });\n if (known.ok || io.unsafe || !ASK_GITHUB.test(known.error)) return known;\n const live = await liveOpenThread(threadId, io.repos(), io.run, now);\n if ('error' in live) return { ok: false, error: `${live.error} (work's last check didn't list it either)` };\n return saveDraft(sessionId, threadId, body, now, { live: live.reply });\n}\n\nconst THREAD_RESOLVED = `query($threadId: ID!) { node(id: $threadId) { ... on PullRequestReviewThread { isResolved } } }`;\n/** At most this many threads looked up per check: a session with many old rows catches up over a few. */\nconst RETIRE_PER_CHECK = 10;\n\n/**\n * Reply rows of the session — handed over, or drafted and not posted —\n * whose thread the PR watch's check doesn't list as open, asked about on\n * GitHub one by one: those it says are resolved are discarded (nothing to\n * answer; Post could only refuse, and \"1 reply to post\" stayed forever).\n * Never from absence alone: a failed lookup leaves a thread off the list\n * too, so only GitHub's own \"resolved\" retires one. Returns the thread ids\n * that went.\n */\nexport async function retireResolvedReplies(sessionId: string, ci: SessionCi, cwd: string | null, run: CommandRunner): Promise<string[]> {\n if (!cwd) return [];\n const open = new Set(ci.repos.flatMap((r) => (r.threads ?? []).map((t) => t.threadId)));\n const suspects = listReplies(sessionId)\n .filter((r) => r.status !== 'posted' && !open.has(r.threadId))\n .slice(0, RETIRE_PER_CHECK);\n const gone: string[] = [];\n for (const r of suspects) {\n const res = await run('gh', ['api', 'graphql', '-f', `query=${THREAD_RESOLVED}`, '-f', `threadId=${r.threadId}`], cwd);\n if (res.code !== 0) continue;\n const j = json.parse(res.stdout) as { data?: { node?: { isResolved?: unknown } | null } } | null;\n if (j?.data?.node?.isResolved !== true) continue;\n if (discardReply(sessionId, r.threadId)) gone.push(r.threadId);\n }\n return gone;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiBO,SAAS,mBAAqG;AACnH,SAAO,CAAC,eAAe;AAAA,IACrB,KAAK,CAAC,MAAM,OAAO,CAAC,MAAM,EAAE,QAAQ,8DAA8D,EAAE,IAAI,WAAW,CAAC,CAAC,MAAM;AAAA,IAC3H,KAAK,CAAC,MAAM;AACV,UAA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IAAI,OAAO,OAAO,GAAG,KAAK,KAAK,6CAA6C;AAC1G,SAAO,UAAU,WAAW,UAAU,MAAM,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;AACvE;AAEA,IAAM,kBAAkB;AAExB,IAAM,mBAAmB;AAWzB,eAAsB,sBAAsB,WAAmB,IAAe,KAAoB,KAAuC;AACvI,MAAI,CAAC,IAAK,QAAO,CAAC;AAClB,QAAM,OAAO,IAAI,IAAI,GAAG,MAAM,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AACtF,QAAM,WAAW,YAAY,SAAS,EACnC,OAAO,CAAC,MAAM,EAAE,WAAW,YAAY,CAAC,KAAK,IAAI,EAAE,QAAQ,CAAC,EAC5D,MAAM,GAAG,gBAAgB;AAC5B,QAAM,OAAiB,CAAC;AACxB,aAAW,KAAK,UAAU;AACxB,UAAM,MAAM,MAAM,IAAI,MAAM,CAAC,OAAO,WAAW,MAAM,SAAS,eAAe,IAAI,MAAM,YAAY,EAAE,QAAQ,EAAE,GAAG,GAAG;AACrH,QAAI,IAAI,SAAS,EAAG;AACpB,UAAM,IAAI,KAAK,MAAM,IAAI,MAAM;AAC/B,QAAI,GAAG,MAAM,MAAM,eAAe,KAAM;AACxC,QAAI,aAAa,WAAW,EAAE,QAAQ,EAAG,MAAK,KAAK,EAAE,QAAQ;AAAA,EAC/D;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/sessions/session-view.ts","../src/core/agents/assistant.ts"],"sourcesContent":["import type { SessionAttention, ActivityState } from '../api-types.js';\nimport { stageWaiting, type PrStageKind } from '../pr/pr-stage.js';\nimport { owedToYou, type Owed } from '../status/attention.js';\n\n/** What the status vocabulary reads from a session: a dashboard row or\n * a `work sessions` row (both are SessionWire-shaped). */\nexport interface SessionLike {\n lastAccessedAt: string;\n lastActivity?: number | null;\n activityState?: ActivityState;\n attention?: SessionAttention | null;\n /** Unresolved review threads on its open PRs (SessionWire). */\n openReviewThreads?: number;\n /** Replies drafted to its review threads, waiting for your Post (SessionWire). */\n replyDrafts?: number;\n /** Where its pull request stands (SessionWire, pr-stage.ts). */\n prStage?: { kind: PrStageKind; text: string; seen?: boolean; prs?: ReadonlyArray<{ kind: PrStageKind; checks?: string }> } | null;\n /** Being archived right now (SessionWire.archiving). */\n archiving?: boolean;\n /** Being restored right now (SessionWire.restoring). */\n restoring?: boolean;\n /** Its Claude was stopped while idle and hasn't run since (SessionWire.asleep). */\n asleep?: boolean;\n}\n\n/**\n * ONE status vocabulary for every view — pure, so the dashboard (it imports\n * this) and `work sessions` say the same thing — (rail, Sessions table, inbox, header\n * strip). Hook-driven attention wins when a session has it; otherwise we fall\n * back to the older transcript-activity signal, so a session never shows two\n * contradicting states in two places.\n *\n * archiving — being archived right now (its Claude stopped, the rest\n * being saved); it leaves the list when done\n * restoring — being restored (its worktree made again, the conversation\n * put back); in the rail again from the click\n * needs_input — blocked on you (permission / question)\n * done — finished a turn you haven't looked at\n * working — mid-turn\n * background — its turn ended, a background agent that turn started is\n * still at it: still busy, but its prompt is free\n * asleep — its Claude was stopped while idle (idle sleep, `work stop`)\n * and hasn't run since: opening it starts it again\n * quiet — finished, and you've seen it\n * active/open/recent/stale — no hook status yet (its Claude has not\n * taken a turn since the dashboard's hooks went in, or runs a tool\n * without them): transcript activity only. Active ≤ 30 s, Open ≤ 5 min,\n * Idle (recent) within a day, Stale after that.\n */\nexport type DisplayKind =\n | 'archiving'\n | 'restoring'\n | 'needs_input'\n | 'done'\n | 'working'\n | 'background'\n | 'asleep'\n | 'quiet'\n | 'active'\n | 'open'\n | 'recent'\n | 'stale';\n\n/** Used today = not stale, whatever the hooks know. */\nexport const RECENT_MS = 24 * 3_600_000;\n\n/** When the session last did anything: the newest of its hook update,\n * Claude's last transcript write and the `work tree` entry. (Reading only\n * the entry time called a session Active and \"1d\" at once.) */\nexport function lastActiveAt(s: SessionLike): string {\n const candidates = [Date.parse(s.lastAccessedAt) || 0, s.lastActivity ?? 0, s.attention ? Date.parse(s.attention.updatedAt) || 0 : 0];\n return new Date(Math.max(...candidates)).toISOString();\n}\n\nexport function displayStatus(s: SessionLike, now: number = Date.now()): DisplayKind {\n if (s.archiving) return 'archiving';\n if (s.restoring) return 'restoring';\n const a = s.attention;\n if (a) {\n if (a.state === 'needs_input') return 'needs_input';\n if (a.state === 'working') return a.background ? 'background' : 'working';\n }\n // A finished turn you haven't looked at is yours to review, not Claude's state: the blue \"review\" badge says it\n // (owedToYou's 'turn'); the icon says what its Claude is — idle, or asleep.\n if (s.asleep) return 'asleep';\n if (a) return 'quiet';\n if (s.activityState === 'active') return 'active';\n if (s.activityState === 'open') return 'open';\n return now - Date.parse(lastActiveAt(s)) < RECENT_MS ? 'recent' : 'stale';\n}\n\nexport const DISPLAY_LABEL: Record<DisplayKind, string> = {\n archiving: 'Archiving',\n restoring: 'Restoring',\n needs_input: 'Needs your input',\n done: 'Done',\n working: 'Working',\n background: 'In background',\n asleep: 'Asleep',\n quiet: 'Idle',\n active: 'Active',\n open: 'Open',\n recent: 'Idle',\n stale: 'Stale',\n};\n\n/** What each status means, in words — the legend and the dots' tooltips. */\nexport const DISPLAY_MEANING: Record<DisplayKind, string> = {\n archiving:\n 'Being archived: its Claude is stopped, its conversation and uncommitted files are saved, and its worktree goes once nothing would be lost. It leaves the list when done; Restore brings it back.',\n restoring:\n 'Being restored: its worktree is made again from its branch, with its uncommitted files and conversation put back. Then it carries on where it was.',\n needs_input: 'Its Claude is waiting for you: a permission prompt or a question.',\n done: \"Its Claude finished a turn you haven't looked at yet: the Inbox's Done section. On a row it's the blue review badge, beside what its Claude is now.\",\n working: 'Its Claude is working on your last instruction right now.',\n background:\n 'Its Claude finished its turn, and a background agent that turn started is still at work. Its prompt is free: you can talk to it. The agent’s result comes back as a new turn.',\n asleep:\n 'Its Claude was stopped to free memory: idle for a while, nothing attached, nothing of it still running. Opening the session starts it again, where it left off.',\n quiet: \"Its Claude finished, and you've seen it. Nothing to do.\",\n active: \"Its Claude wrote in the last 30 seconds (it isn't reporting its status, so this is from its transcript).\",\n open: 'Its Claude wrote in the last 5 minutes, or is open and idle at its prompt.',\n recent: 'Used in the last day; nothing running now.',\n stale: 'Not used for over a day.',\n};\n\n/** The legend's rows, most urgent first. Idle covers `quiet` and `recent` (same colour, same word). */\nexport const LEGEND_KINDS: readonly DisplayKind[] = [\n 'needs_input',\n 'done',\n 'working',\n 'background',\n 'asleep',\n 'archiving',\n 'restoring',\n 'active',\n 'open',\n 'quiet',\n 'stale',\n];\n\n/**\n * How full a Claude conversation may get before it matters: past WARN the\n * header shows it amber and the PR watch's notes ask Claude to hand\n * mechanical work to a sub-agent; past FULL it's red (Claude compacts near\n * the window, and answers get vaguer before that).\n */\nexport const CONTEXT_WARN = 0.7;\nexport const CONTEXT_FULL = 0.9;\n\n/** How long ago a session was used, for the Sessions table's sections. */\nexport type AgeBucket = 'now' | 'week' | 'older';\n\nexport const AGE_LABEL: Record<AgeBucket, string> = {\n now: 'Now',\n week: 'This week',\n older: 'Older',\n};\n\nexport const WEEK_MS = 7 * 24 * 3_600_000;\n\n/** Now: wants you, is working, or was used in the last day. This week:\n * used within 7 days. Older: everything else — cleanup material. */\nexport function ageBucket(s: SessionLike, now: number = Date.now()): AgeBucket {\n const kind = displayStatus(s, now);\n if (owedToYou(s).length) return 'now';\n if (\n kind === 'needs_input' ||\n kind === 'done' ||\n kind === 'working' ||\n kind === 'background' ||\n kind === 'archiving' ||\n kind === 'restoring' ||\n kind === 'active' ||\n kind === 'open'\n )\n return 'now';\n const age = now - Date.parse(lastActiveAt(s));\n if (age < RECENT_MS) return 'now';\n return age < WEEK_MS ? 'week' : 'older';\n}\n\n/** Coarse buckets the Sessions header counts and filters by. */\nexport type StatusBucket = 'needs' | 'working' | 'idle' | 'stale';\n\nexport function statusBucket(kind: DisplayKind): StatusBucket {\n switch (kind) {\n case 'needs_input':\n case 'done':\n return 'needs';\n case 'working':\n case 'background':\n case 'archiving':\n case 'restoring':\n case 'active':\n return 'working';\n case 'quiet':\n case 'asleep':\n case 'open':\n case 'recent':\n return 'idle';\n case 'stale':\n return 'stale';\n default: {\n // Every kind is named above: a new one fails the type check here instead of landing in \"stale\" unasked.\n const unknown: never = kind;\n return unknown;\n }\n }\n}\n\n/** Why a session shows Active / Open / Idle(recent) / Stale instead of a\n * real status: its Claude isn't reporting through work web's hooks. */\nexport const NO_HOOKS_HINT =\n \"Its Claude isn't reporting its status (it was started before work web's hooks were installed, or it isn't Claude), so this is from its transcript activity: Active = wrote in the last 30 s, Open = last 5 min. Restart it with `work tree <target> <branch>` (the conversation continues) to get Working / Needs your input / Done.\";\n\n/** The hint for a status that comes from activity only; undefined otherwise. */\nexport function statusHint(kind: DisplayKind): string | undefined {\n return kind === 'active' || kind === 'open' || kind === 'recent' || kind === 'stale' ? NO_HOOKS_HINT : undefined;\n}\n\n/**\n * The second signal: what waits on you about a session, beside what its\n * Claude is doing (attention.ts `owedToYou`), in words. The rail's badge is\n * the first thing (\"1 reply\", \"merge\"; \"+1\" when there's more), its tooltip\n * all of them; the Sessions table and the Inbox say the same.\n */\nexport const OWED_SHORT: Record<Owed['kind'], (n: number) => string> = {\n turn: () => 'review',\n reply: (n) => `${n} ${n === 1 ? 'reply' : 'replies'}`,\n thread: (n) => `${n} ${n === 1 ? 'thread' : 'threads'}`,\n conflict: () => 'conflict',\n checks: () => 'CI',\n merge: () => 'merge',\n};\nexport const OWED_LONG: Record<Owed['kind'], (n: number) => string> = {\n turn: () => 'a finished turn to review',\n reply: (n) => `${n} ${n === 1 ? 'reply' : 'replies'} to post`,\n thread: (n) => `${n} review ${n === 1 ? 'thread' : 'threads'} with no answer`,\n conflict: (n) => (n === 1 ? 'a merge conflict' : `${n} PRs with merge conflicts`),\n checks: (n) => (n === 1 ? 'checks failing' : `${n} PRs with checks failing`),\n merge: () => 'ready to merge',\n};\n\nexport interface OwedBadge {\n /** \"1 reply\", \"merge +1\", \"review\". */\n text: string;\n /** What it leads with: a finished turn to review is blue (Done's colour), the rest pink. */\n kind: Owed['kind'];\n /** \"Needs you: 1 reply to post · ready to merge\". */\n title: string;\n}\n\n/** The badge for what waits on you, or null when nothing does. */\nexport function owedBadge(s: SessionLike): OwedBadge | null {\n const owed = owedToYou(s);\n if (!owed.length) return null;\n const [first, ...more] = owed;\n return {\n kind: first.kind,\n text: OWED_SHORT[first.kind](first.count) + (more.length ? ` +${more.length}` : ''),\n title: `Needs you: ${owed.map((o) => OWED_LONG[o.kind](o.count)).join(' · ')}`,\n };\n}\n\n/** Nothing waits on you, and its PR waits on others (reviewers, checks): \"in review\", said quietly. */\nexport function waitingOnOthers(s: SessionLike): boolean {\n return !owedToYou(s).length && stageWaiting(s.prStage);\n}\n\n/** The Sessions table's status filter: what waits on you counts as \"needs you\", whatever Claude is doing. */\nexport function sessionBucket(s: SessionLike, now: number = Date.now()): StatusBucket {\n return owedToYou(s).length ? 'needs' : statusBucket(displayStatus(s, now));\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { getConfigDir } from '../platform/config.js';\nimport { atomicWriteFile } from '../platform/fs-safe.js';\nimport type { AssistantView, SessionWire } from '../api-types.js';\nimport { DISPLAY_LABEL, displayStatus } from '../sessions/session-view.js';\nimport type { AgentAdapter, AllowRule, WorkHook } from './types.js';\n\n/**\n * The dashboard assistant (Ctrl+K): a persistent agent session in the PTY\n * host, like any worktree's, with its own folder under ~/.work/assistant. It\n * runs config `assistantAgent` (Claude Code by default; `assistantAgent()`).\n *\n * That folder is written by work: the agent's instructions file (CLAUDE.md\n * for Claude) saying what it is for and how to get the data (the\n * `work … --json` commands), and through its adapter's `workspace` its own\n * settings: the read-only commands pre-allowed, and a hook at the start of\n * each turn that adds what the user is looking at in the dashboard to the\n * prompt (`work hook assistant-context`), so \"clean these up\" or \"why is this\n * one blocked?\" need no explaining. An agent without a workspace gets the\n * instructions only (it asks before every command, and sees no view).\n *\n * It runs in the agent's normal permission mode, never --unsafe: anything\n * not pre-allowed — `work cleanup --apply`, `work remove`, git — asks first,\n * in the panel (and the Inbox).\n */\n\nexport const ASSISTANT_ID = 'assistant';\n\n/** What the dashboard reported, kept this long for the hook. */\nexport const CONTEXT_TTL_MS = 30 * 60_000;\n\nexport function assistantDir(): string {\n return path.join(getConfigDir(), 'assistant');\n}\nconst contextFile = () => path.join(assistantDir(), 'context.json');\n\n/**\n * Read-only commands it may run without asking (each agent's adapter writes\n * them in its own terms). Exact forms for cleanup: a `work cleanup --json`\n * prefix rule would also allow `--apply`.\n */\nexport const ASSISTANT_ALLOW: AllowRule[] = [\n { command: 'work sessions', prefix: true },\n { command: 'work digest', prefix: true },\n { command: 'work overlaps', prefix: true },\n { command: 'work search', prefix: true },\n { command: 'work cleanup --json' },\n { command: 'work cleanup --json --no-fetch' },\n { command: 'work cleanup --no-fetch --json' },\n { command: 'work list', prefix: true },\n { command: 'work recent', prefix: true },\n // The Time tab's day, read only (set / reset / off / gather / post ask first).\n { command: 'work timesheet show', prefix: true },\n { command: 'work timesheet month', prefix: true },\n];\n\n/** Its hook: what the dashboard shows, added at the start of each turn. */\nexport const ASSISTANT_HOOKS: WorkHook[] = [\n { owner: 'assistant', edge: 'turn-start', command: 'work hook assistant-context', timeoutSec: 5 },\n];\n\nexport const ASSISTANT_INSTRUCTIONS = `# You are the work dashboard's assistant\n\nThe user opens you with Ctrl+K in \\`work web\\`, the dashboard over all their git worktrees and the coding agent session in each. Help them make sense of it and act on it: what needs them, what each session did, what can be cleaned up, which sessions will conflict.\n\n## Getting the data\n\nUse the \\`work\\` CLI with \\`--json\\` (see the work-sessions skill) and parse it; don't guess from the filesystem:\n\n- \\`work sessions --json\\` — every session: status (\\`view.label\\`), age, last active, context usage, archive state. \\`--changes\\` adds +N −M and same-file overlaps; \\`--all\\` adds older and archived ones.\n- \\`work digest --json --since today|yesterday|week\\` — what each session did (prompts, turns, PRs).\n- \\`work overlaps --json\\` — live sessions changing the same files.\n- \\`work cleanup --json\\` — which worktrees can go, and why.\n- \\`work timesheet show [day] --json\\` — the Time tab's day: hours per ticket, and why (sessions' Claude minutes, commits, Jira, meetings, chats). On the Time tab, the day on screen is described to you with each message.\n- \\`work timesheet month [YYYY-MM] --json\\` — a month: every day's rows with how each got its hours, the month's tickets, and what posting it would do. On the Month view, the month on screen is described to you with each message.\n- \\`work search <words> --json\\` — sessions whose conversation (live or archived, also older than the agent keeps) mentions it, with the matching lines: \"what did we do about X?\".\n\nEach prompt comes with what the user is looking at in the dashboard (the tab, the selected session). When they say \"this\", \"these\" or \"here\", that is what they mean.\n\n## Changing things\n\nAsk before you change anything, and say exactly what will happen:\n- Removing, archiving or forgetting worktrees: \\`work cleanup --apply <id>… --action delete|archive|forget --json\\`. Each is checked again right before it runs; report what was refused and why. Never \\`--force\\` unless the user asked for exactly that.\n- A day's hours: \\`work timesheet set <day> KEY=HOURS …\\` (all its rows; quarter hours, the day's total as the user wants it), \\`reset <day>\\`, \\`off <day>\\`; several days: one command per day. Explain the change first. To look at a day again (its sessions, commits, Jira, meetings): \\`work timesheet gather <day>\\`, or \\`gather <YYYY-MM>\\` for a month's days not gathered yet. Posting to Tempo (\\`work timesheet post <day>\\`) only when the user asks for it.\n- Anything else (\\`work remove\\`, git, files in a worktree): only when asked, and show the command first.\n\nDon't post on GitHub, and don't send prompts to other sessions, unless the user asks. Keep answers short: the user is in the middle of something.\n`;\n\n/** What work wrote in the folder last time (relative paths), so files an earlier agent's setup left can go. */\nconst writtenFile = () => path.join(assistantDir(), '.work-written.json');\n/** What a work from before the list wrote: Claude's. */\nconst BEFORE_THE_LIST = ['CLAUDE.md', path.join('.claude', 'settings.json')];\n\nfunction readWritten(): string[] {\n try {\n const v = JSON.parse(fs.readFileSync(writtenFile(), 'utf-8')) as unknown;\n return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'ENOENT' ? BEFORE_THE_LIST : [];\n }\n}\n\n/**\n * Write (or refresh) the assistant's folder for the agent it runs; returns\n * it. Idempotent. Files work wrote there for another agent before (its\n * instructions, its settings with their allow rules and hooks) are removed:\n * after a switch they would be instructions and permissions nothing manages.\n * Only files work wrote and listed, inside the folder — never the user's own.\n */\nexport function prepareAssistantDir(agent: Pick<AgentAdapter, 'instructionsFile' | 'workspace'>): string {\n const dir = assistantDir();\n fs.mkdirSync(dir, { recursive: true });\n const before = readWritten();\n atomicWriteFile(path.join(dir, agent.instructionsFile), ASSISTANT_INSTRUCTIONS);\n const written = [agent.instructionsFile, ...(agent.workspace?.write(dir, { allow: ASSISTANT_ALLOW, hooks: ASSISTANT_HOOKS }) ?? [])].map(\n (f) => path.normalize(f),\n );\n const root = path.resolve(dir);\n for (const old of before.map((f) => path.normalize(f))) {\n const file = path.resolve(root, old);\n if (written.includes(old) || path.isAbsolute(old) || !file.startsWith(root + path.sep)) continue; // listed by us, inside the folder: nothing else\n fs.rmSync(file, { force: true });\n }\n atomicWriteFile(writtenFile(), JSON.stringify(written));\n return dir;\n}\n\ninterface StoredContext {\n at: string;\n text: string;\n /** The Time tab's day on screen: described afresh at each prompt (rows change by Save, Post, a rebuild). */\n day?: string;\n /** The Time tab's Month view on screen (`YYYY-MM`), described afresh the same way. */\n month?: string;\n}\n\n/**\n * The dashboard view in words, for the hook: which tab, and the selected\n * session's state. Pure.\n */\nexport function describeView(view: AssistantView, session: SessionWire | null, now = Date.now()): string {\n const lines = [`The user is looking at the dashboard's ${view.tab} tab${view.sub ? ` (${view.sub})` : ''}.`];\n if (session) {\n const status = DISPLAY_LABEL[displayStatus(session, now)];\n lines.push(\n `Selected session: ${session.target} · ${session.branch} (id ${session.id}) — ${status}.`,\n ...(session.attention?.summary ? [` Its last line: ${session.attention.summary}`] : []),\n ...(session.diffStat?.files\n ? [` Uncommitted: +${session.diffStat.added} −${session.diffStat.deleted} in ${session.diffStat.files} files.`]\n : []),\n ...(session.overlaps?.length\n ? [` Changes the same files as: ${session.overlaps.map((o) => `${o.target} · ${o.branch}`).join(', ')}.`]\n : []),\n ...(session.context ? [` Its conversation is ${Math.round((session.context.used / session.context.window) * 100)}% full.`] : []),\n ...(session.archivedAt ? [' It is archived.'] : []),\n ` Worktree: ${session.paths.join(', ')}`,\n );\n }\n if (view.note) lines.push(view.note);\n return lines.join('\\n');\n}\n\nexport function writeAssistantContext(text: string, now = Date.now(), day?: string, month?: string): void {\n fs.mkdirSync(assistantDir(), { recursive: true });\n const stored: StoredContext = { at: new Date(now).toISOString(), text, ...(day ? { day } : {}), ...(month ? { month } : {}) };\n atomicWriteFile(contextFile(), JSON.stringify(stored));\n}\n\n/** The day on screen, if the Time tab is: for the hook to describe as it is now. */\nexport function assistantContextDay(now = Date.now()): string | null {\n const s = readStored(now);\n return s && typeof s.day === 'string' && /^\\d{4}-\\d{2}-\\d{2}$/.test(s.day) ? s.day : null;\n}\n\n/** The month on screen, if the Time tab's Month view is: for the hook to describe as it is now. */\nexport function assistantContextMonth(now = Date.now()): string | null {\n const s = readStored(now);\n return s && typeof s.month === 'string' && /^\\d{4}-(0[1-9]|1[0-2])$/.test(s.month) ? s.month : null;\n}\n\nfunction readStored(now: number): Partial<StoredContext> | null {\n try {\n const s = JSON.parse(fs.readFileSync(contextFile(), 'utf-8')) as Partial<StoredContext> | null;\n if (!s || typeof s.text !== 'string' || typeof s.at !== 'string') return null;\n return now - Date.parse(s.at) > CONTEXT_TTL_MS ? null : s;\n } catch {\n return null;\n }\n}\n\n/**\n * What the hook adds to a prompt; null when the dashboard said nothing\n * lately. `dayNow` describes the Time tab's day as it is at this prompt\n * (the hook reads it from state.db), not as it was when the tab was opened.\n */\nexport function readAssistantContext(now = Date.now(), dayNow?: string | null): string | null {\n const s = readStored(now);\n if (!s) return null;\n return `[work dashboard] ${s.text}${dayNow ? `\\n${dayNow}` : ''}`;\n}\n"],"mappings":";;;;;;;;;;;;;AAgEO,IAAM,YAAY,KAAK;AAKvB,SAAS,aAAa,GAAwB;AACnD,QAAM,aAAa,CAAC,KAA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]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/platform/shell-path.ts","../src/core/agents/agent-path.ts"],"sourcesContent":["import { spawnSync, type SpawnSyncOptionsWithStringEncoding } from 'node:child_process';\nimport path from 'node:path';\nimport { findOnPath } from './find-on-path.js';\nimport { report } from './report.js';\nimport { debugLog } from './logger.js';\nimport { detachHere } from './process.js';\n\n/**\n * The PATH of the user's login shell, for a work started without one.\n *\n * Reported from a Mac: every session ended at once with \"session exited with code 1\", and Enter\n * gave the same. The desktop app started from the Dock or Finder gets the system's minimal PATH\n * (/usr/bin:/bin:/usr/sbin:/sbin), not the one the user's shell sets up, and passes it on to work\n * web, the PTY host and every Claude: `claude` (in ~/.local/bin, /opt/homebrew/bin, an nvm folder…)\n * isn't found, and node-pty's child exits with 1 when its exec fails. So when work web or the PTY\n * host starts on macOS or Linux and the agent's command isn't on its PATH, it asks the login shell\n * for its PATH (`$SHELL -ilc`, as a terminal would set it up) and puts it first. Started from a\n * terminal, the command is found and nothing is asked.\n */\n\nconst MARK = '__WORK_SHELL_PATH__';\n\n/** The shell's PATH first, then what we had that it lacks (e.g. the app's ~/.work/bin). */\nexport function mergePath(current: string | undefined, shellPath: string, sep = path.delimiter): string {\n const out: string[] = [];\n for (const d of [...shellPath.split(sep), ...(current ?? '').split(sep)]) if (d && !out.includes(d)) out.push(d);\n return out.join(sep);\n}\n\n/** The PATH between the markers of the shell's output (an interactive shell may print a greeting around it). */\nexport function parseShellPath(stdout: string): string | null {\n const m = new RegExp(`${MARK}(.*?)${MARK}`, 's').exec(stdout);\n const p = m?.[1].trim();\n return p ? p : null;\n}\n\n/** How long the login shell may take to say its PATH. */\nexport const SHELL_PATH_TIMEOUT_MS = 5_000;\n\n/** The shell's arguments: a login, interactive shell (what a terminal runs) printing its PATH between markers. */\nexport const shellPathArgs = (): string[] => ['-ilc', `printf '%s%s%s' '${MARK}' \"$PATH\" '${MARK}'`];\n\n/**\n * How it's started. `killSignal: SIGKILL`: an interactive bash or zsh ignores SIGTERM (spawnSync's\n * default at the timeout), and Node then waits for it — a stuck profile held work web up for as long as\n * it hung (reproduced: a 2 s timeout returned after 8 s). `detached` (POSIX): its own session, so it\n * never takes this terminal's foreground group — killed while holding it, it left `work web` in the\n * background, where Ctrl+C no longer reached it (reproduced).\n */\nexport const shellPathSpawnOptions = (timeoutMs = SHELL_PATH_TIMEOUT_MS): SpawnSyncOptionsWithStringEncoding =>\n // `detached` isn't in @types/node's spawnSync options, but spawnSync honors it (spawn_sync reads it).\n ({\n encoding: 'utf8',\n timeout: timeoutMs,\n killSignal: 'SIGKILL',\n detached: detachHere(),\n stdio: ['ignore', 'pipe', 'ignore'],\n windowsHide: true,\n }) as SpawnSyncOptionsWithStringEncoding;\n\ntype ShellRun = (cmd: string, args: string[]) => { stdout?: string | null; status?: number | null; signal?: string | null; error?: Error };\n\n/** Ask the login shell for its PATH: its PATH, or why it couldn't say (a timeout, no such shell, no markers). */\nexport function readShellPath(\n shell = process.env.SHELL || '/bin/zsh',\n run: ShellRun = (cmd, args) => spawnSync(cmd, args, shellPathSpawnOptions()),\n): { path: string } | { why: string } {\n try {\n const r = run(shell, shellPathArgs());\n const p = parseShellPath(r.stdout ?? '');\n if (p) return { path: p };\n const how = r.error\n ? r.error.message\n : r.signal\n ? `stopped by ${r.signal} (over ${SHELL_PATH_TIMEOUT_MS / 1000} s?)`\n : `exit ${r.status ?? '?'}, no PATH printed`;\n return { why: `${shell} -ilc: ${how}` };\n } catch (err) {\n return { why: `${shell} -ilc: ${(err as Error).message}` };\n }\n}\n\n/**\n * Make sure the commands in `need` (the agent's binary) can be found: on macOS and Linux, when one\n * isn't on PATH, the login shell's PATH is merged into this process's (which everything it starts\n * inherits). Says what it did; never throws.\n */\nexport function ensureShellPath(\n need: string[],\n opts: {\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n readPath?: () => { path: string } | { why: string };\n find?: (cmd: string, env: NodeJS.ProcessEnv) => string | null;\n } = {},\n): 'found' | 'added' | 'unavailable' {\n const platform = opts.platform ?? process.platform;\n const env = opts.env ?? process.env;\n if (platform === 'win32') return 'found';\n const find = opts.find ?? ((c: string, e: NodeJS.ProcessEnv) => findOnPath(c, e, platform));\n const missing = need.filter((c) => !find(c, env));\n if (!missing.length) return 'found';\n // Said in the debug log too: started by the desktop app, nothing shows what a reporter prints.\n const say = (level: 'info' | 'warn', text: string) => {\n report(level, text);\n debugLog(level === 'warn' ? 'WARN' : 'INFO', text);\n };\n const read = (opts.readPath ?? (() => readShellPath(env.SHELL)))();\n if ('why' in read) {\n say('warn', `${missing.join(', ')} isn't on PATH (${env.PATH ?? ''}), and the login shell's PATH couldn't be read: ${read.why}`);\n return 'unavailable';\n }\n env.PATH = mergePath(env.PATH, read.path);\n const still = missing.filter((c) => !find(c, env));\n say(\n still.length ? 'warn' : 'info',\n still.length\n ? `${still.join(', ')} isn't on PATH, even with the login shell's (${env.PATH})`\n : `${missing.join(', ')} found with the login shell's PATH: using it (${env.PATH})`,\n );\n return 'added';\n}\n","import { agentFor, agentSettings, assistantAgent, internalAgent } from './index.js';\nimport type { AgentSettings } from './index.js';\nimport { ensureShellPath } from '../platform/shell-path.js';\nimport { debugLog } from '../platform/logger.js';\n\n/**\n * The agents' commands, found on PATH before work web or the PTY host starts any of them\n * (`core/platform/shell-path.ts` says why: the Mac app from the Dock gets the system's PATH).\n */\n\n/** The commands work starts agents with, from the registry: new sessions', the Ctrl+K assistant's, the summaries'. */\nexport function agentCommands(settings: AgentSettings = agentSettings()): string[] {\n return [...new Set([agentFor(settings), assistantAgent(settings), internalAgent(settings)].map((a) => a.launch.tool(settings).cmd))];\n}\n\n/** For `work web` and the PTY host as they start (not wd's lean server: it starts no agent). Never throws. */\nexport function ensureAgentPath(\n deps: { commands?: () => string[]; ensure?: (need: string[]) => ReturnType<typeof ensureShellPath> } = {},\n): ReturnType<typeof ensureShellPath> | 'failed' {\n try {\n return (deps.ensure ?? ensureShellPath)((deps.commands ?? agentCommands)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AAc,GAAa;AACjF,SAAO,CAAC,GAAG,IAAI,IAAI,CAAC,SAAS,QAAQ,GAAG,eAAe,QAAQ,GAAG,cAAc,QAAQ,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,KAAK,QAAQ,EAAE,GAAG,CAAC,CAAC;AACrI;AAGO,SAAS,gBACd,OAAuG,CAAC,GACzD;AAC/C,MAAI;AACF,YAAQ,KAAK,UAAU,kBAAkB,KAAK,YAAY,eAAe,CAAC;AAAA,EAC5E,SAAS,KAAK;AACZ,aAAS,QAAQ,sCAAsC,GAAG;AAC1D,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/chunk-MYXLQMF7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/platform/config.ts","../src/core/sessions/saved-prompts.ts","../src/core/time/allocate.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteFile } from './fs-safe.js';\nimport { validatePrompts } from '../sessions/saved-prompts.js';\nimport { isIssueKey } from '../time/allocate.js';\nimport { getConfigDir } from './config-dir.js';\nimport type { SavedPrompt } from '../api-types.js';\n\n/**\n * An opt-in shell command that runs when a session changes status. The command\n * runs with the session's directory as its cwd (passed as the spawn `cwd`\n * option, never interpolated into the command string).\n */\nexport interface StatusHook {\n on: 'idle' | 'needs_input';\n command: string;\n}\n\nexport interface WorkConfig {\n worktreesRoot: string;\n repos: Record<string, string>;\n groups: Record<string, string[]>;\n copyFiles: string[];\n /** Folders the Repos page scans for git repos (repo-scan.ts); default: the one the worktrees root sits in. */\n scanRoots?: string[];\n /** Repos you chose not to enrol (paths), so the Repos page stops offering them. */\n ignoredRepos?: string[];\n /** The Jira watch (jira-watch.ts; turned on and off in the Jira tab): at most this many automatic starts a day (default 5). */\n jiraWatch?: { maxPerDay?: number };\n /** The Time tab's rules (core/time/allocate.ts, defaults in DEFAULT_TIME_SETTINGS), and the Jira\n * projects whose keys count in commit subjects (default: the projects of your sessions' keys). */\n time?: Partial<import('../time/allocate.js').TimeSettings> & {\n projects?: string[];\n /** How many days back the Time tab gathers (default 14, at most 92; Claude's own transcripts go back about 30). */\n catchUpDays?: number;\n /** Tickets a workstream maps to when nothing names them (the timesheet tool's TICKET_HINTS), by key. */\n hints?: Record<string, import('../time/hints.js').TicketHint>;\n /** Posting to Tempo: the env variable with the token (default TEMPO_API_TOKEN) and your Jira account id (else JIRA_ACCOUNT_ID). */\n tempo?: { tokenEnv?: string; accountId?: string };\n /** Outlook and Teams through Microsoft Graph: the app registration to sign in with (else GRAPH_CLIENT_ID / GRAPH_TENANT_ID). */\n graph?: { clientId?: string; tenantId?: string };\n /** The Jira field holding story points (`customfield_…`, each site its own): read for tasks, they weigh the day's split. */\n storyPointsField?: string;\n };\n /** Stacked sessions (stack-sync.ts): bring a parent's new commits into the sessions stacked on it (default true). */\n stacks?: { autoUpdate?: boolean };\n /** Usage meters: `statusLine: false` leaves Claude's status line alone (work otherwise wraps it to read the rate limits). */\n usage?: { statusLine?: boolean };\n /** Claude Code accounts besides the default `~/.claude`: name → its config folder (`CLAUDE_CONFIG_DIR`), as written; agents/claude/accounts.ts checks them. */\n claudeAccounts?: Record<string, string>;\n /** The account new sessions and work's own Claude runs use: `default` or a key of `claudeAccounts`. */\n claudeAccount?: string;\n /** The agent that writes work's own summaries — checkpoint names, catch-up, archive summaries, the Jira watch's choice (default `claude`; one without one-shot runs writes none). */\n internalAgent?: string;\n /** The agent the Ctrl+K assistant runs (an adapter's id; Claude Code by default). */\n assistantAgent?: string;\n /** Environment variable names to keep for a session restored after a reboot (the launching shell's values; secret-looking names are never kept). */\n hostEnv?: string[];\n /** Writing session time to Jira as worklogs (jira-worklog.ts): the site, your email, and the API token (from the env var `tokenEnv`, default JIRA_API_TOKEN, or `token`). */\n jiraWorklog?: { site: string; email: string; tokenEnv?: string; token?: string };\n /**\n * AI tool command to launch in worktrees. May include extra args, e.g.\n * \"claude\" (default), \"gemini\", \"codex\", or \"my-tool --some-flag\".\n */\n aiCommand?: string;\n /**\n * Launch `work tree`'s AI session inside the PTY host and attach this\n * terminal to it (like `work attach`), so it survives closing the tab and\n * the dashboard shows the same screen. Default on; `false` launches\n * directly in the terminal. Per call: `--host` / `--no-host`.\n */\n launchViaHost?: boolean;\n /**\n * Experimental, off by default: NEW sessions are made as a folder with one\n * subfolder per repo — a single repo too (`<root>/<branch>-<id6>/<repo>/`, session-folder.ts) —\n * and the agent runs in the folder, whose instructions file imports each\n * repo's own. Existing sessions keep the layout they were made with.\n */\n sessionFolders?: boolean;\n /**\n * Per-tool flag overrides. Defaults come from the preset matching the\n * binary in `aiCommand` (see AI_TOOL_PRESETS in core/ai-launcher.ts).\n * Set any value to an empty string to disable that flag for the configured tool.\n */\n aiCommandFlags?: {\n /** Flag for skipping permission checks. */\n unsafe?: string;\n /** Flag for resuming the most recent session. */\n resume?: string;\n /** Flag for passing an initial prompt as a file path. */\n promptFile?: string;\n /** Flag for passing an inline prompt; empty string = positional arg. */\n prompt?: string;\n };\n /** Editor command for opening worktrees. Default: \"code\" */\n editor?: string;\n /**\n * Range of dev-server ports to allocate to worktrees (inclusive).\n * Each worktree gets a stable port exposed as $PORT to the launched process.\n * Default when unset: { start: 3000, end: 3099 }.\n */\n portRange?: { start: number; end: number };\n /**\n * Dev-server command per repo alias, run from the dashboard with this\n * worktree's $PORT (e.g. `{ \"web\": \"npm run dev -- --port $PORT\" }`).\n */\n devCommands?: Record<string, string>;\n /**\n * Stop a session's Claude in the PTY host after this many minutes idle with\n * no window attached; opening the session resumes its conversation. Frees\n * memory (each Claude holds a few hundred MB). Default 10, at least 5; 0 = never.\n * Only a truly idle one: never working, waiting on you, or with background work still running (idle-sleep.ts).\n */\n sleepIdleAfterMinutes?: number;\n /**\n * Archived conversations (archive-retention.ts): gzip them once this many\n * days old (default 30; 0 = never; lossless), and delete them after this\n * many (default 0 = never; the summary and prompts stay).\n */\n archive?: { compressAfterDays?: number; dropTranscriptsAfterDays?: number };\n /**\n * Background PR watch in `work web` (both default on): archive a session\n * once all its PRs merged, and tell its Claude when CI fails or reviewers\n * leave feedback.\n */\n prWatch?: {\n autoArchive?: boolean;\n fixCi?: boolean;\n /** A PR of the session's that turns conflicting: its Claude is asked to merge the base in and\n * resolve it (DECISION NEEDED when it isn't clear-cut). Default on. */\n fixConflicts?: boolean;\n reviewComments?: boolean;\n /** Review bots whose comments go to Claude like a colleague's (logins,\n * e.g. \"copilot-pull-request-reviewer\"). Default: Copilot and\n * github-actions (pr-review.ts DEFAULT_TRUSTED_BOTS); [] = none. */\n trustedBots?: string[];\n /** Start a session's Claude (resuming its conversation) when feedback\n * arrives and it isn't running, so it works on it at once. Default on. */\n wakeClaude?: boolean;\n };\n /**\n * Opt-in desktop notifications. When true, the dashboard fires an OS\n * notification when a session goes idle or needs input. Default: off.\n */\n notifications?: boolean;\n /**\n * Opt-in shell commands run when a session changes status (idle /\n * needs_input). Each command runs with the session dir as its cwd.\n * Generalizes `notifications`; both paths work independently. Default: none.\n */\n statusHooks?: StatusHook[];\n /**\n * One-click instructions in a session's \"Prompts ▾\" menu, replacing the\n * built-in ones: `[{ \"label\": \"Add tests\", \"prompt\": \"…\", \"repos\": [\"api\"] }]`\n * (`repos` optional: only for those repo aliases / group names).\n */\n prompts?: SavedPrompt[];\n}\n\n/** Lowest port we allow to be configured (avoid privileged ports < 1024). */\nconst MIN_PORT = 1024;\n/** Highest valid TCP port. */\nconst MAX_PORT = 65535;\n\n/**\n * Validate a configured port range. Returns the normalized range when it is a\n * pair of integers with `MIN_PORT <= start <= end <= MAX_PORT`, otherwise\n * undefined (callers then fall back to the default range). Rejects non-integers,\n * privileged/out-of-bounds ports, and reversed ranges.\n */\nexport function validatePortRange(value: unknown): { start: number; end: number } | undefined {\n if (!value || typeof value !== 'object') return undefined;\n const { start, end } = value as { start?: unknown; end?: unknown };\n if (typeof start !== 'number' || typeof end !== 'number') return undefined;\n if (!Number.isInteger(start) || !Number.isInteger(end)) return undefined;\n if (start < MIN_PORT || end > MAX_PORT) return undefined;\n if (start > end) return undefined;\n return { start, end };\n}\n\nexport { getConfigDir };\n\n/** An agent named in config (`internalAgent`, `assistantAgent`): an adapter's id, a plain word — never a path or a command line. */\nexport function isAgentId(v: unknown): v is string {\n return typeof v === 'string' && /^[\\w.-]+$/.test(v);\n}\n\nexport function getConfigPath(): string {\n return path.join(getConfigDir(), 'config.json');\n}\n\nfunction validateDevCommands(raw: unknown): Record<string, string> | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const out: Record<string, string> = {};\n for (const [alias, cmd] of Object.entries(raw)) if (typeof cmd === 'string' && cmd.trim()) out[alias] = cmd;\n return out;\n}\n\n/** The Time tab's section as written: only well-formed values (a bad one is left to its default). */\nexport function validateTime(raw: unknown): WorkConfig['time'] {\n if (!raw || typeof raw !== 'object') return undefined;\n const t = raw as Record<string, unknown>;\n const num = (k: string, min: number) => (typeof t[k] === 'number' && (t[k] as number) >= min ? { [k]: t[k] as number } : {});\n const key = (k: string) => (typeof t[k] === 'string' && isIssueKey(t[k] as string) ? { [k]: t[k] as string } : {});\n const strs = (o: unknown, keys: string[]) => {\n if (!o || typeof o !== 'object') return undefined;\n const out: Record<string, string> = {};\n for (const k of keys) {\n const v = (o as Record<string, unknown>)[k];\n if (typeof v === 'string' && v.trim()) out[k] = v.trim();\n }\n return Object.keys(out).length ? out : undefined;\n };\n const days = stringList(t.holidays)?.filter((d) => /^\\d{4}-\\d{2}-\\d{2}$/.test(d));\n const vacation = stringList(t.vacation)?.filter((d) => /^\\d{4}-\\d{2}-\\d{2}$/.test(d));\n const hints = validateHints(t.hints);\n const catchUp = typeof t.catchUpDays === 'number' && t.catchUpDays >= 1 ? { catchUpDays: Math.min(92, Math.floor(t.catchUpDays)) } : {};\n const projects = stringList(t.projects)?.filter((p) => /^[A-Z][A-Z0-9]{1,9}$/.test(p));\n const desk = stringList(t.deskProjects)?.filter((p) => /^[A-Z][A-Z0-9]{1,9}$/.test(p));\n const tempo = strs(t.tempo, ['tokenEnv', 'accountId']);\n const graph = strs(t.graph, ['clientId', 'tenantId']);\n return {\n ...num('dayHours', 0.25),\n ...num('multiplier', 0),\n ...num('capHours', 0),\n ...num('stepHours', 0.01),\n ...num('minHours', 0),\n ...key('gapTicket'),\n ...key('timeOffTicket'),\n ...(days ? { holidays: days } : {}),\n ...(vacation ? { vacation } : {}),\n ...(typeof t.effort === 'boolean' ? { effort: t.effort } : {}),\n ...(desk ? { deskProjects: desk } : {}),\n ...(t.taskMinHours === null || (typeof t.taskMinHours === 'number' && t.taskMinHours >= 0)\n ? { taskMinHours: t.taskMinHours as number | null }\n : {}),\n ...num('pointsWeight', 0),\n ...(typeof t.storyPointsField === 'string' && /^customfield_\\d+$/.test(t.storyPointsField)\n ? { storyPointsField: t.storyPointsField }\n : {}),\n ...catchUp,\n ...(hints ? { hints } : {}),\n ...(projects ? { projects } : {}),\n ...(tempo ? { tempo } : {}),\n ...(graph ? { graph } : {}),\n };\n}\n\n/** `time.hints`: each a real issue key with what matches it (text found in a session, commit, meeting or chat). */\nfunction validateHints(raw: unknown): Record<string, import('../time/hints.js').TicketHint> | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const out: Record<string, import('../time/hints.js').TicketHint> = {};\n for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {\n const h = v as Record<string, unknown> | null;\n const matches = stringList(h?.matches)\n ?.map((m) => m.trim())\n .filter((m) => m.length >= 3);\n if (!isIssueKey(k) || !matches?.length) continue;\n out[k] = {\n matches,\n ...(typeof h?.summary === 'string' && h.summary.trim() ? { summary: h.summary.trim() } : {}),\n ...(h?.placeholder === true ? { placeholder: true } : {}),\n };\n }\n return Object.keys(out).length ? out : undefined;\n}\n\n/** A list of non-empty strings, or undefined (not a list). */\nfunction stringList(raw: unknown): string[] | undefined {\n return Array.isArray(raw) ? raw.filter((x): x is string => typeof x === 'string' && x.trim().length > 0) : undefined;\n}\n\n/** `default` is the account at `~/.claude` (a session that records no account runs on it); it can't be a configured name. */\nexport const DEFAULT_ACCOUNT = 'default';\n\n/**\n * `claudeAccounts` as written: the entries whose folder is a string. What makes one an account (a name, a folder that\n * can be one) is Claude's to say (agents/claude/accounts.ts), which checks them where they are read.\n */\nfunction stringRecord(raw: unknown): Record<string, string> | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const out = Object.fromEntries(\n Object.entries(raw as Record<string, unknown>).filter((e): e is [string, string] => typeof e[1] === 'string'),\n );\n return Object.keys(out).length ? out : undefined;\n}\n\nexport function loadConfig(): WorkConfig | null {\n const configPath = getConfigPath();\n if (!fs.existsSync(configPath)) {\n return null;\n }\n\n try {\n const raw = fs.readFileSync(configPath, 'utf-8');\n const parsed = JSON.parse(raw);\n return {\n worktreesRoot: parsed.worktreesRoot ?? '',\n repos: parsed.repos ?? {},\n groups: parsed.groups ?? {},\n copyFiles: parsed.copyFiles ?? [],\n scanRoots: stringList(parsed.scanRoots),\n ignoredRepos: stringList(parsed.ignoredRepos),\n aiCommand: parsed.aiCommand,\n aiCommandFlags: parsed.aiCommandFlags,\n editor: parsed.editor,\n portRange: validatePortRange(parsed.portRange),\n notifications: parsed.notifications === true,\n statusHooks: Array.isArray(parsed.statusHooks) ? parsed.statusHooks : [],\n launchViaHost: typeof parsed.launchViaHost === 'boolean' ? parsed.launchViaHost : undefined,\n sessionFolders: typeof parsed.sessionFolders === 'boolean' ? parsed.sessionFolders : undefined,\n devCommands: validateDevCommands(parsed.devCommands),\n sleepIdleAfterMinutes:\n typeof parsed.sleepIdleAfterMinutes === 'number' && parsed.sleepIdleAfterMinutes >= 0 ? parsed.sleepIdleAfterMinutes : undefined,\n prompts: validatePrompts(parsed.prompts),\n time: validateTime(parsed.time),\n archive:\n parsed.archive && typeof parsed.archive === 'object'\n ? {\n ...(typeof parsed.archive.compressAfterDays === 'number' && parsed.archive.compressAfterDays >= 0\n ? { compressAfterDays: parsed.archive.compressAfterDays }\n : {}),\n ...(typeof parsed.archive.dropTranscriptsAfterDays === 'number' && parsed.archive.dropTranscriptsAfterDays >= 0\n ? { dropTranscriptsAfterDays: parsed.archive.dropTranscriptsAfterDays }\n : {}),\n }\n : undefined,\n stacks: parsed.stacks && typeof parsed.stacks === 'object' ? { autoUpdate: parsed.stacks.autoUpdate !== false } : undefined,\n usage: parsed.usage && typeof parsed.usage === 'object' ? { statusLine: parsed.usage.statusLine !== false } : undefined,\n claudeAccounts: stringRecord(parsed.claudeAccounts),\n claudeAccount: typeof parsed.claudeAccount === 'string' ? parsed.claudeAccount : undefined,\n internalAgent: isAgentId(parsed.internalAgent) ? parsed.internalAgent : undefined,\n assistantAgent: isAgentId(parsed.assistantAgent) ? parsed.assistantAgent : undefined,\n hostEnv: Array.isArray(parsed.hostEnv)\n ? parsed.hostEnv.filter((n: unknown): n is string => typeof n === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(n))\n : undefined,\n jiraWorklog:\n parsed.jiraWorklog &&\n typeof parsed.jiraWorklog === 'object' &&\n typeof parsed.jiraWorklog.site === 'string' &&\n typeof parsed.jiraWorklog.email === 'string'\n ? {\n site: parsed.jiraWorklog.site,\n email: parsed.jiraWorklog.email,\n ...(typeof parsed.jiraWorklog.tokenEnv === 'string' ? { tokenEnv: parsed.jiraWorklog.tokenEnv } : {}),\n ...(typeof parsed.jiraWorklog.token === 'string' ? { token: parsed.jiraWorklog.token } : {}),\n }\n : undefined,\n prWatch:\n parsed.prWatch && typeof parsed.prWatch === 'object'\n ? {\n autoArchive: parsed.prWatch.autoArchive !== false,\n fixCi: parsed.prWatch.fixCi !== false,\n fixConflicts: parsed.prWatch.fixConflicts !== false,\n reviewComments: parsed.prWatch.reviewComments !== false,\n ...(Array.isArray(parsed.prWatch.trustedBots)\n ? {\n trustedBots: parsed.prWatch.trustedBots.filter(\n (b: unknown): b is string => typeof b === 'string' && b.trim().length > 0,\n ),\n }\n : {}),\n wakeClaude: parsed.prWatch.wakeClaude !== false,\n }\n : undefined,\n };\n } catch {\n return null;\n }\n}\n\nexport function saveConfig(config: WorkConfig): void {\n // Atomic (write temp + rename): a crash or a concurrent reader can never\n // see a half-written config (§5.3 — history/tasks already did this).\n atomicWriteFile(getConfigPath(), JSON.stringify(config, null, 2));\n}\n\nexport function ensureConfig(): WorkConfig {\n const config = loadConfig();\n if (!config) {\n throw new Error('Configuration not found. Run \"work init\" to set up.');\n }\n return config;\n}\n","import type { SavedPrompt } from '../api-types.js';\n\nexport type { SavedPrompt } from '../api-types.js';\n\n/**\n * One-click instructions for a session (\"Prompts ▾\" in its header). Sent\n * like a review comment, so they reach Claude the same safe way: pushed to\n * a terminal the dashboard owns, or on the session's next turn — never\n * typed over a permission prompt. Pure (the demo uses it too).\n *\n * `prompts` in config.json replaces these defaults; `repos` limits one to\n * those repo aliases / group names.\n */\nexport const DEFAULT_PROMPTS: SavedPrompt[] = [\n {\n label: 'Review your changes',\n prompt:\n 'Review the changes on this branch as a strict reviewer would: bugs, missing edge cases, missing tests, leftovers (debug output, TODOs, dead code). Fix what you find, then tell me briefly what you changed.',\n },\n {\n label: 'Add tests',\n prompt:\n 'Add tests for what changed on this branch, following the existing test patterns in this repo. Run them and fix anything that fails.',\n },\n {\n label: 'Run checks and fix',\n prompt:\n \"Run this repo's type check, lint and tests (whatever it has). Fix what fails, and tell me if something is failing for a reason outside this change.\",\n },\n {\n label: 'Commit',\n prompt: \"Commit the current changes with a clear message in this repo's commit style. Don't push.\",\n },\n {\n label: 'Open a pull request',\n prompt:\n 'Push this branch and open a pull request for it with `gh pr create`. Write the title and description yourself from what we did in this conversation: what changed and why, how it was tested, anything a reviewer should look at first. Put the Jira key in the title if the branch or our conversation has one. Open it ready for review, not as a draft, and give me its link.',\n },\n {\n label: 'Rebase on the default branch',\n prompt:\n \"Fetch, then rebase this branch on origin's default branch. Resolve conflicts keeping both sides' intent, run the tests, and tell me about any conflict you weren't sure of.\",\n },\n];\n\nconst MAX_PROMPT = 20_000;\n\n/** The configured list, validated; undefined (use the defaults) when absent. */\nexport function validatePrompts(raw: unknown): SavedPrompt[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: SavedPrompt[] = [];\n for (const p of raw) {\n if (!p || typeof p !== 'object') continue;\n const { label, prompt, repos } = p as Record<string, unknown>;\n if (typeof label !== 'string' || !label.trim() || typeof prompt !== 'string' || !prompt.trim()) continue;\n const item: SavedPrompt = { label: label.trim(), prompt: prompt.trim().slice(0, MAX_PROMPT) };\n if (Array.isArray(repos)) {\n const names = repos.filter((r): r is string => typeof r === 'string' && r.length > 0);\n if (names.length) item.repos = names;\n }\n out.push(item);\n }\n return out;\n}\n\n/** The prompts that apply to a session: unscoped ones, and those naming\n * its target (a repo alias or group name) or one of its repos. */\nexport function promptsForSession(prompts: SavedPrompt[], target: string, repoNames: string[] = []): SavedPrompt[] {\n const names = new Set([target, ...repoNames]);\n return prompts.filter((p) => !p.repos || p.repos.some((r) => names.has(r)));\n}\n","/**\n * A day's suggested hours, from what was worked on (pure; the SPA and the\n * demo use it too). The timesheet tool's rules, as settings: a day of\n * `dayHours`, measured Claude time scaled by `multiplier` (an hour of Claude\n * at work stands for more of yours: reading, testing, talking), all of it\n * capped at `capHours`, in `stepHours` steps with at least `minHours` a\n * ticket, and what's left to the `gapTicket` (meetings, reviews, the rest).\n * A ticket touched with no measured time (a commit, an issue moved) gets the\n * minimum. Unlike the tool, it never goes over the day — too many tickets\n * trim the biggest first, then drop the smallest — and nothing is taken out\n * of one entry alone.\n */\n\nexport interface TimeSettings {\n /** A workday's hours. */\n dayHours: number;\n /** Measured Claude minutes × this = your hours on it. */\n multiplier: number;\n /** At most this much of a day to tickets (the gap ticket keeps the rest). */\n capHours: number;\n stepHours: number;\n /** A ticket that gets time gets at least this. */\n minHours: number;\n /** Gets what's left of the day (null: left unallocated). */\n gapTicket: string | null;\n /** A day off is booked to it (null: a day off books nothing). */\n timeOffTicket: string | null;\n /** Days that aren't workdays besides weekends (`YYYY-MM-DD`). */\n holidays: string[];\n /** Your days off (`YYYY-MM-DD`): booked whole to the time-off ticket, whatever else happened (the timesheet tool's VACATION_DAYS). */\n vacation: string[];\n /**\n * Hours as measured (the timesheet tool's `build --effort`): Claude minutes 1:1 in steps, no multiplier and no\n * minimum beyond a step, a ticket only touched gets no row; the gap ticket takes the rest of the day.\n */\n effort: boolean;\n /** Projects whose tickets are service desk (keep `minHours`); any other project's ticket is a task. */\n deskProjects: string[];\n /** A task's row on a day is at least this (null: tasks get `minHours` like any ticket). */\n taskMinHours: number | null;\n /** A task's measured hours × (1 + this × (story points − 1)) before the day is shared out (0: points don't count). */\n pointsWeight: number;\n}\n\nexport const DEFAULT_TIME_SETTINGS: TimeSettings = {\n dayHours: 7.5,\n multiplier: 5,\n capHours: 7,\n stepHours: 0.25,\n minHours: 0.5,\n gapTicket: null,\n timeOffTicket: null,\n holidays: [],\n vacation: [],\n effort: false,\n deskProjects: [],\n taskMinHours: null,\n pointsWeight: 0.25,\n};\n\n/** A ticket that isn't service desk, the gap ticket or time off: a task (its own minimum, its story points count). */\nexport function isTask(key: string, s: Pick<TimeSettings, 'deskProjects' | 'gapTicket' | 'timeOffTicket'>): boolean {\n return key !== s.gapTicket && key !== s.timeOffTicket && !s.deskProjects.includes(key.split('-')[0]);\n}\n\n/** What a ticket got that day: measured Claude minutes (× multiplier), your own minutes on it (a meeting: 1:1), or only touched (0). */\nexport interface TicketActivity {\n key: string;\n minutes: number;\n direct?: number;\n}\n\nexport interface TimeEntry {\n key: string;\n hours: number;\n}\n\nexport interface DaySuggestion {\n entries: TimeEntry[];\n /** Hours of the day no ticket got (no gap ticket set). */\n unallocated: number;\n /** How each row got its hours, in words, by key: \"51 min of Claude × 5 = 4.25 h\". */\n why: Record<string, string>;\n}\n\n/** \"4.25 h\". */\nconst h2 = (h: number) => `${Math.round(h * 100) / 100} h`;\n\n/**\n * A day's suggestion. `dayOff`: all of it to the time-off ticket.\n * `reserveMinutes`: meetings no ticket got — kept for the gap ticket, so\n * the tickets' share shrinks to leave them room.\n */\nexport function suggestDay(\n activity: readonly TicketActivity[],\n s: TimeSettings,\n opts: { dayOff?: boolean; reserveMinutes?: number; points?: Record<string, number> } = {},\n): DaySuggestion {\n // Whole steps, so sums are exact.\n const units = (h: number) => Math.round(h / s.stepHours);\n const day = units(s.dayHours);\n const hours = (u: number) => Math.round(u * s.stepHours * 100) / 100;\n if (opts.dayOff)\n return s.timeOffTicket\n ? { entries: [{ key: s.timeOffTicket, hours: s.dayHours }], unallocated: 0, why: { [s.timeOffTicket]: 'a day off: the whole day' } }\n : { entries: [], unallocated: s.dayHours, why: {} };\n\n // One row per ticket; the gap ticket's own time goes into what it gets at the end.\n const minutes = new Map<string, { claude: number; direct: number }>();\n for (const a of activity) {\n if (!a.key || a.key === s.gapTicket) continue;\n const m = minutes.get(a.key) ?? { claude: 0, direct: 0 };\n m.claude += Math.max(0, a.minutes);\n m.direct += Math.max(0, a.direct ?? 0);\n minutes.set(a.key, m);\n }\n const min = s.effort ? 1 : Math.max(1, units(s.minHours));\n // A task's own minimum (as measured, none beyond a step).\n const task = (key: string) => !s.effort && s.taskMinHours !== null && isTask(key, s);\n const minFor = (key: string) => (task(key) ? Math.max(min, units(s.taskMinHours!)) : min);\n // Story points weigh a task's share: × (1 + weight × (points − 1)); unknown points, a desk ticket: × 1.\n const factorFor = (key: string) => {\n const p = opts.points?.[key];\n return !s.effort && p !== undefined && p > 0 && isTask(key, s) ? Math.max(0, 1 + s.pointsWeight * (p - 1)) : 1;\n };\n const multiplier = s.effort ? 1 : s.multiplier;\n // Room for tickets: the cap, and the day less what the gap ticket keeps (its minimum, or the meetings it has).\n const reserve = s.gapTicket ? Math.max(min, units((opts.reserveMinutes ?? 0) / 60)) : 0;\n const room = Math.max(0, Math.min(units(s.capHours), day - reserve));\n const raw = [...minutes].map(([key, m]) => {\n const h = ((m.claude / 60) * multiplier + m.direct / 60) * factorFor(key);\n // Only touched (a commit, an issue moved): the minimum — or, measuring effort, nothing.\n return { key, raw: h > 0 ? h : s.effort ? 0 : s.minHours };\n });\n const total = raw.reduce((n, r) => n + r.raw, 0);\n const scale = total > room * s.stepHours && total > 0 ? (room * s.stepHours) / total : 1;\n let rows = raw\n .map((r) => {\n const scaled = r.raw * scale;\n const u = units(scaled);\n // Under its minimum: the minimum when it's at least a step's worth, else nothing.\n const least = minFor(r.key);\n return { key: r.key, raw: scaled, u: u >= least ? u : scaled >= s.stepHours ? least : 0, first: 0 };\n })\n .filter((r) => r.u > 0);\n for (const r of rows) r.first = r.u;\n // Rounding up to minimums can overshoot the room: trim the biggest a step at a time, then drop the smallest.\n let used = rows.reduce((n, r) => n + r.u, 0);\n const dropped: string[] = [];\n while (used > room && rows.length) {\n const big = rows.filter((r) => r.u > minFor(r.key)).sort((a, b) => b.u - a.u || a.key.localeCompare(b.key))[0];\n if (big) big.u--;\n else {\n rows = rows.sort((a, b) => a.raw - b.raw);\n dropped.push(rows[0].key);\n rows = rows.slice(1);\n }\n used = rows.reduce((n, r) => n + r.u, 0);\n }\n const entries = rows.sort((a, b) => b.u - a.u || a.key.localeCompare(b.key)).map((r) => ({ key: r.key, hours: hours(r.u) }));\n\n // The words: what it measured, how that became hours, and every step after (cut to fit, a minimum, trimmed).\n const why: Record<string, string> = {};\n const roomWhy =\n room === units(s.capHours) && units(s.capHours) <= day - reserve\n ? `the ${h2(s.capHours)} cap for tickets`\n : `the ${h2(s.dayHours)} day less ${h2(hours(reserve))} kept for ${s.gapTicket}${(opts.reserveMinutes ?? 0) > 0 ? ' (meetings no ticket got)' : ''}`;\n for (const r of rows) {\n const m = minutes.get(r.key)!;\n const parts: string[] = [];\n if (m.claude > 0)\n parts.push(s.effort ? `${Math.round(m.claude)} min of Claude, as measured` : `${Math.round(m.claude)} min of Claude × ${multiplier}`);\n if (m.direct > 0) parts.push(`${Math.round(m.direct)} min of meetings`);\n const measured = (m.claude / 60) * multiplier + m.direct / 60;\n const factor = factorFor(r.key);\n const steps: string[] = [\n measured > 0\n ? `${parts.join(' + ')} = ${h2(measured)}`\n : `only touched (a commit, an issue moved, a chat): the ${h2(s.minHours)} minimum`,\n ];\n if (measured > 0 && factor !== 1)\n steps.push(`× ${Math.round(factor * 100) / 100} for ${opts.points![r.key]} story points = ${h2(measured * factor)}`);\n if (scale < 1) steps.push(`all tickets came to ${h2(total)}, over ${roomWhy}: each cut to ${Math.round(scale * 100)}%`);\n const least = minFor(r.key);\n if (r.first === least && units(r.raw) < least && (measured > 0 || least > min))\n steps.push(least > min ? `raised to the ${h2(hours(least))} minimum for a task` : `raised to the ${h2(s.minHours)} minimum`);\n if (r.u < r.first) steps.push(`trimmed ${h2(hours(r.first - r.u))} so the day adds up`);\n why[r.key] = `${steps.join('; ')} → ${h2(hours(r.u))}`;\n }\n\n const left = day - used;\n if (s.gapTicket && left > 0) {\n why[s.gapTicket] =\n (dropped.length ? `no room left for ${dropped.join(', ')} (each under its minimum); ` : '') +\n `the rest of the ${h2(s.dayHours)} day${(opts.reserveMinutes ?? 0) > 0 ? `, ${Math.round(opts.reserveMinutes ?? 0)} min of it meetings no ticket got` : ''} → ${h2(hours(left))}`;\n return { entries: [...entries, { key: s.gapTicket, hours: hours(left) }], unallocated: 0, why };\n }\n return { entries, unallocated: hours(Math.max(0, left)), why };\n}\n\n/** Sum of a day's entries, in hours (to two decimals). */\nexport function totalHours(entries: readonly TimeEntry[]): number {\n return Math.round(entries.reduce((n, e) => n + e.hours, 0) * 100) / 100;\n}\n\n/** Monday to Friday, and not a holiday. */\nexport function isWorkday(day: string, s: Pick<TimeSettings, 'holidays'>): boolean {\n const d = new Date(`${day}T12:00:00`);\n const wd = d.getDay();\n return wd !== 0 && wd !== 6 && !s.holidays.includes(day);\n}\n\n/** A Jira issue key, as found in a branch, a commit subject or a title. */\nexport const ISSUE_KEY = /\\b([A-Z][A-Z0-9]{1,9}-\\d+)\\b/g;\n\n/** Whether a string is one issue key, whole (a row's key, a configured ticket). */\nexport function isIssueKey(s: string): boolean {\n return new RegExp(`^${ISSUE_KEY.source}$`).test(s);\n}\n\n/** The issue keys in a text, only of the given projects when any are given (`UTF-8` isn't an issue). */\nexport function issueKeys(text: string, projects?: ReadonlySet<string>): string[] {\n const out: string[] = [];\n for (const m of text.matchAll(ISSUE_KEY)) {\n const key = m[1];\n if (projects && projects.size && !projects.has(key.split('-')[0])) continue;\n if (!out.includes(key)) out.push(key);\n }\n return out;\n}\n"],"mappings":";;;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;;;ACYV,IAAM,kBAAiC;AAAA,EAC5C;AAAA,IACE,OAAO;AAAA,IACP,QACE;AAAA,EACJ;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,QACE;AAAA,EACJ;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,QACE;AAAA,EACJ;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,QACE;AAAA,EACJ;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,QACE;AAAA,EACJ;AACF;AAEA,IAAM,aAAa;AAGZ,SAAS,gBAAgB,KAAyC;AACvE,MAAI,CAAC,MAAM,QAAQ,GAAG,EAAG,QAAO;AAChC,QAAM,MAAqB,CAAC;AAC5B,aAAW,KAAK,KAAK;AACnB,QAAI,CAAC,KAAK,OAAO,MAAM,SAAU;AACjC,UAAM,EAAE,OAAO,QAAQ,MAAM,IAAI;AACjC,QAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,OAAO,WAAW,YAAY,CAAC,OAAO,KAAK,EAAG;AAChG,UAAM,OAAoB,EAAE,OAAO,MAAM,KAAK,GAAG,QAAQ,OAAO,KAAK,EAAE,MAAM,GAAG,UAAU,EAAE;AAC5F,QAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,YAAM,QAAQ,MAAM,OAAO,CAAC,MAAmB,OAAO,MAAM,YAAY,EAAE,SAAS,CAAC;AACpF,UAAI,MAAM,OAAQ,MAAK,QAAQ;AAAA,IACjC;AACA,QAAI,KAAK,IAAI;AAA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