A docked pane of the session repo's issues and PRs in run order, each row with its labels in their colours, a toggle that expands it to its full title, label…

Claude Code mods (function-hook plugins), installed through one marketplace.
smart-compact: lets Claude compact its own context at a step boundary it picks, with its own instructions, then resume the work on its own. Reminders arrive at 60% and 80% of the auto-compact point. Interactive sessions only: a -p or SDK session cannot compact on request yet, so there the mod only adds its keep-list to automatic compactions.gh-pane: /gh-pane (run again to hide the pane, so one key binding such as "ctrl+x g": "command:gh-pane" shows and hides it), or the Open gh-pane button above the prompt (Hide gh-pane while the pane is up, each followed by the Nerd Font GitHub mark, which /plugin configure can blank where the terminal font has none), docks a pane of the session repo's open issues and PRs in run order: spec trees from sub-issues, blocked-by edges, claims and their ship runs, planning maps whose tickets close without a PR, and the needs-triage and needs-info lists. Each row shows its labels as dots in their GitHub colours, the state labels its tag already says left off, and an in PR #N tag carries a mark from the PR's check runs (✓ all passed, ✗ one failed, ● still running). A row's ▸ toggle expands it to its full title, its labels as coloured chips, and a line of its assignees, last update, comment count and milestone; expand all (hotkey e while the pane holds focus) expands every row, issues arriving later included, and a /clear keeps what is expanded. Its buttons fill the prompt with /ship N, /triage N, a map's next ticket (/wayfinder MAP N), a request to release a stale claim, or a request to close an issue whose sub-issues are all closed (all done), and never send it. Two band buttons act on this session's own state instead: when a main-loop answer carries the merge-gate text and a PR link, merge PR #N (hotkey m) sends the merge reply as your own prompt, and once that PR reads as merged over REST, clear + /ship N (hotkey n) clears the session and runs the first ready row's command (one that does not start with / shows no button), and goes once the next turn ends. When a ship run merges on its own on a clean gate, its answer's merged line (Merged on a clean gate: with the PR link after it on that line) takes the same read, so clear + /ship N shows with no merge button. A hotkey fires only once the band holds focus (ctrl+x then tab, or a click), never from the prompt, where m types a letter; a click always works. A /clear keeps the open pane's last read of the same folder on screen until the next one lands. It reads the repo through git and gh api (REST only), so gh must be installed and signed in. The label names (the map label included), PR cap, ship worktree layout, the band button's icon, the text each button fills, the merge-gate text, the merged text and the merge reply are options in /plugin configure gh-pane@claude-mods.claude plugin marketplace add Gharib89/claude-mods
claude plugin install smart-compact@claude-mods
claude plugin install gh-pane@claude-modshooks/register.tsx 537 lines1// gh-pane: `/gh-pane`, or the band's button above the prompt, shows or hides a pane of the session repo's open issues
2// and PRs in run order. Its buttons fill the prompt with the next command and never send it: the person reads it and
3// presses Enter. Two band buttons act on this session's own state instead: at its own merge gate one sends the merge
4// reply, and once the PR is merged, there or by a ship run on its own, one clears the session and runs the next command.
5
6import { atom, read, update } from 'claude-code'
7import type { Elements, EngineInterface, PluginOptions, Register } from 'claude-code'
8
9import type { Gate, Issue, Snapshot } from '../types'
10import { isMerged, readBacklog, type Runner } from './github'
11import { commandOf, fill, gatePr, mergedPrOf, runLine } from './rules'
12
13const PANE = 'gh-pane'
14const snapshot = atom({ plugin: 'gh-pane', key: 'snapshot' } as const, null)
15const gate = atom({ plugin: 'gh-pane', key: 'gate' } as const, null)
16
17type E = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button' | 'Link'>
18type Config = ReturnType<typeof configOf>
19
20const configOf = (o: PluginOptions) => ({
21 needsTriage: String(o.needsTriageLabel),
22 needsInfo: String(o.needsInfoLabel),
23 readyForAgent: String(o.readyForAgentLabel),
24 readyForHuman: String(o.readyForHumanLabel),
25 mapLabel: String(o.mapLabel),
26 mapCommand: String(o.mapCommand),
27 prCap: Number(o.prCap),
28 worktreeLayout: String(o.worktreeLayout),
29 shipCommand: String(o.shipCommand),
30 triageCommand: String(o.triageCommand),
31 releaseRequest: String(o.releaseRequest),
32 closeRequest: String(o.closeRequest),
33 gateText: String(o.gateText),
34 mergedText: String(o.mergedText),
35 mergeReply: String(o.mergeReply),
36 buttonIcon: String(o.buttonIcon),
37})
38
39const cut = (text: string, room: number) => (text.length <= room ? text : `${text.slice(0, Math.max(1, room - 1))}…`)
40
41const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error)).split('\n')[0]
42
43// Reads overlap (a timer, a gh call, the command): only the latest one started may land.
44let reads = 0
45// The last snapshot landed, which the pane draws while `$.state` holds none; the state copy stays because its write
46// redraws the pane. A /clear empties `$.state` while the pane stays up, and its one hook, `session.end`, runs before
47// that, so a read started there lands in the old session (seen on 2.1.289). This module variable outlives the /clear,
48// and draws only in the folder it was read in: one process may host more than one session.
49let kept: { cwd: string; view: Snapshot } | null = null
50// Which rows are expanded, per repo: the mode, and the rows toggled against it. A module variable for the reason `kept`
51// is one: it outlives the /clear the next button runs.
52const expansion = new Map<string, { all: boolean; flipped: Set<number> }>()
53
54// Black or white ink on a label's hex colour, by perceived brightness.
55const inkOn = (hex: string) => {
56 const [r, g, b] = [0, 2, 4].map(i => parseInt(hex.slice(i + 1, i + 3), 16))
57 return (0.299 * r! + 0.587 * g! + 0.114 * b!) / 255 > 0.6 ? '#000000' : '#ffffff'
58}
59
60const age = (now: string, then: string) => {
61 const hours = (Date.parse(now) - Date.parse(then)) / 3_600_000
62 return hours < 1 ? `${Math.max(1, Math.floor(hours * 60))}m ago` : hours < 24 ? `${Math.floor(hours)}h ago` : `${Math.floor(hours / 24)}d ago`
63}
64
65const runnerOf = ($: EngineInterface): Runner => async argv => {
66 const { exitCode, stdout, stderr } = await $.process.run(argv).catch((error: unknown) => {
67 throw new Error(`${argv[0]} did not run (not installed, or timed out): ${messageOf(error)}`)
68 })
69 if (exitCode !== 0) throw new Error(`${argv[0]} ${argv[1]}: ${stderr.trim().split('\n')[0]}`)
70 return stdout
71}
72
73// Answers the snapshot it read, landed or not: a read overtaken by a newer one is still fresh for its caller.
74async function refresh($: EngineInterface, config: Config): Promise<Snapshot> {
75 const ticket = ++reads
76 const cwd = await $.session.cwd()
77 const run = runnerOf($)
78 const now = new Date(await $.clock.now()).toISOString()
79 const next = await readBacklog(run, config.worktreeLayout, now).catch((error: unknown) => ({ error: `gh-pane: ${messageOf(error)}` }))
80 if (ticket !== reads) return next
81 kept = { cwd, view: next }
82 await update($, snapshot, () => next)
83 return next
84}
85
86// Opened by the person (the command, the band's button), the pane is placed at any width. The band draws from
87// `$.ui.panes()`, which no redraw follows (2.1.289), so show, hide and the ui.close hook each invalidate it.
88async function show($: EngineInterface, config: Config) {
89 const opened = await $.ui.open({ id: PANE, title: 'gh-pane' })
90 $.ui.invalidate('ui.render')
91 await refresh($, config)
92 return opened
93}
94
95// The mod's own $.ui.close skips its own ui.close hook (seen in `claude plugin test` on 2.1.289), so hide
96// invalidates the band itself.
97async function hide($: EngineInterface) {
98 await $.ui.close({ id: PANE })
99 $.ui.invalidate('ui.render')
100}
101
102async function isOpen($: EngineInterface) {
103 return (await $.ui.panes()).some(pane => pane.id === PANE)
104}
105
106// Nothing awaits a timer tick or a re-read after a tool call, so a failure there is toasted rather than dropped.
107async function refreshIfOpen($: EngineInterface, config: Config) {
108 try {
109 if (await isOpen($)) await refresh($, config)
110 } catch (error) {
111 $.ui.toast(`gh-pane did not refresh: ${messageOf(error)}`)
112 }
113}
114
115async function propose($: EngineInterface, text: string) {
116 const draft = (await $.prompt.read()).text.trim()
117 await $.prompt.fill(draft === '' ? { text } : { text: ` ${text}`, mode: 'append' })
118 $.ui.toast(`In the prompt: ${text} (Enter sends it)`)
119}
120
121/**
122 * A row's state, first match wins. An issue whose sub-issues are all closed waits only on its own close. A map ticket
123 * (a sub-issue of a map) left open, unblocked, unclaimed and waiting on neither triage nor info is next.
124 */
125function stateOf(
126 issue: Issue,
127 config: Config,
128 isMapTicket: boolean,
129): { tag: string; color: string; pr?: number; blockers?: Issue['blockers']; isReady?: true; isNext?: true; isDone?: true } {
130 if (issue.pr !== undefined) return { tag: 'in PR ', color: 'cyan', pr: issue.pr }
131 if (issue.subs.total > 0 && issue.subs.done === issue.subs.total) return { tag: 'all done', color: 'green', isDone: true }
132 if (issue.blockers.length > 0) return { tag: 'blocked by ', color: 'yellow', blockers: issue.blockers }
133 if (issue.assignees.length > 0) return { tag: `claimed (${issue.assignees.join(', ')})`, color: 'blue' }
134 if (issue.labels.includes(config.readyForAgent)) return { tag: 'ready now', color: 'green', isReady: true }
135 if (issue.labels.includes(config.readyForHuman)) return { tag: 'yours', color: 'magenta' }
136 const waiting = issue.labels.find(l => l === config.needsTriage || l === config.needsInfo)
137 if (waiting !== undefined) return { tag: waiting, color: 'gray' }
138 if (issue.labels.includes(config.mapLabel)) return { tag: 'map', color: 'gray' }
139 if (isMapTicket) return { tag: 'ready now', color: 'green', isNext: true }
140 return { tag: 'untriaged', color: 'gray' }
141}
142
143type Open = Exclude<Snapshot, { error: string }>
144
145const has = (issue: Issue, label: string) => issue.labels.includes(label)
146
147/** The pane's order: each root's tree, then the lone issues waiting on triage or info. */
148function arrange(view: Open, config: Config) {
149 const byNumber = new Map(view.issues.map(issue => [issue.number, issue]))
150 // A map and its tickets at every depth resolve by a closing comment, never a PR.
151 const mapOf = (issue: Issue): number | undefined =>
152 has(issue, config.mapLabel) ? issue.number : issue.parent === undefined ? undefined : mapOf(byNumber.get(issue.parent)!)
153 const isMapTicket = (issue: Issue) => mapOf(issue) !== undefined && !has(issue, config.mapLabel)
154 // A spec tree draws in place whatever its root's label; a lone issue waiting on triage or info waits below.
155 const top = view.issues.filter(issue => issue.parent === undefined)
156 const isWaiting = (issue: Issue, label: string) => issue.subs.total === 0 && has(issue, label)
157 const roots = top.filter(issue => !isWaiting(issue, config.needsTriage) && !isWaiting(issue, config.needsInfo))
158 const waiting = [
159 { name: 'needs triage', issues: top.filter(issue => isWaiting(issue, config.needsTriage)), canTriage: true },
160 { name: 'needs info', issues: top.filter(issue => isWaiting(issue, config.needsInfo)), canTriage: false },
161 ]
162 return { byNumber, mapOf, isMapTicket, roots, waiting }
163}
164
165/** The command of the first row in the pane's order whose button starts work: a ready issue's ship or a map's next. */
166function nextCommand(view: Open, config: Config): string | undefined {
167 const { byNumber, mapOf, isMapTicket, roots, waiting } = arrange(view, config)
168 const walk = (issue: Issue): Issue[] => [issue, ...issue.children.flatMap(n => walk(byNumber.get(n)!))]
169 for (const issue of [...roots.flatMap(walk), ...waiting.flatMap(group => group.issues)]) {
170 const state = stateOf(issue, config, isMapTicket(issue))
171 if (state.isReady) return fill(config.shipCommand, { n: issue.number })
172 if (state.isNext) return fill(config.mapCommand, { map: mapOf(issue)!, n: issue.number })
173 }
174 return undefined
175}
176
177const setGate = ($: EngineInterface, to: Gate | null) => update($, gate, () => to)
178
179// Sends the reply as the person's own words. The press marks the merging before the send, so the state is right
180// whether or not the mod's own prompt.submit hook sees this call.
181async function pressMerge($: EngineInterface, config: Config, at: Gate) {
182 await setGate($, { ...at, phase: 'merging' })
183 try {
184 await $.prompt.submit({ text: config.mergeReply, asUser: true })
185 } catch (error) {
186 await setGate($, at)
187 throw error
188 }
189}
190
191// The merge reply's turn, or one carrying the merged text, ended: the PR itself says whether it merged (a stale-base
192// or a no leaves it open), and a fresh read, pane open or not, picks the next command.
193async function settleMerge($: EngineInterface, config: Config, pr: number) {
194 try {
195 if (!(await isMerged(runnerOf($), pr))) return await setGate($, null)
196 const view = await refresh($, config)
197 if ('error' in view) $.ui.toast(view.error)
198 const text = 'error' in view ? undefined : nextCommand(view, config)
199 const run = text === undefined ? undefined : commandOf(text)
200 await setGate($, { pr, phase: 'merged', next: text === undefined || run === undefined ? undefined : { text, ...run } })
201 } catch (error) {
202 await setGate($, null)
203 $.ui.toast(`gh-pane could not read PR #${pr}: ${messageOf(error)}`)
204 }
205}
206
207// Seen on 2.1.291: `$.command.run` works from a button press but is refused inside a `command.run` hook, no
208// `session.start` fires after a /clear, and `$.prompt.submit` refuses text starting with `/`. So the next button runs
209// the whole chain inside one press: /clear, then the command as a command.
210async function pressNext($: EngineInterface, next: NonNullable<Gate['next']>) {
211 await setGate($, null)
212 await $.command.run({ command: 'clear' })
213 await $.command.run({ command: next.command, args: next.args })
214}
215
216export const register: Register = (on, options) => {
217 const config = configOf(options)
218
219 // A main-loop answer carrying the gate text puts this session at the gate, and one carrying the merged text says a
220 // ship run merged on its own, with no gate to answer; a subagent's turn is neither.
221 on('turn.complete', async ($, e, next) => {
222 const done = await next(e)
223 if (e.agentId !== undefined) return done
224 const mergedPr = mergedPrOf(e.answer, config.mergedText)
225 const pr = gatePr(e.answer, config.gateText)
226 if (mergedPr !== undefined) void settleMerge($, config, mergedPr)
227 else if (pr !== undefined) await setGate($, { pr, phase: 'gate' })
228 else {
229 const at = await read($, gate)
230 if (at?.phase === 'merging') void settleMerge($, config, at.pr)
231 // The next command was picked at merge time: it stands for the turn that follows the merge, no longer.
232 else if (at?.phase === 'merged') await setGate($, null)
233 }
234 return done
235 })
236
237 // A typed reply: the merge word counts as the button's press, anything else hides the button until the gate returns.
238 on('prompt.submit', async ($, e, next) => {
239 const at = await read($, gate)
240 if (at?.phase === 'gate') await setGate($, e.text.trim() === config.mergeReply ? { ...at, phase: 'merging' } : null)
241 return next(e)
242 })
243
244 on('session.end', async ($, e, next) => {
245 await setGate($, null)
246 return next(e)
247 })
248
249 on('session.start', async ($, e, next) => {
250 await $.command.register({
251 name: 'gh-pane',
252 description: "Open or hide a pane of this repo's issues and PRs in run order",
253 // Typed mid-turn, the pane opens or hides at once instead of waiting for the turn to end.
254 immediate: true,
255 })
256 $.clock.every(120_000, () => refreshIfOpen($, config))
257 return next(e)
258 })
259
260 // Run again while the pane is open, the command hides it, so one key binding shows and hides it as the band's button does.
261 // An unreadable pane list reads as closed, as on the band, so the command still opens the pane.
262 on('command.run', { command: 'gh-pane' }, async $ => {
263 if (await isOpen($).catch(() => false)) {
264 await hide($)
265 return { text: 'gh-pane hidden.' }
266 }
267 const opened = await show($, config)
268 return { text: opened.isPlaced ? 'gh-pane opened.' : `gh-pane is waiting: ${opened.reason}` }
269 })
270
271 // Closed by the person's close mark; an unload runs none of the opener's hooks.
272 on('ui.close', { id: PANE }, async ($, e, next) => {
273 const closed = await next(e)
274 $.ui.invalidate('ui.render')
275 return closed
276 })
277
278 // One button above the prompt that shows or hides the pane; whatever another plugin draws there stays above it.
279 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
280 const below = await next(e)
281 if (e.props.hasSurvey) return below
282 const { Box, Text, Button }: E = $.ui.resolve(e)
283 // An unreadable pane list or gate reads as closed: a throw here would take the band of every plugin beneath with it.
284 const shown = await isOpen($).catch(() => false)
285 const at = await read($, gate).catch(() => null)
286 const upNext = at?.phase === 'merged' ? at.next : undefined
287 const toast = (error: unknown) => $.ui.toast(`gh-pane: ${messageOf(error)}`)
288 return (
289 <Box flexDirection="column">
290 {below}
291 <Box gap={2}>
292 <Button
293 key="toggle"
294 plain
295 label={`${shown ? 'Hide' : 'Open'} gh-pane ${config.buttonIcon}`.trim()}
296 onPress={() => (shown ? hide($) : show($, config)).catch(toast)}
297 />
298 {at?.phase === 'gate' && <Button key="merge" hotkey="m" label={`merge PR #${at.pr}`} onPress={() => pressMerge($, config, at).catch(toast)} />}
299 {at?.phase === 'merging' && <Text color="cyan">{`merging PR #${at.pr}…`}</Text>}
300 {upNext && <Button key="next" hotkey="n" label={`clear + ${upNext.text}`} onPress={() => pressNext($, upNext).catch(toast)} />}
301 </Box>
302 </Box>
303 )
304 })
305
306 // A gh call or a push moves issues and PRs: re-read once it has run. Each word counts only where a command starts
307 // or follows a space or shell operator, and git's global options (`-C <path>`, `-c <key=value>`, `--no-pager`) may
308 // sit before `push`.
309 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
310 const ran = await next(e)
311 if (/(?:^|[\s;&|(])(?:gh\s|git\s+(?:-[Cc]\s+\S+\s+|-\S+\s+)*push\b)/.test(e.command)) void refreshIfOpen($, config)
312 return ran
313 })
314
315 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
316 const { Box, Text, Button, Link }: E = $.ui.resolve(e)
317 // A snapshot an older version wrote (no `ci`) may still be in `$.state` once the mod reloads, and draws as none.
318 const stored = await read($, snapshot)
319 const view = (stored !== null && !('error' in stored) && !('ci' in stored) ? null : stored) ?? (kept?.cwd === (await $.session.cwd()) ? kept.view : null)
320 const room = e.props.bodyColumns
321 if (view === null) return <Text dimColor>Reading the repo over gh api…</Text>
322 // A failed read (a network blip) holds the pane until the next re-read, so retry starts one now.
323 if ('error' in view) {
324 return (
325 <Box gap={1}>
326 <Text color="red">{cut(view.error, room - 10)}</Text>
327 <Button key="retry" label="retry" onPress={() => refreshIfOpen($, config)} />
328 </Box>
329 )
330 }
331 if (view.issues.length === 0 && view.prs === 0) return <Text dimColor>{`Nothing open in ${view.repo}.`}</Text>
332
333 const { byNumber, mapOf, isMapTicket, roots, waiting } = arrange(view, config)
334 const ref = (n: number, kind: 'issues' | 'pull' = 'issues') => (
335 <Link href={(kind === 'issues' && byNumber.get(n)?.url) || `https://github.com/${view.repo}/${kind}/${n}`} label={`#${n}`} />
336 )
337 const blockers = (list: Issue['blockers']) =>
338 list.flatMap(({ label, url }, i) => [...(i === 0 ? [] : [', ']), <Link key={label} href={url} label={label} />])
339 const runs = new Map(
340 view.issues
341 .filter(issue => issue.assignees.length > 0)
342 .map(issue => [issue.number, runLine({ ...issue, now: view.fetchedAt, hasPr: issue.pr !== undefined, expectsPr: mapOf(issue) === undefined })] as const),
343 )
344 const lines = [...runs.values()].filter(line => line !== null)
345 const stale = lines.filter(line => line.isStale).length
346 // Ready now: every row with a button that starts work, a ship or a map's next.
347 const ready = view.issues.filter(issue => {
348 const state = stateOf(issue, config, isMapTicket(issue))
349 return state.isReady || state.isNext
350 }).length
351 const isCapFull = view.prs >= config.prCap
352
353 const triage = (issues: number[]) =>
354 fill(config.triageCommand, { issues: issues.length === 1 ? `${issues[0]}` : `${issues.map(n => `#${n}`).join(', ')} one by one` })
355
356 // The labels a row shows: all but the state labels its tag already says.
357 const stateLabels = [config.needsTriage, config.needsInfo, config.readyForAgent, config.readyForHuman, config.mapLabel]
358 const colorOf = (issue: Issue, label: string) => `#${issue.labelColors[label] || 'ededed'}`
359 const ciMark = { pass: ['✓', 'green'], fail: ['✗', 'red'], running: ['●', 'yellow'] } as const
360
361 if (!expansion.has(view.repo)) expansion.set(view.repo, { all: false, flipped: new Set() })
362 const expanded = expansion.get(view.repo)!
363 const toggle = (n: number) => {
364 if (!expanded.flipped.delete(n)) expanded.flipped.add(n)
365 $.ui.invalidate('ui.render')
366 }
367
368 const row = (issue: Issue, prefix: string) => {
369 const state = stateOf(issue, config, isMapTicket(issue))
370 const labels = issue.labels.filter(label => !stateLabels.includes(label))
371 const ci = state.pr === undefined ? undefined : view.ci[state.pr]
372 const isExpanded = expanded.all !== expanded.flipped.has(issue.number)
373 const bar = '█'.repeat(Math.round((issue.subs.done / Math.max(1, issue.subs.total)) * 8)).padEnd(8, '░')
374 const run = runs.get(issue.number)
375 const pad = `${prefix.replace('├', '│').replace(/[└•]/, ' ')} ↳`
376 const indent = pad.replace('↳', ' ')
377 const facts = [
378 ...(issue.assignees.length > 0 && !state.tag.startsWith('claimed') ? [issue.assignees.join(', ')] : []),
379 `updated ${age(view.fetchedAt, issue.updatedAt)}`,
380 `${issue.comments} comment${issue.comments === 1 ? '' : 's'}`,
381 ...(issue.milestone ? [issue.milestone] : []),
382 ]
383 // The row's buttons, each named by its label: what it fills in the prompt.
384 const buttons = [
385 state.isReady && { name: 'ship', fills: () => fill(config.shipCommand, { n: issue.number }) },
386 state.isNext && { name: 'next', fills: () => fill(config.mapCommand, { map: mapOf(issue)!, n: issue.number }) },
387 state.isDone && { name: 'close', fills: () => fill(config.closeRequest, { n: issue.number, total: issue.subs.total }) },
388 has(issue, config.needsTriage) && { name: 'triage', fills: () => triage([issue.number]) },
389 ].flatMap(button => button || [])
390 // What follows a collapsed title, measured, each part with its one-column gap: the dots, the count, the tag, the
391 // CI mark and the buttons.
392 const tail = [
393 labels.length,
394 issue.subs.total > 0 ? `${issue.subs.done}/${issue.subs.total}`.length : 0,
395 `${state.tag}${state.pr === undefined ? '' : `#${state.pr}`}${(state.blockers ?? []).map(b => b.label).join(', ')}`.length,
396 ci ? 1 : 0,
397 ...buttons.map(button => button.name.length),
398 ].reduce((sum, width) => sum + (width > 0 ? width + 1 : 0), 0)
399 // The prefix, the toggle and `#N `, each with its gap, and one spare column.
400 const titleRoom = Math.max(8, room - prefix.length - 3 - `#${issue.number} `.length - tail - 1)
401 return [
402 <Box key={`row-${issue.number}`} gap={1}>
403 <Text dimColor>{prefix}</Text>
404 <Button key={`toggle-${issue.number}`} plain label={isExpanded ? '▾' : '▸'} onPress={() => toggle(issue.number)} />
405 <Text bold={state.isReady === true}>
406 {ref(issue.number)}
407 {isExpanded ? '' : ` ${cut(issue.title, titleRoom)}`}
408 </Text>
409 {!isExpanded && labels.length > 0 && (
410 <Text>
411 {labels.map(label => (
412 <Text key={`dot-${issue.number}-${label}`} color={colorOf(issue, label)}>
413 ●
414 </Text>
415 ))}
416 </Text>
417 )}
418 {issue.subs.total > 0 && <Text dimColor>{`${isExpanded ? `${bar} ` : ''}${issue.subs.done}/${issue.subs.total}`}</Text>}
419 <Text color={state.color}>
420 {state.tag}
421 {state.pr !== undefined ? ref(state.pr, 'pull') : ''}
422 {state.blockers ? blockers(state.blockers) : ''}
423 </Text>
424 {ci && <Text color={ciMark[ci][1]}>{ciMark[ci][0]}</Text>}
425 {buttons.map(({ name, fills }) => (
426 <Button key={`${name}-${issue.number}`} plain label={name} onPress={() => propose($, fills())} />
427 ))}
428 </Box>,
429 // The title on lines of its own: wrapped inside the first line's row, it wrapped the prefix and tag too (2.1.296).
430 isExpanded && (
431 <Box key={`title-${issue.number}`} gap={1}>
432 <Box flexShrink={0}>
433 <Text dimColor>{indent}</Text>
434 </Box>
435 <Box flexShrink={1}>
436 <Text bold={state.isReady === true} wrap="wrap">
437 {issue.title}
438 </Text>
439 </Box>
440 </Box>
441 ),
442 run && (
443 <Box key={`run-${issue.number}`} gap={1}>
444 <Text dimColor>{pad}</Text>
445 <Text color={run.isStale ? 'red' : 'cyan'} bold={run.isStale}>
446 {cut(run.text, Math.max(12, room - pad.length - 12))}
447 </Text>
448 {run.isStale && (
449 <Button
450 key={`release-${issue.number}`}
451 plain
452 label="release"
453 onPress={() => propose($, fill(config.releaseRequest, { n: issue.number, user: issue.assignees.join(', ') }))}
454 />
455 )}
456 </Box>
457 ),
458 isExpanded && labels.length > 0 && (
459 <Box key={`chips-${issue.number}`} gap={1}>
460 <Box flexShrink={0}>
461 <Text dimColor>{indent}</Text>
462 </Box>
463 <Box flexShrink={1} gap={1} flexWrap="wrap">
464 {labels.map(label => (
465 <Text key={`chip-${issue.number}-${label}`} backgroundColor={colorOf(issue, label)} color={inkOn(colorOf(issue, label))}>
466 {` ${label} `}
467 </Text>
468 ))}
469 </Box>
470 </Box>
471 ),
472 isExpanded && (
473 <Box key={`facts-${issue.number}`} gap={1}>
474 <Text dimColor>{indent}</Text>
475 <Text dimColor>{facts.join(' · ')}</Text>
476 </Box>
477 ),
478 ]
479 }
480
481 // Each sub-issue below `issue`, at every depth.
482 const branch = (issue: Issue, indent: string): ReturnType<typeof row> => [
483 issue.subs.done > 0 ? <Text key={`done-${issue.number}`} dimColor>{`${indent}├ ✓ ${issue.subs.done} done`}</Text> : undefined,
484 ...issue.children.flatMap((n, i) => {
485 const isLast = i === issue.children.length - 1
486 const child = byNumber.get(n)!
487 return [...row(child, `${indent}${isLast ? '└' : '├'}`), ...branch(child, `${indent}${isLast ? ' ' : '│'} `)]
488 }),
489 ]
490
491 return (
492 <Box flexDirection="column" width={room}>
493 <Text color={isCapFull ? 'yellow' : undefined} dimColor={!isCapFull}>
494 {`PR cap ${view.prs}/${config.prCap} · ready now: ${ready} · runs: ${lines.length - stale} active · ${stale} stale`}
495 </Text>
496 <Box gap={1}>
497 <Button key="refresh" plain label="↻" onPress={() => refreshIfOpen($, config)} />
498 <Button
499 key="expand"
500 plain
501 hotkey="e"
502 label={expanded.all ? 'collapse all' : 'expand all'}
503 onPress={() => {
504 expanded.all = !expanded.all
505 expanded.flipped.clear()
506 $.ui.invalidate('ui.render')
507 }}
508 />
509 </Box>
510 {roots.map(root =>
511 root.subs.total === 0 ? (
512 row(root, '•')
513 ) : (
514 <Box key={`tree-${root.number}`} flexDirection="column" marginTop={1}>
515 {row(root, '•')}
516 {branch(root, ' ')}
517 </Box>
518 ),
519 )}
520 {waiting.map(({ name, issues, canTriage }) =>
521 issues.length === 0 ? null : (
522 <Box key={name} flexDirection="column" marginTop={1}>
523 <Box gap={1}>
524 <Text bold color="gray">{`${name} (${issues.length})`}</Text>
525 {canTriage && issues.length > 1 && (
526 <Button key="triage-all" plain label="triage all" onPress={() => propose($, triage(issues.map(issue => issue.number)))} />
527 )}
528 </Box>
529 {issues.flatMap((issue, i) => row(issue, i === issues.length - 1 ? ' └' : ' ├'))}
530 </Box>
531 ),
532 )}
533 </Box>
534 )
535 })
536}
537hooks/github.ts 98 lines1// Reads the session repo's open issues and PRs over GitHub REST (`gh api`), never GraphQL, which flakes 401
2// mid-session (docs/adr/0001-mods-may-read-the-session-repo.md).
3
4import type { CiState, Issue, Snapshot } from '../types'
5import { closesOf, worktreeIssue } from './rules'
6
7/** Runs argv on the host and answers its stdout, throwing on a nonzero exit; register.tsx owns `$`. */
8export type Runner = (argv: string[]) => Promise<string>
9
10type Raw = Record<string, any>
11
12// Every path read here answers a list, or for check runs one object per page; --slurp wraps each page in an outer array.
13const list = async (run: Runner, path: string): Promise<Raw[]> =>
14 (JSON.parse(await run(['gh', 'api', '--paginate', '--slurp', path])) as (Raw | Raw[])[]).flat()
15
16/** Runs `tasks` at most 8 at a time: GitHub's secondary rate limit refuses many concurrent requests. */
17async function inTurn(tasks: (() => Promise<void>)[]) {
18 const queue = [...tasks]
19 await Promise.all(Array.from({ length: 8 }, async () => {
20 for (let task = queue.shift(); task !== undefined; task = queue.shift()) await task()
21 }))
22}
23
24/** The open backlog, `layout` matching each claimed issue to its ship worktree. */
25export async function readBacklog(run: Runner, layout: string, now: string): Promise<Snapshot> {
26 // gh fills `{owner}/{repo}` from the checkout's remotes, and with none on a GitHub host fails in its own words.
27 const repo = (await run(['gh', 'api', 'repos/{owner}/{repo}', '--jq', '.full_name'])).trim()
28 // The first worktree listed is the main checkout.
29 const [main = '', ...paths] = [...(await run(['git', 'worktree', 'list', '--porcelain'])).matchAll(/^worktree (.+)$/gm)].map(m => m[1]!)
30 const worktrees = new Map(paths.map(path => [worktreeIssue(layout, main, path), path.slice(path.lastIndexOf('/') + 1)]))
31
32 const open = await list(run, `repos/${repo}/issues?state=open&per_page=100`)
33 const prs = open.filter(raw => raw.pull_request)
34 const closer = new Map(prs.flatMap(pr => closesOf(pr.body ?? '').map(n => [n, pr.number as number])))
35 const raws = open.filter(raw => !raw.pull_request)
36 const issues: Issue[] = raws.map(raw => ({
37 number: raw.number,
38 title: raw.title,
39 url: raw.html_url,
40 labels: raw.labels.map((l: Raw) => l.name),
41 labelColors: Object.fromEntries(raw.labels.map((l: Raw) => [l.name, l.color])),
42 updatedAt: raw.updated_at,
43 comments: raw.comments,
44 milestone: raw.milestone?.title,
45 assignees: raw.assignees.map((a: Raw) => a.login),
46 children: [],
47 subs: { total: raw.sub_issues_summary?.total ?? 0, done: raw.sub_issues_summary?.completed ?? 0 },
48 blockers: [],
49 pr: closer.get(raw.number),
50 worktree: worktrees.get(raw.number),
51 }))
52 // Sub-issues and blockers may live in another repo, so they match by url, never by number.
53 const byUrl = new Map(issues.map(issue => [issue.url, issue]))
54
55 await inTurn(
56 issues.flatMap((issue, i) => [
57 issue.subs.total > 0 && (() =>
58 list(run, `repos/${repo}/issues/${issue.number}/sub_issues?per_page=100`).then(subs => {
59 const children = subs.flatMap(s => byUrl.get(s.html_url) ?? [])
60 issue.children = children.map(child => child.number)
61 for (const child of children) child.parent = issue.number
62 })),
63 raws[i]!.issue_dependencies_summary?.blocked_by > 0 && (() =>
64 list(run, `repos/${repo}/issues/${issue.number}/dependencies/blocked_by`).then(blockers => {
65 issue.blockers = blockers
66 .filter(b => b.state === 'open')
67 .map(b => {
68 const where = b.repository_url.slice(b.repository_url.lastIndexOf('/repos/') + '/repos/'.length)
69 return { label: where === repo ? `#${b.number}` : `${where}#${b.number}`, url: b.html_url }
70 })
71 })),
72 issue.assignees.length > 0 && (() =>
73 list(run, `repos/${repo}/issues/${issue.number}/events?per_page=100`).then(events => {
74 issue.claimedAt = events.findLast(ev => ev.event === 'assigned')?.created_at
75 })),
76 ]).filter(task => task !== false),
77 )
78 // Check runs only: legacy commit statuses answer `pending` when a repo posts none, which would mark every PR running.
79 const ci: Record<number, CiState> = {}
80 await inTurn(
81 [...new Set(issues.flatMap(issue => issue.pr ?? []))].map(n => async () => {
82 const runs = (await list(run, `repos/${repo}/commits/refs/pull/${n}/head/check-runs?per_page=100`)).flatMap(page => page.check_runs)
83 if (runs.length === 0) return
84 ci[n] = runs.some(r => r.status !== 'completed')
85 ? 'running'
86 : runs.every(r => ['success', 'skipped', 'neutral'].includes(r.conclusion))
87 ? 'pass'
88 : 'fail'
89 }),
90 )
91 return { repo, issues, prs: prs.length, fetchedAt: now, ci }
92}
93
94/** Whether PR `n` of the session repo is merged. */
95export async function isMerged(run: Runner, n: number): Promise<boolean> {
96 return (await run(['gh', 'api', `repos/{owner}/{repo}/pulls/${n}`, '--jq', '.merged'])).trim() === 'true'
97}
98hooks/rules.ts 67 lines1// The pane's rules as pure functions, so a test reaches them without the pane.
2
3const STALE_HOURS = 24
4
5export type RunLine = { text: string; isStale: boolean }
6
7/**
8 * The line under a claimed issue, first match wins: a claim older than a day with no PR closing it is stale, unless
9 * the issue closes without a PR (`expectsPr: false`); a matching ship worktree names the run; with neither and no PR,
10 * the claim's age. A claim with a PR and no worktree has no line, since its row already says `in PR #N`.
11 */
12export function runLine(run: { claimedAt?: string; now: string; hasPr: boolean; expectsPr?: boolean; worktree?: string }): RunLine | null {
13 const hours = run.claimedAt === undefined ? undefined : (Date.parse(run.now) - Date.parse(run.claimedAt)) / 3_600_000
14 const age = hours === undefined ? '' : hours < 24 ? ` ${Math.floor(hours)}h ago` : ` ${Math.floor(hours / 24)}d ago`
15 const expectsPr = run.expectsPr ?? true
16 if (expectsPr && !run.hasPr && hours !== undefined && hours > STALE_HOURS) {
17 return { text: `✗ stale claim: claimed${age}, no PR`, isStale: true }
18 }
19 if (run.worktree !== undefined) return { text: `◐ ship worktree ${run.worktree}`, isStale: false }
20 if (run.hasPr) return null
21 return { text: `◐ claimed${age}${expectsPr ? ', no PR yet' : ''}`, isStale: false }
22}
23
24const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
25
26/**
27 * The issue a worktree belongs to under `layout`, a path relative to the main checkout's parent folder in which
28 * `{repo}` is the main checkout's folder name, `{slug}` any one path segment and `{n}` the issue number.
29 */
30export function worktreeIssue(layout: string, main: string, path: string): number | undefined {
31 const parent = main.slice(0, main.lastIndexOf('/') + 1)
32 if (!path.startsWith(parent)) return undefined
33 const repo = main.slice(parent.length)
34 const pattern = layout
35 .split(/(\{repo\}|\{slug\}|\{n\})/)
36 .map(part => (part === '{repo}' ? escape(repo) : part === '{slug}' ? '[^/]+' : part === '{n}' ? '(\\d+)' : escape(part)))
37 .join('')
38 const n = new RegExp(`^${pattern}$`).exec(path.slice(parent.length))?.[1]
39 return n === undefined ? undefined : Number(n)
40}
41
42/** The issues a PR body closes, by GitHub's closing keywords on a same-repo `#N`. */
43export const closesOf = (body: string): number[] =>
44 [...body.matchAll(/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\s+#(\d+)\b/gi)].map(m => Number(m[1]))
45
46/** A template with each `{key}` replaced by its value. */
47export const fill = (template: string, values: Record<string, string | number>): string =>
48 template.replace(/\{(\w+)\}/g, (whole, key: string) => (Object.hasOwn(values, key) ? String(values[key]) : whole))
49
50/** The PR a merge-gate answer names: the number in its first `/pull/<N>`, when the answer carries the gate text. */
51export function gatePr(answer: string, gateText: string): number | undefined {
52 const n = answer.includes(gateText) ? /\/pull\/(\d+)/.exec(answer)?.[1] : undefined
53 return n === undefined ? undefined : Number(n)
54}
55
56/** The PR a merged answer names: the first `/pull/<N>` after the merged text on that text's line, as ship's merged line ends. */
57export function mergedPrOf(answer: string, mergedText: string): number | undefined {
58 const at = answer.indexOf(mergedText)
59 return at === -1 ? undefined : gatePr(answer.slice(at).split('\n')[0]!, mergedText)
60}
61
62/** A slash command's name and args, or undefined for text that is no command. */
63export function commandOf(text: string): { command: string; args: string } | undefined {
64 const match = /^\/(\S+)(?:\s+(.*))?$/s.exec(text.trim())
65 return match === null ? undefined : { command: match[1]!, args: match[2] ?? '' }
66}
67types/index.d.ts 55 lines1// The state contract of the gh-pane mod.
2
3/** One open issue of the session repo, as the pane orders it. */
4export type Issue = {
5 number: number
6 title: string
7 url: string
8 labels: string[]
9 /** Each label's colour, hex as GitHub gives it, without `#`. */
10 labelColors: Record<string, string>
11 /** When it last changed, GitHub's `updated_at`. */
12 updatedAt: string
13 /** How many comments it has. */
14 comments: number
15 /** Its milestone's title, when it has one. */
16 milestone?: string
17 assignees: string[]
18 /** Its open sub-issues in this repo, in the parent's order. */
19 children: number[]
20 /** Its sub-issues, all of them and the closed ones (GitHub's `sub_issues_summary`). */
21 subs: { total: number; done: number }
22 /** The open issue it is a sub-issue of. */
23 parent?: number
24 /** Its open blockers, labelled `#N` in this repo and `owner/repo#N` in another. */
25 blockers: { label: string; url: string }[]
26 /** The open PR whose body closes it. */
27 pr?: number
28 /** When it was last assigned: the claim's start. */
29 claimedAt?: string
30 /** The folder name of its ship worktree, when one matches the layout. */
31 worktree?: string
32}
33
34/** A PR's check runs, all read: every one passed (or skipped, or neutral), one failed, or one still running. */
35export type CiState = 'pass' | 'fail' | 'running'
36
37export type Snapshot =
38 /** `ci`: each PR that closes an open issue, by number, read from its head's check runs; absent when it has none. */
39 | { repo: string; issues: Issue[]; prs: number; fetchedAt: string; ci: Record<number, CiState> }
40 | { error: string }
41
42/** Where this session stands at a ship run's merge gate, or once a ship run merged on its own: the PR and the band's offer. */
43export type Gate = {
44 pr: number
45 phase: 'gate' | 'merging' | 'merged'
46 /** Once merged: the command the next button runs after a /clear, the first ready row's. None when nothing is ready or its command is no slash command. */
47 next?: { text: string; command: string; args: string }
48}
49
50declare module 'claude-code' {
51 interface PluginState {
52 'gh-pane': { snapshot: Snapshot | null; gate: Gate | null }
53 }
54}
55