@moberg_hr/work-tree 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +4 -0
  2. package/dist/{answer-2J4XLIP7.js → answer-BD5A6XMM.js} +3 -3
  3. package/dist/{attach-CZKRNPAJ.js → attach-ID6KEOQ5.js} +2 -2
  4. package/dist/bin.js +2 -2
  5. package/dist/{block-RAIDCJ4F.js → block-AQDYKNWG.js} +3 -3
  6. package/dist/{catchup-VVOPL2S5.js → catchup-3454JUMS.js} +3 -3
  7. package/dist/{chunk-HIZBWYPL.js → chunk-2PRI27ND.js} +2 -2
  8. package/dist/{chunk-WF5SBVPZ.js → chunk-CA7LI4N2.js} +18 -1
  9. package/dist/chunk-CA7LI4N2.js.map +1 -0
  10. package/dist/{chunk-SNAQOHNL.js → chunk-G2WWMJJB.js} +5 -3
  11. package/dist/chunk-G2WWMJJB.js.map +1 -0
  12. package/dist/{chunk-CVAVYDXO.js → chunk-ITNPMWPY.js} +3 -3
  13. package/dist/{chunk-HWUINPIL.js → chunk-O3VNU7EZ.js} +2 -2
  14. package/dist/{chunk-BR6OPEE4.js → chunk-OYQFLBLO.js} +2 -2
  15. package/dist/{chunk-C7W5TMFB.js → chunk-QECEHQ4U.js} +27 -27
  16. package/dist/chunk-UJD6QUGG.js +9 -0
  17. package/dist/{chunk-HSICXDMZ.js → chunk-VHWQE2WE.js} +2 -2
  18. package/dist/{cleanup-LDBGWEKZ.js → cleanup-E6OD3TUM.js} +5 -5
  19. package/dist/{cli-UATB4RM2.js → cli-O6IF63TS.js} +3 -3
  20. package/dist/{fork-BKI5UNNS.js → fork-XJPZFNMX.js} +3 -3
  21. package/dist/{hook-SLMZT5OV.js → hook-MTWRSD4S.js} +9 -3
  22. package/dist/hook-MTWRSD4S.js.map +1 -0
  23. package/dist/{note-WGM6LCP2.js → note-M53Q6EWY.js} +3 -3
  24. package/dist/{pin-MQ5ZE37R.js → pin-VMM5TINM.js} +3 -3
  25. package/dist/{pr-527S5HXB.js → pr-EHF642TN.js} +2 -2
  26. package/dist/{prune-AIS5YEXP.js → prune-3DRPO3VJ.js} +4 -4
  27. package/dist/{read-AP6T3ZGN.js → read-DDQDRHRB.js} +3 -3
  28. package/dist/{remove-YGUTSKZP.js → remove-XJYZVAPX.js} +3 -3
  29. package/dist/{screen-DNX4K23V.js → screen-XMGBRC25.js} +3 -3
  30. package/dist/{section-TXLC5XO3.js → section-OO7IOLI7.js} +3 -3
  31. package/dist/{send-6X46WZLC.js → send-GMG27KFT.js} +3 -3
  32. package/dist/{sessions-T3QDTNP7.js → sessions-GOP5Y6LS.js} +3 -3
  33. package/dist/{snooze-KYSFXLPY.js → snooze-HOS6J3SY.js} +3 -3
  34. package/dist/{start-SQSDQK4F.js → start-2XGTR7NW.js} +3 -3
  35. package/dist/{stop-HC7XPSSP.js → stop-2B2HFRHR.js} +3 -3
  36. package/dist/{sync-ITK5UYGM.js → sync-YP6NMA5H.js} +4 -4
  37. package/dist/{time-GN6B4QD6.js → time-5SAXO4M7.js} +3 -3
  38. package/dist/{update-6LQNLRA4.js → update-A7G46IYO.js} +3 -3
  39. package/dist/{wait-MZOZQ3CI.js → wait-NP6HODWB.js} +3 -3
  40. package/dist/wd-bin.js +2 -2
  41. package/dist/web/assets/{PtyView-DYvawzWb.js → PtyView-BdoF3ROW.js} +2 -2
  42. package/dist/web/assets/{PtyView-DYvawzWb.js.map → PtyView-BdoF3ROW.js.map} +1 -1
  43. package/dist/web/assets/{index-C5lJhIwK.js → index-BrkfzFos.js} +7 -7
  44. package/dist/web/assets/index-BrkfzFos.js.map +1 -0
  45. package/dist/web/index.html +1 -1
  46. package/dist/{web-IC3P7EHZ.js → web-FSOY6574.js} +10 -10
  47. package/dist/web-FSOY6574.js.map +1 -0
  48. package/npm-shrinkwrap.json +2 -2
  49. package/package.json +1 -1
  50. package/dist/chunk-LMIEEDDC.js +0 -9
  51. package/dist/chunk-SNAQOHNL.js.map +0 -1
  52. package/dist/chunk-WF5SBVPZ.js.map +0 -1
  53. package/dist/hook-SLMZT5OV.js.map +0 -1
  54. package/dist/web/assets/index-C5lJhIwK.js.map +0 -1
  55. package/dist/web-IC3P7EHZ.js.map +0 -1
  56. /package/dist/{answer-2J4XLIP7.js.map → answer-BD5A6XMM.js.map} +0 -0
  57. /package/dist/{attach-CZKRNPAJ.js.map → attach-ID6KEOQ5.js.map} +0 -0
  58. /package/dist/{block-RAIDCJ4F.js.map → block-AQDYKNWG.js.map} +0 -0
  59. /package/dist/{catchup-VVOPL2S5.js.map → catchup-3454JUMS.js.map} +0 -0
  60. /package/dist/{chunk-HIZBWYPL.js.map → chunk-2PRI27ND.js.map} +0 -0
  61. /package/dist/{chunk-CVAVYDXO.js.map → chunk-ITNPMWPY.js.map} +0 -0
  62. /package/dist/{chunk-HWUINPIL.js.map → chunk-O3VNU7EZ.js.map} +0 -0
  63. /package/dist/{chunk-BR6OPEE4.js.map → chunk-OYQFLBLO.js.map} +0 -0
  64. /package/dist/{chunk-C7W5TMFB.js.map → chunk-QECEHQ4U.js.map} +0 -0
  65. /package/dist/{chunk-LMIEEDDC.js.map → chunk-UJD6QUGG.js.map} +0 -0
  66. /package/dist/{chunk-HSICXDMZ.js.map → chunk-VHWQE2WE.js.map} +0 -0
  67. /package/dist/{cleanup-LDBGWEKZ.js.map → cleanup-E6OD3TUM.js.map} +0 -0
  68. /package/dist/{cli-UATB4RM2.js.map → cli-O6IF63TS.js.map} +0 -0
  69. /package/dist/{fork-BKI5UNNS.js.map → fork-XJPZFNMX.js.map} +0 -0
  70. /package/dist/{note-WGM6LCP2.js.map → note-M53Q6EWY.js.map} +0 -0
  71. /package/dist/{pin-MQ5ZE37R.js.map → pin-VMM5TINM.js.map} +0 -0
  72. /package/dist/{pr-527S5HXB.js.map → pr-EHF642TN.js.map} +0 -0
  73. /package/dist/{prune-AIS5YEXP.js.map → prune-3DRPO3VJ.js.map} +0 -0
  74. /package/dist/{read-AP6T3ZGN.js.map → read-DDQDRHRB.js.map} +0 -0
  75. /package/dist/{remove-YGUTSKZP.js.map → remove-XJYZVAPX.js.map} +0 -0
  76. /package/dist/{screen-DNX4K23V.js.map → screen-XMGBRC25.js.map} +0 -0
  77. /package/dist/{section-TXLC5XO3.js.map → section-OO7IOLI7.js.map} +0 -0
  78. /package/dist/{send-6X46WZLC.js.map → send-GMG27KFT.js.map} +0 -0
  79. /package/dist/{sessions-T3QDTNP7.js.map → sessions-GOP5Y6LS.js.map} +0 -0
  80. /package/dist/{snooze-KYSFXLPY.js.map → snooze-HOS6J3SY.js.map} +0 -0
  81. /package/dist/{start-SQSDQK4F.js.map → start-2XGTR7NW.js.map} +0 -0
  82. /package/dist/{stop-HC7XPSSP.js.map → stop-2B2HFRHR.js.map} +0 -0
  83. /package/dist/{sync-ITK5UYGM.js.map → sync-YP6NMA5H.js.map} +0 -0
  84. /package/dist/{time-GN6B4QD6.js.map → time-5SAXO4M7.js.map} +0 -0
  85. /package/dist/{update-6LQNLRA4.js.map → update-A7G46IYO.js.map} +0 -0
  86. /package/dist/{wait-MZOZQ3CI.js.map → wait-NP6HODWB.js.map} +0 -0
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@moberg_hr/work-tree",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@moberg_hr/work-tree",
9
- "version": "2.0.1",
9
+ "version": "2.0.2",
10
10
  "hasInstallScript": true,
11
11
  "license": "MIT",
12
12
  "dependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moberg_hr/work-tree",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "Cross-platform Git worktree manager for multiple repositories",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,9 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/version.ts
4
- var VERSION = true ? "2.0.1" : "dev";
5
-
6
- export {
7
- VERSION
8
- };
9
- //# sourceMappingURL=chunk-LMIEEDDC.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/sessions/session-wire.ts","../src/core/sessions/session-meta.ts","../src/core/conversations/context-usage.ts","../src/core/conversations/session-title.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { agentOf, agentWire } from '../agents/index.js';\nimport { readStatus } from '../status/session-status.js';\nimport { snoozeActive, type Snooze } from '../rail/snooze.js';\nimport { withLiveClaude } from '../status/session-status.js';\nimport path from 'node:path';\nimport { readSessionMeta } from './session-meta.js';\nimport { checkedOutBranch } from '../git/git-head.js';\nimport { sessionIdFor } from './web-state.js';\nimport { readContextUsage } from '../conversations/context-usage.js';\nimport { bestEffort } from '../platform/best-effort.js';\nimport type { WorktreeSession } from './history.js';\nimport type {\n DiffStat,\n SessionArchiveInfo,\n SessionAttention,\n SessionClaudes,\n SessionWire,\n BlockerWire,\n PrStageWire,\n} from '../api-types.js';\nimport { archiveDirFor, keptList, readArchive } from '../archive/session-archive.js';\nimport { sessionTitle } from '../conversations/session-title.js';\nimport { prStageOf, STAGE_WANTS_YOU, type StagePr } from '../pr/pr-stage.js';\n\n/**\n * One session as every client sees it — the dashboard's /api/sessions rows\n * and `work sessions --json` alike: identity, status, activity, comments,\n * context, archive state. Built in one place so the two can't drift.\n */\nexport interface SessionWireOptions {\n /** The session's `+N −M`, when the caller has one (the web cache). */\n diffStatFor?: (id: string, s: WorktreeSession, hasStatus: boolean) => DiffStat | null;\n /** Whether its Claude runs in the PTY host (the CLI asks the host; the\n * web server's pool knows it already). */\n ptyLive?: (id: string) => boolean;\n /** Its running Claudes, wherever they were started (live-claudes.ts). */\n claudesFor?: (id: string) => SessionClaudes | null;\n /** It shares its folder with another session that owns it\n * (shared-folders.ts): the folder's activity isn't this one's. */\n shadowed?: (id: string) => boolean;\n /** Unresolved review threads on its open PRs (the PR watch's last check). */\n reviewThreadsFor?: (id: string) => number;\n /** Reply drafts its Claude wrote for you to post (pr-replies.ts). */\n replyDraftsFor?: (id: string) => number;\n /** Where its PR stands (pr-stage.ts over the PR watch's last check), and whether you've seen it there. */\n prStageFor?: (id: string) => PrStageWire | null;\n /** You have notes on it (session-notes.ts). */\n hasNote?: (id: string) => boolean;\n /** What it waits on that isn't done yet (session-blocks.ts). */\n blockedByFor?: (id: string) => BlockerWire[];\n /** The running Claudes were read against a real process list, so \"none\" means none. */\n liveKnown?: boolean;\n /** A Claude of ours runs for it (PTY host), whether or not Claude Code's file shows it yet. */\n hostedLive?: (id: string) => boolean;\n /** A status read from its terminal output, for a tool with no hooks (output-status.ts). */\n outputStatusFor?: (id: string) => SessionAttention | null;\n /** Its snooze, if any (snooze-store.ts); shown only while it holds. */\n snoozeFor?: (id: string) => Snooze | null;\n /** How far behind main — or the session it is stacked on — it is (behind-main.ts's cache). */\n behindFor?: (id: string, s: WorktreeSession) => { base: string; commits: number; conflicts: boolean; stacked?: true } | null;\n /** Where it sits in a stack (stack-sessions.ts). */\n stackFor?: (id: string) => {\n parent: { id: string; branch: string; title?: string } | null;\n children: number;\n merged?: { id: string; branch: string } | null;\n };\n}\n\nexport function sessionWire(s: WorktreeSession, opts: SessionWireOptions = {}): SessionWire {\n const id = sessionIdFor(s);\n const meta = readSessionMeta(id, s);\n const shadowed = opts.shadowed?.(id) ?? false;\n const claudes = shadowed ? null : (opts.claudesFor?.(id) ?? null);\n const reviewThreads = s.archivedAt ? 0 : (opts.reviewThreadsFor?.(id) ?? 0);\n const replyDrafts = s.archivedAt ? 0 : (opts.replyDraftsFor?.(id) ?? 0);\n const prStage = s.archivedAt ? null : (opts.prStageFor?.(id) ?? null);\n const wire: SessionWire = {\n id,\n target: s.target,\n branch: s.branch,\n isGroup: s.isGroup,\n paths: s.paths,\n baseBranch: s.baseBranch,\n jiraKey: s.jiraKey,\n createdAt: s.createdAt,\n lastAccessedAt: s.lastAccessedAt,\n draftCount: meta.draftCount,\n commentCount: meta.commentCount,\n claudeCount: meta.claudeCount,\n ptyStatus: opts.ptyLive ? (opts.ptyLive(id) ? 'running' : 'idle') : meta.ptyStatus,\n lastActivity: shadowed ? null : meta.lastActivity,\n // A running Claude is open even when it writes nothing (idle at its prompt).\n activityState: shadowed\n ? 'stale'\n : claudes\n ? claudes.busy\n ? 'active'\n : meta.activityState === 'active'\n ? 'active'\n : 'open'\n : meta.activityState,\n ...(claudes ? { agents: claudes, claudes } : {}),\n agent: agentWire(agentOf(s)),\n ...(s.archivedAt ? archiveInfo(id) : {}),\n title: bestEffort(\n `title of ${s.target}:${s.branch}`,\n () => sessionTitle(s, s.archivedAt ? readArchive(id)?.summary.prompts[0]?.text : null),\n null,\n ),\n ...(s.title ? { titleIsYours: true } : {}),\n pendingForClaudeCount: meta.pendingForClaudeCount,\n // Claude Code's own state file over what the hooks recorded, when newer.\n attention:\n meta.attention && !shadowed && opts.claudesFor\n ? withLiveClaude(meta.attention, claudes, { known: opts.liveKnown === true, hosted: opts.hostedLive?.(id) ?? true })\n : (meta.attention ?? (shadowed || s.archivedAt ? null : (opts.outputStatusFor?.(id) ?? null))),\n diffStat: opts.diffStatFor ? opts.diffStatFor(id, s, meta.attention !== null) : null,\n archivedAt: s.archivedAt ?? null,\n port: s.port ?? null,\n context: s.archivedAt ? null : bestEffort(`context usage for ${s.target}:${s.branch}`, () => readContextUsage(s), null),\n ...(reviewThreads > 0 ? { openReviewThreads: reviewThreads } : {}),\n ...(replyDrafts > 0 ? { replyDrafts } : {}),\n ...(prStage ? { prStage } : {}),\n ...otherBranches(s),\n };\n // Snoozed: only while it holds (a time not yet reached, or the status it\n // was snoozed in). \"Its status\" is what the hooks recorded — the same the\n // snooze was taken against — not the shown one, which a live Claude's state\n // file can override (that would end a snooze the moment it was set).\n const snooze = s.archivedAt ? null : (opts.snoozeFor?.(id) ?? null);\n if (snooze && snoozeActive(snooze, { attention: readStatus(id), openReviewThreads: wire.openReviewThreads, prStage: wire.prStage }))\n wire.snoozed = { until: snooze.until };\n const behind = s.archivedAt ? null : (opts.behindFor?.(id, s) ?? null);\n if (behind && behind.commits > 0) wire.behind = behind;\n const stack = s.archivedAt ? null : (opts.stackFor?.(id) ?? null);\n if (stack?.parent) wire.stackedOn = stack.parent;\n if (stack?.children) wire.stackedChildren = stack.children;\n if (stack?.merged) wire.stackParentMerged = stack.merged;\n if (opts.hasNote?.(id)) wire.hasNote = true;\n const blockers = s.archivedAt ? [] : (opts.blockedByFor?.(id) ?? []);\n if (blockers.length) wire.blockedBy = blockers;\n return wire;\n}\n\n/**\n * Repos of the session checked out on another branch than the session's\n * (read from HEAD files, no git). Ship and the PR watch follow the real\n * branch already; this is so the dashboard says so.\n */\nexport function otherBranches(s: Pick<WorktreeSession, 'branch' | 'paths' | 'target' | 'isGroup' | 'archivedAt'>): {\n onOtherBranch?: Array<{ repo: string; branch: string | null }>;\n} {\n if (s.archivedAt || !s.branch) return {};\n const out: Array<{ repo: string; branch: string | null }> = [];\n for (const p of s.paths) {\n if (!fs.existsSync(p)) continue;\n const branch = checkedOutBranch(p);\n if (branch !== s.branch) out.push({ repo: s.isGroup ? path.basename(p) : s.target, branch });\n }\n return out.length ? { onOtherBranch: out } : {};\n}\n\n/** A session's unresolved review threads, from the PR watch's per-repo counts (open PRs only). */\nexport function reviewThreadsOf(ci: { repos: Array<{ pr: { state: string } | null; openThreads?: number }> } | null | undefined): number {\n return (ci?.repos ?? []).reduce((n, r) => n + (r.pr?.state === 'OPEN' ? (r.openThreads ?? 0) : 0), 0);\n}\n\n/** The `pr_watch_seen` key that says you saw a session at a PR stage. */\nexport const stageSeenKey = (stageKey: string) => `stage:${stageKey}`;\n\n/**\n * A session's PR stage from the PR watch's last check, with `seen` read only\n * for a stage that would bring it back to the Inbox (one lookup, not one per row).\n */\nexport function prStageWire(\n ci: { repos: Array<{ name: string; pr: StagePr | null }> } | null | undefined,\n seen: (key: string) => boolean,\n): PrStageWire | null {\n const stage = prStageOf(ci?.repos ?? []);\n if (!stage) return null;\n return STAGE_WANTS_YOU.has(stage.kind) && seen(stageSeenKey(stage.key)) ? { ...stage, seen: true } : stage;\n}\n\n/** Saved uncommitted files a Restore hasn't put back yet. */\nfunction savedFiles(saved: Record<string, { files: number; restoredAt?: string; restoreError?: string }> | undefined): {\n savedUncommitted?: number;\n} {\n const n = Object.values(saved ?? {})\n .filter((u) => !u.restoredAt && !u.restoreError)\n .reduce((sum, u) => sum + u.files, 0);\n return n ? { savedUncommitted: n } : {};\n}\n\nfunction archiveInfo(id: string): { archive?: SessionArchiveInfo } {\n const rec = readArchive(id);\n if (!rec) return {};\n return {\n archive: {\n worktreeRemoved: rec.worktreeRemoved,\n keptBecause: rec.keptBecause,\n promptCount: rec.summary.promptCount,\n prompts: rec.summary.prompts.map((p) => p.text),\n lastSummary: rec.summary.lastSummary,\n ...(rec.summary.written ? { written: rec.summary.written } : {}),\n ...(rec.buildFolders ? { buildFolders: rec.buildFolders } : {}),\n ...savedFiles(rec.uncommitted),\n ...(keptList(rec.kept) ? { kept: keptList(rec.kept) } : {}),\n },\n };\n}\n\n/** Newest sign of life (ms): the hook update, Claude's last write, the\n * `work tree` entry — the same rule as the dashboard's \"Last active\". */\nexport function lastActiveMs(w: Pick<SessionWire, 'lastAccessedAt' | 'lastActivity' | 'attention'>): number {\n return Math.max(Date.parse(w.lastAccessedAt) || 0, w.lastActivity ?? 0, w.attention ? Date.parse(w.attention.updatedAt) || 0 : 0);\n}\n\n/**\n * Archived sessions' rows, kept between builds of the list: an archived\n * session doesn't change — its Claude is stopped, its worktree mostly gone —\n * and building its row reads its archive (2/3 of /api/sessions' time with\n * fifty of them). A row is built again when its archive file was written\n * (the summary lands after archiving, a Restore records what came back), it\n * was renamed or entered, or your note on it came or went.\n */\nexport function createArchivedRows(\n archiveFile: (id: string) => string = (id) => path.join(archiveDirFor(id), 'archive.json'),\n): (s: WorktreeSession, extra: { hasNote: boolean }, build: () => SessionWire) => SessionWire {\n const rows = new Map<string, { key: string; row: SessionWire }>();\n return (s, extra, build) => {\n if (!s.archivedAt) return build();\n const id = sessionIdFor(s);\n let mtime = 0;\n try {\n mtime = fs.statSync(archiveFile(id)).mtimeMs;\n } catch {\n /* none yet */\n }\n const key = `${s.archivedAt}|${mtime}|${s.title ?? ''}|${s.lastAccessedAt}|${extra.hasNote}`;\n const hit = rows.get(id);\n if (hit?.key === key) return hit.row;\n const row = build();\n rows.set(id, { key, row });\n return row;\n };\n}\n","import { peekPty } from '../pty/pty-pool.js';\nimport { sessionStatusView } from '../status/turn-activity.js';\nimport type { ActivityState } from '../api-types.js';\nimport { readSessionActivity } from './session-activity.js';\nimport { getCommentFileStore } from '../comments/comment-file-store.js';\nimport { readPendingForSession } from '../comments/pending-delivery.js';\nimport type { WorktreeSession } from './history.js';\nimport { readStatus, type EffectiveStatus } from '../status/session-status.js';\n\nexport type { PtyStatus } from '../api-types.js';\nimport type { PtyStatus } from '../api-types.js';\n\nexport interface SessionMeta {\n draftCount: number;\n commentCount: number;\n /** Comments authored by claude — used by the client to compute unread. */\n claudeCount: number;\n /** Set when *our* PTY pool has a live Claude for this session. Doesn't\n * catch external terminals — `activityState` does. */\n ptyStatus: PtyStatus;\n /** ms since epoch of Claude's last write across this worktree, or null. */\n lastActivity: number | null;\n /** Derived from `lastActivity`: 'active' (≤30 s), 'open' (≤5 min), 'stale'. */\n activityState: ActivityState;\n /** Published user comments not yet surfaced to Claude via the\n * UserPromptSubmit hook. Drops to zero after Claude takes its next turn. */\n pendingForClaudeCount: number;\n /** Hook-driven agent status for the attention inbox; null until the\n * session's Claude has fired a hook under a full `work web`. */\n attention: EffectiveStatus | null;\n}\n\n/**\n * Cheap per-session metadata. Goes through the file-store cache so badge\n * counts reflect in-flight writes that haven't yet hit disk — reading the\n * raw JSON behind the cache's back produced stale counts under load.\n *\n * `session` is required because we need the worktree paths to look up\n * Claude's transcript directory (the sessionId hash alone isn't enough).\n */\nexport function readSessionMeta(sessionId: string, session: WorktreeSession): SessionMeta {\n const comments = getCommentFileStore(sessionId).snapshot();\n let drafts = 0;\n let claude = 0;\n for (const c of comments) {\n if (c.status === 'draft') drafts++;\n if (c.author === 'claude') claude++;\n }\n const activity = readSessionActivity(session);\n const pending = readPendingForSession(sessionId).length;\n const status = readStatus(sessionId);\n return {\n draftCount: drafts,\n commentCount: comments.length,\n claudeCount: claude,\n ptyStatus: peekPty(sessionId) ? 'running' : 'idle',\n lastActivity: activity.lastActivity,\n activityState: activity.state,\n pendingForClaudeCount: pending,\n attention: status ? sessionStatusView(status, session, activity.lastActivity ?? 0) : null,\n };\n}\n","import { readJsonlTail } from './jsonl.js';\nimport { agentOf } from '../agents/index.js';\nimport type { ConversationEntry } from '../agents/types.js';\nimport type { ContextUsage } from '../api-types.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\n\nexport type { ContextUsage } from '../api-types.js';\n\n/**\n * How full a session's conversation is. Every assistant message in the\n * transcript carries the token usage of the request that produced it, so\n * the newest one says how big the context is now: its prompt (input +\n * cache reads + cache writes) plus its reply, which the next turn carries.\n * Near the window Claude Code compacts the conversation, and answers get\n * worse before that — the dashboard shows when to start fresh.\n */\n\n/** From conversation entries (oldest first): the newest main-thread usage, in the agent's window (`window`). */\nexport function contextUsageFrom(\n entries: readonly ConversationEntry[],\n window: (model: string | undefined, used: number) => number,\n): ContextUsage | null {\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i];\n // Subagent (Task) turns run in their own context.\n if (e.role !== 'agent' || e.sidechain || !e.usage) continue;\n const used = e.usage.prompt + e.usage.reply;\n if (used === 0) continue;\n return { used, window: window(e.model, used), ...(e.model ? { model: e.model } : {}) };\n }\n return null;\n}\n\n// Claude Code's transcript files, for the callers that still read Claude's own records (turn activity): agents/claude-files.ts.\nexport type { ConversationFile as TranscriptFile } from '../agents/types.js';\n\n/** Only the tail is read — a usage line is always near the end. */\nconst USAGE_TAIL_BYTES = 64 * 1024;\nconst cache = new Map<string, { key: string; usage: ContextUsage | null }>();\n\n/** The session's context usage now, through its agent; re-reads a conversation only after it changed. Null when work can't read its agent's conversations. */\nexport function readContextUsage(session: WorktreeSession): ContextUsage | null {\n const conv = agentOf(session).conversation;\n if (!conv) return null;\n let t: { file: string; size: number; mtimeMs: number } | null = null;\n for (const f of conv.files(session)) if (!t || f.mtimeMs > t.mtimeMs) t = f;\n if (!t) return null;\n const key = `${t.file}:${t.size}:${t.mtimeMs}`;\n const id = session.paths.join('|');\n const hit = cache.get(id);\n if (hit?.key === key) return hit.usage;\n const usage = contextUsageFrom(conv.entries(readJsonlTail(t.file, USAGE_TAIL_BYTES)), conv.contextWindow);\n cache.set(id, { key, usage });\n return usage;\n}\n","import fs from 'node:fs';\nimport { promptsSince } from './digest.js';\nimport { agentOf } from '../agents/index.js';\nimport type { ConversationEntry } from '../agents/types.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\n\n/**\n * A human name for a session, beside its branch: the name you gave it, or\n * else what you first asked its Claude (\"Rotate the terminal encryption\n * keys\"), or else its Jira key. Worked out when read — the first prompt is\n * read from the start of its oldest transcript, cached per file — so a GET\n * writes nothing; only a rename is stored.\n */\n\nconst TITLE_CHARS = 80;\nconst HEAD_BYTES = 256 * 1024;\nconst cache = new Map<string, { size: number; title: string | null }>();\n\n/** The first prompt in a conversation file (read from its start), its lines read by `toEntries` (the agent's). */\nexport function firstPromptOf(file: string, toEntries: (lines: readonly unknown[]) => ConversationEntry[]): string | null {\n let size: number;\n try {\n size = fs.statSync(file).size;\n } catch {\n return null;\n }\n const hit = cache.get(file);\n // The start of a file doesn't change as it grows, unless it was replaced\n // (smaller). \"No prompt in it\" holds as long as the file is the same, or\n // its whole head was read already: re-reading 256 KB of every such\n // transcript on every session-list build cost the most of all.\n if (hit && size >= hit.size && (hit.title !== null || size === hit.size || hit.size >= HEAD_BYTES)) return hit.title;\n let text: string;\n try {\n const fd = fs.openSync(file, 'r');\n try {\n const buf = Buffer.alloc(Math.min(size, HEAD_BYTES));\n fs.readSync(fd, buf, 0, buf.length, 0);\n text = buf.toString('utf8');\n } finally {\n fs.closeSync(fd);\n }\n } catch {\n return null;\n }\n const lines: unknown[] = [];\n for (const line of text.split('\\n')) {\n try {\n lines.push(JSON.parse(line));\n } catch {\n /* the last, cut-off line */\n }\n }\n const first = promptsSince([toEntries(lines)], 0)[0]?.text ?? null;\n const readable = first ? titleText(first) : null;\n const title = readable ? clip(readable) : null;\n cache.set(file, { size, title });\n return title;\n}\n\nconst clip = (s: string) => (s.length > TITLE_CHARS ? s.slice(0, TITLE_CHARS - 1).trimEnd() + '…' : s);\n\n/**\n * A prompt as a name: what you wrote, without markup. A pasted block\n * (`<pasted_content …>…</pasted_content>`, a log or code you pasted) is left\n * out when you also wrote something; a prompt that is only a paste keeps its\n * text. Other tags are dropped, their text kept. Null when nothing is left.\n */\nexport function titleText(prompt: string): string | null {\n const flat = (s: string) =>\n s\n .replace(/<\\/?[A-Za-z][\\w-]*(?:\\s[^>]*)?>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n const outside = flat(prompt.replace(/<pasted_content\\b[^>]*>[\\s\\S]*?<\\/pasted_content>/g, ' '));\n const text = outside || flat(prompt);\n return text ? text : null;\n}\n\n/** The session's name: yours, else its first prompt, else its Jira key. */\nexport function sessionTitle(s: WorktreeSession, fallbackPrompt?: string | null): string | null {\n if (s.title?.trim()) return s.title.trim();\n const conv = agentOf(s).conversation;\n const oldestFirst = (conv?.files(s) ?? []).sort((a, b) => a.mtimeMs - b.mtimeMs);\n for (const t of oldestFirst) {\n const p = firstPromptOf(t.file, conv!.entries);\n if (p) return p;\n }\n const fallback = fallbackPrompt ? titleText(fallbackPrompt) : null;\n if (fallback) return clip(fallback);\n return s.jiraKey ?? null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,SAAQ;AAKf,OAAO,UAAU;;;ACmCV,SAAS,gBAAgB,WAAmB,SAAuC;AACxF,QAAM,WAAW,oBAAoB,SAAS,EAAE,SAAS;AACzD,MAAI,SAAS;AACb,MAAI,SAAS;AACb,aAAW,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,WAAO;AAAA,EACT;AACF;","names":["fs","cache","fs"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/git/git-head.ts","../src/core/comments/pending-delivery.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * The branch checked out in a checkout, read from its HEAD file — no `git`\n * process, so the session list can ask for every session on every request.\n * A worktree's `.git` is a file (`gitdir: <repo>/.git/worktrees/<name>`)\n * whose HEAD names the branch; a base checkout's `.git` is the folder.\n *\n * null: detached HEAD, not a checkout, or unreadable.\n */\nexport function checkedOutBranch(checkout: string): string | null {\n try {\n const dotGit = path.join(checkout, '.git');\n let gitDir = dotGit;\n if (fs.statSync(dotGit).isFile()) {\n const m = /^gitdir:\\s*(.+?)\\s*$/m.exec(fs.readFileSync(dotGit, 'utf8'));\n if (!m) return null;\n gitDir = path.resolve(checkout, m[1]);\n }\n return branchFromHead(fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf8'));\n } catch {\n return null;\n }\n}\n\n/** `ref: refs/heads/fix/x` → `fix/x`; a commit sha (detached) → null. */\nexport function branchFromHead(head: string): string | null {\n const m = /^ref:\\s*refs\\/heads\\/(.+?)\\s*$/m.exec(head);\n return m ? m[1] : null;\n}\n","/**\n * Bridge between `work web` review comments and any live Claude session\n * running in the same worktree. Storage (state.db, see db.ts):\n *\n * comments the comment stores (comment-file-store.ts)\n * comment_deliveries (session, comment id) pairs surfaced to Claude\n *\n * \"Pending\" = published, user-authored, not in the delivered list. Replies\n * authored by Claude (author === 'claude') are excluded — Claude wrote\n * them; we don't need to echo them back.\n *\n * Delivery is lazy: when a Claude in the matching worktree submits a\n * prompt, the hook reads pending comments via this module, prints them as\n * a system-reminder block to stdout (which Claude Code injects into the\n * conversation), and marks them delivered.\n */\n\nimport { checkedOutBranch } from '../git/git-head.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { loadHistory, type WorktreeSession } from '../sessions/history.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { readStoreComments } from './comment-file-store.js';\nimport { scopeHashFor } from '../diff/repo-spec.js';\nimport { tx, withDb, type Db } from '../platform/db.js';\nimport type { Comment } from './comment-types.js';\n\nfunction deliveredIds(d: Db, sessionId: string): Set<string> {\n return new Set(\n (d.prepare('SELECT comment_id FROM comment_deliveries WHERE session_id = ?').all(sessionId) as Array<{ comment_id: string }>).map(\n (r) => r.comment_id,\n ),\n );\n}\n\n/** Norm-path comparison that mirrors what we do server-side. */\nfunction normalize(p: string): string {\n return path.resolve(p).replace(/\\\\/g, '/').toLowerCase();\n}\n\n/** Map a Claude cwd back to a session. Tries direct-match against any\n * session's path first, then ancestor match (so cwd inside a subdir of a\n * worktree still resolves to the worktree's session). */\n/**\n * Two sessions on one folder (an old entry and a newer one, a typo'd target\n * re-added): which of them a Claude there is. Not an archived one when the\n * other isn't; then the one whose branch is checked out there; then the one\n * entered last. The oldest used to win, so status and comments went to an\n * entry nobody looks at.\n */\nfunction owns(candidate: WorktreeSession, current: WorktreeSession, root: string): boolean {\n if (!!candidate.archivedAt !== !!current.archivedAt) return !candidate.archivedAt;\n const onBranch = checkedOutBranch(root);\n const a = candidate.branch === onBranch;\n const b = current.branch === onBranch;\n if (a !== b) return a;\n return (Date.parse(candidate.lastAccessedAt) || 0) > (Date.parse(current.lastAccessedAt) || 0);\n}\n\nexport function findSessionForCwd(cwd: string, sessions: WorktreeSession[] = loadHistory()): WorktreeSession | null {\n const here = normalize(cwd);\n // Deepest root containing cwd wins, so nested worktrees disambiguate. A\n // group's roots include the group root (the sub-repos' parent) — that's\n // where `work tree` launches Claude for a group, so hooks fire from there.\n let best: { session: WorktreeSession; root: string; len: number } | null = null;\n for (const s of sessions) {\n const roots = s.isGroup && s.paths[0] ? [...s.paths, path.dirname(s.paths[0])] : s.paths;\n for (const root of roots) {\n const r = normalize(root);\n if (!(here === r || here.startsWith(r + '/'))) continue;\n if (!best || r.length > best.len || (r.length === best.len && owns(s, best.session, root))) {\n best = { session: s, root, len: r.length };\n }\n }\n }\n if (!best) return null;\n // A separate checkout nested INSIDE the session's tree (a git worktree at\n // <repo>/.claude/worktrees/x, a vendored repo) is not this session: its\n // Claude must not report status, take checkpoints or receive comments as\n // if it were the parent. Any `.git` between cwd and the matched root —\n // other than the session's own repos — marks a different checkout.\n // (Plain fs checks: this runs on every hook.)\n const own = new Set(best.session.paths.map(normalize));\n const top = normalize(best.root);\n for (let dir = path.resolve(cwd); normalize(dir) !== top && normalize(dir).startsWith(top + '/'); dir = path.dirname(dir)) {\n if (!own.has(normalize(dir)) && fs.existsSync(path.join(dir, '.git'))) return null;\n if (path.dirname(dir) === dir) break;\n }\n return best.session;\n}\n\nfunction isPendingFor(delivered: Set<string>) {\n return (c: Comment) => c.status === 'published' && c.author === 'user' && !delivered.has(c.id);\n}\n\n/** Returns published user comments that haven't been delivered yet.\n * Reads through the file-store cache so we see in-flight writes\n * (`session-meta.ts` and other readers couldn't, when they re-read the\n * disk directly). */\n/**\n * The line typed into an idle Claude (or given as the first prompt of one\n * work starts) so its UserPromptSubmit hook attaches the pending comments.\n * Short on purpose: a long typed note got mangled by Claude Code's paste\n * handling. It says where the content is, so it reads right in the\n * transcript.\n */\nexport const NOTE_NUDGE =\n 'work has new notes for you (review feedback, CI results or comments); they are attached to this message. Work through them now.';\n\nexport function readPendingForSession(sessionId: string): Comment[] {\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n return readStoreComments(sessionId).filter(isPendingFor(delivered));\n}\n\n/** Comment-store ids for every `wd` scope that could cover this worktree.\n * A scope is keyed by `sha1` of its sorted repo roots (see\n * `repo-spec.scopeHashFor`), so from a session's paths we can rebuild the\n * exact ids without consulting `work web`'s in-memory scope registry:\n * - the whole-set hash → a group `wd` opened at the group root, or the\n * single-repo `wd` (one path);\n * - each individual path's hash → a `wd` opened inside one sub-repo of a\n * group worktree.\n * `registerScope` hashes `path.resolve()`d roots, so we resolve here too or\n * the hashes won't line up. Mirrors `scope-manager.commentStoreIdForScope`\n * (`scope-<hash>`). */\nfunction scopeStoreIdsForPaths(paths: string[]): string[] {\n const resolved = paths.map((p) => path.resolve(p));\n const ids = new Set<string>();\n ids.add(`scope-${scopeHashFor(resolved)}`);\n for (const p of resolved) ids.add(`scope-${scopeHashFor([p])}`);\n return [...ids];\n}\n\n/**\n * Pending comments for a whole worktree: the session's own comment store\n * PLUS any `wd` / `wd -c` scope review store covering the same paths.\n *\n * `wd` registers its review under a scope-hash comment store, not the\n * session store the hook reads — without this merge, comments left in the\n * `wd` review UI would never reach the Claude running in that worktree.\n * Delivered-tracking stays per-session (one `<sessionId>.delivered.json`),\n * so a comment surfaced here won't be re-delivered regardless of which\n * store it came from.\n */\nexport function readPendingForWorktree(session: WorktreeSession): Comment[] {\n const sessionId = sessionIdFor(session);\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n const pending = isPendingFor(delivered);\n const seen = new Set<string>();\n const out: Comment[] = [];\n const collect = (storeId: string) => {\n for (const c of readStoreComments(storeId)) {\n if (seen.has(c.id) || !pending(c)) continue;\n seen.add(c.id);\n out.push(c);\n }\n };\n collect(sessionId);\n for (const storeId of scopeStoreIdsForPaths(session.paths)) collect(storeId);\n return out;\n}\n\n/** Persist a delivery batch, so these ids are never surfaced again. */\nexport function markDelivered(sessionId: string, ids: string[]): void {\n if (ids.length === 0) return;\n tx((d) => {\n const ins = d.prepare('INSERT OR IGNORE INTO comment_deliveries (session_id, comment_id) VALUES (?, ?)');\n for (const id of ids) ins.run(sessionId, id);\n });\n}\n\n/**\n * Claim comments for delivery: of `ids`, return the ones nobody has\n * delivered yet, and mark them delivered — atomically. Two deliverers\n * racing (a Stop hook and the PTY push for the same comment) then can't\n * both send it: only the one that claimed it does. A deliverer whose send\n * fails gives the ids back with `releaseClaim`.\n */\nexport function claimForDelivery(sessionId: string, ids: string[]): string[] {\n if (ids.length === 0) return [];\n // INSERT OR IGNORE in one write transaction: a row inserted here is our\n // claim; one that already existed was someone else's.\n return tx((d) => {\n const ins = d.prepare('INSERT OR IGNORE INTO comment_deliveries (session_id, comment_id) VALUES (?, ?)');\n return ids.filter((id) => ins.run(sessionId, id).changes > 0);\n });\n}\n\n/** Undo a claim whose delivery failed, so the next hook picks them up. */\nexport function releaseClaim(sessionId: string, ids: string[]): void {\n if (ids.length === 0) return;\n tx((d) => {\n const del = d.prepare('DELETE FROM comment_deliveries WHERE session_id = ? AND comment_id = ?');\n for (const id of ids) del.run(sessionId, id);\n });\n}\n\n/** Cap the size of one comment body we surface to Claude. A pathologically\n * long comment shouldn't blow out Claude's context — we truncate, then\n * hint at the rest via \"(truncated)\". 4 KB is generous for a code-review\n * note while leaving headroom for batches. */\nconst MAX_BODY_BYTES = 4 * 1024;\n/** Overall cap on the whole system-reminder payload. Multiple long\n * comments at once still get bounded. */\nconst MAX_TOTAL_BYTES = 32 * 1024;\n\n/**\n * Format pending comments as a system-reminder block suitable for stdout.\n * Returns empty string when there's nothing pending — the caller (the\n * `work hook` CLI) just exits silently in that case.\n *\n * Truncates pathologically long bodies and caps the overall payload so\n * one runaway comment can't displace the rest of Claude's context.\n */\nexport function formatPendingForPrompt(pending: Comment[]): string {\n if (pending.length === 0) return '';\n\n const sorted = [...pending].sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n\n const general = sorted.filter((c) => c.side === 'general' && !c.parentId);\n const inline = sorted.filter((c) => c.side !== 'general' && !c.parentId);\n const replies = sorted.filter((c) => c.parentId);\n\n const lines: string[] = [];\n lines.push('<system-reminder>');\n lines.push(`New review comments from \\`work web\\` (${pending.length} item${pending.length === 1 ? '' : 's'}):`);\n lines.push('');\n\n if (general.length > 0) {\n lines.push('## General notes');\n for (const c of general) {\n // General notes (this is where `work broadcast` lands) may be multi-line\n // prompts — deliver the whole body, not just line 1. Only the byte cap\n // applies. Inline/reply comments still use the one-line `formatBody`.\n lines.push(formatFullBody('-', c));\n }\n lines.push('');\n }\n\n if (inline.length > 0) {\n lines.push('## Inline comments');\n for (const c of inline) {\n const where = `${c.repo}/${c.file}:${c.line} (${c.side})`;\n lines.push(formatBody(`- ${where}`, c));\n }\n lines.push('');\n }\n\n if (replies.length > 0) {\n lines.push('## Replies');\n for (const c of replies) {\n lines.push(formatBody(`- (reply to ${c.parentId})`, c));\n }\n lines.push('');\n }\n\n lines.push(\n 'Address them as part of your next response. You can reply via the same review UI by posting back to the latest review URL at `~/.work/web.url` + `/api/sessions/<id>/comments` with `author: \"claude\"`.',\n );\n lines.push('</system-reminder>');\n const out = lines.join('\\n');\n if (out.length <= MAX_TOTAL_BYTES) return out;\n const trimmed = out.slice(0, MAX_TOTAL_BYTES - 200);\n return (\n trimmed +\n '\\n\\n(…review payload truncated for context-window safety; ' +\n `${pending.length} comment(s) total — open work web for the full list.)\\n` +\n '</system-reminder>'\n );\n}\n\nfunction formatBody(prefix: string, c: Comment): string {\n const lead = c.body.split('\\n')[0].trim();\n const capped = lead.length > MAX_BODY_BYTES ? `${lead.slice(0, MAX_BODY_BYTES)}…` : lead;\n return `${prefix}: ${capped}${c.body.includes('\\n') ? ' …' : ''}`;\n}\n\n/** Like `formatBody` but preserves the full multi-line body (only the byte\n * cap applies). Multi-line bodies are emitted under the bullet, indented, so\n * a broadcast prompt arrives intact rather than truncated to its first line. */\nfunction formatFullBody(prefix: string, c: Comment): string {\n const body = c.body.trim();\n const capped = body.length > MAX_BODY_BYTES ? `${body.slice(0, MAX_BODY_BYTES)}…` : body;\n const bodyLines = capped.split('\\n');\n if (bodyLines.length === 1) return `${prefix}: ${bodyLines[0]}`;\n const [first, ...rest] = bodyLines;\n return [`${prefix}: ${first}`, ...rest.map((l) => ` ${l}`)].join('\\n');\n}\n\n/** Re-export so consumers don't have to know which module owns it. */\nexport { sessionIdFor };\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAUV,SAAS,iBAAiB,UAAiC;AAChE,MAAI;AACF,UAAM,SAAS,KAAK,KAAK,UAAU,MAAM;AACzC,QAAI,SAAS;AACb,QAAI,GAAG,SAAS,MAAM,EAAE,OAAO,GAA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AAgB,GAAoB;AACtD,QAAM,OAAO,EAAE,KAAK,MAAM,IAAI,EAAE,CAAC,EAAE,KAAK;AACxC,QAAM,SAAS,KAAK,SAAS,iBAAiB,GAAG,KAAK,MAAM,GAAG,cAAc,CAAC,WAAM;AACpF,SAAO,GAAG,MAAM,KAAK,MAAM,GAAG,EAAE,KAAK,SAAS,IAAI,IAAI,YAAO,EAAE;AACjE;AAKA,SAAS,eAAe,QAAgB,GAAoB;AAC1D,QAAM,OAAO,EAAE,KAAK,KAAK;AACzB,QAAM,SAAS,KAAK,SAAS,iBAAiB,GAAG,KAAK,MAAM,GAAG,cAAc,CAAC,WAAM;AACpF,QAAM,YAAY,OAAO,MAAM,IAAI;AACnC,MAAI,UAAU,WAAW,EAAG,QAAO,GAAG,MAAM,KAAK,UAAU,CAAC,CAAC;AAC7D,QAAM,CAAC,OAAO,GAAG,IAAI,IAAI;AACzB,SAAO,CAAC,GAAG,MAAM,KAAK,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC,EAAE,KAAK,IAAI;AACxE;","names":["fs","path","path","fs"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/hook.ts"],"sourcesContent":["import type { CommandModule } from 'yargs';\nimport { readSessionActivity } from '../core/sessions/session-activity.js';\nimport {\n findSessionForCwd,\n formatPendingForPrompt,\n claimForDelivery,\n readPendingForWorktree,\n sessionIdFor,\n} from '../core/comments/pending-delivery.js';\nimport { isInternalRun } from '../core/platform/internal-run.js';\nimport { isOwnCheckout, ownCheckoutNote } from '../core/worktree/own-checkout.js';\nimport { loadConfig } from '../core/platform/config.js';\nimport { readWebUrl } from '../core/platform/web-discovery.js';\nimport { recordStatusEvent, type StatusEvent } from '../core/status/session-status.js';\nimport { bestEffortAsync } from '../core/platform/best-effort.js';\nimport { readAssistantContext } from '../core/agents/assistant.js';\nimport { agentById, type AgentAdapter, type TurnEdge } from '../core/agents/index.js';\n\n/**\n * `work hook prompt-submit` / `work hook stop` — invoked by Claude Code's\n * UserPromptSubmit / Stop hooks (registered by `work web` on startup).\n * Reads pending review comments for the worktree the user is currently\n * in, prints them in the format Claude Code expects for that event, and\n * marks them delivered so they don't repeat.\n *\n * Exits silently when:\n * - cwd isn't a `work`-managed worktree\n * - there are no pending comments\n * - Claude isn't actively running in this worktree (paranoia — the hook\n * only fires from inside a running Claude, but we double-check)\n */\nexport type HookEvent =\n | 'prompt-submit'\n | 'stop'\n | 'checkpoint'\n | 'checkpoint-seal'\n | 'status-prompt'\n | 'status-stop'\n | 'status-notify'\n | 'assistant-context'\n /** One hook per turn edge: delivery + status + checkpoint (the full dashboard). */\n | 'turn-start'\n | 'turn-end';\n\nconst STATUS_EVENTS = new Set<HookEvent>(['status-prompt', 'status-stop', 'status-notify']);\n\n/**\n * Fire-and-forget POST to the running `work web`. Shared by the two\n * checkpoint hooks: `checkpoint` (Stop) hits `api/checkpoint` to refresh the\n * instruction's live step; `checkpoint-seal` (UserPromptSubmit) hits\n * `api/checkpoint/seal` to close it so the next prompt opens a fresh step.\n * Silent + best-effort — no work web running, or cwd not a tracked scope, is\n * a no-op, and we never block Claude's turn on it.\n */\nasync function postToWeb(route: string, cwd: string): Promise<void> {\n const base = readWebUrl();\n if (!base) return; // no work web running\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 3000);\n try {\n await fetch(`${base}${route}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ cwd }),\n signal: controller.signal,\n });\n } catch {\n /* best-effort — never block Claude's turn on a checkpoint */\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface HookInput {\n event: HookEvent;\n cwd: string;\n}\n\nexport interface HookOutput {\n /** Plain text appended to the user's prompt (prompt-submit) or\n * raw JSON `{decision:'block', reason}` that prevents stop (stop). */\n stdout: string;\n /** The comment ids surfaced — caller marks them delivered. */\n deliveredIds: string[];\n /** The session id that produced the output, when there was something\n * to deliver. Null otherwise (so the caller knows to skip markDelivered). */\n sessionId: string | null;\n}\n\n/**\n * Pure transformation: given an event and cwd, produce the stdout payload\n * Claude Code expects plus the ids to mark delivered. Returns null when\n * there's nothing to surface. No I/O on stdin/stdout — the caller wraps.\n */\nexport function computeHookOutput(\n input: HookInput,\n /** Which of these ids this caller may deliver. The real hook claims them\n * atomically (claimForDelivery) so a racing PTY push can't send them too;\n * the default keeps this function pure for tests. */\n claim: (sessionId: string, ids: string[]) => string[] = (_s, ids) => ids,\n /** The agent that ran the hook: it says how notes are handed over (its hook output format). */\n agent: AgentAdapter = agentById('claude'),\n): HookOutput | null {\n const session = findSessionForCwd(input.cwd);\n if (!session) return null;\n\n const activity = readSessionActivity(session);\n if (activity.state === 'stale') return null;\n\n const sessionId = sessionIdFor(session);\n const unclaimed = readPendingForWorktree(session);\n if (unclaimed.length === 0) return null;\n const mine = new Set(\n claim(\n sessionId,\n unclaimed.map((c) => c.id),\n ),\n );\n const pending = unclaimed.filter((c) => mine.has(c.id));\n if (pending.length === 0) return null;\n\n const text = formatPendingForPrompt(pending);\n if (!text) return null;\n\n const ids = pending.map((c) => c.id);\n // The agent's way of taking notes from a hook (Claude: added to the prompt; at Stop, `decision: block`).\n const edge = input.event === 'prompt-submit' ? 'turn-start' : 'turn-end';\n const stdout = agent.events ? agent.events.handOver(edge, text) : text + '\\n';\n return { stdout, deliveredIds: ids, sessionId };\n}\n\n/** What an agent sends a hook on stdin: its own shape, read by its adapter (agents/). */\ntype HookPayload = Record<string, unknown>;\n\n/** The turn edge a status hook is for. */\nconst STATUS_EDGE: Partial<Record<HookEvent, TurnEdge>> = {\n 'status-prompt': 'turn-start',\n 'status-stop': 'turn-end',\n 'status-notify': 'notify',\n};\n\n/** Map a status hook + its payload to a status event, through the agent that ran it. Exported for tests. */\nexport function statusEventFor(event: HookEvent, payload: HookPayload, agent: AgentAdapter = agentById('claude')): StatusEvent | null {\n const edge = STATUS_EDGE[event];\n return edge && agent.events ? agent.events.read(edge, payload).status : null;\n}\n\n/** The folder a hook fired in: what the agent says, else the hook's own. */\nfunction hookCwd(payload: HookPayload, agent: AgentAdapter): string {\n return agent.events?.read('turn-start', payload).cwd ?? (typeof payload.cwd === 'string' ? payload.cwd : process.cwd());\n}\n\nasync function readStdinJson(): Promise<HookPayload> {\n if (process.stdin.isTTY) return {};\n return new Promise((resolve) => {\n const chunks: Buffer[] = [];\n let resolved = false;\n // No payload after 1 s (stdin never closed): carry on without one.\n const fallback = setTimeout(() => done({}), 1000);\n const done = (val: HookPayload) => {\n if (resolved) return;\n resolved = true;\n // The fallback timer kept every hook process alive a full second\n // after its work was done — on each of several hooks per turn.\n clearTimeout(fallback);\n resolve(val);\n };\n process.stdin.on('data', (c: Buffer) => chunks.push(c));\n process.stdin.on('end', () => {\n try {\n const raw = Buffer.concat(chunks).toString('utf-8').trim();\n done(raw ? (JSON.parse(raw) as HookPayload) : {});\n } catch {\n done({});\n }\n });\n process.stdin.on('error', () => done({}));\n });\n}\n\nconst HOOK_EVENTS = [\n 'prompt-submit',\n 'stop',\n 'checkpoint',\n 'checkpoint-seal',\n 'status-prompt',\n 'status-stop',\n 'status-notify',\n 'assistant-context',\n 'turn-start',\n 'turn-end',\n] as const;\n\n/** `work hook <event> [--agent <id>]` without the yargs router (bin.ts's fast path). An\n * unknown event is ignored: a hook must never fail an agent's turn. The agent\n * that runs it says so with --agent (Claude Code's hooks, installed before\n * agents had a name here, don't: Claude is the default). */\nexport async function runHookEvent(event: string | undefined, args: readonly string[] = []): Promise<void> {\n if (!event || !(HOOK_EVENTS as readonly string[]).includes(event)) return;\n await handleHook(event as HookEvent, hookAgentArg(args));\n}\n\n/** The agent a hook names (`--agent <id>`; Claude when it names none). */\nexport function hookAgentArg(args: readonly string[]): string {\n const i = args.indexOf('--agent');\n return i >= 0 && args[i + 1] && !args[i + 1].startsWith('-') ? args[i + 1] : 'claude';\n}\n\nexport const hookCommand: CommandModule = {\n command: 'hook <event>',\n describe: false, // hidden — humans don't call this directly\n builder: (y) =>\n y\n .positional('event', {\n type: 'string',\n choices: HOOK_EVENTS,\n describe: 'Hook event name',\n })\n .option('agent', { type: 'string', default: 'claude', describe: 'The agent running the hook' }),\n handler: async (argv) => handleHook(argv.event as HookEvent, String(argv.agent ?? 'claude')),\n};\n\nexport interface TurnHookIo {\n write: (text: string) => void;\n post: (route: string, cwd: string) => Promise<void>;\n /** The own-checkout note for a folder (tests); default: from the session and config. */\n ownCheckoutNote?: (cwd: string) => string | null;\n}\n\n/** The note for a turn starting in a repo's own checkout (the session for that folder), or null. */\nexport function ownCheckoutNoteFor(cwd: string): string | null {\n const session = findSessionForCwd(cwd);\n if (!session || session.isGroup) return null;\n const repos = loadConfig()?.repos ?? {};\n return isOwnCheckout(session, repos) ? ownCheckoutNote(session) : null;\n}\n\n/**\n * `turn-start` / `turn-end`: what three hooks did, in one process. Pending\n * comments are written for Claude first (prompt-submit / stop output), then\n * the checkpoint nudge and the status record run side by side.\n */\nexport async function runTurnHook(\n start: boolean,\n payload: HookPayload,\n io: TurnHookIo = { write: (t) => void process.stdout.write(t), post: postToWeb },\n agent: AgentAdapter = agentById('claude'),\n): Promise<void> {\n const cwd = hookCwd(payload, agent);\n const result = computeHookOutput({ event: start ? 'prompt-submit' : 'stop', cwd }, claimForDelivery, agent);\n if (result?.sessionId) io.write(result.stdout);\n // On a repo's own checkout: stay on its branch — branches are work's (own-checkout.ts).\n if (start) {\n const note = io.ownCheckoutNote ? io.ownCheckoutNote(cwd) : ownCheckoutNoteFor(cwd);\n if (note) io.write(note + '\\n');\n }\n // A Stop that just handed Claude your comments (`decision: block`) is no\n // end of the turn: Claude goes on with them, and its real Stop comes later\n // (recorded as a stop then, so you hear when it is done).\n const handedOn = !start && !!result?.sessionId;\n await Promise.all([\n io.post(start ? 'api/checkpoint/seal' : 'api/checkpoint', cwd),\n handedOn\n ? recordStatus('status-stop', payload, cwd, io.post, { kind: 'continue', what: 'Working on the comments you sent' }, agent)\n : recordStatus(start ? 'status-prompt' : 'status-stop', payload, cwd, io.post, undefined, agent),\n ]);\n}\n\n/** Record a status event for the cwd's session and nudge work web. No-op outside a work session. */\nasync function recordStatus(\n event: HookEvent,\n payload: HookPayload,\n cwd: string,\n post: (route: string, cwd: string) => Promise<void> = postToWeb,\n override?: StatusEvent,\n agent: AgentAdapter = agentById('claude'),\n): Promise<void> {\n const session = findSessionForCwd(cwd);\n const statusEvent = override ?? statusEventFor(event, payload, agent);\n if (!session || !statusEvent) return;\n // Best-effort — never block Claude's turn on bookkeeping — but logged,\n // so \"why does the inbox not show this session?\" has an answer.\n const recorded = await bestEffortAsync(`record status ${event} for ${session.target}:${session.branch}`, async () => {\n await recordStatusEvent(sessionIdFor(session), statusEvent);\n return true;\n });\n if (recorded) await post('api/status-changed', cwd);\n}\n\nasync function handleHook(event: HookEvent, agentId = 'claude'): Promise<void> {\n {\n // Bail when this hook fired from one of work's OWN internal `claude -p`\n // runs (checkpoint naming, Jira slug, CLAUDE.md gen). Those headless\n // Claudes inherit the WORK_INTERNAL_CLAUDE marker; without this guard the\n // checkpoint-naming run recursively seals + spawns checkpoints, fragmenting\n // one Claude round into many spurious steps. See internal-claude.ts.\n if (isInternalRun()) return;\n const payload = await readStdinJson();\n const agent = agentById(agentId);\n const cwd = hookCwd(payload, agent);\n // The dashboard assistant's UserPromptSubmit hook (installed only in its\n // own folder): stdout becomes context for the prompt — what the user is\n // looking at in the dashboard.\n if (event === 'assistant-context') {\n const text = readAssistantContext();\n if (text) process.stdout.write(text + '\\n');\n return;\n }\n // Checkpoint bridges are independent of comment delivery: just nudge work\n // web, emit nothing to Claude's context.\n if (event === 'checkpoint') {\n await postToWeb('api/checkpoint', cwd);\n return;\n }\n if (event === 'checkpoint-seal') {\n await postToWeb('api/checkpoint/seal', cwd);\n return;\n }\n // One hook per turn edge (the full dashboard installs these): delivery,\n // status and checkpoint in ONE process instead of three — each `work`\n // start is a node boot, for every turn of every Claude on the machine.\n // What Claude reads (pending comments) is written first; the\n // bookkeeping runs after, side by side.\n if (event === 'turn-start' || event === 'turn-end') {\n await runTurnHook(event === 'turn-start', payload, undefined, agent);\n return;\n }\n // Attention inbox: record the session's state, then nudge work web so\n // the dashboard (and desktop notification) updates immediately. Emits\n // nothing to Claude. Outside a work session it's a no-op.\n if (STATUS_EVENTS.has(event)) {\n await recordStatus(event, payload, cwd, postToWeb, undefined, agent);\n return;\n }\n // Claimed (= marked delivered) before printing: the process ends right\n // after this write, and a claim is what stops a PTY push racing us from\n // sending the same comments.\n const result = computeHookOutput({ event, cwd }, claimForDelivery, agent);\n if (!result || !result.sessionId) return;\n process.stdout.write(result.stdout);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAM,gBAAgB,oBAAI,IAAe,CAAC,iBAAiB,eAAe,eAAe,CAAC;AAU1F,eAAe,UAAU,OAAe,KAA4B;AAClE,QAAM,OAAO,WAAW;AACxB,MAAI,CAAC,KAAM;AACX,QAAM,aAAa,IAAI,gBAAgB;AACvC,QAAM,QAAQ,WAAW,MAAM,WAAW,MAAM,GAAG,GAAI;AACvD,MAAI;AACF,UAAM,MAAM,GAAG,IAAI,GAAG,KAAK,IAAI;AAAA,MAC7B,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU,EAAE,IAAI,CAAC;AAAA,MAC5B,QAAQ,WAAW;AAAA,IACrB,CAAC;AAAA,EACH,QAAQ;AAAA,EAER,UAAE;AACA,iBAAa,KAAK;AAAA,EACpB;AACF;AAuBO,SAAS,kBACd,OAIA,QAAwD,CAAC,IAAI,QAAQ,KAErE,QAAsB,UAAU,QAAQ,GACrB;AACnB,QAAM,UAAU,kBAAkB,MAAM,GAAG;AAC3C,MAAI,CAAC,QAAS,QAAO;AAErB,QAAM,WAAW,oBAAoB,OAAO;AAC5C,MAAI,SAAS,UAAU,QAAS,QAAO;AAEvC,QAAM,YAAY,aAAa,OAAO;AACtC,QAAM,YAAY,uBAAuB,OAAO;AAChD,MA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