SLOPSHOPPER

pr-watch

Above the prompt: the branch PR with its checks and failing log lines, uncommitted work with a commit-and-push key, and how far the branch is behind the…

panebandspinnerguardcommandtoast
★ 1v0.6.8MITupdated 2026-10-11cephalofoil/kitt/pr-watch
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pr-watch
│ ┃ PR #undefined ✕ › fix the failing auth test and add an audit log call │ ┃ ✓ PR # · │ ┃ Status all checks green ⏺ Read(src/auth.ts) │ ┃ Branch ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ No checks reported yet. ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ 3: Open in browser r: Refresh ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /pr-watch │ ⎿ pr-watch: PR #undefined ✓ all checks green │ │ ● 2 uncommitted · 1 modified, 1 new c: Commit ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
● 2 uncommitted · 1 modified, 1 new c: Commit ⟨Claude Code's own drawing⟩
Pane · PR #undefined
✓ PR # · Status all checks green Branch No checks reported yet. 3: Open in browser r: Refresh
README

kitt

<img width="2172" height="724" alt="Kitt-Logo mit kobaltblauen Ts" src="https://github.com/user-attachments/assets/0bbde4f9-62bc-4e15-ac01-c3796f27b836" />

Parallel work on a repo as lanes: one worktree per ticket, each with its own ports, its own agent in herdr, and a proof that the change works in the app.

Three parts:

  • kitt, a Go CLI: lanes, dev servers, the emulator, checks, proofs, and a dashboard.
  • lanes, a Claude Code skill: tells an agent how to work in a lane.
  • pr-watch, a Claude Code mod: PR checks, uncommitted work and rebase state above the prompt.

Install

go build -o ~/.local/bin/kitt.exe ./cmd/kitt     # any directory on PATH

/plugin marketplace add cephalofoil/kitt
/plugin install pr-watch@kitt
/plugin install lanes@kitt

kitt doctor says what is missing (git, gh, herdr, adb, symlinks).

A day with it

kitt repo add                 # once, inside the repo: registers it and shows what kitt detects
kitt init                     # optional: write that as kitt.toml to edit (--home for a repo that is not yours)
kitt dash --workspace         # the dashboard as its own herdr workspace

kitt new 338                  # lane for issue 338: worktree, branch, env links, install, and an agent started on the issue
kitt new 412 --apps web       # a lane about the website: starts the web app, leaves the emulator alone
kitt new settings-proto --prompt "/wayfinder settings across several screens"
kitt new tryout --blank --up  # no ticket: a lane, a blank agent to talk to, its dev servers running

The agent opens as soon as the worktree is there; the install runs after it, and a prompt waits for the install.

An agent put on an issue is told where it ends: the change built and checked, seen working in the app and recorded as a proof, then a pull request that closes the issue and says what the proof shows. It does not merge. [agent] prompt in kitt.toml replaces that text; {issue}, {title} and {url} are filled in.

In the dashboard, one row per lane: the apps it has changed files of, the agent's state, uncommitted and behind counts, the PR and its checks, the last proof, which dev servers answer, and which lane the emulator shows.

Key
entergo into the lane, after a dialog that offers what fits its state: go to it as it is (first, when it is open), a blank Claude or one more beside the one at work, its dev servers started or restarted with its app in the emulator, Claude put on the issue or told what you type
gstart the lane's agent (on its issue, if it has one)
eonly point the emulator at the lane
hload the lane on a phone on the Wi-Fi: a second Metro told this machine's address, and the code to scan
oopen the lane's web app in the browser
iinstall what the lane runs, when a lane shows no install (installs run one lane at a time)
u / dstart / stop the lane's dev servers
crun the repo's checks for the apps the lane touched
popen the lane's proof
nnew lane: an issue number or a name, then a dialog for how it opens: a blank Claude, a blank Claude with the dev servers, or Claude prompted (with the issue, or what you type) with the dev servers
bthe backlog: the repo's open issues, the one under the cursor to read beside them (space reads on, / filters by words, a label or a number, tab goes to the next repo). enter on one makes its lane, after the same dialog: a blank Claude, or Claude put on the issue through to a pull request. An issue that has a lane already is gone into
aadopt a worktree kitt did not create (Claude's, herdr's, a hand-made one)
xremove a lane that holds nothing unsaved
tshow the worktrees that are not lanes

Under the lanes, the open pull requests that have no lane yet (a bot's are left out). enter on one fetches its branch and checks it out as a lane about the apps it touches; o shows it on GitHub. The same from the shell: kitt pr 380.

Every key is also a command: kitt focus, kitt agent, kitt backlog, kitt emu, kitt phone, kitt up, kitt check, kitt proof open, kitt adopt, kitt rm. See kitt help.

The header

The dashboard opens with the kitt wordmark and, beside it, three facts: how many lanes there are, whether an agent is waiting for you, and which lane the emulator shows. Below 40 columns the wordmark gives way to the plain name.

KITT_LOGO picks another mark; kitt logo prints them all:

Value
not setthe wordmark, four lines
lockupthe tube beside a narrower wordmark, four lines
smalltube and wordmark in three lines
tube, beadthe tube alone, without or with a bead of putty
medium, large, blocksother sizes; blocks draws the tube with half blocks only
textno logo

The tube is drawn with Unicode sextants (U+1FB00 and up). A font without them shows boxes there; the wordmark uses only block elements and draws everywhere.

How lanes stay apart

  • Ports. Each lane holds a slot; an app listens on its base port plus ten per slot (Metro 8081 in the main checkout, 8091 in the first lane). kitt env prints a lane's ports.
  • Env files. The gitignored files named under link are symlinks into the main checkout, so every lane sees the same secrets and an edit reaches all of them.
  • The emulator. One device, one installed dev client. kitt emu reverses the lane's ports into it and sends the client to the lane's Metro; no native build. A proof holds a lock, so two agents never load over each other.
  • A phone. A device on the Wi-Fi cannot reach the localhost a lane's app is told. kitt phone starts a second Metro next to the lane's (8112 beside 8111), with every local address in the app's env replaced by this machine's address on the network, and prints a code the phone's camera opens the dev client with. The lane's own Metro and the emulator are untouched; kitt down stops both. --host names the address where the machine has several.
  • Shared apps. An app marked shared runs once, from the main checkout, for every lane (a database, a backend whose port is fixed).

kitt.toml

Everything project-specific lives in the repo, in kitt.toml. kitt init writes it:

kitt detect <path>      # look first: what kitt sees in a repo; registers and writes nothing
kitt init               # the wizard: each detected piece shown to keep, edit or drop, then written and registered
kitt init --agent       # an agent reads the repo first (justfile, Makefile, CI, AGENTS.md) and fills in dev commands, checks, ports
kitt init --home        # write into kitt's own folder, for a repo that is not yours to add a file to

Detection alone finds the apps (Expo, Next, Vite, anything with a dev script, a Python backend), their checks from package.json scripts, the package manager from the nearest lockfile, and the gitignored .env files to link. What it cannot see, the agent or you add: which env file means local, how the apps find each other, what CI really runs.

Which apps a lane touched is never stored. kitt reads it from git each time: the files that differ from the base branch, matched to the app whose dir they lie in.

name = "example-app"
base = "master"
link = ["apps/mobile/.env", "apps/mobile/.env.supabase.local"]

[emulator]
reverse = [54321]            # ports besides the apps' own the device must reach

[proof]
guide = "docs/proof.md"      # or the text itself: test accounts, how to reach a screen

[[app]]
name = "mobile"
kind = "expo"                # expo | web | backend
dir = "apps/mobile"
port = 8081
dev = "bunx expo start --dev-client --clear --port {port}"
env_files = [".env.supabase.local"]
setup = ["bun install --frozen-lockfile"]
checks = ["bun run typecheck", "bun run lint", "bun run test"]

[app.env]
EXPO_PUBLIC_API_URL = "http://localhost:{port:api}"

{port}, {port:<app>}, {lane}, {slot}, {root} and {main} are filled per lane. lazy = true defers an app's setup and start until it is named; shared = true runs it once for all lanes.

dev runs in a herdr pane, in your shell; setup and checks run through cmd /C (sh -c elsewhere).

Until a repo has its own kitt.toml on its base branch, a copy at <kitt home>/repos/<repo folder>.toml stands in; the repo's file wins once it exists.

Proof

kitt proof begin             # takes the emulator, loads the lane's app, prints the repo's guide
kitt proof shot "one section, no header"
kitt proof end --pass        # or --fail --note "..."
kitt proof open              # the page: verdict, note, shots in order

Proofs are kept under kitt's own folder (%APPDATA%\kitt\proofs), outside the repo. A proof goes stale when the lane gets a new commit.

pr-watch

Shown above the prompt, only when there is something to act on.

A key runs its fixed steps itself, without a turn, and leaves Claude a note of what it did. While it runs, the band says what it is doing; during kitt check, the line the check last wrote. The one thing it needs a model for, a commit message or a PR's title and body, it asks of a fork of the session, which answers with text alone.

When the usual case does not hold (a refused push, a failing check, a commit that is rejected, a secret or unrelated changes the fork will not commit as one), the band says in one line what failed, with two keys: r resolves it with Claude, n cancels. Cancel sends nothing. Resolving sends what the key stands for ("Push this branch and open a PR."), with the reason attached where only Claude reads it; Claude says in a line what went wrong and does the rest, through the mod's tools. The pane shows the whole reason. While a turn is running a key does nothing but say so.

Two keys go to Claude from the start, because that is what they are for: handing over a failing log, and a rebase the check already found conflicts in, since which side wins differs every time. For that rebase a line in the transcript names the files first.

ShownKeyWhat happens
the open PR: status, issue, one chip per check, the failing step and log lines1 2 3 xretry failed jobs · hand the log to Claude · open in browser · hide
uncommitted workccommits everything with the message the repo asks for, written by the fork; no push
commits not pushed, no PR yetpruns kitt check, rebases if behind and clean, pushes, opens the PR the fork wrote; in a repo without a kitt.toml no checks are run, and the PR says so
commits not pushed, PR openppushes (done by the mod; Claude is told); a refused push goes to Claude, who reads what the remote holds
behind the default branchbthe branch is rebased onto the default branch and then pushed to its own remote branch, ready for a PR: done by the mod when the tree is clean and the check found no conflicts, otherwise Claude calls rebase_and_push, rebases by hand on conflicts and asks where a conflict is not clear
the PR is mergedmswitches to the default branch, brought up to date (done by the mod; Claude is told)

Merging is yours. No key and no tool merges. When Claude runs gh pr merge anyway, the call is held and you are asked; anything but "Merge" refuses it.

Auto-rebase is an option of the plugin, off by default (/plugin, pr-watch, configure). On, a branch with an open PR that falls behind is rebased and pushed without a key press, as long as the tree is clean and the rebase has no conflicts.

The tools, as Claude sees them:

  • mcp__pr-watch__commit { subject, body?, paths? }: stages and commits. Refuses on the default branch. Never pushes.
  • mcp__pr-watch__push { force_with_lease? }: pushes. A refused push answers with the commits the remote holds; forcing then overwrites exactly those.
  • mcp__pr-watch__rebase_and_push: rebases onto the default branch and pushes with lease. A conflicting rebase is undone and answered with the files.

The branch name sits at the end of the hint line. /pr-watch opens the full view of the PR. Keys work once the band has focus (click it, or ctrl+x tab).

License

MIT

Source 3 files
hooks/register.tsx 1303 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { PrWatchCheck, PrWatchGit, PrWatchIssue, PrWatchLog, PrWatchSnapshot } from '../types'
5import { countBoxes, duration, headline, issueNumber, overall, parseChecks, parseLog } from './parse'
6import type { Overall } from './parse'
7
8const PANE = 'pr-watch'
9const FIELDS =
10  'number,title,body,state,isDraft,headRefOid,headRefName,closingIssuesReferences,statusCheckRollup'
11const TICK_MS = 15_000
12const IDLE_TICKS = 4
13const FETCH_TICKS = 20
14
15// The tools Claude calls to act on the branch: each does fixed steps and answers
16// with what happened. A key of the band runs the same steps itself, without a
17// turn; the one thing it needs a model for, a commit message or a PR's text, it
18// asks of a fork of the session. When a step does not go through, the band says
19// so in one line with two keys: resolve it with Claude, or cancel. Only the first
20// gives Claude a turn.
21const TOOL = {
22  commit: 'mcp__pr-watch__commit',
23  push: 'mcp__pr-watch__push',
24  rebase: 'mcp__pr-watch__rebase_and_push',
25} as const
26
27// What a key sends is a few words the person reads in the transcript. How to do
28// it rides along as context only the model reads.
29const ASK = {
30  commit: 'Commit my changes.',
31  ship: 'Push this branch and open a PR.',
32  push: 'Push this branch.',
33  rebase: 'Rebase this branch onto ',
34} as const
35
36const HOW = {
37  commit:
38    `Sent by the Commit key of the pr-watch band. Look at what is uncommitted, write the message this repo asks for (AGENTS.md, ` +
39    `CLAUDE.md, the subjects in \`git log\`, the issue the branch works on), and call the tool ${TOOL.commit} with it. For ` +
40    `clearly unrelated changes, call it once per group with \`paths\`. Do not run \`git commit\` yourself, do not push, do not open a PR. ` +
41    `If something should not be committed (a secret, generated junk, work that is visibly broken), do not call the tool: say what and why. ` +
42    `Answer with the commit subject and nothing else.`,
43  ship:
44    `Sent by the Push & open PR key of the pr-watch band. First run the repo's own checks for what changed: \`kitt check\` when the ` +
45    `repo has a kitt.toml, otherwise the checks AGENTS.md or CLAUDE.md name. If a check fails, stop and report it. If the branch is ` +
46    `behind the default branch, call ${TOOL.rebase} first. Then call ${TOOL.push}, and open a PR against the default branch with ` +
47    `\`gh pr create\`, following the repo's PR conventions: title style, the sections its instructions ask for, the issue it closes. ` +
48    `If \`kitt proof status\` shows a proof for this lane, say in the PR body what it shows. Do not merge the PR: merging is the person's decision. Answer with the PR link and one line on the checks.`,
49  push:
50    `Sent by the Push key of the pr-watch band. Call the tool ${TOOL.push}. If it answers that the remote holds other commits, ` +
51    `read them: call again with force_with_lease only when they are this branch's own commits from before a rebase; if they are ` +
52    `someone else's work, stop and say so. Answer in one line.`,
53  rebase:
54    `Sent by the Rebase key of the pr-watch band. It means: rebase this branch onto the default branch, then push this branch to ` +
55    `its own remote branch, so a PR can be opened or updated. Nothing is pushed to the default branch. Call the tool ${TOOL.rebase}. ` +
56    `If it answers that the rebase conflicts, rebase by hand: resolve each conflict only where the right result is clear from both ` +
57    `sides, and where it is not, stop with the rebase still open and ask, naming the file and the two versions. After a rebase by ` +
58    `hand, call ${TOOL.push} with force_with_lease. Answer in one or two lines.`,
59} as const
60
61// What a key asks of a fork of the session: text alone, or "ASK:" to hand the key to Claude.
62const WRITE = {
63  commit:
64    `The person pressed the Commit key of the pr-watch band. Write the commit message for the uncommitted changes below, in the form ` +
65    `this repo asks for (its instructions, the subjects in the log, the issue the branch works on). Answer with the message alone: the ` +
66    `subject on the first line, then an empty line and a body only where the repo's form asks for one. No quotes, no code fence. ` +
67    `If something should not be committed as it is (a secret, generated junk, work that is visibly broken), or the changes are clearly ` +
68    `unrelated and belong in separate commits, answer instead with one line starting "ASK: " and the reason.`,
69  pr:
70    `The person pressed the Push & open PR key of the pr-watch band. The branch is pushed. Write the pull request ` +
71    `for the commits below, following the repo's PR conventions: title style, the sections its instructions ask for, the issue it closes. ` +
72    `Where a proof is given, say in the body what it shows. Answer with the title on the first line, an empty line, then the body in ` +
73    `Markdown. No quotes, no code fence around the whole.`,
74} as const
75// How much of a diff a model is shown, and how many changed files a commit by key may have.
76const MOST = 200_000
77const FILES = 1000
78
79// What Claude reads beside a key's few words when the key tried first and the person had it resolved.
80const TRIED =
81  `The key ran its fixed steps itself first, without a turn; a step failed, and the person chose to have you do it. Why it failed ` +
82  `follows. Say in one line what went wrong, then do what the key was doing, leaving out what already went through. Ask first only ` +
83  `where the decision is the person's: a secret or junk among the changes, someone else's commits on the remote. Keep the answer ` +
84  `to a few lines.`
85
86/** What the Rebase key sends: the branch goes onto the base, then the branch itself is pushed. */
87const rebaseAsk = (base: string): string => `${ASK.rebase}${base.replace(/^origin\//, '')} and push the branch.`
88
89function howFor(asked: string): string | null {
90  if (asked === ASK.commit) return HOW.commit
91  if (asked === ASK.ship) return HOW.ship
92  if (asked === ASK.push) return HOW.push
93  if (asked.startsWith(ASK.rebase)) return HOW.rebase
94
95  return null
96}
97
98const snapshot = atom({ plugin: 'pr-watch', key: 'snapshot' } as const, null)
99const gitState = atom({ plugin: 'pr-watch', key: 'git' } as const, null)
100const hiddenPr = atom({ plugin: 'pr-watch', key: 'hiddenPr' } as const, null)
101const hiddenRebase = atom({ plugin: 'pr-watch', key: 'hiddenRebase' } as const, null)
102const isLoaded = atom({ plugin: 'pr-watch', key: 'isLoaded' } as const, false)
103const doing = atom({ plugin: 'pr-watch', key: 'doing' } as const, null)
104const halted = atom({ plugin: 'pr-watch', key: 'halted' } as const, null)
105
106const GLYPH = { pass: '✓', fail: '✗', running: '●', queued: '○', skipped: '–' } as const
107const COLOR = { pass: 'green', fail: 'red', running: 'yellow', queued: 'gray', skipped: 'gray' } as const
108const HEAD = {
109  failed: { color: 'red', mark: '✗', word: 'checks failing' },
110  running: { color: 'yellow', mark: '●', word: 'checks running' },
111  green: { color: 'green', mark: '✓', word: 'all checks green' },
112  merged: { color: 'magenta', mark: '✓', word: 'merged' },
113  closed: { color: 'gray', mark: '–', word: 'closed' },
114} as const
115
116// A command that merges a pull request: the CLI's own, or the API's merge endpoint.
117const MERGE = /\bgh\s+pr\s+merge\b|\bgh\s+api\b[^\n]*\/pulls\/\d+\/merge\b/
118const NO_MERGE =
119  'Merging a pull request is the person\'s decision, and they did not approve this one. Do not merge and do not try another way: ' +
120  'say that the PR is ready to merge, and stop.'
121
122// Set from the plugin's options: rebase a PR's branch by itself when it falls behind.
123let isAutoRebase = false
124let autoFor = ''
125
126let isPrBusy = false
127let isGitBusy = false
128let ticks = 0
129let last: { key: string; overall: Overall } | null = null
130let issue: (PrWatchIssue & { at: number }) | null = null
131let base: string | null = null
132let tried: { key: string; conflicts: string[] | null } | null = null
133// The main loop's turns under way: git is not moved under a turn that is working.
134const running = new Set<string>()
135let isActing = false
136// Why a key's own steps stopped: it rides along with the few words Claude is then sent.
137let stopped: string | null = null
138const logs = new Map<string, PrWatchLog>()
139
140const keyOf = (pr: PrWatchSnapshot): string => `${pr.number}:${pr.headSha}`
141
142const plural = (count: number, one: string): string => `${count} ${one}${count === 1 ? '' : 's'}`
143
144async function run($: EngineInterface, argv: readonly string[], timeoutMs = 20_000) {
145  try {
146    return await $.process.run(argv, { timeoutMs })
147  } catch {
148    return null
149  }
150}
151
152async function text($: EngineInterface, argv: readonly string[]): Promise<string | null> {
153  const ran = await run($, argv)
154
155  return ran === null || ran.exitCode !== 0 ? null : ran.stdout.trim()
156}
157
158// --- The branch: what is uncommitted, unpushed, behind ----------------------
159
160/** The remote's default branch (`origin/main`), asked once: origin's HEAD, else main, else master. */
161async function findBase($: EngineInterface): Promise<string | null> {
162  if (base !== null) return base
163
164  const head = await text($, ['git', 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD'])
165
166  if (head !== null && head !== '') {
167    base = head
168
169    return base
170  }
171  for (const name of ['origin/main', 'origin/master']) {
172    if ((await text($, ['git', 'rev-parse', '--verify', '--quiet', name])) !== null) {
173      base = name
174
175      return base
176    }
177  }
178
179  return null
180}
181
182async function loadGit($: EngineInterface): Promise<PrWatchGit | null> {
183  const branch = await text($, ['git', 'branch', '--show-current'])
184
185  if (branch === null || branch === '') return null
186
187  const onto = await findBase($)
188  const status = (await run($, ['git', 'status', '--porcelain']))?.stdout.split(/\r?\n/).filter(Boolean) ?? []
189  const untracked = status.filter(line => line.startsWith('??')).length
190  const counts =
191    (onto === null ? null : await text($, ['git', 'rev-list', '--left-right', '--count', `HEAD...${onto}`])) ?? '0 0'
192  const [ahead = 0, behind = 0] = counts.split(/\s+/).map(Number)
193  const unpushed = await text($, ['git', 'rev-list', '--count', '@{upstream}..HEAD'])
194  const baseSha = (onto === null ? null : await text($, ['git', 'rev-parse', onto])) ?? ''
195  const head = (await text($, ['git', 'rev-parse', 'HEAD'])) ?? ''
196  const key = `${head}:${baseSha}`
197
198  if (behind === 0) tried = { key, conflicts: [] }
199  if (onto !== null && behind > 0 && tried?.key !== key) {
200    // Merges the two tips in memory: nothing in the work tree or the index moves.
201    const merged = await run($, ['git', 'merge-tree', '--write-tree', '--name-only', 'HEAD', onto])
202    const names = merged?.stdout.split(/\r?\n\r?\n/)[0]?.split(/\r?\n/).slice(1).filter(Boolean) ?? []
203
204    tried = { key, conflicts: merged === null || merged.exitCode > 1 ? null : merged.exitCode === 0 ? [] : names }
205  }
206
207  return {
208    branch,
209    head,
210    modified: status.length - untracked,
211    untracked,
212    behind,
213    ahead,
214    unpushed: unpushed === null ? null : Number(unpushed),
215    conflicts: tried?.conflicts ?? null,
216    base: onto ?? '',
217    baseSha,
218  }
219}
220
221async function refreshGit($: EngineInterface) {
222  if (isGitBusy) return
223
224  isGitBusy = true
225
226  try {
227    const now = await loadGit($)
228
229    await update($, gitState, () => now)
230
231    if (isAutoRebase && now !== null && now.behind > 0 && now.modified + now.untracked === 0 && now.conflicts?.length === 0) {
232      const pr = await read($, snapshot)
233      const key = `${now.head}:${now.baseSha}`
234
235      if (pr !== null && pr.state === 'OPEN' && pr.branch === now.branch && autoFor !== key && !isActing && running.size === 0) {
236        autoFor = key
237        $.ui.toast(`${now.behind} behind ${now.base.replace(/^origin\//, '')}: rebasing (auto-rebase is on)`, { timeoutMs: 8000 })
238        void act($, 'Auto-rebase ran', () => rebaseTool($), rebaseAsk(now.base))
239      }
240    }
241  } catch (error) {
242    $.ui.log(`pr-watch: ${error instanceof Error ? error.message : String(error)}`)
243  } finally {
244    isGitBusy = false
245  }
246}
247
248// --- The pull request: checks, failing log, issue ---------------------------
249
250async function loadIssue($: EngineInterface, number: number, now: number) {
251  if (issue !== null && issue.number === number && now - issue.at < 300_000) return issue
252
253  const ran = await text($, ['gh', 'issue', 'view', String(number), '--json', 'title,body'])
254
255  if (ran === null) return issue?.number === number ? issue : null
256
257  const data = JSON.parse(ran) as { title?: string; body?: string }
258  issue = { number, title: data.title ?? '', ...countBoxes(data.body ?? ''), at: now }
259
260  return issue
261}
262
263async function loadLog($: EngineInterface, check: PrWatchCheck) {
264  if (check.jobId === null) return null
265
266  const kept = logs.get(check.jobId)
267
268  if (kept !== undefined) return kept
269
270  const ran = await run($, ['gh', 'run', 'view', '--job', check.jobId, '--log-failed'], 45_000)
271
272  // gh has no log until the whole run is over: ask again at the next poll.
273  if (ran === null || ran.exitCode !== 0 || ran.stdout.trim() === '') return null
274
275  const log = { jobId: check.jobId, ...parseLog(ran.stdout) }
276  logs.set(check.jobId, log)
277
278  return log
279}
280
281async function loadPr($: EngineInterface): Promise<PrWatchSnapshot | null> {
282  const ran = await text($, ['gh', 'pr', 'view', '--json', FIELDS])
283
284  if (ran === null) return null
285
286  const data = JSON.parse(ran) as {
287    number: number
288    title: string
289    body?: string
290    state: PrWatchSnapshot['state']
291    isDraft?: boolean
292    headRefOid: string
293    headRefName: string
294    closingIssuesReferences?: { number?: number }[]
295    statusCheckRollup?: Parameters<typeof parseChecks>[0]
296  }
297  const now = await $.clock.now()
298  const checks = parseChecks(data.statusCheckRollup ?? [], now)
299  const found = issueNumber(data.closingIssuesReferences, data.title, data.body ?? '')
300  const failed: PrWatchLog[] = []
301
302  for (const check of checks.filter(one => one.state === 'fail')) {
303    const log = await loadLog($, check)
304
305    if (log !== null) failed.push(log)
306  }
307
308  return {
309    number: data.number,
310    title: data.title,
311    state: data.state,
312    isDraft: data.isDraft === true,
313    headSha: data.headRefOid,
314    branch: data.headRefName,
315    issue: found === null ? null : await loadIssue($, found, now),
316    checks,
317    logs: failed,
318  }
319}
320
321function summary(pr: PrWatchSnapshot): string {
322  const now = overall(pr)
323  const bad = pr.checks.filter(check => check.state === 'fail').map(check => check.name)
324
325  return now === 'failed'
326    ? `PR #${pr.number} ✗ ${bad[0]}${bad.length > 1 ? ` +${bad.length - 1}` : ''}`
327    : `PR #${pr.number} ${HEAD[now].mark} ${HEAD[now].word}`
328}
329
330async function refreshPr($: EngineInterface) {
331  if (isPrBusy) return
332
333  isPrBusy = true
334
335  try {
336    const pr = await loadPr($)
337    const now = pr === null ? null : overall(pr)
338    const before = pr !== null && last !== null && last.key === keyOf(pr) ? last.overall : null
339
340    await update($, snapshot, () => pr)
341    await update($, isLoaded, () => true)
342    last = pr === null || now === null ? null : { key: keyOf(pr), overall: now }
343
344    if (pr !== null && before !== null && before !== now && now !== 'running' && now !== 'closed') {
345      $.ui.toast(summary(pr), { timeoutMs: 8000 })
346    }
347  } catch (error) {
348    $.ui.log(`pr-watch: ${error instanceof Error ? error.message : String(error)}`)
349  } finally {
350    isPrBusy = false
351  }
352}
353
354async function retry($: EngineInterface, pr: PrWatchSnapshot) {
355  const failed = pr.checks.filter(check => check.state === 'fail')
356  const runs = [...new Set(failed.map(check => check.runId).filter((id): id is string => id !== null))]
357
358  for (const id of runs) {
359    const ran = await run($, ['gh', 'run', 'rerun', id, '--failed'], 30_000)
360
361    $.ui.toast(
362      ran?.exitCode === 0
363        ? `PR #${pr.number}: failed jobs restarted`
364        : `Retry refused: ${(ran?.stderr ?? 'gh did not answer').trim().split('\n')[0]}`,
365      { timeoutMs: 8000 },
366    )
367  }
368  for (const check of failed) if (check.jobId !== null) logs.delete(check.jobId)
369
370  await refreshPr($)
371}
372
373async function hand($: EngineInterface, pr: PrWatchSnapshot) {
374  const parts = pr.checks
375    .filter(check => check.state === 'fail')
376    .map(check => {
377      const log = pr.logs.find(one => one.jobId === check.jobId)
378
379      return log === undefined
380        ? `Job "${check.name}" failed; its log is not available yet.`
381        : `Job "${check.name}" failed in step "${log.step}". Log tail:\n\`\`\`\n${log.lines.join('\n')}\n\`\`\``
382    })
383
384  await $.prompt.submit({
385    text: `CI on PR #${pr.number} (${pr.branch}) is failing.\n\n${parts.join('\n\n')}\n\nFind the cause and fix it.`,
386    asUser: true,
387  })
388}
389
390async function browse($: EngineInterface, pr: PrWatchSnapshot) {
391  await run($, ['gh', 'pr', 'view', String(pr.number), '--web'])
392}
393
394const why = (ran: { stderr: string; stdout: string } | null): string =>
395  ((ran?.stderr || ran?.stdout) ?? 'git did not answer').trim().split('\n').filter(Boolean).pop() ?? ''
396
397const tail = (ran: { stderr: string; stdout: string } | null, most: number): string =>
398  `${ran?.stdout ?? ''}\n${ran?.stderr ?? ''}`.split(/\r?\n/).filter(line => line.trim() !== '').slice(-most).join('\n')
399
400/** Tells Claude what a key did to the branch, without starting a turn. */
401async function tell($: EngineInterface, what: string) {
402  try {
403    await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: `[pr-watch] ${what}` }] } })
404  } catch {
405    // A session that takes no notes still has the toast.
406  }
407}
408
409// --- The tools: fixed steps, an answer Claude reads ---------------------------
410
411/** `isDone` marks a step that went through: a key reads it, Claude never sees it. */
412type Answer = { result: string; isDone?: true } | { deny: string }
413
414const answerOf = (out: Answer): Answer => ('deny' in out ? out : { result: out.result })
415
416/** A step failed: the band says so in one line, with a key to resolve it with Claude and one to cancel. */
417async function stop($: EngineInterface, key: string, why: string, text: string) {
418  await update($, doing, () => null)
419  await update($, halted, () => ({ key, why, text }))
420}
421
422/** The person chose Claude: the key's own few words are sent, the reason rides along unseen. */
423async function resolve($: EngineInterface, halt: { why: string; text: string }) {
424  stopped = halt.why
425  await update($, halted, () => null)
426  void $.prompt.submit({ text: halt.text, asUser: true })
427}
428
429/**
430 * Runs a tool's fixed steps for a key, without a turn, and tells Claude what
431 * was done. `text` is what the key asks of Claude when a step fails and the
432 * person has it resolved.
433 */
434async function act($: EngineInterface, said: string, step: () => Promise<Answer>, text: string) {
435  if (isActing) return
436
437  const key = said.replace(/^The person pressed | ran$/g, '')
438
439  if (running.size > 0) {
440    $.ui.toast(`${key} waits: Claude is working. Press it again when the turn has ended.`, { timeoutMs: 8000 })
441
442    return
443  }
444
445  isActing = true
446  await update($, halted, () => null)
447  await update($, doing, () => key)
448
449  try {
450    const out = await step()
451
452    if ('deny' in out) {
453      $.ui.toast(out.deny, { timeoutMs: 8000 })
454    } else if (out.isDone === true) {
455      $.ui.toast(out.result, { timeoutMs: 8000 })
456      await tell($, `${said}: ${out.result}`)
457    } else {
458      await stop($, key, out.result, text)
459    }
460  } catch (error) {
461    // A step that threw is a step that did not go through.
462    await stop($, key, error instanceof Error ? error.message : String(error), text)
463  } finally {
464    isActing = false
465    await update($, doing, () => null)
466  }
467}
468
469/** The default branch is never committed to, pushed or rebased by a tool. */
470async function branchFor($: EngineInterface): Promise<PrWatchGit | { deny: string }> {
471  const git = await loadGit($)
472
473  if (git === null) return { deny: 'This directory is not on a git branch.' }
474  if (`origin/${git.branch}` === git.base) {
475    return { deny: `${git.branch} is the default branch. Create a branch first (git switch -c <type>/<name>), then call the tool again.` }
476  }
477
478  return git
479}
480
481async function commitTool($: EngineInterface, input: { subject?: unknown; body?: unknown; paths?: unknown }): Promise<Answer> {
482  const git = await branchFor($)
483
484  if ('deny' in git) return git
485
486  const subject = typeof input.subject === 'string' ? input.subject.trim() : ''
487  const body = typeof input.body === 'string' ? input.body.trim() : ''
488  const paths = Array.isArray(input.paths) ? input.paths.filter((path): path is string => typeof path === 'string') : []
489
490  if (subject === '') return { deny: 'A commit needs a subject.' }
491
492  const added = await run($, paths.length > 0 ? ['git', 'add', '--', ...paths] : ['git', 'add', '-A'], 60_000)
493
494  if (added?.exitCode !== 0) return { result: `git add failed: ${why(added)}\nNothing was committed.` }
495
496  const staged = await run($, ['git', 'diff', '--cached', '--quiet'])
497
498  if (staged?.exitCode === 0) return { result: 'There is nothing to commit for these paths.' }
499
500  // A repo's commit hooks run here and may take their time.
501  const committed = await run($, ['git', 'commit', '-m', subject, ...(body === '' ? [] : ['-m', body])], 300_000)
502
503  if (committed?.exitCode !== 0) {
504    return { result: `git refused the commit.\nThe changes stay staged. Output:\n${tail(committed, 30)}` }
505  }
506
507  const sha = (await text($, ['git', 'rev-parse', '--short', 'HEAD'])) ?? ''
508  const left = (await run($, ['git', 'status', '--porcelain']))?.stdout.split(/\r?\n/).filter(Boolean).length ?? 0
509
510  await refreshGit($)
511
512  return {
513    result: `Committed ${sha} ${subject}. ${left === 0 ? 'Nothing is left uncommitted.' : `${left} files are still uncommitted.`} Not pushed.`,
514    isDone: true,
515  }
516}
517
518// The remote head Claude was shown when a push was refused: a forced push is
519// leased to exactly that commit, so it cannot overwrite anything newer.
520let shown: { branch: string; sha: string } | null = null
521
522async function pushTool($: EngineInterface, input: { force_with_lease?: unknown }): Promise<Answer> {
523  const git = await branchFor($)
524
525  if ('deny' in git) return git
526
527  const isForced = input.force_with_lease === true
528  const upstream = await text($, ['git', 'rev-parse', '--abbrev-ref', '@{upstream}'])
529  const lease = shown !== null && shown.branch === git.branch ? `--force-with-lease=${git.branch}:${shown.sha}` : '--force-with-lease'
530  const argv = isForced
531    ? ['git', 'push', lease, 'origin', git.branch]
532    : upstream === null
533      ? ['git', 'push', '--set-upstream', 'origin', git.branch]
534      : ['git', 'push']
535  const pushed = await run($, argv, 180_000)
536
537  if (pushed?.exitCode === 0) {
538    shown = null
539    await refreshGit($)
540    await refreshPr($)
541
542    return { result: `Pushed ${git.branch} to origin${isForced ? ' with --force-with-lease' : ''}.`, isDone: true }
543  }
544  if (isForced || !/rejected|non-fast-forward|fetch first|stale info/.test(`${pushed?.stderr}`)) {
545    return { result: `The push failed: ${why(pushed)}` }
546  }
547
548  // Refused: show what the remote holds that the local branch lacks.
549  await run($, ['git', 'fetch', '--quiet', 'origin', git.branch], 30_000)
550
551  const sha = (await text($, ['git', 'rev-parse', `origin/${git.branch}`])) ?? ''
552  const theirs = (await text($, ['git', 'log', '--format=%h %an: %s', '-10', `HEAD..origin/${git.branch}`])) ?? ''
553
554  shown = { branch: git.branch, sha }
555
556  return {
557    result:
558      `The remote branch has commits this one lacks.\norigin/${git.branch} holds:\n${theirs}\n` +
559      `If these are this branch's own commits from before a rebase, call the tool again with force_with_lease: true. ` +
560      `If any is someone else's work, do not force: stop and tell the person.`,
561  }
562}
563
564async function rebaseTool($: EngineInterface): Promise<Answer> {
565  const git = await branchFor($)
566
567  if ('deny' in git) return git
568  if (git.modified + git.untracked > 0) {
569    return { deny: `There are uncommitted changes. Commit them first (${TOOL.commit}), then call this tool again.` }
570  }
571
572  const onto = git.base.replace(/^origin\//, '')
573
574  await run($, ['git', 'fetch', '--quiet', 'origin', onto], 30_000)
575
576  const behind = await text($, ['git', 'rev-list', '--count', `HEAD..${git.base}`])
577
578  const isRebased = behind !== '0'
579
580  const rebased = isRebased ? await run($, ['git', 'rebase', git.base], 180_000) : null
581
582  if (isRebased && rebased?.exitCode !== 0) {
583    const files = (await text($, ['git', 'diff', '--name-only', '--diff-filter=U'])) ?? ''
584
585    // Back to exactly where the branch was: nothing half-done is left behind.
586    await run($, ['git', 'rebase', '--abort'])
587    await refreshGit($)
588
589    return {
590      result:
591        `The rebase onto ${git.base} has conflicts.\nIt was undone and the branch is as before.\n` +
592        (files === '' ? `git said: ${why(rebased)}` : `Conflicts in:\n${files}`),
593    }
594  }
595
596  // The branch itself is pushed, to its own remote branch: a first push sets the
597  // upstream, a later one is leased, so it refuses when the remote branch moved
598  // since it was last seen.
599  const upstream = await text($, ['git', 'rev-parse', '--abbrev-ref', '@{upstream}'])
600  const pushed = await run(
601    $,
602    upstream === null ? ['git', 'push', '--set-upstream', 'origin', git.branch] : ['git', 'push', '--force-with-lease'],
603    180_000,
604  )
605  const did = isRebased ? `Rebased ${git.branch} onto ${git.base}` : `${git.branch} was already on top of ${git.base}`
606  const outcome =
607    pushed?.exitCode === 0
608      ? `${did} and pushed it to origin/${git.branch}${isRebased && upstream !== null ? ' with --force-with-lease; its commits have new ids' : ''}. A PR can be opened from it now.`
609      : `The push was refused: ${why(pushed)}\n${did}; only the push is missing.`
610  await refreshGit($)
611  await refreshPr($)
612
613  return pushed?.exitCode === 0 ? { result: outcome, isDone: true } : { result: outcome }
614}
615
616// --- The keys: the same steps without a turn, the text from a fork ------------
617
618/** The repo's own instructions, for a model that has not read the session. */
619async function instructions($: EngineInterface): Promise<string> {
620  const found: string[] = []
621
622  for (const name of ['AGENTS.md', 'CLAUDE.md']) {
623    try {
624      found.push(`${name}:\n${String(await $.fs.read(name)).slice(0, 20_000)}`)
625    } catch {
626      // A repo may have neither.
627    }
628  }
629
630  return found.join('\n\n')
631}
632
633/**
634 * Asks a fork of the session for text: its first line and the rest, or why it
635 * was not written. A session with no answer yet has nothing to fork, so a
636 * model on its own writes it, from the repo's instructions.
637 */
638async function write($: EngineInterface, what: string, prompt: string): Promise<{ head: string; rest: string } | { result: string }> {
639  const forked = await $.model.fork({ prompt })
640  const reply =
641    !forked.isAnswered && forked.reason === 'nothing-to-fork'
642      ? await $.model.complete({ model: 'sonnet', prompt, system: await instructions($), maxTokens: 2000 })
643      : forked
644
645  if (!reply.isAnswered) return { result: `The ${what} could not be written (${reply.reason}).` }
646
647  const said = reply.text.trim().replace(/^```\w*\r?\n|\r?\n```$/g, '').trim()
648  const [head = '', ...rest] = said.split(/\r?\n/)
649
650  if (head.startsWith('ASK:')) return { result: said.slice(4).trim() }
651  if (head === '' || head.length > 200) return { result: `The ${what} came back without a one-line subject.` }
652
653  return { head: head.trim(), rest: rest.join('\n').trim() }
654}
655
656/**
657 * The uncommitted work as text: every changed file by name and size of change,
658 * then the diff, new files whole. A long diff is cut and says so: the list of
659 * files stays complete, and the fork knows from the session what was done.
660 */
661async function changes($: EngineInterface): Promise<{ shown: string; files: number }> {
662  const status = ((await text($, ['git', 'status', '--porcelain'])) ?? '').split(/\r?\n/).filter(Boolean)
663  const log = (await text($, ['git', 'log', '-8', '--format=%s'])) ?? ''
664  const stat = (await text($, ['git', 'diff', 'HEAD', '--stat'])) ?? ''
665  const diff = (await run($, ['git', 'diff', 'HEAD']))?.stdout ?? ''
666  const fresh = ((await text($, ['git', 'ls-files', '--others', '--exclude-standard'])) ?? '').split(/\r?\n/).filter(Boolean)
667  let all = diff
668
669  for (const path of fresh) {
670    if (all.length > MOST) break
671
672    all = `${all}\n${(await run($, ['git', 'diff', '--no-index', '--', '/dev/null', path]))?.stdout ?? ''}`
673  }
674
675  return {
676    files: status.length,
677    shown:
678      `Last subjects:\n${log}\n\ngit status --porcelain:\n${status.join('\n')}\n\nNew files:\n${fresh.join('\n')}\n\n` +
679      `git diff --stat:\n${stat}\n\nDiff:\n${all.slice(0, MOST)}` +
680      (all.length > MOST ? '\n(The diff is cut here. The lists above name every changed file.)' : ''),
681  }
682}
683
684async function commitKey($: EngineInterface): Promise<Answer> {
685  const git = await branchFor($)
686
687  if ('deny' in git) return { result: git.deny.replace('. ', '.\n') }
688
689  const work = await changes($)
690
691  // Thousands of files are not a change someone made by hand: a folder that wants ignoring, more likely.
692  if (work.files > FILES) {
693    return { result: `${work.files} files are uncommitted: too many for one commit.\nThat looks like generated files or a folder that should be ignored. Nothing was committed.` }
694  }
695
696  const message = await write($, 'commit message', `${WRITE.commit}\n\n${work.shown}`)
697
698  return 'result' in message ? message : commitTool($, { subject: message.head, body: message.rest })
699}
700
701/** Runs `kitt check`, the band showing the line it last wrote; stopped after ten minutes. */
702async function check($: EngineInterface): Promise<{ exitCode: number | null; stdout: string; stderr: string } | null> {
703  const child = $.process.spawn({ argv: ['kitt', 'check'] })
704  const limit = $.clock.after(600_000, () => void child.return(undefined as never))
705  let stdout = ''
706
707  try {
708    for (;;) {
709      const piece = await child.next()
710
711      if (piece.done === true) return { exitCode: piece.value?.code ?? null, stdout, stderr: '' }
712
713      stdout = `${stdout}${piece.value.text.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '')}`.slice(-20_000)
714
715      const line = stdout.split(/[\r\n]+/).filter(one => one.trim() !== '').pop() ?? ''
716
717      await update($, doing, () => `kitt check · ${line.trim().slice(0, 90)}`)
718    }
719  } catch {
720    return null
721  } finally {
722    limit.cancel()
723  }
724}
725
726/** Why `gh pr create` refused, in a few words; gh's own last line where the cause is not a known one. */
727function ghSaid(ran: { stderr: string; stdout: string } | null): string {
728  const said = `${ran?.stderr ?? ''}${ran?.stdout ?? ''}`
729
730  if (ran === null) return 'gh did not answer.'
731  if (/known GitHub host|not a git repository|no git remotes/i.test(said)) return 'this repo has no remote on GitHub.'
732  if (/already exists/i.test(said)) return 'this branch already has a PR.'
733  if (/gh auth login|authentication|HTTP 401/i.test(said)) return 'gh is not logged in.'
734  if (/No commits between/i.test(said)) return 'the branch has no commits the default branch lacks.'
735
736  return why(ran)
737}
738
739async function shipKey($: EngineInterface): Promise<Answer> {
740  const git = await branchFor($)
741
742  if ('deny' in git) return { result: git.deny.replace('. ', '.\n') }
743
744  let hasKitt = true
745
746  try {
747    await $.fs.read('kitt.toml')
748  } catch {
749    hasKitt = false
750  }
751  // A repo without a kitt.toml names no checks a key could run: the PR is opened all the same, and says so.
752  const checked = hasKitt ? await check($) : { exitCode: 0, stdout: '', stderr: '' }
753  const checks = hasKitt ? 'kitt check passed' : 'no checks were run (this repo has no kitt.toml)'
754
755  if (checked === null) return { result: '`kitt check` could not be started.\nNothing was pushed.' }
756  if (checked.exitCode !== 0) return { result: `\`kitt check\` failed.\nNothing was pushed. Output:\n${tail(checked, 40)}` }
757  if (git.behind > 0 && git.conflicts?.length !== 0) {
758    return { result: `The branch is ${git.behind} behind ${git.base} and the rebase has conflicts.\nNothing was pushed (${checks}).` }
759  }
760
761  await update($, doing, () => (git.behind > 0 ? 'rebasing and pushing' : 'pushing'))
762
763  const pushed = git.behind > 0 ? await rebaseTool($) : await pushTool($, {})
764
765  if ('deny' in pushed) return { result: pushed.deny }
766  if (pushed.isDone !== true) return { result: pushed.result }
767
768  const onto = git.base.replace(/^origin\//, '')
769  const commits = (await text($, ['git', 'log', '--format=%h %s%n%b', `${git.base}..HEAD`])) ?? ''
770  const stat = (await text($, ['git', 'diff', '--stat', `${git.base}...HEAD`])) ?? ''
771  const proof = await text($, ['kitt', 'proof', 'status'])
772
773  await update($, doing, () => 'pushed · writing the PR')
774  const pr = await write(
775    $,
776    'PR text',
777    `${WRITE.pr}\n\nBranch ${git.branch} onto ${onto}.\n\nChecks: ${checks}. Say of the checks only this.\n\nCommits:\n${commits.slice(0, MOST)}\n\nFiles:\n${stat}` +
778      (proof === null || proof === '' ? '' : `\n\nkitt proof status:\n${proof}`),
779  )
780
781  if ('result' in pr) return { result: `${pr.result}\nThe branch is pushed (${checks}); no PR was opened.` }
782
783  const opened = await run($, ['gh', 'pr', 'create', '--base', onto, '--head', git.branch, '--title', pr.head, '--body', pr.rest], 60_000)
784
785  await refreshPr($)
786
787  return opened?.exitCode === 0
788    ? { result: `Pushed and PR opened, ${checks}: ${opened.stdout.trim().split(/\r?\n/).pop() ?? ''}`, isDone: true }
789    : { result: `The PR could not be opened: ${ghSaid(opened)}\nThe branch is pushed (${checks}). gh said: ${why(opened)}` }
790}
791
792/** Leaves a merged branch for the default one, brought up to the remote's tip. */
793async function switchToBase($: EngineInterface, git: PrWatchGit) {
794  const name = git.base.replace(/^origin\//, '')
795  const why = (ran: { stderr: string } | null) => (ran?.stderr ?? 'git did not answer').trim().split('\n')[0]
796
797  await run($, ['git', 'fetch', '--quiet', 'origin', name], 30_000)
798
799  const moved = await run($, ['git', 'switch', name])
800
801  if (moved?.exitCode !== 0) {
802    $.ui.toast(`Switch refused: ${why(moved)}`, { timeoutMs: 8000 })
803
804    return
805  }
806
807  const pulled = await run($, ['git', 'merge', '--ff-only', git.base])
808
809  $.ui.toast(
810    pulled?.exitCode === 0 ? `On ${name}, level with ${git.base}` : `On ${name}, not fast-forwarded: ${why(pulled)}`,
811    { timeoutMs: 8000 },
812  )
813  await tell($, `The person pressed Switch: this checkout is now on ${name}, level with ${git.base}. The branch ${git.branch} is merged and done.`)
814  await refreshGit($)
815  await refreshPr($)
816}
817
818export const register: Register = (on, options) => {
819  isAutoRebase = options.autoRebase === true
820
821  on('session.start', async ($, e, next) => {
822    await $.command.register({
823      name: 'pr-watch',
824      description: "Open the full view of this branch's PR: every check, failing log lines, issue",
825    })
826    // An earlier version pinned the branch here; a pin outlives a reload until cleared.
827    $.ui.status(undefined)
828    try {
829      await $.tool.register({
830        name: 'commit',
831        description:
832          'Commit uncommitted changes of the current branch with the message you give. Stages everything, or only `paths` when given. ' +
833          'Refuses on the default branch. Never pushes. Use it when the person asks to commit.',
834        inputSchema: {
835          type: 'object',
836          properties: {
837            subject: { type: 'string', description: 'The commit subject, in the form this repo uses' },
838            body: { type: 'string', description: 'Optional commit body' },
839            paths: { type: 'array', items: { type: 'string' }, description: 'Only these paths; leave out to commit everything' },
840          },
841          required: ['subject'],
842        },
843      })
844      await $.tool.register({
845        name: 'push',
846        description:
847          'Push the current branch to origin, setting its upstream on the first push. A refused push answers with the commits the ' +
848          'remote holds; force_with_lease then overwrites exactly those, and only those. Refuses on the default branch.',
849        inputSchema: {
850          type: 'object',
851          properties: {
852            force_with_lease: {
853              type: 'boolean',
854              description: "Only after a refused push whose listed commits are this branch's own from before a rebase",
855            },
856          },
857        },
858      })
859      await $.tool.register({
860        name: 'rebase_and_push',
861        description:
862          'Rebase the current branch onto the latest default branch, then push that branch to its own remote branch (first push sets the ' +
863          'upstream, a later one uses --force-with-lease). Nothing is pushed to the default branch. A rebase that conflicts is ' +
864          'undone and answered with the conflicting files. Needs a clean work tree. Refuses on the default branch.',
865        inputSchema: { type: 'object', properties: {} },
866      })
867    } catch (error) {
868      $.ui.log(`pr-watch: tools not registered: ${error instanceof Error ? error.message : String(error)}`)
869    }
870    void refreshGit($)
871    void refreshPr($)
872
873    $.clock.every(TICK_MS, () => {
874      ticks += 1
875
876      if (ticks % FETCH_TICKS === 0) {
877        if (base !== null) void run($, ['git', 'fetch', '--quiet', 'origin', base.replace(/^origin\//, '')], 30_000)
878      }
879
880      const isLive = last !== null && (last.overall === 'failed' || last.overall === 'running')
881
882      void refreshGit($)
883      if (isLive || ticks % IDLE_TICKS === 0) void refreshPr($)
884    })
885
886    return next(e)
887  })
888
889  on('command.run', { command: 'pr-watch' }, async $ => {
890    await refreshPr($)
891
892    const pr = await read($, snapshot)
893
894    await $.ui.open({ id: PANE, title: pr === null ? 'PR' : `PR #${pr.number}`, rows: pr === null ? 4 : 20 })
895
896    return { text: pr === null ? 'pr-watch: this branch has no pull request.' : summary(pr) }
897  })
898
899  on('tool.call', async ($, e, next) => {
900    const command = String((e as { command?: unknown }).command ?? '')
901
902    if (/\bgh pr create\b/.test(command)) {
903      const now = await read($, gitState)
904
905      if (now !== null && now.behind > 0) {
906        $.ui.toast(`${now.behind} behind ${now.base}: this PR goes out unrebased`, { timeoutMs: 8000 })
907      }
908    }
909
910    const ran = await next(e)
911
912    void refreshGit($)
913    if (/\bgh (pr|run) |\bgit (push|checkout|switch)\b/.test(command)) void refreshPr($)
914
915    return ran
916  })
917
918  on('turn.start', ($, e, next) => {
919    running.add(e.turnId)
920
921    return next(e)
922  })
923
924  on('turn.complete', ($, e, next) => {
925    running.delete(e.turnId)
926    void refreshGit($)
927    void refreshPr($)
928
929    return next(e)
930  })
931
932  // The branch rides the engine's own hint line, dim, beside its PR pill.
933  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
934    const git = await read($, gitState)
935
936    if (git === null) return next(e)
937
938    const tail = [e.props.tail, `⎇ ${git.branch}`].filter(Boolean).join(' · ')
939
940    return next({ ...e, props: { ...e.props, tail } })
941  })
942
943  // Merging is held until the person says yes, whoever asked for it and however green the PR is.
944  on('tool.call', { tool: ['Bash', 'PowerShell'] }, async ($, e, next) => {
945    const command = String((e as { command?: unknown }).command ?? '')
946
947    if (!MERGE.test(command)) return next(e)
948
949    let answer = 'Do not merge'
950
951    try {
952      answer = await $.ui.ask(`Claude is about to merge a pull request. Merge it? ${command.slice(0, 140)}`, ['Merge', 'Do not merge'])
953    } catch {
954      // Dismissed, or nobody to ask: the answer stays no.
955    }
956
957    return answer === 'Merge' ? next(e) : { deny: NO_MERGE }
958  }).catch(($, e, next) => (next.called ? next(e) : { deny: NO_MERGE }))
959
960  on('tool.call', { tool: 'mcp__pr-watch__commit' }, async ($, e) =>
961    answerOf(await commitTool($, e as { subject?: unknown; body?: unknown; paths?: unknown })),
962  )
963  on('tool.call', { tool: 'mcp__pr-watch__push' }, async ($, e) => answerOf(await pushTool($, e as { force_with_lease?: unknown })))
964  on('tool.call', { tool: 'mcp__pr-watch__rebase_and_push' }, async $ => answerOf(await rebaseTool($)))
965
966  // A key's few words get their instructions here, unseen by the person.
967  on('prompt.submit', ($, e, next) => {
968    const how = (e.origin as { kind: string }).kind === 'plugin' ? howFor(e.text) : null
969
970    if (how === null) return next(e)
971
972    const before = stopped === null ? [] : [`${TRIED}\n\nWhy it failed:\n${stopped}`]
973
974    stopped = null
975
976    return next({ ...e, context: [...(e.context ?? []), how, ...before] })
977  })
978
979  // --- The band above the prompt: PR, uncommitted work, rebase --------------
980
981  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
982    if (e.props.hasSurvey) return next(e)
983
984    const pr = await read($, snapshot)
985    const git = await read($, gitState)
986    const now = pr === null ? null : overall(pr)
987    const hasPr =
988      pr !== null && git !== null && now !== null && pr.branch === git.branch &&
989      now !== 'merged' && now !== 'closed' && (await read($, hiddenPr)) !== keyOf(pr)
990    const dirty = git === null ? 0 : git.modified + git.untracked
991    // The branch's PR is merged and nothing was committed since: the branch is done.
992    const isDone =
993      pr !== null && git !== null && pr.state === 'MERGED' && pr.branch === git.branch && pr.headSha === git.head
994    const isOpen = pr !== null && git !== null && pr.state === 'OPEN' && pr.branch === git.branch
995    // A branch without an upstream has pushed nothing: everything on top of the base is outgoing.
996    const outgoing = git === null ? 0 : (git.unpushed ?? git.ahead)
997    const isBase = git !== null && `origin/${git.branch}` === git.base
998    const hasPush =
999      git !== null && dirty === 0 && !isDone && !isBase && (outgoing > 0 || (!isOpen && git.ahead > 0))
1000    const hasRebase =
1001      !isDone && git !== null && git.behind > 0 && `origin/${git.branch}` !== git.base && (await read($, hiddenRebase)) !== git.baseSha
1002
1003    const busy = await read($, doing)
1004    const halt = await read($, halted)
1005
1006    if (!hasPr && !isDone && dirty === 0 && !hasPush && !hasRebase && busy === null && halt === null) return next(e)
1007
1008    const below = await next(e)
1009
1010    const { Box, Button, Text } = $.ui.resolve(e)
1011    const width = Math.max(30, e.props.bodyColumns)
1012    const failed = hasPr ? pr.checks.filter(check => check.state === 'fail') : []
1013    const skipped = hasPr ? pr.checks.filter(check => check.state === 'skipped').length : 0
1014    const files = git?.conflicts ?? []
1015
1016    return (
1017      <Box flexDirection="column">
1018        <Box flexDirection="column" width={width}>
1019        {busy !== null && (
1020          <Text color="yellow" wrap="truncate-end">● {busy}</Text>
1021        )}
1022        {halt !== null && (
1023          <Box flexDirection="column">
1024            <Text color="red" wrap="truncate-end">
1025              ✗ {halt.key} failed · {halt.why.split(/\r?\n/).find(line => line.trim() !== '')?.trim() ?? ''}
1026            </Text>
1027            <Box columnGap={2} marginLeft={2}>
1028              <Button key="resolve" plain hotkey="r" label="Resolve with Claude" onPress={() => resolve($, halt)} />
1029              <Button key="cancel" plain dimColor hotkey="n" label="Cancel" onPress={() => update($, halted, () => null)} />
1030            </Box>
1031          </Box>
1032        )}
1033        {hasPr && (
1034          <Box flexDirection="column">
1035            <Box columnGap={1}>
1036              <Text bold color={HEAD[now].color}>
1037                {HEAD[now].mark} PR #{pr.number}
1038              </Text>
1039              <Text color={HEAD[now].color}>{HEAD[now].word}</Text>
1040              <Text dimColor>·</Text>
1041              <Box flexGrow={1} flexShrink={1}>
1042                <Text wrap="truncate-end">
1043                  {pr.issue === null ? pr.title : `#${pr.issue.number} ${pr.issue.title}`}
1044                  {pr.issue !== null && pr.issue.total > 0 ? ` · ${pr.issue.done}/${pr.issue.total} done` : ''}
1045                </Text>
1046              </Box>
1047            </Box>
1048            <Box columnGap={2} flexWrap="wrap" marginLeft={2}>
1049              {pr.checks
1050                .filter(check => check.state !== 'skipped')
1051                .map(check => (
1052                  <Box>
1053                    <Text color={COLOR[check.state]}>{GLYPH[check.state]} </Text>
1054                    <Text bold={check.state === 'fail'} dimColor={check.state === 'pass'}>
1055                      {check.name.split(' — ')[0]}
1056                    </Text>
1057                    <Text dimColor>
1058                      {check.state === 'queued' ? ' queued' : check.seconds === null ? '' : ` ${duration(check.seconds)}`}
1059                    </Text>
1060                  </Box>
1061                ))}
1062              {skipped > 0 && <Text dimColor>– {skipped} skipped</Text>}
1063              {pr.checks.length === 0 && <Text dimColor>no checks reported yet</Text>}
1064            </Box>
1065            {failed.map(check => {
1066              const log = pr.logs.find(one => one.jobId === check.jobId)
1067
1068              return (
1069                <Box flexDirection="column" marginLeft={2}>
1070                  <Text color="red" wrap="truncate-end">
1071                    ✗ {check.name}
1072                    {log === undefined ? ' · log arrives when the run finishes' : log.step === '' ? '' : ` › ${log.step}`}
1073                  </Text>
1074                  {log !== undefined &&
1075                    headline(log.lines, 2).map(line => (
1076                      <Text dimColor wrap="truncate-end">    {line}</Text>
1077                    ))}
1078                </Box>
1079              )
1080            })}
1081            <Box columnGap={2} marginLeft={2}>
1082              {failed.length > 0 && <Button key="retry" plain hotkey="1" label="Retry failed" onPress={() => retry($, pr)} />}
1083              {failed.length > 0 && <Button key="hand" plain hotkey="2" label="Hand log to Claude" onPress={() => hand($, pr)} />}
1084              <Button key="web" plain dimColor hotkey="3" label="Open in browser" onPress={() => browse($, pr)} />
1085              <Button key="hide-pr" plain dimColor hotkey="x" label="Hide" onPress={() => update($, hiddenPr, () => keyOf(pr))} />
1086            </Box>
1087          </Box>
1088        )}
1089        {git !== null && dirty > 0 && (
1090          <Box columnGap={1}>
1091            <Text bold color="cyan">● {dirty} uncommitted</Text>
1092            <Text dimColor>
1093              · {[git.modified > 0 ? `${git.modified} modified` : '', git.untracked > 0 ? `${git.untracked} new` : '']
1094                .filter(Boolean)
1095                .join(', ')}
1096              {outgoing > 0 ? ` · ↑ ${outgoing} not pushed` : ''}
1097            </Text>
1098            <Text> </Text>
1099            <Button
1100              key="commit"
1101              plain
1102              hotkey="c"
1103              label="Commit"
1104              onPress={() => act($, 'The person pressed Commit', () => commitKey($), ASK.commit)}
1105            />
1106          </Box>
1107        )}
1108        {hasPush && (
1109          <Box columnGap={1}>
1110            <Text bold color="cyan">
1111              {outgoing > 0 ? `↑ ${plural(outgoing, 'commit')} not pushed` : '↑ pushed'}
1112            </Text>
1113            {!isOpen && <Text dimColor>· no PR yet</Text>}
1114            <Text> </Text>
1115            <Button
1116              key="push"
1117              plain
1118              hotkey="p"
1119              label={isOpen ? 'Push' : outgoing > 0 ? 'Push & open PR' : 'Open PR'}
1120              onPress={() =>
1121                isOpen
1122                  ? act($, 'The person pressed Push', () => pushTool($, {}), ASK.push)
1123                  : act($, 'The person pressed Push & open PR', () => shipKey($), ASK.ship)
1124              }
1125            />
1126          </Box>
1127        )}
1128        {isDone && (
1129          <Box columnGap={1}>
1130            <Text bold color="magenta">✓ PR #{pr.number} merged</Text>
1131            <Text dimColor>· this branch is done</Text>
1132            <Text> </Text>
1133            {dirty === 0 ? (
1134              <Button
1135                key="switch"
1136                plain
1137                hotkey="m"
1138                label={`Switch to ${git.base.replace(/^origin\//, '')}`}
1139                onPress={() => switchToBase($, git)}
1140              />
1141            ) : (
1142              <Text dimColor>commit or stash first to switch</Text>
1143            )}
1144          </Box>
1145        )}
1146        {hasRebase && (
1147          <Box columnGap={1}>
1148            <Text bold color="yellow">↓ {git.behind} behind {git.base.replace(/^origin\//, '')}</Text>
1149            <Text dimColor>·</Text>
1150            {git.conflicts === null && <Text dimColor>conflict check unavailable</Text>}
1151            {git.conflicts !== null && files.length === 0 && <Text color="green">rebase looks clean</Text>}
1152            {files.length > 0 && (
1153              <Text color="red" wrap="truncate-end">
1154                conflicts likely in {plural(files.length, 'file')}:{' '}
1155                {files.slice(0, 2).map(path => path.split('/').pop()).join(', ')}
1156                {files.length > 2 ? ', …' : ''}
1157              </Text>
1158            )}
1159            <Text> </Text>
1160            <Button
1161              key="rebase"
1162              plain
1163              hotkey="b"
1164              label="Rebase & push"
1165              onPress={() => {
1166                if (dirty === 0 && git.conflicts !== null && files.length === 0) {
1167                  return act($, 'The person pressed Rebase & push', () => rebaseTool($), rebaseAsk(git.base))
1168                }
1169                // Which side wins differs every time: this one is Claude's from the start.
1170                if (files.length > 0) $.ui.log(`Rebase & push: conflicts likely in ${files.join(', ')}; Claude rebases by hand`)
1171
1172                return void $.prompt.submit({ text: rebaseAsk(git.base), asUser: true })
1173              }}
1174            />
1175            <Button key="hide-rebase" plain dimColor hotkey="h" label="Hide" onPress={() => update($, hiddenRebase, () => git.baseSha)} />
1176          </Box>
1177        )}
1178        </Box>
1179        {below}
1180      </Box>
1181    )
1182  })
1183
1184  // --- The full view, opened with /pr-watch --------------------------------
1185
1186  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1187    const { Box, Button, Text } = $.ui.resolve(e)
1188    const pr = await read($, snapshot)
1189    const git = await read($, gitState)
1190    const halt = await read($, halted)
1191    // A key that stopped: its reason whole, every line wrapped, none cut.
1192    const stop = halt !== null && (
1193      <Box flexDirection="column">
1194        <Text bold color="red">✗ {halt.key} failed</Text>
1195        {halt.why.split(/\r?\n/).map(line => (
1196          <Text>{line === '' ? ' ' : line}</Text>
1197        ))}
1198        <Text> </Text>
1199        <Box columnGap={2}>
1200          <Button key="resolve" plain hotkey="r" label="Resolve with Claude" onPress={() => resolve($, halt)} />
hooks/parse.ts 142 lines
1import type { PrWatchCheck, PrWatchCheckState, PrWatchSnapshot } from '../types'
2
3type RollupItem = {
4  __typename?: string
5  name?: string
6  context?: string
7  status?: string
8  state?: string
9  conclusion?: string
10  startedAt?: string
11  completedAt?: string
12  detailsUrl?: string
13}
14
15export type Overall = 'failed' | 'running' | 'green' | 'merged' | 'closed'
16
17const FAILED = new Set(['FAILURE', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE', 'ERROR'])
18const SKIPPED = new Set(['SKIPPED', 'NEUTRAL'])
19
20const stateOf = (item: RollupItem): PrWatchCheckState => {
21  if (item.__typename === 'StatusContext') {
22    if (item.state === 'SUCCESS') return 'pass'
23    if (item.state === 'PENDING' || item.state === 'EXPECTED') return 'running'
24
25    return 'fail'
26  }
27  if (item.status !== 'COMPLETED') {
28    return item.status === 'IN_PROGRESS' ? 'running' : 'queued'
29  }
30  if (FAILED.has(item.conclusion ?? '')) return 'fail'
31  if (SKIPPED.has(item.conclusion ?? '')) return 'skipped'
32
33  return 'pass'
34}
35
36const time = (text: string | undefined): number | null => {
37  const ms = text === undefined ? NaN : Date.parse(text)
38
39  return Number.isNaN(ms) || ms <= 0 ? null : ms
40}
41
42export const parseChecks = (rollup: readonly RollupItem[], now: number): PrWatchCheck[] => {
43  const latest = new Map<string, { check: PrWatchCheck; startedAt: number }>()
44
45  for (const item of rollup) {
46    const name = item.name ?? item.context ?? 'check'
47    const state = stateOf(item)
48    const startedAt = time(item.startedAt)
49    const completedAt = time(item.completedAt)
50    const end = state === 'running' ? now : completedAt
51    const ids = /\/actions\/runs\/(\d+)\/job\/(\d+)/.exec(item.detailsUrl ?? '')
52    const check: PrWatchCheck = {
53      name,
54      state,
55      seconds:
56        startedAt === null || end === null || state === 'skipped' || state === 'queued'
57          ? null
58          : Math.max(0, Math.round((end - startedAt) / 1000)),
59      runId: ids?.[1] ?? null,
60      jobId: ids?.[2] ?? null,
61    }
62    const seen = latest.get(name)
63
64    if (seen === undefined || (startedAt ?? 0) >= seen.startedAt) {
65      latest.set(name, { check, startedAt: startedAt ?? 0 })
66    }
67  }
68
69  return [...latest.values()].map(one => one.check)
70}
71
72const ANSI = /\u001b\[[0-9;]*[A-Za-z]/g
73const STAMP = /^?\d{4}-\d{2}-\d{2}T[\d:.]+Z\s?/
74
75/** `gh run view --log-failed` prints `job<TAB>step<TAB>timestamp text` per line. */
76export const parseLog = (text: string): { step: string; lines: string[] } => {
77  let step = ''
78  const lines: string[] = []
79
80  for (const raw of text.split(/\r?\n/)) {
81    const parts = raw.split('\t')
82    const body = (parts.length >= 3 ? parts.slice(2).join('\t') : raw)
83      .replace(ANSI, '')
84      .replace(STAMP, '')
85      .trimEnd()
86
87    if (body.trim() === '' || /^##\[(group|endgroup|command|debug)\]/.test(body)) continue
88    if (parts.length >= 3) step = parts[1] ?? step
89    lines.push(body.replace(/^##\[error\]/, '').trim())
90  }
91
92  return { step, lines: lines.slice(-40) }
93}
94
95/** The lines worth a row in the pane: the ones that name the failure, else the tail. */
96export const headline = (lines: readonly string[], most: number): string[] => {
97  const telling = lines.filter(line =>
98    /\b(error|failed|failure|FAIL|AssertionError|Exception|not ok)\b/.test(line) &&
99    !/Process completed with exit code/.test(line),
100  )
101
102  return (telling.length > 0 ? telling : lines).slice(-most)
103}
104
105export const countBoxes = (body: string): { done: number; total: number } => {
106  const done = (body.match(/^\s*[-*] \[[xX]\]/gm) ?? []).length
107  const open = (body.match(/^\s*[-*] \[ \]/gm) ?? []).length
108
109  return { done, total: done + open }
110}
111
112export const duration = (seconds: number | null): string => {
113  if (seconds === null) return ''
114  if (seconds < 60) return `${seconds}s`
115
116  return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`
117}
118
119export const overall = (snapshot: PrWatchSnapshot): Overall => {
120  if (snapshot.state === 'MERGED') return 'merged'
121  if (snapshot.state === 'CLOSED') return 'closed'
122  if (snapshot.checks.some(check => check.state === 'fail')) return 'failed'
123  if (snapshot.checks.some(check => check.state === 'running' || check.state === 'queued')) return 'running'
124
125  return 'green'
126}
127
128export const issueNumber = (
129  closing: readonly { number?: number }[] | undefined,
130  title: string,
131  body: string,
132): number | null => {
133  const first = closing?.[0]?.number
134
135  if (typeof first === 'number') return first
136
137  const found =
138    /\(#(\d+)\)\s*$/.exec(title) ?? /\b(?:clos\w*|fix\w*|resolv\w*)\s+#(\d+)/i.exec(body)
139
140  return found === null ? null : Number(found[1])
141}
142
types/index.d.ts 59 lines
1export type PrWatchCheckState = 'pass' | 'fail' | 'running' | 'queued' | 'skipped'
2
3export type PrWatchCheck = {
4  name: string
5  state: PrWatchCheckState
6  seconds: number | null
7  runId: string | null
8  jobId: string | null
9}
10
11export type PrWatchLog = { jobId: string; step: string; lines: string[] }
12
13export type PrWatchIssue = { number: number; title: string; done: number; total: number }
14
15export type PrWatchSnapshot = {
16  number: number
17  title: string
18  state: 'OPEN' | 'MERGED' | 'CLOSED'
19  isDraft: boolean
20  headSha: string
21  branch: string
22  issue: PrWatchIssue | null
23  checks: PrWatchCheck[]
24  logs: PrWatchLog[]
25}
26
27export type PrWatchGit = {
28  branch: string
29  head: string
30  modified: number
31  untracked: number
32  /** Commits the branch lacks from the remote's default branch, and has on top of it. */
33  behind: number
34  ahead: number
35  /** Commits not on the branch's upstream yet; null when it has none. */
36  unpushed: number | null
37  /** Files a rebase would likely conflict in; null when it could not be tried. */
38  conflicts: string[] | null
39  /** The remote's default branch, as `origin/main`; empty when none was found. */
40  base: string
41  baseSha: string
42}
43
44declare module 'claude-code' {
45  interface PluginState {
46    'pr-watch': {
47      snapshot: PrWatchSnapshot | null
48      git: PrWatchGit | null
49      hiddenPr: string | null
50      hiddenRebase: string | null
51      isLoaded: boolean
52      /** What a key is doing right now, as the band shows it; null when none is. */
53      doing: string | null
54      /** The key whose steps failed, why, and the few words Claude is sent when the person has it resolved. */
55      halted: { key: string; why: string; text: string } | null
56    }
57  }
58}
59