SLOPSHOPPER

gh-linear-parse-mod

Band above the prompt listing the GitHub PR and Linear links discussed in the session (your prompts and the assistant's answers); /gh-linear-parse-mod toggles…

bandguardcommandtoastprompttool
v0.1.0no licenseupdated 2026-10-26mreedr/gh-linear-parse-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · gh-linear-parse-mod
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /gh-linear-parse-mod ⎿ gh-linear-parse-mod: Session links hidden. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

gh-linear-parse-mod

A Claude Code mod that keeps the GitHub PR and Linear links discussed in a session in a band above the prompt. It reads your prompts and the assistant's answers (not tool results), and on first load it backfills links already in the transcript. Pressing a link opens it in your default browser, or in the browser the browser option names. The band has up to three sections, each under its own header row: Status (Claude's status line), GitHub, then Linear. PRs show as repo | #N; Linear issues show as ENG-123 | slug words, and other Linear pages as project | name, followed by the tab when the link names one (project | new onboarding · overview). Each PR is followed by its author's first two letters (mr for mreedr), its lines added and deleted (+120 -34, in green and red), and a short, gray form of its title: a conventional-commit scope becomes a tag, ticket references and clauses such as when ... or once ... are dropped, and the rest is cut at the band's edge. The line counts are never cut; on a band too narrow for them the row shows the title alone. Each Linear issue is followed by its workflow status (In progress, In review), read through the session's Linear MCP server. The whole row past its x opens the link. A /clear keeps the band, with its statuses, dismissals and grouping, so the next task can still read its links through links_band; only Claude's status line goes. Use /gh-linear-parse-mod clear to empty it. Each session's links and dismissals are saved (the 30 most recent sessions), so a resumed session gets its band back even after compaction took the links out of the conversation. The header shows how many links the session has and when the PRs and issues were last read, with its buttons at the right edge: Refresh reads them all again. On a narrow band the time is left out so the header stays on one line.

Install

You need a recent Claude Code and the GitHub CLI (gh), signed in with gh auth login; the PR status emoji come from gh. Linear statuses need a Linear MCP server connected to Claude Code (one whose tools are named mcp__<server>__get_issue, such as Linear's own linear-server); without one, Linear rows show no status.

In a Claude Code terminal session:

/plugin install gh-linear-parse-mod --marketplace mreedr/gh-linear-parse-mod

Answer y to add the marketplace, then pick a scope (user scope loads it in every session). If that form is not accepted, add the marketplace and install in two steps:

/plugin marketplace add mreedr/gh-linear-parse-mod
/plugin install gh-linear-parse-mod@gh-linear-parse-mod

Start a new session: PR and Linear links you or Claude mention show up in a band above the prompt. Links open in your default browser; see Browser to pick one. To get later versions, update the plugin from /plugin.

Browser

The browser option is empty by default, which opens links in the system default browser (open, xdg-open or start). On macOS it can name an app instead, such as Brave Browser or Google Chrome; set it in the plugin's config menu or in ~/.claude/settings.json:

"pluginConfigs": { "gh-linear-parse-mod": { "options": { "browser": "Brave Browser" } } }

With a Chromium browser (Brave, Chrome, Edge, Chromium, Vivaldi) the mod first switches to a tab already on the link, including a PR's /files page. The first time, macOS asks whether your terminal may control the browser; without that, links open in a new tab. If the named browser fails to open, the link opens in the default browser with a toast.

Usage

CommandEffect
/gh-linear-parse-modToggle the band (also on, off)
/gh-linear-parse-mod add <url>Add a GitHub PR or Linear link to the band and check its status now, even one dismissed with x (also shows a hidden band)
/gh-linear-parse-mod group [how]Ask Claude to group the PRs in the GitHub section, optionally saying how (group by merge order); see PR groups
/gh-linear-parse-mod group clearDrop the grouping; the GitHub section goes back to newest first
/gh-linear-parse-mod clearEmpty the band for this session
/gh-linear-parse-mod refreshRe-check the status of every PR and Linear issue in the band
`/gh-linear-parse-mod watch on\off`Turn the 5-minute status refresh on or off (this session; on by default)
`/gh-linear-parse-mod nudge on\off`Ask agents in their system prompt to keep their status current, or stop asking (all sessions; on by default)
/gh-linear-parse-mod resetLet links dismissed with x show again (this session)
/gh-linear-parse-mod color <color> [fill]Border (or fill) color for this session: a name, hex or theme key; the default is a gray border, color alone goes back to it, color none removes it
/gh-linear-parse-mod <color> [fill]Same as color <color> [fill], for a color name, hex or theme key; any other unknown option shows the list of options and leaves the band alone

In the band, x dismisses a link for the session, 👀 (next to Refresh, shown while there are some) hides the PRs waiting on a review and shows them again (it reads 👀 N while N are hidden), 🔑 gcloud runs gcloud auth login with its sign-in page opened in Brave (it reads 🔑 gcloud… until gcloud finishes, then a toast says how it went), 🧹 (shown while there are some) dismisses every merged or closed PR, and Show N more / Show less expands the list. App buttons such as 🔑 gcloud and 🔑 vercel sit just after the updated time, and the band's own buttons (Refresh through Hide) sit on the right. 🔑 vercel runs npx vercel login and opens its device sign-in page in Brave (it reads 🔑 vercel… until the CLI finishes, then a toast says how it went).

PR status

PR rows carry three status columns, labelled PR, CI and Rv in the GitHub header row. Linear rows carry one, labelled St in the Linear header row.

ColumnEmoji
PR🟢 open · 📝 draft · 🟣 merged · ⚫ closed
CI✅ pass · ❌ fail · ⏳ running · 💥 merge conflict with the base branch (shown instead of the CI state) · blank when there are no checks; only the newest run of each check counts, so a run cancelled by a rerun or a newer push is ignored
Rv🚀 approved · 👀 review needed, or a reviewer requested on a PR whose base needs no review (a stacked PR) · ✋ changes requested · 💬 a person other than the author commented, no approval yet (bots such as claude don't count) · 🦯 no reviewer assigned (open PRs; a draft is not asking for review yet, so it shows nothing) · 🌒 merged, the review is over

A dim … means not checked yet, and a dim ? means gh could not read the PR. Merged and closed PRs are dimmed. Status comes from gh pr view, so gh must be installed and signed in. A PR is checked when it is first mentioned, again when it is mentioned at least 15 seconds later, every 90 seconds while its CI runs (for up to 6 hours), and on refresh. While the watch is on and the band is showing, open and draft PRs in view are also re-checked every 5 minutes, so approvals, merges and new pushes show up on their own.

Linear status

Status typeEmoji
Triage📥
Backlog💤
Unstarted (todo)⚪
Started (in progress, in review, blocked)🟡
Completed🟣
Canceled or duplicate⚫

The emoji follows the status's type, and the status's own name follows the issue's label, lined up down the band. Completed, canceled and duplicate issues are dimmed, and a dim ? means the Linear server could not read the issue. An issue is checked when it is first mentioned and on refresh; while the watch is on, unfinished issues in view are re-checked every 5 minutes. The mod calls only the server's read-only get_issue tool.

Claude's view of the band

Claude can read the band through the mcp__gh-linear-parse-mod__links_band tool, which returns this session's links with each PR's status and each Linear issue's status, dismissed keys, hidden and expanded flags, and color. Ask something like "what's in my links band?".

Claude's status

Claude can set a status line in the band's Status section with the mcp__gh-linear-parse-mod__set_status tool, a short note of what it is doing or waiting on (waiting on CI for #812), followed by the time it was set. A new status replaces the old one, and an empty text clears it. Press its x to clear it yourself; a /clear clears it too. With no links in the band, the band shows the status line alone. By default the mod adds a short section to the system prompt asking the agent to keep its status current; /gh-linear-parse-mod nudge off removes it in every session from the next request, and nudge on puts it back.

PR groups

Claude groups the GitHub section only when asked: run /gh-linear-parse-mod group, or ask in your own words. It sets the layout with the mcp__gh-linear-parse-mod__group_prs tool, a list of groups from top to bottom, each with an optional label, an optional line of text and optional PRs. A group with no PRs is informational. A step is a to-do row of its own for work that is not a PR, such as applying a migration, drawn as ☐ and ticked to ☑ once done. PRs can be links, owner/repo#N, or repo#N; a repo#N for a PR not in the band yet takes its owner from that repo's PRs in the band.

PR CI Rv GitHub
── round 1 ──
🟢 ✅ 🚀 api | #42 add the export endpoint
🟢 ⏳ 🦯 web | #43 export button
☐ apply the migration
── round 2 ──
   run the smoke checks on staging after round 1
── other ──
🟢 ✅ 🚀 api | #46 fix typo
── ▸ landed (2) ──

Labels are dim dividers and text is a dim italic line; PR rows draw as they always do. PRs in no group show under other, newest first, and mentioning a grouped PR does not move it. Grouped PRs always show; Show N more collapses only the rest. x on a PR takes it out of its group. Labels and text lines have no x; ask Claude to change the grouping, or group clear to drop it. Press a step to tick it, and again to untick it; Claude sees it through links_band. For small changes Claude uses the mcp__gh-linear-parse-mod__edit_groups tool instead of sending the whole layout again: put a PR into a group, remove it, set a group's label or text or tick a step, insert a group or step, or delete one. Merged and closed PRs leave their groups on their own and fold into one landed (N) row at the bottom; press it to show or fold them. A group whose PRs have all landed shows a ✓ after its label, and 🧹 dismisses the landed PRs along with the groups they finished. The grouping is saved with the session's links, links_band reports it, and group clear or clear drops it. links_band also reports sinceGrouping: the grouped PRs that landed and the open PRs that joined the band since the grouping was last set or edited. While PRs are grouped, Claude's system prompt asks it to check that after it opens, merges or closes a PR, and to keep the grouping current.

Develop

claude plugin validate .
claude plugin test .
claude --plugin-dir .
Source 4 files
hooks/register.tsx 1095 lines
1import { atom, read, update } from 'claude-code'
2import type { BoxProps, EngineInterface, Register } from 'claude-code'
3
4import type { StatusNote, BandColor, GroupingBase, IssueStatus, Item, PrGroup, PrStatus } from '../types'
5import { openLink } from './browser'
6import {
7  PR_FIELDS,
8  addKey,
9  authorInitials,
10  bandGroups,
11  cell,
12  clockTime,
13  diffParts,
14  editGroups,
15  extractLinks,
16  fitText,
17  githubRows,
18  isAwaitingReview,
19  isIssueDone,
20  isIssueKey,
21  isPrKey,
22  issueGlyph,
23  issueId,
24  issueWatchKeys,
25  isStale,
26  lastChecked,
27  linkLabel,
28  linksFromHistory,
29  mergeLinks,
30  nextStatus,
31  parseColorArgs,
32  parseIssueResult,
33  parseGroups,
34  parsePrJson,
35  prRef,
36  shortTitle,
37  shouldPoll,
38  statusGlyphs,
39  textWidth,
40  watchKeys,
41  withoutDone,
42  withoutPrs,
43} from './parse'
44
45type $ = EngineInterface
46
47const items = atom({ plugin: 'gh-linear-parse-mod', key: 'items' } as const, [] as Item[])
48const isHidden = atom({ plugin: 'gh-linear-parse-mod', key: 'isHidden' } as const, false)
49const dismissed = atom({ plugin: 'gh-linear-parse-mod', key: 'dismissed' } as const, [] as string[])
50const DEFAULT_COLOR: BandColor = { color: 'gray', isFill: false }
51const bandColor = atom({ plugin: 'gh-linear-parse-mod', key: 'bandColor' } as const, DEFAULT_COLOR as BandColor | null)
52const hasBackfilled = atom({ plugin: 'gh-linear-parse-mod', key: 'hasBackfilled' } as const, false)
53const isExpanded = atom({ plugin: 'gh-linear-parse-mod', key: 'isExpanded' } as const, false)
54const prStatuses = atom({ plugin: 'gh-linear-parse-mod', key: 'prStatuses' } as const, {} as Record<string, PrStatus>)
55const isWatching = atom({ plugin: 'gh-linear-parse-mod', key: 'isWatching' } as const, true)
56const issueStatuses = atom({ plugin: 'gh-linear-parse-mod', key: 'issueStatuses' } as const, {} as Record<string, IssueStatus>)
57const refreshing = atom({ plugin: 'gh-linear-parse-mod', key: 'refreshing' } as const, 0)
58const agentStatus = atom({ plugin: 'gh-linear-parse-mod', key: 'agentStatus' } as const, null as StatusNote | null)
59const hidesAwaitingReview = atom({ plugin: 'gh-linear-parse-mod', key: 'hidesAwaitingReview' } as const, false)
60const prGroups = atom({ plugin: 'gh-linear-parse-mod', key: 'prGroups' } as const, null as PrGroup[] | null)
61const groupingBase = atom({ plugin: 'gh-linear-parse-mod', key: 'groupingBase' } as const, null as GroupingBase | null)
62const showsLanded = atom({ plugin: 'gh-linear-parse-mod', key: 'showsLanded' } as const, false)
63const isSigningIn = atom({ plugin: 'gh-linear-parse-mod', key: 'isSigningIn' } as const, false)
64const isSigningInVercel = atom({ plugin: 'gh-linear-parse-mod', key: 'isSigningInVercel' } as const, false)
65
66const SHOWN = 5
67const MAX_STORED = 40
68const MAX_TEXT = 200_000
69const MAX_DISMISSED = 500
70// a muted slate blue, readable on dark and light themes
71const TEXT_COLOR = '#8b95b8'
72const STATE_TOOL = 'mcp__gh-linear-parse-mod__links_band'
73const STATUS_TOOL = 'mcp__gh-linear-parse-mod__set_status'
74const GROUP_TOOL = 'mcp__gh-linear-parse-mod__group_prs'
75const EDIT_TOOL = 'mcp__gh-linear-parse-mod__edit_groups'
76const MAX_STATUS = 120
77const RECHECK_MS = 15_000
78// gcloud opens its sign-in page through Python's webbrowser, which takes BROWSER as a plain program path.
79const BRAVE = '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'
80const SIGN_IN_MS = 5 * 60_000
81// vercel login opens its device page through the `open` package, which ignores BROWSER: CI=1 keeps it
82// from opening anything, and the band opens the page it prints in Brave.
83const VERCEL_PAGE = /(https:\/\/vercel\.com\/oauth\/device\S*)\s/
84const CI_POLL_MS = 90_000
85const CI_POLL_WINDOW_MS = 6 * 60 * 60_000
86const WATCH_MS = 5 * 60_000
87// Where a Linear MCP server's `get_issue` is found when the tool list names none.
88const LINEAR_SERVERS = ['linear-server', 'claude.ai Linear', 'linear']
89const LINEAR_TOOL = /^mcp__(.*linear.*)__get_issue$/i
90
91async function record($: $, text: string): Promise<string[]> {
92  try {
93    const found = extractLinks(text.slice(0, MAX_TEXT))
94    if (found.length === 0) return []
95    const gone = await read($, dismissed)
96    await update($, items, list => mergeLinks(list, found, MAX_STORED, gone))
97    await persist($)
98    return found.map(l => l.key).filter(k => isChecked(k) && !gone.includes(k))
99  } catch {
100    // a failed update only costs the band an entry, never the prompt
101    return []
102  }
103}
104
105const isChecked = (key: string) => isPrKey(key) || isIssueKey(key)
106
107const HELP =
108  'Use no option to show or hide the band, or one of: add <url>, group [how], group clear, on, off, refresh, clear, reset, watch on|off, nudge on|off, color <color> [fill] (a color name alone works too).'
109
110const NUDGE = {
111  id: 'gh-linear-parse-mod:status-nudge',
112  scope: 'session',
113  text: `Keep a status line current in the links band above the prompt with ${STATUS_TOOL}: set it, in under 80 characters, when you start work that will take more than a minute or begin waiting on something (CI, a subagent, a review); update it when that changes; and clear it with an empty text when you finish. Only the main conversation sets it; subagents leave it alone.`,
114} as const
115
116// While PRs are grouped, each request's system prompt asks the agent to keep the grouping current.
117const GROUP_NUDGE = {
118  id: 'gh-linear-parse-mod:group-nudge',
119  scope: 'session',
120  text: `The person has grouped the PRs in the links band above the prompt. After you open, merge or close a PR, read ${STATE_TOOL}: when its sinceGrouping lists open PRs in no group, or the plan's steps have moved on, change the grouping with ${EDIT_TOOL}, or lay it out again with ${GROUP_TOOL} when most of it moves. Tick a step with ${EDIT_TOOL} once it is done. Merged and closed PRs leave their groups on their own.`,
121} as const
122
123// Whether each request's system prompt asks the agent to keep its status; on unless turned off.
124async function isNudging($: $): Promise<boolean> {
125  try {
126    return (await $.store.get('statusNudge')) !== false
127  } catch {
128    return true
129  }
130}
131
132const SAVED_SESSIONS = 30
133const isItem = (x: unknown): x is Item =>
134  typeof x === 'object' && x !== null && typeof (x as Item).key === 'string' && typeof (x as Item).url === 'string'
135
136const isGroup = (x: unknown): x is PrGroup =>
137  typeof x === 'object' && x !== null && Array.isArray((x as PrGroup).prs) && (x as PrGroup).prs.every(k => typeof k === 'string')
138
139const isStrings = (x: unknown): x is string[] => Array.isArray(x) && x.every(k => typeof k === 'string')
140const isBase = (x: unknown): x is GroupingBase =>
141  typeof x === 'object' && x !== null && isStrings((x as GroupingBase).seen) && isStrings((x as GroupingBase).live)
142
143// Each session's links and dismissals, kept across restarts so a resumed session gets
144// its band back even when compaction took the links out of the transcript.
145async function persist($: $) {
146  try {
147    const id = await $.session.id()
148    const [list, gone, groups, base] = await Promise.all([read($, items), read($, dismissed), read($, prGroups), read($, groupingBase)])
149    const saved = await $.store.get('sessions')
150    const index = Array.isArray(saved) ? saved.filter((s): s is string => typeof s === 'string') : []
151    const ids = [id, ...index.filter(s => s !== id)]
152    for (const old of ids.slice(SAVED_SESSIONS)) await $.store.delete(`links:${old}`)
153    await $.store.set(`links:${id}`, { items: list, dismissed: gone, groups, base })
154    await $.store.set('sessions', ids.slice(0, SAVED_SESSIONS))
155  } catch {
156    // an unsaved band is rebuilt from the transcript on resume
157  }
158}
159
160async function restore($: $) {
161  if ((await read($, items)).length > 0) return
162  const saved = (await $.store.get(`links:${await $.session.id()}`)) as { items?: unknown; dismissed?: unknown; groups?: unknown; base?: unknown } | undefined
163  if (!saved || !Array.isArray(saved.items)) return
164  const list = saved.items.filter(isItem)
165  const gone = Array.isArray(saved.dismissed) ? saved.dismissed.filter((k): k is string => typeof k === 'string') : []
166  await update($, dismissed, keys => (keys.length > 0 ? keys : gone))
167  await update($, items, current => (current.length > 0 ? current : list))
168  const groups = Array.isArray(saved.groups) ? saved.groups.filter(isGroup) : []
169  if (groups.length > 0) await update($, prGroups, current => current ?? groups)
170  if (groups.length > 0 && isBase(saved.base)) await update($, groupingBase, current => current ?? (saved.base as GroupingBase))
171  refreshSoon($, list.map(i => i.key).filter(isChecked))
172}
173
174const inflight = new Set<string>()
175let isPolling = false
176
177// The CI poll runs only while some PR's CI does; a reload drops the timer and the
178// flag together, and session.start restarts it when a PR is still running.
179function ensurePolling($: $) {
180  if (isPolling) return
181  isPolling = true
182  try {
183    $.clock.every(CI_POLL_MS, async () => {
184      const now = await $.clock.now()
185      const known = await read($, prStatuses)
186      const list = await read($, items)
187      refreshSoon($, list.filter(i => shouldPoll(known[i.key], now, CI_POLL_WINDOW_MS)).map(i => i.key), true)
188    })
189  } catch {
190    isPolling = false
191  }
192}
193
194let isWatchTimer = false
195
196// Every 5 minutes, while the watch is on and the band is up, the PRs in view that
197// can still change; started by the first status check, like the CI poll.
198function ensureWatching($: $) {
199  if (isWatchTimer) return
200  isWatchTimer = true
201  try {
202    $.clock.every(WATCH_MS, async () => {
203      if (!(await read($, isWatching)) || (await read($, isHidden))) return
204      const list = await read($, items)
205      const visible = list.slice(0, (await read($, isExpanded)) ? list.length : SHOWN)
206      const now = await $.clock.now()
207      const keys = visible.map(i => i.key)
208      const prs = watchKeys(keys, await read($, prStatuses), now, CI_POLL_WINDOW_MS)
209      refreshSoon($, [...prs, ...issueWatchKeys(keys, await read($, issueStatuses))], true)
210    })
211  } catch {
212    isWatchTimer = false
213  }
214}
215
216let linearServer: string | undefined
217
218// The Linear MCP server the session has, found once: the one the tool list names,
219// else the usual names; the issue's status, or undefined when no server answers.
220async function readIssue($: $, id: string) {
221  const args = { id, fields: ['status', 'statusType'] }
222  if (linearServer) {
223    const r = await $.mcp.call(linearServer, 'get_issue', args).catch(() => undefined)
224    if (r) return parseIssueResult(r)
225    linearServer = undefined
226  }
227  const tools = await $.tool.list().catch(() => [])
228  const listed = tools.map(t => LINEAR_TOOL.exec(t.name)?.[1]).filter((n): n is string => !!n)
229  for (const server of new Set([...listed, ...LINEAR_SERVERS])) {
230    const r = await $.mcp.call(server, 'get_issue', args).catch(() => undefined)
231    const status = r && parseIssueResult(r)
232    if (status) {
233      linearServer = server
234      return status
235    }
236  }
237  return undefined
238}
239
240async function refreshIssue($: $, key: string) {
241  const fetched = await readIssue($, issueId(key))
242  // with no Linear server in the session the row stays blank
243  if (!fetched && !linearServer) return
244  const now = await $.clock.now()
245  if (!(await read($, items)).some(i => i.key === key)) return
246  await update($, issueStatuses, map => ({ ...map, [key]: fetched ? { ...fetched, checkedAt: now } : { ...map[key], checkedAt: now } }))
247  ensureWatching($)
248}
249
250async function refresh($: $, key: string) {
251  if (inflight.has(key)) return
252  if (isIssueKey(key)) {
253    inflight.add(key)
254    try {
255      await refreshIssue($, key)
256    } finally {
257      inflight.delete(key)
258    }
259    return
260  }
261  const item = (await read($, items)).find(i => i.key === key)
262  const ref = item && prRef(item.url)
263  if (!ref) return
264  inflight.add(key)
265  try {
266    const argv = ['gh', 'pr', 'view', String(ref.number), '-R', ref.repo, '--json', PR_FIELDS]
267    const ran = await $.process.run(argv, { timeoutMs: 20_000 }).catch(() => null)
268    const fetched = ran?.exitCode === 0 ? parsePrJson(ran.stdout) : undefined
269    const now = await $.clock.now()
270    if (!(await read($, items)).some(i => i.key === key)) return
271    await update($, prStatuses, map => ({ ...map, [key]: nextStatus(map[key], fetched, now) }))
272    if (fetched?.ci === 'running') ensurePolling($)
273    ensureWatching($)
274  } finally {
275    inflight.delete(key)
276  }
277}
278
279// One at a time, in band order, off the hook's path so `gh` never holds a prompt.
280function refreshSoon($: $, keys: readonly string[], isForced = false) {
281  if (keys.length === 0) return
282  try {
283    $.clock.after(1, () =>
284      void (async () => {
285        await update($, refreshing, n => n + 1)
286        try {
287          for (const key of keys) {
288            const now = await $.clock.now()
289            const s = isIssueKey(key) ? (await read($, issueStatuses))[key] : (await read($, prStatuses))[key]
290            if (isForced || isStale(s, now, RECHECK_MS)) await refresh($, key)
291          }
292        } finally {
293          await update($, refreshing, n => Math.max(0, n - 1))
294        }
295      })().catch(() => undefined),
296    )
297  } catch {
298    // a refused timer leaves the status to the next mention or poll
299  }
300}
301
302let isBackfilling = false
303
304// Once per session, the links already in the transcript. An empty transcript (a new
305// session, or one whose history has not loaded yet) leaves it to the next trigger.
306async function backfill($: $) {
307  if (isBackfilling || (await read($, hasBackfilled))) return
308  isBackfilling = true
309  try {
310    const messages = await $.session.messages()
311    if (messages.length === 0) return
312    const gone = await read($, dismissed)
313    const past = linksFromHistory(messages.map(m => m.text.slice(0, MAX_TEXT)), MAX_STORED, gone)
314    await update($, items, list => mergeLinks(past, list, MAX_STORED))
315    await persist($)
316    await update($, hasBackfilled, () => true)
317    refreshSoon($, (await read($, items)).map(i => i.key).filter(isChecked))
318  } finally {
319    isBackfilling = false
320  }
321}
322
323function backfillSoon($: $) {
324  try {
325    $.clock.after(1, () => void backfill($).catch(() => undefined))
326  } catch {
327    // a refused timer leaves the backfill to the next trigger
328  }
329}
330
331async function refreshAll($: $): Promise<number> {
332  const keys = (await read($, items)).map(i => i.key).filter(isChecked)
333  refreshSoon($, keys, true)
334  return keys.length
335}
336
337async function dismiss($: $, key: string) {
338  await update($, dismissed, keys => addKey(keys, key, MAX_DISMISSED))
339  await update($, items, list => list.filter(i => i.key !== key))
340  await update($, prGroups, groups => groups && withoutPrs(groups, [key]))
341  await persist($)
342  await update($, prStatuses, ({ [key]: _, ...rest }) => rest)
343  await update($, issueStatuses, ({ [key]: _, ...rest }) => rest)
344}
345
346const isFinished = (s: PrStatus | undefined) => s?.state === 'merged' || s?.state === 'closed'
347
348// Dismisses the merged and closed PRs, so a later mention does not bring them back.
349async function sweep($: $) {
350  const known = await read($, prStatuses)
351  const keys = (await read($, items)).map(i => i.key).filter(k => isFinished(known[k]))
352  if (keys.length === 0) return
353  await update($, dismissed, gone => keys.reduce((acc, k) => addKey(acc, k, MAX_DISMISSED), gone))
354  await update($, items, list => list.filter(i => !keys.includes(i.key)))
355  await update($, prGroups, groups => {
356    const left = groups && withoutDone(groups, keys)
357    return left && left.length > 0 ? left : null
358  })
359  await persist($)
360  await update($, prStatuses, s => Object.fromEntries(Object.entries(s).filter(([k]) => !keys.includes(k))))
361}
362
363async function setGroups($: $, groups: PrGroup[] | null) {
364  const isSet = groups !== null && groups.length > 0
365  const known = await read($, prStatuses)
366  const prs = (await read($, items)).map(i => i.key).filter(isPrKey)
367  await update($, prGroups, () => (isSet ? groups : null))
368  await update($, groupingBase, () => (isSet ? { seen: prs, live: prs.filter(k => !isFinished(known[k])) } : null))
369  await persist($)
370}
371
372// A grouping as the tool results name it: each group by its label, text or step, with its PR count.
373const groupsSummary = (groups: readonly PrGroup[]) =>
374  groups
375    .map(g => (g.step ? `step "${g.step}"${g.isDone ? ' (done)' : ''}` : `${g.label ?? (g.text ? 'text' : 'unlabeled')} (${g.prs.length} PR${g.prs.length === 1 ? '' : 's'})`))
376    .join(', ')
377
378// PRs a grouping names that the band does not hold yet join it, even ones dismissed before.
379async function takeLinks($: $, links: readonly Item[]) {
380  const keys = links.map(l => l.key)
381  await update($, dismissed, gone => gone.filter(k => !keys.includes(k)))
382  const have = new Set((await read($, items)).map(i => i.key))
383  const fresh = links.filter(l => !have.has(l.key))
384  if (fresh.length > 0) await update($, items, list => mergeLinks(list, fresh, MAX_STORED))
385  return fresh.map(l => l.key)
386}
387
388// Ticks a step, or unticks it, when it still holds that text.
389async function toggleStep($: $, group: number, step: string) {
390  await update($, prGroups, groups =>
391    groups && groups.map((g, n) => (n === group && g.step === step ? (g.isDone ? { step: g.step, prs: g.prs } : { ...g, isDone: true }) : g)),
392  )
393  await persist($)
394}
395
396const groupPrompt = (how: string) =>
397  `Group the PRs in the links band above the prompt with ${GROUP_TOOL}` +
398  (how
399    ? `: ${how}.`
400    : '. Pick labels that fit the work, such as the order to merge or roll them out in, and add steps for the work in between that is not a PR.') +
401  ` Read ${STATE_TOOL} first for the PRs and their state.`
402
403// Cells the frame takes across: a border and its padding, or a fill's padding.
404const frameColumns = (style: BandColor | null) => (!style ? 0 : style.isFill ? 2 : 4)
405
406function frame(style: BandColor | null): Partial<BoxProps> {
407  if (!style) return {}
408  if (style.isFill) return { backgroundColor: style.color, paddingX: 1 }
409
410  return { borderStyle: 'round', borderColor: style.color, paddingX: 1 }
411}
412
413// App buttons (gcloud, vercel) sit apart from the title, left of the band's own buttons.
414const APP_GAP = 1
415
416async function gcloudLogin($: $) {
417  if (await read($, isSigningIn)) return
418  await update($, isSigningIn, () => true)
419  try {
420    const ran = await $.process.run(['gcloud', 'auth', 'login'], { env: { BROWSER: BRAVE }, timeoutMs: SIGN_IN_MS }).catch(() => null)
421    const reason = ran?.stderr.trim().split('\n').filter(Boolean).at(-1)
422    $.ui.toast(ran?.exitCode === 0 ? 'gcloud: signed in' : `gcloud sign-in failed${reason ? `: ${reason.slice(0, 120)}` : ''}`)
423  } finally {
424    await update($, isSigningIn, () => false)
425  }
426}
427
428async function vercelLogin($: $) {
429  if (await read($, isSigningInVercel)) return
430  await update($, isSigningInVercel, () => true)
431  const login = $.process.spawn({ argv: ['npx', '-y', 'vercel', 'login'], env: { CI: '1' } })
432  let isTimedOut = false
433  const giveUp = $.clock.after(SIGN_IN_MS, () => {
434    isTimedOut = true
435    void login.return({ code: null, signal: null }).catch(() => undefined)
436  })
437  let output = ''
438  let isOpened = false
439  try {
440    for await (const { text } of login) {
441      output += text
442      const page = isOpened ? undefined : VERCEL_PAGE.exec(output)?.[1]
443      if (page) {
444        isOpened = true
445        await $.process.run(['open', '-a', 'Brave Browser', page]).catch(() => undefined)
446      }
447    }
448    const ended = await login.result.catch(() => null)
449    const reason = output.trim().split('\n').map(l => l.trim()).filter(l => l && l !== '>').at(-1)
450    $.ui.toast(
451      ended?.code === 0 ? 'vercel: signed in'
452        : isTimedOut ? 'vercel sign-in timed out'
453          : `vercel sign-in failed${reason ? `: ${reason.slice(0, 120)}` : ''}`,
454    )
455  } catch {
456    $.ui.toast('vercel sign-in failed: npx vercel did not start')
457  } finally {
458    giveUp.cancel()
459    await update($, isSigningInVercel, () => false)
460  }
461}
462
463async function setHidden($: $, value: boolean) {
464  await update($, isHidden, () => value)
465  await $.store.set('isHidden', value)
466}
467
468// Statuses read before the line counts were fetched.
469async function fetchMissingCounts($: $) {
470  const known = await read($, prStatuses)
471  refreshSoon($, (await read($, items)).map(i => i.key).filter(k => isPrKey(k) && known[k] !== undefined && known[k].additions === undefined), true)
472}
473
474export const register: Register = (on, options) => {
475  const browser = typeof options.browser === 'string' ? options.browser.trim() : ''
476
477  on('session.start', async ($, e, next) => {
478    const started = await next(e)
479    await $.command.register({
480      name: 'gh-linear-parse-mod',
481      description: 'Toggle the GitHub/Linear links band (args: add <url>, group [how], group clear, on, off, clear, reset, refresh, watch on|off, color <color> [fill])',
482    })
483    const stored = await $.store.get('isHidden')
484    if (typeof stored === 'boolean') await update($, isHidden, () => stored)
485    // entries from before links carried a `key` (runs, repos) are dropped on reload
486    await update($, items, list => list.filter(i => i.key))
487    // a reload ends the refresh loops that were counted
488    await update($, refreshing, () => 0)
489    await update($, isSigningIn, () => false)
490    await update($, isSigningInVercel, () => false)
491    await restore($).catch(() => undefined)
492    backfillSoon($)
493    await fetchMissingCounts($)
494    await $.tool.register({
495      name: 'links_band',
496      description:
497        "Returns this session's gh-linear-parse-mod links band: the GitHub PR and Linear links newest first (the band shows PRs above Linear links) with each PR's title, author, lines added and deleted, state, CI and review status, whether it has a merge conflict, and each Linear issue's status, as last checked, the links dismissed this session, whether the band is hidden or expanded, its color, and, while PRs are grouped, the groups top to bottom (each a label, text and PRs, or a step and whether it is done) and sinceGrouping: the grouped PRs that merged or closed and the open PRs that joined the band since group_prs or edit_groups last changed the groups. Read-only.",
498      inputSchema: { type: 'object', properties: {} },
499      isDeferred: false,
500    })
501    await $.tool.register({
502      name: 'set_status',
503      description:
504        "Sets this session's status line at the top of the gh-linear-parse-mod links band: a short note of what you are doing or waiting on (for example \"waiting on CI for #812\"), under 80 characters. Replaces any earlier status; an empty or missing text clears it. Set it when the person would want to see it at a glance, and clear it when the work is done.",
505      inputSchema: {
506        type: 'object',
507        properties: { text: { type: 'string', description: 'The status; empty or left out clears it.' } },
508      },
509      isDeferred: false,
510    })
511    await $.tool.register({
512      name: 'group_prs',
513      description:
514        "Sets how the GitHub section of the gh-linear-parse-mod links band is grouped: a list of groups, top to bottom, each with an optional label (a divider such as \"round 1\" or \"blocked\"), an optional line of text, and optional PRs (PR links, owner/repo#N, or repo#N for a repo already in the band), or else a step: a to-do row of its own for work that is not a PR, such as \"apply the migration\", which shows a box ticked once done. Sends the whole layout each time and replaces the last one; an empty list clears it. For a small change, such as moving one PR, editing one group's text or ticking a step, use edit_groups instead. PRs not in any group show under \"other\". Use it only when the person asks you to group or order PRs (for example through /gh-linear-parse-mod group), or to keep a grouping they asked for current. Merged and closed PRs leave their groups on their own and fold into a landed row at the bottom, and a group whose PRs have all landed shows a ✓, so never make a group for merged or closed PRs.",
515      inputSchema: {
516        type: 'object',
517        properties: {
518          groups: {
519            type: 'array',
520            description: 'The groups, top to bottom; empty clears the grouping.',
521            items: {
522              type: 'object',
523              properties: {
524                label: { type: 'string', description: 'The divider text, under 60 characters.' },
525                text: { type: 'string', description: 'A line of text under the label, under 200 characters.' },
526                prs: { type: 'array', items: { type: 'string' }, description: 'The PRs in this group, in order.' },
527                step: { type: 'string', description: 'Makes this group a step, a to-do row of its own, under 120 characters; it takes no label, text or PRs.' },
528                done: { type: 'boolean', description: 'For a step: whether it is done.' },
529              },
530            },
531          },
532        },
533        required: ['groups'],
534      },
535      isDeferred: false,
536    })
537    await $.tool.register({
538      name: 'edit_groups',
539      description:
540        "Changes the gh-linear-parse-mod links band's PR groups in place, one edit after another, without resending the layout. A group is its 0-based place in links_band's groups, and each edit sees the groups as the edits before it left them. Ops: put (pr into group, at a place in it or last, taken out of any other group), remove (pr out of its group, back under \"other\"), set (a group's label or text, an empty string clears one; a step's step text, or done to tick it), insert (a new group at a place or last, with a label, text and PRs, or a step), delete (a group; its PRs go back under \"other\"). A group left with nothing in it goes. PRs are PR links, owner/repo#N, or repo#N for a repo already in the band.",
541      inputSchema: {
542        type: 'object',
543        properties: {
544          edits: {
545            type: 'array',
546            description: 'The edits, applied in order.',
547            items: {
548              type: 'object',
549              properties: {
550                op: { type: 'string', enum: ['put', 'remove', 'set', 'insert', 'delete'] },
551                pr: { type: 'string', description: 'For put and remove: the PR.' },
552                group: { type: 'number', description: 'For put, set and delete: the group, 0-based.' },
553                at: { type: 'number', description: 'For put: the place in the group; for insert: the place among the groups. Last when left out.' },
554                label: { type: 'string', description: 'For set and insert: the divider text.' },
555                text: { type: 'string', description: 'For set and insert: the line of text under the label.' },
556                prs: { type: 'array', items: { type: 'string' }, description: 'For insert: the PRs in the new group.' },
557                step: { type: 'string', description: "For set and insert: a step's text." },
558                done: { type: 'boolean', description: 'For set and insert: whether the step is done.' },
559              },
560              required: ['op'],
561            },
562          },
563        },
564        required: ['edits'],
565      },
566      isDeferred: false,
567    })
568
569    const known = Object.values(await read($, prStatuses))
570    if (known.some(s => s.ci === 'running')) ensurePolling($)
571    if (known.length > 0 || Object.keys(await read($, issueStatuses)).length > 0) ensureWatching($)
572    // left by the removed Diff toggle
573    if ((await $.store.keys()).includes('isDiff')) await $.store.delete('isDiff')
574    // a reload draws the band with the new code without waiting for a change
575    $.ui.invalidate('ui.render')
576
577    return started
578  })
579
580  // A /clear goes on under a new session id with no session.start: the band carries over
581  // so the new task can still reach its links, and only the old task's status goes.
582  // A /resume swaps in another session, whose session.start restores its own band.
583  on('session.end', async ($, e, next) => {
584    if (e.reason === 'clear') {
585      await update($, agentStatus, () => null)
586      $.clock.after(1, () => void persist($))
587    }
588    if (e.reason === 'resume') {
589      await update($, items, () => [])
590      await update($, prStatuses, () => ({}))
591      await update($, issueStatuses, () => ({}))
592      await update($, dismissed, () => [])
593      await update($, isExpanded, () => false)
594      await update($, hasBackfilled, () => false)
595      await update($, agentStatus, () => null)
596      await update($, prGroups, () => null)
597      await update($, groupingBase, () => null)
598      await update($, showsLanded, () => false)
599    }
600
601    return next(e)
602  })
603
604  on('tool.call', { tool: STATE_TOOL }, async $ => {
605    const [links, gone, hidden, expanded, color, known, watching] = await Promise.all([
606      read($, items),
607      read($, dismissed),
608      read($, isHidden),
609      read($, isExpanded),
610      read($, bandColor),
611      read($, prStatuses),
612      read($, isWatching),
613    ])
614    const issues = await read($, issueStatuses)
615    const groups = await read($, prGroups)
616    const base = await read($, groupingBase)
617    const hidesReview = await read($, hidesAwaitingReview)
618    const inView = hidesReview ? links.filter(i => !isAwaitingReview(known[i.key])) : links
619    const grouped = new Set(groups?.flatMap(g => g.prs) ?? [])
620    // With groups up, merged and closed PRs fold into the landed row.
621    const landed = groups ? inView.filter(i => isFinished(known[i.key])).length : 0
622    const ungrouped = inView.filter(i => !grouped.has(i.key) && !(groups && isFinished(known[i.key]))).length
623    const urlOf = (k: string) => links.find(i => i.key === k)?.url ?? k
624    const sinceGrouping = groups && {
625      landed: (base?.live ?? []).filter(k => grouped.has(k) && isFinished(known[k])).map(urlOf),
626      notGrouped: links
627        .filter(i => isPrKey(i.key) && !grouped.has(i.key) && !base?.seen.includes(i.key) && !isFinished(known[i.key]))
628        .map(i => i.url),
629    }
630    const state = {
631      links: links.map(i => {
632        const s = known[i.key]
633        const issue = issues[i.key]
634        if (isIssueKey(i.key) && issue) return { url: i.url, status: issue.name ?? 'unavailable', statusType: issue.type, checkedAt: new Date(issue.checkedAt).toISOString() }
635        if (!isPrKey(i.key)) return { url: i.url }
636        if (!s || s.state === 'unknown') return { url: i.url, status: s ? 'unavailable' : 'not checked yet' }
637        return { url: i.url, title: s.title, author: s.author, additions: s.additions, deletions: s.deletions, state: s.state, ci: s.ci, hasConflict: s.hasConflict ?? false, review: s.review ?? 'none', checkedAt: new Date(s.checkedAt).toISOString() }
638      }),
639      dismissed: gone,
640      isHidden: hidden,
641      isExpanded: expanded,
642      shownInBand: hidden
643        ? 0
644        : inView.length - ungrouped - landed + (expanded ? ungrouped : Math.min(ungrouped, SHOWN)) + ((await read($, showsLanded)) ? landed : 0),
645      hidesAwaitingReview: hidesReview,
646      groups: groups && groups.map(g => ({ ...g, prs: g.prs.map(urlOf) })),
647      sinceGrouping,
648      isWatching: watching,
649      isNudging: await isNudging($),
650      agentStatus: (st => (st ? { text: st.text, setAt: new Date(st.setAt).toISOString() } : null))(await read($, agentStatus)),
651      lastCheckedAt: (t => (t === undefined ? null : new Date(t).toISOString()))(lastChecked(links.map(i => i.key), { ...known, ...issues })),
652      color,
653    }
654
655    return { result: JSON.stringify(state, null, 2) }
656  })
657
658  on('tool.call', { tool: STATUS_TOOL }, async ($, e) => {
659    const text = (typeof e.text === 'string' ? e.text : '').replace(/\s+/g, ' ').trim().slice(0, MAX_STATUS)
660    const setAt = await $.clock.now()
661    await update($, agentStatus, () => (text ? { text, setAt } : null))
662    return { result: text ? `Status set: ${text}` : 'Status cleared.' }
663  })
664
665  on('tool.call', { tool: GROUP_TOOL }, async ($, e) => {
666    const { groups, links, skipped, repeated } = parseGroups(e.groups, await read($, items))
667    const fresh = await takeLinks($, links)
668    await setGroups($, groups)
669    refreshSoon($, fresh, true)
670    const notes = [
671      skipped.length > 0 && `Skipped (not a PR link, owner/repo#N, or a repo#N for a repo in the band): ${skipped.join(', ')}.`,
672      repeated.length > 0 && `Already in an earlier group, so left there: ${repeated.join(', ')}.`,
673    ].filter(Boolean)
674    const summary =
675      groups.length === 0
676        ? 'Grouping cleared; the GitHub section is newest first again.'
677        : `Grouped the GitHub section: ${groupsSummary(groups)}.`
678
679    return { result: [summary, ...notes].join(' ') }
680  })
681
682  on('tool.call', { tool: EDIT_TOOL }, async ($, e) => {
683    const { groups, links, notes } = editGroups((await read($, prGroups)) ?? [], e.edits, await read($, items))
684    const fresh = await takeLinks($, links)
685    await setGroups($, groups)
686    refreshSoon($, fresh, true)
687    const summary = groups.length === 0 ? 'No groups left; the GitHub section is newest first again.' : `Groups now: ${groupsSummary(groups)}.`
688
689    return { result: [summary, ...notes].join(' ') }
690  })
691
692  on('command.run', { command: 'gh-linear-parse-mod' }, async ($, e) => {
693    const arg = e.args.trim()
694    const [verb, ...words] = arg.split(/\s+/)
695    if (verb === 'color') {
696      const parsed = parseColorArgs(words)
697      if (parsed.kind === 'invalid') {
698        return {
699          text: `Unknown color "${parsed.color}". Use a name (red, cyan, magentaBright), a hex value (#3b2a4a) or a theme key (subtle, claude), optionally followed by "fill".`,
700        }
701      }
702      if (parsed.kind === 'clear') {
703        await update($, bandColor, () => DEFAULT_COLOR)
704        return { text: 'Band back to the default gray border for this session.' }
705      }
706      if (parsed.kind === 'none') {
707        await update($, bandColor, () => null)
708        return { text: 'Band border removed for this session.' }
709      }
710      await update($, bandColor, () => parsed.value)
711      return {
712        text: `Band ${parsed.value.isFill ? 'fill' : 'border'} set to ${parsed.value.color} for this session.`,
713      }
714    }
715    if (verb === 'group') {
716      if (words.join(' ') === 'clear') {
717        await setGroups($, null)
718        return { text: 'Grouping cleared; the GitHub section is newest first again.' }
719      }
720      // Submitted from a timer, since a command's own hook cannot start a turn.
721      const text = groupPrompt(words.join(' '))
722      $.clock.after(1, () => void $.prompt.submit({ text, asUser: true }).catch(() => undefined))
723      return { text: 'Asked Claude to group the PRs in the band.' }
724    }
725    if (arg === 'clear') {
726      await update($, prGroups, () => null)
727      await update($, groupingBase, () => null)
728      await update($, showsLanded, () => false)
729      await update($, items, () => [])
730      await update($, prStatuses, () => ({}))
731      await update($, issueStatuses, () => ({}))
732      await persist($)
733      return { text: 'Cleared the session links.' }
734    }
735    if (verb === 'watch') {
736      const [mode] = words
737      if (mode !== undefined && mode !== 'on' && mode !== 'off') return { text: 'Use "watch on" or "watch off".' }
738      const watching = mode === 'on' ? true : mode === 'off' ? false : !(await read($, isWatching))
739      await update($, isWatching, () => watching)
740      return {
741        text: watching
742          ? 'PR status refreshes every 5 minutes for open and draft PRs in view (this session).'
743          : 'PR status auto-refresh off for this session; mentions, running CI and refresh still update it.',
744      }
745    }
746    if (verb === 'nudge') {
747      const [mode] = words
748      if (mode !== undefined && mode !== 'on' && mode !== 'off') return { text: 'Use "nudge on" or "nudge off".' }
749      const nudging = mode === 'on' ? true : mode === 'off' ? false : !(await isNudging($))
750      await $.store.set('statusNudge', nudging)
751      return {
752        text: nudging
753          ? 'Agents are asked to keep their status current with set_status (all sessions, from the next request).'
754          : 'Agents are no longer asked to keep a status (all sessions); they can still set one.',
755      }
756    }
757    if (arg === 'refresh') {
758      const count = await refreshAll($)
759      return { text: `Refreshing ${count} link${count === 1 ? '' : 's'}.` }
760    }
761    if (verb === 'add') {
762      const found = extractLinks(words.join(' '))
763      if (found.length === 0) return { text: 'No GitHub PR or Linear link found. Use "add <url>".' }
764      const keys = found.map(l => l.key)
765      await update($, dismissed, gone => gone.filter(k => !keys.includes(k)))
766      refreshSoon($, await record($, words.join(' ')), true)
767      if (await read($, isHidden)) {
768        await setHidden($, false)
769        backfillSoon($)
770      }
771      return { text: `Added ${found.map(l => l.url).join(', ')}.` }
772    }
773    if (arg === 'reset') {
774      await update($, dismissed, () => [])
775      await persist($)
776      return { text: 'Dismissed links will show again when they come up.' }
777    }
778    if (arg !== '' && arg !== 'on' && arg !== 'off') {
779      // A bare color name sets the color, as `color <name>` does.
780      const parsed = parseColorArgs([verb ?? '', ...words])
781      if (parsed.kind === 'set') {
782        await update($, bandColor, () => parsed.value)
783        return { text: `Band ${parsed.value.isFill ? 'fill' : 'border'} set to ${parsed.value.color} for this session.` }
784      }
785      return { text: `Unknown option "${arg}". ${HELP}` }
786    }
787    const hidden = arg === 'off' ? true : arg === 'on' ? false : !(await read($, isHidden))
788    await setHidden($, hidden)
789    if (!hidden) backfillSoon($)
790    return { text: hidden ? 'Session links hidden.' : 'Session links shown.' }
791  })
792
793  on('prompt.submit', async ($, e, next) => {
794    refreshSoon($, await record($, e.text))
795    backfillSoon($)
796
797    return next(e)
798  })
799
800  on('turn.complete', async ($, e, next) => {
801    refreshSoon($, await record($, e.answer))
802    backfillSoon($)
803
804    return next(e)
805  })
806
807  on('prompt.compose', async ($, e, next) => {
808    const composed = await next(e)
809    const nudges = [
810      ...(e.tools.includes(STATUS_TOOL) && (await isNudging($)) ? [NUDGE] : []),
811      ...(e.tools.includes(GROUP_TOOL) && (await read($, prGroups)) ? [GROUP_NUDGE] : []),
812    ]
813    if (nudges.length === 0) return composed
814
815    return { sections: [...composed.sections.filter(c => !nudges.some(n => n.id === c.id)), ...nudges] }
816  })
817
818  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
819    if (e.props.hasSurvey || (await read($, isHidden))) return next(e)
820
821    const list = await read($, items)
822    const note = await read($, agentStatus)
823    if (list.length === 0 && !note) return next(e)
824
825    const { Box, Button, Text } = $.ui.resolve(e)
826    const groups = (await read($, prGroups)) ?? []
827    const grouped = new Set(groups.flatMap(g => g.prs))
828    const known = await read($, prStatuses)
829    // 👀 in the header hides the PRs waiting on a review, and shows them again.
830    const hidesReview = await read($, hidesAwaitingReview)
831    const awaiting = list.filter(i => isAwaitingReview(known[i.key])).length
832    const shown = hidesReview ? list.filter(i => !isAwaitingReview(known[i.key])) : list
833    // Grouped PRs always show; Show N more collapses the rest. With groups up, merged and
834    // closed PRs leave them for one landed row, folded until pressed.
835    const isLanded = (i: Item) => groups.length > 0 && isFinished(known[i.key])
836    const landedItems = shown.filter(isLanded)
837    const rest = shown.filter(i => !grouped.has(i.key) && !isLanded(i))
838    const more = rest.length - SHOWN
839    const expanded = more > 0 && (await read($, isExpanded))
840    const style = await read($, bandColor)
841    const visible = rest.slice(0, expanded ? rest.length : SHOWN)
842    const issues = await read($, issueStatuses)
843    const updatedAt = lastChecked(list.map(i => i.key), { ...known, ...issues })
844    const isRefreshing = (await read($, refreshing)) > 0
845    const signInLabel = (await read($, isSigningIn)) ? '🔑 gcloud…' : '🔑 gcloud'
846    const vercelLabel = (await read($, isSigningInVercel)) ? '🔑 vercel…' : '🔑 vercel'
847    const { github: ungrouped, linear } = bandGroups(visible)
848    const landed = {
849      items: landedItems,
850      finished: new Set(list.filter(isLanded).map(i => i.key)),
851      listed: new Set(list.map(i => i.key)),
852      isOpen: await read($, showsLanded),
853    }
854    const githubLayout = githubRows(groups, shown, ungrouped, landed)
855    const github = githubLayout.flatMap(r => (r.kind === 'pr' ? [r.item] : []))
856    const hasPr = github.length > 0
857    const hasIssueSlot = linear.some(i => issues[i.key])
858    const canSweep = list.some(i => isFinished(known[i.key]))
859    const reviewLabel = hidesReview ? `👀 ${awaiting}` : '👀'
860    const canRefresh = list.some(i => isPrKey(i.key)) || Object.keys(issues).some(k => list.some(i => i.key === k))
861    const labels = new Map([...github, ...linear].map(i => [i.key, linkLabel(i.url)]))
862    // Each group is its own table, with its own project width.
863    const width = (group: Item[]) => Math.max(0, ...group.map(i => labels.get(i.key)?.project.length ?? 0))
864    const widths = { github: width(github), linear: width(linear) }
865    const labelText = (i: Item) => {
866      const { project, ref } = labels.get(i.key) ?? linkLabel(i.url)
867      return ref ? `${project.padEnd(isPrKey(i.key) ? widths.github : widths.linear)} | ${ref}` : project
868    }
869    // PR labels padded to one width so the descriptions after them line up.
870    const prWidth = Math.max(0, ...github.map(i => labelText(i).length))
871    const issueWidth = Math.max(0, ...linear.filter(i => issues[i.key]?.name).map(i => labelText(i).length))
872    const addWidth = Math.max(0, ...github.map(i => String(known[i.key]?.additions ?? '').length))
873    const delWidth = Math.max(0, ...github.map(i => String(known[i.key]?.deletions ?? '').length))
874    // Fixed two-cell slots line the emoji up under their labels whatever is in them.
875    const slot = (key: string, text: string, isDim = false) => (
876      <Box key={key} width={2}>
877        <Text dimColor={isDim}>{text || ' '}</Text>
878      </Box>
879    )
880
881    // Cells a row's Button has: the band less its frame and the `x `.
882    const columns = Number.isFinite(e.props.bodyColumns) ? e.props.bodyColumns : Infinity
883    const room = columns - frameColumns(style) - 2
884
885    // The whole row past its `x` is one Button; the description is cut to fit, since a
886    // Button's children wrap rather than truncate.
887    const issueRow = (i: Item) => {
888      const s = issues[i.key]
889      const isDone = isIssueDone(s)
890      const glyph = cell(issueGlyph(s))
891      const slots = hasIssueSlot ? `${glyph} ` : ''
892      const lead = textWidth(slots)
893      const label = fitText(s?.name ? labelText(i).padEnd(issueWidth) : labelText(i), room - lead)
894      const status = s?.name ? fitText(s.name, room - lead - textWidth(label) - 2) : ''
895      return (
896        <Box key={i.key} flexDirection="row" gap={1}>
897          <Button key={`dismiss:${i.key}`} label="x" plain dimColor onPress={() => dismiss($, i.key)} />
898          <Button key={`open:${i.key}`} plain onPress={() => void openLink($, i.url, browser)}>
899            {slots && <Text dimColor={!s?.type}>{slots}</Text>}
900            <Text color={TEXT_COLOR} bold={!isDone} dimColor={isDone}>
901              {label}
902            </Text>
903            {status && <Text dimColor>{`  ${status}`}</Text>}
904          </Button>
905        </Box>
906      )
907    }
908
909    const row = (i: Item) => {
910      if (!isPrKey(i.key)) return issueRow(i)
911      const s = known[i.key]
912      const g = isPrKey(i.key) ? statusGlyphs(s) : undefined
913      const isDone = s?.state === 'merged' || s?.state === 'closed'
914      const short = s?.title ? shortTitle(s.title) : undefined
915      const diff = diffParts(s, addWidth)
916      const slots = hasPr ? `${cell(g?.ci ?? '')} ${cell(g?.rv ?? '')} ` : ''
917      const lead = hasPr ? textWidth(cell(g?.pr ?? '')) + 1 + textWidth(slots) : 0
918      const label = fitText(short || diff ? labelText(i).padEnd(prWidth) : labelText(i), room - lead)
919      const by = s?.author ? `${authorInitials(s.author)} ` : ''
920      const tag = short?.tag ? `${short.tag} · ` : ''
921      const descRoom = room - lead - textWidth(label) - 2
922      // Counts are never cut: they show whole or not at all, and the title takes what is left.
923      const counts = diff ? `${by}${diff.plus} ${diff.minus}` : ''
924      const fitsDiff = diff !== undefined && textWidth(counts) <= descRoom
925      // Deletions padded so the titles after them line up.
926      const gap = fitsDiff ? 2 + delWidth + 1 - diff.minus.length : 0
927      const desc = !short
928        ? ''
929        : fitsDiff
930          ? fitText(tag + short.text, descRoom - textWidth(counts) - gap)
931          : fitText(by + tag + short.text, descRoom)
932      return (
933        <Box key={i.key} flexDirection="row" gap={1}>
934          <Button key={`dismiss:${i.key}`} label="x" plain dimColor onPress={() => dismiss($, i.key)} />
935          <Button key={`open:${i.key}`} plain onPress={() => void openLink($, i.url, browser)}>
936            {hasPr && <Text dimColor={g?.isPending}>{cell(g?.pr ?? '')} </Text>}
937            {slots}
938            <Text color={TEXT_COLOR} bold={!isDone} dimColor={isDone}>
939              {label}
940            </Text>
941            {!fitsDiff && desc && <Text dimColor>{`  ${desc}`}</Text>}
942            {fitsDiff && <Text dimColor>{`  ${by}`}</Text>}
943            {fitsDiff && (
944              <Text color="green" dimColor={isDone}>
945                {diff.plus}
946              </Text>
947            )}
948            {fitsDiff && ' '}
949            {fitsDiff && (
950              <Text color="red" dimColor={isDone}>
951                {diff.minus}
952              </Text>
953            )}
954            {fitsDiff && desc && <Text dimColor>{`${' '.repeat(gap)}${desc}`}</Text>}
955          </Button>
956        </Box>
957      )
958    }
959
960    // A section's header row: its column labels over the status cells, then its name.
961    const section = (key: string, name: string, columns: string[]) => (
962      <Box key={key} flexDirection="row" gap={1}>
963        <Box key="pad" width={1} />
964        {columns.map(c => slot(`label-${c.toLowerCase()}`, c, true))}
965        <Text dimColor>{name}</Text>
966      </Box>
967    )
968
969    // A group's label is a dim divider and its text a dim italic line; a done group gets a ✓.
970    const githubRow = (r: (typeof githubLayout)[number]) => {
971      if (r.kind === 'pr') return row(r.item)
972      if (r.kind === 'landed') {
973        return (
974          <Box key="group-landed" flexDirection="row" gap={1}>
975            <Box key="pad" width={1} />
976            <Button
977              key="landed"
978              label={`── ${r.isOpen ? '▾' : '▸'} landed (${r.count}) ──`}
979              plain
980              dimColor
981              onPress={() => update($, showsLanded, v => !v)}
982            />
983          </Box>
984        )
985      }
986      // A step is a to-do row; pressing it ticks or unticks it.
987      if (r.kind === 'step') {
988        return (
989          <Box key={`group-step:${r.group}`} flexDirection="row" gap={1}>
990            <Box key="pad" width={1} />
991            <Button
992              key={`step:${r.group}`}
993              label={fitText(`${r.isDone ? '☑' : '☐'} ${r.text}`, room)}
994              plain
995              dimColor={r.isDone}
996              onPress={() => toggleStep($, r.group, r.text)}
997            />
998          </Box>
999        )
1000      }
1001      const key = r.group === undefined ? 'group-other' : `group-${r.kind}:${r.group}`
1002      const done = r.isDone ? ' ✓' : ''
1003      const text = r.kind === 'label' ? `── ${r.text}${done} ──` : `   ${r.text}${done}`
1004      return (
1005        <Box key={key} flexDirection="row" gap={1}>
1006          <Box key="pad" width={1} />
1007          <Text dimColor italic={r.kind === 'text'}>
1008            {fitText(text, room)}
1009          </Text>
1010        </Box>
1011      )
1012    }
1013
1014    const noteTime = note ? `  ${clockTime(note.setAt)}` : ''
1015    const statusSection = note && [
1016      section('status-header', 'Status', []),
1017      <Box key="status" flexDirection="row" gap={1}>
1018        <Button key="dismiss:status" label="x" plain dimColor onPress={() => update($, agentStatus, () => null)} />
1019        <Text>
1020          <Text italic>{fitText(note.text, room - textWidth(noteTime))}</Text>
1021          <Text dimColor>{noteTime}</Text>
1022        </Text>
1023      </Box>,
1024    ]
1025    const title = `Session links (${list.length})`
1026    const expandLabel = expanded ? 'Show less' : `Show ${more} more`
1027    // The time goes first when the header would not fit on one line.
1028    const actions = [signInLabel, vercelLabel, canRefresh ? (isRefreshing ? 'Refreshing…' : 'Refresh') : '', awaiting > 0 ? reviewLabel : '', canSweep ? '🧹' : '', more > 0 ? expandLabel : '', 'Hide']
1029    const headerLead = 2
1030    const headerNeeds = (withTime: boolean) =>
1031      headerLead + textWidth(title) + (withTime && updatedAt !== undefined ? 3 + textWidth(`updated ${clockTime(updatedAt)}`) : 0) +
1032      actions.filter(Boolean).reduce((n, a) => n + 1 + textWidth(a), 1) + APP_GAP + 1
1033    const showsUpdated = updatedAt !== undefined && headerNeeds(true) <= room + 2
1034    if (list.length === 0) {
1035      return (
1036        <Box flexDirection="column" {...frame(style)}>
1037          {statusSection}
1038        </Box>
1039      )
1040    }
1041
1042    return (
1043      <Box flexDirection="column" {...frame(style)}>
1044        <Box flexDirection="row" gap={1}>
1045          <Box key="pad" width={1} />
1046          <Text dimColor>{title}</Text>
1047          {showsUpdated && (
1048            <Box key="updated">
1049              <Text dimColor>· updated {clockTime(updatedAt)}</Text>
1050            </Box>
1051          )}
1052          <Box key="app-gap" width={APP_GAP} />
1053          <Button key="gcloud-login" label={signInLabel} plain dimColor onPress={() => void gcloudLogin($)} />
1054          <Button key="vercel-login" label={vercelLabel} plain dimColor onPress={() => void vercelLogin($)} />
1055          <Box key="spacer" flexGrow={1} />
1056          {canRefresh && (
1057            <Button
1058              key="refresh"
1059              label={isRefreshing ? 'Refreshing…' : 'Refresh'}
1060              plain
1061              dimColor
1062              onPress={() => void refreshAll($)}
1063            />
1064          )}
1065          {awaiting > 0 && (
1066            <Button
1067              key="awaiting-review"
1068              label={reviewLabel}
1069              plain
1070              dimColor={hidesReview}
1071              onPress={() => update($, hidesAwaitingReview, v => !v)}
1072            />
1073          )}
1074          {canSweep && <Button key="sweep" label="🧹" plain onPress={() => sweep($)} />}
1075          {more > 0 && (
1076            <Button
1077              key="expand"
1078              label={expandLabel}
1079              plain
1080              dimColor
1081              onPress={() => update($, isExpanded, v => !v)}
1082            />
1083          )}
1084          <Button key="hide" label="Hide" plain dimColor onPress={() => setHidden($, true)} />
1085        </Box>
1086        {statusSection}
1087        {githubLayout.length > 0 && section('github-header', 'GitHub', ['PR', 'CI', 'Rv'])}
1088        {githubLayout.map(githubRow)}
1089        {linear.length > 0 && section('linear-header', 'Linear', hasIssueSlot ? ['St'] : [])}
1090        {linear.map(row)}
1091      </Box>
1092    )
1093  })
1094}
1095
hooks/browser.ts 66 lines
1import type { EngineInterface } from 'claude-code'
2
3type $ = EngineInterface
4
5// Chromium browsers share the AppleScript dictionary that lists and selects tabs.
6const CHROMIUM = ['Brave Browser', 'Google Chrome', 'Google Chrome Canary', 'Microsoft Edge', 'Chromium', 'Vivaldi']
7export const canReuseTabs = (browser: string) => CHROMIUM.includes(browser)
8
9// A tab already on `url` (or a page under it, such as a PR's /files) is brought to the front.
10export const FIND_TAB = `function run(argv) {
11  const [name, url] = argv
12  const app = Application(name)
13  if (!app.running()) return 'missing'
14  const want = url.toLowerCase()
15  for (const w of app.windows()) {
16    const urls = w.tabs.url()
17    for (let i = 0; i < urls.length; i++) {
18      const t = (urls[i] || '').toLowerCase()
19      if (t === want || ['/', '?', '#'].some(c => t.startsWith(want + c))) {
20        w.activeTabIndex = i + 1
21        w.index = 1
22        app.activate()
23        return 'found'
24      }
25    }
26  }
27  return 'missing'
28}`
29
30export type Platform = 'mac' | 'linux' | 'windows'
31
32let platform: Platform | undefined
33
34async function detectPlatform($: $): Promise<Platform> {
35  if (platform) return platform
36  const ran = await $.process.run(['uname', '-s'], { timeoutMs: 5_000 }).catch(() => null)
37  const name = ran?.exitCode === 0 ? ran.stdout.trim() : ''
38  platform = name === 'Darwin' ? 'mac' : name ? 'linux' : 'windows'
39  return platform
40}
41
42export function defaultOpen(p: Platform, url: string): string[] {
43  if (p === 'mac') return ['open', url]
44  if (p === 'linux') return ['xdg-open', url]
45  return ['cmd', '/c', 'start', '""', url]
46}
47
48async function ok($: $, argv: string[]) {
49  return (await $.process.run(argv, { timeoutMs: 10_000 }).catch(() => null))?.exitCode === 0
50}
51
52// `browser` empty opens the system default. Named, on macOS, it opens there, first
53// switching to a tab already on the link when the browser is a Chromium one.
54export async function openLink($: $, url: string, browser: string) {
55  const p = await detectPlatform($)
56  if (browser && p === 'mac') {
57    if (canReuseTabs(browser)) {
58      const found = await $.process.run(['osascript', '-l', 'JavaScript', '-e', FIND_TAB, browser, url], { timeoutMs: 10_000 }).catch(() => null)
59      if (found?.exitCode === 0 && found.stdout.trim() === 'found') return
60    }
61    if (await ok($, ['open', '-a', browser, url])) return
62    $.ui.toast(`Could not open ${browser}; used the default browser.`)
63  }
64  await ok($, defaultOpen(p, url))
65}
66
hooks/parse.ts 623 lines
1import type { BandColor, CI, GroupEdit, IssueStatus, IssueType, Item, PrGroup, PrState, PrStatus, Review } from '../types'
2
3export type Link = Item
4
5const LINK = /https?:\/\/(?:www\.)?(?:github\.com|linear\.app)\/[^\s<>"'`()[\]{}\\]+/gi
6const TRAILING = /[.,;:!?*_]+$/
7
8function githubLink(parts: string[]): Link | undefined {
9  const [owner, repo, kind, number] = parts
10  if (!owner || !repo || kind !== 'pull' || !number || !/^\d+$/.test(number)) return undefined
11
12  return {
13    key: `github:${owner}/${repo}#${number}`.toLowerCase(),
14    url: `https://github.com/${owner}/${repo}/pull/${number}`,
15  }
16}
17
18function linearLink(parts: string[]): Link | undefined {
19  const [workspace, kind, id] = parts
20  if (!workspace || !kind) return undefined
21
22  const url = `https://linear.app/${parts.join('/')}`
23  if (kind === 'issue' && id && /^[A-Za-z]+-\d+$/.test(id)) {
24    return { key: `linear:${workspace}/issue/${id}`.toLowerCase(), url }
25  }
26
27  return { key: url.toLowerCase(), url }
28}
29
30export function parseLink(raw: string): Link | undefined {
31  const m = raw.replace(TRAILING, '').match(/^https?:\/\/(?:www\.)?(github\.com|linear\.app)\/([^?#]*)/i)
32  if (!m) return undefined
33  const parts = (m[2] ?? '').split('/').filter(Boolean)
34
35  return m[1]?.toLowerCase() === 'github.com' ? githubLink(parts) : linearLink(parts)
36}
37
38// Only GitHub pull requests and Linear pages count. A PR link collapses to
39// its bare URL (no /files, query or fragment); a Linear issue keeps the URL as
40// written, slug included, and the same issue with or without a slug shows once.
41export function extractLinks(text: string): Link[] {
42  const seen = new Set<string>()
43  const links: Link[] = []
44
45  for (const m of text.matchAll(LINK)) {
46    const link = parseLink(m[0])
47    if (!link || seen.has(link.key)) continue
48    seen.add(link.key)
49    links.push(link)
50  }
51
52  return links
53}
54
55// Past `max` the oldest dismissals fall off, so the stored list stays small.
56export function addKey(keys: readonly string[], key: string, max: number): string[] {
57  return [...keys.filter(k => k !== key), key].slice(-max)
58}
59
60const THEME_KEYS = [
61  'text', 'inverseText', 'inactive', 'subtle', 'suggestion', 'remember', 'success', 'error',
62  'warning', 'merged', 'claude', 'permission', 'planMode', 'autoAccept', 'promptBorder',
63  'bashBorder', 'ide', 'diffAdded', 'diffRemoved', 'diffAddedDimmed', 'diffRemovedDimmed',
64  'diffAddedWord', 'diffRemovedWord',
65]
66const NAMED = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'grey']
67
68export type ColorArg =
69  | { kind: 'clear' }
70  | { kind: 'none' }
71  | { kind: 'set'; value: BandColor }
72  | { kind: 'invalid'; color: string }
73
74// `color` alone or `color reset` goes back to the default, `color none` drops the
75// border; `color <c> [fill]` sets. A color is a
76// terminal name (`red`, `cyanBright`), a hex value or a theme key.
77export function parseColorArgs(words: readonly string[]): ColorArg {
78  const [color, mode, ...rest] = words
79  if (!color || color === 'reset') return { kind: 'clear' }
80  if (color === 'none') return { kind: 'none' }
81  if ((mode !== undefined && mode !== 'fill') || rest.length > 0) return { kind: 'invalid', color: words.join(' ') }
82
83  const named = NAMED.find(n => n === color.toLowerCase() || `${n}bright` === color.toLowerCase())
84  const theme = THEME_KEYS.find(k => k.toLowerCase() === color.toLowerCase())
85  const resolved =
86    named ? (color.toLowerCase().endsWith('bright') ? `${named}Bright` : named)
87      : theme ?? (/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(color) ? color.toLowerCase() : undefined)
88  if (!resolved) return { kind: 'invalid', color }
89
90  return { kind: 'set', value: { color: resolved, isFill: mode === 'fill' } }
91}
92
93// Newest first: links in `found` go to the front in text order, and a link seen
94// again moves up rather than repeating. Dismissed links never come back.
95export function mergeLinks(
96  list: readonly Link[],
97  found: readonly Link[],
98  max: number,
99  dismissed: readonly string[] = [],
100): Link[] {
101  const fresh = found.filter(l => !dismissed.includes(l.key))
102  const keys = new Set(fresh.map(l => l.key))
103
104  return [...fresh, ...list.filter(l => !keys.has(l.key))].slice(0, max)
105}
106
107const REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g
108
109// Messages oldest first in, links newest first out, as if each had been seen live.
110// Reminders the engine injects into user messages are not part of the discussion.
111export function linksFromHistory(texts: readonly string[], max: number, dismissed: readonly string[] = []): Link[] {
112  return texts.reduce<Link[]>(
113    (list, text) => mergeLinks(list, extractLinks(text.replace(REMINDER, '')), max, dismissed),
114    [],
115  )
116}
117
118export const isPrKey = (key: string) => key.startsWith('github:')
119
120export const isIssueKey = (key: string) => /^linear:[^/]+\/issue\/[a-z]+-\d+$/.test(key)
121
122// `linear:acme/issue/eng-12` is `ENG-12`.
123export const issueId = (key: string) => key.slice(key.lastIndexOf('/') + 1).toUpperCase()
124
125export function prRef(url: string): { repo: string; number: number } | undefined {
126  const m = url.match(/^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)$/)
127
128  return m?.[1] && m[2] ? { repo: m[1], number: Number(m[2]) } : undefined
129}
130
131type Check = {
132  __typename?: string
133  status?: string | null
134  conclusion?: string | null
135  state?: string | null
136  name?: string | null
137  context?: string | null
138  workflowName?: string | null
139  startedAt?: string | null
140}
141
142// The newest run of each check: a rerun or a newer push replaces the run it cancelled.
143function latestRuns(rollup: readonly Check[]): Check[] {
144  const latest = new Map<string, Check>()
145  rollup.forEach((c, i) => {
146    const name = c.name ?? c.context
147    const key = name ? `${c.workflowName ?? ''}/${name}` : `#${i}`
148    const seen = latest.get(key)
149    if (!seen || (c.startedAt ?? '') >= (seen.startedAt ?? '')) latest.set(key, c)
150  })
151
152  return [...latest.values()]
153}
154
155export function ciSummary(all: readonly Check[] | null | undefined): CI {
156  if (!all || all.length === 0) return 'none'
157  const rollup = latestRuns(all)
158  const bad = ['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE']
159  if (rollup.some(c => bad.includes(c.conclusion ?? '') || bad.includes(c.state ?? ''))) return 'fail'
160  const isRunning = (c: Check) =>
161    c.__typename === 'StatusContext' || (c.__typename === undefined && c.state != null)
162      ? c.state === 'PENDING' || c.state === 'EXPECTED'
163      : c.status !== 'COMPLETED'
164  if (rollup.some(isRunning)) return 'running'
165
166  return 'pass'
167}
168
169export const PR_FIELDS = 'title,author,state,isDraft,reviewDecision,statusCheckRollup,reviewRequests,latestReviews,additions,deletions,mergeable'
170
171export type Fetched = {
172  state: PrState
173  ci: CI
174  review?: Review
175  title?: string
176  author?: string
177  additions?: number
178  deletions?: number
179  hasConflict?: boolean
180}
181
182// Review apps whose comments are not a person asking for a change.
183const BOTS = new Set(['claude', 'github-advanced-security', 'copilot-pull-request-reviewer', 'coderabbitai'])
184const isBot = (login: string) => BOTS.has(login.toLowerCase()) || login.endsWith('[bot]')
185
186export function parsePrJson(stdout: string): Fetched | undefined {
187  let pr: {
188    title?: string
189    state?: string
190    isDraft?: boolean
191    reviewDecision?: string | null
192    statusCheckRollup?: Check[] | null
193    author?: { login?: string } | null
194    reviewRequests?: unknown[] | null
195    latestReviews?: { author?: { login?: string } | null; state?: string }[] | null
196    additions?: number
197    deletions?: number
198    mergeable?: string
199  }
200  try {
201    pr = JSON.parse(stdout)
202  } catch {
203    return undefined
204  }
205  if (!pr || typeof pr.state !== 'string') return undefined
206
207  const state: PrState =
208    pr.state === 'MERGED' ? 'merged' : pr.state === 'CLOSED' ? 'closed' : pr.isDraft ? 'draft' : 'open'
209  const isLive = state === 'open' || state === 'draft'
210  const others = (pr.latestReviews ?? []).filter(r => {
211    const login = r.author?.login ?? ''
212    return login !== pr.author?.login && !isBot(login)
213  })
214  // An open or draft PR nobody has been asked to review, and nobody has reviewed.
215  const isUnassigned = isLive && (pr.reviewRequests?.length ?? 0) === 0 && others.length === 0
216  // A person other than the author left a comment review, and nobody has approved.
217  const isCommented = isLive && others.some(r => r.state === 'COMMENTED') && !others.some(r => r.state === 'APPROVED')
218  // GitHub leaves reviewDecision empty when the base branch requires no review, as on a stacked PR.
219  const review: Review | undefined =
220    pr.reviewDecision === 'APPROVED' ? 'approved'
221      : pr.reviewDecision === 'CHANGES_REQUESTED' ? 'changes'
222        : isCommented ? 'commented'
223          : isUnassigned ? 'unassigned'
224            : pr.reviewDecision === 'REVIEW_REQUIRED' || (isLive && (pr.reviewRequests?.length ?? 0) > 0) ? 'pending'
225              : undefined
226
227  const title = typeof pr.title === 'string' ? pr.title : undefined
228  const author = pr.author?.login || undefined
229  const hasDiff = typeof pr.additions === 'number' && typeof pr.deletions === 'number'
230  // GitHub works mergeability out lazily: UNKNOWN until then, so only CONFLICTING counts.
231  const hasConflict = isLive && pr.mergeable === 'CONFLICTING'
232
233  return {
234    state,
235    ci: ciSummary(pr.statusCheckRollup),
236    ...(review ? { review } : {}),
237    ...(title ? { title } : {}),
238    ...(author ? { author } : {}),
239    ...(hasDiff ? { additions: pr.additions, deletions: pr.deletions } : {}),
240    ...(hasConflict ? { hasConflict } : {}),
241  }
242}
243
244// A failed check keeps what was known; `ciSince` marks when CI started running so
245// polling can give up on a check that never finishes.
246export function nextStatus(prev: PrStatus | undefined, fetched: Fetched | undefined, now: number): PrStatus {
247  if (!fetched) return prev ? { ...prev, checkedAt: now } : { state: 'unknown', ci: 'none', checkedAt: now }
248  const ciSince = fetched.ci === 'running' ? (prev?.ci === 'running' ? prev.ciSince ?? now : now) : undefined
249
250  return { ...fetched, checkedAt: now, ...(ciSince !== undefined ? { ciSince } : {}) }
251}
252
253export const isStale = (s: PrStatus | IssueStatus | undefined, now: number, ms: number) => !s || now - s.checkedAt > ms
254
255export const shouldPoll = (s: PrStatus | undefined, now: number, windowMs: number) =>
256  s?.ci === 'running' && now - (s.ciSince ?? s.checkedAt) < windowMs
257
258const PR_GLYPH: Record<PrState, string> = { open: '🟢', draft: '📝', merged: '🟣', closed: '⚫' }
259const CI_GLYPH: Record<CI, string> = { pass: '✅', fail: '❌', running: '⏳', none: '' }
260const CONFLICT_GLYPH = '💥'
261const LANDED_GLYPH = '🌒'
262const RV_GLYPH: Record<Review, string> = { approved: '🚀', pending: '👀', changes: '✋', unassigned: '🦯', commented: '💬' }
263
264export type Glyphs = { pr: string; ci: string; rv: string; isPending: boolean }
265
266// A PR that shows 👀: its review is requested and not given yet.
267export const isAwaitingReview = (s: PrStatus | undefined) => statusGlyphs(s).rv === RV_GLYPH.pending
268
269export function statusGlyphs(s: PrStatus | undefined): Glyphs {
270  if (!s) return { pr: '…', ci: '', rv: '', isPending: true }
271  if (s.state === 'unknown') return { pr: '?', ci: '', rv: '', isPending: true }
272
273  // A draft is not asking for review yet, so no reviewer is not news.
274  const isMoot = s.state === 'draft' && s.review === 'unassigned'
275  const rv = s.state === 'merged' ? LANDED_GLYPH : !s.review || isMoot ? '' : RV_GLYPH[s.review]
276
277  // A conflict blocks the merge whatever CI says, so it takes the CI cell.
278  const ci = s.hasConflict ? CONFLICT_GLYPH : CI_GLYPH[s.ci]
279
280  return { pr: PR_GLYPH[s.state], ci, rv, isPending: false }
281}
282
283// What the 5-minute watch re-checks: open and draft PRs, and ones not read yet. Merged
284// and closed PRs do not change, and a PR on the 90-second CI poll is covered there.
285export function watchKeys(
286  keys: readonly string[],
287  known: Readonly<Record<string, PrStatus>>,
288  now: number,
289  ciWindowMs: number,
290): string[] {
291  return keys.filter(k => {
292    if (!isPrKey(k)) return false
293    const s = known[k]
294    if (!s || s.state === 'unknown') return true
295    return (s.state === 'open' || s.state === 'draft') && !shouldPoll(s, now, ciWindowMs)
296  })
297}
298
299export type Label = { project: string; ref: string }
300
301// Dashes become spaces, except inside numbers such as dates.
302const words = (slug: string) => slug.replace(/-[0-9a-f]{8,}$/i, '').replace(/(?<!\d)-|-(?!\d)/g, ' ')
303
304// GitHub PRs read `repo | #N`; Linear issues `ENG-1 | slug words`, other Linear pages
305// `kind | name`, then the tab when the link names one (`· overview`), so two tabs of one
306// project read apart.
307export function linkLabel(url: string): Label {
308  const pr = prRef(url)
309  if (pr) return { project: pr.repo.split('/')[1] ?? pr.repo, ref: `#${pr.number}` }
310
311  const [, kind = '', id = '', ...rest] = url.replace(/^https?:\/\/[^/]+\//, '').split('/')
312  if (kind === 'issue' && id) return { project: id.toUpperCase(), ref: words(rest[0] ?? '') }
313  const tab = rest.filter(Boolean).join('/')
314  return { project: kind, ref: tab ? `${words(id)} · ${tab}` : words(id) }
315}
316
317// PRs above Linear links, each group keeping its order.
318export function bandGroups(list: readonly Item[]): { github: Item[]; linear: Item[] } {
319  return { github: list.filter(i => isPrKey(i.key)), linear: list.filter(i => !isPrKey(i.key)) }
320}
321
322// When the band's PRs were last read from GitHub, failed reads included.
323export function lastChecked(keys: readonly string[], known: Readonly<Record<string, { checkedAt: number }>>): number | undefined {
324  const times = keys.map(k => known[k]?.checkedAt).filter((t): t is number => t !== undefined)
325  return times.length > 0 ? Math.max(...times) : undefined
326}
327
328export const clockTime = (ms: number) =>
329  new Date(ms).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit', second: '2-digit' })
330
331export type ShortTitle = { tag?: string; text: string }
332
333const COMMIT_TYPES = new Set(['feat', 'fix', 'chore', 'build', 'perf', 'refactor', 'docs', 'test', 'ci', 'style', 'revert'])
334const TICKET = /\b[A-Z]{2,}-\d+\b|#\d+|\bT\d+[a-z]?\b/
335const CLAUSE = / (?:when|until|once|while|so|unless) |,? - |, (?:and|or|but|so|then) /
336
337// A PR title cut to what it does: `feat(search): x when y (T2)` reads `search` and `x`.
338export function shortTitle(title: string): ShortTitle {
339  let text = title.trim().replace(/^(?:\[[^\]]*\]\s*)+/, '').replace(/^[A-Z]{2,}-\d+:\s*/, '')
340  let tag: string | undefined
341
342  const scoped = text.match(/^(\w+)\(([^)]+)\)!?:?\s+/)
343  const bare = text.match(/^([a-z][\w-]*):\s+/)
344  if (scoped) {
345    tag = scoped[2]
346    text = text.slice(scoped[0].length)
347  } else if (bare?.[1]) {
348    if (!COMMIT_TYPES.has(bare[1])) tag = bare[1]
349    text = text.slice(bare[0].length)
350  }
351
352  text = text.replace(/\s*\(([^)]*)\)$/, (m, inner: string) => (TICKET.test(inner) ? '' : m))
353  const cut = text.match(CLAUSE)
354  if (cut?.index !== undefined && text.slice(0, cut.index).split(' ').length >= 2) text = text.slice(0, cut.index)
355
356  return { ...(tag ? { tag } : {}), text: text.trim() }
357}
358
359const WIDE = /\p{Extended_Pictographic}/u
360
361// Terminal cells: an emoji takes two, anything else one (variation selectors none).
362export const textWidth = (text: string) =>
363  [...text].reduce((n, ch) => n + (ch === '️' ? 0 : WIDE.test(ch) ? 2 : 1), 0)
364
365// A status glyph in a two-cell slot.
366export const cell = (glyph: string) => glyph + ' '.repeat(Math.max(0, 2 - textWidth(glyph)))
367
368// `text` cut to `room` cells, an ellipsis marking the cut.
369export function fitText(text: string, room: number): string {
370  if (textWidth(text) <= room) return text
371  if (room <= 0) return ''
372  let out = ''
373  for (const ch of text) {
374    if (textWidth(out + ch) > room - 1) break
375    out += ch
376  }
377  return `${out.trimEnd()}…`
378}
379
380// The PR author as two letters of their login, enough to tell the team apart.
381export const authorInitials = (login: string) => login.slice(0, 2).toLowerCase().padEnd(2)
382
383// A PR's changed lines as `+12 -3`, the additions padded to `width` digits so the
384// deletions line up down the band.
385export function diffParts(s: PrStatus | undefined, width: number): { plus: string; minus: string } | undefined {
386  if (s?.additions === undefined || s.deletions === undefined) return undefined
387  return { plus: `+${s.additions}`.padStart(width + 1), minus: `-${s.deletions}` }
388}
389
390const ISSUE_TYPES = new Set<string>(['triage', 'backlog', 'unstarted', 'started', 'completed', 'canceled', 'duplicate'])
391
392// A Linear `get_issue` result: its status name and type, whether the server sends the
393// status as a name or as `{ name, type }`.
394export function parseIssueResult(r: { content: readonly { type: string; text?: string }[]; isError: boolean }): Omit<IssueStatus, 'checkedAt'> | undefined {
395  if (r.isError) return undefined
396  let issue: { status?: unknown; statusType?: unknown; state?: unknown }
397  try {
398    issue = JSON.parse(r.content.find(c => c.type === 'text')?.text ?? '')
399  } catch {
400    return undefined
401  }
402  if (!issue || typeof issue !== 'object') return undefined
403  const raw = issue.status ?? issue.state
404  const obj = raw && typeof raw === 'object' ? (raw as { name?: unknown; type?: unknown }) : undefined
405  const name = typeof raw === 'string' ? raw : typeof obj?.name === 'string' ? obj.name : undefined
406  const kind = issue.statusType ?? obj?.type
407  const type = typeof kind === 'string' && ISSUE_TYPES.has(kind) ? (kind as IssueType) : undefined
408  if (!name && !type) return undefined
409
410  return { ...(name ? { name } : {}), ...(type ? { type } : {}) }
411}
412
413const ISSUE_GLYPH: Record<IssueType, string> = {
414  triage: '📥',
415  backlog: '💤',
416  unstarted: '⚪',
417  started: '🟡',
418  completed: '🟣',
419  canceled: '⚫',
420  duplicate: '⚫',
421}
422
423export const issueGlyph = (s: IssueStatus | undefined) => (!s ? '' : s.type ? ISSUE_GLYPH[s.type] : s.name ? '•' : '?')
424
425export const isIssueDone = (s: IssueStatus | undefined) =>
426  s?.type === 'completed' || s?.type === 'canceled' || s?.type === 'duplicate'
427
428// Linear issues the 5-minute watch re-checks: all but the finished ones.
429export const issueWatchKeys = (keys: readonly string[], known: Readonly<Record<string, IssueStatus>>) =>
430  keys.filter(k => isIssueKey(k) && !isIssueDone(known[k]))
431
432const MAX_GROUPS = 20
433const MAX_LABEL = 60
434const MAX_GROUP_TEXT = 200
435const MAX_STEP = 120
436
437const clean = (v: unknown, max: number) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '')
438
439// A PR link, `owner/repo#N`, `#N` naming exactly one PR already in the band, or `repo#N`
440// for a PR in the band or, when the band holds one owner's `repo`, another PR there.
441export function resolvePr(ref: string, band: readonly Item[]): Link | undefined {
442  const link = parseLink(ref)
443  if (link) return isPrKey(link.key) ? link : undefined
444  const full = ref.match(/^([\w.-]+)\/([\w.-]+)#(\d+)$/)
445  if (full) return githubLink([full[1]!, full[2]!, 'pull', full[3]!])
446  const short = ref.match(/^([\w.-]+)?#(\d+)$/)
447  if (!short) return undefined
448  const [, repo, n] = short
449  const matches = band.filter(i => {
450    const name = i.key.split('/')[1]
451    return isPrKey(i.key) && (repo ? name === `${repo.toLowerCase()}#${n}` : name?.endsWith(`#${n}`))
452  })
453  if (matches.length === 1) return matches[0]
454  if (!repo || matches.length > 0) return undefined
455  const owners = new Set(
456    band.flatMap(i => {
457      const [, owner, name] = i.url.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\//) ?? []
458      return owner && name?.toLowerCase() === repo.toLowerCase() ? [`${owner}/${name}`] : []
459    }),
460  )
461  const [only] = owners
462  return owners.size === 1 ? githubLink([...only!.split('/'), 'pull', n!]) : undefined
463}
464
465export type ParsedGroups = { groups: PrGroup[]; links: Link[]; skipped: string[]; repeated: string[] }
466
467// One group from tool input, its PRs resolved against the band and the PRs taken so far.
468// A step is a row of its own, so it keeps no label, text or PRs.
469function parseGroup(g: unknown, band: readonly Item[], found: Omit<ParsedGroups, 'groups'>): PrGroup | undefined {
470  if (typeof g !== 'object' || g === null) return undefined
471  const { label, text, prs, step, done } = g as { label?: unknown; text?: unknown; prs?: unknown; step?: unknown; done?: unknown }
472  const s = clean(step, MAX_STEP)
473  if (s) return { step: s, ...(done === true && { isDone: true }), prs: [] }
474  const keys: string[] = []
475  for (const ref of Array.isArray(prs) ? prs : []) {
476    const raw = clean(ref, 300)
477    const link = raw ? resolvePr(raw, [...band, ...found.links]) : undefined
478    if (!link) {
479      if (raw) found.skipped.push(raw)
480      continue
481    }
482    if (found.links.some(l => l.key === link.key)) {
483      found.repeated.push(raw)
484      continue
485    }
486    keys.push(link.key)
487    found.links.push(link)
488  }
489  const l = clean(label, MAX_LABEL)
490  const t = clean(text, MAX_GROUP_TEXT)
491  return l || t || keys.length > 0 ? { ...(l && { label: l }), ...(t && { text: t }), prs: keys } : undefined
492}
493
494// The group_prs input as groups of PR keys: unreadable refs are skipped and a PR
495// named twice stays in its first group.
496export function parseGroups(input: unknown, band: readonly Item[]): ParsedGroups {
497  const found = { links: [] as Link[], skipped: [] as string[], repeated: [] as string[] }
498  const groups = (Array.isArray(input) ? input.slice(0, MAX_GROUPS) : []).flatMap(g => parseGroup(g, band, found) ?? [])
499  return { groups, ...found }
500}
501
502const isEmpty = (g: PrGroup) => !g.label && !g.text && !g.step && g.prs.length === 0
503
504export type EditedGroups = { groups: PrGroup[]; links: Link[]; notes: string[] }
505
506// Applies edit_groups' edits in order. Each edit sees the groups the ones before it left,
507// and a group left empty goes once they are all done.
508export function editGroups(start: readonly PrGroup[], edits: unknown, band: readonly Item[]): EditedGroups {
509  let groups = start.map(g => ({ ...g, prs: [...g.prs] }))
510  const links: Link[] = []
511  const notes: string[] = []
512  const known = () => [...band, ...links]
513  const at = (n: unknown, max: number) => (typeof n === 'number' && Number.isInteger(n) ? Math.max(0, Math.min(n, max)) : max)
514  const target = (e: GroupEdit, n: number) => {
515    const g = typeof e.group === 'number' ? groups[e.group] : undefined
516    if (!g) notes.push(`Edit ${n + 1}: no group ${String(e.group)} (groups run from 0 to ${groups.length - 1}).`)
517    return g
518  }
519  const take = (key: string) => groups.forEach(g => (g.prs = g.prs.filter(k => k !== key)))
520
521  ;(Array.isArray(edits) ? edits : []).forEach((raw, n) => {
522    const e = (typeof raw === 'object' && raw !== null ? raw : {}) as GroupEdit
523    if (e.op === 'put' || e.op === 'remove') {
524      const ref = clean(e.pr, 300)
525      const link = ref ? resolvePr(ref, known()) : undefined
526      if (!link) return notes.push(`Edit ${n + 1}: "${ref}" is not a PR link, owner/repo#N, or a repo#N for a repo in the band.`)
527      if (e.op === 'remove') return take(link.key)
528      const g = target(e, n)
529      if (!g) return
530      if (g.step) return notes.push(`Edit ${n + 1}: group ${e.group} is a step, which holds no PRs.`)
531      take(link.key)
532      g.prs.splice(at(e.at, g.prs.length), 0, link.key)
533      if (!links.some(l => l.key === link.key)) links.push(link)
534      return
535    }
536    if (e.op === 'set') {
537      const g = target(e, n)
538      if (!g) return
539      if (g.step) {
540        if (e.label !== undefined || e.text !== undefined) notes.push(`Edit ${n + 1}: group ${e.group} is a step; set its step or done.`)
541        const s = clean(e.step, MAX_STEP)
542        if (s) g.step = s
543        if (e.done === true) g.isDone = true
544        if (e.done === false) delete g.isDone
545        return
546      }
547      if (e.step !== undefined || e.done !== undefined) notes.push(`Edit ${n + 1}: group ${e.group} is not a step; set its label or text.`)
548      for (const [field, max] of [['label', MAX_LABEL], ['text', MAX_GROUP_TEXT]] as const) {
549        if (typeof e[field] !== 'string') continue
550        const v = clean(e[field], max)
551        if (v) g[field] = v
552        else delete g[field]
553      }
554      return
555    }
556    if (e.op === 'insert') {
557      if (groups.length >= MAX_GROUPS) return notes.push(`Edit ${n + 1}: there are already ${MAX_GROUPS} groups.`)
558      const found = { links: [] as Link[], skipped: [] as string[], repeated: [] as string[] }
559      const g = parseGroup(e, known(), found)
560      if (found.skipped.length > 0) notes.push(`Edit ${n + 1}: skipped ${found.skipped.join(', ')} (not a PR link, owner/repo#N, or a repo#N for a repo in the band).`)
561      if (!g) return notes.push(`Edit ${n + 1}: an insert needs a label, text, PRs or a step.`)
562      g.prs.forEach(take)
563      groups.splice(at(e.at, groups.length), 0, g)
564      found.links.forEach(l => links.some(k => k.key === l.key) || links.push(l))
565      return
566    }
567    if (e.op === 'delete') {
568      if (target(e, n)) groups.splice(e.group!, 1)
569      return
570    }
571    notes.push(`Edit ${n + 1}: unknown op "${String(e.op)}"; use put, remove, set, insert or delete.`)
572  })
573  groups = groups.filter(g => !isEmpty(g))
574  return { groups, links, notes }
575}
576
577// Drops PRs from the groups, and any group left with nothing in it.
578export const withoutPrs = (groups: readonly PrGroup[], keys: readonly string[]): PrGroup[] =>
579  groups.map(g => ({ ...g, prs: g.prs.filter(k => !keys.includes(k)) })).filter(g => !isEmpty(g))
580
581// Drops the groups whose PRs all went, and those PRs from the rest.
582export const withoutDone = (groups: readonly PrGroup[], keys: readonly string[]): PrGroup[] =>
583  withoutPrs(groups.filter(g => g.prs.length === 0 || g.prs.some(k => !keys.includes(k))), keys)
584
585export type GithubRow =
586  | { kind: 'label'; group?: number; text: string; isDone?: boolean }
587  | { kind: 'text'; group: number; text: string; isDone?: boolean }
588  | { kind: 'step'; group: number; text: string; isDone: boolean }
589  | { kind: 'landed'; count: number; isOpen: boolean }
590  | { kind: 'pr'; item: Item }
591
592export type Landed = {
593  // The merged and closed PRs in view, folded into one row under the rest.
594  items: readonly Item[]
595  // Every merged or closed PR in the band, in view or not.
596  finished: ReadonlySet<string>
597  listed: ReadonlySet<string>
598  isOpen: boolean
599}
600
601// The GitHub section top to bottom: each group's label, text and PRs, then the PRs in
602// no group (newest first) under `other`, then the landed row. A group whose PRs have
603// all landed is done.
604export function githubRows(groups: readonly PrGroup[], band: readonly Item[], rest: readonly Item[], landed?: Landed): GithubRow[] {
605  const byKey = new Map(band.map(i => [i.key, i]))
606  const rows: GithubRow[] = groups.flatMap((g, group): GithubRow[] => {
607    if (g.step) return [{ kind: 'step', group, text: g.step, isDone: g.isDone === true }]
608    const listed = landed ? g.prs.filter(k => landed.listed.has(k)) : []
609    const isDone = listed.length > 0 && listed.every(k => landed!.finished.has(k))
610    const prs = g.prs.filter(k => byKey.has(k) && !landed?.finished.has(k))
611    return [
612      ...(g.label ? [{ kind: 'label' as const, group, text: g.label, ...(isDone && { isDone }) }] : []),
613      ...(g.text ? [{ kind: 'text' as const, group, text: g.text, ...(isDone && !g.label && { isDone }) }] : []),
614      ...prs.map(k => ({ kind: 'pr' as const, item: byKey.get(k)! })),
615    ]
616  })
617  if (groups.length > 0 && rest.length > 0) rows.push({ kind: 'label', text: 'other' })
618  rows.push(...rest.map(item => ({ kind: 'pr' as const, item })))
619  if (!landed || landed.items.length === 0) return rows
620  rows.push({ kind: 'landed', count: landed.items.length, isOpen: landed.isOpen })
621  return landed.isOpen ? [...rows, ...landed.items.map(item => ({ kind: 'pr' as const, item }))] : rows
622}
623
types/index.d.ts 107 lines
1export type Item = {
2  key: string
3  url: string
4}
5
6export type PrState = 'open' | 'draft' | 'merged' | 'closed'
7export type CI = 'pass' | 'fail' | 'running' | 'none'
8export type Review = 'approved' | 'changes' | 'commented' | 'pending' | 'unassigned'
9
10export type PrStatus = {
11  state: PrState | 'unknown'
12  ci: CI
13  review?: Review
14  title?: string
15  author?: string
16  additions?: number
17  deletions?: number
18  hasConflict?: boolean
19  checkedAt: number
20  ciSince?: number
21}
22
23export type IssueType = 'triage' | 'backlog' | 'unstarted' | 'started' | 'completed' | 'canceled' | 'duplicate'
24
25// A Linear issue's workflow status; neither field when the read failed.
26export type IssueStatus = {
27  name?: string
28  type?: IssueType
29  checkedAt: number
30}
31
32// What the session's agent says it is doing, set through the set_status tool.
33export type StatusNote = {
34  text: string
35  setAt: number
36}
37
38// A group in the GitHub section, set through the group_prs tool: a label, a line of text, PRs (keys), or any mix;
39// or a step, a to-do row of its own that is ticked when done.
40export type PrGroup = {
41  label?: string
42  text?: string
43  prs: string[]
44  step?: string
45  isDone?: boolean
46}
47
48// One change edit_groups makes to the groups.
49export type GroupEdit = {
50  op?: string
51  pr?: string
52  group?: number
53  at?: number
54  label?: string
55  text?: string
56  prs?: string[]
57  step?: string
58  done?: boolean
59}
60
61// The PRs in the band when the groups were last set, and which were still open, so
62// links_band can say what changed since.
63export type GroupingBase = {
64  seen: string[]
65  live: string[]
66}
67
68export type BandColor = {
69  color: string
70  isFill: boolean
71}
72
73declare module 'claude-code' {
74  interface McpToolInputs {
75    /** This session's links band state; the mod registers and answers it itself. */
76    'mcp__gh-linear-parse-mod__links_band': {}
77    /** Sets or clears the status line at the top of the band. */
78    'mcp__gh-linear-parse-mod__set_status': { text?: string }
79    /** Sets the GitHub section's groups, top to bottom; an empty list clears them. */
80    'mcp__gh-linear-parse-mod__group_prs': { groups?: { label?: string; text?: string; prs?: string[]; step?: string; done?: boolean }[] }
81    /** Changes the groups in place, one edit at a time. */
82    'mcp__gh-linear-parse-mod__edit_groups': { edits?: GroupEdit[] }
83  }
84
85  interface PluginState {
86    'gh-linear-parse-mod': {
87      items: Item[]
88      dismissed: string[]
89      isHidden: boolean
90      isExpanded: boolean
91      bandColor: BandColor | null
92      hasBackfilled: boolean
93      prStatuses: Record<string, PrStatus>
94      issueStatuses: Record<string, IssueStatus>
95      isWatching: boolean
96      refreshing: number
97      agentStatus: StatusNote | null
98      prGroups: PrGroup[] | null
99      groupingBase: GroupingBase | null
100      showsLanded: boolean
101      hidesAwaitingReview: boolean
102      isSigningIn: boolean
103      isSigningInVercel: boolean
104    }
105  }
106}
107