@moberg_hr/work-tree 2.5.2 → 2.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{add-repo-RBMTBP6O.js → add-repo-HWMCMFGJ.js} +6 -6
- package/dist/{answer-F3UX2HBG.js → answer-FSDWYBLR.js} +4 -4
- package/dist/{attach-KHMDFCER.js → attach-T7AA6WAX.js} +6 -6
- package/dist/bin.js +2 -2
- package/dist/{block-7E4ZDM25.js → block-OZRDJ3A6.js} +5 -5
- package/dist/{broadcast-GLP77EJM.js → broadcast-C2YZ4ZKU.js} +2 -2
- package/dist/{catchup-CXMUPFER.js → catchup-53TG4CEQ.js} +7 -7
- package/dist/{chunk-JKF7RCNC.js → chunk-25Y4QGBR.js} +7 -7
- package/dist/{chunk-6XIZZOI7.js → chunk-2UIND4T2.js} +34 -1
- package/dist/chunk-2UIND4T2.js.map +1 -0
- package/dist/{chunk-RHIM3XFW.js → chunk-43D2MJFF.js} +3 -3
- package/dist/{chunk-2KRNE6RT.js → chunk-4L4DSECT.js} +2 -2
- package/dist/{chunk-MQEQHOC5.js → chunk-4NAQH5Y7.js} +3 -3
- package/dist/{chunk-UYVRWYCA.js → chunk-5SDEJIX2.js} +2 -2
- package/dist/{chunk-EYUIMTJH.js → chunk-632GRPPZ.js} +2 -2
- package/dist/{chunk-CRBDPAIQ.js → chunk-A64PX3KG.js} +2 -2
- package/dist/{chunk-QEKB6FNC.js → chunk-BF7GCHOR.js} +3 -3
- package/dist/{chunk-HMC2LMMX.js → chunk-BHQ4I4OC.js} +4 -4
- package/dist/{chunk-33U5IQOI.js → chunk-BSST3WH4.js} +2 -2
- package/dist/{chunk-46JCEDH5.js → chunk-CJT4I5L4.js} +47 -47
- package/dist/{chunk-OHJQZKSC.js → chunk-D27KRAYW.js} +3 -3
- package/dist/{chunk-EZJPXUHP.js → chunk-EVMUXUOC.js} +2 -2
- package/dist/{chunk-N2FSEPBV.js → chunk-G3IDKLUT.js} +3 -3
- package/dist/{chunk-ZMNTOJWM.js → chunk-GI32Q6NP.js} +2 -2
- package/dist/{chunk-YNQCIFMB.js → chunk-J6EFEMWE.js} +3 -3
- package/dist/{chunk-RWK4LPHT.js → chunk-K7LJG7OZ.js} +3 -3
- package/dist/{chunk-6FGA2WAC.js → chunk-KCNOEXAQ.js} +2 -2
- package/dist/{chunk-RYIOZCQB.js → chunk-M536QKOX.js} +2 -2
- package/dist/{chunk-VRH7LCYI.js → chunk-N7HVMU2V.js} +3 -3
- package/dist/{chunk-3KY5DQNN.js → chunk-PKUL7SCY.js} +5 -5
- package/dist/{chunk-JF7JPZO3.js → chunk-Q2QTHA54.js} +5 -5
- package/dist/{chunk-ACCE2R4E.js → chunk-SJOZIX5I.js} +2 -2
- package/dist/{chunk-X5O4ZTJD.js → chunk-SOS7D7F6.js} +2 -2
- package/dist/{chunk-EXWT2GMU.js → chunk-UNSDMOHY.js} +12 -5
- package/dist/chunk-UNSDMOHY.js.map +1 -0
- package/dist/chunk-UQVVDKBN.js +9 -0
- package/dist/{chunk-6CYOBKDM.js → chunk-V5PBMTU3.js} +4 -4
- package/dist/{chunk-CJ4HHRQS.js → chunk-WATUEO7H.js} +7 -3
- package/dist/chunk-WATUEO7H.js.map +1 -0
- package/dist/{chunk-MYXVINU4.js → chunk-WMEIUOPN.js} +2 -2
- package/dist/{chunk-MXWO7BAC.js → chunk-ZO2JCDGT.js} +2 -2
- package/dist/{cleanup-5GFWXIUV.js → cleanup-GKKGP3U5.js} +12 -12
- package/dist/{cli-IOFENVTB.js → cli-STUBHZRX.js} +3 -3
- package/dist/{config-2RY25Q4P.js → config-BVIHSFYF.js} +3 -3
- package/dist/{diff-VU3FHCIH.js → diff-AFVD6WR3.js} +4 -4
- package/dist/{digest-TO32RKKS.js → digest-HRRWNJTR.js} +4 -4
- package/dist/{fork-IDEEYEAF.js → fork-F5RRXKCA.js} +12 -12
- package/dist/{history-VQ42JP7C.js → history-HDWU3CW2.js} +2 -2
- package/dist/{hook-JWJU7IFD.js → hook-WMRFRQZG.js} +4 -4
- package/dist/{hydrate-X2PK7ODX.js → hydrate-V2T5SWFR.js} +2 -2
- package/dist/{init-RMWCV47V.js → init-CZNNIVIO.js} +3 -3
- package/dist/{list-XVNG6CJB.js → list-GY4JJHOS.js} +2 -2
- package/dist/{move-LRAZS525.js → move-KYVWNLKP.js} +4 -4
- package/dist/{note-JGT6BFS6.js → note-VU7E44FB.js} +4 -4
- package/dist/{overlaps-3GISSP2T.js → overlaps-ZJBBDJSU.js} +4 -4
- package/dist/{pin-TEIIQEWS.js → pin-J4MPUKGY.js} +4 -4
- package/dist/{pr-EYRXNH6P.js → pr-Y4PFJT55.js} +3 -3
- package/dist/{prune-MIZ66ODS.js → prune-LKRNGOUS.js} +11 -11
- package/dist/{pty-host-PLARLHEB.js → pty-host-T45N4MSW.js} +2 -2
- package/dist/{read-2XP5GI3S.js → read-66WKTM7U.js} +4 -4
- package/dist/{recent-YRWT47JZ.js → recent-TGPYAY7F.js} +2 -2
- package/dist/{remove-K2FPMDIV.js → remove-LHVAPOIE.js} +10 -10
- package/dist/{restart-ZZYYLLMD.js → restart-GSX47NM7.js} +4 -4
- package/dist/{resume-SWTAMXTT.js → resume-QAWLWAYN.js} +2 -2
- package/dist/{run-B5YQ35U7.js → run-7D3ZLDIN.js} +2 -2
- package/dist/{screen-WD2B6YB7.js → screen-5Q346GJT.js} +4 -4
- package/dist/{search-WNJJQDXY.js → search-SSUQKWBC.js} +2 -2
- package/dist/{section-TDALOAKC.js → section-R5JMKEBL.js} +4 -4
- package/dist/{send-ZA4TO5DI.js → send-BCEJDM6P.js} +5 -5
- package/dist/{sessions-TACGEEVJ.js → sessions-4KSO7G74.js} +9 -9
- package/dist/{snooze-ATH7M3XX.js → snooze-KORWOSM4.js} +4 -4
- package/dist/{start-YL5CKGZW.js → start-DYBIQOEE.js} +4 -4
- package/dist/{status-7HACAHEV.js → status-QLFZC2GG.js} +2 -2
- package/dist/{stop-S5DRHSIA.js → stop-EJX3MG7J.js} +4 -4
- package/dist/{sync-3VL66YBR.js → sync-PMUKXPZ3.js} +11 -11
- package/dist/{time-5V467WTN.js → time-2R4XS5E6.js} +5 -5
- package/dist/{timesheet-FUD57KB6.js → timesheet-FP54TJI5.js} +6 -6
- package/dist/{tree-F6ARJ2RJ.js → tree-5B6REQ56.js} +7 -7
- package/dist/{update-VYEVKXR4.js → update-W6OVJBFF.js} +6 -6
- package/dist/{wait-UCB6X5CY.js → wait-RC4N64TA.js} +5 -5
- package/dist/wd-bin.js +2 -2
- package/dist/web/assets/{PtyView-C8-aiRvb.js → PtyView-Dpl0gAY_.js} +2 -2
- package/dist/web/assets/{PtyView-C8-aiRvb.js.map → PtyView-Dpl0gAY_.js.map} +1 -1
- package/dist/web/assets/index-CrOWH9qL.css +1 -0
- package/dist/web/assets/index-o-4LSx5J.js +119 -0
- package/dist/web/assets/index-o-4LSx5J.js.map +1 -0
- package/dist/web/index.html +2 -2
- package/dist/{web-SV6RI7GM.js → web-SPDJQF2J.js} +71 -62
- package/dist/web-SPDJQF2J.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/chunk-6XIZZOI7.js.map +0 -1
- package/dist/chunk-CJ4HHRQS.js.map +0 -1
- package/dist/chunk-EXWT2GMU.js.map +0 -1
- package/dist/chunk-PNKJAWGI.js +0 -9
- package/dist/web/assets/index-DJsQqbOo.js +0 -119
- package/dist/web/assets/index-DJsQqbOo.js.map +0 -1
- package/dist/web/assets/index-IElqPCQj.css +0 -1
- package/dist/web-SV6RI7GM.js.map +0 -1
- /package/dist/{add-repo-RBMTBP6O.js.map → add-repo-HWMCMFGJ.js.map} +0 -0
- /package/dist/{answer-F3UX2HBG.js.map → answer-FSDWYBLR.js.map} +0 -0
- /package/dist/{attach-KHMDFCER.js.map → attach-T7AA6WAX.js.map} +0 -0
- /package/dist/{block-7E4ZDM25.js.map → block-OZRDJ3A6.js.map} +0 -0
- /package/dist/{broadcast-GLP77EJM.js.map → broadcast-C2YZ4ZKU.js.map} +0 -0
- /package/dist/{catchup-CXMUPFER.js.map → catchup-53TG4CEQ.js.map} +0 -0
- /package/dist/{chunk-JKF7RCNC.js.map → chunk-25Y4QGBR.js.map} +0 -0
- /package/dist/{chunk-RHIM3XFW.js.map → chunk-43D2MJFF.js.map} +0 -0
- /package/dist/{chunk-2KRNE6RT.js.map → chunk-4L4DSECT.js.map} +0 -0
- /package/dist/{chunk-MQEQHOC5.js.map → chunk-4NAQH5Y7.js.map} +0 -0
- /package/dist/{chunk-UYVRWYCA.js.map → chunk-5SDEJIX2.js.map} +0 -0
- /package/dist/{chunk-EYUIMTJH.js.map → chunk-632GRPPZ.js.map} +0 -0
- /package/dist/{chunk-CRBDPAIQ.js.map → chunk-A64PX3KG.js.map} +0 -0
- /package/dist/{chunk-QEKB6FNC.js.map → chunk-BF7GCHOR.js.map} +0 -0
- /package/dist/{chunk-HMC2LMMX.js.map → chunk-BHQ4I4OC.js.map} +0 -0
- /package/dist/{chunk-33U5IQOI.js.map → chunk-BSST3WH4.js.map} +0 -0
- /package/dist/{chunk-46JCEDH5.js.map → chunk-CJT4I5L4.js.map} +0 -0
- /package/dist/{chunk-OHJQZKSC.js.map → chunk-D27KRAYW.js.map} +0 -0
- /package/dist/{chunk-EZJPXUHP.js.map → chunk-EVMUXUOC.js.map} +0 -0
- /package/dist/{chunk-N2FSEPBV.js.map → chunk-G3IDKLUT.js.map} +0 -0
- /package/dist/{chunk-ZMNTOJWM.js.map → chunk-GI32Q6NP.js.map} +0 -0
- /package/dist/{chunk-YNQCIFMB.js.map → chunk-J6EFEMWE.js.map} +0 -0
- /package/dist/{chunk-RWK4LPHT.js.map → chunk-K7LJG7OZ.js.map} +0 -0
- /package/dist/{chunk-6FGA2WAC.js.map → chunk-KCNOEXAQ.js.map} +0 -0
- /package/dist/{chunk-RYIOZCQB.js.map → chunk-M536QKOX.js.map} +0 -0
- /package/dist/{chunk-VRH7LCYI.js.map → chunk-N7HVMU2V.js.map} +0 -0
- /package/dist/{chunk-3KY5DQNN.js.map → chunk-PKUL7SCY.js.map} +0 -0
- /package/dist/{chunk-JF7JPZO3.js.map → chunk-Q2QTHA54.js.map} +0 -0
- /package/dist/{chunk-ACCE2R4E.js.map → chunk-SJOZIX5I.js.map} +0 -0
- /package/dist/{chunk-X5O4ZTJD.js.map → chunk-SOS7D7F6.js.map} +0 -0
- /package/dist/{chunk-PNKJAWGI.js.map → chunk-UQVVDKBN.js.map} +0 -0
- /package/dist/{chunk-6CYOBKDM.js.map → chunk-V5PBMTU3.js.map} +0 -0
- /package/dist/{chunk-MYXVINU4.js.map → chunk-WMEIUOPN.js.map} +0 -0
- /package/dist/{chunk-MXWO7BAC.js.map → chunk-ZO2JCDGT.js.map} +0 -0
- /package/dist/{cleanup-5GFWXIUV.js.map → cleanup-GKKGP3U5.js.map} +0 -0
- /package/dist/{cli-IOFENVTB.js.map → cli-STUBHZRX.js.map} +0 -0
- /package/dist/{config-2RY25Q4P.js.map → config-BVIHSFYF.js.map} +0 -0
- /package/dist/{diff-VU3FHCIH.js.map → diff-AFVD6WR3.js.map} +0 -0
- /package/dist/{digest-TO32RKKS.js.map → digest-HRRWNJTR.js.map} +0 -0
- /package/dist/{fork-IDEEYEAF.js.map → fork-F5RRXKCA.js.map} +0 -0
- /package/dist/{history-VQ42JP7C.js.map → history-HDWU3CW2.js.map} +0 -0
- /package/dist/{hook-JWJU7IFD.js.map → hook-WMRFRQZG.js.map} +0 -0
- /package/dist/{hydrate-X2PK7ODX.js.map → hydrate-V2T5SWFR.js.map} +0 -0
- /package/dist/{init-RMWCV47V.js.map → init-CZNNIVIO.js.map} +0 -0
- /package/dist/{list-XVNG6CJB.js.map → list-GY4JJHOS.js.map} +0 -0
- /package/dist/{move-LRAZS525.js.map → move-KYVWNLKP.js.map} +0 -0
- /package/dist/{note-JGT6BFS6.js.map → note-VU7E44FB.js.map} +0 -0
- /package/dist/{overlaps-3GISSP2T.js.map → overlaps-ZJBBDJSU.js.map} +0 -0
- /package/dist/{pin-TEIIQEWS.js.map → pin-J4MPUKGY.js.map} +0 -0
- /package/dist/{pr-EYRXNH6P.js.map → pr-Y4PFJT55.js.map} +0 -0
- /package/dist/{prune-MIZ66ODS.js.map → prune-LKRNGOUS.js.map} +0 -0
- /package/dist/{pty-host-PLARLHEB.js.map → pty-host-T45N4MSW.js.map} +0 -0
- /package/dist/{read-2XP5GI3S.js.map → read-66WKTM7U.js.map} +0 -0
- /package/dist/{recent-YRWT47JZ.js.map → recent-TGPYAY7F.js.map} +0 -0
- /package/dist/{remove-K2FPMDIV.js.map → remove-LHVAPOIE.js.map} +0 -0
- /package/dist/{restart-ZZYYLLMD.js.map → restart-GSX47NM7.js.map} +0 -0
- /package/dist/{resume-SWTAMXTT.js.map → resume-QAWLWAYN.js.map} +0 -0
- /package/dist/{run-B5YQ35U7.js.map → run-7D3ZLDIN.js.map} +0 -0
- /package/dist/{screen-WD2B6YB7.js.map → screen-5Q346GJT.js.map} +0 -0
- /package/dist/{search-WNJJQDXY.js.map → search-SSUQKWBC.js.map} +0 -0
- /package/dist/{section-TDALOAKC.js.map → section-R5JMKEBL.js.map} +0 -0
- /package/dist/{send-ZA4TO5DI.js.map → send-BCEJDM6P.js.map} +0 -0
- /package/dist/{sessions-TACGEEVJ.js.map → sessions-4KSO7G74.js.map} +0 -0
- /package/dist/{snooze-ATH7M3XX.js.map → snooze-KORWOSM4.js.map} +0 -0
- /package/dist/{start-YL5CKGZW.js.map → start-DYBIQOEE.js.map} +0 -0
- /package/dist/{status-7HACAHEV.js.map → status-QLFZC2GG.js.map} +0 -0
- /package/dist/{stop-S5DRHSIA.js.map → stop-EJX3MG7J.js.map} +0 -0
- /package/dist/{sync-3VL66YBR.js.map → sync-PMUKXPZ3.js.map} +0 -0
- /package/dist/{time-5V467WTN.js.map → time-2R4XS5E6.js.map} +0 -0
- /package/dist/{timesheet-FUD57KB6.js.map → timesheet-FP54TJI5.js.map} +0 -0
- /package/dist/{tree-F6ARJ2RJ.js.map → tree-5B6REQ56.js.map} +0 -0
- /package/dist/{update-VYEVKXR4.js.map → update-W6OVJBFF.js.map} +0 -0
- /package/dist/{wait-UCB6X5CY.js.map → wait-RC4N64TA.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/sessions/history.ts","../src/core/sessions/session-activity.ts","../src/core/worktree/port-allocator.ts","../src/core/sessions/session-store.ts","../src/core/api-types.ts","../src/core/archive/session-archive.ts","../src/core/archive/archive-uncommitted.ts","../src/core/diff/git-tree-snapshot.ts","../src/core/platform/best-effort.ts","../src/core/pr/pr-stage.ts","../src/core/rail/snooze.ts","../src/core/status/attention.ts","../src/core/status/session-status.ts","../src/core/rail/snooze-store.ts","../src/core/archive/archiving.ts","../src/core/conversations/work-time.ts","../src/core/conversations/digest.ts","../src/core/conversations/conversation-store.ts","../src/core/archive/archive-search.ts","../src/core/worktree/dev-server.ts","../src/core/sessions/session-repos.ts","../src/core/diff/checkpoint.ts","../src/core/diff/scope-manager.ts","../src/core/platform/fs-watcher.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { WorkConfig } from '../platform/config.js';\nimport { getConfigDir, loadConfig } from '../platform/config.js';\nimport { 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 { SessionInstructions, WorktreeSession } from './session-types.js';\nimport { recordedRepos, sessionRepos } from './session-repos.js';\n\n/**\n * Worktree sessions, in the `sessions` table of ~/.work/state.db (db.ts):\n * one row per target:branch, the record as JSON. Writes are transactions,\n * so concurrent `work tree` / `remove` / work web can't clobber each other\n * (the old history.json needed a file lock for that — and once lost 60+\n * sessions without it).\n */\n\n/** The pre-SQLite history file. Only the one-time import (db-import.ts)\n * reads it now. */\nexport function getHistoryPath(): string {\n return path.join(getConfigDir(), 'history.json');\n}\n\nfunction valid(s: unknown): s is WorktreeSession {\n const x = s as WorktreeSession | null;\n return !!x && typeof x.target === 'string' && typeof x.branch === 'string' && Array.isArray(x.paths);\n}\n\nfunction rows(d: Db): WorktreeSession[] {\n return (d.prepare('SELECT data FROM sessions ORDER BY rowid').all() as Array<{ data: string }>)\n .map((r) => json.parse(r.data))\n .filter(valid);\n}\n\nfunction getRow(d: Db, target: string, branch: string): WorktreeSession | undefined {\n const r = d.prepare('SELECT data FROM sessions WHERE id = ?').get(sessionIdFor({ target, branch })) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return valid(s) ? s : undefined;\n}\n\nfunction putRow(d: Db, s: WorktreeSession): void {\n d.prepare(\n 'INSERT INTO sessions (id, target, branch, data) VALUES (?, ?, ?, ?) ' + 'ON CONFLICT(id) DO UPDATE SET data = excluded.data',\n ).run(sessionIdFor(s), s.target, s.branch, JSON.stringify(s));\n}\n\n/**\n * A repo added to a session (add-repo.ts): its worktree appended to the\n * session's paths, its alias to its repos (a row from before gets its list\n * recorded first, as derived), and its base — in one transaction over the row\n * as it is now. `before` is the paths it had, read in that transaction (the\n * scope its turns move from). Already there: unchanged. Null when the session\n * is gone. Throws, writing nothing, when a folder of a row from before can't\n * be matched to a repo of its group (it would be recorded under a made-up alias).\n *\n * The base: one `baseBranch` stands for every repo only when every repo has it\n * (as a group's is recorded). An added repo made from it keeps that; one made\n * from another, or checked out on a branch it had (no base known), gets its own\n * entry or none, and the others keep theirs — each in `baseBranches`.\n */\nexport function appendSessionRepo(\n id: string,\n alias: string,\n worktree: string,\n from: string | undefined,\n config: WorkConfig,\n /** Its folder's file gets the repo's import (an agent that can import): recorded on the\n * session when it has no mode yet — a group's copied summary keeps it, the block after it. */\n imports = false,\n): { before: string[]; session: WorktreeSession } | null {\n return tx((d) => {\n const r = d.prepare('SELECT data FROM sessions WHERE id = ?').get(id) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n if (!valid(s)) return null;\n const own = sessionRepos(s, config);\n const unknown = own.filter((x) => x.guessed).map((x) => path.basename(x.path));\n if (unknown.length) throw new Error(`no repo of its group is in ${unknown.join(', ')}, so its repos can't be recorded`);\n const repos = own.map((x) => x.alias);\n const before = [...s.paths];\n if (repos.includes(alias)) return { before, session: s };\n if (s.baseBranch && from !== s.baseBranch) {\n const perRepo = { ...(s.baseBranches ?? {}) };\n for (const p of s.paths) perRepo[p] ??= s.baseBranch;\n s.baseBranches = perRepo;\n delete s.baseBranch;\n }\n s.paths = [...s.paths, worktree];\n s.repos = [...repos, alias];\n if (imports && !s.instructions) s.instructions = config.groups?.[s.target] ? 'summary+imports' : 'imports';\n if (from) s.baseBranches = { ...(s.baseBranches ?? {}), [worktree]: from };\n putRow(d, s);\n return { before, session: s };\n });\n}\n\n/** One session by its id (the `sessions` primary key). */\nexport function findSessionById(id: string): WorktreeSession | null {\n return withDb((d) => {\n const r = d.prepare('SELECT data FROM sessions WHERE id = ?').get(id) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return valid(s) ? s : null;\n });\n}\n\n/** Every session, in the order they were first recorded. */\nexport function loadHistory(): WorktreeSession[] {\n return withDb(rows);\n}\n\n/** Replace the whole history (bulk rewrites, tests). */\nexport function saveHistory(sessions: WorktreeSession[]): void {\n tx((d) => {\n d.prepare('DELETE FROM sessions').run();\n const seen = new Set<string>();\n for (const s of sessions) {\n if (!valid(s)) continue;\n const id = sessionIdFor(s);\n if (seen.has(id)) continue; // first entry wins, as findSession does\n seen.add(id);\n putRow(d, s);\n }\n });\n}\n\nfunction sessionKey(target: string, branch: string): string {\n return `${target}:${branch}`;\n}\n\nexport function findSession(sessions: WorktreeSession[], target: string, branch: string): WorktreeSession | undefined {\n return sessions.find((s) => s.target === target && s.branch === branch);\n}\n\n/**\n * A session's folders as a writer gives them (`paths`, and `repos` when it knows\n * them), over the row as it is NOW (inside the writer's transaction). A row that\n * records its repos never loses one the writer didn't know of — a repo added to\n * it (add-repo.ts) after the writer read the row, seconds of git work earlier —:\n * those pairs are kept, after the writer's. A row from before (no list) takes\n * what it's given, as it always did. Mutates `existing`.\n */\nexport function setOwnRepos(existing: WorktreeSession, paths: string[], repos?: string[]): void {\n const recorded = recordedRepos(existing);\n if (!recorded) {\n existing.paths = paths;\n if (repos) existing.repos = [...repos];\n return;\n }\n // The writer's pairs: its own list, else (it knows only the folders) the recorded aliases by place.\n const given =\n repos && repos.length === paths.length\n ? repos.map((alias, i) => ({ alias, path: paths[i] }))\n : paths.length === recorded.length\n ? recorded.map((r, i) => ({ alias: r.alias, path: paths[i] }))\n : recorded;\n const kept = recorded.filter((r) => !given.some((g) => g.alias === r.alias));\n const all = [...given, ...kept];\n existing.paths = all.map((r) => r.path);\n existing.repos = all.map((r) => r.alias);\n}\n\n/**\n * Coming back to a session without changing what it holds (`work resume`,\n * `work recent`): its last access, and un-archived, in one write over the row\n * as it is now — never a copy of its folders read before a picker waited on you.\n */\nexport function touchSession(target: string, branch: string): void {\n tx((d) => {\n const s = getRow(d, target, branch);\n if (!s) return;\n s.lastAccessedAt = new Date().toISOString();\n delete s.archivedAt;\n putRow(d, s);\n });\n}\n\nexport async function upsertSession(\n target: string,\n isGroup: boolean,\n branch: string,\n paths: string[],\n jiraKey?: string,\n baseBranch?: string,\n port?: number,\n /** The repo alias of each of `paths` (WorktreeSession.repos); omitted keeps what the row has. */\n repos?: string[],\n): Promise<void> {\n tx((d) => {\n const existing = getRow(d, target, branch);\n const now = new Date().toISOString();\n\n if (existing) {\n setOwnRepos(existing, paths, repos);\n existing.lastAccessedAt = now;\n delete existing.archivedAt; // coming back to it un-archives it\n if (jiraKey) existing.jiraKey = jiraKey;\n if (baseBranch && !existing.baseBranch) existing.baseBranch = baseBranch;\n if (port !== undefined) existing.port = port;\n putRow(d, existing);\n } else {\n const session: WorktreeSession = {\n target,\n isGroup,\n branch,\n paths,\n createdAt: now,\n lastAccessedAt: now,\n ...recordAgent(),\n };\n if (jiraKey) session.jiraKey = jiraKey;\n if (baseBranch) session.baseBranch = baseBranch;\n if (port !== undefined) session.port = port;\n if (repos) session.repos = [...repos];\n putRow(d, session);\n }\n });\n}\n\n/**\n * Allocate a stable dev-server port AND persist the session, without two\n * concurrent `work tree` runs picking the same port.\n *\n * Allocation probes ports (async) and a transaction can't span an await,\n * so it is optimistic: pick a port against a snapshot, then in one write\n * transaction re-check that no other live session took it meanwhile — and\n * if one did, pick again.\n *\n * Port allocation is best-effort: if it fails (range exhausted, etc.) the\n * session is still persisted, just without a port, and `port` comes back\n * undefined. An already-allocated port on an existing session is preserved\n * (idempotent re-runs keep their port).\n *\n * The allocation seed is `target:branch` (unique per worktree) so two repos\n * that share a branch name don't collide on the same deterministic base offset.\n */\nexport async function upsertSessionWithPort(\n target: string,\n isGroup: boolean,\n branch: string,\n paths: string[],\n config: Pick<WorkConfig, 'portRange'>,\n jiraKey?: string,\n baseBranch?: string,\n baseBranches?: Record<string, string>,\n /** What the session owns: the repo alias of each of `paths` (WorktreeSession.repos) and how\n * its instructions file is made (`instructions`). Each omitted keeps what the row has. */\n own: { repos?: string[]; instructions?: SessionInstructions } = {},\n): Promise<{ port?: number }> {\n const { repos, instructions } = own;\n const hasPerRepo = baseBranches && Object.keys(baseBranches).length > 0;\n const id = sessionIdFor({ target, branch });\n\n const write = (d: Db, port: number | undefined): number | undefined => {\n const existing = getRow(d, target, branch);\n const now = new Date().toISOString();\n if (existing) {\n setOwnRepos(existing, paths, repos);\n existing.lastAccessedAt = now;\n delete existing.archivedAt; // coming back to it un-archives it\n if (jiraKey) existing.jiraKey = jiraKey;\n if (baseBranch && !existing.baseBranch) existing.baseBranch = baseBranch;\n if (hasPerRepo && !existing.baseBranches) existing.baseBranches = baseBranches;\n if (existing.port === undefined && port !== undefined) existing.port = port;\n if (instructions) existing.instructions = instructions;\n putRow(d, existing);\n return existing.port;\n }\n const session: WorktreeSession = { target, isGroup, branch, paths, createdAt: now, lastAccessedAt: now, ...recordAgent() };\n if (jiraKey) session.jiraKey = jiraKey;\n if (baseBranch) session.baseBranch = baseBranch;\n if (hasPerRepo) session.baseBranches = baseBranches;\n if (port !== undefined) session.port = port;\n if (repos) session.repos = [...repos];\n if (instructions) session.instructions = instructions;\n putRow(d, session);\n return port;\n };\n\n for (let attempt = 0; attempt < 5; attempt++) {\n const sessions = loadHistory();\n const existing = findSession(sessions, target, branch);\n let port = existing?.port;\n if (port === undefined) {\n try {\n port = await allocateFreePort(sessionKey(target, branch), config, sessions);\n } catch {\n port = undefined;\n }\n }\n const done = tx((d) => {\n // Another `work tree` may have taken this port since the snapshot:\n // only a port no other live session holds may be kept.\n if (port !== undefined && getRow(d, target, branch)?.port === undefined) {\n const taken = rows(d).some((s) => sessionIdFor(s) !== id && s.port === port && s.paths.some((p) => fs.existsSync(p)));\n if (taken) return null;\n }\n return { port: write(d, port) };\n });\n if (done) return done;\n }\n // Could not get an uncontested port: record the session without one.\n return tx((d) => ({ port: write(d, undefined) }));\n}\n\n/** 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 * A session that records its repos (`repos`) owns its list: its paths keep\n * their order and none is dropped; a folder found on disk that it lacks is\n * added at the end, with its repo.\n */\nexport async function mergeHydratedSessions(incoming: WorktreeSession[]): Promise<{ added: number; updated: number }> {\n return tx((d) => {\n let added = 0;\n let updated = 0;\n\n for (const inc of incoming) {\n const existing = getRow(d, inc.target, inc.branch);\n const own = existing ? recordedRepos(existing) : null;\n if (existing && own) {\n const extra = inc.paths\n .map((p, i) => ({ path: p, alias: inc.repos?.[i] }))\n .filter((x) => !own.some((r) => samePath(r.path, x.path)));\n // Without its repo a new folder can't be recorded beside the others: the list stays as it is.\n if (extra.length && extra.every((x) => typeof x.alias === 'string')) {\n existing.paths = [...existing.paths, ...extra.map((x) => x.path)];\n existing.repos = [...own.map((r) => r.alias), ...extra.map((x) => x.alias as string)];\n putRow(d, existing);\n updated++;\n }\n } else if (existing) {\n const sortedA = [...existing.paths].sort();\n const sortedB = [...inc.paths].sort();\n const same = sortedA.length === sortedB.length && sortedA.every((p, i) => p === sortedB[i]);\n if (!same) {\n existing.paths = inc.paths;\n putRow(d, existing);\n updated++;\n }\n } else {\n putRow(d, inc);\n added++;\n }\n }\n return { added, updated };\n });\n}\n\nconst samePath = (a: string, b: string) => {\n const n = (p: string) => path.resolve(p).split(path.sep).join('/').toLowerCase();\n return n(a) === n(b);\n};\n\n/**\n * A base checkout (`work tree <target>` with no branch) is recorded under the\n * branch it had checked out at the time. Run it again after switching that\n * checkout to another branch and a second entry appeared for the SAME folder\n * — then a third… — each showing the folder's activity as its own (three\n * \"Active\" rows for one busy checkout). Keep one: the entry just recorded.\n * Returns the branches of the entries removed.\n */\nexport async function forgetOtherBaseCheckoutEntries(target: string, keepBranch: string, repoPath: string): Promise<string[]> {\n const others = loadHistory().filter(\n (s) => s.target === target && !s.isGroup && s.branch !== keepBranch && s.paths.length === 1 && samePath(s.paths[0], repoPath),\n );\n for (const s of others) await removeSession(s.target, s.branch);\n return others.map((s) => s.branch);\n}\n","import { agentOf } from '../agents/index.js';\nimport type { ActivityState } from '../api-types.js';\nimport type { WorktreeSession } from './session-types.js';\n\n/**\n * How recently a session's agent wrote: the newest of its conversation files\n * (agents/: `conversation.files`). Works however the agent was started — by\n * `work tree`, `work attach`, a plain terminal or the PTY host — since they\n * all write the same files. An agent work can't read gives no activity (the\n * other signals — hooks, the PTY host's output — still do).\n */\n\n/** Active: it wrote in the last 30 s — mid-turn. */\nconst ACTIVE_MS = 30_000;\n/** Open: it wrote within 5 min — likely still at its prompt. After that, stale. */\nconst OPEN_MS = 5 * 60_000;\n\nexport interface SessionActivity {\n /** ms since epoch of its newest conversation write, or null when there is none. */\n lastActivity: number | null;\n state: ActivityState;\n}\n\n/** The newest write to any of the session's conversation files, ms (0: none). */\nexport function lastConversationWriteMs(session: WorktreeSession): number {\n let latest = 0;\n for (const f of agentOf(session).conversation?.files(session) ?? []) if (f.mtimeMs > latest) latest = f.mtimeMs;\n return latest;\n}\n\nexport function readSessionActivity(session: WorktreeSession, now = Date.now()): SessionActivity {\n const latest = lastConversationWriteMs(session);\n if (latest === 0) return { lastActivity: null, state: 'stale' };\n const age = now - latest;\n return { lastActivity: latest, state: age <= ACTIVE_MS ? 'active' : age <= OPEN_MS ? 'open' : 'stale' };\n}\n\n/**\n * True when an agent wrote within `windowMs` of `nowMs` (0: never). The\n * scope auto-snapshot timer uses it to stay out of the way while an agent is\n * at work (its turn-end hook owns checkpoints then); the timer only fires for\n * hand edits when none is.\n */\nexport function activeWithin(activityMs: number, nowMs: number, windowMs: number): boolean {\n return activityMs > 0 && nowMs - activityMs < windowMs;\n}\n\n/** When it was last used: the newer of its recorded entry and its agent's last write. */\nexport function effectiveLastAccessedAt(session: WorktreeSession): string {\n const recorded = Date.parse(session.lastAccessedAt);\n return new Date(Math.max(Number.isFinite(recorded) ? recorded : 0, lastConversationWriteMs(session))).toISOString();\n}\n","import fs from 'node:fs';\nimport net from 'node:net';\nimport type { WorkConfig } from '../platform/config.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\n\n/** Default dev-server port range when none is configured. */\nexport const DEFAULT_PORT_RANGE = { start: 3000, end: 3099 };\n\n/**\n * Thrown when every port in the configured range is occupied. Distinct class so\n * callers can tell \"range exhausted\" apart from any other allocation failure.\n */\nexport class PortRangeExhaustedError extends Error {\n readonly start: number;\n readonly end: number;\n constructor(start: number, end: number) {\n super(\n `No free dev-server port available in range ${start}-${end} ` +\n `(all ${end - start + 1} in use). Widen \"portRange\" in ~/.work/config.json.`,\n );\n this.name = 'PortRangeExhaustedError';\n this.start = start;\n this.end = end;\n }\n}\n\n/**\n * Deterministic, stable string hash (FNV-1a 32-bit). Same input always yields\n * the same non-negative integer, so a worktree's seed key maps to the same base\n * offset across processes and machines.\n */\nfunction hashString(input: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\nfunction normalizeRange(config: Pick<WorkConfig, 'portRange'>): {\n start: number;\n end: number;\n rangeSize: number;\n} {\n const range = config.portRange ?? DEFAULT_PORT_RANGE;\n const start = Math.min(range.start, range.end);\n const end = Math.max(range.start, range.end);\n const rangeSize = end - start + 1;\n if (rangeSize <= 0) {\n throw new Error(`Invalid port range: ${range.start}-${range.end}`);\n }\n return { start, end, rangeSize };\n}\n\nfunction portsHeldByActiveSessions(sessions: WorktreeSession[]): Set<number> {\n const inUse = new Set<number>();\n for (const session of sessions) {\n if (session.port === undefined) continue;\n const active = session.paths.some((p) => fs.existsSync(p));\n if (active) inUse.add(session.port);\n }\n return inUse;\n}\n\n/**\n * Allocate a stable dev-server port for a worktree.\n *\n * Pure and testable: the caller passes the current `sessions` array (e.g.\n * `loadHistory()`) rather than this function reading state itself.\n *\n * - The range comes from `config.portRange` (falling back to 3000–3099).\n * - A deterministic base offset is derived from `hash(seedKey) % rangeSize`,\n * so the same worktree prefers the same port. The seed key MUST be unique per\n * worktree (e.g. `target:branch` or the full worktree path) — using only a\n * branch name would let two repos sharing a branch collide deterministically.\n * - Ports already held by *active* sessions (at least one path still exists)\n * are considered in use and skipped.\n * - Walks forward from the base offset (wrapping around the range) to the first\n * free port. Throws `PortRangeExhaustedError` if every port is occupied.\n *\n * NOTE: this checks only our own history, not host liveness. Use\n * `allocateFreePort` when you also want to skip ports occupied by unrelated\n * processes on the machine.\n */\nexport function allocatePort(seedKey: string, config: Pick<WorkConfig, 'portRange'>, sessions: WorktreeSession[]): number {\n const { start, end, rangeSize } = normalizeRange(config);\n const inUse = portsHeldByActiveSessions(sessions);\n const baseOffset = hashString(seedKey) % rangeSize;\n\n for (let i = 0; i < rangeSize; i++) {\n const candidate = start + ((baseOffset + i) % rangeSize);\n if (!inUse.has(candidate)) {\n return candidate;\n }\n }\n\n throw new PortRangeExhaustedError(start, end);\n}\n\n/**\n * Probe whether a TCP port is free to bind on localhost. Resolves false on\n * EADDRINUSE (something is already listening), true otherwise. Best-effort: any\n * non-EADDRINUSE error resolves true so a quirky host can't block allocation.\n */\nexport function isPortFree(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once('error', (err: NodeJS.ErrnoException) => {\n resolve(err.code !== 'EADDRINUSE');\n });\n server.once('listening', () => {\n server.close(() => resolve(true));\n });\n server.listen(port, '127.0.0.1');\n });\n}\n\n/**\n * Like `allocatePort`, but additionally probes host liveness: candidates that\n * are already bound by some other process on localhost (EADDRINUSE) are skipped\n * even when our history doesn't know about them. This is what actually prevents\n * collisions with non-work processes.\n *\n * Walks the same deterministic order as `allocatePort` and returns the first\n * candidate that is both free in history and bindable on the host. Throws\n * `PortRangeExhaustedError` if every candidate is taken.\n */\nexport async function allocateFreePort(\n seedKey: string,\n config: Pick<WorkConfig, 'portRange'>,\n sessions: WorktreeSession[],\n probe: (port: number) => Promise<boolean> = isPortFree,\n): Promise<number> {\n const { start, end, rangeSize } = normalizeRange(config);\n const inUse = portsHeldByActiveSessions(sessions);\n const baseOffset = hashString(seedKey) % rangeSize;\n\n for (let i = 0; i < rangeSize; i++) {\n const candidate = start + ((baseOffset + i) % rangeSize);\n if (inUse.has(candidate)) continue;\n if (await probe(candidate)) {\n return candidate;\n }\n }\n\n throw new PortRangeExhaustedError(start, end);\n}\n","import fs from 'node:fs';\nimport { archiveDirFor } from '../archive/session-archive.js';\nimport { conversationDirFor } from '../conversations/conversation-store.js';\nimport { sessionIdFor } from './session-id.js';\nimport { purgeSessionRows, tx } from '../platform/db.js';\nimport { logSwallowed } from '../platform/best-effort.js';\nimport { devLogFile, stopDev } from '../worktree/dev-server.js';\nimport { clearCheckpoints } from '../diff/checkpoint.js';\nimport { dropSessionSaves } from '../archive/archive-uncommitted.js';\nimport { scopeHashForPaths } from '../diff/scope-manager.js';\nimport { loadConfig } from '../platform/config.js';\nimport type { WorktreeSession } from './session-types.js';\nimport { sessionAliases } from './session-repos.js';\n\n/**\n * Owner of a session's state beyond its `sessions` row. Everything\n * per-session is keyed by sessionIdFor(target, branch) and lives in\n * state.db (db.ts):\n *\n * session_status attention status (hooks)\n * comments [store=id] review comments\n * comment_deliveries which comments reached Claude\n * pty_sessions restore-after-reboot entry\n * pr_watch_seen PR watch: comments / CI failures acted on\n * dev_runs dev server pid (the server is stopped first)\n *\n * plus one file, ~/.work/dev/<id>.log (the dev server's output).\n *\n * plus its diff scope's checkpoints: refs/wd/<hash>/* in its repos and the\n * manifest, keyed by the hash of its paths (clearSessionCheckpoints) — the\n * refs keep their commits (untracked files `add -A` captured included) from\n * git's garbage collection.\n *\n * § WHEN adding per-session state, add its table to `purgeSessionRows`\n * (db.ts), or its file here — so removing a session removes it. Before\n * this, deleted sessions left their state behind and a re-created session\n * with the same target:branch inherited it.\n */\n\n/** Per-session files that live outside the database. */\nexport function sessionStatePaths(id: string): string[] {\n // Its archive (kept conversation + summary) and work's copy of its\n // conversations go when the session is deleted for good; archiving keeps\n // the session, so they stay then.\n return [devLogFile(id), archiveDirFor(id), conversationDirFor(id)];\n}\n\n/** Before the session's rows go: stop its dev server (needs the dev_runs\n * row). Best-effort, logged. */\nexport function stopSessionDevServer(id: string): void {\n try {\n stopDev(id);\n } catch (err) {\n logSwallowed(`stop dev server ${id}`, err);\n }\n}\n\n/**\n * A removed session's checkpoints: the refs in its repos' shared git dir\n * (from the base checkouts: the worktree may already be gone) and the\n * manifest. Best-effort, logged.\n */\nexport function clearSessionCheckpoints(s: Pick<WorktreeSession, 'target' | 'isGroup' | 'paths' | 'repos'> & { branch?: string }): void {\n try {\n const cfg = loadConfig();\n const aliases = sessionAliases(s, cfg);\n const roots = aliases.map((a) => cfg?.repos[a]).filter((r): r is string => !!r && fs.existsSync(r));\n clearCheckpoints(scopeHashForPaths(s.paths), roots);\n // Uncommitted work an archive saved (archive-uncommitted.ts): its refs go like the checkpoints'.\n if (s.branch !== undefined) for (const r of roots) dropSessionSaves(r, sessionIdFor({ target: s.target, branch: s.branch }));\n } catch (err) {\n logSwallowed(`clear checkpoints of ${s.target}`, err);\n }\n}\n\n/** After the session's rows are gone: its files. Best-effort per file. */\nexport function removeSessionFiles(id: string): void {\n for (const p of sessionStatePaths(id)) {\n try {\n fs.rmSync(p, { force: true, recursive: true });\n } catch (err) {\n logSwallowed(`purge ${p}`, err);\n }\n }\n}\n\n/**\n * Remove every piece of per-session state for a session that has no\n * `sessions` row (any more). history.ts removes a session's row and its\n * state in ONE transaction (`purgeSessionRows`); this is the standalone\n * form for state left behind. Best-effort per step (logged), never throws.\n */\nexport async function purgeSessionState(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch });\n stopSessionDevServer(id);\n try {\n tx((d) => purgeSessionRows(d, id));\n } catch (err) {\n logSwallowed(`purge state rows ${id}`, err);\n }\n removeSessionFiles(id);\n}\n","import type { AttentionLike } from './status/attention.js';\n\n/**\n * Wire types shared by the server (core) and the browser SPA — ONE\n * definition each, so the two can't drift (they did: fields added on one\n * side had to be remembered on the other). Types only, no runtime imports:\n * the SPA imports this file directly (architecture allowlist), so it must\n * never pull in Node.\n */\n\n// ---- session list ---------------------------------------------------------\n\n/** Derived from Claude's last transcript write: ≤30 s active, ≤5 min open. */\nexport type ActivityState = 'active' | 'open' | 'stale';\n\n/** Whether work web's pool knows of a live PTY for the session. */\nexport type PtyStatus = 'running' | 'idle';\n\n/** `+N −M` for a session's working tree vs HEAD, across its repos. */\nexport interface DiffStat {\n added: number;\n deleted: number;\n /** Changed tracked files + untracked files. */\n files: number;\n}\n\n/** The tool call a permission prompt is about (from the transcript). */\nexport interface PermissionRequest {\n /** Tool name as Claude Code calls it (Bash, Edit, WebFetch, mcp__…). */\n tool: string;\n /** What it wants to do: the command, the file, the URL. One line. */\n detail: string;\n}\n\n/** POST /api/sessions/:id/answer — answer the permission prompt shown. */\nexport interface AnswerRequest {\n answer: 'allow' | 'deny';\n /** The request the user was shown; refused if the prompt moved on. */\n request: PermissionRequest;\n}\n\n/** A session's agent on the wire: who, and which of its adapter's capabilities exist (agents/types.ts). */\nexport interface SessionAgentWire {\n /** Its binary name (`claude`). */\n id: string;\n /** How to name it to you (\"Claude Code\"). */\n name: string;\n can: {\n /** Its conversation can be read (context %, digest, search, `work read`…). */\n read: boolean;\n /** Its turns are heard through hooks (working / done / needs input). */\n hooks: boolean;\n /** Its running processes are seen outside work's own terminals. */\n live: boolean;\n /** Its permission prompts can be answered from the dashboard. */\n answer: boolean;\n };\n}\n\n/** Hook-driven agent status as sent to the dashboard (attention inbox). */\nexport interface SessionAttention extends AttentionLike {\n /** One line: prompt while working, last message when done, the\n * permission request when blocked. */\n summary?: string;\n updatedAt: string;\n /** A \"working\" that went quiet for 15 min, shown as idle. */\n stale: boolean;\n /** needs_input on a permission prompt: what it wants to run. */\n request?: PermissionRequest;\n /** Working because a background agent its turn started is still at it: its turn ended, its prompt is free. `what`:\n * the agent's own description (\"/mtk:code-review-and-quality Re-review…\"), when it gives one. Absent: an older server. */\n background?: { what: string | null };\n}\n\n/** Who archived a session: you (Archive, its key, the bulk bar), Ship's merge, the PR watch once its PR merged, or Clean up. */\nexport const ARCHIVED_BY = ['you', 'shipped', 'pr-merged', 'cleanup'] as const;\nexport type ArchivedBy = (typeof ARCHIVED_BY)[number];\n\n/** An archived session: whether its folder went, and what it was about. */\nexport interface SessionArchiveInfo {\n /** Who archived it (none: archived before work recorded it). */\n by?: ArchivedBy;\n worktreeRemoved: boolean;\n keptBecause: string | null;\n promptCount: number;\n /** Its prompts (first and latest), for recall and search. */\n prompts: string[];\n lastSummary: string | null;\n /** What was done and why, written after archiving (null until then). */\n written?: string | null;\n /** Build output cleared from its kept worktree. */\n buildFolders?: { folders: number; bytes: number };\n /** Uncommitted files saved when its worktree was removed, waiting for Restore to put them back. */\n savedUncommitted?: number;\n /** What was waiting in it when archived, kept with it (\"2 reply drafts, 1 note for its Claude\"). */\n kept?: string;\n}\n\n/** A session's running Claudes: in your terminal, or run by the app. */\nexport interface SessionClaudes {\n inTerminal: number;\n inApp: number;\n /** One of them is in the middle of a turn. */\n busy: boolean;\n /** Two or more on one conversation (they would both write to it). */\n duplicate: boolean;\n /** What Claude Code itself says (~/.claude/sessions/<pid>.json): mid-turn, at its prompt, or waiting on you. */\n state?: 'busy' | 'idle' | 'waiting';\n /** When that last changed (ms). */\n stateAt?: number;\n /** While waiting: what for. */\n waitingFor?: string;\n}\n\n// ---- merged local branches (Clean up) ---------------------------------------\n\nexport interface BranchCandidate {\n /** Repo alias. */\n repo: string;\n repoPath: string;\n branch: string;\n tip: string;\n /** merged: git says so; squash-merged: a merged PR's head is its tip. */\n reason: 'merged' | 'squash-merged';\n prNumber?: number;\n /** An archived session uses it: its Restore needs the branch. */\n archivedSession?: string;\n}\n\n/** GET /api/cleanup/branches */\nexport interface BranchesState {\n scanning: boolean;\n scannedAt: string | null;\n candidates: BranchCandidate[];\n}\n\n// ---- build folders (Clean up: space without archiving) ---------------------\n\nexport interface BuildFolder {\n path: string;\n bytes: number;\n}\n\nexport interface BuildFolderCandidate {\n sessionId: string;\n target: string;\n branch: string;\n /** A repo's own checkout (not a worktree `work` made). */\n baseCheckout?: boolean;\n lastActive: string;\n folders: BuildFolder[];\n bytes: number;\n}\n\n/** GET /api/cleanup/build-folders */\nexport interface BuildFoldersState {\n scanning: boolean;\n checked: number;\n total: number;\n scannedAt: string | null;\n candidates: BuildFolderCandidate[];\n}\n\nexport interface BuildFoldersApplyResult {\n sessionId: string;\n ok: boolean;\n removed: number;\n message: string;\n}\n\n// ---- Repos and groups (repo-admin.ts; the Repos page) ----------------------\n\n/** A repo the Repos page lists: enrolled (by alias), found in a scanned folder and not yet, or ignored. */\nexport interface RepoRow {\n path: string;\n folder: string;\n /** `owner/name` of its origin, when it has one. */\n origin: string | null;\n /** missing: enrolled, but the folder is gone. */\n status: 'enrolled' | 'new' | 'ignored' | 'missing';\n /** Its alias, when enrolled. */\n alias: string | null;\n /** For a new one: the alias it would get. */\n suggestedAlias?: string;\n /** For a new one: why it can't be enrolled as suggested (pick another alias, or it can't be at all). */\n problem?: string | null;\n /** Other aliases on the same folder (an old duplicate). */\n sharedWith?: string[];\n /** Groups it is in. */\n groups: string[];\n /** Live sessions on it. */\n sessions: number;\n}\n\nexport interface GroupRow {\n name: string;\n members: string[];\n /** Members that are no longer enrolled. */\n missing: string[];\n /** Live sessions on the group. */\n sessions: number;\n /** What's wrong with it as it is (fewer than two repos, …); null when fine. */\n problem: string | null;\n}\n\n/** GET /api/repos */\nexport interface ReposWire {\n /** The folders scanned (config `scanRoots`, else the worktrees root's). */\n roots: string[];\n repos: RepoRow[];\n groups: GroupRow[];\n}\n\n// ---- Updates and release notes (core/updates/) --------------------------------\n\nexport type { ReleaseNote, InstallKind, DesktopUpdate, AvailableUpdate } from './updates/updates.js';\n\n/** GET /api/updates */\nexport interface UpdateWire {\n /** This work's version (\"dev\" for an unbuilt run). */\n running: string;\n install: import('./updates/updates.js').InstallKind;\n /** The newest published release, when the list was read. */\n latest: string | null;\n checkedAt: string | null;\n /** Why the release list couldn't be read, the last time. */\n checkError: string | null;\n /** The desktop app's updater, while the app runs. */\n desktop: import('./updates/updates.js').DesktopUpdate | null;\n /** An update to offer, and how it's had. */\n available: import('./updates/updates.js').AvailableUpdate | null;\n /** The version whose notes to open by themselves (once after an upgrade), or null. */\n whatsNew: string | null;\n}\n\n// ---- First run (first-run.ts, the Welcome page) -----------------------------\n\n/** A tool work leans on, and whether it answers here. */\nexport interface ToolCheck {\n id: 'git' | 'claude' | 'gh' | 'acli';\n label: string;\n /** work can't do without it (git, Claude Code); the others add features. */\n needed: boolean;\n ok: boolean;\n /** Its version when it answers; what to do when it doesn't. */\n detail: string;\n}\n\n/** GET /api/setup */\nexport interface SetupWire {\n /** config.json exists, with a worktrees folder. */\n configured: boolean;\n worktreesRoot: string | null;\n /** The folder scanned for repos (config scanRoots[0], else the one holding the worktrees). */\n reposFolder: string | null;\n repos: number;\n /** Live sessions. */\n sessions: number;\n /** Folders to offer when none are set. */\n suggested: { reposFolder: string | null; worktreesRoot: string };\n tools: ToolCheck[];\n}\n\n// ---- Diff: since you last looked (diff-seen.ts) -----------------------------\n\n/** GET/POST /api/sessions/:id/diff-seen: the newest turn (checkpoint id) on screen the last time you looked at its diff. */\nexport interface DiffSeen {\n checkpointId: number;\n at: string;\n /** That turn's own time (its checkpoint's `ts`): a re-baselined scope counts turns from 1 again, and the time\n * tells a reused number from the turn you saw. Absent on a mark from before. */\n ts?: string;\n /** Your looks, oldest first (diff-looks.ts): what \"Since you looked\" showed each time, to see again. */\n looks?: DiffLook[];\n}\n\n/** One look at a session's diff: the turns (checkpoint ids) it went from and to, and when (started, last grew). */\nexport interface DiffLook {\n from: number;\n to: number;\n /** The two turns' own times (see DiffSeen.ts): a look whose numbers now name other turns isn't shown. */\n fromTs?: string;\n toTs?: string;\n startedAt: string;\n at: string;\n}\n\n/** A commit of one of the session's repos since its branch left its base: the Diff tab's picker lists them with the turns. */\nexport interface SessionCommit {\n /** The repo's tab name (its folder). */\n repo: string;\n sha: string;\n subject: string;\n /** Committer date, ISO: commits and turns are listed in time order. */\n at: string;\n}\n\n/** GET /api/sessions/:id/checkpoints: its turns, and (additive) its commits since the branch's base. */\nexport interface SessionHistoryWire {\n scopeHash: string;\n entries: Array<{ id: number; ts: string; label?: string; repos: Record<string, string | null> }>;\n commits?: SessionCommit[];\n}\n\n// ---- New worktree: is the branch new? (branch-check.ts) -------------------\n\n/** GET /api/branch-check?target=&branch= */\nexport interface BranchCheck {\n branch: string;\n /** git takes it as a branch name. */\n valid: boolean;\n /** A branch of that name in one of the project's repos (local or origin): Create checks it out. */\n exists: boolean;\n /** The session already on it: Create reuses it (an archived one is restored). */\n session: { id: string; archived: boolean } | null;\n /** The first free name from it (`branch`, `branch-2`, …); null when none is, or it isn't valid. */\n free: string | null;\n}\n\n// ---- assistant (Ctrl+K) ---------------------------------------------------\n\n/** POST /api/assistant/context — what the dashboard shows right now, so the\n * assistant knows what \"this\" means. */\nexport interface AssistantView {\n /** The top tab or view: inbox, today, sessions, cleanup, prs, jira, tasks, session. */\n tab: string;\n /** Sub-view (a session's diff / term / comments). */\n sub?: string;\n /** The session on screen, if any. */\n sessionId?: string | null;\n /** Anything else worth saying (e.g. \"12 cleanup candidates listed\"). */\n note?: string;\n /** The Time tab's day on screen (`YYYY-MM-DD`). */\n day?: string;\n}\n\n// ---- cleanup --------------------------------------------------------------\n\n/** What cleanup found: `merged` — safe to delete; `work`/`dirty` — has\n * something of its own (offered for archiving once a week quiet); `gone` —\n * folder missing; `keep` — not a candidate. */\nexport type CleanupVerdict = 'merged' | 'work' | 'dirty' | 'gone' | 'keep';\nexport type CleanupAction = 'delete' | 'archive' | 'forget';\n\nexport interface CleanupRepo {\n name: string;\n path: string;\n exists: boolean;\n /** git could read it. */\n readable: boolean;\n /** Uncommitted + untracked files. */\n dirty: number | null;\n /** Commits not in `base`. */\n ahead: number | null;\n /** 'contained' — nothing of its own; 'squash' — squash-merged; null — has work. */\n merged: 'contained' | 'squash' | null;\n /** The ref compared with (origin/HEAD, origin/main…). */\n base: string | null;\n /** The configured repo itself, not a worktree: never removed. */\n baseCheckout: boolean;\n}\n\nexport interface CleanupCandidate {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n lastActive: string;\n archivedAt: string | null;\n verdict: CleanupVerdict;\n /** What the view pre-selects; null — shown for information only. */\n suggested: CleanupAction | null;\n reason: string;\n repos: CleanupRepo[];\n}\n\n/** GET /api/cleanup — the scan / apply job, polled by the Clean up view. */\nexport interface CleanupState {\n phase: 'idle' | 'fetching' | 'scanning' | 'applying';\n done: number;\n total: number;\n candidates: CleanupCandidate[];\n results: Array<{ sessionId: string; action: CleanupAction; ok: boolean; message: string }>;\n startedAt?: string;\n finishedAt?: string;\n error?: string;\n}\n\n/** POST /api/cleanup/apply */\nexport interface CleanupApplyRequest {\n items: Array<{ sessionId: string; action: CleanupAction }>;\n}\n\n/** Terminal WebSocket control frame: the session's Claude is running in\n * a plain terminal (not the PTY host), so nothing was spawned — a second\n * Claude would share its conversation. Reconnect with `?force=1` to\n * spawn anyway. */\nexport interface TerminalElsewhere {\n type: 'elsewhere';\n /** Claude's last transcript write (ms since epoch), or null. */\n lastActivity: number | null;\n state: 'working' | 'needs_input' | 'idle' | null;\n /** A Claude process is known to run on this conversation (Claude's own\n * process files), not inferred from activity: the tab then offers no way\n * to start a second one. */\n confirmed?: boolean;\n}\n\n/** GET /api/digest — what each session did since a point in time. */\nexport interface DigestResponse {\n since: string;\n generatedAt: string;\n sessions: DigestSession[];\n}\n\nexport interface DigestSession {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n /** Where it stands now. */\n state: 'working' | 'needs_input' | 'idle' | null;\n summary?: string;\n /** What you asked it in the window, oldest first (capped). */\n prompts: Array<{ ts: string; text: string }>;\n /** More prompts than listed. */\n morePrompts: number;\n /** Finished turns (checkpoints) in the window, and the names already given to them. */\n turns: number;\n turnLabels: string[];\n /** A transcript was too large to read back to the window's start, so\n * earlier prompts are missing. */\n partial?: boolean;\n diffStat: DiffStat | null;\n prs: Array<{ repo: string; number: number; url: string; state: 'OPEN' | 'MERGED' | 'CLOSED'; mergedAt?: string }>;\n archivedAt: string | null;\n /** Newest activity in the window (ISO). */\n lastActivity: string;\n /** How long its Claude worked in the window (work-time.ts; approximate). */\n workedMs?: number;\n}\n\n/** A one-click instruction for a session (config `prompts`, or defaults). */\nexport interface SavedPrompt {\n label: string;\n prompt: string;\n /** Only for these repo aliases / group names; all when absent. */\n repos?: string[];\n}\n\n/** GET /api/prompts */\nexport interface PromptsResponse {\n prompts: SavedPrompt[];\n /** False when these are the built-in defaults (no `prompts` in config). */\n configured: boolean;\n}\n\n/** How full the session's Claude conversation is (tokens). */\nexport interface ContextUsage {\n /** Tokens the conversation holds now (last request's prompt + reply). */\n used: number;\n /** The model's context window. */\n window: number;\n model?: string;\n}\n\n/** Another live session that changes some of the same files (same repo,\n * same path): the two will conflict when both merge. */\nexport interface SessionOverlap {\n sessionId: string;\n target: string;\n branch: string;\n /** How many files both change. */\n count: number;\n /** The first of them (capped), repo alias + root-relative path. */\n files: Array<{ repo: string; path: string }>;\n}\n\n/** One row of GET /api/sessions — what every dashboard server (the real\n * work web and the demo) sends. */\nexport interface SessionWire {\n id: string;\n /** Snoozed out of the Inbox right now (snooze.ts): until when, or null for \"until it changes\". */\n snoozed?: { until: string | null };\n /** Behind its main branch (behind-main.ts, as of the last fetch) — or, when stacked, behind the\n * session it is stacked on (`stacked`, its local branch): absent when level or unknown. */\n behind?: { base: string; commits: number; conflicts: boolean; stacked?: true };\n /** The live session it is stacked on (stack.ts): made from that session's branch. */\n stackedOn?: { id: string; branch: string; title?: string };\n /** How many live sessions are stacked on this one. */\n stackedChildren?: number;\n /** You have notes on it (session-notes.ts; GET /api/sessions/:id/note). */\n hasNote?: boolean;\n /** What it waits on that isn't done yet (session-blocks.ts): out of the Inbox meanwhile. */\n blockedBy?: BlockerWire[];\n /** It was stacked on a session that merged and is archived: it should move onto main (POST …/retarget). */\n stackParentMerged?: { id: string; branch: string };\n target: string;\n /** The branch it was started on: with target, the session's identity (and its folder's name). */\n branch: string;\n /** Repos whose checkout is on another branch now (Claude switched, or you did); null = detached HEAD. */\n /** `noGit`: its folder has no git left in it (a removal that stopped halfway): `work tree` makes it again. */\n onOtherBranch?: Array<{ repo: string; branch: string | null; noGit?: true }>;\n isGroup: boolean;\n paths: string[];\n /** Its repos' aliases, one per path in the same order (session-repos.ts `sessionRepos`: the recorded list,\n * else a group's config members by folder name, a single repo's target). Absent from a server before this. */\n repos?: string[];\n /** A session folder (a group's, or one made with `sessionFolders`): its agent runs in the folder and a repo\n * can be added to it (POST …/repos). Absent from a server before this. */\n folder?: boolean;\n baseBranch?: string;\n jiraKey?: string;\n createdAt: string;\n lastAccessedAt: string;\n draftCount: number;\n /** Open comment threads (top-level, not resolved): the Diff tab's badge. */\n commentCount: number;\n claudeCount: number;\n ptyStatus: PtyStatus;\n lastActivity: number | null;\n activityState: ActivityState;\n pendingForClaudeCount: number;\n attention: SessionAttention | null;\n diffStat: DiffStat | null;\n archivedAt: string | null;\n /** This worktree's dev-server port ($PORT), when it has one. */\n port: number | null;\n /** Its agent processes running right now (agents/: `live`, grouped by core/live-claudes.ts);\n * absent when none. */\n agents?: SessionClaudes;\n /** @deprecated The same as `agents` (its old name; kept for `work sessions --json` readers for one version). */\n claudes?: SessionClaudes;\n /** The agent it runs, and what work can do with it (a feature it can't is hidden, not shown broken). */\n agent?: SessionAgentWire;\n /** What its archive kept (archived sessions; session-archive.ts). */\n archive?: SessionArchiveInfo;\n /** Its name: the one you gave it, else its first prompt, else its Jira key. */\n title?: string | null;\n /** The title is one you gave it (not the automatic one). */\n titleIsYours?: boolean;\n /** Other sessions changing the same files; absent when there are none. */\n overlaps?: SessionOverlap[];\n /** Context used by its Claude conversation; null before the first reply. */\n context?: ContextUsage | null;\n /** Unresolved review threads on its open PRs whose last word isn't\n * yours (the PR watch's count, pr-review.ts); absent when none or not\n * checked yet. Makes it \"Review comments\" (session-view.ts). */\n openReviewThreads?: number;\n /** Replies its Claude drafted for you to post on those threads (pr-replies.ts). */\n replyDrafts?: number;\n /** Where its pull request stands (pr-stage.ts, the PR watch's last check); `seen` once you\n * opened the session at this stage. Absent with no PR or before the first check. */\n prStage?: PrStageWire;\n}\n\n/** A session's PR stage, as the dashboard gets it. */\nexport type PrStageWire = import('./pr/pr-stage.js').PrStage & { seen?: boolean };\n\n// ---- time (the Time tab: a day's hours per ticket) -------------------------\n\nexport interface TimeEntryWire {\n key: string;\n hours: number;\n}\n\n/** A session that worked that day: its Claude's minutes, and the ticket it is for (null: none known). */\nexport interface TimeSessionEvidence {\n sessionId: string;\n label: string;\n key: string | null;\n minutes: number;\n /** Its ticket is the AI step's guess (classify.ts), not its branch or Jira key. */\n guessed?: true;\n}\n\nexport interface TimeCommitEvidence {\n repo: string;\n sha: string;\n subject: string;\n keys: string[];\n guessed?: true;\n}\n\n/** A meeting from Outlook that day (Graph): it goes to its ticket when the AI step places it, else to the gap ticket. */\nexport interface TimeMeetingEvidence {\n /** Outlook's id for it (what the AI step's answer is kept by; absent in days gathered before). */\n id?: string;\n subject: string;\n /** Local `HH:MM`. */\n start: string;\n end: string;\n minutes: number;\n key?: string | null;\n guessed?: true;\n}\n\n/** A Teams chat you wrote in that day: how many of your messages, a few of them shortened (what the AI step reads). */\nexport interface TimeChatEvidence {\n /** Issue keys anyone in the chat named that day (only the keys are read from others' messages). */\n mentions?: string[];\n /** Teams' id for the chat: untitled ones share a name (\"a one-on-one chat\"). */\n id?: string;\n chat: string;\n messages: number;\n sample: string[];\n key?: string | null;\n guessed?: true;\n}\n\n/** An issue you did something to that day in Jira (moved it). */\nexport interface TimeJiraEvidence {\n key: string;\n summary: string;\n what: string;\n}\n\nexport interface TimeEvidence {\n sessions: TimeSessionEvidence[];\n commits: TimeCommitEvidence[];\n jira: TimeJiraEvidence[];\n meetings?: TimeMeetingEvidence[];\n chats?: TimeChatEvidence[];\n /** What the AI step last placed (a hash of the unplaced items): it isn't asked again until they change. */\n classifiedFor?: string;\n}\n\n/** empty: nothing built yet; draft: the suggestion; edited: your rows; off: a day off; not-workday: a weekend or holiday;\n * posted: in Tempo as it stands; changed: posted, then changed (post again). */\nexport type TimeDayStatus = 'empty' | 'draft' | 'edited' | 'off' | 'not-workday' | 'posted' | 'changed';\n\nexport interface TimeSettingsWire {\n dayHours: number;\n multiplier: number;\n capHours: number;\n stepHours: number;\n minHours: number;\n gapTicket: string | null;\n timeOffTicket: string | null;\n /** Hours as measured (Claude minutes 1:1), not scaled. */\n effort: boolean;\n}\n\n/** POST /api/sessions/:id/diff-page: where the session's diff has a page of its own (the one `wd` opens). */\nexport interface DiffPageWire {\n url: string;\n}\n\n/** GET /api/time/:day */\nexport interface TimeDayWire {\n day: string;\n status: TimeDayStatus;\n workday: boolean;\n dayOff: boolean;\n /** What work suggests from the evidence. */\n suggested: TimeEntryWire[];\n /** What will be posted: your rows when you edited, else the suggestion. */\n entries: TimeEntryWire[];\n edited: boolean;\n /** Hours of the day no ticket has (no gap ticket set). */\n unallocated: number;\n total: number;\n evidence: TimeEvidence;\n /** Issue titles, by key. */\n titles: Record<string, string>;\n builtAt: string | null;\n settings: TimeSettingsWire;\n /** When work last posted the day to Tempo, and what. */\n posted: { at: string; entries: TimeEntryWire[] } | null;\n /** A vacation day (config `time.vacation`): a day off whatever was ticked. */\n vacation: boolean;\n /** Rows whose ticket Jira had as done when the day was gathered. */\n resolved: string[];\n /** Rows whose ticket is a placeholder (`time.hints`): create it in Jira before posting. */\n placeholders: string[];\n /** Whether it can post (a Tempo token and your account id), or why not. Set by the server. */\n posting?: { ready: boolean; why: string | null };\n}\n\n/** GET /api/time/graph: Outlook and Teams for the Time tab (Microsoft Graph). */\nexport interface TimeGraphWire {\n /** Can it sign in at all (an app registration), or why not. */\n ready: boolean;\n why: string | null;\n /** Signed in as. */\n account: string | null;\n /** Signed in, but it stopped working (expired or revoked, another app registration): connect again. */\n problem: string | null;\n /** A sign-in under way: the code to enter at the address. */\n login: { userCode: string; verificationUri: string; expiresAt: string } | null;\n /** How the last sign-in went wrong. */\n error: string | null;\n}\n\n/** POST /api/time/:day/post */\nexport interface TimePostWire {\n posted: number;\n removed: number;\n kept: number;\n /** Rows a worklog you made by hand in Tempo already covered (not posted again). */\n coveredByHand: number;\n /** Your own worklogs that day that no row matches: left alone. */\n otherByHand: number;\n failed: Array<{ key: string; error: string }>;\n day: TimeDayWire;\n}\n\nexport interface TimeDaySummary {\n day: string;\n status: TimeDayStatus;\n workday: boolean;\n total: number;\n tickets: number;\n}\n\n/** GET /api/time?from=&to= */\nexport interface TimeDaysWire {\n days: TimeDaySummary[];\n settings: TimeSettingsWire;\n}\n\n// ---- start on a PR ---------------------------------------------------------\n\n/** The PR a session is started on, as the lookup found it (core/pr/pr-start.ts). */\nexport interface PrToStart {\n /** The repo alias it belongs to (a group's repo: the session is that repo's alone). */\n alias: string;\n number: number;\n title: string;\n url: string;\n /** Its head branch: on origin, so the session's pushes reach the PR. */\n branch: string;\n /** Where it merges into. */\n base: string;\n author: string;\n}\n\n/** GET /api/pr-start?ref=&target=: the PR, or (400) why not — a fork, closed, not one of your repos. */\nexport type PrStartWire = { pr: PrToStart } | { error: string };\n\n// ---- ship -----------------------------------------------------------------\n\nexport type ChecksState = 'pass' | 'fail' | 'pending' | 'none';\n\nexport interface ShipPr {\n number: number;\n url: string;\n state: 'OPEN' | 'MERGED' | 'CLOSED';\n isDraft: boolean;\n /** GitHub mergeStateStatus: CLEAN | DIRTY | BLOCKED | BEHIND | UNSTABLE | HAS_HOOKS | DRAFT | UNKNOWN */\n mergeStateStatus: string;\n checks: ChecksState;\n headSha: string;\n /** When it was merged (ISO), for a MERGED PR. */\n mergedAt?: string;\n /** When anything on it last changed (a push, a comment, a review): the\n * PR watch re-reads review threads only when this moved. */\n updatedAt?: string;\n /** Checks that failed (name + link), when `checks` is 'fail'. */\n failing?: FailingCheck[];\n /** APPROVED | CHANGES_REQUESTED | REVIEW_REQUIRED, or '' when the repo requires no review (gh's reviewDecision). */\n reviewDecision?: string;\n /** Its author's login: a session on someone else's PR (work on it, review it) isn't handed its threads or CI notes. */\n author?: string;\n /** The branch it merges into (gh's baseRefName): what a conflict is resolved against. */\n baseBranch?: string;\n}\n\nexport interface FailingCheck {\n name: string;\n url?: string;\n}\n\nexport interface RepoShipState {\n /** Repo alias (group sub-repo folder, or the target for a single repo). */\n name: string;\n path: string;\n branch: string;\n /** Local HEAD commit. */\n localSha: string;\n /** Uncommitted (incl. untracked) files — shipping needs a clean tree. */\n dirtyFiles: number;\n /** git couldn't read the working tree (a timeout under load): its facts are unknown, so it's never done. */\n gitError?: string;\n /** The branch exists on origin (`origin/<branch>`), whatever the local\n * tracking config says — `work tree` often leaves it tracking the base. */\n hasUpstream: boolean;\n /** Local tracking is set to `origin/<branch>` (a plain `git push` works). */\n tracksRemote: boolean;\n /** vs `origin/<branch>`; null when the branch isn't on origin. */\n ahead: number | null;\n behind: number | null;\n pr: ShipPr | null;\n /** Nothing left to do here: PR merged with nothing since, or the repo\n * was never touched. Never blocks the other repos of a group. */\n done: boolean;\n doneReason?: 'merged' | 'untouched';\n /** Why \"merge\" isn't available right now ([] = go). Empty when done. */\n mergeBlockers: string[];\n /** gh missing / not authenticated / no GitHub remote. */\n ghError?: string;\n /** Commits the remote's default branch doesn't have (null = unknown). */\n commitsVsBase?: number | null;\n}\n\nexport interface ShipPreflight {\n repos: RepoShipState[];\n}\n\nexport type ShipAction = 'push' | 'create-pr' | 'merge';\nexport type MergeMethod = 'squash' | 'merge' | 'rebase';\n\n/** A repo the user chose to merge, with the PR head they were shown. */\nexport interface MergeSelection {\n name: string;\n headSha: string;\n}\n\nexport interface ShipResult {\n repo: string;\n ok: boolean;\n message: string;\n url?: string;\n /** For merge: whether this repo's PR was merged by this call. */\n merged?: boolean;\n}\n\n/** POST /api/sessions/:id/ship body. */\nexport type ShipRequest =\n { action: 'push' | 'create-pr'; draft?: boolean } | { action: 'merge'; method?: MergeMethod; repos: MergeSelection[] };\n\nexport interface ShipResponse {\n results: ShipResult[];\n archived?: boolean;\n allDone?: boolean;\n}\n\n/** POST /api/sessions/:id/revert — undo an uncommitted file, or the lines\n * of one hunk (new-side range), back to HEAD. */\nexport interface RevertRequest {\n repo: string;\n path: string;\n lines?: { start: number; end: number };\n /** Leave Claude a note about it (default true). */\n tell?: boolean;\n}\nexport interface RevertResponse {\n ok: true;\n description: string;\n}\n\n/** POST /api/presence — one dashboard tab says what it is showing. Sent on\n * every change and as a heartbeat; `gone` when the tab closes. */\nexport interface PresenceReport {\n /** Random per tab. */\n clientId: string;\n /** The session the tab shows, or null (Inbox, Sessions table, …). */\n sessionId: string | null;\n visible: boolean;\n focused: boolean;\n /** The tab may show browser notifications (permission granted). */\n canNotify: boolean;\n gone?: boolean;\n}\n\n/** SSE `notify` — a session wants the user and nobody is looking at it. */\nexport interface NotifyEvent {\n sessionId: string;\n kind: 'idle' | 'needs_input' | 'unblocked' | 'pr';\n title: string;\n body?: string;\n}\n\n/** GET /api/sessions/:id/dev — the worktree's port and dev server. */\nexport interface DevServerState {\n port: number | null;\n /** Something is serving on the port (whoever started it). */\n listening: boolean;\n url: string | null;\n /** The configured dev command for this session, if any. */\n command: string | null;\n repo: string | null;\n /** Started from the dashboard and still alive. */\n running: { pid: number; startedAt: string } | null;\n}\n\n/** GET /api/sessions/:id/ci — what GitHub says about the session's PRs. */\nexport interface SessionCi {\n checkedAt: string;\n /** Who gh is signed in as, when the watch knew it: tells your PRs from others' (the PR tab's \"by @…\"). */\n viewer?: string;\n repos: Array<{\n name: string;\n pr: ShipPr | null;\n done: boolean;\n /** Unresolved review threads waiting on the author (open PRs). */\n openThreads?: number;\n /** Those threads (the PR watch's last read). */\n threads?: OpenReviewThread[];\n }>;\n}\n\n/** An unresolved review thread waiting on you (the PR watch's last read). */\nexport interface OpenReviewThread {\n threadId: string;\n repo: string;\n prNumber: number;\n url: string;\n where: string | null;\n reviewer: string;\n excerpt: string;\n /** Its text is from someone with write access or a trusted review bot (the PR watch's rule); only\n * such threads go to Claude in one \"Ask Claude about all\". Missing (an older server): not known. */\n trusted?: boolean;\n}\n\n/** GET /api/sessions/:id/replies: the threads handed to its Claude and its drafts, and the open threads that have no draft. */\nexport interface RepliesWire {\n replies: PrReply[];\n /** Unresolved threads with no reply drafted: nothing to post yet (ask its Claude, or answer on GitHub). */\n waiting: OpenReviewThread[];\n}\n\n// ---- the rail's pins and sections (rail-layout.ts) -------------------------------\n\n/** GET /api/rail (and every rail write's answer). */\nexport type { RailLayout, RailSection, RailPlace, PlacePatch, SectionOp } from './rail/rail-layout.js';\n\n// ---- the PTY host's heartbeat (host-health.ts) ----------------------------------------\n\nexport type { HostHealth, HostState } from './pty/host-health.js';\n\n// ---- a session's timeline (timeline.ts) ---------------------------------------------\n\nexport type { TimelineEvent, TimelineKind } from './conversations/timeline.js';\n\n/** GET /api/sessions/:id/timeline: newest first. */\nexport interface TimelineWire {\n events: import('./conversations/timeline.js').TimelineEvent[];\n}\n\n// ---- blocked by (session-blocks.ts) -------------------------------------------------\n\n/** One thing a session waits on. */\nexport interface BlockerWire {\n key: string;\n kind: 'session' | 'pr';\n label: string;\n sessionId?: string;\n url?: string;\n state?: 'OPEN' | 'MERGED' | 'CLOSED';\n}\n\n// ---- your notes on a session (session-notes.ts) ------------------------------------\n\n/** GET / PUT /api/sessions/:id/note */\nexport interface NoteWire {\n note: { text: string; updatedAt: string } | null;\n}\n\n// ---- the Code tab: a session's files, read only (code-browse.ts) ------------------\n\n/** One repo of a session: its files as git lists them (tracked, and new ones not ignored). */\nexport interface CodeRepoWire {\n /** Its folder's name (a group's repos are folders of the group's). */\n name: string;\n /** Paths relative to the repo, `/`-separated, sorted. */\n files: string[];\n /** Changed on this branch: committed since it left its base, or not committed. */\n changed: string[];\n /** More files than are listed (MAX_CODE_FILES). */\n truncated: boolean;\n}\n\n/** GET /api/sessions/:id/files */\nexport interface CodeFilesWire {\n /** A group: its repos are folders, beside the group folder's own files (`rootFiles`, its CLAUDE.md…). */\n group: boolean;\n rootFiles: string[];\n repos: CodeRepoWire[];\n}\n\n/** A line with what was searched for in it (code-search.ts). */\nexport interface CodeTextHit {\n repo: string;\n path: string;\n line: number;\n text: string;\n}\n\nexport type CodeSymbolKind = 'class' | 'interface' | 'record' | 'struct' | 'enum' | 'type' | 'function' | 'method' | 'property' | 'const';\n\n/** A declaration: a type or member, where it is. */\nexport interface CodeSymbol {\n name: string;\n kind: CodeSymbolKind;\n repo: string;\n path: string;\n line: number;\n /** Its line, trimmed. */\n text: string;\n}\n\n/** GET /api/sessions/:id/code-search?q= — by name and inside the files. */\nexport interface CodeSearchWire {\n query: string;\n symbols: CodeSymbol[];\n text: CodeTextHit[];\n /** More lines matched than came back. */\n truncated: boolean;\n}\n\n/** GET /api/sessions/:id/file?repo=&path= — one file as it is in the worktree now. */\nexport interface CodeFileWire {\n repo: string;\n path: string;\n size: number;\n /** null with `reason`: not shown as text. */\n text: string | null;\n reason?: 'binary' | 'too-large';\n}\n\n// ---- time per session (work-time.ts) ---------------------------------------------\n\n/** GET /api/sessions/:id/time: how long its Claude worked (approximate: see work-time.ts). */\nexport interface WorkTimeWire {\n workedMs: number;\n /** Prompts you gave it, in all its transcripts. */\n prompts: number;\n /** The last two weeks, per local day, newest first; days without work left out. */\n byDay: Array<{ day: string; ms: number }>;\n firstAt: string | null;\n lastAt: string | null;\n}\n\n/** GET /api/sessions/:id/worklog: can it write Jira worklogs, to which issue, and what was logged per day (seconds). */\nexport interface WorklogWire {\n configured: boolean;\n issueKey: string | null;\n logged: Record<string, number>;\n}\n\n// ---- fork (fork.ts) ---------------------------------------------------------------\n\n/** POST /api/sessions/:id/fork: the new session. */\nexport interface ForkWire {\n sessionId: string;\n paths: string[];\n /** Its Claude was given a summary of the original's conversation. */\n summarized: boolean;\n /** The worktree exists, but its Claude didn't start (the Terminal tab can). */\n startError?: string;\n}\n\n// ---- add a repo to a session folder (add-repo.ts) ----------------------------------\n\n/** POST /api/sessions/:id/repos: the repo was checked out into the session folder. */\nexport interface AddRepoWire {\n ok: true;\n /** The new checkout: `<session folder>/<repo folder>`. */\n path: string;\n branch: string;\n /** Its branch was made for it (false: the repo's existing branch of that name). */\n created: boolean;\n /** The branch a new one was made from. */\n from?: string;\n /** The session folder's instructions file imports the repo's own now (absent from an older server). */\n imported?: boolean;\n /** What didn't go as it should once the repo was in (the turns, the instructions file, telling its Claude): it stands. */\n warnings?: string[];\n}\n\n// ---- behind main (behind-main.ts) -------------------------------------------------\n\n/** POST /api/sessions/:id/update-from-main: per repo. */\nexport interface UpdateFromMainWire {\n results: Array<\n | { ok: true; repo: string; how: 'rebase' | 'merge' | 'nothing'; base: string; commits: number }\n | {\n ok: false;\n repo: string;\n reason: string;\n conflicts?: boolean;\n base?: string;\n /** Not for a button: hand it to the session's Claude. */ handOff?: boolean;\n }\n >;\n}\n\n// ---- catch me up (catch-up.ts) -------------------------------------------------------\n\n/** GET / POST /api/sessions/:id/catch-up */\nexport interface CatchUpWire {\n catchUp: { text: string; at: string } | null;\n}\n\n// ---- the Jira watch (jira-watch.ts) -----------------------------------------------\n\n/** What the Jira watch did with an issue assigned to you. */\nexport interface JiraDecision {\n key: string;\n summary: string;\n url: string;\n at: string;\n /** baseline: there when it was turned on · started: worktree + Claude · suggested: not sure, start it yourself · skipped: has a session · failed · dismissed: you said no. */\n action: 'baseline' | 'started' | 'suggested' | 'skipped' | 'failed' | 'dismissed';\n target?: string;\n branch?: string;\n sessionId?: string;\n reason: string;\n}\n\n/** GET /api/jira/watch */\nexport interface JiraWatchState {\n settings: { enabled: boolean; since: string | null };\n /** Newest first; baseline entries left out. */\n decisions: JiraDecision[];\n /** The projects an issue can be started in (for \"Start in …\"). */\n targets: string[];\n lastRunAt: string | null;\n nextRunAt: string | null;\n}\n\n/** What work does in the background (core/activity.ts), for the Activity panel. */\nexport type ActivityKind =\n | 'pr-watch'\n | 'pr-list'\n | 'jira'\n | 'idle-sleep'\n | 'cleanup'\n | 'build-folders'\n | 'branches'\n | 'archive'\n | 'conversations'\n | 'server'\n | 'jira-watch'\n | 'stacks'\n | 'blocks'\n | 'groups'\n | 'updates'\n | 'time'\n | 'agents';\n\n/** One thing a run decided or noticed (\"archived …\", \"kept … because …\"). */\nexport interface ActivityNote {\n at: string;\n text: string;\n /** action: it did something; warn: something stopped it; info: why it didn't. */\n level: 'info' | 'action' | 'warn';\n /** The session it is about (click to open). */\n sessionId?: string;\n}\n\nexport interface ActivityRun {\n id: number;\n kind: ActivityKind;\n label: string;\n startedAt: string;\n endedAt: string | null;\n status: 'running' | 'done' | 'failed' | 'skipped';\n progress: { done: number; total: number } | null;\n /** One line on how it ended (or why it was skipped / failed). */\n summary: string | null;\n notes: ActivityNote[];\n /** The same skip, repeated this many more times (collapsed). */\n repeats?: number;\n}\n\n/** A job that runs on its own, and when it runs next. */\nexport interface ActivitySchedule {\n kind: ActivityKind;\n label: string;\n everyMs: number;\n nextAt: string | null;\n pausedUntil: string | null;\n pausedWhy: string | null;\n}\n\n/** GET /api/activity */\nexport interface ActivityWire {\n running: ActivityRun[];\n /** Finished runs, newest first. */\n recent: ActivityRun[];\n schedules: ActivitySchedule[];\n /** When each job last finished well (absent from a server before this): a failing job that worked once needs you. */\n lastOk?: Partial<Record<ActivityKind, string>>;\n}\n\n/**\n * A review thread handed to a session's Claude, and the reply it drafted\n * for you (pr-replies.ts). GET /api/sessions/:id/replies.\n */\nexport interface PrReply {\n /** GitHub's thread id (PRRT_…). */\n threadId: string;\n repo: string;\n prNumber: number;\n /** The reviewer comment it answers. */\n url: string;\n where: string | null;\n reviewer: string;\n excerpt: string;\n /** sent: Claude has it; draft: Claude wrote a reply; posted: on GitHub (your click, or `work pr post` on your yes). */\n status: 'sent' | 'draft' | 'posted';\n draft: string | null;\n sentAt: string;\n draftedAt?: string;\n postedAt?: string;\n postedUrl?: string;\n resolved?: boolean;\n}\n\n/** GET /api/conversations/search: a session whose kept conversation mentions the query (conversation-store.ts). */\nexport interface ConversationHit {\n sessionId: string;\n target: string;\n branch: string;\n /** Archived now (Restore brings it back). */\n archived: boolean;\n archivedAt: string | null;\n worktreeRemoved: boolean;\n /** When its conversation was last written (the newest transcript). */\n lastAt: string | null;\n snippets: Array<{ role: 'you' | 'claude' | 'summary'; text: string; at: string | null }>;\n}\n\n// ---- driving a session from outside (session-control.ts) ----------------------------\n\n/** How a message reaches a session: typed in now (idle in the PTY host), on its next turn (busy, or a terminal outside work), or by starting its Claude. */\nexport type SendHow = 'typed' | 'next-turn' | 'outside' | 'started';\n\n/** POST /api/sessions/:id/send. */\nexport interface SendWire {\n how: SendHow;\n sentAt: string;\n}\n\n/** POST /api/sessions/:id/agent/start | stop. */\nexport interface AgentControlWire {\n how: 'started' | 'running' | 'stopped' | 'not-running';\n}\n\n/** GET /api/agents: the agents in the PTY host still running a version from before their tool was updated (agent-restart.ts). */\nexport interface AgentsWire {\n /** When the newest of their tools was installed (ISO): what a \"Later\" is for. Null when none is on PATH. */\n installedAt: string | null;\n outdated: Array<{\n id: string;\n tool: string;\n startedAt: string;\n /** Working or waiting on you: restarts after its turn. */ busy: boolean;\n }>;\n /** Asked to restart, waiting for their turn to end. */\n queued: string[];\n}\n\n/** POST /api/agents/restart {ids} | {outdated: true} | {all: true}: restarted now, after their turn, or not (why). */\nexport interface RestartWire {\n now: string[];\n later: string[];\n failed: Array<{ id: string; error: string }>;\n}\n\n/** GET /api/sessions/:id/screen: its terminal as plain text (null: no terminal in the PTY host). */\nexport interface ScreenWire {\n text: string | null;\n}\n","import { ARCHIVED_BY, type ArchivedBy } from '../api-types.js';\nimport fs from 'node:fs';\nimport { isSavedUncommitted, type SavedUncommitted } from './archive-uncommitted.js';\nimport { logSwallowed } from '../platform/best-effort.js';\nimport { clearSnooze } from '../rail/snooze-store.js';\nimport { whileArchiving } from './archiving.js';\nimport path from 'node:path';\nimport zlib from 'node:zlib';\nimport { getConfigDir } from '../platform/config.js';\nimport { promptsSince } from '../conversations/digest.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { readJsonlTail } from '../conversations/jsonl.js';\nimport { agentOf } from '../agents/index.js';\nimport type { ConversationEntry } from '../agents/types.js';\n\n/**\n * Archiving a session: out of the way, its disk space back, its history kept.\n *\n * 0. unless forced, nothing is waiting in it: replies Claude drafted for\n * you to post, notes not yet delivered to its Claude, a Claude mid-turn\n * or waiting for your answer (`waiting`);\n * 1. its Claude and its dev server are stopped;\n * 2. its conversation (every transcript) is copied to\n * ~/.work/archive/<id>/transcripts — Claude Code deletes old transcripts\n * by itself, and this is what \"recall what we did\" reads;\n * 3. a summary is written next to it: your prompts, its PRs, how it ended,\n * the branch tips — and, in the background, a few sentences on what was\n * done and why (`writeArchiveSummary`, an internal `claude -p`);\n * 4. the worktree is removed — only when cleanup's own check says nothing\n * would be lost (merged, clean) — and then its checkpoint refs go, and a\n * branch already merged into the main branch is deleted (its tip is\n * recorded; Restore recreates it). Otherwise the worktree stays, the\n * reason is recorded, and its build output (node_modules, bin/obj, …)\n * is cleared to give the disk back anyway;\n * 5. the session is marked archived.\n *\n * Restoring (`work tree` into it, or Restore in the dashboard) recreates the\n * branch if archiving deleted it, the worktree from the branch, and puts the\n * transcripts back where Claude looks for them, so it continues the\n * conversation. Old archives are compressed (archive-retention.ts).\n */\n\nexport interface ArchivedPr {\n repo: string;\n number: number;\n url: string;\n state: string;\n}\n\n/** A repo's git-ignored files archiving copied (archive-ignored.ts). */\nexport interface SavedIgnored {\n files: number;\n bytes: number;\n /** Left out: over a cap. */\n skipped: number;\n /** It stopped looking at MAX_IGNORED_FILES files: more were there. */\n partial?: true;\n /** Put back by a Restore (then not again). */\n restoredAt?: string;\n /** A Restore that couldn't put them back: why (not tried again). */\n restoreError?: string;\n}\n\nexport interface ArchiveRecord {\n sessionId: string;\n target: string;\n branch: string;\n isGroup: boolean;\n paths: string[];\n archivedAt: string;\n /** Who archived it (ArchiveOptions.by); none in an archive from before it was recorded. */\n archivedBy?: ArchivedBy;\n /** The worktree folder(s) were removed (false: kept, see keptBecause). */\n worktreeRemoved: boolean;\n keptBecause: string | null;\n /** Removed only in part: git stopped at a file in use, leaving these folders with no git in\n * them. The save is kept; Restore makes the worktree again and copies them back (leftover.ts). */\n leftovers?: string[];\n /** Transcript file names under transcripts/, by the folder they belong to\n * (on disk `<file>` or, once compressed, `<file>.gz`). */\n transcripts: Array<{ file: string; projectDir: string }>;\n summary: {\n prompts: Array<{ ts: string; text: string }>;\n promptCount: number;\n lastSummary: string | null;\n prs: ArchivedPr[];\n jiraKey: string | null;\n /** What was done and why, in a few sentences (written after archiving). */\n written?: string | null;\n };\n /** Each repo's branch tip when archived (repo alias → commit): of the branch checked out (`heads`), else the session's. */\n tips?: Record<string, string>;\n /** Repos checked out on another branch than the session's when archived (alias → branch): Restore brings that branch back. */\n heads?: Record<string, string>;\n /** Repos whose local branch was deleted (merged): Restore recreates it at its tip. */\n branchesDeleted?: string[];\n /** Build output cleared from a kept worktree. */\n buildFolders?: { folders: number; bytes: number };\n /** Uncommitted work saved because the worktree was removed (repo alias → where it is): Restore puts it back (archive-uncommitted.ts). */\n uncommitted?: Record<string, SavedUncommitted>;\n /** Git-ignored files that aren't build output (local settings, the editor's state), copied because the\n * worktree was removed (repo alias → how many): Restore puts them back (archive-ignored.ts). */\n ignored?: Record<string, SavedIgnored>;\n /** What was still waiting in it when archived (a merged session isn't held up by these): they stay in\n * state.db with the session, so Restore brings them back — drafts in the header, notes delivered on\n * its next turn. Listed here so the archive says what it holds. */\n kept?: ArchiveKept;\n /** Saved work an earlier Restore couldn't put back, carried over when archived again (still in its ref and patch). */\n unrestored?: SavedUncommitted[];\n /** When the copied git-ignored files were deleted for retention (ISO): they can hold secrets. */\n ignoredDroppedAt?: string;\n /** When the transcripts were compressed / deleted for retention (ISO). */\n compressedAt?: string;\n transcriptsDroppedAt?: string;\n}\n\n/** Who archived it, as stored (archive.json is read back as JSON): only a value work writes. */\nexport function archivedByOf(rec: { archivedBy?: unknown }): ArchivedBy | undefined {\n return ARCHIVED_BY.find((b) => b === rec.archivedBy);\n}\n\nexport interface ArchiveKept {\n replyDrafts: Array<{ threadId: string; url: string; reviewer: string; draft: string }>;\n notes: Array<{ id: string; text: string }>;\n /** Its Claude was waiting for your answer: what it asked. */\n askingYou?: string;\n}\n\nexport interface ArchiveDeps {\n stopClaude: (id: string) => Promise<void>;\n /** Would removing its worktree lose anything? (cleanup's verdict). With\n * `uncommittedSaved`, uncommitted files don't count: they were saved. */\n removable: (s: WorktreeSession, opts?: { uncommittedSaved?: boolean }) => Promise<{ ok: boolean; reason: string }>;\n /** Save each repo's uncommitted work (archive-uncommitted.ts) before the worktree may go. */\n saveUncommitted?: (\n s: WorktreeSession,\n archiveDir: string,\n stamp: number,\n ) => Promise<{ saved: Record<string, SavedUncommitted>; error: string | null }>;\n /** Drop saves that weren't needed (the worktree stayed). */\n dropSaved?: (s: WorktreeSession, saved: Record<string, SavedUncommitted>, archiveDir: string) => Promise<void>;\n /** Copy each repo's git-ignored files that aren't build output into `<archiveDir>/ignored/<repo>` (archive-ignored.ts). */\n saveIgnored?: (s: WorktreeSession, archiveDir: string) => Promise<Record<string, SavedIgnored>>;\n removeWorktree: (s: WorktreeSession) => Promise<boolean>;\n /** After a removal git refused: the session's folders left with no git in them (it stopped halfway). */\n halfRemoved?: (s: WorktreeSession) => string[];\n setArchived: (s: WorktreeSession) => Promise<boolean>;\n /** The session's transcript files. */\n transcripts: (s: WorktreeSession) => string[];\n prs?: (id: string) => ArchivedPr[];\n lastSummary?: (id: string) => string | null;\n /** What archiving now would leave behind unfinished (empty: nothing). */\n waiting?: (id: string) => string[];\n /** Its Claude is in the middle of a turn (stopping it would cut the turn off). */\n working?: (id: string) => boolean;\n /** What waits in it, to list in the record (drafts, notes, a question). */\n kept?: (id: string) => ArchiveKept;\n stopDev?: (id: string) => void;\n /** Stop what still runs from its folders (a dev server or watcher its Claude started in the background,\n * running-from.ts) and say what: otherwise it holds files, and the worktree is removed only in part. */\n stopRunningFrom?: (s: WorktreeSession) => Promise<string[]>;\n /** What runs from its folders, by name, stopping nothing (an unattended archive keeps the worktree then).\n * Rejects when it can't tell, which keeps it too. */\n runningFrom?: (s: WorktreeSession) => Promise<string[]>;\n /** Repos checked out on another branch than the session's (alias → branch). */\n heads?: (s: WorktreeSession) => Record<string, string>;\n /** Each repo's branch tip (alias → commit): of `heads[alias]`, else the session's branch. */\n tips?: (s: WorktreeSession, heads: Record<string, string>) => Promise<Record<string, string>>;\n /** A kept worktree: clear its git-ignored build output. */\n clearBuildFolders?: (s: WorktreeSession) => Promise<{ folders: number; bytes: number }>;\n /** A removed worktree: its checkpoint refs, and merged local branches — the session's and the one checked out (returns the repos whose checked-out branch went). */\n tidy?: (s: WorktreeSession, heads: Record<string, string>) => Promise<string[]>;\n /** A few sentences on what was done (background; null: none). */\n summarize?: (rec: ArchiveRecord) => Promise<string | null>;\n archiveRoot?: string;\n now?: () => number;\n}\n\nexport interface ArchiveOutcome {\n ok: boolean;\n worktreeRemoved: boolean;\n keptBecause: string | null;\n transcripts: number;\n message: string;\n /** Not archived: these were waiting (archive with force to go ahead). */\n blocked?: string[];\n /** What waited in it and was kept with it (\"2 reply drafts, 1 note for its Claude\"). */\n kept?: string;\n}\n\n/** Most prompts kept in the summary: the first ones (what it was about) and the latest. */\nconst SUMMARY_PROMPTS = 40;\n\nexport const archiveRoot = (): string => path.join(getConfigDir(), 'archive');\nexport const archiveDirFor = (id: string, root = archiveRoot()): string => path.join(root, id);\n\n/** Told after each archive that went through (work web: stacked sessions move onto main). */\nconst afterArchive = new Set<(s: WorktreeSession) => void | Promise<unknown>>();\n\n/** Listen for archives (every path: the button, Ship, the PR watch, cleanup); returns the unsubscribe. A listener may be async: its failure is logged, never the archive's. */\nexport function onArchived(listener: (s: WorktreeSession) => void | Promise<unknown>): () => void {\n afterArchive.add(listener);\n return () => afterArchive.delete(listener);\n}\n\n/**\n * `merged`: the session's PR merged (the PR watch, Ship). That decides it:\n * reply drafts, undelivered notes and a question for you don't hold it up —\n * they stay with the session and are listed in the record — and only a\n * Claude in the middle of a turn does (the caller tries again later).\n */\nexport interface ArchiveOptions {\n /** Who asked: kept in the record, and shown with the archived session. */\n by?: ArchivedBy;\n force?: boolean;\n merged?: boolean;\n /** No one asked (the PR watch, a merged PR): nothing running from the worktree is stopped — it keeps it. */\n unattended?: boolean;\n}\n\nexport async function archiveSession(s: WorktreeSession, deps: ArchiveDeps, opts: ArchiveOptions = {}): Promise<ArchiveOutcome> {\n // Nothing starts its Claude again while this runs (archiving.ts).\n const out = await whileArchiving(sessionIdFor(s), () => archiveSteps(s, deps, opts));\n if (out.ok)\n for (const l of afterArchive) {\n // Sync throws and async rejections alike: a listener's trouble isn't the archive's.\n void Promise.resolve()\n .then(() => l(s))\n .catch((err) => logSwallowed('after archiving', err));\n }\n return out;\n}\n\nasync function archiveSteps(s: WorktreeSession, deps: ArchiveDeps, opts: ArchiveOptions): Promise<ArchiveOutcome> {\n const id = sessionIdFor(s);\n const root = deps.archiveRoot ?? archiveRoot();\n const dir = archiveDirFor(id, root);\n const now = deps.now ?? Date.now;\n\n // 0. Work still waiting in it would vanish from view with it.\n const waiting = opts.force\n ? []\n : opts.merged\n ? deps.working?.(id)\n ? ['its Claude is in the middle of a turn']\n : []\n : (deps.waiting?.(id) ?? []);\n if (waiting.length) {\n return {\n ok: false,\n worktreeRemoved: false,\n keptBecause: null,\n transcripts: 0,\n blocked: waiting,\n message: `Not archived: ${waiting.join('; ')}.`,\n };\n }\n\n await deps.stopClaude(id);\n try {\n deps.stopDev?.(id);\n } catch {\n /* not running */\n }\n // Which branch each repo is on: Claude may have switched from the session's.\n let heads: Record<string, string> = {};\n try {\n heads = deps.heads?.(s) ?? {};\n } catch {\n /* unreadable: the session's branch, as before */\n }\n const tips = (await deps.tips?.(s, heads).catch(() => ({}))) ?? {};\n\n // 2. The conversation. Copied before anything is removed; a copy that fails\n // stops the archive (nothing removed, nothing marked).\n const copied: ArchiveRecord['transcripts'] = [];\n // Read as its agent writes them (none when work can't read that agent's conversations).\n const toEntries = agentOf(s).conversation?.entries ?? (() => []);\n const entries: ConversationEntry[][] = [];\n try {\n fs.mkdirSync(path.join(dir, 'transcripts'), { recursive: true });\n for (const file of deps.transcripts(s)) {\n const name = path.basename(file);\n fs.copyFileSync(file, path.join(dir, 'transcripts', name));\n copied.push({ file: name, projectDir: path.basename(path.dirname(file)) });\n entries.push(toEntries(readJsonlTail(file, 64 * 1024 * 1024)));\n }\n } catch (err) {\n return {\n ok: false,\n worktreeRemoved: false,\n keptBecause: null,\n transcripts: copied.length,\n message: `Not archived: could not copy its conversation (${(err as Error).message}).`,\n };\n }\n\n // 3. Uncommitted work is saved (a snapshot commit + a patch), so it\n // doesn't keep the worktree: Restore puts it back. A save that fails\n // keeps the worktree, as before.\n const saving = deps.saveUncommitted\n ? await deps.saveUncommitted(s, dir, now()).catch((err: Error) => ({ saved: {}, error: err.message }))\n : { saved: {}, error: null };\n let saved: Record<string, SavedUncommitted> = saving.error ? {} : saving.saved;\n if (saving.error) await deps.dropSaved?.(s, saving.saved, dir).catch(() => {});\n\n // 4. The folder goes only if nothing would be lost.\n const verdict = await deps.removable(s, { uncommittedSaved: !saving.error });\n let worktreeRemoved = false;\n let keptBecause: string | null = null;\n let leftovers: string[] = [];\n let ignored: Record<string, SavedIgnored> = {};\n const ignoredDir = path.join(dir, 'ignored');\n let stopped: string[] = [];\n // Unasked (the PR watch): what runs from the folder is yours — it keeps the worktree rather than stop it, and\n // stops nothing (not even what started after this look). Processes it can't read keep it too: no guess.\n const runningThere =\n verdict.ok && opts.unattended\n ? ((await deps.runningFrom?.(s).catch(() => [\"(couldn't tell: the process list didn't answer)\"])) ?? [])\n : [];\n if (verdict.ok && runningThere.length === 0) {\n // Only for a folder that goes (never a repo's own checkout, never a kept worktree: what runs there is\n // yours), and only when you asked: what still runs from it holds its files, and git would remove it only in part.\n if (!opts.unattended) stopped = (await deps.stopRunningFrom?.(s).catch(() => [])) ?? [];\n // Local settings and the editor's state go with the folder: kept, so Restore brings them back.\n fs.rmSync(ignoredDir, { recursive: true, force: true });\n ignored = deps.saveIgnored ? await deps.saveIgnored(s, dir).catch(() => ({})) : {};\n worktreeRemoved = await deps.removeWorktree(s);\n // git deletes the files first and stops at one in use (Visual Studio's): the folder\n // that's left is no worktree any more. That's removed — and its save is the copy.\n leftovers = worktreeRemoved ? [] : (deps.halfRemoved?.(s) ?? []);\n // Removed only when every folder is gone or half-removed: a repo of a group whose\n // removal failed outright is still a worktree, and the session keeps it.\n if (leftovers.length && s.paths.every((p) => leftovers.includes(p) || !fs.existsSync(p))) worktreeRemoved = true;\n else if (!worktreeRemoved)\n keptBecause = leftovers.length\n ? `git removed ${leftovers.join(', ')} only in part (a file in use) and kept the rest`\n : 'git refused to remove the worktree';\n } else {\n keptBecause = runningThere.length\n ? `still running from it: ${runningThere.join(', ')}`\n : saving.error && !verdict.reason.includes(saving.error)\n ? `${verdict.reason} (${saving.error})`\n : verdict.reason;\n }\n // Kept: the changes are still in it, so the saves aren't needed.\n // (Not when part of it is gone: the saves are the only copy of that.)\n if (!worktreeRemoved && !leftovers.length && Object.keys(saved).length) {\n await deps.dropSaved?.(s, saved, dir).catch(() => {});\n saved = {};\n }\n if (!worktreeRemoved && !leftovers.length && Object.keys(ignored).length) {\n fs.rmSync(ignoredDir, { recursive: true, force: true });\n ignored = {};\n }\n // What waits in it (kept with the session in state.db), listed in the record.\n const kept = deps.kept?.(id);\n // Work an earlier Restore couldn't put back stays known (its ref and patch are still there).\n const earlier = readArchive(id, root);\n const unrestored = [...(earlier?.unrestored ?? []), ...Object.values(earlier?.uncommitted ?? {}).filter((u) => !u.restoredAt)];\n let branchesDeleted: string[] = [];\n let buildFolders: ArchiveRecord['buildFolders'];\n if (worktreeRemoved) branchesDeleted = (await deps.tidy?.(s, heads).catch(() => [])) ?? [];\n // Not under what still runs from it (a dev server's node_modules): kept so as to leave it alone.\n else if (keptBecause !== \"it is the repo's own checkout\" && runningThere.length === 0 && deps.clearBuildFolders) {\n buildFolders = await deps.clearBuildFolders(s).catch(() => undefined);\n }\n\n const all = promptsSince(entries, 0);\n const prompts = all.length > SUMMARY_PROMPTS ? [...all.slice(0, SUMMARY_PROMPTS / 2), ...all.slice(-SUMMARY_PROMPTS / 2)] : all;\n const record: ArchiveRecord = {\n sessionId: id,\n target: s.target,\n branch: s.branch,\n isGroup: s.isGroup,\n paths: s.paths,\n archivedAt: new Date(now()).toISOString(),\n ...(opts.by ? { archivedBy: opts.by } : {}),\n worktreeRemoved,\n keptBecause,\n ...(leftovers.length ? { leftovers } : {}),\n transcripts: copied,\n summary: {\n prompts,\n promptCount: all.length,\n lastSummary: deps.lastSummary?.(id) ?? null,\n prs: deps.prs?.(id) ?? [],\n jiraKey: s.jiraKey ?? null,\n },\n ...(Object.keys(tips).length ? { tips } : {}),\n ...(Object.keys(heads).length ? { heads } : {}),\n ...(branchesDeleted.length ? { branchesDeleted } : {}),\n ...(buildFolders && buildFolders.folders ? { buildFolders } : {}),\n ...(Object.keys(saved).length ? { uncommitted: saved } : {}),\n ...(Object.keys(ignored).length ? { ignored } : {}),\n ...(unrestored.length ? { unrestored } : {}),\n ...(keptAny(kept) ? { kept } : {}),\n };\n fs.writeFileSync(path.join(dir, 'archive.json'), JSON.stringify(record, null, 2));\n\n await deps.setArchived(s);\n // A snooze doesn't outlive the archive: Restore brings it back as it is now.\n try {\n clearSnooze(id);\n } catch {\n /* best effort */\n }\n if (deps.summarize) void writeArchiveSummary(id, deps.summarize, root).catch(() => {});\n return {\n ok: true,\n worktreeRemoved,\n keptBecause,\n transcripts: copied.length,\n message:\n (worktreeRemoved\n ? `Archived; worktree removed, conversation kept${savedFiles(saved) ? `, ${savedFiles(saved)} uncommitted file${savedFiles(saved) === 1 ? '' : 's'} saved for Restore` : ''}${leftovers.length ? `; git stopped at a file in use, so part of the folder is left (${leftovers.join(', ')}): close what holds it and delete it, or Restore puts it back` : ''}`\n : `Archived; worktree kept (${keptBecause})`) +\n (keptList(kept) ? `; kept for Restore: ${keptList(kept)}` : '') +\n (stopped.length ? `; stopped what still ran from it: ${stopped.join(', ')}` : ''),\n ...(keptList(kept) ? { kept: keptList(kept) } : {}),\n };\n}\n\nconst savedFiles = (saved: Record<string, SavedUncommitted>): number => Object.values(saved).reduce((n, u) => n + u.files, 0);\nconst keptAny = (k: ArchiveKept | undefined): k is ArchiveKept => !!k && (k.replyDrafts.length > 0 || k.notes.length > 0 || !!k.askingYou);\nconst plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;\n/** \"2 reply drafts, 1 note for its Claude, its question to you\" (empty: nothing kept). */\nexport function keptList(k: ArchiveKept | undefined): string {\n if (!keptAny(k)) return '';\n return [\n ...(k.replyDrafts.length ? [plural(k.replyDrafts.length, 'reply draft', 'reply drafts')] : []),\n ...(k.notes.length ? [plural(k.notes.length, 'note for its Claude', 'notes for its Claude')] : []),\n ...(k.askingYou ? ['its question to you'] : []),\n ].join(', ');\n}\n\n/** Ask for the written summary and store it in the record (background, after archiving). */\nexport async function writeArchiveSummary(\n id: string,\n summarize: (rec: ArchiveRecord) => Promise<string | null>,\n root = archiveRoot(),\n): Promise<string | null> {\n const rec = readArchive(id, root);\n if (!rec || rec.summary.written) return rec?.summary.written ?? null;\n const text = (await summarize(rec))?.trim() || null;\n if (!text) return null;\n const now = readArchive(id, root); // re-read: it may have changed meanwhile\n if (!now) return null;\n now.summary.written = text;\n writeArchiveRecord(now, root);\n return text;\n}\n\nexport function writeArchiveRecord(rec: ArchiveRecord, root = archiveRoot()): void {\n const file = path.join(archiveDirFor(rec.sessionId, root), 'archive.json');\n const tmp = `${file}.tmp-${process.pid}`;\n fs.writeFileSync(tmp, JSON.stringify(rec, null, 2));\n fs.renameSync(tmp, file);\n}\n\n/** An archived transcript's text, compressed or not (null: gone). */\nexport function readArchivedTranscript(id: string, file: string, root = archiveRoot()): string | null {\n const plain = path.join(archiveDirFor(id, root), 'transcripts', file);\n try {\n return fs.readFileSync(plain, 'utf8');\n } catch {\n /* compressed, or gone */\n }\n try {\n return zlib.gunzipSync(fs.readFileSync(`${plain}.gz`)).toString('utf8');\n } catch {\n return null;\n }\n}\n\n/** The archive record, or null (never archived with a copy, or unreadable). */\nexport function readArchive(id: string, root = archiveRoot()): ArchiveRecord | null {\n try {\n const raw: unknown = JSON.parse(fs.readFileSync(path.join(archiveDirFor(id, root), 'archive.json'), 'utf8'));\n return isArchiveRecord(raw) ? withValidSaves(raw) : null;\n } catch {\n return null;\n }\n}\n\nfunction isSavedIgnored(v: unknown): v is SavedIgnored {\n if (!v || typeof v !== 'object') return false;\n const o = v as Record<string, unknown>;\n return typeof o.files === 'number' && typeof o.bytes === 'number' && typeof o.skipped === 'number';\n}\n\n/** Saved work comes back only in its known shape (stored JSON); anything else is dropped from the record read. */\nfunction withValidSaves(r: ArchiveRecord): ArchiveRecord {\n const out = { ...r };\n if (r.uncommitted !== undefined) {\n const valid =\n typeof r.uncommitted === 'object' && r.uncommitted ? Object.entries(r.uncommitted).filter(([, v]) => isSavedUncommitted(v)) : [];\n if (valid.length) out.uncommitted = Object.fromEntries(valid);\n else delete out.uncommitted;\n }\n if (r.unrestored !== undefined) {\n const valid = Array.isArray(r.unrestored) ? r.unrestored.filter(isSavedUncommitted) : [];\n if (valid.length) out.unrestored = valid;\n else delete out.unrestored;\n }\n if (r.ignored !== undefined) {\n const valid = typeof r.ignored === 'object' && r.ignored ? Object.entries(r.ignored).filter(([, v]) => isSavedIgnored(v)) : [];\n if (valid.length) out.ignored = Object.fromEntries(valid);\n else delete out.ignored;\n }\n return out;\n}\n\nfunction isArchiveRecord(x: unknown): x is ArchiveRecord {\n const r = x as ArchiveRecord | null;\n return (\n !!r &&\n typeof r === 'object' &&\n typeof r.sessionId === 'string' &&\n typeof r.worktreeRemoved === 'boolean' &&\n Array.isArray(r.transcripts) &&\n !!r.summary &&\n Array.isArray(r.summary.prompts)\n );\n}\n\n/** How far back the newest restored transcript is dated: past the Terminal tab's 5 minutes of \"written just now\". */\nexport const RESTORED_AGE_MS = 10 * 60_000;\n\n/**\n * When a conversation file's last entry was written, as its agent reads it (`conversation.entries` over its\n * tail), or 0 — no time in it (an empty file, a summary only).\n */\nexport function lastEntryTime(file: string, entries: (lines: readonly unknown[]) => ConversationEntry[]): number {\n // 64 KB back almost always has a time; up to 4 MB when it doesn't (a last line can be a big tool result).\n for (const bytes of [64 * 1024, 4 * 1024 * 1024]) {\n let t = 0;\n for (const e of entries(readJsonlTail(file, bytes))) {\n const at = Date.parse(e.at);\n if (Number.isFinite(at) && at > t) t = at;\n }\n if (t || fileSize(file) <= bytes) return t;\n }\n return 0;\n}\n\nfunction fileSize(file: string): number {\n try {\n return fs.statSync(file).size;\n } catch {\n return 0;\n }\n}\n\n/**\n * Put an archived conversation back where Claude looks for it (the project\n * folder of the session's worktree), so `--continue` picks it up. Files that\n * are already there are left alone. Returns how many were restored.\n *\n * Then every conversation in that folder — restored, and kept by Claude Code (it deletes the old ones first) —\n * is dated in the order it was written (by its last entry; one with no time first), a second apart, the newest\n * a few minutes back: --continue and every \"its newest conversation\" reader take the newest, whichever were kept;\n * none reads as written just now (the Terminal tab's \"running in another terminal\"); none lands near Claude\n * Code's 30 days (cleanupPeriodDays), which would delete it.\n */\nexport function restoreArchivedTranscripts(\n s: WorktreeSession,\n root = archiveRoot(),\n /** Where its agent looks for them (agents/: `conversation.restoreDir`; none: it starts fresh, the archive keeps them). */\n restoreDir: (s: WorktreeSession) => string | null = (x) => agentOf(x).conversation?.restoreDir?.(x) ?? null,\n): number {\n const id = sessionIdFor(s);\n const rec = readArchive(id, root);\n if (!rec) return 0;\n const dest = restoreDir(s);\n if (!dest) return 0;\n const written = new Set<string>();\n for (const t of rec.transcripts) {\n const to = path.join(dest, t.file);\n if (fs.existsSync(to)) continue;\n const text = readArchivedTranscript(id, t.file, root);\n if (text === null) continue;\n fs.mkdirSync(dest, { recursive: true });\n fs.writeFileSync(to, text);\n written.add(to);\n }\n if (written.size === 0) return 0;\n // Only this session's own conversations (the archive's list): another conversation in the same folder — you\n // ran Claude there yourself — keeps its date.\n const entries = agentOf(s).conversation?.entries ?? (() => []);\n const files: Array<{ file: string; last: number }> = [];\n for (const t of rec.transcripts) {\n const file = path.join(dest, t.file);\n try {\n // Its last entry's time; with none readable (none at all, or a last line past the tail read), its own\n // date — but not for one just written, whose date is now: that one goes first, never the one resumed.\n files.push({ file, last: lastEntryTime(file, entries) || (written.has(file) ? 0 : fs.statSync(file).mtimeMs) });\n } catch {\n /* gone: nothing to date */\n }\n }\n files.sort((a, b) => a.last - b.last);\n const newest = Date.now() - RESTORED_AGE_MS;\n for (const [i, { file }] of files.entries()) {\n const at = new Date(newest - (files.length - 1 - i) * 1000);\n try {\n fs.utimesSync(file, at, at);\n } catch {\n /* dated as it is */\n }\n }\n return written.size;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { runGitAsync, runGitSync, writeTempTreeAsync } from '../diff/git-tree-snapshot.js';\n\n/**\n * A worktree's uncommitted work, kept when archiving removes the worktree\n * and put back when the session is restored. Modified, deleted and new\n * (untracked, not git-ignored) files are snapshotted into a commit on top of\n * HEAD, the way checkpoints are (a temp index: the real one is untouched),\n * kept alive by a ref in the repo (`refs/work/archive/<session>/<repo>`,\n * shared by its worktrees, so it outlives this one), and written as a binary\n * patch into the archive folder — the copy Restore applies, readable by hand.\n * Git-ignored files aren't included (build output, local settings that\n * `copyFiles` copies again); staged and unstaged come back alike, unstaged.\n */\n\n/** A bigger patch isn't kept: the worktree stays instead (a stray dump file shouldn't land in ~/.work). */\nexport const MAX_SAVED_PATCH_BYTES = 50 * 1024 * 1024;\n\nexport interface SavedUncommitted {\n /** The snapshot commit (its parent is `base`). */\n commit: string;\n /** HEAD when it was saved. */\n base: string;\n ref: string;\n files: number;\n /** The patch's file name in the archive's `uncommitted/` folder. */\n patch: string;\n /** Put back by a Restore (then not again). */\n restoredAt?: string;\n /** A Restore that couldn't put it back: why (the ref and patch stay). */\n restoreError?: string;\n}\n\nexport type SaveResult = { clean: true } | { saved: SavedUncommitted } | { error: string };\n\nconst safeName = (s: string): string => s.replace(/[^A-Za-z0-9._-]/g, '_');\n/** Where a save is kept: per session, repo and archive time, so a later archive never overwrites one a Restore couldn't put back. */\nexport const archiveRefFor = (sessionId: string, repo: string, stamp: number): string =>\n `refs/work/archive/${safeName(sessionId)}/${safeName(repo)}/${stamp}`;\n/** Every save of a session lives under this (deleted with the session). */\nexport const archiveRefsPrefix = (sessionId: string): string => `refs/work/archive/${safeName(sessionId)}/`;\nexport const uncommittedDir = (archiveDir: string): string => path.join(archiveDir, 'uncommitted');\n\nconst COMMIT_ENV = {\n GIT_AUTHOR_NAME: 'work',\n GIT_AUTHOR_EMAIL: 'work@local',\n GIT_COMMITTER_NAME: 'work',\n GIT_COMMITTER_EMAIL: 'work@local',\n};\n\n/** Save `worktree`'s uncommitted work under `ref` and as `<archiveDir>/uncommitted/<patchName>.patch`. */\nexport async function saveUncommitted(\n worktree: string,\n repo: string,\n ref: string,\n archiveDir: string,\n patchName = repo,\n maxBytes = MAX_SAVED_PATCH_BYTES,\n): Promise<SaveResult> {\n const status = await runGitAsync(worktree, { args: ['status', '--porcelain', '--untracked-files=all'] });\n if (status.status !== 0) return { error: `git can't read ${repo}` };\n const files = status.stdout.split('\\n').filter((l) => l.trim()).length;\n if (files === 0) return { clean: true };\n\n const tree = await writeTempTreeAsync(worktree, { includeWorkingTree: true });\n if (!tree?.headSha) return { error: `git couldn't snapshot ${repo}` };\n const commit = await runGitAsync(worktree, {\n args: ['commit-tree', tree.treeSha, '-p', tree.headSha, '-m', 'work archive: uncommitted changes'],\n env: { ...process.env, ...COMMIT_ENV },\n });\n const sha = commit.stdout.trim();\n if (commit.status !== 0 || !sha) return { error: `git couldn't snapshot ${repo}` };\n\n const dir = uncommittedDir(archiveDir);\n fs.mkdirSync(dir, { recursive: true });\n const patch = `${safeName(patchName)}.patch`;\n const patchPath = path.join(dir, patch);\n const diff = await runGitAsync(worktree, {\n args: ['diff', '--binary', '--no-color', '--no-ext-diff', `--output=${patchPath}`, tree.headSha, sha],\n });\n const size = fs.existsSync(patchPath) ? fs.statSync(patchPath).size : 0;\n if (diff.status !== 0 || size === 0) {\n fs.rmSync(patchPath, { force: true });\n return { error: `git couldn't write ${repo}'s changes as a patch` };\n }\n if (size > maxBytes) {\n fs.rmSync(patchPath, { force: true });\n return { error: `${repo}'s uncommitted changes are too large to keep (${Math.round(size / 1024 / 1024)} MB)` };\n }\n const pinned = await runGitAsync(worktree, { args: ['update-ref', ref, sha] });\n if (pinned.status !== 0) {\n fs.rmSync(patchPath, { force: true });\n return { error: `git couldn't keep ${repo}'s changes (update-ref)` };\n }\n return { saved: { commit: sha, base: tree.headSha, ref, files, patch } };\n}\n\n/** Undo a save that wasn't needed after all (the worktree stayed): its ref and patch go. */\nexport async function dropSaved(repoRoot: string, saved: SavedUncommitted, archiveDir: string): Promise<void> {\n await runGitAsync(repoRoot, { args: ['update-ref', '-d', saved.ref] });\n fs.rmSync(path.join(uncommittedDir(archiveDir), saved.patch), { force: true });\n}\n\n/**\n * Put saved work back into a recreated worktree: the patch applied to the\n * working tree (nothing staged). Refuses rather than mixes: when the\n * worktree already has changes of its own, or the patch doesn't apply\n * (the branch moved on) — the ref and the patch stay for doing it by hand.\n * On success the ref goes (the patch stays in the archive).\n */\nexport async function restoreUncommitted(\n worktree: string,\n saved: SavedUncommitted,\n archiveDir: string,\n): Promise<{ ok: true } | { ok: false; error: string }> {\n const patchPath = path.join(uncommittedDir(archiveDir), saved.patch);\n const byHand = `the changes are kept in ${saved.ref} and ${patchPath}`;\n if (!fs.existsSync(patchPath)) return { ok: false, error: `its saved patch is missing (${patchPath})` };\n const status = await runGitAsync(worktree, { args: ['status', '--porcelain', '--untracked-files=all'] });\n if (status.status !== 0) return { ok: false, error: `git can't read the worktree; ${byHand}` };\n if (status.stdout.trim()) return { ok: false, error: `the worktree already has changes, so they weren't mixed in; ${byHand}` };\n const check = await runGitAsync(worktree, { args: ['apply', '--binary', '--check', patchPath] });\n if (check.status !== 0) return { ok: false, error: `they no longer apply (the branch moved on); ${byHand}` };\n const apply = await runGitAsync(worktree, { args: ['apply', '--binary', patchPath] });\n if (apply.status !== 0) return { ok: false, error: `git apply failed; ${byHand}` };\n await runGitAsync(worktree, { args: ['update-ref', '-d', saved.ref] });\n return { ok: true };\n}\n\n/** Delete every saved ref of a session in a repo (the session is deleted; its archive folder goes too). */\nexport function dropSessionSaves(repoRoot: string, sessionId: string): void {\n const refs = runGitSync(repoRoot, { args: ['for-each-ref', '--format=%(refname)', archiveRefsPrefix(sessionId)] });\n for (const ref of refs.stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean))\n runGitSync(repoRoot, { args: ['update-ref', '-d', ref] });\n}\n\n/** Shape guard for the archive record's `uncommitted` map (stored JSON). */\nexport function isSavedUncommitted(x: unknown): x is SavedUncommitted {\n const v = x as SavedUncommitted | null;\n return (\n !!v &&\n typeof v === 'object' &&\n typeof v.commit === 'string' &&\n typeof v.base === 'string' &&\n typeof v.ref === 'string' &&\n typeof v.patch === 'string' &&\n typeof v.files === 'number'\n );\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport spawn from '../platform/spawn.js';\n\nexport interface TempTreeResult {\n /** Tree sha written from the temp index. */\n treeSha: string;\n /** HEAD commit sha, or null when the repo has no commits yet. Callers that\n * build a commit from `treeSha` use this as the parent. */\n headSha: string | null;\n}\n\n/**\n * Build a git tree sha for a repo WITHOUT disturbing the real index, using a\n * throwaway `GIT_INDEX_FILE`. Shared by `checkpoint.ts` (which commits the\n * tree and pins it behind a ref) and `diff-pipeline.ts` (which diffs the tree\n * against a checkpoint commit) — both previously hand-rolled this same\n * read-tree / add / write-tree dance.\n *\n * cp .git/index <tmp> (when includeWorkingTree)\n * GIT_INDEX_FILE=<tmp> git read-tree HEAD (otherwise / on copy failure)\n * GIT_INDEX_FILE=<tmp> git add -A (when includeWorkingTree)\n * GIT_INDEX_FILE=<tmp> git write-tree → treeSha\n *\n * Why the copy: an index built by `read-tree` carries no stat cache, so the\n * following `add -A` has to re-hash EVERY file in the worktree — 3.3s on a\n * mid-size repo, paid on every checkpoint and every `to=working` range diff\n * (twice over for a two-repo group). Seeding from the real index inherits its\n * stat cache, so git only hashes what actually changed: same tree sha, ~0.2s.\n * `add -A` overwrites every entry from the worktree, so staged-but-uncommitted\n * state in the copied index can't leak into the tree — the one exception is a\n * force-added ignored file, which stays (it is staged content, so keeping it\n * is the better answer anyway). An index with assume-unchanged/skip-worktree\n * entries is NOT used as a seed (see `seedFromRealIndex`).\n *\n * With `includeWorkingTree` (default), `add -A` promotes every working-tree\n * change including untracked files (honoring `.gitignore`), so the tree is a\n * full snapshot of the working tree. Without it, the tree is HEAD's tree\n * verbatim (the empty tree on a repo with no commits) — used for the\n * \"Initial\" checkpoint baseline so a diff of Initial→working reproduces the\n * full uncommitted diff instead of hiding pre-existing changes.\n *\n * Returns null on any git failure (caller should skip this repo). The temp\n * index file is always unlinked.\n */\nexport function writeTempTree(repoRoot: string, opts: { includeWorkingTree?: boolean } = {}): TempTreeResult | null {\n const steps = tempTreeSteps(repoRoot, opts.includeWorkingTree ?? true);\n let next = steps.next();\n while (!next.done) next = steps.next(runGitSync(repoRoot, next.value));\n return next.value;\n}\n\n/**\n * writeTempTree without blocking the event loop — for checkpoints, which run\n * on every Claude turn of every session (a synchronous `git add -A` on a big\n * repo froze the server for seconds, once per finishing turn). One snapshot\n * per repo at a time: turns ending together queue rather than run several\n * `add -A` over the same tree at once.\n */\nexport function writeTempTreeAsync(repoRoot: string, opts: { includeWorkingTree?: boolean } = {}): Promise<TempTreeResult | null> {\n return inRepoQueue(repoRoot, async () => {\n const steps = tempTreeSteps(repoRoot, opts.includeWorkingTree ?? true);\n let next = steps.next();\n while (!next.done) next = steps.next(await runGitAsync(repoRoot, next.value));\n return next.value;\n });\n}\n\n/** One git command of the snapshot: its args, and the env it runs with. */\nexport interface GitStep {\n args: string[];\n env?: NodeJS.ProcessEnv;\n}\nexport interface GitResult {\n status: number | null;\n stdout: string;\n}\n\n/**\n * The snapshot's steps, once, for both drivers: yields each git command and\n * gets its result back; returns the tree. (fs work in between — copying the\n * index, removing the temp file — is quick and stays synchronous.)\n */\nfunction* tempTreeSteps(repoRoot: string, includeWorkingTree: boolean): Generator<GitStep, TempTreeResult | null, GitResult> {\n const tmpIndex = path.join(os.tmpdir(), `wd-tree-${process.pid}-${crypto.randomBytes(6).toString('hex')}.idx`);\n const env: NodeJS.ProcessEnv = { ...process.env, GIT_INDEX_FILE: tmpIndex };\n try {\n const headSha = ((yield { args: ['rev-parse', '--verify', 'HEAD'] }).stdout ?? '').trim() || null;\n\n // The working-tree snapshot only needs a starting point that `add -A`\n // will overwrite, so prefer the warm real index (its stat cache: git\n // re-hashes only what changed); HEAD's tree is the fallback. A HEAD-only\n // snapshot must read HEAD verbatim.\n let seeded = false;\n if (includeWorkingTree) {\n const out = (yield { args: ['rev-parse', '--git-path', 'index'] }).stdout;\n if (seedIndexCopy(repoRoot, out, tmpIndex)) {\n // assume-unchanged / skip-worktree bits ride along in the copy, and\n // `add -A` trusts them and never re-reads those files — an edit to a\n // locally-tweaked config would silently vanish from the snapshot. The\n // read-tree index has no such bits, so fall back to it when any exist.\n // `ls-files -v` tags assume-unchanged with a lowercase letter and\n // skip-worktree with S.\n const listed = yield { args: ['ls-files', '-v'], env };\n const flagged =\n listed.status !== 0 ||\n (listed.stdout ?? '').split('\\n').some((line) => {\n const tag = line.charAt(0);\n return tag === 'S' || (tag >= 'a' && tag <= 'z');\n });\n if (flagged) removeQuietly(tmpIndex);\n else seeded = true;\n }\n }\n if (!seeded && headSha) {\n if ((yield { args: ['read-tree', 'HEAD'], env }).status !== 0) return null;\n }\n if (includeWorkingTree) {\n // `-A` against a temp index seeded from HEAD (or empty) captures the\n // full working-tree state, subject to .gitignore.\n if ((yield { args: ['add', '-A'], env }).status !== 0) return null;\n }\n const wt = yield { args: ['write-tree'], env };\n if (wt.status !== 0 || !wt.stdout) return null;\n return { treeSha: wt.stdout.trim(), headSha };\n } finally {\n removeQuietly(tmpIndex);\n }\n}\n\n/** Copy the repo's real index (`git rev-parse --git-path index` output,\n * relative to the repo root in a linked worktree) to `tmpIndex`, keeping\n * its mtime. False when there's nothing to copy (fresh repo). */\nfunction seedIndexCopy(repoRoot: string, gitPathOut: string, tmpIndex: string): boolean {\n try {\n if (!gitPathOut) return false;\n const realIndex = path.resolve(repoRoot, gitPathOut.trim());\n if (!fs.existsSync(realIndex)) return false;\n fs.copyFileSync(realIndex, tmpIndex);\n // Carry the real index's mtime over. Git re-hashes \"racily clean\"\n // entries — file mtime >= the index file's own mtime — rather than\n // trusting their cached stat. A copy stamped \"now\" would make those\n // entries look safely clean, and a same-size edit landing in the same\n // timestamp tick as an index refresh would be missed. copyFileSync\n // preserves times on Windows (CopyFileW) but not on Linux/macOS.\n const st = fs.statSync(realIndex);\n fs.utimesSync(tmpIndex, st.atime, st.mtime);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction removeQuietly(file: string): void {\n try {\n if (fs.existsSync(file)) fs.unlinkSync(file);\n } catch {\n // Temp-file leftover isn't fatal — the OS cleans it eventually.\n }\n}\n\nconst GIT_MAX_BUFFER = 64 * 1024 * 1024;\n\nexport function runGitSync(cwd: string, step: GitStep): GitResult {\n const r = spawn.sync('git', step.args, {\n cwd,\n encoding: 'utf-8',\n env: step.env ?? process.env,\n windowsHide: true,\n maxBuffer: GIT_MAX_BUFFER,\n });\n return { status: r.status, stdout: r.stdout ?? '' };\n}\n\n/** A git command off the event loop (argv only, no shell). */\nexport function runGitAsync(cwd: string, step: GitStep): Promise<GitResult> {\n return new Promise((resolve) => {\n let stdout = '';\n let size = 0;\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn('git', step.args, { cwd, env: step.env ?? process.env, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });\n } catch {\n resolve({ status: null, stdout: '' });\n return;\n }\n child.stdout?.setEncoding('utf-8');\n child.stdout?.on('data', (d: string) => {\n size += d.length;\n if (size <= GIT_MAX_BUFFER) stdout += d;\n });\n child.on('error', () => resolve({ status: null, stdout: '' }));\n child.on('close', (code) => resolve({ status: code, stdout }));\n });\n}\n\nconst repoQueues = new Map<string, Promise<unknown>>();\n\n/** Run `fn` after whatever is queued for this repo; the queue empties itself. */\nexport function inRepoQueue<T>(repoRoot: string, fn: () => Promise<T>): Promise<T> {\n const key = path.resolve(repoRoot).toLowerCase();\n const prev = repoQueues.get(key) ?? Promise.resolve();\n const run = prev.then(fn, fn);\n const tail = run.catch(() => {});\n repoQueues.set(key, tail);\n void tail.then(() => {\n if (repoQueues.get(key) === tail) repoQueues.delete(key);\n });\n return run;\n}\n","import { debugLog } from './logger.js';\n\n/**\n * \"Best effort\" without flying blind. Plenty of work's side paths must never\n * break the main one — a Claude hook must not block the turn, a failed\n * status write must not fail a request — so errors are swallowed. But a\n * silent `catch {}` makes those failures invisible when someone asks \"why\n * didn't my session show up / get restored / get a status?\". These helpers\n * swallow AND record to ~/.work/debug.log (rotated), labelled.\n *\n * Use for failures that would explain a symptom. Plain noise — unlinking a\n * file that's already gone, writing to a socket that just closed — can stay\n * a bare catch.\n */\n\nexport function logSwallowed(label: string, err: unknown): void {\n const e = err as { code?: string; message?: string } | null;\n const detail = e?.message ?? String(err);\n debugLog('WARN', `[best-effort] ${label}: ${e?.code ? `${e.code} ` : ''}${detail}`);\n}\n\n/** Run `fn`; on throw, log it and return `fallback`. */\nexport function bestEffort<T>(label: string, fn: () => T, fallback?: T): T | undefined {\n try {\n return fn();\n } catch (err) {\n logSwallowed(label, err);\n return fallback;\n }\n}\n\n/** Async variant; also catches rejections. */\nexport async function bestEffortAsync<T>(label: string, fn: () => Promise<T>, fallback?: T): Promise<T | undefined> {\n try {\n return await fn();\n } catch (err) {\n logSwallowed(label, err);\n return fallback;\n }\n}\n\n/** For promise chains: `.catch(swallow('label'))`. */\nexport function swallow(label: string): (err: unknown) => undefined {\n return (err) => {\n logSwallowed(label, err);\n return undefined;\n };\n}\n","/**\n * Where a session's pull request stands, in one word and one line — the\n * session header, the rail's tooltip, the Inbox and `work sessions` say\n * the same. Pure and import-free: the SPA and the demo import it.\n *\n * A PR waiting on others (reviewers, checks) keeps the session out of the\n * Inbox (\"In review\"); it comes back when the PR wants you again: approved\n * with checks passing (ready to merge), a merge conflict, or failing checks.\n * Review comments come back on their own (`openReviewThreads`).\n */\n\n/** What the stage reads of a PR (ShipPr, the PR watch's last check). */\nexport interface StagePr {\n number: number;\n url: string;\n state: 'OPEN' | 'MERGED' | 'CLOSED';\n isDraft: boolean;\n mergeStateStatus: string;\n checks: 'pass' | 'fail' | 'pending' | 'none';\n headSha: string;\n /** APPROVED | CHANGES_REQUESTED | REVIEW_REQUIRED, or '' when the repo requires no review. */\n reviewDecision?: string;\n}\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 /** Working because a background agent its turn started is still at it (its turn ended, its prompt is free): what it is. */\n background?: { what: string | null };\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: {\n known: boolean;\n hosted: boolean;\n /** A background agent its conversation started is still at it since its turn ended (asked only when it matters). */\n background?: () => { what: string | null } | null;\n },\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 // Its turn ended, but Claude Code is still busy (said before that end, so older than the hook) and a background\n // agent it started has written since: the turn handed its work to that agent, which is still at it (reported:\n // \"handing it to a background agent\" read Idle). Its end comes back as a new turn, and Claude Code says idle then.\n if (live?.state === 'busy' && status.state === 'idle') {\n const work = opts.background?.();\n // Working, but not on a turn of yours: its prompt is free (the dashboard says \"In background\", what it is).\n if (work) return { ...status, state: 'working', seen: true, stale: false, background: { what: work.what } };\n }\n if (!live && opts.known && !opts.hosted && (status.state === 'working' || status.state === 'needs_input')) {\n return { ...status, state: 'idle', seen: true, stale: true };\n }\n return status;\n}\n\n/** When an idle session's last turn ended: the Stop hook's time, else (a row from before it was kept) `since`. */\nexport function idleFrom(status: SessionStatus): number {\n return Date.parse(status.turnEndedAt ?? '') || Date.parse(status.since) || 0;\n}\n\n/**\n * The newest entry that is a turn's work: your prompt or `!` command and its\n * output, the agent's message or tool call, a tool's result, a background\n * task's result. Not what the agent writes around a turn (durations, hook\n * summaries, away summaries, PR links, titles), slash commands, compaction\n * or meta lines (the agent's mapping marks those: `meta`, no `turn`). Pure;\n * 0 when there is none.\n */\nexport function lastTurnEntryMs(entries: readonly ConversationEntry[]): number {\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i];\n if (e.meta) continue;\n if (e.role === 'other' && !e.turn) continue;\n const ms = Date.parse(e.at);\n if (ms) return ms;\n }\n return 0;\n}\n\n// ---- persistence ----------------------------------------------------------\n\n// One row per session in state.db's `session_status` (db.ts). Hooks for\n// different sessions touch different rows; same-session updates are\n// transactions, so two hooks racing can't lose an event.\n\nfunction isStatus(x: unknown): x is SessionStatus {\n const s = x as SessionStatus | null;\n return !!s && typeof s === 'object' && typeof s.state === 'string' && typeof s.updatedAt === 'string';\n}\n\nfunction readRow(d: Db, sessionId: string): SessionStatus | null {\n const r = d.prepare('SELECT data FROM session_status WHERE session_id = ?').get(sessionId) as { data: string } | undefined;\n const s = r ? json.parse(r.data) : null;\n return isStatus(s) ? s : null;\n}\n\nexport function readStatus(sessionId: string): SessionStatus | null {\n return withDb((d) => readRow(d, sessionId));\n}\n\nasync function updateStatus(\n sessionId: string,\n fn: (prev: SessionStatus | null) => SessionStatus | null,\n): Promise<{ prev: SessionStatus | null; next: SessionStatus | null }> {\n return tx((d) => {\n const prev = readRow(d, sessionId);\n const next = fn(prev);\n if (next) {\n d.prepare('INSERT OR REPLACE INTO session_status (session_id, data) VALUES (?, ?)').run(sessionId, JSON.stringify(next));\n }\n return { prev, next };\n });\n}\n\n/**\n * Apply a hook event and persist it, keeping the pre-event state in\n * `prevState` for the server's notification decision.\n */\nexport function recordStatusEvent(\n sessionId: string,\n event: StatusEvent,\n now: Date = new Date(),\n): Promise<{ prev: SessionStatus | null; next: SessionStatus | null }> {\n return updateStatus(sessionId, (prev) => ({\n ...applyStatusEvent(prev, event, now),\n // A Stop ends a turn even when no prompt hook said one began (a `!`\n // command, a background task's result): as far as notifying goes, it\n // was working — so you hear that it finished.\n prevState: event.kind === 'stop' && prev?.state === 'idle' ? 'working' : (prev?.state ?? null),\n }));\n}\n\n/**\n * Its Claude is in the middle of a turn: working, or stopped mid-turn at a\n * dialog for you (a permission prompt, a question) — a needs-input state\n * entered after the last turn ended. A finished turn that asks you something\n * (DECISION NEEDED, recorded by the Stop) is not: its turn is over. Stopping\n * a Claude mid-turn cuts the turn off (a pending tool call is lost), so the\n * merged-work archive waits for this, and only this.\n */\nexport function turnInProgress(s: Pick<SessionStatus, 'state' | 'since' | 'turnEndedAt'> | null): boolean {\n if (!s) return false;\n if (s.state === 'working') return true;\n if (s.state !== 'needs_input') return false;\n const ended = s.turnEndedAt ? Date.parse(s.turnEndedAt) : NaN;\n return !(ended >= Date.parse(s.since));\n}\n\n/** The user looked at it (opened it in the dashboard). */\nexport async function markSeen(sessionId: string): Promise<SessionStatus | null> {\n const { next } = await updateStatus(sessionId, (prev) =>\n prev && !prev.seen ? { ...prev, seen: true, updatedAt: new Date().toISOString() } : prev,\n );\n return next;\n}\n\n/**\n * Whether a status change deserves a desktop notification / status hook:\n * only on entering a state that wants the user — needs_input from anything\n * else, or idle out of a turn (a finished turn). Repeat events (a second\n * Stop, the 60 s idle nudge) stay silent.\n *\n * \"Out of a turn\" includes needs_input: approving a permission prompt fires\n * no hook, so a turn that paused for one is still stored as needs_input\n * when its Stop arrives — and that finish must notify like any other.\n */\nexport function notifyKindForTransition(\n prev: Pick<SessionStatus, 'state'> | null,\n next: Pick<SessionStatus, 'state'> | null,\n): 'idle' | 'needs_input' | null {\n if (!next) return null;\n if (next.state === 'needs_input' && prev?.state !== 'needs_input') return 'needs_input';\n if (next.state === 'idle' && (prev?.state === 'working' || prev?.state === 'needs_input')) return 'idle';\n return null;\n}\n","import { json, withDb } from '../platform/db.js';\nimport type { PrStageKind } from '../pr/pr-stage.js';\nimport { snoozeFor, snoozeUntil, type Snooze } from './snooze.js';\nimport { readStatus } from '../status/session-status.js';\n\n/** Snoozes, one per session, in state.db `session_snooze` (gone with the session: purgeSessionRows). */\n\nfunction isSnooze(v: unknown): v is Snooze {\n const o = v as Snooze | null;\n return !!o && typeof o === 'object' && (o.until === null || typeof o.until === 'string') && typeof o.at === 'string';\n}\n\nexport function readSnooze(sessionId: string): Snooze | null {\n const row = withDb(\n (d) => d.prepare('SELECT data FROM session_snooze WHERE session_id = ?').get(sessionId) as { data: string } | undefined,\n );\n const v = row ? json.parse(row.data) : null;\n return isSnooze(v) ? v : null;\n}\n\n/** Every session's snooze (one query for the whole session list). */\nexport function allSnoozes(): Map<string, Snooze> {\n const rows = withDb((d) => d.prepare('SELECT session_id, data FROM session_snooze').all() as Array<{ session_id: string; data: string }>);\n const out = new Map<string, Snooze>();\n for (const r of rows) {\n const v = json.parse(r.data);\n if (isSnooze(v)) out.set(r.session_id, v);\n }\n return out;\n}\n\nexport function saveSnooze(sessionId: string, snooze: Snooze): void {\n withDb((d) => d.prepare('INSERT OR REPLACE INTO session_snooze (session_id, data) VALUES (?, ?)').run(sessionId, JSON.stringify(snooze)));\n}\n\nexport function clearSnooze(sessionId: string): boolean {\n return withDb((d) => d.prepare('DELETE FROM session_snooze WHERE session_id = ?').run(sessionId).changes > 0);\n}\n\n/** A snooze asked for: one of the choices, or until a time. */\nexport type SnoozeRequest = { for: '2h' | 'tomorrow' | 'change' } | { until: string };\n\n/** Validate a request body as one; null when it isn't. */\nexport function cleanSnoozeRequest(raw: unknown): SnoozeRequest | null {\n const o = raw as Record<string, unknown> | null;\n if (!o || typeof o !== 'object') return null;\n if (o.for === '2h' || o.for === 'tomorrow' || o.for === 'change') return { for: o.for };\n if (typeof o.until === 'string' && o.until) return { until: o.until };\n return null;\n}\n\n/**\n * Snooze a session — the dashboard's menu and `work snooze` both. \"Until it\n * changes\" is taken against the status the hooks recorded (and the review\n * threads the caller knows of), as the check that ends it compares.\n */\nexport function requestSnooze(\n sessionId: string,\n req: SnoozeRequest,\n shown: { openReviewThreads?: number; prStage?: { kind: PrStageKind; key: string } | null } = {},\n now = new Date(),\n): { ok: true; snooze: Snooze } | { ok: false; error: string } {\n const snooze =\n 'until' in req\n ? snoozeUntil(req.until, now)\n : snoozeFor(\n req.for,\n { attention: readStatus(sessionId), openReviewThreads: shown.openReviewThreads ?? 0, prStage: shown.prStage },\n now,\n );\n if (!snooze) return { ok: false, error: 'not a time to snooze until: give one in the next 30 days' };\n saveSnooze(sessionId, snooze);\n return { ok: true, snooze };\n}\n","/**\n * Sessions being archived right now (archiveSession, from its first step to\n * its last). Nothing may start their Claude meanwhile: archiving stops it\n * first, and a Terminal tab still open on the session would otherwise start\n * it again a moment later — an archived session with a live Claude, put back\n * by the PTY host after every restart. ensurePty refuses them, and archived\n * ones (pty-pool.ts).\n *\n * In memory, per process: archiving runs in work web, which is also what\n * starts session Claudes.\n */\n\nconst inProgress = new Set<string>();\n\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 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 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 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 { sessionRepos } from '../sessions/session-repos.js';\nimport type { DevServerState } from '../api-types.js';\n\n/**\n * Per-worktree dev server + preview.\n *\n * Every worktree already owns a stable port ($PORT, see port-allocator.ts)\n * that its Claude and anything it runs inherit. This module answers \"is\n * something serving on it?\" and can run the repo's dev command there —\n * `devCommands` in config.json, keyed by repo alias, e.g.\n * `{ \"web\": \"npm run dev -- --port $PORT\" }`. In a group the first repo\n * (in the session's order) with a command gets the port.\n *\n * The command comes from the user's own config and runs with `shell: true`\n * (like statusHooks); the worktree path is the spawn cwd, never part of\n * the command string. It runs in the background, its output in\n * ~/.work/dev/<session>.log, its pid in state.db (`dev_runs`) — so a\n * `work web` restart still knows it and can stop it.\n */\n\nfunction devDir(): string {\n const dir = path.join(getConfigDir(), 'dev');\n fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\nexport const devLogFile = (id: string) => path.join(devDir(), `${id}.log`);\n\ninterface RunRecord {\n pid: number;\n command: string;\n cwd: string;\n startedAt: string;\n /** Executable at that pid when we started it (the shell), if known.\n * Records from before this field (imported from the JSON files) have\n * none, and are trusted on pid + boot alone. */\n image?: string | null;\n}\n\n/** A run started this close to a boot can't be told from one started\n * before it, if the clock was stepped meanwhile (NTP after sleep). */\nconst REBOOT_SLACK_MS = 5 * 60_000;\n\nfunction isRunRecord(x: unknown): x is RunRecord {\n const r = x as RunRecord | null;\n return !!r && typeof r === 'object' && typeof r.pid === 'number' && typeof r.command === 'string' && typeof r.startedAt === 'string';\n}\n\n/** The machine has rebooted since this run started, so its pid — if alive —\n * belongs to someone else (Windows reuses pids quickly). Compares the boot\n * time with the run's own start time, both on the wall clock, so a clock\n * step of a few minutes doesn't turn a live run into \"another boot\". */\nfunction rebootedSince(r: RunRecord): boolean {\n const started = Date.parse(r.startedAt);\n if (!Number.isFinite(started)) return true; // unknown start: don't trust it\n return bootTime() - started > REBOOT_SLACK_MS;\n}\n\n/**\n * The live run for a session, or null. A saved pid is trusted only while\n * it is alive and from this boot: after a reboot the row survives but the\n * number may belong to an unrelated process — which the header would show\n * as \"running\" and Stop would kill.\n */\nfunction readRun(id: string): RunRecord | null {\n const row = withDb((d) => d.prepare('SELECT data FROM dev_runs WHERE session_id = ?').get(id) as { data: string } | undefined);\n if (!row) return null;\n const r = json.parse(row.data);\n if (isRunRecord(r) && !rebootedSince(r) && isPidAlive(r.pid)) return r;\n forgetRun(id); // it died on its own, or the machine rebooted\n return null;\n}\n\nfunction forgetRun(id: string): void {\n withDb((d) => d.prepare('DELETE FROM dev_runs WHERE session_id = ?').run(id));\n}\n\n/** The dev command for this session and where it runs, or null. */\nexport function devCommandFor(\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): { command: string; cwd: string; repo: string } | null {\n const commands = config?.devCommands ?? {};\n // Each folder's repo: recorded on the session, else (a row from before) the group\n // member named like the folder (resolve.ts names a worktree folder after its repo's).\n // A folder no member matches has no dev command, as before.\n for (const { alias, path: p, guessed } of sessionRepos(session, config)) {\n if (guessed) continue;\n const command = commands[alias];\n if (typeof command === 'string' && command.trim()) return { command, cwd: p, repo: alias };\n }\n return null;\n}\n\n/** Something accepts TCP connections on localhost:port (IPv4 or IPv6). */\nexport function isListening(port: number, timeoutMs = 400): Promise<boolean> {\n const probe = (host: string) =>\n new Promise<boolean>((resolve) => {\n const sock = net.connect({ host, port });\n const done = (ok: boolean) => {\n sock.destroy();\n resolve(ok);\n };\n sock.setTimeout(timeoutMs, () => done(false));\n sock.once('connect', () => done(true));\n sock.once('error', () => done(false));\n });\n return probe('127.0.0.1').then((ok) => ok || probe('::1'));\n}\n\nexport async function devState(\n id: string,\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): Promise<DevServerState> {\n const port = session.port ?? null;\n const cmd = devCommandFor(session, config);\n const run = readRun(id);\n return {\n port,\n listening: port !== null ? await isListening(port) : false,\n url: port !== null ? `http://localhost:${port}/` : null,\n command: cmd?.command ?? null,\n repo: cmd?.repo ?? null,\n running: run ? { pid: run.pid, startedAt: run.startedAt } : null,\n };\n}\n\nexport type DevStartOutcome = { ok: true; pid: number } | { ok: false; status: 400 | 409; error: string };\n\nexport function startDev(\n id: string,\n session: WorktreeSession,\n config: Pick<WorkConfig, 'repos' | 'groups' | 'devCommands'> | null,\n): DevStartOutcome {\n if (session.port === undefined) return { ok: false, status: 400, error: 'this worktree has no port — recreate it with work tree' };\n const cmd = devCommandFor(session, config);\n if (!cmd) return { ok: false, status: 400, error: 'no dev command — set devCommands in ~/.work/config.json' };\n if (!fs.existsSync(cmd.cwd)) return { ok: false, status: 400, error: `worktree is gone: ${cmd.cwd}` };\n const running = readRun(id);\n if (running) return { ok: false, status: 409, error: `already running (pid ${running.pid})` };\n\n const log = fs.openSync(devLogFile(id), 'w');\n try {\n fs.writeSync(log, `$ ${cmd.command} (PORT=${session.port}, in ${cmd.cwd})\\n`);\n const child = spawn(cmd.command, {\n cwd: cmd.cwd,\n shell: true,\n // POSIX: its own process group, so Stop can signal the whole tree.\n // Windows: NOT detached — a DETACHED_PROCESS cmd.exe drops its\n // children's output — and taskkill /T stops the tree instead.\n detached: process.platform !== 'win32',\n windowsHide: true,\n stdio: ['ignore', log, log],\n 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","import path from 'node:path';\nimport type { WorkConfig } from '../platform/config.js';\nimport type { WorktreeSession } from './session-types.js';\n\n/**\n * A session's repos: which repo alias each of its folders is a checkout of.\n * The session owns that list (`WorktreeSession.repos`, recorded when it is\n * made), so a session can hold a repo its group's config doesn't name, and\n * keep one its group lost. Rows from before it was recorded are read as they\n * always were: a group's from the config, a single repo's by its target.\n * Pure: the config is passed in.\n */\n\ntype SessionShape = Pick<WorktreeSession, 'target' | 'isGroup' | 'paths' | 'repos'>;\n\nexport interface SessionRepo {\n alias: string;\n path: string;\n /** Legacy only: no repo of the group's config has this folder's name, so the\n * alias is just the folder's name (readers that used to find no repo there skip it). */\n guessed?: true;\n}\n\n/** Its recorded list, zipped with its paths — null on a row from before (or one whose list doesn't match its paths). */\nexport function recordedRepos(s: Pick<WorktreeSession, 'paths' | 'repos'>): SessionRepo[] | null {\n if (!Array.isArray(s.repos) || s.repos.length !== s.paths.length || s.repos.length === 0) return null;\n if (!s.repos.every((a) => typeof a === 'string' && a)) return null;\n return s.repos.map((alias, i) => ({ alias, path: s.paths[i] }));\n}\n\nconst sameName = (a: string, b: string) => path.basename(a).toLowerCase() === path.basename(b).toLowerCase();\n\n/**\n * Each of its folders with the repo it is a checkout of. Recorded: as\n * recorded. Legacy: a group's folder is named after its repo's folder, so\n * the group's member (config) with that folder name, else the folder's own\n * name (`guessed`); a single repo's is its target.\n */\nexport function sessionRepos(s: SessionShape, config: Partial<Pick<WorkConfig, 'repos' | 'groups'>> | null | undefined): SessionRepo[] {\n const recorded = recordedRepos(s);\n if (recorded) return recorded;\n if (!s.isGroup) return s.paths.length ? [{ alias: s.target, path: s.paths[0] }] : [];\n // A list that is there but doesn't match its paths (a damaged row): each folder is matched\n // by name among the recorded aliases first — never read as a row from before, whose group\n // config may name none of them (a repo's session folder has no group at all).\n const listed = Array.isArray(s.repos) ? s.repos.filter((a): a is string => typeof a === 'string' && !!a) : [];\n const members = [...new Set([...listed, ...(config?.groups?.[s.target] ?? [])])];\n return s.paths.map((p) => {\n const alias = members.find((a) => {\n const repo = config?.repos?.[a];\n return repo !== undefined && sameName(repo, p);\n });\n return alias ? { alias, path: p } : { alias: path.basename(p), path: p, guessed: true as const };\n });\n}\n\n/**\n * The repo aliases a session acts over (archive, clean-up, checkpoints…).\n * Recorded: its own. Legacy, as before: a group's config members, a single\n * repo's target.\n */\nexport function sessionAliases(s: SessionShape, config: Partial<Pick<WorkConfig, 'repos' | 'groups'>> | null | undefined): string[] {\n const recorded = recordedRepos(s);\n if (recorded) return recorded.map((r) => r.alias);\n // A damaged list: what its folders are matched to, never the group's config alone.\n // (Without the repos' folders to match by, what it lists.)\n if (Array.isArray(s.repos) && s.isGroup)\n return config?.repos\n ? sessionRepos(s, config)\n .filter((r) => !r.guessed)\n .map((r) => r.alias)\n : s.repos.filter((a): a is string => typeof a === 'string' && !!a);\n return s.isGroup ? (config?.groups?.[s.target] ?? []) : [s.target];\n}\n\n/**\n * A session that is a folder of repos (a group's, or a repo's made with\n * `sessionFolders`): Claude runs in the folder, and a repo can be added to it.\n */\nexport function isFolderSession(s: Pick<WorktreeSession, 'isGroup'>): boolean {\n return s.isGroup;\n}\n","/**\n * Per-scope diff checkpoints.\n *\n * A \"checkpoint\" is a snapshot of every repo in a scope's working tree\n * (including untracked files) captured as a real git commit and held alive\n * by `refs/wd/<scope-hash>/<n>` in each repo. A small JSON manifest at\n * `~/.work/diffs/<scope-hash>.checkpoints.json` records the per-checkpoint\n * timestamp + repo→sha mapping so the SPA can list checkpoints and ask for\n * a diff between any two (or between one and the live working tree).\n *\n * Snapshots are taken automatically:\n * - once when a scope is first registered (the \"Initial\" point). This\n * baseline captures HEAD's tree, NOT the working tree — so a range of\n * \"Initial → working\" equals the full uncommitted diff (`git diff HEAD`\n * plus untracked), and any pre-existing uncommitted work the user\n * already had when `wd` launched stays visible instead of being baked\n * into an invisible baseline.\n * - again whenever the scope's fs-watch debounce fires AND the working\n * tree differs from the previous snapshot (the dedup keeps idle saves\n * from spawning empty checkpoints)\n *\n * The capture mechanism uses a temp git index file so the real index is\n * never disturbed:\n *\n * GIT_INDEX_FILE=<tmp> git read-tree HEAD\n * GIT_INDEX_FILE=<tmp> git add -A\n * GIT_INDEX_FILE=<tmp> git write-tree → <tree-sha>\n * git commit-tree <tree-sha> -p HEAD -m \"wd checkpoint\" → <commit-sha>\n * git update-ref refs/wd/<hash>/<n> <commit-sha>\n *\n * Untracked files end up in the snapshot because `git add -A` against the\n * temp index promotes them. `.gitignore` is honoured (same as the diff\n * pipeline's untracked detection).\n */\n\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport spawn from '../platform/spawn.js';\nimport { atomicWriteFile, ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { runGitAsync, writeTempTreeAsync } from './git-tree-snapshot.js';\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,OAAOA,UAAQ;AACf,OAAOC,YAAU;;;ACYjB,IAAM,YAAY;AAElB,IAAM,UAAU,IAAI;AASb,SAAS,wBAAwB,SAAkC;AACxE,MAA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,CAAC,GAAG,IAAI,KAAK,EAAE,KAAK;AACpC,cAAM,OAAO,QAAQ,WAAW,QAAQ,UAAU,QAAQ,MAAM,CAAC,GAAG,MAAM,MAAM,QAAQ,CAAC,CAAC;AAC1F,YAAI,CAAC,MAAM;AACT,mBAAS,QAAQ,IAAI;AACrB,iBAAO,GAAG,QAAQ;AAClB;AAAA,QACF;AAAA,MACF,OAAO;AACL,eAAO,GAAG,GAAG;AACb;AAAA,MACF;AAAA,IACF;AACA,WAAO,EAAE,OAAO,QAAQ;AAAA,EAC1B,CAAC;AACH;AAEA,IAAM,WAAW,CAAC,GAAW,MAAc;AACzC,QAAM,IAAI,CAAC,MAAcD,OAAK,QAAQ,CAAC,EAAE,MAAMA,OAAK,GAAG,EAAE,KAAK,GAAG,EAAE,YAAY;AAC/E,SAAO,EAAE,CAAC,MAAM,EAAE,CAAC;AACrB;AAUA,eAAsB,+BAA+B,QAAgB,YAAoB,UAAqC;AAC5H,QAAM,SAAS,YAAY,EAAE;AAAA,IAC3B,CAAC,MAAM,EAAE,WAAW,UAAU,CAAC,EAAE,WAAW,EAAE,WAAW,cAAc,EAAE,MAAM,WAAW,KAAK,SAAS,EAAE,MAAM,CAAC,GAAG,QAAQ;AAAA,EAC9H;AACA,aAAW,KAAK,OAAQ,OAAM,cAAc,EAAE,QAAQ,EAAE,MAAM;AAC9D,SAAO,OAAO,IAAI,CAAC,MAAM,EAAE,MAAM;AACnC;","names":["fs","path","fs","fs","fs","path","fs","fs","path","fs","lastTurnEntryMs","rows","path","path","fs","valid","fs","path","zlib","path","fs","zlib","fs","net","path","path","path","fs","net","fs","os","path","path","os","fs","path","crypto","fs","path","path","fs","crypto","path","scopes","fs","path","fs"]}
|