SLOPSHOPPER

github

GitHub workflow, Actions monitoring, and rulesets management

spinnerprocesstimer
★ 18v?MITupdated 2026-10-22bendrucker/claude/plugins/github
A shopper browsing a rack in a slop shop
README

GitHub Plugin

GitHub workflow, Actions monitoring, and rulesets management for Claude Code.

Contents

  • Skills:
  • actions-monitor: Watch a PR's CI and stream state events; invokes the logs agent on failures
  • attach: Attach an image or video to an issue, PR, comment, or review, through gh --attach or the user-attachments endpoint it wraps
  • copilot: Cross-model review of the current diff through the Copilot CLI. Slash-invocable only, one call by default and three at most, because the Copilot plan is a fixed budget
  • notifications: Inbox management (list, filter, mark read/done, unsubscribe)
  • pr-comments: Fetch unresolved review comments from a pull request
  • stack: Build, publish, and merge native stacked PRs with the gh stack extension
  • Agents:
  • github-rulesets-manager: Configure repository rulesets and branch protection
  • logs: Extracts relevant lines from failing-job logs (invoked by actions-monitor)
  • Hooks:
  • Intercepts WebFetch for efficient GitHub data access
  • runner-queue.ts follows gh workflow run with the new run's place in line when it waits on a self-hosted runner, so the model knows why the run has not started and how long to wait before checking. Silent when the job starts at once or runs on a GitHub-hosted runner. Self-timed to ~/.claude/hook-metrics/github-runner-queue.jsonl
    [github/runner-queue] Run 39817210542 is queued for a self-hosted runner labeled actions-sandbox: 0 job(s) ahead, 1 matching job(s) running.
    Holding the runner:
    - session-bench run 39815981118 job "bench" on main, started 8m ago (recent successful runs take ~14m)
  • Mod: register.ts watches the current branch's pull request and shows its CI and review state at the end of the prompt footer. The model is told when the PR merges or closes, when it conflicts with its base or needs an update that the base requires, when its branch moves to a commit the local repository lacks, when a check newly fails, and when other people review or comment, in one line per author. A conflict alert points at the git:conflicts skill and fires even when the conflict is already there as the PR is first seen. Every decision and send is logged to mod-events. Needs a signed-in gh. Set the watch option to false to turn it off

Testing

bun test plugins/github
bun scripts/mod-test.ts github
Source 2 files
mod/register.ts 357 lines
1import type { EngineInterface, On, PluginOptions } from "claude-code";
2import {
3  STALE,
4  type Promoted,
5  type Snapshot,
6  VIEW_FIELDS,
7  baselineOf,
8  combine,
9  decide,
10  messageOf,
11  parseView,
12  snapshotOf,
13  statusOf,
14} from "./pr.ts";
15
16const MOD = "github";
17
18export const POLL_MS = {
19  pending: 60_000,
20  settled: 180_000,
21  idle: 120_000,
22  closed: 600_000,
23  error: 300_000,
24} as const;
25
26// A dropped injection is retried on later polls, up to this many attempts.
27export const MAX_ATTEMPTS = 3;
28// Skipped when origin/HEAD is unset and the real default branch is unknown.
29const DEFAULT_BRANCHES = new Set(["main", "master"]);
30// /clear and /resume keep the process running, so the watch continues.
31const CONTINUING = new Set(["clear", "resume"]);
32
33interface Undelivered {
34  head: string;
35  decisions: Promoted[];
36  attempts: number;
37}
38
39interface Watch {
40  snapshot: Snapshot | undefined;
41  me: string | undefined;
42  undelivered: Undelivered | undefined;
43  error: string | undefined;
44  timer: { cancel(): void } | undefined;
45  line: string | undefined;
46  generation: number;
47  isStopped: boolean;
48}
49
50type Read = { kind: "none" } | { kind: "pr"; snapshot: Snapshot };
51
52function show($: EngineInterface, watch: Watch, text: string | undefined) {
53  const line = text === "" ? undefined : text;
54  if (line === watch.line) return;
55  watch.line = line;
56  $.ui.invalidate("ui.render");
57}
58
59function emit($: EngineInterface, event: string, detail: Record<string, unknown>, ok = true) {
60  void $.modEvents.emit({ mod: MOD, event, ok, detail });
61}
62
63async function isDefaultBranch($: EngineInterface, cwd: string, branch: string): Promise<boolean> {
64  const origin = await $.process.run(
65    ["git", "symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"],
66    { cwd },
67  );
68  if (origin.exitCode !== 0) return DEFAULT_BRANCHES.has(branch);
69  return origin.stdout.trim() === `origin/${branch}`;
70}
71
72// The login only filters the viewer's own feedback, so a token that cannot read
73// it leaves that feedback unfiltered rather than failing the poll.
74async function meOf(
75  $: EngineInterface,
76  watch: Watch,
77  cwd: string,
78  url: string,
79): Promise<string | undefined> {
80  if (watch.me !== undefined) return watch.me;
81  const argv = ["gh", "api", "user", "--hostname", new URL(url).hostname, "--jq", ".login"];
82  const user = await $.process.run(argv, { cwd, timeoutMs: 20_000 });
83  const login = user.stdout.trim();
84  if (user.exitCode !== 0 || login === "") return undefined;
85  watch.me = login;
86  return login;
87}
88
89// Every worktree of the repository shares one object store, so only a push from
90// another clone or from GitHub itself leaves the head unknown here. Only exit 1
91// means a missing object, so a failing git reads as known rather than crying push.
92async function isKnown($: EngineInterface, cwd: string, sha: string): Promise<boolean> {
93  const argv = ["git", "rev-parse", "--verify", "--quiet", `${sha}^{commit}`];
94  const result = await $.process.run(argv, { cwd });
95  return result.exitCode !== 1;
96}
97
98// A commit once present stays present, so only a new or missing head is checked again.
99async function isHeadKnownOf(
100  $: EngineInterface,
101  watch: Watch,
102  cwd: string,
103  sha: string,
104): Promise<boolean> {
105  const prev = watch.snapshot;
106  if (prev?.head === sha && prev.isHeadKnown) return true;
107  return isKnown($, cwd, sha);
108}
109
110async function readPr($: EngineInterface, watch: Watch): Promise<Read> {
111  const cwd = await $.session.cwd();
112  const head = await $.process.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd });
113  const branch = head.stdout.trim();
114  if (head.exitCode !== 0 || branch === "HEAD" || (await isDefaultBranch($, cwd, branch))) {
115    return { kind: "none" };
116  }
117  const view = await $.process.run(["gh", "pr", "view", "--json", VIEW_FIELDS], {
118    cwd,
119    timeoutMs: 20_000,
120  });
121  if (view.exitCode !== 0) {
122    if (/no pull requests found/i.test(view.stderr)) return { kind: "none" };
123    const line = view.stderr.trim().split("\n")[0] ?? "";
124    throw new Error(line === "" ? `gh exited ${view.exitCode}` : line);
125  }
126  const parsed = parseView(view.stdout);
127  if (parsed === undefined) throw new Error("gh pr view returned an unexpected shape");
128  const [me, isHeadKnown] = await Promise.all([
129    meOf($, watch, cwd, parsed.url),
130    isHeadKnownOf($, watch, cwd, parsed.headRefOid),
131  ]);
132  return { kind: "pr", snapshot: snapshotOf(parsed, { me, isHeadKnown }) };
133}
134
135async function inject(
136  $: EngineInterface,
137  snapshot: Snapshot,
138  promoted: Promoted[],
139  attempt: number,
140): Promise<boolean> {
141  const text = messageOf(snapshot, promoted);
142  const kinds = promoted.map((d) => d.kind);
143  const detail = { pr: snapshot.pr, head: snapshot.head, kinds, chars: text.length, attempt };
144  try {
145    const result = await $.prompt.submit({ text });
146    if (result.drop !== undefined) {
147      emit($, "inject", { ...detail, dropped: result.drop }, false);
148      return false;
149    }
150    emit($, "inject", detail);
151    return true;
152  } catch (error) {
153    emit($, "inject", { ...detail, error: String(error) }, false);
154    return false;
155  }
156}
157
158interface Due {
159  due: Promoted[];
160  /** Blocks waiting on the forge to decide mergeability, kept unsent. */
161  held: Promoted[];
162}
163
164// `decided` is this poll's own mergeability answer, before any carry-forward.
165function stillDue(
166  undelivered: Undelivered | undefined,
167  next: Snapshot,
168  decided: Snapshot["block"],
169): Due {
170  if (undelivered === undefined) return { due: [], held: [] };
171  const held: Promoted[] = [];
172  const due = undelivered.decisions.flatMap((decision): Promoted[] => {
173    if (decision.kind === "pr.merged") return next.state === "MERGED" ? [decision] : [];
174    if (decision.kind === "pr.closed") return next.state === "CLOSED" ? [decision] : [];
175    if (next.state !== "OPEN") return [];
176    if (decision.kind === "conflict" || decision.kind === "behind") {
177      if (decided === undefined) held.push(decision);
178      return decided === decision.kind ? [decision] : [];
179    }
180    if (decision.kind === "push.foreign") return next.isHeadKnown ? [] : [decision];
181    if (decision.kind !== "ci.failed") return [decision];
182    if (undelivered.head !== next.head) return [];
183    const failed = decision.failed.filter((label) => next.failed.includes(label));
184    return failed.length > 0 ? [{ ...decision, failed }] : [];
185  });
186  return { due, held };
187}
188
189// A failed send joins whatever a poll that ran meanwhile left undelivered.
190async function send(
191  $: EngineInterface,
192  watch: Watch,
193  next: Snapshot,
194  due: Promoted[],
195  attempt: number,
196  isCurrent: () => boolean,
197): Promise<void> {
198  const isSent = await inject($, next, due, attempt);
199  if (!isCurrent() || isSent || attempt >= MAX_ATTEMPTS) return;
200  const pending = watch.undelivered;
201  watch.undelivered = {
202    head: pending?.head ?? next.head,
203    decisions: pending === undefined ? due : combine(due, pending.decisions),
204    attempts: Math.max(attempt, pending?.attempts ?? 0),
205  };
206}
207
208function delayOf(snapshot: Snapshot): number {
209  if (snapshot.state !== "OPEN") return POLL_MS.closed;
210  return snapshot.phase === "pending" ? POLL_MS.pending : POLL_MS.settled;
211}
212
213interface Applied {
214  delay: number;
215  /** The send, which waits for an idle session, so the next poll is not held on it. */
216  delivery: Promise<void> | undefined;
217}
218
219function apply($: EngineInterface, watch: Watch, read: Read, isCurrent: () => boolean): Applied {
220  if (read.kind === "none") {
221    show($, watch, undefined);
222    watch.snapshot = undefined;
223    watch.undelivered = undefined;
224    return { delay: POLL_MS.idle, delivery: undefined };
225  }
226  const prev = watch.snapshot;
227  const isSamePr = prev !== undefined && prev.pr === read.snapshot.pr;
228  // An undecided poll keeps the last answer, so a recompute does not re-announce a block.
229  const decided = read.snapshot.block;
230  const next =
231    isSamePr && decided === undefined ? { ...read.snapshot, block: prev.block } : read.snapshot;
232  let due: Promoted[];
233  let attempt = 1;
234  if (!isSamePr) {
235    emit($, "pr.tracked", { pr: next.pr, head: next.head, phase: next.phase, state: next.state });
236    watch.undelivered = undefined;
237    due = baselineOf(next);
238    for (const { action, ...detail } of due) {
239      emit($, action, { pr: next.pr, head: next.head, baseline: true, ...detail });
240    }
241  } else {
242    const decisions = decide(prev, next);
243    for (const { action, ...detail } of decisions) {
244      emit($, action, { pr: next.pr, head: next.head, ...detail });
245    }
246    const fresh = decisions.filter((d): d is Promoted => d.action === "promote");
247    const still = stillDue(watch.undelivered, next, decided);
248    attempt = fresh.length > 0 ? 1 : (watch.undelivered?.attempts ?? 0) + 1;
249    watch.undelivered =
250      still.held.length > 0
251        ? { head: next.head, decisions: still.held, attempts: attempt - 1 }
252        : undefined;
253    due = combine(still.due, fresh);
254  }
255  watch.snapshot = next;
256  show($, watch, statusOf(next));
257  const delivery = due.length > 0 ? send($, watch, next, due, attempt, isCurrent) : undefined;
258  return { delay: delayOf(next), delivery };
259}
260
261async function poll($: EngineInterface, watch: Watch, generation: number): Promise<void> {
262  const isCurrent = () => !watch.isStopped && watch.generation === generation;
263  if (!isCurrent()) return;
264  let delay: number;
265  let delivery: Promise<void> | undefined;
266  try {
267    const read = await readPr($, watch);
268    // A session.end that landed while gh ran has already cleared the status.
269    if (!isCurrent()) return;
270    ({ delay, delivery } = apply($, watch, read, isCurrent));
271    watch.error = undefined;
272  } catch (error) {
273    const message = error instanceof Error ? error.message : String(error);
274    if (message !== watch.error) emit($, "poll.error", { error: message }, false);
275    watch.error = message;
276    delay = POLL_MS.error;
277    if (watch.snapshot !== undefined && isCurrent()) {
278      const line = statusOf(watch.snapshot);
279      show($, watch, line === "" ? STALE : `${line} · ${STALE}`);
280    }
281  }
282  if (!isCurrent()) return;
283  watch.timer = $.clock.after(delay, () => void poll($, watch, generation));
284  await delivery;
285}
286
287async function hasGh($: EngineInterface): Promise<boolean> {
288  try {
289    return (await $.process.run(["gh", "--version"], { timeoutMs: 5000 })).exitCode === 0;
290  } catch {
291    // run() rejects when gh is not on PATH.
292    return false;
293  }
294}
295
296/**
297 * Watches the current branch's pull request with `gh` and shows its CI and
298 * review state at the end of the prompt footer. What `decide` promotes is sent
299 * to the model, along with a block already present when a PR is first seen.
300 * Every other change is only shown and logged.
301 */
302export function register(on: On, options: PluginOptions): void {
303  const watch: Watch = {
304    snapshot: undefined,
305    me: undefined,
306    undelivered: undefined,
307    error: undefined,
308    timer: undefined,
309    line: undefined,
310    generation: 0,
311    isStopped: true,
312  };
313
314  on("session.start", async ($, e, next) => {
315    const generation = watch.generation;
316    const started = await next(e);
317    if (!e.isInteractive) {
318      emit($, "session.start", { active: false, reason: "non-interactive" });
319      return started;
320    }
321    if (options.watch === false) {
322      emit($, "session.start", { active: false, reason: "watch off" });
323      return started;
324    }
325    if (!(await hasGh($))) {
326      emit($, "session.start", { active: false, reason: "gh unavailable" });
327      return started;
328    }
329    // A session.end while this start was in flight has moved the generation on.
330    if (watch.generation !== generation) return started;
331    emit($, "session.start", { active: true });
332    if (watch.isStopped) {
333      watch.isStopped = false;
334      watch.me = undefined;
335      watch.generation += 1;
336      void poll($, watch, watch.generation);
337    }
338    return started;
339  });
340
341  on("ui.render", { component: "PromptHint" }, ($, e, next) => {
342    if (watch.line === undefined) return next(e);
343    const tail = e.props.tail === undefined ? watch.line : `${e.props.tail} · ${watch.line}`;
344    return next({ ...e, props: { ...e.props, tail } });
345  });
346
347  on("session.end", ($, e, next) => {
348    if (!CONTINUING.has(e.reason)) {
349      watch.isStopped = true;
350      watch.generation += 1;
351      watch.timer?.cancel();
352      show($, watch, undefined);
353    }
354    return next(e);
355  });
356}
357
mod/pr.ts 499 lines
1export const VIEW_FIELDS =
2  "number,url,state,headRefOid,baseRefName,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,reviews,comments";
3
4export interface CheckNode {
5  __typename?: string;
6  name?: string | null;
7  workflowName?: string | null;
8  context?: string | null;
9  status?: string | null;
10  conclusion?: string | null;
11  state?: string | null;
12  startedAt?: string | null;
13}
14
15export interface ReviewNode {
16  id: string;
17  author?: { login?: string } | null;
18  state: string;
19}
20
21export interface CommentNode {
22  id: string;
23  author?: { login?: string } | null;
24  isMinimized?: boolean;
25  viewerDidAuthor?: boolean;
26}
27
28export interface PrView {
29  number: number;
30  url: string;
31  state: string;
32  headRefOid: string;
33  baseRefName?: string | null;
34  mergeable?: string | null;
35  mergeStateStatus?: string | null;
36  reviewDecision?: string | null;
37  statusCheckRollup?: CheckNode[] | null;
38  reviews?: ReviewNode[] | null;
39  comments?: CommentNode[] | null;
40}
41
42const isRecord = (value: unknown): value is Record<string, unknown> =>
43  typeof value === "object" && value !== null && !Array.isArray(value);
44
45const textOf = (value: unknown): string | null => (typeof value === "string" ? value : null);
46
47const loginOf = (value: unknown): { login: string } | null => {
48  const login = isRecord(value) ? textOf(value.login) : null;
49  return login === null ? null : { login };
50};
51
52function checkOf(value: unknown): CheckNode | undefined {
53  if (!isRecord(value)) return undefined;
54  return {
55    __typename: textOf(value.__typename) ?? "CheckRun",
56    name: textOf(value.name),
57    workflowName: textOf(value.workflowName),
58    context: textOf(value.context),
59    status: textOf(value.status),
60    conclusion: textOf(value.conclusion),
61    state: textOf(value.state),
62    startedAt: textOf(value.startedAt),
63  };
64}
65
66function reviewOf(value: unknown): ReviewNode | undefined {
67  if (!isRecord(value) || typeof value.id !== "string" || typeof value.state !== "string") {
68    return undefined;
69  }
70  return { id: value.id, state: value.state, author: loginOf(value.author) };
71}
72
73function commentOf(value: unknown): CommentNode | undefined {
74  if (!isRecord(value) || typeof value.id !== "string") return undefined;
75  return {
76    id: value.id,
77    author: loginOf(value.author),
78    isMinimized: value.isMinimized === true,
79    viewerDidAuthor: value.viewerDidAuthor === true,
80  };
81}
82
83function listOf<T>(value: unknown, item: (v: unknown) => T | undefined): T[] {
84  if (!Array.isArray(value)) return [];
85  return value.map(item).filter((v): v is T => v !== undefined);
86}
87
88/** Narrows `gh pr view --json` output to a PrView, or undefined when it is not one. */
89export function parseView(stdout: string): PrView | undefined {
90  let value: unknown;
91  try {
92    value = JSON.parse(stdout);
93  } catch {
94    // The caller reports malformed output as an unexpected shape.
95    return undefined;
96  }
97  if (
98    !isRecord(value) ||
99    typeof value.number !== "number" ||
100    typeof value.url !== "string" ||
101    typeof value.state !== "string" ||
102    typeof value.headRefOid !== "string"
103  ) {
104    return undefined;
105  }
106  return {
107    number: value.number,
108    url: value.url,
109    state: value.state,
110    headRefOid: value.headRefOid,
111    baseRefName: textOf(value.baseRefName),
112    mergeable: textOf(value.mergeable),
113    mergeStateStatus: textOf(value.mergeStateStatus),
114    reviewDecision: textOf(value.reviewDecision),
115    statusCheckRollup: listOf(value.statusCheckRollup, checkOf),
116    reviews: listOf(value.reviews, reviewOf),
117    comments: listOf(value.comments, commentOf),
118  };
119}
120
121export type Phase = "none" | "pending" | "passing" | "failing";
122
123/** What stands between the branch and a merge that the session can fix. */
124export type Block = "conflict" | "behind" | "none";
125
126export interface Snapshot {
127  pr: number;
128  url: string;
129  state: string;
130  head: string;
131  /** False when the head is a commit this checkout has never seen. */
132  isHeadKnown: boolean;
133  base: string;
134  /** Undefined while GitHub is still computing mergeability. */
135  block: Block | undefined;
136  phase: Phase;
137  total: number;
138  pending: number;
139  failed: string[];
140  reviewDecision: string;
141  reviews: { id: string; author: string; state: string }[];
142  comments: { id: string; author: string }[];
143}
144
145/** The session's own login and whether the PR head commit exists locally. */
146export interface Local {
147  me: string | undefined;
148  isHeadKnown: boolean;
149}
150
151export type Decision =
152  | { action: "promote"; kind: "pr.merged" }
153  | { action: "promote"; kind: "pr.closed" }
154  | { action: "promote"; kind: "conflict" }
155  | { action: "promote"; kind: "behind" }
156  | { action: "promote"; kind: "push.foreign"; from: string }
157  | { action: "promote"; kind: "ci.failed"; failed: string[] }
158  | { action: "promote"; kind: "feedback"; author: string; states: string[]; comments: number }
159  | { action: "drop"; kind: "unblocked" }
160  | { action: "drop"; kind: "ci.passing" | "ci.pending" | "ci.none" }
161  | { action: "drop"; kind: "push"; from: string };
162
163export type Promoted = Extract<Decision, { action: "promote" }>;
164
165// CANCELLED stays out: a newer push or a concurrency group usually cancelled it.
166const FAILED = new Set(["FAILURE", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE", "ERROR"]);
167const PENDING_STATES = new Set(["PENDING", "EXPECTED"]);
168
169type Outcome = "pending" | "passed" | "failed";
170
171function outcomeOf(node: CheckNode): Outcome {
172  if (node.__typename === "StatusContext") {
173    if (PENDING_STATES.has(node.state ?? "")) return "pending";
174    return FAILED.has(node.state ?? "") ? "failed" : "passed";
175  }
176  if (node.status !== "COMPLETED") return "pending";
177  return FAILED.has(node.conclusion ?? "") ? "failed" : "passed";
178}
179
180const LABEL_MAX = 80;
181
182// Any app with checks access names its checks, and the label reaches the model.
183function flatten(text: string): string {
184  const flat = text
185    .replaceAll(/[\p{Cc}\u2028\u2029]/gu, " ")
186    .replaceAll(/\s+/g, " ")
187    .trim();
188  return flat === "" ? "check" : flat;
189}
190
191// The full label identifies a check. Only what is shown is shortened.
192function labelOf(node: CheckNode): string {
193  if (node.__typename === "StatusContext") return flatten(node.context ?? "status");
194  const name = node.name ?? "check";
195  const workflow = node.workflowName ?? "";
196  return flatten(workflow === "" ? name : `${workflow} / ${name}`);
197}
198
199function shown(label: string): string {
200  return label.length > LABEL_MAX ? `${label.slice(0, LABEL_MAX - 1)}…` : label;
201}
202
203// A rerun lists beside the run it replaces, so keep the latest start per label.
204// One not started yet is queued, hence newest.
205function latest(nodes: CheckNode[]): CheckNode[] {
206  const byLabel = new Map<string, CheckNode>();
207  for (const node of nodes) {
208    const label = `${node.__typename}:${labelOf(node)}`;
209    const held = byLabel.get(label);
210    if (held === undefined || (held.startedAt ?? "\uFFFF") <= (node.startedAt ?? "\uFFFF")) {
211      byLabel.set(label, node);
212    }
213  }
214  return [...byLabel.values()];
215}
216
217// `mergeable` and `mergeStateStatus` can lag each other, so either one decides.
218// GitHub reports BEHIND only where a ruleset requires an up-to-date branch.
219function blockOf(view: PrView): Block | undefined {
220  if (view.mergeable === "CONFLICTING" || view.mergeStateStatus === "DIRTY") return "conflict";
221  if (view.mergeStateStatus === "BEHIND") return "behind";
222  if (view.mergeable === "UNKNOWN" || view.mergeStateStatus === "UNKNOWN") return undefined;
223  return "none";
224}
225
226export function snapshotOf(view: PrView, local: Local): Snapshot {
227  const checks = latest(view.statusCheckRollup ?? []);
228  const failed: string[] = [];
229  let pending = 0;
230  for (const node of checks) {
231    const outcome = outcomeOf(node);
232    if (outcome === "failed") failed.push(labelOf(node));
233    else if (outcome === "pending") pending += 1;
234  }
235  failed.sort();
236  let phase: Phase = "passing";
237  if (checks.length === 0) phase = "none";
238  else if (failed.length > 0) phase = "failing";
239  else if (pending > 0) phase = "pending";
240  // A reply to a review thread is itself a review, so the session's own replies come back here.
241  const reviews = (view.reviews ?? [])
242    .map((r) => ({ id: r.id, author: r.author?.login ?? "someone", state: r.state }))
243    .filter((r) => r.author !== local.me);
244  const comments = (view.comments ?? [])
245    .filter((c) => !c.isMinimized && !c.viewerDidAuthor && c.author?.login !== local.me)
246    .map((c) => ({ id: c.id, author: c.author?.login ?? "someone" }));
247  return {
248    pr: view.number,
249    url: view.url,
250    state: view.state,
251    head: view.headRefOid,
252    isHeadKnown: local.isHeadKnown,
253    base: view.baseRefName ?? "",
254    block: blockOf(view),
255    phase,
256    total: checks.length,
257    pending,
258    failed,
259    reviewDecision: view.reviewDecision ?? "",
260    reviews,
261    comments,
262  };
263}
264
265const isBlocked = (block: Block | undefined): block is "conflict" | "behind" =>
266  block === "conflict" || block === "behind";
267
268/** What a PR first seen already blocked has to say. Nothing else counts at baseline. */
269export function baselineOf(snapshot: Snapshot): Promoted[] {
270  if (snapshot.state !== "OPEN" || !isBlocked(snapshot.block)) return [];
271  return [{ action: "promote", kind: snapshot.block }];
272}
273
274function feedbackOf(prev: Snapshot, next: Snapshot): Decision[] {
275  const seen = new Set([...prev.reviews.map((r) => r.id), ...prev.comments.map((c) => c.id)]);
276  const byAuthor = new Map<string, { states: string[]; comments: number }>();
277  const entry = (author: string) => {
278    const held = byAuthor.get(author) ?? { states: [], comments: 0 };
279    byAuthor.set(author, held);
280    return held;
281  };
282  for (const review of next.reviews) {
283    if (!seen.has(review.id)) entry(review.author).states.push(review.state);
284  }
285  for (const comment of next.comments) {
286    if (!seen.has(comment.id)) entry(comment.author).comments += 1;
287  }
288  return [...byAuthor].map(([author, { states, comments }]) => ({
289    action: "promote",
290    kind: "feedback",
291    author,
292    states,
293    comments,
294  }));
295}
296
297/**
298 * What changed between two polls of the same PR. The PR merging or closing, a
299 * new conflict or required update, a push from outside this checkout, a check
300 * that newly fails, and new reviews or comments from someone else are promoted.
301 * Every other change is dropped.
302 */
303export function decide(prev: Snapshot, next: Snapshot): Decision[] {
304  if (next.state !== "OPEN") {
305    if (prev.state !== "OPEN") return [];
306    return [{ action: "promote", kind: next.state === "MERGED" ? "pr.merged" : "pr.closed" }];
307  }
308  const decisions: Decision[] = [];
309  const isSameHead = prev.head === next.head;
310  if (!isSameHead) {
311    decisions.push(
312      next.isHeadKnown
313        ? { action: "drop", kind: "push", from: prev.head }
314        : { action: "promote", kind: "push.foreign", from: prev.head },
315    );
316  }
317
318  // A reopened PR starts clear, so a block it still carries is news again.
319  const before = prev.state === "OPEN" ? prev.block : "none";
320  if (isBlocked(next.block) && next.block !== before) {
321    decisions.push({ action: "promote", kind: next.block });
322  } else if (next.block === "none" && isBlocked(before)) {
323    decisions.push({ action: "drop", kind: "unblocked" });
324  }
325
326  const known = new Set(isSameHead ? prev.failed : []);
327  const failed = next.failed.filter((label) => !known.has(label));
328  if (failed.length > 0) decisions.push({ action: "promote", kind: "ci.failed", failed });
329  else if (next.phase !== prev.phase || !isSameHead) {
330    if (next.phase === "passing") decisions.push({ action: "drop", kind: "ci.passing" });
331    else if (next.phase === "pending") decisions.push({ action: "drop", kind: "ci.pending" });
332    else if (next.phase === "none") decisions.push({ action: "drop", kind: "ci.none" });
333  }
334
335  decisions.push(...feedbackOf(prev, next));
336  return decisions;
337}
338
339/**
340 * Folds a retried send into fresh decisions as one message: the latest block,
341 * the earliest foreign push, every failed check once, and one entry per author.
342 */
343export function combine(carried: Promoted[], fresh: Promoted[]): Promoted[] {
344  const all = [...carried, ...fresh];
345  const ended = all.findLast((d) => d.kind === "pr.merged" || d.kind === "pr.closed");
346  if (ended !== undefined) return [ended];
347  const out: Promoted[] = [];
348  const block = all.findLast((d) => d.kind === "conflict" || d.kind === "behind");
349  if (block !== undefined) out.push(block);
350  const push = all.find((d) => d.kind === "push.foreign");
351  if (push !== undefined) out.push(push);
352  const failed = all.flatMap((d) => (d.kind === "ci.failed" ? d.failed : []));
353  if (failed.length > 0) {
354    out.push({ action: "promote", kind: "ci.failed", failed: [...new Set(failed)].toSorted() });
355  }
356  const byAuthor = new Map<string, { states: string[]; comments: number }>();
357  for (const d of all) {
358    if (d.kind !== "feedback") continue;
359    const held = byAuthor.get(d.author) ?? { states: [], comments: 0 };
360    byAuthor.set(d.author, {
361      states: [...held.states, ...d.states],
362      comments: held.comments + d.comments,
363    });
364  }
365  for (const [author, { states, comments }] of byAuthor) {
366    out.push({ action: "promote", kind: "feedback", author, states, comments });
367  }
368  return out;
369}
370
371const short = (sha: string) => sha.slice(0, 7);
372
373function listed(labels: string[], max = 3): string {
374  const head = labels.slice(0, max).map(shown).join(", ");
375  return labels.length > max ? `${head} (+${labels.length - max})` : head;
376}
377
378function counted(states: string[]): string[] {
379  const counts = new Map<string, number>();
380  for (const state of states) counts.set(state, (counts.get(state) ?? 0) + 1);
381  return [...counts].map(([state, n]) => (n === 1 ? state : `${state} ×${n}`));
382}
383
384function feedbackLineOf(pr: string, decision: Extract<Promoted, { kind: "feedback" }>): string {
385  const { author, states, comments } = decision;
386  const details = counted(states);
387  if (comments > 0) details.push(comments === 1 ? "1 new comment" : `${comments} new comments`);
388  const verb = states.length > 0 ? "reviewed" : "commented on";
389  return `@${author} ${verb} ${pr} (${details.join(", ")})`;
390}
391
392function paragraphOf(
393  snapshot: Snapshot,
394  decision: Exclude<Promoted, { kind: "feedback" }>,
395): string {
396  const pr = `PR #${snapshot.pr}`;
397  const base = snapshot.base === "" ? "its base branch" : `\`${snapshot.base}\``;
398  if (decision.kind === "pr.merged") return `${pr} merged: ${snapshot.url}`;
399  if (decision.kind === "pr.closed") return `${pr} closed without merging: ${snapshot.url}`;
400  if (decision.kind === "conflict") {
401    return [
402      `${pr} has merge conflicts with ${base} at ${short(snapshot.head)}.`,
403      `Update the branch from ${base}, resolve the conflicts with the \`git:conflicts\` skill, and push.`,
404    ].join("\n");
405  }
406  if (decision.kind === "behind") {
407    return [
408      `${pr} is behind ${base} at ${short(snapshot.head)}, and merging requires an up-to-date branch.`,
409      `Update the branch from ${base}, resolve any conflicts with the \`git:conflicts\` skill, and push.`,
410    ].join("\n");
411  }
412  if (decision.kind === "push.foreign") {
413    return [
414      `${pr}'s branch moved from ${short(decision.from)} to ${short(snapshot.head)}, a commit this checkout does not have.`,
415      "Pull it before committing or pushing again.",
416    ].join("\n");
417  }
418  return [
419    `CI failed on ${pr} at ${short(snapshot.head)}: ${decision.failed.map(shown).join(", ")}.`,
420    `Read the failure with \`gh pr checks ${snapshot.pr}\` and \`gh run view <run> --log-failed\`.`,
421  ].join("\n");
422}
423
424export function messageOf(snapshot: Snapshot, promoted: Promoted[]): string {
425  const paragraphs: string[] = [];
426  const feedback: string[] = [];
427  for (const decision of promoted) {
428    if (decision.kind === "feedback") feedback.push(feedbackLineOf(`PR #${snapshot.pr}`, decision));
429    else paragraphs.push(paragraphOf(snapshot, decision));
430  }
431  if (feedback.length > 0) {
432    paragraphs.push(
433      [...feedback, snapshot.url, `Read it with \`gh pr view ${snapshot.pr} --comments\`.`].join(
434        "\n",
435      ),
436    );
437  }
438  if (snapshot.state === "OPEN") {
439    paragraphs.push(
440      "The github plugin watches this PR's checks, reviews, comments, and mergeability, so polling them is unnecessary.",
441    );
442  }
443  return paragraphs.join("\n\n");
444}
445
446// Nerd Font Octicons, the icons GitHub draws for each state, keyed by glyph
447// name: nf-oct-git_merge is gitMerge.
448const OCT = {
449  alert: "\u{f421}",
450  check: "\u{f42e}",
451  checkCircle: "\u{f49e}",
452  dotFill: "\u{f444}",
453  eye: "\u{f441}",
454  fileDiff: "\u{f4d2}",
455  gitCompare: "\u{f47f}",
456  gitMerge: "\u{f419}",
457  gitPullRequestClosed: "\u{f4dc}",
458  xCircle: "\u{f52f}",
459};
460
461export const STALE = `${OCT.alert} stale`;
462
463const BLOCKS: Record<Block, string | undefined> = {
464  conflict: `${OCT.gitCompare} conflicts`,
465  behind: `${OCT.gitCompare} behind`,
466  none: undefined,
467};
468
469const ENDED: Partial<Record<string, string>> = {
470  MERGED: `${OCT.gitMerge} merged`,
471  CLOSED: `${OCT.gitPullRequestClosed} closed`,
472};
473
474const CHECKS: Record<Phase, (snapshot: Snapshot) => string | undefined> = {
475  none: () => undefined,
476  pending: (s) => `${OCT.dotFill} CI ${s.total - s.pending}/${s.total}`,
477  passing: () => `${OCT.checkCircle} CI`,
478  failing: (s) => `${OCT.xCircle} ${listed(s.failed)}`,
479};
480
481const REVIEWS: Partial<Record<string, string>> = {
482  APPROVED: `${OCT.check} approved`,
483  CHANGES_REQUESTED: `${OCT.fileDiff} changes requested`,
484  REVIEW_REQUIRED: `${OCT.eye} review needed`,
485};
486
487// The footer already links the PR, so the state rides after it on that line.
488export function statusOf(snapshot: Snapshot): string {
489  const ended = ENDED[snapshot.state];
490  if (ended !== undefined) return ended;
491  return [
492    BLOCKS[snapshot.block ?? "none"],
493    CHECKS[snapshot.phase](snapshot),
494    REVIEWS[snapshot.reviewDecision],
495  ]
496    .filter((part) => part !== undefined)
497    .join(" · ");
498}
499