SLOPSHOPPER

promote-lights

Shows CI status lights above the prompt while a promote PR (base main) is open. One REST page per minute, PR-open only. Cancelled is not-pass.

bandcommandstatusprocesstimer
★ 298v0.0.15MITupdated 2026-10-23yonatangross/orchestkit/mods/promote-lights
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · promote-lights
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /lights ⎿ promote-lights: no promote PR open with head "dev" into "main" (set PROMOTE_HEAD or PROMOTE_BASE to look for another); try /li ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

promote-lights

Shows CI status lights above the prompt while a promote PR (base main, or PROMOTE_BASE) is open.

The command is /lights; /promote-lights runs the same thing. The promote PR search runs after the session has started, so GitHub never holds up a new session; the band appears once the search finds an open promote PR.

What it does

  • Displays a compact AbovePrompt band: one summary line (PR, head, merge state, green/yellow/red counts), then one line per required context that is not green, full name, red first, at most 5 such lines with a +N more line after them; when everything is green the band is the summary line alone:
  🚦 #4435  3afff24  BLOCKED   19 🟢  0 🟡  2 🔴
     🔴 PR Playground
     🔴 CI Summary
  • Pins a one-line status summary under the prompt
  • Polls one REST page per minute, only while the PR is open
  • Stops automatically when the PR merges, closes, or the head moves
  • Shows HOLD in red when the latest PR comment starts with HOLD*
  • The band is the only place the lights are drawn: each tick clears the plugin status line instead of repeating the band in it, and a degraded promote search shows as DEGRADED in the band. Claude Code gives a mod no signal when the band is collapsed (ctrl+x ctrl+a), so /lights answers the one-line status on demand
  • Draws a one-line dim lights: <reason> band when it cannot show lights (no required contexts, gh failed, head moved), so a failure is never a blank space
  • A seat that cannot write the mod store (a sandboxed session gets EPERM under ~/.claude) keeps working: the lights live in memory for that process, and the status line says lights: store unavailable once. Before 0.0.14 session.start threw there and no band ever drew
  • Demo mode: /lights watch owner/repo#N shows lights for any open PR in any repo, no promote PR needed

How the band is drawn

The band is built from the Box and Text elements that $.ui.resolve(e) hands the ui.render hook. On Claude Code 2.1.282 a plain { type: "Box" } object is not an element and never draws (measured 2026-09-25: the hook settles, nothing appears). The downstream tree from next(e) is an opaque engine node, so the band is placed above it in a column and never mutates it.

Watch mode (demo)

/lights watch owner/repo#123 (also owner/repo 123 or a PR URL) points the tick at any open PR:

  • every gh call targets the watched repo (-R owner/repo); the lights still show in this session's band
  • a watched repo that protects nothing falls back to every check run on the head, worst non-skipped run per name wins
  • a new push to a watched PR is followed, not stopped (a promote PR still stops on a moved head)
  • PROMOTE_HEAD=development PROMOTE_BASE=qa finds the promote PR in a dev, qa, main flow; the required checks are read from that base
  • PROMOTE_LIGHTS_WATCH=owner/repo#123 starts watching at session start with no typing, for recorded demos

A real promote PR keeps its stricter rule: an empty required-context union refuses green instead of falling back.

Only this session's lights

Lights are kept in $.store, which outlives a Claude Code session and is shared by every session on the machine, and the band can be drawn before session.start runs. Each session therefore stores its lights under its own key (the repo plus a session token), stamps the entry with that token, and draws only its own entry. Two live sessions on the same repo keep separate bands, and a new session (including a /clear, which rotates the token and removes the previous entry) never shows older lights, even for a moment.

Light colors

StatusColor
successgreen circle
queued / in_progress / nullyellow circle
failure / timed_out / action_requiredred circle
cancelledwarning sign (its own bucket, never pass)
skippeddropped when the name has a real verdict; a skipped-only name stays yellow (never ran, never pass)
missing (no run found)red circle

Cancelled runs get their own bucket because a superseded attempt leaves tiers CANCELLED, and the aggregate must read failure even though zero tests failed.

Requirements

  • Claude Code 2.1.266 minimum (first measured classic.* binary)
  • On 2.1.266 through 2.1.286 the module system sits behind CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1; set it in your shell profile or personal settings. On 2.1.287+ Mods are public and the flag is no longer needed.

Public Mods status (CC 2.1.287+)

CC 2.1.287 announces Claude Mods as public, so plugins may now modify deeper behaviour than hooks. Measured on CC 2.1.288 (2026-10-03, headless -p --plugin-dir per mod, flag unset then set to 1): all four ork mods load and fire with the flag unset. secrets-veil masked a secret in a Bash tool result, lesson-cards denied gh pr checks via lesson cancelled-check-is-not-pass, memory-lens indexed 384 memories at session start, and promote-lights ran gh through $.process.run. The flag only gates 2.1.266 to 2.1.286. The built-in "You should know" mod (/plugin enable cc-plugin-you-should-know@builtin) ships in the same release; coexistence is unverified and ork does not enable it. Migration questions stay open in GH-3917; the command hook fleet is not part of this check.

Footprint

Hooks:

  • session.start{}
  • turn.complete{}
  • command.register{}
  • ui.render{component=AbovePrompt}

Calls:

  • $.process.run (gh CLI, read-only)
  • $.fs.read (.github/branch-protection.json)
  • $.session.repo
  • $.clock.every
  • $.store.get, $.store.set
  • $.ui.status, $.ui.invalidate, $.ui.resolve
  • $.env.get (PROMOTE_HEAD, PROMOTE_BASE, PROMOTE_LIGHTS_WATCH)

Declared capability: process.run (can run host processes; gh carries your auth, read-only calls only).

Negative: no $.secrets.*, no $.http.fetch, no $.model.*.

Rollback

  1. /lights off or disable the plugin
  2. On 2.1.266 to 2.1.286 also unset CLAUDE_CODE_ENABLE_FUNCTION_HOOKS (inert on 2.1.287+)
  3. $.store keys lights:* are the only residue and are safe to drop

Budget guard

One REST call group per minute. Measured over 10 minutes with a real PR: at most 40 calls (gh API count), staying under the 5000/h budget shared across seats.

Commands

  • /lights - show current status
  • /lights off - stop tracking and clear the band
  • /lights refresh - force immediate refresh
  • /lights watch owner/repo#N - show lights for any open PR (demo mode)
  • /lights owner/repo#N - the same, without the watch word (also owner/repo N and PR URLs)

Acceptance checklist

  • ☐ With a real platform promote PR open, the band shows the summary for its 11 required contexts for main above the prompt within one tick, plus one line per context that is not green
  • ☐ A tier that CI cancelled shows warning sign and the pinned line says so
  • ☐ When the head moves the band says "head moved, stopped" and the tick stops
  • ☐ When the PR merges the band clears itself
  • ☐ One REST call group per minute measured in the gh audit log (<= 40 calls over 10 minutes)
  • ☐ The band survives a hot reload because it re-reads $.store on the next ui.render
  • ☐ The classic merge-on-required.sh is untouched and still the thing that merges
Source 6 files
hooks/register.ts 657 lines
1/**
2 * Promote Lights - Function Hooks registration.
3 *
4 * Hooks registered:
5 * - session.start
6 * - turn.complete
7 * - command.run{command=lights} (declared with $.command.register at session start)
8 * - ui.render { component: 'AbovePrompt' }
9 *
10 * Calls:
11 * - $.process.run (gh commands)
12 * - $.session.repo
13 * - $.clock.every (60s tick)
14 * - $.store.get/set
15 * - $.ui.status (startup warnings; cleared once the band draws)
16 * - $.ui.invalidate
17 * - $.ui.resolve (the band's Box and Text elements)
18 * - $.env.get (PROMOTE_HEAD and PROMOTE_BASE overrides, PROMOTE_LIGHTS_WATCH demo target)
19 *
20 * Two tracking modes share one tick:
21 * - promote: the open promote PR (base main, dev head or promote label) in
22 *   the session repo. An empty required-context union refuses green.
23 * - watch: any open PR in any repo, named with `/lights watch owner/repo#N`
24 *   or PROMOTE_LIGHTS_WATCH. An unprotected repo falls back to every check
25 *   run on the head, so the lights can be shown without a live promote PR.
26 */
27
28import { matchAndClassify, isPassing, type ClassifiedLight } from "../src/classify.js";
29import { computeRequiredUnion } from "../src/required.js";
30import { parsePRList, parsePRView, parseCheckRuns, isPromotePR, DEFAULT_PROMOTE_HEAD, DEFAULT_PROMOTE_BASE, buildHeadQueryArgs, buildLabelQueryArgs, mergePRLists } from "../src/gh.js";
31import { buildStatusLine, buildBand, buildErrorBand, type Elements } from "../src/pane.js";
32import {
33  parseWatchTarget,
34  formatWatchTarget,
35  allCheckNames,
36  WATCH_USAGE,
37  noPrHint,
38  unknownArgHint,
39  type WatchTarget,
40} from "../src/watch.js";
41
42/**
43 * Minimal $ facade for the calls this module uses, mirroring the
44 * lesson-cards mod: hooks are typed locally so the mod typechecks with
45 * only its own devDependencies installed.
46 */
47type Hook$ = {
48  session: {
49    repo: () => Promise<{ owner: string; name: string } | null>;
50  };
51  process: {
52    run: (
53      argv: readonly string[],
54      init?: { timeoutMs?: number }
55    ) => Promise<{ exitCode: number; stdout: string; stderr: string }>;
56  };
57  clock: {
58    // CC 2.1.282 hands back { cancel } only; there is no dispose.
59    every: (ms: number, fn: () => void) => { cancel: () => void };
60  };
61  store: {
62    get: (key: string) => Promise<StoredLights | null>;
63    set: (key: string, value: unknown) => Promise<void>;
64    delete: (key: string) => Promise<void>;
65  };
66  env: {
67    get: (key: string) => Promise<string | undefined>;
68  };
69  ui: {
70    /** undefined clears the line. */
71    status: (line: string | undefined) => Promise<void>;
72    invalidate: (component: string) => void;
73    resolve: (e: HookEvent) => Promise<Elements>;
74  };
75  command: {
76    register: (spec: { name: string; description: string; argumentHint?: string }) => Promise<unknown>;
77  };
78};
79
80/**
81 * $.store, but never fatal. A sandboxed seat cannot write the mod store under
82 * ~/.claude: measured 2026-10-20, "$.store.delete failed: EPERM: operation not
83 * permitted, mkdir", and session.start threw, so no band and no tick. On the
84 * first store failure this process keeps its lights in memory for the rest of
85 * its life and says "lights: store unavailable" once. The memory copy is
86 * per process, so the per-session key rules below still hold.
87 */
88const memoryStore = new Map<string, StoredLights>();
89let storeDown = false;
90let storeWarned = false;
91
92async function storeFailed($: Hook$): Promise<void> {
93  storeDown = true;
94  if (storeWarned) return;
95  storeWarned = true;
96  try {
97    await $.ui.status("lights: store unavailable");
98  } catch {
99    // The warning is best effort; the lights keep working from memory either way.
100  }
101}
102
103async function storeGet($: Hook$, key: string): Promise<StoredLights | null> {
104  if (!storeDown) {
105    try {
106      return await $.store.get(key);
107    } catch {
108      await storeFailed($);
109    }
110  }
111  return memoryStore.get(key) ?? null;
112}
113
114async function storeSet($: Hook$, key: string, value: StoredLights): Promise<void> {
115  memoryStore.set(key, value);
116  if (storeDown) return;
117  try {
118    await $.store.set(key, value);
119  } catch {
120    await storeFailed($);
121  }
122}
123
124async function storeDelete($: Hook$, key: string): Promise<void> {
125  memoryStore.delete(key);
126  if (storeDown) return;
127  try {
128    await $.store.delete(key);
129  } catch {
130    await storeFailed($);
131  }
132}
133
134
135type Matcher = Record<string, unknown>;
136
137type HookEvent = {
138  name?: string;
139  args?: string;
140  component?: string;
141  [key: string]: unknown;
142};
143
144type NextFn = (ev?: HookEvent) => Promise<Record<string, unknown> | undefined>;
145
146type On = (
147  event: string,
148  matcher: Matcher,
149  handler: ($: Hook$, e: HookEvent, next: NextFn) => unknown
150) => void;
151
152export type Register = (on: On) => void;
153
154/** Shape stored under lights:<owner>/<repo> (the SESSION repo, in both modes). */
155type StoredLights = {
156  prNumber?: number;
157  head?: string;
158  label?: string;
159  mode?: "promote" | "watch";
160  lights?: ClassifiedLight[];
161  mergeStateStatus?: string;
162  hold?: boolean;
163  /** True when the promote search ran on one query instead of two. */
164  degraded?: boolean;
165  passing?: boolean;
166  error?: string;
167  /** The token of the session that wrote this entry (see sessionToken). */
168  session?: string;
169  [key: string]: unknown;
170};
171
172/** The PR the tick follows: which repo to ask gh about, and which head. */
173type Tracked = {
174  owner: string;
175  repo: string;
176  number: number;
177  head: string;
178  mode: "promote" | "watch";
179  /** Branch whose protection names the required checks: main for a promote, the PR's own base for a watch. */
180  base: string;
181  /** True when the promote search ran on one query instead of two. */
182  degraded: boolean;
183};
184
185// Module state
186let ticking = false;
187let tickInterval: { cancel: () => void } | null = null;
188let tracked: Tracked | null = null;
189
190const TICK_MS = 60000;
191
192/**
193 * One token per loaded module, so per Claude Code process. $.store outlives
194 * the process, and ui.render can run BEFORE session.start clears the key
195 * (measured on 2.1.283: a new session drew the previous session's lights
196 * for about 3 s). Every write carries this token and every read ignores an
197 * entry with any other token, so a stale entry is never drawn.
198 */
199function newToken(): string {
200  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
201}
202
203/** Rotated at every session.start, so a /clear inside one process starts clean too. */
204let sessionToken = newToken();
205
206/** The current token (tests seed entries with it). */
207export function currentSessionToken(): string {
208  return sessionToken;
209}
210
211/** Tag an entry as written by this process. */
212function stamp<T extends object>(value: T): T & { session: string } {
213  return { ...value, session: sessionToken };
214}
215
216/** The stored entry only when this process wrote it; anything else reads as nothing. */
217function own(stored: StoredLights | null): StoredLights | null {
218  return stored && stored.session === sessionToken ? stored : null;
219}
220
221/**
222 * Store key: the session repo plus this session's token. Per repo alone, two
223 * live sessions on the same repo shared one key, and each write blanked the
224 * other session's band until its next tick.
225 */
226function keyFor(repo: { owner: string; name: string } | null, token: string = sessionToken): string {
227  const base = repo ? `lights:${repo.owner}/${repo.name}` : "lights:_session";
228  return `${base}:${token}`;
229}
230
231function labelFor(t: Tracked): string {
232  return t.mode === "watch"
233    ? `watch ${formatWatchTarget({ owner: t.owner, repo: t.repo, number: t.number })}`
234    : `promote #${t.number}`;
235}
236
237function prViewArgv(t: { owner: string; repo: string; number: number }): string[] {
238  return [
239    "gh",
240    "pr",
241    "view",
242    String(t.number),
243    "--json",
244    "headRefOid,state,mergeStateStatus,baseRefName",
245    "-R",
246    `${t.owner}/${t.repo}`,
247  ];
248}
249
250/**
251 * The promote PR search started by the latest session.start. It runs after
252 * the hook has answered, so two gh queries (15 s timeout each) never hold the
253 * session's start; the band draws once the search stores a snapshot.
254 */
255let discovery: Promise<void> | null = null;
256
257/** Resolves when the latest session.start search has finished (tests await it). */
258export function discoveryDone(): Promise<void> {
259  return discovery ?? Promise.resolve();
260}
261
262/** The promote PR search session.start starts and does not wait for. */
263async function discover($: Hook$, key: string, repo: Awaited<ReturnType<Hook$["session"]["repo"]>>): Promise<void> {
264  // Demo mode first: a configured watch target needs no promote PR and no
265  // session repo.
266  const watchEnv = await $.env.get("PROMOTE_LIGHTS_WATCH").catch(() => undefined);
267  const watchTarget = parseWatchTarget(watchEnv);
268  if (watchTarget) {
269    await startWatch($, key, watchTarget);
270    return;
271  }
272
273  if (!repo) return;
274
275  const { owner, name } = repo;
276
277  // Only a real promote PR matches: dev head (or the configured
278  // promote head) with base main, or the promote label. An ordinary
279  // PR with base main must never match.
280  let promoteHead = DEFAULT_PROMOTE_HEAD;
281  const configured = await $.env.get("PROMOTE_HEAD").catch(() => undefined);
282  if (configured) promoteHead = configured;
283  // A dev, qa, main flow promotes into qa, so the base is configurable too
284  // (orchestkit#4623). The required checks below read this same base.
285  const promoteBase = (await $.env.get("PROMOTE_BASE").catch(() => undefined)) || DEFAULT_PROMOTE_BASE;
286
287  // Both queries are filtered server side so the result is complete
288  // no matter how many ordinary open PRs the repo has. A single
289  // unfiltered list returns at most 30 PRs by default, which misses
290  // a promote PR sitting past position 30. Settled, never all: one
291  // rejected query degrades the search instead of aborting the start.
292  const [headSettled, labelSettled] = await Promise.allSettled([
293    $.process.run(buildHeadQueryArgs(promoteHead, promoteBase), { timeoutMs: 15000 }),
294    $.process.run(buildLabelQueryArgs(promoteBase), { timeoutMs: 15000 }),
295  ]);
296  const byHead = headSettled.status === "fulfilled"
297    ? headSettled.value
298    : { exitCode: 1, stdout: "", stderr: String(headSettled.reason) };
299  const byLabel = labelSettled.status === "fulfilled"
300    ? labelSettled.value
301    : { exitCode: 1, stdout: "", stderr: String(labelSettled.reason) };
302
303  if (byHead.exitCode !== 0 && byLabel.exitCode !== 0) {
304    await storeSet($, key, stamp({ error: "gh: not found" }));
305    return;
306  }
307
308  // One failed query must never pass silently: the search is degraded,
309  // the snapshot records it, and the band keeps saying DEGRADED.
310  const degraded = byHead.exitCode !== 0 || byLabel.exitCode !== 0;
311  if (degraded) {
312    const failed = byHead.exitCode !== 0 ? "head" : "label";
313    await warnStatus($, `lights: promote ${failed} query failed, continuing with the other`);
314  }
315
316  const prs = mergePRLists(
317    byHead.exitCode === 0 ? parsePRList(byHead.stdout) : [],
318    byLabel.exitCode === 0 ? parsePRList(byLabel.stdout) : []
319  );
320  const promotePR = prs.find((pr) => isPromotePR(pr, promoteHead));
321
322  if (!promotePR) {
323    await storeDelete($, key);
324    return;
325  }
326
327  tracked = { owner, repo: name, number: promotePR.number, head: promotePR.headRefOid, mode: "promote", base: promoteBase, degraded };
328
329  if (!ticking) {
330    startTick($, key);
331    await doTick($, key);
332  }
333
334  return;
335}
336
337export const register: Register = (on) => {
338  on("session.start", {}, async ($, e, next) => {
339    // Rotate first, before any await: from here on nothing this process
340    // stored for the previous session (a /clear) can be read or drawn.
341    const previousToken = sessionToken;
342    sessionToken = newToken();
343    // A refused registration must not skip the rest of the hook.
344    await $.command.register({
345      name: "lights",
346      description: "CI lights for the open promote PR, or any PR with /lights watch",
347      argumentHint: "[off|refresh|watch] [owner/repo#N]",
348    }).catch(() => undefined);
349    // The name people guess first: the plugin's own name runs the same command.
350    await $.command.register({
351      name: "promote-lights",
352      description: "Same as /lights",
353      argumentHint: "[off|refresh|watch] [owner/repo#N]",
354    }).catch(() => undefined);
355    const repo = await $.session.repo();
356    const key = keyFor(repo);
357
358    // $.store outlives the session: drop what this process stored under its
359    // previous token (a /clear), so no orphan is left behind. Entries of
360    // other processes live under their own keys and are never touched.
361    await storeDelete($, keyFor(repo, previousToken));
362    // A tick or a tracked PR from before /clear must not outlive it either.
363    stopTick();
364    tracked = null;
365
366    discovery = discover($, key, repo).catch(() => undefined);
367    return next(e);
368  });
369
370  // Re-check on turn complete in case PR changed
371  on("turn.complete", {}, async ($, e, next) => {
372    const repo = await $.session.repo();
373    if (!tracked) return next(e);
374    const key = keyFor(repo);
375    if (!repo && tracked.mode === "promote") return next(e);
376
377    const result = await $.process.run(prViewArgv(tracked), { timeoutMs: 10000 });
378
379    if (result.exitCode !== 0) return next(e);
380
381    const details = parsePRView(result.stdout);
382    if (!details || details.state !== "OPEN") {
383      stopTick();
384      await storeDelete($, key);
385      tracked = null;
386      $.ui.invalidate("ui.render");
387      return next(e);
388    }
389
390    if (details.headRefOid !== tracked.head) {
391      if (tracked.mode === "watch") {
392        // A watched PR is a demo of any PR: follow the new head.
393        tracked = { ...tracked, head: details.headRefOid };
394        await doTick($, key);
395        return next(e);
396      }
397      stopTick();
398      await storeSet($, key, stamp({
399        error: "head moved, stopped",
400      }));
401      tracked = null;
402      $.ui.invalidate("ui.render");
403      return next(e);
404    }
405
406    return next(e);
407  });
408
409  // Render the AbovePrompt band. Compose, never replace: next(e) always runs so
410  // Claude Code's own band and every other plugin's AbovePrompt drawing survive,
411  // and the lights sit above that tree in one column. The downstream tree is an
412  // opaque engine node: it is placed, never mutated. Every node drawn here comes
413  // from $.ui.resolve(e); a plain { type: "Box" } object never draws.
414  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
415    const downstream = await next(e);
416    const repo = await $.session.repo();
417    const stored = own(await storeGet($, keyFor(repo)));
418
419    if (!stored) return downstream;
420
421    let band: unknown = null;
422    if (stored.lights && stored.prNumber) {
423      const els = await $.ui.resolve(e);
424      band = buildBand(
425        els,
426        stored.label ?? `promote #${stored.prNumber}`,
427        stored.lights,
428        stored.head ?? "",
429        stored.mergeStateStatus ?? "",
430        stored.hold ?? false,
431        stored.degraded ?? false
432      );
433    } else if (stored.error) {
434      const els = await $.ui.resolve(e);
435      band = buildErrorBand(els, stored.error);
436    }
437
438    if (band === null) return downstream;
439    const { Box } = await $.ui.resolve(e);
440    return Box({
441      flexDirection: "column",
442      children: downstream ? [band, downstream] : [band],
443    });
444  });
445
446  // Manual control command, under both names
447  for (const command of ["lights", "promote-lights"]) on("command.run", { command }, async ($, e) => {
448    const trimmed = (e.args ?? "").trim();
449    const [arg] = trimmed.split(/\s+/);
450    const repo = await $.session.repo();
451    const key = keyFor(repo);
452
453    if (arg === "off") {
454      stopTick();
455      tracked = null;
456      await storeDelete($, key);
457      $.ui.invalidate("ui.render");
458      return { text: "lights: stopped" };
459    }
460
461    if (arg === "refresh") {
462      if (tracked) await doTick($, key);
463      return { text: "lights: refreshed" };
464    }
465
466    if (arg === "watch") {
467      const target = parseWatchTarget(trimmed.slice("watch".length));
468      if (!target) return { text: WATCH_USAGE };
469      const outcome = await startWatch($, key, target);
470      return { text: outcome };
471    }
472
473    // Any other non-empty argument is a target guess: a bare owner/repo#N,
474    // owner/repo N, or a PR URL starts the same watch as /lights watch.
475    // What does not parse gets its own line naming the word, never the
476    // no-PR hint (which says nothing about an argument it did not read).
477    if (trimmed) {
478      const target = parseWatchTarget(trimmed);
479      if (!target) return { text: unknownArgHint(arg) };
480      const outcome = await startWatch($, key, target);
481      return { text: outcome };
482    }
483
484    const stored = own(await storeGet($, key));
485
486    if (stored && stored.lights) {
487      return {
488        text: buildStatusLine(
489          stored.prNumber ?? 0,
490          stored.lights,
491          stored.mergeStateStatus ?? "",
492          stored.hold ?? false,
493          stored.label,
494          stored.degraded ?? false
495        ),
496      };
497    }
498    if (stored && stored.error) return { text: `lights: ${stored.error}` };
499    const promoteHead = (await $.env.get("PROMOTE_HEAD").catch(() => undefined)) || DEFAULT_PROMOTE_HEAD;
500    const promoteBase = (await $.env.get("PROMOTE_BASE").catch(() => undefined)) || DEFAULT_PROMOTE_BASE;
501    return { text: noPrHint(promoteHead, promoteBase) };
502  });
503};
504
505/**
506 * Point the tick at any open PR. Returns the text /lights watch answers with.
507 */
508async function startWatch($: Hook$, key: string, target: WatchTarget): Promise<string> {
509  const view = await $.process.run(prViewArgv(target), { timeoutMs: 10000 });
510  const details = view.exitCode === 0 ? parsePRView(view.stdout) : null;
511  const name = formatWatchTarget(target);
512  if (!details) {
513    await storeSet($, key, stamp({ error: `watch ${name}: gh pr view failed` }));
514    $.ui.invalidate("ui.render");
515    return `lights: could not read ${name} (gh pr view exit ${view.exitCode})`;
516  }
517  if (details.state !== "OPEN") {
518    return `lights: ${name} is ${details.state}, not open`;
519  }
520
521  stopTick();
522  tracked = {
523    owner: target.owner,
524    repo: target.repo,
525    number: target.number,
526    head: details.headRefOid,
527    mode: "watch",
528    // The watched PR's own base; main only when gh did not report one.
529    base: details.baseRefName || "main",
530    degraded: false,
531  };
532  startTick($, key);
533  const snapshot = await doTick($, key);
534  if (snapshot?.lights) {
535    return buildStatusLine(target.number, snapshot.lights, snapshot.mergeStateStatus ?? "", false, labelFor(tracked), tracked.degraded);
536  }
537  if (snapshot?.error) return `lights: ${snapshot.error}`;
538  return `lights: watching ${name}`;
539}
540
541function startTick($: Hook$, key: string): void {
542  ticking = true;
543  tickInterval = $.clock.every(TICK_MS, () => doTick($, key));
544}
545
546/** One tick: fetch, classify, store, draw. Returns what it stored. */
547async function doTick($: Hook$, key: string): Promise<StoredLights | null> {
548  if (!tracked) return null;
549
550  const t = tracked;
551  const { owner, repo, number: prNumber, head } = t;
552  const base = encodeURIComponent(t.base);
553
554  try {
555    const [protection, rulesets] = await Promise.all([
556      $.process.run(["gh", "api", `repos/${owner}/${repo}/branches/${base}/protection`], { timeoutMs: 10000 }),
557      $.process.run(["gh", "api", `repos/${owner}/${repo}/rules/branches/${base}`], { timeoutMs: 10000 }),
558    ]);
559
560    let requiredContexts = computeRequiredUnion(
561      protection.stdout ?? "",
562      rulesets.stdout ?? ""
563    );
564
565    if (requiredContexts.length === 0 && t.mode === "promote") {
566      // A promote verdict with nothing required would be a green lie.
567      const refused: StoredLights = { error: "empty required contexts", prNumber };
568      await storeSet($, key, stamp(refused));
569      $.ui.invalidate("ui.render");
570      return refused;
571    }
572
573    const checkRunsResult = await $.process.run([
574        "gh",
575        "api",
576        `repos/${owner}/${repo}/commits/${head}/check-runs?per_page=100`,
577      ], { timeoutMs: 10000 });
578    const checkRuns = parseCheckRuns(checkRunsResult.stdout ?? "");
579
580    if (requiredContexts.length === 0) {
581      // Watch mode on an unprotected repo: show every check that ran.
582      requiredContexts = allCheckNames(checkRuns.check_runs ?? []);
583      if (requiredContexts.length === 0) {
584        const empty: StoredLights = {
585          error: `watch ${formatWatchTarget({ owner, repo, number: prNumber })}: no check runs on ${head.slice(0, 7)}`,
586          prNumber,
587        };
588        await storeSet($, key, stamp(empty));
589        $.ui.invalidate("ui.render");
590        return empty;
591      }
592    }
593
594    const lights = matchAndClassify(requiredContexts, checkRuns.check_runs ?? []);
595
596    const prViewResult = await $.process.run(prViewArgv(t), { timeoutMs: 10000 });
597
598    const prDetails = parsePRView(prViewResult.stdout ?? "");
599    const mergeStateStatus = prDetails?.mergeStateStatus ?? "";
600    const passing = isPassing(lights);
601    const label = labelFor(t);
602
603    const snapshot: StoredLights = {
604      prNumber,
605      head,
606      label,
607      mode: t.mode,
608      lights,
609      mergeStateStatus,
610      hold: false,
611      degraded: t.degraded,
612      passing,
613      ts: Date.now(),
614    };
615    await storeSet($, key, stamp(snapshot));
616
617    // The band draws this state; a status line too showed it twice. Clear
618    // it (also drops a startup warning, which the band's DEGRADED now keeps).
619    // A collapsed band is not visible to a mod, so /lights answers the line.
620    await clearStatus($);
621    $.ui.invalidate("ui.render");
622    return snapshot;
623  } catch (err) {
624    const failed: StoredLights = { error: String(err), prNumber };
625    await storeSet($, key, stamp(failed));
626    $.ui.invalidate("ui.render");
627    return failed;
628  }
629}
630
631function stopTick(): void {
632  tickInterval?.cancel();
633  ticking = false;
634  tickInterval = null;
635}
636
637/**
638 * Best effort status sink for warnings: a rejection here must never
639 * abort the tracking that is already set up.
640 */
641async function warnStatus($: Hook$, message: string): Promise<void> {
642  try {
643    await $.ui.status(message);
644  } catch {
645    // Surfacing is best effort; tracking continues without it.
646  }
647}
648
649/** Best effort too: a rejected clear must never replace the stored lights with an error. */
650async function clearStatus($: Hook$): Promise<void> {
651  try {
652    await $.ui.status(undefined);
653  } catch {
654    // The band already carries the state; a stale line is cosmetic.
655  }
656}
657
src/classify.ts 169 lines
1/**
2 * Pure classifier for CI check status.
3 * Maps check-run conclusions to light colors.
4 * Cancelled gets its own bucket and is never pass.
5 * Missing is red (not run).
6 */
7
8export type LightColor = "green" | "yellow" | "red" | "cancelled";
9
10export interface CheckRun {
11  name: string;
12  status: string; // queued, in_progress, completed
13  conclusion: string | null; // success, failure, cancelled, timed_out, action_required, skipped
14}
15
16export interface ClassifiedLight {
17  name: string;
18  color: LightColor;
19  conclusion: string | null;
20}
21
22/**
23 * Classify a single check run into a light color.
24 * Rules from the brief:
25 * - success -> green
26 * - queued, in_progress, conclusion null -> yellow
27 * - cancelled -> cancelled (its own bucket, never pass)
28 * - failure, timed_out, action_required -> red
29 * - missing (no run found) -> red (not run)
30 */
31export function classifyCheckRun(run: CheckRun): ClassifiedLight {
32  const { conclusion, status } = run;
33
34  // Cancelled gets its own bucket
35  if (conclusion === "cancelled") {
36    return { name: run.name, color: "cancelled", conclusion };
37  }
38
39  // Success is green
40  if (conclusion === "success") {
41    return { name: run.name, color: "green", conclusion };
42  }
43
44  // Failure states are red
45  if (
46    conclusion === "failure" ||
47    conclusion === "timed_out" ||
48    conclusion === "action_required"
49  ) {
50    return { name: run.name, color: "red", conclusion };
51  }
52
53  // In-progress states are yellow
54  if (
55    status === "queued" ||
56    status === "in_progress" ||
57    conclusion === null
58  ) {
59    return { name: run.name, color: "yellow", conclusion };
60  }
61
62  // Skipped - we still classify but it depends on context
63  // In the brief, skipped runs don't count for the aggregate if there's a non-skipped run
64  // For classification purposes, we mark skipped as yellow (waiting)
65  if (conclusion === "skipped") {
66    return { name: run.name, color: "yellow", conclusion };
67  }
68
69  // Unknown - treat as red (not run)
70  return { name: run.name, color: "red", conclusion };
71}
72
73/**
74 * Aggregate light colors for the status line.
75 * Returns counts by color.
76 */
77export function aggregateLights(
78  lights: readonly ClassifiedLight[]
79): { green: number; yellow: number; red: number; cancelled: number } {
80  return {
81    green: lights.filter((l) => l.color === "green").length,
82    yellow: lights.filter((l) => l.color === "yellow").length,
83    red: lights.filter((l) => l.color === "red").length,
84    cancelled: lights.filter((l) => l.color === "cancelled").length,
85  };
86}
87
88/**
89 * Determine if the aggregate status is passing.
90 * Only an all-green set passes. Missing (red), pending or in progress
91 * (yellow), skipped (yellow with a skipped conclusion), cancelled, and any
92 * failing run all block the pass. A CI monitor that reports green when it
93 * cannot see is worse than no monitor (GH-4177 class of bug).
94 */
95export function isPassing(lights: readonly ClassifiedLight[]): boolean {
96  if (lights.length === 0) return false; // total_count: 0 is not-pass
97  return lights.every((l) => l.color === "green");
98}
99
100/**
101 * Given required contexts and check runs, match and classify.
102 *
103 * Order-independent worst case wins per context (GH-4177): reruns can put
104 * several runs under one name at the same sha and the API order is not a
105 * contract, so the verdict for a name is computed from the SET of its runs,
106 * never from which run arrived first or last. ANY non-skipped run under a
107 * name that is not success means that name is NOT passing: a pending,
108 * cancelled, failed, or unknown run each blocks the pass even when a green
109 * rerun sits next to it. The representative color shown is the worst color
110 * present: red beats cancelled beats yellow beats green. A name with no
111 * runs is red (not run).
112 *
113 * Skipped runs are the one exception (acct-nir-request-4, measured on Nir's
114 * Windows setup 2026-10-05): a rerun or a conditional leg leaves a skipped
115 * sibling under the same name, and worst-wins read [skipped, success] as
116 * yellow forever, so a green bundle printed "3 yellow". GitHub itself treats
117 * a skipped required check as satisfied, so skipped runs are dropped from
118 * the verdict pool when the name has any real verdict. A name whose runs
119 * are ALL skipped keeps its present colour: yellow (the check never ran,
120 * so it is not pass).
121 */
122export function matchAndClassify(
123  requiredContexts: string[],
124  checkRuns: CheckRun[]
125): ClassifiedLight[] {
126  const result: ClassifiedLight[] = [];
127
128  // Severity ranking for the representative color. Higher wins. green is
129  // only shown when every run under the name classified green.
130  const SEVERITY: Record<string, number> = {
131    green: 0,
132    yellow: 1,
133    cancelled: 2,
134    red: 3,
135  };
136
137  for (const ctx of requiredContexts) {
138    // Find all runs matching this context name
139    const matching = checkRuns.filter((r) => r.name === ctx);
140
141    if (matching.length === 0) {
142      // Missing - red (not run)
143      result.push({ name: ctx, color: "red", conclusion: null });
144      continue;
145    }
146
147    // Skipped runs carry no verdict: drop them when the name has any
148    // non-skipped run, so a skipped sibling cannot drag a success yellow.
149    // When every run under the name is skipped the pool stays the skipped
150    // set and the name keeps its present colour, yellow.
151    const verdicts = matching.filter((r) => r.conclusion !== "skipped");
152    const pool = verdicts.length > 0 ? verdicts : matching;
153
154    // Classify EVERY run in the pool and take the worst color. This is
155    // the order-independent core: sorting the same runs into any order
156    // yields the same worst color, so [success, in_progress] and
157    // [in_progress, success] both read pending, and a green rerun next to
158    // a failure never resuscitates the name.
159    const classified = pool.map((r) => classifyCheckRun(r));
160    const worst = classified.reduce((a, b) =>
161      SEVERITY[b.color] > SEVERITY[a.color] ? b : a
162    );
163
164    result.push(worst);
165  }
166
167  return result;
168}
169
src/required.ts 96 lines
1/**
2 * Compute the live union of required contexts from:
3 * 1. Branch protection (/branches/main/protection)
4 * 2. Rulesets (/rules/branches/main)
5 *
6 * Drops 404 bodies (lines that start with {).
7 * Refuses to return green when the union is empty.
8 */
9
10export interface ProtectionResponse {
11  required_status_checks?: {
12    contexts: string[];
13  };
14}
15
16export interface RulesetResponse {
17  rules?: Array<{
18    type: string;
19    parameters?: {
20      required_status_checks?: Array<{ context: string }>;
21    };
22  }>;
23}
24
25/**
26 * Parse protection response, extracting contexts.
27 */
28export function parseProtection(body: string): string[] {
29  // 404 body starts with { per brief - drop it
30  if (body.startsWith("{") && !body.includes("required_status_checks")) {
31    return [];
32  }
33
34  try {
35    const parsed: ProtectionResponse = JSON.parse(body);
36    return parsed.required_status_checks?.contexts ?? [];
37  } catch {
38    return [];
39  }
40}
41
42/**
43 * Parse rulesets response, extracting contexts from each rule.
44 *
45 * The GitHub rulesets API (GET /repos/{owner}/{repo}/rules/branches/{branch})
46 * returns a TOP-LEVEL ARRAY of rule objects, not an object with a rules key
47 * (GH-4165 review: the old parser expected {rules: []}, matched nothing, and
48 * silently dropped every ruleset-required context, fail-open). Parse the
49 * array; an object with a rules key is still tolerated for robustness.
50 */
51export function parseRulesets(body: string): string[] {
52  const trimmed = body.trim();
53  // 404 body starts with { per brief - drop it
54  if (trimmed.startsWith("{") && !trimmed.includes("rules")) {
55    return [];
56  }
57
58  try {
59    const parsed: unknown = JSON.parse(body);
60    // Real API shape: a top-level array of rules.
61    const rules: RulesetResponse["rules"] = Array.isArray(parsed)
62      ? (parsed as RulesetResponse["rules"])
63      : (parsed as RulesetResponse).rules ?? [];
64    const contexts: string[] = [];
65
66    for (const rule of rules ?? []) {
67      if (rule.parameters?.required_status_checks) {
68        for (const check of rule.parameters.required_status_checks) {
69          if (check.context) {
70            contexts.push(check.context);
71          }
72        }
73      }
74    }
75
76    return contexts;
77  } catch {
78    return [];
79  }
80}
81
82/**
83 * Compute the live union of required contexts.
84 */
85export function computeRequiredUnion(
86  protectionBody: string,
87  rulesetsBody: string
88): string[] {
89  const protection = parseProtection(protectionBody);
90  const rulesets = parseRulesets(rulesetsBody);
91
92  // Union with deduplication
93  const combined = new Set([...protection, ...rulesets]);
94  return Array.from(combined).sort();
95}
96
src/gh.ts 208 lines
1/**
2 * gh CLI wrapper for promote-lights.
3 * Read-only calls only, using the operator's own auth.
4 *
5 * Commands used:
6 * - gh pr list --base main --state open --json number,headRefName,headRefOid,title,labels
7 * - gh pr list with a head filter for the promote branch
8 * - gh pr list with a label filter for the promote label
9 * - gh api repos/{owner}/{repo}/branches/main/protection
10 * - gh api repos/{owner}/{repo}/rules/branches/main
11 * - gh api repos/{owner}/{repo}/commits/{head}/check-runs?per_page=100
12 * - gh api repos/{owner}/{repo}/commits/{head}/status
13 * - gh pr view N --json headRefOid,state,mergeStateStatus
14 *
15 * Also reads .github/branch-protection.json via fs.
16 */
17
18export interface PRInfo {
19  number: number;
20  headRefOid: string;
21  title: string;
22  headRefName?: string;
23  labels?: Array<{ name: string } | string>;
24}
25
26/**
27 * Promote PR matching.
28 *
29 * A real promote PR is an open PR with base main whose head is the
30 * promote branch (dev by default, PROMOTE_HEAD when configured) or
31 * which carries the promote label. Any other PR with base main is
32 * ordinary work and must never match.
33 */
34export const DEFAULT_PROMOTE_HEAD = "dev";
35/** The promote base: main unless PROMOTE_BASE names another (a dev, qa, main flow). */
36export const DEFAULT_PROMOTE_BASE = "main";
37export const PROMOTE_LABEL = "promote";
38
39/**
40 * Fields requested from the PR list endpoint.
41 */
42export const PR_LIST_FIELDS = "number,headRefName,headRefOid,title,labels";
43
44/**
45 * Page size for the filtered PR list queries. Each query is narrowed
46 * server side (one by head branch, one by label) so promote PRs are
47 * returned even when the repo has more open PRs than the gh default
48 * page of 30. Without the filters a promote PR past position 30 is
49 * silently missed.
50 */
51export const PR_LIST_LIMIT = "100";
52
53/**
54 * Query argv listing open PRs into the promote base from the promote branch.
55 */
56export function buildHeadQueryArgs(
57  promoteHead: string = DEFAULT_PROMOTE_HEAD,
58  promoteBase: string = DEFAULT_PROMOTE_BASE
59): readonly string[] {
60  return [
61    "gh",
62    "pr",
63    "list",
64    "--base",
65    promoteBase,
66    "--head",
67    promoteHead,
68    "--state",
69    "open",
70    "--json",
71    PR_LIST_FIELDS,
72    "--limit",
73    PR_LIST_LIMIT,
74  ];
75}
76
77/**
78 * Query argv listing open PRs into the promote base carrying the promote label.
79 * This covers promote PRs raised from a head other than the promote
80 * branch, which the head query alone would miss.
81 */
82export function buildLabelQueryArgs(promoteBase: string = DEFAULT_PROMOTE_BASE): readonly string[] {
83  return [
84    "gh",
85    "pr",
86    "list",
87    "--base",
88    promoteBase,
89    "--label",
90    PROMOTE_LABEL,
91    "--state",
92    "open",
93    "--json",
94    PR_LIST_FIELDS,
95    "--limit",
96    PR_LIST_LIMIT,
97  ];
98}
99
100/**
101 * Merge PR list pages, deduped by PR number. Either query can return
102 * the same PR (a dev head PR that also carries the label), so the
103 * first occurrence wins.
104 */
105export function mergePRLists(...lists: PRInfo[][]): PRInfo[] {
106  const seen = new Map<number, PRInfo>();
107  for (const list of lists) {
108    for (const pr of list) {
109      if (!seen.has(pr.number)) seen.set(pr.number, pr);
110    }
111  }
112  return [...seen.values()];
113}
114
115export function isPromotePR(pr: PRInfo, promoteHead: string = DEFAULT_PROMOTE_HEAD): boolean {
116  if (pr.headRefName !== undefined && pr.headRefName === promoteHead) return true;
117  const labels = pr.labels ?? [];
118  return labels.some((label) => {
119    const name = typeof label === "string" ? label : label.name;
120    return name !== undefined && name.toLowerCase() === PROMOTE_LABEL;
121  });
122}
123
124export interface PRDetails {
125  headRefOid: string;
126  state: string;
127  mergeStateStatus: string;
128  /** The PR's base branch; watch mode reads THIS branch's protection. */
129  baseRefName?: string;
130}
131
132export interface CheckRunsResponse {
133  total_count: number;
134  check_runs: Array<{
135    name: string;
136    status: string;
137    conclusion: string | null;
138  }>;
139}
140
141export interface StatusResponse {
142  statuses: Array<{
143    context: string;
144    state: string;
145  }>;
146}
147
148/**
149 * Parse PR list JSON output.
150 */
151export function parsePRList(stdout: string): PRInfo[] {
152  if (!stdout.trim()) return [];
153  try {
154    return JSON.parse(stdout);
155  } catch {
156    return [];
157  }
158}
159
160/**
161 * Parse PR view JSON output.
162 */
163export function parsePRView(stdout: string): PRDetails | null {
164  if (!stdout.trim()) return null;
165  try {
166    return JSON.parse(stdout);
167  } catch {
168    return null;
169  }
170}
171
172/**
173 * Parse check-runs API response.
174 */
175export function parseCheckRuns(body: string): CheckRunsResponse {
176  try {
177    return JSON.parse(body);
178  } catch {
179    return { total_count: 0, check_runs: [] };
180  }
181}
182
183/**
184 * Parse status API response.
185 */
186export function parseStatus(body: string): StatusResponse {
187  try {
188    return JSON.parse(body);
189  } catch {
190    return { statuses: [] };
191  }
192}
193
194/**
195 * Parse .github/branch-protection.json.
196 */
197export function parseBranchProtectionConfig(content: string): {
198  dev?: string[];
199  main?: string[];
200} | null {
201  if (!content.trim()) return null;
202  try {
203    return JSON.parse(content);
204  } catch {
205    return null;
206  }
207}
208
src/pane.ts 190 lines
1/**
2 * Band rendering for promote-lights.
3 * Draws a summary line plus one line per non-green check above the prompt.
4 * No Client module needed - static between ticks.
5 */
6
7import type { ClassifiedLight } from "./classify.ts";
8
9export const LIGHT_SYMBOLS: Record<string, string> = {
10  green: "\u{1F7E2}", // green circle
11  yellow: "\u{1F7E1}", // yellow circle
12  red: "\u{1F534}", // red circle
13  cancelled: "\u26A0\uFE0F", // warning sign
14};
15
16/**
17 * Build the status line string for $.ui.status().
18 * Format: "promote #N: 9/11 green, 1 yellow, 1 cancelled, BEHIND"
19 */
20export function buildStatusLine(
21  prNumber: number,
22  lights: ClassifiedLight[],
23  mergeStateStatus: string,
24  hold: boolean,
25  label?: string,
26  degraded = false
27): string {
28  const counts = {
29    green: lights.filter((l) => l.color === "green").length,
30    yellow: lights.filter((l) => l.color === "yellow").length,
31    red: lights.filter((l) => l.color === "red").length,
32    cancelled: lights.filter((l) => l.color === "cancelled").length,
33  };
34
35  const parts: string[] = [label ?? `promote #${prNumber}`];
36
37  if (counts.green > 0) parts.push(`${counts.green} green`);
38  if (counts.yellow > 0) parts.push(`${counts.yellow} yellow`);
39  if (counts.red > 0) parts.push(`${counts.red} red`);
40  if (counts.cancelled > 0) parts.push(`${counts.cancelled} cancelled`);
41
42  if (mergeStateStatus && mergeStateStatus !== "CLEAN") {
43    parts.push(mergeStateStatus);
44  }
45
46  if (hold) {
47    parts.unshift("HOLD");
48  }
49
50  if (degraded) {
51    parts.push("DEGRADED");
52  }
53
54  return parts.join(", ");
55}
56
57/**
58 * Build the band content for AbovePrompt.
59 * Returns an array of [name, symbol] pairs plus trailing info.
60 */
61export function buildBandContent(
62  lights: ClassifiedLight[],
63  headSha: string,
64  mergeStateStatus: string,
65  hold: boolean
66): Array<{ name: string; symbol: string }> {
67  const result: Array<{ name: string; symbol: string }> = lights.map((l) => ({
68    name: l.name,
69    symbol: LIGHT_SYMBOLS[l.color] ?? "?",
70  }));
71
72  // Add trailing info cell
73  const head = headSha.slice(0, 7);
74  const status = mergeStateStatus || "";
75  const holdPrefix = hold ? "HOLD " : "";
76
77  result.push({
78    name: `${holdPrefix}${head} ${status}`.trim(),
79    symbol: "",
80  });
81
82  return result;
83}
84
85/** Text color per light, as the terminal Text element takes it. */
86export const LIGHT_COLORS: Record<string, string> = {
87  green: "green",
88  yellow: "yellow",
89  red: "red",
90  cancelled: "yellow",
91};
92
93/** Element props: children plus whatever the element takes. */
94export type ElementProps = { children?: unknown } & Record<string, unknown>;
95/** A constructor from $.ui.resolve(e): Box, Text and the rest. */
96export type ElementCtor = (props?: ElementProps) => unknown;
97export type Elements = { Box: ElementCtor; Text: ElementCtor };
98
99/** Most problem lines drawn under the summary; the rest collapse into "+N more". */
100export const MAX_PROBLEM_LINES = 5;
101
102/** Order for the problem lines: red first, then cancelled, then yellow. */
103const PROBLEM_ORDER: Record<string, number> = { red: 0, cancelled: 1, yellow: 2 };
104
105/** The non-green lights, red then cancelled then yellow, stable within a color. */
106export function problemLights(lights: ClassifiedLight[]): ClassifiedLight[] {
107  return lights
108    .map((l, i) => ({ l, i }))
109    .filter(({ l }) => l.color !== "green")
110    .sort((a, b) => (PROBLEM_ORDER[a.l.color] ?? 0) - (PROBLEM_ORDER[b.l.color] ?? 0) || a.i - b.i)
111    .map(({ l }) => l);
112}
113
114/** The summary label: "#N" for a promote PR, "owner/repo#N" when watching. */
115export function summaryLabel(label: string): string {
116  return label.replace(/^(watch|promote) /, "");
117}
118
119/**
120 * Build the AbovePrompt band from the elements $.ui.resolve(e) hands out.
121 * A plain { type: "Box" } object is not an element on CC 2.1.282 and never
122 * draws, so every node here comes from a constructor.
123 *
124 * Layout (approved 2026-09-26): one summary line always, then one line per
125 * check that is not green, full name, red first. All green is one line.
126 *
127 *   🚦 #4435  3afff24  BLOCKED   19 🟢  0 🟡  2 🔴
128 *      🔴 PR Playground
129 *      🔴 CI Summary
130 */
131export function buildBand(
132  els: Elements,
133  label: string,
134  lights: ClassifiedLight[],
135  headSha: string,
136  mergeStateStatus: string,
137  hold: boolean,
138  degraded = false
139): unknown {
140  const { Box, Text } = els;
141  const count = (color: string) => lights.filter((l) => l.color === color).length;
142  const green = count("green");
143  const yellow = count("yellow");
144  const red = count("red");
145  const cancelled = count("cancelled");
146
147  const runs: unknown[] = [];
148  if (hold) runs.push(Text({ color: "red", bold: true, children: "HOLD " }));
149  runs.push(Text({ bold: true, children: `\u{1F6A6} ${summaryLabel(label)}  ` }));
150  const state = `${headSha.slice(0, 7)}  ${mergeStateStatus}`.trim();
151  if (state) runs.push(Text({ dimColor: true, children: `${state}   ` }));
152  runs.push(Text({ color: "green", children: `${green} ${LIGHT_SYMBOLS.green}  ` }));
153  runs.push(Text({ color: "yellow", children: `${yellow} ${LIGHT_SYMBOLS.yellow}  ` }));
154  runs.push(Text({ color: "red", children: `${red} ${LIGHT_SYMBOLS.red}` }));
155  if (cancelled > 0) {
156    runs.push(Text({ color: "yellow", children: `  ${cancelled} ${LIGHT_SYMBOLS.cancelled}` }));
157  }
158  if (degraded) runs.push(Text({ dimColor: true, children: "  DEGRADED" }));
159
160  const lines: unknown[] = [Text({ children: runs })];
161  const problems = problemLights(lights);
162  for (const l of problems.slice(0, MAX_PROBLEM_LINES)) {
163    lines.push(
164      Text({
165        color: LIGHT_COLORS[l.color] ?? "red",
166        children: `   ${LIGHT_SYMBOLS[l.color] ?? "?"} ${l.name}`,
167      })
168    );
169  }
170  if (problems.length > MAX_PROBLEM_LINES) {
171    lines.push(Text({ dimColor: true, children: `   +${problems.length - MAX_PROBLEM_LINES} more` }));
172  }
173  return Box({ flexDirection: "column", children: lines });
174}
175
176/** One dim line saying why there are no lights, so a failure is never blank. */
177export function buildErrorBand(els: Elements, error: string): unknown {
178  const { Box, Text } = els;
179  return Box({ children: [Text({ dimColor: true, children: `lights: ${error}` })] });
180}
181
182/**
183 * Shorten context name for display.
184 * Truncates to ~20 chars.
185 */
186export function shortName(name: string, maxLen = 20): string {
187  if (name.length <= maxLen) return name;
188  return name.slice(0, maxLen - 1) + "\u2026"; // ellipsis
189}
190
src/watch.ts 78 lines
1// Generated by OrchestKit Claude Plugin
2// Created: 2026-09-25
3
4/**
5 * Watch targets for promote-lights demo mode.
6 *
7 * `/lights watch <target>` (or PROMOTE_LIGHTS_WATCH=<target>) tracks any open
8 * PR in any repo, so the band can be shown without a live promote PR.
9 * Accepted target forms:
10 * - owner/repo#123
11 * - owner/repo 123
12 * - https://github.com/owner/repo/pull/123
13 */
14
15export interface WatchTarget {
16  owner: string;
17  repo: string;
18  number: number;
19}
20
21const NAME = "[A-Za-z0-9_.-]+";
22const HASH_FORM = new RegExp(`^(${NAME})/(${NAME})#(\\d+)$`);
23const SPACE_FORM = new RegExp(`^(${NAME})/(${NAME})\\s+#?(\\d+)$`);
24const URL_FORM = new RegExp(`^https?://github\\.com/(${NAME})/(${NAME})/pull/(\\d+)(?:[/?#].*)?$`);
25
26export function parseWatchTarget(input: string | undefined | null): WatchTarget | null {
27  const text = (input ?? "").trim();
28  if (!text) return null;
29  for (const form of [HASH_FORM, SPACE_FORM, URL_FORM]) {
30    const m = form.exec(text);
31    if (m) {
32      const number = Number(m[3]);
33      if (!Number.isSafeInteger(number) || number <= 0) return null;
34      return { owner: m[1], repo: m[2], number };
35    }
36  }
37  return null;
38}
39
40export function formatWatchTarget(t: WatchTarget): string {
41  return `${t.owner}/${t.repo}#${t.number}`;
42}
43
44/**
45 * Every distinct check-run name on a head, in first-seen order. Used when the
46 * watched repo protects nothing: the lights then cover every check that ran,
47 * and matchAndClassify takes the worst non-skipped run per name.
48 */
49export function allCheckNames(runs: ReadonlyArray<{ name: string }>): string[] {
50  const seen = new Set<string>();
51  const names: string[] = [];
52  for (const r of runs) {
53    if (!seen.has(r.name)) {
54      seen.add(r.name);
55      names.push(r.name);
56    }
57  }
58  return names;
59}
60
61export const WATCH_USAGE = "usage: /lights watch owner/repo#123 (for example cli/cli#1; also owner/repo 123, or a PR URL)";
62
63/**
64 * What a bare /lights answers when nothing is tracked. Names the promote
65 * head and base the session search used (dev into main unless PROMOTE_HEAD or
66 * PROMOTE_BASE overrides them): on a
67 * repo whose promote branch is named anything else, the bare "no promote PR
68 * open" read as a bug instead of a lookup that found nothing.
69 */
70export function noPrHint(promoteHead: string, promoteBase = "main"): string {
71  return `no promote PR open with head "${promoteHead}" into "${promoteBase}" (set PROMOTE_HEAD or PROMOTE_BASE to look for another); try /lights watch owner/repo#123, for example cli/cli#1`;
72}
73
74/** An argument that is neither a subcommand nor a parseable target gets its own line. */
75export function unknownArgHint(arg: string): string {
76  return `lights: unknown argument "${arg}"; try /lights watch owner/repo#123, for example cli/cli#1`;
77}
78