SLOPSHOPPER

dev-statusline

A status line: repo, worktree, branch and the branch's PR (checks, resolved review threads), then Claude's context and 5-hour window beside Codex's; plus a…

guardstatusprocesstimer
v0.5.0no licenseupdated 2026-10-24ekcm/agent-toolkit/mods/dev-statusline
A shopper browsing a rack in a slop shop
README

agent-toolkit

Shared skills, mods and plugins for coding agents — Claude Code, Codex, pi, and anything else that reads the Agent Skills format.

Install

git clone https://github.com/ekcm/agent-toolkit.git ~/Documents/GitHub/agent-toolkit
cd ~/Documents/GitHub/agent-toolkit
./install.sh --dry-run   # preview
./install.sh

Then restart any running agents so they pick up the skills.

install.sh symlinks each folder in skills/ into the user-level skill folder of every supported agent, so this repo stays the only copy:

FolderRead by
~/.agents/skills/<name>Codex, pi, and other Agent Skills tools
~/.claude/skills/<name>Claude Code (it does not read ~/.agents/skills)

It also:

  • Backs up instead of deleting. Anything already at a target path is moved to ~/.agent-toolkit-backups/<timestamp>/.
  • Removes old copies from ~/.codex/skills. Codex still reads that legacy folder as well as ~/.agents/skills, so a copy left there makes each skill appear twice.
  • Links skill by skill, never replacing a whole folder, so skills installed by other tools (e.g. npx skills) are left alone.
  • Is safe to re-run. Links that are already correct are left as they are.

Don't also link skills into ~/.pi/agent/skills: pi already reads ~/.agents/skills and warns about duplicate names.

Updating

Edits to a skill take effect immediately, since the agents read it through the symlink — just restart the agent. After adding, removing or renaming a skill, run ./install.sh again. If the repo moves, run it again from the new location.

Uninstalling

./install.sh --uninstall

This removes only the symlinks that point into this repo. Backups stay in ~/.agent-toolkit-backups/; move a folder back from there to restore it.

The target folders can be overridden with AGENTS_SKILLS_DIR, CLAUDE_SKILLS_DIR, CODEX_HOME and AGENT_TOOLKIT_BACKUP_DIR.

Skills

Each folder in skills/ is a standard SKILL.md skill: frontmatter with only name and description, and plain instructions with no agent-specific tools.

SkillWhat it does
code-review-uncommitted-changesStrict review of uncommitted changes
verify-reviewSecond-pass check that a prior review was implemented, plus a regression scan
review-pull-requestDeep review of a GitHub PR via gh
retrieve-pull-request-commentsFetch and summarise review comments on the current branch's PR
draft-pr-descriptionWrite PR.md from the branch's commits and changes
handover-session-notesSave session context to NOTES.md for the next session
repo-wikiInteractive, verified wiki of a repo or monorepo component, kept outside it

Invoke a skill by name — /name in Claude Code, $name in Codex.

Claude Code mods

Mods change Claude Code itself (panels, commands, hooks), so unlike the skills they work in Claude Code only. Each lives in mods/<name>/, and this repo is a plugin marketplace that lists them.

To install from your local clone instead of GitHub, add it as a marketplace once with claude plugin marketplace add ~/Documents/GitHub/agent-toolkit, then install each mod as <name>@agent-toolkit. An install runs from a cached copy of the mod, so editing the clone changes nothing until you bump version in the mod's plugin.json, run claude plugin marketplace update agent-toolkit and claude plugin update <name>@agent-toolkit, and restart Claude Code. While working on a mod, start Claude Code with claude --plugin-dir ~/Documents/GitHub/agent-toolkit/mods/<name> instead: it loads the clone directly, and /reload-plugins picks up edits.

pr-review-board

Reviews several PRs at once with Claude and Codex side by side, in a live panel. For each PR it runs both reviewers independently, combines their findings, runs the PR's install, tests and build, then has the two agents debate whatever they disagree on, and shows what both agree on, what was confirmed, withdrawn or still disputed, colour-coded by severity and tagged by source.

The PR review panel reviewing two PRs: each reviewer's live activity, verification results and a debate in progress

Install it in Claude Code:

/plugin install pr-review-board --marketplace ekcm/agent-toolkit

Or install from your local clone:

claude plugin marketplace add ~/Documents/GitHub/agent-toolkit
/plugin install pr-review-board@agent-toolkit

It needs gh logged in, the claude and codex CLIs on your PATH, and the review-pull-request skill installed with ./install.sh.

CommandWhat it does
/review-prs ~/path/to/repo 19 22Review PRs 19 and 22 of that repo (inside the repo, /review-prs 19 22 is enough)
/review-prsOpen the panel
/review-prs trust owner/repoLet PRs of a repo you don't own run their install, tests and build
/review-prs untrust owner/repoUndo that; /review-prs trust lists the approved repos

Using the panel:

  • Press ctrl+x tab to focus the panel, then a PR's number key to open its results (or click its title). Inside a PR, 1 shows the combined result, 2 Claude's review and 3 Codex's; b goes back.
  • x (or close) closes the panel. Reviews keep running while it is closed, and /review-prs opens it again.
  • Each row has cancel and retry per reviewer, recombine to redo the combine, verify and debate from the saved reviews, and remove to drop a finished review from the panel (its files stay).
  • A PR number the repo doesn't have is reported in the command's reply and not added. Running a PR again after it finished starts a fresh review and overwrites its saved results.

What it touches:

  • Each PR is checked out as a detached worktree at ~/.agent-toolkit/pr-reviews/<repo>/pr-<n>/worktree, fetched into refs/pr-review/<n> of your local clone. Your own checkout and uncommitted changes are left alone.
  • Both reviewers and the debate are read-only. Verification runs the PR's code, so it runs only for your own repos or ones you approved, and never for a branch from someone else's fork.
  • Reviews, logs and the combined result (reconciled.md) are saved in ~/.agent-toolkit/pr-reviews/<repo>/pr-<n>/, next to the worktree. To remove a review's worktree and ref:
git -C <repo> worktree remove --force ~/.agent-toolkit/pr-reviews/<repo>/pr-<n>/worktree
git -C <repo> update-ref -d refs/pr-review/<n>

dev-statusline

A two-line status line for working across Claude Code and Codex: the repo, branch and the branch's PR on top, and how much room each agent has left below.

agent-toolkit (feat/statusline) · ✓ checks · 4/7 resolved
ctx ▰▰▰▱▱▱▱▱▱▱ 32% 64k/200k · claude 5h 58% left (2h10m) · codex 5h 55% left (1h05m)

Install it in Claude Code:

/plugin install dev-statusline --marketplace ekcm/agent-toolkit

Then point Claude Code's status line at it, in ~/.claude/settings.json (this replaces any statusLine you already have):

"statusLine": {
  "type": "command",
  "command": "sh ~/.agent-toolkit/dev-statusline/statusline.sh"
}

It needs macOS or Linux (it runs sh, sed and find), gh logged in for the PR part, the codex CLI logged in for the Codex figure, and jq for the subagent rows (macOS includes it); a part whose tool is missing is left out or shows —.

The mod keeps the figures and writes the two lines to ~/.agent-toolkit/dev-statusline/<session id>.txt; that script, which the mod writes on start-up, prints the file for the session asking. Each session's file is removed when it ends, and leftovers older than a day are cleared on start-up. The lines show under the prompt, below Claude Code's own line with the permission mode, and update whenever Claude Code redraws its status line.

What each part shows:

  • PR: the open PR for the current branch, from gh (its number is left out, since Claude Code's own line under the prompt shows it): ✓ checks, ◷ 3 running or ✗ 2 failing, then resolved review threads out of all of them. It shows no PR when the branch has none, and drops the PR part when gh is missing, logged out or offline. It refreshes at the end of each turn and every minute.
  • ctx: a gauge of the context window used, ▰ for used and ▱ for free, then the share used and tokens used out of the window (32% 64k/200k), straight from Claude Code.
  • claude 5h: how much of Claude's 5-hour usage window is left, and the time until it resets, straight from Claude Code. It shows — off a subscription.
  • codex 5h: how much of Codex's 5-hour window is left, and the time until it resets, live from your Codex account: the mod starts codex app-server for about a second, asks it for the account's rate limits (no tokens spent) and stops it. It needs the codex CLI on your PATH, logged in. If that fails, it falls back to the newest session log in ~/.codex/sessions (or $CODEX_HOME/sessions), which is only as fresh as your last interactive Codex turn. It shows — when there is no reading.

Worktrees: inside a linked git worktree the first line still leads with the project, the main repository's folder name, followed by the worktree's folder, dim: Muse/DEV-67 (feat/DEV-67-wiki-link-resolver). A detached checkout shows (detached <commit>), and its PR is the open one containing that commit, so pr-review-board's review checkouts show their PR too.

Subagents: when Claude Code runs subagents, the mod also draws their rows in the agent panel under the prompt, as a tree. An agent launched by another agent sits under it:

├─ DEV-67                      running  6m42s  · ✓ checks · 0/5 resolved · Bash: npm test 34s · 48k tokens
└─ Generating wiki for my-app  running  4m40s  · Agent: Research frontend · 61k tokens
   ├─ Research core            running  3m50s  · Read extract.py · 52k tokens
   ├─ Research API             idle     3m50s  · nothing for 2m05s · 40k tokens
   └─ Research evals           ✓ done   in 2m50s · 35k tokens

Each row names the worktree the subagent works in (or the subagent, outside any worktree), then:

  • State and time: running or waiting with how long it has been going; ✓ done in 2m50s (green), ✗ failed after 1m10s (red) or stopped once it ends. Claude Code keeps an ended row for a while, then drops it.
  • Idle: a running agent with no model request or tool call in flight for a minute shows as idle (yellow) with nothing for 2m05s, so a stuck agent stands out from a busy one.
  • That worktree's PR, as on the first line.
  • What it is doing now: the tool call in flight, with the command, file, pattern or task it was given (Bash: npm test, Read extract.py, Agent: Research core), and how long it has been running once that passes 10 seconds; or thinking while it waits on the model. It is cut to fit the terminal's width.
  • Its tokens.

When two or more subagents are at work, a third status line sums them up: 4 agents · 2 running · 1 idle · 1 waiting.

The mod ships the rows as the plugin's subagentStatusLine setting, so they need no settings entry; it runs ~/.agent-toolkit/dev-statusline/subagents.sh, which the mod writes on start-up. Claude Code gives that script each subagent's status, start time and tokens; the mod adds the rest from its hooks on subagents' model requests and tool calls, and the engine's list of agents (for who launched whom), in ~/.agent-toolkit/dev-statusline/<session id>.agents.json. The main session's own tool calls are not tracked. The PR states come from one gh call listing the repository's open PRs, made only when the repository has more than one worktree.

Several sessions share one Codex reading: the first to need it asks Codex and saves it to ~/.agent-toolkit/dev-statusline/codex.json, and the others reuse it for a minute.

Colours: checks and review threads are green, yellow or red, in your terminal's own colours. The repo name is bold in a darker Claude orange. The gauge's used segments, its percentage and claude 5h with its share left are Claude orange, and codex 5h with its share left is Codex lilac; a share left under 10% is also bold and underlined. left, the reset times, the free segments and the token count stay plain, and the separators, the branch's brackets and empty states (no PR, no checks, no threads, —) are dim. The brand colours need a terminal with 24-bit colour. The colours are set in one table, COLORS in hooks/format.ts.

Source 3 files
hooks/register.ts 342 lines
1import type { EngineInterface, Register } from 'claude-code'
2import { READER_SCRIPT, SUBAGENT_SCRIPT } from './reader'
3import {
4  activityText, agentsText, formatStatus, parseChecks, parseCodexLine, parseCodexLive, parseOpenPrs, parseThreads, parseWorktrees, prText, worktreeName,
5  type AgentActivity, type StatusData, type Window,
6} from './format'
7
8type $ = EngineInterface
9
10// gh and the Codex logs are slow or unchanging between turns, so they are
11// read at the end of each turn and once a minute, never on every redraw.
12const REFRESH_MS = 60_000
13
14// Every open PR of the repository with its checks and review threads, for the
15// subagent rows of the repo's other worktrees.
16const OPEN_PRS_QUERY = 'query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { pullRequests(states: OPEN, first: 50, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { number headRefName headRefOid reviewThreads(first: 100) { totalCount nodes { isResolved } } commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 100) { nodes { __typename ... on CheckRun { status conclusion } ... on StatusContext { state } } } } } } } } } } }'
17
18// One Codex reading serves every session for this long, so several open
19// sessions don't each start a Codex app server every minute.
20const CODEX_SHARED_MS = 55_000
21
22const THREADS_QUERY = 'query($owner: String!, $name: String!, $pr: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $pr) { reviewThreads(first: 100) { totalCount nodes { isResolved } } } } }'
23
24// Asks a short-lived Codex app server for the account's live rate limits,
25// which spends no tokens. The server quits when its input closes, before it
26// answers, so the input is held open until the answer comes, then the server
27// is stopped.
28const CODEX_LIVE_SCRIPT = `
29d=$(mktemp -d) || exit 1
30trap 'exec 3>&-; kill "$pid" 2>/dev/null; rm -rf "$d"' EXIT
31mkfifo "$d/in"
32codex app-server < "$d/in" > "$d/out" 2>/dev/null &
33pid=$!
34exec 3> "$d/in"
35printf '%s\\n' '{"id":1,"method":"initialize","params":{"clientInfo":{"name":"dev-statusline","version":"1"}}}' '{"method":"initialized"}' '{"id":2,"method":"account/rateLimits/read"}' >&3
36i=0
37while [ "$i" -lt 100 ] && ! grep -q '"id":2' "$d/out"; do sleep 0.1; i=$((i + 1)); done
38grep -m 1 '"id":2' "$d/out"`
39
40// The fallback when the live query fails (an older Codex, no network): the
41// newest session logs, newest first; the first token_count line with rate
42// limits in any of them is the latest reading Codex wrote down.
43const CODEX_LOG_SCRIPT = `
44for f in $(ls -t "$1"/sessions/*/*/*/rollout-*.jsonl 2>/dev/null | head -5); do
45  line=$(tail -c 4000000 "$f" | grep '"rate_limits":{' | tail -1)
46  if [ -n "$line" ]; then printf '%s\\n' "$line"; exit 0; fi
47done`
48
49// Agent activity changes with every tool call, so it is written at most this
50// often; the agents line is redrawn this often while any agent is about, so
51// an idle one shows as idle without waiting for a turn to end.
52const AGENTS_WRITE_MS = 500
53const AGENTS_TICK_MS = 15_000
54
55// An agent that ended this long ago is dropped from the file.
56const AGENTS_KEEP_MS = 10 * 60_000
57
58const data: StatusData = { repo: null, worktree: null, branch: null, isDetached: false, pr: undefined, context: null, claude: null, codex: null }
59let ticker: { cancel: () => void } | null = null
60let agentsTicker: { cancel: () => void } | null = null
61let isRefreshing = false
62
63// Every subagent's activity by agent id, and its tool calls in flight (an
64// agent can run several at once).
65let agents: Record<string, AgentActivity> = {}
66const toolsInFlight = new Map<string, number>()
67let isAgentsWritePending = false
68
69async function run($: $, argv: string[], cwd?: string): Promise<string | null> {
70  try {
71    const result = await $.process.run(argv, { cwd, timeoutMs: 20_000 })
72    return result.exitCode === 0 ? result.stdout.trim() : null
73  } catch {
74    return null
75  }
76}
77
78// ~/.agent-toolkit/dev-statusline: the reader script and one file of lines
79// per session, named by the session's id.
80async function linesDir($: $): Promise<string> {
81  return `${(await $.env.get('HOME')) ?? ''}/.agent-toolkit/dev-statusline`
82}
83
84// Writes the latest lines for the status line to print. The id is read each
85// time, since /clear goes on under a new one.
86async function show($: $) {
87  const text = formatStatus(data, await $.clock.now())
88  await $.fs.write(`${await linesDir($)}/${await $.session.id()}.txt`, `${text}\n`)
89}
90
91// The project is named after the folder holding the shared .git, so a linked
92// worktree still shows as its repository; git's own directory differing from
93// the shared one is what marks a linked worktree.
94async function readGit($: $, cwd: string) {
95  const paths = await run($, ['git', '-C', cwd, 'rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir'])
96  const [top, gitDir, commonDir] = paths ? paths.split('\n') : []
97  if (!top || !gitDir || !commonDir) {
98    Object.assign(data, { repo: null, worktree: null, branch: null, isDetached: false })
99    return
100  }
101  data.repo = commonDir.endsWith('/.git') ? worktreeName(commonDir.slice(0, -'/.git'.length)) : worktreeName(commonDir).replace(/\.git$/, '')
102  data.worktree = gitDir === commonDir ? null : worktreeName(top)
103  const branch = await run($, ['git', '-C', cwd, 'symbolic-ref', '--short', 'HEAD'])
104  data.isDetached = !branch
105  data.branch = branch ?? await run($, ['git', '-C', cwd, 'rev-parse', '--short', 'HEAD'])
106}
107
108// Leaves the PR unknown (undefined) when gh is missing, logged out or offline,
109// so the line drops the PR part instead of claiming there is none. A detached
110// checkout has no branch to look up, so its PR is the open one containing its
111// commit (how pr-review-board's review checkouts find theirs).
112async function readPr($: $, cwd: string) {
113  if (!data.repo || !data.branch) {
114    data.pr = undefined
115    return
116  }
117  let view: { number: number; statusCheckRollup?: unknown } | null
118  if (data.isDetached) {
119    const sha = await run($, ['git', '-C', cwd, 'rev-parse', 'HEAD'])
120    const found = sha ? await run($, ['gh', 'pr', 'list', '--state', 'open', '--search', sha, '--json', 'number,statusCheckRollup'], cwd) : null
121    if (found === null) {
122      data.pr = undefined
123      return
124    }
125    view = (JSON.parse(found) as { number: number; statusCheckRollup?: unknown }[])[0] ?? null
126  } else {
127    const result = await $.process.run(['gh', 'pr', 'view', '--json', 'number,statusCheckRollup'], { cwd, timeoutMs: 20_000 }).catch(() => null)
128    if (!result || (result.exitCode !== 0 && !/no pull requests found/i.test(result.stderr))) {
129      data.pr = undefined
130      return
131    }
132    view = result.exitCode === 0 ? JSON.parse(result.stdout) as { number: number; statusCheckRollup?: unknown } : null
133  }
134  if (!view) {
135    data.pr = null
136    return
137  }
138  const threads = await run($, ['gh', 'api', 'graphql', '-F', 'owner={owner}', '-F', 'name={repo}', '-F', `pr=${view.number}`, '-f', `query=${THREADS_QUERY}`], cwd)
139  data.pr = { number: view.number, checks: parseChecks(view.statusCheckRollup), threads: threads ? parseThreads(JSON.parse(threads)) : null }
140}
141
142// Writes, for the subagent rows, each of the repository's worktrees with its
143// name and its PR's state, keyed by path. A detached worktree's PR is the one
144// whose head is its commit; with none, its PR is left unknown rather than
145// "no PR", since its commit may sit inside a PR that has moved on. With only
146// one worktree there are no other worktrees to describe, so gh isn't asked.
147async function writeWorktrees($: $, cwd: string) {
148  const file = `${await linesDir($)}/${await $.session.id()}.worktrees.json`
149  const porcelain = data.repo ? await run($, ['git', '-C', cwd, 'worktree', 'list', '--porcelain']) : null
150  const worktrees = porcelain ? parseWorktrees(porcelain) : []
151  const rows: Record<string, { name: string; pr: string }> = {}
152  if (worktrees.length > 1) {
153    const answer = await run($, ['gh', 'api', 'graphql', '-F', 'owner={owner}', '-F', 'name={repo}', '-f', `query=${OPEN_PRS_QUERY}`], cwd)
154    const prs = answer ? parseOpenPrs(JSON.parse(answer)) : null
155    for (const worktree of worktrees) {
156      const pr = !prs ? undefined
157        : worktree.branch ? prs.byBranch.get(worktree.branch) ?? null
158        : worktree.head ? prs.byCommit.get(worktree.head)
159        : undefined
160      rows[worktree.path] = { name: worktreeName(worktree.path), pr: prText(pr) ?? '' }
161    }
162  }
163  await $.fs.write(file, JSON.stringify(rows))
164}
165
166// Reuses another session's reading when it is fresh, else asks Codex live,
167// falling back to its session logs, and shares what it found.
168async function readCodex($: $) {
169  const shared = `${await linesDir($)}/codex.json`
170  const now = await $.clock.now()
171  try {
172    const saved = JSON.parse(await $.fs.read(shared)) as { at: number; codex: Window | null }
173    if (now - saved.at < CODEX_SHARED_MS) {
174      data.codex = saved.codex
175      return
176    }
177  } catch {
178    // No reading yet, or an unreadable one: ask Codex.
179  }
180  const live = await run($, ['sh', '-c', CODEX_LIVE_SCRIPT])
181  let codex = live ? parseCodexLive(live) : null
182  if (!codex) {
183    const home = (await $.env.get('CODEX_HOME')) ?? `${(await $.env.get('HOME')) ?? ''}/.codex`
184    const line = await run($, ['sh', '-c', CODEX_LOG_SCRIPT, 'sh', home])
185    codex = line ? parseCodexLine(line) : null
186  }
187  data.codex = codex
188  await $.fs.write(shared, JSON.stringify({ at: now, codex }))
189}
190
191async function refresh($: $) {
192  if (isRefreshing) return
193  isRefreshing = true
194  try {
195    const cwd = await $.session.cwd()
196    await readGit($, cwd)
197    await Promise.all([
198      readPr($, cwd).catch(() => { data.pr = undefined }),
199      readCodex($),
200      writeWorktrees($, cwd).catch(() => undefined),
201    ])
202  } finally {
203    isRefreshing = false
204  }
205  await show($)
206}
207
208function agentsFile(dir: string, sessionId: string): string {
209  return `${dir}/${sessionId}.agents.json`
210}
211
212// Writes every subagent's activity for the row script, with each one's
213// parent from the engine's own list, and sums them up for the agents line.
214async function writeAgents($: $) {
215  isAgentsWritePending = false
216  const now = await $.clock.now()
217  const list = await $.agent.list().catch(() => null)
218  if (list) {
219    for (const info of list) {
220      const seen = agents[info.id] ?? (agents[info.id] = { phase: null, since: now })
221      if (info.parentId) seen.parent = info.parentId
222    }
223    const listed = new Set(list.map(info => info.id))
224    agents = Object.fromEntries(Object.entries(agents).filter(([id, seen]) => listed.has(id) || !seen.endedAt || now - seen.endedAt < AGENTS_KEEP_MS))
225  }
226  data.agents = list ? agentsText(list, agents, now) : null
227  await $.fs.write(agentsFile(await linesDir($), await $.session.id()), JSON.stringify(agents))
228  await show($)
229}
230
231function scheduleAgentsWrite($: $) {
232  if (isAgentsWritePending) return
233  isAgentsWritePending = true
234  try {
235    $.clock.after(AGENTS_WRITE_MS, () => void writeAgents($).catch(() => { isAgentsWritePending = false }))
236  } catch {
237    isAgentsWritePending = false
238  }
239}
240
241// Never throws: it runs inside every subagent's tool calls and model
242// requests, which must go on whatever happens to the row.
243async function mark($: $, agentId: string, change: Partial<AgentActivity>) {
244  try {
245    const now = await $.clock.now()
246    agents[agentId] = { phase: null, ...agents[agentId], since: now, ...change }
247    scheduleAgentsWrite($)
248  } catch {
249    // The row stays as it was.
250  }
251}
252
253function claudeWindow(limits: { kind: string; percentUsed: number; resetsAt?: string }[]): Window | null {
254  const five = limits.find(limit => limit.kind === 'five_hour')
255  return five ? { percentUsed: five.percentUsed, resetsAt: five.resetsAt ? Date.parse(five.resetsAt) : null } : null
256}
257
258export const register: Register = on => {
259  on('session.start', async ($, e, next) => {
260    // Clears a notice pinned by 0.1.0, which drew the line with $.ui.status.
261    $.ui.status(undefined)
262    const dir = await linesDir($)
263    await $.fs.write(`${dir}/statusline.sh`, READER_SCRIPT)
264    await $.fs.write(`${dir}/subagents.sh`, SUBAGENT_SCRIPT)
265    // Files of sessions that ended without cleaning up (a crash, a kill).
266    await run($, ['find', dir, '(', '-name', '*.txt', '-o', '-name', '*.worktrees.json', '-o', '-name', '*.agents.json', ')', '-mtime', '+1', '-delete'])
267    // A reload starts the module over: pick up what it last wrote.
268    try {
269      agents = JSON.parse(await $.fs.read(agentsFile(dir, await $.session.id()))) as Record<string, AgentActivity>
270    } catch {
271      agents = {}
272    }
273    const usage = await $.session.usage()
274    data.context = usage.context
275    data.claude = claudeWindow(usage.rateLimits)
276    await show($)
277    void refresh($)
278    ticker?.cancel()
279    ticker = $.clock.every(REFRESH_MS, () => void refresh($))
280    agentsTicker?.cancel()
281    agentsTicker = $.clock.every(AGENTS_TICK_MS, () => {
282      if (Object.keys(agents).length) scheduleAgentsWrite($)
283    })
284    return next(e)
285  })
286
287  // A subagent's model request: it is thinking until the response is in.
288  // Tools can start while the response is still streaming in, so a tool call
289  // in flight outranks thinking at either end.
290  on('turn.step', async function* ($, e, next) {
291    if (e.agentId === undefined) return yield* next(e)
292    const agentId = e.agentId
293    if (!toolsInFlight.get(agentId)) await mark($, agentId, { phase: 'thinking', activity: undefined, endedAt: undefined })
294    try {
295      return yield* next(e)
296    } finally {
297      if (!toolsInFlight.get(agentId)) await mark($, agentId, { phase: null })
298    }
299  })
300
301  // A subagent's tool call: what it runs, until the last call in flight ends.
302  on('tool.call', async ($, e, next) => {
303    if (e.agentId === undefined) return next(e)
304    const agentId = e.agentId
305    toolsInFlight.set(agentId, (toolsInFlight.get(agentId) ?? 0) + 1)
306    await mark($, agentId, { phase: 'tool', activity: activityText(e.tool, e as unknown as Record<string, unknown>) })
307    try {
308      return await next(e)
309    } finally {
310      const left = (toolsInFlight.get(agentId) ?? 1) - 1
311      toolsInFlight.set(agentId, left)
312      if (!left) await mark($, agentId, { phase: null, activity: undefined })
313    }
314  })
315
316  // Context and the Claude window come pushed from the engine after each turn.
317  on('session.measure', async ($, e, next) => {
318    data.context = e.context
319    data.claude = claudeWindow(e.rateLimits)
320    await show($)
321    return next(e)
322  })
323
324  // The main session's turns refresh the line; a subagent's turn ending is
325  // only noted, since its row says how long it took.
326  on('turn.complete', async ($, e, next) => {
327    if (e.agentId !== undefined) await mark($, e.agentId, { phase: null, activity: undefined, endedAt: await $.clock.now() })
328    else void refresh($)
329    return next(e)
330  })
331
332  on('session.end', async ($, e, next) => {
333    ticker?.cancel()
334    ticker = null
335    agentsTicker?.cancel()
336    agentsTicker = null
337    const dir = await linesDir($)
338    await run($, ['rm', '-f', `${dir}/${e.sessionId}.txt`, `${dir}/${e.sessionId}.worktrees.json`, agentsFile(dir, e.sessionId)])
339    return next(e)
340  })
341}
342
hooks/reader.ts 99 lines
1// Claude Code's status line runs this with the session as JSON on stdin; it
2// prints the lines the mod last wrote for that session.
3export const READER_SCRIPT = `#!/bin/sh
4# Written by the dev-statusline mod. Prints the lines it wrote for this session.
5id=$(sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p' | head -n 1)
6[ -n "$id" ] && cat "$(dirname "$0")/$id.txt" 2>/dev/null
7exit 0
8`
9
10// Claude Code's subagent status line runs this with every subagent row as JSON
11// on stdin. It draws the rows as a tree, each agent under the one that
12// launched it (from the activity file the mod writes): the worktree the agent
13// works in (or its task), its state and how long it has been at it, the PR
14// the mod last wrote for that worktree, what it is doing now (else Claude
15// Code's own summary of it), and its tokens. A running agent with nothing in
16// flight for a minute shows as idle; one whose turn ended while agents it
17// launched still run shows as waiting on them. What it
18// is doing is cut to fit the terminal's width. Rows it can't draw keep Claude
19// Code's own; without jq it draws none.
20export const SUBAGENT_SCRIPT = `#!/bin/sh
21# Written by the dev-statusline mod. Draws one row per subagent.
22command -v jq >/dev/null 2>&1 || exit 0
23input=$(cat)
24id=$(printf '%s' "$input" | jq -r '.session_id // empty')
25dir=$(dirname "$0")
26map="$dir/$id.worktrees.json"
27{ [ -n "$id" ] && [ -f "$map" ]; } || map=/dev/null
28agents="$dir/$id.agents.json"
29{ [ -n "$id" ] && [ -f "$agents" ]; } || agents=/dev/null
30printf '%s' "$input" | jq -c --slurpfile wt "$map" --slurpfile ag "$agents" '
31  def tokens: if . >= 1000000 then "\\((. / 100000 | floor) / 10)M" elif . >= 1000 then "\\(. / 1000 | round)k" else tostring end;
32  def paint($c): "\\u001b[" + $c + "m" + . + "\\u001b[0m";
33  def dim: paint("2");
34  def plain: gsub("\\u001b\\\\[[0-9;]*m"; "");
35  def pad($n): . + ((" " * ($n - (plain | length))) // "");
36  def two: tostring | if length < 2 then "0" + . else . end;
37  def dur: (. / 1000 | floor | if . < 0 then 0 else . end) as $s
38    | if $s < 60 then "\\($s)s"
39      elif $s < 3600 then "\\($s / 60 | floor)m\\($s % 60 | two)s"
40      else "\\($s / 3600 | floor)h\\(($s % 3600) / 60 | floor | two)m" end;
41  def tree($rows; $parent; $pre):
42    [$rows[] | select(.parent == $parent)] as $kids
43    | ($kids | length) as $n
44    | range(0; $n) as $i
45    | ($i == $n - 1) as $last
46    | ($kids[$i] + {branch: ($pre + (if $last then "└─" else "├─" end))}),
47      tree($rows; $kids[$i].id; $pre + (if $last then "   " else "│  " end));
48  (now * 1000) as $now
49  | ($wt[0] // {}) as $m
50  | ($ag[0] // {}) as $a
51  | (.columns // 120) as $cols
52  | (.tasks // []) as $t
53  | ($t | map(.id)) as $ids
54  | [$t[] | . as $task
55      | ($a[$task.id] // {}) as $s
56      | ($task.cwd // "") as $cwd
57      | ([$m | to_entries[] | .key as $k | select($cwd == $k or ($cwd | startswith($k + "/")))] | max_by(.key | length)) as $w
58      | ($task.startTime // $now) as $start
59      | ($now - ($s.since // $now)) as $quiet
60      | (if $quiet >= 10000 then " " + ($quiet | dur) else "" end) as $for
61      | ([$t[] | select(($a[.id].parent // null) == $task.id and (.status == "running" or .status == "pending" or .status == "waiting"))] | length) as $open
62      | (if ($task.label // "") != "" and $task.label != $task.description then $task.label else "" end) as $summary
63      | { id: $task.id,
64          parent: (($s.parent // null) as $p | if $p != null and ($ids | index($p)) != null then $p else null end),
65          label: ((if $w then $w.value.name else ($task.description // $task.label // "agent") end)[:28]),
66          pr: ($w.value.pr // ""),
67          tokens: (($task.tokenCount // 0) | tokens) }
68        + if $task.status == "running" or $task.status == "pending" then
69            (if $s.phase == "tool" then {state: "running", activity: (($s.activity // "") + ($for | dim))}
70             elif $s.phase == "thinking" then {state: "running", activity: ("thinking" + $for | dim)}
71             elif $s.since != null and $quiet >= 60000 then {state: ("idle" | paint("33")), activity: ("nothing for " + ($quiet | dur) | paint("33"))}
72             else {state: "running", activity: $summary} end)
73            + {time: ($now - $start | dur)}
74          elif $task.status == "waiting" or ($open > 0 and $task.status == "completed") then
75            {state: "waiting", time: ($now - $start | dur),
76             activity: (if $open > 0 then "on \\($open) agent" + (if $open > 1 then "s" else "" end) else $summary end)}
77          elif $task.status == "completed" then {state: ("✓ done" | paint("32")), time: (if $s.endedAt then "in " + ($s.endedAt - $start | dur) else "" end)}
78          elif $task.status == "failed" then {state: ("✗ failed" | paint("31")), time: (if $s.endedAt then "after " + ($s.endedAt - $start | dur) else "" end)}
79          elif $task.status == "killed" then {state: "stopped"}
80          else {state: ($task.status // "")} end
81    ] as $rows
82  | [tree($rows; null; "")] as $tree
83  | ($tree | map((.branch | length) + 1 + (.label | length)) | max // 0) as $lw
84  | ($tree | map(.state | plain | length) | max // 0) as $sw
85  | ($tree | map(.time // "" | length) | max // 0) as $tw
86  | $tree[] | . as $r
87  | (($r.branch | dim) + " " + ($r.label | pad($lw - ($r.branch | length) - 1)) + "  "
88      + ($r.state | pad($sw)) + (if $tw > 0 then " " + ($r.time // "" | pad($tw)) else "" end)
89      + (if $r.pr != "" then " " + ("·" | dim) + " " + $r.pr else "" end)) as $head
90  | (" " + ("·" | dim) + " " + $r.tokens + " tokens") as $tail
91  | ($cols - ($head | plain | length) - ($tail | plain | length) - 5) as $room
92  | ($r.activity // "") as $act
93  | { id: $r.id, content: ($head
94      + (if $act == "" or $room < 8 then ""
95         elif ($act | plain | length) > $room then " " + ("·" | dim) + " " + ($act | plain | .[:$room - 1] + "…" | dim)
96         else " " + ("·" | dim) + " " + $act end)
97      + $tail) }'
98`
99
hooks/format.ts 318 lines
1// Pure parsing and formatting for the status line, kept apart from the hooks
2// so it can be tested without a session.
3
4// Segments in the context gauge.
5const GAUGE_WIDTH = 10
6
7export type Checks = { passing: number; failing: number; running: number }
8export type Threads = { resolved: number; total: number }
9export type Pr = { number: number; checks: Checks; threads: Threads | null }
10
11// A rate-limit window: percent used and when it resets (ms since epoch).
12export type Window = { percentUsed: number; resetsAt: number | null }
13
14export type StatusData = {
15  // The project: the main repository's folder name, also inside a worktree.
16  repo: string | null
17  // The linked worktree's folder name; null in the main checkout.
18  worktree?: string | null
19  // The branch, or the short commit when the checkout is detached.
20  branch: string | null
21  isDetached?: boolean
22  // undefined: not looked up yet (or gh unavailable); null: no PR for the branch.
23  pr: Pr | null | undefined
24  context: { tokens?: number; percent?: number; window: number } | null
25  claude: Window | null
26  codex: Window | null
27  // A third line summing up the subagents, when several are at work.
28  agents?: string | null
29}
30
31// What a subagent is doing as the mod last saw it, for its row. The row
32// script reads these by agent id, beside what Claude Code gives it.
33export type AgentActivity = {
34  // The agent that launched it; absent when the main session did.
35  parent?: string
36  // A model request or a tool call in flight; null between them.
37  phase: 'thinking' | 'tool' | null
38  // The tool call in flight, shortened (`Bash: extract.py --repo …`).
39  activity?: string
40  // When the phase began, or when the last one ended (ms since epoch).
41  since: number
42  // When its last turn ended; cleared when it starts another.
43  endedAt?: number
44}
45
46// Past this long with nothing in flight, a running agent counts as idle.
47export const IDLE_MS = 60_000
48
49// Longest activity text on a row, so the row doesn't wrap.
50const ACTIVITY_WIDTH = 40
51
52const FAILED = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE'])
53const SKIPPED = new Set(['SKIPPED', 'NEUTRAL', 'STALE'])
54
55// Reads `gh pr view --json statusCheckRollup`: check runs carry status and
56// conclusion, commit statuses carry state.
57export function parseChecks(rollup: unknown): Checks {
58  const checks: Checks = { passing: 0, failing: 0, running: 0 }
59  if (!Array.isArray(rollup)) return checks
60  for (const item of rollup as { status?: string; conclusion?: string; state?: string }[]) {
61    if (item.state !== undefined) {
62      if (item.state === 'SUCCESS') checks.passing += 1
63      else if (FAILED.has(item.state)) checks.failing += 1
64      else checks.running += 1
65    } else if (item.status !== 'COMPLETED') checks.running += 1
66    else if (FAILED.has(item.conclusion ?? '')) checks.failing += 1
67    else if (!SKIPPED.has(item.conclusion ?? '')) checks.passing += 1
68  }
69  return checks
70}
71
72// Reads the GraphQL answer for a PR's review threads.
73export function parseThreads(answer: unknown): Threads | null {
74  const threads = (answer as { data?: { repository?: { pullRequest?: { reviewThreads?: { totalCount?: number; nodes?: { isResolved?: boolean }[] } } } } })
75    ?.data?.repository?.pullRequest?.reviewThreads
76  if (!threads || typeof threads.totalCount !== 'number' || !Array.isArray(threads.nodes)) return null
77  return { resolved: threads.nodes.filter(n => n.isResolved).length, total: threads.totalCount }
78}
79
80// Reads the last Codex `token_count` line that carries rate limits; the
81// primary window is the 5-hour one.
82export function parseCodexLine(line: string): Window | null {
83  try {
84    const event = JSON.parse(line) as { payload?: { rate_limits?: { primary?: { used_percent?: number; resets_at?: number } } } }
85    const primary = event.payload?.rate_limits?.primary
86    if (!primary || typeof primary.used_percent !== 'number') return null
87    return { percentUsed: primary.used_percent, resetsAt: typeof primary.resets_at === 'number' ? primary.resets_at * 1000 : null }
88  } catch {
89    return null
90  }
91}
92
93// Reads the app server's answer to account/rateLimits/read; the primary
94// window is the 5-hour one.
95export function parseCodexLive(line: string): Window | null {
96  try {
97    const answer = JSON.parse(line) as { result?: { rateLimits?: { primary?: { usedPercent?: number; resetsAt?: number } } } }
98    const primary = answer.result?.rateLimits?.primary
99    if (!primary || typeof primary.usedPercent !== 'number') return null
100    return { percentUsed: primary.usedPercent, resetsAt: typeof primary.resetsAt === 'number' ? primary.resetsAt * 1000 : null }
101  } catch {
102    return null
103  }
104}
105
106// Terminal colour codes. Green, yellow and red are the terminal's own, so
107// they follow its theme; the brand colours need a terminal with 24-bit colour
108// (most current ones). `repo` is bold in a darker Claude orange.
109export const COLORS = {
110  good: '32',
111  warn: '33',
112  bad: '31',
113  claude: '38;2;215;119;87',
114  codex: '38;2;180;160;255',
115  repo: '1;38;2;193;95;60',
116  dim: '2',
117} as const
118
119// Below this share left, a 5-hour figure is bold and underlined as well.
120export const LOW_LEFT = 10
121
122// `extra` adds styles to the colour, such as '1;4' for bold and underlined.
123export function paint(color: keyof typeof COLORS, text: string, extra = ''): string {
124  if (!text) return ''
125  return `\x1b[${extra ? `${extra};` : ''}${COLORS[color]}m${text}\x1b[0m`
126}
127
128// Parts are joined by a dim dot, so they read apart without competing.
129const SEPARATOR = ` ${paint('dim', '·')} `
130
131// Removes colour codes, for tests and for anything that needs the plain text.
132export function plain(text: string): string {
133  return text.replace(/\x1b\[[0-9;]*m/g, '')
134}
135
136function checksText(checks: Checks): string {
137  if (checks.failing) return paint('bad', `✗ ${checks.failing} failing`)
138  if (checks.running) return paint('warn', `◷ ${checks.running} running`)
139  if (checks.passing) return paint('good', '✓ checks')
140  return paint('dim', 'no checks')
141}
142
143// All resolved is good, some is a warning, none is bad.
144function threadsText(threads: Threads | null): string | null {
145  if (!threads) return null
146  if (!threads.total) return paint('dim', 'no threads')
147  const color = threads.resolved === threads.total ? 'good' : threads.resolved ? 'warn' : 'bad'
148  return paint(color, `${threads.resolved}/${threads.total} resolved`)
149}
150
151export function prText(pr: Pr | null | undefined): string | null {
152  if (pr === undefined) return null
153  if (pr === null) return paint('dim', 'no PR')
154  // No PR number: Claude Code's own line under the prompt already shows it.
155  return [checksText(pr.checks), threadsText(pr.threads)].filter(Boolean).join(SEPARATOR)
156}
157
158// 950 → 950, 222_345 → 222k, 1_000_000 → 1M, 1_250_000 → 1.3M.
159export function tokensText(tokens: number): string {
160  if (tokens >= 1_000_000) return `${Number((tokens / 1_000_000).toFixed(1))}M`
161  if (tokens >= 1_000) return `${Math.round(tokens / 1_000)}k`
162  return String(tokens)
163}
164
165// A gauge of the context window used: the used segments and the share in
166// Claude orange, the free segments and 60k/200k plain.
167function contextText(context: StatusData['context']): string {
168  if (!context || !context.window) return `ctx ${paint('dim', '—')}`
169  const tokens = context.tokens ?? 0
170  const used = Math.max(0, Math.min(100, Math.round(context.percent ?? (tokens / context.window) * 100)))
171  // Rounded down, so the gauge is full only when the window is.
172  const filled = Math.floor((used / 100) * GAUGE_WIDTH)
173  const gauge = `${paint('claude', '▰'.repeat(filled))}${'▱'.repeat(GAUGE_WIDTH - filled)}`
174  return `ctx ${gauge} ${paint('claude', `${used}%`)} ${tokensText(tokens)}/${tokensText(context.window)}`
175}
176
177function untilText(resetsAt: number, now: number): string {
178  const minutes = Math.max(0, Math.round((resetsAt - now) / 60_000))
179  return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
180}
181
182// `claude 5h 37%` in the agent's colour, then `left (3h20m)` plain. Below
183// LOW_LEFT the share is bold and underlined too.
184function windowText(agent: 'claude' | 'codex', window: Window | null, now: number): string {
185  if (!window) return `${paint(agent, `${agent} 5h`)} ${paint('dim', '—')}`
186  // A window that has reset since it was read is whole again.
187  if (window.resetsAt !== null && window.resetsAt <= now) return `${paint(agent, `${agent} 5h 100%`)} left`
188  const left = Math.max(0, Math.round(100 - window.percentUsed))
189  const reset = window.resetsAt !== null ? ` (${untilText(window.resetsAt, now)})` : ''
190  return `${paint(agent, `${agent} 5h`)} ${paint(agent, `${left}%`, left < LOW_LEFT ? '1;4' : '')} left${reset}`
191}
192
193export function formatStatus(data: StatusData, now: number): string {
194  const head = data.isDetached ? `detached ${data.branch}` : data.branch
195  const branch = head ? ` ${paint('dim', '(')}${head}${paint('dim', ')')}` : ''
196  const worktree = data.worktree ? paint('dim', `/${data.worktree}`) : ''
197  const where = data.repo ? `${paint('repo', data.repo)}${worktree}${branch}` : null
198  const first = [where, data.repo ? prText(data.pr) : null].filter(Boolean).join(SEPARATOR)
199  const second = [contextText(data.context), windowText('claude', data.claude, now), windowText('codex', data.codex, now)].join(SEPARATOR)
200  return [first, second, data.agents].filter(Boolean).join('\n')
201}
202
203// 42_000 → 42s, 372_000 → 6m12s, 3_900_000 → 1h05m.
204export function durationText(ms: number): string {
205  const seconds = Math.max(0, Math.floor(ms / 1000))
206  if (seconds < 60) return `${seconds}s`
207  if (seconds < 3600) return `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, '0')}s`
208  return `${Math.floor(seconds / 3600)}h${String(Math.floor((seconds % 3600) / 60)).padStart(2, '0')}m`
209}
210
211function shorten(text: string, width: number): string {
212  const line = text.replace(/\s+/g, ' ').trim()
213  return line.length > width ? `${line.slice(0, width - 1)}…` : line
214}
215
216function baseName(path: unknown): string {
217  return typeof path === 'string' ? path.split('/').filter(Boolean).pop() ?? path : ''
218}
219
220// What a tool call is doing, in a few words: the command (or, for a long one,
221// its description) for Bash, the file for the file tools, the pattern for
222// searches, the task for Agent.
223export function activityText(tool: string, input: Record<string, unknown>): string {
224  const text = (key: string) => typeof input[key] === 'string' ? input[key] as string : ''
225  let detail = ''
226  if (tool === 'Bash') detail = text('description') && text('command').length > ACTIVITY_WIDTH ? text('description') : text('command')
227  else if (['Read', 'Edit', 'Write', 'NotebookEdit'].includes(tool)) detail = baseName(input.file_path ?? input.notebook_path)
228  else if (tool === 'Grep' || tool === 'Glob') detail = text('pattern')
229  else if (tool === 'Agent') detail = text('description')
230  else if (tool === 'WebFetch') detail = text('url').replace(/^https?:\/\//, '')
231  else if (tool === 'WebSearch') detail = text('query')
232  else if (tool === 'Skill') detail = text('skill')
233  // An MCP tool goes by its own name, without the mcp__<server>__ prefix.
234  const name = tool.startsWith('mcp__') ? tool.split('__').slice(2).join('__') || tool : tool
235  if (!detail) return shorten(name, ACTIVITY_WIDTH)
236  return shorten(`${name}${tool === 'Bash' || tool === 'Agent' ? ':' : ''} ${detail}`, ACTIVITY_WIDTH)
237}
238
239// `3 agents · 2 running · 1 idle` once two or more are at work; null for
240// fewer, whose own rows say as much. `waiting` is an agent held on work of its
241// own (its agents, a background command).
242export function agentsText(list: { id: string; status: string }[], activity: Record<string, AgentActivity>, now: number): string | null {
243  let running = 0
244  let idle = 0
245  let waiting = 0
246  for (const agent of list) {
247    const seen = activity[agent.id]
248    if (agent.status === 'waiting') waiting += 1
249    else if (agent.status === 'idle') idle += 1
250    else if (agent.status === 'running' || agent.status === 'pending') {
251      if (seen && !seen.phase && now - seen.since >= IDLE_MS) idle += 1
252      else running += 1
253    }
254  }
255  const total = running + idle + waiting
256  if (total < 2) return null
257  return [
258    `${total} agents`,
259    running ? `${running} running` : '',
260    idle ? paint('warn', `${idle} idle`) : '',
261    waiting ? `${waiting} waiting` : '',
262  ].filter(Boolean).join(SEPARATOR)
263}
264
265export type Worktree = { path: string; head: string | null; branch: string | null }
266
267// Reads `git worktree list --porcelain`: a `worktree <path>` line opens each
268// entry, `HEAD <sha>` gives its commit, and `branch refs/heads/<name>` names
269// its branch unless detached.
270export function parseWorktrees(porcelain: string): Worktree[] {
271  const worktrees: Worktree[] = []
272  for (const line of porcelain.split('\n')) {
273    if (line.startsWith('worktree ')) worktrees.push({ path: line.slice('worktree '.length), head: null, branch: null })
274    else if (line.startsWith('HEAD ') && worktrees.length) worktrees[worktrees.length - 1]!.head = line.slice('HEAD '.length)
275    else if (line.startsWith('branch refs/heads/') && worktrees.length) worktrees[worktrees.length - 1]!.branch = line.slice('branch refs/heads/'.length)
276  }
277  return worktrees
278}
279
280type OpenPrNode = {
281  number?: number
282  headRefName?: string
283  headRefOid?: string
284  reviewThreads?: { totalCount?: number; nodes?: { isResolved?: boolean }[] }
285  commits?: { nodes?: { commit?: { statusCheckRollup?: { contexts?: { nodes?: unknown[] } } | null } }[] }
286}
287
288// Reads the GraphQL answer listing a repository's open PRs, each with its
289// checks and review threads, keyed by branch and by head commit (for detached
290// checkouts, which have no branch to go by).
291export function parseOpenPrs(answer: unknown): { byBranch: Map<string, Pr>; byCommit: Map<string, Pr> } {
292  const byBranch = new Map<string, Pr>()
293  const byCommit = new Map<string, Pr>()
294  const nodes = (answer as { data?: { repository?: { pullRequests?: { nodes?: OpenPrNode[] } } } })?.data?.repository?.pullRequests?.nodes
295  for (const node of Array.isArray(nodes) ? nodes : []) {
296    if (typeof node.number !== 'number' || !node.headRefName) continue
297    const threads = node.reviewThreads
298    const pr: Pr = {
299      number: node.number,
300      checks: parseChecks(node.commits?.nodes?.[0]?.commit?.statusCheckRollup?.contexts?.nodes ?? []),
301      threads: threads && typeof threads.totalCount === 'number' && Array.isArray(threads.nodes)
302        ? { resolved: threads.nodes.filter(n => n.isResolved).length, total: threads.totalCount }
303        : null,
304    }
305    byBranch.set(node.headRefName, pr)
306    if (node.headRefOid) byCommit.set(node.headRefOid, pr)
307  }
308  return { byBranch, byCommit }
309}
310
311// The name a worktree's row goes by: its folder, or for a folder named just
312// `worktree` (as pr-review-board's are, under pr-<n>/) the folder above it.
313export function worktreeName(path: string): string {
314  const parts = path.split('/').filter(Boolean)
315  const last = parts[parts.length - 1] ?? path
316  return last === 'worktree' && parts.length > 1 ? parts[parts.length - 2]! : last
317}
318