@moberg_hr/work-tree 2.0.13 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/dist/{answer-IL5AQHRO.js → answer-EGNJ2KYK.js} +4 -4
  2. package/dist/{attach-MFU4KN47.js → attach-64ILZMTD.js} +6 -6
  3. package/dist/bin.js +2 -2
  4. package/dist/{block-OXGEQ2PZ.js → block-H74FYSLK.js} +5 -5
  5. package/dist/{broadcast-UJURJNEK.js → broadcast-WRHZWOQN.js} +2 -2
  6. package/dist/{catchup-HN4VL5XK.js → catchup-7QBOC5JJ.js} +7 -7
  7. package/dist/{chunk-EU3BS5A6.js → chunk-2LIVAJLK.js} +3 -3
  8. package/dist/{chunk-FX4IA5U4.js → chunk-2QZ3RZOY.js} +4 -4
  9. package/dist/{chunk-PUYXTZ32.js → chunk-37I2GFXK.js} +3 -3
  10. package/dist/{chunk-SH7NSDRW.js → chunk-3D7MELCW.js} +2 -2
  11. package/dist/{chunk-3XY76XBD.js → chunk-3NPEMTQT.js} +2 -2
  12. package/dist/{chunk-427RB7E4.js → chunk-4Y35ABCO.js} +2 -2
  13. package/dist/{chunk-7GQCPGKQ.js → chunk-6DWPIK7D.js} +4 -4
  14. package/dist/{chunk-ZFPV46FA.js → chunk-6OG3W3PY.js} +21 -12
  15. package/dist/chunk-6OG3W3PY.js.map +1 -0
  16. package/dist/{chunk-OQAQMCHF.js → chunk-723C3D5X.js} +1 -1
  17. package/dist/chunk-723C3D5X.js.map +1 -0
  18. package/dist/{chunk-R7B46WXN.js → chunk-A3M5WTVC.js} +3 -3
  19. package/dist/{chunk-YZLNJQAV.js → chunk-ATBH7QW3.js} +2 -2
  20. package/dist/{chunk-YXQIGBL6.js → chunk-DXAIGNWF.js} +2 -2
  21. package/dist/{chunk-KUWFGPGW.js → chunk-DXHZWRVE.js} +7 -7
  22. package/dist/{chunk-BSFL3WDR.js → chunk-HY566NNR.js} +44 -44
  23. package/dist/{chunk-7JPCVEOY.js → chunk-KFSLF65S.js} +3 -3
  24. package/dist/{chunk-PVN5IGDZ.js → chunk-LCSWFGIM.js} +2 -2
  25. package/dist/{chunk-MVU7JAKG.js → chunk-MLTMXVLD.js} +2 -2
  26. package/dist/{chunk-OZIR2255.js → chunk-MXIFBNCV.js} +5 -5
  27. package/dist/{chunk-RLR66XLG.js → chunk-NPVMYGT7.js} +2 -2
  28. package/dist/{chunk-M7AUWYOP.js → chunk-OND6YRWZ.js} +4 -4
  29. package/dist/{chunk-HDO3PXCU.js → chunk-ONEXQW7Q.js} +3 -3
  30. package/dist/{chunk-6O6765M7.js → chunk-POTGMLPV.js} +2 -2
  31. package/dist/{chunk-OW46TR4G.js → chunk-PYOSW6X5.js} +3 -3
  32. package/dist/{chunk-YJVZ5H3I.js → chunk-QXDBVVSC.js} +2 -2
  33. package/dist/{chunk-F375JY4M.js → chunk-S45H7N6X.js} +5 -5
  34. package/dist/{chunk-B2RCWZUW.js → chunk-SSVVCHJB.js} +35 -7
  35. package/dist/chunk-SSVVCHJB.js.map +1 -0
  36. package/dist/chunk-UIZEMKED.js +9 -0
  37. package/dist/{chunk-4KNBN2OF.js.map → chunk-UIZEMKED.js.map} +1 -1
  38. package/dist/{chunk-KSIXTTO6.js → chunk-XILMZRNS.js} +2 -2
  39. package/dist/{chunk-MIIJ2HQS.js → chunk-YEEDWV4H.js} +3 -3
  40. package/dist/{cleanup-LRT6J36R.js → cleanup-YSVZAGJF.js} +12 -12
  41. package/dist/{cli-VGUJI5WG.js → cli-XT4AS3M2.js} +3 -3
  42. package/dist/{config-SSWYCX4C.js → config-GQRUETZ6.js} +2 -2
  43. package/dist/{diff-JBCBQM4I.js → diff-L3TWGBA4.js} +4 -4
  44. package/dist/{digest-WCZD6N7M.js → digest-R52JZ3AK.js} +4 -4
  45. package/dist/{fork-RJ3ZPPWT.js → fork-MCPMOGS5.js} +12 -12
  46. package/dist/{hook-CA5X3VKU.js → hook-S64C4G2C.js} +4 -4
  47. package/dist/{hydrate-Q4FWUQRC.js → hydrate-G5AMKHRD.js} +2 -2
  48. package/dist/{init-AT3BQLXM.js → init-PCZCSRZI.js} +3 -3
  49. package/dist/{move-OLXCDNA3.js → move-MMGOA7MV.js} +4 -4
  50. package/dist/{note-JOR53JP4.js → note-WVKK65IH.js} +4 -4
  51. package/dist/{overlaps-GXSEH2LG.js → overlaps-REVVBZCX.js} +4 -4
  52. package/dist/{pin-DAWKCVB2.js → pin-NRSD2ZT7.js} +4 -4
  53. package/dist/{pr-RKOVRSHC.js → pr-JYOI7LCK.js} +3 -3
  54. package/dist/{prune-UYCQOEUF.js → prune-AGZ24MPD.js} +11 -11
  55. package/dist/{pty-host-X3QK2LSK.js → pty-host-AZ2ORVV2.js} +2 -2
  56. package/dist/{read-IKDSIDJD.js → read-A7LFAPPZ.js} +4 -4
  57. package/dist/{recent-2LM44HN2.js → recent-H2LD5JOK.js} +2 -2
  58. package/dist/{remove-6XACPXUU.js → remove-3HQTJQWN.js} +10 -10
  59. package/dist/{restart-6ZAFDRBO.js → restart-BTUO4DTI.js} +4 -4
  60. package/dist/{resume-VA34T7ZR.js → resume-I7GXT2II.js} +2 -2
  61. package/dist/{run-E2WZPHHK.js → run-TE2AFYA6.js} +2 -2
  62. package/dist/{screen-KUXSDDLB.js → screen-XZPDSK65.js} +4 -4
  63. package/dist/{search-FJUZPI3P.js → search-MGTME3CE.js} +2 -2
  64. package/dist/{section-QLUIAYAV.js → section-YVBDU5MO.js} +4 -4
  65. package/dist/{send-V6LL6YR6.js → send-WKIX3AT5.js} +5 -5
  66. package/dist/{sessions-MKXREA2M.js → sessions-2OWYXO55.js} +9 -9
  67. package/dist/{snooze-JXI7VZJ4.js → snooze-WKY2T4VZ.js} +4 -4
  68. package/dist/{start-5XFUYT6I.js → start-ZCQT7G4C.js} +4 -4
  69. package/dist/{status-U5HKQ7MY.js → status-INIBC7GA.js} +2 -2
  70. package/dist/{stop-PFI7J2CS.js → stop-H4PTRFNX.js} +4 -4
  71. package/dist/{sync-MSU7QJWN.js → sync-6SHCY6LZ.js} +11 -11
  72. package/dist/{time-VDRCEIYQ.js → time-XQ2R7Z33.js} +5 -5
  73. package/dist/{timesheet-LSRRWV7Z.js → timesheet-DX2TLHIB.js} +6 -6
  74. package/dist/{tree-MOIO4GQL.js → tree-5AAHU4K5.js} +6 -6
  75. package/dist/{update-DXIY6BEX.js → update-6G2E5QXG.js} +6 -6
  76. package/dist/{wait-KPH5BQUD.js → wait-LFFXWBY7.js} +5 -5
  77. package/dist/wd-bin.js +2 -2
  78. package/dist/web/assets/{PtyView-D1TEpjVE.js → PtyView-l4za-VIj.js} +2 -2
  79. package/dist/web/assets/{PtyView-D1TEpjVE.js.map → PtyView-l4za-VIj.js.map} +1 -1
  80. package/dist/web/assets/{index-BVeughC2.css → index-B4wFhe7U.css} +1 -1
  81. package/dist/web/assets/index-DaCK_AAw.js +118 -0
  82. package/dist/web/assets/index-DaCK_AAw.js.map +1 -0
  83. package/dist/web/index.html +2 -2
  84. package/dist/{web-6AOR3MIE.js → web-MWSFIUIJ.js} +25 -25
  85. package/npm-shrinkwrap.json +2 -2
  86. package/package.json +1 -1
  87. package/dist/chunk-4KNBN2OF.js +0 -9
  88. package/dist/chunk-B2RCWZUW.js.map +0 -1
  89. package/dist/chunk-OQAQMCHF.js.map +0 -1
  90. package/dist/chunk-ZFPV46FA.js.map +0 -1
  91. package/dist/web/assets/index-DoMf82kx.js +0 -118
  92. package/dist/web/assets/index-DoMf82kx.js.map +0 -1
  93. /package/dist/{answer-IL5AQHRO.js.map → answer-EGNJ2KYK.js.map} +0 -0
  94. /package/dist/{attach-MFU4KN47.js.map → attach-64ILZMTD.js.map} +0 -0
  95. /package/dist/{block-OXGEQ2PZ.js.map → block-H74FYSLK.js.map} +0 -0
  96. /package/dist/{broadcast-UJURJNEK.js.map → broadcast-WRHZWOQN.js.map} +0 -0
  97. /package/dist/{catchup-HN4VL5XK.js.map → catchup-7QBOC5JJ.js.map} +0 -0
  98. /package/dist/{chunk-EU3BS5A6.js.map → chunk-2LIVAJLK.js.map} +0 -0
  99. /package/dist/{chunk-FX4IA5U4.js.map → chunk-2QZ3RZOY.js.map} +0 -0
  100. /package/dist/{chunk-PUYXTZ32.js.map → chunk-37I2GFXK.js.map} +0 -0
  101. /package/dist/{chunk-SH7NSDRW.js.map → chunk-3D7MELCW.js.map} +0 -0
  102. /package/dist/{chunk-3XY76XBD.js.map → chunk-3NPEMTQT.js.map} +0 -0
  103. /package/dist/{chunk-427RB7E4.js.map → chunk-4Y35ABCO.js.map} +0 -0
  104. /package/dist/{chunk-7GQCPGKQ.js.map → chunk-6DWPIK7D.js.map} +0 -0
  105. /package/dist/{chunk-R7B46WXN.js.map → chunk-A3M5WTVC.js.map} +0 -0
  106. /package/dist/{chunk-YZLNJQAV.js.map → chunk-ATBH7QW3.js.map} +0 -0
  107. /package/dist/{chunk-YXQIGBL6.js.map → chunk-DXAIGNWF.js.map} +0 -0
  108. /package/dist/{chunk-KUWFGPGW.js.map → chunk-DXHZWRVE.js.map} +0 -0
  109. /package/dist/{chunk-BSFL3WDR.js.map → chunk-HY566NNR.js.map} +0 -0
  110. /package/dist/{chunk-7JPCVEOY.js.map → chunk-KFSLF65S.js.map} +0 -0
  111. /package/dist/{chunk-PVN5IGDZ.js.map → chunk-LCSWFGIM.js.map} +0 -0
  112. /package/dist/{chunk-MVU7JAKG.js.map → chunk-MLTMXVLD.js.map} +0 -0
  113. /package/dist/{chunk-OZIR2255.js.map → chunk-MXIFBNCV.js.map} +0 -0
  114. /package/dist/{chunk-RLR66XLG.js.map → chunk-NPVMYGT7.js.map} +0 -0
  115. /package/dist/{chunk-M7AUWYOP.js.map → chunk-OND6YRWZ.js.map} +0 -0
  116. /package/dist/{chunk-HDO3PXCU.js.map → chunk-ONEXQW7Q.js.map} +0 -0
  117. /package/dist/{chunk-6O6765M7.js.map → chunk-POTGMLPV.js.map} +0 -0
  118. /package/dist/{chunk-OW46TR4G.js.map → chunk-PYOSW6X5.js.map} +0 -0
  119. /package/dist/{chunk-YJVZ5H3I.js.map → chunk-QXDBVVSC.js.map} +0 -0
  120. /package/dist/{chunk-F375JY4M.js.map → chunk-S45H7N6X.js.map} +0 -0
  121. /package/dist/{chunk-KSIXTTO6.js.map → chunk-XILMZRNS.js.map} +0 -0
  122. /package/dist/{chunk-MIIJ2HQS.js.map → chunk-YEEDWV4H.js.map} +0 -0
  123. /package/dist/{cleanup-LRT6J36R.js.map → cleanup-YSVZAGJF.js.map} +0 -0
  124. /package/dist/{cli-VGUJI5WG.js.map → cli-XT4AS3M2.js.map} +0 -0
  125. /package/dist/{config-SSWYCX4C.js.map → config-GQRUETZ6.js.map} +0 -0
  126. /package/dist/{diff-JBCBQM4I.js.map → diff-L3TWGBA4.js.map} +0 -0
  127. /package/dist/{digest-WCZD6N7M.js.map → digest-R52JZ3AK.js.map} +0 -0
  128. /package/dist/{fork-RJ3ZPPWT.js.map → fork-MCPMOGS5.js.map} +0 -0
  129. /package/dist/{hook-CA5X3VKU.js.map → hook-S64C4G2C.js.map} +0 -0
  130. /package/dist/{hydrate-Q4FWUQRC.js.map → hydrate-G5AMKHRD.js.map} +0 -0
  131. /package/dist/{init-AT3BQLXM.js.map → init-PCZCSRZI.js.map} +0 -0
  132. /package/dist/{move-OLXCDNA3.js.map → move-MMGOA7MV.js.map} +0 -0
  133. /package/dist/{note-JOR53JP4.js.map → note-WVKK65IH.js.map} +0 -0
  134. /package/dist/{overlaps-GXSEH2LG.js.map → overlaps-REVVBZCX.js.map} +0 -0
  135. /package/dist/{pin-DAWKCVB2.js.map → pin-NRSD2ZT7.js.map} +0 -0
  136. /package/dist/{pr-RKOVRSHC.js.map → pr-JYOI7LCK.js.map} +0 -0
  137. /package/dist/{prune-UYCQOEUF.js.map → prune-AGZ24MPD.js.map} +0 -0
  138. /package/dist/{pty-host-X3QK2LSK.js.map → pty-host-AZ2ORVV2.js.map} +0 -0
  139. /package/dist/{read-IKDSIDJD.js.map → read-A7LFAPPZ.js.map} +0 -0
  140. /package/dist/{recent-2LM44HN2.js.map → recent-H2LD5JOK.js.map} +0 -0
  141. /package/dist/{remove-6XACPXUU.js.map → remove-3HQTJQWN.js.map} +0 -0
  142. /package/dist/{restart-6ZAFDRBO.js.map → restart-BTUO4DTI.js.map} +0 -0
  143. /package/dist/{resume-VA34T7ZR.js.map → resume-I7GXT2II.js.map} +0 -0
  144. /package/dist/{run-E2WZPHHK.js.map → run-TE2AFYA6.js.map} +0 -0
  145. /package/dist/{screen-KUXSDDLB.js.map → screen-XZPDSK65.js.map} +0 -0
  146. /package/dist/{search-FJUZPI3P.js.map → search-MGTME3CE.js.map} +0 -0
  147. /package/dist/{section-QLUIAYAV.js.map → section-YVBDU5MO.js.map} +0 -0
  148. /package/dist/{send-V6LL6YR6.js.map → send-WKIX3AT5.js.map} +0 -0
  149. /package/dist/{sessions-MKXREA2M.js.map → sessions-2OWYXO55.js.map} +0 -0
  150. /package/dist/{snooze-JXI7VZJ4.js.map → snooze-WKY2T4VZ.js.map} +0 -0
  151. /package/dist/{start-5XFUYT6I.js.map → start-ZCQT7G4C.js.map} +0 -0
  152. /package/dist/{status-U5HKQ7MY.js.map → status-INIBC7GA.js.map} +0 -0
  153. /package/dist/{stop-PFI7J2CS.js.map → stop-H4PTRFNX.js.map} +0 -0
  154. /package/dist/{sync-MSU7QJWN.js.map → sync-6SHCY6LZ.js.map} +0 -0
  155. /package/dist/{time-VDRCEIYQ.js.map → time-XQ2R7Z33.js.map} +0 -0
  156. /package/dist/{timesheet-LSRRWV7Z.js.map → timesheet-DX2TLHIB.js.map} +0 -0
  157. /package/dist/{tree-MOIO4GQL.js.map → tree-5AAHU4K5.js.map} +0 -0
  158. /package/dist/{update-DXIY6BEX.js.map → update-6G2E5QXG.js.map} +0 -0
  159. /package/dist/{wait-KPH5BQUD.js.map → wait-LFFXWBY7.js.map} +0 -0
  160. /package/dist/{web-6AOR3MIE.js.map → web-MWSFIUIJ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/sessions/session-activity.ts","../src/core/platform/best-effort.ts","../src/core/pr/pr-stage.ts","../src/core/rail/snooze.ts","../src/core/status/attention.ts","../src/core/status/session-status.ts","../src/core/rail/snooze-store.ts","../src/core/conversations/conversation-store.ts","../src/core/archive/session-archive.ts","../src/core/archive/archive-uncommitted.ts","../src/core/diff/git-tree-snapshot.ts","../src/core/archive/archiving.ts","../src/core/conversations/work-time.ts","../src/core/conversations/digest.ts","../src/core/archive/archive-search.ts","../src/core/sessions/history.ts","../src/core/worktree/port-allocator.ts","../src/core/sessions/session-store.ts","../src/core/worktree/dev-server.ts","../src/core/diff/checkpoint.ts","../src/core/diff/scope-manager.ts","../src/core/platform/fs-watcher.ts"],"sourcesContent":["import { agentOf } from '../agents/index.js';\nimport type { ActivityState } from '../api-types.js';\nimport type { WorktreeSession } from './session-types.js';\n\n/**\n * How recently a session's agent wrote: the newest of its conversation files\n * (agents/: `conversation.files`). Works however the agent was started — by\n * `work tree`, `work attach`, a plain terminal or the PTY host — since they\n * all write the same files. An agent work can't read gives no activity (the\n * other signals — hooks, the PTY host's output — still do).\n */\n\n/** Active: it wrote in the last 30 s — mid-turn. */\nconst ACTIVE_MS = 30_000;\n/** Open: it wrote within 5 min — likely still at its prompt. After that, stale. */\nconst OPEN_MS = 5 * 60_000;\n\nexport interface SessionActivity {\n /** ms since epoch of its newest conversation write, or null when there is none. */\n lastActivity: number | null;\n state: ActivityState;\n}\n\n/** The newest write to any of the session's conversation files, ms (0: none). */\nexport function lastConversationWriteMs(session: WorktreeSession): number {\n let latest = 0;\n for (const f of agentOf(session).conversation?.files(session) ?? []) if (f.mtimeMs > latest) latest = f.mtimeMs;\n return latest;\n}\n\nexport function readSessionActivity(session: WorktreeSession, now = Date.now()): SessionActivity {\n const latest = lastConversationWriteMs(session);\n if (latest === 0) return { lastActivity: null, state: 'stale' };\n const age = now - latest;\n return { lastActivity: latest, state: age <= ACTIVE_MS ? 'active' : age <= OPEN_MS ? 'open' : 'stale' };\n}\n\n/**\n * True when an agent wrote within `windowMs` of `nowMs` (0: never). The\n * scope auto-snapshot timer uses it to stay out of the way while an agent is\n * at work (its turn-end hook owns checkpoints then); the timer only fires for\n * hand edits when none is.\n */\nexport function activeWithin(activityMs: number, nowMs: number, windowMs: number): boolean {\n return activityMs > 0 && nowMs - activityMs < windowMs;\n}\n\n/** When it was last used: the newer of its recorded entry and its agent's last write. */\nexport function effectiveLastAccessedAt(session: WorktreeSession): string {\n const recorded = Date.parse(session.lastAccessedAt);\n return new Date(Math.max(Number.isFinite(recorded) ? recorded : 0, lastConversationWriteMs(session))).toISOString();\n}\n","import { debugLog } from './logger.js';\n\n/**\n * \"Best effort\" without flying blind. Plenty of work's side paths must never\n * break the main one — a Claude hook must not block the turn, a failed\n * status write must not fail a request — so errors are swallowed. But a\n * silent `catch {}` makes those failures invisible when someone asks \"why\n * didn't my session show up / get restored / get a status?\". These helpers\n * swallow AND record to ~/.work/debug.log (rotated), labelled.\n *\n * Use for failures that would explain a symptom. Plain noise — unlinking a\n * file that's already gone, writing to a socket that just closed — can stay\n * a bare catch.\n */\n\nexport function logSwallowed(label: string, err: unknown): void {\n const e = err as { code?: string; message?: string } | null;\n const detail = e?.message ?? String(err);\n debugLog('WARN', `[best-effort] ${label}: ${e?.code ? `${e.code} ` : ''}${detail}`);\n}\n\n/** Run `fn`; on throw, log it and return `fallback`. */\nexport function bestEffort<T>(label: string, fn: () => T, fallback?: T): T | undefined {\n try {\n return fn();\n } catch (err) {\n logSwallowed(label, err);\n return fallback;\n }\n}\n\n/** Async variant; also catches rejections. */\nexport async function bestEffortAsync<T>(label: string, fn: () => Promise<T>, fallback?: T): Promise<T | undefined> {\n try {\n return await fn();\n } catch (err) {\n logSwallowed(label, err);\n return fallback;\n }\n}\n\n/** For promise chains: `.catch(swallow('label'))`. */\nexport function swallow(label: string): (err: unknown) => undefined {\n return (err) => {\n logSwallowed(label, err);\n return undefined;\n };\n}\n","/**\n * Where a session's pull request stands, in one word and one line — the\n * session header, the rail's tooltip, the Inbox and `work sessions` say\n * the same. Pure and import-free: the SPA and the demo import it.\n *\n * A PR waiting on others (reviewers, checks) keeps the session out of the\n * Inbox (\"In review\"); it comes back when the PR wants you again: approved\n * with checks passing (ready to merge), a merge conflict, or failing checks.\n * Review comments come back on their own (`openReviewThreads`).\n */\n\n/** What the stage reads of a PR (ShipPr, the PR watch's last check). */\nexport interface StagePr {\n number: number;\n url: string;\n state: 'OPEN' | 'MERGED' | 'CLOSED';\n isDraft: boolean;\n mergeStateStatus: string;\n checks: 'pass' | 'fail' | 'pending' | 'none';\n headSha: string;\n /** APPROVED | CHANGES_REQUESTED | REVIEW_REQUIRED, or '' when the repo requires no review. */\n reviewDecision?: string;\n}\n\nexport type PrStageKind =\n 'draft' | 'in_review' | 'checks_running' | 'checks_failing' | 'changes' | 'conflict' | 'approved' | 'ready' | 'merged' | 'closed';\n\nexport interface PrStage {\n kind: PrStageKind;\n /** \"PR #212 · approved, ready to merge\" */\n text: string;\n /** Each PR with its own stage: a group's are shown (and opened) one by one. Its\n * checks too (additive): a draft's stage is \"draft\" whatever its checks say. */\n prs: Array<{ repo: string; number: number; url: string; kind: PrStageKind; checks?: StagePr['checks'] }>;\n /** Changes when the stage or a PR's head does: what \"seen\" and a snooze compare. */\n key: string;\n}\n\n/** The stages that bring a session back to the Inbox (until you've looked). */\nexport const STAGE_WANTS_YOU: ReadonlySet<PrStageKind> = new Set(['ready', 'conflict', 'checks_failing']);\n/** The stages where it waits on others: \"In review\", out of the Inbox. */\nexport const STAGE_WAITING: ReadonlySet<PrStageKind> = new Set(['in_review', 'checks_running', 'approved', 'changes']);\n\nconst PHRASE: Record<PrStageKind, string> = {\n draft: 'draft',\n in_review: 'waiting for review',\n checks_running: 'checks running',\n checks_failing: 'checks failing',\n changes: 'changes requested',\n conflict: 'merge conflict',\n approved: 'approved',\n ready: 'approved, ready to merge',\n merged: 'merged',\n closed: 'closed',\n};\n\n/** One open PR's stage. Most pressing first: a conflict or failing checks outweigh a review. */\nexport function stageOfPr(pr: StagePr): PrStageKind {\n if (pr.state === 'MERGED') return 'merged';\n if (pr.state === 'CLOSED') return 'closed';\n if (pr.isDraft) return 'draft';\n if (pr.mergeStateStatus === 'DIRTY') return 'conflict';\n if (pr.checks === 'fail') return 'checks_failing';\n if (pr.reviewDecision === 'CHANGES_REQUESTED') return 'changes';\n if (pr.reviewDecision === 'APPROVED') {\n if (pr.checks === 'pending') return 'checks_running';\n // Behind its base or blocked by a rule: approved, not mergeable yet.\n return pr.mergeStateStatus === 'BEHIND' || pr.mergeStateStatus === 'BLOCKED' ? 'approved' : 'ready';\n }\n if (pr.checks === 'pending' && pr.reviewDecision !== 'REVIEW_REQUIRED') return 'checks_running';\n return 'in_review';\n}\n\n/** How pressing a stage is, across a group's repos (the session shows its most pressing). */\nconst RANK: Record<PrStageKind, number> = {\n conflict: 0,\n checks_failing: 1,\n changes: 2,\n draft: 3,\n in_review: 4,\n checks_running: 5,\n approved: 6,\n ready: 7,\n merged: 8,\n closed: 9,\n};\n\n/**\n * A session's stage from its repos' PRs: the most pressing open one; `ready`\n * only when every open PR is. Merged when every PR merged; null with no PR.\n */\nexport function prStageOf(repos: ReadonlyArray<{ name: string; pr: StagePr | null }>): PrStage | null {\n const withPr = repos.filter((r): r is { name: string; pr: StagePr } => !!r.pr);\n if (!withPr.length) return null;\n const open = withPr.filter((r) => r.pr.state === 'OPEN');\n const shown = open.length ? open : withPr;\n let kind: PrStageKind = 'closed';\n for (const r of shown) {\n const k = stageOfPr(r.pr);\n if (RANK[k] < RANK[kind]) kind = k;\n }\n // `ready` is the least pressing open stage, so the loop above already\n // picked anything less ready that another repo has.\n if (!open.length && withPr.some((r) => r.pr.state === 'MERGED')) kind = 'merged';\n const pr = (r: { name: string; pr: StagePr }) => ({\n repo: r.name,\n number: r.pr.number,\n url: r.pr.url,\n kind: stageOfPr(r.pr),\n checks: r.pr.checks,\n });\n const named = shown.map(pr);\n // Its merged PRs too, after the open ones: a group whose backend merged while\n // its frontend is in review shows both pills, so you know it had (and merged)\n // one. The stage, its text and its key are still the open ones'.\n const prs = [...named, ...withPr.filter((r) => r.pr.state === 'MERGED' && !shown.includes(r)).map(pr)];\n const which = named.length === 1 ? `PR #${named[0].number}` : `PRs ${named.map((p) => `${p.repo} #${p.number}`).join(', ')}`;\n return {\n kind,\n text: kind === 'draft' ? `Draft ${which}` : `${which} · ${PHRASE[kind]}`,\n prs,\n key: `${kind}:${shown.map((r) => `${r.name}@${r.pr.headSha}`).join(',')}`,\n };\n}\n\n/** A stage in a word or two, for one PR's pill: \"waiting for review\", \"ready to merge\"… */\nexport const stagePhrase = (kind: PrStageKind): string => (kind === 'ready' ? 'ready to merge' : PHRASE[kind]);\n\n/** How a stage reads at a glance: good (ready), bad (a conflict, failing checks, changes asked), draft, merged, or plain. */\nexport function stageTone(kind: PrStageKind): 'good' | 'bad' | 'draft' | 'merged' | 'plain' {\n if (kind === 'ready') return 'good';\n if (kind === 'merged') return 'merged';\n if (kind === 'conflict' || kind === 'checks_failing' || kind === 'changes') return 'bad';\n return kind === 'draft' ? 'draft' : 'plain';\n}\n\n/** It wants you: a stage that brings it back, not looked at since it got there. */\nexport function stageWantsYou(stage: (Pick<PrStage, 'kind'> & { seen?: boolean }) | null | undefined): boolean {\n return !!stage && STAGE_WANTS_YOU.has(stage.kind) && !stage.seen;\n}\n\n/** A stage as a client sent it back (the snooze and seen routes): its kind and key, or null. */\nexport function cleanStageRef(raw: unknown): { kind: PrStageKind; key: string } | null {\n const o = raw as { kind?: unknown; key?: unknown } | null;\n if (!o || typeof o !== 'object' || typeof o.key !== 'string' || !o.key || o.key.length > 2000) return null;\n return typeof o.kind === 'string' && Object.hasOwn(PHRASE, o.kind) ? { kind: o.kind as PrStageKind, key: o.key } : null;\n}\n\n/**\n * What a new check says against the stage shown before (its key, '' for\n * none, undefined before the first check): nothing new, a change to show,\n * or one that wants you — to tell you about. The first sight after a start\n * is only shown, never told.\n */\nexport function stageNews(prevKey: string | undefined, next: PrStage | null): 'none' | 'changed' | 'notify' {\n const key = next?.key ?? '';\n if (key === prevKey) return 'none';\n if (prevKey === undefined || !next) return 'changed';\n return STAGE_WANTS_YOU.has(next.kind) ? 'notify' : 'changed';\n}\n\n/** It waits on others: in review. */\nexport function stageWaiting(stage: Pick<PrStage, 'kind'> | null | undefined): boolean {\n return !!stage && STAGE_WAITING.has(stage.kind);\n}\n\n/** Per session, what each new check says against the last one (stageNews), remembering it. */\nexport function createStageTracker(): (sessionId: string, stage: PrStage | null) => 'none' | 'changed' | 'notify' {\n const shown = new Map<string, string>();\n return (sessionId, stage) => {\n const news = stageNews(shown.get(sessionId), stage);\n shown.set(sessionId, stage?.key ?? '');\n return news;\n };\n}\n\n/**\n * The session's open PRs the stage doesn't hold. The PR watch knows one PR\n * per repo (`gh pr view <branch>`), and a branch may have more — one into\n * main and one into dev — which the dashboard's PR list still has: those are\n * shown beside the stage's pills, as plainly open (or draft).\n */\nexport function prsBeyondStage<T extends { url: string }>(stage: Pick<PrStage, 'prs'> | null | undefined, prs: T[]): T[] {\n if (!stage) return prs;\n const known = new Set(stage.prs.map((p) => p.url));\n return prs.filter((p) => !known.has(p.url));\n}\n","/**\n * Snooze: \"not now\" for a session that wants you. While snoozed it leaves the\n * Inbox (and its count, `n`, Review all) for a section of its own, and a\n * snooze for a while holds its notifications. Three kinds:\n *\n * 2h — two hours\n * tomorrow — tomorrow 9:00 (today 9:00 when it is still early morning)\n * change — until its status changes (a new turn, a new question, a\n * reviewer's new comment): it notifies then, as usual\n *\n * Pure (the SPA's labels and the server's checks both use it); stored per\n * session by snooze-store.ts.\n */\n\nimport { STAGE_WANTS_YOU, type PrStageKind } from '../pr/pr-stage.js';\n\nexport type SnoozeFor = '2h' | 'tomorrow' | 'change';\n/** One of the choices, or until a time (ISO). */\nexport type SnoozeChoice = SnoozeFor | { until: string };\n\nexport interface Snooze {\n /** Until then (ISO); null for \"until it changes\". */\n until: string | null;\n /** For \"until it changes\": the status it was snoozed in (statusKey). */\n statusKey?: string;\n at: string;\n}\n\n/**\n * What \"its status changed\" compares: Claude's state and since, the review\n * threads waiting, and a PR stage that wants you (only then, so a snooze\n * taken before stages existed still holds).\n */\nexport function statusKey(s: {\n attention?: { state: string; since: string } | null;\n openReviewThreads?: number;\n prStage?: { kind: PrStageKind; key: string } | null;\n}): string {\n const base = `${s.attention?.state ?? '-'}@${s.attention?.since ?? '-'}#${s.openReviewThreads ?? 0}`;\n const pr = s.prStage && STAGE_WANTS_YOU.has(s.prStage.kind);\n return pr ? `${base}|${s.prStage!.key}` : base;\n}\n\n/** The snooze to store for a choice, made at `now` (local time for \"tomorrow\"). */\nexport function snoozeFor(choice: SnoozeFor, subject: Parameters<typeof statusKey>[0], now = new Date()): Snooze {\n const at = now.toISOString();\n if (choice === 'change') return { until: null, statusKey: statusKey(subject), at };\n if (choice === '2h') return { until: new Date(now.getTime() + 2 * 3600_000).toISOString(), at };\n const morning = new Date(now);\n morning.setHours(9, 0, 0, 0);\n // Before 6 in the morning, \"tomorrow\" means the coming morning.\n if (now.getHours() >= 6) morning.setDate(morning.getDate() + 1);\n return { until: morning.toISOString(), at };\n}\n\n/** The longest a snooze for a set time may run. */\nexport const MAX_SNOOZE_MS = 30 * 24 * 3600_000;\n\n/**\n * Snoozed until a time you chose (\"until Friday 14:00\"). Null when that time\n * isn't one: not a date, already past, or more than 30 days away (a session\n * forgotten that long belongs archived, not snoozed).\n */\nexport function snoozeUntil(until: string | Date, now = new Date()): Snooze | null {\n const t = until instanceof Date ? until.getTime() : Date.parse(until);\n if (!Number.isFinite(t) || t <= now.getTime() || t - now.getTime() > MAX_SNOOZE_MS) return null;\n return { until: new Date(t).toISOString(), at: now.toISOString() };\n}\n\nconst WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];\n\n/**\n * A time typed for `work snooze --until`, local: \"14:00\" (today, or\n * tomorrow when that has passed), \"fri\" / \"fri 14:00\" (the coming one, 9:00\n * by default), \"+3h\" / \"+2d\", or a date (\"2026-10-03\", \"2026-10-03 14:00\").\n * Null when it isn't one.\n */\nexport function parseWhen(text: string, now = new Date()): Date | null {\n const t = text.trim().toLowerCase();\n const rel = /^\\+(\\d+)\\s*([hmd])$/.exec(t);\n if (rel && rel[2] === 'd') {\n // Days: the same clock time that many days on (across a DST change too, unlike 24 h steps).\n const d = new Date(now);\n d.setDate(d.getDate() + Number(rel[1]));\n return d;\n }\n if (rel) return new Date(now.getTime() + Number(rel[1]) * (rel[2] === 'h' ? 3_600_000 : 60_000));\n const clock = (h: string, m: string | undefined, base: Date) => {\n const d = new Date(base);\n d.setHours(Number(h), Number(m ?? 0), 0, 0);\n return Number(h) < 24 && Number(m ?? 0) < 60 ? d : null;\n };\n const hm = /^(\\d{1,2}):(\\d{2})$/.exec(t);\n if (hm) {\n const d = clock(hm[1], hm[2], now);\n if (d && d <= now) d.setDate(d.getDate() + 1);\n return d;\n }\n const wd = /^([a-z]{3})[a-z]*(?:\\s+(\\d{1,2})(?::(\\d{2}))?)?$/.exec(t);\n if (wd && WEEKDAYS.includes(wd[1])) {\n const d = new Date(now);\n const ahead = (WEEKDAYS.indexOf(wd[1]) - now.getDay() + 7) % 7 || 7;\n d.setDate(d.getDate() + ahead);\n return clock(wd[2] ?? '9', wd[3], d);\n }\n const date = /^(\\d{4})-(\\d{2})-(\\d{2})(?:[ t](\\d{1,2}):(\\d{2}))?$/.exec(t);\n if (date) {\n const d = new Date(Number(date[1]), Number(date[2]) - 1, Number(date[3]));\n return clock(date[4] ?? '9', date[5], d);\n }\n return null;\n}\n\n/** Is it still snoozed: before its time, or (until it changes) still in the status it was snoozed in. */\nexport function snoozeActive(snooze: Snooze | null | undefined, subject: Parameters<typeof statusKey>[0], now = Date.now()): boolean {\n if (!snooze) return false;\n if (snooze.until !== null) return (Date.parse(snooze.until) || 0) > now;\n return snooze.statusKey === statusKey(subject);\n}\n\n/** For the Inbox's Snoozed section: \"until 17:30\", \"until tomorrow 9:00\", \"until it changes\". */\nexport function snoozeLabel(snooze: Pick<Snooze, 'until'>, now = new Date()): string {\n if (snooze.until === null) return 'until it changes';\n const t = new Date(snooze.until);\n const time = t.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });\n const tomorrow = new Date(now);\n tomorrow.setDate(tomorrow.getDate() + 1);\n if (t.toDateString() === now.toDateString()) return `until ${time}`;\n if (t.toDateString() === tomorrow.toDateString()) return `until tomorrow ${time}`;\n return `until ${t.toLocaleDateString([], { weekday: 'short' })} ${time}`;\n}\n","/**\n * Attention-inbox ordering, shared by the server (session-status.ts) and the\n * browser SPA. Pure and dependency-free on purpose: the SPA may import it\n * (see the architecture test's allowlist), so it must never pull in Node.\n */\n\nexport type AgentState = 'working' | 'needs_input' | 'idle';\n\nexport interface AttentionLike {\n state: AgentState;\n seen: boolean;\n /** When the session entered `state` (ISO). */\n since: string;\n}\n\n/**\n * Inbox order: who needs you next.\n * 0 needs input — blocked on you; longest-waiting first\n * 1 done, unseen — finished a turn you haven't looked at; oldest first\n * 2 working — most recently started first\n * 3 idle, seen — nothing to do\n * 4 no status yet\n */\nexport function attentionRank(s: Pick<AttentionLike, 'state' | 'seen'> | null | undefined): number {\n if (!s) return 4;\n if (s.state === 'needs_input') return 0;\n if (s.state === 'idle' && !s.seen) return 1;\n if (s.state === 'working') return 2;\n return 3;\n}\n\nexport function compareAttention(a: AttentionLike | null | undefined, b: AttentionLike | null | undefined): number {\n const ra = attentionRank(a);\n const rb = attentionRank(b);\n if (ra !== rb) return ra - rb;\n if (!a || !b) return 0;\n const ta = Date.parse(a.since) || 0;\n const tb = Date.parse(b.since) || 0;\n // Waiting on you: oldest first. Working / idle-seen: newest first.\n return ra <= 1 ? ta - tb : tb - ta;\n}\n\n/** Wants the user now — what the inbox count counts. */\nexport function needsAttention(s: Pick<AttentionLike, 'state' | 'seen'> | null | undefined): boolean {\n return attentionRank(s) <= 1;\n}\n\n/** What the inbox ranks: Claude's status plus reviewers waiting on the session's PRs. */\nexport interface InboxSubject {\n attention?: AttentionLike | null;\n /** Snoozed out of the Inbox (snooze.ts): a section of its own, last; it doesn't want you meanwhile. */\n snoozed?: unknown;\n /** Unresolved review threads on its open PRs whose last word isn't yours. */\n openReviewThreads?: number;\n /** What it waits on that isn't done yet (session-blocks.ts): out of the Inbox meanwhile. */\n blockedBy?: readonly unknown[];\n /** Where its pull request stands (pr-stage.ts); `seen` once you looked at it there. */\n prStage?: { kind: string; seen?: boolean } | null;\n}\n\n/**\n * The PR stages that bring a session back (pr-stage.ts STAGE_WANTS_YOU; a\n * test keeps the two equal — this module imports nothing).\n */\nexport const PR_STAGES_WANTING = ['ready', 'conflict', 'checks_failing'] as const;\n\n/** Its PR wants you and you haven't looked since: ready to merge, a conflict, failing checks. */\nexport function prWantsYou(s: Pick<InboxSubject, 'prStage'>): boolean {\n return !!s.prStage && !s.prStage.seen && (PR_STAGES_WANTING as readonly string[]).includes(s.prStage.kind);\n}\n\n/**\n * The inbox's sections, with review feedback — the same order the status\n * vocabulary colours by (session-view.ts `displayStatus`):\n * 0 needs input — blocked on you\n * 1 done, unseen — finished a turn you haven't looked at\n * 2 review comments — reviewers left unresolved comments on its PR(s),\n * or its PR is ready to merge, conflicts or fails its\n * checks (unseen), and its Claude isn't mid-turn\n * 3 working\n * 4 quiet\n * 5 no status, no review comments\n * 6 snoozed\n * 7 waiting on other work (blocked by) — unless its Claude asks you something\n */\nexport function inboxRank(s: InboxSubject): number {\n if (s.snoozed) return 6;\n const a = s.attention;\n if (s.blockedBy?.length && a?.state !== 'needs_input') return 7;\n if (a?.state === 'needs_input') return 0;\n if (a?.state === 'idle' && !a.seen) return 1;\n if (a?.state !== 'working' && ((s.openReviewThreads ?? 0) > 0 || prWantsYou(s))) return 2;\n if (a?.state === 'working') return 3;\n return a ? 4 : 5;\n}\n\n/** Inbox order: by section; waiting on you (0–2) oldest first, the rest newest first. */\nexport function compareInbox(a: InboxSubject, b: InboxSubject): number {\n const ra = inboxRank(a);\n const rb = inboxRank(b);\n if (ra !== rb) return ra - rb;\n const ta = (a.attention && Date.parse(a.attention.since)) || 0;\n const tb = (b.attention && Date.parse(b.attention.since)) || 0;\n return ra <= 2 ? ta - tb : tb - ta;\n}\n\n/** It waits on your answer, as the Inbox's first section has it (not snoozed): what flashes the desktop app's taskbar. */\nexport function waitsOnYou(s: InboxSubject): boolean {\n return inboxRank(s) === 0;\n}\n\n/** Wants you now — what the Inbox badge counts: needs input, done unseen, review comments, a PR that wants you. */\nexport function wantsYou(s: InboxSubject): boolean {\n return inboxRank(s) <= 2;\n}\n\n/** The line Claude starts when it stops to ask you something (the PR\n * watch's CI / review notes ask for it). A finished turn carrying it is\n * \"needs input\", not \"done\": top of the Inbox, and it notifies as such. */\nexport const DECISION_MARKER = 'DECISION NEEDED:';\n","import { json, tx, withDb, type Db } from '../platform/db.js';\nimport type { ConversationEntry } from '../agents/types.js';\n\n/**\n * Per-session agent status, driven by Claude Code's own hooks (installed by\n * `work web`): UserPromptSubmit → working, Stop → idle (done, review me),\n * Notification with a permission/approval message → needs_input. Hooks are\n * the source of truth — no screen scraping — the approach Emdash uses.\n *\n * Stored one row per session in state.db (see persistence below).\n */\n\nimport type { AgentState } from './attention.js';\nimport type { PermissionRequest } from '../api-types.js';\n\nexport type { AgentState } from './attention.js';\nexport { attentionRank, compareAttention, needsAttention } from './attention.js';\n\nexport interface SessionStatus {\n state: AgentState;\n /** When the session entered `state` (ISO). */\n since: string;\n /** One line: the prompt while working, Claude's last message when idle,\n * the permission request when it needs input. */\n summary?: string;\n /** False from the moment the session wants attention until the user looks\n * at it (opens it in the dashboard, or answers it). */\n seen: boolean;\n updatedAt: string;\n /** State before the latest hook event (null for the first). Lets the\n * server, which is only told \"status changed\", decide whether the\n * transition deserves a notification. */\n prevState?: AgentState | null;\n /** While needs_input on a permission prompt: the tool call it is about\n * (from the transcript), so the inbox can show it and answer it. */\n request?: PermissionRequest;\n /** When the last turn ended (the Stop hook). `since` doesn't move on an\n * idle → idle stop, and `updatedAt` moves on seen and on the idle nudge;\n * this is what transcript activity is compared with (effectiveStatus). */\n turnEndedAt?: string;\n}\n\nexport type { StatusEvent } from './status-event.js';\nimport type { StatusEvent } from './status-event.js';\n\n/** Claude's Notification hook fires both for permission prompts and for the\n * \"waiting for your input\" nudge after ~60 s idle; only the former means\n * it's blocked on you. (Same regex Emdash settled on.) */\nconst NEEDS_INPUT_RE = /permission|approval|approve|needs your input|needs network access/i;\n\n/** `notification_type`s that mean Claude waits on you (vs idle_prompt, auth_success). */\nconst WAITS_ON_YOU = new Set(['permission_prompt', 'elicitation_dialog']);\n\n/** A finished turn whose message has a DECISION_MARKER line (attention.ts). */\nconst DECISION_RE = /^[\\W_]*DECISION NEEDED\\b[:\\s-]*(.*)$/im;\n\n/** Squash a prompt / message to one readable line. */\nexport function oneLine(text: string | undefined, max = 140): string | undefined {\n if (!text) return undefined;\n const line = text\n .split(/\\r?\\n/)\n .map((l) =>\n l\n .replace(/^[#>*\\-\\s]+/, '')\n .replace(/[`*_]/g, '')\n .trim(),\n )\n .find((l) => l.length > 0);\n if (!line) return undefined;\n return line.length > max ? line.slice(0, max - 1).trimEnd() + '…' : line;\n}\n\n/** Pure transition. `prev` is null for a session never seen before. */\nexport function applyStatusEvent(prev: SessionStatus | null, event: StatusEvent, now: Date = new Date()): SessionStatus {\n const ts = now.toISOString();\n const enter = (state: AgentState, summary: string | undefined, seen: boolean): SessionStatus => ({\n state,\n since: prev?.state === state ? prev.since : ts,\n summary: summary ?? prev?.summary,\n seen,\n updatedAt: ts,\n });\n switch (event.kind) {\n case 'prompt':\n // The user just typed into it — by definition they've seen it.\n return enter('working', oneLine(event.prompt), true);\n case 'stop': {\n // A turn ended now: `since` is now even when no prompt hook marked it\n // working (a `!` command, a background task's result) — \"finished 2m ago\".\n const ask = event.lastMessage?.match(DECISION_RE);\n if (ask) return { ...enter('needs_input', oneLine(ask[1]) ?? 'Claude needs a decision', false), since: ts, turnEndedAt: ts };\n return { ...enter('idle', oneLine(event.lastMessage), false), since: ts, turnEndedAt: ts };\n }\n case 'notification': {\n // Claude Code says what kind (`notification_type`): a permission prompt\n // or a question / dialog for you, or \"idle at its prompt\" (a minute\n // after it stopped). The message text is the fallback for older\n // versions: it missed \"Claude needs your input\" and the like.\n const blocks = event.type ? WAITS_ON_YOU.has(event.type) : !!event.message && NEEDS_INPUT_RE.test(event.message);\n if (event.type === 'idle_prompt' && prev && (prev.state === 'working' || prev.state === 'needs_input')) {\n // Waiting at its prompt with no Stop: the turn was interrupted (Esc,\n // a denied permission) — by you, so nothing to flag.\n return { ...enter('idle', prev.summary, true), turnEndedAt: ts };\n }\n if (blocks) {\n const next = enter('needs_input', oneLine(event.message), false);\n return event.request ? { ...next, request: event.request } : next;\n }\n // The idle nudge: nothing new happened, don't re-flag it as unseen.\n if (prev) return { ...prev, updatedAt: ts };\n return enter('idle', undefined, false);\n }\n case 'continue':\n return enter('working', oneLine(event.what) ?? prev?.summary, prev?.seen ?? true);\n case 'answered': {\n // Allowed: the tool runs, the turn goes on. Denied: Claude stops and\n // waits for you to say what to do instead.\n const what = prev?.request ? `${prev.request.tool}: ${prev.request.detail}` : 'the request';\n return event.answer === 'allow'\n ? enter('working', oneLine(`Allowed ${what}`), true)\n : enter('idle', oneLine(`Denied ${what} — tell Claude what to do instead`), true);\n }\n }\n}\n\n/** A \"working\" status with no Claude activity for this long is treated as\n * idle: the Claude died, was killed, or the Stop hook never fired. */\nexport const STALE_WORKING_MS = 15 * 60_000;\n\nexport interface EffectiveStatus extends SessionStatus {\n /** True when `state` was downgraded from a stale \"working\". */\n stale: boolean;\n}\n\n/** Transcript activity this long after a needs-input notification means\n * the question was answered. */\nexport const ANSWERED_AFTER_MS = 3_000;\n\nexport function effectiveStatus(\n status: SessionStatus,\n lastActivityMs: number,\n now: number = Date.now(),\n /** The newest transcript entry that is a turn's work (yours or Claude's:\n * `lastTurnEntryMs`), when the caller read it; 0 = unknown. */\n lastTurnEntryMs = 0,\n): EffectiveStatus {\n const last = Math.max(lastActivityMs, Date.parse(status.updatedAt) || 0);\n if (status.state === 'working' && now - last > STALE_WORKING_MS) {\n return { ...status, state: 'idle', seen: true, stale: true };\n }\n // Approving a permission prompt fires no hook until the turn ends, so a\n // blocked session would look blocked while it's working again. Claude\n // writing its transcript after the question is the tell.\n // Answered in its terminal: Claude wrote a turn's message (a tool result,\n // its reply) after the question. Its own lines — the away summary a few\n // minutes after every turn, the last-prompt / cost lines on exit — are no\n // answer, so only turn entries count (`lastTurnEntryMs`, when the caller\n // read them; the bare transcript time otherwise). Quiet 15 min: idle.\n const since = Date.parse(status.since) || 0;\n const answeredAt = lastTurnEntryMs || lastActivityMs;\n if (status.state === 'needs_input' && answeredAt > since + ANSWERED_AFTER_MS) {\n if (now - answeredAt > STALE_WORKING_MS) return { ...status, state: 'idle', seen: true, stale: true };\n return { ...status, state: 'working', seen: true, stale: false };\n }\n // Some turns fire no prompt hook: a `!` shell command and Claude's turn on\n // its output, or any turn while work's hooks were being reinstalled (a work\n // web restart). The session read \"idle\" while it worked. A message in its\n // transcript after the last turn ended is the tell; quiet for 15 min, it\n // decays like a working status.\n if (status.state === 'idle' && lastTurnEntryMs > idleFrom(status) + ANSWERED_AFTER_MS && now - lastTurnEntryMs <= STALE_WORKING_MS) {\n return { ...status, state: 'working', seen: true, stale: false };\n }\n return { ...status, stale: false };\n}\n\n/**\n * Claude Code's own word on a running Claude (~/.claude/sessions/<pid>.json,\n * via SessionClaudes) over what the hooks recorded, when it is newer: the\n * hooks miss turns (a work web restart, an interrupt, a Stop that handed\n * Claude more work), Claude Code's file doesn't. Busy → working, waiting →\n * needs input, idle → a working / needs-input record is over.\n *\n * And with nothing running for the session anywhere (`known`: the process\n * list was read; `hosted`: no PTY of ours either), it can't be working\n * or waiting: idle at once, not after 15 quiet minutes.\n */\nexport function withLiveClaude(\n status: EffectiveStatus,\n live: { state?: 'busy' | 'idle' | 'waiting'; stateAt?: number; waitingFor?: string } | null,\n opts: { known: boolean; hosted: boolean },\n): EffectiveStatus {\n const recorded = Date.parse(status.updatedAt) || 0;\n if (live?.state && (live.stateAt ?? 0) > recorded) {\n if (live.state === 'busy' && status.state !== 'working') return { ...status, state: 'working', seen: true, stale: false };\n if (live.state === 'waiting' && status.state !== 'needs_input') {\n return {\n ...status,\n state: 'needs_input',\n seen: false,\n stale: false,\n summary: live.waitingFor ? `Waiting for you: ${live.waitingFor}` : 'Waiting for you',\n };\n }\n if (live.state === 'idle' && (status.state === 'working' || status.state === 'needs_input'))\n return { ...status, state: 'idle', seen: true, stale: true };\n }\n if (!live && opts.known && !opts.hosted && (status.state === 'working' || status.state === 'needs_input')) {\n return { ...status, state: 'idle', seen: true, stale: true };\n }\n return status;\n}\n\n/** When an idle session's last turn ended: the Stop hook's time, else (a row from before it was kept) `since`. */\nexport function idleFrom(status: SessionStatus): number {\n return Date.parse(status.turnEndedAt ?? '') || Date.parse(status.since) || 0;\n}\n\n/**\n * The newest entry that is a turn's work: your prompt or `!` command and its\n * output, the agent's message or tool call, a tool's result, a background\n * task's result. Not what the agent writes around a turn (durations, hook\n * summaries, away summaries, PR links, titles), slash commands, compaction\n * or meta lines (the agent's mapping marks those: `meta`, no `turn`). Pure;\n * 0 when there is none.\n */\nexport function lastTurnEntryMs(entries: readonly ConversationEntry[]): number {\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i];\n if (e.meta) continue;\n if (e.role === 'other' && !e.turn) continue;\n const ms = Date.parse(e.at);\n if (ms) return ms;\n }\n return 0;\n}\n\n// ---- persistence ----------------------------------------------------------\n\n// One row per session in state.db's `session_status` (db.ts). Hooks for\n// different sessions touch different rows; same-session updates are\n// transactions, so two hooks racing can't lose an event.\n\nfunction isStatus(x: unknown): x is SessionStatus {\n const s = x as SessionStatus | null;\n return !!s && typeof s === 'object' && typeof s.state === 'string' && typeof s.updatedAt === 'string';\n}\n\nfunction readRow(d: Db, sessionId: string): SessionStatus | null {\n const r = d.prepare('SELECT data FROM session_status WHERE session_id = ?').get(sessionId) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return isStatus(s) ? s : null;\n}\n\nexport function readStatus(sessionId: string): SessionStatus | null {\n return withDb((d) => readRow(d, sessionId));\n}\n\nasync function updateStatus(\n sessionId: string,\n fn: (prev: SessionStatus | null) => SessionStatus | null,\n): Promise<{ prev: SessionStatus | null; next: SessionStatus | null }> {\n return tx((d) => {\n const prev = readRow(d, sessionId);\n const next = fn(prev);\n if (next) {\n d.prepare('INSERT OR REPLACE INTO session_status (session_id, data) VALUES (?, ?)').run(sessionId, JSON.stringify(next));\n }\n return { prev, next };\n });\n}\n\n/**\n * Apply a hook event and persist it, keeping the pre-event state in\n * `prevState` for the server's notification decision.\n */\nexport function recordStatusEvent(\n sessionId: string,\n event: StatusEvent,\n now: Date = new Date(),\n): Promise<{ prev: SessionStatus | null; next: SessionStatus | null }> {\n return updateStatus(sessionId, (prev) => ({\n ...applyStatusEvent(prev, event, now),\n // A Stop ends a turn even when no prompt hook said one began (a `!`\n // command, a background task's result): as far as notifying goes, it\n // was working — so you hear that it finished.\n prevState: event.kind === 'stop' && prev?.state === 'idle' ? 'working' : (prev?.state ?? null),\n }));\n}\n\n/**\n * Its Claude is in the middle of a turn: working, or stopped mid-turn at a\n * dialog for you (a permission prompt, a question) — a needs-input state\n * entered after the last turn ended. A finished turn that asks you something\n * (DECISION NEEDED, recorded by the Stop) is not: its turn is over. Stopping\n * a Claude mid-turn cuts the turn off (a pending tool call is lost), so the\n * merged-work archive waits for this, and only this.\n */\nexport function turnInProgress(s: Pick<SessionStatus, 'state' | 'since' | 'turnEndedAt'> | null): boolean {\n if (!s) return false;\n if (s.state === 'working') return true;\n if (s.state !== 'needs_input') return false;\n const ended = s.turnEndedAt ? Date.parse(s.turnEndedAt) : NaN;\n return !(ended >= Date.parse(s.since));\n}\n\n/** The user looked at it (opened it in the dashboard). */\nexport async function markSeen(sessionId: string): Promise<SessionStatus | null> {\n const { next } = await updateStatus(sessionId, (prev) =>\n prev && !prev.seen ? { ...prev, seen: true, updatedAt: new Date().toISOString() } : prev,\n );\n return next;\n}\n\n/**\n * Whether a status change deserves a desktop notification / status hook:\n * only on entering a state that wants the user — needs_input from anything\n * else, or idle out of a turn (a finished turn). Repeat events (a second\n * Stop, the 60 s idle nudge) stay silent.\n *\n * \"Out of a turn\" includes needs_input: approving a permission prompt fires\n * no hook, so a turn that paused for one is still stored as needs_input\n * when its Stop arrives — and that finish must notify like any other.\n */\nexport function notifyKindForTransition(\n prev: Pick<SessionStatus, 'state'> | null,\n next: Pick<SessionStatus, 'state'> | null,\n): 'idle' | 'needs_input' | null {\n if (!next) return null;\n if (next.state === 'needs_input' && prev?.state !== 'needs_input') return 'needs_input';\n if (next.state === 'idle' && (prev?.state === 'working' || prev?.state === 'needs_input')) return 'idle';\n return null;\n}\n","import { json, withDb } from '../platform/db.js';\nimport type { PrStageKind } from '../pr/pr-stage.js';\nimport { snoozeFor, snoozeUntil, type Snooze } from './snooze.js';\nimport { readStatus } from '../status/session-status.js';\n\n/** Snoozes, one per session, in state.db `session_snooze` (gone with the session: purgeSessionRows). */\n\nfunction isSnooze(v: unknown): v is Snooze {\n const o = v as Snooze | null;\n return !!o && typeof o === 'object' && (o.until === null || typeof o.until === 'string') && typeof o.at === 'string';\n}\n\nexport function readSnooze(sessionId: string): Snooze | null {\n const row = withDb(\n (d) => d.prepare('SELECT data FROM session_snooze WHERE session_id = ?').get(sessionId) as { data: string } | undefined,\n );\n const v = row ? json.parse(row.data) : null;\n return isSnooze(v) ? v : null;\n}\n\n/** Every session's snooze (one query for the whole session list). */\nexport function allSnoozes(): Map<string, Snooze> {\n const rows = withDb((d) => d.prepare('SELECT session_id, data FROM session_snooze').all() as Array<{ session_id: string; data: string }>);\n const out = new Map<string, Snooze>();\n for (const r of rows) {\n const v = json.parse(r.data);\n if (isSnooze(v)) out.set(r.session_id, v);\n }\n return out;\n}\n\nexport function saveSnooze(sessionId: string, snooze: Snooze): void {\n withDb((d) => d.prepare('INSERT OR REPLACE INTO session_snooze (session_id, data) VALUES (?, ?)').run(sessionId, JSON.stringify(snooze)));\n}\n\nexport function clearSnooze(sessionId: string): boolean {\n return withDb((d) => d.prepare('DELETE FROM session_snooze WHERE session_id = ?').run(sessionId).changes > 0);\n}\n\n/** A snooze asked for: one of the choices, or until a time. */\nexport type SnoozeRequest = { for: '2h' | 'tomorrow' | 'change' } | { until: string };\n\n/** Validate a request body as one; null when it isn't. */\nexport function cleanSnoozeRequest(raw: unknown): SnoozeRequest | null {\n const o = raw as Record<string, unknown> | null;\n if (!o || typeof o !== 'object') return null;\n if (o.for === '2h' || o.for === 'tomorrow' || o.for === 'change') return { for: o.for };\n if (typeof o.until === 'string' && o.until) return { until: o.until };\n return null;\n}\n\n/**\n * Snooze a session — the dashboard's menu and `work snooze` both. \"Until it\n * changes\" is taken against the status the hooks recorded (and the review\n * threads the caller knows of), as the check that ends it compares.\n */\nexport function requestSnooze(\n sessionId: string,\n req: SnoozeRequest,\n shown: { openReviewThreads?: number; prStage?: { kind: PrStageKind; key: string } | null } = {},\n now = new Date(),\n): { ok: true; snooze: Snooze } | { ok: false; error: string } {\n const snooze =\n 'until' in req\n ? snoozeUntil(req.until, now)\n : snoozeFor(\n req.for,\n { attention: readStatus(sessionId), openReviewThreads: shown.openReviewThreads ?? 0, prStage: shown.prStage },\n now,\n );\n if (!snooze) return { ok: false, error: 'not a time to snooze until: give one in the next 30 days' };\n saveSnooze(sessionId, snooze);\n return { ok: true, snooze };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport zlib from 'node:zlib';\nimport { getConfigDir } from '../platform/config.js';\nimport { agentOf } from '../agents/index.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { archiveRoot, readArchive, readArchivedTranscript } from '../archive/session-archive.js';\nimport { matchingLines, queryWords, snippet } from '../archive/archive-search.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport type { ConversationHit } from '../api-types.js';\n\n/**\n * work's own copy of every session's Claude conversations, at\n * ~/.work/conversations/<session id>/<transcript>.jsonl. Claude Code\n * deletes its transcripts after a while (`cleanupPeriodDays`, 30 days by\n * default); this copy stays as long as the session, so a session's whole\n * history can be searched (`searchConversations`, GET\n * /api/conversations/search, `work search`). Disk is cheap here; nothing of\n * it is held in memory.\n *\n * Synced incrementally: a transcript only ever grows, so only its new bytes\n * are appended (a source that got smaller was replaced: copied whole). Run\n * after each Claude turn (the status hook) and by a sweep at start and every\n * 30 minutes. Removing the session removes it (sessionStatePaths).\n */\n\nexport const conversationRoot = (): string => path.join(getConfigDir(), 'conversations');\nexport const conversationDirFor = (id: string, root = conversationRoot()): string => path.join(root, id);\n\nexport interface SyncResult {\n files: number;\n bytes: number;\n}\n\n/** Bring a session's copy up to date with its transcripts. */\nexport async function syncConversation(\n s: WorktreeSession,\n root = conversationRoot(),\n sources = agentOf(s).conversation?.files(s) ?? [],\n): Promise<SyncResult> {\n const dir = conversationDirFor(sessionIdFor(s), root);\n const out: SyncResult = { files: 0, bytes: 0 };\n for (const src of sources) {\n const dest = path.join(dir, path.basename(src.file));\n // Packed while it was quiet (compressQuietCopies): unchanged since, it\n // stays packed; the conversation went on, so unpack it and copy the rest.\n const packed = await packedState(dest, src.mtimeMs);\n if (packed === 'current') continue;\n if (packed === 'stale') await unpack(dest);\n let have = 0;\n let haveMtime = 0;\n try {\n const st = await fs.promises.stat(dest);\n [have, haveMtime] = [st.size, st.mtimeMs];\n } catch {\n /* not copied yet */\n }\n if (have === src.size) {\n // Complete; only its time may be off (a copy from before times were kept).\n if (Math.abs(haveMtime - src.mtimeMs) > 1000)\n await fs.promises.utimes(dest, new Date(), new Date(src.mtimeMs)).catch(() => undefined);\n continue;\n }\n await fs.promises.mkdir(dir, { recursive: true });\n if (have > src.size) {\n // Smaller than our copy: the file was replaced. Copy it whole.\n await fs.promises.copyFile(src.file, dest);\n out.bytes += src.size;\n } else {\n out.bytes += await appendRange(src.file, dest, have, src.size);\n }\n // The copy's time is the conversation's last write, not when we copied\n // it: search orders by it, and shows it.\n await fs.promises.utimes(dest, new Date(), new Date(src.mtimeMs)).catch(() => undefined);\n out.files++;\n }\n return out;\n}\n\n/** A copy kept gzipped: its time is the conversation's last write, so a newer source means it went on. */\nasync function packedState(dest: string, srcMtimeMs: number): Promise<'none' | 'current' | 'stale'> {\n try {\n const st = await fs.promises.stat(`${dest}.gz`);\n return srcMtimeMs <= st.mtimeMs + 1000 ? 'current' : 'stale';\n } catch {\n return 'none';\n }\n}\n\n/** Back to a plain copy (the conversation went on): written beside it, then put in place. */\nasync function unpack(dest: string): Promise<void> {\n const gz = `${dest}.gz`;\n const tmp = `${dest}.unpack-${process.pid}`;\n await fs.promises.writeFile(tmp, zlib.gunzipSync(await fs.promises.readFile(gz)));\n await fs.promises.rename(tmp, dest);\n await fs.promises.rm(gz, { force: true });\n}\n\n/** How long a conversation stays untouched before its copy is gzipped. */\nexport const PACK_QUIET_MS = 2 * 24 * 3600_000;\n\n/**\n * Gzip the copies of conversations nobody has written to for a while\n * (JSON lines shrink about tenfold). Lossless: search reads `.gz`, and a\n * sync unpacks one whose conversation goes on. Written beside it and\n * renamed, so a reader never sees half a file; its time stays the\n * conversation's last write.\n */\nexport async function compressQuietCopies(\n root = conversationRoot(),\n now = Date.now(),\n quietMs = PACK_QUIET_MS,\n): Promise<{ files: number; bytesSaved: number }> {\n const out = { files: 0, bytesSaved: 0 };\n let dirs: string[];\n try {\n dirs = await fs.promises.readdir(root);\n } catch {\n return out;\n }\n for (const d of dirs) {\n const dir = path.join(root, d);\n let names: string[];\n try {\n names = (await fs.promises.readdir(dir)).filter((n) => n.endsWith('.jsonl'));\n } catch {\n continue;\n }\n for (const n of names) {\n const file = path.join(dir, n);\n try {\n const st = await fs.promises.stat(file);\n if (now - st.mtimeMs < quietMs) continue;\n const packed = zlib.gzipSync(await fs.promises.readFile(file));\n const tmp = `${file}.gz.tmp-${process.pid}`;\n await fs.promises.writeFile(tmp, packed);\n await fs.promises.utimes(tmp, new Date(), new Date(st.mtimeMs));\n await fs.promises.rename(tmp, `${file}.gz`);\n await fs.promises.rm(file, { force: true });\n out.files++;\n out.bytesSaved += st.size - packed.length;\n } catch {\n /* busy or gone: next sweep */\n }\n }\n }\n return out;\n}\n\n/**\n * Copy bytes [from, to) of `src` to the same offsets of `dest`; returns how\n * many. Written at the source's offsets, not appended: two syncs of one\n * session at once (a turn's and the sweep's, or `work search` beside work\n * web) write the same bytes to the same place instead of doubling lines.\n */\nasync function appendRange(src: string, dest: string, from: number, to: number): Promise<number> {\n await (await fs.promises.open(dest, 'a')).close(); // create it if new\n const [inp, out] = [await fs.promises.open(src, 'r'), await fs.promises.open(dest, 'r+')];\n try {\n const chunk = 4 * 1024 * 1024;\n let done = 0;\n for (let pos = from; pos < to; pos += chunk) {\n const buf = Buffer.alloc(Math.min(chunk, to - pos));\n const { bytesRead } = await inp.read(buf, 0, buf.length, pos);\n if (bytesRead === 0) break;\n await out.write(buf, 0, bytesRead, pos);\n done += bytesRead;\n }\n return done;\n } finally {\n await inp.close();\n await out.close();\n }\n}\n\n/** Sync many sessions, a few at a time. */\nexport async function syncConversations(\n sessions: WorktreeSession[],\n root = conversationRoot(),\n concurrency = 3,\n): Promise<SyncResult & { sessions: number }> {\n const total = { files: 0, bytes: 0, sessions: 0 };\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, sessions.length) }, async () => {\n for (let i = next++; i < sessions.length; i = next++) {\n const r = await syncConversation(sessions[i], root).catch(() => ({ files: 0, bytes: 0 }));\n total.files += r.files;\n total.bytes += r.bytes;\n if (r.files) total.sessions++;\n }\n }),\n );\n return total;\n}\n\nconst MAX_SESSIONS = 20;\nconst SNIPPETS_PER_SESSION = 3;\n\n/** A session's transcript texts from its copy (plain or gzipped), newest first. */\nfunction storedTranscripts(dir: string): Array<{ mtimeMs: number; read: () => string | null }> {\n let names: string[];\n try {\n names = fs.readdirSync(dir).filter((n) => n.endsWith('.jsonl') || n.endsWith('.jsonl.gz'));\n } catch {\n return [];\n }\n return names\n .map((n) => {\n const file = path.join(dir, n);\n let mtimeMs = 0;\n try {\n mtimeMs = fs.statSync(file).mtimeMs;\n } catch {\n /* vanished */\n }\n const read = () => {\n try {\n const buf = fs.readFileSync(file);\n return (n.endsWith('.gz') ? zlib.gunzipSync(buf) : buf).toString('utf8');\n } catch {\n return null;\n }\n };\n return { mtimeMs, read };\n })\n .sort((a, b) => b.mtimeMs - a.mtimeMs);\n}\n\n/**\n * \"What did we do about X?\" across every session's kept conversation — live\n * and archived (an archive made before this store existed is read from its\n * archive copy). Every word must appear in one message (yours or Claude's)\n * or in an archive's written summary. Most recently active sessions first,\n * up to 20.\n */\nexport async function searchConversations(\n query: string,\n opts: { sessions: WorktreeSession[]; root?: string; archive?: string },\n): Promise<ConversationHit[]> {\n const { words, jsonWords } = queryWords(query);\n if (words.length === 0) return [];\n const root = opts.root ?? conversationRoot();\n const archive = opts.archive ?? archiveRoot();\n const candidates = opts.sessions.map((s) => {\n const id = sessionIdFor(s);\n const stored = storedTranscripts(conversationDirFor(id, root));\n const rec = readArchive(id, archive);\n const lastMs = Math.max(0, ...stored.map((t) => t.mtimeMs), rec ? Date.parse(rec.archivedAt) || 0 : 0);\n // Its lines read as its agent writes them; none when work can't read that agent's conversations.\n const entries = agentOf(s).conversation?.entries ?? (() => []);\n return { s, id, stored, rec, lastMs, entries };\n });\n candidates.sort((a, b) => b.lastMs - a.lastMs);\n const hits: ConversationHit[] = [];\n for (const c of candidates) {\n if (hits.length >= MAX_SESSIONS) break;\n const snippets: ConversationHit['snippets'] = [];\n const written = c.rec?.summary.written;\n if (written && words.every((w) => written.toLowerCase().includes(w))) {\n snippets.push({ role: 'summary', text: snippet(written, words), at: c.rec!.archivedAt });\n }\n // An archived session reads its archive (complete as of archiving; from\n // before this store existed too), a live one its own copy. Each falls\n // back to the other when it has nothing readable (archive transcripts\n // dropped by config, no sync yet).\n const fromArchive = (c.rec?.transcripts ?? []).map((t) => () => readArchivedTranscript(c.id, t.file, archive));\n const fromStore = c.stored.map((t) => t.read);\n const [first, second] = c.s.archivedAt ? [fromArchive, fromStore] : [fromStore, fromArchive];\n for (const texts of [first, second]) {\n let readAny = false;\n for (const read of texts) {\n if (snippets.length >= SNIPPETS_PER_SESSION) break;\n const raw = read();\n if (raw === null) continue;\n readAny = true;\n await new Promise((r) => setImmediate(r)); // a big history doesn't hold up the server\n snippets.push(...matchingLines(raw, words, jsonWords, SNIPPETS_PER_SESSION - snippets.length, c.entries));\n }\n if (readAny) break;\n }\n if (!snippets.length) continue;\n hits.push({\n sessionId: c.id,\n target: c.s.target,\n branch: c.s.branch,\n archived: !!c.s.archivedAt,\n archivedAt: c.s.archivedAt ?? null,\n worktreeRemoved: !!c.rec?.worktreeRemoved && !!c.s.archivedAt,\n lastAt: c.lastMs ? new Date(c.lastMs).toISOString() : null,\n snippets,\n });\n }\n return hits;\n}\n","import fs from 'node:fs';\nimport { isSavedUncommitted, type SavedUncommitted } from './archive-uncommitted.js';\nimport { logSwallowed } from '../platform/best-effort.js';\nimport { clearSnooze } from '../rail/snooze-store.js';\nimport { whileArchiving } from './archiving.js';\nimport path from 'node:path';\nimport zlib from 'node:zlib';\nimport { getConfigDir } from '../platform/config.js';\nimport { promptsSince } from '../conversations/digest.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { readJsonlTail } from '../conversations/jsonl.js';\nimport { agentOf } from '../agents/index.js';\nimport type { ConversationEntry } from '../agents/types.js';\n\n/**\n * Archiving a session: out of the way, its disk space back, its history kept.\n *\n * 0. unless forced, nothing is waiting in it: replies Claude drafted for\n * you to post, notes not yet delivered to its Claude, a Claude mid-turn\n * or waiting for your answer (`waiting`);\n * 1. its Claude and its dev server are stopped;\n * 2. its conversation (every transcript) is copied to\n * ~/.work/archive/<id>/transcripts — Claude Code deletes old transcripts\n * by itself, and this is what \"recall what we did\" reads;\n * 3. a summary is written next to it: your prompts, its PRs, how it ended,\n * the branch tips — and, in the background, a few sentences on what was\n * done and why (`writeArchiveSummary`, an internal `claude -p`);\n * 4. the worktree is removed — only when cleanup's own check says nothing\n * would be lost (merged, clean) — and then its checkpoint refs go, and a\n * branch already merged into the main branch is deleted (its tip is\n * recorded; Restore recreates it). Otherwise the worktree stays, the\n * reason is recorded, and its build output (node_modules, bin/obj, …)\n * is cleared to give the disk back anyway;\n * 5. the session is marked archived.\n *\n * Restoring (`work tree` into it, or Restore in the dashboard) recreates the\n * branch if archiving deleted it, the worktree from the branch, and puts the\n * transcripts back where Claude looks for them, so it continues the\n * conversation. Old archives are compressed (archive-retention.ts).\n */\n\nexport interface ArchivedPr {\n repo: string;\n number: number;\n url: string;\n state: string;\n}\n\n/** A repo's git-ignored files archiving copied (archive-ignored.ts). */\nexport interface SavedIgnored {\n files: number;\n bytes: number;\n /** Left out: over a cap. */\n skipped: number;\n /** It stopped looking at MAX_IGNORED_FILES files: more were there. */\n partial?: true;\n /** Put back by a Restore (then not again). */\n restoredAt?: string;\n /** A Restore that couldn't put them back: why (not tried again). */\n restoreError?: string;\n}\n\nexport interface ArchiveRecord {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n paths: string[];\n archivedAt: string;\n /** The worktree folder(s) were removed (false: kept, see keptBecause). */\n worktreeRemoved: boolean;\n keptBecause: string | null;\n /** Removed only in part: git stopped at a file in use, leaving these folders with no git in\n * them. The save is kept; Restore makes the worktree again and copies them back (leftover.ts). */\n leftovers?: string[];\n /** Transcript file names under transcripts/, by the folder they belong to\n * (on disk `<file>` or, once compressed, `<file>.gz`). */\n transcripts: Array<{ file: string; projectDir: string }>;\n summary: {\n prompts: Array<{ ts: string; text: string }>;\n promptCount: number;\n lastSummary: string | null;\n prs: ArchivedPr[];\n jiraKey: string | null;\n /** What was done and why, in a few sentences (written after archiving). */\n written?: string | null;\n };\n /** Each repo's branch tip when archived (repo alias → commit): of the branch checked out (`heads`), else the session's. */\n tips?: Record<string, string>;\n /** Repos checked out on another branch than the session's when archived (alias → branch): Restore brings that branch back. */\n heads?: Record<string, string>;\n /** Repos whose local branch was deleted (merged): Restore recreates it at its tip. */\n branchesDeleted?: string[];\n /** Build output cleared from a kept worktree. */\n buildFolders?: { folders: number; bytes: number };\n /** Uncommitted work saved because the worktree was removed (repo alias → where it is): Restore puts it back (archive-uncommitted.ts). */\n uncommitted?: Record<string, SavedUncommitted>;\n /** Git-ignored files that aren't build output (local settings, the editor's state), copied because the\n * worktree was removed (repo alias → how many): Restore puts them back (archive-ignored.ts). */\n ignored?: Record<string, SavedIgnored>;\n /** What was still waiting in it when archived (a merged session isn't held up by these): they stay in\n * state.db with the session, so Restore brings them back — drafts in the header, notes delivered on\n * its next turn. Listed here so the archive says what it holds. */\n kept?: ArchiveKept;\n /** Saved work an earlier Restore couldn't put back, carried over when archived again (still in its ref and patch). */\n unrestored?: SavedUncommitted[];\n /** When the copied git-ignored files were deleted for retention (ISO): they can hold secrets. */\n ignoredDroppedAt?: string;\n /** When the transcripts were compressed / deleted for retention (ISO). */\n compressedAt?: string;\n transcriptsDroppedAt?: string;\n}\n\nexport interface ArchiveKept {\n replyDrafts: Array<{ threadId: string; url: string; reviewer: string; draft: string }>;\n notes: Array<{ id: string; text: string }>;\n /** Its Claude was waiting for your answer: what it asked. */\n askingYou?: string;\n}\n\nexport interface ArchiveDeps {\n stopClaude: (id: string) => Promise<void>;\n /** Would removing its worktree lose anything? (cleanup's verdict). With\n * `uncommittedSaved`, uncommitted files don't count: they were saved. */\n removable: (s: WorktreeSession, opts?: { uncommittedSaved?: boolean }) => Promise<{ ok: boolean; reason: string }>;\n /** Save each repo's uncommitted work (archive-uncommitted.ts) before the worktree may go. */\n saveUncommitted?: (\n s: WorktreeSession,\n archiveDir: string,\n stamp: number,\n ) => Promise<{ saved: Record<string, SavedUncommitted>; error: string | null }>;\n /** Drop saves that weren't needed (the worktree stayed). */\n dropSaved?: (s: WorktreeSession, saved: Record<string, SavedUncommitted>, archiveDir: string) => Promise<void>;\n /** Copy each repo's git-ignored files that aren't build output into `<archiveDir>/ignored/<repo>` (archive-ignored.ts). */\n saveIgnored?: (s: WorktreeSession, archiveDir: string) => Promise<Record<string, SavedIgnored>>;\n removeWorktree: (s: WorktreeSession) => Promise<boolean>;\n /** After a removal git refused: the session's folders left with no git in them (it stopped halfway). */\n halfRemoved?: (s: WorktreeSession) => string[];\n setArchived: (s: WorktreeSession) => Promise<boolean>;\n /** The session's transcript files. */\n transcripts: (s: WorktreeSession) => string[];\n prs?: (id: string) => ArchivedPr[];\n lastSummary?: (id: string) => string | null;\n /** What archiving now would leave behind unfinished (empty: nothing). */\n waiting?: (id: string) => string[];\n /** Its Claude is in the middle of a turn (stopping it would cut the turn off). */\n working?: (id: string) => boolean;\n /** What waits in it, to list in the record (drafts, notes, a question). */\n kept?: (id: string) => ArchiveKept;\n stopDev?: (id: string) => void;\n /** Repos checked out on another branch than the session's (alias → branch). */\n heads?: (s: WorktreeSession) => Record<string, string>;\n /** Each repo's branch tip (alias → commit): of `heads[alias]`, else the session's branch. */\n tips?: (s: WorktreeSession, heads: Record<string, string>) => Promise<Record<string, string>>;\n /** A kept worktree: clear its git-ignored build output. */\n clearBuildFolders?: (s: WorktreeSession) => Promise<{ folders: number; bytes: number }>;\n /** A removed worktree: its checkpoint refs, and merged local branches — the session's and the one checked out (returns the repos whose checked-out branch went). */\n tidy?: (s: WorktreeSession, heads: Record<string, string>) => Promise<string[]>;\n /** A few sentences on what was done (background; null: none). */\n summarize?: (rec: ArchiveRecord) => Promise<string | null>;\n archiveRoot?: string;\n now?: () => number;\n}\n\nexport interface ArchiveOutcome {\n ok: boolean;\n worktreeRemoved: boolean;\n keptBecause: string | null;\n transcripts: number;\n message: string;\n /** Not archived: these were waiting (archive with force to go ahead). */\n blocked?: string[];\n /** What waited in it and was kept with it (\"2 reply drafts, 1 note for its Claude\"). */\n kept?: string;\n}\n\n/** Most prompts kept in the summary: the first ones (what it was about) and the latest. */\nconst SUMMARY_PROMPTS = 40;\n\nexport const archiveRoot = (): string => path.join(getConfigDir(), 'archive');\nexport const archiveDirFor = (id: string, root = archiveRoot()): string => path.join(root, id);\n\n/** Told after each archive that went through (work web: stacked sessions move onto main). */\nconst afterArchive = new Set<(s: WorktreeSession) => void | Promise<unknown>>();\n\n/** Listen for archives (every path: the button, Ship, the PR watch, cleanup); returns the unsubscribe. A listener may be async: its failure is logged, never the archive's. */\nexport function onArchived(listener: (s: WorktreeSession) => void | Promise<unknown>): () => void {\n afterArchive.add(listener);\n return () => afterArchive.delete(listener);\n}\n\n/**\n * `merged`: the session's PR merged (the PR watch, Ship). That decides it:\n * reply drafts, undelivered notes and a question for you don't hold it up —\n * they stay with the session and are listed in the record — and only a\n * Claude in the middle of a turn does (the caller tries again later).\n */\nexport interface ArchiveOptions {\n force?: boolean;\n merged?: boolean;\n}\n\nexport async function archiveSession(s: WorktreeSession, deps: ArchiveDeps, opts: ArchiveOptions = {}): Promise<ArchiveOutcome> {\n // Nothing starts its Claude again while this runs (archiving.ts).\n const out = await whileArchiving(sessionIdFor(s), () => archiveSteps(s, deps, opts));\n if (out.ok)\n for (const l of afterArchive) {\n // Sync throws and async rejections alike: a listener's trouble isn't the archive's.\n void Promise.resolve()\n .then(() => l(s))\n .catch((err) => logSwallowed('after archiving', err));\n }\n return out;\n}\n\nasync function archiveSteps(s: WorktreeSession, deps: ArchiveDeps, opts: ArchiveOptions): Promise<ArchiveOutcome> {\n const id = sessionIdFor(s);\n const root = deps.archiveRoot ?? archiveRoot();\n const dir = archiveDirFor(id, root);\n const now = deps.now ?? Date.now;\n\n // 0. Work still waiting in it would vanish from view with it.\n const waiting = opts.force\n ? []\n : opts.merged\n ? deps.working?.(id)\n ? ['its Claude is in the middle of a turn']\n : []\n : (deps.waiting?.(id) ?? []);\n if (waiting.length) {\n return {\n ok: false,\n worktreeRemoved: false,\n keptBecause: null,\n transcripts: 0,\n blocked: waiting,\n message: `Not archived: ${waiting.join('; ')}.`,\n };\n }\n\n await deps.stopClaude(id);\n try {\n deps.stopDev?.(id);\n } catch {\n /* not running */\n }\n // Which branch each repo is on: Claude may have switched from the session's.\n let heads: Record<string, string> = {};\n try {\n heads = deps.heads?.(s) ?? {};\n } catch {\n /* unreadable: the session's branch, as before */\n }\n const tips = (await deps.tips?.(s, heads).catch(() => ({}))) ?? {};\n\n // 2. The conversation. Copied before anything is removed; a copy that fails\n // stops the archive (nothing removed, nothing marked).\n const copied: ArchiveRecord['transcripts'] = [];\n // Read as its agent writes them (none when work can't read that agent's conversations).\n const toEntries = agentOf(s).conversation?.entries ?? (() => []);\n const entries: ConversationEntry[][] = [];\n try {\n fs.mkdirSync(path.join(dir, 'transcripts'), { recursive: true });\n for (const file of deps.transcripts(s)) {\n const name = path.basename(file);\n fs.copyFileSync(file, path.join(dir, 'transcripts', name));\n copied.push({ file: name, projectDir: path.basename(path.dirname(file)) });\n entries.push(toEntries(readJsonlTail(file, 64 * 1024 * 1024)));\n }\n } catch (err) {\n return {\n ok: false,\n worktreeRemoved: false,\n keptBecause: null,\n transcripts: copied.length,\n message: `Not archived: could not copy its conversation (${(err as Error).message}).`,\n };\n }\n\n // 3. Uncommitted work is saved (a snapshot commit + a patch), so it\n // doesn't keep the worktree: Restore puts it back. A save that fails\n // keeps the worktree, as before.\n const saving = deps.saveUncommitted\n ? await deps.saveUncommitted(s, dir, now()).catch((err: Error) => ({ saved: {}, error: err.message }))\n : { saved: {}, error: null };\n let saved: Record<string, SavedUncommitted> = saving.error ? {} : saving.saved;\n if (saving.error) await deps.dropSaved?.(s, saving.saved, dir).catch(() => {});\n\n // 4. The folder goes only if nothing would be lost.\n const verdict = await deps.removable(s, { uncommittedSaved: !saving.error });\n let worktreeRemoved = false;\n let keptBecause: string | null = null;\n let leftovers: string[] = [];\n let ignored: Record<string, SavedIgnored> = {};\n const ignoredDir = path.join(dir, 'ignored');\n if (verdict.ok) {\n // Local settings and the editor's state go with the folder: kept, so Restore brings them back.\n fs.rmSync(ignoredDir, { recursive: true, force: true });\n ignored = deps.saveIgnored ? await deps.saveIgnored(s, dir).catch(() => ({})) : {};\n worktreeRemoved = await deps.removeWorktree(s);\n // git deletes the files first and stops at one in use (Visual Studio's): the folder\n // that's left is no worktree any more. That's removed — and its save is the copy.\n leftovers = worktreeRemoved ? [] : (deps.halfRemoved?.(s) ?? []);\n // Removed only when every folder is gone or half-removed: a repo of a group whose\n // removal failed outright is still a worktree, and the session keeps it.\n if (leftovers.length && s.paths.every((p) => leftovers.includes(p) || !fs.existsSync(p))) worktreeRemoved = true;\n else if (!worktreeRemoved)\n keptBecause = leftovers.length\n ? `git removed ${leftovers.join(', ')} only in part (a file in use) and kept the rest`\n : 'git refused to remove the worktree';\n } else {\n keptBecause = saving.error && !verdict.reason.includes(saving.error) ? `${verdict.reason} (${saving.error})` : verdict.reason;\n }\n // Kept: the changes are still in it, so the saves aren't needed.\n // (Not when part of it is gone: the saves are the only copy of that.)\n if (!worktreeRemoved && !leftovers.length && Object.keys(saved).length) {\n await deps.dropSaved?.(s, saved, dir).catch(() => {});\n saved = {};\n }\n if (!worktreeRemoved && !leftovers.length && Object.keys(ignored).length) {\n fs.rmSync(ignoredDir, { recursive: true, force: true });\n ignored = {};\n }\n // What waits in it (kept with the session in state.db), listed in the record.\n const kept = deps.kept?.(id);\n // Work an earlier Restore couldn't put back stays known (its ref and patch are still there).\n const earlier = readArchive(id, root);\n const unrestored = [...(earlier?.unrestored ?? []), ...Object.values(earlier?.uncommitted ?? {}).filter((u) => !u.restoredAt)];\n let branchesDeleted: string[] = [];\n let buildFolders: ArchiveRecord['buildFolders'];\n if (worktreeRemoved) branchesDeleted = (await deps.tidy?.(s, heads).catch(() => [])) ?? [];\n else if (keptBecause !== \"it is the repo's own checkout\" && deps.clearBuildFolders) {\n buildFolders = await deps.clearBuildFolders(s).catch(() => undefined);\n }\n\n const all = promptsSince(entries, 0);\n const prompts = all.length > SUMMARY_PROMPTS ? [...all.slice(0, SUMMARY_PROMPTS / 2), ...all.slice(-SUMMARY_PROMPTS / 2)] : all;\n const record: ArchiveRecord = {\n sessionId: id,\n target: s.target,\n branch: s.branch,\n isGroup: s.isGroup,\n paths: s.paths,\n archivedAt: new Date(now()).toISOString(),\n worktreeRemoved,\n keptBecause,\n ...(leftovers.length ? { leftovers } : {}),\n transcripts: copied,\n summary: {\n prompts,\n promptCount: all.length,\n lastSummary: deps.lastSummary?.(id) ?? null,\n prs: deps.prs?.(id) ?? [],\n jiraKey: s.jiraKey ?? null,\n },\n ...(Object.keys(tips).length ? { tips } : {}),\n ...(Object.keys(heads).length ? { heads } : {}),\n ...(branchesDeleted.length ? { branchesDeleted } : {}),\n ...(buildFolders && buildFolders.folders ? { buildFolders } : {}),\n ...(Object.keys(saved).length ? { uncommitted: saved } : {}),\n ...(Object.keys(ignored).length ? { ignored } : {}),\n ...(unrestored.length ? { unrestored } : {}),\n ...(keptAny(kept) ? { kept } : {}),\n };\n fs.writeFileSync(path.join(dir, 'archive.json'), JSON.stringify(record, null, 2));\n\n await deps.setArchived(s);\n // A snooze doesn't outlive the archive: Restore brings it back as it is now.\n try {\n clearSnooze(id);\n } catch {\n /* best effort */\n }\n if (deps.summarize) void writeArchiveSummary(id, deps.summarize, root).catch(() => {});\n return {\n ok: true,\n worktreeRemoved,\n keptBecause,\n transcripts: copied.length,\n message:\n (worktreeRemoved\n ? `Archived; worktree removed, conversation kept${savedFiles(saved) ? `, ${savedFiles(saved)} uncommitted file${savedFiles(saved) === 1 ? '' : 's'} saved for Restore` : ''}${leftovers.length ? `; git stopped at a file in use, so part of the folder is left (${leftovers.join(', ')}): close what holds it and delete it, or Restore puts it back` : ''}`\n : `Archived; worktree kept (${keptBecause})`) + (keptList(kept) ? `; kept for Restore: ${keptList(kept)}` : ''),\n ...(keptList(kept) ? { kept: keptList(kept) } : {}),\n };\n}\n\nconst savedFiles = (saved: Record<string, SavedUncommitted>): number => Object.values(saved).reduce((n, u) => n + u.files, 0);\nconst keptAny = (k: ArchiveKept | undefined): k is ArchiveKept => !!k && (k.replyDrafts.length > 0 || k.notes.length > 0 || !!k.askingYou);\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;\n/** \"2 reply drafts, 1 note for its Claude, its question to you\" (empty: nothing kept). */\nexport function keptList(k: ArchiveKept | undefined): string {\n if (!keptAny(k)) return '';\n return [\n ...(k.replyDrafts.length ? [plural(k.replyDrafts.length, 'reply draft', 'reply drafts')] : []),\n ...(k.notes.length ? [plural(k.notes.length, 'note for its Claude', 'notes for its Claude')] : []),\n ...(k.askingYou ? ['its question to you'] : []),\n ].join(', ');\n}\n\n/** Ask for the written summary and store it in the record (background, after archiving). */\nexport async function writeArchiveSummary(\n id: string,\n summarize: (rec: ArchiveRecord) => Promise<string | null>,\n root = archiveRoot(),\n): Promise<string | null> {\n const rec = readArchive(id, root);\n if (!rec || rec.summary.written) return rec?.summary.written ?? null;\n const text = (await summarize(rec))?.trim() || null;\n if (!text) return null;\n const now = readArchive(id, root); // re-read: it may have changed meanwhile\n if (!now) return null;\n now.summary.written = text;\n writeArchiveRecord(now, root);\n return text;\n}\n\nexport function writeArchiveRecord(rec: ArchiveRecord, root = archiveRoot()): void {\n const file = path.join(archiveDirFor(rec.sessionId, root), 'archive.json');\n const tmp = `${file}.tmp-${process.pid}`;\n fs.writeFileSync(tmp, JSON.stringify(rec, null, 2));\n fs.renameSync(tmp, file);\n}\n\n/** An archived transcript's text, compressed or not (null: gone). */\nexport function readArchivedTranscript(id: string, file: string, root = archiveRoot()): string | null {\n const plain = path.join(archiveDirFor(id, root), 'transcripts', file);\n try {\n return fs.readFileSync(plain, 'utf8');\n } catch {\n /* compressed, or gone */\n }\n try {\n return zlib.gunzipSync(fs.readFileSync(`${plain}.gz`)).toString('utf8');\n } catch {\n return null;\n }\n}\n\n/** The archive record, or null (never archived with a copy, or unreadable). */\nexport function readArchive(id: string, root = archiveRoot()): ArchiveRecord | null {\n try {\n const raw: unknown = JSON.parse(fs.readFileSync(path.join(archiveDirFor(id, root), 'archive.json'), 'utf8'));\n return isArchiveRecord(raw) ? withValidSaves(raw) : null;\n } catch {\n return null;\n }\n}\n\nfunction isSavedIgnored(v: unknown): v is SavedIgnored {\n if (!v || typeof v !== 'object') return false;\n const o = v as Record<string, unknown>;\n return typeof o.files === 'number' && typeof o.bytes === 'number' && typeof o.skipped === 'number';\n}\n\n/** Saved work comes back only in its known shape (stored JSON); anything else is dropped from the record read. */\nfunction withValidSaves(r: ArchiveRecord): ArchiveRecord {\n const out = { ...r };\n if (r.uncommitted !== undefined) {\n const valid =\n typeof r.uncommitted === 'object' && r.uncommitted ? Object.entries(r.uncommitted).filter(([, v]) => isSavedUncommitted(v)) : [];\n if (valid.length) out.uncommitted = Object.fromEntries(valid);\n else delete out.uncommitted;\n }\n if (r.unrestored !== undefined) {\n const valid = Array.isArray(r.unrestored) ? r.unrestored.filter(isSavedUncommitted) : [];\n if (valid.length) out.unrestored = valid;\n else delete out.unrestored;\n }\n if (r.ignored !== undefined) {\n const valid = typeof r.ignored === 'object' && r.ignored ? Object.entries(r.ignored).filter(([, v]) => isSavedIgnored(v)) : [];\n if (valid.length) out.ignored = Object.fromEntries(valid);\n else delete out.ignored;\n }\n return out;\n}\n\nfunction isArchiveRecord(x: unknown): x is ArchiveRecord {\n const r = x as ArchiveRecord | null;\n return (\n !!r &&\n typeof r === 'object' &&\n typeof r.sessionId === 'string' &&\n typeof r.worktreeRemoved === 'boolean' &&\n Array.isArray(r.transcripts) &&\n !!r.summary &&\n Array.isArray(r.summary.prompts)\n );\n}\n\n/**\n * Put an archived conversation back where Claude looks for it (the project\n * folder of the session's worktree), so `--continue` picks it up. Files that\n * are already there are left alone. Returns how many were restored.\n */\nexport function restoreArchivedTranscripts(\n s: WorktreeSession,\n root = archiveRoot(),\n /** Where its agent looks for them (agents/: `conversation.restoreDir`; none: it starts fresh, the archive keeps them). */\n restoreDir: (s: WorktreeSession) => string | null = (x) => agentOf(x).conversation?.restoreDir?.(x) ?? null,\n): number {\n const id = sessionIdFor(s);\n const rec = readArchive(id, root);\n if (!rec) return 0;\n const dest = restoreDir(s);\n if (!dest) return 0;\n let n = 0;\n for (const t of rec.transcripts) {\n const to = path.join(dest, t.file);\n if (fs.existsSync(to)) continue;\n const text = readArchivedTranscript(id, t.file, root);\n if (text === null) continue;\n fs.mkdirSync(dest, { recursive: true });\n fs.writeFileSync(to, text);\n n++;\n }\n return n;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { runGitAsync, runGitSync, writeTempTreeAsync } from '../diff/git-tree-snapshot.js';\n\n/**\n * A worktree's uncommitted work, kept when archiving removes the worktree\n * and put back when the session is restored. Modified, deleted and new\n * (untracked, not git-ignored) files are snapshotted into a commit on top of\n * HEAD, the way checkpoints are (a temp index: the real one is untouched),\n * kept alive by a ref in the repo (`refs/work/archive/<session>/<repo>`,\n * shared by its worktrees, so it outlives this one), and written as a binary\n * patch into the archive folder — the copy Restore applies, readable by hand.\n * Git-ignored files aren't included (build output, local settings that\n * `copyFiles` copies again); staged and unstaged come back alike, unstaged.\n */\n\n/** A bigger patch isn't kept: the worktree stays instead (a stray dump file shouldn't land in ~/.work). */\nexport const MAX_SAVED_PATCH_BYTES = 50 * 1024 * 1024;\n\nexport interface SavedUncommitted {\n /** The snapshot commit (its parent is `base`). */\n commit: string;\n /** HEAD when it was saved. */\n base: string;\n ref: string;\n files: number;\n /** The patch's file name in the archive's `uncommitted/` folder. */\n patch: string;\n /** Put back by a Restore (then not again). */\n restoredAt?: string;\n /** A Restore that couldn't put it back: why (the ref and patch stay). */\n restoreError?: string;\n}\n\nexport type SaveResult = { clean: true } | { saved: SavedUncommitted } | { error: string };\n\nconst safeName = (s: string): string => s.replace(/[^A-Za-z0-9._-]/g, '_');\n/** Where a save is kept: per session, repo and archive time, so a later archive never overwrites one a Restore couldn't put back. */\nexport const archiveRefFor = (sessionId: string, repo: string, stamp: number): string =>\n `refs/work/archive/${safeName(sessionId)}/${safeName(repo)}/${stamp}`;\n/** Every save of a session lives under this (deleted with the session). */\nexport const archiveRefsPrefix = (sessionId: string): string => `refs/work/archive/${safeName(sessionId)}/`;\nexport const uncommittedDir = (archiveDir: string): string => path.join(archiveDir, 'uncommitted');\n\nconst COMMIT_ENV = {\n GIT_AUTHOR_NAME: 'work',\n GIT_AUTHOR_EMAIL: 'work@local',\n GIT_COMMITTER_NAME: 'work',\n GIT_COMMITTER_EMAIL: 'work@local',\n};\n\n/** Save `worktree`'s uncommitted work under `ref` and as `<archiveDir>/uncommitted/<patchName>.patch`. */\nexport async function saveUncommitted(\n worktree: string,\n repo: string,\n ref: string,\n archiveDir: string,\n patchName = repo,\n maxBytes = MAX_SAVED_PATCH_BYTES,\n): Promise<SaveResult> {\n const status = await runGitAsync(worktree, { args: ['status', '--porcelain', '--untracked-files=all'] });\n if (status.status !== 0) return { error: `git can't read ${repo}` };\n const files = status.stdout.split('\\n').filter((l) => l.trim()).length;\n if (files === 0) return { clean: true };\n\n const tree = await writeTempTreeAsync(worktree, { includeWorkingTree: true });\n if (!tree?.headSha) return { error: `git couldn't snapshot ${repo}` };\n const commit = await runGitAsync(worktree, {\n args: ['commit-tree', tree.treeSha, '-p', tree.headSha, '-m', 'work archive: uncommitted changes'],\n env: { ...process.env, ...COMMIT_ENV },\n });\n const sha = commit.stdout.trim();\n if (commit.status !== 0 || !sha) return { error: `git couldn't snapshot ${repo}` };\n\n const dir = uncommittedDir(archiveDir);\n fs.mkdirSync(dir, { recursive: true });\n const patch = `${safeName(patchName)}.patch`;\n const patchPath = path.join(dir, patch);\n const diff = await runGitAsync(worktree, {\n args: ['diff', '--binary', '--no-color', '--no-ext-diff', `--output=${patchPath}`, tree.headSha, sha],\n });\n const size = fs.existsSync(patchPath) ? fs.statSync(patchPath).size : 0;\n if (diff.status !== 0 || size === 0) {\n fs.rmSync(patchPath, { force: true });\n return { error: `git couldn't write ${repo}'s changes as a patch` };\n }\n if (size > maxBytes) {\n fs.rmSync(patchPath, { force: true });\n return { error: `${repo}'s uncommitted changes are too large to keep (${Math.round(size / 1024 / 1024)} MB)` };\n }\n const pinned = await runGitAsync(worktree, { args: ['update-ref', ref, sha] });\n if (pinned.status !== 0) {\n fs.rmSync(patchPath, { force: true });\n return { error: `git couldn't keep ${repo}'s changes (update-ref)` };\n }\n return { saved: { commit: sha, base: tree.headSha, ref, files, patch } };\n}\n\n/** Undo a save that wasn't needed after all (the worktree stayed): its ref and patch go. */\nexport async function dropSaved(repoRoot: string, saved: SavedUncommitted, archiveDir: string): Promise<void> {\n await runGitAsync(repoRoot, { args: ['update-ref', '-d', saved.ref] });\n fs.rmSync(path.join(uncommittedDir(archiveDir), saved.patch), { force: true });\n}\n\n/**\n * Put saved work back into a recreated worktree: the patch applied to the\n * working tree (nothing staged). Refuses rather than mixes: when the\n * worktree already has changes of its own, or the patch doesn't apply\n * (the branch moved on) — the ref and the patch stay for doing it by hand.\n * On success the ref goes (the patch stays in the archive).\n */\nexport async function restoreUncommitted(\n worktree: string,\n saved: SavedUncommitted,\n archiveDir: string,\n): Promise<{ ok: true } | { ok: false; error: string }> {\n const patchPath = path.join(uncommittedDir(archiveDir), saved.patch);\n const byHand = `the changes are kept in ${saved.ref} and ${patchPath}`;\n if (!fs.existsSync(patchPath)) return { ok: false, error: `its saved patch is missing (${patchPath})` };\n const status = await runGitAsync(worktree, { args: ['status', '--porcelain', '--untracked-files=all'] });\n if (status.status !== 0) return { ok: false, error: `git can't read the worktree; ${byHand}` };\n if (status.stdout.trim()) return { ok: false, error: `the worktree already has changes, so they weren't mixed in; ${byHand}` };\n const check = await runGitAsync(worktree, { args: ['apply', '--binary', '--check', patchPath] });\n if (check.status !== 0) return { ok: false, error: `they no longer apply (the branch moved on); ${byHand}` };\n const apply = await runGitAsync(worktree, { args: ['apply', '--binary', patchPath] });\n if (apply.status !== 0) return { ok: false, error: `git apply failed; ${byHand}` };\n await runGitAsync(worktree, { args: ['update-ref', '-d', saved.ref] });\n return { ok: true };\n}\n\n/** Delete every saved ref of a session in a repo (the session is deleted; its archive folder goes too). */\nexport function dropSessionSaves(repoRoot: string, sessionId: string): void {\n const refs = runGitSync(repoRoot, { args: ['for-each-ref', '--format=%(refname)', archiveRefsPrefix(sessionId)] });\n for (const ref of refs.stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean))\n runGitSync(repoRoot, { args: ['update-ref', '-d', ref] });\n}\n\n/** Shape guard for the archive record's `uncommitted` map (stored JSON). */\nexport function isSavedUncommitted(x: unknown): x is SavedUncommitted {\n const v = x as SavedUncommitted | null;\n return (\n !!v &&\n typeof v === 'object' &&\n typeof v.commit === 'string' &&\n typeof v.base === 'string' &&\n typeof v.ref === 'string' &&\n typeof v.patch === 'string' &&\n typeof v.files === 'number'\n );\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport spawn from '../platform/spawn.js';\n\nexport interface TempTreeResult {\n /** Tree sha written from the temp index. */\n treeSha: string;\n /** HEAD commit sha, or null when the repo has no commits yet. Callers that\n * build a commit from `treeSha` use this as the parent. */\n headSha: string | null;\n}\n\n/**\n * Build a git tree sha for a repo WITHOUT disturbing the real index, using a\n * throwaway `GIT_INDEX_FILE`. Shared by `checkpoint.ts` (which commits the\n * tree and pins it behind a ref) and `diff-pipeline.ts` (which diffs the tree\n * against a checkpoint commit) — both previously hand-rolled this same\n * read-tree / add / write-tree dance.\n *\n * cp .git/index <tmp> (when includeWorkingTree)\n * GIT_INDEX_FILE=<tmp> git read-tree HEAD (otherwise / on copy failure)\n * GIT_INDEX_FILE=<tmp> git add -A (when includeWorkingTree)\n * GIT_INDEX_FILE=<tmp> git write-tree → treeSha\n *\n * Why the copy: an index built by `read-tree` carries no stat cache, so the\n * following `add -A` has to re-hash EVERY file in the worktree — 3.3s on a\n * mid-size repo, paid on every checkpoint and every `to=working` range diff\n * (twice over for a two-repo group). Seeding from the real index inherits its\n * stat cache, so git only hashes what actually changed: same tree sha, ~0.2s.\n * `add -A` overwrites every entry from the worktree, so staged-but-uncommitted\n * state in the copied index can't leak into the tree — the one exception is a\n * force-added ignored file, which stays (it is staged content, so keeping it\n * is the better answer anyway). An index with assume-unchanged/skip-worktree\n * entries is NOT used as a seed (see `seedFromRealIndex`).\n *\n * With `includeWorkingTree` (default), `add -A` promotes every working-tree\n * change including untracked files (honoring `.gitignore`), so the tree is a\n * full snapshot of the working tree. Without it, the tree is HEAD's tree\n * verbatim (the empty tree on a repo with no commits) — used for the\n * \"Initial\" checkpoint baseline so a diff of Initial→working reproduces the\n * full uncommitted diff instead of hiding pre-existing changes.\n *\n * Returns null on any git failure (caller should skip this repo). The temp\n * index file is always unlinked.\n */\nexport function writeTempTree(repoRoot: string, opts: { includeWorkingTree?: boolean } = {}): TempTreeResult | null {\n const steps = tempTreeSteps(repoRoot, opts.includeWorkingTree ?? true);\n let next = steps.next();\n while (!next.done) next = steps.next(runGitSync(repoRoot, next.value));\n return next.value;\n}\n\n/**\n * writeTempTree without blocking the event loop — for checkpoints, which run\n * on every Claude turn of every session (a synchronous `git add -A` on a big\n * repo froze the server for seconds, once per finishing turn). One snapshot\n * per repo at a time: turns ending together queue rather than run several\n * `add -A` over the same tree at once.\n */\nexport function writeTempTreeAsync(repoRoot: string, opts: { includeWorkingTree?: boolean } = {}): Promise<TempTreeResult | null> {\n return inRepoQueue(repoRoot, async () => {\n const steps = tempTreeSteps(repoRoot, opts.includeWorkingTree ?? true);\n let next = steps.next();\n while (!next.done) next = steps.next(await runGitAsync(repoRoot, next.value));\n return next.value;\n });\n}\n\n/** One git command of the snapshot: its args, and the env it runs with. */\nexport interface GitStep {\n args: string[];\n env?: NodeJS.ProcessEnv;\n}\nexport interface GitResult {\n status: number | null;\n stdout: string;\n}\n\n/**\n * The snapshot's steps, once, for both drivers: yields each git command and\n * gets its result back; returns the tree. (fs work in between — copying the\n * index, removing the temp file — is quick and stays synchronous.)\n */\nfunction* tempTreeSteps(repoRoot: string, includeWorkingTree: boolean): Generator<GitStep, TempTreeResult | null, GitResult> {\n const tmpIndex = path.join(os.tmpdir(), `wd-tree-${process.pid}-${crypto.randomBytes(6).toString('hex')}.idx`);\n const env: NodeJS.ProcessEnv = { ...process.env, GIT_INDEX_FILE: tmpIndex };\n try {\n const headSha = ((yield { args: ['rev-parse', '--verify', 'HEAD'] }).stdout ?? '').trim() || null;\n\n // The working-tree snapshot only needs a starting point that `add -A`\n // will overwrite, so prefer the warm real index (its stat cache: git\n // re-hashes only what changed); HEAD's tree is the fallback. A HEAD-only\n // snapshot must read HEAD verbatim.\n let seeded = false;\n if (includeWorkingTree) {\n const out = (yield { args: ['rev-parse', '--git-path', 'index'] }).stdout;\n if (seedIndexCopy(repoRoot, out, tmpIndex)) {\n // assume-unchanged / skip-worktree bits ride along in the copy, and\n // `add -A` trusts them and never re-reads those files — an edit to a\n // locally-tweaked config would silently vanish from the snapshot. The\n // read-tree index has no such bits, so fall back to it when any exist.\n // `ls-files -v` tags assume-unchanged with a lowercase letter and\n // skip-worktree with S.\n const listed = yield { args: ['ls-files', '-v'], env };\n const flagged =\n listed.status !== 0 ||\n (listed.stdout ?? '').split('\\n').some((line) => {\n const tag = line.charAt(0);\n return tag === 'S' || (tag >= 'a' && tag <= 'z');\n });\n if (flagged) removeQuietly(tmpIndex);\n else seeded = true;\n }\n }\n if (!seeded && headSha) {\n if ((yield { args: ['read-tree', 'HEAD'], env }).status !== 0) return null;\n }\n if (includeWorkingTree) {\n // `-A` against a temp index seeded from HEAD (or empty) captures the\n // full working-tree state, subject to .gitignore.\n if ((yield { args: ['add', '-A'], env }).status !== 0) return null;\n }\n const wt = yield { args: ['write-tree'], env };\n if (wt.status !== 0 || !wt.stdout) return null;\n return { treeSha: wt.stdout.trim(), headSha };\n } finally {\n removeQuietly(tmpIndex);\n }\n}\n\n/** Copy the repo's real index (`git rev-parse --git-path index` output,\n * relative to the repo root in a linked worktree) to `tmpIndex`, keeping\n * its mtime. False when there's nothing to copy (fresh repo). */\nfunction seedIndexCopy(repoRoot: string, gitPathOut: string, tmpIndex: string): boolean {\n try {\n if (!gitPathOut) return false;\n const realIndex = path.resolve(repoRoot, gitPathOut.trim());\n if (!fs.existsSync(realIndex)) return false;\n fs.copyFileSync(realIndex, tmpIndex);\n // Carry the real index's mtime over. Git re-hashes \"racily clean\"\n // entries — file mtime >= the index file's own mtime — rather than\n // trusting their cached stat. A copy stamped \"now\" would make those\n // entries look safely clean, and a same-size edit landing in the same\n // timestamp tick as an index refresh would be missed. copyFileSync\n // preserves times on Windows (CopyFileW) but not on Linux/macOS.\n const st = fs.statSync(realIndex);\n fs.utimesSync(tmpIndex, st.atime, st.mtime);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction removeQuietly(file: string): void {\n try {\n if (fs.existsSync(file)) fs.unlinkSync(file);\n } catch {\n // Temp-file leftover isn't fatal — the OS cleans it eventually.\n }\n}\n\nconst GIT_MAX_BUFFER = 64 * 1024 * 1024;\n\nexport function runGitSync(cwd: string, step: GitStep): GitResult {\n const r = spawn.sync('git', step.args, {\n cwd,\n encoding: 'utf-8',\n env: step.env ?? process.env,\n windowsHide: true,\n maxBuffer: GIT_MAX_BUFFER,\n });\n return { status: r.status, stdout: r.stdout ?? '' };\n}\n\n/** A git command off the event loop (argv only, no shell). */\nexport function runGitAsync(cwd: string, step: GitStep): Promise<GitResult> {\n return new Promise((resolve) => {\n let stdout = '';\n let size = 0;\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn('git', step.args, { cwd, env: step.env ?? process.env, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });\n } catch {\n resolve({ status: null, stdout: '' });\n return;\n }\n child.stdout?.setEncoding('utf-8');\n child.stdout?.on('data', (d: string) => {\n size += d.length;\n if (size <= GIT_MAX_BUFFER) stdout += d;\n });\n child.on('error', () => resolve({ status: null, stdout: '' }));\n child.on('close', (code) => resolve({ status: code, stdout }));\n });\n}\n\nconst repoQueues = new Map<string, Promise<unknown>>();\n\n/** Run `fn` after whatever is queued for this repo; the queue empties itself. */\nexport function inRepoQueue<T>(repoRoot: string, fn: () => Promise<T>): Promise<T> {\n const key = path.resolve(repoRoot).toLowerCase();\n const prev = repoQueues.get(key) ?? Promise.resolve();\n const run = prev.then(fn, fn);\n const tail = run.catch(() => {});\n repoQueues.set(key, tail);\n void tail.then(() => {\n if (repoQueues.get(key) === tail) repoQueues.delete(key);\n });\n return run;\n}\n","/**\n * Sessions being archived right now (archiveSession, from its first step to\n * its last). Nothing may start their Claude meanwhile: archiving stops it\n * first, and a Terminal tab still open on the session would otherwise start\n * it again a moment later — an archived session with a live Claude, put back\n * by the PTY host after every restart. ensurePty refuses them, and archived\n * ones (pty-pool.ts).\n *\n * In memory, per process: archiving runs in work web, which is also what\n * starts session Claudes.\n */\n\nconst inProgress = new Set<string>();\n\nexport function isArchiving(sessionId: string): boolean {\n return inProgress.has(sessionId);\n}\n\n/** Run `fn` with the session marked as being archived. */\nexport async function whileArchiving<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {\n inProgress.add(sessionId);\n try {\n return await fn();\n } finally {\n inProgress.delete(sessionId);\n }\n}\n\n/** Why a session's Claude can't be started now, or null. */\nexport function noClaudeBecause(session: { archivedAt?: string | null } | null, sessionId: string): string | null {\n if (isArchiving(sessionId)) return 'This session is being archived.';\n if (session?.archivedAt) return 'This session is archived. Restore it to continue the conversation.';\n return null;\n}\n","import type { ConversationEntry } from '../agents/types.js';\nimport { dayKey } from './work-time-view.js';\n\n/**\n * How long a session's Claude worked, from its transcripts — for a worklog,\n * or to see where the time went. Approximate by design: the time between\n * two transcript lines counts when the later one is Claude's own (its reply,\n * a tool's result), each gap at most STEP_CAP_MS — so your time reading and\n * typing isn't counted, and a permission prompt left an hour isn't an hour of\n * work. Pure: entries in, steps out.\n */\n\n/** The most one step counts for (a long test run still counts; a prompt waiting all afternoon doesn't). */\nexport const STEP_CAP_MS = 15 * 60_000;\n\n/** One step of Claude's: when it ended (ms) and how long it counted for. */\nexport type WorkStep = readonly [endMs: number, ms: number];\n\n/** The agent's own line: its message or tool call, or a tool's result coming back to it.\n * A subagent's lines count too (unlike the digest's prompts): its work is\n * the agent's work, and the steps of one file never overlap, so nothing is\n * counted twice. */\nfunction isAgents(e: ConversationEntry): boolean {\n return e.role === 'agent' || e.role === 'tool' || e.role === 'tool-result';\n}\n\n/**\n * The steps in `entries` (in file order), continuing from `prevMs` — the\n * time of the line before them, when they continue a file already read.\n * Returns the steps and the time of the last line, to continue from.\n */\nexport function workSteps(\n entries: readonly ConversationEntry[],\n prevMs: number | null = null,\n): { steps: WorkStep[]; lastMs: number | null } {\n const steps: WorkStep[] = [];\n let prev = prevMs;\n for (const e of entries) {\n const ts = Date.parse(e.at);\n if (!Number.isFinite(ts)) continue;\n if (prev !== null && isAgents(e)) {\n const gap = ts - prev;\n if (gap > 0) steps.push([ts, Math.min(gap, STEP_CAP_MS)]);\n }\n // Lines can arrive a little out of order (a subagent's): never step back.\n prev = prev === null ? ts : Math.max(prev, ts);\n }\n return { steps, lastMs: prev };\n}\n\n/**\n * Steps from several transcripts of one session (two Claudes on one folder\n * at once, a conversation resumed beside another) as one timeline: time\n * covered by both counts once. Pure.\n */\nexport function mergeSteps(steps: readonly WorkStep[]): WorkStep[] {\n const spans = steps.map(([end, ms]) => [end - ms, end] as [number, number]).sort((a, b) => a[0] - b[0]);\n const out: WorkStep[] = [];\n let cur: [number, number] | null = null;\n for (const [start, end] of spans) {\n if (cur && start <= cur[1]) cur[1] = Math.max(cur[1], end);\n else {\n if (cur) out.push([cur[1], cur[1] - cur[0]]);\n cur = [start, end];\n }\n }\n if (cur) out.push([cur[1], cur[1] - cur[0]]);\n return out;\n}\n\n/** Time worked in steps ending at or after `sinceMs` (and before `untilMs`). */\nexport function workedBetween(steps: readonly WorkStep[], sinceMs = 0, untilMs = Infinity): number {\n let ms = 0;\n for (const [end, d] of steps) if (end >= sinceMs && end < untilMs) ms += d;\n return ms;\n}\n\n/** Time worked per local day (`YYYY-MM-DD`), newest first, for the days after `sinceMs`. */\nexport function workedByDay(steps: readonly WorkStep[], sinceMs = 0): Array<{ day: string; ms: number }> {\n const by = new Map<string, number>();\n for (const [end, d] of steps) {\n if (end < sinceMs) continue;\n const k = dayKey(end);\n by.set(k, (by.get(k) ?? 0) + d);\n }\n return [...by].map(([day, ms]) => ({ day, ms })).sort((a, b) => b.day.localeCompare(a.day));\n}\n","import type { ConversationEntry } from '../agents/types.js';\nimport { workedBetween, type WorkStep } from './work-time.js';\nimport type { DiffStat, DigestSession, SessionCi } from '../api-types.js';\n\n/**\n * \"What did each session do today?\" — for a standup, or for coming back\n * after a weekend. Built from what's already on disk: the prompts you gave\n * (the transcripts), the turns it finished (checkpoints, named when a name\n * was already made — the digest never runs Claude), where it stands now,\n * its diff and its PRs. The assembly is pure; web-server.ts feeds it.\n */\n\nexport const MAX_PROMPTS = 12;\nconst MAX_PROMPT_CHARS = 240;\n\n/** What `checkpoint-summary.ts` names a turn when Claude was unavailable:\n * \"3 files · +52 −8\" or \"no changes\". A size, not what the turn did. */\nexport const HEURISTIC_LABEL_RE = /^(\\d+ files? · \\+\\d+ −\\d+|no changes)$/;\n\n/** One line of at most MAX_PROMPT_CHARS. */\nfunction clip(text: string): string {\n const line = text.replace(/\\s+/g, ' ').trim();\n return line.length > MAX_PROMPT_CHARS ? line.slice(0, MAX_PROMPT_CHARS - 1).trimEnd() + '…' : line;\n}\n\n/**\n * Of a conversation's entries, only what the digest reads — your prompts.\n * A day's conversations hold tool output too (megabytes per session); the\n * digest kept all of it in memory for every session in the window, for the\n * sake of a few lines.\n */\nexport function promptEntries(entries: readonly ConversationEntry[]): ConversationEntry[] {\n return entries.filter((e) => e.role === 'you' && !e.sidechain && e.text !== '');\n}\n\n/** Your prompts after `sinceMs`, oldest first. The same entry seen twice\n * (by its id, else time + text) counts once; typing \"commit\" three times\n * is three prompts. */\nexport function promptsSince(transcripts: readonly (readonly ConversationEntry[])[], sinceMs: number): Array<{ ts: string; text: string }> {\n const out: Array<{ ts: string; text: string }> = [];\n const seen = new Set<string>();\n for (const entries of transcripts) {\n for (const e of entries) {\n const ts = Date.parse(e.at);\n if (!(ts >= sinceMs)) continue;\n if (e.role !== 'you' || e.sidechain || !e.text) continue;\n const line = clip(e.text);\n const key = e.id ? e.id : `${ts}|${line}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push({ ts: new Date(ts).toISOString(), text: line });\n }\n }\n return out.sort((a, b) => a.ts.localeCompare(b.ts));\n}\n\nexport interface DigestInput {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n lastAccessedAt: string;\n archivedAt: string | null;\n status: { state: 'working' | 'needs_input' | 'idle'; summary?: string; updatedAt: string } | null;\n /** Entries of the transcripts written to since the window opened. */\n transcripts: ConversationEntry[][];\n /** A transcript was too large to read back to the window's start. */\n transcriptsPartial?: boolean;\n /** Claude's work steps in those transcripts (work-time.ts). */\n work?: WorkStep[][];\n /** The session scope's checkpoints (id 0 is the baseline, not a turn). */\n checkpoints: Array<{ id: number; ts: string; label?: string }>;\n diffStat: DiffStat | null;\n ci: SessionCi | null;\n}\n\n/** One digest row, or null when the session did nothing in the window. */\nexport function digestSession(s: DigestInput, sinceMs: number): DigestSession | null {\n const prompts = promptsSince(s.transcripts, sinceMs);\n const turns = s.checkpoints.filter((c) => c.id > 0 && Date.parse(c.ts) >= sinceMs);\n const archivedInWindow = !!s.archivedAt && Date.parse(s.archivedAt) >= sinceMs;\n const prs = (s.ci?.repos ?? [])\n .filter((r) => r.pr)\n .map((r) => ({\n repo: r.name,\n number: r.pr!.number,\n url: r.pr!.url,\n state: r.pr!.state,\n ...(r.pr!.mergedAt ? { mergedAt: r.pr!.mergedAt } : {}),\n }));\n const mergedInWindow = prs.some((p) => p.mergedAt && Date.parse(p.mergedAt) >= sinceMs);\n if (prompts.length === 0 && turns.length === 0 && !archivedInWindow && !mergedInWindow) return null;\n\n const times = [\n ...prompts.map((p) => Date.parse(p.ts)),\n ...turns.map((t) => Date.parse(t.ts)),\n ...prs.map((p) => (p.mergedAt && Date.parse(p.mergedAt) >= sinceMs ? Date.parse(p.mergedAt) : 0)),\n archivedInWindow ? Date.parse(s.archivedAt!) : 0,\n s.status ? Date.parse(s.status.updatedAt) || 0 : 0,\n ];\n return {\n sessionId: s.sessionId,\n target: s.target,\n branch: s.branch,\n isGroup: s.isGroup,\n state: s.status?.state ?? null,\n ...(s.status?.summary ? { summary: s.status.summary } : {}),\n prompts: prompts.slice(-MAX_PROMPTS),\n morePrompts: Math.max(0, prompts.length - MAX_PROMPTS),\n turns: turns.length,\n turnLabels: turns.map((t) => t.label?.trim()).filter((l): l is string => !!l && l !== 'Initial' && !HEURISTIC_LABEL_RE.test(l)),\n ...(s.transcriptsPartial ? { partial: true } : {}),\n diffStat: s.diffStat,\n prs,\n archivedAt: s.archivedAt,\n lastActivity: new Date(Math.max(...times)).toISOString(),\n ...(() => {\n const ms = (s.work ?? []).reduce((n, steps) => n + workedBetween(steps, sinceMs), 0);\n return ms > 0 ? { workedMs: ms } : {};\n })(),\n };\n}\n\n/** Rows for every session that did something, most recent first. */\nexport function buildDigest(inputs: DigestInput[], sinceMs: number): DigestSession[] {\n return inputs\n .map((s) => digestSession(s, sinceMs))\n .filter((d): d is DigestSession => d !== null)\n .sort((a, b) => b.lastActivity.localeCompare(a.lastActivity));\n}\n","import type { ConversationEntry } from '../agents/types.js';\n\n/**\n * Matching a query in a conversation: every word of the query must appear\n * in one message (yours or its agent's). Used by the conversation search\n * (conversation-store.ts) over kept and archived conversations; the lines\n * are read through the session's agent (agents/: `entries`).\n */\n\nconst SNIPPET_CHARS = 220;\n\n/** A readable message: your prompt, or the agent's text — not tool calls, results, a subagent's lines or tagged echoes. */\nexport function messageOf(e: ConversationEntry): { role: 'you' | 'claude'; text: string } | null {\n if (e.sidechain || (e.role !== 'you' && e.role !== 'agent')) return null;\n const text = e.text.trim();\n if (!text || text.startsWith('<')) return null; // tagged command echoes, reminders\n return { role: e.role === 'you' ? 'you' : 'claude', text };\n}\n\n/** The part of `text` around the first query word, one line. */\nexport function snippet(text: string, words: string[]): string {\n const flat = text.replace(/\\s+/g, ' ');\n const lower = flat.toLowerCase();\n const at = Math.max(0, lower.indexOf(words[0]));\n const start = Math.max(0, at - 60);\n const cut = flat.slice(start, start + SNIPPET_CHARS);\n return (start > 0 ? '…' : '') + cut + (start + SNIPPET_CHARS < flat.length ? '…' : '');\n}\n\n/** A query's words, lower case, and as JSON writes them (`\\` and `\"` escaped) for the raw-line pre-filter. */\nexport function queryWords(query: string): { words: string[]; jsonWords: string[] } {\n const words = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((w) => w.length > 0);\n return { words, jsonWords: words.map((w) => JSON.stringify(w).slice(1, -1)) };\n}\n\n/** Up to `max` messages of a transcript's text in which every word appears (yours or Claude's). */\nexport function matchingLines(\n raw: string,\n words: string[],\n jsonWords: string[],\n max: number,\n entries: (lines: readonly unknown[]) => ConversationEntry[],\n): Array<{ role: 'you' | 'claude'; text: string; at: string | null }> {\n const out: Array<{ role: 'you' | 'claude'; text: string; at: string | null }> = [];\n if (max <= 0) return out;\n for (const line of raw.split('\\n')) {\n if (out.length >= max) break;\n if (!line) continue;\n const lower = line.toLowerCase();\n if (!jsonWords.every((w) => lower.includes(w))) continue; // cheap pre-filter on the raw JSON line\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n continue;\n }\n for (const e of entries([parsed])) {\n const m = messageOf(e);\n if (!m || !words.every((w) => m.text.toLowerCase().includes(w))) continue;\n out.push({ role: m.role, text: snippet(m.text, words), at: e.at || null });\n break; // one hit per line\n }\n }\n return out;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { WorkConfig } from '../platform/config.js';\nimport { getConfigDir, loadConfig } from '../platform/config.js';\nimport { agentToRecord } from '../agents/index.js';\n\n/** The agent a new session records: the configured one when work has an adapter for it (agents/). */\nconst recordAgent = (): { agent?: string } => {\n const agent = agentToRecord(loadConfig());\n return agent ? { agent } : {};\n};\nimport { json, purgeSessionRows, tx, withDb, type Db } from '../platform/db.js';\nimport { sessionIdFor } from './session-id.js';\nimport { effectiveLastAccessedAt } from './session-activity.js';\nimport { allocateFreePort } from '../worktree/port-allocator.js';\nimport { removeSessionFiles, stopSessionDevServer, clearSessionCheckpoints } from './session-store.js';\n\nexport type { WorktreeSession } from './session-types.js';\nimport type { WorktreeSession } from './session-types.js';\n\n/**\n * Worktree sessions, in the `sessions` table of ~/.work/state.db (db.ts):\n * one row per target:branch, the record as JSON. Writes are transactions,\n * so concurrent `work tree` / `remove` / work web can't clobber each other\n * (the old history.json needed a file lock for that — and once lost 60+\n * sessions without it).\n */\n\n/** The pre-SQLite history file. Only the one-time import (db-import.ts)\n * reads it now. */\nexport function getHistoryPath(): string {\n return path.join(getConfigDir(), 'history.json');\n}\n\nfunction valid(s: unknown): s is WorktreeSession {\n const x = s as WorktreeSession | null;\n return !!x && typeof x.target === 'string' && typeof x.branch === 'string' && Array.isArray(x.paths);\n}\n\nfunction rows(d: Db): WorktreeSession[] {\n return (d.prepare('SELECT data FROM sessions ORDER BY rowid').all() as Array<{ data: string }>)\n .map((r) => json.parse(r.data))\n .filter(valid);\n}\n\nfunction getRow(d: Db, target: string, branch: string): WorktreeSession | undefined {\n const r = d.prepare('SELECT data FROM sessions WHERE id = ?').get(sessionIdFor({ target, branch })) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return valid(s) ? s : undefined;\n}\n\nfunction putRow(d: Db, s: WorktreeSession): void {\n d.prepare(\n 'INSERT INTO sessions (id, target, branch, data) VALUES (?, ?, ?, ?) ' + 'ON CONFLICT(id) DO UPDATE SET data = excluded.data',\n ).run(sessionIdFor(s), s.target, s.branch, JSON.stringify(s));\n}\n\n/** One session by its id (the `sessions` primary key). */\nexport function findSessionById(id: string): WorktreeSession | null {\n return withDb((d) => {\n const r = d.prepare('SELECT data FROM sessions WHERE id = ?').get(id) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return valid(s) ? s : null;\n });\n}\n\n/** Every session, in the order they were first recorded. */\nexport function loadHistory(): WorktreeSession[] {\n return withDb(rows);\n}\n\n/** Replace the whole history (bulk rewrites, tests). */\nexport function saveHistory(sessions: WorktreeSession[]): void {\n tx((d) => {\n d.prepare('DELETE FROM sessions').run();\n const seen = new Set<string>();\n for (const s of sessions) {\n if (!valid(s)) continue;\n const id = sessionIdFor(s);\n if (seen.has(id)) continue; // first entry wins, as findSession does\n seen.add(id);\n putRow(d, s);\n }\n });\n}\n\nfunction sessionKey(target: string, branch: string): string {\n return `${target}:${branch}`;\n}\n\nexport function findSession(sessions: WorktreeSession[], target: string, branch: string): WorktreeSession | undefined {\n return sessions.find((s) => s.target === target && s.branch === branch);\n}\n\nexport async function upsertSession(\n target: string,\n isGroup: boolean,\n branch: string,\n paths: string[],\n jiraKey?: string,\n baseBranch?: string,\n port?: number,\n): Promise<void> {\n tx((d) => {\n const existing = getRow(d, target, branch);\n const now = new Date().toISOString();\n\n if (existing) {\n existing.paths = paths;\n existing.lastAccessedAt = now;\n delete existing.archivedAt; // coming back to it un-archives it\n if (jiraKey) existing.jiraKey = jiraKey;\n if (baseBranch && !existing.baseBranch) existing.baseBranch = baseBranch;\n if (port !== undefined) existing.port = port;\n putRow(d, existing);\n } else {\n const session: WorktreeSession = {\n target,\n isGroup,\n branch,\n paths,\n createdAt: now,\n lastAccessedAt: now,\n ...recordAgent(),\n };\n if (jiraKey) session.jiraKey = jiraKey;\n if (baseBranch) session.baseBranch = baseBranch;\n if (port !== undefined) session.port = port;\n putRow(d, session);\n }\n });\n}\n\n/**\n * Allocate a stable dev-server port AND persist the session, without two\n * concurrent `work tree` runs picking the same port.\n *\n * Allocation probes ports (async) and a transaction can't span an await,\n * so it is optimistic: pick a port against a snapshot, then in one write\n * transaction re-check that no other live session took it meanwhile — and\n * if one did, pick again.\n *\n * Port allocation is best-effort: if it fails (range exhausted, etc.) the\n * session is still persisted, just without a port, and `port` comes back\n * undefined. An already-allocated port on an existing session is preserved\n * (idempotent re-runs keep their port).\n *\n * The allocation seed is `target:branch` (unique per worktree) so two repos\n * that share a branch name don't collide on the same deterministic base offset.\n */\nexport async function upsertSessionWithPort(\n target: string,\n isGroup: boolean,\n branch: string,\n paths: string[],\n config: Pick<WorkConfig, 'portRange'>,\n jiraKey?: string,\n baseBranch?: string,\n baseBranches?: Record<string, string>,\n): Promise<{ port?: number }> {\n const hasPerRepo = baseBranches && Object.keys(baseBranches).length > 0;\n const id = sessionIdFor({ target, branch });\n\n const write = (d: Db, port: number | undefined): number | undefined => {\n const existing = getRow(d, target, branch);\n const now = new Date().toISOString();\n if (existing) {\n existing.paths = paths;\n existing.lastAccessedAt = now;\n delete existing.archivedAt; // coming back to it un-archives it\n if (jiraKey) existing.jiraKey = jiraKey;\n if (baseBranch && !existing.baseBranch) existing.baseBranch = baseBranch;\n if (hasPerRepo && !existing.baseBranches) existing.baseBranches = baseBranches;\n if (existing.port === undefined && port !== undefined) existing.port = port;\n putRow(d, existing);\n return existing.port;\n }\n const session: WorktreeSession = { target, isGroup, branch, paths, createdAt: now, lastAccessedAt: now, ...recordAgent() };\n if (jiraKey) session.jiraKey = jiraKey;\n if (baseBranch) session.baseBranch = baseBranch;\n if (hasPerRepo) session.baseBranches = baseBranches;\n if (port !== undefined) session.port = port;\n putRow(d, session);\n return port;\n };\n\n for (let attempt = 0; attempt < 5; attempt++) {\n const sessions = loadHistory();\n const existing = findSession(sessions, target, branch);\n let port = existing?.port;\n if (port === undefined) {\n try {\n port = await allocateFreePort(sessionKey(target, branch), config, sessions);\n } catch {\n port = undefined;\n }\n }\n const done = tx((d) => {\n // Another `work tree` may have taken this port since the snapshot:\n // only a port no other live session holds may be kept.\n if (port !== undefined && getRow(d, target, branch)?.port === undefined) {\n const taken = rows(d).some((s) => sessionIdFor(s) !== id && s.port === port && s.paths.some((p) => fs.existsSync(p)));\n if (taken) return null;\n }\n return { port: write(d, port) };\n });\n if (done) return done;\n }\n // Could not get an uncontested port: record the session without one.\n return tx((d) => ({ port: write(d, undefined) }));\n}\n\n/** Record how the AI tool was just launched for this session. */\nexport function recordLaunch(target: string, branch: string, opts: { unsafe: boolean }): void {\n tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return;\n if (opts.unsafe) s.launchedUnsafe = true;\n else delete s.launchedUnsafe;\n putRow(d, s);\n });\n}\n\n/** Archive / un-archive a session. Returns false when it doesn't exist. */\nexport async function setSessionArchived(target: string, branch: string, archived: boolean): Promise<boolean> {\n return tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return false;\n if (archived) s.archivedAt = new Date().toISOString();\n else delete s.archivedAt;\n putRow(d, s);\n return true;\n });\n}\n\n/** Name a session (an empty title goes back to the automatic name). */\nexport async function setSessionTitle(target: string, branch: string, title: string): Promise<boolean> {\n return tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return false;\n const t = title.trim().slice(0, 120);\n if (t) s.title = t;\n else delete s.title;\n putRow(d, s);\n return true;\n });\n}\n\n/**\n * Record the branches it is now based on (a stacked session moved onto\n * main): by checkout path. One name for every repo is `baseBranch` alone;\n * repos with different mainlines (main and master) keep `baseBranches` too.\n */\nexport async function setSessionBase(target: string, branch: string, bases: Record<string, string>): Promise<boolean> {\n const names = [...new Set(Object.values(bases))];\n if (names.length === 0) return false;\n return tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return false;\n s.baseBranch = names[0];\n if (names.length === 1) delete s.baseBranches;\n else s.baseBranches = { ...bases };\n putRow(d, s);\n return true;\n });\n}\n\nexport async function removeSession(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch });\n if (!withDb((d) => getRow(d, target, branch))) return; // nothing to remove: touch nothing\n const session = findSession(loadHistory(), target, branch);\n // The session's other state (status, comments, saved PTY entry, …) goes\n // with it — in the SAME transaction, so a crash can't leave state behind\n // for a re-created session to inherit (see session-store.ts).\n stopSessionDevServer(id);\n const removed = tx((d) => {\n const gone = d.prepare('DELETE FROM sessions WHERE id = ?').run(id).changes > 0;\n if (gone) purgeSessionRows(d, id);\n return gone;\n });\n if (removed) {\n removeSessionFiles(id);\n if (session) clearSessionCheckpoints(session);\n }\n}\n\nexport function getSessionsForTarget(sessions: WorktreeSession[], target: string): WorktreeSession[] {\n return sessions.filter((s) => s.target === target);\n}\n\nexport function getRecentSessions(sessions: WorktreeSession[], count: number): WorktreeSession[] {\n return [...sessions]\n .sort((a, b) => new Date(effectiveLastAccessedAt(b)).getTime() - new Date(effectiveLastAccessedAt(a)).getTime())\n .slice(0, count);\n}\n\nexport function pruneStaleEntries(sessions: WorktreeSession[]): {\n kept: WorktreeSession[];\n pruned: number;\n} {\n const kept: WorktreeSession[] = [];\n let pruned = 0;\n\n for (const session of sessions) {\n const anyPathExists = session.paths.some((p) => fs.existsSync(p));\n if (anyPathExists) {\n kept.push(session);\n } else {\n pruned++;\n }\n }\n\n return { kept, pruned };\n}\n\n/** Persisted prune for `status --prune` callers. */\nexport async function prunePersistedStaleEntries(): Promise<{ pruned: number }> {\n const stale = pruneStaleEntries(loadHistory()).kept;\n const keep = new Set(stale.map((s) => sessionIdFor(s)));\n for (const s of loadHistory()) if (!keep.has(sessionIdFor(s))) stopSessionDevServer(sessionIdFor(s));\n const gone = tx((d) => {\n const drop = rows(d).filter((s) => !keep.has(sessionIdFor(s)));\n const del = d.prepare('DELETE FROM sessions WHERE id = ?');\n for (const s of drop) {\n del.run(sessionIdFor(s));\n purgeSessionRows(d, sessionIdFor(s));\n }\n return drop;\n });\n for (const s of gone) removeSessionFiles(sessionIdFor(s));\n return { pruned: gone.length };\n}\n\n/**\n * Merge hydrated sessions into history without clobbering existing entries.\n * For each incoming session: if a matching target+branch exists, refresh its\n * paths (if different) but keep original timestamps. Otherwise insert.\n */\nexport async function mergeHydratedSessions(incoming: WorktreeSession[]): Promise<{ added: number; updated: number }> {\n return tx((d) => {\n let added = 0;\n let updated = 0;\n\n for (const inc of incoming) {\n const existing = getRow(d, inc.target, inc.branch);\n if (existing) {\n const sortedA = [...existing.paths].sort();\n const sortedB = [...inc.paths].sort();\n const same = sortedA.length === sortedB.length && sortedA.every((p, i) => p === sortedB[i]);\n if (!same) {\n existing.paths = inc.paths;\n putRow(d, existing);\n updated++;\n }\n } else {\n putRow(d, inc);\n added++;\n }\n }\n return { added, updated };\n });\n}\n\nconst samePath = (a: string, b: string) => {\n const n = (p: string) => path.resolve(p).split(path.sep).join('/').toLowerCase();\n return n(a) === n(b);\n};\n\n/**\n * A base checkout (`work tree <target>` with no branch) is recorded under the\n * branch it had checked out at the time. Run it again after switching that\n * checkout to another branch and a second entry appeared for the SAME folder\n * — then a third… — each showing the folder's activity as its own (three\n * \"Active\" rows for one busy checkout). Keep one: the entry just recorded.\n * Returns the branches of the entries removed.\n */\nexport async function forgetOtherBaseCheckoutEntries(target: string, keepBranch: string, repoPath: string): Promise<string[]> {\n const others = loadHistory().filter(\n (s) => s.target === target && !s.isGroup && s.branch !== keepBranch && s.paths.length === 1 && samePath(s.paths[0], repoPath),\n );\n for (const s of others) await removeSession(s.target, s.branch);\n return others.map((s) => s.branch);\n}\n","import fs from 'node:fs';\nimport net from 'node:net';\nimport type { WorkConfig } from '../platform/config.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\n\n/** Default dev-server port range when none is configured. */\nexport const DEFAULT_PORT_RANGE = { start: 3000, end: 3099 };\n\n/**\n * Thrown when every port in the configured range is occupied. Distinct class so\n * callers can tell \"range exhausted\" apart from any other allocation failure.\n */\nexport class PortRangeExhaustedError extends Error {\n readonly start: number;\n readonly end: number;\n constructor(start: number, end: number) {\n super(\n `No free dev-server port available in range ${start}-${end} ` +\n `(all ${end - start + 1} in use). Widen \"portRange\" in ~/.work/config.json.`,\n );\n this.name = 'PortRangeExhaustedError';\n this.start = start;\n this.end = end;\n }\n}\n\n/**\n * Deterministic, stable string hash (FNV-1a 32-bit). Same input always yields\n * the same non-negative integer, so a worktree's seed key maps to the same base\n * offset across processes and machines.\n */\nfunction hashString(input: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\nfunction normalizeRange(config: Pick<WorkConfig, 'portRange'>): {\n start: number;\n end: number;\n rangeSize: number;\n} {\n const range = config.portRange ?? DEFAULT_PORT_RANGE;\n const start = Math.min(range.start, range.end);\n const end = Math.max(range.start, range.end);\n const rangeSize = end - start + 1;\n if (rangeSize <= 0) {\n throw new Error(`Invalid port range: ${range.start}-${range.end}`);\n }\n return { start, end, rangeSize };\n}\n\nfunction portsHeldByActiveSessions(sessions: WorktreeSession[]): Set<number> {\n const inUse = new Set<number>();\n for (const session of sessions) {\n if (session.port === undefined) continue;\n const active = session.paths.some((p) => fs.existsSync(p));\n if (active) inUse.add(session.port);\n }\n return inUse;\n}\n\n/**\n * Allocate a stable dev-server port for a worktree.\n *\n * Pure and testable: the caller passes the current `sessions` array (e.g.\n * `loadHistory()`) rather than this function reading state itself.\n *\n * - The range comes from `config.portRange` (falling back to 3000–3099).\n * - A deterministic base offset is derived from `hash(seedKey) % rangeSize`,\n * so the same worktree prefers the same port. The seed key MUST be unique per\n * worktree (e.g. `target:branch` or the full worktree path) — using only a\n * branch name would let two repos sharing a branch collide deterministically.\n * - Ports already held by *active* sessions (at least one path still exists)\n * are considered in use and skipped.\n * - Walks forward from the base offset (wrapping around the range) to the first\n * free port. Throws `PortRangeExhaustedError` if every port is occupied.\n *\n * NOTE: this checks only our own history, not host liveness. Use\n * `allocateFreePort` when you also want to skip ports occupied by unrelated\n * processes on the machine.\n */\nexport function allocatePort(seedKey: string, config: Pick<WorkConfig, 'portRange'>, sessions: WorktreeSession[]): number {\n const { start, end, rangeSize } = normalizeRange(config);\n const inUse = portsHeldByActiveSessions(sessions);\n const baseOffset = hashString(seedKey) % rangeSize;\n\n for (let i = 0; i < rangeSize; i++) {\n const candidate = start + ((baseOffset + i) % rangeSize);\n if (!inUse.has(candidate)) {\n return candidate;\n }\n }\n\n throw new PortRangeExhaustedError(start, end);\n}\n\n/**\n * Probe whether a TCP port is free to bind on localhost. Resolves false on\n * EADDRINUSE (something is already listening), true otherwise. Best-effort: any\n * non-EADDRINUSE error resolves true so a quirky host can't block allocation.\n */\nexport function isPortFree(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once('error', (err: NodeJS.ErrnoException) => {\n resolve(err.code !== 'EADDRINUSE');\n });\n server.once('listening', () => {\n server.close(() => resolve(true));\n });\n server.listen(port, '127.0.0.1');\n });\n}\n\n/**\n * Like `allocatePort`, but additionally probes host liveness: candidates that\n * are already bound by some other process on localhost (EADDRINUSE) are skipped\n * even when our history doesn't know about them. This is what actually prevents\n * collisions with non-work processes.\n *\n * Walks the same deterministic order as `allocatePort` and returns the first\n * candidate that is both free in history and bindable on the host. Throws\n * `PortRangeExhaustedError` if every candidate is taken.\n */\nexport async function allocateFreePort(\n seedKey: string,\n config: Pick<WorkConfig, 'portRange'>,\n sessions: WorktreeSession[],\n probe: (port: number) => Promise<boolean> = isPortFree,\n): Promise<number> {\n const { start, end, rangeSize } = normalizeRange(config);\n const inUse = portsHeldByActiveSessions(sessions);\n const baseOffset = hashString(seedKey) % rangeSize;\n\n for (let i = 0; i < rangeSize; i++) {\n const candidate = start + ((baseOffset + i) % rangeSize);\n if (inUse.has(candidate)) continue;\n if (await probe(candidate)) {\n return candidate;\n }\n }\n\n throw new PortRangeExhaustedError(start, end);\n}\n","import fs from 'node:fs';\nimport { archiveDirFor } from '../archive/session-archive.js';\nimport { conversationDirFor } from '../conversations/conversation-store.js';\nimport { sessionIdFor } from './session-id.js';\nimport { purgeSessionRows, tx } from '../platform/db.js';\nimport { logSwallowed } from '../platform/best-effort.js';\nimport { devLogFile, stopDev } from '../worktree/dev-server.js';\nimport { clearCheckpoints } from '../diff/checkpoint.js';\nimport { dropSessionSaves } from '../archive/archive-uncommitted.js';\nimport { scopeHashForPaths } from '../diff/scope-manager.js';\nimport { loadConfig } from '../platform/config.js';\nimport type { WorktreeSession } from './session-types.js';\n\n/**\n * Owner of a session's state beyond its `sessions` row. Everything\n * per-session is keyed by sessionIdFor(target, branch) and lives in\n * state.db (db.ts):\n *\n * session_status attention status (hooks)\n * comments [store=id] review comments\n * comment_deliveries which comments reached Claude\n * pty_sessions restore-after-reboot entry\n * pr_watch_seen PR watch: comments / CI failures acted on\n * dev_runs dev server pid (the server is stopped first)\n *\n * plus one file, ~/.work/dev/<id>.log (the dev server's output).\n *\n * plus its diff scope's checkpoints: refs/wd/<hash>/* in its repos and the\n * manifest, keyed by the hash of its paths (clearSessionCheckpoints) — the\n * refs keep their commits (untracked files `add -A` captured included) from\n * git's garbage collection.\n *\n * § WHEN adding per-session state, add its table to `purgeSessionRows`\n * (db.ts), or its file here — so removing a session removes it. Before\n * this, deleted sessions left their state behind and a re-created session\n * with the same target:branch inherited it.\n */\n\n/** Per-session files that live outside the database. */\nexport function sessionStatePaths(id: string): string[] {\n // Its archive (kept conversation + summary) and work's copy of its\n // conversations go when the session is deleted for good; archiving keeps\n // the session, so they stay then.\n return [devLogFile(id), archiveDirFor(id), conversationDirFor(id)];\n}\n\n/** Before the session's rows go: stop its dev server (needs the dev_runs\n * row). Best-effort, logged. */\nexport function stopSessionDevServer(id: string): void {\n try {\n stopDev(id);\n } catch (err) {\n logSwallowed(`stop dev server ${id}`, err);\n }\n}\n\n/**\n * A removed session's checkpoints: the refs in its repos' shared git dir\n * (from the base checkouts: the worktree may already be gone) and the\n * manifest. Best-effort, logged.\n */\nexport function clearSessionCheckpoints(s: Pick<WorktreeSession, 'target' | 'isGroup' | 'paths'> & { branch?: string }): void {\n try {\n const cfg = loadConfig();\n const aliases = s.isGroup ? (cfg?.groups[s.target] ?? []) : [s.target];\n const roots = aliases.map((a) => cfg?.repos[a]).filter((r): r is string => !!r && fs.existsSync(r));\n clearCheckpoints(scopeHashForPaths(s.paths), roots);\n // Uncommitted work an archive saved (archive-uncommitted.ts): its refs go like the checkpoints'.\n if (s.branch !== undefined) for (const r of roots) dropSessionSaves(r, sessionIdFor({ target: s.target, branch: s.branch }));\n } catch (err) {\n logSwallowed(`clear checkpoints of ${s.target}`, err);\n }\n}\n\n/** After the session's rows are gone: its files. Best-effort per file. */\nexport function removeSessionFiles(id: string): void {\n for (const p of sessionStatePaths(id)) {\n try {\n fs.rmSync(p, { force: true, recursive: true });\n } catch (err) {\n logSwallowed(`purge ${p}`, err);\n }\n }\n}\n\n/**\n * Remove every piece of per-session state for a session that has no\n * `sessions` row (any more). history.ts removes a session's row and its\n * state in ONE transaction (`purgeSessionRows`); this is the standalone\n * form for state left behind. Best-effort per step (logged), never throws.\n */\nexport async function purgeSessionState(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch });\n stopSessionDevServer(id);\n try {\n tx((d) => purgeSessionRows(d, id));\n } catch (err) {\n logSwallowed(`purge state rows ${id}`, err);\n }\n removeSessionFiles(id);\n}\n","import fs from 'node:fs';\nimport net from 'node:net';\nimport path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { getConfigDir, type WorkConfig } from '../platform/config.js';\nimport { bootTime, isPidAlive, killTree, processName } from '../platform/process.js';\nimport { json, withDb } from '../platform/db.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport type { DevServerState } from '../api-types.js';\n\n/**\n * Per-worktree dev server + preview.\n *\n * Every worktree already owns a stable port ($PORT, see port-allocator.ts)\n * that its Claude and anything it runs inherit. This module answers \"is\n * something serving on it?\" and can run the repo's dev command there —\n * `devCommands` in config.json, keyed by repo alias, e.g.\n * `{ \"web\": \"npm run dev -- --port $PORT\" }`. In a group the first repo\n * (in the session's order) with a command gets the port.\n *\n * The command comes from the user's own config and runs with `shell: true`\n * (like statusHooks); the worktree path is the spawn cwd, never part of\n * the command string. It runs in the background, its output in\n * ~/.work/dev/<session>.log, its pid in state.db (`dev_runs`) — so a\n * `work web` restart still knows it and can stop it.\n */\n\nfunction devDir(): string {\n const dir = path.join(getConfigDir(), 'dev');\n fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\nexport const devLogFile = (id: string) => path.join(devDir(), `${id}.log`);\n\ninterface RunRecord {\n pid: number;\n command: string;\n cwd: string;\n startedAt: string;\n /** Executable at that pid when we started it (the shell), if known.\n * Records from before this field (imported from the JSON files) have\n * none, and are trusted on pid + boot alone. */\n image?: string | null;\n}\n\n/** A run started this close to a boot can't be told from one started\n * before it, if the clock was stepped meanwhile (NTP after sleep). */\nconst REBOOT_SLACK_MS = 5 * 60_000;\n\nfunction isRunRecord(x: unknown): x is RunRecord {\n const r = x as RunRecord | null;\n return !!r && typeof r === 'object' && typeof r.pid === 'number' && typeof r.command === 'string' && typeof r.startedAt === 'string';\n}\n\n/** The machine has rebooted since this run started, so its pid — if alive —\n * belongs to someone else (Windows reuses pids quickly). Compares the boot\n * time with the run's own start time, both on the wall clock, so a clock\n * step of a few minutes doesn't turn a live run into \"another boot\". */\nfunction rebootedSince(r: RunRecord): boolean {\n const started = Date.parse(r.startedAt);\n if (!Number.isFinite(started)) return true; // unknown start: don't trust it\n return bootTime() - started > REBOOT_SLACK_MS;\n}\n\n/**\n * The live run for a session, or null. A saved pid is trusted only while\n * it is alive and from this boot: after a reboot the row survives but the\n * number may belong to an unrelated process — which the header would show\n * as \"running\" and Stop would kill.\n */\nfunction readRun(id: string): RunRecord | null {\n const row = withDb((d) => d.prepare('SELECT data FROM dev_runs WHERE session_id = ?').get(id) as { data: string } | undefined);\n if (!row) return null;\n const r = json.parse(row.data);\n if (isRunRecord(r) && !rebootedSince(r) && isPidAlive(r.pid)) return r;\n forgetRun(id); // it died on its own, or the machine rebooted\n return null;\n}\n\nfunction forgetRun(id: string): void {\n withDb((d) => d.prepare('DELETE FROM dev_runs WHERE session_id = ?').run(id));\n}\n\n/** The dev command for this session and where it runs, or null. */\nexport function devCommandFor(\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): { command: string; cwd: string; repo: string } | null {\n const commands = config?.devCommands ?? {};\n const aliases = session.isGroup ? (config?.groups?.[session.target] ?? []) : [session.target];\n for (const p of session.paths) {\n // A worktree folder is named after its repo's folder (resolve.ts), so\n // match the alias by the repo path's basename.\n const alias =\n aliases.find((a) => {\n const repo = config?.repos?.[a];\n return repo !== undefined && path.basename(repo).toLowerCase() === path.basename(p).toLowerCase();\n }) ?? (session.isGroup ? undefined : session.target);\n const command = alias ? commands[alias] : undefined;\n if (alias && typeof command === 'string' && command.trim()) return { command, cwd: p, repo: alias };\n }\n return null;\n}\n\n/** Something accepts TCP connections on localhost:port (IPv4 or IPv6). */\nexport function isListening(port: number, timeoutMs = 400): Promise<boolean> {\n const probe = (host: string) =>\n new Promise<boolean>((resolve) => {\n const sock = net.connect({ host, port });\n const done = (ok: boolean) => {\n sock.destroy();\n resolve(ok);\n };\n sock.setTimeout(timeoutMs, () => done(false));\n sock.once('connect', () => done(true));\n sock.once('error', () => done(false));\n });\n return probe('127.0.0.1').then((ok) => ok || probe('::1'));\n}\n\nexport async function devState(\n id: string,\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): Promise<DevServerState> {\n const port = session.port ?? null;\n const cmd = devCommandFor(session, config);\n const run = readRun(id);\n return {\n port,\n listening: port !== null ? await isListening(port) : false,\n url: port !== null ? `http://localhost:${port}/` : null,\n command: cmd?.command ?? null,\n repo: cmd?.repo ?? null,\n running: run ? { pid: run.pid, startedAt: run.startedAt } : null,\n };\n}\n\nexport type DevStartOutcome = { ok: true; pid: number } | { ok: false; status: 400 | 409; error: string };\n\nexport function startDev(\n id: string,\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): DevStartOutcome {\n if (session.port === undefined) return { ok: false, status: 400, error: 'this worktree has no port — recreate it with work tree' };\n const cmd = devCommandFor(session, config);\n if (!cmd) return { ok: false, status: 400, error: 'no dev command — set devCommands in ~/.work/config.json' };\n if (!fs.existsSync(cmd.cwd)) return { ok: false, status: 400, error: `worktree is gone: ${cmd.cwd}` };\n const running = readRun(id);\n if (running) return { ok: false, status: 409, error: `already running (pid ${running.pid})` };\n\n const log = fs.openSync(devLogFile(id), 'w');\n try {\n fs.writeSync(log, `$ ${cmd.command} (PORT=${session.port}, in ${cmd.cwd})\\n`);\n const child = spawn(cmd.command, {\n cwd: cmd.cwd,\n shell: true,\n // POSIX: its own process group, so Stop can signal the whole tree.\n // Windows: NOT detached — a DETACHED_PROCESS cmd.exe drops its\n // children's output — and taskkill /T stops the tree instead.\n detached: process.platform !== 'win32',\n windowsHide: true,\n stdio: ['ignore', log, log],\n env: { ...process.env, PORT: String(session.port) },\n });\n child.on('error', () => {});\n if (child.pid === undefined) return { ok: false, status: 400, error: 'could not start the dev command' };\n child.unref();\n const rec: RunRecord = {\n pid: child.pid,\n command: cmd.command,\n cwd: cmd.cwd,\n startedAt: new Date().toISOString(),\n image: processName(child.pid),\n };\n withDb((d) => d.prepare('INSERT OR REPLACE INTO dev_runs (session_id, data) VALUES (?, ?)').run(id, JSON.stringify(rec)));\n return { ok: true, pid: child.pid };\n } finally {\n fs.closeSync(log);\n }\n}\n\n/** Stop this session's dev server (the whole process tree). `name` looks\n * up a live pid's executable (injectable for tests). */\nexport function stopDev(id: string, name: (pid: number) => string | null = processName): boolean {\n const run = readRun(id);\n if (!run) return false;\n // Last check before killing a whole tree: the pid must still be the shell\n // we started. A DIFFERENT program at that number means the dev server is\n // long gone and the pid was reused — forget it, kill nothing. An\n // unreadable name (tasklist/ps slow or missing) proves nothing: the pid\n // is alive and from this boot, so go ahead.\n const now = name(run.pid);\n if (run.image && now !== null && now.toLowerCase() !== run.image.toLowerCase()) {\n forgetRun(id);\n return false;\n }\n // Detached on POSIX = its own process group: signal the group, so the\n // shell's children (npm → vite) go too. Windows: taskkill /T.\n let killed = false;\n if (process.platform !== 'win32') {\n try {\n process.kill(-run.pid, 'SIGTERM');\n killed = true;\n } catch {\n /* fall through */\n }\n }\n if (!killed) killed = killTree(run.pid);\n forgetRun(id);\n return killed;\n}\n\n/** The tail of the dev server's log. */\nexport function devLogTail(id: string, maxBytes = 64 * 1024): string {\n try {\n const file = devLogFile(id);\n const size = fs.statSync(file).size;\n const fd = fs.openSync(file, 'r');\n try {\n const len = Math.min(size, maxBytes);\n const buf = Buffer.alloc(len);\n fs.readSync(fd, buf, 0, len, size - len);\n return buf.toString('utf-8');\n } finally {\n fs.closeSync(fd);\n }\n } catch {\n return '';\n }\n}\n","/**\n * Per-scope diff checkpoints.\n *\n * A \"checkpoint\" is a snapshot of every repo in a scope's working tree\n * (including untracked files) captured as a real git commit and held alive\n * by `refs/wd/<scope-hash>/<n>` in each repo. A small JSON manifest at\n * `~/.work/diffs/<scope-hash>.checkpoints.json` records the per-checkpoint\n * timestamp + repo→sha mapping so the SPA can list checkpoints and ask for\n * a diff between any two (or between one and the live working tree).\n *\n * Snapshots are taken automatically:\n * - once when a scope is first registered (the \"Initial\" point). This\n * baseline captures HEAD's tree, NOT the working tree — so a range of\n * \"Initial → working\" equals the full uncommitted diff (`git diff HEAD`\n * plus untracked), and any pre-existing uncommitted work the user\n * already had when `wd` launched stays visible instead of being baked\n * into an invisible baseline.\n * - again whenever the scope's fs-watch debounce fires AND the working\n * tree differs from the previous snapshot (the dedup keeps idle saves\n * from spawning empty checkpoints)\n *\n * The capture mechanism uses a temp git index file so the real index is\n * never disturbed:\n *\n * GIT_INDEX_FILE=<tmp> git read-tree HEAD\n * GIT_INDEX_FILE=<tmp> git add -A\n * GIT_INDEX_FILE=<tmp> git write-tree → <tree-sha>\n * git commit-tree <tree-sha> -p HEAD -m \"wd checkpoint\" → <commit-sha>\n * git update-ref refs/wd/<hash>/<n> <commit-sha>\n *\n * Untracked files end up in the snapshot because `git add -A` against the\n * temp index promotes them. `.gitignore` is honoured (same as the diff\n * pipeline's untracked detection).\n */\n\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport spawn from '../platform/spawn.js';\nimport { atomicWriteFile, ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { runGitAsync, writeTempTreeAsync } from './git-tree-snapshot.js';\n\nexport interface CheckpointEntry {\n /** Monotonic per-scope sequence id, starting at 0 for the initial\n * snapshot. */\n id: number;\n /** ISO timestamp of capture. */\n ts: string;\n /** Human label — \"Initial\" for id 0, otherwise empty (the SPA shows\n * \"#1\", \"#2\", ...). Reserved for future user-labelled checkpoints. */\n label?: string;\n /** Per-repo commit sha captured. Keyed by repo name (the same `name`\n * used in `RepoData`). When a repo has no head yet (fresh repo, no\n * commits), the value is null — diff ranges that touch it on the\n * \"from\" side fall back to the empty tree. */\n repos: Record<string, string | null>;\n}\n\nexport interface CheckpointManifest {\n version: 1;\n scopeHash: string;\n entries: CheckpointEntry[];\n}\n\n/** Where this scope's manifest lives on disk. */\nexport function manifestPath(scopeHash: string): string {\n const dir = path.join(os.homedir(), '.work', 'diffs');\n fs.mkdirSync(dir, { recursive: true });\n return path.join(dir, `${scopeHash}.checkpoints.json`);\n}\n\nfunction emptyManifest(scopeHash: string): CheckpointManifest {\n return { version: 1, scopeHash, entries: [] };\n}\n\n/** Read manifest from disk (returns an empty one if the file is missing\n * or unparseable). Never throws. */\nexport function loadManifest(scopeHash: string): CheckpointManifest {\n const file = manifestPath(scopeHash);\n if (!fs.existsSync(file)) return emptyManifest(scopeHash);\n try {\n const raw = fs.readFileSync(file, 'utf-8');\n const parsed = JSON.parse(raw) as Partial<CheckpointManifest>;\n if (parsed.version !== 1 || !Array.isArray(parsed.entries)) {\n return emptyManifest(scopeHash);\n }\n return {\n version: 1,\n scopeHash,\n entries: parsed.entries as CheckpointEntry[],\n };\n } catch {\n return emptyManifest(scopeHash);\n }\n}\n\n// (Previously a separate `appendCheckpoint` lived here. It was folded\n// into `takeCheckpoint` so id assignment + snapshot + ref write + manifest\n// append all happen under a single lock — concurrent fs-watch fires across\n// the same scope must not race on `nextId`.)\n\n/**\n * Capture a single repo as a commit and return its sha. Updates\n * `refs/wd/<scopeHash>/<id>` to point at the commit so git GC can't\n * reclaim it. Returns null on failure (caller should skip this repo).\n *\n * `includeWorkingTree` (default true) controls what tree is captured:\n * - true — the working tree, incl. untracked files (subject to\n * .gitignore). This is the normal per-change snapshot.\n * - false — HEAD's tree verbatim (no `git add -A`). Used for the\n * \"Initial\" baseline so a diff of Initial → working reproduces\n * the full uncommitted diff rather than hiding pre-existing\n * changes inside the baseline. On a repo with no commits this\n * yields the empty tree (everything shows as added).\n *\n * Internally uses a temp `GIT_INDEX_FILE` so the user's real index is\n * untouched. The temp file is unlinked on success and on most failures.\n */\nexport async function snapshotRepo(repoRoot: string, scopeHash: string, id: number, includeWorkingTree = true): Promise<string | null> {\n // Build the tree (HEAD baseline, or full working tree) via the shared\n // temp-index helper — same dance `diff-pipeline.ts` uses to diff against\n // a checkpoint.\n // Off the event loop, one per repo at a time (writeTempTreeAsync): this\n // runs on every Claude turn of every session.\n const tree = await writeTempTreeAsync(repoRoot, { includeWorkingTree });\n if (!tree) return null;\n const { treeSha, headSha } = tree;\n\n // commit-tree doesn't need the temp index. Use a fixed author/committer +\n // date so two snapshots of identical content produce the SAME commit sha\n // (the tree sha is already identical; matching commit shas help dedup).\n // The dedup path in `takeCheckpoint` relies on this: when nothing changed\n // between captures, every repo's recomputed sha matches the previous entry\n // and the new manifest row is discarded. (The id isn't in the message; it\n // lives in the ref name + manifest entry.)\n const commitArgs = ['commit-tree', treeSha, '-m', 'wd checkpoint'];\n if (headSha) commitArgs.push('-p', headSha);\n const commitEnv = {\n ...process.env,\n GIT_AUTHOR_NAME: 'wd',\n GIT_AUTHOR_EMAIL: 'wd@local',\n GIT_AUTHOR_DATE: '2000-01-01T00:00:00Z',\n GIT_COMMITTER_NAME: 'wd',\n GIT_COMMITTER_EMAIL: 'wd@local',\n GIT_COMMITTER_DATE: '2000-01-01T00:00:00Z',\n };\n const commit = await runGitAsync(repoRoot, { args: commitArgs, env: commitEnv });\n if (commit.status !== 0 || !commit.stdout) return null;\n const commitSha = commit.stdout.trim();\n\n const refName = `refs/wd/${scopeHash}/${id}`;\n const updateRef = await runGitAsync(repoRoot, { args: ['update-ref', refName, commitSha] });\n if (updateRef.status !== 0) return null;\n\n return commitSha;\n}\n\nexport interface ScopeRepo {\n name: string;\n root: string;\n}\n\n/**\n * Take one checkpoint across every repo in a scope. Returns the appended\n * entry, or null when the snapshot is identical to the previous entry's\n * (every repo's commit sha matches — i.e. nothing changed). The caller\n * uses the null return to skip the SSE broadcast.\n *\n * When this is the first checkpoint for the scope, `label` defaults to\n * \"Initial\" so the SPA can render it specially.\n */\nexport async function takeCheckpoint(\n scopeHash: string,\n repos: ScopeRepo[],\n opts: { force?: boolean; label?: string } = {},\n): Promise<CheckpointEntry | null> {\n // Entire flow runs under one file lock so concurrent fs-watch fires\n // (or a register-handler racing with a debounced auto-snapshot) can't\n // assign duplicate ids or interleave manifest writes. Snapshot work\n // itself is git-side-effect-safe to concurrent — git's index/ref\n // locking handles same-repo overlap, and our temp `GIT_INDEX_FILE`\n // means the user's real index is untouched either way. We only need\n // the file lock to serialise the *id assignment + ref write + append*\n // triple, which has to be atomic across processes.\n const file = manifestPath(scopeHash);\n ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));\n return withFileLock(file, async () => {\n const manifest = loadManifest(scopeHash);\n const isFirst = manifest.entries.length === 0;\n const nextId = isFirst ? 0 : manifest.entries[manifest.entries.length - 1].id + 1;\n\n // The first checkpoint baselines HEAD (not the working tree) so\n // pre-existing uncommitted work stays visible in an \"Initial → working\"\n // range. Every subsequent checkpoint captures the working tree.\n const captured: Record<string, string | null> = {};\n for (const repo of repos) {\n captured[repo.name] = await snapshotRepo(repo.root, scopeHash, nextId, !isFirst);\n }\n\n // Delete `refs/wd/<hash>/<id>` in every listed repo. Used by both\n // the partial-failure bailout and the dedup-cancel path —\n // `update-ref -d` is a no-op on a missing ref, so the same helper\n // covers \"rollback what we wrote\" and \"rollback what we might\n // have written\" without needing per-repo state.\n const rollbackRefs = () => {\n const refName = `refs/wd/${scopeHash}/${nextId}`;\n for (const repo of repos) {\n spawn.sync('git', ['update-ref', '-d', refName], {\n cwd: repo.root,\n encoding: 'utf-8',\n windowsHide: true,\n });\n }\n };\n\n // If any repo snapshot failed (returned null), bail — a partial\n // entry would let range diffs against this id silently produce\n // empty diffs for the failed repos (via the `?? 'HEAD'` fallback\n // in scope-routes) instead of surfacing the problem. The next\n // fs-event will retry.\n if (repos.some((r) => captured[r.name] === null)) {\n rollbackRefs();\n return null;\n }\n\n // Dedup: when not forced, compare against the previous entry by\n // TREE sha rather than commit sha. Two captures of the same working\n // tree produce identical trees but can have different commit shas\n // (different parent because HEAD moved, different `-p` argument\n // when one capture saw an empty HEAD). Compare-by-tree means we\n // drop checkpoints that didn't actually change any content —\n // exactly what the user expects from \"no changes since last snapshot\".\n if (!opts.force && !isFirst) {\n const prev = manifest.entries[manifest.entries.length - 1];\n const treeOf = (root: string, commitSha: string | null): string | null => {\n if (!commitSha) return null;\n const r = spawn.sync('git', ['rev-parse', `${commitSha}^{tree}`], { cwd: root, encoding: 'utf-8', windowsHide: true });\n if (r.status !== 0 || typeof r.stdout !== 'string') return null;\n return r.stdout.trim() || null;\n };\n const allTreesMatch = repos.every((repo) => {\n const curTree = treeOf(repo.root, captured[repo.name]);\n const prevTree = treeOf(repo.root, prev.repos[repo.name] ?? null);\n return curTree !== null && curTree === prevTree;\n });\n if (allTreesMatch) {\n rollbackRefs();\n return null;\n }\n }\n\n const entry: CheckpointEntry = {\n id: nextId,\n ts: new Date().toISOString(),\n repos: captured,\n };\n const label = opts.label ?? (isFirst ? 'Initial' : undefined);\n if (label) entry.label = label;\n manifest.entries.push(entry);\n // At most MAX_CHECKPOINTS per scope: the oldest steps go (never the\n // Initial baseline), refs and all — each ref keeps a full snapshot's\n // objects from git's garbage collection.\n const dropped = checkpointsOverCap(manifest.entries);\n if (dropped.length) {\n const gone = new Set(dropped.map((e) => e.id));\n manifest.entries = manifest.entries.filter((e) => !gone.has(e.id));\n }\n atomicWriteFile(file, JSON.stringify(manifest, null, 2));\n for (const e of dropped) {\n for (const repo of repos) await runGitAsync(repo.root, { args: ['update-ref', '-d', `refs/wd/${scopeHash}/${e.id}`] });\n }\n return entry;\n });\n}\n\n/** How many checkpoints a scope keeps (Initial included). */\nexport const MAX_CHECKPOINTS = 200;\n\n/** The entries to drop to get back to `max`: the oldest after the Initial one. */\nexport function checkpointsOverCap<T extends { id: number }>(entries: T[], max = MAX_CHECKPOINTS): T[] {\n if (entries.length <= max) return [];\n return entries.slice(1, 1 + (entries.length - max));\n}\n\nexport type UpdateCheckpointResult = { status: 'updated'; entry: CheckpointEntry } | { status: 'unchanged' } | { status: 'missing' };\n\n/**\n * Re-snapshot every repo into an EXISTING checkpoint `id`, replacing its\n * captured shas + timestamp in place. This is the \"one step per instruction\"\n * primitive: while a Claude instruction is in progress, each turn refreshes\n * the same (live) checkpoint instead of appending a brand-new step, so all\n * the turns answering one prompt collapse into a single entry. The label is\n * cleared on a real change so the caller re-summarises the new content.\n *\n * Returns:\n * - { status:'updated', entry } — content changed and was written\n * - { status:'unchanged' } — the refreshed tree matches what's stored\n * - { status:'missing' } — no entry with `id`, or a repo snapshot\n * failed (caller should append instead)\n *\n * Ref/manifest consistency: `snapshotRepo` overwrites `refs/wd/<hash>/<id>`.\n * On both the 'missing' (partial-failure) and 'unchanged' paths we restore\n * each ref to the entry's recorded sha so a moved ref can't orphan the commit\n * the manifest still points at.\n */\nexport async function updateCheckpoint(scopeHash: string, repos: ScopeRepo[], id: number): Promise<UpdateCheckpointResult> {\n const file = manifestPath(scopeHash);\n ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));\n return withFileLock(file, async () => {\n const manifest = loadManifest(scopeHash);\n const entry = manifest.entries.find((e) => e.id === id);\n if (!entry) return { status: 'missing' as const };\n\n const refName = `refs/wd/${scopeHash}/${id}`;\n const restoreRefs = () => {\n for (const repo of repos) {\n const old = entry.repos[repo.name] ?? null;\n if (old) {\n spawn.sync('git', ['update-ref', refName, old], {\n cwd: repo.root,\n encoding: 'utf-8',\n windowsHide: true,\n });\n } else {\n spawn.sync('git', ['update-ref', '-d', refName], {\n cwd: repo.root,\n encoding: 'utf-8',\n windowsHide: true,\n });\n }\n }\n };\n\n // Capture the current working tree into the SAME ref id (overwrites the\n // previous commit for this id).\n const captured: Record<string, string | null> = {};\n for (const repo of repos) {\n captured[repo.name] = await snapshotRepo(repo.root, scopeHash, id, true);\n }\n if (repos.some((r) => captured[r.name] === null)) {\n restoreRefs();\n return { status: 'missing' as const };\n }\n\n const treeOf = (root: string, commitSha: string | null): string | null => {\n if (!commitSha) return null;\n const r = spawn.sync('git', ['rev-parse', `${commitSha}^{tree}`], {\n cwd: root,\n encoding: 'utf-8',\n windowsHide: true,\n });\n if (r.status !== 0 || typeof r.stdout !== 'string') return null;\n return r.stdout.trim() || null;\n };\n const unchanged = repos.every((repo) => {\n const curTree = treeOf(repo.root, captured[repo.name]);\n const prevTree = treeOf(repo.root, entry.repos[repo.name] ?? null);\n return curTree !== null && curTree === prevTree;\n });\n if (unchanged) {\n restoreRefs();\n return { status: 'unchanged' as const };\n }\n\n entry.repos = captured;\n entry.ts = new Date().toISOString();\n delete entry.label; // content changed → re-summarise\n atomicWriteFile(file, JSON.stringify(manifest, null, 2));\n return { status: 'updated' as const, entry };\n });\n}\n\n/**\n * Atomically re-baseline a scope at the current HEAD: under a SINGLE file\n * lock, capture a fresh \"Initial\" snapshot (HEAD's tree, not the working\n * tree) for every repo into id 0, delete the refs of all previous steps, and\n * replace the manifest with just that Initial entry.\n *\n * This is the locked, all-or-nothing form of \"clearCheckpoints +\n * takeCheckpoint\": doing those as two separate (and, for clearCheckpoints,\n * unlocked) steps let a concurrent checkpoint write interleave between the\n * clear and the new Initial — leaving a dangling ref or a dropped entry.\n * Holding one lock across the whole reset closes that window.\n *\n * Returns the new Initial entry, or null if any repo's snapshot failed (the\n * manifest is left untouched in that case; the partial id-0 ref is undone).\n */\nexport async function resetBaseline(scopeHash: string, repos: ScopeRepo[]): Promise<CheckpointEntry | null> {\n const file = manifestPath(scopeHash);\n ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));\n return withFileLock(file, async () => {\n const prevIds = loadManifest(scopeHash).entries.map((e) => e.id);\n\n // Fresh Initial baselines HEAD (includeWorkingTree=false). snapshotRepo\n // overwrites refs/wd/<hash>/0 in place.\n const captured: Record<string, string | null> = {};\n for (const repo of repos) {\n captured[repo.name] = await snapshotRepo(repo.root, scopeHash, 0, false);\n }\n\n const delRef = (id: number) => {\n for (const repo of repos) {\n spawn.sync('git', ['update-ref', '-d', `refs/wd/${scopeHash}/${id}`], {\n cwd: repo.root,\n encoding: 'utf-8',\n windowsHide: true,\n });\n }\n };\n\n // Any repo failed → undo the partial id-0 write, leave the old manifest.\n if (repos.some((r) => captured[r.name] === null)) {\n delRef(0);\n return null;\n }\n\n // Drop every previous step's ref except id 0 (just overwritten with the\n // fresh Initial). These are the now-orphaned snapshots being discarded.\n for (const id of prevIds) {\n if (id !== 0) delRef(id);\n }\n\n const entry: CheckpointEntry = {\n id: 0,\n ts: new Date().toISOString(),\n label: 'Initial',\n repos: captured,\n };\n const manifest: CheckpointManifest = {\n version: 1,\n scopeHash,\n entries: [entry],\n };\n atomicWriteFile(file, JSON.stringify(manifest, null, 2));\n return entry;\n });\n}\n\n/**\n * Set (cache) a checkpoint's human label. Runs under the same file lock as\n * `takeCheckpoint` so a concurrent auto-snapshot can't clobber the write.\n * No-op when the id isn't found. Idempotent.\n */\nexport async function setCheckpointLabel(scopeHash: string, id: number, label: string): Promise<void> {\n const file = manifestPath(scopeHash);\n ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));\n await withFileLock(file, () => {\n const manifest = loadManifest(scopeHash);\n const entry = manifest.entries.find((e) => e.id === id);\n if (!entry || entry.label === label) return;\n entry.label = label;\n atomicWriteFile(file, JSON.stringify(manifest, null, 2));\n });\n}\n\n/**\n * True when the branch has advanced (pull / merge / new commit) since the\n * Initial (id 0) checkpoint was captured — i.e. any repo's current HEAD tree\n * differs from the tree the Initial baseline recorded.\n *\n * The Initial checkpoint commits HEAD's tree verbatim (`snapshotRepo` with\n * `includeWorkingTree=false`), so its tree equals HEAD-at-capture's tree. When\n * that no longer matches the live HEAD's tree the baseline is stale, and an\n * \"Initial → working\" range silently absorbs every commit pulled in since\n * (e.g. a `git pull`/merge of an upstream branch) — ballooning the diff far\n * beyond the user's own work. Callers re-baseline when this returns true.\n *\n * Returns false when there's no Initial entry, when HEAD can't be resolved, or\n * when every recorded tree still matches (uncommitted edits don't move HEAD's\n * tree, so a dirty-but-not-advanced worktree is correctly left alone).\n */\nexport function headAdvancedSinceInitial(scopeHash: string, repos: ScopeRepo[]): boolean {\n const manifest = loadManifest(scopeHash);\n const initial = manifest.entries.find((e) => e.id === 0);\n if (!initial) return false;\n const treeOf = (root: string, rev: string): string | null => {\n const r = spawn.sync('git', ['rev-parse', `${rev}^{tree}`], {\n cwd: root,\n encoding: 'utf-8',\n windowsHide: true,\n });\n if (r.status !== 0 || typeof r.stdout !== 'string') return null;\n return r.stdout.trim() || null;\n };\n return repos.some((repo) => {\n const headTree = treeOf(repo.root, 'HEAD');\n if (headTree === null) return false; // can't resolve HEAD → don't reset\n const baselineSha = initial.repos[repo.name];\n if (!baselineSha) return true; // baseline had no commit, HEAD exists now\n const baselineTree = treeOf(repo.root, baselineSha);\n if (baselineTree === null) return false; // baseline ref gone → leave it\n return baselineTree !== headTree;\n });\n}\n\n/**\n * A session's scope keeps its turns across its own commits, but not across\n * a HEAD move that brought in work the session didn't do: the next turn,\n * diffed against the one before, would show all of it as Claude's. Since the\n * newest checkpoint (whose snapshot commit's parent is the HEAD then): a\n * rebase or reset (that HEAD is no longer underneath), a merge (Update from\n * main, a pull that merged), or commits already on the main branch\n * (`origin/HEAD`: a fast-forward pull, a rebase onto main) — true; only new\n * commits of its own on top — false. Can't tell (git failed): false.\n */\nexport function headBroughtInOtherWork(scopeHash: string, repos: ScopeRepo[]): boolean {\n const entries = loadManifest(scopeHash).entries;\n if (entries.length === 0) return false;\n const newest = entries.reduce((a, b) => (b.id > a.id ? b : a));\n const run = (root: string, args: string[]) => {\n const r = spawn.sync('git', args, { cwd: root, encoding: 'utf-8', windowsHide: true });\n return { ok: r.status === 0, out: typeof r.stdout === 'string' ? r.stdout.trim() : '' };\n };\n const count = (root: string, args: string[]) => {\n const r = run(root, ['rev-list', '--count', ...args]);\n return r.ok && /^\\d+$/.test(r.out) ? Number(r.out) : null;\n };\n return repos.some((repo) => {\n const snap = newest.repos[repo.name];\n if (!snap) return false;\n const was = run(repo.root, ['rev-parse', '--verify', '--quiet', `${snap}^`]);\n const now = run(repo.root, ['rev-parse', '--verify', '--quiet', 'HEAD']);\n if (!was.ok || !now.ok || !was.out || was.out === now.out) return false;\n if (!run(repo.root, ['merge-base', '--is-ancestor', was.out, now.out]).ok) return true;\n const range = `${was.out}..${now.out}`;\n if ((count(repo.root, ['--merges', range]) ?? 0) > 0) return true;\n const main = run(repo.root, ['rev-parse', '--verify', '--quiet', 'origin/HEAD']);\n if (!main.ok) return false;\n const all = count(repo.root, [range]);\n const own = count(repo.root, [range, '^origin/HEAD']);\n return all !== null && own !== null && own < all;\n });\n}\n\n/** Remove the manifest + every ref for this scope. Called when a scope\n * is explicitly torn down. Best-effort — partial failure leaves orphaned\n * refs but doesn't otherwise corrupt state. */\nexport function clearCheckpoints(scopeHash: string, repoRoots: string[]): void {\n const manifest = loadManifest(scopeHash);\n for (const root of repoRoots) {\n for (const entry of manifest.entries) {\n const refName = `refs/wd/${scopeHash}/${entry.id}`;\n spawn.sync('git', ['update-ref', '-d', refName], {\n cwd: root,\n encoding: 'utf-8',\n windowsHide: true,\n });\n }\n }\n const file = manifestPath(scopeHash);\n if (fs.existsSync(file)) {\n try {\n fs.unlinkSync(file);\n } catch {\n // Leave it — next register will overwrite.\n }\n }\n}\n","/**\n * Stage 1 of the migration to \"one server per machine.\"\n *\n * A scope is an ad-hoc registration from a `wd` (or `wd -c`) invocation:\n * a label and a list of repo roots. Identified by the same sha1-of-roots\n * hash that `stableDiffPath` produces, so the same directory always gets\n * the same scope id across CLI invocations.\n *\n * Scopes are in-memory only — registering one doesn't touch disk. The\n * file watcher and comment store are per-scope, lazily started on first\n * access and reused thereafter.\n *\n * This module is mounted into `work web` so multiple `wd` invocations\n * share a single server process. Eventually `wd` itself will become a\n * thin client that registers a scope and opens a URL.\n */\n\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport { createFsWatcher, type FsWatcher } from '../platform/fs-watcher.js';\nimport { loadConfig } from '../platform/config.js';\n\nexport interface Scope {\n /** Stable hash — same as `stableDiffPath` would emit. */\n hash: string;\n /** Repo roots this scope covers. One for a single-repo worktree,\n * many for a group. */\n paths: string[];\n /** Optional human label (e.g. \"work-tree · feat/x\"). */\n label: string;\n /** When the scope was first registered. */\n createdAt: string;\n /** Set when the user clicks \"End Review\" in the browser. The scope\n * itself stays alive (browser tab still works) — this is just a\n * signal so the `wd -c` CLI proxy knows to emit\n * `--- review done ---` and exit. */\n ended: boolean;\n}\n\ninterface ScopeEntry {\n scope: Scope;\n watcher: FsWatcher | null;\n subscribers: Set<() => void>;\n /** ms-since-epoch until which fs-watch events for this scope are ignored.\n * The diff server sets a short window right after it computes a diff so\n * the `.git` churn from its OWN git commands (e.g. the `to=working`\n * range diff's `git add -A` / `write-tree`) doesn't fire a reload — which\n * would refetch the diff, churn `.git` again, and loop. Real user edits\n * land outside this window and still reload. */\n suppressWatchUntil: number;\n}\n\nconst scopes = new Map<string, ScopeEntry>();\n\nfunction hashFor(paths: string[]): string {\n const key = paths.slice().sort().join('|');\n return crypto.createHash('sha1').update(key).digest('hex').slice(0, 12);\n}\n\n/** Thrown by registerScope when the requested paths aren't inside any\n * configured repo or under the configured worktrees root. */\nexport class ScopePathRejectedError extends Error {\n constructor(public rejected: string[]) {\n super(`paths not allowed: ${rejected.join(', ')} (must be inside a configured repo or worktreesRoot)`);\n this.name = 'ScopePathRejectedError';\n }\n}\n\nfunction normaliseForCompare(p: string): string {\n return path.resolve(p).replace(/\\\\/g, '/').toLowerCase();\n}\n\n/**\n * Reject paths that aren't inside any configured repo or under the\n * configured `worktreesRoot`. The work web server binds to 127.0.0.1\n * only, but any local process can still POST `/api/scopes` with an\n * arbitrary filesystem path — without this check a malicious npm\n * package could cause `git` and chokidar to operate on\n * `C:\\Windows\\System32` or the user's home root.\n *\n * Returns the rejected subset (empty array when everything's allowed).\n */\nfunction rejectedPaths(normalised: string[]): string[] {\n const config = loadConfig();\n if (!config) {\n // No config means no allowlist to check against. Fall back to\n // permissive — `work init` hasn't been run yet, and rejecting\n // everything would break first-run flows.\n return [];\n }\n const allowed = [...Object.values(config.repos), ...(config.worktreesRoot ? [config.worktreesRoot] : [])].map(normaliseForCompare);\n if (allowed.length === 0) return [];\n return normalised.filter((p) => {\n const np = normaliseForCompare(p);\n return !allowed.some((a) => np === a || np.startsWith(a + '/'));\n });\n}\n\n/** Register a scope (idempotent). Returns the resolved entry — same call\n * twice with the same paths gets the same hash and the same entry.\n * Throws `ScopePathRejectedError` when any path is outside the configured\n * repos / worktrees root. */\nexport function registerScope(paths: string[], label?: string): Scope {\n const normalised = paths.map((p) => path.resolve(p));\n const rejected = rejectedPaths(normalised);\n if (rejected.length > 0) throw new ScopePathRejectedError(rejected);\n const hash = hashFor(normalised);\n const existing = scopes.get(hash);\n if (existing) {\n if (label && existing.scope.label !== label) {\n existing.scope.label = label;\n }\n return existing.scope;\n }\n const scope: Scope = {\n hash,\n paths: normalised,\n label: label ?? path.basename(normalised[0]),\n createdAt: new Date().toISOString(),\n ended: false,\n };\n scopes.set(hash, {\n scope,\n watcher: null,\n subscribers: new Set(),\n suppressWatchUntil: 0,\n });\n return scope;\n}\n\n/** Mark a scope as ended (the user clicked \"End Review\"). Idempotent.\n * Does NOT remove the scope — the URL stays viewable. */\nexport function markScopeEnded(hash: string): boolean {\n const entry = scopes.get(hash);\n if (!entry) return false;\n if (entry.scope.ended) return false;\n entry.scope.ended = true;\n return true;\n}\n\n/**\n * Clear a scope's `ended` flag. Called when a scope is re-registered —\n * a new `wd -c` run on the same paths is a fresh review, not a replay of\n * the finished one. Returns true when the flag was actually set (so the\n * caller knows to also reset the previous run's comments).\n */\nexport function reviveScope(hash: string): boolean {\n const entry = scopes.get(hash);\n if (!entry || !entry.scope.ended) return false;\n entry.scope.ended = false;\n return true;\n}\n\n/**\n * Which scopes a work web shutdown may sweep (checkpoint refs + manifest):\n * only ones no session owns. A session's scope holds its turn history\n * (\"Last turn\"), which must survive a restart; sweeping it on every clean\n * shutdown erased every session's turns. What's left are `wd` scopes for\n * paths outside any session (or one sub-repo of a group).\n */\nexport function scopesToSweep(scopes: Scope[], sessionPaths: string[][]): Scope[] {\n const owned = new Set(sessionPaths.map((paths) => hashFor(paths.map((p) => path.resolve(p)))));\n return scopes.filter((s) => !owned.has(s.hash));\n}\n\n/**\n * Is this scope a session's (its paths are a session's paths)? A session's\n * turns are its history: the Diff tab lists them beside its commits, so a\n * commit must not wipe them (wd's own scopes re-baseline at each commit).\n */\nexport function sessionOwnsScope(hash: string, sessionPaths: string[][]): boolean {\n return sessionPaths.some((paths) => hashFor(paths.map((p) => path.resolve(p))) === hash);\n}\n\n/** The registered scope for exactly these paths, or null — no side effects\n * (unlike registerScope, which relabels). */\nexport function findScope(paths: string[]): Scope | null {\n return getScope(scopeHashForPaths(paths));\n}\n\n/** The scope hash for these paths, registered or not (its checkpoint\n * manifest on disk is keyed by it). */\nexport function scopeHashForPaths(paths: string[]): string {\n return hashFor(paths.map((p) => path.resolve(p)));\n}\n\nexport function getScope(hash: string): Scope | null {\n return scopes.get(hash)?.scope ?? null;\n}\n\n/** Ignore this scope's fs-watch events for the next `ms`. The diff server\n * calls this right after computing a diff so its own `.git` churn doesn't\n * trigger a reload (which would recompute → churn → loop). */\nexport function suppressScopeWatch(hash: string, ms: number): void {\n const entry = scopes.get(hash);\n if (entry) entry.suppressWatchUntil = Date.now() + ms;\n}\n\n/**\n * Pure predicate: does a scope with these repo roots cover `cwd`? True when\n * cwd equals a root, sits inside one, or contains one (the group-root case,\n * where Claude runs in the parent of the sub-repos). Exported for testing\n * without the registry / config allowlist.\n */\nexport function scopeCoversCwd(paths: string[], cwd: string): boolean {\n const nc = normaliseForCompare(cwd);\n return paths.some((p) => {\n const np = normaliseForCompare(p);\n return np === nc || np.startsWith(nc + '/') || nc.startsWith(np + '/');\n });\n}\n\n/**\n * Scopes relevant to `cwd` — used by the `work hook checkpoint` bridge to\n * snapshot the right scope when a Claude turn ends.\n */\nexport function scopesForCwd(cwd: string): Scope[] {\n return Array.from(scopes.values())\n .map((e) => e.scope)\n .filter((s) => scopeCoversCwd(s.paths, cwd));\n}\n\nexport function listScopes(): Scope[] {\n return Array.from(scopes.values()).map((e) => e.scope);\n}\n\nexport function removeScope(hash: string): boolean {\n const entry = scopes.get(hash);\n if (!entry) return false;\n entry.watcher?.stop();\n entry.subscribers.clear();\n scopes.delete(hash);\n return true;\n}\n\n/**\n * Subscribe to file-change events for a scope. Lazy-starts the\n * chokidar watcher on first subscribe; tears it down when the last\n * subscriber unsubscribes. Same lifecycle as `web-state.subscribeSession`.\n *\n * The callback fires once per debounced fs event burst.\n */\nexport function subscribeScope(hash: string, cb: () => void): (() => void) | null {\n const entry = scopes.get(hash);\n if (!entry) return null;\n entry.subscribers.add(cb);\n if (!entry.watcher) {\n entry.watcher = createFsWatcher({\n roots: entry.scope.paths,\n debounceMs: 150,\n onChange: () => {\n // Ignore the burst of `.git` churn our own diff computation just\n // produced (see suppressWatchUntil) — firing here would loop the\n // live-reload. Real edits arrive outside the window.\n if (Date.now() < entry.suppressWatchUntil) return;\n for (const sub of entry.subscribers) {\n try {\n sub();\n } catch {\n /* */\n }\n }\n },\n });\n }\n return () => {\n entry.subscribers.delete(cb);\n if (entry.subscribers.size === 0 && entry.watcher) {\n entry.watcher.stop();\n entry.watcher = null;\n }\n };\n}\n\n/** Shut down every scope's watcher. Web server shutdown hook. */\nexport function disposeAllScopes(): void {\n for (const e of scopes.values()) {\n e.watcher?.stop();\n e.subscribers.clear();\n }\n scopes.clear();\n}\n\n/** Build a comment-store id for a scope. Distinguishes from session\n * ids so the two namespaces can't collide on disk. */\nexport function commentStoreIdForScope(hash: string): string {\n return `scope-${hash}`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { report } from './report.js';\n\n/** chokidar, loaded when a watch starts (Linux only uses it): every `work` process\n * that imports this module — a hook, on each Claude turn — would otherwise load it too. */\nconst loadChokidar = () => createRequire(import.meta.url)('chokidar') as typeof import('chokidar');\n\nexport interface FsWatcherOptions {\n /** Working-tree roots to watch. .git/ subdirs are filtered out. */\n roots: string[];\n /** Debounce window for fs events before firing `onChange`. */\n debounceMs?: number;\n /** Fires once per debounce window when anything under `roots` changed. */\n onChange: () => void;\n}\n\nexport interface FsWatcher {\n stop(): void;\n}\n\n/**\n * Directory names the watcher must never descend into. chokidar (v4+, no\n * fsevents) opens one OS watch per directory, so recursively watching a\n * dependency install or build-output tree exhausts the process's file\n * descriptors (EMFILE) and wedges the server. These are all git-ignored in\n * practice, so changes there never affect the diff — at worst a manual\n * browser refresh is needed for an edit inside one.\n */\nconst IGNORED_DIRS = new Set([\n '.git',\n 'node_modules',\n 'bin', // .NET build output\n 'obj', // .NET build output\n 'dist',\n 'build',\n 'out',\n 'target', // Rust / JVM\n '.next',\n '.nuxt',\n '.svelte-kit',\n '.turbo',\n '.gradle',\n 'coverage',\n '.vs',\n '.idea',\n]);\n\n/**\n * Whether chokidar should skip a path. A path is ignored when any segment\n * *below one of the watched roots* is in {@link IGNORED_DIRS}. Matching\n * relative to the root (not the absolute path) avoids false positives when an\n * ancestor directory happens to be named e.g. `build`.\n */\nexport function isIgnoredWatchPath(roots: string[], filePath: string): boolean {\n for (const root of roots) {\n const rel = path.relative(root, filePath).replace(/\\\\/g, '/');\n if (rel === '' || rel.startsWith('../')) continue; // not under this root\n if (rel.split('/').some((seg) => IGNORED_DIRS.has(seg))) return true;\n }\n return false;\n}\n\n// macOS and Windows support recursive fs.watch (backed by FSEvents /\n// ReadDirectoryChangesW) — a single OS handle covers the whole tree with\n// O(1) file descriptors. Linux has no recursive fs.watch, so we keep\n// chokidar there.\nconst SUPPORTS_RECURSIVE_WATCH = process.platform === 'darwin' || process.platform === 'win32';\n\nfunction logWatchError(err: unknown): void {\n report('warn', `[watcher] fs error: ${(err as Error).message}`);\n}\n\n/**\n * Debounced recursive watcher over one-or-more repo roots, filtering out\n * `.git/`, `node_modules/`, and build output. Shared between `wd` (the diff\n * server's reload trigger) and any other live file-watcher need.\n *\n * On macOS/Windows this uses one recursive `fs.watch` per root: O(1) fds no\n * matter how big the tree. chokidar (v4 — no bundled fsevents) instead opens\n * one watch per directory, which on a large repo exhausts the process's file\n * descriptors and starves the `git` subprocesses the diff server spawns\n * (branch detection then silently returns nothing). Linux keeps chokidar.\n */\nexport function createFsWatcher(opts: FsWatcherOptions): FsWatcher {\n const debounceMs = opts.debounceMs ?? 150;\n let debounceTimer: NodeJS.Timeout | null = null;\n\n const fire = (): void => {\n if (debounceTimer) clearTimeout(debounceTimer);\n debounceTimer = setTimeout(() => {\n debounceTimer = null;\n opts.onChange();\n }, debounceMs);\n };\n\n if (SUPPORTS_RECURSIVE_WATCH) {\n const watchers = opts.roots.map((root) => {\n const w = fs.watch(root, { recursive: true }, (_event, filename) => {\n // `filename` is relative to `root` (and may be null on some events).\n // The single FSEvents handle still reports ignored dirs, so filter\n // here to avoid spurious reloads from node_modules / build churn.\n if (filename && isIgnoredWatchPath([root], path.join(root, filename.toString()))) {\n return;\n }\n fire();\n });\n w.on('error', logWatchError);\n return w;\n });\n return {\n stop() {\n if (debounceTimer) clearTimeout(debounceTimer);\n for (const w of watchers) {\n try {\n w.close();\n } catch {\n /* already closed */\n }\n }\n },\n };\n }\n\n const watcher = loadChokidar().watch(opts.roots, {\n ignored: (filePath) => isIgnoredWatchPath(opts.roots, filePath),\n ignoreInitial: true,\n persistent: true,\n awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 20 },\n });\n watcher.on('all', fire);\n watcher.on('error', logWatchError);\n\n return {\n stop() {\n if (debounceTimer) clearTimeout(debounceTimer);\n watcher.close().catch(() => {\n /* */\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,IAAM,YAAY;AAElB,IAAM,UAAU,IA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eAAO,GAAG,GAAG;AACb;AAAA,MACF;AAAA,IACF;AACA,WAAO,EAAE,OAAO,QAAQ;AAAA,EAC1B,CAAC;AACH;AAEA,IAAM,WAAW,CAAC,GAAW,MAAc;AACzC,QAAM,IAAI,CAAC,MAAcC,MAAK,QAAQ,CAAC,EAAE,MAAMA,MAAK,GAAG,EAAE,KAAK,GAAG,EAAE,YAAY;AAC/E,SAAO,EAAE,CAAC,MAAM,EAAE,CAAC;AACrB;AAUA,eAAsB,+BAA+B,QAAgB,YAAoB,UAAqC;AAC5H,QAAM,SAAS,YAAY,EAAE;AAAA,IAC3B,CAAC,MAAM,EAAE,WAAW,UAAU,CAAC,EAAE,WAAW,EAAE,WAAW,cAAc,EAAE,MAAM,WAAW,KAAK,SAAS,EAAE,MAAM,CAAC,GAAG,QAAQ;AAAA,EAC9H;AACA,aAAW,KAAK,OAAQ,OAAM,cAAc,EAAE,QAAQ,EAAE,MAAM;AAC9D,SAAO,OAAO,IAAI,CAAC,MAAM,EAAE,MAAM;AACnC;","names":["lastTurnEntryMs","rows","fs","path","zlib","fs","fs","path","path","fs","path","path","fs","valid","path","fs","zlib","fs","path","fs","fs","fs","net","path","path","fs","net","fs","os","path","path","os","fs","path","crypto","fs","path","path","fs","crypto","path","scopes","fs","fs","path"]}