From 0c203ba4d4c969f9e966762fefe236d061c619ba Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 10:19:23 -0800 Subject: [PATCH 1/8] chore(quest): claim quest/m0/github-quota/forge-reads.md Quest-Claim: a508c71577285b0e From cc20c19304612f077ca494cddc0912fe59d4a893 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 10:31:40 -0800 Subject: [PATCH 2/8] wip: forge reads --- src/cli/breakage.ts | 2 +- src/cli/claims.ts | 46 ++- src/cli/forge.ts | 170 +++++++++ src/cli/github.ts | 12 +- src/cli/hold.ts | 14 +- src/cli/land-apply.ts | 3 +- src/cli/land-bump.ts | 13 +- src/cli/land-daemon.ts | 3 +- src/cli/land-head.ts | 3 +- src/cli/land-queue.ts | 12 +- src/cli/land-watch.ts | 13 +- src/cli/land.ts | 16 +- src/cli/main.ts | 51 ++- src/cli/review-eval.ts | 3 +- src/cli/send.ts | 2 +- src/cli/start.ts | 3 +- src/cli/status.ts | 2 +- src/cli/usage.ts | 3 +- src/cli/wait.ts | 736 +++--------------------------------- src/core/forge.ts | 472 +++++++++++++++++++++++ src/core/index.ts | 33 ++ src/github/claims.ts | 66 +--- src/github/client.ts | 12 +- src/github/forge.ts | 56 +++ src/github/hold.ts | 16 +- src/github/index.ts | 44 +-- src/github/online-review.ts | 3 +- src/github/signals.ts | 14 +- src/github/status.ts | 112 +----- src/github/wait.ts | 718 +++++++++++++++++++++++++++++++++++ test/online-review.test.ts | 3 +- test/start.test.ts | 8 +- test/usage.test.ts | 1 + test/wait.test.ts | 196 +++++----- 34 files changed, 1739 insertions(+), 1122 deletions(-) create mode 100644 src/cli/forge.ts create mode 100644 src/core/forge.ts create mode 100644 src/github/forge.ts create mode 100644 src/github/wait.ts diff --git a/src/cli/breakage.ts b/src/cli/breakage.ts index 42c9002e..ec5600b2 100644 --- a/src/cli/breakage.ts +++ b/src/cli/breakage.ts @@ -1,7 +1,7 @@ // What a PR body says about breakage: the culprits its `## Caused by` names, and, for a culprit, how it was made and // checked, as its own body records it. import { type Culprit, FINDERS, type Finder, SIZES, type Seat, type Size, recordedRisk } from "../core"; -import type { Repository } from "../github/client"; +import type { Repository } from "../core"; import { recorded } from "./models-record"; import { parseReview } from "./review-record"; import type { Pull } from "./usage"; diff --git a/src/cli/claims.ts b/src/cli/claims.ts index 412a5f02..41484e99 100644 --- a/src/cli/claims.ts +++ b/src/cli/claims.ts @@ -3,20 +3,16 @@ // and `quest start` records a claim the same way, judging readiness by the upstream tree. import { git } from "./git"; import { type Remote, readRemote, remoteRepository, requireRemote } from "./github"; -import { type GitHubDependencies, type Repository, GitHub, object, repositoryPath, string } from "../github/client"; -import { - type Claim, - type Holdings, - type OpenPull, - held as githubHeld, - openPullRequests, - questBranches, -} from "../github/claims"; +import { type GitHubDependencies, GitHub, object, repositoryPath, string } from "../github/client"; +import type { Claim, Forge, Holdings, OpenPull, Repository } from "../core"; +import { questBranches } from "../github/claims"; import { type Snapshot, snapshot } from "./tree"; export interface ClaimDependencies { /** Called only when the remote is on GitHub, so other forges need no token. */ github(): GitHubDependencies; + /** The forge answering reads of a repository on GitHub, such as its claims and open PRs. */ + forge(repository: Repository): Promise; warn(message: string): void; } @@ -39,6 +35,8 @@ export interface Upstream { defaultBranch: string; /** Where this checkout's tree sits in the repository: empty at the top level, else a path ending in `/`. */ prefix: string; + /** The forge answering reads of `repository`, chosen on first use. */ + forge(): Promise; } | null; } @@ -73,13 +71,21 @@ export async function upstream(root: string, remote: Remote, deps: ClaimDependen // The README where this checkout's tree sits, which may be below the top level. const prefix = git(root, ["rev-parse", "--show-prefix"]); const up = await base(client, self, prefix); + let forge: Promise | undefined; return { // Reach an ancestor the way the remote is reached, so the same credentials work. git: up === self ? remote.name : /^https:/.test(source.url) ? up.https : up.ssh, get push() { return remote.used().push; }, - github: { client, repository: up.repository, head, defaultBranch: up.defaultBranch, prefix }, + github: { + client, + repository: up.repository, + head, + defaultBranch: up.defaultBranch, + prefix, + forge: () => (forge ??= deps.forge(up.repository)), + }, }; } @@ -173,7 +179,7 @@ export async function reach(root: string, name: string, deps: ClaimDependencies) } /** - * Which of `branches` someone holds, as {@link githubHeld} decides it on GitHub. `tips` are the + * Which of `branches` someone holds, as the upstream's forge decides it on GitHub. `tips` are the * upstream's `quest/*` branches, when already read; the fork's are read through git too. Off GitHub, * every branch pushed upstream holds its quest. */ @@ -191,15 +197,13 @@ export async function held( .map((branch) => ({ branch, url: null, pull: null })), landed: new Map(), }; - const { client, repository, head } = up.github; - return githubHeld( - client, - { - upstream: { repository, tips }, - ...(same(head, repository) ? {} : { fork: { repository: head, tips: remoteBranches(root, up.push) } }), - }, - branches, - ); + const { repository, head } = up.github; + const forge = await up.github.forge(); + const sources = { + upstream: { repository, tips }, + ...(same(head, repository) ? {} : { fork: { repository: head, tips: remoteBranches(root, up.push) } }), + }; + return (await forge.held(sources, branches)).value; } /** @@ -220,7 +224,7 @@ export async function openDrafts(root: string, name: string, deps: ClaimDependen deps.warn(`${name} is not on GitHub, so draft PRs were skipped`); return []; } - const pulls = await openPullRequests(up.github.client, up.github.repository); + const pulls = (await (await up.github.forge()).pulls(up.github.repository)).value; return pulls.filter((pull) => pull.draft).sort((a, b) => a.number - b.number); } catch (error) { deps.warn(`draft PRs were skipped: ${error instanceof Error ? error.message : String(error)}`); diff --git a/src/cli/forge.ts b/src/cli/forge.ts new file mode 100644 index 00000000..eb80a700 --- /dev/null +++ b/src/cli/forge.ts @@ -0,0 +1,170 @@ +// Which forge answers a repository's reads: Kixel Quest's index, for a person holding its token and a repository it +// serves, else GitHub. A Kixel Quest failure fails the command, naming the setting that reads GitHub instead. +import { + type Answer, + type ClaimSources, + type Forge, + type ForgeCall, + type ForgeCalls, + type ForgeInfo, + type Holdings, + type OpenPull, + type PullRequest, + type Repository, + type Status, + type Watch, + type WatchOptions, + forgeJson, + parseForgeAnswer, + parseForgeInfo, +} from "../core"; +import type { GitHubDependencies } from "../github/client"; +import { GitHubForge } from "../github/forge"; +import { checkedEndpoint, tokenFor, tokensPath } from "./send"; + +/** Kixel Quest's own URL. */ +export const KIXEL_QUEST = "https://kixel.quest"; +/** The variable naming another Kixel Quest, such as one running locally. */ +export const KIXEL_QUEST_URL = "QUEST_KIXEL_URL"; +/** The variable that, set to `github`, reads GitHub even where Kixel Quest serves the repository. */ +export const FORGE = "QUEST_FORGE"; + +/** What choosing a forge needs from its host. */ +export interface ForgeDependencies { + env: NodeJS.ProcessEnv; + fetch: typeof fetch; + now(): number; + /** Called only once a read goes to GitHub, so Kixel Quest's reads need no GitHub token. */ + github(): GitHubDependencies; +} + +/** The Kixel Quest `env` names, with the person's token for it; null without a token, or when reads are on GitHub. */ +export function kixelQuest(deps: ForgeDependencies): KixelQuest | null { + const forced = deps.env[FORGE]; + if (forced !== undefined && forced !== "" && forced !== "github") + throw new Error(`${FORGE} is ${forced}; set it to github to read GitHub, or leave it unset`); + if (forced === "github") return null; + const url = checkedEndpoint(deps.env[KIXEL_QUEST_URL] || KIXEL_QUEST, KIXEL_QUEST_URL).replace(/\/+$/, ""); + const token = tokenFor(url, deps.env); + return token === null ? null : new KixelQuest(url, token, deps); +} + +/** The forge whose answers `repository`'s reads use: Kixel Quest when it serves the repository to this person. */ +export async function forgeFor(repository: Repository, deps: ForgeDependencies): Promise { + const kixel = kixelQuest(deps); + return kixel !== null && (await kixel.serves(repository)) + ? new KixelQuestForge(kixel) + : new GitHubForge(deps.github()); +} + +/** Kixel Quest's read API, with a person's token. */ +export class KixelQuest { + #info: Promise | undefined; + + constructor( + readonly url: string, + private readonly token: string, + private readonly deps: ForgeDependencies, + ) {} + + /** The person the token names, and the repositories Kixel Quest serves them; read once. */ + info(): Promise { + this.#info ??= this.#send("GET", "/forge", undefined, Infinity).then(parseForgeInfo); + return this.#info; + } + + /** Whether Kixel Quest answers `repository`'s reads for this person. */ + async serves(repository: Repository): Promise { + return (await this.info()).repositories.includes(`${repository.owner}/${repository.repo}`.toLowerCase()); + } + + /** Ask for `call`, giving up at `deadline` (epoch milliseconds). */ + async call( + call: C, + request: ForgeCalls[C]["request"], + deadline = Infinity, + ): Promise> { + return parseForgeAnswer(call, await this.#send("POST", `/forge/${call}`, request, deadline)); + } + + /** The JSON answer to a request, or an error naming the setting that reads GitHub instead. */ + async #send(method: "GET" | "POST", path: string, body: unknown, deadline: number): Promise { + const failed = (why: string) => + new Error(`Kixel Quest (${this.url}) failed ${method} ${path}: ${why}; set ${FORGE}=github to read GitHub`); + const remaining = deadline - this.deps.now(); + let response: Response; + let text: string; + try { + response = await this.deps.fetch(`${this.url}${path}`, { + method, + headers: { + Authorization: `Bearer ${this.token}`, + Accept: "application/json", + "User-Agent": "quest", + ...(body === undefined ? {} : { "Content-Type": "application/json" }), + }, + ...(body === undefined ? {} : { body: forgeJson(body) }), + ...(Number.isFinite(remaining) ? { signal: AbortSignal.timeout(Math.max(0, Math.ceil(remaining))) } : {}), + }); + text = await response.text(); + } catch (error) { + throw failed(error instanceof Error ? error.message : String(error)); + } + if (response.status === 401 || response.status === 403) + throw failed(`it refused the token ${tokensPath(this.deps.env)} pairs with it (HTTP ${response.status})`); + if (!response.ok) throw failed(`HTTP ${response.status}${reason(text)}`); + try { + return JSON.parse(text); + } catch { + throw failed("its answer is not JSON"); + } + } +} + +/** The reason in an error body, `{"error": "..."}`, if it gives one. */ +function reason(text: string): string { + try { + const error = (JSON.parse(text) as { error?: unknown } | null)?.error; + return typeof error === "string" && error !== "" ? `, ${error}` : ""; + } catch { + return ""; + } +} + +/** Reads from Kixel Quest's index. */ +export class KixelQuestForge implements Forge { + readonly name = "Kixel Quest"; + + constructor(private readonly kixel: KixelQuest) {} + + async viewer(): Promise { + return (await this.kixel.info()).login; + } + + status(pull: PullRequest): Promise> { + return this.kixel.call("status", { pull }); + } + + pulls(repository: Repository): Promise> { + return this.kixel.call("pulls", { repository }); + } + + held(sources: ClaimSources, branches: string[]): Promise> { + return this.kixel.call("held", { sources, branches }); + } + + watch(pull: PullRequest, { since, deadline }: WatchOptions): Watch { + const kixel = this.kixel; + let cursor: string | undefined; + return { + get resume() { + return cursor ?? since; + }, + async poll() { + const answer = await kixel.call("watch", { pull, from: cursor ?? since ?? null }, deadline); + cursor = answer.value.cursor; + return answer; + }, + }; + } +} diff --git a/src/cli/github.ts b/src/cli/github.ts index b44de553..8aea5faf 100644 --- a/src/cli/github.ts +++ b/src/cli/github.ts @@ -1,12 +1,10 @@ // The CLI's side of the GitHub client: PR arguments, git remotes, and the token, which need a checkout or Node. import { execFileSync } from "node:child_process"; import { setTimeout as sleep } from "node:timers/promises"; -import type { GitHubDependencies, PullRequest, Repository } from "../github/client"; +import type { GitHubDependencies } from "../github/client"; +import { InputError, type PullRequest, type Repository } from "../core"; import { git } from "./git"; -/** A bad PR argument or option, reported as a usage error. */ -export class GitHubInputError extends Error {} - /** Accept a GitHub PR URL, or a number in the origin repository. */ export function pullRequest(value: string, root: string): PullRequest { if (/^[1-9]\d*$/.test(value)) { @@ -17,13 +15,13 @@ export function pullRequest(value: string, root: string): PullRequest { } catch { origin = null; } - if (!origin) throw new GitHubInputError(`${root} is not a checkout with an origin remote: ${outside}`); + if (!origin) throw new InputError(`${root} is not a checkout with an origin remote: ${outside}`); const { repository } = remoteRepository(origin); - if (!repository) throw new GitHubInputError(`origin does not name a github.com repository: ${outside}`); + if (!repository) throw new InputError(`origin does not name a github.com repository: ${outside}`); return { ...repository, number: Number(value) }; } const match = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/([1-9]\d*)\/?(?:[?#].*)?$/.exec(value); - if (!match) throw new GitHubInputError("expected a GitHub pull request URL or a PR number in origin"); + if (!match) throw new InputError("expected a GitHub pull request URL or a PR number in origin"); return { owner: match[1], repo: match[2], number: Number(match[3]) }; } diff --git a/src/cli/hold.ts b/src/cli/hold.ts index 769e6ce9..381dfbfb 100644 --- a/src/cli/hold.ts +++ b/src/cli/hold.ts @@ -4,18 +4,8 @@ // `quest merge` takes no label: the pinned auto-merge or merge-queue entry it creates is the queue signal. import { ACTIVE_LABEL, formatFinding, handedBack, latestHold, heldToken, withoutHandBack } from "../core"; import { cleanAutoMergeRefusal, immediateMerge, queueHead } from "../github/merge"; -import { - currentChecks, - GitHub, - type GitHubDependencies, - GitHubGraphQLError, - object, - type ObjectValue, - type PullRequest, - requirements, - string, - repositoryPath, -} from "../github/client"; +import { currentChecks, GitHub, type GitHubDependencies, GitHubGraphQLError, object, type ObjectValue, requirements, string, repositoryPath } from "../github/client"; +import type { PullRequest } from "../core"; import { ALLOWS, METHOD_NAMES, contexts, enqueue } from "./land"; import { LAND_CHECK } from "../github/land"; import { QUEUE_CHECK } from "./land-queue"; diff --git a/src/cli/land-apply.ts b/src/cli/land-apply.ts index 4c5bca81..823cf895 100644 --- a/src/cli/land-apply.ts +++ b/src/cli/land-apply.ts @@ -4,7 +4,8 @@ import { rmSync } from "node:fs"; import { resolve } from "node:path"; import { gunzipSync, gzipSync } from "node:zlib"; import { remoteRepository, requireRemote } from "./github"; -import { GitHub, type GitHubDependencies, type PullRequest, object, string } from "../github/client"; +import { GitHub, type GitHubDependencies, object, string } from "../github/client"; +import type { PullRequest } from "../core"; import { discoveryEnv } from "./git"; import { contains, git, gitEnvironment, tryGit } from "./land"; import { Refusal } from "./start"; diff --git a/src/cli/land-bump.ts b/src/cli/land-bump.ts index ce9d7c66..d0adbd91 100644 --- a/src/cli/land-bump.ts +++ b/src/cli/land-bump.ts @@ -4,17 +4,8 @@ import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { isAbsolute, join, relative, sep } from "node:path"; import { checksState, currentContexts, newerRun, replacedRun, type WorkflowRun } from "../github/checks"; -import { - array, - GitHub, - type GitHubDependencies, - object, - type ObjectValue, - type Repository, - requirements, - string, - workflowRuns, -} from "../github/client"; +import { array, GitHub, type GitHubDependencies, object, type ObjectValue, requirements, string, workflowRuns } from "../github/client"; +import type { Repository } from "../core"; import { land } from "./hold"; import { commandEnvironment, contexts, git, type RemoteRead } from "./land"; import { push, remoteHead } from "./land-head"; diff --git a/src/cli/land-daemon.ts b/src/cli/land-daemon.ts index 0437fd15..304e8c96 100644 --- a/src/cli/land-daemon.ts +++ b/src/cli/land-daemon.ts @@ -4,7 +4,8 @@ import { createPrivateKey, createSign } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; -import { array, GitHub, type GitHubDependencies, type Repository, object, string } from "../github/client"; +import { array, GitHub, type GitHubDependencies, object, string } from "../github/client"; +import type { Repository } from "../core"; import { git } from "./land"; /** A request to GitHub's API as the App itself, signed with its key. */ diff --git a/src/cli/land-head.ts b/src/cli/land-head.ts index b4d27fab..1ebabe76 100644 --- a/src/cli/land-head.ts +++ b/src/cli/land-head.ts @@ -3,7 +3,8 @@ import { existsSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFil import { join } from "node:path"; import { carriedBy } from "./land-fixer"; import { gitAuthentication } from "./land-git"; -import { GitHub, type GitHubDependencies, type Repository, object, string } from "../github/client"; +import { GitHub, type GitHubDependencies, object, string } from "../github/client"; +import type { Repository } from "../core"; import { baseRemote, type LandMethod, diff --git a/src/cli/land-queue.ts b/src/cli/land-queue.ts index 9e6d0c9f..006bbd1a 100644 --- a/src/cli/land-queue.ts +++ b/src/cli/land-queue.ts @@ -3,16 +3,8 @@ // exactly the tested tree with the App. import { existsSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; -import { - GitHub, - type GitHubDependencies, - object, - type ObjectValue, - type RequiredCheck, - type Repository, - requirements, - string, -} from "../github/client"; +import { GitHub, type GitHubDependencies, object, type ObjectValue, type RequiredCheck, requirements, string } from "../github/client"; +import type { Repository } from "../core"; import { baseRemote, eject, diff --git a/src/cli/land-watch.ts b/src/cli/land-watch.ts index 28788fbc..f4683391 100644 --- a/src/cli/land-watch.ts +++ b/src/cli/land-watch.ts @@ -3,17 +3,8 @@ import { accessSync, constants, existsSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; -import { - array, - GitHub, - type GitHubDependencies, - GitHubGraphQLError, - link, - object, - type ObjectValue, - type Repository, - string, -} from "../github/client"; +import { array, GitHub, type GitHubDependencies, GitHubGraphQLError, link, object, type ObjectValue, string } from "../github/client"; +import type { Repository } from "../core"; import { lacksApproval } from "../github/merge"; import type { Entry, LandMethod, Plan } from "./land"; import type { Reason } from "../github/land"; diff --git a/src/cli/land.ts b/src/cli/land.ts index 3bb44de8..b55f967d 100644 --- a/src/cli/land.ts +++ b/src/cli/land.ts @@ -4,20 +4,8 @@ import { resolve } from "node:path"; import { isQuest, remove } from "../core"; import { LAND_CHECK, type Reason, pin, pinned } from "../github/land"; import { programEnvironment } from "./program"; -import { - GitHub, - GitHubDeadline, - type GitHubDependencies, - object, - type ObjectValue, - type Repository, - type RequiredCheck, - array, - currentChecks, - requirements, - string, - repositoryPath, -} from "../github/client"; +import { GitHub, GitHubDeadline, type GitHubDependencies, object, type ObjectValue, type RequiredCheck, array, currentChecks, requirements, string, repositoryPath } from "../github/client"; +import type { Repository } from "../core"; import type { WorkflowRun } from "../github/checks"; import { appOf } from "../github/checks"; import { classifyCheck, reported, type Needs } from "../github/status"; diff --git a/src/cli/main.ts b/src/cli/main.ts index 8e41b041..6992095a 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -28,6 +28,7 @@ import { unblocked, onMaintainer, waiting, + InputError, } from "../core"; import { AgentInputError, @@ -40,11 +41,13 @@ import { stopAgent, stopAll, } from "./agent"; -import { held, openDrafts, reach, target, upstream, upstreamRefs } from "./claims"; +import { type ClaimDependencies, held, openDrafts, reach, target, upstream, upstreamRefs } from "./claims"; +import { type ForgeDependencies, forgeFor } from "./forge"; import { PENDING_MS } from "./admission"; import { gate } from "./gate"; -import { gitHubDependencies, GitHubInputError, pullRequest, readRemote, remoteRepository } from "./github"; -import { mergedHolds } from "../github/client"; +import { gitHubDependencies, pullRequest, readRemote, remoteRepository } from "./github"; +import { type GitHubDependencies, mergedHolds } from "../github/client"; +import { setTimeout as sleep } from "node:timers/promises"; import { type Hold, finish, land, release, take } from "./hold"; import { LAND_CHECK } from "../github/land"; import { apply, pushCommand } from "./land-apply"; @@ -106,7 +109,6 @@ import { CONTEXT, GUIDE, GUIDE_SECTIONS, SKILLS, guideSections, sectionHeading, import { type Terminal, Theme } from "./theme"; import { type Snapshot, checkout, collect, load, snapshot, under } from "./tree"; import { statusLines } from "./status"; -import { pullRequestStatus } from "../github/status"; import { TOKEN_MAX_MISSING, daysBefore, runTokenMax, usage, usageDependencies, usageLines } from "./usage"; import { waitForActivity, WaitTimeout } from "./wait"; import { version } from "./version"; @@ -135,6 +137,17 @@ export function main(argv: string[], out: Output): number | Promise { const warn = (line: string): void => { out.stderr(`quest: ${line}\n`); }; + const forgeDependencies = (quota?: GitHubDependencies["quota"]): ForgeDependencies => ({ + env: process.env, + fetch: globalThis.fetch, + now: Date.now, + github: () => gitHubDependencies(warn, quota), + }); + const claimDependencies = (): ClaimDependencies => ({ + github: () => gitHubDependencies(warn), + forge: (repository) => forgeFor(repository, forgeDependencies()), + warn, + }); const theme = out.terminal ? new Theme(out.terminal) : null; const program = new Command("quest") @@ -396,7 +409,7 @@ export function main(argv: string[], out: Output): number | Promise { } // Readiness comes from the upstream default branch, so a stale checkout cannot offer // a deleted quest or one whose prerequisite has since finished. - const deps = { github: () => gitHubDependencies(warn), warn }; + const deps = claimDependencies(); settle( (async () => { const up = await reach(root(), options.remote, deps); @@ -455,7 +468,7 @@ export function main(argv: string[], out: Output): number | Promise { .action((options: { json?: boolean; maintainer?: boolean; limit?: number; remote: string }) => { const tree = checkout(root(), warn); if (!valid(tree)) return; - settle(openDrafts(root(), options.remote, { github: () => gitHubDependencies(warn), warn }), (drafts) => { + settle(openDrafts(root(), options.remote, claimDependencies()), (drafts) => { const found = waiting(tree.docs, today(), drafts) .map((quest) => options.maintainer ? { ...quest, waits: quest.waits.filter(onMaintainer) } : quest, @@ -512,7 +525,7 @@ export function main(argv: string[], out: Output): number | Promise { .option("--release", "Release the claim instead: delete the empty claim branch and close its PR") .option("--remote ", "Remote to push the claim to", "origin") .action((path: string, options: { release?: boolean; remote: string }) => { - const deps = { github: () => gitHubDependencies(warn), warn }; + const deps = claimDependencies(); if (options.release) { settle(releaseQuest(root(), find(load(root()), path).path, options.remote, deps), (released) => { print(`deleted ${released.branch}`); @@ -582,7 +595,9 @@ export function main(argv: string[], out: Output): number | Promise { return false; } }; - pending = waitForActivity(pr, options, gitHubDependencies(warn, "wait")).then( + pending = forgeFor(pr, forgeDependencies("wait")) + .then((forge) => waitForActivity(pr, options, forge, { now: Date.now, sleep })) + .then( (lines) => { for (const line of lines) print(line); return logged(lines[0]?.split(" ")[1] ?? null) ? 0 : 1; @@ -591,7 +606,7 @@ export function main(argv: string[], out: Output): number | Promise { if (error instanceof WaitTimeout && error.cursor) print(error.cursor); warn(error instanceof Error ? error.message : String(error)); if (error instanceof WaitTimeout) return logged(null) ? 3 : 1; - return error instanceof GitHubInputError ? 2 : 1; + return error instanceof InputError ? 2 : 1; }, ); }); @@ -632,8 +647,10 @@ export function main(argv: string[], out: Output): number | Promise { .option("--json", "Print a deterministic JSON object") .action((value: string, options: { json?: boolean }) => { const pr = pullRequest(value, root()); - pending = pullRequestStatus(pr, gitHubDependencies(warn)).then( - (status) => { + pending = forgeFor(pr, forgeDependencies()) + .then((forge) => forge.status(pr)) + .then( + ({ value: status }) => { if (options.json) print(JSON.stringify(status)); else for (const line of statusLines(status)) print(line); return 0; @@ -966,7 +983,7 @@ export function main(argv: string[], out: Output): number | Promise { const merged = async (repository: string, commit: string) => { const origin = readRemote(repository, "origin"); if (origin === null) return false; // No forge to ask. - const up = await upstream(repository, origin, { github: () => gitHubDependencies(warn), warn }); + const up = await upstream(repository, origin, claimDependencies()); return up.github !== null && mergedHolds(up.github.client, up.github.repository, commit); }; worktree @@ -1222,7 +1239,7 @@ export function main(argv: string[], out: Output): number | Promise { ) .option("--json", "Print one JSON object") .action((options: { since?: string; quest?: string; pr?: number; ssh?: string[]; json?: boolean }) => { - const github = { github: () => gitHubDependencies(warn), warn }; + const github = claimDependencies(); const since = options.since ?? daysBefore(new Date(), 7); settle( usage( @@ -1548,7 +1565,7 @@ export function main(argv: string[], out: Output): number | Promise { options.responses === undefined ? undefined : readFileSync(options.responses === "-" ? 0 : options.responses, "utf8"); - const github = { github: () => gitHubDependencies(warn), warn }; + const github = claimDependencies(); const run = review( { ...options, root: root(), exclude: options.excludeModel, responses, fresh: options.new }, { @@ -1700,7 +1717,7 @@ export function main(argv: string[], out: Output): number | Promise { given === 3 ? { at: options.defect!, fix: options.fix!, what: options.what! } : undefined, env: process.env, }, - { github: () => gitHubDependencies(warn), warn }, + claimDependencies(), ); pending = run.then((entry) => { print(JSON.stringify(entry)); @@ -1735,7 +1752,7 @@ export function main(argv: string[], out: Output): number | Promise { .argument("", "Quest file or epic directory, as /quest/..., quest/..., or a filesystem path") .argument("", "Its new path, which must not exist") .action((from: string, to: string) => { - pending = moveQuest(root(), from, to, { github: () => gitHubDependencies(warn), warn }).then( + pending = moveQuest(root(), from, to, claimDependencies()).then( report, (error: unknown) => { warn(error instanceof Error ? error.message : String(error)); @@ -1946,7 +1963,7 @@ export function main(argv: string[], out: Output): number | Promise { // Help and version exit 0; any other parse failure is a usage error. return error.exitCode === 0 ? 0 : 2; } - if (error instanceof UsageError || error instanceof GitHubInputError) { + if (error instanceof UsageError || error instanceof InputError) { out.stderr(`error: ${error.message}\n`); return 2; } diff --git a/src/cli/review-eval.ts b/src/cli/review-eval.ts index 0e92d911..37a818ab 100644 --- a/src/cli/review-eval.ts +++ b/src/cli/review-eval.ts @@ -9,7 +9,8 @@ import { join } from "node:path"; import { SIZES, type Size, TIERS, type Tier } from "../core"; import { parser } from "../core/parse"; -import { type GitHub, type Repository, object, repositoryPath } from "../github/client"; +import { type GitHub, object, repositoryPath } from "../github/client"; +import type { Repository } from "../core"; import type { HarnessName } from "./agent"; import { git } from "./git"; import { type ClaimDependencies, upstream } from "./claims"; diff --git a/src/cli/send.ts b/src/cli/send.ts index e6d70dd9..7c6e10bc 100644 --- a/src/cli/send.ts +++ b/src/cli/send.ts @@ -64,7 +64,7 @@ export function checkoutEndpoint(root: string): string | null { } /** `endpoint` when it is HTTPS, or HTTP to this host for a local store; anything else would send records in clear. */ -function checkedEndpoint(endpoint: string, where: string): string { +export function checkedEndpoint(endpoint: string, where: string): string { let url: URL; try { url = new URL(endpoint); diff --git a/src/cli/start.ts b/src/cli/start.ts index b4ed3278..4630a8ee 100644 --- a/src/cli/start.ts +++ b/src/cli/start.ts @@ -18,7 +18,8 @@ import { GitError, git } from "./git"; import { requireRemote } from "./github"; import { object, repositoryPath, string } from "../github/client"; import { ago } from "../github/hold"; -import { type OpenPull, mergedPull, openPullRequests, pullsFrom } from "../github/claims"; +import type { OpenPull } from "../core"; +import { mergedPull, openPullRequests, pullsFrom } from "../github/claims"; /** Someone else holds the quest, or the claim cannot be released; distinct from a failure. */ export class Refusal extends Error {} diff --git a/src/cli/status.ts b/src/cli/status.ts index 6610c257..5298de47 100644 --- a/src/cli/status.ts +++ b/src/cli/status.ts @@ -1,5 +1,5 @@ // `quest status`: a pull request's state as stable plain lines. -import type { Check, Status } from "../github/status"; +import type { Check, Status } from "../core"; /** Stable plain lines: a record type, then space-separated fields, with any free text last. */ export function statusLines(status: Status): string[] { diff --git a/src/cli/usage.ts b/src/cli/usage.ts index 09b632f3..a442765c 100644 --- a/src/cli/usage.ts +++ b/src/cli/usage.ts @@ -12,7 +12,8 @@ import { culpritOf, culprits } from "./breakage"; import { fixes } from "./land-fixer"; import { MERGER } from "./land-watch-fix"; import { githubRepository, requireRemote } from "./github"; -import { type GitHub, type ObjectValue, type Repository, link, object } from "../github/client"; +import { type GitHub, type ObjectValue, link, object } from "../github/client"; +import type { Repository } from "../core"; import { type OnlineReview, readOnlineReviews } from "../github/online-review"; import { type Counts, diff --git a/src/cli/wait.ts b/src/cli/wait.ts index d793500c..7cce535a 100644 --- a/src/cli/wait.ts +++ b/src/cli/wait.ts @@ -1,86 +1,14 @@ -// GitHub-specific PR activity waiting stays outside the repository-independent core. -import { createHash } from "node:crypto"; - -import { GitHubInputError } from "./github"; -import { - actor, - array, - currentChecks, - GitHub, - type GitHubDependencies, - link, - object, - type ObjectValue, - type PullRequest, - string, -} from "../github/client"; -import { - BRANCH_UPDATES, - classifyCheck, - enabledHead, - type Needs, - type Reported, - reported, - requiredOf, - unreported, -} from "../github/status"; +// `quest wait`: poll a pull request's activity through its forge until something happens or the timeout. +import type { Forge, PullRequest } from "../core"; const POLL = 5 * 60_000; /** * The last poll before a timeout starts this long before it, leaving time for its few requests; * activity after it is left for the returned cursor. Polling only on the 5-minute schedule left - * up to 5 minutes before a timeout unread. A longer X-Poll-Interval from GitHub still wins. + * up to 5 minutes before a timeout unread. A longer poll interval from the forge still wins. */ const FINAL_POLL = 30_000; -/** The REST page size. A full last page cannot show by itself that a next page has appeared. */ -const PAGE = 100; -/** How often setup rereads repository activity while GitHub has yet to list the head's push. */ -const LISTING_POLL = 15_000; - -/** Repository activity types a person's push makes; merges into the branch also move it (`BRANCH_UPDATES`). */ -const PUSHES = ["push", "force_push", "branch_creation"]; -const SHA = /^[a-f\d]{7,40}$/i; -/** The timeline records a force push a few seconds after repository activity (1-2s observed). */ -const TIMELINE_LAG = 60_000; -/** Reactions on the PR body and on each review; the newest 100 per subject are enough to spot new ones. */ -const REACTIONS = `query($owner: String!, $repo: String!, $number: Int!, $after: String) { - viewer { login } - repository(owner: $owner, name: $repo) { - pullRequest(number: $number) { - reactions(last: 100) { nodes { ...reaction } } - reviews(first: 100, after: $after) { - pageInfo { hasNextPage endCursor } - nodes { url reactions(last: 100) { nodes { ...reaction } } } - } - } - } -} -fragment reaction on Reaction { id content createdAt user { login } }`; -/** The head's check runs and commit statuses, with whether the base branch requires each. */ -const CHECKS = `query($owner: String!, $repo: String!, $number: Int!, $after: String) { - repository(owner: $owner, name: $repo) { - pullRequest(number: $number) { - baseRefName - headRefOid - headRefName - headRepository { nameWithOwner } - autoMergeRequest { enabledAt commitBody enabledBy { login } } - commits(last: 1) { nodes { commit { oid statusCheckRollup { - contexts(first: 100, after: $after) { - pageInfo { hasNextPage endCursor } - nodes { - __typename - ... on CheckRun { - databaseId name status conclusion completedAt detailsUrl isRequired(pullRequestNumber: $number) - checkSuite { databaseId status app { databaseId } workflowRun { file { path repositoryName } } } - } - ... on StatusContext { context state createdAt targetUrl isRequired(pullRequestNumber: $number) } - } - } - } } } } - } - } -}`; +const MAX_SLEEP = 2_147_483_647; export interface WaitOptions { since?: string; @@ -89,632 +17,60 @@ export interface WaitOptions { } export class WaitTimeout extends Error { - /** Where to resume, when the wait got far enough to know. */ - constructor(readonly cursor?: string) { - super("timed out waiting for pull request activity"); + /** Where to resume, when the wait got far enough to know; and how current an index's last answer was. */ + constructor( + readonly cursor?: string, + asOf?: { forge: string; at: string }, + ) { + super( + `timed out waiting for pull request activity${asOf ? `; ${asOf.forge}'s last answer was current to ${asOf.at}` : ""}`, + ); } } -interface Activity { - point: string; - time: number; - type: string; - actor: string; - url: string; - id: string; -} - -/** Each source is read separately, so each keeps its own position. */ -type Source = "timeline" | "replies" | "reactions" | "edits"; -const SOURCES: Source[] = ["timeline", "replies", "reactions", "edits"]; -/** The newest event time read from a source, and the IDs of events at that time. */ -interface Mark { - time: number; - ids: string[]; +/** The clock a wait polls on. */ +export interface Clock { + now(): number; + sleep(milliseconds: number): Promise; } -/** A cursor is a snapshot, since git timestamps cannot describe push order. */ -interface Cursor { - pr: string; - marks: Record; - commits: string[]; - /** Force pushes at or before the starting point, at their repository-activity time. */ - pushes: { sha: string; time: number }[]; - /** Check results reached at or after `since` are reported once per head, as `:`. */ - checks: { since: number; reported: string[] }; -} - -/** One check run or commit status on the head, with its result once it has one. */ -interface Check extends Reported { - required: boolean; - url: string | null; - /** A GitHub Actions job whose workflow run has not finished, so it may still create jobs. */ - running: boolean; - result?: { outcome: "passed" | "failed"; point: string; time: number }; -} - -/** Wait until activity, returning plain output lines. Network and time are injected. */ +/** Wait until activity, returning plain output lines: each event, the last followed by its resume cursor. */ export async function waitForActivity( pr: PullRequest, options: WaitOptions, - deps: GitHubDependencies, + forge: Forge, + clock: Clock, ): Promise { - const started = deps.now(); - const progress = { resume: options.since }; - try { - return await watch(pr, options, deps, started, progress); - } catch (error) { - // This also covers a deadline expiring while a response body is read. - if (options.timeout !== undefined && deps.now() - started >= options.timeout * 1000) - throw new WaitTimeout(progress.resume); - throw error; - } -} - -async function watch( - pr: PullRequest, - options: WaitOptions, - deps: GitHubDependencies, - started: number, - progress: { resume?: string }, -): Promise { - // Cursors are case-sensitive base64url; a recased one would otherwise be misreported as a bad timestamp. - if (options.since && /^q1\./i.test(options.since) && !options.since.startsWith("q1.")) - throw new GitHubInputError( - "invalid --since cursor: cursors start with lower-case q1.; pass it exactly as printed", - ); - if (options.since && !options.since.startsWith("q1.") && !SHA.test(options.since)) { - try { - timestamp(options.since); - } catch (error) { - throw new GitHubInputError((error as Error).message); - } - } - const name = `${pr.owner}/${pr.repo}#${pr.number}`; - const base = `/repos/${encodeURIComponent(pr.owner)}/${encodeURIComponent(pr.repo)}`; - const prUrl = `https://github.com/${pr.owner}/${pr.repo}/pull/${pr.number}`; + const started = clock.now(); const deadline = options.timeout === undefined ? Infinity : started + options.timeout * 1000; - const github = new GitHub(deps, deadline); - - let cursor: Cursor; - let historical: Activity[] = []; - const baselineCommits = new Set(); - let pushedTips: string[] = []; - if (options.since?.startsWith("q1.")) { - cursor = decodeCursor(options.since, name); - } else { - const pullResponse = await github.request(`${base}/pulls/${pr.number}`); - const pull = object(await pullResponse.json()); - const head = object(pull.head); - const currentSha = string(head.sha); - // Until setup finishes, a timeout resumes from this head rather than whatever is pushed next. - progress.resume = options.since ?? currentSha; - // Verify the listing belongs to this exact head before treating it as - // baseline membership. A racing push must never be silently swallowed. - let commitsPath: string | undefined = `${base}/pulls/${pr.number}/commits?per_page=100`; - let listedHead: string | undefined; - while (commitsPath) { - const { rows, response } = await github.list(commitsPath); - for (const commit of rows) { - listedHead = string(commit.sha); - if (!fullSha(listedHead)) throw new Error("invalid GitHub commit SHA"); - baselineCommits.add(listedHead); - } - commitsPath = link(response, "next"); - } - if (listedHead !== currentSha) { - throw new Error( - "cannot snapshot PR commits: head changed during setup, or GitHub's 250-commit listing limit was reached; rerun after checking the PR head", - ); - } - const point = options.since ?? currentSha; - const shaPoint = SHA.test(point); - const time = shaPoint ? undefined : timestamp(point); - // A merge into the branch, such as GitHub's Update branch, can also have moved the head to the point. - const moved = (row: ObjectValue) => BRANCH_UPDATES.includes(string(row.activity_type)); - const isPoint = (row: ObjectValue) => moved(row) && string(row.after).startsWith(point.toLowerCase()); - let activities: ObjectValue[] = []; - if (head.repo !== null) { - const headRepo = object(head.repo); - const fullName = string(headRepo.full_name); - if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) throw new Error("invalid GitHub head repository"); - let warned = false; - for (;;) { - activities = []; - let path: string | undefined = - `/repos/${fullName}/activity?ref=${encodeURIComponent(string(head.ref))}&per_page=100`; - while (path) { - const { rows, response } = await github.list(path); - activities.push(...rows); - if (shaPoint ? rows.some(isPoint) : rows.some((row) => timestamp(string(row.timestamp)) <= time!)) - break; - path = link(response, "next"); - } - // The head was pushed, but GitHub lists a push seconds to minutes later (14s-6min observed), - // so a wait started right after pushing reads the listing again until the push appears. - if (!shaPoint || activities.some(isPoint) || !currentSha.startsWith(point.toLowerCase())) break; - if (!warned) deps.warn(`GitHub has not listed the push of ${point} yet; waiting for it`); - warned = true; - await github.pause(LISTING_POLL); - } - } else if (shaPoint) { - throw new Error("head repository was deleted; pass a timestamp with --since"); - } - const pushed = activities.filter((row) => PUSHES.includes(string(row.activity_type))); - const match = shaPoint ? activities.find(isPoint) : undefined; - if (shaPoint && !match) throw new Error(`cannot resolve push time for ${point}; pass a timestamp with --since`); - const since = time ?? timestamp(string(match!.timestamp)); - // An explicit timestamp includes its own instant; a SHA point excludes its own push. - const after = (row: ObjectValue) => { - const pushedAt = timestamp(string(row.timestamp)); - return shaPoint ? pushedAt > since : pushedAt >= since; - }; - // Force pushes are reported from the timeline alone, so one push prints once. - const forced = pushed.filter((row) => string(row.activity_type) === "force_push"); - cursor = { - pr: name, - marks: { - timeline: { time: since, ids: [] }, - replies: { time: since, ids: [] }, - reactions: { time: since, ids: [] }, - edits: { time: since, ids: [] }, - }, - commits: [], - pushes: forced - .filter((row) => !after(row)) - .map((row) => ({ sha: string(row.after), time: timestamp(string(row.timestamp)) })), - checks: { since, reported: [] }, - }; - const plain = pushed.filter((row) => string(row.activity_type) !== "force_push" && after(row)); - // A push racing setup is reported once, as a push, not again as a new commit. - pushedTips = plain.map((row) => string(row.after)); - for (const sha of pushedTips) baselineCommits.add(sha); - // A merge into the branch after the point is not a push, so it is reported as its new commit. - for (const row of activities) - if ( - moved(row) && - !PUSHES.includes(string(row.activity_type)) && - after(row) && - !pushedTips.includes(string(row.after)) - ) - baselineCommits.delete(string(row.after)); - historical = plain.map((row) => ({ - point: string(row.timestamp), - time: timestamp(string(row.timestamp)), - type: "pushed", - actor: actor(row.actor), - url: `https://github.com/${string(object(head.repo).full_name)}/commit/${string(row.after)}`, - id: `push:${string(row.after)}:${string(row.timestamp)}`, - })); - } - - const seenCommits = new Set([...baselineCommits, ...cursor.commits]); - // Activity found before a timeout is not printed, so resuming must find it again; - // a push found during setup comes back as its new commit. - progress.resume = encodeCursor({ - ...cursor, - commits: [...seenCommits].filter((sha) => !pushedTips.includes(sha)), - }); - const seen = Object.fromEntries(SOURCES.map((source) => [source, new Set(cursor.marks[source].ids)])) as Record< - Source, - Set - >; - const fresh = (source: Source, event: Activity) => { - const mark = cursor.marks[source]; - return event.time > mark.time || (event.time === mark.time && !seen[source].has(event.id)); - }; - /** - * Read every page once, then poll the last page conditionally, following it when it fills. A 304 - * has no Link header and the ETag covers only the body, so a full last page is reread whole to - * learn of a next one. - */ - const pager = (first: string) => { - let path = first; - let etag: string | undefined; - return async (): Promise => { - const rows: ObjectValue[] = []; - for (;;) { - const response = await github.request(path, { etag }); - if (response.status === 304) { - if (!etag) throw new Error("unexpected GitHub 304 without a cached response"); - return rows; - } - const page = array(await response.json()); - rows.push(...page); - const next = link(response, "next"); - if (!next) { - etag = page.length < PAGE ? (response.headers.get("etag") ?? undefined) : undefined; - return rows; - } - path = next; - etag = undefined; - } - }; - }; - const graphql = (query: string, after: string | null) => - github.graphql(query, { owner: pr.owner, repo: pr.repo, number: pr.number, after }); - /** REST has no endpoint for reactions on reviews, and GraphQL also names the waiter. */ - const reactions = async (): Promise<{ viewer: string; events: Activity[] }> => { - const events: Activity[] = []; - let viewer: string; - let after: string | null = null; - do { - const data = await graphql(REACTIONS, after); - viewer = string(object(data.viewer).login); - const pull = object(object(data.repository).pullRequest); - const reviews = object(pull.reviews); - const reacted = (owner: ObjectValue, url: string) => - array(object(owner.reactions).nodes).map((row) => reaction(row, url)); - if (after === null) events.push(...reacted(pull, prUrl)); - for (const review of array(reviews.nodes)) events.push(...reacted(review, string(review.url))); - const page = object(reviews.pageInfo); - after = page.hasNextPage === true ? string(page.endCursor) : null; - } while (after !== null); - return { viewer, events }; - }; - /** GraphQL says which checks the base branch requires, through branch protection or rulesets. */ - const checks = async (): Promise< - { head: string; base: string; checks: Check[]; unfinished: boolean; pull: ObjectValue } | undefined - > => { - const rows: ObjectValue[] = []; - let head: string | undefined; - let after: string | null = null; - let pull: ObjectValue; - do { - pull = object(object((await graphql(CHECKS, after)).repository).pullRequest); - const commit = object(array(object(pull.commits).nodes)[0]?.commit); - // A push racing these pages is read whole on the next poll. - if (commit.oid !== pull.headRefOid || (head !== undefined && commit.oid !== head)) return undefined; - head = string(commit.oid); - if (!fullSha(head)) throw new Error("invalid GitHub head SHA"); - if (commit.statusCheckRollup === null) break; - const contexts = object(object(commit.statusCheckRollup).contexts); - rows.push(...array(contexts.nodes)); - const page = object(contexts.pageInfo); - after = page.hasNextPage === true ? string(page.endCursor) : null; - } while (after !== null); - const current = await currentChecks(github, pr, head!, rows); - // A replacing run may have no check run yet, so an unfinished run it read keeps the head busy. - const unfinished = current.runs?.some((run) => run.status !== "completed") ?? false; - return { head: head!, base: string(pull.baseRefName), checks: current.checks.map(check), unfinished, pull }; - }; - /** - * What the base branch requires, read once per wait, as `quest status` reads it. Only a requirement - * says whether a missing check has yet to start, or whether the repository requires none. - */ - const known = new Map(); - const required = async (branch: string): Promise => { - const cached = known.get(branch); - if (cached) return cached; - const needs = await requiredOf(github, pr, branch); - known.set(branch, needs); - return needs; - }; - - /** The head each auto-merge request was enabled on, by when it was enabled, once that can be told. */ - const enabledHeads = new Map(); - /** Warnings already printed, so a forbidden activity listing warns once per wait rather than per poll. */ - const warned = new Set(); - const warnOnce = (message: string) => { - if (!warned.has(message)) deps.warn(message); - warned.add(message); - }; - /** Auto-merge left on for a head other than `head`, reported once per head and request. */ - const movedAutoMerge = async (head: string, pull: ObjectValue): Promise => { - if (pull.autoMergeRequest == null) return []; - const request = object(pull.autoMergeRequest); - const enabledAt = string(request.enabledAt); - const id = `${head}:auto-merge:${enabledAt}`; - if (cursor.checks.reported.includes(id)) return []; - const enabled = enabledHeads.get(enabledAt) ?? (await enabledHead(github, pull, warnOnce)); - if (enabled === null) return []; - enabledHeads.set(enabledAt, enabled); - if (enabled === head) return []; - const point = new Date(deps.now()).toISOString(); - const url = `${prUrl}/commits/${enabled}`; - return [{ point, time: deps.now(), type: "auto-merge:moved", actor: actor(request.enabledBy), url, id }]; + const watch = forge.watch(pr, { since: options.since, deadline }); + let asOf: string | null = null; + const timedOut = () => new WaitTimeout(watch.resume, asOf === null ? undefined : { forge: forge.name, at: asOf }); + const pause = async (milliseconds: number) => { + const remaining = deadline - clock.now(); + if (remaining <= 0) throw timedOut(); + await clock.sleep(Math.min(milliseconds, remaining, MAX_SLEEP)); + if (clock.now() >= deadline) throw timedOut(); }; - - const timeline = pager(`${base}/issues/${pr.number}/timeline?per_page=${PAGE}`); - // `since` excludes its own instant and filters by update time, which is never before - // creation; start a second early so unseen replies at the mark's second are still read. - const comments = pager( - `${base}/pulls/${pr.number}/comments?per_page=${PAGE}&since=${new Date(cursor.marks.replies.time - 1000).toISOString()}`, - ); - // Issue comments are ordered by creation: an old comment can be edited on an - // earlier page, so reread this update-filtered list from its first page. - const edits = async () => { - const rows: ObjectValue[] = []; - let path: string | undefined = - `${base}/issues/${pr.number}/comments?per_page=${PAGE}&since=${new Date(cursor.marks.edits.time - 1000).toISOString()}`; - while (path) { - const page = await github.list(path); - rows.push(...page.rows); - path = link(page.response, "next"); - } - return rows; - }; - const found: Record = { timeline: historical, replies: [], reactions: [], edits: [] }; - for (;;) { - github.pollInterval = 0; - const labels: Activity[] = []; - for (const row of await timeline()) { - const type = string(row.event); - if (type === "committed") { - const sha = string(row.sha); - if (!fullSha(sha)) throw new Error("invalid GitHub committed SHA"); - if (!seenCommits.has(sha)) { - found.timeline.push({ - point: sha, - time: cursor.marks.timeline.time, - type: "committed", - actor: actor(row.actor ?? row.committer), - url: string(row.html_url), - id: `commit:${sha}`, - }); - } - seenCommits.add(sha); - continue; - } - for (const event of timelineActivities(row, prUrl)) { - if ( - type === "head_ref_force_pushed" && - cursor.pushes.some( - (push) => - push.sha === row.commit_id && - event.time >= push.time && - event.time - push.time <= TIMELINE_LAG, - ) - ) - continue; - if (fresh("timeline", event)) (LABELS.includes(type) ? labels : found.timeline).push(event); - } - } - const replies = await comments(); - const { viewer, events } = await reactions(); - // The waiter's own label changes, replies, and reactions never wake it. - found.timeline.push(...labels.filter((event) => event.actor !== viewer)); - for (const row of replies) { - // A thread's first comment belongs to a review, which the timeline reports. - if (row.in_reply_to_id === undefined || row.in_reply_to_id === null) continue; - const event = timedActivity(row, "replied", "created_at", prUrl); - if (event.actor !== viewer && fresh("replies", event)) found.replies.push(event); - } - found.reactions.push(...events.filter((event) => event.actor !== viewer && fresh("reactions", event))); - for (const row of await edits()) { - if (timestamp(string(row.updated_at)) <= timestamp(string(row.created_at))) continue; - const event = timedActivity(row, "edited", "updated_at", prUrl); - // GitHub timestamps have second precision: two different edits in that - // second remain distinct, without storing the comment text in a cursor. - event.id += `:${createHash("sha256").update(string(row.body)).digest("hex")}`; - if (event.actor !== viewer && fresh("edits", event)) found.edits.push(event); - } - // Check results are state rather than a log, so each poll reads them afresh. - const head = await checks(); - const reached = head - ? [ - ...checkActivities(head, await required(head.base), cursor.checks, prUrl), - ...(await movedAutoMerge(head.head, head.pull)), - ] - : []; - - if (reached.length || SOURCES.some((source) => found[source].length)) { - const marks = Object.fromEntries( - SOURCES.map((source) => { - const mark = cursor.marks[source]; - const time = Math.max(mark.time, ...found[source].map((event) => event.time)); - const ids = [ - ...(time === mark.time ? mark.ids : []), - ...found[source].filter((event) => event.time === time).map((event) => event.id), - ]; - return [source, { time, ids: [...new Set(ids)] }]; - }), - ) as Record; - const nextCursor = encodeCursor({ - pr: name, - marks, - commits: [...seenCommits], - pushes: cursor.pushes.filter((push) => push.time + TIMELINE_LAG >= marks.timeline.time), - checks: { - since: cursor.checks.since, - // A new head starts over, so only the current head's reports are kept. - reported: [ - ...cursor.checks.reported.filter((id) => !head || id.startsWith(`${head.head}:`)), - ...reached.map((event) => event.id), - ], - }, - }); - const all = [...SOURCES.flatMap((source) => found[source]), ...reached].sort((a, b) => a.time - b.time); - const unique = [...new Map(all.map((event) => [event.id, event])).values()]; - return unique.map( - (event, index) => - `${event.point} ${event.type} ${event.actor} ${event.url}${index === unique.length - 1 ? ` ${nextCursor}` : ""}`, - ); - } - // GitHub's X-Poll-Interval is a floor: the final poll shortens only the default schedule, - // and is skipped when that interval runs past it. - const remaining = deadline - deps.now(); - const next = Math.min(Math.max(POLL, github.pollInterval), remaining - FINAL_POLL); - await github.pause(next > 0 && next >= github.pollInterval ? next : remaining); - } -} - -// A dequeue or a disabled auto-merge needs the agent. A merge also leaves the queue, a second before "merged". -// A label-driven queue dequeues by removing its label. -const LABELS = ["labeled", "unlabeled"]; -const WAKES = [ - ...LABELS, - "reviewed", - "commented", - "merged", - "closed", - "head_ref_force_pushed", - "removed_from_merge_queue", - "auto_merge_disabled", -]; - -function timelineActivities(row: ObjectValue, prUrl: string): Activity[] { - const type = string(row.event); - if (type === "line-commented" || type === "commit-commented") { - return array(row.comments).map((comment) => timedActivity(comment, type, "created_at", prUrl)); - } - if (!WAKES.includes(type)) return []; - if (LABELS.includes(type)) { - const event = timedActivity(row, type, "created_at", prUrl); - return [{ ...event, type: `${type}:${string(object(row.label).name).replace(/\s/g, "_")}` }]; - } - return [timedActivity(row, type, type === "reviewed" ? "submitted_at" : "created_at", prUrl)]; -} - -/** A check run or commit status, classified as `quest status` does, with when it finished. */ -function check(row: ObjectValue): Check { - const run = row.__typename === "CheckRun"; - const { check: classified, outcome } = classifyCheck(row); - const suite = run && row.checkSuite ? object(row.checkSuite) : undefined; - const found: Check = { - ...reported(row), - required: classified.required, - url: classified.url, - running: suite?.workflowRun ? suite.status !== "COMPLETED" : false, - }; - if (outcome === "pending") return found; - const point = string(run ? row.completedAt : row.createdAt); - found.result = { outcome: outcome === "passed" ? "passed" : "failed", point, time: timestamp(point) }; - return found; -} - -/** - * The head's first required failure, and every required check passing once the head is idle, each - * reported once per head when reached at or after the starting point. A base branch that requires - * no checks requires them all. - */ -function checkActivities( - { head, checks: all, unfinished }: { head: string; checks: Check[]; unfinished: boolean }, - needs: Needs, - state: Cursor["checks"], - prUrl: string, -): Activity[] { - const inWorkflow = (entry: Check) => entry.workflow !== undefined && needs.workflows.includes(entry.workflow); - const required = - needs.checks.length || needs.workflows.length - ? all.filter((entry) => entry.required || inWorkflow(entry)) - : all; - const reached = ( - outcome: "passed" | "failed", - entry: Check | undefined, - optional = false, - at = entry?.result, - ): Activity[] => { - const id = optional ? `${head}:optional:${entry?.name}:${entry?.url}:${at?.point}` : `${head}:${outcome}`; - if (!entry?.result || !at || at.time < state.since || state.reported.includes(id)) return []; - return [ - { - point: at.point, - time: at.time, - type: `${optional ? "check" : "checks"}:${outcome}`, - actor: entry.name.replace(/\s/g, "_"), - url: entry.url ?? `${prUrl}/checks`, - id, - }, - ]; - }; - const settled = required.flatMap((entry) => (entry.result ? [{ ...entry, result: entry.result }] : [])); - settled.sort((a, b) => a.result.time - b.result.time); - const failed = settled.find((entry) => entry.result.outcome === "failed" && entry.result.time >= state.since); - // A pass waits for the head to go idle, including jobs a running workflow - // may still create. Its date is the last completion, but its name and link - // always identify a required check that passed. - const idle = - !unfinished && all.every((entry) => entry.result && !entry.running) && unreported(all, needs).length === 0; - const passed = - idle && settled.length === required.length && settled.every((entry) => entry.result.outcome === "passed") - ? settled.at(-1) - : undefined; - const last = idle - ? all.reduce( - (latest, entry) => (!latest || entry.result!.time >= latest.result!.time ? entry : latest), - undefined, - ) - : undefined; - const optional = all.filter((entry) => !required.includes(entry) && entry.result?.outcome === "failed"); - return [ - ...reached("failed", failed), - ...optional.flatMap((entry) => reached("failed", entry, true)), - ...reached("passed", passed, false, last?.result), - ]; -} - -function timedActivity(row: ObjectValue, type: string, timeField: string, fallback: string): Activity { - const point = string(row[timeField]); - const id = row.id; - if (typeof id !== "number" && typeof id !== "string") throw new Error("missing GitHub event ID"); - return { - point, - time: timestamp(point), - type, - actor: actor(row.actor ?? row.user), - url: row.html_url === undefined ? fallback : string(row.html_url), - id: `${type}:${id}`, - }; -} - -function reaction(row: ObjectValue, url: string): Activity { - const point = string(row.createdAt); - return { - point, - time: timestamp(point), - type: `reacted:${string(row.content).toLowerCase()}`, - actor: actor(row.user), - url, - id: `reacted:${string(row.id)}`, - }; -} - -function timestamp(value: string): number { - const result = Date.parse(value); - if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) || !Number.isFinite(result)) - throw new Error(`invalid timestamp: ${value}; use an ISO 8601 timestamp, a pushed SHA, or a returned cursor`); - return result; -} - -function fullSha(value: unknown): boolean { - return typeof value === "string" && /^[a-f\d]{40}$/i.test(value); -} - -function encodeCursor(cursor: Cursor): string { - return `q1.${Buffer.from(JSON.stringify(cursor)).toString("base64url")}`; -} - -function decodeCursor(value: string, pr: string): Cursor { try { - const parsed = object(JSON.parse(Buffer.from(value.slice(3), "base64url").toString("utf8"))); - const marks = object(parsed.marks); - const checks = object(parsed.checks); - // Older resumable cursors predate edited-comment tracking. Start that - // source at the original baseline so an edit is never silently skipped. - marks.edits ??= { time: checks.since, ids: [] }; - if ( - parsed.pr !== pr || - !SOURCES.every((source) => { - const mark = object(marks[source]); - return ( - typeof mark.time === "number" && - Number.isFinite(mark.time) && - Array.isArray(mark.ids) && - mark.ids.every((id) => typeof id === "string") + for (;;) { + const answer = await watch.poll(); + asOf = answer.asOf; + const { events, cursor, pollInterval } = answer.value; + if (events.length) + return events.map( + (event, index) => + `${event.point} ${event.type} ${event.actor} ${event.url}${index === events.length - 1 ? ` ${cursor}` : ""}`, ); - }) || - !Array.isArray(parsed.commits) || - !parsed.commits.every(fullSha) || - !Array.isArray(parsed.pushes) || - !parsed.pushes.every((push: ObjectValue | null) => fullSha(push?.sha) && Number.isFinite(push?.time)) || - !Number.isFinite(checks.since) || - !Array.isArray(checks.reported) || - !checks.reported.every((id) => typeof id === "string") - ) - throw new Error(); - return parsed as unknown as Cursor; - } catch { - throw new GitHubInputError("invalid --since cursor, or cursor belongs to another pull request"); + // The forge's poll interval is a floor: the final poll shortens only the default schedule, + // and is skipped when that interval runs past it. + const remaining = deadline - clock.now(); + const next = Math.min(Math.max(POLL, pollInterval), remaining - FINAL_POLL); + await pause(next > 0 && next >= pollInterval ? next : remaining); + } + } catch (error) { + // This also covers a deadline expiring inside a read, such as while a response body is read. + if (options.timeout !== undefined && clock.now() - started >= options.timeout * 1000) throw timedOut(); + throw error; } } diff --git a/src/core/forge.ts b/src/core/forge.ts new file mode 100644 index 00000000..b2879a06 --- /dev/null +++ b/src/core/forge.ts @@ -0,0 +1,472 @@ +// What quest reads from a forge, as one interface with a backend per forge: pull request, check, review, hold, and +// queue state, claims, and activity to wait on. Its types are the wire format Kixel Quest serves them in, so both +// sides parse the same shapes and neither guesses. +import { TIERS, type Tier } from "./risk"; + +/** A repository on its forge, by owner and name. */ +export interface Repository { + owner: string; + repo: string; +} + +/** A pull request by its repository and number. */ +export interface PullRequest extends Repository { + number: number; +} + +/** A bad argument, such as a malformed PR or wait point, reported as a usage error. */ +export class InputError extends Error {} + +/** A check run or commit status on the head, as `quest status` prints it. */ +export interface Check { + name: string; + required: boolean; + /** The lowercased check-run conclusion or status, or commit-status state. */ + result: string; + url: string | null; +} + +/** A reviewer's latest submitted review. */ +export interface Review { + reviewer: string; + /** approved, changes_requested, commented, or dismissed. */ + state: string; + /** Whether the review was submitted against the current head. */ + current: boolean; + commit: string | null; + submittedAt: string; + url: string; +} + +/** A reaction on the PR or one of its reviews. */ +export interface Reaction { + content: string; + actor: string; + createdAt: string; + /** The PR or review reacted to. */ + url: string; +} + +/** An unresolved review thread. */ +export interface Thread { + id: string; + path: string; + /** The line on the current diff, or the original line once outdated. */ + line: number | null; + outdated: boolean; + lastAuthor: string; + /** The thread's latest comment. */ + url: string; +} + +/** + * The head the PR body's `## Review` section names last, the latest reviewed one: a round's record, or a line after + * it for low-severity fixes or a skip. `current` is the PR's head; `diff-identical` an earlier head whose diff from + * the base (`git diff ...`) matches the head's; `unknown` one the forge cannot compare, such as a diff too + * large to render. + */ +export interface ReviewRecord { + state: "current" | "diff-identical" | "stale" | "unknown"; + head: string; +} + +/** One signal on a PR's head that holds it from landing until it is fixed or answered. */ +export interface Signal { + /** `finding`: an online reviewer's, on the head. `decision`: a marked comment newer than the head's commit. */ + kind: "finding" | "decision"; + /** The review, thread, or comment that raised it. */ + url: string; + author: string; + /** The finding's title or thread's first line, or the decision's first line. */ + text: string; +} + +/** A hold label on a PR, and the event that took it when the timeline still shows it. */ +export interface HoldFact { + label: string; + /** Null when the acquisition is older than the available timeline. */ + token: string | null; + takenAt: string | null; + age: string | null; + /** The forge's verified event URL; the opaque token is not a browser anchor. */ + eventUrl: string | null; +} + +/** A draft its starter still holds: one not handed back with `## Waiting`. */ +export interface StarterHold { + lastActive: string; + age: string; + url: string; +} + +/** Everything `quest status` reports about a PR. */ +export interface Status { + url: string; + state: "open" | "closed" | "merged"; + draft: boolean; + head: string; + mergeable: string; + mergeState: string; + reviewDecision: string | null; + /** `head` is the head it was enabled on, or null when that cannot be told. */ + autoMerge: { method: string; enabledBy: string; enabledAt: string; head: string | null } | null; + mergeQueue: { state: string; position: number; enqueuedAt: string } | null; + /** + * The latest exit from the merge queue, auto-merge, or `quest land`'s queue, and the reason for it; + * null once the PR is queued again. + */ + landingStopped: { reason: string; actor: string; at: string } | null; + checks: { state: string | null; passed: number; failing: Check[]; pending: Check[] }; + /** Each reviewer's latest submitted review, oldest first. */ + reviews: Review[]; + /** The design checkpoints online reviewers put on the head. */ + checkpoints: { reviewer: string; round: number; url: string }[]; + /** Null when the `## Review` section names no full SHA. */ + reviewRecord: ReviewRecord | null; + /** + * The head's risk tier as the `## Review` record names it, and the classifier's own tier, lower when a reviewer + * raised it; null when the record names none. `state` is the review record's, which a line after it carries to a + * later head, else `current` when the record names the head and `stale` when not. + */ + risk: { tier: Tier; reason: string; classified: Tier; state: ReviewRecord["state"] } | null; + reactions: Reaction[]; + /** Unresolved review threads, oldest first. */ + threads: Thread[]; + /** What holds the head from landing: online reviewers' unanswered findings on it and newer maintainer decisions. */ + signals: Signal[]; + holds: HoldFact[]; + starterHold: StarterHold | null; +} + +/** An open PR, from any head repository, as the claim checks read it. */ +export interface OpenPull { + number: number; + url: string; + branch: string; + /** The head repository as `owner/repo`, or `null` once a fork is deleted. */ + head: string | null; + draft: boolean; + /** Epoch milliseconds. The earliest open PR on a branch holds the claim. */ + created: number; + /** Epoch milliseconds of the last push, comment, or edit. */ + updated: number; + /** Its body has a `## Waiting` section, so it waits on the maintainer. */ + handedBack: boolean; + body: string; +} + +/** A held quest branch, and the open PR from it if there is one. */ +export interface Claim { + branch: string; + /** The PR holding the claim: the earliest open one. */ + url: string | null; + pull: OpenPull | null; +} + +/** Which branches someone holds, and which landed branches a new claim replaces. */ +export interface Holdings { + /** Sorted by branch. */ + claims: Claim[]; + /** + * Branches in the head fork, or upstream without one, whose tip is the head of a merged PR, by + * that tip. Their work landed, so they hold nothing and a claim may replace them. + */ + landed: Map; +} + +/** A repository claim branches live in, and its `quest/*` branch tips when the caller already read them. */ +export interface ClaimSource { + repository: Repository; + tips?: Map; +} + +/** Where claims live: the upstream repository, and the fork a contributor pushes claims to, if any. */ +export interface ClaimSources { + upstream: ClaimSource; + /** Absent when claims are pushed upstream. */ + fork?: ClaimSource; +} + +/** One line of `quest wait`'s output: when (a timestamp or commit SHA), what, who, and where. */ +export interface WaitEvent { + point: string; + type: string; + actor: string; + url: string; +} + +/** One poll of a PR's activity: what is new, in order, and where the next poll resumes. */ +export interface WatchPoll { + events: WaitEvent[]; + /** Opaque to the caller; `quest wait --since` takes it back. */ + cursor: string; + /** The least time to the next poll the forge asks for, in milliseconds; 0 for none. */ + pollInterval: number; +} + +/** A forge's answer, and the time of the newest webhook behind it, or null for a live read from the forge itself. */ +export interface Answer { + value: T; + asOf: string | null; +} + +/** Polls of one PR's activity, each resuming where the last stopped. */ +export interface Watch { + /** Where a wait that times out now resumes: the latest cursor, else the point it started from, once known. */ + readonly resume: string | undefined; + /** The activity since the last poll, or since the starting point on the first. */ + poll(): Promise>; +} + +/** Where a watch starts, and when it gives up: epoch milliseconds, or Infinity. */ +export interface WatchOptions { + /** An ISO timestamp, a pushed SHA, or a cursor; the head's push time when absent. */ + since?: string; + deadline: number; +} + +/** The reads quest makes of a forge. */ +export interface Forge { + /** What it is called in messages, such as `GitHub`. */ + readonly name: string; + /** The person reading: whose own activity `quest wait` ignores, whichever credential serves the reads. */ + viewer(): Promise; + /** A PR's state, as `quest status` prints it. */ + status(pull: PullRequest): Promise>; + /** Every open PR in `repository`, from any head repository. */ + pulls(repository: Repository): Promise>; + /** Which of `branches` someone holds, as `quest start` decides it. */ + held(sources: ClaimSources, branches: string[]): Promise>; + /** Polls of a PR's activity, starting from `options.since`. */ + watch(pull: PullRequest, options: WatchOptions): Watch; +} + +/** Each read Kixel Quest serves at `POST /forge/`: the request it takes and the value it answers. */ +export interface ForgeCalls { + status: { request: { pull: PullRequest }; value: Status }; + pulls: { request: { repository: Repository }; value: OpenPull[] }; + held: { request: { sources: ClaimSources; branches: string[] }; value: Holdings }; + /** `from` is a `--since` point or a cursor; null starts at the head's push time. */ + watch: { request: { pull: PullRequest; from: string | null }; value: WatchPoll }; +} + +/** A read Kixel Quest serves. */ +export type ForgeCall = keyof ForgeCalls; + +/** The calls, as their paths name them. */ +export const FORGE_CALLS: readonly ForgeCall[] = ["status", "pulls", "held", "watch"]; + +/** `GET /forge`: the person a token names and the repositories, as lowercase `owner/repo`, read through Kixel Quest. */ +export interface ForgeInfo { + login: string; + repositories: string[]; +} + +/** `value` as JSON: maps become objects. */ +export function forgeJson(value: unknown): string { + return JSON.stringify(value, (_, entry: unknown) => (entry instanceof Map ? Object.fromEntries(entry) : entry)); +} + +/** A `GET /forge` answer, failing on any missing, extra, or ill-typed field. */ +export function parseForgeInfo(value: unknown): ForgeInfo { + return info(value, "info"); +} + +/** A request for `call`, failing on any missing, extra, or ill-typed field. */ +export function parseForgeRequest(call: C, value: unknown): ForgeCalls[C]["request"] { + return REQUESTS[call](value, "request") as ForgeCalls[C]["request"]; +} + +/** An answer to `call`, failing on any missing, extra, or ill-typed field. */ +export function parseForgeAnswer(call: C, value: unknown): Answer { + return answer(VALUES[call])(value, "answer") as Answer; +} + +/** Parses untrusted JSON at a path named for its error, such as `answer.value.checks`. */ +type Parse = (value: unknown, at: string) => T; + +const fail = (at: string, expected: string): never => { + throw new Error(`malformed forge ${at}: expected ${expected}`); +}; +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const string: Parse = (value, at) => (typeof value === "string" ? value : fail(at, "a string")); +const name: Parse = (value, at) => (typeof value === "string" && value !== "" ? value : fail(at, "a name")); +const boolean: Parse = (value, at) => (typeof value === "boolean" ? value : fail(at, "a boolean")); +const count: Parse = (value, at) => + Number.isSafeInteger(value) && (value as number) >= 0 ? (value as number) : fail(at, "a count"); +const time: Parse = (value, at) => + typeof value === "string" && !Number.isNaN(Date.parse(value)) ? value : fail(at, "a timestamp"); +const oneOf = + (options: readonly T[]): Parse => + (value, at) => + options.includes(value as T) ? (value as T) : fail(at, `one of ${options.join(", ")}`); +const nullable = + (parse: Parse): Parse => + (value, at) => + value === null ? null : parse(value, at); +const list = + (parse: Parse): Parse => + (value, at) => + Array.isArray(value) ? value.map((entry, index) => parse(entry, `${at}[${index}]`)) : fail(at, "a list"); +/** An object of exactly these fields, rebuilt in their order so JSON output stays deterministic. */ +const shape = + (fields: { [K in keyof T]-?: Parse }): Parse => + (value, at) => { + if (!isRecord(value)) return fail(at, "an object"); + const extra = Object.keys(value).find((key) => !Object.hasOwn(fields, key)); + if (extra !== undefined) fail(`${at}.${extra}`, "no such field"); + const out: Record = {}; + for (const key of Object.keys(fields) as (keyof T & string)[]) { + const field = (fields as Record>)[key]!; + if (Object.hasOwn(value, key)) out[key] = field(value[key], `${at}.${key}`); + else if (!optional.has(field)) fail(`${at}.${key}`, "a value"); + } + return out as T; + }; +/** Fields a shape may leave out. */ +const optional = new WeakSet>(); +const maybe = (parse: Parse): Parse => { + const parsed: Parse = (value, at) => parse(value, at); + optional.add(parsed); + return parsed; +}; +/** A JSON object of names to values, as a map. */ +const mapOf = + (key: Parse, entry: Parse): Parse> => + (value, at) => { + if (!isRecord(value)) return fail(at, "an object"); + return new Map(Object.entries(value).map(([k, v]) => [key(k, `${at} key`), entry(v, `${at}.${k}`)])); + }; + +const sha: Parse = (value, at) => + typeof value === "string" && /^[0-9a-f]{40}$/.test(value) ? value : fail(at, "a full commit SHA"); +const branch: Parse = (value, at) => + typeof value === "string" && value.startsWith("quest/") ? value : fail(at, "a quest branch"); +const repository = shape({ owner: name, repo: name }); +const pullRequest: Parse = (value, at) => { + const pull = shape({ owner: name, repo: name, number: count })(value, at); + return pull.number > 0 ? pull : fail(`${at}.number`, "a PR number"); +}; +const check = shape({ name: string, required: boolean, result: string, url: nullable(string) }); +const reviewStates = ["current", "diff-identical", "stale", "unknown"] as const; +const tier = oneOf(TIERS); + +const status = shape({ + url: string, + state: oneOf(["open", "closed", "merged"]), + draft: boolean, + head: string, + mergeable: string, + mergeState: string, + reviewDecision: nullable(string), + autoMerge: nullable( + shape>({ + method: string, + enabledBy: string, + enabledAt: time, + head: nullable(string), + }), + ), + mergeQueue: nullable( + shape>({ state: string, position: count, enqueuedAt: time }), + ), + landingStopped: nullable(shape>({ reason: string, actor: string, at: time })), + checks: shape({ + state: nullable(string), + passed: count, + failing: list(check), + pending: list(check), + }), + reviews: list( + shape({ + reviewer: string, + state: string, + current: boolean, + commit: nullable(string), + submittedAt: time, + url: string, + }), + ), + checkpoints: list(shape({ reviewer: string, round: count, url: string })), + reviewRecord: nullable(shape({ state: oneOf(reviewStates), head: string })), + risk: nullable( + shape>({ tier, reason: string, classified: tier, state: oneOf(reviewStates) }), + ), + reactions: list(shape({ content: string, actor: string, createdAt: time, url: string })), + threads: list( + shape({ + id: string, + path: string, + line: nullable(count), + outdated: boolean, + lastAuthor: string, + url: string, + }), + ), + signals: list(shape({ kind: oneOf(["finding", "decision"]), url: string, author: string, text: string })), + holds: list( + shape({ + label: string, + token: nullable(string), + takenAt: nullable(time), + age: nullable(string), + eventUrl: nullable(string), + }), + ), + starterHold: nullable(shape({ lastActive: time, age: string, url: string })), +}); + +const openPull = shape({ + number: count, + url: string, + branch: name, + head: nullable(name), + draft: boolean, + created: count, + updated: count, + handedBack: boolean, + body: string, +}); + +const holdings = shape({ + claims: list(shape({ branch, url: nullable(string), pull: nullable(openPull) })), + landed: mapOf(branch, sha), +}); + +const source = shape({ repository, tips: maybe(mapOf(branch, sha)) }); + +const watchPoll = shape({ + events: list(shape({ point: name, type: name, actor: name, url: name })), + cursor: name, + pollInterval: count, +}); + +const info = shape({ + login: name, + repositories: list((value, at) => + typeof value === "string" && /^[a-z\d._-]+\/[a-z\d._-]+$/.test(value) + ? value + : fail(at, "a lowercase owner/repo"), + ), +}); + +const REQUESTS: { [C in ForgeCall]: Parse } = { + status: shape({ pull: pullRequest }), + pulls: shape({ repository }), + held: shape({ + sources: shape({ upstream: source, fork: maybe(source) }), + branches: list(branch), + }), + watch: shape({ pull: pullRequest, from: nullable(name) }), +}; + +const VALUES: { [C in ForgeCall]: Parse } = { + status, + pulls: list(openPull), + held: holdings, + watch: watchPoll, +}; + +const answer = (value: Parse): Parse> => shape>({ value, asOf: nullable(time) }); diff --git a/src/core/index.ts b/src/core/index.ts index d2677d93..7ae922d9 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -120,3 +120,36 @@ export { parseRecord, parseUpload, } from "./record"; +export { + type Answer, + type Check, + type Claim, + type ClaimSource, + type ClaimSources, + FORGE_CALLS, + type Forge, + type ForgeCall, + type ForgeCalls, + type ForgeInfo, + type HoldFact, + type Holdings, + InputError, + type OpenPull, + type PullRequest, + type Reaction, + type Repository, + type Review, + type ReviewRecord, + type Signal, + type StarterHold, + type Status, + type Thread, + type WaitEvent, + type Watch, + type WatchOptions, + type WatchPoll, + forgeJson, + parseForgeAnswer, + parseForgeInfo, + parseForgeRequest, +} from "./forge"; diff --git a/src/github/claims.ts b/src/github/claims.ts index 8a246df8..81a8bf3a 100644 --- a/src/github/claims.ts +++ b/src/github/claims.ts @@ -1,56 +1,16 @@ // Who holds a quest on GitHub: its claim branch upstream or in the head fork, unless that branch is a // merged PR's head, or the earliest open PR from a branch of that name in either. -import { handedBack, landed } from "../core"; -import { type GitHub, type Repository, object, repositoryPath, string } from "./client"; - -/** An open PR, from any head repository, as the claim checks read it. */ -export interface OpenPull { - number: number; - url: string; - branch: string; - /** The head repository as `owner/repo`, or `null` once a fork is deleted. */ - head: string | null; - draft: boolean; - /** Epoch milliseconds. The earliest open PR on a branch holds the claim. */ - created: number; - /** Epoch milliseconds of the last push, comment, or edit. */ - updated: number; - /** Its body has a `## Waiting` section, so it waits on the maintainer. */ - handedBack: boolean; - body: string; -} - -/** A held quest branch, and the open PR from it if there is one. */ -export interface Claim { - branch: string; - /** The PR holding the claim: the earliest open one. */ - url: string | null; - pull: OpenPull | null; -} - -/** Which branches someone holds, and which landed branches a new claim replaces. */ -export interface Holdings { - /** Sorted by branch. */ - claims: Claim[]; - /** - * Branches in the head fork, or upstream without one, whose tip is the head of a merged PR, by - * that tip. Their work landed, so they hold nothing and a claim may replace them. - */ - landed: Map; -} - -/** A repository claim branches live in, and its `quest/*` branch tips when the caller already read them. */ -export interface Source { - repository: Repository; - tips?: Map; -} - -/** Where claims live: the upstream repository, and the fork a contributor pushes claims to, if any. */ -export interface Sources { - upstream: Source; - /** Absent when claims are pushed upstream. */ - fork?: Source; -} +import { + type Claim, + type ClaimSource, + type ClaimSources, + type Holdings, + type OpenPull, + type Repository, + handedBack, + landed, +} from "../core"; +import { type GitHub, object, repositoryPath, string } from "./client"; /** Every open PR in `repository`, from any head repository. */ export async function openPullRequests(github: GitHub, repository: Repository): Promise { @@ -97,9 +57,9 @@ export async function claimBranches(github: GitHub, repository: Repository): Pro * PR's branch still holds its quest, since that work may be wanted back. A fork's own branches and PRs * count, so a claim pushed there is seen before its PR opens. Tips a source leaves out are read here. */ -export async function held(github: GitHub, sources: Sources, branches: string[]): Promise { +export async function held(github: GitHub, sources: ClaimSources, branches: string[]): Promise { const { upstream, fork } = sources; - const read = async (source: Source) => ({ + const read = async (source: ClaimSource) => ({ repository: source.repository, tips: source.tips ?? (await claimBranches(github, source.repository)), }); diff --git a/src/github/client.ts b/src/github/client.ts index ff71ae59..2a8a4401 100644 --- a/src/github/client.ts +++ b/src/github/client.ts @@ -1,21 +1,11 @@ // The GitHub client: authenticated REST and GraphQL requests with paging, retries, rate limits, and a deadline. // No Node APIs, so it runs wherever `fetch` does; the caller supplies the token and clock. +import type { Repository } from "../core"; import { cancelled, currentContexts, latestContexts, type RollupContext, type WorkflowRun } from "./checks"; const API = "https://api.github.com"; const MAX_SLEEP = 2_147_483_647; -/** A repository on github.com. */ -export interface Repository { - owner: string; - repo: string; -} - -/** A pull request by its repository and number. */ -export interface PullRequest extends Repository { - number: number; -} - /** * What the client needs from its host: `fetch`, a clock, a way to pause, the token, where warnings * go, and what to do once the token's hourly quota is spent. diff --git a/src/github/forge.ts b/src/github/forge.ts new file mode 100644 index 00000000..af83c488 --- /dev/null +++ b/src/github/forge.ts @@ -0,0 +1,56 @@ +// The GitHub backend of the forge reads: each read as GitHub answers it, live. +import type { + Answer, + ClaimSources, + Forge, + Holdings, + OpenPull, + PullRequest, + Repository, + Status, + Watch, + WatchOptions, +} from "../core"; +import { held, openPullRequests } from "./claims"; +import { GitHub, type GitHubDependencies, object, string } from "./client"; +import { pullRequestStatus } from "./status"; +import { watchPull } from "./wait"; + +/** Reads from GitHub with the dependencies' token. */ +export class GitHubForge implements Forge { + readonly name = "GitHub"; + #viewer: Promise | undefined; + + /** `viewer` names the person reading when the token is not theirs, such as an App installation's. */ + constructor( + private readonly deps: GitHubDependencies, + viewer?: string, + ) { + if (viewer !== undefined) this.#viewer = Promise.resolve(viewer); + } + + viewer(): Promise { + this.#viewer ??= new GitHub(this.deps) + .graphql("query { viewer { login } }", {}) + .then((data) => string(object(data.viewer).login)); + return this.#viewer; + } + + async status(pull: PullRequest): Promise> { + return live(await pullRequestStatus(pull, this.deps)); + } + + async pulls(repository: Repository): Promise> { + return live(await openPullRequests(new GitHub(this.deps), repository)); + } + + async held(sources: ClaimSources, branches: string[]): Promise> { + return live(await held(new GitHub(this.deps), sources, branches)); + } + + watch(pull: PullRequest, options: WatchOptions): Watch { + return watchPull(new GitHub(this.deps, options.deadline), this.deps, pull, options.since, this); + } +} + +const live = (value: T): Answer => ({ value, asOf: null }); diff --git a/src/github/hold.ts b/src/github/hold.ts index 710b7a57..28cb151b 100644 --- a/src/github/hold.ts +++ b/src/github/hold.ts @@ -1,11 +1,10 @@ // Reading who holds a PR: its `quest:*` labels, the events that added them, and a draft its starter still holds. // Taking and releasing holds stays in the CLI. -import { handedBack, isHoldLabel, latestHold } from "../core"; +import { type HoldFact, type PullRequest, type StarterHold, handedBack, isHoldLabel, latestHold } from "../core"; import { GitHub, type GitHubDependencies, type ObjectValue, - type PullRequest, array, object, repositoryPath, @@ -63,22 +62,11 @@ export interface Snapshot { events: LabelEvent[]; } -/** A hold label on a PR, and the event that took it when the timeline still shows it. */ -export interface HoldFact { - label: string; - /** Null when the acquisition is older than the available timeline. */ - token: string | null; - takenAt: string | null; - age: string | null; - /** GitHub's verified event URL; the opaque GraphQL token is not a browser anchor. */ - eventUrl: string | null; -} - /** The PR head a hold read saw, its holds, and its starter's hold on a draft not handed back. */ export interface HoldReport { head: string; holds: HoldFact[]; - starter: { lastActive: string; age: string; url: string } | null; + starter: StarterHold | null; } /** Read `pr` and its hold labels. */ diff --git a/src/github/index.ts b/src/github/index.ts index f5b67313..dde8a9f3 100644 --- a/src/github/index.ts +++ b/src/github/index.ts @@ -1,36 +1,10 @@ -// Quest's GitHub readers for a host with no checkout, git, or Node APIs, such as a Worker: a PR's -// status as `quest status` reads it, and the claims on quest branches as `quest start` decides them. -// The caller supplies `fetch` and the token through `GitHubDependencies`. +// Quest's GitHub readers for a host with no checkout, git, or Node APIs, such as a Worker: the forge reads' +// GitHub backend, a PR's status as `quest status` reads it, and the claims on quest branches as `quest start` +// decides them. The caller supplies `fetch` and the token through `GitHubDependencies`; the read types are +// `quest/core`'s. -export { - GitHub, - GitHubDeadline, - type GitHubDependencies, - GitHubGraphQLError, - type PullRequest, - type Repository, -} from "./client"; -export { - type BaseNeeds, - type Check, - type Reaction, - type Review, - type ReviewRecord, - type Status, - type Needs, - type Thread, - pullRequestStatus, - requiredOf, -} from "./status"; -export { type HoldFact, type HoldReport } from "./hold"; -export { type Signal } from "./signals"; -export { - type Claim, - type Holdings, - type OpenPull, - type Source, - type Sources, - claimBranches, - held, - openPullRequests, -} from "./claims"; +export { GitHub, GitHubDeadline, type GitHubDependencies, GitHubGraphQLError } from "./client"; +export { GitHubForge } from "./forge"; +export { type BaseNeeds, type Needs, pullRequestStatus, requiredOf } from "./status"; +export { type HoldReport } from "./hold"; +export { claimBranches, held, openPullRequests } from "./claims"; diff --git a/src/github/online-review.ts b/src/github/online-review.ts index 34b02a97..d860ef13 100644 --- a/src/github/online-review.ts +++ b/src/github/online-review.ts @@ -2,7 +2,8 @@ // thread, and any review whose // body opens with `Automated review by `, as a reviewer posting under a person's account does. A finding is a // review thread one opens, or a `[P]` line in its review body; whoever answers it says whether it was taken. -import { type GitHub, type ObjectValue, type Repository, array, object } from "./client"; +import { type GitHub, type ObjectValue, array, object } from "./client"; +import type { Repository } from "../core"; /** One online reviewer's record on one PR. */ export interface OnlineReview { diff --git a/src/github/signals.ts b/src/github/signals.ts index 45a88d4a..4ebbbc17 100644 --- a/src/github/signals.ts +++ b/src/github/signals.ts @@ -1,19 +1,9 @@ // What holds a PR's head from landing besides its checks: an online reviewer's finding on the head that no writer has // answered, and a maintainer decision recorded in a comment after the head was committed that nothing has answered. -import { type GitHub, type ObjectValue, type Repository, array, object, string } from "./client"; +import type { Repository, Signal } from "../core"; +import { type GitHub, type ObjectValue, array, object, string } from "./client"; import { type Activity, bodyFindings, isBot, login, readActivity, reviewerOf } from "./online-review"; -/** One signal on a PR's head that holds it from landing until it is fixed or answered. */ -export interface Signal { - /** `finding`: an online reviewer's, on the head. `decision`: a marked comment newer than the head's commit. */ - kind: "finding" | "decision"; - /** The review, thread, or comment that raised it. */ - url: string; - author: string; - /** The finding's title or thread's first line, or the decision's first line. */ - text: string; -} - /** The picked heads whose signals a later commit carries unread, and when the pick was made. */ export interface Carried { heads: string[]; diff --git a/src/github/status.ts b/src/github/status.ts index 3ef6e6ed..8ea3e0e2 100644 --- a/src/github/status.ts +++ b/src/github/status.ts @@ -9,17 +9,26 @@ import { link, object, type ObjectValue, - type PullRequest, - type Repository, requirements, string, workflowKey, } from "./client"; import { appOf, checksState, contextOutcome } from "./checks"; import { EJECTED, LAND_CHECK, pinned } from "./land"; -import { type Tier, recordedRisk, reviewSection } from "../core"; -import { readHoldStatus, type HoldFact, type HoldReport } from "./hold"; -import { readSignals, type Signal } from "./signals"; +import { + type Check, + type PullRequest, + type Reaction, + type Repository, + type Review, + type ReviewRecord, + type Status, + type Thread, + recordedRisk, + reviewSection, +} from "../core"; +import { readHoldStatus } from "./hold"; +import { readSignals } from "./signals"; /** * One query covers the PR; each connection pages by its own cursor, and a @@ -70,99 +79,6 @@ const STATUS = `query($owner: String!, $repo: String!, $number: Int!, } fragment reaction on Reaction { content createdAt user { login } }`; -/** A check run or commit status on the head, as `quest status` prints it. */ -export interface Check { - name: string; - required: boolean; - /** The lowercased check-run conclusion or status, or commit-status state. */ - result: string; - url: string | null; -} - -/** A reviewer's latest submitted review. */ -export interface Review { - reviewer: string; - /** approved, changes_requested, commented, or dismissed. */ - state: string; - /** Whether the review was submitted against the current head. */ - current: boolean; - commit: string | null; - submittedAt: string; - url: string; -} - -/** A reaction on the PR or one of its reviews. */ -export interface Reaction { - content: string; - actor: string; - createdAt: string; - /** The PR or review reacted to. */ - url: string; -} - -/** An unresolved review thread. */ -export interface Thread { - id: string; - path: string; - /** The line on the current diff, or the original line once outdated. */ - line: number | null; - outdated: boolean; - lastAuthor: string; - /** The thread's latest comment. */ - url: string; -} - -/** - * The head the PR body's `## Review` section names last, the latest reviewed one: a round's record, or a line after - * it for low-severity fixes or a skip. `current` is the PR's head; `diff-identical` an earlier head whose diff from - * the base (`git diff ...`) matches the head's; `unknown` one GitHub cannot compare, such as a diff too - * large to render. - */ -export interface ReviewRecord { - state: "current" | "diff-identical" | "stale" | "unknown"; - head: string; -} - -/** Everything `quest status` reports about a PR. */ -export interface Status { - url: string; - state: "open" | "closed" | "merged"; - draft: boolean; - head: string; - mergeable: string; - mergeState: string; - reviewDecision: string | null; - /** `head` is the head it was enabled on, or null when that cannot be told; see {@link enabledHead}. */ - autoMerge: { method: string; enabledBy: string; enabledAt: string; head: string | null } | null; - mergeQueue: { state: string; position: number; enqueuedAt: string } | null; - /** - * The latest exit from the merge queue, auto-merge, or `quest land`'s queue, and the reason for it; - * null once the PR is queued again. - */ - landingStopped: { reason: string; actor: string; at: string } | null; - checks: { state: string | null; passed: number; failing: Check[]; pending: Check[] }; - /** Each reviewer's latest submitted review, oldest first. */ - reviews: Review[]; - /** The design checkpoints online reviewers put on the head, as {@link checkpoints} finds them. */ - checkpoints: { reviewer: string; round: number; url: string }[]; - /** Null when the `## Review` section names no full SHA. */ - reviewRecord: ReviewRecord | null; - /** - * The head's risk tier as the `## Review` record names it, and the classifier's own tier, lower when a reviewer - * raised it; null when the record names none. `state` is the review record's, which a line after it carries to a - * later head, else `current` when the record names the head and `stale` when not. - */ - risk: { tier: Tier; reason: string; classified: Tier; state: ReviewRecord["state"] } | null; - reactions: Reaction[]; - /** Unresolved review threads, oldest first. */ - threads: Thread[]; - /** What holds the head from landing: online reviewers' unanswered findings on it and newer maintainer decisions. */ - signals: Signal[]; - /** Ownership facts read by the same client as the state commands. */ - holds: HoldFact[]; - starterHold: HoldReport["starter"]; -} - /** What a repository's base branch requires, as {@link requiredOf} read it for that repository and branch. */ export interface BaseNeeds extends Repository { branch: string; diff --git a/src/github/wait.ts b/src/github/wait.ts new file mode 100644 index 00000000..0750fbbf --- /dev/null +++ b/src/github/wait.ts @@ -0,0 +1,718 @@ +// Polls of a pull request's activity on GitHub, as `quest wait` reports it: the GitHub backend's watch. +import { type Answer, InputError, type PullRequest, type Watch, type WaitEvent, type WatchPoll } from "../core"; +import { + actor, + array, + currentChecks, + type GitHub, + type GitHubDependencies, + link, + object, + type ObjectValue, + string, +} from "./client"; +import { + BRANCH_UPDATES, + classifyCheck, + enabledHead, + type Needs, + type Reported, + reported, + requiredOf, + unreported, +} from "./status"; + +/** The REST page size. A full last page cannot show by itself that a next page has appeared. */ +const PAGE = 100; +/** How often setup rereads repository activity while GitHub has yet to list the head's push. */ +const LISTING_POLL = 15_000; + +/** Repository activity types a person's push makes; merges into the branch also move it (`BRANCH_UPDATES`). */ +const PUSHES = ["push", "force_push", "branch_creation"]; +const SHA = /^[a-f\d]{7,40}$/i; +/** The timeline records a force push a few seconds after repository activity (1-2s observed). */ +const TIMELINE_LAG = 60_000; +/** Reactions on the PR body and on each review; the newest 100 per subject are enough to spot new ones. */ +const REACTIONS = `query($owner: String!, $repo: String!, $number: Int!, $after: String) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + reactions(last: 100) { nodes { ...reaction } } + reviews(first: 100, after: $after) { + pageInfo { hasNextPage endCursor } + nodes { url reactions(last: 100) { nodes { ...reaction } } } + } + } + } +} +fragment reaction on Reaction { id content createdAt user { login } }`; +/** The head's check runs and commit statuses, with whether the base branch requires each. */ +const CHECKS = `query($owner: String!, $repo: String!, $number: Int!, $after: String) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + baseRefName + headRefOid + headRefName + headRepository { nameWithOwner } + autoMergeRequest { enabledAt commitBody enabledBy { login } } + commits(last: 1) { nodes { commit { oid statusCheckRollup { + contexts(first: 100, after: $after) { + pageInfo { hasNextPage endCursor } + nodes { + __typename + ... on CheckRun { + databaseId name status conclusion completedAt detailsUrl isRequired(pullRequestNumber: $number) + checkSuite { databaseId status app { databaseId } workflowRun { file { path repositoryName } } } + } + ... on StatusContext { context state createdAt targetUrl isRequired(pullRequestNumber: $number) } + } + } + } } } } + } + } +}`; + +interface Activity { + point: string; + time: number; + type: string; + actor: string; + url: string; + id: string; +} + +/** Each source is read separately, so each keeps its own position. */ +type Source = "timeline" | "replies" | "reactions" | "edits"; +const SOURCES: Source[] = ["timeline", "replies", "reactions", "edits"]; +/** The newest event time read from a source, and the IDs of events at that time. */ +interface Mark { + time: number; + ids: string[]; +} + +/** A cursor is a snapshot, since git timestamps cannot describe push order. */ +interface Cursor { + pr: string; + marks: Record; + commits: string[]; + /** Force pushes at or before the starting point, at their repository-activity time. */ + pushes: { sha: string; time: number }[]; + /** Check results reached at or after `since` are reported once per head, as `:`. */ + checks: { since: number; reported: string[] }; +} + +/** One check run or commit status on the head, with its result once it has one. */ +interface Check extends Reported { + required: boolean; + url: string | null; + /** A GitHub Actions job whose workflow run has not finished, so it may still create jobs. */ + running: boolean; + result?: { outcome: "passed" | "failed"; point: string; time: number }; +} + +/** Names the person waiting. */ +interface Viewer { + viewer(): Promise; +} + +/** + * Polls of `pr`'s activity since `since`, on `github` and bounded by its deadline. The first poll reads the starting + * point; each later one rereads only what may have changed, conditionally where GitHub allows it. `identity` names + * the person whose own label changes, replies, reactions, and edits never wake them. + */ +export function watchPull( + github: GitHub, + deps: GitHubDependencies, + pr: PullRequest, + since: string | undefined, + identity: Viewer, +): Watch { + const progress = { resume: since }; + let polling: (() => Promise) | undefined; + return { + get resume() { + return progress.resume; + }, + async poll(): Promise> { + polling ??= await start(github, deps, pr, progress.resume, identity, progress); + const value = await polling(); + // The next poll starts after what this one reported. + if (value.events.length) { + progress.resume = value.cursor; + polling = undefined; + } + return { value, asOf: null }; + }, + }; +} + +/** Read the starting point, returning one poll from it. */ +async function start( + github: GitHub, + deps: GitHubDependencies, + pr: PullRequest, + from: string | undefined, + identity: Viewer, + progress: { resume?: string }, +): Promise<() => Promise> { + // Cursors are case-sensitive base64url; a recased one would otherwise be misreported as a bad timestamp. + if (from && /^q1\./i.test(from) && !from.startsWith("q1.")) + throw new InputError("invalid --since cursor: cursors start with lower-case q1.; pass it exactly as printed"); + if (from && !from.startsWith("q1.") && !SHA.test(from)) { + try { + timestamp(from); + } catch (error) { + throw new InputError((error as Error).message); + } + } + const name = `${pr.owner}/${pr.repo}#${pr.number}`; + const base = `/repos/${encodeURIComponent(pr.owner)}/${encodeURIComponent(pr.repo)}`; + const prUrl = `https://github.com/${pr.owner}/${pr.repo}/pull/${pr.number}`; + + let cursor: Cursor; + let historical: Activity[] = []; + const baselineCommits = new Set(); + let pushedTips: string[] = []; + if (from?.startsWith("q1.")) { + cursor = decodeCursor(from, name); + } else { + const pullResponse = await github.request(`${base}/pulls/${pr.number}`); + const pull = object(await pullResponse.json()); + const head = object(pull.head); + const currentSha = string(head.sha); + // Until setup finishes, a timeout resumes from this head rather than whatever is pushed next. + progress.resume = from ?? currentSha; + // Verify the listing belongs to this exact head before treating it as + // baseline membership. A racing push must never be silently swallowed. + let commitsPath: string | undefined = `${base}/pulls/${pr.number}/commits?per_page=100`; + let listedHead: string | undefined; + while (commitsPath) { + const { rows, response } = await github.list(commitsPath); + for (const commit of rows) { + listedHead = string(commit.sha); + if (!fullSha(listedHead)) throw new Error("invalid GitHub commit SHA"); + baselineCommits.add(listedHead); + } + commitsPath = link(response, "next"); + } + if (listedHead !== currentSha) { + throw new Error( + "cannot snapshot PR commits: head changed during setup, or GitHub's 250-commit listing limit was reached; rerun after checking the PR head", + ); + } + const point = from ?? currentSha; + const shaPoint = SHA.test(point); + const time = shaPoint ? undefined : timestamp(point); + // A merge into the branch, such as GitHub's Update branch, can also have moved the head to the point. + const moved = (row: ObjectValue) => BRANCH_UPDATES.includes(string(row.activity_type)); + const isPoint = (row: ObjectValue) => moved(row) && string(row.after).startsWith(point.toLowerCase()); + let activities: ObjectValue[] = []; + if (head.repo !== null) { + const headRepo = object(head.repo); + const fullName = string(headRepo.full_name); + if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) throw new Error("invalid GitHub head repository"); + let warned = false; + for (;;) { + activities = []; + let path: string | undefined = + `/repos/${fullName}/activity?ref=${encodeURIComponent(string(head.ref))}&per_page=100`; + while (path) { + const { rows, response } = await github.list(path); + activities.push(...rows); + if (shaPoint ? rows.some(isPoint) : rows.some((row) => timestamp(string(row.timestamp)) <= time!)) + break; + path = link(response, "next"); + } + // The head was pushed, but GitHub lists a push seconds to minutes later (14s-6min observed), + // so a wait started right after pushing reads the listing again until the push appears. + if (!shaPoint || activities.some(isPoint) || !currentSha.startsWith(point.toLowerCase())) break; + if (!warned) deps.warn(`GitHub has not listed the push of ${point} yet; waiting for it`); + warned = true; + await github.pause(LISTING_POLL); + } + } else if (shaPoint) { + throw new Error("head repository was deleted; pass a timestamp with --since"); + } + const pushed = activities.filter((row) => PUSHES.includes(string(row.activity_type))); + const match = shaPoint ? activities.find(isPoint) : undefined; + if (shaPoint && !match) throw new Error(`cannot resolve push time for ${point}; pass a timestamp with --since`); + const since = time ?? timestamp(string(match!.timestamp)); + // An explicit timestamp includes its own instant; a SHA point excludes its own push. + const after = (row: ObjectValue) => { + const pushedAt = timestamp(string(row.timestamp)); + return shaPoint ? pushedAt > since : pushedAt >= since; + }; + // Force pushes are reported from the timeline alone, so one push prints once. + const forced = pushed.filter((row) => string(row.activity_type) === "force_push"); + cursor = { + pr: name, + marks: { + timeline: { time: since, ids: [] }, + replies: { time: since, ids: [] }, + reactions: { time: since, ids: [] }, + edits: { time: since, ids: [] }, + }, + commits: [], + pushes: forced + .filter((row) => !after(row)) + .map((row) => ({ sha: string(row.after), time: timestamp(string(row.timestamp)) })), + checks: { since, reported: [] }, + }; + const plain = pushed.filter((row) => string(row.activity_type) !== "force_push" && after(row)); + // A push racing setup is reported once, as a push, not again as a new commit. + pushedTips = plain.map((row) => string(row.after)); + for (const sha of pushedTips) baselineCommits.add(sha); + // A merge into the branch after the point is not a push, so it is reported as its new commit. + for (const row of activities) + if ( + moved(row) && + !PUSHES.includes(string(row.activity_type)) && + after(row) && + !pushedTips.includes(string(row.after)) + ) + baselineCommits.delete(string(row.after)); + historical = plain.map((row) => ({ + point: string(row.timestamp), + time: timestamp(string(row.timestamp)), + type: "pushed", + actor: actor(row.actor), + url: `https://github.com/${string(object(head.repo).full_name)}/commit/${string(row.after)}`, + id: `push:${string(row.after)}:${string(row.timestamp)}`, + })); + } + + const seenCommits = new Set([...baselineCommits, ...cursor.commits]); + // Activity found before a timeout is not printed, so resuming must find it again; + // a push found during setup comes back as its new commit. + progress.resume = encodeCursor({ + ...cursor, + commits: [...seenCommits].filter((sha) => !pushedTips.includes(sha)), + }); + const seen = Object.fromEntries(SOURCES.map((source) => [source, new Set(cursor.marks[source].ids)])) as Record< + Source, + Set + >; + const fresh = (source: Source, event: Activity) => { + const mark = cursor.marks[source]; + return event.time > mark.time || (event.time === mark.time && !seen[source].has(event.id)); + }; + /** + * Read every page once, then poll the last page conditionally, following it when it fills. A 304 + * has no Link header and the ETag covers only the body, so a full last page is reread whole to + * learn of a next one. + */ + const pager = (first: string) => { + let path = first; + let etag: string | undefined; + return async (): Promise => { + const rows: ObjectValue[] = []; + for (;;) { + const response = await github.request(path, { etag }); + if (response.status === 304) { + if (!etag) throw new Error("unexpected GitHub 304 without a cached response"); + return rows; + } + const page = array(await response.json()); + rows.push(...page); + const next = link(response, "next"); + if (!next) { + etag = page.length < PAGE ? (response.headers.get("etag") ?? undefined) : undefined; + return rows; + } + path = next; + etag = undefined; + } + }; + }; + const graphql = (query: string, after: string | null) => + github.graphql(query, { owner: pr.owner, repo: pr.repo, number: pr.number, after }); + /** REST has no endpoint for reactions on reviews. */ + const reactions = async (): Promise => { + const events: Activity[] = []; + let after: string | null = null; + do { + const data = await graphql(REACTIONS, after); + const pull = object(object(data.repository).pullRequest); + const reviews = object(pull.reviews); + const reacted = (owner: ObjectValue, url: string) => + array(object(owner.reactions).nodes).map((row) => reaction(row, url)); + if (after === null) events.push(...reacted(pull, prUrl)); + for (const review of array(reviews.nodes)) events.push(...reacted(review, string(review.url))); + const page = object(reviews.pageInfo); + after = page.hasNextPage === true ? string(page.endCursor) : null; + } while (after !== null); + return events; + }; + /** GraphQL says which checks the base branch requires, through branch protection or rulesets. */ + const checks = async (): Promise< + { head: string; base: string; checks: Check[]; unfinished: boolean; pull: ObjectValue } | undefined + > => { + const rows: ObjectValue[] = []; + let head: string | undefined; + let after: string | null = null; + let pull: ObjectValue; + do { + pull = object(object((await graphql(CHECKS, after)).repository).pullRequest); + const commit = object(array(object(pull.commits).nodes)[0]?.commit); + // A push racing these pages is read whole on the next poll. + if (commit.oid !== pull.headRefOid || (head !== undefined && commit.oid !== head)) return undefined; + head = string(commit.oid); + if (!fullSha(head)) throw new Error("invalid GitHub head SHA"); + if (commit.statusCheckRollup === null) break; + const contexts = object(object(commit.statusCheckRollup).contexts); + rows.push(...array(contexts.nodes)); + const page = object(contexts.pageInfo); + after = page.hasNextPage === true ? string(page.endCursor) : null; + } while (after !== null); + const current = await currentChecks(github, pr, head!, rows); + // A replacing run may have no check run yet, so an unfinished run it read keeps the head busy. + const unfinished = current.runs?.some((run) => run.status !== "completed") ?? false; + return { head: head!, base: string(pull.baseRefName), checks: current.checks.map(check), unfinished, pull }; + }; + /** + * What the base branch requires, read once per wait, as `quest status` reads it. Only a requirement + * says whether a missing check has yet to start, or whether the repository requires none. + */ + const known = new Map(); + const required = async (branch: string): Promise => { + const cached = known.get(branch); + if (cached) return cached; + const needs = await requiredOf(github, pr, branch); + known.set(branch, needs); + return needs; + }; + + /** The head each auto-merge request was enabled on, by when it was enabled, once that can be told. */ + const enabledHeads = new Map(); + /** Warnings already printed, so a forbidden activity listing warns once per wait rather than per poll. */ + const warned = new Set(); + const warnOnce = (message: string) => { + if (!warned.has(message)) deps.warn(message); + warned.add(message); + }; + /** Auto-merge left on for a head other than `head`, reported once per head and request. */ + const movedAutoMerge = async (head: string, pull: ObjectValue): Promise => { + if (pull.autoMergeRequest == null) return []; + const request = object(pull.autoMergeRequest); + const enabledAt = string(request.enabledAt); + const id = `${head}:auto-merge:${enabledAt}`; + if (cursor.checks.reported.includes(id)) return []; + const enabled = enabledHeads.get(enabledAt) ?? (await enabledHead(github, pull, warnOnce)); + if (enabled === null) return []; + enabledHeads.set(enabledAt, enabled); + if (enabled === head) return []; + const point = new Date(deps.now()).toISOString(); + const url = `${prUrl}/commits/${enabled}`; + return [{ point, time: deps.now(), type: "auto-merge:moved", actor: actor(request.enabledBy), url, id }]; + }; + + const timeline = pager(`${base}/issues/${pr.number}/timeline?per_page=${PAGE}`); + // `since` excludes its own instant and filters by update time, which is never before + // creation; start a second early so unseen replies at the mark's second are still read. + const comments = pager( + `${base}/pulls/${pr.number}/comments?per_page=${PAGE}&since=${new Date(cursor.marks.replies.time - 1000).toISOString()}`, + ); + // Issue comments are ordered by creation: an old comment can be edited on an + // earlier page, so reread this update-filtered list from its first page. + const edits = async () => { + const rows: ObjectValue[] = []; + let path: string | undefined = + `${base}/issues/${pr.number}/comments?per_page=${PAGE}&since=${new Date(cursor.marks.edits.time - 1000).toISOString()}`; + while (path) { + const page = await github.list(path); + rows.push(...page.rows); + path = link(page.response, "next"); + } + return rows; + }; + const found: Record = { timeline: historical, replies: [], reactions: [], edits: [] }; + return async () => { + github.pollInterval = 0; + const labels: Activity[] = []; + for (const row of await timeline()) { + const type = string(row.event); + if (type === "committed") { + const sha = string(row.sha); + if (!fullSha(sha)) throw new Error("invalid GitHub committed SHA"); + if (!seenCommits.has(sha)) { + found.timeline.push({ + point: sha, + time: cursor.marks.timeline.time, + type: "committed", + actor: actor(row.actor ?? row.committer), + url: string(row.html_url), + id: `commit:${sha}`, + }); + } + seenCommits.add(sha); + continue; + } + for (const event of timelineActivities(row, prUrl)) { + if ( + type === "head_ref_force_pushed" && + cursor.pushes.some( + (push) => + push.sha === row.commit_id && + event.time >= push.time && + event.time - push.time <= TIMELINE_LAG, + ) + ) + continue; + if (fresh("timeline", event)) (LABELS.includes(type) ? labels : found.timeline).push(event); + } + } + const replies = await comments(); + const events = await reactions(); + const viewer = await identity.viewer(); + // The waiter's own label changes, replies, and reactions never wake it. + found.timeline.push(...labels.filter((event) => event.actor !== viewer)); + for (const row of replies) { + // A thread's first comment belongs to a review, which the timeline reports. + if (row.in_reply_to_id === undefined || row.in_reply_to_id === null) continue; + const event = timedActivity(row, "replied", "created_at", prUrl); + if (event.actor !== viewer && fresh("replies", event)) found.replies.push(event); + } + found.reactions.push(...events.filter((event) => event.actor !== viewer && fresh("reactions", event))); + for (const row of await edits()) { + if (timestamp(string(row.updated_at)) <= timestamp(string(row.created_at))) continue; + const event = timedActivity(row, "edited", "updated_at", prUrl); + // GitHub timestamps have second precision: two different edits in that + // second remain distinct, without storing the comment text in a cursor. + event.id += `:${await sha256(string(row.body))}`; + if (event.actor !== viewer && fresh("edits", event)) found.edits.push(event); + } + // Check results are state rather than a log, so each poll reads them afresh. + const head = await checks(); + const reached = head + ? [ + ...checkActivities(head, await required(head.base), cursor.checks, prUrl), + ...(await movedAutoMerge(head.head, head.pull)), + ] + : []; + + if (reached.length || SOURCES.some((source) => found[source].length)) { + const marks = Object.fromEntries( + SOURCES.map((source) => { + const mark = cursor.marks[source]; + const time = Math.max(mark.time, ...found[source].map((event) => event.time)); + const ids = [ + ...(time === mark.time ? mark.ids : []), + ...found[source].filter((event) => event.time === time).map((event) => event.id), + ]; + return [source, { time, ids: [...new Set(ids)] }]; + }), + ) as Record; + const nextCursor = encodeCursor({ + pr: name, + marks, + commits: [...seenCommits], + pushes: cursor.pushes.filter((push) => push.time + TIMELINE_LAG >= marks.timeline.time), + checks: { + since: cursor.checks.since, + // A new head starts over, so only the current head's reports are kept. + reported: [ + ...cursor.checks.reported.filter((id) => !head || id.startsWith(`${head.head}:`)), + ...reached.map((event) => event.id), + ], + }, + }); + const all = [...SOURCES.flatMap((source) => found[source]), ...reached].sort((a, b) => a.time - b.time); + const unique = [...new Map(all.map((event) => [event.id, event])).values()]; + return { + events: unique.map(({ point, type, actor, url }): WaitEvent => ({ point, type, actor, url })), + cursor: nextCursor, + pollInterval: github.pollInterval, + }; + } + return { events: [], cursor: progress.resume!, pollInterval: github.pollInterval }; + }; +} + +// A dequeue or a disabled auto-merge needs the agent. A merge also leaves the queue, a second before "merged". +// A label-driven queue dequeues by removing its label. +const LABELS = ["labeled", "unlabeled"]; +const WAKES = [ + ...LABELS, + "reviewed", + "commented", + "merged", + "closed", + "head_ref_force_pushed", + "removed_from_merge_queue", + "auto_merge_disabled", +]; + +function timelineActivities(row: ObjectValue, prUrl: string): Activity[] { + const type = string(row.event); + if (type === "line-commented" || type === "commit-commented") { + return array(row.comments).map((comment) => timedActivity(comment, type, "created_at", prUrl)); + } + if (!WAKES.includes(type)) return []; + if (LABELS.includes(type)) { + const event = timedActivity(row, type, "created_at", prUrl); + return [{ ...event, type: `${type}:${string(object(row.label).name).replace(/\s/g, "_")}` }]; + } + return [timedActivity(row, type, type === "reviewed" ? "submitted_at" : "created_at", prUrl)]; +} + +/** A check run or commit status, classified as `quest status` does, with when it finished. */ +function check(row: ObjectValue): Check { + const run = row.__typename === "CheckRun"; + const { check: classified, outcome } = classifyCheck(row); + const suite = run && row.checkSuite ? object(row.checkSuite) : undefined; + const found: Check = { + ...reported(row), + required: classified.required, + url: classified.url, + running: suite?.workflowRun ? suite.status !== "COMPLETED" : false, + }; + if (outcome === "pending") return found; + const point = string(run ? row.completedAt : row.createdAt); + found.result = { outcome: outcome === "passed" ? "passed" : "failed", point, time: timestamp(point) }; + return found; +} + +/** + * The head's first required failure, and every required check passing once the head is idle, each + * reported once per head when reached at or after the starting point. A base branch that requires + * no checks requires them all. + */ +function checkActivities( + { head, checks: all, unfinished }: { head: string; checks: Check[]; unfinished: boolean }, + needs: Needs, + state: Cursor["checks"], + prUrl: string, +): Activity[] { + const inWorkflow = (entry: Check) => entry.workflow !== undefined && needs.workflows.includes(entry.workflow); + const required = + needs.checks.length || needs.workflows.length + ? all.filter((entry) => entry.required || inWorkflow(entry)) + : all; + const reached = ( + outcome: "passed" | "failed", + entry: Check | undefined, + optional = false, + at = entry?.result, + ): Activity[] => { + const id = optional ? `${head}:optional:${entry?.name}:${entry?.url}:${at?.point}` : `${head}:${outcome}`; + if (!entry?.result || !at || at.time < state.since || state.reported.includes(id)) return []; + return [ + { + point: at.point, + time: at.time, + type: `${optional ? "check" : "checks"}:${outcome}`, + actor: entry.name.replace(/\s/g, "_"), + url: entry.url ?? `${prUrl}/checks`, + id, + }, + ]; + }; + const settled = required.flatMap((entry) => (entry.result ? [{ ...entry, result: entry.result }] : [])); + settled.sort((a, b) => a.result.time - b.result.time); + const failed = settled.find((entry) => entry.result.outcome === "failed" && entry.result.time >= state.since); + // A pass waits for the head to go idle, including jobs a running workflow + // may still create. Its date is the last completion, but its name and link + // always identify a required check that passed. + const idle = + !unfinished && all.every((entry) => entry.result && !entry.running) && unreported(all, needs).length === 0; + const passed = + idle && settled.length === required.length && settled.every((entry) => entry.result.outcome === "passed") + ? settled.at(-1) + : undefined; + const last = idle + ? all.reduce( + (latest, entry) => (!latest || entry.result!.time >= latest.result!.time ? entry : latest), + undefined, + ) + : undefined; + const optional = all.filter((entry) => !required.includes(entry) && entry.result?.outcome === "failed"); + return [ + ...reached("failed", failed), + ...optional.flatMap((entry) => reached("failed", entry, true)), + ...reached("passed", passed, false, last?.result), + ]; +} + +function timedActivity(row: ObjectValue, type: string, timeField: string, fallback: string): Activity { + const point = string(row[timeField]); + const id = row.id; + if (typeof id !== "number" && typeof id !== "string") throw new Error("missing GitHub event ID"); + return { + point, + time: timestamp(point), + type, + actor: actor(row.actor ?? row.user), + url: row.html_url === undefined ? fallback : string(row.html_url), + id: `${type}:${id}`, + }; +} + +function reaction(row: ObjectValue, url: string): Activity { + const point = string(row.createdAt); + return { + point, + time: timestamp(point), + type: `reacted:${string(row.content).toLowerCase()}`, + actor: actor(row.user), + url, + id: `reacted:${string(row.id)}`, + }; +} + +function timestamp(value: string): number { + const result = Date.parse(value); + if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) || !Number.isFinite(result)) + throw new Error(`invalid timestamp: ${value}; use an ISO 8601 timestamp, a pushed SHA, or a returned cursor`); + return result; +} + +function fullSha(value: unknown): boolean { + return typeof value === "string" && /^[a-f\d]{40}$/i.test(value); +} + +function encodeCursor(cursor: Cursor): string { + const bytes = new TextEncoder().encode(JSON.stringify(cursor)); + const base64 = btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join("")); + return `q1.${base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`; +} + +function decodeCursor(value: string, pr: string): Cursor { + try { + const binary = atob(value.slice(3).replace(/-/g, "+").replace(/_/g, "/")); + const text = new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (c) => c.charCodeAt(0))); + const parsed = object(JSON.parse(text)); + const marks = object(parsed.marks); + const checks = object(parsed.checks); + // Older resumable cursors predate edited-comment tracking. Start that + // source at the original baseline so an edit is never silently skipped. + marks.edits ??= { time: checks.since, ids: [] }; + if ( + parsed.pr !== pr || + !SOURCES.every((source) => { + const mark = object(marks[source]); + return ( + typeof mark.time === "number" && + Number.isFinite(mark.time) && + Array.isArray(mark.ids) && + mark.ids.every((id) => typeof id === "string") + ); + }) || + !Array.isArray(parsed.commits) || + !parsed.commits.every(fullSha) || + !Array.isArray(parsed.pushes) || + !parsed.pushes.every((push: ObjectValue | null) => fullSha(push?.sha) && Number.isFinite(push?.time)) || + !Number.isFinite(checks.since) || + !Array.isArray(checks.reported) || + !checks.reported.every((id) => typeof id === "string") + ) + throw new Error(); + return parsed as unknown as Cursor; + } catch { + throw new InputError("invalid --since cursor, or cursor belongs to another pull request"); + } +} + +/** The SHA-256 of `text`, in hex. */ +async function sha256(text: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); +} diff --git a/test/online-review.test.ts b/test/online-review.test.ts index 6ffc9dfc..6431f7ac 100644 --- a/test/online-review.test.ts +++ b/test/online-review.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "vitest"; -import type { GitHub, Repository } from "../src/github/client"; +import type { GitHub } from "../src/github/client"; +import type { Repository } from "../src/core"; import { type Activity, bodyFindings, classify, onlineReviews, readActivity } from "../src/github/online-review"; import { readSignals } from "../src/github/signals"; diff --git a/test/start.test.ts b/test/start.test.ts index e6d8aac5..b8ae8dce 100644 --- a/test/start.test.ts +++ b/test/start.test.ts @@ -11,6 +11,7 @@ import { describe, expect, test, vi } from "vitest"; import { claims, openDrafts, target } from "../src/cli/claims"; import { githubRepository, readRemote, remoteRepository } from "../src/cli/github"; import { type GitHubDependencies, type ObjectValue } from "../src/github/client"; +import { GitHubForge } from "../src/github/forge"; import { type Output, main } from "../src/cli/main"; import { Refusal, releaseQuest, startQuest } from "../src/cli/start"; import { ago } from "../src/github/hold"; @@ -192,7 +193,11 @@ class FakeGitHub { } function deps(github: FakeGitHub, warnings: string[] = []) { - return { github: () => github.deps(), warn: (message: string) => warnings.push(message) }; + return { + github: () => github.deps(), + forge: async () => new GitHubForge(github.deps()), + warn: (message: string) => warnings.push(message), + }; } /** Commit `files` in `work`, where `null` deletes one, and push them to origin's default branch. */ @@ -778,6 +783,7 @@ test("openDrafts skips drafts with a warning when GitHub cannot be read", async github: () => { throw new Error("set GH_TOKEN or GITHUB_TOKEN, or sign in with gh auth login"); }, + forge: async () => new GitHubForge(offline.github()), warn: (message: string) => warnings.push(message), }; expect(await openDrafts(work, "origin", offline)).toEqual([]); diff --git a/test/usage.test.ts b/test/usage.test.ts index 7fb6d3ba..b671d2c9 100644 --- a/test/usage.test.ts +++ b/test/usage.test.ts @@ -808,6 +808,7 @@ describe("usage", () => { quota: "wait" as const, warn: () => {}, }), + forge: () => Promise.reject(new Error("usage reads no forge")), warn: () => {}, sessions: (since: Date, ssh: string[]) => { calls.push([since, ssh]); diff --git a/test/wait.test.ts b/test/wait.test.ts index ff46f594..a74de7e4 100644 --- a/test/wait.test.ts +++ b/test/wait.test.ts @@ -5,9 +5,11 @@ import { join } from "node:path"; import { expect, test } from "vitest"; import { main } from "../src/cli/main"; -import { GitHubInputError, pullRequest } from "../src/cli/github"; +import { InputError } from "../src/core"; +import { pullRequest } from "../src/cli/github"; +import { GitHubForge } from "../src/github/forge"; import { type GitHubDependencies } from "../src/github/client"; -import { waitForActivity, WaitTimeout } from "../src/cli/wait"; +import { waitForActivity, WaitTimeout, type WaitOptions } from "../src/cli/wait"; const A = "a".repeat(40); const B = "b".repeat(40); @@ -211,6 +213,7 @@ function setup( } if (parsed.pathname === "/graphql") { const body = JSON.parse(String(init?.body)) as { query: string }; + if (body.query === "query { viewer { login } }") return response({ data: { viewer: { login: "waiter" } } }); if (body.query.includes("statusCheckRollup")) { checkCalls.push({ ...call, body }); return side.checks?.shift() ?? checks(); @@ -263,6 +266,11 @@ function setup( return { deps, calls, sideCalls, checkCalls, editCalls, ruleCalls, sleeps, warnings, responses }; } +/** Wait on GitHub, with the fixture's clock. */ +function waitOn(pull: typeof pr, options: WaitOptions, deps: GitHubDependencies): Promise { + return waitForActivity(pull, options, new GitHubForge(deps), deps); +} + function graphql(fixture: ReturnType) { return fixture.sideCalls .filter((call) => call.path === "/graphql") @@ -275,7 +283,7 @@ function cursor(lines: string[]): string { test("default point includes reviews already submitted on the current head and uses the fork's push time", async () => { const fixture = setup([pull(), response([pushed()]), response([committed(A), reviewed()])]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch( /^2026-10-07T12:00:00Z reviewed reviewer https:\/\/github.com\/example\/project\/pull\/1#pullrequestreview-1 q1\./, @@ -301,7 +309,7 @@ test("a plain push is detected by new SHA regardless of git dates, with conditio ], [A], ); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(new RegExp(`^${B} committed A_Person `)); expect(fixture.sleeps).toEqual([300_000, 300_000]); @@ -337,7 +345,7 @@ test("force pushes, comments, inline comments, merges, closes and dequeues are p event("auto_merge_enabled", 10), ]), ]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines.map((line) => line.split(" ")[1])).toEqual([ "head_ref_force_pushed", "commented", @@ -368,7 +376,7 @@ test("label changes wake the waiter by label name, except the waiter's own", asy label("labeled", 3, "needs review", "person"), ]), ]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines.map((line) => line.split(" ").slice(0, 4).join(" "))).toEqual([ "2026-10-07T12:00:00Z unlabeled:merge github-actions[bot] https://github.com/example/project/pull/1", "2026-10-07T12:00:00Z labeled:needs_review person https://github.com/example/project/pull/1", @@ -378,16 +386,16 @@ test("label changes wake the waiter by label name, except the waiter's own", asy test("a resume cursor catches same-second activity without replaying events or commits", async () => { const first = setup([pull(), response([pushed()]), response([committed(A), reviewed(1)])]); - const point = cursor(await waitForActivity(pr, {}, first.deps)); + const point = cursor(await waitOn(pr, {}, first.deps)); const second = setup([response([committed(A), reviewed(1), reviewed(2), committed(B)])]); - const lines = await waitForActivity(pr, { since: point }, second.deps); + const lines = await waitOn(pr, { since: point }, second.deps); expect(lines).toHaveLength(2); expect(lines[0].split(" ")).toHaveLength(4); expect(lines[1].split(" ")).toHaveLength(5); expect(lines.some((line) => line.includes("review-1"))).toBe(false); expect(lines.some((line) => line.startsWith(B))).toBe(true); const third = setup([response([committed(A), reviewed(1), reviewed(2), committed(B), committed(C)])]); - const later = await waitForActivity(pr, { since: cursor(lines) }, third.deps); + const later = await waitOn(pr, { since: cursor(lines) }, third.deps); expect(later).toHaveLength(1); expect(later[0]).toMatch(new RegExp(`^${C} committed `)); }); @@ -402,7 +410,7 @@ test("historical timestamp and SHA starts detect pushes through repository activ ], [A, B], ); - const lines = await waitForActivity(pr, { since }, fixture.deps); + const lines = await waitOn(pr, { since }, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain( `2026-10-07T12:05:00Z pushed author https://github.com/contributor/fork/commit/${B}`, @@ -412,7 +420,7 @@ test("historical timestamp and SHA starts detect pushes through repository activ test("an explicit timestamp includes a push at that instant", async () => { const fixture = setup([pull(undefined, B), response([pushed(B)]), response([committed(A), committed(B)])], [A, B]); - const lines = await waitForActivity(pr, { since: POINT }, fixture.deps); + const lines = await waitOn(pr, { since: POINT }, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain(`${POINT} pushed author https://github.com/contributor/fork/commit/${B}`); }); @@ -430,7 +438,7 @@ test("a historical force push prints once, from the timeline", async () => { ], [B], ); - const lines = await waitForActivity(pr, { since: POINT }, fixture.deps); + const lines = await waitOn(pr, { since: POINT }, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:05:02Z head_ref_force_pushed author /); }); @@ -445,26 +453,26 @@ test("the force push that created the starting head is not activity, even after ], [B], ); - const lines = await waitForActivity(pr, {}, first.deps); + const lines = await waitOn(pr, {}, first.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain("review-1"); const second = setup([ response([committed(B), reviewed(1, "2026-10-07T12:05:01Z"), forcePushed(B, "2026-10-07T12:05:02Z"), later]), ]); - const resumed = await waitForActivity(pr, { since: cursor(lines) }, second.deps); + const resumed = await waitOn(pr, { since: cursor(lines) }, second.deps); expect(resumed).toHaveLength(1); expect(resumed[0]).toContain("review-2"); }); test("a timed-out wait prints a cursor that still reports a push landing before the retry", async () => { const first = setup([pull(), response([pushed()]), response([committed(A)])]); - const timeout = await waitForActivity(pr, { timeout: 10 }, first.deps).catch((error: unknown) => error); + const timeout = await waitOn(pr, { timeout: 10 }, first.deps).catch((error: unknown) => error); expect(timeout).toBeInstanceOf(WaitTimeout); const point = (timeout as WaitTimeout).cursor!; expect(point).toMatch(/^q1\./); // Rerunning without the cursor would take B as its starting head and stay silent. const second = setup([response([committed(A), committed(B)])]); - const lines = await waitForActivity(pr, { since: point }, second.deps); + const lines = await waitOn(pr, { since: point }, second.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(new RegExp(`^${B} committed `)); expect(second.calls.map((call) => call.path)).toEqual([timeline]); @@ -472,7 +480,7 @@ test("a timed-out wait prints a cursor that still reports a push landing before test("a wait timed out during setup resumes from the head it read, so a later push is reported", async () => { const first = setup([pull(), response({ message: "rate limit" }, { "retry-after": "120" }, 429)]); - const timeout = await waitForActivity(pr, { timeout: 10 }, first.deps).catch((error: unknown) => error); + const timeout = await waitOn(pr, { timeout: 10 }, first.deps).catch((error: unknown) => error); expect(timeout).toMatchObject({ cursor: A }); const second = setup( [ @@ -482,7 +490,7 @@ test("a wait timed out during setup resumes from the head it read, so a later pu ], [A, B], ); - const lines = await waitForActivity(pr, { since: (timeout as WaitTimeout).cursor }, second.deps); + const lines = await waitOn(pr, { since: (timeout as WaitTimeout).cursor }, second.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:05:00Z pushed author /); }); @@ -504,7 +512,7 @@ test("a later force push back to a SHA pushed before the starting point is activ ], [B], ); - const lines = await waitForActivity(pr, { since: "2026-10-07T11:30:00Z" }, fixture.deps); + const lines = await waitOn(pr, { since: "2026-10-07T11:30:00Z" }, fixture.deps); expect(lines.map((line) => line.split(" ").slice(0, 2).join(" "))).toEqual([ "2026-10-07T12:05:02Z head_ref_force_pushed", "2026-10-07T12:30:00Z head_ref_force_pushed", @@ -517,7 +525,7 @@ test("a push racing setup prints once, as a push", async () => { response([pushed(B, "2026-10-07T12:05:00Z"), pushed()]), response([committed(A), committed(B)]), ]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:05:00Z pushed author /); }); @@ -533,7 +541,7 @@ test("all initial timeline pages are read, and the last known page is polled bef response([], { link: `<${page3}>; rel="next"` }), response([reviewed()]), ]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(fixture.calls.slice(3).map((call) => call.path)).toEqual([ timeline, @@ -555,7 +563,7 @@ test("a full last page is reread whole, since a 304 cannot show that a next page response(full, { etag: '"full"', link: `<${page2}>; rel="next"` }), response([reviewed(1, "2026-10-07T12:12:00Z")]), ]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:12:00Z reviewed /); expect(fixture.calls[4].headers.has("if-none-match")).toBe(false); @@ -570,7 +578,7 @@ test("a review landing after the last scheduled poll is reported by a final poll response(null, {}, 304), response([committed(A), reviewed(1, "2026-10-07T12:18:00Z")]), ]); - const lines = await waitForActivity(pr, { timeout: 540 }, fixture.deps); + const lines = await waitOn(pr, { timeout: 540 }, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:18:00Z reviewed /); expect(fixture.sleeps).toEqual([300_000, 210_000]); @@ -584,11 +592,11 @@ test("a review landing after the final poll is left for the timeout's cursor, ne response(null, {}, 304), response(null, {}, 304), ]); - const timeout = await waitForActivity(pr, { timeout: 540 }, first.deps).catch((error: unknown) => error); + const timeout = await waitOn(pr, { timeout: 540 }, first.deps).catch((error: unknown) => error); expect(timeout).toBeInstanceOf(WaitTimeout); expect(first.sleeps).toEqual([300_000, 210_000, 30_000]); const second = setup([response([committed(A), reviewed(1, "2026-10-07T12:18:50Z")])]); - const lines = await waitForActivity(pr, { since: (timeout as WaitTimeout).cursor }, second.deps); + const lines = await waitOn(pr, { since: (timeout as WaitTimeout).cursor }, second.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:18:50Z reviewed /); }); @@ -604,7 +612,7 @@ test("older initial pages are not skipped even when the last page has no recent ], [B, A], ); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(fixture.calls).toHaveLength(5); }); @@ -616,7 +624,7 @@ test("GitHub errors and malformed successful bodies never become activity", asyn response([{ event: "reviewed", id: 1, submitted_at: "yesterday" }]), ]) { const fixture = setup([pull(), response([pushed()]), bad]); - await expect(waitForActivity(pr, {}, fixture.deps)).rejects.toThrow(); + await expect(waitOn(pr, {}, fixture.deps)).rejects.toThrow(); expect(fixture.sleeps).toEqual([]); } }); @@ -629,7 +637,7 @@ test("rate limits honor Retry-After and then exponentially back off", async () = response([pushed()]), response([reviewed()]), ]); - await waitForActivity(pr, {}, fixture.deps); + await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([120_000, 120_000]); expect(fixture.warnings).toHaveLength(2); }); @@ -647,26 +655,26 @@ test("primary rate limit reset and server poll intervals are honored", async () response([], { "x-poll-interval": "600" }), response([reviewed()]), ]); - await waitForActivity(pr, {}, fixture.deps); + await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([60_000, 600_000]); }); test("a server poll interval past the final poll skips it rather than polling early", async () => { // A 600 s X-Poll-Interval outlasts a 540 s timeout, so no final poll runs at 510 s. const fixture = setup([pull(), response([pushed()]), response([], { "x-poll-interval": "600" })]); - await expect(waitForActivity(pr, { timeout: 540 }, fixture.deps)).rejects.toBeInstanceOf(WaitTimeout); + await expect(waitOn(pr, { timeout: 540 }, fixture.deps)).rejects.toBeInstanceOf(WaitTimeout); expect(fixture.sleeps).toEqual([540_000]); }); test("persistent rate limiting eventually fails loudly instead of masking an error", async () => { const fixture = setup(Array.from({ length: 7 }, () => response({ message: "secondary rate limit" }, {}, 403))); - await expect(waitForActivity(pr, {}, fixture.deps)).rejects.toThrow("rate limit persisted"); + await expect(waitOn(pr, {}, fixture.deps)).rejects.toThrow("rate limit persisted"); expect(fixture.sleeps).toEqual([60_000, 120_000, 240_000, 480_000, 960_000, 1_920_000]); }); test("a permission-denied 403 fails without rate-limit retries", async () => { const fixture = setup([response({ message: "Resource not accessible by integration" }, {}, 403)]); - await expect(waitForActivity(pr, {}, fixture.deps)).rejects.toThrow("HTTP 403"); + await expect(waitOn(pr, {}, fixture.deps)).rejects.toThrow("HTTP 403"); expect(fixture.sleeps).toEqual([]); }); @@ -676,12 +684,12 @@ test("timeout is distinct and limits both poll sleeps and rate-limit waits", asy [response({ message: "rate limit" }, { "retry-after": "120" }, 429)], ]) { const fixture = setup(responses); - await expect(waitForActivity(pr, { timeout: 10 }, fixture.deps)).rejects.toBeInstanceOf(WaitTimeout); + await expect(waitOn(pr, { timeout: 10 }, fixture.deps)).rejects.toBeInstanceOf(WaitTimeout); expect(fixture.sleeps).toEqual([10_000]); } // A deadline before the PR is read can only hand back the starting point it was given. const setupLimited = setup([response({ message: "rate limit" }, { "retry-after": "120" }, 429)]); - await expect(waitForActivity(pr, { since: POINT, timeout: 10 }, setupLimited.deps)).rejects.toMatchObject({ + await expect(waitOn(pr, { since: POINT, timeout: 10 }, setupLimited.deps)).rejects.toMatchObject({ cursor: POINT, }); }); @@ -694,7 +702,7 @@ test("a head GitHub has yet to list is waited for, then starts at its listed pus response([pushed(), pushed(B, "2026-10-07T11:50:00Z")]), response([committed(A), reviewed(1, "2026-10-07T11:55:00Z"), reviewed(2)]), ]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain("pullrequestreview-2 q1."); expect(fixture.sleeps).toEqual([15_000, 15_000]); @@ -703,14 +711,14 @@ test("a head GitHub has yet to list is waited for, then starts at its listed pus test("a timeout while GitHub has yet to list the head resumes from that head", async () => { const fixture = setup([pull(), response([]), response([])]); - const timeout = await waitForActivity(pr, { timeout: 20 }, fixture.deps).catch((error: unknown) => error); + const timeout = await waitOn(pr, { timeout: 20 }, fixture.deps).catch((error: unknown) => error); expect(timeout).toBeInstanceOf(WaitTimeout); expect(timeout).toMatchObject({ cursor: A }); }); test("unresolvable pushed SHA fails with a timestamp recommendation", async () => { const fixture = setup([pull(), response([pushed()])]); - await expect(waitForActivity(pr, { since: B }, fixture.deps)).rejects.toThrow("pass a timestamp with --since"); + await expect(waitOn(pr, { since: B }, fixture.deps)).rejects.toThrow("pass a timestamp with --since"); }); test("a SHA a merge into the branch made resolves to the merge's time, and the merge never prints as a push", async () => { @@ -728,7 +736,7 @@ test("a SHA a merge into the branch made resolves to the merge's time, and the m ], [B, A], ); - const lines = await waitForActivity(pr, { since: A }, fixture.deps); + const lines = await waitOn(pr, { since: A }, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain("pullrequestreview-2 q1."); } @@ -736,7 +744,7 @@ test("a SHA a merge into the branch made resolves to the merge's time, and the m test("the current head a merge into the branch made is the default point", async () => { const fixture = setup([pull(), response([pushed(A, POINT, "pr_merge")]), response([committed(A), reviewed()])]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain("pullrequestreview-1 q1."); }); @@ -750,14 +758,14 @@ test("a merge into the branch after the point is reported as its new commit, not ], [A, B], ); - const lines = await waitForActivity(pr, { since: A }, fixture.deps); + const lines = await waitOn(pr, { since: A }, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(new RegExp(`^${B} committed `)); }); test("a branch update that is not a move never resolves the point", async () => { const fixture = setup([pull(), response([pushed(), pushed(B, POINT, "branch_deletion")])]); - await expect(waitForActivity(pr, { since: B }, fixture.deps)).rejects.toThrow("cannot resolve push time"); + await expect(waitOn(pr, { since: B }, fixture.deps)).rejects.toThrow("cannot resolve push time"); }); test("SHA lookup paginates repository activity", async () => { @@ -772,16 +780,16 @@ test("SHA lookup paginates repository activity", async () => { ], [A, B], ); - const lines = await waitForActivity(pr, { since: A }, fixture.deps); + const lines = await waitOn(pr, { since: A }, fixture.deps); expect(lines[0]).toContain("pushed author"); expect(fixture.calls[3].path).toBe("/repos/contributor/fork/activity?page=2"); }); test("deleted forks accept timestamps but cannot guess SHA push times", async () => { const missing = setup([pull(null)]); - await expect(waitForActivity(pr, {}, missing.deps)).rejects.toThrow("pass a timestamp"); + await expect(waitOn(pr, {}, missing.deps)).rejects.toThrow("pass a timestamp"); const timestamp = setup([pull(null), response([reviewed()])]); - expect(await waitForActivity(pr, { since: POINT }, timestamp.deps)).toHaveLength(1); + expect(await waitOn(pr, { since: POINT }, timestamp.deps)).toHaveLength(1); }); test("untrusted pagination cannot leak an authorization token", async () => { @@ -790,22 +798,22 @@ test("untrusted pagination cannot leak an authorization token", async () => { response([pushed()]), response([], { link: '; rel="next"' }), ]); - await expect(waitForActivity(pr, {}, fixture.deps)).rejects.toThrow("pagination URL"); + await expect(waitOn(pr, {}, fixture.deps)).rejects.toThrow("pagination URL"); expect(fixture.calls).toHaveLength(4); }); test("malformed and wrong-PR cursors fail without requests", async () => { const first = setup([pull(), response([pushed()]), response([reviewed()])]); - const other = cursor(await waitForActivity(pr, {}, first.deps)); + const other = cursor(await waitOn(pr, {}, first.deps)); for (const point of ["q1.garbage", other]) { const fixture = setup([]); - await expect(waitForActivity({ ...pr, number: 2 }, { since: point }, fixture.deps)).rejects.toThrow( + await expect(waitOn({ ...pr, number: 2 }, { since: point }, fixture.deps)).rejects.toThrow( "invalid --since cursor", ); expect(fixture.calls).toEqual([]); } const recased = setup([]); - await expect(waitForActivity(pr, { since: `Q1.${other.slice(3)}` }, recased.deps)).rejects.toThrow( + await expect(waitOn(pr, { since: `Q1.${other.slice(3)}` }, recased.deps)).rejects.toThrow( "cursors start with lower-case q1.", ); expect(recased.calls).toEqual([]); @@ -827,7 +835,7 @@ test("PR URL parsing and timeout usage fail before authentication", () => { test("a bare PR number outside a checkout says to pass the URL instead", () => { const outside = mkdtempSync(join(tmpdir(), "quest-wait-")); try { - expect(() => pullRequest("1", outside)).toThrow(GitHubInputError); + expect(() => pullRequest("1", outside)).toThrow(InputError); expect(() => pullRequest("1", outside)).toThrow("pass the full GitHub PR URL, or run inside a checkout"); } finally { rmSync(outside, { recursive: true }); @@ -848,7 +856,7 @@ test("auto-merge left on a moved head wakes the wait once per head, naming the h const first = setup([pull(undefined, B), response([pushed(B)]), response([committed(A), committed(B)])], [A, B], { checks: [pinned(B)], }); - const moved = await waitForActivity(pr, {}, first.deps); + const moved = await waitOn(pr, {}, first.deps); expect(moved).toHaveLength(1); expect(moved[0]).toMatch( new RegExp( @@ -857,7 +865,7 @@ test("auto-merge left on a moved head wakes the wait once per head, naming the h ); // Resuming reports other activity, not the same moved head again. const next = setup([response([committed(A), committed(B), reviewed(2, LATEST)])], [A, B], { checks: [pinned(B)] }); - const lines = await waitForActivity(pr, { since: cursor(moved) }, next.deps); + const lines = await waitOn(pr, { since: cursor(moved) }, next.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/ reviewed reviewer /); }); @@ -874,12 +882,12 @@ test("auto-merge on the current head is not activity", async () => { const fixture = setup([pull(), response([pushed()]), response([committed(A)]), response([committed(A)])], [A], { checks: [current(), current()], }); - await expect(waitForActivity(pr, { timeout: 60 }, fixture.deps)).rejects.toBeInstanceOf(WaitTimeout); + await expect(waitOn(pr, { timeout: 60 }, fixture.deps)).rejects.toBeInstanceOf(WaitTimeout); }); test("a push racing initial setup is not swallowed by the baseline", async () => { const fixture = setup([pull(), response([pushed()]), response([committed(A), committed(B)])]); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(new RegExp(`^${B} committed `)); expect(fixture.sleeps).toEqual([]); @@ -887,23 +895,23 @@ test("a push racing initial setup is not swallowed by the baseline", async () => test("a changed head during the commit listing fails rather than swallowing a push", async () => { const fixture = setup([pull()], [A, B]); - await expect(waitForActivity(pr, {}, fixture.deps)).rejects.toThrow("head changed during setup"); + await expect(waitOn(pr, {}, fixture.deps)).rejects.toThrow("head changed during setup"); expect(fixture.calls).toHaveLength(2); }); test("malformed timestamps and unexpected 304 responses fail without phantom activity", async () => { const invalid = setup([]); - await expect(waitForActivity(pr, { since: "yesterday" }, invalid.deps)).rejects.toThrow("invalid timestamp"); + await expect(waitOn(pr, { since: "yesterday" }, invalid.deps)).rejects.toThrow("invalid timestamp"); expect(invalid.calls).toHaveLength(0); const cached = setup([pull(), response([pushed()]), response(null, {}, 304)]); - await expect(waitForActivity(pr, {}, cached.deps)).rejects.toThrow("without a cached response"); + await expect(waitOn(pr, {}, cached.deps)).rejects.toThrow("without a cached response"); }); test("a clean review's reaction on the PR body ends the wait", async () => { const fixture = setup([pull(), response([pushed()]), response([committed(A)])], [A], { graphql: [reactions([reacted("r1", "2026-10-07T12:05:00Z")])], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch( /^2026-10-07T12:05:00Z reacted:thumbs_up codex\[bot\] https:\/\/github.com\/example\/project\/pull\/1 q1\./, @@ -922,7 +930,7 @@ test("reactions on reviews are read from every page of reviews", async () => { reactions([], [review(2, [reacted("r2", POINT, "author", "EYES")])]), ], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain("reacted:eyes author https://github.com/example/project/pull/1#pullrequestreview-2"); expect(graphql(fixture).map((body) => body.variables.after)).toEqual([null, "next"]); @@ -936,7 +944,7 @@ test("a review-thread reply wakes the waiter, but its own activity and a thread' ], graphql: [reactions([reacted("r1", POINT, "waiter")]), reactions([reacted("r1", POINT, "waiter")])], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch( /^2026-10-07T12:00:00Z replied reviewer https:\/\/github.com\/example\/project\/pull\/1#discussion_r3 q1\./, @@ -954,13 +962,13 @@ test("resuming tracks replies and reactions separately, so neither replays nor h const first = setup([pull(), response([pushed()]), response([committed(A)])], [A], { graphql: [reactions([reacted("r1", "2026-10-07T12:05:00Z")])], }); - const point = cursor(await waitForActivity(pr, {}, first.deps)); + const point = cursor(await waitOn(pr, {}, first.deps)); // A reply older than the reaction, first visible after the waiter returned. const second = setup([response([committed(A)])], [A], { comments: [response([replied(2, "2026-10-07T12:03:00Z")])], graphql: [reactions([reacted("r1", "2026-10-07T12:05:00Z")])], }); - const lines = await waitForActivity(pr, { since: point }, second.deps); + const lines = await waitOn(pr, { since: point }, second.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:03:00Z replied reviewer /); expect(second.sideCalls[0].path).toContain("since=2026-10-07T11:59:59.000Z"); @@ -971,7 +979,7 @@ test("resuming tracks replies and reactions separately, so neither replays nor h reactions([reacted("r1", "2026-10-07T12:05:00Z"), reacted("r2", "2026-10-07T12:05:00Z")]), ], }); - const later = await waitForActivity(pr, { since: cursor(lines) }, third.deps); + const later = await waitOn(pr, { since: cursor(lines) }, third.deps); expect(later).toHaveLength(1); expect(later[0]).toContain("reacted:thumbs_up"); expect(third.sleeps).toEqual([300_000]); @@ -982,7 +990,7 @@ test("GraphQL errors fail loudly instead of hiding reactions", async () => { const fixture = setup([pull(), response([pushed()]), response([committed(A)])], [A], { graphql: [response({ errors: [{ message: "Could not resolve to a PullRequest" }] })], }); - await expect(waitForActivity(pr, {}, fixture.deps)).rejects.toThrow("GitHub GraphQL error"); + await expect(waitOn(pr, {}, fixture.deps)).rejects.toThrow("GitHub GraphQL error"); }); const LATER = "2026-10-07T12:05:00Z"; @@ -999,7 +1007,7 @@ test("a required failure wakes the wait, naming the check and linking its detail ], protected: ["build and test", "check"], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(2); expect(lines[0]).toContain("check:failed lint"); expect(lines[1]).toMatch( @@ -1019,7 +1027,7 @@ test("an optional failure wakes separately, and resuming still waits for all che ], ruled: ["check", "test"], }); - const failed = await waitForActivity(pr, {}, first.deps); + const failed = await waitOn(pr, {}, first.deps); expect(failed).toHaveLength(1); expect(failed[0]).toMatch(/^2026-10-07T12:05:00Z check:failed lint /); const next = setup([response([committed(A)]), response([committed(A)])], [A], { @@ -1039,7 +1047,7 @@ test("an optional failure wakes separately, and resuming still waits for all che ], ruled: ["check", "test"], }); - const lines = await waitForActivity(pr, { since: cursor(failed) }, next.deps); + const lines = await waitOn(pr, { since: cursor(failed) }, next.deps); expect(next.sleeps).toEqual([300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:passed test /); @@ -1062,7 +1070,7 @@ test("classic protection that lists only contexts still names required checks", protected: ["check", "gate"], contextsOnly: true, }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:passed gate /); @@ -1073,7 +1081,7 @@ test("a gated base's quest land check, which no head carries, never holds back c checks: [checks([{ name: "check", required: true, result: "SUCCESS", time: LATER }])], ruled: ["check", "quest land"], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:05:00Z checks:passed check /); }); @@ -1092,7 +1100,7 @@ test("a rerun supersedes a cancelled run of a required check, which never wakes ], protected: ["check"], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:passed check /); @@ -1118,7 +1126,7 @@ test("a superseded workflow run's failed gate never wakes the wait, as on moq-de ], protected: ["Release gate"], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toEqual([expect.stringMatching(/^2026-10-07T12:08:00Z checks:passed Release_gate /)]); }); @@ -1144,7 +1152,7 @@ test("optional checks never stand in for required checks that have not started", ruled: ["gate"], }, ); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000, 300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:passed gate /); @@ -1167,7 +1175,7 @@ test("a required check named on a later page of rules holds back checks:passed", }, ], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:passed deploy /); @@ -1189,7 +1197,7 @@ test("a required check from another app than its requirement names holds back ch ], ruled: ["check"], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toEqual([expect.stringMatching(/^2026-10-07T12:08:00Z checks:passed check /)]); }); @@ -1226,7 +1234,7 @@ test("a cancelled check a newer run replaced never fails the wait, which stays b [run(1, "completed"), { ...run(2, "completed"), run_started_at: "2026-10-07T12:02:00Z" }], ], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toEqual([expect.stringMatching(/^2026-10-07T12:08:00Z checks:passed check /)]); }); @@ -1255,7 +1263,7 @@ test("a required workflow requires its jobs, keeps optional checks optional, and rules: [workflowRule], }, ); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000, 300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:passed gate /); @@ -1271,7 +1279,7 @@ test("a required workflow's job counts toward checks:passed when another workflo ], rules: [workflowRule], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/ checks:passed /); }); @@ -1286,7 +1294,7 @@ test("a failing job in a required workflow wakes the wait", async () => { ], rules: [workflowRule], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:failed build /); }); @@ -1302,7 +1310,7 @@ test("checks:passed is dated when the head goes idle, after required checks fini ], protected: ["check"], }); - const lines = await waitForActivity(pr, { since: LATER }, fixture.deps); + const lines = await waitOn(pr, { since: LATER }, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:passed check /); @@ -1321,7 +1329,7 @@ test("with no required checks, an unfinished workflow run holds back checks:pass ]), ], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:passed gate /); @@ -1345,7 +1353,7 @@ test("a repository with no required checks requires every check, commit statuses ], }, ); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000, 300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch( @@ -1358,7 +1366,7 @@ test("results reached before an explicit starting point are not reported", async checks: [checks([{ name: "check", required: true, result: "FAILURE", time: LATER }])], protected: ["check"], }); - const timeout = await waitForActivity(pr, { since: LATEST, timeout: 10 }, fixture.deps).catch( + const timeout = await waitOn(pr, { since: LATEST, timeout: 10 }, fixture.deps).catch( (error: unknown) => error, ); expect(timeout).toBeInstanceOf(WaitTimeout); @@ -1372,20 +1380,20 @@ test("a resumed wait never replays a reported result, but a push starts over for checks: [failing(A)], ...protect, }); - const reported = await waitForActivity(pr, {}, first.deps); + const reported = await waitOn(pr, {}, first.deps); expect(reported[0]).toContain("checks:failed check"); // The same failure is not reported again; the push is. const second = setup([response([committed(A)]), response([committed(A), committed(B)])], [A], { checks: [failing(A), failing(A)], ...protect, }); - const pushedLines = await waitForActivity(pr, { since: cursor(reported) }, second.deps); + const pushedLines = await waitOn(pr, { since: cursor(reported) }, second.deps); expect(second.sleeps).toEqual([300_000]); expect(pushedLines).toHaveLength(1); expect(pushedLines[0]).toMatch(new RegExp(`^${B} committed `)); // The new head's failure is reported even though the old head's was. const third = setup([response([committed(A), committed(B)])], [A], { checks: [failing(B, LATEST)], ...protect }); - const again = await waitForActivity(pr, { since: cursor(pushedLines) }, third.deps); + const again = await waitOn(pr, { since: cursor(pushedLines) }, third.deps); expect(again).toHaveLength(1); expect(again[0]).toMatch(/^2026-10-07T12:08:00Z checks:failed check /); // A later pass on that head is still reported once. @@ -1393,7 +1401,7 @@ test("a resumed wait never replays a reported result, but a push starts over for checks: [checks([{ name: "check", required: true, result: "SUCCESS", time: "2026-10-07T12:09:00Z" }], B)], ...protect, }); - const passed = await waitForActivity(pr, { since: cursor(again) }, fourth.deps); + const passed = await waitOn(pr, { since: cursor(again) }, fourth.deps); expect(passed).toHaveLength(1); expect(passed[0]).toContain("checks:passed check"); }); @@ -1403,12 +1411,12 @@ test("a timed-out wait's cursor still reports a result reached during the first checks: [checks([{ name: "check", required: true }])], protected: ["check"], }); - const timeout = await waitForActivity(pr, { timeout: 10 }, first.deps).catch((error: unknown) => error); + const timeout = await waitOn(pr, { timeout: 10 }, first.deps).catch((error: unknown) => error); const second = setup([response([committed(A)])], [A], { checks: [checks([{ name: "check", required: true, result: "SUCCESS", time: LATER }])], protected: ["check"], }); - const lines = await waitForActivity(pr, { since: (timeout as WaitTimeout).cursor }, second.deps); + const lines = await waitOn(pr, { since: (timeout as WaitTimeout).cursor }, second.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain("checks:passed check"); }); @@ -1423,7 +1431,7 @@ test("checks are read from every page, and a head racing the read waits for the ], protected: ["check", "test"], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(fixture.sleeps).toEqual([300_000]); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z checks:failed test /); @@ -1449,14 +1457,14 @@ test("edited bot comments wake once, including different edits in the same secon const first = setup([pull(), response([pushed()]), response([committed(A)])], [A], { edits: [response([edited(1)])], }); - const lines = await waitForActivity(pr, {}, first.deps); + const lines = await waitOn(pr, {}, first.deps); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/^2026-10-07T12:05:00Z edited codex\[bot\] /); expect(Buffer.from(cursor(lines).slice(3), "base64url").toString()).not.toContain("Review completed"); const resumed = setup([response([committed(A)]), response([committed(A)])], [A], { edits: [response([edited(1)]), response([edited(1, LATER, "Security review completed")])], }); - const changed = await waitForActivity(pr, { since: cursor(lines) }, resumed.deps); + const changed = await waitOn(pr, { since: cursor(lines) }, resumed.deps); expect(resumed.sleeps).toEqual([300_000]); expect(changed[0]).toContain(" edited codex[bot] "); }); @@ -1471,7 +1479,7 @@ test("edits reread every creation-ordered page, so an old first-page comment can response([edited(1)]), ], }); - expect((await waitForActivity(pr, {}, fixture.deps))[0]).toContain(" edited codex[bot] "); + expect((await waitOn(pr, {}, fixture.deps))[0]).toContain(" edited codex[bot] "); expect(fixture.editCalls.map((call) => call.path)).toEqual([ `${base}/issues/1/comments?per_page=100&since=2026-10-07T11:59:59.000Z`, page2, @@ -1484,14 +1492,14 @@ test("a later reaction does not hide an older edit, and old cursors learn the ed graphql: [reactions([reacted("r1", LATEST)])], }); const previous = JSON.parse( - Buffer.from(cursor(await waitForActivity(pr, {}, first.deps)).slice(3), "base64url").toString(), + Buffer.from(cursor(await waitOn(pr, {}, first.deps)).slice(3), "base64url").toString(), ); delete previous.marks.edits; const old = `q1.${Buffer.from(JSON.stringify(previous)).toString("base64url")}`; const next = setup([response([committed(A)])], [A], { edits: [response([edited(1), edited(2, LATEST, "My reply", "waiter")])], }); - const lines = await waitForActivity(pr, { since: old }, next.deps); + const lines = await waitOn(pr, { since: old }, next.deps); expect(lines).toHaveLength(1); expect(lines[0]).toContain(" edited codex[bot] "); }); @@ -1506,7 +1514,7 @@ test("a later failing optional check cannot name the aggregate required pass", a ]), ], }); - const lines = await waitForActivity(pr, {}, fixture.deps); + const lines = await waitOn(pr, {}, fixture.deps); expect(lines).toHaveLength(2); expect(lines[0]).toMatch(/^2026-10-07T12:08:00Z check:failed optional /); expect(lines[1]).toMatch(/^2026-10-07T12:08:00Z checks:passed check /); From e3eaa3361224e7d68817a2c9c758a98f33176513 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 10:36:48 -0800 Subject: [PATCH 3/8] wip: forge tests, docs, quests --- README.md | 28 ++ quest/m0/benchmark/records-endpoint.md | 13 +- quest/m0/github-quota/forge-reads.md | 41 --- quest/m1/forge-writes.md | 9 +- src/cli/forge.ts | 34 +- src/cli/hold.ts | 12 +- src/cli/land-bump.ts | 11 +- src/cli/land-queue.ts | 10 +- src/cli/land-watch.ts | 11 +- src/cli/land.ts | 14 +- src/cli/main.ts | 75 ++-- src/github/hold.ts | 10 +- test/forge.test.ts | 452 +++++++++++++++++++++++++ test/status-fakes.ts | 229 +++++++++++++ test/status.test.ts | 228 +------------ test/wait-fakes.ts | 275 +++++++++++++++ test/wait.test.ts | 305 ++--------------- 17 files changed, 1147 insertions(+), 610 deletions(-) delete mode 100644 quest/m0/github-quota/forge-reads.md create mode 100644 test/forge.test.ts create mode 100644 test/status-fakes.ts create mode 100644 test/wait-fakes.ts diff --git a/README.md b/README.md index c7ee8b83..c9da39bc 100644 --- a/README.md +++ b/README.md @@ -551,6 +551,34 @@ until GitHub lists the current head's push, which takes seconds to minutes, and when a push shares the second auto-merge was enabled. A head there that differs from `head` means a push followed auto-merge: disable it, or land the new head. +### Read through Kixel Quest + +Agents polling `quest status`, `quest wait`, and `quest unblocked --unclaimed` +can spend a person's whole hourly GitHub quota. Where +[Kixel Quest](https://kixel.quest) serves the repository, those reads, and the +claim and draft reads of `quest start` and `quest waiting`, go to its index of +GitHub's webhooks instead. It serves only people its allow-list gives a token, +which `quest` takes from `$XDG_CONFIG_HOME/quest/records.json`, paired with +`https://kixel.quest`: + +```json +{ "https://kixel.quest": "" } +``` + +Without a token, or for a repository Kixel Quest does not serve, reads go to +GitHub as above; the output is the same either way. When Kixel Quest fails, the +command fails too, naming `QUEST_FORGE=github`, which reads GitHub instead. +`QUEST_KIXEL_URL` names another Kixel Quest, such as one running locally, whose +token the same file pairs with its URL. + +Its read API lives under `/forge`, with the token as a bearer token: +`GET /forge` answers `{"login", "repositories"}`, the person the token names +and the lowercase `owner/repo` of each repository served to them, and +`POST /forge/` takes one of `status`, `pulls`, `held`, or `watch` and +answers `{"value", "asOf"}`, the read's value and the time of the newest +webhook behind it. `quest/core` exports each read's types and their parsers; +`quest/github`'s `GitHubForge` answers the same reads from GitHub. + ## Own a pull request Before a session pushes to an existing PR, it takes the PR, so two agents diff --git a/quest/m0/benchmark/records-endpoint.md b/quest/m0/benchmark/records-endpoint.md index 1f23cb0c..c700560f 100644 --- a/quest/m0/benchmark/records-endpoint.md +++ b/quest/m0/benchmark/records-endpoint.md @@ -23,14 +23,15 @@ repository named by its remote (rejected: a committed `.quest.json`, which no repository had committed yet). - Delete the `.quest.json` reader (`CHECKOUT_CONFIG` in `src/cli/send.ts`) - and the help text naming it. The token file keeps one token for Kixel - Quest, the same one the [forge reads](/quest/m0/github-quota/forge-reads.md) - use. + and the help text naming it. Send to the Kixel Quest that + `kixelQuest()` in `src/cli/forge.ts` names, `https://kixel.quest` or + `QUEST_KIXEL_URL`, with the token the forge reads use: the one + `~/.config/quest/records.json` pairs with that URL. - Kixel Quest refuses a whole upload naming a repository it does not index or the sender cannot read, so the sender sends only the repositories - Kixel Quest says it serves, the same answer the forge reads use, and - keeps the rest on the host as it does today for a checkout with no - endpoint. + Kixel Quest says it serves, `KixelQuest.serves()`, the same answer the + forge reads use, and keeps the rest on the host as it does today for a + checkout with no endpoint. - Put the token on each host, and start its sender with `quest records install`, through kixel-ai/dotfiles, which owns the maintainer's host configuration, not by hand. diff --git a/quest/m0/github-quota/forge-reads.md b/quest/m0/github-quota/forge-reads.md deleted file mode 100644 index a7454ae4..00000000 --- a/quest/m0/github-quota/forge-reads.md +++ /dev/null @@ -1,41 +0,0 @@ -# [L] Forge interface with a Kixel Quest backend for reads - -## Goal - -quest reads pull request, check, review, claim, hold, and queue state through -one forge interface with two backends: GitHub, which every command uses -today, and Kixel Quest, which answers from its index without spending the -person's GitHub quota. A person with a Kixel Quest token reads a repository -Kixel Quest serves through it; everyone else reads GitHub as before, so -skills and output do not change. - -## Plan - -Decided 2026-11-15 (maintainer, `/quest-plan` in kixel-ai/kixel.quest, -[kixel-ai/kixel.quest#48](https://github.com/kixel-ai/kixel.quest/pull/48)): -✅ a forge interface in quest with GitHub and Kixel Quest backends (rejected: -Kixel Quest emulating the subset of GitHub's REST and GraphQL that quest and -`gh` call, which ties its API to GitHub's shape, `mergeQueueEntry` and -`reviewThreads` included). The same interface later takes the -[writes](/quest/m1/forge-writes.md) for repositories that move off GitHub. -The backend choice and outage behavior are in the -[epic](/quest/m0/github-quota/README.md). - -- This quest owns the API's shape. Export the interface's read types and the - wire format from `quest/core`, which kixel-ai/kixel.quest already pins, so - its index reads (`quest/m0/read-api.md` there) serve the same types and - neither side guesses. -- Put `src/github`'s readers behind the interface first, then add the Kixel - Quest backend. Commands take the interface, not the GitHub client. -- Each answer carries the time of the newest webhook behind it, so - `quest wait` can tell a quiet PR from a stale index. -- The caller's identity is part of the interface, not read off whichever - credential served the read: the Kixel Quest backend names the token's - person, so `quest wait` still ignores the person's own activity. -- A read Kixel Quest's index cannot answer falls through to GitHub inside - Kixel Quest, never back in quest. - -Tests: the same scenarios run against both backends, a fake GitHub and a -fake Kixel Quest, and give equal answers; a repository Kixel Quest does not -serve reads GitHub; and a Kixel Quest error fails the command naming the -override. diff --git a/quest/m1/forge-writes.md b/quest/m1/forge-writes.md index 51d54551..c37eba14 100644 --- a/quest/m1/forge-writes.md +++ b/quest/m1/forge-writes.md @@ -15,8 +15,9 @@ our private repositories move onto Cloudflare Artifacts with Kixel Quest as their whole forge, kixel-ai/kixel.ai first as the pilot; public repositories stay on GitHub. -- Extend the [forge interface](/quest/m0/github-quota/forge-reads.md) with - the writes, typed in `quest/core` as its reads are. This quest owns their +- Extend the forge interface (`Forge` in `src/core/forge.ts`, with its + Kixel Quest backend in `src/cli/forge.ts`) with the writes, typed and + parsed in `quest/core` as its reads are. This quest owns their shape: kixel-ai/kixel.quest serves it (`quest/m1/forge/pulls.md` there), so build against a fake Kixel Quest and land first. - A pick names the head the person saw, as `Quest-Land-Head` does on GitHub; @@ -27,7 +28,3 @@ stay on GitHub. Tests: against a fake Kixel Quest, quest opens a PR, edits its body, readies it, resolves a thread, claims and holds it, and queues a pick of its head. - -## Required - -- [Forge reads](/quest/m0/github-quota/forge-reads.md) - the interface these writes extend diff --git a/src/cli/forge.ts b/src/cli/forge.ts index eb80a700..30a46272 100644 --- a/src/cli/forge.ts +++ b/src/cli/forge.ts @@ -69,7 +69,13 @@ export class KixelQuest { /** The person the token names, and the repositories Kixel Quest serves them; read once. */ info(): Promise { - this.#info ??= this.#send("GET", "/forge", undefined, Infinity).then(parseForgeInfo); + this.#info ??= this.#send("GET", "/forge", undefined, Infinity).then((json) => { + try { + return parseForgeInfo(json); + } catch (error) { + throw this.#failed("GET", "/forge", (error as Error).message); + } + }); return this.#info; } @@ -84,18 +90,32 @@ export class KixelQuest { request: ForgeCalls[C]["request"], deadline = Infinity, ): Promise> { - return parseForgeAnswer(call, await this.#send("POST", `/forge/${call}`, request, deadline)); + const path = `/forge/${call}`; + const json = await this.#send("POST", path, request, deadline); + try { + return parseForgeAnswer(call, json); + } catch (error) { + throw this.#failed("POST", path, (error as Error).message); + } + } + + /** A failed request, naming the setting that reads GitHub instead. */ + #failed(method: string, path: string, why: string): Error { + return new Error( + `Kixel Quest (${this.url}) failed ${method} ${path}: ${why}; set ${FORGE}=github to read GitHub`, + ); } /** The JSON answer to a request, or an error naming the setting that reads GitHub instead. */ async #send(method: "GET" | "POST", path: string, body: unknown, deadline: number): Promise { - const failed = (why: string) => - new Error(`Kixel Quest (${this.url}) failed ${method} ${path}: ${why}; set ${FORGE}=github to read GitHub`); + const failed = (why: string) => this.#failed(method, path, why); const remaining = deadline - this.deps.now(); + // Called unbound, as a Worker's fetch requires. + const fetch = this.deps.fetch; let response: Response; let text: string; try { - response = await this.deps.fetch(`${this.url}${path}`, { + response = await fetch(`${this.url}${path}`, { method, headers: { Authorization: `Bearer ${this.token}`, @@ -104,7 +124,9 @@ export class KixelQuest { ...(body === undefined ? {} : { "Content-Type": "application/json" }), }, ...(body === undefined ? {} : { body: forgeJson(body) }), - ...(Number.isFinite(remaining) ? { signal: AbortSignal.timeout(Math.max(0, Math.ceil(remaining))) } : {}), + ...(Number.isFinite(remaining) + ? { signal: AbortSignal.timeout(Math.max(0, Math.ceil(remaining))) } + : {}), }); text = await response.text(); } catch (error) { diff --git a/src/cli/hold.ts b/src/cli/hold.ts index 381dfbfb..d8df0d8d 100644 --- a/src/cli/hold.ts +++ b/src/cli/hold.ts @@ -4,7 +4,17 @@ // `quest merge` takes no label: the pinned auto-merge or merge-queue entry it creates is the queue signal. import { ACTIVE_LABEL, formatFinding, handedBack, latestHold, heldToken, withoutHandBack } from "../core"; import { cleanAutoMergeRefusal, immediateMerge, queueHead } from "../github/merge"; -import { currentChecks, GitHub, type GitHubDependencies, GitHubGraphQLError, object, type ObjectValue, requirements, string, repositoryPath } from "../github/client"; +import { + currentChecks, + GitHub, + type GitHubDependencies, + GitHubGraphQLError, + object, + type ObjectValue, + requirements, + string, + repositoryPath, +} from "../github/client"; import type { PullRequest } from "../core"; import { ALLOWS, METHOD_NAMES, contexts, enqueue } from "./land"; import { LAND_CHECK } from "../github/land"; diff --git a/src/cli/land-bump.ts b/src/cli/land-bump.ts index d0adbd91..ebb0131f 100644 --- a/src/cli/land-bump.ts +++ b/src/cli/land-bump.ts @@ -4,7 +4,16 @@ import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { isAbsolute, join, relative, sep } from "node:path"; import { checksState, currentContexts, newerRun, replacedRun, type WorkflowRun } from "../github/checks"; -import { array, GitHub, type GitHubDependencies, object, type ObjectValue, requirements, string, workflowRuns } from "../github/client"; +import { + array, + GitHub, + type GitHubDependencies, + object, + type ObjectValue, + requirements, + string, + workflowRuns, +} from "../github/client"; import type { Repository } from "../core"; import { land } from "./hold"; import { commandEnvironment, contexts, git, type RemoteRead } from "./land"; diff --git a/src/cli/land-queue.ts b/src/cli/land-queue.ts index 006bbd1a..bd4ead38 100644 --- a/src/cli/land-queue.ts +++ b/src/cli/land-queue.ts @@ -3,7 +3,15 @@ // exactly the tested tree with the App. import { existsSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; -import { GitHub, type GitHubDependencies, object, type ObjectValue, type RequiredCheck, requirements, string } from "../github/client"; +import { + GitHub, + type GitHubDependencies, + object, + type ObjectValue, + type RequiredCheck, + requirements, + string, +} from "../github/client"; import type { Repository } from "../core"; import { baseRemote, diff --git a/src/cli/land-watch.ts b/src/cli/land-watch.ts index f4683391..f6442da1 100644 --- a/src/cli/land-watch.ts +++ b/src/cli/land-watch.ts @@ -3,7 +3,16 @@ import { accessSync, constants, existsSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; -import { array, GitHub, type GitHubDependencies, GitHubGraphQLError, link, object, type ObjectValue, string } from "../github/client"; +import { + array, + GitHub, + type GitHubDependencies, + GitHubGraphQLError, + link, + object, + type ObjectValue, + string, +} from "../github/client"; import type { Repository } from "../core"; import { lacksApproval } from "../github/merge"; import type { Entry, LandMethod, Plan } from "./land"; diff --git a/src/cli/land.ts b/src/cli/land.ts index b55f967d..2c35b2ba 100644 --- a/src/cli/land.ts +++ b/src/cli/land.ts @@ -4,7 +4,19 @@ import { resolve } from "node:path"; import { isQuest, remove } from "../core"; import { LAND_CHECK, type Reason, pin, pinned } from "../github/land"; import { programEnvironment } from "./program"; -import { GitHub, GitHubDeadline, type GitHubDependencies, object, type ObjectValue, type RequiredCheck, array, currentChecks, requirements, string, repositoryPath } from "../github/client"; +import { + GitHub, + GitHubDeadline, + type GitHubDependencies, + object, + type ObjectValue, + type RequiredCheck, + array, + currentChecks, + requirements, + string, + repositoryPath, +} from "../github/client"; import type { Repository } from "../core"; import type { WorkflowRun } from "../github/checks"; import { appOf } from "../github/checks"; diff --git a/src/cli/main.ts b/src/cli/main.ts index 6992095a..00385fe8 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -149,6 +149,10 @@ export function main(argv: string[], out: Output): number | Promise { warn, }); const theme = out.terminal ? new Theme(out.terminal) : null; + const FORGE_READS = + "Where Kixel Quest serves the repository and $XDG_CONFIG_HOME/quest/records.json pairs a token with it, " + + "these reads go to Kixel Quest's index instead, sparing the GitHub quota, and its failure fails the command; " + + "QUEST_FORGE=github reads GitHub, and QUEST_KIXEL_URL names another Kixel Quest. "; const program = new Command("quest") .description(description) @@ -359,6 +363,7 @@ export function main(argv: string[], out: Output): number | Promise { "through parents whose default branch has quest/README.md, so a fork with its own quests is its own " + "upstream. The branches and PRs of the fork the remote pushes to count too. Each skipped quest is listed on stderr with its PR and how long ago that PR was last " + "active, so a stale claim can be offered for takeover. Off GitHub, only branches are checked. " + + FORGE_READS + "Outside conditions are never checked.\n\n" + "Given a path, piped output lists its blockers, one per line with nesting indented, with an " + "explanation on stderr; no output means it is ready. On a terminal it prints a quest log instead: a " + @@ -458,8 +463,10 @@ export function main(argv: string[], out: Output): number | Promise { "Invalid trees fail before printing. Outside conditions are never checked, nor whether another " + "session holds a draft.\n\n" + "Drafts are read from the open PRs of the remote's upstream, found as for quest unblocked " + - "--unclaimed, using GH_TOKEN, GITHUB_TOKEN, or gh auth token. Without the remote, off GitHub, or " + - "when GitHub cannot be read, it lists the quest tree's items alone and warns that drafts were skipped.", + "--unclaimed, using GH_TOKEN, GITHUB_TOKEN, or gh auth token. " + + FORGE_READS + + "Without the remote, off GitHub, or when the drafts cannot be read, it lists the quest tree's items alone " + + "and warns that drafts were skipped.", ) .option("--json", "Print a deterministic JSON array") .option("--maintainer", "Only items waiting on the maintainer") @@ -517,7 +524,9 @@ export function main(argv: string[], out: Output): number | Promise { "with a warning.\n\n" + "--release deletes the quest's branch on the remote, with a lease on its tip, and closes its PR, only " + "while that tip is still an empty commit.\n\n" + - "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token on GitHub. Exits 0 when done, 3 when refused " + + "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token on GitHub. " + + FORGE_READS.replace("these reads", "the check for an existing claim") + + "Exits 0 when done, 3 when refused " + "(blocked, held, a branch in the way, or work on the branch), 2 for invalid arguments, and 1 for other " + "failures.", ) @@ -573,6 +582,9 @@ export function main(argv: string[], out: Output): number | Promise { "Pass the final field of the last line to --since to resume without replaying events. " + "On timeout, the only line is a resume point for --since (a cursor, or the given --since or head SHA if setup did not finish), so a retry with it still reports activity from the first wait.\n\n" + "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. Label changes, replies, and reactions by that account are ignored. " + + FORGE_READS.replace("these reads", "its polls") + + "Through Kixel Quest, that account is the person its token names, and a timeout says how current its " + + "index's last answer was. " + "Exits 0 for activity, 3 on timeout, 2 for invalid arguments, and 1 for other failures. " + "Issue-comment edits print as edited, including updates to older bot status comments. The account's own edits are ignored.\n\n" + "In an agent session, where CLAUDE_CODE_SESSION_ID or CODEX_THREAD_ID is set, the wait is logged under " + @@ -598,17 +610,17 @@ export function main(argv: string[], out: Output): number | Promise { pending = forgeFor(pr, forgeDependencies("wait")) .then((forge) => waitForActivity(pr, options, forge, { now: Date.now, sleep })) .then( - (lines) => { - for (const line of lines) print(line); - return logged(lines[0]?.split(" ")[1] ?? null) ? 0 : 1; - }, - (error: unknown) => { - if (error instanceof WaitTimeout && error.cursor) print(error.cursor); - warn(error instanceof Error ? error.message : String(error)); - if (error instanceof WaitTimeout) return logged(null) ? 3 : 1; - return error instanceof InputError ? 2 : 1; - }, - ); + (lines) => { + for (const line of lines) print(line); + return logged(lines[0]?.split(" ")[1] ?? null) ? 0 : 1; + }, + (error: unknown) => { + if (error instanceof WaitTimeout && error.cursor) print(error.cursor); + warn(error instanceof Error ? error.message : String(error)); + if (error instanceof WaitTimeout) return logged(null) ? 3 : 1; + return error instanceof InputError ? 2 : 1; + }, + ); }); program @@ -640,7 +652,9 @@ export function main(argv: string[], out: Output): number | Promise { "reaction on the PR or a review; a thread line per unresolved review thread, led by its node ID; and a " + "signal line per finding or decision that holds the head from landing (see the README). " + "A missing value prints as -. --json prints the same facts as one deterministic object.\n\n" + - "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. Exits 0 for any PR state, 2 for invalid arguments, " + + "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. " + + FORGE_READS.replace("these reads", "the read") + + "Exits 0 for any PR state, 2 for invalid arguments, " + "and 1 for other failures.", ) .argument("", "GitHub PR URL, or a PR number in origin") @@ -650,16 +664,16 @@ export function main(argv: string[], out: Output): number | Promise { pending = forgeFor(pr, forgeDependencies()) .then((forge) => forge.status(pr)) .then( - ({ value: status }) => { - if (options.json) print(JSON.stringify(status)); - else for (const line of statusLines(status)) print(line); - return 0; - }, - (error: unknown) => { - warn(error instanceof Error ? error.message : String(error)); - return 1; - }, - ); + ({ value: status }) => { + if (options.json) print(JSON.stringify(status)); + else for (const line of statusLines(status)) print(line); + return 0; + }, + (error: unknown) => { + warn(error instanceof Error ? error.message : String(error)); + return 1; + }, + ); }); const OWNERSHIP = @@ -1752,13 +1766,10 @@ export function main(argv: string[], out: Output): number | Promise { .argument("", "Quest file or epic directory, as /quest/..., quest/..., or a filesystem path") .argument("", "Its new path, which must not exist") .action((from: string, to: string) => { - pending = moveQuest(root(), from, to, claimDependencies()).then( - report, - (error: unknown) => { - warn(error instanceof Error ? error.message : String(error)); - return 1; - }, - ); + pending = moveQuest(root(), from, to, claimDependencies()).then(report, (error: unknown) => { + warn(error instanceof Error ? error.message : String(error)); + return 1; + }); }); program diff --git a/src/github/hold.ts b/src/github/hold.ts index 28cb151b..9d4b87f1 100644 --- a/src/github/hold.ts +++ b/src/github/hold.ts @@ -1,15 +1,7 @@ // Reading who holds a PR: its `quest:*` labels, the events that added them, and a draft its starter still holds. // Taking and releasing holds stays in the CLI. import { type HoldFact, type PullRequest, type StarterHold, handedBack, isHoldLabel, latestHold } from "../core"; -import { - GitHub, - type GitHubDependencies, - type ObjectValue, - array, - object, - repositoryPath, - string, -} from "./client"; +import { GitHub, type GitHubDependencies, type ObjectValue, array, object, repositoryPath, string } from "./client"; import { lacksApproval } from "./merge"; /** The PR, its `quest:*` labels, and the timeline events that add a label. */ diff --git a/test/forge.test.ts b/test/forge.test.ts new file mode 100644 index 00000000..f57b6b99 --- /dev/null +++ b/test/forge.test.ts @@ -0,0 +1,452 @@ +// The forge reads answer the same through GitHub and through Kixel Quest. The fake Kixel Quest serves each read by +// running the GitHub backend on a fake GitHub, as its index's fallthrough does, so an answer that differs is the +// wire's doing: a field lost, reordered, or retyped between the two. +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, test } from "vitest"; + +import { + type Forge, + type ForgeCall, + FORGE_CALLS, + type Holdings, + type PullRequest, + forgeJson, + parseForgeAnswer, + parseForgeInfo, + parseForgeRequest, +} from "../src/core"; +import { type ForgeDependencies, forgeFor, KixelQuest, KixelQuestForge } from "../src/cli/forge"; +import { waitForActivity, WaitTimeout } from "../src/cli/wait"; +import { type GitHubDependencies } from "../src/github/client"; +import { GitHubForge } from "../src/github/forge"; +import * as status from "./status-fakes"; +import * as wait from "./wait-fakes"; + +const URL_ = "https://kixel.quest"; +const TOKEN = "kq-token"; +const repository = { owner: "example", repo: "project" }; + +/** A fake Kixel Quest serving `github`'s answers to the person `login`, at `asOf`. */ +function kixelQuest( + github: () => GitHubDependencies, + options: { login?: string; repositories?: string[]; asOf?: string | null; fail?: number; answer?: unknown } = {}, +) { + const requests: { method: string; path: string; body: unknown }[] = []; + const fetch = async (input: string | URL | Request, init?: RequestInit): Promise => { + const url = new URL(String(input)); + const method = init?.method ?? "GET"; + const body = init?.body === undefined ? undefined : JSON.parse(String(init.body)); + requests.push({ method, path: url.pathname, body }); + if (new Headers(init?.headers).get("authorization") !== `Bearer ${TOKEN}`) + return Response.json({ error: "This token was never issued here, or it was revoked." }, { status: 401 }); + if (options.fail) return Response.json({ error: "index unavailable" }, { status: options.fail }); + if (method === "GET" && url.pathname === "/forge") + return Response.json({ + login: options.login ?? "waiter", + repositories: options.repositories ?? ["example/project"], + }); + const call = /^\/forge\/(\w+)$/.exec(url.pathname)?.[1] as ForgeCall | undefined; + if (method !== "POST" || call === undefined || !FORGE_CALLS.includes(call)) + return Response.json({ error: "no such read" }, { status: 404 }); + if (options.answer !== undefined) return Response.json(options.answer); + const forge = new GitHubForge(github(), options.login ?? "waiter"); + const value = await serve(forge, call, parseForgeRequest(call, body)); + return new Response(forgeJson({ value, asOf: options.asOf ?? null }), { + headers: { "content-type": "application/json" }, + }); + }; + return { fetch, requests }; +} + +/** One read, as Kixel Quest's fallthrough answers it. */ +async function serve(forge: Forge, call: ForgeCall, request: any): Promise { + switch (call) { + case "status": + return (await forge.status(request.pull)).value; + case "pulls": + return (await forge.pulls(request.repository)).value; + case "held": + return (await forge.held(request.sources, request.branches)).value; + case "watch": + return (await forge.watch(request.pull, { since: request.from ?? undefined, deadline: Infinity }).poll()) + .value; + } +} + +let config: string | undefined; +afterEach(() => { + if (config) rmSync(config, { recursive: true, force: true }); + config = undefined; +}); + +/** Forge dependencies whose token file pairs `TOKEN` with Kixel Quest, unless `token` is false. */ +function dependencies( + fetch: ForgeDependencies["fetch"], + github: () => GitHubDependencies, + env: NodeJS.ProcessEnv = {}, + token = true, +): ForgeDependencies { + config = mkdtempSync(join(tmpdir(), "quest-forge-")); + if (token) { + mkdirSync(join(config, "quest")); + writeFileSync(join(config, "quest", "records.json"), JSON.stringify({ [URL_]: TOKEN })); + } + return { env: { XDG_CONFIG_HOME: config, ...env }, fetch, now: () => 0, github }; +} + +/** Kixel Quest's backend over a fake serving `github`. */ +async function throughKixelQuest(github: () => GitHubDependencies, options?: Parameters[1]) { + const server = kixelQuest(github, options); + // Kixel Quest's reads keep the fake GitHub's clock, which a wait's deadline is set by. + const forge = await forgeFor(repository, { ...dependencies(server.fetch, github), now: () => github().now() }); + expect(forge).toBeInstanceOf(KixelQuestForge); + return { forge, server }; +} + +describe("status", () => { + const scenarios: [string, () => ReturnType][] = [ + [ + "checks, reviews, reactions, and threads", + () => + status.setup( + [ + status.pull({ + checks: status.page([ + status.run("lint", "COMPLETED", "FAILURE", true), + status.run("test", "IN_PROGRESS", null, true), + status.run("build", "COMPLETED", "SUCCESS", true), + { __typename: "StatusContext", context: "ci/legacy", state: "ERROR", targetUrl: null }, + ]), + reviews: status.page([ + status.review("alice", "APPROVED", status.B, 1), + status.review("alice", "COMMENTED", status.A, 3, [ + { + content: "THUMBS_UP", + createdAt: "2026-10-07T12:04:00Z", + user: { login: "codex[bot]" }, + }, + ]), + status.review("gone", "COMMENTED", null, 5), + ]), + threads: status.page([ + status.thread("T1", true), + status.thread("T2", false, null, "author"), + ]), + reactions: [{ content: "EYES", createdAt: "2026-10-07T12:00:00Z", user: null }], + }), + ], + { runs: [] }, + ), + ], + [ + "a queued draft with auto-merge", + () => + status.setup([ + status.pull({ + isDraft: true, + reviewDecision: null, + autoMergeRequest: { + enabledAt: "2026-10-07T12:00:00Z", + mergeMethod: "SQUASH", + enabledBy: { login: "kixelated" }, + }, + mergeQueueEntry: { state: "AWAITING_CHECKS", position: 2, enqueuedAt: "2026-10-07T12:01:00Z" }, + checks: null, + reviews: status.page([]), + threads: status.page([]), + }), + ]), + ], + [ + "a maintainer decision and a hold", + () => + status.setup( + [ + status.pull({ + checks: null, + reviews: status.page([]), + threads: status.page([]), + labels: { nodes: [{ name: "quest:active" }] }, + }), + ], + { + now: Date.parse("2026-10-07T12:00:00Z"), + holdFields: { + timelineItems: { + nodes: [ + { + __typename: "LabeledEvent", + id: "token", + createdAt: "2026-10-07T11:00:00Z", + label: { name: "quest:active" }, + }, + ], + }, + }, + eventPages: [ + { + rows: [ + { + node_id: "token", + event: "labeled", + label: { name: "quest:active" }, + url: "event-url", + }, + ], + }, + ], + signals: { + comments: status.page([ + { + author: { __typename: "User", login: "kixelated" }, + authorAssociation: "OWNER", + body: "Maintainer decision: raise the timeout.", + createdAt: "2026-10-16T01:00:00Z", + url: `${status.URL_}#issuecomment-9`, + }, + ]), + }, + }, + ), + ], + ]; + + test.each(scenarios)("%s reads the same through Kixel Quest as from GitHub", async (_, scenario) => { + const direct = await new GitHubForge(scenario().deps).status(status.pr); + const fixture = scenario(); + const { forge } = await throughKixelQuest(() => fixture.deps, { asOf: "2026-10-07T12:10:00Z" }); + const served = await forge.status(status.pr); + expect(served.value).toEqual(direct.value); + // `quest status --json` prints the same bytes either way. + expect(JSON.stringify(served.value)).toBe(JSON.stringify(direct.value)); + expect([direct.asOf, served.asOf]).toEqual([null, "2026-10-07T12:10:00Z"]); + }); +}); + +/** A fake GitHub holding open PRs and a merged one, as the claim reads list them. */ +function claimsGitHub(): GitHubDependencies { + const pull = (number: number, ref: string, extra: Record = {}) => ({ + number, + html_url: `https://github.com/example/project/pull/${number}`, + head: { ref, sha: "c".repeat(40), repo: { full_name: "example/project" } }, + draft: true, + created_at: `2026-10-0${number}T00:00:00Z`, + updated_at: `2026-10-0${number}T01:00:00Z`, + body: number === 2 ? "## Waiting\n\n- Maintainer: pick" : "", + ...extra, + }); + const open = [pull(1, "quest/m0/one"), pull(2, "quest/m0/two"), pull(3, "feature", { draft: false, body: null })]; + const merged = [pull(4, "quest/m0/done", { head: { ref: "quest/m0/done", sha: "d".repeat(40) }, merged_at: "x" })]; + return { + token: "test-token", + quota: "fail", + now: () => 0, + sleep: async () => {}, + warn: () => {}, + fetch: async (input) => { + const url = new URL(String(input)); + if (url.pathname !== "/repos/example/project/pulls") throw new Error(`unexpected ${url.pathname}`); + if (url.searchParams.get("state") === "open") return Response.json(open); + const head = url.searchParams.get("head"); + return Response.json(merged.filter((row) => `example:${row.head.ref}` === head)); + }, + }; +} + +test("open PRs and claims read the same through Kixel Quest as from GitHub, landed branches included", async () => { + const sources = { + upstream: { + repository, + tips: new Map([ + ["quest/m0/one", "c".repeat(40)], + ["quest/m0/done", "d".repeat(40)], + ["quest/m0/pushed", "e".repeat(40)], + ]), + }, + }; + const branches = ["quest/m0/one", "quest/m0/two", "quest/m0/done", "quest/m0/pushed", "quest/m0/free"]; + const github = new GitHubForge(claimsGitHub()); + const { forge, server } = await throughKixelQuest(claimsGitHub); + expect((await forge.pulls(repository)).value).toEqual((await github.pulls(repository)).value); + const direct = (await github.held(sources, branches)).value; + const served = (await forge.held(sources, branches)).value; + expect(served).toEqual(direct); + expect(served.claims.map((claim) => claim.branch)).toEqual(["quest/m0/one", "quest/m0/pushed", "quest/m0/two"]); + expect([...served.landed]).toEqual([["quest/m0/done", "d".repeat(40)]]); + // The tips git read travel with the request, so Kixel Quest judges the branches the person sees. + expect(server.requests.find((request) => request.path === "/forge/held")?.body).toMatchObject({ + sources: { upstream: { tips: { "quest/m0/one": "c".repeat(40) } } }, + }); +}); + +describe("wait", () => { + const scenarios: [string, () => ReturnType][] = [ + [ + "a review already on the head", + () => + wait.setup([ + wait.pull(), + wait.response([wait.pushed()]), + wait.response([wait.committed(wait.A), wait.reviewed()]), + ]), + ], + [ + "a push found on the third poll", + () => + wait.setup([ + wait.pull(), + wait.response([wait.pushed()]), + wait.response([wait.committed(wait.A)]), + wait.response([wait.committed(wait.A)]), + wait.response([wait.committed(wait.A), wait.committed(wait.B)]), + ]), + ], + [ + "the waiter's own reply, then another's", + () => + wait.setup( + [wait.pull(), wait.response([wait.pushed()]), wait.response([]), wait.response([])], + [wait.A], + { + comments: [ + wait.response([wait.replied(2, wait.POINT, "waiter")]), + wait.response([wait.replied(2, wait.POINT, "waiter"), wait.replied(3)]), + ], + }, + ), + ], + ]; + + test.each(scenarios)("%s wakes the same through Kixel Quest as from GitHub", async (_, scenario) => { + const direct = scenario(); + const expected = await waitForActivity(wait.pr, {}, new GitHubForge(direct.deps), direct.deps); + const fixture = scenario(); + const { forge } = await throughKixelQuest(() => fixture.deps); + expect(await waitForActivity(wait.pr, {}, forge, fixture.deps)).toEqual(expected); + expect(fixture.sleeps).toEqual(direct.sleeps); + }); + + test("a timeout resumes from Kixel Quest's cursor and says how current its index was", async () => { + const fixture = wait.setup([wait.pull(), wait.response([wait.pushed()]), wait.response([]), wait.response([])]); + const { forge } = await throughKixelQuest(() => fixture.deps, { asOf: "2026-10-07T12:09:00Z" }); + const error = await waitForActivity(wait.pr, { timeout: 60 }, forge, fixture.deps).catch((e: unknown) => e); + expect(error).toBeInstanceOf(WaitTimeout); + expect((error as WaitTimeout).cursor).toMatch(/^q1\./); + expect((error as Error).message).toBe( + "timed out waiting for pull request activity; Kixel Quest's last answer was current to 2026-10-07T12:09:00Z", + ); + }); +}); + +describe("choosing the forge", () => { + const unreachable = (): GitHubDependencies => { + throw new Error("read GitHub"); + }; + + test("a repository Kixel Quest does not serve reads GitHub", async () => { + const server = kixelQuest(unreachable); + const deps = dependencies(server.fetch, claimsGitHub); + expect(await forgeFor({ owner: "other", repo: "project" }, deps)).toBeInstanceOf(GitHubForge); + // Kixel Quest names repositories in lowercase; GitHub ignores case. + expect(await forgeFor({ owner: "Example", repo: "Project" }, deps)).toBeInstanceOf(KixelQuestForge); + }); + + test("without a token, or with QUEST_FORGE=github, reads go to GitHub and never ask Kixel Quest", async () => { + const server = kixelQuest(unreachable); + expect(await forgeFor(repository, dependencies(server.fetch, claimsGitHub, {}, false))).toBeInstanceOf( + GitHubForge, + ); + const forced = await forgeFor(repository, dependencies(server.fetch, claimsGitHub, { QUEST_FORGE: "github" })); + expect(forced).toBeInstanceOf(GitHubForge); + expect(server.requests).toEqual([]); + await expect( + forgeFor(repository, dependencies(server.fetch, claimsGitHub, { QUEST_FORGE: "gitlab" })), + ).rejects.toThrow("QUEST_FORGE is gitlab; set it to github to read GitHub, or leave it unset"); + }); + + test("QUEST_KIXEL_URL names another Kixel Quest, whose own token the file pairs with it", async () => { + const server = kixelQuest(unreachable); + const deps = dependencies(server.fetch, unreachable, { QUEST_KIXEL_URL: "http://localhost:8787" }); + // The token file pairs the token with kixel.quest only, so the local one gets none and reads go to GitHub. + await expect(forgeFor(repository, deps)).rejects.toThrow("read GitHub"); + writeFileSync(join(config!, "quest", "records.json"), JSON.stringify({ "http://localhost:8787": TOKEN })); + expect(await forgeFor(repository, deps)).toBeInstanceOf(KixelQuestForge); + expect(server.requests.map((request) => new URL(request.path, "http://localhost:8787").pathname)).toEqual([ + "/forge", + ]); + await expect( + forgeFor(repository, { ...deps, env: { ...deps.env, QUEST_KIXEL_URL: "http://example.com" } }), + ).rejects.toThrow("not an HTTPS URL"); + }); + + test("a Kixel Quest error fails the read, naming the setting that reads GitHub", async () => { + const override = "set QUEST_FORGE=github to read GitHub"; + const down = kixelQuest(unreachable, { fail: 503 }); + await expect(forgeFor(repository, dependencies(down.fetch, unreachable))).rejects.toThrow( + `Kixel Quest (${URL_}) failed GET /forge: HTTP 503, index unavailable; ${override}`, + ); + const refused = kixelQuest(unreachable); + const deps = dependencies(refused.fetch, unreachable); + writeFileSync(join(config!, "quest", "records.json"), JSON.stringify({ [URL_]: "revoked" })); + await expect(forgeFor(repository, deps)).rejects.toThrow(`it refused the token`); + await expect(forgeFor(repository, deps)).rejects.toThrow(override); + const malformed = kixelQuest(unreachable, { answer: { value: [], asOf: null, extra: true } }); + const forge = await forgeFor(repository, dependencies(malformed.fetch, unreachable)); + await expect(forge.pulls(repository)).rejects.toThrow( + `Kixel Quest (${URL_}) failed POST /forge/pulls: malformed forge answer.extra: expected no such field; ${override}`, + ); + }); + + test("the person is the token's, not the reading credential's", async () => { + const server = kixelQuest(unreachable, { login: "kixelated" }); + const forge = new KixelQuestForge(new KixelQuest(URL_, TOKEN, dependencies(server.fetch, unreachable))); + expect(await forge.viewer()).toBe("kixelated"); + expect(await new GitHubForge(claimsGitHub(), "kixelated").viewer()).toBe("kixelated"); + }); +}); + +describe("wire", () => { + const pull: PullRequest = { owner: "example", repo: "project", number: 7 }; + + test("requests and answers round-trip, maps included", () => { + const holdings: Holdings = { + claims: [{ branch: "quest/m0/one", url: null, pull: null }], + landed: new Map([["quest/m0/done", "d".repeat(40)]]), + }; + const sources = { upstream: { repository, tips: new Map([["quest/m0/one", "c".repeat(40)]]) } }; + expect(parseForgeRequest("held", JSON.parse(forgeJson({ sources, branches: ["quest/m0/one"] })))).toEqual({ + sources, + branches: ["quest/m0/one"], + }); + expect(parseForgeAnswer("held", JSON.parse(forgeJson({ value: holdings, asOf: null })))).toEqual({ + value: holdings, + asOf: null, + }); + expect(parseForgeRequest("watch", { pull, from: null })).toEqual({ pull, from: null }); + expect(parseForgeInfo({ login: "kixelated", repositories: ["moq-dev/quest"] })).toEqual({ + login: "kixelated", + repositories: ["moq-dev/quest"], + }); + }); + + test("anything missing, extra, or ill-typed is refused whole", () => { + expect(() => parseForgeRequest("status", { pull: { ...pull, number: 0 } })).toThrow("request.pull.number"); + expect(() => parseForgeRequest("status", { pull, extra: 1 })).toThrow("request.extra: expected no such field"); + expect(() => parseForgeRequest("held", { sources: { upstream: { repository } }, branches: ["main"] })).toThrow( + "request.branches[0]: expected a quest branch", + ); + expect(() => + parseForgeAnswer("held", { value: { claims: [], landed: { "quest/m0/a": "short" } }, asOf: null }), + ).toThrow("answer.value.landed.quest/m0/a: expected a full commit SHA"); + expect(() => parseForgeAnswer("watch", { value: { events: [], cursor: "q1.x" }, asOf: null })).toThrow( + "answer.value.pollInterval: expected a value", + ); + expect(() => parseForgeAnswer("pulls", { value: [], asOf: "yesterday" })).toThrow("answer.asOf"); + expect(() => parseForgeInfo({ login: "kixelated", repositories: ["Moq-Dev/Quest"] })).toThrow( + "lowercase owner/repo", + ); + }); +}); diff --git a/test/status-fakes.ts b/test/status-fakes.ts new file mode 100644 index 00000000..05b113c5 --- /dev/null +++ b/test/status-fakes.ts @@ -0,0 +1,229 @@ +// A fake GitHub for `quest status`: recorded GraphQL answers and the REST reads around them. +import { expect } from "vitest"; + +import { type GitHubDependencies } from "../src/github/client"; + +export const A = "a".repeat(40); +export const B = "b".repeat(40); +export const pr = { owner: "example", repo: "project", number: 1 }; +export const URL_ = "https://github.com/example/project/pull/1"; + +export type Node = Record; +export const page = (nodes: Node[], next?: string) => ({ + pageInfo: { hasNextPage: next !== undefined, endCursor: next ?? null }, + nodes, +}); + +/** A recorded GraphQL response; omitted connections stand for ones the query skipped. */ +export const CI = ".github/workflows/ci.yml"; + +export function pull( + fields: { + head?: string; + checks?: ReturnType | null; + reviews?: ReturnType; + threads?: ReturnType; + reactions?: Node[]; + } & Node = {}, +) { + const { head = A, checks, reviews, threads, reactions = [], ...rest } = fields; + return { + data: { + repository: { + pullRequest: { + id: "PR_1", + url: URL_, + body: "Summary.", + updatedAt: "2026-10-07T12:00:00Z", + baseRefName: "main", + baseRefOid: "b".repeat(40), + headRefName: "quest/m0/example", + isMergeQueueEnabled: false, + labels: { nodes: [] }, + state: "OPEN", + isDraft: false, + headRefOid: head, + mergeable: "MERGEABLE", + mergeStateStatus: "BLOCKED", + reviewDecision: "REVIEW_REQUIRED", + autoMergeRequest: null, + mergeQueueEntry: null, + timelineItems: { nodes: [] }, + reactions: { nodes: reactions }, + commits: { + nodes: [ + { + commit: { + oid: head, + statusCheckRollup: + checks === null + ? null + : { state: "FAILURE", ...(checks ? { contexts: checks } : {}) }, + }, + }, + ], + }, + ...(reviews ? { reviews } : {}), + ...(threads ? { reviewThreads: threads } : {}), + ...rest, + }, + }, + }, + }; +} + +export function run(name: string, status: string, conclusion: string | null, isRequired: boolean) { + return { + __typename: "CheckRun", + name, + status, + conclusion, + detailsUrl: `https://github.com/example/project/actions/runs/1/job/${name}`, + isRequired, + }; +} + +export function review(login: string, state: string, commit: string | null, id: number, reactions: Node[] = []) { + return { + author: { login }, + state, + submittedAt: `2026-10-07T12:0${id}:00Z`, + url: `${URL_}#pullrequestreview-${id}`, + commit: commit === null ? null : { oid: commit }, + reactions: { nodes: reactions }, + }; +} + +export function thread(id: string, isResolved: boolean, line: number | null = 3, author = "reviewer") { + return { + id, + isResolved, + isOutdated: line === null, + path: "src/a.ts", + line, + originalLine: 2, + comments: { nodes: [{ author: { login: author }, url: `${URL_}#discussion_r${id}` }] }, + }; +} + +export function setup( + bodies: unknown[], + options: { + now?: number; + holdFields?: Node; + eventPages?: { rows: Node[]; next?: string }[]; + /** Pages of the head repository's activity, newest first. */ + activity?: { rows: Node[]; next?: string; status?: number }[]; + warnings?: string[]; + /** The base-to-head diff per compared head, or the status GitHub refuses it with. */ + diffs?: Record; + /** The PR's reviews, threads, and comments as the signal reader reads them; none by default. */ + signals?: Node; + /** The base's active ruleset rules. */ + rules?: Node[]; + /** The base branch is gone, so reading it fails. */ + noBase?: boolean; + /** The head's workflow runs, as `GET /actions/runs` lists them. */ + runs?: Node[]; + } = {}, +) { + const queries: Record[] = []; + const texts: string[] = []; + const holdQueries: Record[] = []; + const eventRequests: string[] = []; + let last: ReturnType | undefined; + const eventPages = [...(options.eventPages ?? [])]; + const activityPages = [...(options.activity ?? [])]; + const activityRequests: string[] = []; + const deps: GitHubDependencies = { + token: "test-token", + quota: "wait", + now: () => options.now ?? 0, + sleep: async () => {}, + warn: (message) => options.warnings?.push(message), + fetch: async (url, init) => { + const path = new URL(String(url)); + if (path.pathname === "/repos/fork/project/activity") { + activityRequests.push(`${path.pathname}${path.search}`); + const page = activityPages.shift(); + if (!page) return Response.json({ message: "Not Found" }, { status: 404 }); + if (page.status === 403) + return Response.json({ message: "Resource not accessible by integration" }, { status: 403 }); + return Response.json(page.rows, { headers: page.next ? { Link: `<${page.next}>; rel="next"` } : {} }); + } + // Ruleset workflows name their repository by ID: 1 is this one, 2 another. + if (path.pathname === "/repositories/1") return Response.json({ full_name: "example/project" }); + if (path.pathname === "/repositories/2") return Response.json({ full_name: "example/policies" }); + if (path.pathname === "/repos/example/project/branches/main") + return options.noBase + ? Response.json({ message: "Branch not found" }, { status: 404 }) + : Response.json({ protection: { enabled: false } }); + if (path.pathname === "/repos/example/project/rules/branches/main") + return Response.json(options.rules ?? []); + if (path.pathname === "/repos/example/project/actions/runs") { + if (!options.runs) throw new Error("unexpected workflow run request"); + return Response.json({ total_count: options.runs.length, workflow_runs: options.runs }); + } + const compare = /^\/repos\/example\/project\/compare\/main\.\.\.([0-9a-f]{40})$/.exec(path.pathname); + if (compare) { + expect(new Headers(init?.headers).get("Accept")).toBe("application/vnd.github.diff"); + const diff = options.diffs?.[compare[1]!]; + if (diff === undefined) throw new Error("unexpected compare request"); + return typeof diff === "number" + ? Response.json({ message: "No diff" }, { status: diff }) + : new Response(diff); + } + if (path.pathname !== "/graphql") { + expect(path.pathname).toBe("/repos/example/project/issues/1/events"); + eventRequests.push(String(url)); + const page = eventPages.shift(); + if (!page) throw new Error("unexpected event request"); + return Response.json(page.rows, { headers: page.next ? { Link: `<${page.next}>; rel="next"` } : {} }); + } + const request = JSON.parse(String(init?.body)); + if (request.query.includes("p1: pullRequest(number: 1)")) { + if (!last) throw new Error("signals read before PR state"); + const head = last.data.repository.pullRequest.headRefOid; + const empty = { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] }; + return Response.json({ + data: { + repository: { + p1: { + headRefOid: head, + commits: { nodes: [{ commit: { oid: head, committedDate: "2026-10-16T00:00:00Z" } }] }, + reviews: empty, + reviewThreads: empty, + comments: empty, + ...options.signals, + }, + }, + }, + }); + } + if (request.query.includes("query HoldOwnership(")) { + holdQueries.push(request.variables); + if (!last) throw new Error("ownership read before PR state"); + const row = last.data.repository.pullRequest; + const events = (row.timelineItems as { nodes: Node[] }).nodes.filter((event) => + ["LabeledEvent", "AutoMergeEnabledEvent", "AddedToMergeQueueEvent"].includes( + String(event.__typename), + ), + ); + return Response.json({ + data: { + repository: { + pullRequest: { ...row, timelineItems: { nodes: events }, ...options.holdFields }, + }, + }, + }); + } + queries.push(request.variables); + texts.push(request.query); + const body = bodies.shift(); + if (body === undefined) throw new Error("unexpected request"); + last = body as ReturnType; + return Response.json(body); + }, + }; + return { deps, queries, texts, holdQueries, eventRequests, activityRequests }; +} diff --git a/test/status.test.ts b/test/status.test.ts index e2637b03..3fe38ecb 100644 --- a/test/status.test.ts +++ b/test/status.test.ts @@ -1,234 +1,10 @@ import { describe, expect, test } from "vitest"; -import { GitHub, type GitHubDependencies } from "../src/github/client"; +import { GitHub } from "../src/github/client"; import { main } from "../src/cli/main"; import { statusLines } from "../src/cli/status"; import { pullRequestStatus, requiredOf } from "../src/github/status"; - -const A = "a".repeat(40); -const B = "b".repeat(40); -const pr = { owner: "example", repo: "project", number: 1 }; -const URL_ = "https://github.com/example/project/pull/1"; - -type Node = Record; -const page = (nodes: Node[], next?: string) => ({ - pageInfo: { hasNextPage: next !== undefined, endCursor: next ?? null }, - nodes, -}); - -/** A recorded GraphQL response; omitted connections stand for ones the query skipped. */ -const CI = ".github/workflows/ci.yml"; - -function pull( - fields: { - head?: string; - checks?: ReturnType | null; - reviews?: ReturnType; - threads?: ReturnType; - reactions?: Node[]; - } & Node = {}, -) { - const { head = A, checks, reviews, threads, reactions = [], ...rest } = fields; - return { - data: { - repository: { - pullRequest: { - id: "PR_1", - url: URL_, - body: "Summary.", - updatedAt: "2026-10-07T12:00:00Z", - baseRefName: "main", - baseRefOid: "b".repeat(40), - headRefName: "quest/m0/example", - isMergeQueueEnabled: false, - labels: { nodes: [] }, - state: "OPEN", - isDraft: false, - headRefOid: head, - mergeable: "MERGEABLE", - mergeStateStatus: "BLOCKED", - reviewDecision: "REVIEW_REQUIRED", - autoMergeRequest: null, - mergeQueueEntry: null, - timelineItems: { nodes: [] }, - reactions: { nodes: reactions }, - commits: { - nodes: [ - { - commit: { - oid: head, - statusCheckRollup: - checks === null - ? null - : { state: "FAILURE", ...(checks ? { contexts: checks } : {}) }, - }, - }, - ], - }, - ...(reviews ? { reviews } : {}), - ...(threads ? { reviewThreads: threads } : {}), - ...rest, - }, - }, - }, - }; -} - -function run(name: string, status: string, conclusion: string | null, isRequired: boolean) { - return { - __typename: "CheckRun", - name, - status, - conclusion, - detailsUrl: `https://github.com/example/project/actions/runs/1/job/${name}`, - isRequired, - }; -} - -function review(login: string, state: string, commit: string | null, id: number, reactions: Node[] = []) { - return { - author: { login }, - state, - submittedAt: `2026-10-07T12:0${id}:00Z`, - url: `${URL_}#pullrequestreview-${id}`, - commit: commit === null ? null : { oid: commit }, - reactions: { nodes: reactions }, - }; -} - -function thread(id: string, isResolved: boolean, line: number | null = 3, author = "reviewer") { - return { - id, - isResolved, - isOutdated: line === null, - path: "src/a.ts", - line, - originalLine: 2, - comments: { nodes: [{ author: { login: author }, url: `${URL_}#discussion_r${id}` }] }, - }; -} - -function setup( - bodies: unknown[], - options: { - now?: number; - holdFields?: Node; - eventPages?: { rows: Node[]; next?: string }[]; - /** Pages of the head repository's activity, newest first. */ - activity?: { rows: Node[]; next?: string; status?: number }[]; - warnings?: string[]; - /** The base-to-head diff per compared head, or the status GitHub refuses it with. */ - diffs?: Record; - /** The PR's reviews, threads, and comments as the signal reader reads them; none by default. */ - signals?: Node; - /** The base's active ruleset rules. */ - rules?: Node[]; - /** The base branch is gone, so reading it fails. */ - noBase?: boolean; - /** The head's workflow runs, as `GET /actions/runs` lists them. */ - runs?: Node[]; - } = {}, -) { - const queries: Record[] = []; - const texts: string[] = []; - const holdQueries: Record[] = []; - const eventRequests: string[] = []; - let last: ReturnType | undefined; - const eventPages = [...(options.eventPages ?? [])]; - const activityPages = [...(options.activity ?? [])]; - const activityRequests: string[] = []; - const deps: GitHubDependencies = { - token: "test-token", - quota: "wait", - now: () => options.now ?? 0, - sleep: async () => {}, - warn: (message) => options.warnings?.push(message), - fetch: async (url, init) => { - const path = new URL(String(url)); - if (path.pathname === "/repos/fork/project/activity") { - activityRequests.push(`${path.pathname}${path.search}`); - const page = activityPages.shift(); - if (!page) return Response.json({ message: "Not Found" }, { status: 404 }); - if (page.status === 403) - return Response.json({ message: "Resource not accessible by integration" }, { status: 403 }); - return Response.json(page.rows, { headers: page.next ? { Link: `<${page.next}>; rel="next"` } : {} }); - } - // Ruleset workflows name their repository by ID: 1 is this one, 2 another. - if (path.pathname === "/repositories/1") return Response.json({ full_name: "example/project" }); - if (path.pathname === "/repositories/2") return Response.json({ full_name: "example/policies" }); - if (path.pathname === "/repos/example/project/branches/main") - return options.noBase - ? Response.json({ message: "Branch not found" }, { status: 404 }) - : Response.json({ protection: { enabled: false } }); - if (path.pathname === "/repos/example/project/rules/branches/main") - return Response.json(options.rules ?? []); - if (path.pathname === "/repos/example/project/actions/runs") { - if (!options.runs) throw new Error("unexpected workflow run request"); - return Response.json({ total_count: options.runs.length, workflow_runs: options.runs }); - } - const compare = /^\/repos\/example\/project\/compare\/main\.\.\.([0-9a-f]{40})$/.exec(path.pathname); - if (compare) { - expect(new Headers(init?.headers).get("Accept")).toBe("application/vnd.github.diff"); - const diff = options.diffs?.[compare[1]!]; - if (diff === undefined) throw new Error("unexpected compare request"); - return typeof diff === "number" - ? Response.json({ message: "No diff" }, { status: diff }) - : new Response(diff); - } - if (path.pathname !== "/graphql") { - expect(path.pathname).toBe("/repos/example/project/issues/1/events"); - eventRequests.push(String(url)); - const page = eventPages.shift(); - if (!page) throw new Error("unexpected event request"); - return Response.json(page.rows, { headers: page.next ? { Link: `<${page.next}>; rel="next"` } : {} }); - } - const request = JSON.parse(String(init?.body)); - if (request.query.includes("p1: pullRequest(number: 1)")) { - if (!last) throw new Error("signals read before PR state"); - const head = last.data.repository.pullRequest.headRefOid; - const empty = { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] }; - return Response.json({ - data: { - repository: { - p1: { - headRefOid: head, - commits: { nodes: [{ commit: { oid: head, committedDate: "2026-10-16T00:00:00Z" } }] }, - reviews: empty, - reviewThreads: empty, - comments: empty, - ...options.signals, - }, - }, - }, - }); - } - if (request.query.includes("query HoldOwnership(")) { - holdQueries.push(request.variables); - if (!last) throw new Error("ownership read before PR state"); - const row = last.data.repository.pullRequest; - const events = (row.timelineItems as { nodes: Node[] }).nodes.filter((event) => - ["LabeledEvent", "AutoMergeEnabledEvent", "AddedToMergeQueueEvent"].includes( - String(event.__typename), - ), - ); - return Response.json({ - data: { - repository: { - pullRequest: { ...row, timelineItems: { nodes: events }, ...options.holdFields }, - }, - }, - }); - } - queries.push(request.variables); - texts.push(request.query); - const body = bodies.shift(); - if (body === undefined) throw new Error("unexpected request"); - last = body as ReturnType; - return Response.json(body); - }, - }; - return { deps, queries, texts, holdQueries, eventRequests, activityRequests }; -} +import { A, B, pr, URL_, type Node, page, CI, pull, run, review, thread, setup } from "./status-fakes"; test("reports checks by requiredness, each reviewer's latest review against the head, and open threads", async () => { const fixture = setup( diff --git a/test/wait-fakes.ts b/test/wait-fakes.ts new file mode 100644 index 00000000..67f611e7 --- /dev/null +++ b/test/wait-fakes.ts @@ -0,0 +1,275 @@ +// A fake GitHub for `quest wait`: scripted REST pages and GraphQL answers, and a clock that advances as it sleeps. +import { type GitHubDependencies } from "../src/github/client"; +import { GitHubForge } from "../src/github/forge"; +import { waitForActivity, type WaitOptions } from "../src/cli/wait"; + +export const A = "a".repeat(40); +export const B = "b".repeat(40); +export const C = "c".repeat(40); +export const POINT = "2026-10-07T12:00:00Z"; +export const pr = { owner: "example", repo: "project", number: 1 }; +export const base = "/repos/example/project"; +export const timeline = `${base}/issues/1/timeline?per_page=100`; +/** The GitHub Actions app, which reports workflow check runs. */ +export const ACTIONS = 15368; + +export function response(body: unknown, headers?: Record, status = 200): Response { + return new Response(status === 304 ? null : JSON.stringify(body), { status, headers }); +} + +export function pull(headRepo: unknown = { full_name: "contributor/fork" }, sha = A) { + return response({ base: { sha: C }, head: { sha, ref: "feature/a", repo: headRepo } }); +} + +export function pushed(after = A, time = POINT, type = "push") { + return { activity_type: type, after, timestamp: time, actor: { login: "author" } }; +} + +export function committed(sha: string) { + return { + event: "committed", + sha, + committer: { name: "A Person", date: "2000-01-01T00:00:00Z" }, + html_url: `https://github.com/example/project/commit/${sha}`, + }; +} + +export function reviewed(id = 1, time = POINT) { + return { + event: "reviewed", + id, + submitted_at: time, + user: { login: "reviewer" }, + html_url: `https://github.com/example/project/pull/1#pullrequestreview-${id}`, + }; +} + +export function reactions( + pull: unknown[] = [], + reviews: unknown[] = [], + page: { hasNextPage: boolean; endCursor: string | null } = { hasNextPage: false, endCursor: null }, +) { + return response({ + data: { + viewer: { login: "waiter" }, + repository: { pullRequest: { reactions: { nodes: pull }, reviews: { pageInfo: page, nodes: reviews } } }, + }, + }); +} + +export function reacted(id: string, time = POINT, login = "codex[bot]", content = "THUMBS_UP") { + return { id, content, createdAt: time, user: { login } }; +} + +export function replied(id: number, time = POINT, login = "reviewer", inReplyTo: number | null = 1) { + return { + id, + in_reply_to_id: inReplyTo, + created_at: time, + user: { login }, + html_url: `https://github.com/example/project/pull/1#discussion_r${id}`, + }; +} + +export interface CheckFixture { + name: string; + required?: boolean; + /** A check run's conclusion, or a commit status's state; omitted while it runs. */ + result?: string; + time?: string; + status?: boolean; + /** The workflow file a job runs in, and whether its run is still going, so it may yet create jobs. */ + workflow?: string; + running?: boolean; + /** A check run's ID, which grows with each run; its place in the page by default. */ + id?: number; + /** The app behind a check run; GitHub Actions by default. */ + app?: number; + /** The check suite of the workflow run behind a check run. */ + suite?: number; +} + +/** The head's checks; `null` means the head has no checks at all. */ +export function checks( + contexts: CheckFixture[] | null = null, + head = A, + page: { hasNextPage: boolean; endCursor: string | null } = { hasNextPage: false, endCursor: null }, + listed = head, + extra: Record = {}, +) { + const node = (entry: CheckFixture, index: number) => + entry.status + ? { + __typename: "StatusContext", + context: entry.name, + state: entry.result ?? "PENDING", + createdAt: entry.time ?? POINT, + targetUrl: null, + isRequired: entry.required ?? false, + } + : { + __typename: "CheckRun", + databaseId: entry.id ?? index + 1, + name: entry.name, + status: entry.result ? "COMPLETED" : "IN_PROGRESS", + conclusion: entry.result ?? null, + completedAt: entry.result ? (entry.time ?? POINT) : null, + detailsUrl: `https://github.com/example/project/actions/runs/1/job/${entry.name.length}`, + isRequired: entry.required ?? false, + checkSuite: { + status: entry.result && !entry.running ? "COMPLETED" : "IN_PROGRESS", + databaseId: entry.suite ?? null, + app: { databaseId: entry.app ?? ACTIONS }, + workflowRun: { + file: { + path: entry.workflow ?? ".github/workflows/check.yml", + repositoryName: "example/project", + }, + }, + }, + }; + return response({ + data: { + repository: { + pullRequest: { + baseRefName: "main", + headRefOid: head, + ...extra, + commits: { + nodes: [ + { + commit: { + oid: listed, + statusCheckRollup: contexts && { + contexts: { pageInfo: page, nodes: contexts.map(node) }, + }, + }, + }, + ], + }, + }, + }, + }, + }); +} + +/** + * Review comments, reactions, and checks come from their own queues, empty once drained. + * The base branch requires `protected` through branch protection and `ruled` through rulesets, + * reported by GitHub Actions. `rules` adds further rules on a second page. + */ +export function setup( + responses: Response[], + baseline = [A], + side: { + comments?: Response[]; + edits?: Response[]; + graphql?: Response[]; + checks?: Response[]; + protected?: string[]; + /** Classic protection that lists only `contexts`, without `checks`. */ + contextsOnly?: boolean; + ruled?: string[]; + rules?: unknown[]; + /** The head's workflow runs, as `GET /actions/runs` lists them, one listing per read; the last repeats. */ + runs?: unknown[][]; + } = {}, +) { + let now = Date.parse("2026-10-07T12:10:00Z"); + const calls: { path: string; headers: Headers }[] = []; + const sideCalls: { path: string; headers: Headers; body?: unknown }[] = []; + const checkCalls: { path: string; headers: Headers; body?: unknown }[] = []; + const editCalls: { path: string; headers: Headers }[] = []; + const ruleCalls: { path: string; headers: Headers }[] = []; + const sleeps: number[] = []; + const warnings: string[] = []; + const deps: GitHubDependencies = { + token: "test-token", + quota: "wait", + now: () => now, + sleep: async (ms) => { + sleeps.push(ms); + now += ms; + }, + warn: (text) => warnings.push(text), + fetch: async (url, init) => { + const parsed = new URL(String(url)); + const call = { path: parsed.pathname + parsed.search, headers: new Headers(init?.headers) }; + if (parsed.pathname.endsWith("/issues/1/comments")) { + editCalls.push(call); + return side.edits?.shift() ?? response([]); + } + if (parsed.pathname.endsWith("/pulls/1/comments")) { + sideCalls.push(call); + return side.comments?.shift() ?? response([]); + } + if (parsed.pathname === "/graphql") { + const body = JSON.parse(String(init?.body)) as { query: string }; + if (body.query === "query { viewer { login } }") + return response({ data: { viewer: { login: "waiter" } } }); + if (body.query.includes("statusCheckRollup")) { + checkCalls.push({ ...call, body }); + return side.checks?.shift() ?? checks(); + } + sideCalls.push({ ...call, body }); + return side.graphql?.shift() ?? reactions(); + } + if (parsed.pathname === "/repositories/1") return Response.json({ full_name: "example/project" }); + if (parsed.pathname === `${base}/branches/main`) { + ruleCalls.push(call); + const contexts = side.protected ?? []; + const checks = contexts.map((context) => ({ context, app_id: null })); + const level = contexts.length ? "everyone" : "off"; + return response({ + protection: { + enabled: contexts.length > 0, + required_status_checks: side.contextsOnly + ? { enforcement_level: level, contexts } + : { enforcement_level: level, checks }, + }, + }); + } + if (parsed.pathname === `${base}/actions/runs` && side.runs) { + ruleCalls.push(call); + const listed = side.runs.length > 1 ? side.runs.shift()! : side.runs[0]!; + return response({ total_count: listed.length, workflow_runs: listed }); + } + if (parsed.pathname === `${base}/rules/branches/main`) { + ruleCalls.push(call); + if (parsed.searchParams.get("page") === "2") return response(side.rules); + const checks = (side.ruled ?? []).map((context) => ({ context, integration_id: ACTIONS })); + const next = `; rel="next"`; + return response( + [ + { type: "deletion" }, + ...(checks.length + ? [{ type: "required_status_checks", parameters: { required_status_checks: checks } }] + : []), + ], + side.rules ? { link: next } : undefined, + ); + } + calls.push(call); + if (parsed.pathname.endsWith("/commits")) return response(baseline.map((sha) => ({ sha }))); + const next = responses.shift(); + if (!next) throw new Error(`unexpected request: ${parsed.pathname + parsed.search}`); + return next; + }, + }; + return { deps, calls, sideCalls, checkCalls, editCalls, ruleCalls, sleeps, warnings, responses }; +} + +/** Wait on GitHub, with the fixture's clock. */ +export function waitOn(pull: typeof pr, options: WaitOptions, deps: GitHubDependencies): Promise { + return waitForActivity(pull, options, new GitHubForge(deps), deps); +} + +export function graphql(fixture: ReturnType) { + return fixture.sideCalls + .filter((call) => call.path === "/graphql") + .map((call) => call.body as { variables: Record }); +} + +export function cursor(lines: string[]): string { + return lines.at(-1)!.split(" ").at(-1)!; +} diff --git a/test/wait.test.ts b/test/wait.test.ts index a74de7e4..33a5418b 100644 --- a/test/wait.test.ts +++ b/test/wait.test.ts @@ -7,279 +7,30 @@ import { expect, test } from "vitest"; import { main } from "../src/cli/main"; import { InputError } from "../src/core"; import { pullRequest } from "../src/cli/github"; -import { GitHubForge } from "../src/github/forge"; -import { type GitHubDependencies } from "../src/github/client"; -import { waitForActivity, WaitTimeout, type WaitOptions } from "../src/cli/wait"; - -const A = "a".repeat(40); -const B = "b".repeat(40); -const C = "c".repeat(40); -const POINT = "2026-10-07T12:00:00Z"; -const pr = { owner: "example", repo: "project", number: 1 }; -const base = "/repos/example/project"; -const timeline = `${base}/issues/1/timeline?per_page=100`; -/** The GitHub Actions app, which reports workflow check runs. */ -const ACTIONS = 15368; - -function response(body: unknown, headers?: Record, status = 200): Response { - return new Response(status === 304 ? null : JSON.stringify(body), { status, headers }); -} - -function pull(headRepo: unknown = { full_name: "contributor/fork" }, sha = A) { - return response({ base: { sha: C }, head: { sha, ref: "feature/a", repo: headRepo } }); -} - -function pushed(after = A, time = POINT, type = "push") { - return { activity_type: type, after, timestamp: time, actor: { login: "author" } }; -} - -function committed(sha: string) { - return { - event: "committed", - sha, - committer: { name: "A Person", date: "2000-01-01T00:00:00Z" }, - html_url: `https://github.com/example/project/commit/${sha}`, - }; -} - -function reviewed(id = 1, time = POINT) { - return { - event: "reviewed", - id, - submitted_at: time, - user: { login: "reviewer" }, - html_url: `https://github.com/example/project/pull/1#pullrequestreview-${id}`, - }; -} - -function reactions( - pull: unknown[] = [], - reviews: unknown[] = [], - page: { hasNextPage: boolean; endCursor: string | null } = { hasNextPage: false, endCursor: null }, -) { - return response({ - data: { - viewer: { login: "waiter" }, - repository: { pullRequest: { reactions: { nodes: pull }, reviews: { pageInfo: page, nodes: reviews } } }, - }, - }); -} - -function reacted(id: string, time = POINT, login = "codex[bot]", content = "THUMBS_UP") { - return { id, content, createdAt: time, user: { login } }; -} - -function replied(id: number, time = POINT, login = "reviewer", inReplyTo: number | null = 1) { - return { - id, - in_reply_to_id: inReplyTo, - created_at: time, - user: { login }, - html_url: `https://github.com/example/project/pull/1#discussion_r${id}`, - }; -} - -interface CheckFixture { - name: string; - required?: boolean; - /** A check run's conclusion, or a commit status's state; omitted while it runs. */ - result?: string; - time?: string; - status?: boolean; - /** The workflow file a job runs in, and whether its run is still going, so it may yet create jobs. */ - workflow?: string; - running?: boolean; - /** A check run's ID, which grows with each run; its place in the page by default. */ - id?: number; - /** The app behind a check run; GitHub Actions by default. */ - app?: number; - /** The check suite of the workflow run behind a check run. */ - suite?: number; -} - -/** The head's checks; `null` means the head has no checks at all. */ -function checks( - contexts: CheckFixture[] | null = null, - head = A, - page: { hasNextPage: boolean; endCursor: string | null } = { hasNextPage: false, endCursor: null }, - listed = head, - extra: Record = {}, -) { - const node = (entry: CheckFixture, index: number) => - entry.status - ? { - __typename: "StatusContext", - context: entry.name, - state: entry.result ?? "PENDING", - createdAt: entry.time ?? POINT, - targetUrl: null, - isRequired: entry.required ?? false, - } - : { - __typename: "CheckRun", - databaseId: entry.id ?? index + 1, - name: entry.name, - status: entry.result ? "COMPLETED" : "IN_PROGRESS", - conclusion: entry.result ?? null, - completedAt: entry.result ? (entry.time ?? POINT) : null, - detailsUrl: `https://github.com/example/project/actions/runs/1/job/${entry.name.length}`, - isRequired: entry.required ?? false, - checkSuite: { - status: entry.result && !entry.running ? "COMPLETED" : "IN_PROGRESS", - databaseId: entry.suite ?? null, - app: { databaseId: entry.app ?? ACTIONS }, - workflowRun: { - file: { - path: entry.workflow ?? ".github/workflows/check.yml", - repositoryName: "example/project", - }, - }, - }, - }; - return response({ - data: { - repository: { - pullRequest: { - baseRefName: "main", - headRefOid: head, - ...extra, - commits: { - nodes: [ - { - commit: { - oid: listed, - statusCheckRollup: contexts && { - contexts: { pageInfo: page, nodes: contexts.map(node) }, - }, - }, - }, - ], - }, - }, - }, - }, - }); -} - -/** - * Review comments, reactions, and checks come from their own queues, empty once drained. - * The base branch requires `protected` through branch protection and `ruled` through rulesets, - * reported by GitHub Actions. `rules` adds further rules on a second page. - */ -function setup( - responses: Response[], - baseline = [A], - side: { - comments?: Response[]; - edits?: Response[]; - graphql?: Response[]; - checks?: Response[]; - protected?: string[]; - /** Classic protection that lists only `contexts`, without `checks`. */ - contextsOnly?: boolean; - ruled?: string[]; - rules?: unknown[]; - /** The head's workflow runs, as `GET /actions/runs` lists them, one listing per read; the last repeats. */ - runs?: unknown[][]; - } = {}, -) { - let now = Date.parse("2026-10-07T12:10:00Z"); - const calls: { path: string; headers: Headers }[] = []; - const sideCalls: { path: string; headers: Headers; body?: unknown }[] = []; - const checkCalls: { path: string; headers: Headers; body?: unknown }[] = []; - const editCalls: { path: string; headers: Headers }[] = []; - const ruleCalls: { path: string; headers: Headers }[] = []; - const sleeps: number[] = []; - const warnings: string[] = []; - const deps: GitHubDependencies = { - token: "test-token", - quota: "wait", - now: () => now, - sleep: async (ms) => { - sleeps.push(ms); - now += ms; - }, - warn: (text) => warnings.push(text), - fetch: async (url, init) => { - const parsed = new URL(String(url)); - const call = { path: parsed.pathname + parsed.search, headers: new Headers(init?.headers) }; - if (parsed.pathname.endsWith("/issues/1/comments")) { - editCalls.push(call); - return side.edits?.shift() ?? response([]); - } - if (parsed.pathname.endsWith("/pulls/1/comments")) { - sideCalls.push(call); - return side.comments?.shift() ?? response([]); - } - if (parsed.pathname === "/graphql") { - const body = JSON.parse(String(init?.body)) as { query: string }; - if (body.query === "query { viewer { login } }") return response({ data: { viewer: { login: "waiter" } } }); - if (body.query.includes("statusCheckRollup")) { - checkCalls.push({ ...call, body }); - return side.checks?.shift() ?? checks(); - } - sideCalls.push({ ...call, body }); - return side.graphql?.shift() ?? reactions(); - } - if (parsed.pathname === "/repositories/1") return Response.json({ full_name: "example/project" }); - if (parsed.pathname === `${base}/branches/main`) { - ruleCalls.push(call); - const contexts = side.protected ?? []; - const checks = contexts.map((context) => ({ context, app_id: null })); - const level = contexts.length ? "everyone" : "off"; - return response({ - protection: { - enabled: contexts.length > 0, - required_status_checks: side.contextsOnly - ? { enforcement_level: level, contexts } - : { enforcement_level: level, checks }, - }, - }); - } - if (parsed.pathname === `${base}/actions/runs` && side.runs) { - ruleCalls.push(call); - const listed = side.runs.length > 1 ? side.runs.shift()! : side.runs[0]!; - return response({ total_count: listed.length, workflow_runs: listed }); - } - if (parsed.pathname === `${base}/rules/branches/main`) { - ruleCalls.push(call); - if (parsed.searchParams.get("page") === "2") return response(side.rules); - const checks = (side.ruled ?? []).map((context) => ({ context, integration_id: ACTIONS })); - const next = `; rel="next"`; - return response( - [ - { type: "deletion" }, - ...(checks.length - ? [{ type: "required_status_checks", parameters: { required_status_checks: checks } }] - : []), - ], - side.rules ? { link: next } : undefined, - ); - } - calls.push(call); - if (parsed.pathname.endsWith("/commits")) return response(baseline.map((sha) => ({ sha }))); - const next = responses.shift(); - if (!next) throw new Error(`unexpected request: ${parsed.pathname + parsed.search}`); - return next; - }, - }; - return { deps, calls, sideCalls, checkCalls, editCalls, ruleCalls, sleeps, warnings, responses }; -} - -/** Wait on GitHub, with the fixture's clock. */ -function waitOn(pull: typeof pr, options: WaitOptions, deps: GitHubDependencies): Promise { - return waitForActivity(pull, options, new GitHubForge(deps), deps); -} - -function graphql(fixture: ReturnType) { - return fixture.sideCalls - .filter((call) => call.path === "/graphql") - .map((call) => call.body as { variables: Record }); -} - -function cursor(lines: string[]): string { - return lines.at(-1)!.split(" ").at(-1)!; -} +import { WaitTimeout } from "../src/cli/wait"; +import { + A, + B, + C, + POINT, + pr, + base, + timeline, + response, + pull, + pushed, + committed, + reviewed, + reactions, + reacted, + replied, + type CheckFixture, + checks, + setup, + waitOn, + graphql, + cursor, +} from "./wait-fakes"; test("default point includes reviews already submitted on the current head and uses the fork's push time", async () => { const fixture = setup([pull(), response([pushed()]), response([committed(A), reviewed()])]); @@ -1366,9 +1117,7 @@ test("results reached before an explicit starting point are not reported", async checks: [checks([{ name: "check", required: true, result: "FAILURE", time: LATER }])], protected: ["check"], }); - const timeout = await waitOn(pr, { since: LATEST, timeout: 10 }, fixture.deps).catch( - (error: unknown) => error, - ); + const timeout = await waitOn(pr, { since: LATEST, timeout: 10 }, fixture.deps).catch((error: unknown) => error); expect(timeout).toBeInstanceOf(WaitTimeout); }); @@ -1491,9 +1240,7 @@ test("a later reaction does not hide an older edit, and old cursors learn the ed const first = setup([pull(), response([pushed()]), response([committed(A)])], [A], { graphql: [reactions([reacted("r1", LATEST)])], }); - const previous = JSON.parse( - Buffer.from(cursor(await waitOn(pr, {}, first.deps)).slice(3), "base64url").toString(), - ); + const previous = JSON.parse(Buffer.from(cursor(await waitOn(pr, {}, first.deps)).slice(3), "base64url").toString()); delete previous.marks.edits; const old = `q1.${Buffer.from(JSON.stringify(previous)).toString("base64url")}`; const next = setup([response([committed(A)])], [A], { From b4696ab9bc856c73ce6b5396e04d0095751d48eb Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 10:41:00 -0800 Subject: [PATCH 4/8] feat(forge)!: read PR, claim, and wait state through a forge with a Kixel Quest backend quest status, quest wait, and the claim and draft reads of quest unblocked --unclaimed, quest start, and quest waiting go through a Forge interface. GitHubForge reads GitHub as before; KixelQuestForge reads Kixel Quest's /forge API for a person holding its token, for the repositories it says it serves. The read types and wire parsers move to quest/core. Co-Authored-By: Claude Opus 5.5 --- quest/m0/benchmark/records-endpoint.md | 4 ++- src/cli/breakage.ts | 12 +++++++-- src/cli/forge.ts | 2 ++ src/cli/hold.ts | 11 ++++++-- src/cli/land.ts | 3 +-- src/cli/review-eval.ts | 3 +-- src/cli/start.ts | 3 +-- src/cli/usage.ts | 35 +++++++++++++++----------- src/core/forge.ts | 6 ++++- 9 files changed, 53 insertions(+), 26 deletions(-) diff --git a/quest/m0/benchmark/records-endpoint.md b/quest/m0/benchmark/records-endpoint.md index c700560f..b2d92efe 100644 --- a/quest/m0/benchmark/records-endpoint.md +++ b/quest/m0/benchmark/records-endpoint.md @@ -34,7 +34,9 @@ no repository had committed yet). checkout with no endpoint. - Put the token on each host, and start its sender with `quest records install`, through kixel-ai/dotfiles, which owns the maintainer's host - configuration, not by hand. + configuration, not by hand. Only once Kixel Quest serves `GET /forge` + (kixel-ai/kixel.quest's `quest/m0/read-api.md`): with that token, every + forge read goes to Kixel Quest and fails until it answers. Tests: a session in a checkout whose remote Kixel Quest serves is sent with its `owner/repo`; one it refuses stays queued on the host; and the override diff --git a/src/cli/breakage.ts b/src/cli/breakage.ts index ec5600b2..1e3df9fd 100644 --- a/src/cli/breakage.ts +++ b/src/cli/breakage.ts @@ -1,7 +1,15 @@ // What a PR body says about breakage: the culprits its `## Caused by` names, and, for a culprit, how it was made and // checked, as its own body records it. -import { type Culprit, FINDERS, type Finder, SIZES, type Seat, type Size, recordedRisk } from "../core"; -import type { Repository } from "../core"; +import { + type Culprit, + type Finder, + FINDERS, + recordedRisk, + type Repository, + type Seat, + type Size, + SIZES, +} from "../core"; import { recorded } from "./models-record"; import { parseReview } from "./review-record"; import type { Pull } from "./usage"; diff --git a/src/cli/forge.ts b/src/cli/forge.ts index 30a46272..a8c36dea 100644 --- a/src/cli/forge.ts +++ b/src/cli/forge.ts @@ -117,6 +117,8 @@ export class KixelQuest { try { response = await fetch(`${this.url}${path}`, { method, + // The token is Kixel Quest's alone, so it follows no redirect elsewhere. + redirect: "error", headers: { Authorization: `Bearer ${this.token}`, Accept: "application/json", diff --git a/src/cli/hold.ts b/src/cli/hold.ts index d8df0d8d..404128dd 100644 --- a/src/cli/hold.ts +++ b/src/cli/hold.ts @@ -2,7 +2,15 @@ // a time. It holds the `quest:active` label, and the ID of the timeline event // that added the label is its hold token, since sessions often share an account. // `quest merge` takes no label: the pinned auto-merge or merge-queue entry it creates is the queue signal. -import { ACTIVE_LABEL, formatFinding, handedBack, latestHold, heldToken, withoutHandBack } from "../core"; +import { + ACTIVE_LABEL, + formatFinding, + handedBack, + heldToken, + latestHold, + type PullRequest, + withoutHandBack, +} from "../core"; import { cleanAutoMergeRefusal, immediateMerge, queueHead } from "../github/merge"; import { currentChecks, @@ -15,7 +23,6 @@ import { string, repositoryPath, } from "../github/client"; -import type { PullRequest } from "../core"; import { ALLOWS, METHOD_NAMES, contexts, enqueue } from "./land"; import { LAND_CHECK } from "../github/land"; import { QUEUE_CHECK } from "./land-queue"; diff --git a/src/cli/land.ts b/src/cli/land.ts index 2c35b2ba..063d06c5 100644 --- a/src/cli/land.ts +++ b/src/cli/land.ts @@ -1,7 +1,7 @@ import { spawnSync } from "node:child_process"; import { resolve } from "node:path"; -import { isQuest, remove } from "../core"; +import { isQuest, remove, type Repository } from "../core"; import { LAND_CHECK, type Reason, pin, pinned } from "../github/land"; import { programEnvironment } from "./program"; import { @@ -17,7 +17,6 @@ import { string, repositoryPath, } from "../github/client"; -import type { Repository } from "../core"; import type { WorkflowRun } from "../github/checks"; import { appOf } from "../github/checks"; import { classifyCheck, reported, type Needs } from "../github/status"; diff --git a/src/cli/review-eval.ts b/src/cli/review-eval.ts index 37a818ab..4d0e88eb 100644 --- a/src/cli/review-eval.ts +++ b/src/cli/review-eval.ts @@ -7,10 +7,9 @@ import { randomUUID } from "node:crypto"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { SIZES, type Size, TIERS, type Tier } from "../core"; +import { type Repository, type Size, SIZES, type Tier, TIERS } from "../core"; import { parser } from "../core/parse"; import { type GitHub, object, repositoryPath } from "../github/client"; -import type { Repository } from "../core"; import type { HarnessName } from "./agent"; import { git } from "./git"; import { type ClaimDependencies, upstream } from "./claims"; diff --git a/src/cli/start.ts b/src/cli/start.ts index 4630a8ee..454d2f06 100644 --- a/src/cli/start.ts +++ b/src/cli/start.ts @@ -3,7 +3,7 @@ // while nothing but the claim commit is on the branch. import { randomBytes } from "node:crypto"; -import { questBranch } from "../core"; +import { type OpenPull, questBranch } from "../core"; import { type ClaimDependencies, type Target, @@ -18,7 +18,6 @@ import { GitError, git } from "./git"; import { requireRemote } from "./github"; import { object, repositoryPath, string } from "../github/client"; import { ago } from "../github/hold"; -import type { OpenPull } from "../core"; import { mergedPull, openPullRequests, pullsFrom } from "../github/claims"; /** Someone else holds the quest, or the claim cannot be released; distinct from a failure. */ diff --git a/src/cli/usage.ts b/src/cli/usage.ts index a442765c..4d0ae223 100644 --- a/src/cli/usage.ts +++ b/src/cli/usage.ts @@ -2,7 +2,27 @@ // the work went by the PR's own record. token-max reads and prices the sessions, on this host and any SSH host // named; quest ties each to a PR by the branches and repositories token-max exports for it. import { spawnSync } from "node:child_process"; -import { type RecordedRisk, type Size, SIZES, TIERS, type Tier, handedBack, questBranch, recordedRisk } from "../core"; +import { + breakageKey, + type BreakageRecord, + handedBack, + questBranch, + type RecordedRisk, + recordedRisk, + type Repository, + type Role, + ROLES, + type Seat, + type SessionRecord, + type Size, + SIZES, + SPLIT_CATEGORIES, + type SplitUsage, + type Tier, + TIERS, + type TimeSplit, + WAIT_KINDS, +} from "../core"; import type { Arm } from "./models"; import { recorded } from "./models-record"; import { type ClaimDependencies, upstream } from "./claims"; @@ -13,7 +33,6 @@ import { fixes } from "./land-fixer"; import { MERGER } from "./land-watch-fix"; import { githubRepository, requireRemote } from "./github"; import { type GitHub, type ObjectValue, link, object } from "../github/client"; -import type { Repository } from "../core"; import { type OnlineReview, readOnlineReviews } from "../github/online-review"; import { type Counts, @@ -25,18 +44,6 @@ import { severityText, } from "./review-record"; import { SEVERITIES } from "./review"; -import { - type BreakageRecord, - ROLES, - breakageKey, - type Role, - SPLIT_CATEGORIES, - type Seat, - type SessionRecord, - type SplitUsage, - type TimeSplit, - WAIT_KINDS, -} from "../core"; import { type RecordInput, buildRecords } from "./records"; import { stateDirectory } from "./send"; import { keptSplit } from "./split"; diff --git a/src/core/forge.ts b/src/core/forge.ts index b2879a06..2c5ff126 100644 --- a/src/core/forge.ts +++ b/src/core/forge.ts @@ -297,7 +297,11 @@ const boolean: Parse = (value, at) => (typeof value === "boolean" ? val const count: Parse = (value, at) => Number.isSafeInteger(value) && (value as number) >= 0 ? (value as number) : fail(at, "a count"); const time: Parse = (value, at) => - typeof value === "string" && !Number.isNaN(Date.parse(value)) ? value : fail(at, "a timestamp"); + typeof value === "string" && + /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) && + !Number.isNaN(Date.parse(value)) + ? value + : fail(at, "an ISO 8601 timestamp"); const oneOf = (options: readonly T[]): Parse => (value, at) => From 0d360445245a1d99fa973b0fcce4fe2ca1481828 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 10:48:46 -0800 Subject: [PATCH 5/8] fix(forge): bound wait's forge choice and viewer read by its timeout, keep usage errors Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- src/cli/forge.ts | 26 +++++++++++----- src/cli/main.ts | 31 ++++++++++--------- src/cli/wait.ts | 25 ++++++++++++--- src/github/forge.ts | 10 ++++-- test/forge.test.ts | 74 ++++++++++++++++++++++++++++++++++++++++++--- test/wait-fakes.ts | 6 ++-- 7 files changed, 139 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index c9da39bc..2522360d 100644 --- a/README.md +++ b/README.md @@ -576,7 +576,8 @@ Its read API lives under `/forge`, with the token as a bearer token: and the lowercase `owner/repo` of each repository served to them, and `POST /forge/` takes one of `status`, `pulls`, `held`, or `watch` and answers `{"value", "asOf"}`, the read's value and the time of the newest -webhook behind it. `quest/core` exports each read's types and their parsers; +webhook behind it. A 400 with `{"error"}` refuses a bad argument, such as a +malformed `--since`, which `quest` reports as a usage error. `quest/core` exports each read's types and their parsers; `quest/github`'s `GitHubForge` answers the same reads from GitHub. ## Own a pull request diff --git a/src/cli/forge.ts b/src/cli/forge.ts index a8c36dea..45f126f0 100644 --- a/src/cli/forge.ts +++ b/src/cli/forge.ts @@ -15,6 +15,7 @@ import { type Watch, type WatchOptions, forgeJson, + InputError, parseForgeAnswer, parseForgeInfo, } from "../core"; @@ -49,10 +50,13 @@ export function kixelQuest(deps: ForgeDependencies): KixelQuest | null { return token === null ? null : new KixelQuest(url, token, deps); } -/** The forge whose answers `repository`'s reads use: Kixel Quest when it serves the repository to this person. */ -export async function forgeFor(repository: Repository, deps: ForgeDependencies): Promise { +/** + * The forge whose answers `repository`'s reads use: Kixel Quest when it serves the repository to this person. Asking + * Kixel Quest gives up at `deadline`, epoch milliseconds. + */ +export async function forgeFor(repository: Repository, deps: ForgeDependencies, deadline = Infinity): Promise { const kixel = kixelQuest(deps); - return kixel !== null && (await kixel.serves(repository)) + return kixel !== null && (await kixel.serves(repository, deadline)) ? new KixelQuestForge(kixel) : new GitHubForge(deps.github()); } @@ -67,9 +71,9 @@ export class KixelQuest { private readonly deps: ForgeDependencies, ) {} - /** The person the token names, and the repositories Kixel Quest serves them; read once. */ - info(): Promise { - this.#info ??= this.#send("GET", "/forge", undefined, Infinity).then((json) => { + /** The person the token names, and the repositories Kixel Quest serves them; read once, by `deadline`. */ + info(deadline = Infinity): Promise { + this.#info ??= this.#send("GET", "/forge", undefined, deadline).then((json) => { try { return parseForgeInfo(json); } catch (error) { @@ -80,8 +84,10 @@ export class KixelQuest { } /** Whether Kixel Quest answers `repository`'s reads for this person. */ - async serves(repository: Repository): Promise { - return (await this.info()).repositories.includes(`${repository.owner}/${repository.repo}`.toLowerCase()); + async serves(repository: Repository, deadline = Infinity): Promise { + return (await this.info(deadline)).repositories.includes( + `${repository.owner}/${repository.repo}`.toLowerCase(), + ); } /** Ask for `call`, giving up at `deadline` (epoch milliseconds). */ @@ -110,6 +116,7 @@ export class KixelQuest { async #send(method: "GET" | "POST", path: string, body: unknown, deadline: number): Promise { const failed = (why: string) => this.#failed(method, path, why); const remaining = deadline - this.deps.now(); + if (remaining <= 0) throw failed("its deadline passed"); // Called unbound, as a Worker's fetch requires. const fetch = this.deps.fetch; let response: Response; @@ -136,6 +143,9 @@ export class KixelQuest { } if (response.status === 401 || response.status === 403) throw failed(`it refused the token ${tokensPath(this.deps.env)} pairs with it (HTTP ${response.status})`); + // A bad argument, such as a malformed wait point, is the caller's to fix on any forge. + if (response.status === 400) + throw new InputError(`Kixel Quest refused ${method} ${path}${reason(text) || ", a bad request"}`); if (!response.ok) throw failed(`HTTP ${response.status}${reason(text)}`); try { return JSON.parse(text); diff --git a/src/cli/main.ts b/src/cli/main.ts index 00385fe8..d52c05d2 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -41,6 +41,7 @@ import { stopAgent, stopAll, } from "./agent"; +import type { Repository } from "../core"; import { type ClaimDependencies, held, openDrafts, reach, target, upstream, upstreamRefs } from "./claims"; import { type ForgeDependencies, forgeFor } from "./forge"; import { PENDING_MS } from "./admission"; @@ -607,20 +608,22 @@ export function main(argv: string[], out: Output): number | Promise { return false; } }; - pending = forgeFor(pr, forgeDependencies("wait")) - .then((forge) => waitForActivity(pr, options, forge, { now: Date.now, sleep })) - .then( - (lines) => { - for (const line of lines) print(line); - return logged(lines[0]?.split(" ")[1] ?? null) ? 0 : 1; - }, - (error: unknown) => { - if (error instanceof WaitTimeout && error.cursor) print(error.cursor); - warn(error instanceof Error ? error.message : String(error)); - if (error instanceof WaitTimeout) return logged(null) ? 3 : 1; - return error instanceof InputError ? 2 : 1; - }, - ); + const choice = { + choose: (repository: Repository, deadline: number) => + forgeFor(repository, forgeDependencies("wait"), deadline), + }; + pending = waitForActivity(pr, options, choice, { now: Date.now, sleep }).then( + (lines) => { + for (const line of lines) print(line); + return logged(lines[0]?.split(" ")[1] ?? null) ? 0 : 1; + }, + (error: unknown) => { + if (error instanceof WaitTimeout && error.cursor) print(error.cursor); + warn(error instanceof Error ? error.message : String(error)); + if (error instanceof WaitTimeout) return logged(null) ? 3 : 1; + return error instanceof InputError ? 2 : 1; + }, + ); }); program diff --git a/src/cli/wait.ts b/src/cli/wait.ts index 7cce535a..cf410a34 100644 --- a/src/cli/wait.ts +++ b/src/cli/wait.ts @@ -1,5 +1,5 @@ // `quest wait`: poll a pull request's activity through its forge until something happens or the timeout. -import type { Forge, PullRequest } from "../core"; +import type { Forge, PullRequest, Repository, Watch } from "../core"; const POLL = 5 * 60_000; /** @@ -34,18 +34,31 @@ export interface Clock { sleep(milliseconds: number): Promise; } -/** Wait until activity, returning plain output lines: each event, the last followed by its resume cursor. */ +/** Chooses the forge a wait reads, asking no longer than its deadline, epoch milliseconds. */ +export interface ForgeChoice { + choose(repository: Repository, deadline: number): Promise; +} + +/** + * Wait until activity, returning plain output lines: each event, the last followed by its resume cursor. The timeout + * covers choosing the forge too. + */ export async function waitForActivity( pr: PullRequest, options: WaitOptions, - forge: Forge, + choice: ForgeChoice, clock: Clock, ): Promise { const started = clock.now(); const deadline = options.timeout === undefined ? Infinity : started + options.timeout * 1000; - const watch = forge.watch(pr, { since: options.since, deadline }); + let forge: Forge | undefined; + let watch: Watch | undefined; let asOf: string | null = null; - const timedOut = () => new WaitTimeout(watch.resume, asOf === null ? undefined : { forge: forge.name, at: asOf }); + const timedOut = () => + new WaitTimeout( + watch ? watch.resume : options.since, + asOf === null || forge === undefined ? undefined : { forge: forge.name, at: asOf }, + ); const pause = async (milliseconds: number) => { const remaining = deadline - clock.now(); if (remaining <= 0) throw timedOut(); @@ -53,6 +66,8 @@ export async function waitForActivity( if (clock.now() >= deadline) throw timedOut(); }; try { + forge = await choice.choose(pr, deadline); + watch = forge.watch(pr, { since: options.since, deadline }); for (;;) { const answer = await watch.poll(); asOf = answer.asOf; diff --git a/src/github/forge.ts b/src/github/forge.ts index af83c488..fe2ab626 100644 --- a/src/github/forge.ts +++ b/src/github/forge.ts @@ -30,7 +30,12 @@ export class GitHubForge implements Forge { } viewer(): Promise { - this.#viewer ??= new GitHub(this.deps) + return this.#viewerOn(new GitHub(this.deps)); + } + + /** The viewer, read once on `github`, whose deadline then bounds the read. */ + #viewerOn(github: GitHub): Promise { + this.#viewer ??= github .graphql("query { viewer { login } }", {}) .then((data) => string(object(data.viewer).login)); return this.#viewer; @@ -49,7 +54,8 @@ export class GitHubForge implements Forge { } watch(pull: PullRequest, options: WatchOptions): Watch { - return watchPull(new GitHub(this.deps, options.deadline), this.deps, pull, options.since, this); + const github = new GitHub(this.deps, options.deadline); + return watchPull(github, this.deps, pull, options.since, { viewer: () => this.#viewerOn(github) }); } } diff --git a/test/forge.test.ts b/test/forge.test.ts index f57b6b99..5ff39487 100644 --- a/test/forge.test.ts +++ b/test/forge.test.ts @@ -10,6 +10,7 @@ import { afterEach, describe, expect, test } from "vitest"; import { type Forge, type ForgeCall, + InputError, FORGE_CALLS, type Holdings, type PullRequest, @@ -53,7 +54,13 @@ function kixelQuest( return Response.json({ error: "no such read" }, { status: 404 }); if (options.answer !== undefined) return Response.json(options.answer); const forge = new GitHubForge(github(), options.login ?? "waiter"); - const value = await serve(forge, call, parseForgeRequest(call, body)); + let value: unknown; + try { + value = await serve(forge, call, parseForgeRequest(call, body)); + } catch (error) { + if (error instanceof InputError) return Response.json({ error: error.message }, { status: 400 }); + throw error; + } return new Response(forgeJson({ value, asOf: options.asOf ?? null }), { headers: { "content-type": "application/json" }, }); @@ -322,17 +329,27 @@ describe("wait", () => { test.each(scenarios)("%s wakes the same through Kixel Quest as from GitHub", async (_, scenario) => { const direct = scenario(); - const expected = await waitForActivity(wait.pr, {}, new GitHubForge(direct.deps), direct.deps); + const expected = await waitForActivity( + wait.pr, + {}, + { choose: async () => new GitHubForge(direct.deps) }, + direct.deps, + ); const fixture = scenario(); const { forge } = await throughKixelQuest(() => fixture.deps); - expect(await waitForActivity(wait.pr, {}, forge, fixture.deps)).toEqual(expected); + expect(await waitForActivity(wait.pr, {}, { choose: async () => forge }, fixture.deps)).toEqual(expected); expect(fixture.sleeps).toEqual(direct.sleeps); }); test("a timeout resumes from Kixel Quest's cursor and says how current its index was", async () => { const fixture = wait.setup([wait.pull(), wait.response([wait.pushed()]), wait.response([]), wait.response([])]); const { forge } = await throughKixelQuest(() => fixture.deps, { asOf: "2026-10-07T12:09:00Z" }); - const error = await waitForActivity(wait.pr, { timeout: 60 }, forge, fixture.deps).catch((e: unknown) => e); + const error = await waitForActivity( + wait.pr, + { timeout: 60 }, + { choose: async () => forge }, + fixture.deps, + ).catch((e: unknown) => e); expect(error).toBeInstanceOf(WaitTimeout); expect((error as WaitTimeout).cursor).toMatch(/^q1\./); expect((error as Error).message).toBe( @@ -341,6 +358,55 @@ describe("wait", () => { }); }); +describe("wait deadlines and arguments", () => { + test("the timeout covers asking Kixel Quest which forge to read", async () => { + const server = kixelQuest(() => wait.setup([]).deps); + let now = 0; + // The first reading starts the clock; by the time Kixel Quest would be asked, the timeout has passed. + const clock = { now: () => (now++ === 0 ? 0 : 20_000), sleep: async () => {} }; + const deps = { ...dependencies(server.fetch, unreachableGitHub), now: clock.now }; + const choice = { choose: (pull: PullRequest, deadline: number) => forgeFor(pull, deps, deadline) }; + const error = await waitForActivity(wait.pr, { timeout: 10 }, choice, clock).catch((e: unknown) => e); + expect(error).toBeInstanceOf(WaitTimeout); + expect(server.requests).toEqual([]); + }); + + test("a rate-limited viewer read on GitHub gives up at the wait's timeout", async () => { + const fixture = wait.setup([wait.pull(), wait.response([wait.pushed()]), wait.response([])], [wait.A], { + viewer: wait.response( + { message: "API rate limit exceeded" }, + { + "x-ratelimit-remaining": "0", + "x-ratelimit-reset": String(Date.parse("2026-10-07T13:10:00Z") / 1000), + }, + 403, + ), + }); + const error = await wait.waitOn(wait.pr, { timeout: 60 }, fixture.deps).catch((e: unknown) => e); + expect(error).toBeInstanceOf(WaitTimeout); + expect(fixture.sleeps.reduce((sum, ms) => sum + ms, 0)).toBeLessThanOrEqual(60_000); + }); + + test("Kixel Quest's refusal of a bad wait point is a usage error, as GitHub's is", async () => { + const bad = { since: "yesterday" }; + const direct = wait.setup([]); + await expect(wait.waitOn(wait.pr, bad, direct.deps)).rejects.toBeInstanceOf(InputError); + const fixture = wait.setup([]); + const { forge } = await throughKixelQuest(() => fixture.deps); + const error = await waitForActivity(wait.pr, bad, { choose: async () => forge }, fixture.deps).catch( + (e: unknown) => e, + ); + expect(error).toBeInstanceOf(InputError); + expect((error as Error).message).toMatch( + /^Kixel Quest refused POST \/forge\/watch, invalid timestamp: yesterday/, + ); + }); +}); + +const unreachableGitHub = (): GitHubDependencies => { + throw new Error("read GitHub"); +}; + describe("choosing the forge", () => { const unreachable = (): GitHubDependencies => { throw new Error("read GitHub"); diff --git a/test/wait-fakes.ts b/test/wait-fakes.ts index 67f611e7..ccc8542a 100644 --- a/test/wait-fakes.ts +++ b/test/wait-fakes.ts @@ -173,6 +173,8 @@ export function setup( rules?: unknown[]; /** The head's workflow runs, as `GET /actions/runs` lists them, one listing per read; the last repeats. */ runs?: unknown[][]; + /** GitHub's answer to the viewer query; `waiter` by default. */ + viewer?: Response; } = {}, ) { let now = Date.parse("2026-10-07T12:10:00Z"); @@ -206,7 +208,7 @@ export function setup( if (parsed.pathname === "/graphql") { const body = JSON.parse(String(init?.body)) as { query: string }; if (body.query === "query { viewer { login } }") - return response({ data: { viewer: { login: "waiter" } } }); + return side.viewer ?? response({ data: { viewer: { login: "waiter" } } }); if (body.query.includes("statusCheckRollup")) { checkCalls.push({ ...call, body }); return side.checks?.shift() ?? checks(); @@ -261,7 +263,7 @@ export function setup( /** Wait on GitHub, with the fixture's clock. */ export function waitOn(pull: typeof pr, options: WaitOptions, deps: GitHubDependencies): Promise { - return waitForActivity(pull, options, new GitHubForge(deps), deps); + return waitForActivity(pull, options, { choose: async () => new GitHubForge(deps) }, deps); } export function graphql(fixture: ReturnType) { From c2556e664e070b4746670894cd28600f04da1472 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 10:52:21 -0800 Subject: [PATCH 6/8] fix(forge): read the viewer and Kixel Quest's info again after a failure Co-Authored-By: Claude Opus 5.5 --- src/cli/forge.ts | 10 +++++++--- src/github/forge.ts | 11 +++++++---- test/forge.test.ts | 24 ++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/cli/forge.ts b/src/cli/forge.ts index 45f126f0..c73e2ac3 100644 --- a/src/cli/forge.ts +++ b/src/cli/forge.ts @@ -71,16 +71,20 @@ export class KixelQuest { private readonly deps: ForgeDependencies, ) {} - /** The person the token names, and the repositories Kixel Quest serves them; read once, by `deadline`. */ + /** The person the token names, and the repositories Kixel Quest serves them, by `deadline`; kept once read. */ info(deadline = Infinity): Promise { - this.#info ??= this.#send("GET", "/forge", undefined, deadline).then((json) => { + const read = (this.#info ??= this.#send("GET", "/forge", undefined, deadline).then((json) => { try { return parseForgeInfo(json); } catch (error) { throw this.#failed("GET", "/forge", (error as Error).message); } + })); + // A failure, such as a deadline passing, is asked again next time. + read.catch(() => { + if (this.#info === read) this.#info = undefined; }); - return this.#info; + return read; } /** Whether Kixel Quest answers `repository`'s reads for this person. */ diff --git a/src/github/forge.ts b/src/github/forge.ts index fe2ab626..4ce96782 100644 --- a/src/github/forge.ts +++ b/src/github/forge.ts @@ -33,12 +33,15 @@ export class GitHubForge implements Forge { return this.#viewerOn(new GitHub(this.deps)); } - /** The viewer, read once on `github`, whose deadline then bounds the read. */ + /** The viewer, read on `github`, whose deadline then bounds the read; kept once read, and read again after a failure. */ #viewerOn(github: GitHub): Promise { - this.#viewer ??= github + const read = (this.#viewer ??= github .graphql("query { viewer { login } }", {}) - .then((data) => string(object(data.viewer).login)); - return this.#viewer; + .then((data) => string(object(data.viewer).login))); + read.catch(() => { + if (this.#viewer === read) this.#viewer = undefined; + }); + return read; } async status(pull: PullRequest): Promise> { diff --git a/test/forge.test.ts b/test/forge.test.ts index 5ff39487..f871d88d 100644 --- a/test/forge.test.ts +++ b/test/forge.test.ts @@ -387,6 +387,30 @@ describe("wait deadlines and arguments", () => { expect(fixture.sleeps.reduce((sum, ms) => sum + ms, 0)).toBeLessThanOrEqual(60_000); }); + test("a viewer or Kixel Quest read that failed is read again, not kept", async () => { + let viewers = 0; + const github: GitHubDependencies = { + ...claimsGitHub(), + fetch: async () => + ++viewers === 1 + ? Response.json({ message: "Bad gateway" }, { status: 400 }) + : Response.json({ data: { viewer: { login: "kixelated" } } }), + }; + const forge = new GitHubForge(github); + await expect(forge.viewer()).rejects.toThrow("Bad gateway"); + expect(await forge.viewer()).toBe("kixelated"); + expect(await forge.viewer()).toBe("kixelated"); + expect(viewers).toBe(2); + const server = kixelQuest(unreachableGitHub); + let now = 0; + const kixel = new KixelQuest(URL_, TOKEN, { ...dependencies(server.fetch, unreachableGitHub), now: () => now }); + now = 10; + await expect(kixel.info(5)).rejects.toThrow("its deadline passed"); + expect((await kixel.info()).login).toBe("waiter"); + await kixel.info(); + expect(server.requests).toHaveLength(1); + }); + test("Kixel Quest's refusal of a bad wait point is a usage error, as GitHub's is", async () => { const bad = { since: "yesterday" }; const direct = wait.setup([]); From c03d86cae836456e8a30e9f016dd6f0349ec5978 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 17 Nov 2026 00:19:48 -0800 Subject: [PATCH 7/8] fix(forge): keep a Kixel Quest wait's resume point before its first answer, and name the override on a read's 400 Co-Authored-By: Claude Opus 5.5 --- README.md | 3 ++- bun.lock | 1 + src/cli/forge.ts | 15 ++++++++++++--- src/cli/main.ts | 2 +- test/forge.test.ts | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 63 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2522360d..3d4684cd 100644 --- a/README.md +++ b/README.md @@ -464,7 +464,8 @@ connection a few times, and fails loudly on invalid responses. There is no deadline unless `--timeout ` is supplied. Activity exits 0, timeout exits 3, invalid arguments exit 2, and other failures exit 1; interrupt with Ctrl-C to stop waiting. A timeout prints a resume point as its only line: -a cursor, or the given `--since` (else the head SHA) if setup had not finished. +a cursor, or the given `--since` (else the head SHA, or through Kixel Quest the +time the wait started) if setup had not finished. Retry with it, not the original command, so activity that landed during the first wait is still reported. diff --git a/bun.lock b/bun.lock index fdda18f9..006fedd7 100644 --- a/bun.lock +++ b/bun.lock @@ -21,6 +21,7 @@ }, }, }, + "trustedDependencies": [], "packages": { "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], diff --git a/src/cli/forge.ts b/src/cli/forge.ts index c73e2ac3..5a5d4e97 100644 --- a/src/cli/forge.ts +++ b/src/cli/forge.ts @@ -94,6 +94,11 @@ export class KixelQuest { ); } + /** The time now, epoch milliseconds. */ + now(): number { + return this.deps.now(); + } + /** Ask for `call`, giving up at `deadline` (epoch milliseconds). */ async call( call: C, @@ -147,8 +152,9 @@ export class KixelQuest { } if (response.status === 401 || response.status === 403) throw failed(`it refused the token ${tokensPath(this.deps.env)} pairs with it (HTTP ${response.status})`); - // A bad argument, such as a malformed wait point, is the caller's to fix on any forge. - if (response.status === 400) + // A malformed wait point is the caller's to fix on any forge; the other reads take no free-form argument, so + // their 400 means the CLI and Kixel Quest disagree on the wire, which reading GitHub sidesteps. + if (response.status === 400 && path === "/forge/watch") throw new InputError(`Kixel Quest refused ${method} ${path}${reason(text) || ", a bad request"}`); if (!response.ok) throw failed(`HTTP ${response.status}${reason(text)}`); try { @@ -194,9 +200,12 @@ export class KixelQuestForge implements Forge { watch(pull: PullRequest, { since, deadline }: WatchOptions): Watch { const kixel = this.kixel; let cursor: string | undefined; + // Until Kixel Quest first answers, a timeout resumes from when the wait started, so a retry still reports a + // push made meanwhile; GitHub's backend resumes from the head, which needs a read that could time out too. + const started = since ?? new Date(kixel.now()).toISOString(); return { get resume() { - return cursor ?? since; + return cursor ?? started; }, async poll() { const answer = await kixel.call("watch", { pull, from: cursor ?? since ?? null }, deadline); diff --git a/src/cli/main.ts b/src/cli/main.ts index d52c05d2..4ccfeb61 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -581,7 +581,7 @@ export function main(argv: string[], out: Output): number | Promise { "auto-merge:moved prints once per head, with the account that enabled it as the actor and a URL naming the head it " + "was enabled on, which it reads as quest status does. " + "Pass the final field of the last line to --since to resume without replaying events. " + - "On timeout, the only line is a resume point for --since (a cursor, or the given --since or head SHA if setup did not finish), so a retry with it still reports activity from the first wait.\n\n" + + "On timeout, the only line is a resume point for --since (a cursor, or the given --since, else the head SHA, or through Kixel Quest the time the wait started, if setup did not finish), so a retry with it still reports activity from the first wait.\n\n" + "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. Label changes, replies, and reactions by that account are ignored. " + FORGE_READS.replace("these reads", "its polls") + "Through Kixel Quest, that account is the person its token names, and a timeout says how current its " + diff --git a/test/forge.test.ts b/test/forge.test.ts index f871d88d..7c85ff30 100644 --- a/test/forge.test.ts +++ b/test/forge.test.ts @@ -356,6 +356,43 @@ describe("wait", () => { "timed out waiting for pull request activity; Kixel Quest's last answer was current to 2026-10-07T12:09:00Z", ); }); + test("a first poll that times out resumes from when the wait started, so a retry reports a push made meanwhile", async () => { + const first = wait.setup([]); + const server = kixelQuest(() => first.deps); + // Kixel Quest never answers the first poll: the timeout passes while it is asked. + const fetch = async (input: string | URL | Request, init?: RequestInit) => { + if (new URL(String(input)).pathname !== "/forge/watch") return server.fetch(input, init); + await first.deps.sleep(61_000); + throw new Error("The operation timed out."); + }; + const forge = await forgeFor(repository, { ...dependencies(fetch, () => first.deps), now: first.deps.now }); + const timeout = await waitForActivity( + wait.pr, + { timeout: 60 }, + { choose: async () => forge }, + first.deps, + ).catch((e: unknown) => e); + expect(timeout).toBeInstanceOf(WaitTimeout); + expect((timeout as WaitTimeout).cursor).toBe("2026-10-07T12:10:00.000Z"); + // The head moved to B during the timed-out wait; the retry reports that push. + const second = wait.setup( + [ + wait.pull(undefined, wait.B), + wait.response([wait.pushed(wait.B, "2026-10-07T12:10:30Z"), wait.pushed()]), + wait.response([wait.committed(wait.A), wait.committed(wait.B)]), + ], + [wait.A, wait.B], + ); + const retry = await throughKixelQuest(() => second.deps); + const lines = await waitForActivity( + wait.pr, + { since: (timeout as WaitTimeout).cursor }, + { choose: async () => retry.forge }, + second.deps, + ); + expect(lines).toHaveLength(1); + expect(lines[0]).toMatch(/^2026-10-07T12:10:30Z pushed author /); + }); }); describe("wait deadlines and arguments", () => { @@ -490,6 +527,16 @@ describe("choosing the forge", () => { ); }); + test("a Kixel Quest 400 on a read without a free-form argument names the setting that reads GitHub", async () => { + const server = kixelQuest(unreachable, { fail: 400 }); + const kixel = new KixelQuest(URL_, TOKEN, dependencies(server.fetch, unreachable)); + const error = await new KixelQuestForge(kixel).pulls(repository).catch((e: unknown) => e); + expect(error).not.toBeInstanceOf(InputError); + expect((error as Error).message).toBe( + `Kixel Quest (${URL_}) failed POST /forge/pulls: HTTP 400, index unavailable; set QUEST_FORGE=github to read GitHub`, + ); + }); + test("the person is the token's, not the reading credential's", async () => { const server = kixelQuest(unreachable, { login: "kixelated" }); const forge = new KixelQuestForge(new KixelQuest(URL_, TOKEN, dependencies(server.fetch, unreachable))); From 00dfac4a30580b7a9fd9b8d07e4ffa68029fe645 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 17 Nov 2026 00:30:10 -0800 Subject: [PATCH 8/8] fix(forge): resume a Kixel Quest wait from when it began, to the second Co-Authored-By: Claude Opus 5.5 --- src/cli/forge.ts | 9 +++++---- src/cli/wait.ts | 2 +- src/core/forge.ts | 2 ++ test/forge.test.ts | 18 ++++++++++-------- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/cli/forge.ts b/src/cli/forge.ts index 5a5d4e97..ff43d7f3 100644 --- a/src/cli/forge.ts +++ b/src/cli/forge.ts @@ -197,12 +197,13 @@ export class KixelQuestForge implements Forge { return this.kixel.call("held", { sources, branches }); } - watch(pull: PullRequest, { since, deadline }: WatchOptions): Watch { + watch(pull: PullRequest, { since, deadline, started: began }: WatchOptions): Watch { const kixel = this.kixel; let cursor: string | undefined; - // Until Kixel Quest first answers, a timeout resumes from when the wait started, so a retry still reports a - // push made meanwhile; GitHub's backend resumes from the head, which needs a read that could time out too. - const started = since ?? new Date(kixel.now()).toISOString(); + // Until Kixel Quest first answers, a timeout resumes from when the wait began, so a retry still reports a push + // made meanwhile; GitHub's backend resumes from the head, which needs a read that could time out too. GitHub + // times activity to the second, so the point rounds down to keep activity in the wait's first second. + const started = since ?? new Date(Math.floor((began ?? kixel.now()) / 1000) * 1000).toISOString(); return { get resume() { return cursor ?? started; diff --git a/src/cli/wait.ts b/src/cli/wait.ts index cf410a34..19097a67 100644 --- a/src/cli/wait.ts +++ b/src/cli/wait.ts @@ -67,7 +67,7 @@ export async function waitForActivity( }; try { forge = await choice.choose(pr, deadline); - watch = forge.watch(pr, { since: options.since, deadline }); + watch = forge.watch(pr, { since: options.since, deadline, started }); for (;;) { const answer = await watch.poll(); asOf = answer.asOf; diff --git a/src/core/forge.ts b/src/core/forge.ts index 2c5ff126..eec5632d 100644 --- a/src/core/forge.ts +++ b/src/core/forge.ts @@ -223,6 +223,8 @@ export interface WatchOptions { /** An ISO timestamp, a pushed SHA, or a cursor; the head's push time when absent. */ since?: string; deadline: number; + /** When the wait began, epoch milliseconds; where a backend resumes before it knows the head. Now when absent. */ + started?: number; } /** The reads quest makes of a forge. */ diff --git a/test/forge.test.ts b/test/forge.test.ts index 7c85ff30..5b2138a0 100644 --- a/test/forge.test.ts +++ b/test/forge.test.ts @@ -359,26 +359,28 @@ describe("wait", () => { test("a first poll that times out resumes from when the wait started, so a retry reports a push made meanwhile", async () => { const first = wait.setup([]); const server = kixelQuest(() => first.deps); - // Kixel Quest never answers the first poll: the timeout passes while it is asked. + // Asking which forge to read takes 10 seconds, then Kixel Quest never answers the first poll. const fetch = async (input: string | URL | Request, init?: RequestInit) => { - if (new URL(String(input)).pathname !== "/forge/watch") return server.fetch(input, init); - await first.deps.sleep(61_000); + await first.deps.sleep(new URL(String(input)).pathname === "/forge" ? 10_000 : 61_000); + if (new URL(String(input)).pathname === "/forge") return server.fetch(input, init); throw new Error("The operation timed out."); }; - const forge = await forgeFor(repository, { ...dependencies(fetch, () => first.deps), now: first.deps.now }); + const deps = { ...dependencies(fetch, () => first.deps), now: first.deps.now }; + // The wait starts half a second into 12:10:00, which GitHub times activity in as 12:10:00. + await first.deps.sleep(500); const timeout = await waitForActivity( wait.pr, { timeout: 60 }, - { choose: async () => forge }, + { choose: (pull, deadline) => forgeFor(pull, deps, deadline) }, first.deps, ).catch((e: unknown) => e); expect(timeout).toBeInstanceOf(WaitTimeout); expect((timeout as WaitTimeout).cursor).toBe("2026-10-07T12:10:00.000Z"); - // The head moved to B during the timed-out wait; the retry reports that push. + // The head moved to B in the wait's first second; the retry reports that push. const second = wait.setup( [ wait.pull(undefined, wait.B), - wait.response([wait.pushed(wait.B, "2026-10-07T12:10:30Z"), wait.pushed()]), + wait.response([wait.pushed(wait.B, "2026-10-07T12:10:00Z"), wait.pushed()]), wait.response([wait.committed(wait.A), wait.committed(wait.B)]), ], [wait.A, wait.B], @@ -391,7 +393,7 @@ describe("wait", () => { second.deps, ); expect(lines).toHaveLength(1); - expect(lines[0]).toMatch(/^2026-10-07T12:10:30Z pushed author /); + expect(lines[0]).toMatch(/^2026-10-07T12:10:00Z pushed author /); }); });