From 544f22be84427af33dee41a3d26a49a000ed8d10 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 19:34:43 -0500 Subject: [PATCH 01/11] chore: pass app arguments through the verify sandbox --- .claude/skills/verify-wt-dash/SKILL.md | 4 ++- .claude/skills/verify-wt-dash/stack.ts | 36 ++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/.claude/skills/verify-wt-dash/SKILL.md b/.claude/skills/verify-wt-dash/SKILL.md index f81298a..a97a6d9 100644 --- a/.claude/skills/verify-wt-dash/SKILL.md +++ b/.claude/skills/verify-wt-dash/SKILL.md @@ -22,7 +22,7 @@ Every stack command prints one JSON object, `{"ok":true,...}` or `{"ok":false,"e An instance is a name (1–24 of `a-z0-9-`; use one per task, such as the branch topic) and everything under `.verify//` (gitignored): - `sandbox/`: its own HOME (so its own `~/.cache/wt-dash/sizes.json` and `removals.log`), Git config, Worktrunk config (`WORKTRUNK_CONFIG_PATH` and friends), the scan root `sandbox/projects/` with the seeded repos, and their worktrees in `sandbox/worktrees/`. -- A tmux server on its own socket, `tmux -L wt-dash-verify--`, holding one session, `app`, running `bun src/index.ts sandbox/projects` from this checkout with the instance env. The hash keeps the same name in two checkouts apart; `env` prints the exact socket. +- A tmux server on its own socket, `tmux -L wt-dash-verify--`, holding one session, `app`, running `bun src/index.ts sandbox/projects` from this checkout with the instance env, plus any `up --app-args` (below). The hash keeps the same name in two checkouts apart; `env` prints the exact socket. - `logs/` (`app.log` is the app's stderr, `stack.log` every up/down) and `evidence/`. There are no ports. Two agents in one checkout only need different names. Never drive the developer's own wt-dash, `~/projects` or `~/.cache/wt-dash`, and never drive an instance you did not start: `list` shows what exists. `up` refuses an instance started on another branch; recreate it with `down --purge` then `up`. @@ -55,6 +55,8 @@ The list's AGE column (`now`, `3d`) is the age of the row's last commit, not of `up --seed ` builds the sandbox with a module's default export instead (a `SeedModule` from `stack.ts`); `scripts/readme-images/seed.ts`, the README's made-up projects, is one. Its rows differ from this table, and `state` lists only repos under its scan root. +`up --app-args=''` puts extra arguments on the app's command line after the scan root, so a flag such as `--depth 0` or `--offline` can be driven in the real app: `up --name --app-args='--depth 0'`. The arguments are split on spaces, so one cannot contain a space, and a value that starts with `--` needs the `=`. The instance keeps them: a stopped instance restarts with them, `up` on a running one with other arguments is refused (`down --name `, then `up` again), and `down --purge` forgets them. Without the option the command is unchanged. If the app exits on its arguments (`--version`, an invalid flag), `up` fails with the pane's text in `screen`. + Assume nothing beyond this table, and only what `state` shows after you change things. Removals are real, so a check that removes rows starts from a fresh seed: `down --purge`, then `up` (half a second). To arrange other state, use Git or `wt` as the instance's user, through a supported path, in the same shell call as the `eval` of `env` → `exports` (it reads `env --full`), as [features/rescan.md](features/rescan.md) does. Never edit `.git` files or the cache to fake the behavior under test. On Linux, backdating a worktree does not move its birth time, so the real binary sees `feature/login` and `docs/typos` as new (Review, "Created just now…"); `env` reports `backdatesOnDisk: false` and `env --full` → `seed` already expects that. This skill was only run on macOS. diff --git a/.claude/skills/verify-wt-dash/stack.ts b/.claude/skills/verify-wt-dash/stack.ts index 0cab422..18172d5 100644 --- a/.claude/skills/verify-wt-dash/stack.ts +++ b/.claude/skills/verify-wt-dash/stack.ts @@ -75,6 +75,8 @@ interface Instance { backdatesOnDisk: boolean; /** The `--seed` module, or null for the default seed. */ seedFile?: string | null; + /** Extra arguments from `--app-args`, put after the scan root on the app's command line. */ + appArgs?: string[]; seed: SeedRow[]; } @@ -114,6 +116,11 @@ function parseFlags(args: string[]): { flags: Record; res continue; } const key = arg.slice(2); + const equals = key.indexOf("="); + if (equals > 0) { + flags[key.slice(0, equals)] = key.slice(equals + 1); + continue; + } const next = args[index + 1]; if (next !== undefined && !next.startsWith("--")) { flags[key] = next; @@ -390,6 +397,7 @@ async function startApp(instance: Instance): Promise { process.execPath, join(repoRoot, "src", "index.ts"), instance.scanRoot, + ...(instance.appArgs ?? []), // In the config file this option crashes tmux 3.6a's server before the first session exists. ";", "set-option", @@ -435,6 +443,15 @@ async function up(flags: Record) { `Instance ${name} was seeded from ${instance.seedFile ?? "the default seed"}.`, `Recreate it: bun ${self} down --name ${name} --purge, then up again.`, ); + if (flags["app-args"] === true) + throw new Failure( + "--app-args needs a value, and a value starting with -- must be joined with =.", + "Example: --app-args='--depth 0'", + ); + const appArgs = + typeof flags["app-args"] === "string" + ? flags["app-args"].split(/\s+/).filter((word) => word !== "") + : undefined; const variant: Variant = variantFlag ?? instance?.variant ?? "wide"; let seeded = false; if (!instance) { @@ -473,6 +490,11 @@ async function up(flags: Record) { let resized = false; if (info && !info.dead) { reused = true; + if (appArgs && appArgs.join(" ") !== (instance.appArgs ?? []).join(" ")) + throw new Failure( + `Instance ${name} is running with ${instance.appArgs?.length ? `app arguments ${instance.appArgs.join(" ")}` : "no app arguments"}.`, + `Restart it with the new ones: bun ${self} down --name ${name}, then up again.`, + ); if (instance.variant !== variant) { const { cols, rows } = VARIANTS[variant]; tmux(instance.socket, "resize-window", "-t", "app", "-x", String(cols), "-y", String(rows)); @@ -483,17 +505,27 @@ async function up(flags: Record) { } else { if (info?.dead) tmux(instance.socket, "kill-server"); instance.variant = variant; + if (appArgs) instance.appArgs = appArgs; await startApp(instance); } const ready = await waitUntilReady(instance.socket, p.appLog); const size = paneInfo(instance.socket)?.size; - await log(name, { event: "up", reused, resized, seeded, variant, readyMs: ready.ms }); + await log(name, { + event: "up", + reused, + resized, + seeded, + variant, + appArgs: instance.appArgs ?? [], + readyMs: ready.ms, + }); return { name, reused, seeded, resized, variant, + appArgs: instance.appArgs ?? [], size, branch: instance.branch, header: ready.header, @@ -1042,7 +1074,7 @@ async function list() { } const COMMANDS = { - up: "up --name [--variant wide|narrow] [--seed ] Seed if new, start wt-dash in tmux, wait until listed. Reuses a running instance (resizing it to the variant). --seed builds the sandbox with a module's default export (SeedModule) instead of the test fixture's seed.", + up: "up --name [--variant wide|narrow] [--seed ] [--app-args=''] Seed if new, start wt-dash in tmux, wait until listed. Reuses a running instance (resizing it to the variant). --seed builds the sandbox with a module's default export (SeedModule) instead of the test fixture's seed. --app-args adds space-separated arguments after the scan root, such as --app-args='--depth 0'; join the value with = when it starts with --. A stopped instance restarts with the last ones; a running one with other arguments is refused.", env: "env --name [--full] The shell preamble, tmux commands and paths to drive the instance; --full adds its env and the seeded rows with their expected verdicts.", doctor: "doctor --name Read-only health check.", state: From 0b049ade0bd4ba651067031bad8cb8e8d2b278a7 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 19:40:17 -0500 Subject: [PATCH 02/11] refactor: share the cache file writer --- src/core/cache-file.ts | 67 ++++++++++++++++ src/core/sizes.ts | 85 ++++++++------------ tests/cache-file.test.ts | 165 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 266 insertions(+), 51 deletions(-) create mode 100644 src/core/cache-file.ts create mode 100644 tests/cache-file.test.ts diff --git a/src/core/cache-file.ts b/src/core/cache-file.ts new file mode 100644 index 0000000..057e18c --- /dev/null +++ b/src/core/cache-file.ts @@ -0,0 +1,67 @@ +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; + +export interface CacheFileCodec { + /** Turns the parsed JSON into a value. Throwing is the same as a corrupt file. */ + parse(raw: unknown): T; + /** Turns the value into JSON data, read when the write starts. */ + serialize(value: T): unknown; + /** The value when the file is missing or corrupt. */ + empty(): T; +} + +export interface CacheFile { + load(): Promise; + /** + * Writes the value. While a write is running, later saves share one more + * write that reads the newest value, and every save resolves once its + * value, or a newer one, is on disk. Write errors are swallowed. + */ + save(value: T): Promise; + /** Resolves when no write is running. */ + flush(): Promise; +} + +/** A JSON cache file written through a temporary file and a rename, so a reader never sees half a file. */ +export function createCacheFile(path: string, codec: CacheFileCodec): CacheFile { + let writeNumber = 0; + let latest: { value: T } | null = null; + let dirty = false; + let writes: Promise | null = null; + + return { + async load() { + try { + return codec.parse(JSON.parse(await readFile(path, "utf8")) as unknown); + } catch { + // Missing and corrupt cache files both mean there is nothing saved. + return codec.empty(); + } + }, + save(value) { + latest = { value }; + dirty = true; + writes ??= Promise.resolve().then(async () => { + try { + while (dirty) { + dirty = false; + try { + await mkdir(dirname(path), { recursive: true }); + const temporary = `${path}.tmp-${process.pid}-${++writeNumber}`; + // A save during mkdir is covered by this write, which reads the newest value. + dirty = false; + await writeFile(temporary, JSON.stringify(codec.serialize(latest!.value), null, 2)); + await rename(temporary, path); + } catch {} + } + } finally { + writes = null; + } + }); + return writes; + }, + async flush() { + await writes; + }, + }; +} diff --git a/src/core/sizes.ts b/src/core/sizes.ts index 3627a04..27e9a7e 100644 --- a/src/core/sizes.ts +++ b/src/core/sizes.ts @@ -1,5 +1,6 @@ -import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; -import { dirname, join } from "node:path"; +import { stat } from "node:fs/promises"; +import { join } from "node:path"; +import { createCacheFile } from "./cache-file"; import type { CommandRunner, SizeEntry, SizeService, SizeSignature } from "./types"; /** A saved size older than this is measured again even when its folders look unchanged. */ @@ -36,6 +37,29 @@ function parseSignature(raw: unknown): SizeSignature | undefined { return { mtimeMs: mtimeMs as number, nodeModulesMtimeMs: nodeModulesMtimeMs as number | null }; } +function parseEntries(parsed: unknown): Map { + const entries = new Map(); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return entries; + for (const [path, raw] of Object.entries(parsed)) { + if (typeof raw !== "object" || raw === null) continue; + const entry = raw as Record; + if ( + Number.isSafeInteger(entry.sizeKiB) && + (entry.sizeKiB as number) >= 0 && + typeof entry.measuredAt === "string" + ) { + const loaded: SizeEntry = { + sizeKiB: entry.sizeKiB as number, + measuredAt: entry.measuredAt, + }; + const signature = parseSignature(entry.signature); + if (signature) loaded.signature = signature; + entries.set(path, loaded); + } + } + return entries; +} + export function createSizeService( cachePath: string, runner: CommandRunner, @@ -50,12 +74,14 @@ export function createSizeService( const inFlight = new Map>(); const newestByPath = new Map(); const abort = new AbortController(); + const file = createCacheFile>(cachePath, { + parse: parseEntries, + serialize: (entries) => Object.fromEntries(entries), + empty: () => new Map(), + }); let requests = 0; let active = 0; let closed = false; - let writeNumber = 0; - let dirty = false; - let writes: Promise | null = null; async function acquire(hadEntry: boolean, first: boolean): Promise { if (closed) return false; @@ -79,27 +105,6 @@ export function createSizeService( else active--; } - function persist(): Promise { - dirty = true; - writes ??= Promise.resolve().then(async () => { - try { - while (dirty) { - dirty = false; - try { - await mkdir(dirname(cachePath), { recursive: true }); - const temporary = `${cachePath}.tmp-${process.pid}-${++writeNumber}`; - dirty = false; - await writeFile(temporary, JSON.stringify(Object.fromEntries(cache), null, 2)); - await rename(temporary, cachePath); - } catch {} - } - } finally { - writes = null; - } - }); - return writes; - } - async function isFresh(path: string): Promise { const entry = cache.get(path); if (!entry?.signature) return false; @@ -130,7 +135,7 @@ export function createSizeService( const entry: SizeEntry = { sizeKiB, measuredAt: new Date(now()).toISOString() }; if (signature) entry.signature = signature; cache.set(path, entry); - saved = persist(); + saved = file.save(cache); measured = entry; } catch { return null; @@ -150,29 +155,7 @@ export function createSizeService( return { async load() { cache.clear(); - try { - const parsed = JSON.parse(await readFile(cachePath, "utf8")) as unknown; - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return; - for (const [path, raw] of Object.entries(parsed)) { - if (typeof raw !== "object" || raw === null) continue; - const entry = raw as Record; - if ( - Number.isSafeInteger(entry.sizeKiB) && - (entry.sizeKiB as number) >= 0 && - typeof entry.measuredAt === "string" - ) { - const loaded: SizeEntry = { - sizeKiB: entry.sizeKiB as number, - measuredAt: entry.measuredAt, - }; - const signature = parseSignature(entry.signature); - if (signature) loaded.signature = signature; - cache.set(path, loaded); - } - } - } catch { - // Missing and corrupt cache files both mean there is no saved size. - } + for (const [path, entry] of await file.load()) cache.set(path, entry); }, get(path) { return cache.get(path) ?? null; @@ -202,7 +185,7 @@ export function createSizeService( ]) resume(); await Promise.allSettled(tasks); - await writes; + await file.flush(); }, }; } diff --git a/tests/cache-file.test.ts b/tests/cache-file.test.ts new file mode 100644 index 0000000..1d53e64 --- /dev/null +++ b/tests/cache-file.test.ts @@ -0,0 +1,165 @@ +import { afterEach, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createCacheFile } from "../src/core/cache-file"; + +const roots: string[] = []; +async function folder(): Promise { + const root = await mkdtemp(join(tmpdir(), "dash-cache-file-")); + roots.push(root); + return root; +} +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +const realRename = fs.rename; +type Counts = Record; +function counts(path: string) { + return createCacheFile(path, { + parse: (raw) => { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("bad"); + return raw as Counts; + }, + serialize: (value) => value, + empty: () => ({}), + }); +} + +test("saves a value and loads it back", async () => { + const path = join(await folder(), "counts.json"); + await counts(path).save({ a: 1, b: 2 }); + expect(await readFile(path, "utf8")).toBe(JSON.stringify({ a: 1, b: 2 }, null, 2)); + expect(await counts(path).load()).toEqual({ a: 1, b: 2 }); +}); + +test("creates the missing folder when saving", async () => { + const path = join(await folder(), "deep", "er", "counts.json"); + await counts(path).save({ a: 1 }); + expect(await counts(path).load()).toEqual({ a: 1 }); +}); + +test("loads the empty value when the file is missing", async () => { + const path = join(await folder(), "counts.json"); + expect(await counts(path).load()).toEqual({}); +}); + +test("loads the empty value when the file is not JSON or fails to parse", async () => { + const path = join(await folder(), "counts.json"); + await writeFile(path, "{ not json"); + expect(await counts(path).load()).toEqual({}); + await writeFile(path, "[1, 2]"); + expect(await counts(path).load()).toEqual({}); +}); + +test("saves made during a write share one more write and the last value wins", async () => { + const root = await folder(); + const path = join(root, "counts.json"); + let release!: () => void; + const blocked = new Promise((resolve) => (release = resolve)); + let reached!: () => void; + const writing = new Promise((resolve) => (reached = resolve)); + let renames = 0; + const spy = spyOn(fs, "rename").mockImplementation(async (...args) => { + if (++renames === 1) { + reached(); + await blocked; + } + return realRename(...args); + }); + try { + const file = counts(path); + const saves = [file.save({ n: 1 })]; + await writing; + saves.push(file.save({ n: 2 }), file.save({ n: 3 }), file.save({ n: 4 })); + release(); + await Promise.all(saves); + expect(renames).toBe(2); + expect(await counts(path).load()).toEqual({ n: 4 }); + } finally { + spy.mockRestore(); + } +}); + +test("a save resolves only after its value is on disk", async () => { + const path = join(await folder(), "counts.json"); + const file = counts(path); + const first = file.save({ n: 1 }); + const second = file.save({ n: 2 }); + await first; + expect(await counts(path).load()).toEqual({ n: 2 }); + await second; +}); + +test("serializes the value as it is when the write starts", async () => { + const path = join(await folder(), "counts.json"); + const shared: Counts = { n: 1 }; + const file = counts(path); + const saved = file.save(shared); + shared.n = 2; + await saved; + expect(await counts(path).load()).toEqual({ n: 2 }); +}); + +test("flush waits for a running write and resolves when idle", async () => { + const path = join(await folder(), "counts.json"); + const file = counts(path); + await file.flush(); + void file.save({ n: 1 }); + await file.flush(); + expect(await counts(path).load()).toEqual({ n: 1 }); +}); + +test("leaves only the cache file in the folder after the writes", async () => { + const root = await folder(); + const path = join(root, "counts.json"); + const file = counts(path); + await Promise.all([1, 2, 3, 4, 5].map((n) => file.save({ n }))); + await file.save({ n: 6 }); + expect(await readdir(root)).toEqual(["counts.json"]); +}); + +test("keeps the old file whole while a new one is written beside it", async () => { + const root = await folder(); + const path = join(root, "counts.json"); + const file = counts(path); + await file.save({ n: 1 }); + let release!: () => void; + const blocked = new Promise((resolve) => (release = resolve)); + let reached!: () => void; + const writing = new Promise((resolve) => (reached = resolve)); + const spy = spyOn(fs, "rename").mockImplementation(async (...args) => { + reached(); + await blocked; + return realRename(...args); + }); + try { + const saved = file.save({ n: 2 }); + await writing; + expect(JSON.parse(await readFile(path, "utf8"))).toEqual({ n: 1 }); + expect((await readdir(root)).filter((name) => name.includes(".tmp-"))).toHaveLength(1); + release(); + await saved; + expect(await counts(path).load()).toEqual({ n: 2 }); + expect(await readdir(root)).toEqual(["counts.json"]); + } finally { + spy.mockRestore(); + } +}); + +test("swallows a failed write and writes again on the next save", async () => { + const root = await folder(); + const path = join(root, "counts.json"); + const file = counts(path); + const spy = spyOn(fs, "rename").mockRejectedValueOnce(new Error("disk full")); + try { + await file.save({ n: 1 }); + } finally { + spy.mockRestore(); + } + expect(await counts(path).load()).toEqual({}); + await file.save({ n: 2 }); + expect(await counts(path).load()).toEqual({ n: 2 }); +}); From 5cd5f26497b2c770a83b927c4bebd2d627fc9b04 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 19:40:31 -0500 Subject: [PATCH 03/11] refactor: add a per-repo follow-up step to the scan A dashboard service option, followUp, runs once per scan after each repository's full listing without holding the scan up. Its RowPatch results patch rows by id while the row's HEAD still matches, last across listings and rescans until replaced, and are dropped when a rescan or close has aborted them. The snapshot counts running follow-ups in checking, which keeps the spinner ticking. --- src/core/scan/dashboard.ts | 95 ++++++-- src/core/types.ts | 2 + src/ui/selectors.ts | 1 + tests/integration/follow-up.test.ts | 72 ++++++ tests/scan/follow-up.test.ts | 339 ++++++++++++++++++++++++++++ tests/support/update.ts | 1 + tests/terminal.test.ts | 1 + 7 files changed, 494 insertions(+), 17 deletions(-) create mode 100644 tests/integration/follow-up.test.ts create mode 100644 tests/scan/follow-up.test.ts diff --git a/src/core/scan/dashboard.ts b/src/core/scan/dashboard.ts index 9bd80a1..b6d29ad 100644 --- a/src/core/scan/dashboard.ts +++ b/src/core/scan/dashboard.ts @@ -1,3 +1,4 @@ +import { assess } from "../assess"; import { listArgs, parseWorktrunk, SchemaMismatchError } from "../worktrunk/list"; import { discoverRepos, readLinkedWorktrees, type LinkedWorktrees } from "./discovery"; import { enrichRows } from "./enrich"; @@ -11,9 +12,21 @@ import { type RunningProcess, type SizeEntry, type SizeService, + type WorktreeFacts, type WorktreeRow, } from "../types"; +/** + * Facts a follow-up learned about the row `id`, which apply only while the row's HEAD is still `headSha`. A + * patch lasts across listings and rescans until a later follow-up returns one for the same row, so it should + * set every field it owns, null included. + */ +export interface RowPatch { + id: string; + headSha: string; + facts: Partial>; +} + interface DashboardOptions { projectRoot: string; wtPath: string; @@ -32,6 +45,11 @@ interface DashboardOptions { paths: string[], signal: AbortSignal, ) => Promise>; + /** + * Runs once per scan after each repository's full listing, without holding the scan up, and patches its rows + * when it resolves. It gets the rows as listed, earlier patches applied; if it fails, they keep their facts. + */ + followUp?: (repo: string, rows: WorktreeRow[], signal: AbortSignal) => Promise; } export function createDashboardService(options: DashboardOptions): DashboardService { @@ -42,9 +60,11 @@ export function createDashboardService(options: DashboardOptions): DashboardServ const ticketByTask = new WeakMap, number>(); let rowsByPath = new Map(); const completed = new Map(); + const patches = new Map(); let completionTimer: ReturnType | null = null; const completionWaiters: Array<() => void> = []; let measurements = 0; + let checking = 0; let closed = false; let generation = 0; let snapshot: DashboardSnapshot = { @@ -55,10 +75,11 @@ export function createDashboardService(options: DashboardOptions): DashboardServ errors: {}, fatalError: null, sizing: [], + checking: 0, processes: {}, }; - function publish(next: Omit): void { + function publish(next: Omit): void { if (next.rows !== snapshot.rows) { rowsByPath = new Map(); for (const row of next.rows) { @@ -68,7 +89,7 @@ export function createDashboardService(options: DashboardOptions): DashboardServ rowsByPath.set(row.path, rows); } } - snapshot = { ...next, sizing: [...runningByPath.keys()] }; + snapshot = { ...next, sizing: [...runningByPath.keys()], checking }; for (const listener of listeners) listener(snapshot); } @@ -83,6 +104,17 @@ export function createDashboardService(options: DashboardOptions): DashboardServ }); } + function withPatches(rows: WorktreeRow[]): WorktreeRow[] { + if (!patches.size) return rows; + return rows.map((row) => { + const patch = patches.get(row.id); + if (!patch || patch.headSha !== row.headSha) return row; + const patched = { ...row, ...patch.facts }; + const { verdict, reason } = assess(patched); + return { ...patched, verdict, reason }; + }); + } + /** Callers publish afterwards, so the sizing mark reaches the screen. */ function track(path: string, task: Promise): Promise { const ticket = ticketByTask.get(task) ?? ++measurements; @@ -263,15 +295,19 @@ export function createDashboardService(options: DashboardOptions): DashboardServ controller.signal, ); if (result.exitCode !== 0 || !current(scanGeneration)) return; - const rows = await enrichRows( - repo, - withSizes(parseWorktrunk(repo, result.stdout).filter((row) => row.kind === "worktree")), - options.runner, - { - readCreated: options.readCreated, - readBranchCreated: options.readBranchCreated, - signal: controller.signal, - }, + const rows = withPatches( + await enrichRows( + repo, + withSizes( + parseWorktrunk(repo, result.stdout).filter((row) => row.kind === "worktree"), + ), + options.runner, + { + readCreated: options.readCreated, + readBranchCreated: options.readBranchCreated, + signal: controller.signal, + }, + ), ); if (!current(scanGeneration)) return; scheduleSizes(rows, first.has(repo)); @@ -322,12 +358,14 @@ export function createDashboardService(options: DashboardOptions): DashboardServ } else { let rows: WorktreeRow[]; try { - rows = withSizes( - await enrichRows(repo, parseWorktrunk(repo, result.stdout), options.runner, { - readCreated: options.readCreated, - readBranchCreated: options.readBranchCreated, - signal: controller.signal, - }), + rows = withPatches( + withSizes( + await enrichRows(repo, parseWorktrunk(repo, result.stdout), options.runner, { + readCreated: options.readCreated, + readBranchCreated: options.readBranchCreated, + signal: controller.signal, + }), + ), ); } catch (error) { if (!current(scanGeneration)) continue; @@ -353,6 +391,7 @@ export function createDashboardService(options: DashboardOptions): DashboardServ ...snapshot, rows: [...snapshot.rows.filter((row) => row.repoPath !== repo), ...rows], }); + if (options.followUp) void followUp(options.followUp, repo, rows); } } catch (error) { if (!current(scanGeneration)) continue; @@ -389,6 +428,28 @@ export function createDashboardService(options: DashboardOptions): DashboardServ // After the listing, so the first rows never wait on it. if (options.findProcesses) await findProcesses(options.findProcesses); } + async function followUp( + check: NonNullable, + repo: string, + rows: WorktreeRow[], + ): Promise { + const controller = new AbortController(); + controllers.add(controller); + checking++; + publish(snapshot); + let learned: RowPatch[] = []; + try { + learned = await check(repo, rows, controller.signal); + } catch { + // The rows keep the facts their listing gave them. + } + controllers.delete(controller); + checking--; + if (closed) return; + const fresh = learned.length > 0 && current(scanGeneration); + for (const patch of fresh ? learned : []) patches.set(patch.id, patch); + publish({ ...snapshot, rows: fresh ? withPatches(snapshot.rows) : snapshot.rows }); + } async function findProcesses( find: NonNullable, ): Promise { diff --git a/src/core/types.ts b/src/core/types.ts index 066eaee..b89389e 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -164,6 +164,8 @@ export interface DashboardSnapshot { fatalError: string | null; /** Worktree folders whose size is being measured right now. */ sizing: string[]; + /** Follow-ups started after a repository's listing that haven't finished yet. */ + checking: number; /** Processes running inside each row's folder, keyed by the folder, as of the last completed scan. */ processes: Record; } diff --git a/src/ui/selectors.ts b/src/ui/selectors.ts index 7664cd5..912533a 100644 --- a/src/ui/selectors.ts +++ b/src/ui/selectors.ts @@ -226,6 +226,7 @@ export function projectsReady(state: UiState, snapshot: DashboardSnapshot): bool export function spinning(state: UiState, snapshot: DashboardSnapshot): boolean { return ( snapshot.progress.phase === "scanning" || + snapshot.checking > 0 || state.pending !== null || state.jobs.length > 0 || state.pruning diff --git a/tests/integration/follow-up.test.ts b/tests/integration/follow-up.test.ts new file mode 100644 index 0000000..ef94197 --- /dev/null +++ b/tests/integration/follow-up.test.ts @@ -0,0 +1,72 @@ +import { afterAll, beforeAll, expect, test, setDefaultTimeout } from "bun:test"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { createDashboardService, type RowPatch } from "../../src/core/scan/dashboard"; +import type { WorktreeRow } from "../../src/core/types"; +import { createSandbox, findRow, type Sandbox, TEST_TIMEOUT } from "../support/fixture"; +import { row, scan, waitFor } from "./helpers"; + +setDefaultTimeout(TEST_TIMEOUT); + +let sandbox: Sandbox; + +beforeAll(async () => { + sandbox = await createSandbox(); +}); + +afterAll(() => sandbox?.cleanup()); + +test("a follow-up sees every row of a real listing, and its patch holds only while HEAD stays put", async () => { + const repo = await sandbox.repo("checks"); + const ahead = await repo.unmergedWorktree("ahead"); + const leftover = await repo.unmergedBranch("leftover"); + const { sizes } = await sandbox.services(); + const seen: WorktreeRow[][] = []; + let answer: (rows: WorktreeRow[]) => RowPatch[] = (rows) => { + const target = findRow(rows, ahead)!; + return [ + { + id: target.id, + headSha: target.headSha!, + facts: { mainState: "integrated", integrationReason: "trees_match" }, + }, + ]; + }; + const dashboard = createDashboardService({ + projectRoot: sandbox.scanRoot, + wtPath: sandbox.wtPath, + runner: sandbox.runner, + sizeService: sizes, + readCreated: sandbox.readCreated, + followUp: async (listed, rows) => { + if (listed === repo.path) seen.push(rows); + return answer(rows); + }, + }); + try { + await scan(dashboard, repo); + expect(seen).toHaveLength(1); + expect(findRow(seen[0]!, ahead)?.verdict).toBe("Review"); + expect(findRow(seen[0]!, leftover)?.headSha).toBe(await repo.git("rev-parse", "leftover")); + const checked = await waitFor(dashboard, (snapshot) => snapshot.checking === 0); + expect(row(checked, ahead)).toMatchObject({ mainState: "integrated", verdict: "Safe" }); + + answer = () => []; + await scan(dashboard, repo); + const kept = await waitFor(dashboard, (snapshot) => snapshot.checking === 0); + expect(row(kept, ahead).verdict).toBe("Safe"); + + await writeFile(join(ahead.path!, "more.txt"), "more\n"); + await sandbox.git(ahead.path!, "add", "more.txt"); + await sandbox.git(ahead.path!, "commit", "-q", "-m", "More"); + await scan(dashboard, repo); + const moved = await waitFor(dashboard, (snapshot) => snapshot.checking === 0); + expect(row(moved, ahead)).toMatchObject({ + headSha: await sandbox.git(ahead.path!, "rev-parse", "HEAD"), + mainState: "ahead", + verdict: "Review", + }); + } finally { + await dashboard.close(); + } +}); diff --git a/tests/scan/follow-up.test.ts b/tests/scan/follow-up.test.ts new file mode 100644 index 0000000..b1cd9ba --- /dev/null +++ b/tests/scan/follow-up.test.ts @@ -0,0 +1,339 @@ +import { expect, test } from "bun:test"; +import fixture from "../fixtures/list-v2.json"; +import { createDashboardService, type RowPatch } from "../../src/core/scan/dashboard"; +import type { + CommandRunner, + DashboardService, + DashboardSnapshot, + SizeService, + WorktreeRow, +} from "../../src/core/types"; + +const sizeService: SizeService = { + load: async () => {}, + get: () => null, + measure: async () => null, + measureIfStale: async () => null, + close: async () => {}, +}; + +/** The fixture's listing, with the detached worktree's HEAD at `sha`. */ +function listing(sha = "ccc"): string { + return JSON.stringify({ + ...fixture, + items: fixture.items.map((item) => + item.branch === null ? { ...item, head: { ...item.head, sha } } : item, + ), + }); +} + +function runner(stdout: () => string = () => listing()): CommandRunner { + return async () => ({ stdout: stdout(), stderr: "", exitCode: 0 }); +} + +const detached = (rows: WorktreeRow[]) => rows.find((row) => row.branch === null)!; + +/** Proves the detached worktree merged, which only a follow-up can say about the fixture. */ +function merged(rows: WorktreeRow[], subject = "checked"): RowPatch[] { + const row = detached(rows); + return [ + { + id: row.id, + headSha: row.headSha!, + facts: { mainState: "integrated", integrationReason: "trees_match", subject }, + }, + ]; +} + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} + +function waitFor( + service: DashboardService, + predicate: (snapshot: DashboardSnapshot) => boolean, +): Promise { + return new Promise((resolve, reject) => { + let unsubscribe = () => {}; + const timer = setTimeout(() => { + unsubscribe(); + reject(new Error("snapshot timeout")); + }, 1000); + unsubscribe = service.subscribe((snapshot) => { + if (!predicate(snapshot)) return; + clearTimeout(timer); + queueMicrotask(unsubscribe); + resolve(snapshot); + }); + }); +} + +test("a follow-up's result arrives after the listing, patches its row and is published", async () => { + const held = deferred(); + const calls: Array<{ repo: string; rows: WorktreeRow[] }> = []; + const service = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/repo"], + followUp: (repo, rows) => { + calls.push({ repo, rows }); + return held.promise; + }, + }); + try { + await service.refresh(); + const listed = service.getSnapshot(); + expect(listed.progress.phase).toBe("complete"); + expect(listed.checking).toBe(1); + expect(detached(listed.rows).verdict).toBe("Review"); + expect(calls.map((call) => call.repo)).toEqual(["/repo"]); + expect(calls[0]!.rows).toEqual(listed.rows); + + held.resolve(merged(listed.rows)); + const patched = await waitFor(service, (snapshot) => snapshot.checking === 0); + expect(detached(patched.rows)).toMatchObject({ + subject: "checked", + mainState: "integrated", + verdict: "Safe", + }); + expect(patched.rows.filter((row) => row.branch !== null)).toEqual( + listed.rows.filter((row) => row.branch !== null), + ); + } finally { + await service.close(); + } +}); + +test("checking counts each repo's follow-up while it runs and returns to 0", async () => { + const held = new Map>>(); + const service = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/one", "/two"], + followUp: (repo) => { + const next = deferred(); + held.set(repo, next); + return next.promise; + }, + }); + const counts: number[] = []; + service.subscribe((snapshot) => counts.push(snapshot.checking)); + try { + await service.refresh(); + expect(service.getSnapshot().checking).toBe(2); + held.get("/one")!.resolve([]); + await waitFor(service, (snapshot) => snapshot.checking === 1); + held.get("/two")!.resolve([]); + await waitFor(service, (snapshot) => snapshot.checking === 0); + expect(counts).toContain(2); + expect(counts.at(-1)).toBe(0); + } finally { + await service.close(); + } +}); + +test("a patch lasts through later listings and rescans until a follow-up replaces it", async () => { + let answer: (rows: WorktreeRow[]) => Promise = async (rows) => merged(rows); + const service = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/repo"], + // Linked worktrees, so each scan lists them alone before the full listing. + readLinked: async () => ({ count: 2, paths: [], unread: [] }), + followUp: (_repo, rows) => answer(rows), + }); + try { + await service.refresh(); + await waitFor(service, (snapshot) => detached(snapshot.rows).subject === "checked"); + + const held = deferred(); + answer = () => held.promise; + const seen: DashboardSnapshot[] = []; + const unsubscribe = service.subscribe((snapshot) => seen.push(snapshot)); + await service.refresh(); + unsubscribe(); + const listings = seen.filter((snapshot) => snapshot.rows.length > 0); + expect(listings.length).toBeGreaterThan(1); + for (const snapshot of listings) + expect(detached(snapshot.rows)).toMatchObject({ subject: "checked", verdict: "Safe" }); + held.resolve([]); + await waitFor(service, (snapshot) => snapshot.checking === 0); + expect(detached(service.getSnapshot().rows).subject).toBe("checked"); + + answer = async (rows) => merged(rows, "checked again"); + await service.refresh(); + await waitFor(service, (snapshot) => detached(snapshot.rows).subject === "checked again"); + } finally { + await service.close(); + } +}); + +test("a patch does not apply once the row's HEAD has moved", async () => { + let sha = "ccc"; + let answer: (rows: WorktreeRow[]) => RowPatch[] = merged; + const service = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(() => listing(sha)), + sizeService, + discover: async () => ["/repo"], + followUp: async (_repo, rows) => answer(rows), + }); + try { + await service.refresh(); + await waitFor(service, (snapshot) => detached(snapshot.rows).subject === "checked"); + + sha = "ddd"; + answer = () => []; + await service.refresh(); + await waitFor(service, (snapshot) => snapshot.checking === 0); + expect(detached(service.getSnapshot().rows)).toMatchObject({ + headSha: "ddd", + subject: "detached", + mainState: "ahead", + verdict: "Review", + }); + } finally { + await service.close(); + } +}); + +test("a rescan aborts the follow-ups still running", async () => { + const signals: AbortSignal[] = []; + const service = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/repo"], + followUp: (_repo, _rows, signal) => { + signals.push(signal); + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason)); + }); + }, + }); + try { + await service.refresh(); + expect(signals[0]!.aborted).toBe(false); + const rescan = service.refresh(); + expect(signals[0]!.aborted).toBe(true); + await rescan; + expect(signals).toHaveLength(2); + expect(signals[1]!.aborted).toBe(false); + expect(service.getSnapshot().checking).toBe(1); + } finally { + await service.close(); + } +}); + +test("a result from a scan that a rescan replaced is dropped", async () => { + const held: Array>> = []; + const service = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/repo"], + // Ignores the abort, as a request that already answered would. + followUp: () => { + held.push(deferred()); + return held.at(-1)!.promise; + }, + }); + try { + await service.refresh(); + const rows = service.getSnapshot().rows; + await service.refresh(); + held[0]!.resolve(merged(rows)); + await waitFor(service, (snapshot) => snapshot.checking === 1); + expect(detached(service.getSnapshot().rows).subject).toBe("detached"); + held[1]!.resolve([]); + await waitFor(service, (snapshot) => snapshot.checking === 0); + expect(detached(service.getSnapshot().rows).subject).toBe("detached"); + } finally { + await service.close(); + } +}); + +test("close aborts the follow-ups still running", async () => { + let signal!: AbortSignal; + const service = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/repo"], + followUp: (_repo, _rows, given) => { + signal = given; + return new Promise(() => {}); + }, + }); + await service.refresh(); + expect(signal.aborted).toBe(false); + await service.close(); + expect(signal.aborted).toBe(true); +}); + +test("a follow-up that rejects leaves the rows as listed and the scan intact", async () => { + const plain = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/repo"], + }); + const failing = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/repo"], + followUp: async () => { + throw new Error("offline"); + }, + }); + try { + await plain.refresh(); + await failing.refresh(); + const snapshot = await waitFor(failing, (next) => next.checking === 0); + expect(snapshot.progress.phase).toBe("complete"); + expect(snapshot.errors).toEqual({}); + expect(snapshot.fatalError).toBeNull(); + expect(snapshot.rows).toEqual(plain.getSnapshot().rows); + } finally { + await plain.close(); + await failing.close(); + } +}); + +test("without a follow-up, every snapshot counts 0 checking", async () => { + const service = createDashboardService({ + projectRoot: "/projects", + wtPath: "/wt", + runner: runner(), + sizeService, + discover: async () => ["/repo"], + }); + const counts: number[] = []; + service.subscribe((snapshot) => counts.push(snapshot.checking)); + try { + await service.refresh(); + expect(counts.length).toBeGreaterThan(1); + expect(new Set(counts)).toEqual(new Set([0])); + } finally { + await service.close(); + } +}); diff --git a/tests/support/update.ts b/tests/support/update.ts index 561bf0e..492d54c 100644 --- a/tests/support/update.ts +++ b/tests/support/update.ts @@ -65,6 +65,7 @@ export function context(rows: WorktreeRow[], sizing: string[] = []): Context { errors: {}, fatalError: null, sizing, + checking: 0, processes: {}, progress: { phase: "complete", diff --git a/tests/terminal.test.ts b/tests/terminal.test.ts index 109b2f3..b3d93e2 100644 --- a/tests/terminal.test.ts +++ b/tests/terminal.test.ts @@ -100,6 +100,7 @@ function fakeService( errors: {}, fatalError: null, sizing: [], + checking: 0, processes: {}, }; let refreshes = 0; From 663091574bccf576ef2e60d4dffeecc17583702b Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 19:47:06 -0500 Subject: [PATCH 04/11] refactor: let assess settle rows with a forge proof --- src/core/assess.ts | 96 ++++++++++++-- src/core/scan/enrich.ts | 8 +- src/core/scan/orphans.ts | 5 +- src/core/types.ts | 44 +++++++ src/core/worktrunk/list.ts | 5 +- tests/assess.test.ts | 250 ++++++++++++++++++++++++++++++++++++- 6 files changed, 386 insertions(+), 22 deletions(-) diff --git a/src/core/assess.ts b/src/core/assess.ts index 698d131..dd8451f 100644 --- a/src/core/assess.ts +++ b/src/core/assess.ts @@ -1,4 +1,12 @@ -import type { OrphanCause, Verdict, WorktreeFacts } from "./types"; +import type { + ForgeCheck, + ForgeProofKind, + ForgeUncheckedReason, + OrphanCause, + Verdict, + WorktreeFacts, + WorktreeRow, +} from "./types"; export interface Assessment { /** A few words for the STATUS column. */ @@ -67,6 +75,59 @@ export function markerNote(facts: WorktreeFacts, now = Date.now()): string | nul return age === null ? `Marked ${facts.marker}.` : `Marked ${facts.marker} ${ago(age)}.`; } +const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** "Oct 30" in local time, with the year when it isn't the current one; null when the time can't be read. */ +function dayLabel(iso: string, now: number): string | null { + const date = new Date(iso); + if (Number.isNaN(date.getTime())) return null; + const day = `${months[date.getMonth()]} ${date.getDate()}`; + return date.getFullYear() === new Date(now).getFullYear() ? day : `${day}, ${date.getFullYear()}`; +} + +function prMerged(pr: number, mergedAt: string, now: number): string { + const day = dayLabel(mergedAt, now); + return day ? `PR #${pr} merged ${day}` : `PR #${pr} merged`; +} + +const provenEndings: Record = { + commit: " with this exact commit.", + tree: " with the same files.", + stacked: " and brought in this commit from a stacked pull request.", +}; + +const uncheckedNotes: Record = { + offline: "Not checked against GitHub: offline.", + "gh-missing": "Not checked against GitHub: gh isn't installed.", + "signed-out": "Not checked against GitHub: gh isn't signed in.", + // A repository that isn't on GitHub was never going to be checked, so its rows read as before. + "no-github-remote": null, + failed: "Not checked against GitHub: GitHub didn't answer.", +}; + +/** The row's forge check, or null when it has none or it answers for a commit that is no longer the tip. */ +function currentForge(facts: WorktreeFacts): ForgeCheck | null { + const forge = facts.forge; + if (!forge) return null; + if ((forge.kind === "proven" || forge.kind === "not-found") && forge.tip !== facts.headSha) + return null; + return forge; +} + +/** The sentence an unproven forge check adds to a Review reason, or null when it adds none. */ +function forgeNote(forge: Exclude, now: number): string | null { + switch (forge.kind) { + case "pending": + return "Checking GitHub…"; + case "unchecked": + return uncheckedNotes[forge.why]; + case "not-found": + return forge.samePr + ? `${prMerged(forge.samePr.number, forge.samePr.mergedAt, now)} without this commit.` + : "No merged pull request on GitHub has this commit."; + } +} + /** One authority for Git status, verdict, explanation, and removal eligibility. A recent agent mark turns Safe into Review. */ export function assess(facts: WorktreeFacts, now = Date.now()): Assessment { const git = assessGit(facts, now); @@ -173,6 +234,19 @@ function assessGit(facts: WorktreeFacts, now: number): Assessment { return result(status, "Review", `Created ${ago(age)}, so it may still be in use.`); return result(status, "Safe", reason); }; + // Squash merges often hide a merge from Worktrunk; a merged pull request holding the tip proves it. + const unmerged = (status: string, reason: string): Assessment => { + const forge = currentForge(facts); + if (forge?.kind === "proven") { + const proof = prMerged(forge.pr, forge.mergedAt, now) + provenEndings[forge.by]; + // Like Worktrunk's squash-merge proofs, a worktree is Safe at once and a branch without one waits a day. + return facts.kind === "branch" + ? safeOnceDayOld("merged on GitHub", proof) + : result("merged on GitHub", "Safe", proof); + } + const note = forge && forgeNote(forge, now); + return result(status, "Review", note ? `${reason} ${note}` : reason); + }; switch (state) { case "integrated": { if (facts.integrationReason === "same_commit") @@ -191,23 +265,20 @@ function assessGit(facts: WorktreeFacts, now: number): Assessment { case "empty": return safeOnceDayOld("no new commits", `No commits beyond ${base}.`); case "ahead": - return result("unmerged commits", "Review", `${commitsArent(facts.mainAhead)} in ${base}.`); + return unmerged("unmerged commits", `${commitsArent(facts.mainAhead)} in ${base}.`); case "would_conflict": - return result( + return unmerged( "unmerged commits", - "Review", `${commitsArent(facts.mainAhead)} in ${base}, and merging would conflict.`, ); case "diverged": - return result( + return unmerged( "unmerged commits", - "Review", `${commitsArent(facts.mainAhead)} in ${base}, which has also moved on.`, ); case "behind": - return result( + return unmerged( "behind main", - "Review", `${base} has moved ahead, and Worktrunk didn't confirm this branch is in it.`, ); case "orphan": @@ -233,6 +304,15 @@ function assessOrphan(cause: OrphanCause): Assessment { : orphaned("repository gone", `Its repository at ${cause.repo} no longer exists.`); } +/** The row with its verdict and reason recomputed from its facts. */ +export function assessRow( + row: T, + now = Date.now(), +): T & Pick { + const { verdict, reason } = assess(row, now); + return { ...row, verdict, reason }; +} + export function removalBlockReason(row: WorktreeFacts): string | null { return assess(row).removalBlockReason; } diff --git a/src/core/scan/enrich.ts b/src/core/scan/enrich.ts index 78fcf1f..d52e621 100644 --- a/src/core/scan/enrich.ts +++ b/src/core/scan/enrich.ts @@ -1,4 +1,4 @@ -import { assess } from "../assess"; +import { assessRow } from "../assess"; import { readBranchCreatedAt, readComparisonBase, readDescriptions } from "../git/refs"; import type { CommandRunner, WorktreeRow } from "../types"; import { readMarks } from "../worktrunk/list"; @@ -41,15 +41,13 @@ export async function enrichRows( // Worktrunk's JSON carries the marker only for worktrees; its state in Git config has it for every branch. const mark = row.branch ? marks.get(row.branch) : undefined; const marker = row.marker ?? mark?.marker ?? null; - const enriched: WorktreeRow = { + return assessRow({ ...row, mainBase: base, createdAt: created[index]!, marker, markerSetAt: mark && mark.marker === marker ? mark.setAt : null, description: (row.branch && descriptions.get(row.branch)) ?? null, - }; - const assessment = assess(enriched); - return { ...enriched, verdict: assessment.verdict, reason: assessment.reason }; + }); }); } diff --git a/src/core/scan/orphans.ts b/src/core/scan/orphans.ts index c15f74c..b68d6d5 100644 --- a/src/core/scan/orphans.ts +++ b/src/core/scan/orphans.ts @@ -1,6 +1,6 @@ import { lstat, readdir, readFile, realpath, stat } from "node:fs/promises"; import { basename, dirname, join, resolve } from "node:path"; -import { assess } from "../assess"; +import { assessRow } from "../assess"; import { ORPHANS, type OrphanCause, type WorktreeFacts, type WorktreeRow } from "../types"; import { toolForPath } from "../worktrunk/list"; import type { LinkedWorktrees } from "./discovery"; @@ -159,8 +159,7 @@ export function orphanRow({ path, cause }: Orphan): WorktreeRow { operation: null, orphan: cause, }; - const { verdict, reason } = assess(facts); - return { ...facts, sizeKiB: null, sizeMeasuredAt: null, verdict, reason }; + return assessRow({ ...facts, sizeKiB: null, sizeMeasuredAt: null }); } export function sameCause(a: OrphanCause | null | undefined, b: OrphanCause | null | undefined) { diff --git a/src/core/types.ts b/src/core/types.ts index 066eaee..0fbda94 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -45,6 +45,48 @@ export type OrphanCause = /** A Codex `` folder holding only `.codex-worktree-name`, with no worktree inside. */ | { kind: "emptyShell" }; +/** Why GitHub wasn't asked about a row's tip. `failed` means gh returned an error or timed out. */ +export type ForgeUncheckedReason = + | "offline" + | "gh-missing" + | "signed-out" + | "no-github-remote" + | "failed"; + +/** + * How a merged pull request holds the tip. `commit`: the tip is a commit of a PR merged into the default + * branch, possibly an earlier one than the PR's last. `tree`: the tip's tree equals the tree of a commit in + * such a PR. `stacked`: the tip is in a PR merged into another branch, which PR `pr` then merged into the + * default branch. + */ +export type ForgeProofKind = "commit" | "tree" | "stacked"; + +/** + * What GitHub says about whether the row's tip reached the default branch through a merged pull request. + * A `proven` or `not-found` answer counts only while its `tip` is still the row's `headSha`. + */ +export type ForgeCheck = + | { kind: "pending" } + | { kind: "unchecked"; why: ForgeUncheckedReason } + | { + kind: "proven"; + /** The 40-hex commit GitHub was asked about. */ + tip: string; + /** The pull request merged into the default branch. */ + pr: number; + /** When PR `pr` was merged, as an ISO 8601 time. */ + mergedAt: string; + /** The branch PR `pr` merged into. */ + base: string; + by: ForgeProofKind; + } + | { + kind: "not-found"; + tip: string; + /** A merged PR from a branch of the same name that doesn't hold the tip. */ + samePr?: { number: number; mergedAt: string }; + }; + export interface WorktreeFacts { id: string; kind: RowKind; @@ -87,6 +129,8 @@ export interface WorktreeFacts { operation: string | null; /** Set only on an orphan row. */ orphan?: OrphanCause; + /** GitHub's answer for the tip, consulted only when Worktrunk can't show the branch is merged. */ + forge?: ForgeCheck; } export interface WorktreeRow extends WorktreeFacts { diff --git a/src/core/worktrunk/list.ts b/src/core/worktrunk/list.ts index 5ab345c..49746bd 100644 --- a/src/core/worktrunk/list.ts +++ b/src/core/worktrunk/list.ts @@ -7,7 +7,7 @@ import type { WorktreeFacts, WorktreeRow, } from "../types"; -import { assess } from "../assess"; +import { assessRow } from "../assess"; /** `wt list` arguments for a repo's worktrees and, unless `branches` is false, its local branches without one. */ export function listArgs(repo: string, branches = true): string[] { @@ -184,8 +184,7 @@ export function parseWorktrunk(repoPath: string, stdout: string): WorktreeRow[] prunable: object(worktree?.prunable) !== null, operation: string(worktree?.operation), }; - const { verdict, reason } = assess(facts); - rows.push({ ...facts, sizeKiB: null, sizeMeasuredAt: null, verdict, reason }); + rows.push(assessRow({ ...facts, sizeKiB: null, sizeMeasuredAt: null })); } return rows; } diff --git a/tests/assess.test.ts b/tests/assess.test.ts index 80bc4ae..e4a000d 100644 --- a/tests/assess.test.ts +++ b/tests/assess.test.ts @@ -1,9 +1,15 @@ -import { describe, expect, test } from "bun:test"; -import { assess, markerNote, MIN_AGE_MS } from "../src/core/assess"; +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { assess, assessRow, markerNote, MIN_AGE_MS } from "../src/core/assess"; import { orphanRow } from "../src/core/scan/orphans"; import { parseWorktrunk } from "../src/core/worktrunk/list"; import fixture from "./fixtures/list-v2.json"; -import type { ChangeFlags, OrphanCause, WorktreeFacts } from "../src/core/types"; +import type { + ChangeFlags, + ForgeCheck, + OrphanCause, + WorktreeFacts, + WorktreeRow, +} from "../src/core/types"; const base = { ...parseWorktrunk("/repo", JSON.stringify(fixture))[0]!, @@ -348,3 +354,241 @@ test("an orphan is judged by its cause alone, whatever its Git fields or agent m assess({ ...row, prunable: true, marker: "🤖", markerSetAt: base.createdAt }, now), ).toEqual(assess(row, now)); }); + +// Merge dates read in local time. +const zone = process.env.TZ; +beforeAll(() => { + process.env.TZ = "UTC"; +}); +afterAll(() => { + process.env.TZ = zone; +}); + +describe("a forge check", () => { + const tip = "3f2c9a1e4b7d6c5a8f0e1d2c3b4a59687f6e5d4c"; + const mergedAt = "2026-10-27T15:00:00Z"; + const unmerged: Partial = { + headSha: tip, + mainAhead: 2, + integrationReason: null, + createdAt: createdBefore(60_000), + }; + const proven = ( + by: "commit" | "tree" | "stacked", + update: { tip?: string; mergedAt?: string } = {}, + ): ForgeCheck => ({ kind: "proven", tip, pr: 60, mergedAt, base: "main", by, ...update }); + const forged = (forge: ForgeCheck | undefined, update: Partial = {}) => + assess({ ...base, ...unmerged, mainState: "ahead", ...update, forge }, now); + + const states = [ + ["ahead", "unmerged commits", "2 commits aren't in origin/main."], + [ + "would_conflict", + "unmerged commits", + "2 commits aren't in origin/main, and merging would conflict.", + ], + ["diverged", "unmerged commits", "2 commits aren't in origin/main, which has also moved on."], + [ + "behind", + "behind main", + "origin/main has moved ahead, and Worktrunk didn't confirm this branch is in it.", + ], + ] as const; + const unproven: [string, ForgeCheck | undefined, string | null][] = [ + ["absent", undefined, null], + ["pending", { kind: "pending" }, "Checking GitHub…"], + ["offline", { kind: "unchecked", why: "offline" }, "Not checked against GitHub: offline."], + [ + "gh-missing", + { kind: "unchecked", why: "gh-missing" }, + "Not checked against GitHub: gh isn't installed.", + ], + [ + "signed-out", + { kind: "unchecked", why: "signed-out" }, + "Not checked against GitHub: gh isn't signed in.", + ], + ["no-github-remote", { kind: "unchecked", why: "no-github-remote" }, null], + [ + "failed", + { kind: "unchecked", why: "failed" }, + "Not checked against GitHub: GitHub didn't answer.", + ], + ["not-found", { kind: "not-found", tip }, "No merged pull request on GitHub has this commit."], + [ + "not-found with a same-named PR", + { kind: "not-found", tip, samePr: { number: 27, mergedAt: "2026-10-26T09:00:00Z" } }, + "PR #27 merged Oct 26 without this commit.", + ], + ]; + + describe.each(states)("on a %s worktree", (mainState, status, first) => { + test.each(unproven)("%s keeps it in Review", (_label, forge, note) => { + expect(forged(forge, { mainState })).toEqual({ + status, + verdict: "Review", + reason: note ? `${first} ${note}` : first, + removalBlockReason: null, + }); + }); + + test.each([ + ["commit", "PR #60 merged Oct 27 with this exact commit."], + ["tree", "PR #60 merged Oct 27 with the same files."], + ["stacked", "PR #60 merged Oct 27 and brought in this commit from a stacked pull request."], + ] as const)("proven by %s makes it Safe", (by, reason) => { + expect(forged(proven(by), { mainState })).toEqual({ + status: "merged on GitHub", + verdict: "Safe", + reason, + removalBlockReason: null, + }); + }); + }); + + test("a proven worktree is Safe at any age", () => { + for (const createdAt of [createdBefore(60_000), createdBefore(MIN_AGE_MS), null]) + expect(forged(proven("commit"), { createdAt }).verdict).toBe("Safe"); + }); + + test("a proven branch without a worktree is Safe only once a day old", () => { + const at = (createdAt: string | null) => + assess( + { ...leftover, ...unmerged, mainState: "diverged", createdAt, forge: proven("tree") }, + now, + ); + expect(at(createdBefore(MIN_AGE_MS))).toEqual({ + status: "merged on GitHub", + verdict: "Safe", + reason: "PR #60 merged Oct 27 with the same files.", + removalBlockReason: null, + }); + expect(at(createdBefore(2 * 3_600_000))).toEqual({ + status: "merged on GitHub", + verdict: "Review", + reason: "Created 2h ago, so it may still be in use.", + removalBlockReason: null, + }); + expect([at(null).verdict, at(null).reason]).toEqual([ + "Review", + "Its creation time is unknown, so it may still be in use.", + ]); + }); + + test("a recent agent mark turns a proven row back into Review", () => { + const worktree = forged(proven("commit"), marked("🤖", 20 * 60_000)); + expect([worktree.status, worktree.verdict, worktree.reason]).toEqual([ + "merged on GitHub", + "Review", + "An agent was working here 20m ago.", + ]); + const branchRow = assess( + { + ...leftover, + ...unmerged, + ...marked("💬", null), + createdAt: createdBefore(MIN_AGE_MS), + forge: proven("commit"), + }, + now, + ); + expect([branchRow.verdict, branchRow.reason]).toEqual([ + "Review", + "An agent was waiting for input here; when is unknown.", + ]); + expect(forged(proven("commit"), marked("🤖", 2 * MIN_AGE_MS)).verdict).toBe("Safe"); + }); + + test.each([ + ["uncommitted changes", { changes: { ...base.changes!, modified: true } }], + ["unpushed commits", { upstreamAhead: 1 }], + ["locked", { locked: true, lockReason: "manual" }], + ["rebase in progress", { operation: "rebase" }], + ["unresolved conflicts", { changes: { ...base.changes!, conflicted: true } }], + ["folder missing", { prunable: true }], + ] as const)("%s outranks a proven check", (status, update) => { + const result = forged(proven("commit"), update); + expect(result.status).toBe(status); + expect(result).toEqual(forged(undefined, update)); + }); + + test.each(["integrated", "empty", "same_commit", "orphan", null])( + "a %p main state ignores the forge check", + (mainState) => { + for (const forge of [proven("commit"), { kind: "not-found", tip } as const]) + expect(forged(forge, { mainState })).toEqual(forged(undefined, { mainState })); + }, + ); + + test("a check about another commit is ignored", () => { + const other = "0".repeat(40); + expect(forged(proven("commit", { tip: other }))).toEqual(forged(undefined)); + expect(forged({ kind: "not-found", tip: other })).toEqual(forged(undefined)); + expect(forged(proven("commit"), { headSha: null })).toEqual( + forged(undefined, { headSha: null }), + ); + }); + + test("dates read in local time, with the year when it isn't this one", () => { + expect(forged(proven("commit", { mergedAt: "2025-12-30T10:00:00Z" })).reason).toBe( + "PR #60 merged Dec 30, 2025 with this exact commit.", + ); + expect(forged(proven("commit", { mergedAt: "not a date" })).reason).toBe( + "PR #60 merged with this exact commit.", + ); + process.env.TZ = "Asia/Tokyo"; + try { + expect(forged(proven("commit", { mergedAt: "2026-10-27T20:00:00Z" })).reason).toBe( + "PR #60 merged Oct 28 with this exact commit.", + ); + } finally { + process.env.TZ = "UTC"; + } + }); +}); + +describe("assessRow", () => { + const tip = "3f2c9a1e4b7d6c5a8f0e1d2c3b4a59687f6e5d4c"; + const row: WorktreeRow = { + ...base, + headSha: tip, + mainState: "ahead", + mainAhead: 1, + sizeKiB: 2048, + sizeMeasuredAt: "2026-10-28T11:00:00Z", + verdict: "Review", + reason: "1 commit isn't in origin/main.", + }; + + test("recomputes the verdict and reason from the facts and keeps the rest", () => { + const pending = { ...row, forge: { kind: "pending" } as const }; + expect(assessRow(pending, now)).toEqual({ + ...pending, + reason: "1 commit isn't in origin/main. Checking GitHub…", + }); + expect(pending.reason).toBe("1 commit isn't in origin/main."); + }); + + test("settles a row once a forge proof arrives", () => { + const forge: ForgeCheck = { + kind: "proven", + tip, + pr: 60, + mergedAt: "2026-10-27T15:00:00Z", + base: "main", + by: "commit", + }; + expect(assessRow({ ...row, forge }, now)).toEqual({ + ...row, + forge, + verdict: "Safe", + reason: "PR #60 merged Oct 27 with this exact commit.", + }); + }); + + test("gives facts without a row the verdict and reason assess gives them", () => { + const facts: WorktreeFacts = { ...base, mainState: "diverged" }; + const { verdict, reason } = assess(facts, now); + expect(assessRow(facts, now)).toEqual({ ...facts, verdict, reason }); + }); +}); From e50902232c76953e7d0671f7d4a3c58231ac66c3 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 19:49:04 -0500 Subject: [PATCH 05/11] refactor: settle patched rows through assessRow --- src/core/scan/dashboard.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/core/scan/dashboard.ts b/src/core/scan/dashboard.ts index b6d29ad..0cee12e 100644 --- a/src/core/scan/dashboard.ts +++ b/src/core/scan/dashboard.ts @@ -1,4 +1,4 @@ -import { assess } from "../assess"; +import { assessRow } from "../assess"; import { listArgs, parseWorktrunk, SchemaMismatchError } from "../worktrunk/list"; import { discoverRepos, readLinkedWorktrees, type LinkedWorktrees } from "./discovery"; import { enrichRows } from "./enrich"; @@ -109,9 +109,7 @@ export function createDashboardService(options: DashboardOptions): DashboardServ return rows.map((row) => { const patch = patches.get(row.id); if (!patch || patch.headSha !== row.headSha) return row; - const patched = { ...row, ...patch.facts }; - const { verdict, reason } = assess(patched); - return { ...patched, verdict, reason }; + return assessRow({ ...row, ...patch.facts }); }); } From 48ca2dd30d246367b904af5eb61e99dfd76ba4a4 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 19:58:32 -0500 Subject: [PATCH 06/11] test: fake gh and a GitHub remote in the sandbox --- .claude/skills/verify-wt-dash/SKILL.md | 2 +- CONTRIBUTING.md | 2 +- tests/integration/github.test.ts | 189 +++++++ tests/support/fixture.ts | 354 ++++++++++++- tests/support/gh-cli.ts | 26 + tests/support/gh.test.ts | 364 +++++++++++++ tests/support/gh.ts | 676 +++++++++++++++++++++++++ 7 files changed, 1602 insertions(+), 11 deletions(-) create mode 100644 tests/integration/github.test.ts create mode 100644 tests/support/gh-cli.ts create mode 100644 tests/support/gh.test.ts create mode 100644 tests/support/gh.ts diff --git a/.claude/skills/verify-wt-dash/SKILL.md b/.claude/skills/verify-wt-dash/SKILL.md index f81298a..2a66d1d 100644 --- a/.claude/skills/verify-wt-dash/SKILL.md +++ b/.claude/skills/verify-wt-dash/SKILL.md @@ -21,7 +21,7 @@ Every stack command prints one JSON object, `{"ok":true,...}` or `{"ok":false,"e An instance is a name (1–24 of `a-z0-9-`; use one per task, such as the branch topic) and everything under `.verify//` (gitignored): -- `sandbox/`: its own HOME (so its own `~/.cache/wt-dash/sizes.json` and `removals.log`), Git config, Worktrunk config (`WORKTRUNK_CONFIG_PATH` and friends), the scan root `sandbox/projects/` with the seeded repos, and their worktrees in `sandbox/worktrees/`. +- `sandbox/`: its own HOME (so its own `~/.cache/wt-dash/sizes.json` and `removals.log`), Git config, Worktrunk config (`WORKTRUNK_CONFIG_PATH` and friends), the scan root `sandbox/projects/` with the seeded repos, and their worktrees in `sandbox/worktrees/`. Its PATH has no real `gh`: `gh` is the fake from `tests/support/gh.ts`, answering from `sandbox/gh/state.json` and logging to `sandbox/gh/calls.jsonl`, so after the `eval` of `env` → `exports`, run your own `gh` in another shell call. - A tmux server on its own socket, `tmux -L wt-dash-verify--`, holding one session, `app`, running `bun src/index.ts sandbox/projects` from this checkout with the instance env. The hash keeps the same name in two checkouts apart; `env` prints the exact socket. - `logs/` (`app.log` is the app's stderr, `stack.log` every up/down) and `evidence/`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 56b68c9..a273610 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,7 +25,7 @@ Title pull requests with [Conventional Commits](https://www.conventionalcommits. Keep the Git assessment and cleanup rules in `src/core`, and terminal interaction in `src/ui`. `src/core` has no terminal dependency, so another interface can reuse its data and rules. For cleanup changes, cover stale confirmations, locks, unfinished Git operations, local changes, and branch retention. Tests must use temporary repositories and never remove the contributor's own worktrees. -Tests come in three layers. Module tests check one module with Git and Worktrunk faked, and follow the source layout: `tests/.test.ts` for a file directly in `src`, `src/core` or `src/ui`, and `tests//` for a folder such as `src/core/removal` or `src/ui/update`. `tests/integration` runs the real services from `src/app.ts` against real Git and Worktrunk in a sandbox from `tests/support/fixture.ts`, which builds a worktree or branch in each state the dashboard tells apart. `tests/e2e` drives the real terminal UI on those services with key presses and checks the rendered text and what happened on disk. A change that crosses a boundary (Worktrunk output, a service the UI calls, what a removal does) needs an integration or end-to-end test, because a faked boundary is where earlier regressions hid. A bug fix adds a test, named for its pull request, that fails without the fix. +Tests come in three layers. Module tests check one module with Git and Worktrunk faked, and follow the source layout: `tests/.test.ts` for a file directly in `src`, `src/core` or `src/ui`, and `tests//` for a folder such as `src/core/removal` or `src/ui/update`. `tests/integration` runs the real services from `src/app.ts` against real Git and Worktrunk in a sandbox from `tests/support/fixture.ts`, which builds a worktree or branch in each state the dashboard tells apart. The sandbox's PATH has no real `gh`; `tests/support/gh.ts` is a fake GitHub CLI that answers from a model the fixture writes, and `repo(name, { github: true })` gives a repository a github.com `origin` served from a local bare repository. `tests/e2e` drives the real terminal UI on those services with key presses and checks the rendered text and what happened on disk. A change that crosses a boundary (Worktrunk output, a service the UI calls, what a removal does) needs an integration or end-to-end test, because a faked boundary is where earlier regressions hid. A bug fix adds a test, named for its pull request, that fails without the fix. ## Continuous integration diff --git a/tests/integration/github.test.ts b/tests/integration/github.test.ts new file mode 100644 index 0000000..6d7770e --- /dev/null +++ b/tests/integration/github.test.ts @@ -0,0 +1,189 @@ +import { afterAll, beforeAll, expect, setDefaultTimeout, test } from "bun:test"; +import { assess } from "../../src/core/assess"; +import { + createSandbox, + type Built, + type Repo, + type Sandbox, + TEST_TIMEOUT, +} from "../support/fixture"; +import { chainedQuery, GH_ENV, graphqlArgs, lookupQuery } from "../support/gh"; +import { row, scan } from "./helpers"; + +setDefaultTimeout(TEST_TIMEOUT); + +let sandbox: Sandbox; +let hub: Repo; +let built: Record<"merged" | "branch" | "earlier" | "treeMatch" | "missing" | "stacked", Built>; + +beforeAll(async () => { + sandbox = await createSandbox(); + hub = await sandbox.repo("hub", { github: true }); + // Each merges into main, so they run one after another. + built = { + merged: await hub.prMergedWorktree("feature/merged"), + branch: await hub.prMergedBranch("leftover/merged"), + earlier: await hub.prMergedEarlierCommit("feature/earlier"), + treeMatch: await hub.prTreeMatch("feature/rebased"), + missing: await hub.prMissingCommit("feature/missing"), + stacked: await hub.prStacked("feature/top", { base: "feature/bottom" }), + }; +}, 60_000); + +afterAll(() => sandbox?.cleanup()); + +test("Worktrunk sees a GitHub forge in the fixture's origin, which Git serves from a local bare repo", async () => { + const listed = JSON.parse( + await sandbox.wt( + hub.path, + "--config-set", + "list.json-schema=2", + "list", + "--branches", + "--format=json", + ), + ) as { + repo: { forge?: Record }; + items: Array<{ branch: string; upstream?: unknown }>; + }; + expect(listed.repo.forge).toEqual({ + url: "https://github.com/acme/hub", + provider: "github", + host: "github.com", + owner: "acme", + name: "hub", + remote: "origin", + }); + expect(await hub.git("config", "remote.origin.url")).toBe("https://github.com/acme/hub.git"); + expect(await hub.git("rev-parse", "--abbrev-ref", "main@{upstream}")).toBe("origin/main"); + expect(await hub.git("rev-parse", "origin/main")).toBe(await hub.git("rev-parse", "main")); + expect(await sandbox.git(hub.github!.bare, "rev-parse", "main")).toBe( + await hub.git("rev-parse", "main"), + ); + // GitHub deleted each merged branch, so none has an upstream left. + expect(listed.items.filter((item) => item.upstream).map((item) => item.branch)).toEqual(["main"]); + // Listing never runs gh, so the fake's log holds only the app's calls. + expect(await sandbox.gh.calls()).toEqual([]); +}); + +test("today every pr… row is Review: Worktrunk finds no integration, and only GitHub can tell", async () => { + const { dashboard } = await sandbox.services(); + const snapshot = await scan(dashboard, hub); + for (const [name, expected] of Object.entries(built)) { + const shown = row(snapshot, expected); + expect({ name, kind: shown.kind, path: shown.path }).toEqual({ + name, + kind: expected.kind, + path: expected.path, + }); + expect({ + name, + verdict: shown.verdict, + status: assess(shown).status, + reason: shown.reason, + integration: shown.integrationReason, + unproven: ["would_conflict", "diverged"].includes(shown.mainState ?? ""), + }).toEqual({ + name, + verdict: "Review", + status: expected.expected.status, + reason: expected.expected.reason, + integration: null, + unproven: true, + }); + } + expect( + Object.fromEntries(Object.entries(built).map(([name, { github }]) => [name, github?.verdict])), + ).toEqual({ + merged: "Safe", + branch: "Safe", + earlier: "Safe", + treeMatch: "Safe", + missing: "Review", + stacked: "Safe", + }); + expect(await sandbox.gh.calls()).toEqual([]); +}); + +interface Answer { + data: { + repository: Record< + string, + { + associatedPullRequests?: { + nodes: Array<{ number: number; headRefOid: string; baseRefName: string }>; + }; + nodes?: Array<{ + number: number; + commits: { nodes: Array<{ commit: { oid: string; tree?: { oid: string } } }> }; + }>; + } | null + >; + }; +} + +async function ask(args: string[]): Promise { + const result = await sandbox.exec("gh", args, { env: GH_ENV }); + expect({ exitCode: result.exitCode, stderr: result.stderr }).toEqual({ exitCode: 0, stderr: "" }); + return (JSON.parse(result.stdout) as Answer).data.repository; +} + +test("the fake GitHub holds what each builder's Git implies", async () => { + const { dashboard } = await sandbox.services(); + const snapshot = await scan(dashboard, hub); + const order = Object.keys(built) as Array; + const tips = order.map((name) => row(snapshot, built[name]).headSha!); + const trees = await Promise.all(tips.map((tip) => hub.git("rev-parse", `${tip}^{tree}`))); + const answer = await ask( + graphqlArgs(lookupQuery(order.length, order.length), { + owner: "acme", + name: "hub", + ...Object.fromEntries(tips.map((tip, index) => [`oid${index}`, tip])), + ...Object.fromEntries(order.map((name, index) => [`head${index}`, built[name].branch])), + }), + ); + const at = (name: keyof typeof built) => order.indexOf(name); + const associated = (name: keyof typeof built) => + answer[`a${at(name)}`]?.associatedPullRequests?.nodes.map( + ({ number, headRefOid, baseRefName }) => ({ + number, + tipIsHead: headRefOid === tips[at(name)], + baseRefName, + }), + ) ?? null; + const fromHead = (name: keyof typeof built) => + answer[`b${at(name)}`]!.nodes!.map(({ number, commits }) => ({ + number, + hasTip: commits.nodes.some(({ commit }) => commit.oid === tips[at(name)]), + hasTree: commits.nodes.some(({ commit }) => commit.tree?.oid === trees[at(name)]), + })); + const [merged, branch, earlier, treeMatch, missing] = order.map( + (name) => built[name].github!.pullRequests[0]!, + ); + const [intoBase, intoMain] = built.stacked.github!.pullRequests; + + expect(associated("merged")).toEqual([{ number: merged, tipIsHead: true, baseRefName: "main" }]); + expect(associated("branch")).toEqual([{ number: branch, tipIsHead: true, baseRefName: "main" }]); + expect(associated("earlier")).toEqual([ + { number: earlier, tipIsHead: false, baseRefName: "main" }, + ]); + // Rebased here: GitHub doesn't have the tip, but a merged commit from the branch has its files. + expect(associated("treeMatch")).toBeNull(); + expect(fromHead("treeMatch")).toEqual([{ number: treeMatch, hasTip: false, hasTree: true }]); + // Committed after the merge: neither the tip nor its files are on GitHub. + expect(associated("missing")).toBeNull(); + expect(fromHead("missing")).toEqual([{ number: missing, hasTip: false, hasTree: false }]); + // Stacked: merged into feature/bottom, which a later pull request merged into main. + expect(associated("stacked")).toEqual([ + { number: intoBase!, tipIsHead: true, baseRefName: "feature/bottom" }, + ]); + const chained = await ask( + graphqlArgs(chainedQuery(1), { + owner: "acme", + name: "hub", + default: "main", + base0: "feature/bottom", + }), + ); + expect(chained.k0!.nodes!.map(({ number }) => number)).toEqual([intoMain!]); +}); diff --git a/tests/support/fixture.ts b/tests/support/fixture.ts index c658a43..724f8dc 100644 --- a/tests/support/fixture.ts +++ b/tests/support/fixture.ts @@ -1,7 +1,19 @@ import { randomBytes } from "node:crypto"; -import { mkdir, mkdtemp, readFile, realpath, rm, stat, utimes, writeFile } from "node:fs/promises"; +import { + lstat, + mkdir, + mkdtemp, + readdir, + readFile, + realpath, + rm, + stat, + symlink, + utimes, + writeFile, +} from "node:fs/promises"; import { tmpdir } from "node:os"; -import { delimiter, dirname, join, resolve, sep } from "node:path"; +import { delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path"; import { createServices } from "../../src/app"; import type { ActionService } from "../../src/core/removal/types"; import { discoverRepos, readCreatedAt, type RepoSource } from "../../src/core/scan/discovery"; @@ -14,6 +26,7 @@ import type { Verdict, WorktreeRow, } from "../../src/core/types"; +import { createFakeGh, type FakeGh, GH_LOG_ENV, GH_STATE_ENV, type GhCommit } from "./gh"; const DAY_MS = 24 * 60 * 60 * 1000; /** How old builders make anything that must be older than a day, unless told otherwise. */ @@ -44,6 +57,29 @@ export interface Built { expected: Expected; /** KiB written into the worktree, for `sizedWorktree`; `du` reports at least this. */ minSizeKiB?: number; + /** For the `pr…` builders: the pull requests recorded in the fake GitHub, and the verdict once it's asked. */ + github?: GitHubExpected; +} + +/** What the fake GitHub holds for a built row, and how the dashboard should judge the row once it asks. */ +export interface GitHubExpected { + /** The merged pull requests the builder recorded, in merge order. */ + pullRequests: number[]; + /** Safe when GitHub shows the row's tip merged into the default branch; Review when it doesn't. */ + verdict: Verdict; +} + +/** The owner of every fixture repo given a GitHub remote. */ +export const GITHUB_OWNER = "acme"; + +/** A repo's `origin`: a github.com URL that Git rewrites to a local bare repo with `url..insteadOf`. */ +export interface GitHubRemote { + owner: string; + name: string; + /** `https://github.com//.git`, what Worktrunk and `git config remote.origin.url` see. */ + url: string; + /** The bare repository Git fetches from and pushes to. */ + bare: string; } export interface ExecOptions { @@ -103,6 +139,33 @@ export interface Repo { mergedBranch(branch: string, options?: { ageMs?: number }): Promise; /** A branch with a commit not in main whose worktree was removed: Review. */ unmergedBranch(branch: string): Promise; + /** The GitHub `origin` from `repo(name, { github: true })`, or null. */ + github: GitHubRemote | null; + /* + * The `pr…` builders need the GitHub remote. Each pushes its branch, merges a pull request on the fake + * GitHub the way GitHub's squash merge does, pushes main, and deletes the remote branch, leaving its + * upstream gone. Main moves a line near the change while the pull request is open, and changes the branch's + * line again after the merge, so Worktrunk shows unmerged commits that would conflict and finds no + * integration: Review. Only GitHub can tell; `github.verdict` is the verdict once the dashboard asks it. + */ + /** A worktree whose tip GitHub squash-merged into main: Safe once GitHub is asked. */ + prMergedWorktree(branch: string): Promise; + /** A branch, its worktree removed, created `ageMs` ago, whose tip GitHub squash-merged: Safe once asked. */ + prMergedBranch(branch: string, options?: { ageMs?: number }): Promise; + /** A worktree whose tip is an earlier commit of a merged pull request that got one more: Safe once asked. */ + prMergedEarlierCommit(branch: string): Promise; + /** + * A worktree rebased here after its pull request was rebased on GitHub too, so GitHub lacks the tip but a + * merged commit has the same tree: Safe once asked. + */ + prTreeMatch(branch: string): Promise; + /** A worktree with a commit made after its pull request merged, which GitHub lacks: still Review. */ + prMissingCommit(branch: string): Promise; + /** + * A worktree whose tip was squash-merged into `base` by one pull request, then `base` into main by a + * second; `base` has a commit of its own and no local branch. Safe once asked. + */ + prStacked(branch: string, options?: { base?: string }): Promise; } export interface Sandbox { @@ -110,8 +173,13 @@ export interface Sandbox { home: string; /** Where repositories live; pass it to the dashboard as the project root. */ scanRoot: string; - /** The complete environment commands run with; only PATH comes from process.env, with wt's folder first. */ + /** + * The complete environment commands run with. Only PATH comes from process.env: wt's folder first, then + * the developer's PATH without the real `gh`, and the fake `gh` before both unless it's missing. + */ env: Record; + /** The fake GitHub CLI and the GitHub it answers from. */ + gh: FakeGh; wtPath: string; /** `/.cache/wt-dash`, where the app keeps sizes.json and removals.log. */ cacheDir: string; @@ -132,8 +200,12 @@ export interface Sandbox { git(cwd: string, ...args: string[]): Promise; /** Runs Worktrunk in `cwd` and returns trimmed stdout; throws on a non-zero exit. */ wt(cwd: string, ...args: string[]): Promise; - /** Creates `/` with one commit on main. */ - repo(name: string): Promise; + /** + * Creates `/` with one commit on main. `github` adds an `origin` at + * `https://github.com/acme/.git` that Git rewrites to a local bare repo, pushes main to it with main + * tracking `origin/main`, and adds the repo to the fake GitHub. + */ + repo(name: string, options?: { github?: boolean }): Promise; /** * Dashboard, action and size services on the sandbox; `cleanup` closes any still open. `runner` replaces the * sandbox runner, for wrappers from tests/support/runners.ts. `sources` replaces the scan root. @@ -213,12 +285,42 @@ async function birthMovesWithMtime(root: string): Promise { return Math.abs(birthtimeMs - old.getTime()) < 1000; } +const isGh = (name: string) => name.toLowerCase() === "gh"; + +/** + * `folders`, in order and without repeats, with no `gh` in any: each folder holding one is replaced by a folder + * under `root` of links to everything else in it. Every other tool resolves as before, wherever it's installed + * (on GitHub's Linux runners `gh` sits in /usr/bin beside everything else). Empty and relative entries, which + * name the working folder, are dropped. + */ +async function withoutGh(folders: string[], root: string): Promise { + const out: string[] = []; + for (const folder of new Set(folders)) { + if (!isAbsolute(folder)) continue; + // lstat finds a broken link too, and matches a "GH" on a case-insensitive file system as exec would. + const hasGh = await lstat(join(folder, "gh")).then( + () => true, + () => false, + ); + if (!hasGh) { + out.push(folder); + continue; + } + const mirror = join(root, "path", String(out.length)); + await mkdir(mirror, { recursive: true }); + const names = (await readdir(folder)).filter((name) => !isGh(name)); + await Promise.all(names.map((name) => symlink(join(folder, name), join(mirror, name)))); + out.push(mirror); + } + return out; +} + /** * Creates an isolated world in a fresh temp folder, or in `root`, which must not exist yet. Call `cleanup` when - * done. + * done. `gh` puts the fake GitHub CLI on PATH (the default) or leaves PATH with no `gh` at all. */ export async function createSandbox( - options: { wtPath?: string; root?: string } = {}, + options: { wtPath?: string; root?: string; gh?: "fake" | "missing" } = {}, ): Promise { const wtPath = options.wtPath ?? resolveWtPath(); if (!Bun.which("git")) throw new Error("Git was not found on PATH."); @@ -234,7 +336,8 @@ export async function createSandbox( const config = join(home, ".config"); const template = join(root, "git-template"); const env: Record = { - PATH: [dirname(wtPath), process.env.PATH ?? "/usr/bin:/bin"].join(delimiter), + // Set once the sandbox folder exists. + PATH: "", HOME: home, TMPDIR: join(root, "tmp"), LC_ALL: "C", @@ -255,7 +358,16 @@ export async function createSandbox( WORKTRUNK_APPROVALS_PATH: join(config, "worktrunk", "approvals.toml"), }; let backdatesOnDisk: boolean; + let gh: FakeGh; try { + gh = await createFakeGh(join(root, "gh"), options.gh !== "missing"); + const developerPath = (process.env.PATH ?? "/usr/bin:/bin").split(delimiter); + env.PATH = [ + ...(gh.installed ? [gh.bin] : []), + ...(await withoutGh([dirname(wtPath), ...developerPath], root)), + ].join(delimiter); + env[GH_STATE_ENV] = gh.statePath; + env[GH_LOG_ENV] = gh.logPath; for (const folder of [home, scanRoot, worktrees, template, join(root, "tmp")]) await mkdir(folder, { recursive: true }); await mkdir(join(config, "worktrunk"), { recursive: true }); @@ -324,7 +436,7 @@ export async function createSandbox( return new Date(forced).toISOString(); } - async function repo(name: string): Promise { + async function repo(name: string, { github = false } = {}): Promise { const path = join(scanRoot, name); await git(scanRoot, "init", "-q", path); repos.push(path); @@ -333,7 +445,23 @@ export async function createSandbox( await writeFile(join(path, ".git", "info", "exclude"), "node_modules/\ndist/\n"); await git(path, "add", "README.md"); await git(path, "commit", "-q", "-m", "Initial commit"); + let remote: GitHubRemote | null = null; + if (github) { + remote = { + owner: GITHUB_OWNER, + name, + url: `https://github.com/${GITHUB_OWNER}/${name}.git`, + bare: join(root, "remotes", `${name}.git`), + }; + await git(root, "init", "-q", "--bare", remote.bare); + await git(path, "remote", "add", "origin", remote.url); + await git(path, "config", `url.${remote.bare}.insteadOf`, remote.url); + await git(path, "push", "-q", "-u", "origin", "main"); + await git(path, "remote", "set-head", "origin", "main"); + await gh.addRepo(remote.owner, remote.name, "main"); + } let pinnedBy: string | null = null; + let pullRequests = 0; const dated = (ageMs: number): Record => { const date = `@${Math.floor((Date.now() - ageMs) / 1000)} +0000`; @@ -400,9 +528,98 @@ export async function createSandbox( } const squashReason = "Merging it into main would change nothing."; + // The `pr…` builders' file: nine numbered lines. The branch changes CHANGED and main moves NEAR, which is + // inside the diff's context but leaves a line between them, so Git merges the two without a conflict. + const CHANGED = 6; + const NEAR = 4; + const toGitHub = (builder: string): GitHubRemote => { + if (!remote) + throw new Error( + `${name}: ${builder} needs a GitHub remote; make the repo with { github: true }`, + ); + return remote; + }; + async function editLine( + cwd: string, + file: string, + line: number, + text: string, + env?: Record, + ) { + const lines = (await readFile(join(cwd, file), "utf8")).split("\n"); + lines[line - 1] = text; + await commit(cwd, file, lines.join("\n"), env); + } + const head = (cwd: string) => git(cwd, "rev-parse", "HEAD"); + const described = (oids: string[]): Promise => + Promise.all( + oids.map(async (oid) => ({ oid, tree: await git(path, "rev-parse", `${oid}^{tree}`) })), + ); + async function pullRequestFile(branch: string): Promise { + const file = `${slug(branch)}.pr.txt`; + const lines = Array.from({ length: 9 }, (_, index) => `line ${index + 1}`); + await commit(path, file, `${lines.join("\n")}\n`); + return file; + } + /** Adds the builder's file to main, then a worktree whose one commit changes it, pushed with upstream. */ + async function pullRequestBranch(branch: string, env?: Record) { + const file = await pullRequestFile(branch); + const worktree = await add(branch, env); + await editLine(worktree, file, CHANGED, branch, env); + await check("git", ["push", "-q", "-u", "origin", branch], { cwd: worktree, env }); + return { file, worktree, tip: await head(worktree) }; + } + /** + * Merges `pr.head` into main as GitHub's squash merge does, records the pull request, pushes main and + * deletes the remote branch, as GitHub does after a merge, and returns its number. + */ + async function mergePullRequest( + file: string, + pr: { headRefName: string; head: string; commits: string[] }, + ): Promise { + const github = toGitHub("mergePullRequest"); + const number = ++pullRequests; + // Main moves on near the change while the pull request is open, so the squash's patch differs. + await editLine(path, file, NEAR, `main moved during #${number}`); + const tree = (await git(path, "merge-tree", "--write-tree", "main", pr.head)).split("\n")[0]!; + const squash = await git( + path, + "commit-tree", + tree, + "-p", + "main", + "-m", + `${pr.headRefName} (#${number})`, + ); + await git(path, "merge", "-q", "--ff-only", squash); + // And changes the same line afterwards, so merging the branch would conflict. + await editLine(path, file, CHANGED, `changed again after #${number}`); + await git(path, "push", "-q", "origin", "main"); + await gh.addPullRequest(github.owner, github.name, { + number, + mergedAt: new Date().toISOString(), + base: "main", + headRefName: pr.headRefName, + headRefOid: pr.head, + commits: await described(pr.commits), + }); + await git(path, "push", "-q", "origin", "--delete", pr.headRefName); + await git(path, "fetch", "-q", "--prune", "origin"); + return number; + } + const unprovable = (commits: number) => ({ + verdict: "Review" as const, + status: "unmerged commits", + reason: `${commits === 1 ? "1 commit isn't" : `${commits} commits aren't`} in main, and merging would conflict.`, + }); + const onGitHub = (pullRequests: number[], verdict: Verdict) => ({ + github: { pullRequests, verdict }, + }); + return { name, path, + github: remote, git: (...args) => git(path, ...args), async mergedWorktree(branch, { ageMs = OLD_AGE_MS } = {}) { movesMain("mergedWorktree"); @@ -593,6 +810,124 @@ export async function createSandbox( reason: "1 commit isn't in main.", }); }, + async prMergedWorktree(branch) { + movesMain("prMergedWorktree"); + toGitHub("prMergedWorktree"); + const { file, worktree, tip } = await pullRequestBranch(branch); + const number = await mergePullRequest(file, { + headRefName: branch, + head: tip, + commits: [tip], + }); + return { ...built(branch, worktree, unprovable(1)), ...onGitHub([number], "Safe") }; + }, + async prMergedBranch(branch, { ageMs = OLD_AGE_MS } = {}) { + movesMain("prMergedBranch"); + toGitHub("prMergedBranch"); + const { file, worktree, tip } = await pullRequestBranch(branch, dated(ageMs)); + await git(path, "worktree", "remove", worktree); + const number = await mergePullRequest(file, { + headRefName: branch, + head: tip, + commits: [tip], + }); + return { + ...built(branch, null, unprovable(1)), + ...onGitHub([number], ageMs < DAY_MS ? "Review" : "Safe"), + }; + }, + async prMergedEarlierCommit(branch) { + movesMain("prMergedEarlierCommit"); + toGitHub("prMergedEarlierCommit"); + const { file, worktree, tip } = await pullRequestBranch(branch); + // One more commit, pushed from elsewhere: made here, then dropped, so no ref here reaches it. + await editLine(worktree, file, CHANGED, `${branch}, revised in review`); + const later = await head(worktree); + await git(worktree, "reset", "-q", "--hard", tip); + const number = await mergePullRequest(file, { + headRefName: branch, + head: later, + commits: [tip, later], + }); + return { ...built(branch, worktree, unprovable(1)), ...onGitHub([number], "Safe") }; + }, + async prTreeMatch(branch) { + movesMain("prTreeMatch"); + toGitHub("prTreeMatch"); + const { file, worktree } = await pullRequestBranch(branch); + await editLine(path, file, NEAR, "main moved before the rebase"); + await git(worktree, "rebase", "-q", "main"); + // GitHub's "Update branch" rebased the pull request too: the same files in a commit of its own. + const rebasedOnGitHub = await check( + "git", + ["commit-tree", `${await head(worktree)}^{tree}`, "-p", "main", "-m", `Change ${branch}`], + { + cwd: path, + env: { GIT_COMMITTER_NAME: "GitHub", GIT_COMMITTER_EMAIL: "noreply@github.com" }, + }, + ); + const number = await mergePullRequest(file, { + headRefName: branch, + head: rebasedOnGitHub, + commits: [rebasedOnGitHub], + }); + return { ...built(branch, worktree, unprovable(1)), ...onGitHub([number], "Safe") }; + }, + async prMissingCommit(branch) { + movesMain("prMissingCommit"); + toGitHub("prMissingCommit"); + const { file, worktree, tip } = await pullRequestBranch(branch); + const number = await mergePullRequest(file, { + headRefName: branch, + head: tip, + commits: [tip], + }); + await editLine(worktree, file, 9, `${branch}, after the merge`); + return { ...built(branch, worktree, unprovable(2)), ...onGitHub([number], "Review") }; + }, + async prStacked(branch, { base = `${branch}-base` } = {}) { + movesMain("prStacked"); + const github = toGitHub("prStacked"); + const file = await pullRequestFile(branch); + const worktree = await add(branch); + // `base`'s own commit, under this branch's; `base` has no local branch. + await editLine(worktree, file, 2, base); + const lower = await head(worktree); + await editLine(worktree, file, CHANGED, branch); + const tip = await head(worktree); + await git(worktree, "push", "-q", "-u", "origin", branch); + // The first pull request squash-merges this branch into `base` on GitHub. + const first = ++pullRequests; + const intoBase = await git( + path, + "commit-tree", + `${tip}^{tree}`, + "-p", + lower, + "-m", + `${branch} (#${first})`, + ); + await git(path, "push", "-q", "origin", `${intoBase}:refs/heads/${base}`); + await gh.addPullRequest(github.owner, github.name, { + number: first, + mergedAt: new Date(Date.now() - 60 * 60_000).toISOString(), + base, + headRefName: branch, + headRefOid: tip, + commits: await described([tip]), + }); + const second = await mergePullRequest(file, { + headRefName: base, + head: intoBase, + commits: [lower, intoBase], + }); + await git(path, "push", "-q", "origin", "--delete", branch); + await git(path, "fetch", "-q", "--prune", "origin"); + return { + ...built(branch, worktree, unprovable(2)), + ...onGitHub([first, second], "Safe"), + }; + }, }; } @@ -658,6 +993,7 @@ export async function createSandbox( home, scanRoot, env, + gh, wtPath, cacheDir, backdatesOnDisk, diff --git a/tests/support/gh-cli.ts b/tests/support/gh-cli.ts new file mode 100644 index 0000000..9c1ec39 --- /dev/null +++ b/tests/support/gh-cli.ts @@ -0,0 +1,26 @@ +// The fake `gh` the sandbox puts on PATH (see gh.ts). It logs the call, waits `delayMs`, then answers. +import { readFileSync } from "node:fs"; +import { answerGh, GH_LOG_ENV, GH_STATE_ENV, type GhState, logGhCall } from "./gh"; + +const statePath = process.env[GH_STATE_ENV]; +const logPath = process.env[GH_LOG_ENV]; +if (!statePath || !logPath) { + process.stderr.write( + `fake gh: ${GH_STATE_ENV} and ${GH_LOG_ENV} must be set; use the sandbox env\n`, + ); + process.exit(2); +} +const args = process.argv.slice(2); +const env = Object.fromEntries( + Object.entries(process.env).filter( + (entry): entry is [string, string] => + entry[1] !== undefined && /^(GH_|GITHUB_|NO_COLOR$)/.test(entry[0]), + ), +); +await logGhCall(logPath, { argv: args, cwd: process.cwd(), env }); +const state = JSON.parse(readFileSync(statePath, "utf8")) as GhState; +if (state.delayMs) await Bun.sleep(state.delayMs); +const result = answerGh(state, args); +process.stdout.write(result.stdout); +process.stderr.write(result.stderr); +process.exitCode = result.exitCode; diff --git a/tests/support/gh.test.ts b/tests/support/gh.test.ts new file mode 100644 index 0000000..30ec87b --- /dev/null +++ b/tests/support/gh.test.ts @@ -0,0 +1,364 @@ +import { afterAll, beforeAll, expect, setDefaultTimeout, test } from "bun:test"; +import { lstat, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { delimiter, join } from "node:path"; +import { createSandbox, type Sandbox, TEST_TIMEOUT } from "./fixture"; +import { + chainedQuery, + GH_ENV, + graphqlArgs, + type GhPullRequest, + type GhState, + lookupQuery, +} from "./gh"; + +setDefaultTimeout(TEST_TIMEOUT); + +const oid = (digit: string) => digit.repeat(40); +const [A, B, C, D] = [oid("a"), oid("b"), oid("c"), oid("d")]; +const tree = (digit: string) => oid(digit); + +const pullRequests: GhPullRequest[] = [ + { + number: 1, + mergedAt: "2026-01-01T00:00:00Z", + base: "main", + headRefName: "feature/x", + headRefOid: A, + commits: [{ oid: A, tree: tree("1") }], + }, + // Merged later from the same branch, containing A again. + { + number: 2, + mergedAt: "2026-01-02T00:00:00Z", + base: "main", + headRefName: "feature/x", + headRefOid: B, + commits: [ + { oid: A, tree: tree("1") }, + { oid: B, tree: tree("2") }, + ], + }, + { + number: 3, + mergedAt: "2026-01-03T00:00:00Z", + base: "stack/base", + headRefName: "stack/top", + headRefOid: C, + commits: [{ oid: C, tree: tree("3") }], + }, + { + number: 4, + mergedAt: "2026-01-04T00:00:00Z", + base: "main", + headRefName: "stack/base", + headRefOid: D, + headRepository: "someone/app", + commits: [{ oid: D, tree: tree("4") }], + }, +]; + +let sandbox: Sandbox; + +beforeAll(async () => { + sandbox = await createSandbox(); +}); + +afterAll(() => sandbox?.cleanup()); + +async function given(state: Partial) { + await sandbox.gh.update((current) => { + current.mode = "ok"; + delete current.delayMs; + current.repos = [{ owner: "acme", name: "app", defaultBranch: "main", pullRequests }]; + Object.assign(current, state); + }); +} + +const gh = (args: string[], env: Record = GH_ENV) => + sandbox.exec("gh", args, { env }); + +const lookup = (oids: string[], heads: string[], repo = { owner: "acme", name: "app" }) => + gh( + graphqlArgs(lookupQuery(oids.length, heads.length), { + ...repo, + ...Object.fromEntries(oids.map((value, index) => [`oid${index}`, value])), + ...Object.fromEntries(heads.map((value, index) => [`head${index}`, value])), + }), + ); + +const associated = (pr: GhPullRequest) => ({ + number: pr.number, + state: "MERGED", + mergedAt: pr.mergedAt, + baseRefName: pr.base, + headRefName: pr.headRefName, + headRefOid: pr.headRefOid, + repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, +}); +const fromHead = (pr: GhPullRequest) => ({ + number: pr.number, + mergedAt: pr.mergedAt, + baseRefName: pr.base, + headRefOid: pr.headRefOid, + headRepository: { nameWithOwner: pr.headRepository ?? "acme/app" }, + commits: { nodes: pr.commits.map(({ oid, tree }) => ({ commit: { oid, tree: { oid: tree } } })) }, +}); + +test("answers aN with the pull request that first brought the commit in, and null for a commit GitHub lacks", async () => { + await given({}); + const result = await lookup([A, B, oid("f")], ["feature/x", "nothing/here"]); + expect({ exitCode: result.exitCode, stderr: result.stderr }).toEqual({ exitCode: 0, stderr: "" }); + expect(JSON.parse(result.stdout)).toEqual({ + data: { + rateLimit: { cost: 1, remaining: 4999 }, + repository: { + defaultBranchRef: { name: "main" }, + a0: { associatedPullRequests: { nodes: [associated(pullRequests[0]!)] } }, + a1: { associatedPullRequests: { nodes: [associated(pullRequests[1]!)] } }, + a2: null, + b0: { nodes: [fromHead(pullRequests[1]!), fromHead(pullRequests[0]!)] }, + b1: { nodes: [] }, + }, + }, + }); +}); + +test("answers kN with the pull requests that merged branch $baseN into $default", async () => { + await given({}); + const result = await gh( + graphqlArgs(chainedQuery(2), { + owner: "acme", + name: "app", + default: "main", + base0: "stack/base", + base1: "stack/top", + }), + ); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + data: { + rateLimit: { cost: 1, remaining: 4999 }, + repository: { + k0: { + nodes: [ + { + number: 4, + mergedAt: "2026-01-04T00:00:00Z", + commits: { nodes: [{ commit: { oid: D } }] }, + }, + ], + }, + // stack/top was merged into stack/base, not main. + k1: { nodes: [] }, + }, + }, + }); +}); + +test("lists at most `first` pull requests from a branch, newest first", async () => { + await given({ + repos: [ + { + owner: "acme", + name: "app", + defaultBranch: "main", + pullRequests: Array.from({ length: 7 }, (_, index) => ({ + ...pullRequests[0]!, + number: index + 1, + })), + }, + ], + }); + const result = await lookup([], ["feature/x"]); + const numbers = ( + JSON.parse(result.stdout) as { + data: { repository: { b0: { nodes: Array<{ number: number }> } } }; + } + ).data.repository.b0.nodes.map(({ number }) => number); + expect(numbers).toEqual([7, 6, 5, 4, 3]); +}); + +test("a missing repository gives partial data, an errors array on stdout and exit 1", async () => { + const missing = { + data: { rateLimit: { cost: 1, remaining: 4999 }, repository: null }, + errors: [ + { + type: "NOT_FOUND", + path: ["repository"], + message: "Could not resolve to a Repository with the name 'acme/app'.", + }, + ], + }; + await given({ mode: "missing-repo" }); + const forced = await lookup([A], ["feature/x"]); + expect({ ...forced, stdout: JSON.parse(forced.stdout) as unknown }).toEqual({ + exitCode: 1, + stdout: missing, + stderr: "gh: Could not resolve to a Repository with the name 'acme/app'.\n", + }); + await given({}); + const unknown = await lookup([A], [], { owner: "acme", name: "gone" }); + expect(unknown.exitCode).toBe(1); + expect(JSON.parse(unknown.stdout)).toEqual({ + data: missing.data, + errors: [ + { + ...missing.errors[0]!, + message: "Could not resolve to a Repository with the name 'acme/gone'.", + }, + ], + }); +}); + +test.each([ + [ + "signed-out", + 4, + "To get started with GitHub CLI, please run: gh auth login\nAlternatively, populate the GH_TOKEN environment variable with a GitHub API authentication token.\n", + ], + ["bad-credentials", 1, "gh: Bad credentials (HTTP 401)\n"], + ["offline", 1, 'Post "https://api.github.com/graphql": dial tcp: connection refused\n'], +] as const)("%s exits %d with the real CLI's message", async (mode, exitCode, stderr) => { + await given({ mode }); + expect(await lookup([A], ["feature/x"])).toEqual({ exitCode, stderr, stdout: "" }); +}); + +test("waits delayMs before answering", async () => { + await given({ delayMs: 400 }); + const started = Date.now(); + const result = await lookup([A], []); + expect(result.exitCode).toBe(0); + expect(Date.now() - started).toBeGreaterThanOrEqual(400); +}); + +test.each([ + ["another subcommand", ["auth", "status"]], + ["another API", ["api", "repos/acme/app"]], + ["a typed -F field", ["api", "graphql", "-f", "query={ viewer { login } }", "-F", "first=5"]], + ["another flag", ["api", "graphql", "--jq", ".data", "-f", "query={ viewer { login } }"]], +])("refuses %s loudly", async (_, args) => { + await given({}); + const result = await gh(args); + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toStartWith("fake gh: "); + expect(result.stdout).toBe(""); +}); + +test.each([ + [ + "an oid that isn't 40 hex digits", + { oid0: "abc123" }, + "Variable $oid0 of type GitObjectID! was provided invalid value", + ], + [ + "a declared variable not given", + {}, + "Variable $oid0 of type GitObjectID! was provided invalid value", + ], +])("rejects %s as GitHub does", async (_, variables, message) => { + await given({}); + const result = await gh( + graphqlArgs(lookupQuery(1, 0), { owner: "acme", name: "app", ...variables }), + ); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout)).toEqual({ errors: [{ message }] }); + expect(result.stderr).toBe(`gh: ${message}\n`); +}); + +test("rejects a field the fake doesn't model instead of inventing it", async () => { + await given({}); + const result = await gh( + graphqlArgs( + "query($owner:String!,$name:String!) { repository(owner:$owner, name:$name) { stargazerCount } }", + { + owner: "acme", + name: "app", + }, + ), + ); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("Field 'stargazerCount' doesn't exist on type 'Repository'"); +}); + +test("logs every call with its arguments, folder and GitHub variables, refused ones too", async () => { + await given({}); + const before = (await sandbox.gh.calls()).length; + const args = graphqlArgs(lookupQuery(1, 0), { owner: "acme", name: "app", oid0: A }); + await sandbox.exec("gh", args, { + cwd: sandbox.home, + env: { ...GH_ENV, GITHUB_TOKEN: "t", UNRELATED: "x" }, + }); + await gh(["pr", "list"]); + const calls = (await sandbox.gh.calls()).slice(before); + expect(calls).toEqual([ + { + argv: args, + cwd: sandbox.home, + env: { ...GH_ENV, GITHUB_TOKEN: "t", NO_COLOR: "1" }, + }, + { argv: ["pr", "list"], cwd: sandbox.root, env: { ...GH_ENV, NO_COLOR: "1" } }, + ]); +}); + +const hasGh = (folder: string) => + lstat(join(folder, "gh")).then( + () => true, + () => false, + ); + +test("the sandbox PATH has the fake gh first and no other gh, and still finds the tools tests use", async () => { + const folders = sandbox.env.PATH.split(delimiter); + expect(folders[0]).toBe(sandbox.gh.bin); + expect(Bun.which("gh", { PATH: sandbox.env.PATH })).toBe(join(sandbox.gh.bin, "gh")); + for (const folder of folders.slice(1)) + expect(`${folder}: ${await hasGh(folder)}`).toBe(`${folder}: false`); + const shell = await sandbox.exec("sh", ["-c", "command -v gh"]); + expect(shell.stdout.trim()).toBe(join(sandbox.gh.bin, "gh")); + for (const tool of ["git", "bun", "du", "lsof", "ps", "sh", "perl", "python3"]) + expect(`${tool}: ${Bun.which(tool, { PATH: sandbox.env.PATH }) !== null}`).toBe( + `${tool}: true`, + ); +}); + +test("with gh missing, nothing on the sandbox PATH answers to gh", async () => { + const bare = await createSandbox({ gh: "missing" }); + try { + expect(bare.gh.installed).toBe(false); + expect(Bun.which("gh", { PATH: bare.env.PATH })).toBeNull(); + for (const folder of bare.env.PATH.split(delimiter)) + expect(`${folder}: ${await hasGh(folder)}`).toBe(`${folder}: false`); + const shell = await bare.exec("sh", ["-c", "command -v gh"]); + expect(shell.exitCode).not.toBe(0); + await expect(bare.exec("gh", ["--version"])).rejects.toThrow( + "gh was not found on the sandbox PATH", + ); + } finally { + await bare.cleanup(); + } +}); + +test("a gh on the developer's PATH is left out while the tools beside it still run", async () => { + const planted = await realpath(await mkdtemp(join(tmpdir(), "wt-dash-planted-"))); + const original = process.env.PATH; + try { + await writeFile(join(planted, "gh"), "#!/bin/sh\necho real gh\n", { mode: 0o755 }); + await writeFile(join(planted, "neighbour"), "#!/bin/sh\necho neighbour\n", { mode: 0o755 }); + process.env.PATH = [planted, original].join(delimiter); + for (const gh of ["fake", "missing"] as const) { + const other = await createSandbox({ gh }); + try { + expect(other.env.PATH.split(delimiter)).not.toContain(planted); + const found = await other.exec("sh", ["-c", "neighbour; command -v gh || echo none"]); + expect(found.stdout).toBe( + `neighbour\n${gh === "fake" ? join(other.gh.bin, "gh") : "none"}\n`, + ); + } finally { + await other.cleanup(); + } + } + } finally { + process.env.PATH = original; + await rm(planted, { recursive: true, force: true }); + } +}); diff --git a/tests/support/gh.ts b/tests/support/gh.ts new file mode 100644 index 0000000..91a35b0 --- /dev/null +++ b/tests/support/gh.ts @@ -0,0 +1,676 @@ +import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +/** + * A fake GitHub CLI for the sandbox. `gh-cli.ts` is the executable; this module holds the GitHub model it + * answers from, and `createFakeGh`, which the fixture uses to write that model and read the calls made. + * It answers only `gh api graphql -f query=… -f =…`, and only the fields wt-dash's query asks for. + */ + +/** The environment variable naming the state file the fake reads on every call. */ +export const GH_STATE_ENV = "WT_DASH_FAKE_GH_STATE"; +/** The environment variable naming the JSONL file the fake appends each call to. */ +export const GH_LOG_ENV = "WT_DASH_FAKE_GH_LOG"; + +/** + * How the fake answers: `ok` from the model; `signed-out`, `bad-credentials` and `offline` with the real + * CLI's exit code and message; `missing-repo` as if no repository in the model existed. + */ +export type GhMode = "ok" | "signed-out" | "bad-credentials" | "offline" | "missing-repo"; + +export interface GhCommit { + oid: string; + tree: string; +} + +/** A merged pull request. */ +export interface GhPullRequest { + number: number; + mergedAt: string; + /** The branch it was merged into, `baseRefName`. */ + base: string; + headRefName: string; + headRefOid: string; + /** `owner/name` of the repository its head branch lives in, when that's a fork. */ + headRepository?: string; + /** Its commits, oldest first, as GitHub lists them after any force push. */ + commits: GhCommit[]; +} + +export interface GhRepo { + owner: string; + name: string; + defaultBranch: string; + pullRequests: GhPullRequest[]; +} + +/** The state file: what GitHub holds, and how the fake answers. */ +export interface GhState { + mode: GhMode; + /** Milliseconds every call waits after it is logged and before it answers. */ + delayMs?: number; + repos: GhRepo[]; +} + +/** One line of the call log. */ +export interface GhCall { + argv: string[]; + cwd: string; + /** The caller's `GH_*` and `GITHUB_*` variables, and `NO_COLOR`. */ + env: Record; +} + +export interface GhResult { + stdout: string; + stderr: string; + exitCode: number; +} + +export const emptyGhState = (): GhState => ({ mode: "ok", repos: [] }); + +const failures: Record, GhResult> = { + "signed-out": { + stdout: "", + stderr: + "To get started with GitHub CLI, please run: gh auth login\nAlternatively, populate the GH_TOKEN environment variable with a GitHub API authentication token.\n", + exitCode: 4, + }, + "bad-credentials": { stdout: "", stderr: "gh: Bad credentials (HTTP 401)\n", exitCode: 1 }, + offline: { + stdout: "", + stderr: 'Post "https://api.github.com/graphql": dial tcp: connection refused\n', + exitCode: 1, + }, +}; + +/** The fake's own failures: a call outside the contract, so the test that made it fails loudly. */ +const refuse = (message: string): GhResult => ({ + stdout: "", + stderr: `fake gh: ${message}\n`, + exitCode: 2, +}); + +/** Answers one `gh` invocation, given its arguments without the leading `gh`. */ +export function answerGh(state: GhState, args: string[]): GhResult { + if (args[0] !== "api" || args[1] !== "graphql") + return refuse( + `only "gh api graphql -f …" is supported, not "gh ${args.join(" ")}". Extend tests/support/gh.ts if the app needs it.`, + ); + const fields: Record = {}; + for (let index = 2; index < args.length; index++) { + const arg = args[index]!; + let field: string | undefined; + if (arg === "-f" || arg === "--raw-field") field = args[++index]; + else if (arg.startsWith("--raw-field=")) field = arg.slice("--raw-field=".length); + else if (arg.startsWith("-f") && arg.length > 2) field = arg.slice(2); + else if (arg === "-F" || arg.startsWith("-F") || arg.startsWith("--field")) + return refuse(`${arg}: pass every value with -f, which never converts types or reads files`); + else return refuse(`unsupported argument ${JSON.stringify(arg)}`); + const equals = field?.indexOf("=") ?? -1; + if (field === undefined || equals < 1) return refuse(`-f needs key=value, got ${field}`); + fields[field.slice(0, equals)] = field.slice(equals + 1); + } + if (state.mode !== "ok" && state.mode !== "missing-repo") return failures[state.mode]; + const { query, ...variables } = fields; + if (query === undefined) return refuse("no -f query=…"); + + const errors: Array<{ message: string; type?: string; path?: string[] }> = []; + let data: unknown; + try { + const operation = parse(query); + const values = bindVariables(operation, variables); + data = project(root(state, errors), operation.selections, values); + } catch (error) { + if (!(error instanceof QueryError)) throw error; + errors.push({ message: error.message }); + data = undefined; + } + const body = data === undefined ? { errors } : errors.length ? { data, errors } : { data }; + return { + stdout: JSON.stringify(body), + stderr: errors.map(({ message }) => `gh: ${message}\n`).join(""), + exitCode: errors.length ? 1 : 0, + }; +} + +class QueryError extends Error {} + +// ---- A GraphQL subset: one query operation, fields with aliases and arguments, inline fragments. + +type Value = + | { kind: "variable"; name: string } + | { kind: "literal"; value: unknown } + | { kind: "list"; items: Value[] } + | { kind: "object"; fields: Record }; + +interface Field { + alias: string | null; + name: string; + args: Record; + selections: Selection[]; +} +type Selection = Field | { on: string; selections: Selection[] }; + +interface Operation { + /** Declared variables and their types, such as `GitObjectID!`. */ + variables: Record; + selections: Selection[]; +} + +const token = /\s+|,|#[^\n]*|(\.\.\.|[{}():!$[\]=]|"(?:[^"\\]|\\.)*"|-?\d+|[A-Za-z_]\w*)/y; + +function parse(query: string): Operation { + const tokens: string[] = []; + token.lastIndex = 0; + while (token.lastIndex < query.length) { + const at = token.lastIndex; + const match = token.exec(query); + if (!match) throw new QueryError(`Parse error on ${JSON.stringify(query.slice(at, at + 20))}`); + if (match[1] !== undefined) tokens.push(match[1]); + } + let position = 0; + const peek = () => tokens[position]; + const next = () => { + const value = tokens[position++]; + if (value === undefined) throw new QueryError("Parse error: unexpected end of query"); + return value; + }; + const expect = (value: string) => { + const got = next(); + if (got !== value) throw new QueryError(`Parse error: expected ${value}, got ${got}`); + }; + const name = () => { + const value = next(); + if (!/^[A-Za-z_]\w*$/.test(value)) + throw new QueryError(`Parse error: expected a name, got ${value}`); + return value; + }; + + function value(): Value { + const first = next(); + if (first === "$") return { kind: "variable", name: name() }; + if (first === "[") { + const items: Value[] = []; + while (peek() !== "]") items.push(value()); + next(); + return { kind: "list", items }; + } + if (first === "{") { + const fields: Record = {}; + while (peek() !== "}") { + const key = name(); + expect(":"); + fields[key] = value(); + } + next(); + return { kind: "object", fields }; + } + if (first.startsWith('"')) return { kind: "literal", value: JSON.parse(first) as string }; + if (/^-?\d+$/.test(first)) return { kind: "literal", value: Number(first) }; + if (first === "true" || first === "false") return { kind: "literal", value: first === "true" }; + if (first === "null") return { kind: "literal", value: null }; + if (/^[A-Za-z_]\w*$/.test(first)) return { kind: "literal", value: first }; + throw new QueryError(`Parse error: unexpected ${first}`); + } + + function selections(): Selection[] { + expect("{"); + const out: Selection[] = []; + while (peek() !== "}") { + if (peek() === "...") { + next(); + if (next() !== "on") + throw new QueryError("Parse error: only inline fragments are supported"); + const on = name(); + out.push({ on, selections: selections() }); + continue; + } + let alias: string | null = null; + let fieldName = name(); + if (peek() === ":") { + next(); + alias = fieldName; + fieldName = name(); + } + const args: Record = {}; + if (peek() === "(") { + next(); + while (peek() !== ")") { + const key = name(); + expect(":"); + args[key] = value(); + } + next(); + } + out.push({ + alias, + name: fieldName, + args, + selections: peek() === "{" ? selections() : [], + }); + } + next(); + return out; + } + + const variables: Record = {}; + if (peek() === "query") { + next(); + if (peek() !== "(" && peek() !== "{") name(); + if (peek() === "(") { + next(); + while (peek() !== ")") { + expect("$"); + const variable = name(); + expect(":"); + let type = ""; + while (peek() !== "$" && peek() !== ")") { + const part = next(); + if (part === "=") throw new QueryError("Parse error: default values aren't supported"); + type += part; + } + variables[variable] = type; + } + next(); + } + } + const operation = { variables, selections: selections() }; + if (position !== tokens.length) throw new QueryError("Parse error: text after the operation"); + return operation; +} + +/** Checks the `-f` values against the declared variables, as GitHub does, and returns them by name. */ +function bindVariables( + operation: Operation, + given: Record, +): Record { + const used = new Set(); + const visit = (value: Value) => { + if (value.kind === "variable") used.add(value.name); + else if (value.kind === "list") value.items.forEach(visit); + else if (value.kind === "object") Object.values(value.fields).forEach(visit); + }; + const walk = (list: Selection[]) => { + for (const selection of list) { + if ("name" in selection) Object.values(selection.args).forEach(visit); + walk(selection.selections); + } + }; + walk(operation.selections); + for (const name of used) + if (!(name in operation.variables)) + throw new QueryError(`Variable $${name} is used by anonymous query but not declared`); + for (const [name, type] of Object.entries(operation.variables)) { + if (!used.has(name)) + throw new QueryError(`Variable $${name} is declared by anonymous query but not used`); + const value = given[name]; + if (value === undefined) { + if (type.endsWith("!")) + throw new QueryError(`Variable $${name} of type ${type} was provided invalid value`); + continue; + } + if (type.startsWith("GitObjectID") && !/^[0-9a-f]{40}$/i.test(value)) + throw new QueryError(`Variable $${name} of type ${type} was provided invalid value`); + if (!/^(String|GitObjectID)!?$/.test(type)) + throw new QueryError(`fake gh: variables of type ${type} aren't modelled; -f sends strings`); + } + return given; +} + +function resolve(value: Value, variables: Record): unknown { + switch (value.kind) { + case "variable": + return variables[value.name] ?? null; + case "literal": + return value.value; + case "list": + return value.items.map((item) => resolve(item, variables)); + case "object": + return Object.fromEntries( + Object.entries(value.fields).map(([key, field]) => [key, resolve(field, variables)]), + ); + } +} + +/** A GraphQL object: plain fields, or functions of the field's arguments. `__typename` names its type. */ +type Node = { __typename: string } & Record; +type Args = Record; + +function project(value: unknown, list: Selection[], variables: Record): unknown { + if (value === null || value === undefined) return null; + if (Array.isArray(value)) return value.map((item) => project(item, list, variables)); + const node = value as Node; + const out: Record = {}; + for (const selection of list) { + if (!("name" in selection)) { + if (node.__typename === selection.on) + Object.assign(out, project(node, selection.selections, variables)); + continue; + } + const key = selection.alias ?? selection.name; + if (selection.name === "__typename") { + out[key] = node.__typename; + continue; + } + if (!(selection.name in node)) + throw new QueryError( + `Field '${selection.name}' doesn't exist on type '${node.__typename}' (or the fake doesn't model it)`, + ); + const args = Object.fromEntries( + Object.entries(selection.args).map(([name, arg]) => [name, resolve(arg, variables)]), + ); + let field = node[selection.name]; + if (typeof field === "function") field = (field as (args: Args) => unknown)(args); + else if (Object.keys(args).length) + throw new QueryError(`Field '${selection.name}' doesn't accept arguments`); + const scalar = typeof field !== "object"; + if (selection.selections.length ? scalar : field !== null && !scalar) + throw new QueryError( + `Field '${selection.name}' on type '${node.__typename}' ${scalar ? "has no subfields" : "must have a selection of subfields"}`, + ); + out[key] = selection.selections.length + ? project(field, selection.selections, variables) + : field; + } + return out; +} + +// ---- The model as GraphQL objects. + +function page(items: T[], args: Args, field: string): T[] { + const first = args.first; + const last = args.last; + if (typeof first !== "number" && typeof last !== "number") + throw new QueryError( + `You must provide a \`first\` or \`last\` value to properly paginate the \`${field}\` connection.`, + ); + if (typeof first === "number") items = items.slice(0, first); + if (typeof last === "number") items = items.slice(Math.max(0, items.length - last)); + return items; +} + +function root( + state: GhState, + errors: Array<{ message: string; type?: string; path?: string[] }>, +): Node { + return { + __typename: "Query", + rateLimit: { __typename: "RateLimit", cost: 1, remaining: 4999, limit: 5000 }, + repository: ({ owner, name }: Args) => { + const repo = + state.mode === "missing-repo" + ? undefined + : state.repos.find( + (candidate) => + candidate.owner.toLowerCase() === String(owner).toLowerCase() && + candidate.name.toLowerCase() === String(name).toLowerCase(), + ); + if (repo) return repository(repo); + errors.push({ + type: "NOT_FOUND", + path: ["repository"], + message: `Could not resolve to a Repository with the name '${owner}/${name}'.`, + }); + return null; + }, + }; +} + +function repository(repo: GhRepo): Node { + const nameWithOwner = `${repo.owner}/${repo.name}`; + const byMerge = [...repo.pullRequests].sort( + (a, b) => Date.parse(a.mergedAt) - Date.parse(b.mergedAt) || a.number - b.number, + ); + const node: Node = { + __typename: "Repository", + name: repo.name, + nameWithOwner, + defaultBranchRef: { __typename: "Ref", name: repo.defaultBranch }, + object: ({ oid, expression }: Args) => { + if (expression !== undefined) + throw new QueryError("fake gh: object(expression:) isn't modelled"); + const found = repo.pullRequests + .flatMap((pr) => pr.commits) + .find((commit) => commit.oid === String(oid).toLowerCase()); + return found ? commit(found) : null; + }, + pullRequests: (args: Args) => { + const states = [args.states ?? []].flat(); + const order = args.orderBy as { field?: string; direction?: string } | undefined; + if (order && order.field !== "CREATED_AT") + throw new QueryError(`fake gh: orderBy ${order.field} isn't modelled`); + // Numbers grow with creation time. + const sorted = [...repo.pullRequests].sort((a, b) => + order?.direction === "DESC" ? b.number - a.number : a.number - b.number, + ); + const nodes = sorted.filter( + (pr) => + (!states.length || states.includes("MERGED")) && + (args.headRefName === undefined || pr.headRefName === args.headRefName) && + (args.baseRefName === undefined || pr.base === args.baseRefName), + ); + return { + __typename: "PullRequestConnection", + totalCount: nodes.length, + nodes: page(nodes, args, "pullRequests").map(pullRequest), + }; + }, + }; + function commit(found: GhCommit): Node { + return { + __typename: "Commit", + oid: found.oid, + tree: { __typename: "Tree", oid: found.tree }, + // GitHub lists the pull request that first brought the commit in, not later ones that contain it too. + associatedPullRequests: (args: Args) => { + const first = byMerge.find((pr) => pr.commits.some(({ oid }) => oid === found.oid)); + const nodes = first ? [pullRequest(first)] : []; + return { + __typename: "PullRequestConnection", + totalCount: nodes.length, + nodes: page(nodes, args, "associatedPullRequests"), + }; + }, + }; + } + function pullRequest(pr: GhPullRequest): Node { + return { + __typename: "PullRequest", + number: pr.number, + state: "MERGED", + merged: true, + mergedAt: pr.mergedAt, + baseRefName: pr.base, + headRefName: pr.headRefName, + headRefOid: pr.headRefOid, + repository: node, + headRepository: { + __typename: "Repository", + nameWithOwner: pr.headRepository ?? nameWithOwner, + }, + commits: (args: Args) => ({ + __typename: "PullRequestCommitConnection", + totalCount: pr.commits.length, + nodes: page(pr.commits, args, "commits").map((found) => ({ + __typename: "PullRequestCommit", + commit: commit(found), + })), + }), + }; + } + return node; +} + +// ---- The query wt-dash will send, for tests that call the fake as the app will. + +const range = (count: number) => Array.from({ length: count }, (_, index) => index); + +/** The lookup query: `aN` asks for commit `$oidN`, `bN` for merged pull requests from branch `$headN`. */ +export function lookupQuery(oids: number, heads: number): string { + const variables = [ + "$owner:String!", + "$name:String!", + ...range(oids).map((index) => `$oid${index}:GitObjectID!`), + ...range(heads).map((index) => `$head${index}:String!`), + ]; + return `query(${variables.join(",")}) { + rateLimit { cost remaining } + repository(owner:$owner, name:$name) { + defaultBranchRef { name } +${range(oids) + .map( + (index) => ` a${index}: object(oid:$oid${index}) { ... on Commit { + associatedPullRequests(first:5) { nodes { number state mergedAt baseRefName headRefName headRefOid + repository { nameWithOwner defaultBranchRef { name } } } } } }`, + ) + .join("\n")} +${range(heads) + .map( + ( + index, + ) => ` b${index}: pullRequests(headRefName:$head${index}, states:MERGED, first:5, orderBy:{field:CREATED_AT,direction:DESC}) { + nodes { number mergedAt baseRefName headRefOid headRepository { nameWithOwner } + commits(last:250) { nodes { commit { oid tree { oid } } } } } }`, + ) + .join("\n")} + } +}`; +} + +/** The chained query: `kN` asks for pull requests that merged branch `$baseN` into `$default`. */ +export function chainedQuery(bases: number): string { + const variables = [ + "$owner:String!", + "$name:String!", + "$default:String!", + ...range(bases).map((index) => `$base${index}:String!`), + ]; + return `query(${variables.join(",")}) { + rateLimit { cost remaining } + repository(owner:$owner, name:$name) { +${range(bases) + .map( + (index) => + ` k${index}: pullRequests(headRefName:$base${index}, baseRefName:$default, states:MERGED, first:5, orderBy:{field:CREATED_AT,direction:DESC}) { nodes { number mergedAt commits(last:250) { nodes { commit { oid } } } } }`, + ) + .join("\n")} + } +}`; +} + +/** `gh` arguments for `query`, every value passed with `-f` as the app will. */ +export function graphqlArgs(query: string, variables: Record): string[] { + return [ + "api", + "graphql", + "-f", + `query=${query}`, + ...Object.entries(variables).flatMap(([key, value]) => ["-f", `${key}=${value}`]), + ]; +} + +/** The environment the app will run `gh` with. */ +export const GH_ENV = { GH_NO_UPDATE_NOTIFIER: "1", GH_PROMPT_DISABLED: "1" }; + +// ---- The fixture's side: writing the model and reading the log. + +export interface FakeGh { + /** A folder holding only the fake `gh`, first on the sandbox PATH when `installed`. */ + bin: string; + /** Whether the sandbox PATH has the fake; when false it has no `gh` at all. */ + installed: boolean; + statePath: string; + logPath: string; + /** The model as last written. */ + state(): GhState; + /** Changes the model and writes it before resolving; calls are applied in order. */ + update(change: (state: GhState) => void): Promise; + setMode(mode: GhMode, delayMs?: number): Promise; + /** Adds `owner/name` with no pull requests, unless the model has it. */ + addRepo(owner: string, name: string, defaultBranch?: string): Promise; + addPullRequest(owner: string, name: string, pullRequest: GhPullRequest): Promise; + /** Every call made so far, oldest first. */ + calls(): Promise; +} + +/** Writes the fake's state, log and executable into `folder`. `installed` only records the fixture's choice. */ +export async function createFakeGh(folder: string, installed: boolean): Promise { + const bin = join(folder, "bin"); + const statePath = join(folder, "state.json"); + const logPath = join(folder, "calls.jsonl"); + await mkdir(bin, { recursive: true }); + const quote = (text: string) => `'${text.replaceAll("'", `'\\''`)}'`; + await writeFile( + join(bin, "gh"), + `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(join(import.meta.dir, "gh-cli.ts"))} "$@"\n`, + { mode: 0o755 }, + ); + await writeFile(logPath, ""); + let current = emptyGhState(); + let writing = Promise.resolve(); + const save = async () => { + const temporary = `${statePath}.${process.pid}.tmp`; + await writeFile(temporary, JSON.stringify(current, null, 2)); + await rename(temporary, statePath); + }; + await save(); + const update = (change: (state: GhState) => void): Promise => { + const done = writing.then(async () => { + const next = structuredClone(current); + change(next); + current = next; + await save(); + return structuredClone(current); + }); + writing = done.then( + () => undefined, + () => undefined, + ); + return done; + }; + const repoIn = (state: GhState, owner: string, name: string) => { + const repo = state.repos.find( + (candidate) => candidate.owner === owner && candidate.name === name, + ); + if (!repo) throw new Error(`The fake GitHub has no ${owner}/${name}; add it first`); + return repo; + }; + return { + bin, + installed, + statePath, + logPath, + state: () => structuredClone(current), + update, + setMode: (mode, delayMs) => + update((state) => { + state.mode = mode; + if (delayMs === undefined) delete state.delayMs; + else state.delayMs = delayMs; + }), + addRepo: (owner, name, defaultBranch = "main") => + update((state) => { + if (!state.repos.some((repo) => repo.owner === owner && repo.name === name)) + state.repos.push({ owner, name, defaultBranch, pullRequests: [] }); + }), + addPullRequest: (owner, name, pullRequest) => + update((state) => { + const repo = repoIn(state, owner, name); + if (repo.pullRequests.some(({ number }) => number === pullRequest.number)) + throw new Error(`${owner}/${name} already has PR #${pullRequest.number}`); + repo.pullRequests.push(pullRequest); + }), + async calls() { + const text = await readFile(logPath, "utf8"); + return text + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as GhCall); + }, + }; +} + +/** Appends one call to the log; used by gh-cli.ts. */ +export async function logGhCall(path: string, call: GhCall): Promise { + await appendFile(path, `${JSON.stringify(call)}\n`); +} From 9c920a267b6bb8f5d762993889f5552f8e874226 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 19:59:25 -0500 Subject: [PATCH 07/11] feat: delete the branch of a row proven merged on GitHub --- README.md | 2 +- src/core/removal/execute.ts | 4 +- src/core/removal/plan.ts | 48 +++++---- src/core/removal/types.ts | 5 + src/ui/render/dialogs.ts | 18 +++- tests/e2e/merged-on-github.test.ts | 75 ++++++++++++++ tests/integration/helpers.ts | 2 + tests/integration/merged-on-github.test.ts | 113 +++++++++++++++++++++ tests/removal/execute.test.ts | 73 +++++++++++++ tests/removal/helpers.ts | 25 ++++- tests/removal/plan.test.ts | 39 +++++++ tests/removal/recheck.test.ts | 54 ++++++++++ tests/support/app.ts | 16 ++- tests/support/fixture.ts | 46 ++++++++- tests/terminal.test.ts | 52 ++++++++++ 15 files changed, 541 insertions(+), 31 deletions(-) create mode 100644 tests/e2e/merged-on-github.test.ts create mode 100644 tests/integration/merged-on-github.test.ts diff --git a/README.md b/README.md index da8b20c..126ef55 100644 --- a/README.md +++ b/README.md @@ -215,7 +215,7 @@ wt-dash names the tool that made each worktree from the folder it sits in. The t The dialog lists each row and its size, the total, and which ones would lose uncommitted or untracked changes or ignored files that aren't caches, such as `.env.local`. -- **Branches are kept unless they are merged.** Press `D` in the dialog to delete unmerged branches too. An unmerged branch without a worktree is skipped unless you press `D`, since deleting it is all its removal does. +- **Branches are kept unless they are merged.** A branch proven merged by a GitHub pull request is deleted like a merged branch, and the dialog names the pull request. Press `D` in the dialog to delete unmerged branches too. An unmerged branch without a worktree is skipped unless you press `D`, since deleting it is all its removal does. - **Processes running inside are stopped**, such as dev servers, watchers and language servers, so they don't hold the folder open. The dialog names the worktrees that have some, such as `Running in feature/login: 1 process · :3000`. Worktrunk leaves interactive shells and terminal editors alone. Press `e` in the dialog to leave every process running. - **Ignored files go with the worktree**, including `.env` copies, local databases and caches, the same way Worktrunk treats them. - **Worktrunk hooks are skipped.** Project-defined cleanup commands do not run. diff --git a/src/core/removal/execute.ts b/src/core/removal/execute.ts index 628cddd..b628615 100644 --- a/src/core/removal/execute.ts +++ b/src/core/removal/execute.ts @@ -171,7 +171,8 @@ export async function removeBatch( } const flags = [ choice.discardChanges && entry.requiresDiscard ? "-f" : null, - choice.forceDeleteBranch ? "-D" : null, + // Worktrunk keeps a branch its own checks can't show merged, so a merged pull request needs -D. + choice.forceDeleteBranch || entry.branchProof ? "-D" : null, choice.reapProcesses && row.kind === "worktree" ? "--reap" : null, ].filter((flag): flag is string => flag !== null); const label = row.path ?? `branch ${row.branch}`; @@ -215,6 +216,7 @@ export async function removeBatch( exitCode, branchOutcome: branchOutcome ?? null, ...(pruned === undefined ? {} : { pruned }), + ...(entry.branchProof ? { branchProof: entry.branchProof } : {}), error: error ?? null, }); } diff --git a/src/core/removal/plan.ts b/src/core/removal/plan.ts index 7ada9d0..24985a0 100644 --- a/src/core/removal/plan.ts +++ b/src/core/removal/plan.ts @@ -1,4 +1,4 @@ -import { assess, recentAgentMark } from "../assess"; +import { assessRow, recentAgentMark, removalBlockReason } from "../assess"; import { readFiles } from "../git/status"; import type { WorktreeState } from "../git/worktrees"; import { failure } from "../process"; @@ -71,8 +71,33 @@ export async function listRepo( readBranchCreated: options.readBranchCreated, }); } +/** The states in which assess lets a merged pull request stand in for Worktrunk's merge check. */ +const forgeStates = ["ahead", "would_conflict", "diverged", "behind"]; + +/** The pull request GitHub says merged the row's tip, or null when no proof holds for its current tip. */ +function provenBy(row: WorktreeRow): { pr: number } | null { + const forge = row.forge; + return forge?.kind === "proven" && + forge.tip === row.headSha && + forgeStates.includes(row.mainState ?? "") + ? { pr: forge.pr } + : null; +} + export function matchListing(row: WorktreeRow, listing: WorktreeRow[]): RemovalEntry { - const fresh = listing.find((item) => item.id === row.id); + const listed = listing.find((item) => item.id === row.id); + // `wt list` knows nothing of GitHub, so the confirmed row's answer carries over while the tip is the same. + const fresh = + listed && row.forge && listed.headSha === row.headSha + ? { ...listed, forge: row.forge } + : listed; + // Worktrunk deletes a branch whenever an integration check matched, but a dirty worktree + // shows that match as "behind" or "diverged" rather than "integrated". + const unmerged = + row.branch !== null && + !row.integrationReason && + !["empty", "integrated", "same_commit"].includes(row.mainState ?? ""); + const proof = unmerged ? provenBy(row) : null; const blockedReason = !fresh ? row.kind === "branch" ? "it is missing or now has a worktree" @@ -87,23 +112,12 @@ export function matchListing(row: WorktreeRow, listing: WorktreeRow[]): RemovalE ignoredFiles: [], disposableIgnored: 0, requiresDiscard: false, - // Worktrunk deletes a branch whenever an integration check matched, but a dirty worktree - // shows that match as "behind" or "diverged" rather than "integrated". - branchWillBeRetained: - row.branch !== null && - !row.integrationReason && - !["empty", "integrated", "same_commit"].includes(row.mainState ?? ""), + branchWillBeRetained: unmerged && !proof, + ...(proof ? { branchProof: proof } : {}), }; if (blockedReason) return entry; - const assessment = assess(fresh!); - entry.row = { - ...fresh!, - sizeKiB: row.sizeKiB, - sizeMeasuredAt: row.sizeMeasuredAt, - verdict: assessment.verdict, - reason: assessment.reason, - }; - entry.blockedReason = assessment.removalBlockReason; + entry.row = assessRow({ ...fresh!, sizeKiB: row.sizeKiB, sizeMeasuredAt: row.sizeMeasuredAt }); + entry.blockedReason = removalBlockReason(entry.row); return entry; } export async function checkAgainst( diff --git a/src/core/removal/types.ts b/src/core/removal/types.ts index 2ecd4cb..ecb0f8d 100644 --- a/src/core/removal/types.ts +++ b/src/core/removal/types.ts @@ -18,6 +18,11 @@ export interface RemovalEntry extends FileReport { blockedReason: string | null; requiresDiscard: boolean; branchWillBeRetained: boolean; + /** + * Set when Worktrunk can't prove the branch merged but GitHub can: PR `pr` merged its tip. Removal then + * force-deletes the branch for this row alone. + */ + branchProof?: { pr: number }; /** Device and inode of an orphan folder at the preview; removal skips it if the folder at the path differs. */ folderId?: string; } diff --git a/src/ui/render/dialogs.ts b/src/ui/render/dialogs.ts index 6676d2c..afe060d 100644 --- a/src/ui/render/dialogs.ts +++ b/src/ui/render/dialogs.ts @@ -23,13 +23,23 @@ import type { RenderContext } from "./layout"; import { toastLine } from "./chrome"; import { repoCell, rowSize } from "./list"; -function names(entries: RemovalEntry[]): string { - const labels = entries.map((entry) => branchLabel(entry.row)); +function names( + entries: RemovalEntry[], + label: (entry: RemovalEntry) => string = (entry) => branchLabel(entry.row), +): string { + const labels = entries.map(label); return labels.length <= 2 ? labels.join(" and ") : `${labels.slice(0, 2).join(", ")} +${labels.length - 2} more`; } +function provenNote(proven: RemovalEntry[]): string { + if (proven.length === 1) + return `Deletes branch ${names(proven)}: merged on GitHub as PR #${proven[0]!.branchProof!.pr}`; + const label = (entry: RemovalEntry) => `${branchLabel(entry.row)} (PR #${entry.branchProof!.pr})`; + return `Deletes ${proven.length} branches merged on GitHub: ${names(proven, label)}`; +} + function ignoredNote(entries: RemovalEntry[]): string { if (entries.length > 1) return `! Deletes ignored files in ${names(entries)}`; const files = entries[0]!.ignoredFiles; @@ -146,6 +156,7 @@ function removeDialog( ); const unmerged = ready.filter((entry) => entry.branchWillBeRetained); const merged = ready.filter((entry) => entry.row.branch !== null && !entry.branchWillBeRetained); + const proven = merged.filter((entry) => entry.branchProof); const bare = unmerged.filter((entry) => entry.row.kind === "branch"); if (bare.length && !confirm.deleteUnmerged) notes.push(...warn(`! Skips ${names(bare)} unless you press D: not merged, and no worktree`)); @@ -159,7 +170,8 @@ function removeDialog( key(theme, "D"), dim(confirm.deleteUnmerged ? " keep them" : " delete too"), ]); - } else if (merged.length) options.push([dim("Merged branches are deleted.")]); + } else if (merged.length > proven.length) options.push([dim("Merged branches are deleted.")]); + if (proven.length) options.push(...wrap(provenNote(proven), inner).map((text) => [dim(text)])); const hasProcessesToStop = orphans.length < ready.length; if (hasProcessesToStop) options.push([ diff --git a/tests/e2e/merged-on-github.test.ts b/tests/e2e/merged-on-github.test.ts new file mode 100644 index 0000000..13eb523 --- /dev/null +++ b/tests/e2e/merged-on-github.test.ts @@ -0,0 +1,75 @@ +import { expect, test } from "bun:test"; +import type { RowPatch } from "../../src/core/scan/dashboard"; +import type { WorktreeRow } from "../../src/core/types"; +import { + dialog, + dialogRow, + exists, + inSandbox, + removals, + rowOf, + withApp, + TEST_TIMEOUT, +} from "../support/app"; + +test( + "a worktree a follow-up proves merged on GitHub: the dialog names its PR, and removing it deletes the branch", + () => + inSandbox(async (sandbox) => { + const alpha = await sandbox.repo("alpha"); + const feature = await alpha.unmergedWorktree("feature"); + // As the GitHub check would answer: PR #60 merged the tip of feature. + const followUp = async (_repo: string, rows: WorktreeRow[]): Promise => + rows + .filter((row) => row.branch === "feature") + .map((row) => ({ + id: row.id, + headSha: row.headSha!, + facts: { + forge: { + kind: "proven", + tip: row.headSha!, + pr: 60, + mergedAt: "2026-10-30T12:00:00Z", + base: "main", + by: "commit", + }, + }, + })); + await withApp(sandbox, { width: 120, name: "merged on GitHub", followUp }, async (app) => { + await app.settled(); + let frame = await app.waitFor( + (text) => rowOf(text, "feature")?.includes("merged on GitHub") ?? false, + ); + expect(rowOf(frame, "feature")).toStartWith("□ feature merged on GitHub PR #60 merged "); + + await app.focus("feature"); + await app.press("x"); + frame = await app.waitFor("Remove 1 worktree"); + expect(dialogRow(frame, "feature")).toStartWith("• feature alpha "); + expect(dialog(frame)).toContain("Deletes branch feature: merged on GitHub as PR #60"); + expect(dialog(frame)).not.toContain("unmerged branch"); + await app.press("y"); + frame = await app.waitFor(/✓ Removed 1 worktree · (freed|up to) .+/); + await app.waitFor((text) => rowOf(text, "feature") === null); + expect(await exists(feature.path!)).toBe(false); + expect(await alpha.git("branch", "--list", "feature")).toBe(""); + expect( + (await removals(sandbox)).map(({ branch, flags, branchOutcome, branchProof }) => ({ + branch, + flags, + branchOutcome, + branchProof, + })), + ).toEqual([ + { + branch: "feature", + flags: ["-D", "--reap"], + branchOutcome: "deleted", + branchProof: { pr: 60 }, + }, + ]); + }); + }), + TEST_TIMEOUT, +); diff --git a/tests/integration/helpers.ts b/tests/integration/helpers.ts index f442c39..8e1a5bf 100644 --- a/tests/integration/helpers.ts +++ b/tests/integration/helpers.ts @@ -64,6 +64,8 @@ export interface LogLine { flags: string[]; exitCode: number; branchOutcome: string | null; + /** The pull request that proved the branch merged, when that is why it was force-deleted. */ + branchProof?: { pr: number }; error: string | null; } diff --git a/tests/integration/merged-on-github.test.ts b/tests/integration/merged-on-github.test.ts new file mode 100644 index 0000000..c988faf --- /dev/null +++ b/tests/integration/merged-on-github.test.ts @@ -0,0 +1,113 @@ +import { afterAll, beforeAll, expect, test, setDefaultTimeout } from "bun:test"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { assessRow } from "../../src/core/assess"; +import type { ForgeCheck, WorktreeRow } from "../../src/core/types"; +import { createSandbox, type Built, type Sandbox, TEST_TIMEOUT } from "../support/fixture"; +import { branches, exists, logFor, row, scan } from "./helpers"; + +setDefaultTimeout(TEST_TIMEOUT); + +let sandbox: Sandbox; + +beforeAll(async () => { + sandbox = await createSandbox(); +}); + +afterAll(() => sandbox?.cleanup()); + +/** The row as the scan shows it once GitHub has answered that PR `pr` merged its tip. */ +function provenOnGitHub(shown: WorktreeRow, pr: number): WorktreeRow { + const forge: ForgeCheck = { + kind: "proven", + tip: shown.headSha!, + pr, + mergedAt: "2026-10-30T12:00:00Z", + base: "main", + by: "commit", + }; + return assessRow({ ...shown, forge }); +} + +const logged = async (built: Built) => + (await logFor(sandbox, built)).map(({ flags, exitCode, branchOutcome, branchProof, error }) => ({ + flags, + exitCode, + branchOutcome, + branchProof, + error, + })); + +test("a worktree Worktrunk can't show merged but GitHub proves merged is removed with its branch, and the log names the PR", async () => { + const repo = await sandbox.repo("proven"); + const built = await repo.unmergedWorktree("feature"); + const { dashboard, actions } = await sandbox.services(); + const shown = row(await scan(dashboard, repo), built); + expect([shown.verdict, shown.mainState, shown.integrationReason]).toEqual([ + "Review", + "ahead", + null, + ]); + const proven = provenOnGitHub(shown, 60); + expect(proven.verdict).toBe("Safe"); + + const plan = await actions.prepareRemoval([proven]); + expect(plan.entries[0]).toMatchObject({ + blockedReason: null, + branchWillBeRetained: false, + branchProof: { pr: 60 }, + row: { verdict: "Safe" }, + }); + const result = await actions.executeRemoval(plan, { [proven.id]: { include: true } }); + expect(result.items).toEqual([{ id: proven.id, status: "removed", branchOutcome: "deleted" }]); + expect(await exists(built.path!)).toBe(false); + expect(await branches(repo)).toEqual(["main"]); + expect(await logged(built)).toEqual([ + { flags: ["-D"], exitCode: 0, branchOutcome: "deleted", branchProof: { pr: 60 }, error: null }, + ]); +}); + +test("a worktree proven merged on GitHub that gains a commit after confirmation is skipped, and its branch kept", async () => { + const repo = await sandbox.repo("moved"); + const built = await repo.unmergedWorktree("feature"); + const { dashboard, actions } = await sandbox.services(); + const proven = provenOnGitHub(row(await scan(dashboard, repo), built), 61); + const plan = await actions.prepareRemoval([proven]); + expect(plan.entries[0]?.branchProof).toEqual({ pr: 61 }); + + await writeFile(join(built.path!, "later.txt"), "later\n"); + await sandbox.git(built.path!, "add", "later.txt"); + await sandbox.git(built.path!, "commit", "-q", "-m", "Later"); + const moved = await sandbox.git(built.path!, "rev-parse", "HEAD"); + + const result = await actions.executeRemoval(plan, { [proven.id]: { include: true } }); + expect(result.items).toEqual([ + { id: proven.id, status: "skipped", error: "it changed; refresh and preview again" }, + ]); + expect(await exists(built.path!)).toBe(true); + expect(await repo.git("rev-parse", "refs/heads/feature")).toBe(moved); + expect(await logged(built)).toEqual([]); +}); + +test("a branch without a worktree that GitHub proves merged is deleted without D", async () => { + const repo = await sandbox.repo("leftover"); + const built = await repo.unmergedBranch("leftover"); + const { dashboard, actions } = await sandbox.services(); + const shown = row(await scan(dashboard, repo), built); + expect(shown.verdict).toBe("Review"); + const proven = provenOnGitHub(shown, 62); + expect(proven.verdict).toBe("Safe"); + + const plan = await actions.prepareRemoval([proven]); + expect(plan.entries[0]).toMatchObject({ + blockedReason: null, + branchWillBeRetained: false, + branchProof: { pr: 62 }, + }); + const result = await actions.executeRemoval(plan, { [proven.id]: { include: true } }); + expect(result.items).toEqual([{ id: proven.id, status: "removed", branchOutcome: "deleted" }]); + expect(await branches(repo)).toEqual(["main"]); + expect(await logged(built)).toEqual([ + { flags: ["-D"], exitCode: 0, branchOutcome: "deleted", branchProof: { pr: 62 }, error: null }, + ]); +}); diff --git a/tests/removal/execute.test.ts b/tests/removal/execute.test.ts index 72ef49e..dcfafbb 100644 --- a/tests/removal/execute.test.ts +++ b/tests/removal/execute.test.ts @@ -4,8 +4,11 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import fixture from "../fixtures/list-v2.json"; import { parseWorktrunk } from "../../src/core/worktrunk/list"; +import { assessRow } from "../../src/core/assess"; import { aged, + aheadPayload, + aheadRow, branchOnly, branchRemoved, branchRow, @@ -14,6 +17,7 @@ import { detachedRow, fakeRepos, payloadB, + proven, removed, repo, repoB, @@ -640,3 +644,72 @@ test("a branch Worktrunk keeps counts as not removed", async () => { error: "Worktrunk kept the branch (retained unmerged)", }); }); + +test("a worktree proven merged on GitHub is removed with -D for that row alone, and the log names its PR", async () => { + const directory = await mkdtemp(join(tmpdir(), "dash-action-")); + try { + const row = aheadRow(proven("bbb")); + const { calls, runner } = fakeRepos({ payloads: { [repo]: aheadPayload() } }); + const actions = createActionService({ wtPath: "/wt", runner, logPath: join(directory, "log") }); + const plan = await actions.prepareRemoval([row, detachedRow]); + expect(plan.entries.map((entry) => [entry.branchWillBeRetained, entry.branchProof])).toEqual([ + [false, { pr: 60 }], + [false, undefined], + ]); + const result = await actions.executeRemoval(plan, { + [row.id]: { include: true }, + [detachedRow.id]: { include: true }, + }); + expect(result.items.map((item) => item.status)).toEqual(["removed", "removed"]); + const removals = calls.filter((call) => call.includes("remove")).map((call) => call.slice(-2)); + expect(removals).toEqual([ + ["-D", row.path!], + ["--format=json", detachedRow.path!], + ]); + const log = (await readFile(join(directory, "log"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect(log.map(({ path, flags, branchProof }) => ({ path, flags, branchProof }))).toEqual([ + { path: row.path, flags: ["-D"], branchProof: { pr: 60 } }, + { path: detachedRow.path, flags: [], branchProof: undefined }, + ]); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test("a worktree whose GitHub proof is for an earlier tip is removed without -D", async () => { + const row = { ...aheadRow(), forge: proven("earlier") }; + const { calls, runner } = fakeRepos({ payloads: { [repo]: aheadPayload() } }); + const actions = createActionService({ wtPath: "/wt", runner, logPath: "/dev/null" }); + const plan = await actions.prepareRemoval([row]); + expect(plan.entries[0]).toMatchObject({ branchWillBeRetained: true, row: { verdict: "Review" } }); + await actions.executeRemoval(plan, { [row.id]: { include: true } }); + expect(calls.find((call) => call.includes("remove"))?.slice(-2)).toEqual([ + "--format=json", + row.path!, + ]); +}); + +test("a branch without a worktree proven merged on GitHub is deleted without pressing D", async () => { + const payload = withBranch("ahead"); + const row = assessRow({ ...branchOnly(payload), forge: proven("old-sha", 61) }); + expect(row.verdict).toBe("Safe"); + const { calls, runner } = fakeRepos({ + payloads: { [repo]: payload }, + tips: { "refs/heads/old": "old-sha" }, + removeOutput: () => branchRemoved(), + }); + const actions = createActionService({ wtPath: "/wt", runner, logPath: "/dev/null", ...aged }); + const plan = await actions.prepareRemoval([row]); + expect(plan.entries[0]).toMatchObject({ + blockedReason: null, + branchWillBeRetained: false, + branchProof: { pr: 61 }, + row: { verdict: "Safe" }, + }); + const result = await actions.executeRemoval(plan, { [row.id]: { include: true } }); + expect(result.items).toEqual([{ id: row.id, status: "removed", branchOutcome: "deleted" }]); + expect(calls.find((call) => call.includes("remove"))?.slice(-2)).toEqual(["-D", "old"]); +}); diff --git a/tests/removal/helpers.ts b/tests/removal/helpers.ts index 91ceca6..86fd737 100644 --- a/tests/removal/helpers.ts +++ b/tests/removal/helpers.ts @@ -1,6 +1,7 @@ import fixture from "../fixtures/list-v2.json"; +import { assessRow } from "../../src/core/assess"; import { parseWorktrunk } from "../../src/core/worktrunk/list"; -import type { CommandRunner } from "../../src/core/types"; +import type { CommandRunner, ForgeCheck, WorktreeRow } from "../../src/core/types"; export const repo = "/Users/test/projects/sample"; export const rows = parseWorktrunk(repo, JSON.stringify(fixture)); @@ -160,3 +161,25 @@ export const branchRemoved = (outcome = "deleted") => pruned: false, }, ]); + +/** GitHub's answer that PR `pr` merged `tip` into main, as a follow-up attaches it to a row. */ +export const proven = (tip: string, pr = 60): ForgeCheck => ({ + kind: "proven", + tip, + pr, + mergedAt: "2026-10-30T12:00:00Z", + base: "main", + by: "commit", +}); + +/** The fixture with feature/name one commit ahead of main, which Worktrunk can't show merged. */ +export function aheadPayload(): any { + const payload: any = structuredClone(fixture); + payload.items[1].default_branch = { ahead: 1, behind: 0 }; + payload.items[1].display = { state: "ahead" }; + return payload; +} + +/** feature/name from `aheadPayload`, with `forge` attached and the row settled as the scan does. */ +export const aheadRow = (forge?: ForgeCheck): WorktreeRow => + assessRow({ ...parseWorktrunk(repo, JSON.stringify(aheadPayload()))[0]!, forge }); diff --git a/tests/removal/plan.test.ts b/tests/removal/plan.test.ts index 5118573..a3ede39 100644 --- a/tests/removal/plan.test.ts +++ b/tests/removal/plan.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import fixture from "../fixtures/list-v2.json"; import { parseWorktrunk } from "../../src/core/worktrunk/list"; import { + aheadRow, branchRow, branchRowB, commandResult, @@ -12,6 +13,7 @@ import { detachedRowB, fakeRepos, noNewCommits, + proven, removed, repo, repoB, @@ -222,3 +224,40 @@ test.each([ expect(matchListing(row, [row]).branchWillBeRetained).toBe(retained); }, ); + +test("a row proven merged on GitHub stays Safe in the preview, and its branch is deleted for its PR", () => { + const row = aheadRow(proven("bbb")); + expect(row.verdict).toBe("Safe"); + const listed = aheadRow(); + expect(listed.forge).toBeUndefined(); + const entry = matchListing(row, [listed]); + expect(entry).toMatchObject({ + blockedReason: null, + branchWillBeRetained: false, + branchProof: { pr: 60 }, + row: { verdict: "Safe", forge: proven("bbb") }, + }); + expect(entry.row.reason).toStartWith("PR #60 merged "); +}); + +test.each([ + ["answers for an earlier tip", { ...aheadRow(), forge: proven("earlier") }], + ["found no merged PR", aheadRow({ kind: "not-found", tip: "bbb" })], + [ + "proves a branch that shares no history with main", + { ...aheadRow(proven("bbb")), mainState: "orphan" }, + ], +])("a row whose GitHub check %s keeps its branch unless D is pressed", (_name, row) => { + const entry = matchListing(row, [{ ...row, forge: undefined }]); + expect(entry.blockedReason).toBeNull(); + expect(entry.branchWillBeRetained).toBe(true); + expect(entry.branchProof).toBeUndefined(); + expect(entry.row.verdict).toBe("Review"); +}); + +test("a proven row whose tip moved since confirmation is skipped, and the proof doesn't carry to the new tip", () => { + const moved = { ...aheadRow(), headSha: "moved" }; + const entry = matchListing(aheadRow(proven("bbb")), [moved]); + expect(entry.blockedReason).toBe("it changed; refresh and preview again"); + expect(entry.row.forge).toBeUndefined(); +}); diff --git a/tests/removal/recheck.test.ts b/tests/removal/recheck.test.ts index 5c292cf..5576635 100644 --- a/tests/removal/recheck.test.ts +++ b/tests/removal/recheck.test.ts @@ -6,12 +6,16 @@ import fixture from "../fixtures/list-v2.json"; import { parseWorktrunk } from "../../src/core/worktrunk/list"; import { aged, + aheadPayload, + aheadRow, branchOnly, branchRemoved, branchRow, commandResult, + detachedRow, fakeRepos, noNewCommits, + proven, removed, repo, threeWorktrees, @@ -454,3 +458,53 @@ test("a branch named like a worktree's folder is not removed, since Worktrunk wo await rm(directory, { recursive: true, force: true }); } }); + +test("a worktree proven merged on GitHub whose HEAD moves after the repo's removals start is skipped, not force-deleted", async () => { + const payload = aheadPayload(); + const row = aheadRow(proven("bbb")); + const { calls, runner } = fakeRepos({ + payloads: { [repo]: payload }, + onRemove: (target) => { + if (target === detachedRow.path) payload.items[1].head.sha = "moved"; + }, + }); + const actions = createActionService({ wtPath: "/wt", runner, logPath: "/dev/null" }); + const plan = await actions.prepareRemoval([detachedRow, row]); + expect(plan.entries[1]?.branchProof).toEqual({ pr: 60 }); + const result = await actions.executeRemoval(plan, { + [detachedRow.id]: { include: true }, + [row.id]: { include: true }, + }); + expect(result.items[1]).toEqual({ + id: row.id, + status: "skipped", + error: "it changed; refresh and preview again", + }); + expect(removed(calls)).toEqual([detachedRow.path!]); +}); + +test("a branch proven merged on GitHub that moves after the repo's removals start is skipped, not force-deleted", async () => { + const payload = withBranch("ahead"); + const row = { ...branchOnly(payload), forge: proven("old-sha") }; + const tips: Record = { "refs/heads/old": "old-sha" }; + const { calls, runner } = fakeRepos({ + payloads: { [repo]: payload }, + tips, + onRemove: (target) => { + if (target === branchRow.path) tips["refs/heads/old"] = "newer"; + }, + }); + const actions = createActionService({ wtPath: "/wt", runner, logPath: "/dev/null", ...aged }); + const plan = await actions.prepareRemoval([branchRow, row]); + expect(plan.entries[1]?.branchProof).toEqual({ pr: 60 }); + const result = await actions.executeRemoval(plan, { + [branchRow.id]: { include: true }, + [row.id]: { include: true }, + }); + expect(result.items[1]).toEqual({ + id: row.id, + status: "skipped", + error: "it changed; refresh and preview again", + }); + expect(removed(calls)).toEqual([branchRow.path!]); +}); diff --git a/tests/support/app.ts b/tests/support/app.ts index ebc0b25..9357e24 100644 --- a/tests/support/app.ts +++ b/tests/support/app.ts @@ -7,7 +7,14 @@ import type { RepoSource } from "../../src/core/scan/discovery"; import type { CommandRunner } from "../../src/core/types"; import { runTerminal } from "../../src/ui/terminal"; import { sizeLabel } from "../../src/ui/format"; -import { createSandbox, type Built, type SavedRepos, type Sandbox, type Services } from "./fixture"; +import { + createSandbox, + type Built, + type FollowUp, + type SavedRepos, + type Sandbox, + type Services, +} from "./fixture"; /** Keys `press` sends by name; anything else is sent as typed text, so "D" is a shifted d. */ const NAMED = ["escape", "enter", "tab", "space", "backspace", "up", "down", "left", "right"]; @@ -61,7 +68,7 @@ const matches = (frame: string, match: FrameMatch): boolean => /** * Starts the real runTerminal on the sandbox's real services, in an OpenTUI test renderer. `sources` replaces the - * scan root, as from prepareStartup. + * scan root, as from prepareStartup. `followUp` is the dashboard's, as in `Sandbox.services`. */ export async function startApp( sandbox: Sandbox, @@ -71,15 +78,17 @@ export async function startApp( runner, sources, savedRepos, + followUp, }: { width: number; height?: number; runner?: CommandRunner; sources?: RepoSource[]; savedRepos?: SavedRepos; + followUp?: FollowUp; }, ): Promise { - const services = await sandbox.services({ runner, sources, savedRepos }); + const services = await sandbox.services({ runner, sources, savedRepos, followUp }); const setup = await createTestRenderer({ width, height }); const running = runTerminal(services.dashboard, { renderer: setup.renderer, @@ -221,6 +230,7 @@ export async function withApp( runner?: CommandRunner; sources?: RepoSource[]; savedRepos?: SavedRepos; + followUp?: FollowUp; name: string; }, body: (app: App) => Promise, diff --git a/tests/support/fixture.ts b/tests/support/fixture.ts index c658a43..6716ac0 100644 --- a/tests/support/fixture.ts +++ b/tests/support/fixture.ts @@ -4,7 +4,15 @@ import { tmpdir } from "node:os"; import { delimiter, dirname, join, resolve, sep } from "node:path"; import { createServices } from "../../src/app"; import type { ActionService } from "../../src/core/removal/types"; -import { discoverRepos, readCreatedAt, type RepoSource } from "../../src/core/scan/discovery"; +import { findProcesses } from "../../src/core/processes"; +import { createDashboardService } from "../../src/core/scan/dashboard"; +import { + discoverRepos, + findRepos, + readCreatedAt, + type RepoSource, +} from "../../src/core/scan/discovery"; +import { findOrphans } from "../../src/core/scan/orphans"; import type { CommandResult, CommandRunner, @@ -53,6 +61,8 @@ export interface ExecOptions { } export type SavedRepos = NonNullable[0]["savedRepos"]>; +/** The dashboard's per-repository follow-up, such as the check that asks GitHub about each row's tip. */ +export type FollowUp = NonNullable[0]["followUp"]>; export interface Services { dashboard: DashboardService; @@ -136,12 +146,14 @@ export interface Sandbox { repo(name: string): Promise; /** * Dashboard, action and size services on the sandbox; `cleanup` closes any still open. `runner` replaces the - * sandbox runner, for wrappers from tests/support/runners.ts. `sources` replaces the scan root. + * sandbox runner, for wrappers from tests/support/runners.ts. `sources` replaces the scan root. `followUp` + * patches each repository's rows after its listing, as the GitHub check does; saved repos are ignored with it. */ services(options?: { runner?: CommandRunner; sources?: RepoSource[]; savedRepos?: SavedRepos; + followUp?: FollowUp; }): Promise; /** Closes services, removes every worktree of the sandbox's repos, then the sandbox. Safe to call twice. */ cleanup(): Promise; @@ -597,21 +609,45 @@ export async function createSandbox( } async function services( - options: { runner?: CommandRunner; sources?: RepoSource[]; savedRepos?: SavedRepos } = {}, + options: { + runner?: CommandRunner; + sources?: RepoSource[]; + savedRepos?: SavedRepos; + followUp?: FollowUp; + } = {}, ): Promise { + const sources = options.sources ?? [{ kind: "scan", folder: scanRoot }]; + const commands = options.runner ?? runner; const app = await createServices({ home, - sources: options.sources ?? [{ kind: "scan", folder: scanRoot }], + sources, depth: 2, wtPath, - runner: options.runner ?? runner, + runner: commands, readCreated, savedRepos: options.savedRepos, }); + // createServices takes no follow-up, so this builds the same dashboard with one, minus saved repos. + const dashboard = options.followUp + ? createDashboardService({ + projectRoot: home, + wtPath, + runner: commands, + sizeService: app.sizes, + discover: async () => + [...new Set((await findRepos(sources, 2)).flatMap(({ repos }) => repos))].sort(), + readCreated, + findOrphans: (repos) => findOrphans(home, repos), + findProcesses: (paths, signal) => findProcesses(paths, commands, { signal }), + followUp: options.followUp, + }) + : app.dashboard; const service: Services = { ...app, + dashboard, async close() { if (!opened.delete(service)) return; + if (dashboard !== app.dashboard) await dashboard.close(); await app.close(); }, }; diff --git a/tests/terminal.test.ts b/tests/terminal.test.ts index b3d93e2..66dbbda 100644 --- a/tests/terminal.test.ts +++ b/tests/terminal.test.ts @@ -637,6 +637,58 @@ test("the confirm bar names uncommitted changes it will discard, and esc cancels } }); +test("the confirm dialog names the PR that proves a branch merged on GitHub, and D leaves that branch alone", async () => { + const item = row("api", 2000); + const { actions, executed } = fakeActions((rows) => + rows.map((selected) => entry(selected, { branchProof: { pr: 60 } })), + ); + const ui = await start(110, 24, [item], actions); + try { + ui.setup.mockInput.pressKey("x"); + let frame = await ui.frame(); + expect(frame).toContain("Deletes branch api: merged on GitHub as PR #60"); + expect(frame).not.toContain("Merged branches are deleted."); + expect(frame).not.toContain("unmerged branch"); + ui.setup.mockInput.pressKey("D"); + frame = await ui.frame(); + expect(frame).toContain("Every branch here is merged or detached; nothing extra to delete"); + ui.setup.mockInput.pressKey("y"); + await ui.frame(); + expect(executed[0]).toEqual({ + [item.id]: { + include: true, + discardChanges: false, + forceDeleteBranch: false, + reapProcesses: true, + }, + }); + } finally { + await ui.stop(); + } +}); + +test("the confirm dialog shortens the PRs of many branches merged on GitHub, beside merged and unmerged ones", async () => { + const items = ["api", "docs", "web", "merged", "open"].map((name) => row(name, 100)); + const { actions } = fakeActions(() => [ + entry(items[0]!, { branchProof: { pr: 60 } }), + entry(items[1]!, { branchProof: { pr: 61 } }), + entry(items[2]!, { branchProof: { pr: 62 } }), + entry(items[3]!), + entry(items[4]!, { branchWillBeRetained: true }), + ]); + const ui = await start(110, 30, items, actions); + try { + ui.setup.mockInput.pressKey("x"); + const frame = await ui.frame(); + expect(frame).toContain("Keeps 1 unmerged branch D delete too"); + expect(frame).toContain( + "Deletes 3 branches merged on GitHub: api (PR #60), docs (PR #61) +1 more", + ); + } finally { + await ui.stop(); + } +}); + test("the confirm dialog shows live sizes and says which are still sizing", async () => { const sized = row("api", 2000); const unsized = row("docs", 0, { sizeKiB: null, sizeMeasuredAt: null }); From 5ab7a11cdf9392440a0bcd8d8f074d179a7cf496 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 20:07:06 -0500 Subject: [PATCH 08/11] feat: add --offline and report GitHub in --doctor --- src/app.ts | 2 ++ src/cli.ts | 9 ++++++- src/index.ts | 9 ++++++- src/startup.ts | 5 +++- tests/cli.test.ts | 13 +++++++++- tests/e2e/first-run.test.ts | 47 ++++++++++++++++++++++++++++++++++++- tests/startup.test.ts | 13 ++++++++++ 7 files changed, 93 insertions(+), 5 deletions(-) diff --git a/src/app.ts b/src/app.ts index fa5dc07..6139242 100644 --- a/src/app.ts +++ b/src/app.ts @@ -26,6 +26,8 @@ export async function createServices(options: { readCreated?: (worktree: string) => Promise; /** Saves each scan's repositories to `file`, and with `listed` (a run without folders) lists the saved ones too. */ savedRepos?: { file: string; listed: boolean }; + /** Whether to ask GitHub, through the `gh` at `ghPath` (null when not found), if a merged pull request contains a commit. */ + github?: { offline: boolean; ghPath: string | null }; }): Promise { const { home, sources, depth, wtPath, runner, readCreated, savedRepos } = options; const cache = join(home, ".cache/wt-dash"); diff --git a/src/cli.ts b/src/cli.ts index 09b1693..ced5e2c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -19,6 +19,7 @@ To forget them, delete ~/.local/state/wt-dash/repos.json (in $XDG_STATE_HOME whe Options: --depth Folder levels to search below each root (0–20; default: 2) --wt-path Use a specific Worktrunk executable + --offline Don't ask GitHub about merged pull requests --doctor Check scan folders, Git, and Worktrunk without opening the UI -h, --help Show this help -v, --version Show the version @@ -37,6 +38,8 @@ export interface CliOptions { defaults: boolean; depth: number; wtPath?: string; + /** Don't run `gh` to ask GitHub whether a merged pull request contains a commit. */ + offline: boolean; } export function expandPath(path: string, home: string, cwd: string): string { @@ -45,7 +48,7 @@ export function expandPath(path: string, home: string, cwd: string): string { } export function parseArgs(args: string[], home: string, cwd: string): CliOptions { - const options: CliOptions = { mode: "run", roots: [], defaults: false, depth: 2 }; + const options: CliOptions = { mode: "run", roots: [], defaults: false, depth: 2, offline: false }; let positional = false; for (let index = 0; index < args.length; index++) { const arg = args[index]!; @@ -65,6 +68,10 @@ export function parseArgs(args: string[], home: string, cwd: string): CliOptions options.mode = "doctor"; continue; } + if (!positional && arg === "--offline") { + options.offline = true; + continue; + } if (!positional && (arg === "--depth" || arg === "--wt-path")) { const value = args[++index]; if (!value || value.startsWith("-")) diff --git a/src/index.ts b/src/index.ts index 3b82001..b72acb6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,12 @@ import { createServices } from "./app"; import { runCommand } from "./core/process"; import { savedReposFile } from "./core/scan/saved"; +function githubLine(offline: boolean, ghPath: string | null): string { + if (offline) return "GitHub: off (--offline)"; + if (!ghPath) return "GitHub: gh not found; rows Git can't prove merged stay Review"; + return `GitHub: checks merged pull requests with gh at ${ghPath}`; +} + async function main(): Promise { const home = homedir(); const options = parseArgs(process.argv.slice(2), home, process.cwd()); @@ -21,7 +27,7 @@ async function main(): Promise { const savedFile = savedReposFile(home); if (options.mode === "doctor") { console.log( - `wt-dash ${version}\nPlatform: ${platformName()} ${process.arch}\nGit: ${ready.gitVersion}\nWorktrunk: ${ready.wtVersion} (${ready.wtPath})\n${await doctorSources(ready.sources, options, savedFile)}\nSearch depth: ${options.depth}\nSetup checks passed.`, + `wt-dash ${version}\nPlatform: ${platformName()} ${process.arch}\nGit: ${ready.gitVersion}\nWorktrunk: ${ready.wtVersion} (${ready.wtPath})\n${githubLine(options.offline, ready.ghPath)}\n${await doctorSources(ready.sources, options, savedFile)}\nSearch depth: ${options.depth}\nSetup checks passed.`, ); return; } @@ -37,6 +43,7 @@ async function main(): Promise { wtPath: ready.wtPath, runner: runCommand, savedRepos: { file: savedFile, listed: options.defaults }, + github: { offline: options.offline, ghPath: ready.ghPath }, }); try { await runTerminal(dashboard, { diff --git a/src/startup.ts b/src/startup.ts index 6ed96a6..618f718 100644 --- a/src/startup.ts +++ b/src/startup.ts @@ -131,7 +131,10 @@ export async function prepareStartup( throw new Error( `Worktrunk 0.80.0 or newer is required; found ${wtVersion} at ${wtPath}.\nUpdate it with: brew upgrade worktrunk, or cargo install worktrunk`, ); - return { sources, wtPath, gitVersion, wtVersion }; + // A missing gh is not an error: the check that uses it is skipped. It is only looked for, never run, + // because even `gh auth status` contacts GitHub. + const ghPath = Bun.which("gh", { PATH: path }); + return { sources, wtPath, gitVersion, wtVersion, ghPath }; } /** diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 7e6d060..ee74dcc 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { parseArgs } from "../src/cli"; +import { help, parseArgs } from "../src/cli"; test("uses the default folders when none are given and resolves supplied folders independently", () => { expect(parseArgs([], "/Users/test", "/Users/test/code")).toMatchObject({ @@ -39,6 +39,17 @@ test("rejects unknown options, missing values, and invalid scan depths", () => { ]); }); +test("--offline is parsed, off by default, and listed in the help", () => { + expect(parseArgs([], "/home", "/repo").offline).toBe(false); + expect(parseArgs(["--offline", "."], "/home", "/repo")).toMatchObject({ + offline: true, + mode: "run", + roots: ["/repo"], + }); + expect(parseArgs(["--", "--offline"], "/home", "/repo").roots).toEqual(["/repo/--offline"]); + expect(help).toContain("--offline Don't ask GitHub about merged pull requests"); +}); + test("help, version and doctor have explicit modes", () => { expect(parseArgs(["--help"], "/home", "/repo").mode).toBe("help"); expect(parseArgs(["-v"], "/home", "/repo").mode).toBe("version"); diff --git a/tests/e2e/first-run.test.ts b/tests/e2e/first-run.test.ts index c2de4a2..9d546d1 100644 --- a/tests/e2e/first-run.test.ts +++ b/tests/e2e/first-run.test.ts @@ -4,7 +4,7 @@ import { delimiter, join, resolve } from "node:path"; import { parseArgs } from "../../src/cli"; import { prepareStartup } from "../../src/startup"; import { inSandbox, withApp, TEST_TIMEOUT } from "../support/app"; -import type { Sandbox } from "../support/fixture"; +import { createSandbox, type Sandbox } from "../support/fixture"; import { savedReposFile } from "../../src/core/scan/saved"; async function repoWithWorktree(sandbox: Sandbox, path: string, branch: string, worktree: string) { @@ -124,6 +124,51 @@ test( TEST_TIMEOUT, ); +async function doctor(sandbox: Sandbox, ...args: string[]) { + const child = Bun.spawn( + [process.execPath, join(import.meta.dir, "../../src/index.ts"), "--doctor", ...args], + { cwd: sandbox.home, env: sandbox.env, stdout: "pipe", stderr: "pipe" }, + ); + const [stdout, stderr, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + expect({ code, stderr }).toEqual({ code: 0, stderr: "" }); + return stdout; +} + +test( + "--doctor says whether pull requests are checked with gh, and never runs it", + () => + inSandbox(async (sandbox) => { + await arrangeFirstRun(sandbox); + expect(await doctor(sandbox)).toContain( + `GitHub: checks merged pull requests with gh at ${join(sandbox.gh.bin, "gh")}\n`, + ); + expect(await doctor(sandbox, "--offline")).toContain("GitHub: off (--offline)\n"); + expect(await sandbox.gh.calls()).toEqual([]); + }), + TEST_TIMEOUT, +); + +test( + "--doctor says when gh is not found and what that costs", + async () => { + const sandbox = await createSandbox({ gh: "missing" }); + try { + await arrangeFirstRun(sandbox); + expect(await doctor(sandbox)).toContain( + "GitHub: gh not found; rows Git can't prove merged stay Review\n", + ); + expect(await doctor(sandbox, "--offline")).toContain("GitHub: off (--offline)\n"); + } finally { + await sandbox.cleanup(); + } + }, + TEST_TIMEOUT, +); + test( "--doctor accepts a Worktrunk built from crates.io, whose --version reads wt 0.80.0 (#59)", () => diff --git a/tests/startup.test.ts b/tests/startup.test.ts index 9d9410b..0811a28 100644 --- a/tests/startup.test.ts +++ b/tests/startup.test.ts @@ -35,6 +35,19 @@ test("finds dependencies on PATH and deduplicates resolved scan folders", async expect(ready.gitVersion).toContain("2.50.0"); }); +test("finds gh on PATH without running it, and a missing gh is not an error", async () => { + const { root, bin } = await environment(); + const options = parseArgs([root], root, root); + expect((await prepareStartup(options, { platform: "darwin", path: bin })).ghPath).toBeNull(); + // A gh that leaves a mark if it runs, as `gh auth status` would contact GitHub. + const marker = join(root, "gh-ran"); + await writeFile(join(bin, "gh"), `#!/bin/sh\ntouch '${marker}'\n`); + await chmod(join(bin, "gh"), 0o755); + const ready = await prepareStartup(options, { platform: "darwin", path: bin }); + expect(ready.ghPath).toBe(join(bin, "gh")); + expect(await Bun.file(marker).exists()).toBe(false); +}); + test("honors an explicit executable instead of a different Worktrunk on PATH", async () => { const { root, bin } = await environment(); const path = join(root, "custom-wt"); From 22ec1cbcd2a869bd0fa31a91437c1823dbec5c9a Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 20:23:22 -0500 Subject: [PATCH 09/11] feat: check unproven rows against merged GitHub pull requests --- README.md | 13 +- src/app.ts | 22 +- src/core/git/refs.ts | 18 ++ src/core/github/cache.ts | 79 ++++++ src/core/github/check.ts | 195 ++++++++++++++ src/core/github/gh.ts | 75 ++++++ src/core/github/query.ts | 238 +++++++++++++++++ src/core/github/remote.ts | 47 ++++ src/core/scan/dashboard.ts | 16 +- src/core/types.ts | 29 ++- src/core/worktrunk/list.ts | 1 + src/ui/render/chrome.ts | 7 +- tests/e2e/merged-on-github.test.ts | 39 +++ tests/git/refs.test.ts | 22 +- tests/github/cache.test.ts | 94 +++++++ tests/github/check.test.ts | 377 +++++++++++++++++++++++++++ tests/github/gh.test.ts | 128 +++++++++ tests/github/query.test.ts | 340 ++++++++++++++++++++++++ tests/github/remote.test.ts | 68 +++++ tests/integration/github.test.ts | 405 +++++++++++++++++++++++------ tests/support/app.ts | 8 +- tests/support/fixture.ts | 66 ++--- tests/terminal.test.ts | 15 ++ 23 files changed, 2158 insertions(+), 144 deletions(-) create mode 100644 src/core/github/cache.ts create mode 100644 src/core/github/check.ts create mode 100644 src/core/github/gh.ts create mode 100644 src/core/github/query.ts create mode 100644 src/core/github/remote.ts create mode 100644 tests/github/cache.test.ts create mode 100644 tests/github/check.test.ts create mode 100644 tests/github/gh.test.ts create mode 100644 tests/github/query.test.ts create mode 100644 tests/github/remote.test.ts diff --git a/README.md b/README.md index 126ef55..81aee75 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ Everywhere, `r` rescans every repository, `?` shows every key, and `q` or `ctrl+ | Verdict | Status | Removal | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------- | -| **Safe** | no new commits, merged | Allowed | +| **Safe** | no new commits, merged, merged on GitHub | Allowed | | **Review** | uncommitted changes, unpushed commits, unmerged commits, behind main, unrelated history; no new commits, under a day old; an agent marked it in the last day | Allowed after you read the warning | | **Review** | locked, status unknown | Blocked | | **Busy** | rebase, merge, or cherry-pick in progress; unresolved conflicts | Blocked | @@ -165,10 +165,14 @@ wt-dash also reads agent marks. Worktrunk's agent plugins, such as the one `wt c Running processes don't change a verdict. After each scan the strip shows the processes whose working directory is inside a worktree, with the TCP ports they listen on, such as `2 processes · :3000 :5173`, and `i` lists each one's command. A process that holds a terminal, such as a shell or a terminal editor, reads `zsh (terminal)`. The remove dialog names the worktrees that have one. -wt-dash does not check pull request status. - +### Pull requests merged on GitHub + +A squash merge on GitHub puts a branch's work into the default branch as a new commit, so Git often can't tell the branch is merged, and the row stays Review with unmerged commits. For these rows only, wt-dash asks GitHub through your own `gh` whether a merged pull request holds the branch's last commit, or a commit with exactly the same files. If one does, the row is Safe with a reason such as "PR #42 merged Oct 30 with this exact commit". A branch without a worktree still waits until it is a day old. If none does, the row stays Review, and the reason says what GitHub found, such as "PR #42 merged Oct 30 without this commit", or why GitHub wasn't asked. + +GitHub is asked only about clean worktrees and branches whose commits are all pushed and that Git can't show merged, and only in a repository whose default branch tracks a github.com remote (or, tracking none, whose `origin` is on github.com). For each such repository, a scan sends one read-only GraphQL query with `gh api graphql`, holding the repository's owner and name and those rows' commit IDs and branch names. A second query follows only when a pull request was merged into another branch first. The header reads "checking GitHub" while it waits. A merged pull request never changes, so each proof is kept in `~/.cache/wt-dash/pull-requests.json` and its commit isn't asked about again. Run with `--offline` to never ask; rows GitHub could settle then say they weren't checked. + ### Orphaned folders Git and Worktrunk find a worktree only through its repository, so neither can see a worktree folder whose link to its repository is broken. wt-dash looks for these in the folders agents keep worktrees in: `.claude/worktrees` inside each scanned repository, `~/.codex/worktrees`, and t3's `~/.t3/worktrees` and `~/.t3-lines/lines/worktrees`. They are listed under "Orphaned folders", last on the projects screen and in "All projects", with their size and the reason: @@ -245,6 +249,7 @@ wt-dash --doctor # check Git, Worktrunk and folder access without openin | ---------------------------------- | --------------------------------------------------------- | | `--depth ` | Folder levels to search below each root, 0–20 (default 2) | | `--wt-path ` | Use a specific Worktrunk executable | +| `--offline` | Never ask GitHub about merged pull requests | | `--doctor` | Check the setup and exit | | `-h`, `--help` / `-v`, `--version` | Show help or the version | @@ -272,7 +277,7 @@ Projects with the most worktrees come first, each with how much space its Safe w ### Good to know - Sizes come from `du` and are cached in `~/.cache/wt-dash/sizes.json`. A worktree is measured again when its saved size is more than a day old, or when files were added or removed at the top level of the worktree or its `node_modules` folder. Press `R` to remeasure the focused worktree. Totals read "up to" because disk blocks shared between files can make `du` overstate the space you get back. -- wt-dash runs Git and Worktrunk locally. It makes no network requests of its own and never changes your Worktrunk settings. +- wt-dash runs Git and Worktrunk locally and never changes your Worktrunk settings. It reaches the network only to ask GitHub about [merged pull requests](#pull-requests-merged-on-github), through your own `gh`. ## Contributing diff --git a/src/app.ts b/src/app.ts index fa5dc07..d15057b 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,7 +1,9 @@ import { join } from "node:path"; +import { createProofCache } from "./core/github/cache"; +import { createGitHubCheck, type GitHubOptions } from "./core/github/check"; import { createActionService } from "./core/removal/service"; import type { ActionService } from "./core/removal/types"; -import { createDashboardService } from "./core/scan/dashboard"; +import { createDashboardService, type FollowUp } from "./core/scan/dashboard"; import { findRepos, type RepoSource } from "./core/scan/discovery"; import { findProcesses } from "./core/processes"; import { findOrphans } from "./core/scan/orphans"; @@ -13,7 +15,7 @@ export interface Services { dashboard: DashboardService; actions: ActionService; sizes: SizeService; - /** Closes the dashboard, then saves and closes the size cache. */ + /** Closes the dashboard, then saves and closes the size and pull request caches. */ close(): Promise; } @@ -26,11 +28,16 @@ export async function createServices(options: { readCreated?: (worktree: string) => Promise; /** Saves each scan's repositories to `file`, and with `listed` (a run without folders) lists the saved ones too. */ savedRepos?: { file: string; listed: boolean }; + /** How rows Git can't prove merged are checked against GitHub; offline when omitted. */ + github?: GitHubOptions; + /** Runs after each repository's listing in place of the GitHub check. */ + followUp?: FollowUp; }): Promise { const { home, sources, depth, wtPath, runner, readCreated, savedRepos } = options; const cache = join(home, ".cache/wt-dash"); const sizes = createSizeService(join(cache, "sizes.json"), runner); - await sizes.load(); + const proofs = createProofCache(join(cache, "pull-requests.json")); + await Promise.all([sizes.load(), proofs.load()]); const dashboard = createDashboardService({ projectRoot: home, wtPath, @@ -47,6 +54,13 @@ export async function createServices(options: { readCreated, findOrphans: (repos) => findOrphans(home, repos), findProcesses: (paths, signal) => findProcesses(paths, runner, { signal }), + followUp: + options.followUp ?? + createGitHubCheck({ + github: options.github ?? { offline: true, ghPath: null }, + runner, + proofs, + }), }); const actions = createActionService({ wtPath, @@ -60,7 +74,7 @@ export async function createServices(options: { sizes, async close() { await dashboard.close(); - await sizes.close(); + await Promise.all([sizes.close(), proofs.close()]); }, }; } diff --git a/src/core/git/refs.ts b/src/core/git/refs.ts index d203fb5..a5c6ff3 100644 --- a/src/core/git/refs.ts +++ b/src/core/git/refs.ts @@ -99,6 +99,24 @@ export async function readTips( return new Map(unique.map((ref, index) => [ref, tips[index]!])); } +/** Each commit's tree, from one `git rev-parse`; empty when Git can't read every one of them. */ +export async function readTrees( + repo: string, + commits: string[], + runner: CommandRunner, + signal?: AbortSignal, +): Promise> { + if (!commits.length) return new Map(); + const result = await runner( + "git", + ["-C", repo, "rev-parse", ...commits.map((commit) => `${commit}^{tree}`)], + signal, + ); + const trees = result.stdout.trim().split("\n"); + if (result.exitCode !== 0 || trees.length !== commits.length) return new Map(); + return new Map(commits.map((commit, index) => [commit, trees[index]!])); +} + /** * When a branch without a worktree was created, the way `wt step prune` judges its age: its oldest reflog * entry, or else when Git last wrote its ref. Null when neither can be read, as in a reftable repository. diff --git a/src/core/github/cache.ts b/src/core/github/cache.ts new file mode 100644 index 0000000..38f731f --- /dev/null +++ b/src/core/github/cache.ts @@ -0,0 +1,79 @@ +import { createCacheFile } from "../cache-file"; +import type { ForgeProof, ForgeProofKind } from "../types"; +import type { GitHubRepo } from "./remote"; + +/** + * Proofs GitHub gave, kept forever because a merged pull request never changes. Only proofs are kept: a tip + * GitHub didn't know may be merged later. + */ +export interface ProofCache { + load(): Promise; + get(repo: GitHubRepo, tip: string): ForgeProof | null; + /** Saves the proofs in the background; `close` waits for the write. */ + add(repo: GitHubRepo, proofs: ForgeProof[]): void; + close(): Promise; +} + +/** `owner/name@`, lowercased, as GitHub matches names without case. */ +export const proofKey = (repo: GitHubRepo, tip: string) => + `${repo.owner}/${repo.name}@${tip}`.toLowerCase(); + +const kinds: ForgeProofKind[] = ["commit", "tree", "stacked"]; + +function parseProofs(raw: unknown): Map { + const proofs = new Map(); + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return proofs; + for (const [key, value] of Object.entries(raw)) { + if (typeof value !== "object" || value === null) continue; + const { tip, pr, mergedAt, base, by } = value as Record; + if ( + typeof tip === "string" && + /^[0-9a-f]{40}$/.test(tip) && + key.endsWith(`@${tip}`) && + Number.isSafeInteger(pr) && + (pr as number) > 0 && + typeof mergedAt === "string" && + typeof base === "string" && + kinds.includes(by as ForgeProofKind) + ) + proofs.set(key, { + kind: "proven", + tip, + pr: pr as number, + mergedAt, + base, + by: by as ForgeProofKind, + }); + } + return proofs; +} + +export function createProofCache(path: string): ProofCache { + const proofs = new Map(); + const file = createCacheFile>(path, { + parse: parseProofs, + serialize: (entries) => + Object.fromEntries( + [...entries].map(([key, { tip, pr, mergedAt, base, by }]) => [ + key, + { tip, pr, mergedAt, base, by }, + ]), + ), + empty: () => new Map(), + }); + return { + async load() { + proofs.clear(); + for (const [key, proof] of await file.load()) proofs.set(key, proof); + }, + get(repo, tip) { + return proofs.get(proofKey(repo, tip)) ?? null; + }, + add(repo, added) { + if (!added.length) return; + for (const proof of added) proofs.set(proofKey(repo, proof.tip), proof); + void file.save(proofs); + }, + close: () => file.flush(), + }; +} diff --git a/src/core/github/check.ts b/src/core/github/check.ts new file mode 100644 index 0000000..c41bcd7 --- /dev/null +++ b/src/core/github/check.ts @@ -0,0 +1,195 @@ +import { readTrees } from "../git/refs"; +import type { FollowUp } from "../scan/dashboard"; +import type { CommandRunner, ForgeCheck, WorktreeFacts, WorktreeRow } from "../types"; +import type { ProofCache } from "./cache"; +import { GH_TIMEOUT_MS, runGraphql, type GhOutcome } from "./gh"; +import { + chainedRequest, + chunk, + lookupRequest, + readChained, + readLookup, + type GraphqlRequest, + type LookupRow, +} from "./query"; +import { readGitHubRepo, type GitHubRepo } from "./remote"; + +export interface GitHubOptions { + /** Never ask GitHub; rows it could settle say so. */ + offline: boolean; + /** The user's `gh`, or null when it wasn't found. */ + ghPath: string | null; +} + +/** States in which Worktrunk couldn't show the branch's work is in the default branch. */ +const UNPROVEN = new Set(["ahead", "would_conflict", "diverged", "behind"]); + +/** + * Whether GitHub may settle the row: a clean worktree or a branch, with every commit pushed, whose work + * Worktrunk couldn't find in the default branch, and nothing else keeping it out of Safe. + */ +export function canAskGitHub(row: WorktreeFacts): boolean { + if (row.kind !== "worktree" && row.kind !== "branch") return false; + if (!row.headSha || !/^[0-9a-f]{40}$/.test(row.headSha)) return false; + if (!row.mainState || !UNPROVEN.has(row.mainState)) return false; + if (row.operation || row.locked || row.prunable) return false; + if (row.upstreamAhead !== null && row.upstreamAhead > 0) return false; + const changes = row.changes; + if (row.kind === "worktree" && changes?.conflicted !== false) return false; + return !( + changes && + (changes.staged || + changes.modified || + changes.untracked || + changes.renamed || + changes.deleted || + changes.conflicted) + ); +} + +type Unchecked = Extract; +/** Merged pull requests from one branch into the default branch. */ +type MergedInto = NonNullable[number]>; +const unchecked = (why: Unchecked["why"]): Unchecked => ({ kind: "unchecked", why }); + +/** + * The dashboard follow-up that asks GitHub, through the user's `gh`, whether a merged pull request holds each + * eligible row's tip. Every other row gets no forge check; aborting reports nothing. + */ +export function createGitHubCheck(options: { + github: GitHubOptions; + runner: CommandRunner; + proofs: ProofCache; + timeoutMs?: number; +}): FollowUp { + const { github, runner, proofs, timeoutMs = GH_TIMEOUT_MS } = options; + + async function check( + repo: string, + rows: WorktreeRow[], + signal: AbortSignal, + ): Promise> { + const forges = new Map(); + const remote = await readGitHubRepo(repo, rows[0]!.defaultBranch, runner, signal); + if (!remote) { + for (const row of rows) forges.set(row.id, unchecked("no-github-remote")); + return forges; + } + const uncached = rows.filter((row) => { + const proof = proofs.get(remote, row.headSha!); + if (proof) forges.set(row.id, proof); + return !proof; + }); + if (!uncached.length) return forges; + if (github.offline || github.ghPath === null) { + const why = unchecked(github.offline ? "offline" : "gh-missing"); + for (const row of uncached) forges.set(row.id, why); + return forges; + } + const found = await lookUp(repo, remote, uncached, github.ghPath, signal); + proofs.add( + remote, + [...found.values()].flatMap((forge) => (forge.kind === "proven" ? [forge] : [])), + ); + for (const [id, forge] of found) forges.set(id, forge); + return forges; + } + + /** Sends each request in turn; once gh is missing or signed out, the rest get the same answer unsent. */ + function sender(ghPath: string, signal: AbortSignal) { + let stop: GhOutcome | null = null; + return async (request: GraphqlRequest): Promise => { + if (stop) return stop; + const outcome = await runGraphql(ghPath, request, runner, signal, timeoutMs); + if (outcome.kind === "unchecked" && outcome.why !== "failed") stop = outcome; + return outcome; + }; + } + + async function lookUp( + repo: string, + remote: GitHubRepo, + rows: WorktreeRow[], + ghPath: string, + signal: AbortSignal, + ): Promise> { + const send = sender(ghPath, signal); + const trees = await readTrees( + repo, + rows.map((row) => row.headSha!), + runner, + signal, + ); + const found = new Map(); + /** Rows a merged pull request took into another branch than the default, and those branches. */ + const stacked: Array<{ row: WorktreeRow; bases: string[] }> = []; + let defaultBranch: string | null = null; + for (const part of chunk(rows)) { + const asked: LookupRow[] = part.map((row) => ({ + tip: row.headSha!, + tree: trees.get(row.headSha!) ?? null, + heads: [ + ...new Set([row.branch, row.upstreamBranch].filter((name): name is string => !!name)), + ], + })); + const { request, heads } = lookupRequest(remote, asked); + const reply = await send(request); + if (reply.kind === "unchecked") { + for (const row of part) found.set(row.id, reply); + continue; + } + const read = readLookup(remote, asked, heads, reply); + defaultBranch ??= read.defaultBranch; + read.answers.forEach((answer, index) => { + const row = part[index]!; + if (answer.kind === "proven") found.set(row.id, answer.proof); + else if (answer.kind === "failed") found.set(row.id, unchecked("failed")); + else { + found.set(row.id, { + kind: "not-found", + tip: row.headSha!, + ...(answer.samePr ? { samePr: answer.samePr } : {}), + }); + if (answer.bases.length) stacked.push({ row, bases: answer.bases }); + } + }); + } + if (!stacked.length || !defaultBranch) return found; + + // Stacked pull requests: was a branch the tip went into merged into the default branch with the tip in it? + const merges = new Map(); + for (const bases of chunk([...new Set(stacked.flatMap(({ bases }) => bases))])) { + const reply = await send(chainedRequest(remote, defaultBranch, bases)); + const lists = reply.kind === "unchecked" ? bases.map(() => reply) : readChained(bases, reply); + lists.forEach((list, index) => merges.set(bases[index]!, list ?? unchecked("failed"))); + } + for (const { row, bases } of stacked) { + const answers = bases.map((base) => merges.get(base)!); + const pr = answers + .flatMap((answer) => (Array.isArray(answer) ? answer : [])) + .find(({ commits }) => commits.includes(row.headSha!)); + const failure = answers.find((answer): answer is Unchecked => !Array.isArray(answer)); + if (pr) + found.set(row.id, { + kind: "proven", + tip: row.headSha!, + pr: pr.number, + mergedAt: pr.mergedAt, + base: defaultBranch, + by: "stacked", + }); + else if (failure) found.set(row.id, failure); + } + return found; + } + + return async (repo, rows, signal) => { + const asked = rows.filter(canAskGitHub); + const forges = asked.length ? await check(repo, asked, signal) : new Map(); + return rows.flatMap((row) => + row.headSha === null + ? [] + : [{ id: row.id, headSha: row.headSha, facts: { forge: forges.get(row.id) } }], + ); + }; +} diff --git a/src/core/github/gh.ts b/src/core/github/gh.ts new file mode 100644 index 0000000..7b01e9f --- /dev/null +++ b/src/core/github/gh.ts @@ -0,0 +1,75 @@ +import type { CommandRunner, ForgeUncheckedReason } from "../types"; +import type { GraphqlReply, GraphqlRequest } from "./query"; + +/** How long one request may take before its rows count as not checked. */ +export const GH_TIMEOUT_MS = 15_000; + +/** gh never stops to ask a question or to announce an update. */ +export const GH_ENV = { GH_NO_UPDATE_NOTIFIER: "1", GH_PROMPT_DISABLED: "1" }; + +export type GhOutcome = + | ({ kind: "reply" } & GraphqlReply) + | { + kind: "unchecked"; + why: Extract; + }; + +/** `gh api graphql` with the query and every variable passed as a raw string with `-f`. */ +export function ghArgs(request: GraphqlRequest): string[] { + return [ + "api", + "graphql", + "-f", + `query=${request.query}`, + ...Object.entries(request.variables).flatMap(([key, value]) => ["-f", `${key}=${value}`]), + ]; +} + +const object = (value: unknown): Record | null => + typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : null; + +/** + * Sends `request` through the user's `gh` at `ghPath`. Exit 1 with JSON on stdout still gives the data GitHub + * returned, with its errors' paths. Throws only when `signal` aborts, so an aborted check reports nothing. + */ +export async function runGraphql( + ghPath: string, + request: GraphqlRequest, + runner: CommandRunner, + signal: AbortSignal, + timeoutMs = GH_TIMEOUT_MS, +): Promise { + const unchecked = (why: Extract["why"]): GhOutcome => ({ + kind: "unchecked", + why, + }); + const timeout = AbortSignal.timeout(timeoutMs); + let result; + try { + result = await runner(ghPath, ghArgs(request), AbortSignal.any([signal, timeout]), GH_ENV); + } catch (error) { + if (signal.aborted) throw error; + if (timeout.aborted) return unchecked("failed"); + return unchecked((error as NodeJS.ErrnoException).code === "ENOENT" ? "gh-missing" : "failed"); + } + if (signal.aborted) throw new Error("Command aborted"); + if (result.exitCode === 4) return unchecked("signed-out"); + if (result.exitCode !== 0 && result.exitCode !== 1) return unchecked("failed"); + let body: Record | null; + try { + body = object(JSON.parse(result.stdout) as unknown); + } catch { + return unchecked("failed"); + } + const data = object(body?.data); + const errors = Array.isArray(body?.errors) ? body.errors.map(object) : []; + if (!data || errors.some((error) => error?.type === "MAX_NODE_LIMIT_EXCEEDED")) + return unchecked("failed"); + return { + kind: "reply", + repository: data.repository ?? null, + errorPaths: errors.map((error) => (Array.isArray(error?.path) ? error.path : null)), + }; +} diff --git a/src/core/github/query.ts b/src/core/github/query.ts new file mode 100644 index 0000000..f7065b2 --- /dev/null +++ b/src/core/github/query.ts @@ -0,0 +1,238 @@ +import type { ForgeProof } from "../types"; +import type { GitHubRepo } from "./remote"; + +/** Rows asked about in one request, which keeps it far below GitHub's limit of 500,000 nodes. */ +export const ROWS_PER_REQUEST = 100; + +export interface GraphqlRequest { + query: string; + /** Every value is sent as a string with `-f`. */ + variables: Record; +} + +/** What GitHub returned for `repository`, and where its errors were. */ +export interface GraphqlReply { + /** `data.repository`; null when GitHub couldn't resolve the repository. */ + repository: unknown; + /** Each error's `path`, or null for an error without one. */ + errorPaths: Array; +} + +/** A row to ask about: its tip, the tip's tree when Git could read it, and the branch names it was pushed as. */ +export interface LookupRow { + tip: string; + tree: string | null; + heads: string[]; +} + +export type LookupAnswer = + | { kind: "proven"; proof: ForgeProof } + | { + kind: "not-found"; + samePr?: { number: number; mergedAt: string }; + /** Branches other than the default that a merged pull request brought the tip into. */ + bases: string[]; + } + | { kind: "failed" }; + +export function chunk(items: T[], size = ROWS_PER_REQUEST): T[][] { + const chunks: T[][] = []; + for (let start = 0; start < items.length; start += size) + chunks.push(items.slice(start, start + size)); + return chunks; +} + +const MERGED_FROM = "states:MERGED, first:5, orderBy:{field:CREATED_AT,direction:DESC}"; + +/** + * One query for up to `ROWS_PER_REQUEST` rows: `aN` asks which pull requests hold row N's tip, and `bN` lists + * the merged pull requests from `heads[N]`, a branch name some row was pushed as. + */ +export function lookupRequest( + repo: GitHubRepo, + rows: LookupRow[], +): { request: GraphqlRequest; heads: string[] } { + const heads = [...new Set(rows.flatMap((row) => row.heads))]; + const variables: Record = { owner: repo.owner, name: repo.name }; + rows.forEach((row, index) => (variables[`oid${index}`] = row.tip)); + heads.forEach((head, index) => (variables[`head${index}`] = head)); + const declared = [ + "$owner:String!", + "$name:String!", + ...rows.map((_, index) => `$oid${index}:GitObjectID!`), + ...heads.map((_, index) => `$head${index}:String!`), + ]; + const fields = [ + ...rows.map( + (_, index) => + `a${index}: object(oid:$oid${index}) { ... on Commit { associatedPullRequests(first:5) { nodes { number state mergedAt baseRefName headRefName headRefOid repository { nameWithOwner defaultBranchRef { name } } } } } }`, + ), + ...heads.map( + (_, index) => + `b${index}: pullRequests(headRefName:$head${index}, ${MERGED_FROM}) { nodes { number mergedAt baseRefName headRefOid headRepository { nameWithOwner } commits(last:250) { nodes { commit { oid tree { oid } } } } } }`, + ), + ]; + const query = `query(${declared.join(",")}) { + rateLimit { cost remaining } + repository(owner:$owner, name:$name) { + defaultBranchRef { name } +${fields.map((field) => ` ${field}`).join("\n")} + } +}`; + return { request: { query, variables }, heads }; +} + +/** The follow-up query for stacked pull requests: `kN` lists merged pull requests from `bases[N]` into `defaultBranch`. */ +export function chainedRequest( + repo: GitHubRepo, + defaultBranch: string, + bases: string[], +): GraphqlRequest { + const variables: Record = { + owner: repo.owner, + name: repo.name, + default: defaultBranch, + }; + bases.forEach((base, index) => (variables[`base${index}`] = base)); + const declared = [ + "$owner:String!", + "$name:String!", + "$default:String!", + ...bases.map((_, index) => `$base${index}:String!`), + ]; + const fields = bases.map( + (_, index) => + `k${index}: pullRequests(headRefName:$base${index}, baseRefName:$default, ${MERGED_FROM}) { nodes { number mergedAt commits(last:250) { nodes { commit { oid } } } } }`, + ); + const query = `query(${declared.join(",")}) { + rateLimit { cost remaining } + repository(owner:$owner, name:$name) { +${fields.map((field) => ` ${field}`).join("\n")} + } +}`; + return { query, variables }; +} + +// ---- Reading replies. GitHub's JSON is checked field by field; anything malformed counts as absent. + +type Json = Record; + +const object = (value: unknown): Json | null => + typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Json) : null; +const text = (value: unknown): string | null => (typeof value === "string" ? value : null); +const nodes = (connection: unknown): Json[] => { + const list = object(connection)?.nodes; + return Array.isArray(list) ? list.map(object).filter((node): node is Json => node !== null) : []; +}; + +interface MergedPr { + number: number; + mergedAt: string; +} + +/** The pull request's number and merge time, or null when GitHub gave either malformed. */ +function merged(node: Json): MergedPr | null { + const number = node.number; + const mergedAt = text(node.mergedAt); + return Number.isSafeInteger(number) && (number as number) > 0 && mergedAt + ? { number: number as number, mergedAt } + : null; +} + +const sameRepo = (nameWithOwner: unknown, repo: GitHubRepo) => + text(nameWithOwner)?.toLowerCase() === `${repo.owner}/${repo.name}`.toLowerCase(); + +const commitOids = (node: Json, field: "oid" | "tree"): string[] => + nodes(node.commits).flatMap((entry) => { + const commit = object(entry.commit); + const oid = field === "oid" ? text(commit?.oid) : text(object(commit?.tree)?.oid); + return oid ?? []; + }); + +/** + * The aliases under `repository` that GitHub reported errors for, or "all" when an error names the repository + * itself or no field at all. + */ +function failedAliases(reply: GraphqlReply): Set | "all" { + const failed = new Set(); + for (const path of reply.errorPaths) { + if (!path || path.length === 0) return "all"; + if (path[0] !== "repository") continue; + if (path.length === 1 || typeof path[1] !== "string") return "all"; + failed.add(path[1]); + } + return object(reply.repository) ? failed : "all"; +} + +/** Each row's answer, given the reply to `lookupRequest(repo, rows)` and its `heads`. */ +export function readLookup( + repo: GitHubRepo, + rows: LookupRow[], + heads: string[], + reply: GraphqlReply, +): { defaultBranch: string | null; answers: LookupAnswer[] } { + const failed = failedAliases(reply); + if (failed === "all") + return { defaultBranch: null, answers: rows.map(() => ({ kind: "failed" })) }; + const repository = object(reply.repository)!; + const defaultBranch = text(object(repository.defaultBranchRef)?.name); + const answers = rows.map((row, index): LookupAnswer => { + const prove = (pr: MergedPr, base: string, by: ForgeProof["by"]): LookupAnswer => ({ + kind: "proven", + proof: { kind: "proven", tip: row.tip, pr: pr.number, mergedAt: pr.mergedAt, base, by }, + }); + // Proof A: GitHub lists a merged pull request of this repository holding the exact tip. + const bases = new Set(); + for (const node of nodes(object(repository[`a${index}`])?.associatedPullRequests)) { + const pr = merged(node); + const target = object(node.repository); + const base = text(node.baseRefName); + if (!pr || node.state !== "MERGED" || !base || !sameRepo(target?.nameWithOwner, repo)) + continue; + if (base === text(object(target?.defaultBranchRef)?.name)) return prove(pr, base, "commit"); + bases.add(base); + } + // Proof B: a pull request from the branch, merged into the default branch, has a commit with the tip's files. + const aliases = [`a${index}`, ...row.heads.map((head) => `b${heads.indexOf(head)}`)]; + let samePr: MergedPr | undefined; + for (const alias of aliases.slice(1)) { + for (const node of nodes(repository[alias])) { + const pr = merged(node); + if ( + !pr || + !defaultBranch || + text(node.baseRefName) !== defaultBranch || + !sameRepo(object(node.headRepository)?.nameWithOwner, repo) + ) + continue; + if (row.tree && commitOids(node, "tree").includes(row.tree)) + return prove(pr, defaultBranch, "tree"); + if (!samePr || Date.parse(pr.mergedAt) > Date.parse(samePr.mergedAt)) samePr = pr; + } + } + if (aliases.some((alias) => failed.has(alias))) return { kind: "failed" }; + return { kind: "not-found", ...(samePr ? { samePr } : {}), bases: [...bases] }; + }); + return { defaultBranch, answers }; +} + +/** + * For each base in `chainedRequest`'s order, the merged pull requests from it into the default branch with their + * commits, or null when GitHub reported an error for it. + */ +export function readChained( + bases: string[], + reply: GraphqlReply, +): Array | null> { + const failed = failedAliases(reply); + if (failed === "all") return bases.map(() => null); + const repository = object(reply.repository)!; + return bases.map((_, index) => + failed.has(`k${index}`) + ? null + : nodes(repository[`k${index}`]).flatMap((node) => { + const pr = merged(node); + return pr ? [{ ...pr, commits: commitOids(node, "oid") }] : []; + }), + ); +} diff --git a/src/core/github/remote.ts b/src/core/github/remote.ts new file mode 100644 index 0000000..11a3282 --- /dev/null +++ b/src/core/github/remote.ts @@ -0,0 +1,47 @@ +import type { CommandRunner } from "../types"; + +export interface GitHubRepo { + owner: string; + name: string; +} + +const owner = "([A-Za-z0-9][A-Za-z0-9-]*)"; +const name = "([A-Za-z0-9._-]+?)"; +const end = "(?:\\.git)?/?$"; +const forms = [ + new RegExp(`^https://(?:[^@/]+@)?github\\.com/${owner}/${name}${end}`, "i"), + new RegExp(`^git@github\\.com:${owner}/${name}${end}`, "i"), + new RegExp(`^ssh://git@github\\.com(?::22)?/${owner}/${name}${end}`, "i"), +]; + +/** The repository a github.com HTTPS or SSH remote URL names, or null for any other URL. */ +export function parseGitHubUrl(url: string): GitHubRepo | null { + for (const form of forms) { + const match = form.exec(url.trim()); + if (match) return { owner: match[1]!, name: match[2]! }; + } + return null; +} + +/** + * The GitHub repository of the remote the default branch tracks, or of `origin` when it tracks none; null when + * that remote isn't on github.com. The URL is read as configured, before any `insteadOf` rewrite. + */ +export async function readGitHubRepo( + repo: string, + defaultBranch: string | null, + runner: CommandRunner, + signal?: AbortSignal, +): Promise { + let remote = "origin"; + if (defaultBranch) { + const tracked = await runner( + "git", + ["-C", repo, "config", "--get", `branch.${defaultBranch}.remote`], + signal, + ); + if (tracked.exitCode === 0 && tracked.stdout.trim()) remote = tracked.stdout.trim(); + } + const url = await runner("git", ["-C", repo, "config", "--get", `remote.${remote}.url`], signal); + return url.exitCode === 0 ? parseGitHubUrl(url.stdout) : null; +} diff --git a/src/core/scan/dashboard.ts b/src/core/scan/dashboard.ts index 0cee12e..ed7b40f 100644 --- a/src/core/scan/dashboard.ts +++ b/src/core/scan/dashboard.ts @@ -27,6 +27,16 @@ export interface RowPatch { facts: Partial>; } +/** + * Runs once per scan after each repository's full listing, without holding the scan up, and patches its rows + * when it resolves. It gets the rows as listed, earlier patches applied; if it fails, they keep their facts. + */ +export type FollowUp = ( + repo: string, + rows: WorktreeRow[], + signal: AbortSignal, +) => Promise; + interface DashboardOptions { projectRoot: string; wtPath: string; @@ -45,11 +55,7 @@ interface DashboardOptions { paths: string[], signal: AbortSignal, ) => Promise>; - /** - * Runs once per scan after each repository's full listing, without holding the scan up, and patches its rows - * when it resolves. It gets the rows as listed, earlier patches applied; if it fails, they keep their facts. - */ - followUp?: (repo: string, rows: WorktreeRow[], signal: AbortSignal) => Promise; + followUp?: FollowUp; } export function createDashboardService(options: DashboardOptions): DashboardService { diff --git a/src/core/types.ts b/src/core/types.ts index be67dfd..4b97c0f 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -61,6 +61,20 @@ export type ForgeUncheckedReason = */ export type ForgeProofKind = "commit" | "tree" | "stacked"; +/** A merged pull request that holds the tip. */ +export interface ForgeProof { + kind: "proven"; + /** The 40-hex commit GitHub was asked about. */ + tip: string; + /** The pull request merged into the default branch. */ + pr: number; + /** When PR `pr` was merged, as an ISO 8601 time. */ + mergedAt: string; + /** The branch PR `pr` merged into. */ + base: string; + by: ForgeProofKind; +} + /** * What GitHub says about whether the row's tip reached the default branch through a merged pull request. * A `proven` or `not-found` answer counts only while its `tip` is still the row's `headSha`. @@ -68,18 +82,7 @@ export type ForgeProofKind = "commit" | "tree" | "stacked"; export type ForgeCheck = | { kind: "pending" } | { kind: "unchecked"; why: ForgeUncheckedReason } - | { - kind: "proven"; - /** The 40-hex commit GitHub was asked about. */ - tip: string; - /** The pull request merged into the default branch. */ - pr: number; - /** When PR `pr` was merged, as an ISO 8601 time. */ - mergedAt: string; - /** The branch PR `pr` merged into. */ - base: string; - by: ForgeProofKind; - } + | ForgeProof | { kind: "not-found"; tip: string; @@ -109,6 +112,8 @@ export interface WorktreeFacts { tool: ToolName; changes: ChangeFlags | null; upstreamAhead: number | null; + /** The name of the upstream branch on its remote, which may differ from `branch`; null without one. */ + upstreamBranch?: string | null; mainState: string | null; integrationReason?: string | null; lockReason: string | null; diff --git a/src/core/worktrunk/list.ts b/src/core/worktrunk/list.ts index 49746bd..405b528 100644 --- a/src/core/worktrunk/list.ts +++ b/src/core/worktrunk/list.ts @@ -168,6 +168,7 @@ export function parseWorktrunk(repoPath: string, stdout: string): WorktreeRow[] tool: path === null ? "Other" : toolForPath(path, repoPath), changes: changesFrom(worktree?.changes), upstreamAhead: typeof upstream?.ahead === "number" ? upstream.ahead : null, + upstreamBranch: string(upstream?.branch), mainState: string(display?.state), integrationReason: string(integration?.reason), lockReason: string(object(worktree?.locked)?.reason), diff --git a/src/ui/render/chrome.ts b/src/ui/render/chrome.ts index 8284c08..5951945 100644 --- a/src/ui/render/chrome.ts +++ b/src/ui/render/chrome.ts @@ -54,11 +54,11 @@ export function statusLine(state: UiState, ctx: RenderContext): Line { return bannerLine(ctx) ?? []; } -type SummaryPart = "projects" | "worktrees" | "size" | "sizing"; +type SummaryPart = "projects" | "worktrees" | "size" | "sizing" | "checking"; const SUMMARY_PARTS_BY_WIDTH: SummaryPart[][] = [ - ["projects", "worktrees", "size", "sizing"], - ["worktrees", "size", "sizing"], + ["projects", "worktrees", "size", "sizing", "checking"], + ["worktrees", "size", "sizing", "checking"], ["worktrees", "size"], ["size"], [], @@ -99,6 +99,7 @@ export function headerLine( worktrees: rowsLabel(rows), size: `up to ${sizeLabel(total)}`, sizing: unknown ? `${unknown} sizing` : "", + checking: snapshot.checking ? "checking GitHub" : "", }; const summary = (names: SummaryPart[]): Line => { const listing = !rows.length && progress.phase === "scanning"; diff --git a/tests/e2e/merged-on-github.test.ts b/tests/e2e/merged-on-github.test.ts index 13eb523..f4073ab 100644 --- a/tests/e2e/merged-on-github.test.ts +++ b/tests/e2e/merged-on-github.test.ts @@ -6,11 +6,50 @@ import { dialogRow, exists, inSandbox, + lineWith, removals, rowOf, withApp, TEST_TIMEOUT, } from "../support/app"; +import { online } from "../support/fixture"; + +test( + "a worktree squash-merged on GitHub shows Review while gh is asked, then Safe with its pull request", + () => + inSandbox(async (sandbox) => { + const alpha = await sandbox.repo("alpha", { github: true }); + const feature = await alpha.prMergedWorktree("feature"); + const pr = feature.github!.pullRequests[0]!; + // gh answers after a pause, so the screen shows the row before GitHub settles it. + await sandbox.gh.setMode("ok", 1500); + await withApp( + sandbox, + { width: 120, name: "checked on GitHub", github: online(sandbox) }, + async (app) => { + let frame = await app.waitFor( + (text) => + lineWith(text, "wt-dash").includes("checking GitHub") && + rowOf(text, "feature") !== null, + ); + expect(rowOf(frame, "feature")).toStartWith( + "□ feature unmerged commits 1 commit isn't in main, and merging would conflict ", + ); + frame = await app.waitFor( + (text) => rowOf(text, "feature")?.includes("merged on GitHub") ?? false, + ); + expect(rowOf(frame, "feature")).toStartWith( + `□ feature merged on GitHub PR #${pr} merged `, + ); + expect(rowOf(frame, "feature")).toContain(" with this exact commit "); + frame = await app.waitFor((text) => !lineWith(text, "wt-dash").includes("checking")); + expect(lineWith(frame, "Review 0")).toContain("Safe 1"); + expect(await sandbox.gh.calls()).toHaveLength(1); + }, + ); + }), + TEST_TIMEOUT, +); test( "a worktree a follow-up proves merged on GitHub: the dialog names its PR, and removing it deletes the branch", diff --git a/tests/git/refs.test.ts b/tests/git/refs.test.ts index 0393664..d40caa0 100644 --- a/tests/git/refs.test.ts +++ b/tests/git/refs.test.ts @@ -2,7 +2,12 @@ import { afterAll, beforeAll, expect, test } from "bun:test"; import { mkdtemp, rm, utimes } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { readBranchCreatedAt, readComparisonBase, readTips } from "../../src/core/git/refs"; +import { + readBranchCreatedAt, + readComparisonBase, + readTips, + readTrees, +} from "../../src/core/git/refs"; import type { CommandRunner } from "../../src/core/types"; const ok = (stdout = "") => ({ stdout, stderr: "", exitCode: 0 }); test.each([ @@ -102,6 +107,21 @@ test("reference batches preserve missing refs, revision expressions and Git fail ); }); +test("trees come from one rev-parse, and none when any commit can't be read", async () => { + const sha = await git("rev-parse", "HEAD"); + const tree = await git("rev-parse", "HEAD^{tree}"); + let commands = 0; + const counted: CommandRunner = (command, args) => { + commands++; + return runner(command, args); + }; + expect([...(await readTrees(repo, [sha], counted))]).toEqual([[sha, tree]]); + expect(commands).toBe(1); + expect(await readTrees(repo, [sha, "0".repeat(40)], runner)).toEqual(new Map()); + expect(await readTrees(repo, [], counted)).toEqual(new Map()); + expect(commands).toBe(1); +}); + test("a branch's age comes from its oldest reflog entry, else when its ref was written", async () => { await git("branch", "aged"); const logPath = join(repo, ".git", "logs", "refs", "heads", "aged"); diff --git a/tests/github/cache.test.ts b/tests/github/cache.test.ts new file mode 100644 index 0000000..fbd6035 --- /dev/null +++ b/tests/github/cache.test.ts @@ -0,0 +1,94 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createProofCache, proofKey } from "../../src/core/github/cache"; +import type { ForgeProof } from "../../src/core/types"; + +const roots: string[] = []; +async function file(): Promise { + const root = await mkdtemp(join(tmpdir(), "dash-proofs-")); + roots.push(root); + return join(root, "cache", "pull-requests.json"); +} +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +const repo = { owner: "Acme", name: "App" }; +const proof = (tip: string, pr = 7): ForgeProof => ({ + kind: "proven", + tip, + pr, + mergedAt: "2026-10-30T12:00:00Z", + base: "main", + by: "commit", +}); +const A = "a".repeat(40); +const B = "b".repeat(40); + +test("proofs are saved under owner/name@tip and load back in a later run", async () => { + const path = await file(); + const cache = createProofCache(path); + await cache.load(); + cache.add(repo, [proof(A), { ...proof(B, 8), by: "stacked", base: "trunk" }]); + await cache.close(); + expect(JSON.parse(await readFile(path, "utf8"))).toEqual({ + [`acme/app@${A}`]: { + tip: A, + pr: 7, + mergedAt: "2026-10-30T12:00:00Z", + base: "main", + by: "commit", + }, + [`acme/app@${B}`]: { + tip: B, + pr: 8, + mergedAt: "2026-10-30T12:00:00Z", + base: "trunk", + by: "stacked", + }, + }); + const later = createProofCache(path); + await later.load(); + expect(later.get({ owner: "acme", name: "app" }, A)).toEqual(proof(A)); + expect(later.get(repo, B)?.by).toBe("stacked"); + expect(later.get({ owner: "acme", name: "other" }, A)).toBeNull(); + expect(proofKey(repo, A)).toBe(`acme/app@${A}`); +}); + +test("a missing or corrupt file is empty, and malformed entries are dropped", async () => { + const path = await file(); + const cache = createProofCache(path); + await cache.load(); + expect(cache.get(repo, A)).toBeNull(); + + await Bun.write(path, "{ not json"); + await cache.load(); + expect(cache.get(repo, A)).toBeNull(); + + const good = { tip: A, pr: 7, mergedAt: "2026-10-30T12:00:00Z", base: "main", by: "commit" }; + await Bun.write( + path, + JSON.stringify({ + [`acme/app@${A}`]: good, + [`acme/app@${B}`]: { ...good, tip: B, by: "guess" }, + [`acme/other@${B}`]: { ...good, tip: A }, + [`acme/third@${B}`]: { ...good, tip: B, pr: -1 }, + [`acme/fourth@${B}`]: { ...good, tip: B, mergedAt: null }, + [`acme/fifth@${B}`]: "proven", + }), + ); + await cache.load(); + expect(cache.get(repo, A)).toEqual(proof(A)); + for (const name of ["app", "other", "third", "fourth", "fifth"]) + expect(cache.get({ owner: "acme", name }, B)).toBeNull(); +}); + +test("adding nothing writes nothing", async () => { + const path = await file(); + const cache = createProofCache(path); + cache.add(repo, []); + await cache.close(); + expect(await Bun.file(path).exists()).toBe(false); +}); diff --git a/tests/github/check.test.ts b/tests/github/check.test.ts new file mode 100644 index 0000000..ba72ec9 --- /dev/null +++ b/tests/github/check.test.ts @@ -0,0 +1,377 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createProofCache, type ProofCache } from "../../src/core/github/cache"; +import { canAskGitHub, createGitHubCheck, type GitHubOptions } from "../../src/core/github/check"; +import type { RowPatch } from "../../src/core/scan/dashboard"; +import type { CommandRunner, WorktreeRow } from "../../src/core/types"; +import { answerGh, type GhPullRequest, type GhState } from "../support/gh"; +import { row as baseRow } from "../support/update"; + +const GH = "/usr/local/bin/gh"; +const REPO = "/repos/alpha"; +const sha = (index: number) => index.toString(16).padStart(40, "0"); +const treeOf = (tip: string) => `${tip.slice(0, 39)}f`; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); +async function proofCache(): Promise<{ proofs: ProofCache; path: string }> { + const root = await mkdtemp(join(tmpdir(), "dash-check-")); + roots.push(root); + const path = join(root, "pull-requests.json"); + const proofs = createProofCache(path); + await proofs.load(); + return { proofs, path }; +} + +/** A row Worktrunk couldn't show merged, which GitHub may settle. */ +const row = (index: number, overrides: Partial = {}): WorktreeRow => + baseRow(`feature/${index}`, 0, { + headSha: sha(index), + mainState: "would_conflict", + verdict: "Review", + reason: "1 commit isn't in main, and merging would conflict.", + ...overrides, + }); + +const merged = (index: number, overrides: Partial = {}): GhPullRequest => ({ + number: index, + mergedAt: "2026-10-30T12:00:00Z", + base: "main", + headRefName: `feature/${index}`, + headRefOid: sha(index), + commits: [{ oid: sha(index), tree: treeOf(sha(index)) }], + ...overrides, +}); + +/** + * Git answers config from `config` and trees from `treeOf`; gh answers from the fake GitHub with `pullRequests` + * unless `gh` overrides it. + */ +function world( + options: { + pullRequests?: GhPullRequest[]; + config?: Record; + gh?: CommandRunner; + } = {}, +) { + const model: GhState = { + mode: "ok", + repos: [ + { + owner: "acme", + name: "alpha", + defaultBranch: "main", + pullRequests: options.pullRequests ?? [], + }, + ], + }; + const config = options.config ?? { "remote.origin.url": "git@github.com:acme/alpha.git" }; + const commands: Array<{ command: string; args: string[] }> = []; + const runner: CommandRunner = async (command, args, signal, environment) => { + commands.push({ command, args }); + if (command === "git" && args[2] === "config") { + const value = config[args.at(-1)!]; + return value === undefined + ? { stdout: "", stderr: "", exitCode: 1 } + : { stdout: `${value}\n`, stderr: "", exitCode: 0 }; + } + if (command === "git" && args[2] === "rev-parse") { + const trees = args.slice(3).map((arg) => treeOf(arg.replace("^{tree}", ""))); + return { stdout: `${trees.join("\n")}\n`, stderr: "", exitCode: 0 }; + } + if (command === GH) + return options.gh ? options.gh(command, args, signal, environment) : answerGh(model, args); + throw new Error(`unexpected ${command} ${args.join(" ")}`); + }; + const ghCalls = () => commands.filter(({ command }) => command === GH); + const gitCalls = () => commands.filter(({ command }) => command === "git"); + return { runner, ghCalls, gitCalls }; +} + +const ONLINE: GitHubOptions = { offline: false, ghPath: GH }; +const live = () => new AbortController().signal; +const forges = (patches: RowPatch[]) => + Object.fromEntries(patches.map(({ id, facts }) => [id, facts.forge])); + +test.each<[string, Partial, boolean]>([ + ["a clean worktree with unmerged commits", {}, true], + ["one Worktrunk calls ahead", { mainState: "ahead" }, true], + ["diverged", { mainState: "diverged" }, true], + ["behind", { mainState: "behind" }, true], + ["a branch without a worktree", { kind: "branch", path: null, changes: null }, true], + ["with no upstream", { upstreamAhead: null }, true], + ["merged as Git sees it", { mainState: "integrated" }, false], + ["with no commits beyond main", { mainState: "empty" }, false], + ["with unrelated history", { mainState: "orphan" }, false], + ["of unknown state", { mainState: null }, false], + ["with unpushed commits", { upstreamAhead: 2 }, false], + ["with uncommitted changes", { changes: { ...baseRow("x", 0).changes!, modified: true } }, false], + ["with untracked files", { changes: { ...baseRow("x", 0).changes!, untracked: true } }, false], + ["with conflicts", { changes: { ...baseRow("x", 0).changes!, conflicted: true } }, false], + [ + "whose files Git couldn't read", + { changes: { ...baseRow("x", 0).changes!, conflicted: null } }, + false, + ], + ["with no status at all", { changes: null }, false], + ["mid-rebase", { operation: "rebase" }, false], + ["locked", { locked: true, lockReason: "agent" }, false], + ["whose folder is gone", { prunable: true }, false], + ["an orphan folder", { kind: "orphan" }, false], + ["with a short SHA", { headSha: "abcdef1" }, false], + ["with no HEAD", { headSha: null }, false], +])("GitHub is asked about a row %s: %p", (_name, overrides, asked) => { + expect(canAskGitHub(row(1, overrides))).toBe(asked); +}); + +test("every row gets a patch: proofs and answers for rows it asked about, no forge check for the rest", async () => { + const { proofs } = await proofCache(); + const { runner, ghCalls } = world({ + pullRequests: [ + merged(1), + merged(2, { + headRefName: "feature/2", + headRefOid: sha(99), + commits: [{ oid: sha(99), tree: "t".repeat(40) }], + }), + ], + }); + const rows = [row(1), row(2), row(3, { mainState: "integrated" }), row(4, { headSha: null })]; + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs })(REPO, rows, live()); + expect(patches.map(({ id, headSha }) => [id, headSha])).toEqual([ + [rows[0]!.id, sha(1)], + [rows[1]!.id, sha(2)], + [rows[2]!.id, sha(3)], + ]); + expect(forges(patches)).toEqual({ + [rows[0]!.id]: { + kind: "proven", + tip: sha(1), + pr: 1, + mergedAt: "2026-10-30T12:00:00Z", + base: "main", + by: "commit", + }, + [rows[1]!.id]: { + kind: "not-found", + tip: sha(2), + samePr: { number: 2, mergedAt: "2026-10-30T12:00:00Z" }, + }, + [rows[2]!.id]: undefined, + }); + expect(ghCalls()).toHaveLength(1); +}); + +test("the upstream's name is asked about too when it differs from the branch's", async () => { + const { proofs } = await proofCache(); + const pushedAs = merged(5, { + headRefName: "someone/renamed", + headRefOid: sha(77), + commits: [{ oid: sha(77), tree: treeOf(sha(5)) }], + }); + const { runner, ghCalls } = world({ pullRequests: [pushedAs] }); + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs })( + REPO, + [row(5, { upstreamBranch: "someone/renamed" })], + live(), + ); + expect(Object.values(forges(patches))).toEqual([ + expect.objectContaining({ kind: "proven", pr: 5, by: "tree" }), + ]); + expect(ghCalls()[0]!.args).toContain("head1=someone/renamed"); +}); + +test("250 rows go in three requests of at most 100", async () => { + const { proofs } = await proofCache(); + const { runner, ghCalls } = world(); + const rows = Array.from({ length: 250 }, (_, index) => row(index + 1)); + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs })(REPO, rows, live()); + expect(Object.values(forges(patches)).every((forge) => forge?.kind === "not-found")).toBe(true); + expect(ghCalls().map(({ args }) => args.filter((arg) => /^oid\d+=/.test(arg)).length)).toEqual([ + 100, 100, 50, + ]); +}); + +test("a repository with no rows to ask about, or no GitHub remote, never runs gh", async () => { + const { proofs } = await proofCache(); + const settled = world(); + const check = createGitHubCheck({ github: ONLINE, runner: settled.runner, proofs }); + await check(REPO, [row(1, { mainState: "integrated" })], live()); + expect(settled.gitCalls()).toEqual([]); + + const gitlab = world({ config: { "remote.origin.url": "https://gitlab.com/acme/alpha.git" } }); + const patches = await createGitHubCheck({ github: ONLINE, runner: gitlab.runner, proofs })( + REPO, + [row(1)], + live(), + ); + expect(Object.values(forges(patches))).toEqual([{ kind: "unchecked", why: "no-github-remote" }]); + expect(gitlab.ghCalls()).toEqual([]); +}); + +test("proofs are cached and not asked again; answers that aren't proofs are asked every time", async () => { + const { proofs, path } = await proofCache(); + const { runner, ghCalls } = world({ pullRequests: [merged(1)] }); + const check = createGitHubCheck({ github: ONLINE, runner, proofs }); + await check(REPO, [row(1), row(2)], live()); + await proofs.close(); + expect(Object.keys(JSON.parse(await readFile(path, "utf8")) as object)).toEqual([ + `acme/alpha@${sha(1)}`, + ]); + + const second = await check(REPO, [row(1), row(2)], live()); + expect(Object.values(forges(second)).map((forge) => forge?.kind)).toEqual([ + "proven", + "not-found", + ]); + expect(ghCalls()).toHaveLength(2); + expect(ghCalls()[1]!.args.filter((arg) => /^oid\d+=/.test(arg))).toEqual([`oid0=${sha(2)}`]); + + const onlyCached = await check(REPO, [row(1)], live()); + expect(Object.values(forges(onlyCached))).toEqual([expect.objectContaining({ kind: "proven" })]); + expect(ghCalls()).toHaveLength(2); +}); + +test("offline or without gh, rows say so and nothing is sent; cached proofs still count", async () => { + const { proofs } = await proofCache(); + proofs.add({ owner: "acme", name: "alpha" }, [ + { + kind: "proven", + tip: sha(1), + pr: 1, + mergedAt: "2026-10-30T12:00:00Z", + base: "main", + by: "commit", + }, + ]); + for (const [github, why] of [ + [{ offline: true, ghPath: GH }, "offline"], + [{ offline: false, ghPath: null }, "gh-missing"], + ] as const) { + const { runner, ghCalls } = world(); + const patches = await createGitHubCheck({ github, runner, proofs })( + REPO, + [row(1), row(2)], + live(), + ); + expect(Object.values(forges(patches))).toEqual([ + expect.objectContaining({ kind: "proven", pr: 1 }), + { kind: "unchecked", why }, + ]); + expect(ghCalls()).toEqual([]); + } +}); + +test("once gh is signed out, the remaining requests aren't sent", async () => { + const { proofs } = await proofCache(); + const { runner, ghCalls } = world({ + gh: async () => ({ stdout: "", stderr: "gh auth login", exitCode: 4 }), + }); + const rows = Array.from({ length: 150 }, (_, index) => row(index + 1)); + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs })(REPO, rows, live()); + expect(new Set(Object.values(forges(patches)).map((forge) => JSON.stringify(forge)))).toEqual( + new Set([JSON.stringify({ kind: "unchecked", why: "signed-out" })]), + ); + expect(ghCalls()).toHaveLength(1); +}); + +test("a stacked pull request is asked about in one chained request, and proves the row stacked", async () => { + const { proofs } = await proofCache(); + const lower = sha(50); + const { runner, ghCalls } = world({ + pullRequests: [ + merged(1, { base: "stack/base", mergedAt: "2026-10-01T00:00:00Z" }), + merged(2, { + headRefName: "stack/base", + headRefOid: sha(60), + commits: [ + { oid: lower, tree: treeOf(lower) }, + { oid: sha(1), tree: treeOf(sha(1)) }, + { oid: sha(60), tree: treeOf(sha(1)) }, + ], + mergedAt: "2026-10-02T00:00:00Z", + }), + merged(3, { base: "stack/other", mergedAt: "2026-10-01T00:00:00Z" }), + ], + }); + const rows = [row(1), row(3)]; + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs })(REPO, rows, live()); + expect(forges(patches)).toEqual({ + [rows[0]!.id]: { + kind: "proven", + tip: sha(1), + pr: 2, + mergedAt: "2026-10-02T00:00:00Z", + base: "main", + by: "stacked", + }, + [rows[1]!.id]: { kind: "not-found", tip: sha(3) }, + }); + expect(ghCalls()).toHaveLength(2); + expect(ghCalls()[1]!.args.filter((arg) => !arg.startsWith("query=") && arg !== "-f")).toEqual([ + "api", + "graphql", + "owner=acme", + "name=alpha", + "default=main", + "base0=stack/base", + "base1=stack/other", + ]); +}); + +test("a chained request that fails leaves its rows unchecked", async () => { + const { proofs } = await proofCache(); + const pullRequests = [merged(1, { base: "stack/base" })]; + const model: GhState = { + mode: "ok", + repos: [{ owner: "acme", name: "alpha", defaultBranch: "main", pullRequests }], + }; + let calls = 0; + const { runner } = world({ + gh: async (_command, args) => + ++calls === 1 ? answerGh(model, args) : { stdout: "", stderr: "timeout", exitCode: 1 }, + }); + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs })( + REPO, + [row(1)], + live(), + ); + expect(Object.values(forges(patches))).toEqual([{ kind: "unchecked", why: "failed" }]); +}); + +test("a check aborted by a rescan throws, and caches nothing", async () => { + const { proofs, path } = await proofCache(); + const controller = new AbortController(); + const { runner } = world({ + gh: (_command, _args, signal) => + new Promise((_, reject) => { + signal?.addEventListener("abort", () => reject(new Error("Command aborted"))); + controller.abort(); + }), + }); + await expect( + createGitHubCheck({ github: ONLINE, runner, proofs })(REPO, [row(1)], controller.signal), + ).rejects.toThrow("Command aborted"); + await proofs.close(); + expect(await Bun.file(path).exists()).toBe(false); +}); + +test("a request that times out leaves its rows unchecked", async () => { + const { proofs } = await proofCache(); + const { runner } = world({ + gh: (_command, _args, signal) => + new Promise((_, reject) => + signal?.addEventListener("abort", () => reject(new Error("Command aborted"))), + ), + }); + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs, timeoutMs: 20 })( + REPO, + [row(1)], + live(), + ); + expect(Object.values(forges(patches))).toEqual([{ kind: "unchecked", why: "failed" }]); +}); diff --git a/tests/github/gh.test.ts b/tests/github/gh.test.ts new file mode 100644 index 0000000..5fa09f9 --- /dev/null +++ b/tests/github/gh.test.ts @@ -0,0 +1,128 @@ +import { expect, test } from "bun:test"; +import { GH_ENV, runGraphql } from "../../src/core/github/gh"; +import type { CommandResult, CommandRunner } from "../../src/core/types"; +import { GH_ENV as FAKE_GH_ENV } from "../support/gh"; + +const request = { query: "query { rateLimit { cost } }", variables: { owner: "acme" } }; +const live = () => new AbortController().signal; +const answering = + (result: Partial): CommandRunner => + async () => ({ stdout: "", stderr: "", exitCode: 0, ...result }); + +test("runs gh with every value passed by -f, and the environment that keeps it quiet", async () => { + const seen: Array<{ command: string; args: string[]; environment?: Record }> = []; + const runner: CommandRunner = async (command, args, _signal, environment) => { + seen.push({ command, args, environment }); + return { stdout: JSON.stringify({ data: { repository: { x: 1 } } }), stderr: "", exitCode: 0 }; + }; + expect(await runGraphql("/opt/gh", request, runner, live())).toEqual({ + kind: "reply", + repository: { x: 1 }, + errorPaths: [], + }); + expect(seen).toEqual([ + { + command: "/opt/gh", + args: ["api", "graphql", "-f", `query=${request.query}`, "-f", "owner=acme"], + environment: { GH_NO_UPDATE_NOTIFIER: "1", GH_PROMPT_DISABLED: "1" }, + }, + ]); + expect(GH_ENV).toEqual(FAKE_GH_ENV); +}); + +test("exit 1 with JSON on stdout gives the data that came back, with its errors' paths", async () => { + const stdout = JSON.stringify({ + data: { repository: { a0: null, a1: { y: 1 } } }, + errors: [{ path: ["repository", "a0"], message: "boom" }, { message: "no path" }], + }); + expect(await runGraphql("gh", request, answering({ stdout, exitCode: 1 }), live())).toEqual({ + kind: "reply", + repository: { a0: null, a1: { y: 1 } }, + errorPaths: [["repository", "a0"], null], + }); +}); + +test.each<[string, Partial, string]>([ + ["exit 4, gh not signed in", { exitCode: 4, stderr: "gh auth login" }, "signed-out"], + [ + "exit 1 with nothing on stdout", + { exitCode: 1, stderr: "Bad credentials (HTTP 401)" }, + "failed", + ], + [ + "another exit code", + { exitCode: 2, stdout: JSON.stringify({ data: { repository: {} } }) }, + "failed", + ], + ["unparseable output", { stdout: "" }, "failed"], + [ + "JSON without data", + { stdout: JSON.stringify({ errors: [{ message: "x" }] }), exitCode: 1 }, + "failed", + ], + [ + "a query over GitHub's node limit", + { + stdout: JSON.stringify({ + data: { repository: {} }, + errors: [{ type: "MAX_NODE_LIMIT_EXCEEDED", message: "too many" }], + }), + exitCode: 1, + }, + "failed", + ], +])("%s leaves the rows unchecked", async (_name, result, why) => { + expect(await runGraphql("gh", request, answering(result), live())).toEqual({ + kind: "unchecked", + why: why as "failed", + }); +}); + +test("gh that can't be started is missing; any other spawn error is a failure", async () => { + const throwing = + (code: string): CommandRunner => + async () => { + throw Object.assign(new Error(`${code}: posix_spawn`), { code }); + }; + expect(await runGraphql("/gone/gh", request, throwing("ENOENT"), live())).toEqual({ + kind: "unchecked", + why: "gh-missing", + }); + expect(await runGraphql("/gone/gh", request, throwing("EACCES"), live())).toEqual({ + kind: "unchecked", + why: "failed", + }); +}); + +/** A runner that never answers, and throws like the real one once its signal aborts. */ +const hanging: CommandRunner = (_command, _args, signal) => + new Promise((_, reject) => + signal?.addEventListener("abort", () => reject(new Error("Command aborted")), { once: true }), + ); + +test("a request that outlasts the timeout fails, and the command is cancelled", async () => { + let cancelled = false; + const runner: CommandRunner = (command, args, signal, environment) => { + signal?.addEventListener("abort", () => (cancelled = true)); + return hanging(command, args, signal, environment); + }; + expect(await runGraphql("gh", request, runner, live(), 20)).toEqual({ + kind: "unchecked", + why: "failed", + }); + expect(cancelled).toBe(true); +}); + +test("an aborted scan throws instead of answering, so the check reports nothing", async () => { + const controller = new AbortController(); + const asked = runGraphql("gh", request, hanging, controller.signal, 5_000); + controller.abort(); + await expect(asked).rejects.toThrow("Command aborted"); + // Aborted while gh was finishing: the answer is dropped too. + const late = new AbortController(); + const finishing: CommandRunner = async () => { + late.abort(); + return { stdout: JSON.stringify({ data: { repository: {} } }), stderr: "", exitCode: 0 }; + }; + await expect(runGraphql("gh", request, finishing, late.signal)).rejects.toThrow(); +}); diff --git a/tests/github/query.test.ts b/tests/github/query.test.ts new file mode 100644 index 0000000..a75c8c6 --- /dev/null +++ b/tests/github/query.test.ts @@ -0,0 +1,340 @@ +import { expect, test } from "bun:test"; +import { ghArgs } from "../../src/core/github/gh"; +import { + chainedRequest, + chunk, + lookupRequest, + readChained, + readLookup, + ROWS_PER_REQUEST, + type GraphqlReply, + type LookupRow, +} from "../../src/core/github/query"; +import { answerGh, type GhPullRequest, type GhState } from "../support/gh"; + +const repo = { owner: "acme", name: "app" }; +const sha = (seed: string) => seed.repeat(40).slice(0, 40); +const [A, B, C, D, E] = ["a", "b", "c", "d", "e"].map(sha) as [ + string, + string, + string, + string, + string, +]; +const tree = (seed: string) => sha(`f${seed}`); + +const pr = (overrides: Partial & Pick): GhPullRequest => ({ + mergedAt: `2026-01-0${overrides.number}T00:00:00Z`, + base: "main", + headRefName: "feature/x", + headRefOid: A, + commits: [{ oid: A, tree: tree("1") }], + ...overrides, +}); + +const state = (pullRequests: GhPullRequest[]): GhState => ({ + mode: "ok", + repos: [{ owner: "acme", name: "app", defaultBranch: "main", pullRequests }], +}); + +/** Sends the request to the fake GitHub and returns what wt-dash reads from its stdout. */ +function send(model: GhState, request: Parameters[0]): GraphqlReply { + const result = answerGh(model, ghArgs(request)); + expect(result.stderr).not.toContain("fake gh:"); + const body = JSON.parse(result.stdout) as { + data?: { repository: unknown }; + errors?: Array<{ path?: unknown[] }>; + }; + return { + repository: body.data?.repository ?? null, + errorPaths: (body.errors ?? []).map((error) => error.path ?? null), + }; +} + +const row = (tip: string, heads: string[] = [], treeOid: string | null = null): LookupRow => ({ + tip, + tree: treeOid, + heads, +}); + +test("chunks hold at most 100 rows", () => { + expect(ROWS_PER_REQUEST).toBe(100); + const items = Array.from({ length: 250 }, (_, index) => index); + expect(chunk(items).map((part) => part.length)).toEqual([100, 100, 50]); + expect(chunk(items).flat()).toEqual(items); + expect(chunk([])).toEqual([]); +}); + +test("the lookup passes every value as a variable, one per tip and one per distinct branch name", () => { + const { request, heads } = lookupRequest(repo, [ + row(A, ["feature/x"]), + row(B, ["feature/y", "feature/x"]), + row(C), + ]); + expect(heads).toEqual(["feature/x", "feature/y"]); + expect(request.variables).toEqual({ + owner: "acme", + name: "app", + oid0: A, + oid1: B, + oid2: C, + head0: "feature/x", + head1: "feature/y", + }); + expect(request.query).toStartWith( + "query($owner:String!,$name:String!,$oid0:GitObjectID!,$oid1:GitObjectID!,$oid2:GitObjectID!,$head0:String!,$head1:String!) {", + ); + // No value is ever spliced into the query text. + for (const value of [A, B, C, "feature/x", "acme"]) expect(request.query).not.toContain(value); + expect(ghArgs(request)).toEqual([ + "api", + "graphql", + "-f", + `query=${request.query}`, + ...Object.entries(request.variables).flatMap(([key, value]) => ["-f", `${key}=${value}`]), + ]); +}); + +test("proof A: a merged pull request into the default branch holding the exact tip", () => { + const model = state([ + pr({ + number: 1, + commits: [ + { oid: A, tree: tree("1") }, + { oid: B, tree: tree("2") }, + ], + }), + ]); + const rows = [row(A, ["feature/x"]), row(B, ["feature/x"])]; + const { request, heads } = lookupRequest(repo, rows); + const read = readLookup(repo, rows, heads, send(model, request)); + expect(read.defaultBranch).toBe("main"); + expect(read.answers).toEqual( + [A, B].map((tip) => ({ + kind: "proven", + proof: { + kind: "proven", + tip, + pr: 1, + mergedAt: "2026-01-01T00:00:00Z", + base: "main", + by: "commit", + }, + })), + ); +}); + +test("proof B: a pull request from the branch merged into the default branch with a commit of the same tree", () => { + const model = state([ + pr({ number: 2, headRefOid: B, commits: [{ oid: B, tree: tree("same") }] }), + ]); + const rows = [row(C, ["feature/x"], tree("same")), row(D, ["feature/x"], tree("other"))]; + const { request, heads } = lookupRequest(repo, rows); + const { answers } = readLookup(repo, rows, heads, send(model, request)); + expect(answers[0]).toEqual({ + kind: "proven", + proof: { + kind: "proven", + tip: C, + pr: 2, + mergedAt: "2026-01-02T00:00:00Z", + base: "main", + by: "tree", + }, + }); + // GitHub has no commit D (a null object) and no tree match: a PR from the same branch merged without it. + expect(answers[1]).toEqual({ + kind: "not-found", + samePr: { number: 2, mergedAt: "2026-01-02T00:00:00Z" }, + bases: [], + }); +}); + +test("not-found names the newest same-branch merge into the default branch, never a fork's or another base's", () => { + const model = state([ + pr({ number: 3, mergedAt: "2026-02-01T00:00:00Z" }), + pr({ number: 4, mergedAt: "2026-03-01T00:00:00Z", headRepository: "someone/app" }), + pr({ number: 5, mergedAt: "2026-04-01T00:00:00Z", base: "release" }), + pr({ number: 6, mergedAt: "2026-01-15T00:00:00Z" }), + ]); + const rows = [row(E, ["feature/x"], tree("none")), row(D, ["feature/elsewhere"])]; + const { request, heads } = lookupRequest(repo, rows); + const { answers } = readLookup(repo, rows, heads, send(model, request)); + expect(answers).toEqual([ + { kind: "not-found", samePr: { number: 3, mergedAt: "2026-02-01T00:00:00Z" }, bases: [] }, + { kind: "not-found", bases: [] }, + ]); +}); + +test("a tree match from a fork's pull request or into another base proves nothing", () => { + const model = state([ + pr({ number: 1, headRepository: "someone/app", commits: [{ oid: B, tree: tree("t") }] }), + pr({ number: 2, base: "release", commits: [{ oid: C, tree: tree("t") }] }), + ]); + const rows = [row(D, ["feature/x"], tree("t"))]; + const { request, heads } = lookupRequest(repo, rows); + expect(readLookup(repo, rows, heads, send(model, request)).answers).toEqual([ + { kind: "not-found", bases: [] }, + ]); +}); + +test("a tip merged into another branch is not proven, and names that branch for the chained request", () => { + const model = state([pr({ number: 7, base: "stack/base", headRefName: "stack/top" })]); + const rows = [row(A, ["stack/top"])]; + const { request, heads } = lookupRequest(repo, rows); + expect(readLookup(repo, rows, heads, send(model, request)).answers).toEqual([ + { kind: "not-found", bases: ["stack/base"] }, + ]); +}); + +test("associated pull requests of another repository, or not merged, prove nothing", () => { + const reply: GraphqlReply = { + repository: { + defaultBranchRef: { name: "main" }, + a0: { + associatedPullRequests: { + nodes: [ + { + number: 1, + state: "MERGED", + mergedAt: "2026-01-01T00:00:00Z", + baseRefName: "main", + repository: { nameWithOwner: "upstream/app", defaultBranchRef: { name: "main" } }, + }, + { + number: 2, + state: "OPEN", + mergedAt: null, + baseRefName: "main", + repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, + }, + { + number: 3, + state: "CLOSED", + mergedAt: null, + baseRefName: "main", + repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, + }, + { + number: "4", + state: "MERGED", + mergedAt: "x", + baseRefName: "main", + repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, + }, + ], + }, + }, + }, + errorPaths: [], + }; + expect(readLookup(repo, [row(A)], [], reply).answers).toEqual([{ kind: "not-found", bases: [] }]); + // Owner and name match without case, as on GitHub. + const upper = { owner: "ACME", name: "App" }; + const proven: GraphqlReply = { + ...reply, + repository: { + defaultBranchRef: { name: "main" }, + a0: { + associatedPullRequests: { + nodes: [ + { + number: 9, + state: "MERGED", + mergedAt: "2026-01-01T00:00:00Z", + baseRefName: "main", + repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, + }, + ], + }, + }, + }, + }; + expect(readLookup(upper, [row(A)], [], proven).answers[0]?.kind).toBe("proven"); +}); + +test("partial data: rows whose fields errored fail, the others are read", () => { + const model = state([pr({ number: 1 })]); + const rows = [row(A, ["feature/x"]), row(B, ["feature/y"]), row(C, ["feature/x"])]; + const { request, heads } = lookupRequest(repo, rows); + const reply = send(model, request); + const partial: GraphqlReply = { + repository: { ...(reply.repository as object), a1: null, b0: null }, + errorPaths: [ + ["repository", "a1"], + ["repository", "b0", "nodes", 0], + ], + }; + // A is proven by its own field despite b0 failing; B's object errored; C, not in a PR, needed b0. + expect(readLookup(repo, rows, heads, partial).answers.map((answer) => answer.kind)).toEqual([ + "proven", + "failed", + "failed", + ]); + // Errors outside the repository leave the rows alone. + expect( + readLookup(repo, rows, heads, { ...reply, errorPaths: [["rateLimit"]] }).answers.map( + (answer) => answer.kind, + ), + ).toEqual(["proven", "not-found", "not-found"]); +}); + +test("no repository, or an error that names no field, fails every row", () => { + const rows = [row(A), row(B)]; + const failed = { + defaultBranch: null, + answers: [{ kind: "failed" as const }, { kind: "failed" as const }], + }; + const missing = send({ ...state([]), mode: "missing-repo" }, lookupRequest(repo, rows).request); + expect(missing).toMatchObject({ repository: null, errorPaths: [["repository"]] }); + expect(readLookup(repo, rows, [], missing)).toEqual(failed); + expect( + readLookup(repo, rows, [], { + repository: { defaultBranchRef: { name: "main" } }, + errorPaths: [null], + }), + ).toEqual(failed); + expect(readLookup(repo, rows, [], { repository: "nonsense", errorPaths: [] })).toEqual(failed); +}); + +test("the chained request lists merges from each base into the default branch, with their commits", () => { + const model = state([ + pr({ + number: 3, + base: "stack/base", + headRefName: "stack/top", + commits: [{ oid: C, tree: tree("3") }], + }), + pr({ + number: 4, + base: "main", + headRefName: "stack/base", + commits: [ + { oid: C, tree: tree("3") }, + { oid: D, tree: tree("4") }, + ], + }), + ]); + const request = chainedRequest(repo, "main", ["stack/base", "stack/top"]); + expect(request.variables).toEqual({ + owner: "acme", + name: "app", + default: "main", + base0: "stack/base", + base1: "stack/top", + }); + expect(request.query).toStartWith( + "query($owner:String!,$name:String!,$default:String!,$base0:String!,$base1:String!) {", + ); + const reply = send(model, request); + expect(readChained(["stack/base", "stack/top"], reply)).toEqual([ + [{ number: 4, mergedAt: "2026-01-04T00:00:00Z", commits: [C, D] }], + [], + ]); + expect( + readChained(["stack/base", "stack/top"], { ...reply, errorPaths: [["repository", "k1"]] }), + ).toEqual([[{ number: 4, mergedAt: "2026-01-04T00:00:00Z", commits: [C, D] }], null]); + expect(readChained(["stack/base"], { repository: null, errorPaths: [["repository"]] })).toEqual([ + null, + ]); +}); diff --git a/tests/github/remote.test.ts b/tests/github/remote.test.ts new file mode 100644 index 0000000..40fb8a5 --- /dev/null +++ b/tests/github/remote.test.ts @@ -0,0 +1,68 @@ +import { expect, test } from "bun:test"; +import { parseGitHubUrl, readGitHubRepo } from "../../src/core/github/remote"; +import type { CommandRunner } from "../../src/core/types"; + +test.each([ + ["https://github.com/acme/app.git", { owner: "acme", name: "app" }], + ["https://github.com/acme/app", { owner: "acme", name: "app" }], + ["https://github.com/acme/app/", { owner: "acme", name: "app" }], + ["https://token@github.com/acme/my.app.git", { owner: "acme", name: "my.app" }], + ["https://GitHub.com/Acme/App.git\n", { owner: "Acme", name: "App" }], + ["git@github.com:acme/app.git", { owner: "acme", name: "app" }], + ["git@github.com:acme/app", { owner: "acme", name: "app" }], + ["ssh://git@github.com/acme/app.git", { owner: "acme", name: "app" }], + ["ssh://git@github.com:22/acme/app.git", { owner: "acme", name: "app" }], +])("%s is a GitHub remote", (url, repo) => { + expect(parseGitHubUrl(url)).toEqual(repo); +}); + +test.each([ + "http://github.com/acme/app.git", + "https://gitlab.com/acme/app.git", + "https://github.example.com/acme/app.git", + "https://github.com.evil.dev/acme/app.git", + "https://github.com/acme", + "https://github.com/acme/app/tree/main", + "git@gitlab.com:acme/app.git", + "/srv/git/app.git", + "../app", + "", +])("%p is not", (url) => { + expect(parseGitHubUrl(url)).toBeNull(); +}); + +function config(values: Record) { + const asked: string[] = []; + const runner: CommandRunner = async (_command, args) => { + const key = args.at(-1)!; + asked.push(key); + const value = values[key]; + return value === undefined + ? { stdout: "", stderr: "", exitCode: 1 } + : { stdout: `${value}\n`, stderr: "", exitCode: 0 }; + }; + return { runner, asked }; +} + +test("the remote the default branch tracks names the repository, read as configured", async () => { + const { runner, asked } = config({ + "branch.trunk.remote": "upstream", + "remote.upstream.url": "git@github.com:acme/app.git", + "remote.origin.url": "https://github.com/me/app.git", + }); + expect(await readGitHubRepo("/repo", "trunk", runner)).toEqual({ owner: "acme", name: "app" }); + expect(asked).toEqual(["branch.trunk.remote", "remote.upstream.url"]); +}); + +test("without a tracked remote it is origin's; a remote off GitHub, or none, gives null", async () => { + const origin = config({ "remote.origin.url": "https://github.com/me/app.git" }); + expect(await readGitHubRepo("/repo", "main", origin.runner)).toEqual({ + owner: "me", + name: "app", + }); + expect(origin.asked).toEqual(["branch.main.remote", "remote.origin.url"]); + expect(await readGitHubRepo("/repo", null, origin.runner)).toEqual({ owner: "me", name: "app" }); + const gitlab = config({ "remote.origin.url": "https://gitlab.com/me/app.git" }); + expect(await readGitHubRepo("/repo", "main", gitlab.runner)).toBeNull(); + expect(await readGitHubRepo("/repo", "main", config({}).runner)).toBeNull(); +}); diff --git a/tests/integration/github.test.ts b/tests/integration/github.test.ts index 6d7770e..b014476 100644 --- a/tests/integration/github.test.ts +++ b/tests/integration/github.test.ts @@ -1,24 +1,51 @@ -import { afterAll, beforeAll, expect, setDefaultTimeout, test } from "bun:test"; +import { afterAll, afterEach, beforeAll, expect, setDefaultTimeout, test } from "bun:test"; +import { rm } from "node:fs/promises"; +import { join } from "node:path"; import { assess } from "../../src/core/assess"; +import type { DashboardService, DashboardSnapshot, ForgeCheck } from "../../src/core/types"; import { createSandbox, + online, type Built, + type GitHubOptions, type Repo, type Sandbox, + type Services, TEST_TIMEOUT, } from "../support/fixture"; -import { chainedQuery, GH_ENV, graphqlArgs, lookupQuery } from "../support/gh"; -import { row, scan } from "./helpers"; +import { + chainedQuery, + GH_ENV, + type GhCall, + type GhMode, + graphqlArgs, + lookupQuery, +} from "../support/gh"; +import { row, scan, waitFor } from "./helpers"; setDefaultTimeout(TEST_TIMEOUT); +type Name = "merged" | "branch" | "earlier" | "treeMatch" | "missing" | "stacked"; + let sandbox: Sandbox; let hub: Repo; -let built: Record<"merged" | "branch" | "earlier" | "treeMatch" | "missing" | "stacked", Built>; +let solo: Repo; +let plain: Repo; +let settled: Repo; +let built: Record; +let soloBuilt: Built; +let plainBuilt: Built; +let settledBuilt: Built; +let open: Services[] = []; beforeAll(async () => { sandbox = await createSandbox(); - hub = await sandbox.repo("hub", { github: true }); + [hub, solo, plain, settled] = await Promise.all([ + sandbox.repo("hub", { github: true }), + sandbox.repo("solo", { github: true }), + sandbox.repo("plain"), + sandbox.repo("settled", { github: true }), + ]); // Each merges into main, so they run one after another. built = { merged: await hub.prMergedWorktree("feature/merged"), @@ -28,10 +55,54 @@ beforeAll(async () => { missing: await hub.prMissingCommit("feature/missing"), stacked: await hub.prStacked("feature/top", { base: "feature/bottom" }), }; + [soloBuilt, plainBuilt, settledBuilt] = await Promise.all([ + solo.prMergedWorktree("feature/solo"), + plain.unmergedWorktree("feature/plain"), + settled.mergedWorktree("feature/settled"), + ]); }, 60_000); +afterEach(async () => { + await Promise.all(open.splice(0).map((services) => services.close())); + await rm(join(sandbox.cacheDir, "pull-requests.json"), { force: true }); +}); + afterAll(() => sandbox?.cleanup()); +async function services(github?: GitHubOptions): Promise { + const opened = await sandbox.services({ github }); + open.push(opened); + return opened; +} + +/** Scans every repository and waits for each follow-up to finish. */ +async function scanAll(dashboard: DashboardService): Promise { + await dashboard.refresh(); + return waitFor(dashboard, (snapshot) => snapshot.checking === 0); +} + +/** The calls made since `before` calls were logged. */ +async function callsSince(before: number): Promise { + return (await sandbox.gh.calls()).slice(before); +} + +/** The `-f` fields of a call, by name, after checking every value was passed with `-f`. */ +function fields(call: GhCall): Record { + expect(call.argv.slice(0, 2)).toEqual(["api", "graphql"]); + const pairs = call.argv.slice(2); + expect(pairs.filter((_, index) => index % 2 === 0).every((flag) => flag === "-f")).toBe(true); + return Object.fromEntries( + pairs + .filter((_, index) => index % 2 === 1) + .map((field) => [field.slice(0, field.indexOf("=")), field.slice(field.indexOf("=") + 1)]), + ); +} + +const verdicts = (snapshot: DashboardSnapshot) => + Object.fromEntries( + Object.entries(built).map(([name, expected]) => [name, row(snapshot, expected).verdict]), + ); + test("Worktrunk sees a GitHub forge in the fixture's origin, which Git serves from a local bare repo", async () => { const listed = JSON.parse( await sandbox.wt( @@ -66,72 +137,10 @@ test("Worktrunk sees a GitHub forge in the fixture's origin, which Git serves fr expect(await sandbox.gh.calls()).toEqual([]); }); -test("today every pr… row is Review: Worktrunk finds no integration, and only GitHub can tell", async () => { - const { dashboard } = await sandbox.services(); - const snapshot = await scan(dashboard, hub); - for (const [name, expected] of Object.entries(built)) { - const shown = row(snapshot, expected); - expect({ name, kind: shown.kind, path: shown.path }).toEqual({ - name, - kind: expected.kind, - path: expected.path, - }); - expect({ - name, - verdict: shown.verdict, - status: assess(shown).status, - reason: shown.reason, - integration: shown.integrationReason, - unproven: ["would_conflict", "diverged"].includes(shown.mainState ?? ""), - }).toEqual({ - name, - verdict: "Review", - status: expected.expected.status, - reason: expected.expected.reason, - integration: null, - unproven: true, - }); - } - expect( - Object.fromEntries(Object.entries(built).map(([name, { github }]) => [name, github?.verdict])), - ).toEqual({ - merged: "Safe", - branch: "Safe", - earlier: "Safe", - treeMatch: "Safe", - missing: "Review", - stacked: "Safe", - }); - expect(await sandbox.gh.calls()).toEqual([]); -}); - -interface Answer { - data: { - repository: Record< - string, - { - associatedPullRequests?: { - nodes: Array<{ number: number; headRefOid: string; baseRefName: string }>; - }; - nodes?: Array<{ - number: number; - commits: { nodes: Array<{ commit: { oid: string; tree?: { oid: string } } }> }; - }>; - } | null - >; - }; -} - -async function ask(args: string[]): Promise { - const result = await sandbox.exec("gh", args, { env: GH_ENV }); - expect({ exitCode: result.exitCode, stderr: result.stderr }).toEqual({ exitCode: 0, stderr: "" }); - return (JSON.parse(result.stdout) as Answer).data.repository; -} - test("the fake GitHub holds what each builder's Git implies", async () => { - const { dashboard } = await sandbox.services(); + const { dashboard } = await services(); const snapshot = await scan(dashboard, hub); - const order = Object.keys(built) as Array; + const order = Object.keys(built) as Name[]; const tips = order.map((name) => row(snapshot, built[name]).headSha!); const trees = await Promise.all(tips.map((tip) => hub.git("rev-parse", `${tip}^{tree}`))); const answer = await ask( @@ -142,8 +151,8 @@ test("the fake GitHub holds what each builder's Git implies", async () => { ...Object.fromEntries(order.map((name, index) => [`head${index}`, built[name].branch])), }), ); - const at = (name: keyof typeof built) => order.indexOf(name); - const associated = (name: keyof typeof built) => + const at = (name: Name) => order.indexOf(name); + const associated = (name: Name) => answer[`a${at(name)}`]?.associatedPullRequests?.nodes.map( ({ number, headRefOid, baseRefName }) => ({ number, @@ -151,7 +160,7 @@ test("the fake GitHub holds what each builder's Git implies", async () => { baseRefName, }), ) ?? null; - const fromHead = (name: keyof typeof built) => + const fromHead = (name: Name) => answer[`b${at(name)}`]!.nodes!.map(({ number, commits }) => ({ number, hasTip: commits.nodes.some(({ commit }) => commit.oid === tips[at(name)]), @@ -173,7 +182,7 @@ test("the fake GitHub holds what each builder's Git implies", async () => { // Committed after the merge: neither the tip nor its files are on GitHub. expect(associated("missing")).toBeNull(); expect(fromHead("missing")).toEqual([{ number: missing, hasTip: false, hasTree: false }]); - // Stacked: merged into feature/bottom, which a later pull request merged into main. + // Stacked: merged into feature/bottom, which a later pull request merged into main with the tip in it. expect(associated("stacked")).toEqual([ { number: intoBase!, tipIsHead: true, baseRefName: "feature/bottom" }, ]); @@ -185,5 +194,253 @@ test("the fake GitHub holds what each builder's Git implies", async () => { base0: "feature/bottom", }), ); - expect(chained.k0!.nodes!.map(({ number }) => number)).toEqual([intoMain!]); + expect( + chained.k0!.nodes!.map(({ number, commits }) => ({ + number, + hasTip: commits.nodes.some(({ commit }) => commit.oid === tips[at("stacked")]), + })), + ).toEqual([{ number: intoMain!, hasTip: true }]); }); + +test("asked online, every pr… row reaches the builder's verdict, with one request per GitHub repo that has rows to ask about", async () => { + const before = (await sandbox.gh.calls()).length; + const { dashboard } = await services(online(sandbox)); + const snapshot = await scanAll(dashboard); + expect(snapshot.errors).toEqual({}); + + expect(verdicts(snapshot)).toEqual( + Object.fromEntries(Object.entries(built).map(([name, { github }]) => [name, github!.verdict])), + ); + const forge = (name: Name) => row(snapshot, built[name]).forge; + const [merged, branch, earlier, treeMatch, missing] = (Object.keys(built) as Name[]).map( + (name) => built[name].github!.pullRequests[0]!, + ); + const proven = (name: Name, pr: number, by: string) => ({ + kind: "proven", + tip: row(snapshot, built[name]).headSha, + pr, + base: "main", + by, + }); + expect(forge("merged")).toMatchObject(proven("merged", merged!, "commit")); + expect(forge("branch")).toMatchObject(proven("branch", branch!, "commit")); + expect(forge("earlier")).toMatchObject(proven("earlier", earlier!, "commit")); + expect(forge("treeMatch")).toMatchObject(proven("treeMatch", treeMatch!, "tree")); + expect(forge("stacked")).toMatchObject( + proven("stacked", built.stacked.github!.pullRequests[1]!, "stacked"), + ); + expect(forge("missing")).toMatchObject({ + kind: "not-found", + tip: row(snapshot, built.missing).headSha, + samePr: { number: missing }, + }); + const shown = row(snapshot, built.merged); + expect(assess(shown).status).toBe("merged on GitHub"); + expect(shown.reason).toStartWith(`PR #${merged} merged `); + expect(shown.reason).toEndWith(" with this exact commit."); + expect(row(snapshot, built.missing).reason).toMatch( + new RegExp( + `^2 commits aren't in main, and merging would conflict\\. PR #${missing} merged .+ without this commit\\.$`, + ), + ); + + // Not on GitHub, or nothing left for GitHub to settle: no forge check, the reason as before, and no call. + expect(row(snapshot, plainBuilt)).toMatchObject({ + verdict: "Review", + reason: plainBuilt.expected.reason, + forge: { kind: "unchecked", why: "no-github-remote" }, + }); + expect(row(snapshot, settledBuilt)).toMatchObject({ verdict: "Safe" }); + expect(row(snapshot, settledBuilt).forge).toBeUndefined(); + expect(row(snapshot, soloBuilt).verdict).toBe("Safe"); + + const calls = await callsSince(before); + const asked = calls.map((call) => { + const { query, ...variables } = fields(call); + return { + repo: `${variables.owner}/${variables.name}`, + chained: "default" in variables, + query, + variables, + }; + }); + expect( + asked + .map(({ repo, chained }) => ({ repo, chained })) + .sort((a, b) => a.repo.localeCompare(b.repo) || Number(a.chained) - Number(b.chained)), + ).toEqual([ + { repo: "acme/hub", chained: false }, + { repo: "acme/hub", chained: true }, + { repo: "acme/solo", chained: false }, + ]); + const lookup = asked.find(({ repo, chained }) => repo === "acme/hub" && !chained)!; + const rows = Object.values(built).map((one) => row(snapshot, one)); + expect(Object.keys(lookup.variables).filter((key) => key.startsWith("oid"))).toHaveLength(6); + expect( + Object.entries(lookup.variables) + .filter(([key]) => key.startsWith("oid")) + .map(([, oid]) => oid) + .sort(), + ).toEqual(rows.map((one) => one.headSha!).sort()); + expect( + Object.entries(lookup.variables) + .filter(([key]) => key.startsWith("head")) + .map(([, head]) => head) + .sort(), + ).toEqual( + Object.values(built) + .map((one) => one.branch!) + .sort(), + ); + const chained = asked.find(({ repo, chained }) => repo === "acme/hub" && chained)!; + expect(chained.variables).toEqual({ + owner: "acme", + name: "hub", + default: "main", + base0: "feature/bottom", + }); + for (const call of calls) { + expect(call.env).toMatchObject(GH_ENV); + expect(call.argv.some((arg) => arg.startsWith("-F") || arg.startsWith("--field"))).toBe(false); + } +}); + +test("a second scan sends nothing for the proofs it cached, and a repo with only cached rows is not asked", async () => { + const first = await services(online(sandbox)); + await scanAll(first.dashboard); + await first.close(); + const before = (await sandbox.gh.calls()).length; + + const { dashboard } = await services(online(sandbox)); + const snapshot = await scanAll(dashboard); + expect(verdicts(snapshot)).toEqual( + Object.fromEntries(Object.entries(built).map(([name, { github }]) => [name, github!.verdict])), + ); + expect(row(snapshot, soloBuilt).verdict).toBe("Safe"); + const calls = await callsSince(before); + // Only the tip GitHub didn't hold is asked about again. + expect(calls.map((call) => fields(call))).toEqual([ + expect.objectContaining({ + owner: "acme", + name: "hub", + oid0: row(snapshot, built.missing).headSha!, + head0: built.missing.branch!, + }), + ]); + expect(Object.keys(fields(calls[0]!)).sort()).toEqual([ + "head0", + "name", + "oid0", + "owner", + "query", + ]); +}); + +const reviewWith = (note: string) => (name: Name) => ({ + verdict: "Review" as const, + reason: `${built[name].expected.reason} ${note}`, +}); + +async function checkedIn(mode: GhMode): Promise<{ snapshot: DashboardSnapshot; calls: GhCall[] }> { + await sandbox.gh.setMode(mode); + try { + const before = (await sandbox.gh.calls()).length; + const { dashboard } = await services(online(sandbox)); + await scan(dashboard, hub); + const snapshot = await waitFor(dashboard, (next) => next.checking === 0); + return { snapshot, calls: await callsSince(before) }; + } finally { + await sandbox.gh.setMode("ok"); + } +} + +function expectAll(snapshot: DashboardSnapshot, forge: ForgeCheck, note: string): void { + for (const name of Object.keys(built) as Name[]) { + const shown = row(snapshot, built[name]); + expect({ name, forge: shown.forge, verdict: shown.verdict, reason: shown.reason }).toEqual({ + name, + forge, + ...reviewWith(note)(name), + }); + } +} + +test.each([ + ["signed-out", "signed-out", "Not checked against GitHub: gh isn't signed in."], + ["bad-credentials", "failed", "Not checked against GitHub: GitHub didn't answer."], + ["offline", "failed", "Not checked against GitHub: GitHub didn't answer."], + ["missing-repo", "failed", "Not checked against GitHub: GitHub didn't answer."], +] as const)("gh answering %s leaves every row Review, saying why", async (mode, why, note) => { + const { snapshot, calls } = await checkedIn(mode); + expectAll(snapshot, { kind: "unchecked", why }, note); + // One request; nothing came back to chain from. + expect(calls).toHaveLength(1); +}); + +test("offline, or without gh, no request is made and every row says why", async () => { + const before = (await sandbox.gh.calls()).length; + for (const [github, why, note] of [ + [{ offline: true, ghPath: null }, "offline", "Not checked against GitHub: offline."], + [undefined, "offline", "Not checked against GitHub: offline."], + [ + { offline: false, ghPath: null }, + "gh-missing", + "Not checked against GitHub: gh isn't installed.", + ], + [ + { offline: false, ghPath: join(sandbox.gh.bin, "no-such-gh") }, + "gh-missing", + "Not checked against GitHub: gh isn't installed.", + ], + ] as const) { + const { dashboard } = await services(github); + await scan(dashboard, hub); + const snapshot = await waitFor(dashboard, (next) => next.checking === 0); + expectAll(snapshot, { kind: "unchecked", why }, note); + } + expect(await callsSince(before)).toEqual([]); +}); + +test("a sandbox with no gh on PATH asks nothing and says gh isn't installed", async () => { + const bare = await createSandbox({ gh: "missing" }); + try { + const repo = await bare.repo("lonely", { github: true }); + const lonely = await repo.prMergedWorktree("feature/lonely"); + const options = online(bare); + expect(options).toEqual({ offline: false, ghPath: null }); + const { dashboard } = await bare.services({ github: options }); + await scan(dashboard, repo); + const snapshot = await waitFor(dashboard, (next) => next.checking === 0); + expect(row(snapshot, lonely)).toMatchObject({ + verdict: "Review", + reason: `${lonely.expected.reason} Not checked against GitHub: gh isn't installed.`, + forge: { kind: "unchecked", why: "gh-missing" }, + }); + expect(await bare.gh.calls()).toEqual([]); + } finally { + await bare.cleanup(); + } +}); + +interface Answer { + data: { + repository: Record< + string, + { + associatedPullRequests?: { + nodes: Array<{ number: number; headRefOid: string; baseRefName: string }>; + }; + nodes?: Array<{ + number: number; + commits: { nodes: Array<{ commit: { oid: string; tree?: { oid: string } } }> }; + }>; + } | null + >; + }; +} + +async function ask(args: string[]): Promise { + const result = await sandbox.exec("gh", args, { env: GH_ENV }); + expect({ exitCode: result.exitCode, stderr: result.stderr }).toEqual({ exitCode: 0, stderr: "" }); + return (JSON.parse(result.stdout) as Answer).data.repository; +} diff --git a/tests/support/app.ts b/tests/support/app.ts index 9357e24..acc6e03 100644 --- a/tests/support/app.ts +++ b/tests/support/app.ts @@ -11,6 +11,7 @@ import { createSandbox, type Built, type FollowUp, + type GitHubOptions, type SavedRepos, type Sandbox, type Services, @@ -68,7 +69,7 @@ const matches = (frame: string, match: FrameMatch): boolean => /** * Starts the real runTerminal on the sandbox's real services, in an OpenTUI test renderer. `sources` replaces the - * scan root, as from prepareStartup. `followUp` is the dashboard's, as in `Sandbox.services`. + * scan root, as from prepareStartup. `github` and `followUp` are the app's, as in `Sandbox.services`. */ export async function startApp( sandbox: Sandbox, @@ -78,6 +79,7 @@ export async function startApp( runner, sources, savedRepos, + github, followUp, }: { width: number; @@ -85,10 +87,11 @@ export async function startApp( runner?: CommandRunner; sources?: RepoSource[]; savedRepos?: SavedRepos; + github?: GitHubOptions; followUp?: FollowUp; }, ): Promise { - const services = await sandbox.services({ runner, sources, savedRepos, followUp }); + const services = await sandbox.services({ runner, sources, savedRepos, github, followUp }); const setup = await createTestRenderer({ width, height }); const running = runTerminal(services.dashboard, { renderer: setup.renderer, @@ -230,6 +233,7 @@ export async function withApp( runner?: CommandRunner; sources?: RepoSource[]; savedRepos?: SavedRepos; + github?: GitHubOptions; followUp?: FollowUp; name: string; }, diff --git a/tests/support/fixture.ts b/tests/support/fixture.ts index afd02a6..69626f4 100644 --- a/tests/support/fixture.ts +++ b/tests/support/fixture.ts @@ -16,15 +16,9 @@ import { tmpdir } from "node:os"; import { delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path"; import { createServices } from "../../src/app"; import type { ActionService } from "../../src/core/removal/types"; -import { findProcesses } from "../../src/core/processes"; -import { createDashboardService } from "../../src/core/scan/dashboard"; -import { - discoverRepos, - findRepos, - readCreatedAt, - type RepoSource, -} from "../../src/core/scan/discovery"; -import { findOrphans } from "../../src/core/scan/orphans"; +import type { GitHubOptions } from "../../src/core/github/check"; +import type { FollowUp } from "../../src/core/scan/dashboard"; +import { discoverRepos, readCreatedAt, type RepoSource } from "../../src/core/scan/discovery"; import type { CommandResult, CommandRunner, @@ -97,8 +91,13 @@ export interface ExecOptions { } export type SavedRepos = NonNullable[0]["savedRepos"]>; -/** The dashboard's per-repository follow-up, such as the check that asks GitHub about each row's tip. */ -export type FollowUp = NonNullable[0]["followUp"]>; +export type { FollowUp, GitHubOptions }; + +/** The app's `github` option that asks the sandbox's fake GitHub, or finds no `gh` when the sandbox has none. */ +export const online = (sandbox: Sandbox): GitHubOptions => ({ + offline: false, + ghPath: sandbox.gh.installed ? join(sandbox.gh.bin, "gh") : null, +}); export interface Services { dashboard: DashboardService; @@ -172,8 +171,9 @@ export interface Repo { /** A worktree with a commit made after its pull request merged, which GitHub lacks: still Review. */ prMissingCommit(branch: string): Promise; /** - * A worktree whose tip was squash-merged into `base` by one pull request, then `base` into main by a - * second; `base` has a commit of its own and no local branch. Safe once asked. + * A worktree whose tip was merged into `base` with a merge commit by one pull request, then `base` squash-merged + * into main by a second, whose commits include the tip; `base` has a commit of its own and no local branch. + * Safe once asked. */ prStacked(branch: string, options?: { base?: string }): Promise; } @@ -218,13 +218,15 @@ export interface Sandbox { repo(name: string, options?: { github?: boolean }): Promise; /** * Dashboard, action and size services on the sandbox; `cleanup` closes any still open. `runner` replaces the - * sandbox runner, for wrappers from tests/support/runners.ts. `sources` replaces the scan root. `followUp` - * patches each repository's rows after its listing, as the GitHub check does; saved repos are ignored with it. + * sandbox runner, for wrappers from tests/support/runners.ts. `sources` replaces the scan root. `github` is + * the app's option, offline when omitted; `online(sandbox)` asks the fake GitHub. `followUp` replaces the GitHub + * check after each repository's listing. */ services(options?: { runner?: CommandRunner; sources?: RepoSource[]; savedRepos?: SavedRepos; + github?: GitHubOptions; followUp?: FollowUp; }): Promise; /** Closes services, removes every worktree of the sandbox's repos, then the sandbox. Safe to call twice. */ @@ -908,7 +910,7 @@ export async function createSandbox( await editLine(worktree, file, CHANGED, branch); const tip = await head(worktree); await git(worktree, "push", "-q", "-u", "origin", branch); - // The first pull request squash-merges this branch into `base` on GitHub. + // The first pull request merges this branch into `base` on GitHub with a merge commit, so `base` holds the tip. const first = ++pullRequests; const intoBase = await git( path, @@ -916,8 +918,10 @@ export async function createSandbox( `${tip}^{tree}`, "-p", lower, + "-p", + tip, "-m", - `${branch} (#${first})`, + `Merge ${branch} (#${first})`, ); await git(path, "push", "-q", "origin", `${intoBase}:refs/heads/${base}`); await gh.addPullRequest(github.owner, github.name, { @@ -931,7 +935,7 @@ export async function createSandbox( const second = await mergePullRequest(file, { headRefName: base, head: intoBase, - commits: [lower, intoBase], + commits: [lower, tip, intoBase], }); await git(path, "push", "-q", "origin", "--delete", branch); await git(path, "fetch", "-q", "--prune", "origin"); @@ -948,41 +952,25 @@ export async function createSandbox( runner?: CommandRunner; sources?: RepoSource[]; savedRepos?: SavedRepos; + github?: GitHubOptions; followUp?: FollowUp; } = {}, ): Promise { - const sources = options.sources ?? [{ kind: "scan", folder: scanRoot }]; - const commands = options.runner ?? runner; const app = await createServices({ home, - sources, + sources: options.sources ?? [{ kind: "scan", folder: scanRoot }], depth: 2, wtPath, - runner: commands, + runner: options.runner ?? runner, readCreated, savedRepos: options.savedRepos, + github: options.github, + followUp: options.followUp, }); - // createServices takes no follow-up, so this builds the same dashboard with one, minus saved repos. - const dashboard = options.followUp - ? createDashboardService({ - projectRoot: home, - wtPath, - runner: commands, - sizeService: app.sizes, - discover: async () => - [...new Set((await findRepos(sources, 2)).flatMap(({ repos }) => repos))].sort(), - readCreated, - findOrphans: (repos) => findOrphans(home, repos), - findProcesses: (paths, signal) => findProcesses(paths, commands, { signal }), - followUp: options.followUp, - }) - : app.dashboard; const service: Services = { ...app, - dashboard, async close() { if (!opened.delete(service)) return; - if (dashboard !== app.dashboard) await dashboard.close(); await app.close(); }, }; diff --git a/tests/terminal.test.ts b/tests/terminal.test.ts index 66dbbda..0461686 100644 --- a/tests/terminal.test.ts +++ b/tests/terminal.test.ts @@ -472,6 +472,21 @@ for (const activity of ["scanning", "sizing", "toast"] as const) { }); } +test("the header says GitHub is being checked while a follow-up runs, beside the sizing count", async () => { + const item = row("api", 2000, { sizeKiB: null, sizeMeasuredAt: null }); + const ui = await start(130, 20, [item]); + try { + ui.fake.update({ checking: 2, sizing: [item.path!] }); + let header = (await ui.frame()).split("\n")[0]!; + expect(header).toContain("1 sizing · checking GitHub · scanned "); + ui.fake.update({ checking: 0, sizing: [] }); + header = (await ui.frame()).split("\n")[0]!; + expect(header).not.toContain("checking GitHub"); + } finally { + await ui.stop(); + } +}); + test("focus changes restart the file debounce, including a quick return to the same row (audit #4)", async () => { const inspected: string[] = []; const { actions } = fakeActions((rows) => rows.map((item) => entry(item)), { From 8087a089e39f570a7ae3e84617c76af9f19ec7d0 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 20:47:08 -0500 Subject: [PATCH 10/11] fix: pin the GitHub host and require the tip in the merged pull request --- README.md | 4 +- src/core/github/check.ts | 57 ++++++++++- src/core/github/gh.ts | 7 +- src/core/github/query.ts | 20 +++- tests/github/check.test.ts | 118 +++++++++++++++++++++ tests/github/gh.test.ts | 11 +- tests/github/query.test.ts | 170 +++++++++++++++++++------------ tests/integration/github.test.ts | 159 ++++++++++++++++++++++++----- tests/support/fixture.ts | 54 +++++++++- tests/support/gh.test.ts | 7 ++ tests/support/gh.ts | 67 +++++++++--- 11 files changed, 560 insertions(+), 114 deletions(-) diff --git a/README.md b/README.md index 81aee75..5d325d0 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,9 @@ Running processes don't change a verdict. After each scan the strip shows the pr A squash merge on GitHub puts a branch's work into the default branch as a new commit, so Git often can't tell the branch is merged, and the row stays Review with unmerged commits. For these rows only, wt-dash asks GitHub through your own `gh` whether a merged pull request holds the branch's last commit, or a commit with exactly the same files. If one does, the row is Safe with a reason such as "PR #42 merged Oct 30 with this exact commit". A branch without a worktree still waits until it is a day old. If none does, the row stays Review, and the reason says what GitHub found, such as "PR #42 merged Oct 30 without this commit", or why GitHub wasn't asked. -GitHub is asked only about clean worktrees and branches whose commits are all pushed and that Git can't show merged, and only in a repository whose default branch tracks a github.com remote (or, tracking none, whose `origin` is on github.com). For each such repository, a scan sends one read-only GraphQL query with `gh api graphql`, holding the repository's owner and name and those rows' commit IDs and branch names. A second query follows only when a pull request was merged into another branch first. The header reads "checking GitHub" while it waits. A merged pull request never changes, so each proof is kept in `~/.cache/wt-dash/pull-requests.json` and its commit isn't asked about again. Run with `--offline` to never ask; rows GitHub could settle then say they weren't checked. +GitHub is asked only about clean worktrees and branches whose commits are all pushed and that Git can't show merged, and only in a repository whose default branch tracks a github.com remote (or, tracking none, whose `origin` is on github.com). For each such repository, a scan sends one read-only GraphQL query to github.com with `gh api graphql`, holding the repository's owner and name and those rows' commit IDs and branch names, and one more for every 100 rows beyond the first 100. Another query follows only when a pull request was merged into another branch first. The header reads "checking GitHub" while it waits. A merged pull request never changes, so each proof is kept in `~/.cache/wt-dash/pull-requests.json` and its commit isn't asked about again. Run with `--offline` to never ask: proofs already cached still count, and other rows GitHub could settle say they weren't checked. + +Only pull requests in that repository count. If `origin` is your fork, the default branch tracks it, and your pull requests merge into the repository you forked from, the rows stay Review. ### Orphaned folders diff --git a/src/core/github/check.ts b/src/core/github/check.ts index c41bcd7..a6789d1 100644 --- a/src/core/github/check.ts +++ b/src/core/github/check.ts @@ -47,6 +47,9 @@ export function canAskGitHub(row: WorktreeFacts): boolean { ); } +/** `gh` processes running at once, across every repository. */ +export const GH_CONCURRENCY = 4; + type Unchecked = Extract; /** Merged pull requests from one branch into the default branch. */ type MergedInto = NonNullable[number]>; @@ -61,8 +64,10 @@ export function createGitHubCheck(options: { runner: CommandRunner; proofs: ProofCache; timeoutMs?: number; + concurrency?: number; }): FollowUp { const { github, runner, proofs, timeoutMs = GH_TIMEOUT_MS } = options; + const slots = createSlots(options.concurrency ?? GH_CONCURRENCY); async function check( repo: string, @@ -95,13 +100,18 @@ export function createGitHubCheck(options: { return forges; } - /** Sends each request in turn; once gh is missing or signed out, the rest get the same answer unsent. */ + /** + * Sends a repository's requests in turn. Once one goes unanswered (gh missing, signed out, failed or timed + * out), the rest get the same answer unsent. + */ function sender(ghPath: string, signal: AbortSignal) { let stop: GhOutcome | null = null; return async (request: GraphqlRequest): Promise => { if (stop) return stop; - const outcome = await runGraphql(ghPath, request, runner, signal, timeoutMs); - if (outcome.kind === "unchecked" && outcome.why !== "failed") stop = outcome; + const outcome = await slots.run(signal, () => + runGraphql(ghPath, request, runner, signal, timeoutMs), + ); + if (outcome.kind === "unchecked") stop = outcome; return outcome; }; } @@ -193,3 +203,44 @@ export function createGitHubCheck(options: { ); }; } + +/** Runs at most `size` tasks at once, in the order they asked; a task whose signal aborts while waiting throws. */ +function createSlots(size: number) { + let running = 0; + const waiting: Array<() => void> = []; + async function acquire(signal: AbortSignal): Promise { + if (signal.aborted) throw new Error("Command aborted"); + if (running < size) { + running++; + return; + } + await new Promise((resolve, reject) => { + const start = () => { + signal.removeEventListener("abort", cancel); + resolve(); + }; + const cancel = () => { + waiting.splice(waiting.indexOf(start), 1); + reject(new Error("Command aborted")); + }; + waiting.push(start); + signal.addEventListener("abort", cancel, { once: true }); + }); + } + function release(): void { + // The slot passes straight to the next task waiting, if any. + const next = waiting.shift(); + if (next) next(); + else running--; + } + return { + async run(signal: AbortSignal, task: () => Promise): Promise { + await acquire(signal); + try { + return await task(); + } finally { + release(); + } + }, + }; +} diff --git a/src/core/github/gh.ts b/src/core/github/gh.ts index 7b01e9f..a8286c9 100644 --- a/src/core/github/gh.ts +++ b/src/core/github/gh.ts @@ -14,11 +14,16 @@ export type GhOutcome = why: Extract; }; -/** `gh api graphql` with the query and every variable passed as a raw string with `-f`. */ +/** + * `gh api graphql` on github.com, with the query and every variable passed as a raw string with `-f`. Without + * `--hostname`, gh would use `GH_HOST` or the only host it is signed in to, such as a GitHub Enterprise server. + */ export function ghArgs(request: GraphqlRequest): string[] { return [ "api", "graphql", + "--hostname", + "github.com", "-f", `query=${request.query}`, ...Object.entries(request.variables).flatMap(([key, value]) => ["-f", `${key}=${value}`]), diff --git a/src/core/github/query.ts b/src/core/github/query.ts index f7065b2..e43f4b2 100644 --- a/src/core/github/query.ts +++ b/src/core/github/query.ts @@ -1,7 +1,12 @@ import type { ForgeProof } from "../types"; import type { GitHubRepo } from "./remote"; -/** Rows asked about in one request, which keeps it far below GitHub's limit of 500,000 nodes. */ +/** + * Rows asked about in one request. GitHub limits a query to 500,000 nodes, counting each connection's `first` or + * `last` times those of the connections around it. Each row costs 5 + 5 × 250 = 1,255 nodes for `aN` and as much + * for each of its at most two branch names in `bN`, so 100 rows cost at most 100 × 3 × 1,255 = 376,500, and + * 251,000 when no upstream is renamed. + */ export const ROWS_PER_REQUEST = 100; export interface GraphqlRequest { @@ -65,7 +70,7 @@ export function lookupRequest( const fields = [ ...rows.map( (_, index) => - `a${index}: object(oid:$oid${index}) { ... on Commit { associatedPullRequests(first:5) { nodes { number state mergedAt baseRefName headRefName headRefOid repository { nameWithOwner defaultBranchRef { name } } } } } }`, + `a${index}: object(oid:$oid${index}) { ... on Commit { associatedPullRequests(first:5) { nodes { number state mergedAt baseRefName headRefName headRefOid repository { nameWithOwner defaultBranchRef { name } } commits(last:250) { nodes { commit { oid } } } } } } }`, ), ...heads.map( (_, index) => @@ -181,13 +186,20 @@ export function readLookup( kind: "proven", proof: { kind: "proven", tip: row.tip, pr: pr.number, mergedAt: pr.mergedAt, base, by }, }); - // Proof A: GitHub lists a merged pull request of this repository holding the exact tip. + // Proof A: a merged pull request of this repository whose own commits include the exact tip. GitHub also + // associates commits that were force-pushed away from a pull request, so the association alone proves nothing. const bases = new Set(); for (const node of nodes(object(repository[`a${index}`])?.associatedPullRequests)) { const pr = merged(node); const target = object(node.repository); const base = text(node.baseRefName); - if (!pr || node.state !== "MERGED" || !base || !sameRepo(target?.nameWithOwner, repo)) + if ( + !pr || + node.state !== "MERGED" || + !base || + !sameRepo(target?.nameWithOwner, repo) || + !commitOids(node, "oid").includes(row.tip) + ) continue; if (base === text(object(target?.defaultBranchRef)?.name)) return prove(pr, base, "commit"); bases.add(base); diff --git a/tests/github/check.test.ts b/tests/github/check.test.ts index ba72ec9..b74c16d 100644 --- a/tests/github/check.test.ts +++ b/tests/github/check.test.ts @@ -315,6 +315,8 @@ test("a stacked pull request is asked about in one chained request, and proves t expect(ghCalls()[1]!.args.filter((arg) => !arg.startsWith("query=") && arg !== "-f")).toEqual([ "api", "graphql", + "--hostname", + "github.com", "owner=acme", "name=alpha", "default=main", @@ -323,6 +325,122 @@ test("a stacked pull request is asked about in one chained request, and proves t ]); }); +test("after a request fails or times out, the repository's other requests aren't sent and their rows fail", async () => { + for (const [name, gh, timeoutMs] of [ + ["failed", async () => ({ stdout: "", stderr: "HTTP 502", exitCode: 1 }), undefined], + [ + "timed out", + ((_command, _args, signal) => + new Promise((_, reject) => + signal?.addEventListener("abort", () => reject(new Error("Command aborted"))), + )) as CommandRunner, + 20, + ], + ] as const) { + const { proofs } = await proofCache(); + const { runner, ghCalls } = world({ gh }); + const rows = Array.from({ length: 250 }, (_, index) => row(index + 1)); + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs, timeoutMs })( + REPO, + rows, + live(), + ); + expect({ + name, + forges: new Set(Object.values(forges(patches)).map((f) => JSON.stringify(f))), + }).toEqual({ + name, + forges: new Set([JSON.stringify({ kind: "unchecked", why: "failed" })]), + }); + expect({ name, calls: ghCalls().length }).toEqual({ name, calls: 1 }); + } +}); + +test("a failure after a stacked candidate skips the chained request and fails that row too", async () => { + const { proofs } = await proofCache(); + const model: GhState = { + mode: "ok", + repos: [ + { + owner: "acme", + name: "alpha", + defaultBranch: "main", + pullRequests: [merged(1, { base: "stack/base" })], + }, + ], + }; + let calls = 0; + const { runner, ghCalls } = world({ + gh: async (_command, args) => + ++calls === 1 ? answerGh(model, args) : { stdout: "", stderr: "HTTP 502", exitCode: 1 }, + }); + const rows = Array.from({ length: 101 }, (_, index) => row(index + 1)); + const patches = await createGitHubCheck({ github: ONLINE, runner, proofs })(REPO, rows, live()); + // Row 1 needed the chained request; row 101 was in the chunk that failed. + expect(forges(patches)[rows[0]!.id]).toEqual({ kind: "unchecked", why: "failed" }); + expect(forges(patches)[rows[100]!.id]).toEqual({ kind: "unchecked", why: "failed" }); + expect(forges(patches)[rows[1]!.id]).toEqual({ kind: "not-found", tip: sha(2) }); + expect(ghCalls()).toHaveLength(2); +}); + +test("at most 4 gh processes run at once across repositories; a fifth waits for one to finish", async () => { + const { proofs } = await proofCache(); + const answers: Array<() => void> = []; + const { runner, ghCalls } = world({ + gh: () => + new Promise((resolve) => + answers.push(() => + resolve({ + stdout: JSON.stringify({ data: { repository: null } }), + stderr: "", + exitCode: 0, + }), + ), + ), + }); + const check = createGitHubCheck({ github: ONLINE, runner, proofs }); + const repos = Array.from({ length: 5 }, (_, index) => `/repos/r${index}`); + const done = repos.map((repo, index) => check(repo, [row(index + 1)], live())); + const settle = async () => { + for (let tick = 0; tick < 20; tick++) await Bun.sleep(1); + }; + await settle(); + expect(ghCalls()).toHaveLength(4); + expect(answers).toHaveLength(4); + answers.shift()!(); + await settle(); + expect(ghCalls()).toHaveLength(5); + for (const answer of answers.splice(0)) answer(); + await Promise.all(done); +}); + +test("a check waiting for a gh slot that is aborted throws without running gh", async () => { + const { proofs } = await proofCache(); + const answers: Array<() => void> = []; + const { runner, ghCalls } = world({ + gh: () => + new Promise((resolve) => + answers.push(() => + resolve({ + stdout: JSON.stringify({ data: { repository: null } }), + stderr: "", + exitCode: 0, + }), + ), + ), + }); + const check = createGitHubCheck({ github: ONLINE, runner, proofs, concurrency: 1 }); + const first = check(REPO, [row(1)], live()); + const controller = new AbortController(); + const second = check("/repos/other", [row(2)], controller.signal); + await Bun.sleep(5); + controller.abort(); + await expect(second).rejects.toThrow("Command aborted"); + answers.shift()!(); + await first; + expect(ghCalls()).toHaveLength(1); +}); + test("a chained request that fails leaves its rows unchecked", async () => { const { proofs } = await proofCache(); const pullRequests = [merged(1, { base: "stack/base" })]; diff --git a/tests/github/gh.test.ts b/tests/github/gh.test.ts index 5fa09f9..6153d5f 100644 --- a/tests/github/gh.test.ts +++ b/tests/github/gh.test.ts @@ -23,7 +23,16 @@ test("runs gh with every value passed by -f, and the environment that keeps it q expect(seen).toEqual([ { command: "/opt/gh", - args: ["api", "graphql", "-f", `query=${request.query}`, "-f", "owner=acme"], + args: [ + "api", + "graphql", + "--hostname", + "github.com", + "-f", + `query=${request.query}`, + "-f", + "owner=acme", + ], environment: { GH_NO_UPDATE_NOTIFIER: "1", GH_PROMPT_DISABLED: "1" }, }, ]); diff --git a/tests/github/query.test.ts b/tests/github/query.test.ts index a75c8c6..f79f0d2 100644 --- a/tests/github/query.test.ts +++ b/tests/github/query.test.ts @@ -89,6 +89,8 @@ test("the lookup passes every value as a variable, one per tip and one per disti expect(ghArgs(request)).toEqual([ "api", "graphql", + "--hostname", + "github.com", "-f", `query=${request.query}`, ...Object.entries(request.variables).flatMap(([key, value]) => ["-f", `${key}=${value}`]), @@ -187,70 +189,112 @@ test("a tip merged into another branch is not proven, and names that branch for ]); }); -test("associated pull requests of another repository, or not merged, prove nothing", () => { - const reply: GraphqlReply = { - repository: { - defaultBranchRef: { name: "main" }, - a0: { - associatedPullRequests: { - nodes: [ - { - number: 1, - state: "MERGED", - mergedAt: "2026-01-01T00:00:00Z", - baseRefName: "main", - repository: { nameWithOwner: "upstream/app", defaultBranchRef: { name: "main" } }, - }, - { - number: 2, - state: "OPEN", - mergedAt: null, - baseRefName: "main", - repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, - }, - { - number: 3, - state: "CLOSED", - mergedAt: null, - baseRefName: "main", - repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, - }, - { - number: "4", - state: "MERGED", - mergedAt: "x", - baseRefName: "main", - repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, - }, - ], - }, - }, - }, - errorPaths: [], - }; - expect(readLookup(repo, [row(A)], [], reply).answers).toEqual([{ kind: "not-found", bases: [] }]); +/** An associatedPullRequests node as GitHub returns it, merged into main in acme/app and holding A. */ +const node = (overrides: Record = {}) => ({ + number: 9, + state: "MERGED", + mergedAt: "2026-01-01T00:00:00Z", + baseRefName: "main", + repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, + commits: { nodes: [{ commit: { oid: A } }] }, + ...overrides, +}); +const associatedReply = (...nodes: unknown[]): GraphqlReply => ({ + repository: { defaultBranchRef: { name: "main" }, a0: { associatedPullRequests: { nodes } } }, + errorPaths: [], +}); + +test("associated pull requests of another repository, not merged, or malformed prove nothing", () => { + expect(readLookup(repo, [row(A)], [], associatedReply(node())).answers[0]?.kind).toBe("proven"); // Owner and name match without case, as on GitHub. - const upper = { owner: "ACME", name: "App" }; - const proven: GraphqlReply = { - ...reply, - repository: { - defaultBranchRef: { name: "main" }, - a0: { - associatedPullRequests: { - nodes: [ - { - number: 9, - state: "MERGED", - mergedAt: "2026-01-01T00:00:00Z", - baseRefName: "main", - repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, - }, - ], - }, - }, - }, - }; - expect(readLookup(upper, [row(A)], [], proven).answers[0]?.kind).toBe("proven"); + expect( + readLookup({ owner: "ACME", name: "App" }, [row(A)], [], associatedReply(node())).answers[0] + ?.kind, + ).toBe("proven"); + for (const overrides of [ + { repository: { nameWithOwner: "upstream/app", defaultBranchRef: { name: "main" } } }, + { state: "OPEN", mergedAt: null }, + { state: "CLOSED", mergedAt: null }, + // Open or closed, even if GitHub gave a time. + { state: "OPEN" }, + { state: "CLOSED" }, + { number: "9" }, + { mergedAt: 5 }, + ]) + expect({ + overrides, + answers: readLookup(repo, [row(A)], [], associatedReply(node(overrides))).answers, + }).toEqual({ + overrides, + answers: [{ kind: "not-found", bases: [] }], + }); +}); + +test("a merged pull request GitHub associates with the tip proves nothing unless its own commits include the tip", () => { + // GitHub keeps associating a commit force-pushed away from a pull request with it. + const forcedAway = node({ commits: { nodes: [{ commit: { oid: B } }] } }); + expect(readLookup(repo, [row(A)], [], associatedReply(forcedAway)).answers).toEqual([ + { kind: "not-found", bases: [] }, + ]); + expect(readLookup(repo, [row(A)], [], associatedReply(node({ commits: null }))).answers).toEqual([ + { kind: "not-found", bases: [] }, + ]); + // Into another branch, it isn't a stacked candidate either. + expect( + readLookup(repo, [row(A)], [], associatedReply({ ...forcedAway, baseRefName: "stack/base" })) + .answers, + ).toEqual([{ kind: "not-found", bases: [] }]); + + // The same through the fake: the tip was force-pushed away from PR 1, which merged other commits. + const model = state([ + pr({ + number: 1, + headRefOid: B, + commits: [{ oid: B, tree: tree("2") }], + forcePushed: [{ oid: A, tree: tree("1") }], + }), + ]); + const rows = [row(A, ["feature/x"], tree("1"))]; + const { request, heads } = lookupRequest(repo, rows); + const reply = send(model, request); + expect((reply.repository as { a0: unknown }).a0).toMatchObject({ + associatedPullRequests: { nodes: [{ number: 1, state: "MERGED" }] }, + }); + expect(readLookup(repo, rows, heads, reply).answers).toEqual([ + { kind: "not-found", samePr: { number: 1, mergedAt: "2026-01-01T00:00:00Z" }, bases: [] }, + ]); +}); + +test("the fake lists open and closed pull requests for a commit no merged one holds, and they prove nothing", () => { + const model = state([ + pr({ number: 1, state: "OPEN", mergedAt: null }), + pr({ + number: 2, + state: "CLOSED", + mergedAt: null, + headRefOid: B, + commits: [{ oid: B, tree: tree("2") }], + }), + ]); + const rows = [row(A, ["feature/x"], tree("1")), row(B, ["feature/x"], tree("2"))]; + const { request, heads } = lookupRequest(repo, rows); + const reply = send(model, request); + const listed = reply.repository as Record< + string, + { associatedPullRequests?: { nodes: unknown[] }; nodes?: unknown[] } + >; + expect(listed.a0!.associatedPullRequests!.nodes).toEqual([ + expect.objectContaining({ number: 1, state: "OPEN", mergedAt: null }), + ]); + expect(listed.a1!.associatedPullRequests!.nodes).toEqual([ + expect.objectContaining({ number: 2, state: "CLOSED", mergedAt: null }), + ]); + // states:MERGED leaves them out of the branch's list. + expect(listed.b0!.nodes).toEqual([]); + expect(readLookup(repo, rows, heads, reply).answers).toEqual([ + { kind: "not-found", bases: [] }, + { kind: "not-found", bases: [] }, + ]); }); test("partial data: rows whose fields errored fail, the others are read", () => { diff --git a/tests/integration/github.test.ts b/tests/integration/github.test.ts index b014476..452338e 100644 --- a/tests/integration/github.test.ts +++ b/tests/integration/github.test.ts @@ -25,14 +25,18 @@ import { row, scan, waitFor } from "./helpers"; setDefaultTimeout(TEST_TIMEOUT); -type Name = "merged" | "branch" | "earlier" | "treeMatch" | "missing" | "stacked"; +type Name = "merged" | "branch" | "earlier" | "treeMatch" | "missing" | "forced" | "stacked"; let sandbox: Sandbox; let hub: Repo; let solo: Repo; let plain: Repo; let settled: Repo; +let opened: Repo; +let closed: Repo; let built: Record; +let openBuilt: Built; +let closedBuilt: Built; let soloBuilt: Built; let plainBuilt: Built; let settledBuilt: Built; @@ -40,11 +44,13 @@ let open: Services[] = []; beforeAll(async () => { sandbox = await createSandbox(); - [hub, solo, plain, settled] = await Promise.all([ + [hub, solo, plain, settled, opened, closed] = await Promise.all([ sandbox.repo("hub", { github: true }), sandbox.repo("solo", { github: true }), sandbox.repo("plain"), sandbox.repo("settled", { github: true }), + sandbox.repo("opened", { github: true }), + sandbox.repo("closed", { github: true }), ]); // Each merges into main, so they run one after another. built = { @@ -53,12 +59,15 @@ beforeAll(async () => { earlier: await hub.prMergedEarlierCommit("feature/earlier"), treeMatch: await hub.prTreeMatch("feature/rebased"), missing: await hub.prMissingCommit("feature/missing"), + forced: await hub.prForcePushedAway("feature/forced"), stacked: await hub.prStacked("feature/top", { base: "feature/bottom" }), }; - [soloBuilt, plainBuilt, settledBuilt] = await Promise.all([ + [soloBuilt, plainBuilt, settledBuilt, openBuilt, closedBuilt] = await Promise.all([ solo.prMergedWorktree("feature/solo"), plain.unmergedWorktree("feature/plain"), settled.mergedWorktree("feature/settled"), + opened.prUnmerged("feature/open", { state: "OPEN" }), + closed.prUnmerged("feature/closed", { state: "CLOSED" }), ]); }, 60_000); @@ -86,10 +95,10 @@ async function callsSince(before: number): Promise { return (await sandbox.gh.calls()).slice(before); } -/** The `-f` fields of a call, by name, after checking every value was passed with `-f`. */ +/** The `-f` fields of a call, by name, after checking it names github.com and passes every value with `-f`. */ function fields(call: GhCall): Record { - expect(call.argv.slice(0, 2)).toEqual(["api", "graphql"]); - const pairs = call.argv.slice(2); + expect(call.argv.slice(0, 4)).toEqual(["api", "graphql", "--hostname", "github.com"]); + const pairs = call.argv.slice(4); expect(pairs.filter((_, index) => index % 2 === 0).every((flag) => flag === "-f")).toBe(true); return Object.fromEntries( pairs @@ -166,10 +175,14 @@ test("the fake GitHub holds what each builder's Git implies", async () => { hasTip: commits.nodes.some(({ commit }) => commit.oid === tips[at(name)]), hasTree: commits.nodes.some(({ commit }) => commit.tree?.oid === trees[at(name)]), })); - const [merged, branch, earlier, treeMatch, missing] = order.map( + const [merged, branch, earlier, treeMatch, missing, forced] = order.map( (name) => built[name].github!.pullRequests[0]!, ); const [intoBase, intoMain] = built.stacked.github!.pullRequests; + const tipInCommits = (name: Name) => + answer[`a${at(name)}`]?.associatedPullRequests?.nodes.map(({ commits }) => + commits.nodes.some(({ commit }) => commit.oid === tips[at(name)]), + ) ?? null; expect(associated("merged")).toEqual([{ number: merged, tipIsHead: true, baseRefName: "main" }]); expect(associated("branch")).toEqual([{ number: branch, tipIsHead: true, baseRefName: "main" }]); @@ -182,6 +195,12 @@ test("the fake GitHub holds what each builder's Git implies", async () => { // Committed after the merge: neither the tip nor its files are on GitHub. expect(associated("missing")).toBeNull(); expect(fromHead("missing")).toEqual([{ number: missing, hasTip: false, hasTree: false }]); + // Force-pushed away: GitHub still associates the tip with the merged pull request, whose commits lack it. + expect(associated("forced")).toEqual([{ number: forced, tipIsHead: false, baseRefName: "main" }]); + expect(tipInCommits("forced")).toEqual([false]); + expect(fromHead("forced")).toEqual([{ number: forced, hasTip: false, hasTree: false }]); + expect(tipInCommits("merged")).toEqual([true]); + expect(tipInCommits("earlier")).toEqual([true]); // Stacked: merged into feature/bottom, which a later pull request merged into main with the tip in it. expect(associated("stacked")).toEqual([ { number: intoBase!, tipIsHead: true, baseRefName: "feature/bottom" }, @@ -212,7 +231,7 @@ test("asked online, every pr… row reaches the builder's verdict, with one requ Object.fromEntries(Object.entries(built).map(([name, { github }]) => [name, github!.verdict])), ); const forge = (name: Name) => row(snapshot, built[name]).forge; - const [merged, branch, earlier, treeMatch, missing] = (Object.keys(built) as Name[]).map( + const [merged, branch, earlier, treeMatch, missing, forced] = (Object.keys(built) as Name[]).map( (name) => built[name].github!.pullRequests[0]!, ); const proven = (name: Name, pr: number, by: string) => ({ @@ -234,6 +253,19 @@ test("asked online, every pr… row reaches the builder's verdict, with one requ tip: row(snapshot, built.missing).headSha, samePr: { number: missing }, }); + // GitHub associates the force-pushed-away tip with the merged pull request, which doesn't hold it. + expect(forge("forced")).toMatchObject({ + kind: "not-found", + tip: row(snapshot, built.forced).headSha, + samePr: { number: forced }, + }); + // Only an open, or closed and unmerged, pull request holds the tip. + for (const unmerged of [openBuilt, closedBuilt]) + expect(row(snapshot, unmerged)).toMatchObject({ + verdict: "Review", + reason: "1 commit isn't in main. No merged pull request on GitHub has this commit.", + forge: { kind: "not-found", tip: row(snapshot, unmerged).headSha }, + }); const shown = row(snapshot, built.merged); expect(assess(shown).status).toBe("merged on GitHub"); expect(shown.reason).toStartWith(`PR #${merged} merged `); @@ -269,13 +301,15 @@ test("asked online, every pr… row reaches the builder's verdict, with one requ .map(({ repo, chained }) => ({ repo, chained })) .sort((a, b) => a.repo.localeCompare(b.repo) || Number(a.chained) - Number(b.chained)), ).toEqual([ + { repo: "acme/closed", chained: false }, { repo: "acme/hub", chained: false }, { repo: "acme/hub", chained: true }, + { repo: "acme/opened", chained: false }, { repo: "acme/solo", chained: false }, ]); const lookup = asked.find(({ repo, chained }) => repo === "acme/hub" && !chained)!; const rows = Object.values(built).map((one) => row(snapshot, one)); - expect(Object.keys(lookup.variables).filter((key) => key.startsWith("oid"))).toHaveLength(6); + expect(Object.keys(lookup.variables).filter((key) => key.startsWith("oid"))).toHaveLength(7); expect( Object.entries(lookup.variables) .filter(([key]) => key.startsWith("oid")) @@ -318,22 +352,71 @@ test("a second scan sends nothing for the proofs it cached, and a repo with only ); expect(row(snapshot, soloBuilt).verdict).toBe("Safe"); const calls = await callsSince(before); - // Only the tip GitHub didn't hold is asked about again. - expect(calls.map((call) => fields(call))).toEqual([ - expect.objectContaining({ - owner: "acme", - name: "hub", - oid0: row(snapshot, built.missing).headSha!, - head0: built.missing.branch!, + // Only tips GitHub didn't prove are asked about again; solo, all cached, isn't asked. + const asked = Object.fromEntries( + calls.map((call) => { + const { query: _query, owner, name, ...variables } = fields(call); + return [`${owner}/${name}`, Object.values(variables).sort()]; }), - ]); - expect(Object.keys(fields(calls[0]!)).sort()).toEqual([ - "head0", - "name", - "oid0", - "owner", - "query", - ]); + ); + const tipAndBranch = (one: Built) => [row(snapshot, one).headSha!, one.branch!]; + expect(calls).toHaveLength(3); + expect(asked).toEqual({ + "acme/hub": [...tipAndBranch(built.missing), ...tipAndBranch(built.forced)].sort(), + "acme/opened": tipAndBranch(openBuilt).sort(), + "acme/closed": tipAndBranch(closedBuilt).sort(), + }); +}); + +test("gh is told github.com even when GH_HOST names another host", async () => { + const before = (await sandbox.gh.calls()).length; + const elsewhere = await sandbox.services({ + github: online(sandbox), + runner: (command, args, signal, environment) => + sandbox.runner(command, args, signal, { ...environment, GH_HOST: "ghe.example.com" }), + }); + open.push(elsewhere); + await scan(elsewhere.dashboard, solo); + const snapshot = await waitFor(elsewhere.dashboard, (next) => next.checking === 0); + expect(row(snapshot, soloBuilt)).toMatchObject({ verdict: "Safe", forge: { kind: "proven" } }); + const calls = await callsSince(before); + expect(calls).toHaveLength(1); + expect(calls[0]!.env.GH_HOST).toBe("ghe.example.com"); + expect(fields(calls[0]!)).toMatchObject({ owner: "acme", name: "solo" }); +}); + +test("Worktrunk gives the upstream's branch name without its remote, and both names are asked about", async () => { + const renamed = await sandbox.repo("renamed", { github: true }); + const local = await renamed.unmergedWorktree("feature/local"); + await sandbox.git(local.path!, "push", "-q", "-u", "origin", "feature/local:pushed/elsewhere"); + const same = await renamed.unmergedWorktree("feature/same"); + await sandbox.git(same.path!, "push", "-q", "-u", "origin", "feature/same"); + const listed = JSON.parse( + await sandbox.wt(renamed.path, "--config-set", "list.json-schema=2", "list", "--format=json"), + ) as { items: Array<{ branch: string; upstream?: { remote?: string; branch?: string } }> }; + const upstreams = Object.fromEntries(listed.items.map((item) => [item.branch, item.upstream])); + expect(upstreams["feature/local"]).toMatchObject({ + remote: "origin", + branch: "pushed/elsewhere", + }); + expect(upstreams["feature/same"]).toMatchObject({ remote: "origin", branch: "feature/same" }); + + const before = (await sandbox.gh.calls()).length; + const { dashboard } = await services(online(sandbox)); + await scan(dashboard, renamed); + const snapshot = await waitFor(dashboard, (next) => next.checking === 0); + expect(row(snapshot, local)).toMatchObject({ + upstreamBranch: "pushed/elsewhere", + upstreamAhead: 0, + }); + expect(row(snapshot, same)).toMatchObject({ upstreamBranch: "feature/same", upstreamAhead: 0 }); + const calls = await callsSince(before); + expect(calls).toHaveLength(1); + const heads = Object.entries(fields(calls[0]!)) + .filter(([key]) => key.startsWith("head")) + .map(([, head]) => head) + .sort(); + expect(heads).toEqual(["feature/local", "feature/same", "pushed/elsewhere"]); }); const reviewWith = (note: string) => (name: Name) => ({ @@ -428,7 +511,12 @@ interface Answer { string, { associatedPullRequests?: { - nodes: Array<{ number: number; headRefOid: string; baseRefName: string }>; + nodes: Array<{ + number: number; + headRefOid: string; + baseRefName: string; + commits: { nodes: Array<{ commit: { oid: string } }> }; + }>; }; nodes?: Array<{ number: number; @@ -444,3 +532,24 @@ async function ask(args: string[]): Promise { expect({ exitCode: result.exitCode, stderr: result.stderr }).toEqual({ exitCode: 0, stderr: "" }); return (JSON.parse(result.stdout) as Answer).data.repository; } + +// Last: it removes a hub worktree the other tests list. +test("a worktree whose tip GitHub associates with a merged pull request it isn't in stays Review and keeps its branch", async () => { + const { dashboard, actions } = await services(online(sandbox)); + await scan(dashboard, hub); + const snapshot = await waitFor(dashboard, (next) => next.checking === 0); + const shown = row(snapshot, built.forced); + expect(shown).toMatchObject({ verdict: "Review", forge: { kind: "not-found" } }); + const plan = await actions.prepareRemoval([shown]); + expect(plan.entries[0]).toMatchObject({ branchWillBeRetained: true }); + expect(plan.entries[0]?.branchProof).toBeUndefined(); + const result = await actions.executeRemoval(plan, { [shown.id]: { include: true } }); + expect(result.items).toEqual([ + expect.objectContaining({ + id: shown.id, + status: "removed", + branchOutcome: "retained_unmerged", + }), + ]); + expect(await hub.git("rev-parse", `refs/heads/${built.forced.branch}`)).toBe(shown.headSha!); +}); diff --git a/tests/support/fixture.ts b/tests/support/fixture.ts index 69626f4..ba00ac8 100644 --- a/tests/support/fixture.ts +++ b/tests/support/fixture.ts @@ -170,6 +170,17 @@ export interface Repo { prTreeMatch(branch: string): Promise; /** A worktree with a commit made after its pull request merged, which GitHub lacks: still Review. */ prMissingCommit(branch: string): Promise; + /** + * A worktree whose pushed tip was force-pushed away from its pull request before the pull request merged + * other work. GitHub still associates the tip with the merged pull request, but its commits don't include + * it: still Review. + */ + prForcePushedAway(branch: string): Promise; + /** + * A worktree whose tip is only in a pull request that is still open, or `closed` without merging. Its branch + * is still on GitHub and main hasn't moved, so Worktrunk shows one unmerged commit: still Review. + */ + prUnmerged(branch: string, options: { state: "OPEN" | "CLOSED" }): Promise; /** * A worktree whose tip was merged into `base` with a merge commit by one pull request, then `base` squash-merged * into main by a second, whose commits include the tip; `base` has a commit of its own and no local branch. @@ -589,7 +600,7 @@ export async function createSandbox( */ async function mergePullRequest( file: string, - pr: { headRefName: string; head: string; commits: string[] }, + pr: { headRefName: string; head: string; commits: string[]; forcePushed?: string[] }, ): Promise { const github = toGitHub("mergePullRequest"); const number = ++pullRequests; @@ -616,6 +627,7 @@ export async function createSandbox( headRefName: pr.headRefName, headRefOid: pr.head, commits: await described(pr.commits), + ...(pr.forcePushed ? { forcePushed: await described(pr.forcePushed) } : {}), }); await git(path, "push", "-q", "origin", "--delete", pr.headRefName); await git(path, "fetch", "-q", "--prune", "origin"); @@ -899,6 +911,46 @@ export async function createSandbox( await editLine(worktree, file, 9, `${branch}, after the merge`); return { ...built(branch, worktree, unprovable(2)), ...onGitHub([number], "Review") }; }, + async prForcePushedAway(branch) { + movesMain("prForcePushedAway"); + toGitHub("prForcePushedAway"); + const { file, worktree, tip } = await pullRequestBranch(branch); + // Other work replaced the tip on GitHub: made here, then dropped, so no ref here reaches it. + await git(worktree, "reset", "-q", "--hard", `${tip}~1`); + await editLine(worktree, file, CHANGED, `${branch}, rewritten`); + const rewritten = await head(worktree); + await git(worktree, "reset", "-q", "--hard", tip); + const number = await mergePullRequest(file, { + headRefName: branch, + head: rewritten, + commits: [rewritten], + forcePushed: [tip], + }); + return { ...built(branch, worktree, unprovable(1)), ...onGitHub([number], "Review") }; + }, + async prUnmerged(branch, { state }) { + movesMain("prUnmerged"); + const github = toGitHub("prUnmerged"); + const { worktree, tip } = await pullRequestBranch(branch); + const number = ++pullRequests; + await gh.addPullRequest(github.owner, github.name, { + number, + state, + mergedAt: null, + base: "main", + headRefName: branch, + headRefOid: tip, + commits: await described([tip]), + }); + return { + ...built(branch, worktree, { + verdict: "Review", + status: "unmerged commits", + reason: "1 commit isn't in main.", + }), + ...onGitHub([number], "Review"), + }; + }, async prStacked(branch, { base = `${branch}-base` } = {}) { movesMain("prStacked"); const github = toGitHub("prStacked"); diff --git a/tests/support/gh.test.ts b/tests/support/gh.test.ts index 30ec87b..3e7c37b 100644 --- a/tests/support/gh.test.ts +++ b/tests/support/gh.test.ts @@ -95,6 +95,7 @@ const associated = (pr: GhPullRequest) => ({ headRefName: pr.headRefName, headRefOid: pr.headRefOid, repository: { nameWithOwner: "acme/app", defaultBranchRef: { name: "main" } }, + commits: { nodes: pr.commits.map(({ oid }) => ({ commit: { oid } })) }, }); const fromHead = (pr: GhPullRequest) => ({ number: pr.number, @@ -237,6 +238,12 @@ test.each([ ["another API", ["api", "repos/acme/app"]], ["a typed -F field", ["api", "graphql", "-f", "query={ viewer { login } }", "-F", "first=5"]], ["another flag", ["api", "graphql", "--jq", ".data", "-f", "query={ viewer { login } }"]], + // Without --hostname real gh picks GH_HOST or the only signed-in host, which may be GitHub Enterprise. + ["a query without --hostname", ["api", "graphql", "-f", "query={ rateLimit { cost } }"]], + [ + "another host", + ["api", "graphql", "--hostname", "ghe.example.com", "-f", "query={ rateLimit { cost } }"], + ], ])("refuses %s loudly", async (_, args) => { await given({}); const result = await gh(args); diff --git a/tests/support/gh.ts b/tests/support/gh.ts index 91a35b0..26a4802 100644 --- a/tests/support/gh.ts +++ b/tests/support/gh.ts @@ -4,7 +4,8 @@ import { join } from "node:path"; /** * A fake GitHub CLI for the sandbox. `gh-cli.ts` is the executable; this module holds the GitHub model it * answers from, and `createFakeGh`, which the fixture uses to write that model and read the calls made. - * It answers only `gh api graphql -f query=… -f =…`, and only the fields wt-dash's query asks for. + * It answers only `gh api graphql --hostname github.com -f query=… -f =…`, and only the fields wt-dash's + * query asks for. Without `--hostname`, real gh asks `GH_HOST` or the only signed-in host, so the fake refuses it. */ /** The environment variable naming the state file the fake reads on every call. */ @@ -23,10 +24,13 @@ export interface GhCommit { tree: string; } -/** A merged pull request. */ +/** A pull request, merged unless `state` says otherwise. */ export interface GhPullRequest { number: number; - mergedAt: string; + /** MERGED when omitted. */ + state?: "MERGED" | "OPEN" | "CLOSED"; + /** When it merged; null for an open or closed one. */ + mergedAt: string | null; /** The branch it was merged into, `baseRefName`. */ base: string; headRefName: string; @@ -35,6 +39,11 @@ export interface GhPullRequest { headRepository?: string; /** Its commits, oldest first, as GitHub lists them after any force push. */ commits: GhCommit[]; + /** + * Commits pushed to its branch and later force-pushed away. GitHub still knows them and still lists this pull + * request among their associated pull requests, but they aren't among its commits. + */ + forcePushed?: GhCommit[]; } export interface GhRepo { @@ -97,9 +106,18 @@ export function answerGh(state: GhState, args: string[]): GhResult { `only "gh api graphql -f …" is supported, not "gh ${args.join(" ")}". Extend tests/support/gh.ts if the app needs it.`, ); const fields: Record = {}; + let hostname: string | undefined; for (let index = 2; index < args.length; index++) { const arg = args[index]!; let field: string | undefined; + if (arg === "--hostname") { + hostname = args[++index]; + continue; + } + if (arg.startsWith("--hostname=")) { + hostname = arg.slice("--hostname=".length); + continue; + } if (arg === "-f" || arg === "--raw-field") field = args[++index]; else if (arg.startsWith("--raw-field=")) field = arg.slice("--raw-field=".length); else if (arg.startsWith("-f") && arg.length > 2) field = arg.slice(2); @@ -110,6 +128,11 @@ export function answerGh(state: GhState, args: string[]): GhResult { if (field === undefined || equals < 1) return refuse(`-f needs key=value, got ${field}`); fields[field.slice(0, equals)] = field.slice(equals + 1); } + if (hostname === undefined) + return refuse( + "no --hostname: gh would ask GH_HOST or the only signed-in host, which may not be github.com", + ); + if (hostname !== "github.com") return refuse(`only github.com is modelled, not ${hostname}`); if (state.mode !== "ok" && state.mode !== "missing-repo") return failures[state.mode]; const { query, ...variables } = fields; if (query === undefined) return refuse("no -f query=…"); @@ -416,11 +439,18 @@ function root( }; } +const stateOf = (pr: GhPullRequest) => pr.state ?? "MERGED"; + function repository(repo: GhRepo): Node { const nameWithOwner = `${repo.owner}/${repo.name}`; - const byMerge = [...repo.pullRequests].sort( - (a, b) => Date.parse(a.mergedAt) - Date.parse(b.mergedAt) || a.number - b.number, - ); + const byMerge = repo.pullRequests + .filter((pr) => stateOf(pr) === "MERGED") + .sort((a, b) => Date.parse(a.mergedAt!) - Date.parse(b.mergedAt!) || a.number - b.number); + const unmerged = repo.pullRequests + .filter((pr) => stateOf(pr) !== "MERGED") + .sort((a, b) => a.number - b.number); + const known = (pr: GhPullRequest) => [...pr.commits, ...(pr.forcePushed ?? [])]; + const holds = (pr: GhPullRequest, oid: string) => known(pr).some((commit) => commit.oid === oid); const node: Node = { __typename: "Repository", name: repo.name, @@ -430,7 +460,7 @@ function repository(repo: GhRepo): Node { if (expression !== undefined) throw new QueryError("fake gh: object(expression:) isn't modelled"); const found = repo.pullRequests - .flatMap((pr) => pr.commits) + .flatMap(known) .find((commit) => commit.oid === String(oid).toLowerCase()); return found ? commit(found) : null; }, @@ -445,7 +475,7 @@ function repository(repo: GhRepo): Node { ); const nodes = sorted.filter( (pr) => - (!states.length || states.includes("MERGED")) && + (!states.length || states.includes(stateOf(pr))) && (args.headRefName === undefined || pr.headRefName === args.headRefName) && (args.baseRefName === undefined || pr.base === args.baseRefName), ); @@ -461,10 +491,14 @@ function repository(repo: GhRepo): Node { __typename: "Commit", oid: found.oid, tree: { __typename: "Tree", oid: found.tree }, - // GitHub lists the pull request that first brought the commit in, not later ones that contain it too. + // GitHub lists the merged pull request that first brought the commit in, not later ones that contain it + // too, and counts a commit force-pushed away from it. A commit no merged pull request has lists the open and + // closed ones it was pushed to. associatedPullRequests: (args: Args) => { - const first = byMerge.find((pr) => pr.commits.some(({ oid }) => oid === found.oid)); - const nodes = first ? [pullRequest(first)] : []; + const first = byMerge.find((pr) => holds(pr, found.oid)); + const nodes = (first ? [first] : unmerged.filter((pr) => holds(pr, found.oid))).map( + pullRequest, + ); return { __typename: "PullRequestConnection", totalCount: nodes.length, @@ -477,8 +511,8 @@ function repository(repo: GhRepo): Node { return { __typename: "PullRequest", number: pr.number, - state: "MERGED", - merged: true, + state: stateOf(pr), + merged: stateOf(pr) === "MERGED", mergedAt: pr.mergedAt, baseRefName: pr.base, headRefName: pr.headRefName, @@ -521,7 +555,8 @@ ${range(oids) .map( (index) => ` a${index}: object(oid:$oid${index}) { ... on Commit { associatedPullRequests(first:5) { nodes { number state mergedAt baseRefName headRefName headRefOid - repository { nameWithOwner defaultBranchRef { name } } } } } }`, + repository { nameWithOwner defaultBranchRef { name } } + commits(last:250) { nodes { commit { oid } } } } } } }`, ) .join("\n")} ${range(heads) @@ -558,11 +593,13 @@ ${range(bases) }`; } -/** `gh` arguments for `query`, every value passed with `-f` as the app will. */ +/** `gh` arguments for `query` on github.com, every value passed with `-f` as the app will. */ export function graphqlArgs(query: string, variables: Record): string[] { return [ "api", "graphql", + "--hostname", + "github.com", "-f", `query=${query}`, ...Object.entries(variables).flatMap(([key, value]) => ["-f", `${key}=${value}`]), From 3c3acc936c67b18ae95887f6fcf0ee682ebc7972 Mon Sep 17 00:00:00 2001 From: Miguel Rodriguez Date: Fri, 6 Nov 2026 20:47:45 -0500 Subject: [PATCH 11/11] chore: verify pull request proofs in the real app --- .claude/skills/verify-wt-dash/SKILL.md | 53 +++--- .../skills/verify-wt-dash/features/README.md | 39 ++--- .../skills/verify-wt-dash/features/details.md | 2 +- .../features/filter-search-sort.md | 4 +- .../verify-wt-dash/features/narrow-table.md | 6 +- .../features/orphaned-folders.md | 2 +- .../features/projects-screen.md | 8 +- .../verify-wt-dash/features/pull-requests.md | 49 ++++++ .../features/remembered-repos.md | 10 +- .../verify-wt-dash/features/remove-dialog.md | 2 + .../skills/verify-wt-dash/features/rescan.md | 4 +- .../verify-wt-dash/features/selection.md | 6 +- .../features/worktree-list-and-verdicts.md | 3 +- .claude/skills/verify-wt-dash/stack.ts | 153 +++++++++++++++++- 14 files changed, 274 insertions(+), 67 deletions(-) create mode 100644 .claude/skills/verify-wt-dash/features/pull-requests.md diff --git a/.claude/skills/verify-wt-dash/SKILL.md b/.claude/skills/verify-wt-dash/SKILL.md index 870900c..ce3b192 100644 --- a/.claude/skills/verify-wt-dash/SKILL.md +++ b/.claude/skills/verify-wt-dash/SKILL.md @@ -29,27 +29,33 @@ There are no ports. Two agents in one checkout only need different names. Never ## Users and test data -There are no users. The data is the seed, built by `tests/support/fixture.ts` with real Git and Worktrunk: four repos under the scan root, one of which (`tools`) has no worktrees. `env --full` → `seed` lists every row with the verdict, status and reason the fixture expects; read it compactly with `bun .claude/skills/verify-wt-dash/stack.ts env --name --full | jq -c '.seed[] | [.repo, .branch, .verdict, .status, .reason]'`. On macOS: - -| Repo | Row (kind) | Verdict | Status | Notes | -| ---- | -------------------------- | --------------- | -------------------- | ---------------------------------- | -| api | feature/assets | Safe | merged | 12.0 MB of ignored files | -| api | feature/login | Safe | merged | 3 days old | -| api | agent/old-session | Safe | merged | 💬 mark 3 days old, "likely stale" | -| api | leftover/hotfix (branch) | Safe | merged | no worktree | -| api | agent/refactor | Review | merged | 🤖 mark set at seed time | -| api | feature/new-endpoint | Review | no new commits | created at seed time; AGE `3d` | -| api | feature/dirty-form | Review | uncommitted changes | | -| api | feature/locked | Review, blocked | locked | reason "agent session" | -| api | leftover/spike (branch) | Review | unmerged commits | no worktree | -| web | fix/header, feature/bundle | Safe | merged | bundle is 4.0 MB | -| web | feature/search | Review | unmerged commits | 2 commits | -| web | feature/cache | Review | unpushed commits | local bare `origin` | -| web | feature/rebase | Busy, blocked | rebase in progress | | -| web | feature/gone | Broken | folder missing | | -| docs | docs/typos | Safe | merged | 3 days old | -| docs | docs/conflict | Busy, blocked | unresolved conflicts | | -| docs | docs/locked-bare | Review, blocked | locked | no reason | +There are no users. The data is the seed, built by `tests/support/fixture.ts` with real Git and Worktrunk: five repos under the scan root, one of which (`tools`) has no worktrees, and one (`worker`) on GitHub through the fake `gh`. `env --full` → `seed` lists every row with the verdict, status and reason the fixture expects; read it compactly with `bun .claude/skills/verify-wt-dash/stack.ts env --name --full | jq -c '.seed[] | [.repo, .branch, .verdict, .status, .reason]'`. On macOS: + +| Repo | Row (kind) | Verdict | Status | Notes | +| ------ | ------------------------------------------------------------------- | --------------- | -------------------- | ------------------------------------------ | +| api | feature/assets | Safe | merged | 12.0 MB of ignored files | +| api | feature/login | Safe | merged | 3 days old | +| api | agent/old-session | Safe | merged | 💬 mark 3 days old, "likely stale" | +| api | leftover/hotfix (branch) | Safe | merged | no worktree | +| api | agent/refactor | Review | merged | 🤖 mark set at seed time | +| api | feature/new-endpoint | Review | no new commits | created at seed time; AGE `3d` | +| api | feature/dirty-form | Review | uncommitted changes | | +| api | feature/locked | Review, blocked | locked | reason "agent session" | +| api | leftover/spike (branch) | Review | unmerged commits | no worktree | +| web | fix/header, feature/bundle | Safe | merged | bundle is 4.0 MB | +| web | feature/search | Review | unmerged commits | 2 commits | +| web | feature/cache | Review | unpushed commits | local bare `origin` | +| web | feature/rebase | Busy, blocked | rebase in progress | | +| web | feature/gone | Broken | folder missing | | +| docs | docs/typos | Safe | merged | 3 days old | +| docs | docs/conflict | Busy, blocked | unresolved conflicts | | +| docs | docs/locked-bare | Review, blocked | locked | no reason | +| worker | feature/squashed, feature/revised, feature/rebased, feature/stacked | Safe | merged on GitHub | squash-merged; Review until GitHub answers | +| worker | leftover/squashed (branch) | Safe | merged on GitHub | no worktree, 3 days old | +| worker | feature/after-merge | Review | unmerged commits | a commit made after its PR merged | +| worker | feature/no-pr | Review | unmerged commits | pushed, in no pull request | + +`worker` is the only repository on github.com, and the app starts online, so its first scan asks the fake GitHub; `seed` holds each `worker` row as it reads once GitHub has answered, and `github.gitOnly` as it reads before or without an answer. [features/pull-requests.md](features/pull-requests.md) has the details. `stack.ts gh --name [--mode ] [--delay ]` changes how the fake answers from its next call and prints its call count; `up --gh-mode`/`--gh-delay` do the same before the app starts, which is the only way to see the first scan's check, since proofs are cached. The list's AGE column (`now`, `3d`) is the age of the row's last commit, not of the worktree; verdict reasons such as "Created just now" use when the worktree was created. So `feature/new-endpoint`, made at seed time on top of a main commit dated 3 days back, reads `3d` beside `Created just now, so it may s…`: expected, and `i` shows the same split (`LAST COMMIT 3d ago`). The worktrees made by the fixture's squash-merge builders read `now` because their own commits are new. @@ -99,7 +105,7 @@ It defines `t` (tmux on the instance socket), `screen` (plain text of the pane), - **One key, then wait for its effect, then read.** A capture right after `send-keys` can still show the previous frame. Wait for text that only the new state has: the screen title on line 1 (`wt-dash › web`), a dialog title, a toast. Before waiting for something to go, confirm it was there. - **Locate by text and line.** Line 1 is the header (screen title, counts, `scanned HH:MM`); line 2 the tabs and search in a list; the second-last line the status (toasts, removal progress); the last line the key hints. The focused row starts with `▌`, a selected row has `■`, an unselectable one `–`. In the wide layout everything right of the sidebar's `│` is the list: `screen | sed 's/^.*│ //'` reads it alone. - **Exact values.** Compare whole lines or exact substrings (`grep -F`), never "something changed". Colors: `t capture-pane -p -e -t app` keeps the escapes (Safe `38;5;2`, Review `38;5;3`, Busy `38;5;4`, Broken `38;5;1`). -- **Git state** after an action: `bun .claude/skills/verify-wt-dash/stack.ts state --name ` prints `{"ok":true,"name":…,"repos":{"":{"worktrees":[{"path","branch","head","locked"?,"prunable"?,"exists"}],"branches":["…"]}},"removalsLog":[{"timestamp","repo","branch","path","flags","exitCode","branchOutcome","error",…}]}`. `repos` is an object keyed by repo name (`api`, `web`, `docs`, `tools`), not an array; the main checkout is the first worktree; `branch` is null for a detached HEAD (`feature/rebase` mid-rebase); `removalsLog` is the last 20 lines of the instance's `removals.log`, oldest first (`--log ` for more). For example `state --name | jq -c '.repos.api.branches, [.repos.web.worktrees[].branch], .removalsLog[-1]'`. +- **Git state** after an action: `bun .claude/skills/verify-wt-dash/stack.ts state --name ` prints `{"ok":true,"name":…,"repos":{"":{"worktrees":[{"path","branch","head","locked"?,"prunable"?,"exists"}],"branches":["…"]}},"removalsLog":[{"timestamp","repo","branch","path","flags","exitCode","branchOutcome","error",…}]}`. `repos` is an object keyed by repo name (`api`, `web`, `docs`, `tools`, `worker`), not an array; the main checkout is the first worktree; `branch` is null for a detached HEAD (`feature/rebase` mid-rebase); `removalsLog` is the last 20 lines of the instance's `removals.log`, oldest first (`--log ` for more). For example `state --name | jq -c '.repos.api.branches, [.repos.web.worktrees[].branch], .removalsLog[-1]'`. - **Watch it yourself** (optional, read-only): `t attach -r -t app` from a real terminal. Worked example, [leftover-branches.md](features/leftover-branches.md) checks 3 and 4, as run: @@ -150,7 +156,7 @@ It saves the pane with colors (`evidence/.ansi`), renders rows and columns - **Escape followed closely by a key is Alt+key.** `t send-keys -t app Escape 3` (or two quick calls) reaches the app as Alt+3: the Escape is lost. Send Escape alone, wait for its effect, then the next key. - **The remove dialog ignores Enter for 400 ms after it opens** (`y` is never ignored). `send-keys Enter Enter` opens it and leaves it open; wait for the dialog before confirming with Enter. - **Toasts last 2.5–10 s** (most 4 s; removal summaries 10 s; "Can't select" 6 s) on the status line. Read them right after the key, and do not mistake an earlier toast for a new one. -- **Spinners and progress** (`⠼ scanning 0/4 repos`, `Removing 1 of 1: …`) change every 120 ms and a local scan or removal ends in under a second; poll every 50 ms right after the key to catch them, and never compare whole screens while one is up. +- **Spinners and progress** (`⠼ scanning 0/5 repos`, `Removing 1 of 1: …`) change every 120 ms and a local scan or removal ends in under a second; poll every 50 ms right after the key to catch them, and never compare whole screens while one is up. - **A removal in `web` drops the Broken `feature/gone` record** (it becomes a branch row; seen twice). Prove anything about Broken rows before removing in `web`, or on a fresh seed. - **`sizing` is gone within a second of `scanned`** on the seed. To see it, add a worktree with a large folder (a few hundred thousand files) as the instance's user and press `r`: `1 sizing` shows while `du` runs. A worktree whose saved size went stale keeps its old size while re-measured, so it never reads `sizing`. A worktree whose `du` fails (an unreadable subfolder, a missing folder) stops reading `sizing` once it fails. - **Selections and screen survive a resize.** `resize-window` keeps the selection, the open project and the focus (a row selected wide is still `■ 1 selected` narrow, and back). Clear the selection (Esc) before switching variants, or the next variant's checks start with it. @@ -158,6 +164,7 @@ It saves the pane with colors (`evidence/.ansi`), renders rows and columns - **Truncation.** The list cuts reasons and long branch names with `…` (`feature/n…-endpoint` at 80 columns) and drops the reason's final period; the sidebar and strip cut paths in the middle. Read full values from `i` or `state`. - **The wide sidebar never mentions `tools`** (no worktrees); only the narrow table says `1 project with no worktrees`. - **zsh does not split a variable into words**: `T="tmux -L x"; $T ls` fails with "command not found". Use the preamble's `t` function. +- **A checkout under `.claude/worktrees`** (an agent's worktree) puts the sandbox there too, so every seeded worktree reads `Claude Code` where the feature files say `other` (`Claude Code 22 · no worktree 3`). The counts still match. - **Paths are real paths.** The sandbox lives in the checkout, so paths are what `env` prints. A worktree added under a macOS temp folder (`/var/folders/...`) shows in the app and in `state` as `/private/var/folders/...`. Add worktrees under `env` → `paths.worktrees`: `down --purge` deletes only the sandbox, so one outside it stays behind until you `git worktree remove` it. - **Do not run `wt config show`** to inspect the instance's Worktrunk settings: per the developer it runs the claude CLI (its `--full` runs commit-generation checks). Read `$HOME/.config/worktrunk/config.toml` from `env` → `paths.home`. - **tmux 3.6a's server exits at start** ("server exited unexpectedly") when `set -g window-size manual` is in the config file; the stack sets it after creating the session. To watch, attach read-only (`t attach -r -t app`), so no stray key reaches the app. diff --git a/.claude/skills/verify-wt-dash/features/README.md b/.claude/skills/verify-wt-dash/features/README.md index 2dec5b2..2603c87 100644 --- a/.claude/skills/verify-wt-dash/features/README.md +++ b/.claude/skills/verify-wt-dash/features/README.md @@ -2,22 +2,23 @@ What to prove about each user-visible feature of wt-dash. Prove a change by driving its new behavior and rerunning the checks of every feature it touched. Row names (`api › feature/assets`) refer to the seeded rows listed in SKILL.md. -| Feature | Behavior | Not covered | -| ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| [Projects screen](projects-screen.md) | Opens on the projects, most worktrees first, with each project's counts, free space and details. | A scan that finds only one project (opens it directly); a scan error banner | -| [Worktree list and verdicts](worktree-list-and-verdicts.md) | Each project's rows sit in Safe, Review, Busy and Broken sections with their status and reason. | Status unknown; unrelated history; behind main; Linux ages (backdated worktrees read as new) | -| [Filter, search and sort](filter-search-sort.md) | Tabs 1–6, `/` search, `s`/`S` sort and `v` grouping narrow and order the list. | Search from the projects screen; `g`/`G`, PageUp/PageDown | -| [Selection and a](selection.md) | Space selects one row, `a` every Safe row in view or project, Esc clears; selections carry across screens and resizes. | Selection surviving a rescan | -| [Remove dialog and removal](remove-dialog.md) | One dialog lists what goes, warns about discarded changes, names worktrees with running processes, toggles D and e, and removes in the background. | Esc stopping a running removal; queuing a second removal; the stale-confirmation recheck; a failed removal | -| [Blocked rows](blocked-rows.md) | Locked, Busy and Broken rows cannot be selected or removed and say what to do; Broken offers a prune. | Status unknown | -| [Leftover branches](leftover-branches.md) | Local branches without a worktree are listed as "branch" rows; unmerged ones are deleted only with D. | A branch whose name matches a worktree folder; a branch with a recent agent mark | -| [Details i](details.md) | `i` shows a row's full details, including its commits beyond main, notes, agent marks, running processes and the tool that made it; the strip shows a summary. | `R` remeasure; details of a branch row | -| [Orphaned folders](orphaned-folders.md) | Worktree folders no repository knows are listed under "Orphaned folders" with their size and reason, and wt-dash deletes them itself. | A `.claude/worktrees` orphan; the t3 folders; a folder a scanned repo still records (moved repo) | -| [Rescan r](rescan.md) | `r` rescans every repository and picks up changes made outside the app. | A repository deleted between scans; scan errors | -| [Remembered repositories](remembered-repos.md) | Every repository found is saved; a run without folders lists the saved ones too, and gone ones are dropped. | Two runs writing the file at once; a saved repository on an unmounted disk | -| [Narrow table layout](narrow-table.md) | Below 100 columns the projects fill a table with a column per verdict, and Enter opens one. | Widths under 64 (short tab labels) and under 40 | -| Keys overlay `?` | Lists every key. | No checks yet | -| Quit `q` / Ctrl-C | Leaves the terminal. | No checks yet | -| [First run without folders](first-run.md) | With no folder, scans the usual code folders that exist and follows agents' worktrees to their repos; an empty scan names its folders. | Cursor, Conductor and the other agent folders; `--depth` on the default folders | -| [Setups a first run meets](setups.md) | Worktrunk missing, old or built from source, Git missing, a folder that can't be scanned, small terminals and a light theme each get a clear result. | Linux; Git present but broken (Apple's `git` stub without the command line tools) | -| `--depth`, `--wt-path`, several scan folders | Command-line options. | `--wt-path` errors are in [setups](setups.md); the rest has no checks yet | +| Feature | Behavior | Not covered | +| ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| [Projects screen](projects-screen.md) | Opens on the projects, most worktrees first, with each project's counts, free space and details. | A scan that finds only one project (opens it directly); a scan error banner | +| [Worktree list and verdicts](worktree-list-and-verdicts.md) | Each project's rows sit in Safe, Review, Busy and Broken sections with their status and reason. | Status unknown; unrelated history; behind main; Linux ages (backdated worktrees read as new) | +| [Filter, search and sort](filter-search-sort.md) | Tabs 1–6, `/` search, `s`/`S` sort and `v` grouping narrow and order the list. | Search from the projects screen; `g`/`G`, PageUp/PageDown | +| [Selection and a](selection.md) | Space selects one row, `a` every Safe row in view or project, Esc clears; selections carry across screens and resizes. | Selection surviving a rescan | +| [Remove dialog and removal](remove-dialog.md) | One dialog lists what goes, warns about discarded changes, names worktrees with running processes, toggles D and e, and removes in the background. | Esc stopping a running removal; queuing a second removal; the stale-confirmation recheck; a failed removal | +| [Pull requests merged on GitHub](pull-requests.md) | Rows Git can't prove merged are checked with `gh`; a merged pull request makes them Safe and lets removal delete the branch, `--offline` skips it. | gh not installed (the app's note); bad credentials, a timeout, a repository GitHub doesn't know; fork heads; a remote on another host | +| [Blocked rows](blocked-rows.md) | Locked, Busy and Broken rows cannot be selected or removed and say what to do; Broken offers a prune. | Status unknown | +| [Leftover branches](leftover-branches.md) | Local branches without a worktree are listed as "branch" rows; unmerged ones are deleted only with D. | A branch whose name matches a worktree folder; a branch with a recent agent mark | +| [Details i](details.md) | `i` shows a row's full details, including its commits beyond main, notes, agent marks, running processes and the tool that made it; the strip shows a summary. | `R` remeasure; details of a branch row | +| [Orphaned folders](orphaned-folders.md) | Worktree folders no repository knows are listed under "Orphaned folders" with their size and reason, and wt-dash deletes them itself. | A `.claude/worktrees` orphan; the t3 folders; a folder a scanned repo still records (moved repo) | +| [Rescan r](rescan.md) | `r` rescans every repository and picks up changes made outside the app. | A repository deleted between scans; scan errors | +| [Remembered repositories](remembered-repos.md) | Every repository found is saved; a run without folders lists the saved ones too, and gone ones are dropped. | Two runs writing the file at once; a saved repository on an unmounted disk | +| [Narrow table layout](narrow-table.md) | Below 100 columns the projects fill a table with a column per verdict, and Enter opens one. | Widths under 64 (short tab labels) and under 40 | +| Keys overlay `?` | Lists every key. | No checks yet | +| Quit `q` / Ctrl-C | Leaves the terminal. | No checks yet | +| [First run without folders](first-run.md) | With no folder, scans the usual code folders that exist and follows agents' worktrees to their repos; an empty scan names its folders. | Cursor, Conductor and the other agent folders; `--depth` on the default folders | +| [Setups a first run meets](setups.md) | Worktrunk missing, old or built from source, Git missing, a folder that can't be scanned, small terminals and a light theme each get a clear result. | Linux; Git present but broken (Apple's `git` stub without the command line tools) | +| `--depth`, `--wt-path`, several scan folders | Command-line options. | `--wt-path` errors are in [setups](setups.md); the rest has no checks yet | diff --git a/.claude/skills/verify-wt-dash/features/details.md b/.claude/skills/verify-wt-dash/features/details.md index 526cf1b..3304aa2 100644 --- a/.claude/skills/verify-wt-dash/features/details.md +++ b/.claude/skills/verify-wt-dash/features/details.md @@ -20,7 +20,7 @@ 5. Notes left on a branch show in both places. After `git config branch..description` and `wt config state vars set = --branch ` as the instance's user, and `r`: the strip shows a line under the commits line with the description's first line and each var, joined by `·` (`Spike: try GraphQL` for `leftover/spike`); `i` shows `DESCRIPTION` with every non-blank line of the description, then `VARS` with one `key: value` per line. A row with no notes has no such line or fields. 6. On a marked row that also has notes, such as `api › agent/old-session` after `wt config state vars set task=cleanup --branch agent/old-session`, the strip still shows `Agent mark from 3d ago, likely stale.`, above `nothing uncommitted`. 7. For `api › feature/locked`, details read `Locked: agent session` and `Can't be removed: it's locked (agent session); unlock it first`. -8. The tool comes from the worktree's folder (#43). After `git worktree add -b feature/t3 "$HOME/.t3/worktrees/api/feature" main` as the instance's user and `r`, the strip for `api › feature/t3` reads `t3 · last commit · · clean · no tracking branch` in both variants, `i` reads `CREATED BY t3`, `api`'s sidebar details read `other 7 · t3 1 · no workt…`, and the narrow "All projects" strip reads `MADE BY other 16 · t3 1 · no worktree 2`. The seeded worktrees stay `other` even when the checkout itself sits under `~/.t3/worktrees`. +8. The tool comes from the worktree's folder (#43). After `git worktree add -b feature/t3 "$HOME/.t3/worktrees/api/feature" main` as the instance's user and `r`, the strip for `api › feature/t3` reads `t3 · last commit · · clean · no tracking branch` in both variants, `i` reads `CREATED BY t3`, `api`'s sidebar details read `other 7 · t3 1 · no workt…`, and the narrow "All projects" strip reads `MADE BY other 22 · t3 1 · no worktree 3`. The seeded worktrees stay `other` even when the checkout itself sits under `~/.t3/worktrees`. 9. Processes running in a worktree show in both places (#44). Start a server in `api › feature/assets` as the instance's user, outside the app (`cd && nohup python3 -m http.server 8765 >/dev/null 2>&1 &`, noting its pid), and an interactive shell in `api › feature/login` from a tmux server of your own (`tmux -L new-session -d -c zsh -f`), then `r`. The strip for `feature/assets` reads `1 process · :8765` on its own line between the commits line and `nothing uncommitted`, and `i` reads `PROCESSES Python -m http.server 8765 :8765` (macOS names Homebrew's and python.org's Python `Python`). `feature/login` reads `1 process` and `PROCESSES zsh -f (terminal)`. A marked row with a process, such as `agent/old-session`, shows the mark line above the process line. Both rows stay `● Safe · merged`, and rows with nothing running have no such line or field. In both variants. Stop both afterwards (`kill `, `tmux -L kill-server`). 10. File details load while background work or a toast is active (audit #4). In a list, select Safe rows with `a`, then immediately focus a worktree whose files have not loaded. While `Selected …` is still visible, `checking files…` becomes `nothing uncommitted` or the row's uncommitted/ignored file summary; `i` shows the same files. Repeat in "All projects" and both variants. File inspection also proceeds during scanning, sizing, and removals. Rapid focus movement still waits until focus rests for 150 ms; a rescan starts a fresh inspection and results from an older scan never replace the current files. Branch and orphan rows never run a file inspection. diff --git a/.claude/skills/verify-wt-dash/features/filter-search-sort.md b/.claude/skills/verify-wt-dash/features/filter-search-sort.md index f5dd664..3d5a0b8 100644 --- a/.claude/skills/verify-wt-dash/features/filter-search-sort.md +++ b/.claude/skills/verify-wt-dash/features/filter-search-sort.md @@ -13,10 +13,10 @@ In a worktree list, 1–6 show All, Safe, Review, Busy, Broken or Orphaned; `/` ## Checks 1. In `api`, `3` leaves only `? REVIEW 4 worktrees and 1 branch`; `5` shows `No Broken worktrees. Press 1 to see all.`; `1` shows every section again. -2. `/` opens the search: line 2 ends with `/ 9 of 18` (rows in view of all rows). Typing `spike` (send it with `send-keys -l`) leaves one row, `leftover/spike`, the tabs read `All 1 Safe 0 Review 1 Busy 0 Broken 0 Orphaned 0`, and line 2 ends `/ spike 1 of 18`. +2. `/` opens the search: line 2 ends with `/ 9 of 25` (rows in view of all rows). Typing `spike` (send it with `send-keys -l`) leaves one row, `leftover/spike`, the tabs read `All 1 Safe 0 Review 1 Busy 0 Broken 0 Orphaned 0`, and line 2 ends `/ spike 1 of 25`. 3. Enter keeps the search: line 2 ends with `/ spike esc clears`. Esc alone clears it: line 2 ends with `/ search` and the tabs are back to `All 9`. 4. `s` cycles the footer label `s sort: size ↓` → `s sort: age ↓` → `s sort: repo ↑` → `s sort: size ↓`; `S` turns `size ↓` into `size ↑`. -5. With `size ↓` on "All projects", the Safe section starts `feature/assets` (12.0 MB) then `feature/bundle` (4.0 MB); with `size ↑` it starts `docs/typos`, and `leftover/hotfix` (branch) stays last either way. +5. With `size ↓` on "All projects", the Safe section starts `feature/assets` (12.0 MB) then `feature/bundle` (4.0 MB); with `size ↑` it starts `docs/typos`, `fix/header`, `feature/squashed` (12 KB each), and the branch rows `leftover/hotfix` then `leftover/squashed` stay last either way. 6. `v` on "All projects" replaces the verdict sections with repo groups, the first reading `▸ api 7 worktrees and 2 branches · 12.2 MB 4 safe 5 review`, each row with a colored `●`, and the footer shows `v by repo`; `v` again restores them. In a single project, `v` shows the toast `Grouping by repo works in the all-projects view`. 7. Search matches the name a tool is shown by (#43). After `git worktree add -b try/gemini /.gemini/worktrees/try-gemini main` as the instance's user and `r`, typing `gemini cli` leaves one row, `try/gemini`, and line 2 ends `/ gemini cli 1 of `. The path holds `.gemini` but not `gemini cli`, so only the tool's name matches. diff --git a/.claude/skills/verify-wt-dash/features/narrow-table.md b/.claude/skills/verify-wt-dash/features/narrow-table.md index 42dd0e2..b6afab1 100644 --- a/.claude/skills/verify-wt-dash/features/narrow-table.md +++ b/.claude/skills/verify-wt-dash/features/narrow-table.md @@ -12,10 +12,10 @@ Below 100 columns the projects fill a table with a column per verdict, Safe size ## Checks -1. Right after `up --variant narrow`, line 1 reads `wt-dash 16 worktrees and 2 branches · up to 16.4 MB · scanned HH:MM r rescan`, the focused row is `▌ api` (not "All projects"), and the footer is `enter open a select safe / search`. -2. The header row is `PROJECT WORKTREES SAFE REV BUSY BRK ORPH SAFE SIZE TOTAL` (the long titles, `REVIEW … BROKEN ORPHANED`, from 89 columns), followed by `All projects 16 7 8 2 1 · 16.1 MB 16.4 MB`, `api 7 4 5 · · · 12.1 MB 12.2 MB`, `web 6 2 2 1 1 · 4.0 MB 4.1 MB`, `docs 3 1 1 1 · · 12 KB 40 KB` (spacing aside; `·` means zero). +1. Right after `up --variant narrow`, line 1 reads `wt-dash 22 worktrees and 3 branches · up to 16.5 MB · scanned HH:MM r rescan`, the focused row is `▌ api` (not "All projects"), and the footer is `enter open a select safe / search`. +2. The header row is `PROJECT WORKTREES SAFE REV BUSY BRK ORPH SAFE SIZE TOTAL` (the long titles, `REVIEW … BROKEN ORPHANED`, from 89 columns), followed, once GitHub has answered, by `All projects 22 12 10 2 1 · 16.2 MB 16.5 MB`, `api 7 4 5 · · · 12.1 MB 12.2 MB`, `web 6 2 2 1 1 · 4.0 MB 4.1 MB`, `worker 6 5 2 · · · 72 KB 136 KB`, `docs 3 1 1 1 · · 12 KB 40 KB` (spacing aside; `·` means zero). 3. Under the table: `1 project with no worktrees` (the seeded `tools` repo, which the wide sidebar does not mention). -4. Up to "All projects" (`▌ All projects`): the strip reads `SAFE TO FREE 16.1 MB of 16.4 MB` with no `sizing` (#24), `UNCOMMITTED 3 worktrees`, `MADE BY other 16 · no worktree 2`, `LARGEST feature/assets · 12.0 MB`. +4. Up to "All projects" (`▌ All projects`): the strip reads `SAFE TO FREE 16.2 MB of 16.5 MB` with no `sizing` (#24), `UNCOMMITTED 3 worktrees`, `MADE BY other 22 · no worktree 3`, `LARGEST feature/assets · 12.0 MB`. 5. With `api` focused (the start; Down from "All projects"), Enter opens `wt-dash › api` with tabs `All 9 Safe 4 Review 5 Busy 0 Broken 0 Orphaned 0` and the footer `space select enter remove a all safe / search s sort: size ↓ ? keys q quit`. 6. Long branch names are cut in the middle: `feature/n…-endpoint`. diff --git a/.claude/skills/verify-wt-dash/features/orphaned-folders.md b/.claude/skills/verify-wt-dash/features/orphaned-folders.md index 68bc2af..f8bb750 100644 --- a/.claude/skills/verify-wt-dash/features/orphaned-folders.md +++ b/.claude/skills/verify-wt-dash/features/orphaned-folders.md @@ -16,7 +16,7 @@ Worktree folders that no repository knows are listed under an "Orphaned folders" ## Checks -1. The sidebar ends with `Orphaned folders 2` (no FREE cell) and reads `All projects 18`; the live `lib` worktree is not listed anywhere (search `lib` finds nothing). +1. The sidebar ends with `Orphaned folders 2` (no FREE cell) and reads `All projects 24`; the live `lib` worktree is not listed anywhere (search `lib` finds nothing). 2. Focused, the entry's card reads `Orphaned folders`, `2 folders no repo knows`, `up to 2.9 MB`, `Codex 2`, `largest 2.9 MB · abcd/app`, and line 1 reads `wt-dash › Orphaned folders` with `2 orphaned folders · up to 2.9 MB`. 3. Its list shows `○ ORPHANED 2 orphaned folders · 2.9 MB · no repository knows it`, then `□ abcd/app repository gone Its repository at ~/old/app … ? 2.9 MB` and `□ ef01 no worktree inside Codex left this folder be… ? 0 KB`. Tabs read `All 2 Safe 0 Review 0 Busy 0 Broken 0 Orphaned 2`; the header escape before `○ ORPHANED` is `38;5;5` (magenta). 4. The strip for `abcd/app` reads `abcd/app ● Orphaned · repository gone`, `~/.codex/worktrees/abcd/app`, `Its repository at ~/old/app no longer exists.`, `Codex · 2.9 MB · measured …`; `i` shows `PATH`, `CREATED BY Codex` and `SIZE`, and no LAST COMMIT, CHANGES, UPSTREAM or files. diff --git a/.claude/skills/verify-wt-dash/features/projects-screen.md b/.claude/skills/verify-wt-dash/features/projects-screen.md index 74bf74a..30dcca6 100644 --- a/.claude/skills/verify-wt-dash/features/projects-screen.md +++ b/.claude/skills/verify-wt-dash/features/projects-screen.md @@ -15,12 +15,12 @@ wt-dash opens on its projects: an "All projects" entry first, then each reposito ## Checks 1. Right after `up`, line 1 reads `wt-dash › api` and `7 worktrees and 2 branches · up to 12.2 MB · scanned HH:MM r rescan`; the focused sidebar row is `▌ api 7` with `12.1 MB`, `api`'s rows show on the right without focus, and the footer reads `→ worktrees a select safe / search`. -2. The sidebar lists, in order: `All projects 16 16.1 MB`, `api 7 12.1 MB`, `web 6 4.0 MB`, `docs 3 12 KB`. The repo `tools` (no worktrees) is not listed. -3. Up to "All projects": line 1 reads `wt-dash › all projects` with `3 projects · 16 worktrees and 2 branches · up to 16.4 MB · scanned HH:MM`, with no `sizing`; line 2 tabs read `All 18 Safe 7 Review 8 Busy 2 Broken 1 Orphaned 0`. -4. The details under the sidebar for "All projects": `3 projects`, `16.1 MB safe of 16.4 MB`, `3 worktrees uncommitted`, `other 16 · no worktree 2`. +2. The sidebar lists, in order: `All projects 22 16.2 MB`, `api 7 12.1 MB`, `web 6 4.0 MB`, `worker 6 72 KB`, `docs 3 12 KB` (`worker` ties `web` and sorts after it by name). The repo `tools` (no worktrees) is not listed. +3. Up to "All projects", once GitHub has answered: line 1 reads `wt-dash › all projects` with `4 projects · 22 worktrees and 3 branches · up to 16.5 MB · scanned HH:MM`, with no `sizing` or `checking GitHub`; line 2 tabs read `All 25 Safe 12 Review 10 Busy 2 Broken 1 Orphaned 0`. +4. The details under the sidebar for "All projects": `4 projects`, `16.2 MB safe of 16.5 MB`, `3 worktrees uncommitted`, `other 22 · no worktree 3`. 5. Focusing `web`: details read `4.0 MB safe of 4.1 MB`, `1 worktree uncommitted`, `other 6`, `largest 4.0 MB · feat…ndle`. 6. Tab moves into the list: the footer starts `space select enter remove`; ← brings back `→ worktrees a select safe` in the footer. -7. From web's list, `]` shows `wt-dash › docs` with tabs `All 3 Safe 1 Review 1 Busy 1 Broken 0 Orphaned 0`; `[` returns to `wt-dash › web`. +7. From web's list, `]` shows `wt-dash › worker` with tabs `All 7 Safe 5 Review 2 Busy 0 Broken 0 Orphaned 0`, and `]` again `wt-dash › docs` with `All 3 Safe 1 Review 1 Busy 1 Broken 0 Orphaned 0`; `[` steps back to `wt-dash › worker`, then `wt-dash › web`. ## Traps diff --git a/.claude/skills/verify-wt-dash/features/pull-requests.md b/.claude/skills/verify-wt-dash/features/pull-requests.md new file mode 100644 index 0000000..77eaa1d --- /dev/null +++ b/.claude/skills/verify-wt-dash/features/pull-requests.md @@ -0,0 +1,49 @@ +# Pull requests merged on GitHub + +A row Git can't show merged (unmerged commits, behind main) in a repository on github.com is checked against GitHub through the user's `gh`, one GraphQL request per repository plus one more for a stacked pull request. A merged pull request holding the row's tip commit, or a commit with the same files, or bringing it in from a pull request merged into another branch, makes the row Safe with status `merged on GitHub` and a reason naming the pull request. Otherwise the row stays Review and its reason says what GitHub found or why it wasn't asked. Line 1 reads `checking GitHub` while a request is out. Proofs are kept in `~/.cache/wt-dash/pull-requests.json`, so a proven commit isn't asked about again. Removing a proven row deletes its branch without `D`, and the dialog names the pull request. `--offline` never asks; `--doctor` reports the GitHub line. + +## Entry points and variants + +- The `worker` project's list and "All projects", `i` on a `worker` row, the remove dialog (Enter, `x`). Wide and narrow. +- `--offline` through `up --app-args=--offline`; `--doctor` as the instance's user. +- The fake gh, set with `stack.ts gh --name --mode --delay ` on a running instance (from its next call), or `up --gh-mode --gh-delay ` before the first scan. Its log is `env` → `paths.ghCalls`, one JSON line per call. + +## Preconditions + +- A fresh instance. `worker` is the seed's GitHub repository (`https://github.com/acme/worker.git`, served from a local bare repository). Its rows, with the pull requests the fake holds (`env --full` → `seed`, each `worker` row's `github`): + + | Row | Builder | Once GitHub answers | + | ------------------- | --------------------- | ----------------------------------------------------------------------------------- | + | feature/squashed | prMergedWorktree | Safe, `PR #1 merged with this exact commit.` | + | feature/revised | prMergedEarlierCommit | Safe, `PR #2 merged with this exact commit.` | + | feature/rebased | prTreeMatch | Safe, `PR #3 merged with the same files.` | + | feature/stacked | prStacked (#4, #5) | Safe, `PR #5 merged and brought in this commit from a stacked pull request.` | + | feature/after-merge | prMissingCommit | Review, `… PR #6 merged without this commit.` | + | leftover/squashed | prMergedBranch, 3d | Safe (branch) | + | feature/no-pr | pushed, no PR | Review, `1 commit isn't in main. No merged pull request on GitHub has this commit.` | + + `` is the seed day, such as `Nov 6`. Before GitHub answers, or when it can't be asked, every row is Review with `seed` → `github.gitOnly`'s reason (`1 commit isn't in main, and merging would conflict.` and the like). + +- The first scan after `up` asks GitHub. To watch it, start a fresh instance with `up --gh-delay 8000`: each call then waits 8 s (two calls, so about 16 s). Keep the delay under 15 s, gh's timeout, or rows read `Not checked against GitHub: GitHub didn't answer.` + +## Checks + +1. Fresh instance, `up --gh-delay 8000`, wide: `up`'s header already reads `… · checking GitHub · scanned HH:MM`. In `worker` (projects focused, Down twice) line 1 reads `wt-dash › worker 6 worktrees and 1 branch · up to 136 KB · checking GitHub · scanned HH:MM`, tabs `All 7 Safe 0 Review 7`, every row `unmerged commits`, the sidebar `worker 6 ·`. When `checking GitHub` goes, the tabs read `All 7 Safe 5 Review 2`, `✓ SAFE 4 worktrees and 1 branch · 72 KB · can go` lists `feature/stacked`, `feature/rebased`, `feature/revised`, `feature/squashed` and `leftover/squashed` with `merged on GitHub PR # merged …`, and the sidebar reads `worker 6 72 KB`. `paths.ghCalls` holds 2 lines. +2. Same in narrow (`--variant narrow`, Enter on `worker`): the rows read `unmerged commits` and then `merged on GitHub` as in check 1, but line 1 never shows `checking GitHub` (see Traps). +3. `i` on each `worker` row shows the reason in full on the line under `● · `, matching the table above: `PR #1 merged with this exact commit.`, `PR #3 merged with the same files.`, `PR #5 merged and brought in this commit from a stacked pull request.`, `2 commits aren't in main, and merging would conflict. PR #6 merged without this commit.` (wrapped), `1 commit isn't in main. No merged pull request on GitHub has this commit.`. Wide and narrow. +4. A rescan asks only about the rows not proven: after `r`, the last line of `paths.ghCalls` carries `oid0`/`oid1` and `head0=feature/after-merge`, `head1=feature/no-pr`, and the proven rows stay Safe while `checking GitHub` shows. +5. A Review row's dialog keeps its branch: `x` on `feature/after-merge` reads `Keeps 1 unmerged branch D delete too`. +6. `x` on `feature/squashed` (wide): `Remove 1 worktree · up to 12 KB?`, `• feature/squashed worker 12 KB`, `Deletes branch feature/squashed: merged on GitHub as PR #1` in place of `Merged branches are deleted.`, and no `Keeps 1 unmerged branch`. `y` shows `✓ Removed 1 worktree · freed …`; `state` has no `feature/squashed` in `repos.worker.worktrees` or `branches`, its folder is gone from `paths.worktrees`, and the last `removalsLog` entry has `"branch":"feature/squashed","flags":["-D","--reap"],"exitCode":0,"branchOutcome":"deleted","branchProof":{"pr":1}`. +7. Narrow, Space on `leftover/squashed` and `feature/revised`, Enter: `Remove 1 worktree and 1 branch · up to 16 KB?` with `Deletes 2 branches merged on GitHub: feature/revised (PR #2) and` / `leftover/squashed (PR #7)`. Enter removes both: `✓ Removed 1 worktree and 1 branch`; the `removalsLog` entries are `feature/revised` with `flags: ["-D","--reap"]`, `branchProof: {"pr":2}` and `leftover/squashed` with `flags: ["-D"]`, `branchProof: {"pr":7}`, both `branchOutcome: "deleted"`. +8. Offline: a fresh instance with `up --app-args=--offline` shows all 7 `worker` rows Review (`Safe 0 Review 7`), `i` reads ` Not checked against GitHub: offline.` (`1 commit isn't in main. Not checked against GitHub: offline.` on `feature/no-pr`), line 1 never shows `checking GitHub`, and `paths.ghCalls` stays empty (`gh` → `calls: 0`). Wide and narrow. +9. Offline after an online run: `down`, `up --app-args=` (online; proofs cached), `down`, `up --app-args=--offline`: the five proven rows are Safe again from the cache, `feature/after-merge` and `feature/no-pr` read `Not checked against GitHub: offline.`, and no call is added. +10. Signed out: a fresh instance with `up --gh-mode signed-out`: all 7 rows Review, `i` reads `… Not checked against GitHub: gh isn't signed in.` (wide and narrow), one call logged. On a running instance, `gh --mode signed-out` then `r` gives the same note on `feature/after-merge` and `feature/no-pr` while the cached proofs stay Safe. +11. `--doctor ` as the instance's user prints `GitHub: checks merged pull requests with gh at /gh/bin/gh` between the Worktrunk line and `Scan folders:`, and `Repositories found: 5`; with `--offline`, `GitHub: off (--offline)`; with the fake's folder left off PATH, `GitHub: gh not found; rows Git can't prove merged stay Review`. Each exits 0, and none adds a line to `paths.ghCalls`. + +## Traps + +- Under 100 columns or so, line 1 drops `checking GitHub` for width (as it drops `sizing`), in a list and on the projects table, and the rows don't say they are being checked: in narrow, only the rows turning Safe show that the check ran. Check `checking GitHub` wide. +- Proofs are cached in `paths.pullRequests`. To watch rows turn Safe again, start from a fresh seed (`down --purge`, `up --gh-delay …`); a rescan or restart shows them Safe at once. +- `up` returns as soon as line 1 reads `scanned`, which is before GitHub answers when the fake is delayed. Wait for `checking GitHub` to go before comparing `worker` against `seed`. +- With focus not yet moved in a list, the focused row is the first one, so it changes when the rows re-sort as GitHub answers; once you have moved, focus follows the row. +- The merge day is the local day the seed ran; `seed` holds it as worded then. An instance kept past midnight still matches, since the pull requests' `mergedAt` doesn't move. diff --git a/.claude/skills/verify-wt-dash/features/remembered-repos.md b/.claude/skills/verify-wt-dash/features/remembered-repos.md index c48e37d..39dfaa2 100644 --- a/.claude/skills/verify-wt-dash/features/remembered-repos.md +++ b/.claude/skills/verify-wt-dash/features/remembered-repos.md @@ -16,11 +16,11 @@ Every repository a run finds, from any source (the default scan folders, the age ## Checks -1. After `up`, `$XDG_STATE_HOME/wt-dash/repos.json` is `{"repos": [...]}` listing the scan root's `api`, `docs`, `tools` and `web`, sorted, as real paths. The app shows only the scan root's projects, as before. -2. A run without folders: wide, the sidebar lists `All projects 16`, `▌ api 7`, `web 6`, `docs 3`; narrow, the table lists the same rows and `1 project with no worktrees`. -3. `--doctor` without folders prints `Scan folders: none of ~/projects, ~/code, ~/dev, ~/src, ~/work exists`, `Agent worktree folders: none of the known ones exists`, then `Saved repositories:` / ` /.local/state/wt-dash/repos.json 4 repositories` / `Repositories found: 4`, and exits 0. `--doctor ` prints no `Saved repositories` section and `Repositories found: 4` from the folder alone. -4. `bun src/index.ts $HOME/elsewhere` opens on `lib` alone (`wt-dash › lib`, `□ feature/lib`); the file now holds five repos. A run without folders then lists `lib 1` under `docs 3`, with `All projects 17`. -5. Move `$HOME/elsewhere/lib` away and delete the `.git` folder of the scan root's `tools`, then press `r` in a run without folders: `lib` is gone, `All projects 16`, and the file holds only `api`, `docs` and `web`. +1. After `up`, `$XDG_STATE_HOME/wt-dash/repos.json` is `{"repos": [...]}` listing the scan root's `api`, `docs`, `tools`, `web` and `worker`, sorted, as real paths. The app shows only the scan root's projects, as before. +2. A run without folders: wide, the sidebar lists `All projects 22`, `▌ api 7`, `web 6`, `worker 6`, `docs 3`; narrow, the table lists the same rows and `1 project with no worktrees`. +3. `--doctor` without folders prints `Scan folders: none of ~/projects, ~/code, ~/dev, ~/src, ~/work exists`, `Agent worktree folders: none of the known ones exists`, then `Saved repositories:` / ` /.local/state/wt-dash/repos.json 5 repositories` / `Repositories found: 5`, and exits 0. `--doctor ` prints no `Saved repositories` section and `Repositories found: 5` from the folder alone. +4. `bun src/index.ts $HOME/elsewhere` opens on `lib` alone (`wt-dash › lib`, `□ feature/lib`); the file now holds six repos. A run without folders then lists `lib 1` under `docs 3`, with `All projects 23`. +5. Move `$HOME/elsewhere/lib` away and delete the `.git` folder of the scan root's `tools`, then press `r` in a run without folders: `lib` is gone, `All projects 22`, and the file holds only `api`, `docs`, `web` and `worker`. 6. Write `{oops` to the file and start a run with the folder `/web`: it opens `wt-dash › web` with no error, and the file holds only `web`, as valid JSON. `chmod 000` the file and start the same run: the same result, with the file readable again. No `repos.json.tmp-*` file is left in its folder. 7. A run without folders in `home3`: the projects read `No worktrees found, and no folder to scan exists.`, `Scan other folders with: wt-dash `, `wt-dash remembers the repositories it finds, and lists them in every run without folders.` (wrapped after `every run` in narrow) and `To forget them, delete ~/.local/state/wt-dash/repos.json`. `home3` has no `.local/state/wt-dash` folder afterwards: a run that finds nothing creates no file. diff --git a/.claude/skills/verify-wt-dash/features/remove-dialog.md b/.claude/skills/verify-wt-dash/features/remove-dialog.md index 3c2e8a8..ec235e9 100644 --- a/.claude/skills/verify-wt-dash/features/remove-dialog.md +++ b/.claude/skills/verify-wt-dash/features/remove-dialog.md @@ -29,6 +29,8 @@ Enter or `x` opens one confirmation dialog listing each row and its size, the to 13. Cancellation and retry while checks are still running (#63): slow the first preview's command, open with Enter or `x`, and press Esc while `Checking …` is visible. The status reads `Cancelled`, no removal or prune happens, and any selection stays. Retry, let the newer check finish and open its confirmation, then let the first check finish. The newer dialog stays open and `y` succeeds, without `Removal preview is stale` or `Prune preview is stale`. Check removal from the list with Enter and `x`, and with `x` on the projects selection; check prune with Enter on a Broken row. Check wide and narrow. For removal, verify the worktree and branch are gone and the log records success as in check 7. For prune, verify only the missing record is gone, its branch stays, and no removal is logged (see [blocked-rows.md](blocked-rows.md) check 5). 14. Large mixed selections: select a merged worktree and several unmerged branches without worktrees. With `D` off, confirmation removes only the worktree, retains every unmerged branch and records only the worktree's removal. On a fresh seed with `D` enabled, those branches are deleted too. Check list Enter, list `x` and projects-selection `x` at both sizes. Reference lookups before execution exclude entries whose confirmation is missing or blocked, and each lookup group runs at most eight Git commands at once; the final per-row ref/agent/file checks still run. Use an isolated command recorder for the process counts, and Git state plus the removal log for outcomes. Screenshots prove the unchanged confirmation/outcome, while benchmarks measure the performance change. +15. A row proven merged on GitHub deletes its branch without `D`, and the dialog names the pull request: see [pull-requests.md](pull-requests.md) checks 6 and 7. + ## Traps - A local removal finishes in under a second; the `Removing …` line is gone by the next capture unless you poll for it. diff --git a/.claude/skills/verify-wt-dash/features/rescan.md b/.claude/skills/verify-wt-dash/features/rescan.md index 1abddfc..c0390e5 100644 --- a/.claude/skills/verify-wt-dash/features/rescan.md +++ b/.claude/skills/verify-wt-dash/features/rescan.md @@ -14,8 +14,8 @@ ## Checks 1. Before `r`, `docs` reads `docs 3` and no row named `feature/external` exists. -2. Right after `r`, line 1 shows a spinner, initially `scanning 0/0 repos` until discovery finishes, then `scanning 0/4 repos` (the 4 seeded repos, `tools` included). -3. When line 1 reads `scanned HH:MM` again, the sidebar reads `docs 4` and `All projects 17`, and in `docs` the row `feature/external` is in REVIEW with `no new commits Created just now, so it may s…`. +2. Right after `r`, line 1 shows a spinner, initially `scanning 0/0 repos` until discovery finishes, then `scanning 0/5 repos` (the 5 seeded repos, `tools` included). +3. When line 1 reads `scanned HH:MM` again, the sidebar reads `docs 4` and `All projects 23`, and in `docs` the row `feature/external` is in REVIEW with `no new commits Created just now, so it may s…`. 4. Once sizes settle, another `r` keeps the saved sizes. Paths still being measured remain marked as sizing until their own pending measurements finish; failed measurements stop being marked even when their size is unknown. Fresh-cache checks can share one snapshot update across a short display frame. 5. On `api › feature/assets`, add a 2 MiB file at the worktree root outside the app, then `r`. Its displayed size grows from `12.0 MB` to `14.0 MB` once sizing finishes. A root-level untracked file also moves this row to REVIEW; find and focus it again before the next check. 6. Add a 2 MiB file under the existing `node_modules/pkg/` folder. `r` keeps the cached size while the worktree root and `node_modules` timestamps are unchanged and the measurement is under 24 hours old. `R` on the focused worktree always measures again: the toast reads `Measuring feature/assets…`, then the row reads `16.0 MB`. Repeat in the other layout, adding another 2 MiB: `R` then shows `18.0 MB`. diff --git a/.claude/skills/verify-wt-dash/features/selection.md b/.claude/skills/verify-wt-dash/features/selection.md index 6af2086..23b95ba 100644 --- a/.claude/skills/verify-wt-dash/features/selection.md +++ b/.claude/skills/verify-wt-dash/features/selection.md @@ -16,9 +16,9 @@ Space selects or unselects the focused row. `a` selects every Safe row in view ( 1. Projects focused on `api` (the start of either variant): `a` shows `✓ Selected 3 Safe worktrees and 1 branch in api · up to 12.1 MB` and the footer `■ 4 selected · up to 12.1 MB x remove esc clear`. The wide sidebar row reads `▌ api 7 ■4`. Esc clears it: the footer returns to `→ worktrees a select safe / search` (wide) or `enter open a select safe / search` (narrow). 2. List focused in `api`: `a` shows `✓ Selected 3 Safe worktrees and 1 branch · up to 12.1 MB` and the footer `■ 4 selected · up to 12.1 MB enter remove esc clear`. The four Safe rows show `■`; `feature/new-endpoint` and `agent/refactor` stay `□`. 3. List focused, continuing: Space on `feature/dirty-form` marks it `■` and the footer reads `■ 5 selected · up to 12.1 MB`. -4. Moving to `web` (`]`, list focused), then back to the projects (←) and up to "All projects", keeps the marks: the sidebar reads `All p…jects 16 ■5` and `api 7 ■5`, and the footer `■ 5 selected · up to 12.1 MB x remove esc clear`. -5. Projects focused on "All projects", continuing: `a` selects every Safe row, including those already selected: `✓ Selected 6 Safe worktrees and 1 branch in every project · up to 16.1 MB`, footer `■ 8 selected · up to 16.1 MB x remove esc clear`. -6. Same focus, `a` again: `Cleared 6 Safe worktrees and 1 branch in every project`, and `feature/dirty-form` stays selected: footer `■ 1 selected · up to 44 KB`. +4. Moving to `web` (`]`, list focused), then back to the projects (←) and up to "All projects", keeps the marks: the sidebar reads `All p…jects 22 ■5` and `api 7 ■5`, and the footer `■ 5 selected · up to 12.1 MB x remove esc clear`. +5. Projects focused on "All projects", continuing, once GitHub has answered: `a` selects every Safe row, including those already selected and the `worker` rows proven merged on GitHub: `✓ Selected 10 Safe worktrees and 2 branches in every project · up to 16.2 MB`, footer `■ 13 selected · up to 16.2 MB x remove esc clear`. +6. Same focus, `a` again: `Cleared 10 Safe worktrees and 2 branches in every project`, and `feature/dirty-form` stays selected: footer `■ 1 selected · up to 44 KB`. 7. List focused with a selection and no search: Esc clears it, and the footer returns to `space select enter remove a all safe`. 8. A selection survives `resize-window` both ways: `■ 1 selected` before, narrow and wide again. diff --git a/.claude/skills/verify-wt-dash/features/worktree-list-and-verdicts.md b/.claude/skills/verify-wt-dash/features/worktree-list-and-verdicts.md index 169e800..418a1e2 100644 --- a/.claude/skills/verify-wt-dash/features/worktree-list-and-verdicts.md +++ b/.claude/skills/verify-wt-dash/features/worktree-list-and-verdicts.md @@ -13,13 +13,14 @@ A project's rows are grouped into Safe, Review, Busy and Broken sections. Each r ## Checks 1. In `api`, section headers read `✓ SAFE 3 worktrees and 1 branch · 12.1 MB · can go` and `? REVIEW 4 worktrees and 1 branch · 148 KB · needs a look`. -2. Every seeded row appears once, in the section of its seeded verdict, with its seeded status. Compare each row on "All projects" (18 rows) against `seed`. +2. Every seeded row appears once, in the section of its seeded verdict, with its seeded status. Compare each row on "All projects" (25 rows) against `seed`, once line 1 no longer reads `checking GitHub`: until then the `worker` rows read as `seed` → `github.gitOnly` (see [pull-requests.md](pull-requests.md)). 3. The reason column is the seeded reason without its final period, cut with `…` when narrow: `feature/login` shows `Its commits are already in main`; a locked row shows its lock reason only (`agent session`, `no reason given`). 4. Agent marks: `api › agent/refactor` is Review with `An agent was working here ` (a mark under a day old); `api › agent/old-session` is Safe (its mark is 3 days old). 5. Fresh worktree: `api › feature/new-endpoint` is Review, `no new commits`, `Created , so it may s…`. 6. `web` shows `‖ BUSY 1 worktree · 28 KB · finish the Git operation first` and `✗ BROKEN 1 worktree · 0 KB · folder missing; prune the record`, the Broken row with age `?` and size `…`. 7. Blocked rows (`feature/locked`, `docs/locked-bare`, `feature/rebase`, `docs/conflict`, `feature/gone`) show `–` instead of `□`. 8. Section colors, read with `capture-pane -p -e`: the header escape before `✓ SAFE` is `38;5;2` (green), `? REVIEW` `38;5;3`, `‖ BUSY` `38;5;4`, `✗ BROKEN` `38;5;1`. How they look is checked by eye on a PR image. +9. Once GitHub has answered, `worker` shows `✓ SAFE 4 worktrees and 1 branch · 72 KB · can go`, every row in it with status `merged on GitHub`, and `? REVIEW 2 worktrees · 64 KB · needs a look`. The GitHub check itself is in [pull-requests.md](pull-requests.md). ## Traps diff --git a/.claude/skills/verify-wt-dash/stack.ts b/.claude/skills/verify-wt-dash/stack.ts index 18172d5..6cdef3c 100644 --- a/.claude/skills/verify-wt-dash/stack.ts +++ b/.claude/skills/verify-wt-dash/stack.ts @@ -6,7 +6,7 @@ */ import { createHash } from "node:crypto"; import { existsSync, readFileSync } from "node:fs"; -import { appendFile, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { appendFile, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { dirname, join, resolve, sep } from "node:path"; import { createSandbox, @@ -15,6 +15,7 @@ import { type Repo, type Sandbox, } from "../../../tests/support/fixture"; +import { GH_LOG_ENV, GH_STATE_ENV, type GhMode, type GhState } from "../../../tests/support/gh"; const repoRoot = resolve(import.meta.dir, "../../.."); const verifyRoot = join(repoRoot, ".verify"); @@ -45,6 +46,12 @@ export interface SeedRow { blocked: boolean; note?: string; minSizeKiB?: number; + /** + * For a row only GitHub can settle: the pull requests the fake GitHub holds for it, and the row as Git alone + * judges it, shown before GitHub answers and with a "Not checked against GitHub" note when it can't be asked. + * `verdict`, `status` and `reason` above are the row once the fake GitHub has answered. + */ + github?: { pullRequests: number[]; gitOnly: { verdict: string; status: string; reason: string } }; } /** @@ -294,9 +301,47 @@ async function seed( }; } +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** How the GitHub check answers for each `pr…` builder's row, and the `worker` row no pull request holds. */ +type GitHubAnswer = "commit" | "tree" | "stacked" | "without" | "none"; + +/** The row once the fake GitHub has answered, worded as the app words it (the merge day in local time). */ +function answered( + built: Built, + answer: GitHubAnswer, +): { expected: Built["expected"]; github: NonNullable } { + const { verdict, status, reason } = built.expected; + const prs = built.github?.pullRequests ?? []; + const today = new Date(); + // The fixture merges every pull request at seed time; the last one is the one merged into main. + const pr = `PR #${prs.at(-1)} merged ${MONTHS[today.getMonth()]} ${today.getDate()}`; + const endings = { + commit: " with this exact commit.", + tree: " with the same files.", + stacked: " and brought in this commit from a stacked pull request.", + without: "", + none: "", + }; + const expected = + answer === "without" || answer === "none" + ? { + ...built.expected, + reason: `${reason} ${answer === "none" ? "No merged pull request on GitHub has this commit." : `${pr} without this commit.`}`, + } + : { + ...built.expected, + verdict: built.github!.verdict, + status: "merged on GitHub", + reason: pr + endings[answer], + }; + return { expected, github: { pullRequests: prs, gitOnly: { verdict, status, reason } } }; +} + async function defaultSeed(sandbox: Sandbox): Promise { const inRepo = async (name: string, build: (repo: Repo) => Promise) => build(await sandbox.repo(name)); + const answers = new Map(); const sequence = async (repo: Repo, steps: Array<(repo: Repo) => Promise>) => { const out: Built[] = []; for (const step of steps) out.push(await step(repo)); @@ -334,9 +379,39 @@ async function defaultSeed(sandbox: Sandbox): Promise { ]), ), inRepo("tools", async () => []), + // Squash-merged on GitHub, so only the fake GitHub can settle these rows. Named to sort after `web`, its tie. + (async () => { + const repo = await sandbox.repo("worker", { github: true }); + const steps: Array<[GitHubAnswer, () => Promise]> = [ + ["commit", () => repo.prMergedWorktree("feature/squashed")], + ["commit", () => repo.prMergedEarlierCommit("feature/revised")], + ["tree", () => repo.prTreeMatch("feature/rebased")], + ["stacked", () => repo.prStacked("feature/stacked")], + ["without", () => repo.prMissingCommit("feature/after-merge")], + ["commit", () => repo.prMergedBranch("leftover/squashed")], + [ + "none", + // Pushed, and in no pull request at all. + async () => { + const built = await repo.unmergedWorktree("feature/no-pr"); + await sandbox.git(built.path!, "push", "-q", "-u", "origin", "feature/no-pr"); + return built; + }, + ], + ]; + const out: Built[] = []; + for (const [answer, step] of steps) { + const built = await step(); + answers.set(built, answer); + out.push(built); + } + return out; + })(), ]); return groups.flat().map((built) => { - let expected = built.expected; + const answer = answers.get(built); + const github = answer ? answered(built, answer) : null; + let expected = github?.expected ?? built.expected; // Without on-disk backdating (Linux) the real binary sees mergedWorktree's worktree as new. if ( !sandbox.backdatesOnDisk && @@ -355,10 +430,73 @@ async function defaultSeed(sandbox: Sandbox): Promise { path: built.path, ...expected, ...(built.minSizeKiB === undefined ? {} : { minSizeKiB: built.minSizeKiB }), + ...(github ? { github: github.github } : {}), }; }); } +const GH_MODES: GhMode[] = ["ok", "signed-out", "bad-credentials", "offline", "missing-repo"]; + +interface GhChange { + mode?: GhMode; + delayMs?: number; +} + +/** A mode and a delay for the fake gh, from `--mode` and `--delay`. */ +function ghChangeFrom(flags: Record, prefix: string): GhChange { + const change: GhChange = {}; + const mode = flags[`${prefix}mode`]; + if (mode !== undefined) { + if (typeof mode !== "string" || !GH_MODES.includes(mode as GhMode)) + throw new Failure(`Unknown gh mode: ${String(mode)}`, `Use one of ${GH_MODES.join(", ")}.`); + change.mode = mode as GhMode; + } + const delay = flags[`${prefix}delay`]; + if (delay !== undefined) { + const ms = typeof delay === "string" ? Number(delay) : Number.NaN; + if (!Number.isInteger(ms) || ms < 0) + throw new Failure( + `--${prefix}delay needs milliseconds, got ${String(delay)}.`, + "Example: 3000; 0 answers at once.", + ); + change.delayMs = ms; + } + return change; +} + +/** + * Applies `change` to the instance's fake gh, which reads its state file on every call, and returns how it + * answers now and how many calls it has logged. + */ +async function fakeGh(instance: Instance, change: GhChange = {}) { + const statePath = instance.env[GH_STATE_ENV]; + const callsPath = instance.env[GH_LOG_ENV]; + if (!statePath || !callsPath || !existsSync(statePath)) + throw new Failure( + `Instance ${instance.name} has no fake gh.`, + `Recreate it: bun ${self} down --name ${instance.name} --purge, then up again.`, + ); + const state = JSON.parse(await readFile(statePath, "utf8")) as GhState; + if (change.mode !== undefined || change.delayMs !== undefined) { + if (change.mode !== undefined) state.mode = change.mode; + if (change.delayMs === 0) delete state.delayMs; + else if (change.delayMs !== undefined) state.delayMs = change.delayMs; + const temporary = `${statePath}.${process.pid}.tmp`; + await writeFile(temporary, JSON.stringify(state, null, 2)); + await rename(temporary, statePath); + } + const calls = existsSync(callsPath) + ? (await readFile(callsPath, "utf8")).split("\n").filter(Boolean).length + : 0; + return { mode: state.mode, delayMs: state.delayMs ?? 0, calls, statePath, callsPath }; +} + +async function gh(flags: Record) { + const name = nameFrom(flags); + const instance = await requireInstance(name); + return { name, ...(await fakeGh(instance, ghChangeFrom(flags, ""))) }; +} + async function startApp(instance: Instance): Promise { const p = paths(instance.name); const { cols, rows } = VARIANTS[instance.variant]; @@ -452,6 +590,7 @@ async function up(flags: Record) { typeof flags["app-args"] === "string" ? flags["app-args"].split(/\s+/).filter((word) => word !== "") : undefined; + const ghChange = ghChangeFrom(flags, "gh-"); const variant: Variant = variantFlag ?? instance?.variant ?? "wide"; let seeded = false; if (!instance) { @@ -485,6 +624,8 @@ async function up(flags: Record) { await saveInstance(instance); await log(name, { event: "seeded", ms: Date.now() - started, rows: seededWorld.rows.length }); } + // Before the app starts, so its first scan meets the fake as asked. + const fake = await fakeGh(instance, ghChange); const info = paneInfo(instance.socket); let reused = false; let resized = false; @@ -526,6 +667,7 @@ async function up(flags: Record) { resized, variant, appArgs: instance.appArgs ?? [], + gh: { mode: fake.mode, delayMs: fake.delayMs }, size, branch: instance.branch, header: ready.header, @@ -585,6 +727,9 @@ async function env(flags: Record) { worktrees: join(instance.sandbox, "worktrees"), removalsLog: join(instance.env.HOME!, ".cache", "wt-dash", "removals.log"), sizes: join(instance.env.HOME!, ".cache", "wt-dash", "sizes.json"), + pullRequests: join(instance.env.HOME!, ".cache", "wt-dash", "pull-requests.json"), + ghState: instance.env[GH_STATE_ENV], + ghCalls: instance.env[GH_LOG_ENV], appLog: p.appLog, evidence: p.evidence, }, @@ -1074,7 +1219,8 @@ async function list() { } const COMMANDS = { - up: "up --name [--variant wide|narrow] [--seed ] [--app-args=''] Seed if new, start wt-dash in tmux, wait until listed. Reuses a running instance (resizing it to the variant). --seed builds the sandbox with a module's default export (SeedModule) instead of the test fixture's seed. --app-args adds space-separated arguments after the scan root, such as --app-args='--depth 0'; join the value with = when it starts with --. A stopped instance restarts with the last ones; a running one with other arguments is refused.", + up: "up --name [--variant wide|narrow] [--seed ] [--app-args=''] [--gh-mode ] [--gh-delay ] Seed if new, start wt-dash in tmux, wait until listed. Reuses a running instance (resizing it to the variant). --seed builds the sandbox with a module's default export (SeedModule) instead of the test fixture's seed. --app-args adds space-separated arguments after the scan root, such as --app-args='--depth 0'; join the value with = when it starts with --. A stopped instance restarts with the last ones; a running one with other arguments is refused. --gh-mode and --gh-delay set the fake gh as the gh command does, before the app starts.", + gh: "gh --name [--mode ok|signed-out|bad-credentials|offline|missing-repo] [--delay ] Set how the instance's fake gh answers from its next call (--delay 0 answers at once); prints its mode, delay and how many calls it has logged.", env: "env --name [--full] The shell preamble, tmux commands and paths to drive the instance; --full adds its env and the seeded rows with their expected verdicts.", doctor: "doctor --name Read-only health check.", state: @@ -1101,6 +1247,7 @@ async function main(): Promise { doctor, state, image, + gh, down, list, };