SLOPSHOPPER

repo-brief

Gathers the repo's state at session start (branch, ahead/behind, uncommitted work, recent commits, open PRs with CI, focus-label issues, stale branches) with…

bandcommandpromptprocess
★ 1v0.2.0no licenseupdated 2026-10-12joeldg/claude-mods/repo-brief
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · repo-brief
› 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 › /brief ⎿ repo-brief: Repo state just now (gathered by the repo-brief mod): ⎿ repo-brief: Branch: none, HEAD is detached ⎿ repo-brief: Working tree: clean ⎿ repo-brief: PRs and issues: not gathered (gh unavailable, or the remote is not GitHub) HEAD@detached · clean Hide ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
HEAD@detached · clean Hide
README

claude-mods

Claude Code mods (function-hook plugins) I find helpful. Each folder is one plugin.

Requires a Claude Code build with function-hook plugins (2.1.289 or newer). machine-guard reads macOS tools (sysctl, vm_stat, ioreg, ps).

git clone https://github.com/joeldg/claude-mods ~/Projects/claude-mods

dev-servers

A pane of your project's running dev servers, so you don't have to ask Claude to restart them — and a tool so Claude doesn't have to run lsof to find out what's listening.

  • /servers opens the Servers pane:
  • running servers whose working folder is in this repo: name, port, pid and uptime, with Restart, Stop and Log
  • known start commands that aren't running, with Start: package.json dev/start/serve/preview scripts (run with your lockfile's package manager), .claude/launch.json and Procfile
  • a count of other listeners on the machine. Claude Code's own sessions (the desktop app's engine and the claude CLI, which also listen on localhost from the project's folder) are never listed as servers nor counted as other listeners.
  • Only button presses start or stop anything:
  • Start runs the command detached, logging to ~/.claude/dev-servers/<project>/.
  • Stop sends SIGTERM. If the server ignores it, pressing again within 10s force-stops it.
  • Restart stops the server, waits for the port to free up, then starts it.
  • Before any signal, it checks the pid still runs the same command.
  • Claude gets a read-only dev_servers tool: this project's running servers (name, port, pid, uptime, and the log when it was started from the pane), the start commands that aren't running, and with all: true every other listener on the machine (port, process), ending with how many Claude Code sessions it left out, e.g. (7 Claude Code sessions not listed), so nothing is hidden silently. Its description tells Claude to use it instead of lsof/netstat/ps. It never starts or stops anything.
  • When a command fails with "address already in use", Claude gets a note (and you a toast) naming the holder, e.g. Port 4000 is held by node (pid 123, up 2h, in /Users/me/other).
  • Status line: servers: :4000 :5173.
  • Makes no model calls. The port scan is netstat -anv -p tcp (macOS) or ss -ltnp (Linux), never a bare lsof; ps and lsof -d cwd run once per new pid, one pid at a time. One open session scans per interval (15s by default) and writes ~/.claude/dev-servers/scan-cache.json for the others; a slow scan doubles the interval, up to 5 minutes.

downloads-drop

Puts files you just downloaded into your prompt with one click.

  • Watches ~/Downloads (top level). When a new file arrives (PDF, Markdown, images, 3MF/STL/OBJ, zip, video…), a band appears above the prompt: New in Downloads: paper.pdf, model-b.3mf · 2m ago [Attach] [Dismiss].
  • Attach puts @"/Users/you/Downloads/paper.pdf" mentions in your prompt. Dismiss hides those files.
  • Waits until a file has finished downloading (skips partial downloads and files still growing), and ignores hidden and zero-byte files.
  • /downloads lists the 10 newest files, numbered. /downloads attach 1 3 (or 2-4) adds those, and /downloads clear dismisses everything new.
  • Stacks with other mods' bands (repo-brief, standing-orders, secret-guard) instead of hiding them.
  • Makes no model calls.

Settings: folder (~/Downloads), extensions, pollSeconds (5), maxAgeMinutes (120).

effort-router

Sets effort per message, so you don't have to switch it by hand.

  • Git chores ("merged", "#219 merged", "commit and push", "push it", "open a PR", "close the issue") run at low effort and come back faster.
  • Deep asks (audit, review, plan, design, investigate, root cause, "why does…", "figure out") run at max.
  • Everything else, including approvals like "yes", "go ahead" and "continue" and anything that starts new work ("merged 219, go ahead with #214"), keeps your session's own effort.
  • Prompt cache: changing effort makes the whole conversation get cached again. So it never switches mid-turn, raises effort at once, and over a large, warm cache lowers it only after 2 routine turns in a row. In small contexts, or once the cache has lapsed, it switches right away.
  • Budget cap: reads usage-meter's machine-wide summary of the last 5 hours (~/.claude/usage-meter/summary.json, at most every 30 s) and, once pct reaches budgetCapAt (80%), caps every turn at budgetCapEffort (high), deep asks included, so you stop hitting the 5-hour wall. A turn already at or below the cap is left alone; lowering over a warm cache waits like any other lowering and never happens mid-turn. A missing or stale summary (over 10 minutes old), or one with no percentage yet (no fresh API reading and no limit learned), is no budget information. The debug log gets one line when the cap engages and one when it releases. budgetCapAt: 0 turns it off.
  • Subagents: set subagentEffort (empty by default) to run every subagent request at that effort; the budget cap applies to them too (the lower of the two). Each subagent turn's effort is decided at its first request and kept for the turn.
  • Model guard: set avoidModel (a regex such as fable) to send those requests to fallbackModel instead, subagents included.
  • /route shows the last decision, the session's counts, the budget state (percent used, the cap, whether it is engaged) and the subagent effort. /route off and /route on toggle it all; /route deep and /route routine force the next turn.
  • Status line while a turn is routed: effort: low (routine); while the budget cap lowers it: effort: high (budget 84%).
  • Makes no model calls.

Settings: routineEffort (low), deepEffort (max), routinePattern, deepPattern, avoidModel, fallbackModel (opus), stickyTurns (2), freeSwitchTokens (30000), cacheTtlMinutes (60), budgetCapAt (80; 0 = off), budgetCapEffort (high), subagentEffort (empty = the session's own).

job-watch

A Jobs pane for long-running work: training runs, downloads, extractions — and three tools so Claude follows them instead of polling.

  • Picks up background Bash tasks and detached nohup … > log & launches by itself.
  • /watch <log> [label] adds any other log file.
  • Shows progress, ETA and the last log line, and flags a job as stalled when its log goes quiet; a background task's exit code is read from the end of its output.
  • Shows free space on / and /Volumes/* (the NAS).
  • Toasts when a job finishes or stalls. The status line shows jobs: 2 running · 1 stalled. A timer Claude sets for itself — sleep 600 && echo done, a loop of sleeps, or a task described as a wait, timer, pause or delay that only polls and reports with read-only programs (rg, tail, pgrep…) — is still listed by jobs_list and shown as a dim timer row, but never toasts, never counts in the status line, does not open the pane, is judged by its exit marker alone (no ps), and leaves a minute after it ends. Anything that runs a real program is a job, however it is described.
  • /jobs opens the pane, /unwatch <label|id|done|all> removes jobs.
  • Tools for Claude: jobs_list (every watched job's state, pid, progress, ETA, last-output age, exit code and log path), jobs_watch ({ pid?, log?, name?, quietMinutes? }: follow a process or log started elsewhere; it never starts commands) and jobs_unwatch ({ name }). The first message of each conversation says jobs are watched and names them, so Claude stops writing until … sleep loops and running ps. They need no permission prompt: they only read the mod's own list.
  • Makes no model calls: it reads logs with tail, checks processes with ps (one listing, or a per-pid lookup when only pids are watched), and runs df. A probe that times out or takes over 2 s is retried at a doubling interval, up to 5 minutes, until it is fast again. The debug log names a probe's pace only once it has held for two probes in a row, and at most once per five minutes per probe, so a pace that flips with the Mac's load leaves no trail.

Settings (in /config): stall minutes (10), refresh seconds (10), how long finished jobs stay (120 min; a timer leaves after a minute), auto-open (on), which disks to show.

machine-guard

Memory, swap and GPU on the status line, a machine_status tool for Claude, and a guard that refuses heavy local jobs when the Mac can't take them.

  • Status line: RAM tight 12% free · swap 7.9/8G · top python 31G · GPU 87%, and CPU 4/16 cores whenever macOS has parked the performance cores. "Free" is unused memory (vm_stat's free + inactive + speculative pages): what a new job can take without pushing anyone out. macOS's own "memory free percentage" counts active pages too, which is how a Mac can be "55% free" with the swap nearly full.
  • It reads the kernel's counters only (two sysctl calls and vm_stat), every 15 s by default; the GPU (ioreg) on every third sample, never right after a slow one. One session samples and writes ~/.claude/machine-guard/sample.json (with a lock.json while it probes); every other session shows the same numbers instead of probing too. When probes are slow or time out (10–40 s while the Mac swaps) on two samples in a row, the interval doubles, and doubles again with each further slow sample, up to 2 min; a single slow sample is a blip and changes nothing. The configured pace returns once two samples in a row are fast again. The other sessions follow the sampler's pace, so a blip stays quiet in every session.
  • Parked cores: every sample also reads kern.sched_recommended_cores, the bitmask of CPUs the scheduler may use. When macOS's performance controller parks the performance cores (after a thermal event, or stuck until a sleep/wake or reboot), the status line shows CPU 4/16 cores, machine_status and /guard report it with the parked count, you get one toast once at least half the cores have been parked for a minute, or any parking has lasted five minutes (masks blip for seconds under GPU load), and one when they come back, and Claude gets a note when it starts heavy work so it keeps worker counts small. The guard never blocks on it.
  • The process table (ps, the slowest probe) is taken only on demand (/guard, machine_status) or when a sample shows pressure, at most once a minute; "biggest" means the apps from a table taken in the last 5 minutes.
  • It refuses heavy jobs (training, inference, rendering, extraction, Blender, Docker, ffmpeg) when:
  • macOS reports critical memory pressure (kernel level 4, or under 10% free with the swap 95% full), or
  • the Mac is reserved with /busy.

When memory is only tight (under 20% free, or kernel level 2), the job runs and Claude gets a note to start one heavy job at a time.

  • machine_status is a tool Claude can call (no input, allowed without asking): the sample's age, RAM free, swap, GPU, the pressure level, the biggest apps (or how to get a table), the guard's verdict and its rules. Claude is told to use it instead of ps, top, vm_stat, memory_pressure or project scripts before launching heavy work.
  • /busy 3h training a vision model reserves the Mac in every Claude session. /busy off lifts it. The reservation lives in ~/.claude/machine-guard.json, so a training script can write it too: ``bash echo '{"reason":"overnight training","until":'$(( ($(date +%s) + 8*3600) * 1000 ))'}' > ~/.claude/machine-guard.json ``
  • /guard shows what it sees (and takes a process table when one is due). /guard pause 15m lets heavy jobs through in this session; /guard on resumes the guard.
  • Remote runs (modal run, ssh), tests (pytest) and installs are never treated as heavy.
  • Add your own heavy commands with the "Also heavy" setting (a regex), e.g. overnight_|nightly_run\.sh.

mod-monitor

Watches how the other mods behave in real use, without changing them. It is listed first in CLAUDE_CODE_PLUGIN_DIRS, so the other mods' hooks run beneath it.

  • Failures: any mod hook that throws, times out or rejects, read from the hook chain's results (next.trace), with the mod's name, the event and how long it ran. Slow hooks (over 1.5 s) are recorded too. The first failure of each mod in a session raises a toast.
  • What each mod did: its toasts ("#219 merged → …", "Blocked: …"), status-line changes, the mod commands you used (never their arguments), and failed subprocesses (a burst of 5 in 10 minutes raises a toast). Git checks run outside a repository, and rg, grep, pgrep or pkill exiting 1 with nothing on stderr (no match, no such process), are logged as expected (proc-expected, with why), not as failures; an exit of 2 or more, or anything on stderr, still counts. It also records model calls (the only usage the mods cost: /second-opinion, /recall ask) and file writes (folders only, never contents).
  • /mods: a pane with one row per mod: ✓ active, ⚠ failing, ✗ not seen this session, · seen but idle. Each row shows today's counts and last activity, with Details for its recent events. It also says which mods it can't see, if any of them run above it.
  • /mods report [24h|7d|30d]: a per-mod report across all sessions, also written to ~/.claude/mods/monitor/report-latest.md for a scheduled review or Claude to read.
  • /mods failures [7d]: failures and failed subprocesses only.
  • Logs: ~/.claude/mods/monitor/<date>/<session>.jsonl, flushed every minute and at session end, with secrets masked and old days removed after 30 days.
  • Makes no model calls and adds no measurable latency.
  • Error lines mods log themselves ($.ui.log with wording like "failed" or "could not"): shown in Details and in /mods failures. Three in an hour mark the mod ⚠ and raise one toast. That is how effort-router's per-request hook, which runs inside the response stream where no monitor should sit, reports a failure. It also always sends the request on unchanged.
  • Transcript-row hooks (secret-guard masks /secrets records there) are watched for failures and slow runs, but not counted per run.

Settings: alerts (on), slowMs (1500), watchRender (on), watchCommands (on; off stops "mod-monitor" appearing beside other mods' command output), watchAppend (on), retentionDays (30), flushSeconds (60).

modal-meter

Keeps an eye on Modal so idle GPU containers don't burn credits — in the projects that use Modal, with one CLI run per minute for the whole machine.

  • Watches a project only when it uses Modal: a .py file with import modal / from modal import … (one rg run, 5 s at most), or modal named in pyproject.toml, requirements*.txt, uv.lock or poetry.lock. The answer is remembered per project for a day. Running /modal, or any modal … command in Bash, switches it on for the session; alwaysPoll (off) watches every project.
  • One session polls for all of them: whoever holds ~/.claude/modal-meter/lock.json runs modal app list --json every pollSeconds (60) and writes cache.json; the other open sessions read the cache and refresh their own status line and pane from it. Once one session learns the CLI has no billing report, none tries it again for a day.
  • Backs off while Modal is slow: an app list over 2 s or a timeout doubles the interval (up to 10 minutes); a fast answer brings it back.
  • Status line while containers run: Modal: 1 running (2 containers). Deployed apps with no containers cost nothing, so they stay off it.
  • A toast when an app has had containers up longer than alertMinutes (30), repeated at most every 30 minutes.
  • /modal opens a pane of apps with state, containers and uptime. Stop asks for Confirm, then runs modal app stop. Nothing is stopped any other way.
  • Shows today's spend and alerts on a budgetToday where the Modal CLI supports billing report (1.3.3+, Team/Enterprise workspaces). Otherwise /modal says why spend isn't shown.
  • Finds the CLI as modal or python3 -m modal. It checks PATH first rather than running a command that can only fail, never retries one that isn't there, and stays silent when Modal isn't set up.
  • Makes no model calls: only the Modal CLI, never at session start — the first read runs in the background.

pr-autopilot

Does the "merged #219, clean up branches and start #214" round trip for you, and surfaces CI failures with their logs.

  • Watches your open PRs in the session's repo: it adopts them at session start, and picks up every gh pr create Claude runs. It polls gh pr view every 60s.
  • Status line: PRs: #219 ✓ · #220 CI… · #221 ✗, for every watched PR.
  • CI toasts only where they're wanted. A CI pass or failure (with the failing check names) toasts for the PRs this session opened (gh pr create) or you added with /prs watch, and for any PR whose branch this worktree has checked out. PRs adopted from the repository at start stay on the status line, in /prs and in prs_status, and still get the merge ritual, but their CI results don't toast — so with seven worktree sessions of one repo a result toasts once, where it matters, not seven times. toastAdoptedCi (off) brings back toasts for every watched PR.
  • When a PR merges, it cleans up with plain local git, then toasts the outcome and suggests carrying on (Tab to accept):
  • git fetch --prune, switch to the default branch (only from the PR's own branch) and git pull --ff-only.
  • Never with uncommitted changes, never --force, never other branches.
  • Deletes the local branch only if it points at exactly the commit GitHub merged, so nothing local is lost. It also leaves a branch checked out in any worktree alone.
  • In a linked worktree (git worktree add, such as Claude Code's .claude/worktrees/<name> sessions) it only fetches: it never switches or pulls there, because the default branch is checked out in the primary worktree and the switch could only fail ('main' is already used by worktree …). When the merged branch is the one the worktree has checked out, the toast says #N merged → this worktree's branch; remove the worktree when you're done (git worktree remove <path>) and the Tab suggestion tells Claude the branch and worktree stay until you remove them. In the primary worktree the ritual is unchanged.
  • A merge seen mid-turn is cleaned up when the turn ends, so git never races Claude.
  • When you mention failing CI ("#258 is failing", "CI failed, fix it"), your message goes to Claude with gh pr checks and the tail of the failed log attached, so you don't paste it.
  • Claude reads the watched PRs with a tool, prs_status (number, title, state, branch, CI, URL, and how old the data is), instead of running gh pr view or gh pr checks itself: no API call, and it refreshes first when the data is older than a poll.
  • When gh can't read the checks (a fine-grained token without "Checks: read" — the cause of Resource not accessible by personal access token), it tells you once with the fix (gh auth login --web, or grant the token "Checks: read"), keeps polling the PRs without their checks so merges are still handled, shows them as #219 CI?, and tries the checks again after 30 minutes or when you run /prs. If gh can't read PRs at all (not logged in), the status line says PRs: gh can't read them and nothing is polled until then. A GitHub rate limit pauses polling for 5 minutes; any other failure doubles the wait up to 10 minutes, back to normal on the next success. Nothing retries every minute forever; the debug log gets one line per change.
  • /prs lists watched PRs and asks gh again at once. /prs watch <n|url> and /prs forget <n|all> add and remove them.
  • Makes no model calls: only gh and git, at about one GitHub API call per open PR per minute.

Settings:

  • pollSeconds (60)
  • authRetryMinutes (30): how long before the checks are tried again after gh refused them over auth.
  • attachCiLogs (on)
  • logLines (120)
  • deleteRemoteBranch (off): deletes the branch on GitHub too, only while it still points at the merged commit. GitHub's own "Automatically delete head branches" setting does the same job.
  • toastAdoptedCi (off): toast the CI results of PRs adopted from the repository too, as every PR's used to; with several worktree sessions of one repo, each would toast.

It never closes issues; put "Closes #N" in PR bodies for that.

recall

Search everything you've done with coding agents, from Claude or from /recall. It replaces the broken agent-memory plugin.

  • What it searches: Claude Code sessions, Codex sessions, subagent and workflow runs, Claude's memory files, standing orders, second-opinion reviews, and your /remember notes. Routine (scheduled) runs are left out unless you add routines:include to a query.
  • What it keeps: prompts, answers, compaction summaries, session titles, commands, files touched, commits, PRs, issues, URLs, tasks and decisions (what you approved or ruled out). Read-only look-ups like grep and cat are kept but ranked low.
  • History survives cleanup: extracts stay searchable after Claude Code deletes old transcripts.
  • Claude searches it itself with four read-only tools, search, expand, recap and list, which run without permission prompts. It checks them when you say "like last time" or "what did we decide", and before asking you something you already settled.
  • The ledger survives compaction: as a session goes, recall keeps what it has settled — your /goal (or the Stop hook's condition), open tasks with a count of the done ones, the questions you asked with the first line of each answer, the files touched, the commits made and PRs opened. After a compaction it goes back into Claude's context as Ledger (this session, before compaction) (about 40 lines at most), so you don't have to say "don't lose track of where we were". /recall ledger prints it any time; /clear starts a fresh one. It is written to ~/.claude/recall/ledger/<session>.json (readable only by you, secrets masked) so a reload keeps it.
  • Commands:
  • /recall <query> opens a pane of hits grouped by session. Open shows the conversation around a hit, Attach sends it with your next message, and Copy resume command copies claude --resume <id>.
  • /recall last [n] recaps your last session in this repo: last asks, last answer, PRs, commits, open tasks and decisions. Send to Claude attaches it.
  • /recall ledger prints this session's ledger (above).
  • /recall timeline [7d|30d|90d] [all]
  • /recall decisions|commands|files|prs|commits|issues|urls|tasks|notes [query]
  • /recall ask <question> answers from your history with Haiku 4.5, citing sessions. It costs a little usage and sends the matching excerpts to the model.
  • /recall stats, /recall reindex, /recall forget session <id>|project <name>|before <date> (asks you to confirm), /recall help.
  • /remember <fact>, /remember list, /remember forget <ref>.
  • Bands:
  • Once per session: Last session here (2d ago): "…" · PR #99 · 3 open tasks [Recap].
  • When a prompt mentions #214, ABC-12, a file name or a quoted phrase seen in past sessions, a band offers what happened then. Nothing is sent unless you click.
  • Query syntax: words must all match. OR gives alternatives, "quotes" an exact phrase, and -word excludes. Filters: project:name, kind:decision, since:7d, until:2026-09-30, source:codex, routines:include.
  • Privacy:
  • The index lives at ~/.claude/recall/index.db, readable only by you, and never goes in a repo. The ledgers beside it are kept the same way.
  • Secrets are masked before anything is stored: known token shapes, labelled values ("password: …"), the values of secret-named exports in ~/.zshrc, ~/.zprofile, ~/.bashrc and `~/.bash_profile
Source 3 files
hooks/register.tsx 315 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Snapshot } from '../types'
5import {
6  ISSUE_LIMIT,
7  PR_LIMIT,
8  bandParts,
9  branchNames,
10  countWorktrees,
11  emptySnapshot,
12  goneBranches,
13  isBlankTree,
14  isGhAuthFailure,
15  isGitHubRemote,
16  parseFocusLabels,
17  parseIssues,
18  parseLog,
19  parsePrs,
20  parseStatus,
21  pickDefaultBranch,
22  summary,
23} from './brief'
24import type { BandPart } from './brief'
25
26type Engine = EngineInterface
27
28/** The name the brief renders under in the first message's context. */
29const BLOCK = 'repoBrief'
30
31const snapshot = atom({ plugin: 'repo-brief', key: 'snapshot' } as const, null)
32const isHidden = atom({ plugin: 'repo-brief', key: 'isHidden' } as const, false)
33
34/** How long each git and gh command may take: a background gather, and one the first message waits on. */
35type Timing = { gitMs: number; ghMs: number }
36const FULL: Timing = { gitMs: 10_000, ghMs: 15_000 }
37const QUICK: Timing = { gitMs: 3_000, ghMs: 5_000 }
38/** The longest the first message waits for a gather still under way. */
39const BRIEF_WAIT_MS = 5_000
40/** How long a gh list refused over auth is not asked again in this session. */
41const AUTH_HOLD_MS = 30 * 60_000
42
43const LEAD_START =
44  'Repo state when this session started (gathered by the repo-brief mod; run git yourself for anything newer):'
45const LEAD_LATER =
46  'Repo state at its last refresh (gathered by the repo-brief mod; run git yourself for anything newer):'
47const LEAD_NOW = 'Repo state just now (gathered by the repo-brief mod):'
48
49type Config = { focusLabels: string[]; refreshMs: number; briefClaude: boolean }
50
51/** Until when each gh list is not asked again (ms) after it was refused over auth; 0 while it is asked. */
52type GhHeld = { prs: number; issues: number }
53
54let config: Config = { focusLabels: ['owner', 'todo', 'P0', 'blocked'], refreshMs: 120_000, briefClaude: true }
55let inflight: Promise<Snapshot | null> | null = null
56let lastGatherAt = 0
57let hasBriefed = false
58let ghHeld: GhHeld = { prs: 0, issues: 0 }
59
60type GitHub = Pick<Snapshot, 'ghOk' | 'prsDenied' | 'prs' | 'issueCount' | 'focusIssues'>
61
62const NO_GITHUB: GitHub = { ghOk: false, prsDenied: false, prs: [], issueCount: 0, focusIssues: [] }
63
64/** A command's stdout, or null when it could not start, timed out or exited non-zero. */
65async function run($: Engine, cwd: string, argv: readonly string[], timeoutMs: number): Promise<string | null> {
66  const out = await $.process.run(argv, { cwd, timeoutMs }).catch(() => null)
67  return out && out.exitCode === 0 ? out.stdout : null
68}
69
70/** One gh list's stdout, or null and whether gh refused it over auth. */
71type Listed = { out: string | null; isDenied: boolean }
72/** Where and how a gh list is asked: the folder, how long it may take, and the time now. */
73type Ask = { cwd: string; timeoutMs: number; now: number }
74
75/**
76 * A gh list's stdout, or null when it could not start, timed out, exited non-zero or is held: a list
77 * refused over auth (a token that may not read it, no login) is expected and quiet, so it is not asked
78 * again for AUTH_HOLD_MS in this session; /brief asks anyway.
79 */
80async function ghList($: Engine, ask: Ask, kind: keyof GhHeld, argv: readonly string[]): Promise<Listed> {
81  if (ask.now < ghHeld[kind]) {
82    return { out: null, isDenied: true }
83  }
84  const ran = await $.process.run(argv, { cwd: ask.cwd, timeoutMs: ask.timeoutMs }).catch(() => null)
85  if (ran && ran.exitCode === 0) {
86    return { out: ran.stdout, isDenied: false }
87  }
88  const isDenied = ran !== null && isGhAuthFailure(ran.stdout, ran.stderr)
89  if (isDenied) {
90    ghHeld[kind] = ask.now + AUTH_HOLD_MS
91  }
92  return { out: null, isDenied }
93}
94
95async function gatherGitHub($: Engine, cwd: string, timing: Timing, now: number): Promise<GitHub> {
96  const ask: Ask = { cwd, timeoutMs: timing.ghMs, now }
97  const [prList, issueList] = await Promise.all([
98    ghList($, ask, 'prs', [
99      'gh',
100      'pr',
101      'list',
102      '--state',
103      'open',
104      '--limit',
105      String(PR_LIMIT),
106      '--json',
107      'number,title,headRefName,isDraft,statusCheckRollup',
108    ]),
109    ghList($, ask, 'issues', ['gh', 'issue', 'list', '--state', 'open', '--limit', String(ISSUE_LIMIT), '--json', 'number,title,labels']),
110  ])
111  const prs = prList.out === null ? null : parsePrs(prList.out)
112  if (prs === null && !prList.isDenied) {
113    return NO_GITHUB
114  }
115  const issues = issueList.out === null ? null : parseIssues(issueList.out, config.focusLabels)
116  return {
117    ghOk: prs !== null || issues !== null,
118    prsDenied: prList.isDenied,
119    prs: prs ?? [],
120    issueCount: issues?.count ?? 0,
121    focusIssues: issues?.focus ?? [],
122  }
123}
124
125async function collect($: Engine, timing: Timing): Promise<Snapshot | null> {
126  const previous = await read($, snapshot)
127  const cwd = await $.session.cwd()
128  const now = await $.clock.now()
129  lastGatherAt = now
130  const git = (...args: string[]) => run($, cwd, ['git', ...args], timing.gitMs)
131
132  const status = await $.process
133    .run(['git', '--no-optional-locks', 'status', '--porcelain=v1', '--branch'], { cwd, timeoutMs: timing.gitMs })
134    .catch(() => null)
135  if (status === null && previous !== null) {
136    return previous
137  }
138  if (status === null || status.exitCode !== 0) {
139    const outside = emptySnapshot(now)
140    await update($, snapshot, () => outside)
141    return outside
142  }
143
144  const parsed = parseStatus(status.stdout)
145  const [log, branchVv, refs, worktreeList, remote] = await Promise.all([
146    git('log', '-8', '--format=%h%x09%cr%x09%an%x09%s'),
147    git('branch', '-vv'),
148    // origin/HEAD (a symref, its target beside it) and the branches that stand in for it, in one read that never fails.
149    git(
150      'for-each-ref',
151      '--format=%(refname)%09%(symref)',
152      'refs/remotes/origin/HEAD',
153      'refs/remotes/origin/main',
154      'refs/remotes/origin/master',
155      'refs/heads/main',
156      'refs/heads/master',
157    ),
158    git('worktree', 'list', '--porcelain'),
159    git('remote', 'get-url', 'origin'),
160  ])
161  const defaultBranch = pickDefaultBranch(refs, parsed.branch)
162  const [merged, github] = await Promise.all([
163    defaultBranch ? git('branch', '--merged', defaultBranch) : Promise.resolve(null),
164    isGitHubRemote(remote) ? gatherGitHub($, cwd, timing, now) : Promise.resolve(NO_GITHUB),
165  ])
166
167  const defaultName = defaultBranch?.replace(/^origin\//, '') ?? ''
168  const gone = goneBranches(branchVv ?? '').filter(name => name !== parsed.branch)
169  const stale = [...new Set([...gone, ...branchNames(merged ?? '', [defaultName])])]
170  const fresh: Snapshot = {
171    ...emptySnapshot(now, true),
172    ...parsed,
173    commits: parseLog(log ?? ''),
174    defaultBranch,
175    staleBranches: stale,
176    worktrees: countWorktrees(worktreeList ?? ''),
177    ...github,
178  }
179  await update($, snapshot, () => fresh)
180  return fresh
181}
182
183/** Gathers the repo's state into `snapshot`; a gather already under way is shared, not repeated. */
184function gather($: Engine, timing: Timing): Promise<Snapshot | null> {
185  if (!inflight) {
186    inflight = collect($, timing)
187      .catch(() => null)
188      .finally(() => {
189        inflight = null
190      })
191  }
192  return inflight
193}
194
195/** What `work` resolves to, or null once `ms` has passed first. */
196async function within<T>($: Engine, work: Promise<T>, ms: number): Promise<T | null> {
197  const stop = new AbortController()
198  const timeout = $.clock.sleep(ms, { signal: stop.signal }).then(
199    () => null,
200    () => null,
201  )
202  try {
203    return await Promise.race([work, timeout])
204  } finally {
205    stop.abort()
206  }
207}
208
209/** Starts a background gather when the last one is older than `refreshMinutes`. */
210async function refreshIfStale($: Engine) {
211  const now = await $.clock.now()
212  if (!inflight && now - lastGatherAt >= config.refreshMs) {
213    void gather($, FULL)
214  }
215}
216
217export const register: Register = (on, options) => {
218  const minutes = Number(options.refreshMinutes ?? 2)
219  config = {
220    focusLabels: parseFocusLabels(String(options.focusLabels ?? 'owner,todo,P0,blocked')),
221    refreshMs: Math.max(0.25, Number.isFinite(minutes) ? minutes : 2) * 60_000,
222    briefClaude: options.briefClaude !== false,
223  }
224  inflight = null
225  lastGatherAt = 0
226  hasBriefed = false
227  ghHeld = { prs: 0, issues: 0 }
228
229  // The gather is started, not awaited: the first message reads the snapshot if it is ready, else waits
230  // for a quick one up to BRIEF_WAIT_MS (prompt.context), and the band draws once it lands.
231  on('session.start', async ($, e, next) => {
232    await $.command.register({
233      name: 'brief',
234      description: 'Re-gather the repo brief (branch, uncommitted work, commits, PRs, focus issues) and show it',
235    })
236    void gather($, FULL)
237    return next(e)
238  })
239
240  on('prompt.context', async ($, e, next) => {
241    const result = await next(e)
242    if (!config.briefClaude) {
243      return result
244    }
245    const known = await read($, snapshot)
246    const current = known ?? (await within($, gather($, QUICK), BRIEF_WAIT_MS))
247    if (!current?.isRepo) {
248      return result
249    }
250    const text = summary(current, hasBriefed ? LEAD_LATER : LEAD_START, config.focusLabels)
251    hasBriefed = true
252    return { ...result, blocks: [...result.blocks.filter(block => block.name !== BLOCK), { name: BLOCK, text }] }
253  })
254
255  on('turn.complete', async ($, e, next) => {
256    await refreshIfStale($)
257    return next(e)
258  })
259
260  // Started before the compaction runs, so the context re-read after it finds a fresh snapshot.
261  on('session.compact', async ($, e, next) => {
262    await refreshIfStale($)
263    return next(e)
264  })
265
266  on('command.run', { command: 'brief' }, async $ => {
267    if (inflight) {
268      await inflight
269    }
270    // Asked for by the person: gh is asked again, hold or not.
271    ghHeld = { prs: 0, issues: 0 }
272    const current = await gather($, FULL)
273    await update($, isHidden, () => false)
274    if (current === null) {
275      return { text: 'repo-brief: git did not answer, so the repo could not be read.' }
276    }
277    if (!current.isRepo) {
278      return { text: `repo-brief: ${await $.session.cwd()} is not inside a git repository.` }
279    }
280    return { text: summary(current, LEAD_NOW, config.focusLabels) }
281  })
282
283  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
284    const current = await read($, snapshot)
285    const hidden = await read($, isHidden)
286    if (e.props.hasSurvey || hidden || !current?.isRepo) {
287      return next(e)
288    }
289    const { Box, Text, Button } = $.ui.resolve(e)
290    const span = (part: BandPart) =>
291      part.color ? <Text color={part.color}>{part.text}</Text> : part.dim ? <Text dimColor>{part.text}</Text> : part.text
292
293    const band = (
294      <Box flexDirection="row" gap={1}>
295        <Box flexShrink={1}>
296          <Text wrap="truncate-end">{bandParts(current, config.focusLabels).map(span)}</Text>
297        </Box>
298        <Box flexShrink={0}>
299          <Button key="hide" label="Hide" plain dimColor onPress={() => update($, isHidden, () => true)} />
300        </Box>
301      </Box>
302    )
303    // Another plugin's band beneath stays, under this one.
304    const below = await next(e)
305    return isBlankTree(below) ? (
306      band
307    ) : (
308      <Box flexDirection="column">
309        {band}
310        {below}
311      </Box>
312    )
313  })
314}
315
hooks/brief.ts 448 lines
1import type { RenderElement } from 'claude-code'
2import type { Changed, Ci, Commit, FocusIssue, PullRequest, Snapshot } from '../types'
3
4/** How many changed files a snapshot keeps by name. */
5export const MAX_PATHS = 15
6/** How many open PRs and issues `gh` is asked for. */
7export const PR_LIMIT = 10
8export const ISSUE_LIMIT = 30
9/** The longest brief Claude is handed, in characters. */
10export const MAX_BRIEF = 2500
11
12const clip = (text: string, max: number): string => (text.length <= max ? text : `${text.slice(0, max - 1)}…`)
13
14const plural = (count: number, one: string, many = `${one}s`): string => `${count} ${count === 1 ? one : many}`
15
16/** A snapshot with nothing in it: what a folder outside any git work tree gets. */
17export const emptySnapshot = (at: number, isRepo = false): Snapshot => ({
18  at,
19  isRepo,
20  branch: null,
21  upstream: null,
22  isUpstreamGone: false,
23  ahead: 0,
24  behind: 0,
25  changed: { staged: 0, unstaged: 0, untracked: 0, conflicted: 0, total: 0 },
26  changedPaths: [],
27  commits: [],
28  defaultBranch: null,
29  staleBranches: [],
30  worktrees: 0,
31  ghOk: false,
32  prsDenied: false,
33  prs: [],
34  issueCount: 0,
35  focusIssues: [],
36})
37
38export const parseFocusLabels = (text: string): string[] =>
39  text
40    .split(',')
41    .map(label => label.trim())
42    .filter(Boolean)
43
44export type Status = {
45  branch: string | null
46  upstream: string | null
47  isUpstreamGone: boolean
48  ahead: number
49  behind: number
50  changed: Changed
51  changedPaths: string[]
52}
53
54const CONFLICTS = new Set(['DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'])
55
56/**
57 * `git status --porcelain=v1 --branch`: the `## branch...upstream [ahead 1, behind 2]`
58 * header, then one `XY path` line per changed file.
59 */
60export const parseStatus = (output: string): Status => {
61  const lines = output.split('\n').filter(line => line.length > 0)
62  const header = lines[0]?.startsWith('## ') ? (lines.shift() ?? '').slice(3) : ''
63  let branch: string | null = null
64  let upstream: string | null = null
65  let isUpstreamGone = false
66  let ahead = 0
67  let behind = 0
68  const fresh = header.match(/^(?:No commits yet on|Initial commit on) (\S+)/)
69  if (fresh) {
70    branch = fresh[1] ?? null
71  } else if (header && !header.startsWith('HEAD (no branch)')) {
72    const found = header.match(/^(\S+?)(?:\.\.\.(\S+))?(?: \[(.+)\])?$/)
73    branch = found?.[1] ?? null
74    upstream = found?.[2] ?? null
75    const tracking = found?.[3] ?? ''
76    isUpstreamGone = tracking === 'gone'
77    ahead = Number(tracking.match(/ahead (\d+)/)?.[1] ?? 0)
78    behind = Number(tracking.match(/behind (\d+)/)?.[1] ?? 0)
79  }
80
81  const changed: Changed = { staged: 0, unstaged: 0, untracked: 0, conflicted: 0, total: 0 }
82  const changedPaths: string[] = []
83  for (const line of lines) {
84    const code = line.slice(0, 2)
85    if (code === '!!') {
86      continue
87    }
88    changed.total += 1
89    if (code === '??') {
90      changed.untracked += 1
91    } else if (CONFLICTS.has(code)) {
92      changed.conflicted += 1
93    } else {
94      if (code[0] !== ' ') {
95        changed.staged += 1
96      }
97      if (code[1] !== ' ') {
98        changed.unstaged += 1
99      }
100    }
101    if (changedPaths.length < MAX_PATHS) {
102      changedPaths.push(line)
103    }
104  }
105  return { branch, upstream, isUpstreamGone, ahead, behind, changed, changedPaths }
106}
107
108/** `git log --format=%h%x09%cr%x09%an%x09%s`: one commit per line. */
109export const parseLog = (output: string): Commit[] =>
110  output
111    .split('\n')
112    .map(line => line.split('\t'))
113    .filter(fields => fields.length >= 4 && fields[0])
114    .map(([sha = '', when = '', author = '', ...subject]) => ({ sha, when, author, subject: subject.join('\t') }))
115
116/** Local branches `git branch -vv` shows tracking an upstream that no longer exists (`[origin/x: gone]`). */
117export const goneBranches = (output: string): string[] =>
118  output
119    .split('\n')
120    .map(line => line.slice(2).match(/^([^\s(]\S*)\s+[0-9a-f]{4,}\s+(?:\([^)]*\)\s+)?\[[^\]]*: gone\]/)?.[1])
121    .filter((name): name is string => Boolean(name))
122
123/**
124 * Branch names from `git branch` output, leaving out the checked-out one (`* `), any checked
125 * out in another worktree (`+ `, work in use), a detached HEAD and the names in `exclude`.
126 */
127export const branchNames = (output: string, exclude: readonly string[]): string[] =>
128  output
129    .split('\n')
130    .filter(line => line.startsWith('  '))
131    .map(line => line.trim())
132    .filter(name => name.length > 0 && !name.startsWith('(') && !exclude.includes(name))
133
134/** `refs/remotes/origin/main` as `origin/main`, `refs/heads/main` as `main`. */
135const shortRef = (ref: string): string => ref.replace(/^refs\/(?:remotes|heads)\//, '')
136
137/** The branches that stand in for an unset origin/HEAD, in order. */
138const STAND_INS = ['refs/remotes/origin/main', 'refs/remotes/origin/master', 'refs/heads/main', 'refs/heads/master']
139
140/**
141 * The default branch to check merges against, from one `git for-each-ref --format=%(refname)%09%(symref)`
142 * read over origin/HEAD and its stand-ins (a read that never fails): what origin/HEAD points to when
143 * it is set (a clone made without it has none), else the first of origin/main, origin/master, main,
144 * master that exists, else the branch checked out now (null on a detached HEAD).
145 */
146export const pickDefaultBranch = (refs: string | null, currentBranch: string | null): string | null => {
147  const rows = (refs ?? '').split('\n').map(line => line.split('\t'))
148  const head = rows.find(([name, target]) => name === 'refs/remotes/origin/HEAD' && target)
149  if (head?.[1]) {
150    return shortRef(head[1])
151  }
152  const names = new Set(rows.map(([name]) => name ?? ''))
153  const found = STAND_INS.find(ref => names.has(ref))
154  return found ? shortRef(found) : currentBranch
155}
156
157/** Linked worktrees besides the main one, from `git worktree list --porcelain`. */
158export const countWorktrees = (output: string): number =>
159  Math.max(0, output.split('\n').filter(line => line.startsWith('worktree ')).length - 1)
160
161export const isGitHubRemote = (url: string | null): boolean => /github\.com[:/]/i.test(url ?? '')
162
163const GH_AUTH_FAILURE =
164  /Resource not accessible by (?:personal access token|integration)|Requires authentication|HTTP 40[13]\b|not logged into|gh auth login|Bad credentials/i
165const GH_RATE_LIMIT = /rate limit/i
166
167/**
168 * True when gh failed over its login or its token's permissions (a fine-grained PAT lacking
169 * "Checks: read" cannot read statusCheckRollup): expected, and not worth asking again soon. A rate
170 * limit comes as an HTTP 403 too, and is not one.
171 */
172export const isGhAuthFailure = (stdout: string, stderr: string): boolean => {
173  const said = `${stderr}\n${stdout}`
174  return !GH_RATE_LIMIT.test(said) && GH_AUTH_FAILURE.test(said)
175}
176
177type Check = { status?: string | null; conclusion?: string | null; state?: string | null }
178
179const FAILED = new Set(['FAILURE', 'TIMED_OUT', 'CANCELLED', 'ERROR', 'STARTUP_FAILURE'])
180const WAITING = new Set(['PENDING', 'EXPECTED', 'QUEUED', 'IN_PROGRESS', 'WAITING', 'REQUESTED'])
181
182/** A PR's `statusCheckRollup` (CheckRuns and StatusContexts) as one mark: ✗ any failed, … any pending, ✓ the rest. */
183export const ciOf = (rollup: readonly Check[] | null | undefined): Ci => {
184  const checks = rollup ?? []
185  if (checks.length === 0) {
186    return ''
187  }
188  const outcome = (check: Check): string => (check.conclusion || check.state || '').toUpperCase()
189  if (checks.some(check => FAILED.has(outcome(check)))) {
190    return '✗'
191  }
192  const isPending = (check: Check): boolean => {
193    const status = (check.status ?? '').toUpperCase()
194    return (status !== '' && status !== 'COMPLETED') || WAITING.has(outcome(check)) || outcome(check) === ''
195  }
196  return checks.some(isPending) ? '…' : '✓'
197}
198
199const parseJson = (text: string): unknown => {
200  try {
201    return JSON.parse(text) as unknown
202  } catch {
203    return null
204  }
205}
206
207type RawPr = { number?: number; title?: string; headRefName?: string; isDraft?: boolean; statusCheckRollup?: Check[] }
208
209/** `gh pr list --json number,title,headRefName,isDraft,statusCheckRollup`; null when it is not that. */
210export const parsePrs = (json: string): PullRequest[] | null => {
211  const list = parseJson(json)
212  if (!Array.isArray(list)) {
213    return null
214  }
215  return (list as RawPr[])
216    .filter(pr => typeof pr.number === 'number')
217    .map(pr => ({
218      number: pr.number ?? 0,
219      title: pr.title ?? '',
220      branch: pr.headRefName ?? '',
221      ci: ciOf(pr.statusCheckRollup),
222      isDraft: pr.isDraft === true,
223    }))
224}
225
226type RawIssue = { number?: number; title?: string; labels?: { name?: string }[] }
227
228/** `gh issue list --json number,title,labels`: how many, and those carrying a focus label. */
229export const parseIssues = (
230  json: string,
231  focusLabels: readonly string[],
232): { count: number; focus: FocusIssue[] } | null => {
233  const list = parseJson(json)
234  if (!Array.isArray(list)) {
235    return null
236  }
237  const wanted = new Set(focusLabels.map(label => label.toLowerCase()))
238  const issues = (list as RawIssue[])
239    .filter(issue => typeof issue.number === 'number')
240    .map(issue => ({
241      number: issue.number ?? 0,
242      title: issue.title ?? '',
243      labels: (issue.labels ?? []).map(label => label.name ?? '').filter(Boolean),
244    }))
245  return { count: issues.length, focus: issues.filter(issue => issue.labels.some(label => wanted.has(label.toLowerCase()))) }
246}
247
248const AGO_UNITS: Record<string, string> = {
249  second: 's',
250  minute: 'm',
251  hour: 'h',
252  day: 'd',
253  week: 'w',
254  month: 'mo',
255  year: 'y',
256}
257
258/** `%cr`'s "2 hours ago" as "2h ago"; "2 years, 3 months ago" keeps its first unit. */
259export const shortAgo = (when: string): string => {
260  const found = when.match(/^(\d+) (second|minute|hour|day|week|month|year)s?\b/)
261  return found ? `${found[1]}${AGO_UNITS[found[2] ?? ''] ?? ''} ago` : when
262}
263
264/** The issues' first matching focus label, in the configured order, for the band's count. */
265const focusWord = (issues: readonly FocusIssue[], focusLabels: readonly string[]): string => {
266  const firstLabel = (issue: FocusIssue) =>
267    focusLabels.find(label => issue.labels.some(own => own.toLowerCase() === label.toLowerCase())) ?? 'focus'
268  const words = new Set(issues.map(firstLabel))
269  return words.size === 1 ? ([...words][0] ?? 'focus') : 'focus'
270}
271
272const ciWord: Record<Ci, string> = { '✓': 'CI passing', '✗': 'CI failing', '…': 'CI running', '': 'no CI' }
273
274type Limits = { paths: number; commits: number; prs: number; issues: number; stale: number }
275
276/** Each step lists fewer of everything, until the brief fits MAX_BRIEF. */
277const LIMITS: readonly Limits[] = [
278  { paths: 15, commits: 8, prs: 10, issues: 10, stale: 12 },
279  { paths: 8, commits: 6, prs: 6, issues: 6, stale: 6 },
280  { paths: 4, commits: 4, prs: 3, issues: 3, stale: 3 },
281]
282
283const more = (shown: number, total: number): string[] => (total > shown ? [`  … and ${total - shown} more`] : [])
284
285const branchLine = (s: Snapshot): string => {
286  if (s.branch === null) {
287    return `Branch: none, HEAD is detached${s.commits[0] ? ` at ${s.commits[0].sha}` : ''}`
288  }
289  if (s.upstream === null) {
290    return `Branch: ${s.branch} (no upstream: not pushed or not tracking)`
291  }
292  if (s.isUpstreamGone) {
293    return `Branch: ${s.branch}, its upstream ${s.upstream} is gone (deleted on the remote)`
294  }
295  const drift = [s.ahead > 0 && `ahead ${s.ahead}`, s.behind > 0 && `behind ${s.behind}`].filter(Boolean)
296  return `Branch: ${s.branch} tracking ${s.upstream}, ${drift.length > 0 ? drift.join(', ') : 'up to date'}`
297}
298
299const changedLine = (changed: Changed): string => {
300  if (changed.total === 0) {
301    return 'Working tree: clean'
302  }
303  const kinds = [
304    changed.staged > 0 && `${changed.staged} staged`,
305    changed.unstaged > 0 && `${changed.unstaged} unstaged`,
306    changed.untracked > 0 && `${changed.untracked} untracked`,
307    changed.conflicted > 0 && `${changed.conflicted} conflicted`,
308  ].filter(Boolean)
309  return `Uncommitted: ${plural(changed.total, 'file')} (${kinds.join(', ')})`
310}
311
312const briefWith = (s: Snapshot, lead: string, focusLabels: readonly string[], limits: Limits): string => {
313  const lines = [lead, branchLine(s), changedLine(s.changed)]
314  const paths = s.changedPaths.slice(0, limits.paths)
315  lines.push(...paths.map(path => `  ${clip(path, 90)}`), ...more(paths.length, s.changed.total))
316
317  if (s.commits.length > 0) {
318    lines.push('Recent commits:')
319    lines.push(
320      ...s.commits
321        .slice(0, limits.commits)
322        .map(commit => `  ${commit.sha} ${commit.when}, ${clip(commit.author, 20)}: ${clip(commit.subject, 72)}`),
323    )
324  }
325
326  if (s.prsDenied) {
327    lines.push("PRs: gh token can't read them")
328  } else if (s.ghOk) {
329    if (s.prs.length === 0) {
330      lines.push('Open PRs: none')
331    } else {
332      lines.push(`Open PRs (${s.prs.length}${s.prs.length >= PR_LIMIT ? '+' : ''}):`)
333      const prs = s.prs.slice(0, limits.prs)
334      lines.push(
335        ...prs.map(
336          pr =>
337            `  #${pr.number} ${pr.ci ? `${pr.ci} ` : ''}${ciWord[pr.ci]}: ${clip(pr.title, 70)} (${clip(pr.branch, 40)}${pr.isDraft ? ', draft' : ''})`,
338        ),
339        ...more(prs.length, s.prs.length),
340      )
341    }
342  }
343  if (s.ghOk) {
344    const count = `${s.issueCount}${s.issueCount >= ISSUE_LIMIT ? '+' : ''}`
345    const labels = focusLabels.join(', ')
346    if (s.focusIssues.length === 0) {
347      lines.push(`Open issues: ${count}${labels ? `, none labelled ${labels}` : ''}`)
348    } else {
349      lines.push(`Open issues: ${count}; labelled ${labels} (${s.focusIssues.length}):`)
350      const issues = s.focusIssues.slice(0, limits.issues)
351      lines.push(
352        ...issues.map(issue => `  #${issue.number} ${clip(issue.title, 70)} [${issue.labels.join(', ')}]`),
353        ...more(issues.length, s.focusIssues.length),
354      )
355    }
356  } else if (!s.prsDenied) {
357    lines.push('PRs and issues: not gathered (gh unavailable, or the remote is not GitHub)')
358  }
359
360  if (s.staleBranches.length > 0) {
361    const shown = s.staleBranches.slice(0, limits.stale)
362    const rest = s.staleBranches.length - shown.length
363    lines.push(
364      `Stale local branches (${s.staleBranches.length}; upstream gone or merged into ${s.defaultBranch ?? 'the default branch'}): ` +
365        shown.map(name => clip(name, 40)).join(', ') +
366        (rest > 0 ? `, +${rest} more` : ''),
367    )
368  }
369  if (s.worktrees > 0) {
370    lines.push(`Worktrees: ${s.worktrees} besides the main one`)
371  }
372  return lines.join('\n')
373}
374
375/** The plain-text brief: branch, uncommitted work, commits, PRs, focus issues, stale branches, under MAX_BRIEF. */
376export const summary = (s: Snapshot, lead: string, focusLabels: readonly string[]): string => {
377  let text = ''
378  for (const limits of LIMITS) {
379    text = briefWith(s, lead, focusLabels, limits)
380    if (text.length <= MAX_BRIEF) {
381      return text
382    }
383  }
384  return `${text.slice(0, text.lastIndexOf('\n', MAX_BRIEF - 2))}\n…`
385}
386
387export type BandPart = { text: string; color?: 'red' | 'yellow' | 'green'; dim?: boolean }
388
389const CI_COLOR: Record<Ci, BandPart['color']> = { '✗': 'red', '…': 'yellow', '✓': 'green', '': undefined }
390
391/** The band's one line, in pieces so the CI marks can be colored. */
392export const bandParts = (s: Snapshot, focusLabels: readonly string[]): BandPart[] => {
393  const groups: BandPart[][] = []
394
395  let head = s.branch ?? `HEAD@${s.commits[0]?.sha ?? 'detached'}`
396  if (s.branch !== null && s.upstream === null) {
397    head += ' (no upstream)'
398  } else if (s.isUpstreamGone) {
399    head += ' (upstream gone)'
400  }
401  head += `${s.ahead > 0 ? ` ↑${s.ahead}` : ''}${s.behind > 0 ? ` ↓${s.behind}` : ''}`
402  groups.push([{ text: head }])
403
404  groups.push([{ text: s.changed.total > 0 ? `${s.changed.total} changed` : 'clean' }])
405  if (s.changed.conflicted > 0) {
406    groups.push([{ text: `${s.changed.conflicted} conflicted`, color: 'red' }])
407  }
408
409  if (s.ghOk && s.prs.length > 0) {
410    const shown = s.prs.slice(0, 4)
411    const prs: BandPart[] = [{ text: 'PRs' }]
412    for (const pr of shown) {
413      prs.push({ text: ` #${pr.number}` })
414      if (pr.ci) {
415        prs.push({ text: ` ${pr.ci}`, color: CI_COLOR[pr.ci] })
416      }
417    }
418    if (s.prs.length > shown.length) {
419      prs.push({ text: ` +${s.prs.length - shown.length}` })
420    }
421    groups.push(prs)
422  }
423  if (s.ghOk && s.focusIssues.length > 0) {
424    groups.push([{ text: plural(s.focusIssues.length, `${focusWord(s.focusIssues, focusLabels)} issue`) }])
425  }
426  if (s.staleBranches.length > 0) {
427    groups.push([{ text: plural(s.staleBranches.length, 'stale branch', 'stale branches') }])
428  }
429  if (s.worktrees > 0) {
430    groups.push([{ text: plural(s.worktrees, 'worktree') }])
431  }
432  if (s.commits[0]) {
433    groups.push([{ text: `last commit ${shortAgo(s.commits[0].when)}` }])
434  }
435
436  return groups.flatMap((group, index) => (index === 0 ? group : [{ text: ' · ', dim: true }, ...group]))
437}
438
439export const bandLine = (parts: readonly BandPart[]): string => parts.map(part => part.text).join('')
440
441/** True for what the engine draws when no plugin draws the band, or an empty Box. */
442export function isBlankTree(tree: RenderElement): boolean {
443  if (tree.type === 'engine') {
444    return true
445  }
446  return tree.type === 'Box' && (tree.children ?? []).length === 0
447}
448
types/index.d.ts 49 lines
1/** A PR's checks summed up: any failed ✗, any still running …, all passed ✓, none at all ''. */
2export type Ci = '✓' | '✗' | '…' | ''
3
4export type Commit = { sha: string; when: string; author: string; subject: string }
5
6export type PullRequest = { number: number; title: string; branch: string; ci: Ci; isDraft: boolean }
7
8export type FocusIssue = { number: number; title: string; labels: string[] }
9
10/** Files `git status` lists, by kind; a file both staged and edited again counts in both. */
11export type Changed = { staged: number; unstaged: number; untracked: number; conflicted: number; total: number }
12
13export type Snapshot = {
14  at: number
15  /** False when the session's folder is not inside a git work tree: nothing else is gathered. */
16  isRepo: boolean
17  /** The checked-out branch; null when HEAD is detached. */
18  branch: string | null
19  /** The branch's upstream (`origin/main`); null when it has none. */
20  upstream: string | null
21  /** True when the upstream is configured but its remote branch was deleted. */
22  isUpstreamGone: boolean
23  ahead: number
24  behind: number
25  changed: Changed
26  /** The first changed files as `git status --porcelain` shows them (`XY path`). */
27  changedPaths: string[]
28  commits: Commit[]
29  /** The default branch the merged check ran against (`origin/main`); null when none was found. */
30  defaultBranch: string | null
31  /** Local branches whose upstream is gone, then ones already merged into the default branch. */
32  staleBranches: string[]
33  /** Linked worktrees besides the main one. */
34  worktrees: number
35  /** True when `gh` answered for a GitHub remote; PRs and issues are empty otherwise. */
36  ghOk: boolean
37  /** True when gh refused the PR list over auth (a token that may not read them): the brief says so in its place. */
38  prsDenied: boolean
39  prs: PullRequest[]
40  issueCount: number
41  focusIssues: FocusIssue[]
42}
43
44declare module 'claude-code' {
45  interface PluginState {
46    'repo-brief': { snapshot: Snapshot | null; isHidden: boolean }
47  }
48}
49