SLOPSHOPPER

pr-watch

A line above the prompt for each pull request Claude opens, merges by number, or is asked to watch, showing its GitHub workflows with a progress bar, then…

bandguardtoastprompttoolprocess
v0.6.1MITupdated 2026-10-24oakoss/claude-plugins/plugins/pr-watch
A shopper browsing a rack in a slop shop
README

pr-watch

A line above the Claude Code prompt for each pull request Claude opens, merges by number, URL or branch, or is asked to watch, until the pull request closes, or until its merge has run its checks on the base branch. A branch Claude pushes gets a line too, until its checks pass.

#128 ● CI ████████████▏░░░░░░░░░░░ 1m11s / ~2m20s · CodeQL ✓ · Dependency Review ●
#128 ✓ ready to merge
#128 ✗ CI: Typecheck failed
#128 ⚠ conflicts
#128 merged into main · ● Release ████▏░░░░░░░░░░░░░░ 0m21s / ~1m40s · CI ●
#128 merged into main · ✓ checks passed
⟳ push feat/x · ● CI ███████▏░░░░░░░░░░░░░░░░░ 0m40s / ~2m20s

What it shows

  • Running. Of the running workflows that hold a required check (any running one when nothing on the commit is required), the longest gets a progress bar. Its length is the median of that workflow's last 10 successful runs, re-runs left out, learned again each time a run of it finishes, so the bar stops short of full until the run ends; a workflow with no successful run shows only the time so far. Once some of that workflow's jobs have finished, the line names those left, ● CI: Windows, marking each that has not started queued, or counts them past two, ● CI: 3 jobs, with queued when none of them has started; a workflow none of whose jobs has started reads ● CI queued. A re-run reads ● CI re-run and the time since its attempt started, with no bar, since re-running the failed jobs takes less than the whole workflow. The other workflows follow as marks: ✓ passed, ✗ failed, ● running.
  • Ready to merge. GitHub reports the pull request mergeable: required checks pass, no review blocks it, and it has no conflicts.
  • Failing. A job failed in a workflow that holds a required check, or in any workflow when nothing on the commit is required. The line names that job rather than a summary job that failed on it, and links to its log.
  • Blocked. Conflicts, changes requested, a branch behind its base, or a rule GitHub does not name (⚠ blocked).
  • Waiting. On a review, on a required check from a GitHub App, on GitHub to start the checks, or on GitHub to work out the merge state.
  • Draft. A draft's line starts #128 draft · and otherwise follows its checks: the bar while they run, the job that failed, ○ waiting on checks while a required GitHub App check runs, or ✓ checks passed once they pass, since a draft is not ready to merge. Conflicts, requested changes or a branch behind its base follow as · ⚠ conflicts. A draft with no checks reads #128 ○ draft.
  • Stacked. A layer of a github/gh-stack stack carries its place after its number, #235 ≡ #236 2/3, counted from the bottom as GitHub's badge is, with the stack's number to tell two stacks apart. A stack's lines sit together, top layer first, where its first line was. pr-watch asks GitHub's stacks API for an open pull request again after Claude runs a gh stack command that can change a stack, and every 10 minutes for a change made elsewhere; a merged layer is asked once it has merged, and that answer is kept. A lookup that gets no answer keeps the last one. GitHub reports each layer ready to merge by itself, though merging one with gh stack merge merges the open layers below it too, so a layer reads ready only once every layer below it has merged or reads ready itself; until then it shows ○ waiting on layer 2/3, naming the nearest that is not. A layer below that pr-watch does not watch counts as not ready unless the stacks API reports it merged, so watch every layer (as gh stack submit does) for the top one to read ready. A layer whose base is the trunk has none open below. When a layer's line changes, the layers above it are read again at once; after a partial merge, the next layer follows GitHub's retargeting, rebase and new checks like any other change. The total counts merged layers, as the stacks API keeps them listed.
  • Merged. The line names the base branch, #128 merged into main; for a layer of a github/gh-stack stack, which GitHub keeps based on the layer below, it names the stack's trunk, asked of GitHub's stacks API until it answers, at most once a minute. A host without that API keeps the base. It follows the merge commit's runs there, every workflow counting, with the same bar and marks. Once they finish it reads ✓ checks passed or names the job that failed. It keeps reading for 90 seconds after the merge in case a later run starts. A passed merge then leaves the band a few seconds later. A failed one stays, read once a minute, until a re-run passes, or the workflow's newest finished run on a later commit of that branch passes, which reads ✓ <workflow> failed, since passed; then it leaves the same way, and the × removes it sooner. A push to the branch runs CI on its newest commit only, so a stack layer's merge commit landed beneath another gets no runs: past the 90 seconds it follows the oldest later commit that has some, reading ✓ checks passed on a later commit once they pass. Later commits count only when the merge commit is among the branch's newest 10. Any other merge whose commit starts no runs within 90 seconds leaves the band.
  • Pushed. A branch Claude pushes with git push gets a line, ⟳ push <branch>, that follows the runs on the branch's newest commit the way a merged line does: it reads ✓ checks passed or names the job that failed, and leaves the same way. A branch that is the head of an open pull request hands its line to that pull request instead, upstream when the branch is on a fork; a pull request in the same repository watched after the push, such as one Claude opens with gh pr create, takes over the push's line in place the first time it is read, and a fork's push is handed over upstream by its own next read. A push that moved no branch, such as a delete, a tag or Everything up-to-date, adds none, and neither does a git push -q, which prints nothing to read. A --dry-run prints what a push would, so it gets a line: a new branch leaves at its first read, and an existing one shows its current checks. A branch gone by the time it is read leaves at once, and one that cannot be read at all, such as on a host gh does not know, leaves once 90 seconds have passed. One whose read GitHub refused, such as for a bad token, a missing scope, SSO or, on github.com, no gh login, stays until pr-watch gives up on it and says so, as for a pull request.

When a workflow has run more than once on the same commit, only its newest run counts.

Once nothing the merge waits on is running, a workflow it does not wait on still shows as a mark while it runs or after it fails.

A toast says when a pull request turns ready to merge, a job fails in a workflow the merge waits on, or a merge's runs on the base branch pass or fail, once per change. A ready toast, and what Claude is told, name any workflow still running that the merge does not wait on. A line says why when gh fails, and · more checks not shown when a commit has more check suites than one read returns (100). Hover a line and press × to stop watching it. A pull request closed without merging leaves the band.

pr-watch draws above whatever other plugins draw in the same band, rather than replacing it.

Telling Claude

pr-watch also tells Claude, so you do not have to prompt it. For news Claude can act on alone, it submits a message to the session, which runs once Claude is idle, when:

  • a run fails, in any workflow, as soon as its first job does, naming the jobs failed by then with links to the first job's log and to the run;
  • a pull request has merge conflicts or a reviewer requests changes, whatever its checks say;
  • someone other than you comments on or reviews it.

News Claude has nothing to do about waits for your next message instead, which carries it to Claude unseen:

  • GitHub reports a pull request ready to merge. Merging needs your ask, so this waits, unless review-cycle's stop-before setting is release or never stop, which lets Claude merge unasked; then it wakes Claude like the news above. pr-watch reads that setting where review-cycle does: .claude/settings.local.json, else the value review-cycle shows in /config, made earlier by .claude/settings.json. Without review-cycle loaded, or with its commit gate off, a ready pull request waits; so it does in a headless claude -p session, where /config lists no plugin's settings. A release tool's version pull request, one headed */version-packages or changeset-release/*, always waits, whatever that setting: merging it is the release. Its news says so, it is neither offered nor suggested, and its line and toasts name it release #<number>.
  • A merge's or a push's checks pass, once its 90 seconds are up, unless Claude made the merge itself (a failure on the merge commit is still told, at once).

Claude can ask to be woken for both instead: the watch tool's wake makes that pull request's turning ready to merge, and its merge's checks passing, wake Claude like the news above, once each, even for a merge Claude made. It is for an ask such as "merge it once it's green", so Claude needs no polling loop of its own. Asked of a pull request already ready, or whose merge's checks already passed, the tool's answer says so, and what already waits for your message still comes with it. An opt-in made while pr-watch is reading that pull request can miss what that read finds, which then waits for your message. It lasts while the pull request is watched in this session, ending however the watch does, and a resumed session does not bring it back. Wake Claude: off still tells Claude nothing.

A pull request ready to merge, a release pull request aside, also puts merge #<number> in the empty prompt box as a suggestion, Tab to take, unless promptSuggestionEnabled is false in your settings. A ready pull request and a failed run also send a notification through your notification channel, beside the toast, for when you are away from the terminal.

Each is told once while it lasts: a later job failing in a run already told, such as a summary job, is not told again, while a new run or a re-run that fails, or a pull request ready again after new checks, is. A watch's first read hears the comments and reviews already there without telling them. Each message says it is news, not a request to merge, and one that says a pull request is ready to merge says so first. If it cannot be submitted, a toast says so; a hook that refuses it shows its own reason. News from these reads that arrives while Claude is working is held until the turn ends, each line once. A pull request it calls ready is then read again, and is not called ready if it has merged or closed meanwhile, or a later read found it no longer ready; a read that fails counts as still open. Your next message reads a waiting ready pull request again the same way, for up to 3 seconds, so it is not called ready once it has merged or closed, is no longer watched, or a later read found it no longer ready. Only a message you send carries the news: a slash command, a background task's notification or another plugin's prompt leaves it waiting, as does a message a hook drops. A ready pull request that cannot be kept for your message wakes Claude instead, a release pull request aside, whose line is dropped; a toast says so, as it does for passed checks it could not keep.

After ten reads in a row whose only news was comments and reviews, those stop waking Claude until other news comes, so a chatty bot or thread cannot keep it busy. The tenth message says so.

Settings

In /config:

SettingValuesDefault
Wake Claudeoff, checks, checks and commentschecks and comments
Bots wake Claudenever, reviews, comments and reviewsnever

checks tells everything above except comments and reviews. off tells Claude nothing, at once or with your next message, and leaves the line, its toasts and notifications as they are. The bot setting applies when Wake Claude includes comments: reviews lets a review bot's reviews through, such as CodeRabbit or Copilot, but not bot comments such as plans, coverage reports or previews. Changing a setting reports no history: comments heard while they were not told stay quiet, and whatever still lasts when waking is turned back on is told once.

Tools for Claude

pr-watch gives Claude three tools, so it can follow a pull request it did not open, such as a teammate's, instead of polling gh pr checks or sleeping:

  • watch takes a pull request's number, URL or head branch, with a repository when it is not the current directory's, and wake to be woken when it turns ready to merge or its merge's checks pass. It reads the pull request at once and answers with what its line shows, along with any news that first read found; pr-watch then tells Claude when that changes. Calling it for a pull request already watched sets wake on it.
  • unwatch stops watching a pull request, by number, URL or head branch, or a pushed branch. A number two watched repositories share is refused until the repository is named.
  • watches lists what pr-watch is watching and what each line shows.

How it works

  • It watches the pull request in the output of a gh pr create that Claude runs through its Bash tool, each pull request a gh stack submit there prints as ✓ Created PR #<n>, even when the command failed after opening some, and the branches in the output of a git push it runs there. Pull requests opened and branches pushed from your own terminal or a GitHub tool are not seen.
  • A gh pr merge Claude runs that names its pull request (a number, URL or branch) watches it too, if nothing did, and follows its merge onto the base branch; with --auto, the line follows the open pull request until it merges. A bare gh pr merge is not followed: after --delete-branch, or on a fork's branch, nothing names its pull request. Neither is a merge run after a cd in the same command or with a GH_HOST= prefix, nor a pull request merged more than two minutes before the command started (the leeway is for GitHub's clock), so a command that only mentions an old merge adds nothing.
  • It reads each pull request, with its latest 10 comments and 10 reviews, in one gh api graphql call: every 10 seconds while any workflow runs or GitHub is still settling, every 60 seconds while it waits on a person, and every 5 minutes once the line has said the same for half an hour, so a pull request left waiting on review, conflicts or failed checks, or a merge left failing, can wait up to 5 minutes for news of a comment or re-run. When Claude runs git push, gh pr merge, gh run rerun, gh workflow run, or gh stack submit, push, sync or merge, it reads every watched pull request at once and every 5 seconds for the next minute, while GitHub starts the new runs. Each workflow's length comes from one gh api call the first time pr-watch sees it, asked again a minute later if that call fails, and once each time a run of it finishes. A re-run's start comes from one gh api call per attempt of the workflow the line draws, asked again a minute later if that call fails, until GitHub refuses it.
  • Each read costs one point of GitHub's GraphQL quota, 5,000 an hour, which your own and Claude's gh calls share: an open pull request is read for its head commit's runs, a merged one for its merge commit's, and the read that first finds it merged reads again for those. A merged one whose merge commit has a failed run, or a stack layer's with none past 90 seconds, also reads its branch's newest 10 commits, for 2 points. While fewer than a tenth of the points are left, every watch on that host is read once a minute, after a push or merge too.
  • When GitHub refuses a read for a rate limit, every watch on that host pauses and its line says rate limited until HH:MM: until the quota resets when the last read left none, otherwise a minute, doubling each time the limit is hit again up to 15 minutes. Each line on the host is read again as the pause ends, and a push not yet read stays through it. When gh cannot reach GitHub at all, as on a dropped connection, a laptop offline, or a 502 to 504 from GitHub's gateway, the line keeps what it last showed, adds a dim · offline, retrying from the second such read, and is never given up on: one read at a time tries the host, 15 seconds after the last, doubling up to a minute, and the note leaves every line on it as soon as GitHub answers anything, a refusal included. After 15 minutes out of reach, a toast names the host and gh's reason once, in case the host or a proxy is wrong. A push no read has answered yet waits 15 minutes from the later of the outage and the push, then leaves; if GitHub answers first, it is read. A read that fails for any other reason is retried after 10 seconds, doubling up to 5 minutes, and shows why in red; after 8 in a row, some 15 minutes, pr-watch stops watching that pull request or push, says why in a toast, and tells Claude, as /config allows. Neither a rate limit nor an unreachable GitHub counts toward the 8. A push that no read has answered yet leaves 90 seconds after it, rate limits and an unreachable GitHub aside, as one on a host gh cannot read would, unless GitHub refused one of its reads.
  • It needs gh, logged in to the pull request's host. GitHub Enterprise hosts are passed to gh as --hostname.
  • Watched pull requests last for the session, and come back when it is resumed, with claude --resume or /resume: pr-watch saves them, keyed by session id, in its own store each time the list changes, and a resumed session keeps its id. Each is read again at once and tells what changed while the session was away, once, as above; news already told before the exit is not told again, but a ready pull request or passed checks kept for a message the exit cut short are. A new session, a fork or a /clear gets a new id and starts with none. Pushed branches are not brought back. The store keeps the latest 20 sessions.

Install

claude plugin marketplace add oakoss/claude-plugins
claude plugin install pr-watch@oakoss

pr-watch is a mod: Claude Code runs its hooks module itself.

Source 5 files
hooks/register.tsx 1450 lines
1import {
2  atom,
3  read,
4  update,
5  type EngineInterface,
6  type PromptOrigin,
7  type PromptSubmitInput,
8  type Register,
9  type Timer,
10} from 'claude-code';
11
12import type { Held, Pull, Stack, Watch, Workflow } from '../types';
13import {
14  attemptArgs,
15  estimateArgs,
16  parseAttemptStart,
17  parseEstimate,
18  parsePull,
19  parsePush,
20  parseQuota,
21  parseStack,
22  parseTrunk,
23  pullArgs,
24  pushArgs,
25  stackArgs,
26  trunkArgs,
27  viewArgs,
28  type Quota,
29} from './github';
30import { configured, loadedRung, mergesUnasked } from './ladder';
31import {
32  changesStacks,
33  createdPull,
34  orderedOf,
35  submittedPulls,
36  mergedPullOf,
37  mergingPull,
38  viewedPull,
39  pushedBranches,
40  pushedPull,
41  belowOf,
42  layerOf,
43  delayOf,
44  errorLine,
45  followTrunk,
46  layeredOf,
47  needsStack,
48  needsTrunk,
49  estimateKey,
50  rerunKey,
51  lineOf,
52  movesPulls,
53  isGone,
54  isChecking,
55  isMergeFresh,
56  isQuotaLow,
57  isReleasePull,
58  isRefused,
59  isNetworkError,
60  isRateLimited,
61  OFFLINE_TELL_MS,
62  offlineDelayOf,
63  GIVE_UP_AFTER,
64  LOW_QUOTA_MS,
65  pauseOf,
66  retryDelayOf,
67  untilText,
68  isSettled,
69  labelOf,
70  shownOf,
71  takeOverPush,
72  settingsOf,
73  tellsOf,
74  stillRunning,
75  toastOf,
76  toldAfter,
77  verdictOf,
78  wakeOf,
79  noticeOf,
80  heldWith,
81  isToldReady,
82  savedOf,
83  entryOf,
84  prunedOf,
85  SESSION_PREFIX,
86  SESSIONS_KEPT,
87  contextOf,
88  suggestionOf,
89  type Merging,
90  type Memory,
91  type Pause,
92  type Segment,
93  type Target,
94  type Wake,
95} from './watch';
96
97type $ = EngineInterface;
98
99const watches = atom({ plugin: 'pr-watch', key: 'watches' } as const, []);
100const estimates = atom({ plugin: 'pr-watch', key: 'estimates' } as const, {});
101const clock = atom({ plugin: 'pr-watch', key: 'now' } as const, 0);
102// A plugin's prompt waits out the turn, so a ready pull request merged in it
103// would arrive stale: news is held until the turn ends.
104const turn = atom({ plugin: 'pr-watch', key: 'turn' } as const, { isTurning: false, held: [] });
105// Merges Claude ran, whose passed checks are no news to it.
106const ownMerges = atom({ plugin: 'pr-watch', key: 'ownMerges' } as const, []);
107// Watches whose ready line and passed checks wake Claude, as it asked.
108const wakeAsked = atom({ plugin: 'pr-watch', key: 'wakeAsked' } as const, []);
109// A ready pull request Claude would need asking to merge, and a merge's passed
110// checks, wait for the person's next prompt rather than waking Claude.
111const quiet = atom({ plugin: 'pr-watch', key: 'quiet' } as const, []);
112// The session id whose saved watches were restored; a resume starts it over.
113const restored = atom({ plugin: 'pr-watch', key: 'restored' } as const, null);
114
115const TICK_MS = 1000;
116const ESTIMATE_RETRY_MS = 60_000;
117const VIEW_TIMEOUT_MS = 10_000;
118// A prompt waits on this read, so it is kept short.
119const PROMPT_VIEW_TIMEOUT_MS = 3000;
120// The prompts the person sent, whose turn may carry kept news.
121const PERSON = new Set<PromptOrigin['kind']>(['composer', 'bridge', 'sdk']);
122const busy = new Set<string>();
123// Layers to read at the next tick, above one whose line changed; apart from
124// the watch, so a read in flight cannot clear the mark.
125const restack = new Set<string>();
126// When each watch was last read, kept here too so a read whose result could
127// not be saved still waits out its delay.
128const tried = new Map<string, number>();
129// When each unanswered length was last asked for, by estimate key.
130const asked = new Map<string, number>();
131// The GraphQL quota each host's latest read reported.
132const quota = new Map<string, Quota>();
133// Each rate-limited host's pause, kept after it ends until a read succeeds, so
134// a limit hit again waits longer.
135const paused = new Map<string, Pause>();
136// Hosts gh could not reach: one read probes each until it answers.
137const unreachable = new Map<
138  string,
139  { count: number; until: number; since: number; isTold: boolean; why: string }
140>();
141
142// GitHub answered, so no line on the host waits on it any more.
143// A push not yet read keeps its note until a read of its own.
144const reachedOn = (w: Watch, host: string): Watch =>
145  w.host === host && w.pull && w.offline !== undefined ? { ...w, offline: undefined } : w;
146// Finished runs a length was learned after, so each one re-learns it once.
147const learnedAfter = new Set<string>();
148// After Claude pushes, merges or starts a run, a watch last read before
149// pushedAt is read at once, and every watch every BURST_MS until burstUntil:
150// GitHub starts the new runs a few seconds later.
151const BURST_MS = 5000;
152const BURST_FOR_MS = 60_000;
153let pushedAt = 0;
154let burstUntil = 0;
155// When Claude last ran a `gh stack` command that can change a stack.
156let stacksChangedAt = 0;
157let poller: Timer | undefined;
158let isTickFailing = false;
159let isSaveFailing = false;
160let isSettingsFailing = false;
161let isStoreFailing = false;
162// A store that failed is not tried again before this, so a broken one is not
163// read every second.
164const STORE_RETRY_MS = 30_000;
165let storeRetryAt = 0;
166// What `remember` last saved, so an unchanged list writes nothing.
167let lastRemembered: string | null = null;
168// The watch ids the last tick saw, so its sweep of wakes drops only those gone since.
169let lastLive = new Set<string>();
170// From /config; a change there reloads the module with the new values.
171let config = { isAwake: true, tells: tellsOf('checks and comments', 'never') };
172
173const idOf = (w: Pick<Watch, 'host' | 'repo' | 'number' | 'push'>) =>
174  `${w.host}/${w.repo}${w.push ? `@${w.push.branch}` : `#${w.number}`}`;
175
176// The same watch, not a later push of the same branch that replaced it.
177const isSame = (a: Watch, b: Watch) => idOf(a) === idOf(b) && a.push?.pushedAt === b.push?.pushedAt;
178
179function errorText(error: unknown): string {
180  return errorLine(error instanceof Error ? error.message : String(error));
181}
182
183// Not awaited: a plugin's prompt runs once the session is idle, so the news
184// waits for any turn in progress rather than holding up the poll. A hook that
185// drops it has its reason shown by the engine.
186function wake($: $, text: string, label: string): void {
187  Promise.resolve()
188    .then(() => $.prompt.submit({ text }))
189    .catch((error: unknown) => {
190      $.ui.toast(`pr-watch could not tell Claude about ${label}: ${errorText(error)}`);
191    })
192    // A toast that throws leaves nowhere to say so.
193    .catch(() => null);
194}
195
196async function tell($: $, h: Held): Promise<void> {
197  if (h.news.length === 0 && h.ready === null) return;
198  if (!(await hold($, h))) await deliver($, h);
199}
200
201// Ready wakes Claude where it asked the watch tool to, or review-cycle lets it
202// merge unasked (not a release pull request: that merge is the release); else
203// it waits for the person's next prompt, decided as it is sent.
204async function deliver($: $, h: Held): Promise<void> {
205  let { ready } = h;
206  if (ready !== null) {
207    const asked = await read($, wakeAsked);
208    if (asked.includes(h.id) || (!h.isRelease && (await isMergeUnasked($)))) {
209      await forgetReady($, h.id).catch((error) =>
210        $.ui.toast(`pr-watch could not clear ${h.label}'s kept ready line: ${errorText(error)}`),
211      );
212    }
213    // A ready line that cannot be kept wakes Claude instead of being lost; a
214    // release's is dropped, its toast having told the person.
215    else if ((await keep($, { ...h, news: [] })) || h.isRelease) ready = null;
216  }
217  if (h.news.length === 0 && ready === null) return;
218  // A turn that started while the settings were read holds it like any other.
219  if (!(await hold($, { ...h, ready }))) wake($, noticeOf(h.news, ready, h.url), h.label);
220}
221
222// Settings that cannot be read leave the merge asked, as no review-cycle does.
223async function isMergeUnasked($: $): Promise<boolean> {
224  try {
225    const of = async (source: 'project' | 'local') => {
226      const settings = await $.settings.read({ source });
227      return configured(settings.pluginConfigs);
228    };
229    const user = loadedRung(await $.config.list());
230    const asked =
231      user !== null &&
232      mergesUnasked({ user, project: await of('project'), local: await of('local') });
233    isSettingsFailing = false;
234    return asked;
235  } catch (error) {
236    if (!isSettingsFailing) {
237      $.ui.toast(
238        `pr-watch could not read review-cycle's stop-before, so a ready pull request waits for your next message: ${errorText(error)}`,
239      );
240    }
241    isSettingsFailing = true;
242    return false;
243  }
244}
245
246// Whether the news is kept; a failure is said, so the caller can send it instead.
247async function keep($: $, h: Held): Promise<boolean> {
248  if (h.news.length === 0 && h.ready === null) return true;
249  try {
250    await update($, quiet, (all) => {
251      const was = all.find((x) => x.id === h.id);
252      return [...all.filter((x) => x.id !== h.id), was ? heldWith(was, h) : h];
253    });
254  } catch (error) {
255    $.ui.toast(
256      `pr-watch could not keep ${h.label}'s news for your next message: ${errorText(error)}`,
257    );
258    return false;
259  }
260  if (h.ready !== null) {
261    await suggest($).catch((error) =>
262      $.ui.toast(`pr-watch could not suggest merging ${h.label}: ${errorText(error)}`),
263    );
264  }
265  return true;
266}
267
268// A ready line Claude is woken for is not told again with the next message.
269async function forgetReady($: $, id: string): Promise<void> {
270  await update($, quiet, (all) =>
271    all.flatMap((x) => {
272      if (x.id !== id) return [x];
273      return x.news.length > 0 ? [{ ...x, ready: null }] : [];
274    }),
275  );
276}
277
278// Shows only between turns; a ready line held through one is kept as it ends.
279async function suggest($: $): Promise<void> {
280  const { isTurning } = await read($, turn);
281  if (isTurning) return;
282  const text = suggestionOf(await read($, quiet));
283  if (text === null) return;
284  // A suggestion is a convenience: one with nowhere to show is let go.
285  try {
286    const settings: { promptSuggestionEnabled?: unknown } = await $.settings.read();
287    if (settings.promptSuggestionEnabled === false) return;
288    await $.prompt.suggest({ text });
289  } catch {
290    // Headless, or the settings unreadable.
291  }
292}
293
294// The ready line stands while GitHub still has the pull request open and the
295// watch is still watched and its latest read found it ready. The saved watch is
296// read after GitHub, so a read during it counts.
297async function isStillReady($: $, id: string, url: string, timeoutMs: number): Promise<boolean> {
298  const isStillOpen = await isOpen($, url, timeoutMs);
299  const all = await read($, watches);
300  const w = all.find((x) => idOf(x) === id);
301  return isStillOpen && w !== undefined && isToldReady(w);
302}
303
304// The kept news a person's prompt carries to Claude, taken in one write so two
305// prompts cannot both carry it, and how to put it back if the prompt is dropped.
306async function quietContext(
307  $: $,
308  e: Pick<PromptSubmitInput, 'origin' | 'command'>,
309): Promise<{ text: string | null; restore: () => Promise<void> } | null> {
310  if (!PERSON.has(e.origin.kind) || e.command !== undefined || !config.isAwake) return null;
311  // Read first, so a prompt with nothing kept writes nothing a refusing store would toast.
312  const waiting = await read($, quiet);
313  if (waiting.length === 0) return null;
314  let taken: readonly Held[] = [];
315  await update($, quiet, (all) => {
316    taken = all;
317    return all.length === 0 ? all : [];
318  });
319  if (taken.length === 0) return null;
320  const restore = async () => {
321    await update($, quiet, (all) => [
322      ...taken.filter((q) => !all.some((x) => x.id === q.id)),
323      ...all.map((x) => {
324        const was = taken.find((q) => q.id === x.id);
325        return was ? heldWith(was, x) : x;
326      }),
327    ]);
328  };
329  try {
330    const current = await Promise.all(
331      taken.map(async (q) =>
332        q.ready === null || (await isStillReady($, q.id, q.url, PROMPT_VIEW_TIMEOUT_MS))
333          ? q
334          : { ...q, ready: null },
335      ),
336    );
337    return { text: contextOf(current), restore };
338  } catch (error) {
339    // Said apart, so the caller's toast keeps the error that stopped the prompt.
340    await restore().catch((restoreError) =>
341      $.ui.toast(`pr-watch lost the news it took for your prompt: ${errorText(restoreError)}`),
342    );
343    throw error;
344  }
345}
346
347// Decided in the same write, so a turn ending meanwhile cannot strand it.
348async function hold($: $, h: Held): Promise<boolean> {
349  let isHeld = false;
350  await update($, turn, (t) => {
351    isHeld = t.isTurning;
352    if (!isHeld) return t;
353    const was = t.held.find((x) => x.id === h.id);
354    return { ...t, held: [...t.held.filter((x) => x.id !== h.id), was ? heldWith(was, h) : h] };
355  });
356  return isHeld;
357}
358
359// A failed read leaves the pull request as last read: open, so still ready.
360async function isOpen($: $, url: string, timeoutMs = VIEW_TIMEOUT_MS): Promise<boolean> {
361  try {
362    const r = await $.process.run(viewArgs(url, null), { timeoutMs });
363    const state = r.exitCode === 0 ? viewedPull(r.stdout)?.body?.state : undefined;
364    return state === undefined || state === 'OPEN';
365  } catch {
366    return true;
367  }
368}
369
370// Not awaited, so the turn's end waits on no gh call.
371function releaseHeld($: $): void {
372  void release($).catch((error) =>
373    $.ui.toast(`pr-watch could not send the news it held: ${errorText(error)}`),
374  );
375}
376
377// Each watch's news at once, so one slow read delays only its own.
378async function release($: $): Promise<void> {
379  const { held } = await read($, turn);
380  await Promise.all(held.map(({ id }) => releaseOne($, id)));
381}
382
383async function releaseOne($: $, id: string): Promise<void> {
384  const { held } = await read($, turn);
385  const seen = held.find((x) => x.id === id);
386  if (!seen) return;
387  const isStale = seen.ready !== null && !(await isStillReady($, id, seen.url, VIEW_TIMEOUT_MS));
388  // Taken only now: a reload during the read leaves it held, news held for it
389  // meanwhile joins this notice, and a turn started meanwhile keeps it.
390  let h: Held | undefined;
391  await update($, turn, (t) => {
392    h = t.isTurning ? undefined : t.held.find((x) => x.id === id);
393    return h ? { ...t, held: t.held.filter((x) => x.id !== id) } : t;
394  });
395  if (!h) return;
396  await deliver($, { ...h, ready: isStale ? null : h.ready });
397}
398
399// An unknown length that cannot be learned or kept is asked again after the
400// retry delay, the run drawing no bar meanwhile. A known one is asked again
401// once per finished run, and kept when that answer is missing or says none.
402async function learnEstimates($: $, w: Watch, now: number): Promise<void> {
403  let known: Record<string, number>;
404  try {
405    known = await read($, estimates);
406  } catch {
407    return;
408  }
409  // Only the workflow the line draws shows a re-run's clock.
410  const v = w.pull ? verdictOf(w.pull, known, w.host, now) : null;
411  const drawn = v?.kind === 'running' || v?.kind === 'merged-running' ? v.gate : null;
412  if (drawn?.isRerun) await learnRerunStart($, w, drawn, known, now);
413  for (const flow of [...(w.pull?.workflows ?? []), ...(w.pull?.mergeRuns?.workflows ?? [])]) {
414    const key = estimateKey(w.host, flow.id);
415    const run = flow.status === 'done' ? JSON.stringify([key, flow.url, flow.attempt]) : null;
416    const isKnown = known[key] !== undefined;
417    if (isKnown) {
418      if (run === null || learnedAfter.has(run)) continue;
419      learnedAfter.add(run);
420    } else if (now - (asked.get(key) ?? -Infinity) < ESTIMATE_RETRY_MS) {
421      continue;
422    }
423    asked.set(key, now);
424    try {
425      const r = await $.process.run(estimateArgs(w.host, w.repo, flow.id), {
426        timeoutMs: VIEW_TIMEOUT_MS,
427      });
428      const ms = r.exitCode === 0 ? parseEstimate(r.stdout) : null;
429      if (ms === null || (ms === 0 && isKnown)) continue;
430      await update($, estimates, (all) => ({ ...all, [key]: ms }));
431      asked.delete(key);
432      if (run !== null) learnedAfter.add(run);
433    } catch {
434      continue;
435    }
436  }
437}
438
439// Asked once per attempt, and again after the retry delay when that fails,
440// until GitHub refuses it; the line says `re-run` without a clock meanwhile.
441async function learnRerunStart(
442  $: $,
443  w: Watch,
444  flow: Workflow,
445  known: Record<string, number>,
446  now: number,
447): Promise<void> {
448  if (flow.runId === undefined) return;
449  const key = rerunKey(w.host, flow.runId, flow.attempt);
450  if (known[key] !== undefined || now - (asked.get(key) ?? -Infinity) < ESTIMATE_RETRY_MS) return;
451  asked.set(key, now);
452  try {
453    const r = await $.process.run(attemptArgs(w.host, w.repo, flow.runId, flow.attempt), {
454      timeoutMs: VIEW_TIMEOUT_MS,
455    });
456    // The run is gone, or the token cannot read Actions: asking again will not
457    // help. A rate limit is a 403 too, but it lifts.
458    if (r.exitCode !== 0 && /HTTP 40[34]\b/.test(r.stderr) && !isRateLimited(r.stdout, r.stderr)) {
459      asked.set(key, Infinity);
460      return;
461    }
462    const start = r.exitCode === 0 ? parseAttemptStart(r.stdout) : null;
463    if (start === null) return;
464    await update($, estimates, (all) => ({ ...all, [key]: start }));
465    asked.delete(key);
466  } catch {
467    // Left for the retry delay, as an estimate is.
468  }
469}
470
471class Offline extends Error {}
472
473class RateLimited extends Error {
474  constructor(readonly until: number) {
475    super(`rate limited until ${untilText(until)}`);
476  }
477}
478
479// gh exits non-zero when GraphQL reports any error, even beside usable data.
480async function readGh<T>(
481  $: $,
482  host: string,
483  argv: string[],
484  parse: (stdout: string) => T,
485): Promise<T> {
486  const before = paused.get(host);
487  if (before && (await $.clock.now()) < before.until) {
488    throw new RateLimited(before.until);
489  }
490  const r = await $.process.run(argv);
491  const left = parseQuota(r.stdout);
492  const was = quota.get(host);
493  // Reads finish out of order: within one reset window, the lowest count is the latest.
494  const isStale = was?.resetAt === left?.resetAt && (was?.remaining ?? 0) < (left?.remaining ?? 0);
495  if (left && !isStale) quota.set(host, left);
496  if (r.exitCode !== 0 && isRateLimited(r.stdout, r.stderr)) {
497    const now = await $.clock.now();
498    // Reads limited together pause once, rather than each doubling the wait.
499    const current = paused.get(host);
500    const pause = current && current !== before ? current : pauseOf(quota.get(host), current, now);
501    paused.set(host, pause);
502    throw new RateLimited(pause.until);
503  }
504  try {
505    return parse(r.stdout);
506  } catch (error) {
507    if (r.exitCode === 0) throw error;
508    if (isNetworkError(r.stderr)) throw new Offline(r.stderr.trim(), { cause: error });
509    throw new Error(r.stderr.trim() || `gh exited ${r.exitCode}`, { cause: error });
510  }
511}
512
513type Read = { kind: 'pull'; pull: Pull } | { kind: 'handoff'; to: Watch } | { kind: 'gone' };
514
515// A push whose branch heads an open pull request hands its line to that PR.
516async function readWatch($: $, w: Watch): Promise<Read> {
517  if (!w.push) {
518    const readPull = (isMerged: boolean) =>
519      readGh($, w.host, pullArgs(w.host, w.repo, w.number, isMerged), parsePull);
520    // Until a read says it merged, read the open variant; on the read that
521    // first finds it merged, read again for the merge commit's runs.
522    const wasMerged = w.pull?.state === 'MERGED';
523    const pull = await readPull(wasMerged);
524    const askedAt = await $.clock.now();
525    // A stack kept from before a module reload is asked again once.
526    stacksChangedAt ||= askedAt - 1;
527    const isMerged = pull.state === 'MERGED';
528    const isAsked = needsStack(w.pull, isMerged, askedAt, stacksChangedAt);
529    const answer = isAsked ? await stackOf($, w) : undefined;
530    const layered = layeredOf(w.pull, answer, isMerged, askedAt);
531    if (pull.state !== 'MERGED') {
532      const open = { ...pull, ...layered };
533      const below = belowOf(w, open, await read($, watches), await read($, estimates));
534      return { kind: 'pull', pull: below ? { ...open, below } : open };
535    }
536    let merged = pull;
537    if (!wasMerged) {
538      try {
539        merged = await readPull(true);
540      } catch (error) {
541        // Just merged, it shows as waiting on checks while the next read asks for
542        // them. Older, it would read as closed and leave, so the failure is said.
543        if (error instanceof RateLimited || !isMergeFresh(pull, await $.clock.now())) throw error;
544        merged = { ...pull, workflows: [], mergeRuns: null };
545      }
546    }
547    const { stack } = layered;
548    const trunk = stack === undefined ? undefined : (stack?.trunk ?? null);
549    const onTrunk = { ...merged, ...layered, base: trunk ?? merged.base };
550    // Until the stacks API answers, the base may be the layer below, whose
551    // history never holds the merge commit.
552    if (trunk === undefined || !needsTrunk(onTrunk, await $.clock.now())) {
553      return { kind: 'pull', pull: onTrunk };
554    }
555    try {
556      const commits = await readGh($, w.host, trunkArgs(w.host, w.repo, onTrunk.base), parseTrunk);
557      return { kind: 'pull', pull: followTrunk(onTrunk, commits) };
558    } catch (error) {
559      // The merge commit's own runs, a failure among them, stand; with none,
560      // the line would read as closed and leave. A rate limit has already
561      // paused the host for the next read.
562      if ((onTrunk.mergeRuns?.workflows.length ?? 0) === 0) throw error;
563      return { kind: 'pull', pull: onTrunk };
564    }
565  }
566  const { branch, pushedAt } = w.push;
567  const pushed = await readGh($, w.host, pushArgs(w.host, w.repo, branch), parsePush);
568  if (pushed.kind === 'gone') return pushed;
569  if (pushed.kind === 'pr') {
570    const { repo, number } = pushed;
571    const url = pushed.url ?? `https://${w.host}/${repo}/pull/${number}`;
572    return { kind: 'handoff', to: { host: w.host, repo, number, url, checkedAt: 0 } };
573  }
574  return { kind: 'pull', pull: pushedPull(branch, pushedAt, pushed.runs) };
575}
576
577// Null in no stack, 'unreadable' without the stacks API or access to it, and
578// undefined when GitHub did not say. REST, so its rate limit pauses no GraphQL read.
579async function stackOf($: $, w: Watch): Promise<Stack | null | 'unreadable' | undefined> {
580  const now = await $.clock.now();
581  const key = `${w.host}/stack/${w.repo}#${w.number}`;
582  const pause = paused.get(w.host);
583  if ((pause && now < pause.until) || now - (asked.get(key) ?? -Infinity) < ESTIMATE_RETRY_MS) {
584    return undefined;
585  }
586  asked.set(key, now);
587  try {
588    const r = await $.process.run(stackArgs(w.host, w.repo, w.number), {
589      timeoutMs: VIEW_TIMEOUT_MS,
590    });
591    if (r.exitCode !== 0) {
592      // No stacks API, or a token that may not read it; a rate limit is a 403 too.
593      const isMissing = /HTTP 40[34]\b/.test(r.stderr) && !isRateLimited(r.stdout, r.stderr);
594      return isMissing ? 'unreadable' : undefined;
595    }
596    const stack = parseStack(r.stdout);
597    asked.delete(key);
598    return stack;
599  } catch {
600    return undefined;
601  }
602}
603
604// What a read leaves for a caller that tells it itself: its news, whether it
605// found the pull request closed, and why it could not finish.
606type Kept = { news: string | null; isClosed?: boolean; error?: string };
607
608async function refresh($: $, target: Watch, now: number, kept?: Kept): Promise<void> {
609  const id = idOf(target);
610  busy.add(id);
611  restack.delete(id);
612  tried.set(id, now);
613  try {
614    let next: Watch;
615    let isLimited = false;
616    let isOffline = false;
617    const pause = paused.get(target.host);
618    // A read that began before another read paused the host still waits it out.
619    const pausedUntil = async () => {
620      const until = paused.get(target.host)?.until;
621      return until !== undefined && (await $.clock.now()) < until ? until : undefined;
622    };
623    try {
624      const read = await readWatch($, target);
625      // Only a whole read that began after the pause was set shows the limit
626      // lifted: a merged pull request's second read may still be refused.
627      if (paused.get(target.host) === pause) paused.delete(target.host);
628      unreachable.delete(target.host);
629      const limitedUntil = await pausedUntil();
630      if (read.kind === 'gone') {
631        await update($, watches, (all) =>
632          all.filter((w) => !isSame(w, target)).map((w) => reachedOn(w, target.host)),
633        );
634        return;
635      }
636      if (read.kind === 'handoff') {
637        // The PR's runs are the push's, so what Claude was told of carries over.
638        const told = target.told ?? [];
639        const to = { ...read.to, told };
640        await update($, watches, (all) => {
641          if (!all.some((w) => isSame(w, target))) return all;
642          const rest = all.filter((w) => !isSame(w, target)).map((w) => reachedOn(w, target.host));
643          if (!rest.some((w) => idOf(w) === idOf(to))) return [...rest, to];
644          return rest.map((w) =>
645            idOf(w) === idOf(to) ? { ...w, told: [...new Set([...(w.told ?? []), ...told])] } : w,
646          );
647        });
648        return;
649      }
650      next = {
651        ...target,
652        pull: read.pull,
653        error: undefined,
654        failures: undefined,
655        refused: undefined,
656        offline: undefined,
657        limitedUntil,
658        checkedAt: now,
659      };
660    } catch (error) {
661      // checkedAt stays the last good read's: settling is judged by it, and
662      // `tried` already spaces the retries. A rate limit is GitHub's to lift,
663      // so it does not count toward giving up.
664      if (!(error instanceof Offline)) unreachable.delete(target.host);
665      if (error instanceof RateLimited) {
666        isLimited = true;
667        next = { ...target, offline: undefined, limitedUntil: error.until };
668      } else if (error instanceof Offline) {
669        // Neither counted toward giving up nor shown in red: the line stays as last read.
670        isOffline = true;
671        const at = await $.clock.now();
672        const was = unreachable.get(target.host);
673        // Lines that fail in the same round count once, so the wait doubles per probe.
674        const isSameRound = was !== undefined && at < was.until;
675        const count = isSameRound ? was.count : (was?.count ?? 0) + 1;
676        unreachable.set(target.host, {
677          count,
678          since: was?.since ?? at,
679          isTold: was?.isTold ?? false,
680          until: isSameRound ? was.until : at + offlineDelayOf(count),
681          why: errorText(error),
682        });
683        if (kept)
684          kept.error = `GitHub could not be reached (${errorText(error)}); pr-watch keeps trying`;
685        next = { ...target, offline: count, limitedUntil: await pausedUntil() };
686      } else {
687        const why = errorText(error);
688        next = {
689          ...target,
690          error: `gh failed: ${why}`,
691          failures: (target.failures ?? 0) + 1,
692          refused: isRefused(why, target.host) ? true : target.refused,
693          offline: undefined,
694          limitedUntil: await pausedUntil(),
695        };
696      }
697    }
698    // An offline read keeps the line, so failures left by earlier saves must not end it.
699    const isGivenUp = !isLimited && !isOffline && (next.failures ?? 0) >= GIVE_UP_AFTER;
700    // Only a read that answered is judged; a limited one keeps the last good state.
701    const isFresh = !isLimited && !isOffline && next.error === undefined;
702    let toast: string | null = null;
703    let isUrgent = false;
704    let news: string | null = null;
705    let woke = null as Wake | null;
706    let wakeFor: ((last: Memory) => Wake) | null = null;
707    let isClosed = false;
708    let isMoved = false;
709    let isWakeAsked = false;
710    if (next.pull && isFresh) {
711      const pull = next.pull;
712      const verdict = verdictOf(pull, await read($, estimates), next.host, now);
713      isClosed = verdict.kind === 'closed';
714      if (kept) kept.isClosed = isClosed;
715      if (!isClosed) {
716        // A passed merge is said only once no later run can start: until then
717        // it is not yet what the line has said.
718        const isEarly = verdict.kind === 'merged-passed' && !isSettled(verdict, pull, now);
719        const shown = target.shown;
720        const merged = await read($, ownMerges);
721        const asked = await read($, wakeAsked);
722        isWakeAsked = asked.includes(idOf(next));
723        // A merge Claude made is news once it asked to hear its checks pass.
724        const isOwnMerge = merged.includes(idOf(next)) && !isWakeAsked;
725        wakeFor = (last) =>
726          wakeOf(next, pull, verdict, last, { isEarly, isOwnMerge, tells: config.tells });
727        // A ready pull request read as checking is not ready again afterwards.
728        if (!isEarly && !isChecking(verdict)) {
729          const after = next.push ? '' : ' merged';
730          toast = toastOf(labelOf(next), verdict, shown, after, stillRunning(pull));
731          // What someone away from the terminal comes back for; a passed merge is not.
732          isUrgent = ['ready', 'failing', 'merged-failing'].includes(verdict.kind);
733          next.shown = shownOf(verdict);
734          if (next.shown !== shown || next.shownAt === undefined) next.shownAt = now;
735          isMoved = next.shown !== shown;
736        }
737      }
738    }
739    let isSaved = false;
740    await update($, watches, (all) => {
741      isSaved = all.some((w) => isSame(w, target));
742      // The host's other lines wait on this read's probe, so they say so too.
743      if (isOffline) {
744        const { offline } = next;
745        return all.map((w) =>
746          isSame(w, target) ? next : w.host === next.host ? { ...w, offline } : w,
747        );
748      }
749      // Any answer, a refusal or a limit included, shows GitHub is reachable.
750      const reached = all.map((w) => reachedOn(w, next.host));
751      if (isClosed || isGivenUp) return reached.filter((w) => !isSame(w, target));
752      // Every watch on the host waits out the pause, so each line says so.
753      if (isLimited) {
754        const { limitedUntil } = next;
755        return reached.map((w) =>
756          isSame(w, target) ? next : w.host === next.host ? { ...w, limitedUntil } : w,
757        );
758      }
759      if (wakeFor) {
760        // Judged against every watch on the host as saved now: a push and its
761        // pull request read the same runs, and either may be read first.
762        const known = all.filter((w) => w.host === next.host).flatMap((w) => w.told ?? []);
763        const told = [...new Set([...(target.told ?? []), ...known])];
764        woke = wakeFor({ told, heard: target.heard });
765        // With waking off, comments are still heard, so turning it on reports no
766        // history of them.
767        if (config.isAwake) news = woke.text;
768        next.told = toldAfter(woke.told, target.told, config.isAwake);
769        next.heard = woke.heard;
770      }
771      // A layer above one whose line changed is read at once, since it may
772      // wait on this one.
773      const layer = isMoved ? layerOf(next) : null;
774      for (const number of layer ? (next.pull?.stack?.layers.slice(layer.at) ?? []) : []) {
775        restack.add(idOf({ host: next.host, repo: next.repo, number }));
776      }
777      return takeOverPush(
778        reached.map((w) => (isSame(w, target) ? next : w)),
779        next,
780      );
781    });
782    isSaveFailing = false;
783    // Only once the line says it, so a lost save does not toast or wake again.
784    if (toast && isSaved) {
785      $.ui.toast(toast);
786      if (isUrgent) void $.ui.notify(toast).catch(() => null);
787    }
788    if (isGivenUp && isSaved) {
789      $.ui.toast(`pr-watch stopped watching ${labelOf(next)}: ${next.error}`);
790      news = [
791        `pr-watch: ${GIVE_UP_AFTER} reads of ${nameOf(next)} in a row failed, so pr-watch stopped watching it. The last: ${next.error}`,
792        next.push
793          ? `pr-watch follows the branch again on its next push once gh can read it. ${next.url}`
794          : `Watch it again with pr-watch's watch tool once gh can read it. ${next.url}`,
795      ].join('\n');
796      // A tool's caller is told in its answer, whatever /config says.
797      if (!kept && !config.isAwake) news = null;
798    }
799    if (news && isSaved) {
800      if (kept) kept.news = news;
801      else if (isGivenUp || !woke) wake($, news, labelOf(next));
802      else {
803        const { news: lines, ready, passed } = woke;
804        const isRelease = next.pull !== undefined && isReleasePull(next.pull);
805        const h = { id: idOf(next), label: labelOf(next), url: next.url, isRelease };
806        if (isWakeAsked) await tell($, { ...h, news: [...lines, ...passed], ready });
807        else {
808          await tell($, { ...h, news: lines, ready });
809          await keep($, { ...h, news: passed, ready: null });
810        }
811      }
812    }
813    if (!isClosed && isFresh) await learnEstimates($, next, now);
814  } catch (error) {
815    // Kept on the line so the band says why; said once when even that fails.
816    // The read itself succeeded or was caught above, so this is pr-watch's own,
817    // counted so that one failing every time is retried less often.
818    const why = errorText(error);
819    if (kept) kept.error = why;
820    // The read ran, so the line says a pause only while its host is still in one.
821    const until = paused.get(target.host)?.until;
822    const limitedUntil = until !== undefined && (await $.clock.now()) < until ? until : undefined;
823    try {
824      await update($, watches, (all) =>
825        all.map((w) =>
826          isSame(w, target)
827            ? {
828                ...w,
829                error: `pr-watch failed: ${why}`,
830                failures: (w.failures ?? 0) + 1,
831                limitedUntil,
832              }
833            : w,
834        ),
835      );
836    } catch {
837      if (!isSaveFailing) $.ui.toast(`pr-watch could not save ${labelOf(target)}: ${why}`);
838      isSaveFailing = true;
839    }
840  } finally {
841    busy.delete(id);
842  }
843}
844
845async function tick($: $): Promise<void> {
846  const saved = await read($, watches);
847  await remember($, saved);
848  // A watch gone by any route takes its wake with it, so a later watch of the
849  // same pull request starts quiet. Only one seen at the last tick counts as
850  // gone, so a wake asked while this read was out is kept.
851  const live = new Set(saved.map((w) => idOf(w)));
852  const gone = [...lastLive].filter((id) => !live.has(id));
853  lastLive = live;
854  if (gone.length > 0) await update($, wakeAsked, (ids) => ids.filter((id) => !gone.includes(id)));
855  // A host no line is on any more is forgotten, so a later outage starts afresh.
856  for (const host of unreachable.keys()) {
857    if (!saved.some((w) => w.host === host)) unreachable.delete(host);
858  }
859  if (saved.length === 0) return;
860  const now = await $.clock.now();
861  const known = await read($, estimates);
862  // A host or proxy that will never answer looks like a blip until someone is
863  // told; said before the lines that waited on it can leave.
864  for (const [host, down] of unreachable) {
865    if (down.isTold || now - down.since < OFFLINE_TELL_MS) continue;
866    down.isTold = true;
867    $.ui.toast(
868      `pr-watch cannot reach ${host}: ${down.why}. It keeps trying; unwatch a line with its × if the host or proxy is wrong.`,
869    );
870  }
871  // Judged on the list as saved, so a push that replaced a watch since stays.
872  let list: Watch[] = [];
873  await update($, watches, (all) => {
874    // A watch added while its host is paused waits it out like the rest, and
875    // says so; a push not yet read stays while it waits.
876    let isChanged = false;
877    list = all.flatMap((w) => {
878      const until = paused.get(w.host)?.until ?? 0;
879      const held = now < until && w.limitedUntil === undefined ? { ...w, limitedUntil: until } : w;
880      if (held !== w) isChanged = true;
881      // A line GitHub could not be asked about waits, as a paused unread push does,
882      // until its host has been out of reach long enough to be told.
883      const down = unreachable.get(held.host);
884      const isLongDown = down !== undefined && now - down.since >= OFFLINE_TELL_MS;
885      const isUnreached = down !== undefined && !isLongDown;
886      // An unread push waits for a read of its own: while its host is out of
887      // reach, 15 minutes from the later of the outage and the push; after, until read.
888      const waitedFrom = Math.max(down?.since ?? 0, held.push?.pushedAt ?? 0);
889      const isUnread =
890        !held.pull &&
891        (down === undefined
892          ? held.offline !== undefined || held.limitedUntil !== undefined
893          : now - waitedFrom < OFFLINE_TELL_MS);
894      const isWaiting = isUnreached || isUnread;
895      const isKept = !isGone(held, known, now) || isWaiting;
896      if (!isKept) isChanged = true;
897      return isKept ? [held] : [];
898    });
899    return isChanged ? list : all;
900  });
901  let isMoving = false;
902  const probed = new Set<string>();
903  for (const w of list) {
904    // Settling and closing are judged at the last read, so a run that started
905    // after it is not missed.
906    const verdict = w.pull ? verdictOf(w.pull, known, w.host, w.checkedAt) : null;
907    if (verdict?.kind === 'running' || verdict?.kind === 'merged-running') isMoving = true;
908    const pauseEnd = paused.get(w.host)?.until ?? 0;
909    if (now < pauseEnd) continue;
910    // One read at a time tries a host gh could not reach, not every line on it.
911    const down = unreachable.get(w.host);
912    if (down) {
913      // A probe still in flight counts, so a slow one is not joined by another.
914      const isProbing = list.some((x) => x.host === w.host && busy.has(idOf(x)));
915      if (now < down.until || probed.has(w.host) || isProbing) continue;
916      probed.add(w.host);
917      void refresh($, w, now);
918      continue;
919    }
920    const usual = verdict && w.pull ? delayOf(verdict, w.pull, w.checkedAt, w.shownAt) : 10_000;
921    // A failing watch retries on its own schedule; low on quota, a watch waits
922    // its slow delay. Neither bursts.
923    const low = isQuotaLow(quota.get(w.host)) ? LOW_QUOTA_MS : 0;
924    const isSlowed = low > 0 || Boolean(w.failures);
925    const delay =
926      usual === null
927        ? null
928        : w.failures
929          ? Math.max(retryDelayOf(w.failures), low)
930          : low > 0
931            ? Math.max(usual, low)
932            : now < burstUntil
933              ? Math.min(usual, BURST_MS)
934              : usual;
935    if (delay === null || busy.has(idOf(w))) continue;
936    const last = Math.max(w.checkedAt, tried.get(idOf(w)) ?? 0);
937    // A line says the pause until a read of its own, so the end of one reads it at once.
938    const isDue =
939      w.limitedUntil !== undefined ||
940      (last <= pushedAt && !isSlowed) ||
941      now - last >= delay ||
942      (restack.has(idOf(w)) && !isSlowed);
943    if (isDue) void refresh($, w, now);
944  }
945  if (isMoving) await update($, clock, () => now);
946}
947
948async function storeFailed($: $, what: string, error: unknown): Promise<void> {
949  if (!isStoreFailing) $.ui.toast(`pr-watch could not ${what}: ${errorText(error)}`);
950  isStoreFailing = true;
951  storeRetryAt = (await $.clock.now()) + STORE_RETRY_MS;
952}
953
954// The pull requests watched, saved under the session's id whenever they
955// change, so `claude --resume` can watch them again. Nothing is written for
956// the session until its own saved watches are restored, so a failed restore
957// does not overwrite them, and the list is saved from the next tick, which
958// holds what the restore added; a session that never watched one saves
959// nothing. A store that refuses is tried again after STORE_RETRY_MS.
960async function remember($: $, list: readonly Watch[]): Promise<void> {
961  try {
962    const now = await $.clock.now();
963    if (now < storeRetryAt) return;
964    const id = await $.session.id();
965    if ((await read($, restored)) !== id) {
966      await restore($, id);
967      return;
968    }
969    const { held } = await read($, turn);
970    const kept = await read($, quiet);
971    const pending = {
972      ready: new Set([...held, ...kept].filter((h) => h.ready !== null).map((h) => h.id)),
973      passed: new Set(kept.filter((h) => h.news.length > 0).map((h) => h.id)),
974    };
975    const pulls = savedOf(list, pending, idOf);
976    const text = JSON.stringify([id, pulls]);
977    if (text === lastRemembered) return;
978    const key = SESSION_PREFIX + id;
979    if (pulls.length > 0 || (await $.store.get(key)) !== undefined) {
980      await $.store.set(key, { at: now, pulls });
981      await prune($);
982    }
983    lastRemembered = text;
984    storeRecovered();
985  } catch (error) {
986    await storeFailed($, 'save its watches for a resume', error);
987  }
988}
989
990function storeRecovered(): void {
991  isStoreFailing = false;
992  storeRetryAt = 0;
993}
994
995async function prune($: $): Promise<void> {
996  const all = await $.store.keys();
997  const keys = all.filter((k) => k.startsWith(SESSION_PREFIX));
998  if (keys.length <= SESSIONS_KEPT) return;
999  const entries = await Promise.all(keys.map(async (k) => [k, await $.store.get(k)] as const));
1000  for (const key of prunedOf(entries)) await $.store.delete(key);
1001}
1002
1003// A resumed session keeps its id, so it finds what it watched; a new one, a
1004// fork or a /clear does not. Each is read again at once, telling what changed
1005// while the session was away. Done once per session: `restored` outlives a
1006// reload of this module, so a reload brings back nothing the person unwatched.
1007async function restore($: $, id: string): Promise<void> {
1008  try {
1009    const { pulls, skipped } = entryOf(await $.store.get(SESSION_PREFIX + id));
1010    if (pulls.length > 0)
1011      await update($, watches, (all) => {
1012        const added: Watch[] = [];
1013        for (const p of pulls) {
1014          if (![...all, ...added].some((w) => idOf(w) === idOf(p)))
1015            added.push({ ...p, checkedAt: 0 });
1016        }
1017        return added.length === 0 ? all : [...all, ...added];
1018      });
1019    await update($, restored, () => id);
1020    storeRecovered();
1021    if (skipped > 0) {
1022      $.ui.toast(
1023        `pr-watch restored the session's watches but skipped ${skipped} it could not read`,
1024      );
1025    }
1026  } catch (error) {
1027    await storeFailed($, "restore the session's watches", error);
1028  }
1029}
1030
1031// A poll that fails is said once, until one succeeds.
1032async function safeTick($: $): Promise<void> {
1033  try {
1034    await tick($);
1035    isTickFailing = false;
1036  } catch (error) {
1037    if (!isTickFailing) $.ui.toast(`pr-watch stopped updating: ${errorText(error)}`);
1038    isTickFailing = true;
1039  }
1040}
1041
1042// Watches the pull request a merge named, unless something already does.
1043async function followMerge($: $, m: Merging, startedAt: number): Promise<void> {
1044  try {
1045    const r = await $.process.run(viewArgs(m.pull, m.repo), { timeoutMs: VIEW_TIMEOUT_MS });
1046    if (r.exitCode !== 0) throw new Error(r.stderr.trim() || `gh exited ${r.exitCode}`);
1047    const target = mergedPullOf(r.stdout, startedAt);
1048    if (target === 'stale') return;
1049    if (target === null) {
1050      throw new Error(
1051        `gh pr view named no pull request: ${r.stdout.trim().slice(0, 80) || '(empty)'}`,
1052      );
1053    }
1054    const id = idOf(target);
1055    // Not one GitHub merged later on --auto, which is news to Claude.
1056    if (viewedPull(r.stdout)?.body?.state === 'MERGED') {
1057      await update($, ownMerges, (ids) => [...new Set([...ids, id])]);
1058    }
1059    await update($, watches, (all) =>
1060      all.some((w) => idOf(w) === id) ? all : [...all, { ...target, checkedAt: 0 }],
1061    );
1062  } catch (error) {
1063    $.ui.toast(`pr-watch could not follow the merge of ${m.pull}: ${errorText(error)}`);
1064  }
1065}
1066
1067async function stop($: $, id: string): Promise<void> {
1068  await update($, watches, (all) => all.filter((w) => idOf(w) !== id));
1069  await forgetWake($, id);
1070}
1071
1072// So a later watch of the same pull request starts quiet.
1073async function forgetWake($: $, id: string): Promise<void> {
1074  await update($, wakeAsked, (ids) => ids.filter((x) => x !== id));
1075}
1076
1077const TOOL_COLUMNS = 80;
1078
1079// A watch's line as text, for a tool's answer.
1080function textOf(w: Watch, now: number, known: Record<string, number>): string {
1081  return lineOf(w, now, known, TOOL_COLUMNS)
1082    .map((s) => s.text)
1083    .join('');
1084}
1085
1086const nameOf = (w: Pick<Watch, 'repo' | 'number' | 'push'>) =>
1087  w.push ? `the push to ${w.push.branch} on ${w.repo}` : `${w.repo}#${w.number}`;
1088
1089type ToolInput = { pull: string; repo: string | null; wake: boolean };
1090
1091function toolInputOf(e: unknown): ToolInput | string {
1092  const { pull, repo, wake } = e as { pull?: unknown; repo?: unknown; wake?: unknown };
1093  if (typeof pull !== 'string' || pull.trim() === '') {
1094    return 'pr-watch: `pull` names a pull request: its number, URL or head branch.';
1095  }
1096  if (repo !== undefined && repo !== null && typeof repo !== 'string') {
1097    return 'pr-watch: `repo` is the repository as owner/name.';
1098  }
1099  if (wake !== undefined && wake !== null && typeof wake !== 'boolean') {
1100    return 'pr-watch: `wake` is true or false.';
1101  }
1102  return {
1103    pull: pull.trim(),
1104    repo: typeof repo === 'string' && repo !== '' ? repo : null,
1105    wake: wake === true,
1106  };
1107}
1108
1109// The pull request gh resolves a tool's input to, or why it cannot.
1110async function viewedTarget($: $, input: ToolInput): Promise<Target | string> {
1111  const r = await $.process.run(viewArgs(input.pull, input.repo), {
1112    timeoutMs: VIEW_TIMEOUT_MS,
1113  });
1114  if (r.exitCode !== 0) {
1115    const why = r.stderr.trim() ? errorText(r.stderr) : `gh exited ${r.exitCode}`;
1116    return `pr-watch could not read ${input.pull} with gh pr view: ${why}`;
1117  }
1118  const printed = r.stdout.trim().slice(0, 80) || '(empty)';
1119  return (
1120    viewedPull(r.stdout)?.target ??
1121    `pr-watch: gh pr view named no pull request for ${input.pull}: ${printed}`
1122  );
1123}
1124
1125// Watches a pull request and answers with what it shows now. The news a first
1126// read finds goes in the answer: the host refuses a prompt from a tool call's
1127// hook, since it would wait on the turn the hook holds.
1128async function onWatchTool($: $, e: unknown): Promise<{ result: string }> {
1129  const input = toolInputOf(e);
1130  if (typeof input === 'string') return { result: input };
1131  let name = input.pull;
1132  let isAdded = false;
1133  try {
1134    const target = await viewedTarget($, input);
1135    if (typeof target === 'string') return { result: target };
1136    const id = idOf(target);
1137    name = nameOf(target);
1138    let isNew = false;
1139    await update($, watches, (all) => {
1140      if (all.some((w) => idOf(w) === id)) return all;
1141      isNew = true;
1142      return [...all, { ...target, checkedAt: 0 }];
1143    });
1144    isAdded = true;
1145    if (input.wake) await update($, wakeAsked, (ids) => [...new Set([...ids, id])]);
1146    const now = await $.clock.now();
1147    const kept: Kept = { news: null };
1148    const before = await read($, watches);
1149    const watch = before.find((w) => idOf(w) === id);
1150    // A read already in flight tells its own news; a second would toast it again.
1151    if (watch && !busy.has(id)) await refresh($, watch, now, kept);
1152    const saved = await read($, watches);
1153    const after = saved.find((w) => idOf(w) === id);
1154    if (!after) {
1155      if (kept.isClosed) return { result: `${name} is closed, so pr-watch is not watching it.` };
1156      return {
1157        result:
1158          kept.news ?? `${name} is no longer watched: its line was removed while pr-watch read it.`,
1159      };
1160    }
1161    const known = await read($, estimates);
1162    const line = textOf(after, now, known);
1163    const head = `pr-watch ${isNew ? 'is now watching' : 'was already watching'} ${name}: ${line}`;
1164    if (kept.error !== undefined) {
1165      return { result: `${head}\npr-watch could not finish its first read: ${kept.error}` };
1166    }
1167    // Already there, it was told before and will not wake: the line says it now.
1168    // A passed merge counts only once settled, as a read tells it.
1169    const verdict = after.pull ? verdictOf(after.pull, known, after.host, now) : null;
1170    const isPassed =
1171      verdict?.kind === 'merged-passed' && after.pull && isSettled(verdict, after.pull, now);
1172    const closing = !config.isAwake
1173      ? 'Waking Claude is off in /config: changes show on the line, and the watches tool reads them.'
1174      : !input.wake
1175        ? 'pr-watch tells you when that changes, at once or with the next message, so there is no need to poll gh.'
1176        : verdict?.kind === 'ready' || isPassed
1177          ? `${isPassed ? "Its merge's checks have passed" : 'It is ready to merge'} now, as its line says. pr-watch wakes you if that happens again after new checks, and tells you the rest when it changes.`
1178          : 'pr-watch wakes you when it turns ready to merge or its checks pass, and tells you the rest when it changes, so there is no need to poll gh.';
1179    return { result: [head, kept.news, closing].filter(Boolean).join('\n') };
1180  } catch (error) {
1181    const why = errorText(error);
1182    return {
1183      result: isAdded
1184        ? `pr-watch is watching ${name} but could not read it yet: ${why}`
1185        : `pr-watch could not watch ${input.pull}: ${why}`,
1186    };
1187  }
1188}
1189
1190async function onUnwatchTool($: $, e: unknown): Promise<{ result: string }> {
1191  const input = toolInputOf(e);
1192  if (typeof input === 'string') return { result: input };
1193  try {
1194    const list = await read($, watches);
1195    const number = /^#?(\d+)$/.exec(input.pull)?.[1];
1196    const inRepo = (w: Watch) => input.repo === null || w.repo === input.repo;
1197    let found = list.filter(
1198      (w) =>
1199        w.url === input.pull ||
1200        (!w.push && number !== undefined && w.number === Number(number) && inRepo(w)) ||
hooks/github.ts 453 lines
1// The gh calls pr-watch makes and what it reads from their output. Pure:
2// register.tsx runs the commands.
3import type { Activity, Commit, Job, Pull, Runs, RunStatus, Stack, Workflow } from '../types';
4
5// Whether a check is required is asked only of the head commit: the base
6// branch's runs after a merge gate nothing.
7const suites = (required: string, first = 100) => `checkSuites(first: ${first}) {
8      pageInfo { hasNextPage }
9      nodes {
10        status conclusion
11        workflowRun { databaseId runAttempt createdAt url workflow { databaseId name } }
12        checkRuns(first: 100) { nodes { name status conclusion detailsUrl ${required} } }
13      }
14    }`;
15
16// The quota every query reports, shared with every other gh call the user makes.
17const RATE = 'rateLimit { cost remaining limit resetAt }';
18
19// An open pull request reads its head commit's runs, a merged one its merge
20// commit's: each costs 1 point, both together 2. The latest comments and
21// reviews, and who reads them: someone else's are news.
22const pullQuery = (isMerged: boolean) => `query($o: String!, $r: String!, $n: Int!) {
23  ${RATE}
24  viewer { login }
25  repository(owner: $o, name: $r) { pullRequest(number: $n) {
26    number title url state isDraft mergeStateStatus reviewDecision baseRefName mergedAt
27    headRefName headRepository { nameWithOwner }
28    ${
29      isMerged
30        ? `mergeCommit { oid ${suites('')} }`
31        : `commits(last: 1) { nodes { commit { ${suites('isRequired(pullRequestNumber: $n)')} } } }`
32    }
33    comments(last: 10) { nodes { author { login __typename } createdAt url } }
34    reviews(last: 10) { nodes { author { login __typename } submittedAt state url } }
35  } }
36}`;
37
38const PUSH_QUERY = `query($o: String!, $r: String!, $b: String!) {
39  ${RATE}
40  repository(owner: $o, name: $r) { nameWithOwner parent { nameWithOwner } ref(qualifiedName: $b) {
41    target { ... on Commit { ${suites('')} } }
42    associatedPullRequests(states: OPEN, first: 100) {
43      nodes { number url repository { nameWithOwner } headRepository { nameWithOwner } }
44    }
45  } }
46}`;
47
48// 2 points, where 25 commits cost 5 (measured). A commit's committed time can
49// precede its pull request's merge by a second, so the merge commit is found by
50// oid, not `since`.
51const TRUNK_QUERY = `query($o: String!, $r: String!, $b: String!) {
52  ${RATE}
53  repository(owner: $o, name: $r) { ref(qualifiedName: $b) {
54    target { ... on Commit { history(first: 10) { nodes {
55      oid parents(first: 2) { nodes { oid } } ${suites('', 20)}
56    } } } }
57  } }
58}`;
59
60function onHost(host: string): string[] {
61  return host === 'github.com' ? [] : ['--hostname', host];
62}
63
64export function pullArgs(host: string, repo: string, number: number, isMerged = false): string[] {
65  const [owner = '', name = ''] = repo.split('/');
66  return [
67    'gh',
68    'api',
69    'graphql',
70    ...onHost(host),
71    '-f',
72    `query=${pullQuery(isMerged)}`,
73    '-f',
74    `o=${owner}`,
75    '-f',
76    `r=${name}`,
77    '-F',
78    `n=${number}`,
79  ];
80}
81
82// A pull request's URL, state and merge time, as gh resolves a number, URL or
83// branch.
84export function viewArgs(pull: string, repo: string | null): string[] {
85  return [
86    'gh',
87    'pr',
88    'view',
89    pull,
90    ...(repo === null ? [] : ['--repo', repo]),
91    '--json',
92    'url,state,mergedAt',
93  ];
94}
95
96function branchArgs(query: string, host: string, repo: string, branch: string): string[] {
97  const [owner = '', name = ''] = repo.split('/');
98  return [
99    'gh',
100    'api',
101    'graphql',
102    ...onHost(host),
103    '-f',
104    `query=${query}`,
105    '-f',
106    `o=${owner}`,
107    '-f',
108    `r=${name}`,
109    '-f',
110    `b=refs/heads/${branch}`,
111  ];
112}
113
114export function pushArgs(host: string, repo: string, branch: string): string[] {
115  return branchArgs(PUSH_QUERY, host, repo, branch);
116}
117
118export function trunkArgs(host: string, repo: string, branch: string): string[] {
119  return branchArgs(TRUNK_QUERY, host, repo, branch);
120}
121
122// The github/gh-stack stacks a pull request belongs to.
123export function stackArgs(host: string, repo: string, number: number): string[] {
124  return [
125    'gh',
126    'api',
127    ...onHost(host),
128    '-X',
129    'GET',
130    `repos/${repo}/stacks`,
131    '-f',
132    `pull_request=${number}`,
133  ];
134}
135
136// The first stack a pull request is a layer of; `pull_requests` lists the
137// layers bottom first. Null for one in no stack. An error body, or a stack
138// missing its number or a layer's, throws rather than read as no stack or
139// shift every layer's place.
140export function parseStack(stdout: string): Stack | null {
141  const stacks = parse(stdout);
142  if (!Array.isArray(stacks)) throw new Error('gh printed no list of stacks');
143  if (stacks.length === 0) return null;
144  const number = id(stacks[0]?.number);
145  const trunk = str(stacks[0]?.base?.ref);
146  const pulls = list(stacks[0]?.pull_requests);
147  const layers = pulls.map((p) => id(p?.number));
148  if (number === null || trunk === null || layers.includes(null)) {
149    throw new Error('gh printed a stack without its number, trunk or layers');
150  }
151  const numbers = layers as number[];
152  const merged = numbers.filter((_, i) => str(pulls[i]?.merged_at) !== null);
153  return { number, trunk, layers: numbers, merged };
154}
155
156// Over three repositories' history, 10 runs predicted the next run as well as
157// 20 or better; a median of 20 lagged a CI slowdown by about 10 runs.
158const ESTIMATE_RUNS = 10;
159
160export function estimateArgs(host: string, repo: string, workflowId: number): string[] {
161  return [
162    'gh',
163    'api',
164    ...onHost(host),
165    `repos/${repo}/actions/workflows/${workflowId}/runs?status=success&per_page=${ESTIMATE_RUNS}`,
166  ];
167}
168
169// GraphQL has no start time for a re-run: its run keeps the first attempt's.
170export function attemptArgs(host: string, repo: string, runId: number, attempt: number): string[] {
171  return ['gh', 'api', ...onHost(host), `repos/${repo}/actions/runs/${runId}/attempts/${attempt}`];
172}
173
174// When the attempt started, in ms; null when the answer has no such time.
175export function parseAttemptStart(stdout: string): number | null {
176  const start = (parse(stdout) as { run_started_at?: unknown } | null)?.run_started_at;
177  return isTime(start) ? Date.parse(start) : null;
178}
179
180function statusOf(status: unknown): RunStatus {
181  if (status === 'COMPLETED') return 'done';
182  if (status === 'IN_PROGRESS') return 'running';
183  return 'queued';
184}
185
186function str(value: unknown): string | null {
187  return typeof value === 'string' && value !== '' ? value : null;
188}
189
190function id(value: unknown): number | null {
191  return Number.isSafeInteger(value) && (value as number) > 0 ? (value as number) : null;
192}
193
194const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
195
196// Date.parse alone accepts almost any string, "1" included.
197function isTime(value: unknown): value is string {
198  return typeof value === 'string' && ISO_TIME.test(value) && Number.isFinite(Date.parse(value));
199}
200
201function list(value: unknown): any[] {
202  return Array.isArray(value) ? value : [];
203}
204
205function parse(stdout: string): unknown {
206  try {
207    return JSON.parse(stdout);
208  } catch {
209    throw new Error('gh printed something other than JSON');
210  }
211}
212
213function jobOf(j: any): Job | null {
214  const name = str(j?.name);
215  if (name === null) return null;
216  return {
217    name,
218    status: statusOf(j.status),
219    conclusion: str(j.conclusion),
220    url: str(j.detailsUrl) ?? '',
221    isRequired: j.isRequired === true,
222  };
223}
224
225function workflowOf(s: any): Workflow | null {
226  const run = s?.workflowRun;
227  const workflowId = id(run?.workflow?.databaseId);
228  const name = str(run?.workflow?.name);
229  if (workflowId === null || name === null || !isTime(run.createdAt)) return null;
230  const runId = id(run.databaseId);
231  const jobs: Job[] = [];
232  for (const node of list(s.checkRuns?.nodes)) {
233    const j = jobOf(node);
234    if (j) jobs.push(j);
235  }
236  return {
237    id: workflowId,
238    name,
239    status: statusOf(s.status),
240    conclusion: str(s.conclusion),
241    startedAt: run.createdAt,
242    // A re-run keeps the first attempt's creation time, so its clock is asked of REST.
243    isRerun: typeof run.runAttempt === 'number' && run.runAttempt > 1,
244    attempt: typeof run.runAttempt === 'number' ? run.runAttempt : 1,
245    ...(runId === null ? {} : { runId }),
246    url: str(run.url) ?? '',
247    jobs,
248  };
249}
250
251export type Checks = Pick<Pull, 'workflows' | 'isGated' | 'isRequiredPending' | 'isTruncated'>;
252
253// A commit's check suites. Those with no workflow run come from GitHub Apps,
254// not Actions, and can sit queued forever; they count only as required checks.
255function checksOf(suites: any): Checks {
256  // A commit keeps a suite for every run of a workflow; the newest stands for it.
257  const newest = new Map<number, Workflow>();
258  let isGated = false;
259  let isRequiredPending = false;
260  for (const s of list(suites?.nodes)) {
261    const required = list(s?.checkRuns?.nodes).filter((j) => j?.isRequired === true);
262    // A required check from a GitHub App gates the merge too.
263    if (required.length > 0) isGated = true;
264    const w = workflowOf(s);
265    if (!w) {
266      if (required.some((j) => j.status !== 'COMPLETED')) isRequiredPending = true;
267      continue;
268    }
269    const seen = newest.get(w.id);
270    if (!seen || Date.parse(w.startedAt) >= Date.parse(seen.startedAt)) newest.set(w.id, w);
271  }
272  return {
273    workflows: [...newest.values()],
274    isGated,
275    isRequiredPending,
276    isTruncated: suites?.pageInfo?.hasNextPage === true,
277  };
278}
279
280// Nothing on the base branch is required, so a merge keeps only its runs.
281function runsOf({ workflows, isTruncated }: Checks): Runs {
282  return { workflows, isTruncated };
283}
284
285const isBot = (author: any) => author?.__typename === 'Bot';
286
287const REVIEWED: Record<string, string> = {
288  APPROVED: 'approved',
289  CHANGES_REQUESTED: 'requested changes on',
290  COMMENTED: 'reviewed',
291  DISMISSED: 'reviewed',
292};
293
294// Null without the viewer, whose own are not news, or without either list,
295// which a reply carrying errors may leave out.
296function activityOf(pr: any, viewer: string | null): Activity[] | null {
297  if (viewer === null || !Array.isArray(pr.comments?.nodes) || !Array.isArray(pr.reviews?.nodes)) {
298    return null;
299  }
300  const found: Activity[] = [];
301  for (const c of list(pr.comments?.nodes)) {
302    const author = str(c?.author?.login);
303    if (author === null || author === viewer || !isTime(c.createdAt)) continue;
304    const url = str(c.url) ?? '';
305    const bot = isBot(c.author);
306    found.push({ author, at: c.createdAt, url, did: 'commented on', isBot: bot, isReview: false });
307  }
308  for (const r of list(pr.reviews?.nodes)) {
309    const author = str(r?.author?.login);
310    const did = REVIEWED[str(r?.state) ?? ''];
311    if (author === null || author === viewer || !did || !isTime(r.submittedAt)) continue;
312    const url = str(r.url) ?? '';
313    found.push({ author, at: r.submittedAt, url, did, isBot: isBot(r.author), isReview: true });
314  }
315  return found.toSorted((a, b) => Date.parse(a.at) - Date.parse(b.at));
316}
317
318// The newest comment or review in the window, the viewer's included: an older
319// one can only come into view when a newer one is deleted.
320function windowNewest(pr: any): string | null {
321  let newest: string | null = null;
322  const times = [
323    ...list(pr.comments?.nodes).map((c) => c?.createdAt),
324    ...list(pr.reviews?.nodes).map((r) => r?.submittedAt),
325  ];
326  for (const t of times) {
327    if (isTime(t) && (newest === null || Date.parse(t) > Date.parse(newest))) newest = t;
328  }
329  return newest;
330}
331
332export function parsePull(stdout: string): Pull {
333  const body: any = parse(stdout);
334  const pr = body?.data?.repository?.pullRequest;
335  if (!pr) {
336    const problem = str(body?.errors?.[0]?.message);
337    throw new Error(problem ?? 'pull request not found');
338  }
339  const number = id(pr.number);
340  if (number === null) throw new Error('pull request has no number');
341  const headBranch = str(pr.headRefName);
342  const headRepo = str(pr.headRepository?.nameWithOwner);
343  const mergeOid = str(pr.mergeCommit?.oid);
344  return {
345    number,
346    ...(headBranch === null || headRepo === null
347      ? {}
348      : { head: { branch: headBranch, repo: headRepo } }),
349    title: str(pr.title) ?? '',
350    url: str(pr.url) ?? '',
351    state: pr.state === 'MERGED' || pr.state === 'CLOSED' ? pr.state : 'OPEN',
352    isDraft: pr.isDraft === true,
353    merge: str(pr.mergeStateStatus) ?? 'UNKNOWN',
354    review: str(pr.reviewDecision),
355    base: str(pr.baseRefName) ?? 'base',
356    mergedAt: isTime(pr.mergedAt) ? pr.mergedAt : null,
357    ...checksOf(pr.commits?.nodes?.[0]?.commit?.checkSuites),
358    mergeRuns: pr.mergeCommit ? runsOf(checksOf(pr.mergeCommit.checkSuites)) : null,
359    ...(mergeOid === null ? {} : { mergeOid }),
360    activity: activityOf(pr, str(body?.data?.viewer?.login)),
361    activityAt: windowNewest(pr),
362  };
363}
364
365export type Quota = { remaining: number; limit: number; resetAt: string };
366
367// The GraphQL quota a query reported; null when its answer does not say.
368export function parseQuota(stdout: string): Quota | null {
369  let body: any;
370  try {
371    body = JSON.parse(stdout);
372  } catch {
373    return null;
374  }
375  const rate = body?.data?.rateLimit;
376  const { remaining, limit, resetAt } = rate ?? {};
377  // The reset time tells one window from the next, so an answer without one is no use.
378  if (typeof remaining !== 'number' || typeof limit !== 'number' || limit <= 0) return null;
379  return isTime(resetAt) ? { remaining, limit, resetAt } : null;
380}
381
382export type Pushed =
383  | { kind: 'runs'; runs: Pull['mergeRuns'] }
384  // The PR's own repository: a fork's branch heads a PR upstream.
385  | { kind: 'pr'; repo: string; number: number; url: string | null }
386  // No such branch: deleted since, or a forced tag read as one.
387  | { kind: 'gone' };
388
389// A pushed branch's tip runs, or the open pull request it heads.
390export function parsePush(stdout: string): Pushed {
391  const body: any = parse(stdout);
392  const problem = str(body?.errors?.[0]?.message);
393  if (problem) throw new Error(problem);
394  const repository = body?.data?.repository;
395  if (!repository) throw new Error('repository not found');
396  const ref = repository.ref;
397  if (!ref) return { kind: 'gone' };
398  // Strangers' forks open PRs from a popular branch too; only one from this
399  // repository into itself or its parent is this push's.
400  const self = str(repository.nameWithOwner)?.toLowerCase();
401  const parent = str(repository.parent?.nameWithOwner)?.toLowerCase();
402  const open = list(ref.associatedPullRequests?.nodes).find((n) => {
403    const base = str(n?.repository?.nameWithOwner)?.toLowerCase();
404    const head = str(n?.headRepository?.nameWithOwner)?.toLowerCase();
405    return self !== undefined && head === self && (base === self || base === parent);
406  });
407  const number = id(open?.number);
408  const repo = str(open?.repository?.nameWithOwner);
409  if (number !== null && repo !== null) return { kind: 'pr', repo, number, url: str(open.url) };
410  return { kind: 'runs', runs: runsOf(checksOf(ref.target?.checkSuites)) };
411}
412
413// Newest first; none when the branch is gone.
414export function parseTrunk(stdout: string): Commit[] {
415  const body: any = parse(stdout);
416  const problem = str(body?.errors?.[0]?.message);
417  if (problem) throw new Error(problem);
418  const repository = body?.data?.repository;
419  if (!repository) throw new Error('repository not found');
420  const commits: Commit[] = [];
421  for (const node of list(repository.ref?.target?.history?.nodes)) {
422    const oid = str(node?.oid);
423    if (oid === null) continue;
424    const parents = list(node.parents?.nodes).flatMap((p) => str(p?.oid) ?? []);
425    commits.push({ oid, parents, runs: runsOf(checksOf(node.checkSuites)) });
426  }
427  return commits;
428}
429
430// The median length of the recent successful first attempts: one run off a
431// release branch or a cached re-run (7 s, measured) does not set it. 0 when the
432// workflow has none, null when gh's answer does not say.
433export function parseEstimate(stdout: string): number | null {
434  let body: any;
435  try {
436    body = JSON.parse(stdout);
437  } catch {
438    return null;
439  }
440  const runs = body?.workflow_runs;
441  if (!Array.isArray(runs)) return null;
442  const firsts = runs.filter((run) => run && (run.run_attempt ?? 1) === 1);
443  if (firsts.length === 0) return 0;
444  const lengths = firsts
445    .filter((run) => isTime(run.run_started_at) && isTime(run.updated_at))
446    .map((run) => Date.parse(run.updated_at) - Date.parse(run.run_started_at))
447    .filter((ms) => ms > 0)
448    .toSorted((a, b) => a - b);
449  if (lengths.length === 0) return null;
450  const mid = Math.floor(lengths.length / 2);
451  return lengths.length % 2 === 1 ? lengths[mid]! : (lengths[mid - 1]! + lengths[mid]!) / 2;
452}
453
hooks/ladder.ts 51 lines
1// Whether review-cycle's stop-before setting lets Claude merge unasked. Pure.
2//
3// The same precedence review-cycle applies, repeated because a module imports
4// only its own plugin's files: the local file's value, else the one review-cycle
5// loaded with, made earlier by the project file's.
6
7const RUNGS = ['commit', 'push', 'open PR', 'merge', 'release', 'never stop'] as const;
8type Rung = (typeof RUNGS)[number];
9
10const PLUGIN = /^review-cycle(@|$)/;
11const DEFAULT: Rung = 'push';
12
13const rank = (r: Rung): number => RUNGS.indexOf(r);
14
15// The engine lists review-cycle's /config rows only while it is loaded; null
16// when it is not, or its gate is off, since nothing then lets a merge go unasked.
17export function loadedRung(rows: readonly { key: string; value: unknown }[]): Rung | null {
18  const valueOf = (field: string) => rows.find((r) => r.key === `review-cycle.${field}`)?.value;
19  if (valueOf('enabled') !== true) return null;
20  return RUNGS.find((r) => r === valueOf('stopBefore')) ?? DEFAULT;
21}
22
23// A settings file's value for review-cycle, under its bare or qualified name;
24// a value outside the options stops before every step, as review-cycle reads it.
25export function configured(pluginConfigs: unknown): Rung | null {
26  if (pluginConfigs === null || typeof pluginConfigs !== 'object') return null;
27  let found: Rung | null = null;
28  for (const [name, entry] of Object.entries(pluginConfigs)) {
29    if (!PLUGIN.test(name) || entry === null || typeof entry !== 'object') continue;
30    const options: unknown = (entry as { options?: unknown }).options;
31    if (options === null || typeof options !== 'object' || !('stopBefore' in options)) continue;
32    const value = RUNGS.find((r) => r === options.stopBefore) ?? RUNGS[0];
33    if (found === null || rank(value) < rank(found)) found = value;
34  }
35  return found;
36}
37
38export function mergesUnasked({
39  user,
40  project,
41  local,
42}: {
43  user: Rung;
44  project: Rung | null;
45  local: Rung | null;
46}): boolean {
47  let rung = local ?? user;
48  if (local === null && project !== null && rank(project) < rank(rung)) rung = project;
49  return rank('merge') < rank(rung);
50}
51
hooks/watch.ts 1299 lines
1// What the band says about a pull request, and when to look again. Pure.
2import type { Activity, Commit, Held, Job, Pull, Runs, Stack, Watch, Workflow } from '../types';
3
4const LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?';
5const PR_URL = new RegExp(
6  `^https://(${LABEL}(?:\\.${LABEL})*)/([\\w-][\\w.-]*/[\\w-][\\w.-]*)/pull/([1-9]\\d{0,9})\\s*$`,
7  'gm',
8);
9// The start of a command: the line's, or after a shell separator, with any
10// leading VAR=value assignments.
11const START = String.raw`(?:^|[;&|(\n])\s*(?:\w+=\S*\s+)*`;
12const PR_CREATE = new RegExp(String.raw`${START}gh\s+pr\s+create\b`);
13const STACK_SUBMIT = new RegExp(String.raw`${START}gh\s+stack\s+submit\b`);
14// What can add, drop or merge a stack's layers.
15const STACK_CHANGE = new RegExp(
16  String.raw`${START}gh\s+stack\s+(?:init|add|submit|push|sync|merge|modify|unstack|delete|link)\b`,
17);
18// gh stack submit's line for each pull request it opened, after its success mark.
19const SUBMIT_CREATED = /^(?:✓ )?Created PR #\d+ \((\S+)\) for \S+\s*$/gm;
20// git's own options may come before the subcommand: -C dir, -c key=value, --flag.
21const MOVES_PR = new RegExp(
22  String.raw`${START}(?:git(?:\s+(?:-[Cc]\s+\S+|--\S+))*\s+push\b|gh\s+pr\s+merge\b|gh\s+run\s+rerun\b|gh\s+workflow\s+run\b|gh\s+stack\s+(?:submit|push|sync|merge)\b)`,
23);
24
25const GIT_PUSH = new RegExp(String.raw`${START}git(?:\s+(?:-[Cc]\s+\S+|--\S+))*\s+push\b`);
26// git's "To <remote>" line: scp, https:// or ssh:// form.
27const PUSH_TO =
28  /^To\s+(?:\w+:\/\/)?(?:[^@\s/]+@)?([A-Za-z0-9.-]+)(?::\d+)?[:/]([\w-][\w.-]*\/[\w-][\w.-]*?)(?:\.git)?\/?\s*$/;
29// A ref the push moved: "a..b  src -> dst", "+ a...b src -> dst (forced
30// update)", "* [new branch]  src -> dst". Deleted, rejected, up-to-date and
31// new-tag lines name none.
32const PUSH_REF =
33  /^\s*[+*]?\s*(?:[0-9a-f]{4,}\.{2,3}[0-9a-f]{4,}|\[new branch\])\s+\S+\s+->\s+(\S+)/;
34// The same with --porcelain: "<flag>\t<src>:<dst>\t<summary>".
35const PORCELAIN_REF = /^[ +*]\t\S*:(\S+)\t/;
36
37export type PushTarget = Pick<Target, 'host' | 'repo' | 'url'> & { branch: string };
38
39// The branches a `git push` moved, read from its output, which reaches the
40// hook in stdout with stderr merged in. A forced tag reads like a branch
41// here, and a --dry-run like a push; the read drops a branch that is not
42// there, and an existing one shows its tip's runs.
43export function pushedBranches(command: string, stdout: string): PushTarget[] {
44  if (!GIT_PUSH.test(command)) return [];
45  const found: PushTarget[] = [];
46  let to: { host: string; repo: string } | null = null;
47  for (const line of stdout.split('\n')) {
48    if (/^To\s/.test(line)) {
49      // A remote that is not on a host, such as a local path, names no repo.
50      const remote = PUSH_TO.exec(line);
51      to = remote ? { host: remote[1]!.toLowerCase(), repo: remote[2]! } : null;
52      continue;
53    }
54    const dst = (PUSH_REF.exec(line) ?? PORCELAIN_REF.exec(line))?.[1];
55    if (!dst || !to || (dst.startsWith('refs/') && !dst.startsWith('refs/heads/'))) continue;
56    const branch = dst.replace(/^refs\/heads\//, '');
57    const url = `https://${to.host}/${to.repo}/tree/${branch}`;
58    if (!found.some((p) => p.host === to!.host && p.repo === to!.repo && p.branch === branch)) {
59      found.push({ ...to, url, branch });
60    }
61  }
62  return found;
63}
64
65// How the band, toasts and errors name a watch: "release #259" tells a
66// release tool's version pull request from the others.
67export function labelOf(w: Pick<Watch, 'number' | 'push' | 'pull'>): string {
68  if (w.push) return `push ${w.push.branch}`;
69  return w.pull !== undefined && isReleasePull(w.pull) ? `release #${w.number}` : `#${w.number}`;
70}
71
72// GitHub refusing the token or hiding the repository; other hosts answer 404,
73// 405 or a GraphQL schema error. GraphQL states an organization's or a token's
74// refusal in its message, with no HTTP status.
75const REFUSED = new RegExp(
76  [
77    String.raw`\bHTTP 40[13]\b`,
78    'Could not resolve to a Repository',
79    'Resource protected by organization SAML enforcement',
80    'Resource not accessible by',
81    'Although you appear to have the correct authorization credentials',
82    'has not been granted the required scopes',
83  ].join('|'),
84);
85
86// gh prints the same login prompt for every host, so only github.com's is GitHub's refusal.
87export function isRefused(error: string, host: string): boolean {
88  return REFUSED.test(error) || (host === 'github.com' && /\bgh auth login\b/.test(error));
89}
90
91// A push unread in the grace, such as one on a host gh does not know, leaves
92// quietly; one GitHub refused gives up and says so, as a pull request does.
93export function isUnreadable(w: Watch, now: number): boolean {
94  return (
95    w.push !== undefined &&
96    w.pull === undefined &&
97    !w.refused &&
98    now - w.push.pushedAt >= MERGE_GRACE_MS
99  );
100}
101
102// Whether a line leaves with time alone: a merge or push that started no runs
103// in its grace, a passed one past its stay, or a push never read.
104export function isGone(w: Watch, estimates: Record<string, number>, now: number): boolean {
105  if (isUnreadable(w, now)) return true;
106  if (!w.pull) return false;
107  const verdict = verdictOf(w.pull, estimates, w.host, w.checkedAt);
108  return verdict.kind === 'closed' || isCleared(verdict, w.pull, w.checkedAt, now);
109}
110
111// A push follows its branch's runs as a merge follows its merge commit's.
112export function pushedPull(branch: string, pushedAt: number, runs: Runs | null): Pull {
113  return {
114    number: 0,
115    title: '',
116    url: '',
117    state: 'MERGED',
118    isDraft: false,
119    merge: 'UNKNOWN',
120    review: null,
121    workflows: [],
122    isGated: false,
123    isRequiredPending: false,
124    isTruncated: false,
125    base: branch,
126    mergedAt: new Date(pushedAt).toISOString(),
127    mergeRuns: runs,
128    activity: [],
129    activityAt: null,
130  };
131}
132
133// Whether a command can start new runs or close a pull request, so the
134// band should look again soon rather than at its next slow poll.
135export function movesPulls(command: string): boolean {
136  return MOVES_PR.test(command);
137}
138const FAILED = new Set(['FAILURE', 'TIMED_OUT', 'CANCELLED', 'STARTUP_FAILURE', 'ACTION_REQUIRED']);
139const PASSED = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED']);
140const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉'];
141
142export type Target = Pick<Watch, 'host' | 'repo' | 'number' | 'url'>;
143
144// The pull request a `gh pr create` printed: the URL on its last line of its own.
145export function createdPull(command: string, stdout: string): Target | null {
146  if (!PR_CREATE.test(command)) return null;
147  return pullAt(stdout);
148}
149
150// The pull requests a `gh stack submit` opened, bottom layer first.
151export function submittedPulls(command: string, stdout: string): Target[] {
152  if (!STACK_SUBMIT.test(command)) return [];
153  return [...stdout.matchAll(SUBMIT_CREATED)].flatMap((m) => pullAt(m[1]!) ?? []);
154}
155
156// After one, every watched pull request's stack is asked again.
157export function changesStacks(command: string): boolean {
158  return STACK_CHANGE.test(command);
159}
160
161export type Layered = Pick<Pull, 'stack' | 'stackAt' | 'stackMerged'>;
162
163const STACK_STALE_MS = 10 * 60_000;
164
165// Whether to ask GitHub's stacks API again, given the last answer and when a
166// `gh stack` command last ran. A merged layer's trunk is fixed by an answer
167// from a read that saw it merged, which no clock skew can fake; an open one's
168// stack can change with any such command, or from elsewhere.
169export function needsStack(
170  was: Layered | undefined,
171  isMerged: boolean,
172  now: number,
173  changedAt: number,
174): boolean {
175  if (was?.stack === undefined) return true;
176  if (isMerged) return was.stackMerged !== true;
177  const at = was.stackAt ?? 0;
178  return at <= changedAt || now - at >= STACK_STALE_MS;
179}
180
181// The stack a read leaves. No answer keeps the last, to be asked again; no
182// stacks API, or no access to it, answers as no stack, but leaves one known.
183export function layeredOf(
184  was: Layered | undefined,
185  answer: Stack | null | 'unreadable' | undefined,
186  isMerged: boolean,
187  now: number,
188): Layered {
189  if (answer === undefined) {
190    return { stack: was?.stack, stackAt: was?.stackAt, stackMerged: was?.stackMerged };
191  }
192  const stack = answer === 'unreadable' ? (was?.stack ?? null) : answer;
193  return { stack, stackAt: now, stackMerged: isMerged };
194}
195
196// The nearest open layer below this one that is not ready, or null; `of` is 0
197// when its place is not yet known. A stack merge of a layer merges the open
198// layers below it, while GitHub reports each layer ready by itself. A layer
199// whose base is the trunk has none open below; one not watched, and not
200// reported merged, counts as not ready.
201export function belowOf(
202  w: Pick<Watch, 'host' | 'repo' | 'number'>,
203  pull: Pull,
204  all: readonly Watch[],
205  estimates: Record<string, number>,
206): { at: number; of: number } | null {
207  const near = (x: Watch) => !x.push && x.host === w.host && x.repo === w.repo;
208  const isReady = (x: Watch | undefined) =>
209    x?.pull?.state === 'OPEN' && verdictOf(x.pull, estimates, x.host, x.checkedAt).kind === 'ready';
210  const { stack } = pull;
211  // Until the stacks API answers, a watched pull request this one is based on
212  // stands for the layer below.
213  if (stack === undefined) {
214    const under = all.find(
215      (x) => near(x) && x.pull?.head?.branch === pull.base && x.pull.head.repo === w.repo,
216    );
217    return under?.pull?.state === 'OPEN' && !isReady(under) ? { at: 0, of: 0 } : null;
218  }
219  if (stack === null || pull.base === stack.trunk) return null;
220  const at = stack.layers.indexOf(w.number);
221  for (let i = at - 1; i >= 0; i--) {
222    const n = stack.layers[i];
223    if (n === undefined || stack.merged?.includes(n)) continue;
224    const lower = all.find((x) => near(x) && x.number === n);
225    if (lower?.pull?.state === 'MERGED') continue;
226    if (!isReady(lower)) return { at: i + 1, of: stack.layers.length };
227    // A ready layer based on the trunk has every layer under it merged, even
228    // where this one's stack list is older than that merge.
229    if (lower?.pull?.base === stack.trunk) return null;
230  }
231  return null;
232}
233
234// A layer's place in its stack, numbered from the bottom as GitHub's badge is;
235// null for a lane.
236export function layerOf(watch: Watch): { stack: number; at: number; of: number } | null {
237  const stack = watch.pull?.stack;
238  const at = stack ? stack.layers.indexOf(watch.number) + 1 : 0;
239  if (!stack || at === 0) return null;
240  return { stack: stack.number, at, of: stack.layers.length };
241}
242
243function stackKeyOf(w: Watch): string | null {
244  const layer = layerOf(w);
245  return layer === null ? null : `${w.host}/${w.repo}#${layer.stack}`;
246}
247
248// Each stack's lines together, top layer first, where its first line was;
249// lanes keep their place.
250export function orderedOf(list: readonly Watch[]): Watch[] {
251  const placed = new Set<string>();
252  return list.flatMap((w) => {
253    const key = stackKeyOf(w);
254    if (key === null) return [w];
255    if (placed.has(key)) return [];
256    placed.add(key);
257    return list
258      .filter((other) => stackKeyOf(other) === key)
259      .toSorted((a, b) => layerOf(b)!.at - layerOf(a)!.at);
260  });
261}
262
263// The pull request `gh pr view --json url,…` names, with the rest of its answer.
264export function viewedPull(stdout: string): { target: Target; body: any } | null {
265  let body: any;
266  try {
267    body = JSON.parse(stdout);
268  } catch {
269    return null;
270  }
271  const target = typeof body?.url === 'string' ? pullAt(body.url) : null;
272  return target === null ? null : { target, body };
273}
274
275// How far GitHub's clock may run behind this machine's.
276const MERGE_SKEW_MS = 2 * 60_000;
277
278// 'stale' unless open (an --auto merge waits) or merged after the command
279// started: a merge from before is not the one it ran, but a mention of it.
280export function mergedPullOf(stdout: string, startedAt: number): Target | 'stale' | null {
281  const viewed = viewedPull(stdout);
282  if (viewed === null) return null;
283  const { target, body } = viewed;
284  if (body.state === 'OPEN') return target;
285  const at = typeof body.mergedAt === 'string' ? Date.parse(body.mergedAt) : Number.NaN;
286  return body.state === 'MERGED' && at >= startedAt - MERGE_SKEW_MS ? target : 'stale';
287}
288
289// The pull request a URL names: one line holding only the URL.
290export function pullAt(text: string): Target | null {
291  const m = [...text.matchAll(PR_URL)].at(-1);
292  if (!m) return null;
293  return { host: m[1]!.toLowerCase(), repo: m[2]!, number: Number(m[3]), url: m[0].trim() };
294}
295
296// gh pr merge's options that take a value, long and short.
297const MERGE_VALUED = new Set([
298  '--body',
299  '--body-file',
300  '--subject',
301  '--author-email',
302  '--match-head-commit',
303  '--repo',
304]);
305const MERGE_VALUED_SHORT = new Set(['b', 'F', 't', 'A', 'R']);
306// A command before the merge that moves it to another repository, where gh
307// resolves the pull request it names; a checkout does not change that.
308const MOVES_REPO = new RegExp(String.raw`${START}(?:cd|pushd|popd)\b`);
309
310// The words of the command `text` starts, quotes removed, up to the first
311// separator or comment outside them: enough for gh's arguments, not a shell
312// parser.
313function wordsOf(text: string): string[] {
314  const words: string[] = [];
315  const unbroken = text.replaceAll('\\\n', ' ');
316  for (const m of unbroken.matchAll(/'([^']*)'|"((?:[^"\\]|\\.)*)"|([;&|\n#])|([^\s;&|'"]+)/g)) {
317    if (m[3] !== undefined) break;
318    words.push(m[1] ?? m[2]?.replaceAll(/\\(.)/g, '$1') ?? m[4]!);
319  }
320  return words;
321}
322
323export type Merging = { pull: string; repo: string | null };
324
325// Null for a bare merge: after --delete-branch, or on a fork's branch, nothing
326// names its pull request. Null too where pr-watch cannot follow the merge:
327// after a cd in the same line, or on another GH_HOST.
328export function mergingPull(command: string): Merging | null {
329  const at = new RegExp(String.raw`${START}gh\s+pr\s+merge\b`).exec(command);
330  if (!at || MOVES_REPO.test(command.slice(0, at.index)) || /\bGH_HOST=/.test(at[0])) {
331    return null;
332  }
333  const env = /\bGH_REPO=(\S+)/.exec(at[0])?.[1];
334  let repo = env === undefined ? null : (wordsOf(env)[0] ?? null);
335  let pull: string | null = null;
336  const words = wordsOf(command.slice(at.index + at[0].length));
337  for (let i = 0; i < words.length; i += 1) {
338    const word = words[i]!;
339    if (word === '--help' || word === '--disable-auto') return null;
340    // A redirection, with its target when that is the next word.
341    if (/^\d*(?:>>?|<)/.test(word)) {
342      if (/^\d*(?:>>?|<)$/.test(word)) i += 1;
343      continue;
344    }
345    let flag: string | null = null;
346    let value: string | undefined;
347    if (word.startsWith('--')) {
348      const [name, inline] = word.split(/=(.*)/s, 2);
349      if (MERGE_VALUED.has(name!)) [flag, value] = [name!, inline];
350    } else if (/^-[A-Za-z]/.test(word)) {
351      // Short options group, and a valued one takes the rest of the word:
352      // -dR o/r, -Ro/r, -R=o/r.
353      for (let j = 1; j < word.length; j += 1) {
354        const letter = word[j]!;
355        if (letter === 'h') return null;
356        if (MERGE_VALUED_SHORT.has(letter)) {
357          flag = `-${letter}`;
358          value = word.slice(j + 1).replace(/^=/, '') || undefined;
359          break;
360        }
361      }
362    }
363    if (flag !== null) {
364      value ??= words[(i += 1)];
365      if (flag === '-R' || flag === '--repo') repo = value ?? null;
366      continue;
367    }
368    if (!word.startsWith('-') && pull === null) pull = word;
369  }
370  return pull === null ? null : { pull, repo };
371}
372
373// The 5,000 points an hour are shared with every gh call the user and Claude
374// make, so pr-watch backs off before they run out.
375export const LOW_QUOTA_MS = 60_000;
376const LOW_QUOTA_SHARE = 0.1;
377
378export function isQuotaLow(q: { remaining: number; limit: number } | undefined): boolean {
379  return q !== undefined && q.remaining < q.limit * LOW_QUOTA_SHARE;
380}
381
382// GitHub's words for a primary or secondary limit, and the status a secondary
383// one may answer with; its docs name no exact wording.
384const LIMITED = /rate limit (?:already )?exceeded|secondary rate limit|\bHTTP 429\b/i;
385
386// gh prints a GraphQL answer's body on stdout and its first message on stderr.
387export function isRateLimited(stdout: string, stderr: string): boolean {
388  if (LIMITED.test(stderr)) return true;
389  try {
390    const errors: unknown = JSON.parse(stdout)?.errors;
391    return (
392      Array.isArray(errors) &&
393      errors.some((e) => e?.type === 'RATE_LIMITED' || LIMITED.test(String(e?.message)))
394    );
395  } catch {
396    return false;
397  }
398}
399
400// GitHub asks for at least a minute's wait on a secondary limit, longer each time.
401const PAUSE_FIRST_MS = 60_000;
402const PAUSE_MAX_MS = 15 * 60_000;
403
404export type Pause = { until: number; backoff: number };
405
406// A spent quota waits for its reset; any other limit, a secondary one, waits
407// longer each time it is hit again.
408export function pauseOf(
409  q: { remaining: number; limit: number; resetAt: string } | undefined,
410  last: Pause | undefined,
411  now: number,
412): Pause {
413  const backoff = last ? Math.min(last.backoff * 2, PAUSE_MAX_MS) : PAUSE_FIRST_MS;
414  const reset = q && q.remaining <= 0 ? Date.parse(q.resetAt) : Number.NaN;
415  return { until: reset > now ? reset : now + backoff, backoff };
416}
417
418export function untilText(at: number): string {
419  const d = new Date(at);
420  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
421}
422
423// gh exits 1 for these as for a 404, so only its words tell them apart.
424const UNREACHABLE =
425  /error connecting to |check your internet connection|TLS handshake timeout|i\/o timeout|connection (?:refused|reset)|no such host|network is unreachable|(?:unexpected|:) EOF\b|context deadline exceeded|Client\.Timeout|\bHTTP 50[234]\b/i;
426
427export function isNetworkError(stderr: string): boolean {
428  return UNREACHABLE.test(stderr);
429}
430
431// How long out of reach before someone is told: GIVE_UP_AFTER failed reads' worth.
432export const OFFLINE_TELL_MS = 15 * 60_000;
433
434// Soon enough to notice a laptop back online; never given up on.
435const OFFLINE_FIRST_MS = 15_000;
436const OFFLINE_MAX_MS = 60_000;
437
438export function offlineDelayOf(count: number): number {
439  return Math.min(OFFLINE_FIRST_MS * 2 ** Math.max(count - 1, 0), OFFLINE_MAX_MS);
440}
441
442// One unreachable read is a blip, kept quiet.
443const OFFLINE_NOTE_AFTER = 2;
444
445// Reads that fail for any other reason are retried less often each time, and
446// after GIVE_UP_AFTER in a row, some 15 minutes, the watch ends.
447export const GIVE_UP_AFTER = 8;
448const RETRY_MAX_MS = 5 * 60_000;
449
450export function retryDelayOf(failures: number): number {
451  return Math.min(10_000 * 2 ** Math.max(failures - 1, 0), RETRY_MAX_MS);
452}
453
454export function errorLine(text: string): string {
455  const line = text.trim().split('\n')[0]?.trim() ?? '';
456  return line.replace(/^gh: /, '') || 'no message';
457}
458
459export type Verdict =
460  | { kind: 'running'; gate: Workflow }
461  | { kind: 'failing'; workflowId: number; workflow: string; job: string; url: string }
462  | { kind: 'ready' }
463  | { kind: 'blocked'; reason: string }
464  | { kind: 'waiting'; reason: string }
465  | { kind: 'merged-running'; gate: Workflow }
466  | { kind: 'merged-failing'; workflowId: number; workflow: string; job: string; url: string }
467  | { kind: 'merged-passed' }
468  | { kind: 'merged-waiting' }
469  | { kind: 'closed' };
470
471// How long a merged pull request waits for its merge commit's runs to start.
472const MERGE_GRACE_MS = 90_000;
473
474// Merged inside the grace in which its runs may not have started.
475export function isMergeFresh(pull: Pick<Pull, 'mergedAt'>, now: number): boolean {
476  return pull.mergedAt !== null && now - Date.parse(pull.mergedAt) < MERGE_GRACE_MS;
477}
478
479const gates = (w: Workflow) => w.jobs.some((j) => j.isRequired);
480const failed = (conclusion: string | null) => FAILED.has(conclusion ?? '');
481
482type Gated = Pick<Pull, 'workflows' | 'isGated'>;
483
484// Whether the merge waits on this workflow: one holding a required check, or
485// any when nothing on the commit is required.
486function counts(runs: Gated): (w: Workflow) => boolean {
487  return (w) => !runs.isGated || gates(w);
488}
489
490// The job that failed, not the summary job that failed on it.
491function failure(runs: Gated): Verdict | null {
492  const isCounted = counts(runs);
493  for (const w of runs.workflows) {
494    if (!isCounted(w)) continue;
495    const bad = w.jobs.filter((j) => j.status === 'done' && failed(j.conclusion));
496    const job = bad.find((j) => !j.isRequired) ?? bad[0];
497    if (job) {
498      const url = job.url || w.url;
499      return { kind: 'failing', workflowId: w.id, workflow: w.name, job: job.name, url };
500    }
501  }
502  return null;
503}
504
505// The running workflow the merge waits on longest.
506function gateOf(running: Workflow[], estimates: Record<string, number>, host: string): Workflow {
507  let longest = running[0]!;
508  for (const w of running) {
509    if (
510      (estimates[estimateKey(host, w.id)] ?? 0) > (estimates[estimateKey(host, longest.id)] ?? 0)
511    ) {
512      longest = w;
513    }
514  }
515  return longest;
516}
517
518export function estimateKey(host: string, workflowId: number): string {
519  return `${host}/${workflowId}`;
520}
521
522export function rerunKey(host: string, runId: number, attempt: number): string {
523  return `${host}/run/${runId}/${attempt}`;
524}
525
526const JOB_NAME_MAX = 24;
527
528const isQueued = (j: Job) => j.status === 'queued';
529
530const clip = (name: string) =>
531  name.length > JOB_NAME_MAX ? `${name.slice(0, JOB_NAME_MAX - 1)}…` : name;
532
533// A running gate's name, with what it still waits on once some of its jobs
534// are done: up to two names, else a count. `queued` covers GitHub's queued,
535// waiting and pending alike, since none of them has started.
536function gateTextOf(gate: Workflow): string {
537  const name = gate.isRerun ? `${gate.name} re-run` : gate.name;
538  const left = gate.jobs.filter((j) => j.status !== 'done');
539  const allQueued = left.length > 0 && left.every((j) => isQueued(j)) ? ' queued' : '';
540  if (left.length === 0 || left.length === gate.jobs.length) return `${name}${allQueued}`;
541  if (left.length > 2) return `${name}: ${left.length} jobs${allQueued}`;
542  const names = left.map((j) => `${clip(j.name)}${isQueued(j) ? ' queued' : ''}`);
543  return `${name}: ${names.join(', ')}`;
544}
545
546// Null once every counted workflow has passed.
547function runsVerdict(runs: Gated, estimates: Record<string, number>, host: string): Verdict | null {
548  const fail = failure(runs);
549  if (fail) return fail;
550  const isCounted = counts(runs);
551  const running = runs.workflows.filter((w) => w.status !== 'done' && isCounted(w));
552  if (running.length > 0) return { kind: 'running', gate: gateOf(running, estimates, host) };
553  return null;
554}
555
556// A merged pull request follows its merge commit's runs on the base branch,
557// where nothing is required, so every workflow counts.
558function mergedVerdict(
559  pull: Pull,
560  estimates: Record<string, number>,
561  host: string,
562  now: number,
563): Verdict {
564  const merged = pull.mergeRuns;
565  if (!merged || merged.workflows.length === 0) {
566    const since = pull.mergedAt ? now - Date.parse(pull.mergedAt) : Infinity;
567    return since < MERGE_GRACE_MS ? { kind: 'merged-waiting' } : { kind: 'closed' };
568  }
569  const runs = runsVerdict({ workflows: merged.workflows, isGated: false }, estimates, host);
570  if (runs?.kind === 'failing') return { ...runs, kind: 'merged-failing' };
571  if (runs?.kind === 'running') return { ...runs, kind: 'merged-running' };
572  return { kind: 'merged-passed' };
573}
574
575const isFailedRun = (w: Workflow) => w.status === 'done' && failed(w.conclusion);
576
577// A push to the trunk runs CI on its newest commit only, so a merge commit
578// landed beneath another, as a stack's lower layer is, never gets runs.
579export function needsTrunk(pull: Pull, now: number): boolean {
580  const runs = pull.mergeRuns;
581  if (pull.state !== 'MERGED' || !runs || pull.mergeOid === undefined) return false;
582  // Outside a stack, a merge commit with no runs was skipped on purpose, as by
583  // a path filter, and a later commit's runs are someone else's.
584  if (runs.workflows.length === 0)
585    return typeof pull.stack?.trunk === 'string' && !isMergeFresh(pull, now);
586  return runs.workflows.some(isFailedRun);
587}
588
589// `trunk` is newest first, in git log order, so a commit above the merge
590// commit holds it only when the merge commit is among its ancestors there.
591export function followTrunk(pull: Pull, trunk: readonly Commit[]): Pull {
592  const at = trunk.findIndex((c) => c.oid === pull.mergeOid);
593  if (at === -1) return pull;
594  // The merge commit heads the chain with its own read's runs, which see 100
595  // check suites to the trunk read's 20.
596  const merge = { ...trunk[at]!, runs: pull.mergeRuns ?? { workflows: [], isTruncated: false } };
597  const chain: Commit[] = [merge];
598  const holds = new Set([merge.oid]);
599  for (const c of trunk.slice(0, at).toReversed()) {
600    if (!c.parents.some((p) => holds.has(p))) continue;
601    holds.add(c.oid);
602    chain.push(c);
603  }
604  const base = chain.findIndex((c) => c.runs.workflows.length > 0);
605  if (base === -1) return pull;
606  const { runs } = chain[base]!;
607  const newer = chain.slice(base + 1).flatMap((c) => c.runs.workflows);
608  const since: string[] = [];
609  const workflows = runs.workflows.map((w) => {
610    if (!isFailedRun(w)) return w;
611    // A skipped run, as from an `if:` on every job, passed nothing.
612    const last = newer.findLast(
613      (n) => n.id === w.id && n.status === 'done' && n.conclusion !== 'SKIPPED',
614    );
615    if (!last || !PASSED.has(last.conclusion ?? '')) return w;
616    since.push(w.name);
617    return last;
618  });
619  if (base === 0 && since.length === 0) return pull;
620  return { ...pull, mergeRuns: { ...runs, workflows }, followed: { isLater: base > 0, since } };
621}
622
623// What stops a merge on the pull request itself; a draft's line says it too.
624function blockerOf(pull: Pull): string | null {
625  if (pull.merge === 'DIRTY') return 'conflicts';
626  if (pull.review === 'CHANGES_REQUESTED') return 'changes requested';
627  if (pull.merge === 'BEHIND') return 'behind base';
628  return null;
629}
630
631export function verdictOf(
632  pull: Pull,
633  estimates: Record<string, number>,
634  host: string,
635  now: number,
636): Verdict {
637  if (pull.state === 'MERGED') return mergedVerdict(pull, estimates, host, now);
638  if (pull.state !== 'OPEN') return { kind: 'closed' };
639  const runs = runsVerdict(pull, estimates, host);
640  if (runs) return runs;
641  if (pull.isDraft) return { kind: 'waiting', reason: 'draft' };
642  const blocker = blockerOf(pull);
643  if (blocker !== null) return { kind: 'blocked', reason: blocker };
644  if (['CLEAN', 'HAS_HOOKS', 'UNSTABLE'].includes(pull.merge)) {
645    const { below } = pull;
646    if (below) {
647      const reason = below.of === 0 ? 'layer below' : `layer ${below.at}/${below.of}`;
648      return { kind: 'waiting', reason };
649    }
650    return { kind: 'ready' };
651  }
652  if (pull.merge === 'BLOCKED') {
653    if (pull.review === 'REVIEW_REQUIRED') return { kind: 'waiting', reason: 'review' };
654    // A required check outside any workflow, a GitHub App's, still running.
655    if (pull.isRequiredPending) return { kind: 'waiting', reason: 'checks' };
656    // Required checks GitHub has not yet started leave the merge blocked.
657    if (pull.workflows.length === 0) return { kind: 'waiting', reason: 'checks to start' };
658    return { kind: 'blocked', reason: 'blocked' };
659  }
660  // GitHub computes the merge state lazily and reports UNKNOWN until it has.
661  return { kind: 'waiting', reason: 'checking' };
662}
663
664const PASSED_STAYS_MS = 5000;
665
666// Every run on the merge commit passed, and the grace for a late one is over.
667// A failed merge settles once a re-run, or a later run on the trunk, passes.
668export function isSettled(verdict: Verdict, pull: Pull, now: number): boolean {
669  if (verdict.kind !== 'merged-passed') return false;
670  const isDone = pull.mergeRuns?.workflows.every((w) => w.status === 'done') ?? true;
671  const since = pull.mergedAt ? now - Date.parse(pull.mergedAt) : Infinity;
672  return isDone && since >= MERGE_GRACE_MS;
673}
674
675export function isCleared(verdict: Verdict, pull: Pull, checkedAt: number, now: number): boolean {
676  return isSettled(verdict, pull, checkedAt) && now - checkedAt >= PASSED_STAYS_MS;
677}
678
679// A line that has waited on a person this long is read every STILL_MS.
680const STILL_AFTER_MS = 30 * 60_000;
681const STILL_MS = 5 * 60_000;
682
683// Poll fast while something moves, slowly while it waits on a person, and
684// slower once the line has said the same for half an hour. A workflow the
685// merge does not wait on still moves the line's marks.
686export function delayOf(verdict: Verdict, pull: Pull, now: number, shownAt = now): number | null {
687  if (verdict.kind === 'closed' || isSettled(verdict, pull, now)) return null;
688  const slow = now - shownAt >= STILL_AFTER_MS ? STILL_MS : 60_000;
689  // A failed merge waits on someone to re-run it.
690  if (verdict.kind === 'merged-failing') {
691    return pull.mergeRuns?.workflows.every((w) => w.status === 'done') === false ? 10_000 : slow;
692  }
693  if (verdict.kind === 'running' || verdict.kind.startsWith('merged-')) return 10_000;
694  if (pull.workflows.some((w) => w.status !== 'done')) return 10_000;
695  // A layer waiting on one below changes when that one's read does.
696  const isPerson = ['review', 'draft'].includes(verdict.kind === 'waiting' ? verdict.reason : '');
697  if (verdict.kind === 'waiting' && !isPerson && !verdict.reason.startsWith('layer')) {
698    return 10_000;
699  }
700  return slow;
701}
702
703// An open pull request takes the row of the push line of its head branch,
704// with what Claude was told of that push, so the two lines do not stack. Only
705// within one repository: a fork's push is handed over by its own read, which
706// knows the fork's parent. One unwatched during its read takes nothing over.
707export function takeOverPush(all: readonly Watch[], pr: Watch): Watch[] {
708  const head = pr.pull?.head;
709  if (pr.push || pr.pull?.state !== 'OPEN' || !head || !all.includes(pr)) return [...all];
710  const repo = pr.repo.toLowerCase();
711  const at = all.findIndex(
712    (w) =>
713      w.push?.branch === head.branch &&
714      w.host === pr.host &&
715      w.repo.toLowerCase() === repo &&
716      head.repo.toLowerCase() === repo,
717  );
718  const push = all[at];
719  if (!push) return [...all];
720  const told = [...new Set([...(pr.told ?? []), ...(push.told ?? [])])];
721  const moved = told.length === 0 ? pr : { ...pr, told };
722  return all.flatMap((w, i) => (i === at ? [moved] : w === pr ? [] : [w]));
723}
724
725// What the line says, as a key: a new failure differs from an old one.
726export function shownOf(verdict: Verdict): string {
727  if (verdict.kind === 'failing' || verdict.kind === 'merged-failing') {
728    return `${verdict.kind}:${JSON.stringify([verdict.workflow, verdict.job])}`;
729  }
730  return verdict.kind;
731}
732
733// The commit a merged line's runs came from.
734const commitOf = (followed: Pull['followed']) =>
735  followed?.isLater ? 'a later commit' : 'the merge commit';
736
737function passedOn({ followed, base }: Pull): string {
738  if (followed?.since.length) {
739    return `${followed.since.join(', ')} failed on ${commitOf(followed)} and since passed on ${base}`;
740  }
741  return followed?.isLater
742    ? `a later commit's checks on ${base} passed`
743    : "the merge commit's checks passed";
744}
745
746// A release tool's version pull request (oakum's, Changesets'), whose merge is
747// the release.
748export function isReleasePull(pull: Pick<Pull, 'head'>): boolean {
749  const branch = pull.head?.branch ?? '';
750  return /(^|\/)version-packages$/.test(branch) || branch.startsWith('changeset-release/');
751}
752
753// The workflows still running on a ready pull request, which the merge does
754// not wait on, since it is ready only once every one it waits on is done.
755export function stillRunning(pull: Pick<Pull, 'workflows'>): string[] {
756  return [...new Set(pull.workflows.filter((w) => w.status !== 'done').map((w) => w.name))];
757}
758
759export function toastOf(
760  label: string,
761  verdict: Verdict,
762  shown?: string,
763  after = ' merged',
764  running: string[] = [],
765): string | null {
766  if (shownOf(verdict) === shown) return null;
767  if (verdict.kind === 'ready') {
768    const note = running.length === 0 ? '' : `; ${running.join(', ')} still running, not required`;
769    return `${label} is ready to merge${note}`;
770  }
771  if (verdict.kind === 'failing') return `${label} ${verdict.workflow}: ${verdict.job} failed`;
772  if (verdict.kind === 'merged-passed') return `${label}${after}: its checks passed`;
773  if (verdict.kind === 'merged-failing') {
774    return `${label}${after}: ${verdict.workflow}: ${verdict.job} failed`;
775  }
776  return null;
777}
778
779// Something Claude is told of once, for as long as it lasts. A passed one is
780// news Claude cannot act on, so it never wakes Claude.
781type Condition = { key: string; text: string; isPassed?: true };
782
783type Who = Pick<Watch, 'repo' | 'number' | 'push'>;
784
785// A watch's own conditions carry it, so watches on the host can share what
786// they told; a push's carries the push, its number being 0.
787const keyOf = (watch: Who, what: string) =>
788  JSON.stringify([
789    watch.repo,
790    watch.push ? [watch.push.branch, watch.push.pushedAt] : watch.number,
791    what,
792  ]);
793
794export const isToldReady = (watch: Who & Pick<Watch, 'told'>) =>
795  (watch.told ?? []).includes(keyOf(watch, 'ready'));
796
797// A pull request a session watched, as saved for its resume.
798export type Saved = Pick<Watch, 'host' | 'repo' | 'number' | 'url' | 'heard'> & {
799  told: string[];
800};
801// One session's entry in the store, under its own key, so sessions never
802// write over each other.
803export type Entry = { at: number; pulls: Saved[] };
804
805export const SESSION_PREFIX = 'session:';
806// The sessions a store keeps watches for; more than this drops the oldest.
807export const SESSIONS_KEPT = 20;
808
809// The ids of watches whose ready line, or passed checks, wait undelivered.
810export type Pending = { ready: ReadonlySet<string>; passed: ReadonlySet<string> };
811
812// The pull requests to watch again on a resume. A push is not: its line lasts
813// only past its checks. A ready or passed line still waiting to be delivered
814// is lost with the exit, so it counts as untold and the first read after the
815// resume tells it again; one Claude was told stays told.
816export function savedOf(
817  watches: readonly Watch[],
818  pending: Pending,
819  idOf: (w: Watch) => string,
820): Saved[] {
821  return watches.flatMap((w) => {
822    if (w.push) return [];
823    const id = idOf(w);
824    const quiet = new Set([
825      ...(pending.ready.has(id) ? [keyOf(w, 'ready')] : []),
826      ...(pending.passed.has(id) ? [keyOf(w, 'passed')] : []),
827    ]);
828    const told = (w.told ?? []).filter((k) => !quiet.has(k));
829    const { host, repo, number, url, heard } = w;
830    return [{ host, repo, number, url, told, ...(heard && { heard }) }];
831  });
832}
833
834const strings = (xs: unknown): string[] =>
835  Array.isArray(xs) ? xs.filter((x): x is string => typeof x === 'string') : [];
836
837// One saved pull request rebuilt from what the store holds, or null when it
838// does not name one: the store is a file on disk, so nothing else is trusted.
839export function savedFrom(p: unknown): Saved | null {
840  const { host, repo, number, told, heard } = (p ?? {}) as Record<string, unknown>;
841  if (typeof host !== 'string' || typeof repo !== 'string') return null;
842  if (!Number.isSafeInteger(number) || (number as number) <= 0) return null;
843  const h: { since?: unknown; keys?: unknown; streak?: unknown } | null =
844    typeof heard === 'object' ? heard : null;
845  const isHeard =
846    h !== null && Array.isArray(h.keys) && (h.since === null || typeof h.since === 'string');
847  const streak = isHeard && Number.isSafeInteger(h.streak) && (h.streak as number) > 0;
848  return {
849    host,
850    repo,
851    number: number as number,
852    url: `https://${host}/${repo}/pull/${number}`,
853    told: strings(told),
854    ...(isHeard && {
855      heard: {
856        since: h.since as string | null,
857        keys: strings(h.keys),
858        ...(streak && { streak: h.streak as number }),
859      },
860    }),
861  };
862}
863
864// A session's entry as the store holds it: the pull requests it names, and
865// how many entries could not be read.
866export function entryOf(stored: unknown): { pulls: Saved[]; skipped: number } {
867  const pulls = (stored as { pulls?: unknown } | null)?.pulls;
868  if (!Array.isArray(pulls)) return { pulls: [], skipped: stored === undefined ? 0 : 1 };
869  const read = pulls.map((p) => savedFrom(p));
870  const found = read.filter((p): p is Saved => p !== null);
871  return { pulls: found, skipped: read.length - found.length };
872}
873
874const atOf = (v: unknown) => {
875  const t = (v as { at?: unknown } | null)?.at;
876  return typeof t === 'number' && Number.isFinite(t) ? t : -Infinity;
877};
878
879// The session keys past the newest SESSIONS_KEPT, oldest first; an entry with
880// no readable time counts as the oldest.
881export function prunedOf(entries: readonly (readonly [string, unknown])[]): string[] {
882  return entries
883    .toSorted(([, a], [, b]) => atOf(b) - atOf(a))
884    .slice(SESSIONS_KEPT)
885    .map(([key]) => key);
886}
887
888// A ready or passed state, conflicts and requested changes whatever the checks
889// say, and every failing run the line follows, gating or not, as soon as a job
890// in it fails. A run is told once, by its first failed jobs: later ones, a
891// summary job among them, are news Claude finds in the run it was sent to.
892function conditionsOf(
893  watch: Who,
894  pull: Pull,
895  verdict: Verdict,
896  name: string,
897  isEarly: boolean,
898): Condition[] {
899  const found: Condition[] = [];
900  if (verdict.kind === 'ready') {
901    const running = stillRunning(pull);
902    // Said as of this read, since held news may reach Claude after they finish.
903    const note =
904      running.length === 0
905        ? ''
906        : ` When pr-watch read it, ${running.join(', ')} ${running.length === 1 ? 'was' : 'were'} still running, not required to merge.`;
907    const text = isReleasePull(pull)
908      ? `GitHub reports ${name}, the release pull request, ready to merge.${note} Merging it is the release: leave it for the user to ask.`
909      : `GitHub reports ${name} ready to merge.${note}`;
910    found.push({ key: keyOf(watch, 'ready'), text });
911  }
912  if (verdict.kind === 'merged-passed' && !isEarly) {
913    const text = watch.push
914      ? `The checks on ${name} passed.`
915      : `${name} merged into ${pull.base}, and ${passedOn(pull)}.`;
916    found.push({ key: keyOf(watch, 'passed'), text, isPassed: true });
917  }
918  if (pull.state === 'OPEN' && pull.merge === 'DIRTY') {
919    const text = `${name} has merge conflicts with ${pull.base}.`;
920    found.push({ key: keyOf(watch, 'conflicts'), text });
921  }
922  if (pull.state === 'OPEN' && pull.review === 'CHANGES_REQUESTED') {
923    const text = `A reviewer requested changes on ${name}.`;
924    found.push({ key: keyOf(watch, 'changes requested'), text });
925  }
926  const isMerged = verdict.kind.startsWith('merged-');
927  const workflows = isMerged ? (pull.mergeRuns?.workflows ?? []) : pull.workflows;
928  const where = isMerged && !watch.push ? ` on ${commitOf(pull.followed)}` : '';
929  for (const w of workflows) {
930    const bad = w.jobs.filter((j) => j.status === 'done' && failed(j.conclusion));
931    if (bad.length === 0) continue;
932    const jobs = bad.map((j) => j.name).join(', ');
933    const log = bad[0]!.url || w.url;
934    const run = w.url && w.url !== log ? `; the run: ${w.url}` : '';
935    const text = `${w.name}: ${jobs} failed${where} for ${name}: ${log}${run}`;
936    found.push({ key: JSON.stringify([w.id, w.url, w.attempt]), text });
937  }
938  return found;
939}
940
941export type Memory = Pick<Watch, 'told' | 'heard'>;
942// `ready` is kept apart from the rest of the news, so a notice held past a
943// merge can leave it out, and so can one whose merge would need asking; `passed`
944// is news for the next prompt, never a wake. `text` is all of it, for a tool's answer.
945export type Wake = {
946  text: string | null;
947  news: string[];
948  ready: string | null;
949  passed: string[];
950  told: string[];
951  heard: Watch['heard'];
952};
953
954export function heldWith(was: Held, next: Held): Held {
955  const news = [...new Set([...was.news, ...next.news])];
956  const isRelease = next.isRelease === true || was.isRelease === true;
957  return { ...next, news, ready: next.ready ?? was.ready, ...(isRelease && { isRelease }) };
958}
959
960// The ready line leads: it is the news Claude acts on.
961export function noticeOf(news: readonly string[], ready: string | null, url: string): string {
962  return [
963    `pr-watch: ${[...(ready === null ? [] : [ready]), ...news].join(' ')}`,
964    `This is news from pr-watch, not a request to merge. ${url}`,
965  ].join('\n');
966}
967
968// With waking off nothing new counts as told, so what lasts is told once it is
969// on again, while what ends is let go, so its return is news.
970export function toldAfter(now: string[], before: string[] | undefined, isAwake: boolean): string[] {
971  return isAwake ? now : now.filter((key) => (before ?? []).includes(key));
972}
973
974// GitHub reports UNKNOWN while it recomputes the merge state.
975export const isChecking = (verdict: Verdict) =>
976  verdict.kind === 'waiting' && verdict.reason === 'checking';
977
978// A comment's or review's identity; its time alone ties at the second.
979const heardKey = (a: Activity) => a.url || JSON.stringify([a.author, a.at, a.did]);
980
981// Enough to outlast an item leaving the 10-item window and coming back.
982const HEARD_KEPT = 100;
983
984// t3code stops a watch after 10 comment-only wakes in a row; this stops the
985// comments alone.
986export const QUIET_CAP = 10;
987
988// The comments and reviews not heard before, and what is heard after them. The
989// first read hears what is there without telling it; a read that cannot tell
990// whose they are hears nothing.
991function hearOf(
992  pull: Pull,
993  heard: Watch['heard'],
994  name: string,
995  tells: (a: Activity) => boolean,
996): { heard: Watch['heard']; lines: string[] } {
997  if (pull.activity === null) return { heard, lines: [] };
998  const keys = pull.activity.map(heardKey);
999  if (heard === undefined) return { heard: { since: pull.activityAt, keys }, lines: [] };
1000  // An unheard item older than the first read's newest slid into the window
1001  // when a newer one was deleted.
1002  const since = heard.since === null ? -Infinity : Date.parse(heard.since);
1003  const lines: string[] = [];
1004  for (const a of pull.activity) {
1005    if (heard.keys.includes(heardKey(a)) || Date.parse(a.at) < since || !tells(a)) continue;
1006    lines.push(`@${a.author} ${a.did} ${name}: ${a.url}`);
1007  }
1008  const kept = [...new Set([...heard.keys, ...keys])].slice(-HEARD_KEPT);
1009  return { heard: { since: heard.since, keys: kept }, lines };
1010}
1011
1012const WAKE_SETTINGS = ['off', 'checks', 'checks and comments'] as const;
1013const BOT_SETTINGS = ['never', 'reviews', 'comments and reviews'] as const;
1014export type WakeSetting = (typeof WAKE_SETTINGS)[number];
1015export type BotSetting = (typeof BOT_SETTINGS)[number];
1016
1017// The two /config settings as plugin.json declares them, each its default when unset.
1018export function settingsOf(options: Record<string, unknown>): {
1019  wake: WakeSetting;
1020  bots: BotSetting;
1021} {
1022  const wake = WAKE_SETTINGS.find((s) => s === options.wake) ?? 'checks and comments';
1023  const bots = BOT_SETTINGS.find((s) => s === options.botComments) ?? 'never';
1024  return { wake, bots };
1025}
1026
1027// Which comments and reviews are told, by the two /config settings. Those not
1028// told are still heard, so a later change of setting reports no history.
1029export function tellsOf(wake: WakeSetting, bots: BotSetting): (a: Activity) => boolean {
1030  if (wake !== 'checks and comments') return () => false;
1031  if (bots === 'comments and reviews') return () => true;
1032  if (bots === 'reviews') return (a) => !a.isBot || a.isReview;
1033  return (a) => !a.isBot;
1034}
1035
1036const PEOPLE_ONLY = tellsOf('checks and comments', 'never');
1037
1038// What Claude is told unasked: each condition it has not been told of while it
1039// lasts, and each comment or review it has not heard that `tells` lets through.
1040// `isEarly` holds back a passed merge whose grace has not ended; `isOwnMerge`
1041// counts a passed merge Claude made as told, since only a failure is news then.
1042export function wakeOf(
1043  watch: Pick<Watch, 'repo' | 'number' | 'push' | 'url'>,
1044  pull: Pull,
1045  verdict: Verdict,
1046  last: Memory,
1047  { isEarly = false, isOwnMerge = false, tells = PEOPLE_ONLY } = {},
1048): Wake {
1049  const name = watch.push
1050    ? `the push to ${watch.push.branch} on ${watch.repo}`
1051    : `${watch.repo}#${watch.number}`;
1052  const told = last.told ?? [];
1053  const news: string[] = [];
1054  const passed: string[] = [];
1055  const kept: string[] = [];
1056  let ready: string | null = null;
1057  for (const c of conditionsOf(watch, pull, verdict, name, isEarly)) {
1058    const isQuiet = isOwnMerge && c.isPassed;
1059    const isNew = !told.includes(c.key) && !isQuiet;
1060    if (isNew && c.key === keyOf(watch, 'ready')) ready = c.text;
1061    else if (isNew && c.isPassed) passed.push(c.text);
1062    else if (isNew) news.push(c.text);
1063    kept.push(c.key);
1064  }
1065  // GitHub reports UNKNOWN while it recomputes the merge state; ready stands only
1066  // through a read that is otherwise ready, since a new run ends it.
1067  if (pull.state === 'OPEN' && pull.merge === 'UNKNOWN') {
1068    for (const what of isChecking(verdict) ? ['ready', 'conflicts'] : ['conflicts']) {
1069      const key = keyOf(watch, what);
1070      if (told.includes(key) && !kept.includes(key)) kept.push(key);
1071    }
1072  }
1073  const { heard: next, lines } = hearOf(pull, last.heard, name, tells);
1074  // So a chatty bot or thread cannot keep waking Claude, comments and reviews
1075  // stop after QUIET_CAP wakes in a row of nothing else, until other news comes.
1076  const before = last.heard?.streak ?? 0;
1077  const isOther = news.length > 0 || ready !== null || passed.length > 0;
1078  const streak = isOther ? 0 : lines.length > 0 ? before + 1 : before;
1079  if (streak <= QUIET_CAP) news.push(...lines);
1080  if (lines.length > 0 && streak === QUIET_CAP) {
1081    news.push(
1082      `pr-watch will tell you of no more comments or reviews on ${name} until other news comes.`,
1083    );
1084  }
1085  const heard = next && { since: next.since, keys: next.keys, ...(streak > 0 && { streak }) };
1086  const all = [...news, ...passed];
1087  const text = all.length === 0 && ready === null ? null : noticeOf(all, ready, watch.url);
1088  return { text, news, ready, passed, told: kept, heard };
1089}
1090
1091// What the person's next prompt carries of the news held back from waking
1092// Claude: each line once, with what it may do about a ready pull request.
1093export function contextOf(quiet: readonly Held[]): string | null {
1094  const lines = quiet.flatMap((q) => [...(q.ready === null ? [] : [q.ready]), ...q.news]);
1095  if (lines.length === 0) return null;
1096  // A release pull request is not offered: its merge is the release. Beside
1097  // one, the offer names the pull requests it covers.
1098  const offerable = quiet.filter((q) => q.ready !== null && !q.isRelease);
1099  const isBeside = quiet.some((q) => q.ready !== null && q.isRelease);
1100  const what = isBeside ? offerable.map((q) => q.label).join(', ') : 'it';
1101  return [
1102    `pr-watch, since your last turn: ${lines.join(' ')}`,
1103    ...(offerable.length > 0
1104      ? [`Merging needs the user to ask for it; offer ${what} if it fits.`]
1105      : []),
1106  ].join('\n');
1107}
1108
1109// The prompt-box suggestion for the latest pull request held ready.
1110export function suggestionOf(quiet: readonly Held[]): string | null {
1111  const ready = quiet.findLast((q) => q.ready !== null && !q.isRelease);
1112  return ready ? `merge ${ready.label}` : null;
1113}
1114
1115export function clockText(ms: number): string {
1116  const s = Math.max(0, Math.round(ms / 1000));
1117  return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`;
1118}
1119
1120// A bar `width` cells wide, filled to `fraction` in eighths of a cell.
1121export function barOf(fraction: number, width: number): { filled: string; rest: string } {
1122  const eighths = Math.round(Math.min(Math.max(fraction, 0), 1) * width * 8);
1123  const full = Math.floor(eighths / 8);
1124  const head = EIGHTHS[eighths % 8] ?? '';
1125  const filled = '█'.repeat(full) + head;
1126  return { filled, rest: '░'.repeat(width - full - (head ? 1 : 0)) };
1127}
1128
1129export function markOf(w: Workflow): string {
1130  if (w.status !== 'done') return '●';
1131  return PASSED.has(w.conclusion ?? '') ? '✓' : '✗';
1132}
1133
1134// `isMark` is drawn whole: a row too wide for the band cuts its words first.
1135export type Segment = {
1136  text: string;
1137  color?: string;
1138  isDim?: boolean;
1139  url?: string;
1140  isMark?: true;
1141};
1142
1143// A status colors its mark alone; the words beside it keep the plain text color.
1144const icon = (text: string, color: string | undefined): Segment => ({
1145  text,
1146  ...(color === undefined ? {} : { color }),
1147  isMark: true,
1148});
1149
1150const BAR_MAX = 24;
1151const BAR_MIN = 8;
1152
1153const MARK_COLOR: Record<string, string> = { '✓': 'green', '✗': 'red', '●': 'blue' };
1154
1155function markSegments(w: Workflow): Segment[] {
1156  const mark = markOf(w);
1157  return [{ text: ` · ${w.name} ` }, icon(mark, MARK_COLOR[mark])];
1158}
1159
1160// One line of the band. A running gate whose length is known draws a bar that
1161// stops short of full until the run ends.
1162// A stack layer's line carries its place after the label, as `≡ #236 1/2`.
1163export function lineOf(
1164  watch: Watch,
1165  now: number,
1166  estimates: Record<string, number>,
1167  columns: number,
1168): Segment[] {
1169  const layer = layerOf(watch);
1170  if (layer === null) return bodyOf(watch, now, estimates, columns);
1171  const badge = { text: ` ≡ #${layer.stack} ${layer.at}/${layer.of}`, isDim: true };
1172  const [label, ...rest] = bodyOf(watch, now, estimates, columns - badge.text.length);
1173  return [label!, badge, ...rest];
1174}
1175
1176function bodyOf(
1177  watch: Watch,
1178  now: number,
1179  estimates: Record<string, number>,
1180  columns: number,
1181): Segment[] {
1182  const isPush = watch.push !== undefined;
1183  const title = isPush ? `⟳ ${labelOf(watch)}` : labelOf(watch);
1184  const label = { text: title, color: 'cyan', url: watch.url };
1185  const pull = watch.pull;
1186  // A failure and a pause are separate facts, so a line says both.
1187  const pause =
1188    watch.limitedUntil === undefined
1189      ? undefined
1190      : `rate limited until ${untilText(watch.limitedUntil)}`;
1191  const problem = [watch.error, pause].filter(Boolean).join(' · ') || undefined;
1192  const isOffline = (watch.offline ?? 0) >= OFFLINE_NOTE_AFTER;
1193  if (!pull) {
1194    const quiet = isOffline ? 'offline, retrying' : 'loading…';
1195    return [
1196      label,
1197      {
1198        text: ` ${problem ?? quiet}`,
1199        isDim: problem === undefined,
1200        color: problem === undefined ? undefined : 'red',
types/index.d.ts 154 lines
1export type RunStatus = 'queued' | 'running' | 'done';
2
3export type Job = {
4  name: string;
5  status: RunStatus;
6  conclusion: string | null;
7  url: string;
8  isRequired: boolean;
9};
10
11export type Workflow = {
12  id: number;
13  name: string;
14  status: RunStatus;
15  conclusion: string | null;
16  // The run's creation, which a re-run keeps from its first attempt.
17  startedAt: string;
18  isRerun: boolean;
19  // The run's attempt, 1 for the first: a re-run keeps the run's URL.
20  attempt: number;
21  // The run's id, which asks GitHub when a re-run's attempt started.
22  runId?: number;
23  url: string;
24  jobs: Job[];
25};
26
27export type Runs = { workflows: Workflow[]; isTruncated: boolean };
28
29export type Commit = { oid: string; parents: string[]; runs: Runs };
30
31// A github/gh-stack stack: its number, the branch its bottom layer merges
32// into, and its layers' pull request numbers, bottom first.
33// `merged` lists the layers the stacks API reports merged; it keeps them in `layers`.
34export type Stack = { number: number; trunk: string; layers: number[]; merged?: number[] };
35
36// A comment or review on a pull request by someone other than the viewer.
37export type Activity = {
38  author: string;
39  at: string;
40  url: string;
41  did: string;
42  isBot: boolean;
43  isReview: boolean;
44};
45
46export type Pull = {
47  number: number;
48  title: string;
49  url: string;
50  state: 'OPEN' | 'MERGED' | 'CLOSED';
51  isDraft: boolean;
52  merge: string;
53  review: string | null;
54  workflows: Workflow[];
55  // Some check on the head commit is required, from a workflow or an App.
56  isGated: boolean;
57  // A required check from a GitHub App has not finished.
58  isRequiredPending: boolean;
59  // The head commit has more check suites than one read returns.
60  isTruncated: boolean;
61  // The branch merged into, and once merged, when and the merge commit's runs.
62  base: string;
63  // The branch and repository it merges from, which a push line of it matches.
64  head?: { branch: string; repo: string };
65  mergedAt: string | null;
66  mergeRuns: Runs | null;
67  mergeOid?: string;
68  // Set when `mergeRuns` holds later trunk commits' runs: one later commit's
69  // in place of none (`isLater`), newer passing runs of `since`, or both.
70  followed?: { isLater: boolean; since: string[] };
71  // The stack it is a layer of, null in none, unset until GitHub's stacks API
72  // answers; `stackAt` is when it was asked, so a `gh stack` command since
73  // has it asked again.
74  stack?: Stack | null;
75  stackAt?: number;
76  // `stack` was answered on a read that found it merged.
77  stackMerged?: boolean;
78  // The nearest open layer below that is not ready, by place in the stack;
79  // a stack merge of this layer would merge it too.
80  below?: { at: number; of: number };
81  // The latest comments and reviews by others, oldest first; null when the
82  // reply lacks the viewer or either list.
83  activity: Activity[] | null;
84  // The newest comment or review in the window, the viewer's included.
85  activityAt: string | null;
86};
87
88// A pull request the band follows, as the last poll left it. A push Claude
89// made to a branch with no open pull request has `push` and number 0, and its
90// `pull` reads as a merge into that branch at the push.
91export type Watch = {
92  host: string;
93  repo: string;
94  number: number;
95  url: string;
96  push?: { branch: string; pushedAt: number };
97  pull?: Pull;
98  error?: string;
99  checkedAt: number;
100  // What the line last said, so a toast fires once per change.
101  shown?: string;
102  // When `shown` last changed, so a line long the same is read less often.
103  shownAt?: number;
104  // Reads in a row that failed, a rate limit and an unreachable GitHub aside.
105  failures?: number;
106  // A read since the last good one was refused by GitHub, so a later failure of
107  // another kind does not let an unread push leave quietly. Cleared with `failures`.
108  refused?: boolean;
109  // Reads in a row on its host that could not reach GitHub.
110  offline?: number;
111  // When the rate limit pausing its host ends, until a read of its own.
112  limitedUntil?: number;
113  // The conditions Claude has been told of, so each is told once while it lasts.
114  told?: string[];
115  // The comments and reviews heard, and the newest time at the first read,
116  // which hears without telling: older ones are history.
117  // `streak` counts the reads in a row whose only news was comments and reviews.
118  heard?: { since: string | null; keys: string[]; streak?: number };
119};
120
121export type Held = {
122  id: string;
123  label: string;
124  url: string;
125  news: string[];
126  ready: string | null;
127  // A release tool's version pull request, whose merge is the release.
128  isRelease?: boolean;
129};
130
131declare module 'claude-code' {
132  interface PluginState {
133    'pr-watch': {
134      watches: Watch[];
135      // The last successful run's length in ms, by `<host>/<workflow id>`; 0
136      // when the workflow has none. Also a re-run attempt's start in ms, by
137      // `<host>/run/<run id>/<attempt>`.
138      estimates: Record<string, number>;
139      now: number;
140      // On the host, so a reload mid-turn keeps held news already saved as told.
141      turn: { isTurning: boolean; held: Held[] };
142      // Watch ids, kept apart from the watch so a read in flight cannot drop one.
143      ownMerges: string[];
144      // Watch ids whose ready line and passed checks wake Claude, as the watch
145      // tool was asked; kept apart for the same reason.
146      wakeAsked: string[];
147      // News kept from Claude until the person's next prompt carries it.
148      quiet: Held[];
149      // The session id whose saved watches were restored.
150      restored: string | null;
151    };
152  }
153}
154