diff --git a/README.md b/README.md index c0755cf7..f4638d4e 100644 --- a/README.md +++ b/README.md @@ -644,6 +644,40 @@ 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. +### Work on a repository Kixel Quest hosts + +A repository can move off GitHub with Kixel Quest as its whole forge. Its +remote is then a Kixel Quest URL, `https://kixel.quest//.git`, +and its PRs are `https://kixel.quest///pull/`; that alone +tells `quest` the repository lives there, so every read and write goes to +Kixel Quest, with the token `records.json` pairs with it, and never to GitHub. +`QUEST_FORGE=github` cannot reach such a repository, and a failure there names +no override. `quest start` claims with a draft PR there, `quest iterate`, +`ready`, and `release` take and give back holds that Kixel Quest records rather +than labels, and `quest merge --land ` records a pick of that head, which +Kixel Quest's queue lands by fast-forwarding the base and drops once the head +moves, so it takes no `--squash`, `--rebase`, or `--direct`. `quest review` +records its rounds in the PR body there too. + +Where `gh` cannot reach, `quest pr` opens, edits, and comments on PRs and +resolves review threads, with `gh pr`'s flags; it works on GitHub too: + +```sh +quest pr create --title "Plan the forge" --body-file .tmp/body.md --draft +quest pr edit 12 --body-file .tmp/body.md +quest pr comment 12 --thread --body "Fixed in the head." +quest pr resolve 12 +``` + +The writes are `POST /forge/`, beside the reads: `open`, `close`, +`edit`, `comment`, `resolve`, `hold`, `ready`, `release`, and `pick`, each +answering `{"value", "asOf"}` with `asOf` null. A 409 with `{"error"}` refuses +the write as things stand, such as a PR another session holds, a second open +PR on a claimed quest branch, or a pick of a head that moved, and `quest` +reports it as a refusal; a 400 refuses a malformed argument as a usage error. +`quest/core` exports the `ForgeWrites` interface and each write's types and +parsers, and the CLI's `GitHubWrites` makes the same writes to GitHub. + ## Own a pull request Before a session pushes to an existing PR, it takes the PR, so two agents @@ -656,6 +690,9 @@ quest release 128 # hand it back quest merge 128 --land # auto-merge bound to that head; takes no label ``` +`quest ready 128` without a token only marks a draft ready, refusing while any +session holds it, for a draft its starter reviewed without taking a hold. + A taken PR carries the `quest:active` label while an agent works on it. Sessions often share a GitHub account, so taking it prints a hold token: the ID of the timeline event that added the label. Every command refuses while a @@ -715,7 +752,9 @@ GitHub keeps auto-merge across a writer's push, so disable it before pushing to the PR; `quest status` and `quest wait` report a head that moved since. The commands accept the same PR argument and authentication as `quest wait`, and exit 0 when done, 3 when refused, 2 for invalid arguments, -and 1 for other failures. +and 1 for other failures. On a repository +[Kixel Quest hosts](#work-on-a-repository-kixel-quest-hosts), they write there +instead. This repository lands through GitHub's merge queue. Its required `Queue` check passes a merge group only when the group's build, `just check` and `just test` diff --git a/quest/m1/forge-writes.md b/quest/m1/forge-writes.md deleted file mode 100644 index c37eba14..00000000 --- a/quest/m1/forge-writes.md +++ /dev/null @@ -1,30 +0,0 @@ -# [L] Forge writes for repositories on Kixel Quest - -## Goal - -On a repository whose forge is Kixel Quest rather than GitHub, quest's Kixel -Quest backend opens, edits, readies, comments on, holds, claims, picks, and -lands pull requests, and resolves review threads, so every quest skill works -there unchanged. - -## 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)): -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 (`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; - holds and claims are records keyed by the token quest already treats as - opaque, not labels. -- A moved repository's remote is a Kixel Quest URL, so the backend for it is - known from the remote alone. - -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. diff --git a/quest/m1/kixel-pull-reads.md b/quest/m1/kixel-pull-reads.md new file mode 100644 index 00000000..40401d41 --- /dev/null +++ b/quest/m1/kixel-pull-reads.md @@ -0,0 +1,32 @@ +# [M] PR bodies and comments for repositories Kixel Quest hosts + +## Goal + +An agent working on a repository Kixel Quest hosts reads a PR's body, +comments, and reviews through `quest`, and is steered to `quest pr` when it +reaches for `gh`, so `/quest-iterate` and `/quest-review` run there without +`gh`. + +## Plan + +The forge writes gave `quest pr` its create, edit, comment, and resolve, but +an agent still reads a PR's body and discussion with `gh pr view`, which +cannot reach Kixel Quest, and nothing tells it to use `quest pr` instead. + +- Add a `view` read to the forge interface and its wire, typed in + `quest/core` like the others: the body, title, comments, and reviews, as + `quest pr view ` prints them. GitHub's backend reads them as `gh pr view + --comments` shows them. +- `quest hook` denies `gh pr` and `gh api` calls in a checkout whose origin + is on Kixel Quest, naming the `quest pr` command to run, through a checked + rule in `src/cli/rules.ts` that adds one line to the Checked section `quest + context` prints: ✅ hook denial with a Checked line (rejected: a prose rule in + `quest context` only; neither). The maintainer settled this in + [moq-dev/quest#769](https://github.com/moq-dev/quest/pull/769#issuecomment-6944655958), + since an agent without it tries `gh`, fails, and has no pointer to the + command that works. + +Tests: against the fake Kixel Quest, `quest pr view` prints a PR's body and +comments; and the hook denies `gh pr view` in a checkout whose origin is on +Kixel Quest while it lets the same call through on a GitHub checkout. + diff --git a/src/cli/claims.ts b/src/cli/claims.ts index 41484e99..a84fe294 100644 --- a/src/cli/claims.ts +++ b/src/cli/claims.ts @@ -2,10 +2,13 @@ // `src/github/claims.ts` decides them. Commands that must not disturb held work look here first, // 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 Remote, readRemote, remoteHost, remoteRepository, requireRemote } from "./github"; import { type GitHubDependencies, GitHub, object, repositoryPath, string } from "../github/client"; -import type { Claim, Forge, Holdings, OpenPull, Repository } from "../core"; +import type { Claim, Forge, ForgeWrites, Holdings, OpenPull, Repository } from "../core"; import { questBranches } from "../github/claims"; +import { GitHubForge } from "../github/forge"; +import { landingCheck } from "./landed"; +import { GitHubWrites } from "./writes"; import { type Snapshot, snapshot } from "./tree"; export interface ClaimDependencies { @@ -13,9 +16,35 @@ export interface ClaimDependencies { github(): GitHubDependencies; /** The forge answering reads of a repository on GitHub, such as its claims and open PRs. */ forge(repository: Repository): Promise; + /** Kixel Quest, for remotes on it; without it, no remote is. */ + kixel?: { + /** The repository `url` on Kixel Quest names, or null for none. */ + hosted(url: string): Repository | null; + /** Kixel Quest's backend for a repository it hosts, which both reads and writes there. */ + forge(repository: Repository): Forge & ForgeWrites; + }; warn(message: string): void; } +/** The forge an upstream's PRs and claims live on, GitHub or Kixel Quest. */ +export interface Hosting { + /** Where PRs open and claims are checked. */ + repository: Repository; + /** The repository the remote pushes to: `repository` itself, or a fork. */ + head: Repository; + 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; + /** The forge's own answers, never an index that may lag, for a read that verifies or rewrites what it read. */ + live(): Forge; + /** The forge taking writes to `repository`, created on first use. */ + writes(): ForgeWrites; + /** A link to `path` on the default branch, where the forge shows files. */ + link(path: string): string | null; +} + /** * Where claims live: the furthest repository up the remote's fork chain that * keeps quests, so a contributor's fork claims on the project it came from, @@ -26,18 +55,10 @@ export interface Upstream { git: string; /** The URL the remote pushes to, where a claim branch is pushed. Read from git on first use. */ readonly push: string; - github: { - client: GitHub; - /** Where PRs open and claims are checked. */ - repository: Repository; - /** The repository the remote pushes to: `repository` itself, or a fork. */ - head: Repository; - 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; + /** The forge PRs open on, or null off GitHub and Kixel Quest. */ + hosting: Hosting | null; + /** `hosting` on GitHub, with its client for what only GitHub answers; null elsewhere. */ + github: (Hosting & { client: GitHub }) | null; } /** @@ -45,19 +66,38 @@ export interface Upstream { * up to each parent whose default branch holds the quest tree's README, and * stops at the first parent without one; a failed lookup fails rather than * stops the walk. An ancestor is reached with the same URL scheme as the - * remote. Off GitHub, the remote is its own upstream. The head repository is - * where the remote pushes, which may be a fork even when it fetches from upstream. + * remote. Off GitHub, the remote is its own upstream, and on Kixel Quest, which + * keeps no forks, it is the repository there. The head repository is where the + * remote pushes, which may be a fork even when it fetches from upstream. */ export async function upstream(root: string, remote: Remote, deps: ClaimDependencies): Promise { - const source = remoteRepository(remote); - if (source.repository === null) + const kixel = deps.kixel; + const source = remoteHost(remote, kixel ? (url) => kixel.hosted(url) : null); + if (source?.forge !== "github") { + const repository = source?.repository ?? null; + let hosted: (Forge & ForgeWrites) | undefined; + const forge = () => (hosted ??= kixel!.forge(repository!)); return { git: remote.name, get push() { return remote.used().push; }, + hosting: + repository === null + ? null + : { + repository, + head: repository, + defaultBranch: defaultBranch(root, remote.name), + prefix: git(root, ["rev-parse", "--show-prefix"]), + forge: async () => forge(), + live: forge, + writes: forge, + link: () => null, + }, github: null, }; + } const client = new GitHub(deps.github()); const self = await repositoryInfo(client, source.repository); @@ -72,23 +112,38 @@ export async function upstream(root: string, remote: Remote, deps: ClaimDependen const prefix = git(root, ["rev-parse", "--show-prefix"]); const up = await base(client, self, prefix); let forge: Promise | undefined; + let writes: ForgeWrites | undefined; + const { owner, repo } = up.repository; + const github = { + client, + repository: up.repository, + head, + defaultBranch: up.defaultBranch, + prefix, + forge: () => (forge ??= deps.forge(up.repository)), + live: () => new GitHubForge(deps.github()), + writes: () => (writes ??= new GitHubWrites(deps.github(), landingCheck(root))), + link: (path: string) => + `https://github.com/${owner}/${repo}/blob/${up.defaultBranch}/${encodeURI(prefix + path)}`, + }; 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, - forge: () => (forge ??= deps.forge(up.repository)), - }, + hosting: github, + github, }; } +/** The branch `remote`'s HEAD names, as `git ls-remote --symref` reports it. */ +function defaultBranch(root: string, remote: string): string { + const match = /^ref: refs\/heads\/(\S+)\tHEAD$/m.exec(git(root, ["ls-remote", "--symref", remote, "HEAD"])); + if (match === null) throw new Error(`${remote} names no default branch`); + return match[1]!; +} + type Info = Awaited>; /** `self`, or the nearest fork ancestor whose default branch keeps the quest tree at `prefix`. */ @@ -151,7 +206,7 @@ function listRemote(root: string, remote: string, patterns: string[]): Map { const remote = readRemote(root, name); @@ -174,14 +229,15 @@ export async function reach(root: string, name: string, deps: ClaimDependencies) return null; } const up = await upstream(root, remote, deps); - if (up.github === null) deps.warn(`${name} is not on GitHub, so only its branches were checked for claims`); + if (up.hosting === null) + deps.warn(`${name} is not on GitHub or Kixel Quest, so only its branches were checked for claims`); return up; } /** - * 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. + * Which of `branches` someone holds, as the upstream's forge decides it. `tips` are the upstream's + * `quest/*` branches, when already read; the fork's are read through git too. Off GitHub and Kixel + * Quest, every branch pushed upstream holds its quest. */ export async function held( root: string, @@ -189,7 +245,7 @@ export async function held( branches: string[], tips: Map = remoteBranches(root, up.git), ): Promise { - if (up.github === null) + if (up.hosting === null) return { claims: [...new Set(branches)] .sort() @@ -197,8 +253,8 @@ export async function held( .map((branch) => ({ branch, url: null, pull: null })), landed: new Map(), }; - const { repository, head } = up.github; - const forge = await up.github.forge(); + const { repository, head } = up.hosting; + const forge = await up.hosting.forge(); const sources = { upstream: { repository, tips }, ...(same(head, repository) ? {} : { fork: { repository: head, tips: remoteBranches(root, up.push) } }), @@ -208,8 +264,8 @@ export async function held( /** * The open drafts in the upstream of the remote `name`, from any head - * repository. Reading them needs GitHub, so without the remote, off GitHub, - * or when GitHub cannot be reached or refuses, it warns that they were + * repository. Reading them needs a forge, so without the remote, off GitHub + * and Kixel Quest, or when the forge cannot be reached or refuses, it warns that they were * skipped and returns none, leaving the caller the quest tree. */ export async function openDrafts(root: string, name: string, deps: ClaimDependencies): Promise { @@ -220,11 +276,11 @@ export async function openDrafts(root: string, name: string, deps: ClaimDependen } try { const up = await upstream(root, remote, deps); - if (up.github === null) { - deps.warn(`${name} is not on GitHub, so draft PRs were skipped`); + if (up.hosting === null) { + deps.warn(`${name} is not on GitHub or Kixel Quest, so draft PRs were skipped`); return []; } - const pulls = (await (await up.github.forge()).pulls(up.github.repository)).value; + const pulls = (await (await up.hosting.forge()).pulls(up.hosting.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 index ff43d7f3..df45ba3d 100644 --- a/src/cli/forge.ts +++ b/src/cli/forge.ts @@ -1,5 +1,7 @@ -// 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. +// Which forge answers a repository's reads and takes its writes. A repository Kixel Quest hosts, named by a remote or +// PR URL on Kixel Quest, is read and written there alone. For one on GitHub, reads go to Kixel Quest's index for a +// person holding its token when it serves the repository, else GitHub, and writes go to GitHub. A Kixel Quest failure +// fails the command, naming the setting that reads GitHub instead where that would help. import { type Answer, type ClaimSources, @@ -7,8 +9,13 @@ import { type ForgeCall, type ForgeCalls, type ForgeInfo, + type ForgeWrites, + FORGE_WRITES, + type Hold, type Holdings, type OpenPull, + type Opening, + type Pick, type PullRequest, type Repository, type Status, @@ -18,9 +25,11 @@ import { InputError, parseForgeAnswer, parseForgeInfo, + Refusal, } from "../core"; import type { GitHubDependencies } from "../github/client"; import { GitHubForge } from "../github/forge"; +import { pullRequest, readRemote, remoteHost } from "./github"; import { checkedEndpoint, tokenFor, tokensPath } from "./send"; /** Kixel Quest's own URL. */ @@ -39,36 +48,105 @@ export interface ForgeDependencies { github(): GitHubDependencies; } +/** The Kixel Quest `env` names, without a trailing slash. */ +export function kixelUrl(env: NodeJS.ProcessEnv): string { + return checkedEndpoint(env[KIXEL_QUEST_URL] || KIXEL_QUEST, KIXEL_QUEST_URL).replace(/\/+$/, ""); +} + /** 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 url = kixelUrl(deps.env); + const token = tokenFor(url, deps.env); + return token === null ? null : new KixelQuest(url, token, deps, false); +} + +/** Kixel Quest's backend for `repository`, which it hosts, failing without the person's token for it. */ +export function hostedForge(repository: Repository, deps: ForgeDependencies): KixelQuestForge { + const name = `${repository.owner}/${repository.repo}`; + if (deps.env[FORGE] === "github") throw new Error(`Kixel Quest hosts ${name}, so ${FORGE}=github cannot reach it`); + const url = kixelUrl(deps.env); const token = tokenFor(url, deps.env); - return token === null ? null : new KixelQuest(url, token, deps); + if (token === null) + throw new Error(`Kixel Quest (${url}) hosts ${name}; pair a token with it in ${tokensPath(deps.env)}`); + return new KixelQuestForge(new KixelQuest(url, token, deps, true)); } /** - * 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. + * The forge whose answers `repository`'s reads use: Kixel Quest when it hosts the repository, or serves it to this + * person. Asking Kixel Quest gives up at `deadline`, epoch milliseconds. */ -export async function forgeFor(repository: Repository, deps: ForgeDependencies, deadline = Infinity): Promise { +export async function forgeFor( + repository: Repository, + deps: ForgeDependencies, + deadline = Infinity, + hosted = false, +): Promise { + if (hosted) return hostedForge(repository, deps); const kixel = kixelQuest(deps); return kixel !== null && (await kixel.serves(repository, deadline)) ? new KixelQuestForge(kixel) : new GitHubForge(deps.github()); } -/** Kixel Quest's read API, with a person's token. */ +/** A PR named on the command line, and whether Kixel Quest hosts its repository rather than GitHub. */ +export interface Located { + pull: PullRequest; + hosted: boolean; +} + +/** + * The PR `value` names: a GitHub PR URL, a Kixel Quest one (`///pull/`), or a number in + * the repository the origin remote at `root` names on either. + */ +export function locate(value: string, root: string, env: NodeJS.ProcessEnv): Located { + const base = kixelUrl(env); + if (/^[1-9]\d*$/.test(value)) { + let origin = null; + try { + origin = readRemote(root, "origin"); + } catch { + // Not a checkout: pullRequest says so. + } + const host = origin === null ? null : remoteHost(origin, (url) => hostedRepository(base, url)); + if (host?.forge === "kixel") return { pull: { ...host.repository, number: Number(value) }, hosted: true }; + } else if (value.startsWith(`${base}/`)) { + const match = /^([\w.-]+)\/([\w.-]+)\/pull\/([1-9]\d*)\/?(?:[?#].*)?$/.exec(value.slice(base.length + 1)); + if (!match) throw new InputError(`expected a Kixel Quest PR URL, ${base}///pull/`); + return { pull: { owner: match[1]!, repo: match[2]!, number: Number(match[3]) }, hosted: true }; + } + return { pull: pullRequest(value, root), hosted: false }; +} + +/** The repository `value` on Kixel Quest at `base` names, as `//[.git]`, or null. */ +export function hostedRepository(base: string, value: string): Repository | null { + const at = new URL(base); + const prefix = at.pathname.replace(/\/+$/, ""); + let url: URL; + try { + url = new URL(value); + } catch { + return null; + } + // Credentials in the URL, as a helper may leave, name the same repository. + if (url.protocol !== at.protocol || url.host !== at.host || !url.pathname.startsWith(`${prefix}/`)) return null; + const match = /^([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url.pathname.slice(prefix.length + 1)); + return match ? { owner: match[1]!, repo: match[2]! } : null; +} + +/** Kixel Quest's forge API, with a person's token. */ export class KixelQuest { #info: Promise | undefined; + /** `hosted` when it hosts the repository, so reading GitHub instead would not help. */ constructor( readonly url: string, private readonly token: string, private readonly deps: ForgeDependencies, + private readonly hosted: boolean, ) {} /** The person the token names, and the repositories Kixel Quest serves them, by `deadline`; kept once read. */ @@ -114,11 +192,10 @@ export class KixelQuest { } } - /** A failed request, naming the setting that reads GitHub instead. */ + /** A failed request, naming the setting that reads GitHub instead where Kixel Quest does not host the repository. */ #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`, - ); + const instead = this.hosted ? "" : `; set ${FORGE}=github to read GitHub`; + return new Error(`Kixel Quest (${this.url}) failed ${method} ${path}: ${why}${instead}`); } /** The JSON answer to a request, or an error naming the setting that reads GitHub instead. */ @@ -152,10 +229,15 @@ 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 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") + // A malformed wait point, token, thread, or body 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. + const write = (FORGE_WRITES as readonly string[]).includes(path.slice("/forge/".length)); + if (response.status === 400 && (path === "/forge/watch" || write)) throw new InputError(`Kixel Quest refused ${method} ${path}${reason(text) || ", a bad request"}`); + // A write the forge declines as things stand, such as a PR another session holds, is a refusal to report. + if (response.status === 409 && write) + throw new Refusal(reason(text).slice(2) || `Kixel Quest refused ${method} ${path}`); if (!response.ok) throw failed(`HTTP ${response.status}${reason(text)}`); try { return JSON.parse(text); @@ -175,8 +257,8 @@ function reason(text: string): string { } } -/** Reads from Kixel Quest's index. */ -export class KixelQuestForge implements Forge { +/** Reads from Kixel Quest's index, and writes to a repository it hosts. */ +export class KixelQuestForge implements Forge, ForgeWrites { readonly name = "Kixel Quest"; constructor(private readonly kixel: KixelQuest) {} @@ -215,4 +297,45 @@ export class KixelQuestForge implements Forge { }, }; } + + async open(opening: Opening): Promise { + return (await this.kixel.call("open", { opening })).value; + } + + async close(pull: PullRequest): Promise { + await this.kixel.call("close", { pull }); + } + + async edit(pull: PullRequest, { title, body }: { title: string | null; body: string | null }): Promise { + await this.kixel.call("edit", { pull, title, body }); + } + + async comment(pull: PullRequest, { body, thread }: { body: string; thread: string | null }): Promise { + return (await this.kixel.call("comment", { pull, body, thread })).value.url; + } + + async resolve(pull: PullRequest, thread: string): Promise { + await this.kixel.call("resolve", { pull, thread }); + } + + async hold(pull: PullRequest, token: string | null): Promise { + return (await this.kixel.call("hold", { pull, token })).value; + } + + async ready(pull: PullRequest, token: string | null): Promise { + return (await this.kixel.call("ready", { pull, token })).value; + } + + async release(pull: PullRequest, token: string): Promise { + return (await this.kixel.call("release", { pull, token })).value; + } + + /** Kixel Quest's queue fast-forwards the base, so it takes no merge method, and it lands nothing at once. */ + async pick(pull: PullRequest, { head, method, direct }: Pick): Promise { + if (method !== null || direct) + throw new InputError( + `Kixel Quest lands by fast-forwarding the base through its queue, so it takes no --${method ?? "direct"}`, + ); + await this.kixel.call("pick", { pull, head }); + } } diff --git a/src/cli/github.ts b/src/cli/github.ts index e2006f97..a8266995 100644 --- a/src/cli/github.ts +++ b/src/cli/github.ts @@ -107,6 +107,24 @@ export function remoteRepository(remote: Remote, push = false): { url: string; r return { url, repository: githubRepository(url) }; } +/** The forge a remote names: Kixel Quest's repository, or GitHub's with the URL that names it. */ +export type RemoteHost = + { forge: "kixel"; repository: Repository } | { forge: "github"; url: string; repository: Repository }; + +/** + * The forge `remote`'s fetch URL names, asking `kixel` and then GitHub of its configured URL before the one + * `insteadOf` rewrites make, so a rewrite to the other forge's mirror never moves its writes there; null for neither. + */ +export function remoteHost(remote: Remote, kixel: ((url: string) => Repository | null) | null): RemoteHost | null { + const at = (url: string): RemoteHost | null => { + const hosted = kixel?.(url) ?? null; + if (hosted !== null) return { forge: "kixel", repository: hosted }; + const repository = githubRepository(url); + return repository === null ? null : { forge: "github", url, repository }; + }; + return at(remote.configured.fetch) ?? at(remote.used().fetch); +} + /** * The github.com repository a remote URL names, or `null` for any other host: * HTTPS with or without credentials, `ssh://`, or the scp-like `user@github.com:` form. diff --git a/src/cli/hold.ts b/src/cli/hold.ts index 404128dd..e2cf9dc1 100644 --- a/src/cli/hold.ts +++ b/src/cli/hold.ts @@ -8,7 +8,10 @@ import { handedBack, heldToken, latestHold, + type Hold, + type Method, type PullRequest, + Refusal, withoutHandBack, } from "../core"; import { cleanAutoMergeRefusal, immediateMerge, queueHead } from "../github/merge"; @@ -28,30 +31,37 @@ import { LAND_CHECK } from "../github/land"; import { QUEUE_CHECK } from "./land-queue"; import type { LandingCheck } from "./landed"; import { classifyCheck } from "../github/status"; -import { Refusal } from "./start"; import { type Snapshot, ago, readSnapshot, starterHeld } from "../github/hold"; import { describe, readSignals } from "../github/signals"; -export type Method = "merge" | "squash" | "rebase"; - -/** A session's hold: its label and the token naming the event that added it. */ -export interface Hold { - label: string; - token: string; -} - /** Take `pr`, or keep the hold `token` names. Prints nothing; returns the hold. */ -export async function take(pr: PullRequest, token: string | undefined, deps: GitHubDependencies): Promise { - const { hold } = await acquire(new Labels(pr, deps), token); +export async function take(pr: PullRequest, token: string | null, deps: GitHubDependencies): Promise { + const { hold } = await acquire(new Labels(pr, deps), token ?? undefined); return hold; } /** * While `token` holds `pr`, hand it to reviewers: drop its `## Waiting` section - * and mark a draft ready for review. The hold stays. + * and mark a draft ready for review. The hold stays. Without a token, mark a draft + * ready only while no session holds it. */ -export async function finish(pr: PullRequest, token: string, deps: GitHubDependencies): Promise { +export async function finish(pr: PullRequest, token: string | null, deps: GitHubDependencies): Promise { const labels = new Labels(pr, deps); + const markReady = (snapshot: Snapshot) => + snapshot.draft + ? labels.github.graphql( + `mutation($id: ID!) { markPullRequestReadyForReview(input: { pullRequestId: $id }) { clientMutationId } }`, + { id: snapshot.id }, + ) + : undefined; + if (token === null) { + const snapshot = await labels.read(); + open(snapshot); + const label = snapshot.labels[0]; + if (label !== undefined) throw new Refusal(holder(snapshot, label, deps.now())); + await markReady(snapshot); + return null; + } const { hold, snapshot } = await acquire(labels, token); return holding(hold, async () => { if (handedBack(snapshot.body)) { @@ -60,12 +70,7 @@ export async function finish(pr: PullRequest, token: string, deps: GitHubDepende body: { body: withoutHandBack(snapshot.body) }, }); } - if (snapshot.draft) { - await labels.github.graphql( - `mutation($id: ID!) { markPullRequestReadyForReview(input: { pullRequestId: $id }) { clientMutationId } }`, - { id: snapshot.id }, - ); - } + await markReady(snapshot); }); } @@ -347,18 +352,18 @@ async function holding(hold: Hold, work: () => Promise): Promise { } /** Remove the label `token` holds. A label already gone is released; one added again since is not ours. */ -export async function release(pr: PullRequest, token: string, deps: GitHubDependencies): Promise { +export async function release(pr: PullRequest, token: string, deps: GitHubDependencies): Promise { const labels = new Labels(pr, deps); const snapshot = await labels.read(); const event = snapshot.events.find((candidate) => candidate.id === token && candidate.label !== null); if (!event?.label) throw new Refusal(unknown(snapshot, token)); if (!snapshot.labels.includes(event.label)) { deps.warn(`${event.label} is already off ${snapshot.url}`); - return event.label; + return { label: event.label, token }; } held(snapshot, token); await labels.remove(event.label); - return event.label; + return { label: event.label, token }; } /** diff --git a/src/cli/land-apply.ts b/src/cli/land-apply.ts index 823cf895..d71b9d13 100644 --- a/src/cli/land-apply.ts +++ b/src/cli/land-apply.ts @@ -8,7 +8,7 @@ import { GitHub, type GitHubDependencies, object, string } from "../github/clien import type { PullRequest } from "../core"; import { discoveryEnv } from "./git"; import { contains, git, gitEnvironment, tryGit } from "./land"; -import { Refusal } from "./start"; +import { Refusal } from "../core"; /** GitHub refuses a comment body longer than this many characters. */ export const COMMENT_LIMIT = 65_536; diff --git a/src/cli/land-bump.ts b/src/cli/land-bump.ts index ebb0131f..87120baf 100644 --- a/src/cli/land-bump.ts +++ b/src/cli/land-bump.ts @@ -18,7 +18,7 @@ import type { Repository } from "../core"; import { land } from "./hold"; import { commandEnvironment, contexts, git, type RemoteRead } from "./land"; import { push, remoteHead } from "./land-head"; -import { Refusal } from "./start"; +import { Refusal } from "../core"; import { excerpt, save } from "./land-daemon"; /** The one branch each target's bump PR uses. */ diff --git a/src/cli/land.ts b/src/cli/land.ts index 063d06c5..d60cd968 100644 --- a/src/cli/land.ts +++ b/src/cli/land.ts @@ -21,7 +21,7 @@ import type { WorkflowRun } from "../github/checks"; import { appOf } from "../github/checks"; import { classifyCheck, reported, type Needs } from "../github/status"; import { type Carried, describe, readSignals } from "../github/signals"; -import type { Method } from "./hold"; +import type { Method } from "../core"; import { committedSources } from "./tree"; /** How the watcher's own queue lands each PR: as a squash commit, or as a merge commit keeping its ancestry. */ diff --git a/src/cli/landed.ts b/src/cli/landed.ts index 200f3a88..789f8f1c 100644 --- a/src/cli/landed.ts +++ b/src/cli/landed.ts @@ -165,9 +165,10 @@ function questAt(root: string, commit: string, branch: string, relative: string) return git(root, ["cat-file", "-e", `${commit}:${relative}${path}`]).status === 0 ? path : null; } -function currentBranch(root: string): string { +/** The branch checked out at `root`, failing on a detached HEAD with a hint to pass `flag`. */ +export function currentBranch(root: string, flag = "--branch"): string { const head = git(root, ["symbolic-ref", "--quiet", "--short", "HEAD"]); - if (head.status !== 0) throw new Error("HEAD is not on a branch; pass --branch with the PR's head branch"); + if (head.status !== 0) throw new Error(`HEAD is not on a branch; pass ${flag} with the PR's head branch`); return head.stdout.trim(); } diff --git a/src/cli/main.ts b/src/cli/main.ts index f2b9d20c..6163c9c2 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -30,6 +30,7 @@ import { onMaintainer, waiting, InputError, + Refusal, } from "../core"; import { AgentInputError, @@ -42,21 +43,29 @@ import { stopAgent, stopAll, } from "./agent"; -import type { Repository } from "../core"; +import type { ForgeWrites, Hold, Repository } from "../core"; +import { GitHubWrites } from "./writes"; import { type ClaimDependencies, held, openDrafts, reach, target, upstream, upstreamRefs } from "./claims"; -import { type ForgeDependencies, forgeFor } from "./forge"; +import { + type ForgeDependencies, + type Located, + forgeFor, + hostedForge, + hostedRepository, + kixelUrl, + locate as locatePull, +} from "./forge"; import { PENDING_MS } from "./admission"; import { gate } from "./gate"; -import { gitHubDependencies, pullRequest, readRemote, remoteRepository } from "./github"; +import { gitHubDependencies, pullRequest, readRemote, remoteRepository, requireRemote } 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 { audit } from "./audits"; import { apply, pushCommand } from "./land-apply"; import { EFFORT_VARIABLE, EFFORTS, fix, FixerAgentError } from "./land-fix"; import { watch, type WatchOptions } from "./land-watch"; -import { landed, landingCheck } from "./landed"; +import { currentBranch, landed, landingCheck } from "./landed"; import { type Report, fixHeadings, fixLinks, moveQuest, removeQuest } from "./move"; import { type ResolveOptions, resolveFile } from "./resolve"; import { @@ -107,7 +116,7 @@ import { } from "./send"; import { installSender, uninstallSender } from "./service"; import { heal, init, stubFindings, uninstall } from "./setup"; -import { Refusal, describe, notUpstream, releaseQuest, startQuest } from "./start"; +import { describe, notUpstream, releaseQuest, startQuest } from "./start"; import { CONTEXT, GUIDE, GUIDE_SECTIONS, SKILLS, guideSections, sectionHeading, skill } from "./skills"; import { type Terminal, Theme } from "./theme"; import { type Snapshot, checkout, collect, load, snapshot, under } from "./tree"; @@ -149,13 +158,34 @@ export function main(argv: string[], out: Output): number | Promise { const claimDependencies = (): ClaimDependencies => ({ github: () => gitHubDependencies(warn), forge: (repository) => forgeFor(repository, forgeDependencies()), + kixel: { + hosted: (url) => hostedRepository(kixelUrl(process.env), url), + forge: (repository) => hostedForge(repository, forgeDependencies()), + }, warn, }); + /** The forge taking writes to the PR `value` names: Kixel Quest for a repository it hosts, else GitHub. */ + const located = (value: string): Located & { writes: ForgeWrites } => { + const at = locatePull(value, root(), process.env); + return { + ...at, + writes: at.hosted + ? hostedForge(at.pull, forgeDependencies()) + : new GitHubWrites(gitHubDependencies(warn), landingCheck(root())), + }; + }; const theme = out.terminal ? new Theme(out.terminal) : null; + const PR_ARGUMENT = "GitHub or Kixel Quest PR URL, or a PR number in origin"; + const FORGE_WRITES = + "On GitHub, uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. On a repository Kixel Quest hosts, named by a " + + "Kixel Quest PR URL (///pull/) or an origin remote there (//.git), " + + "it writes to Kixel Quest with the token $XDG_CONFIG_HOME/quest/records.json pairs with it, and holds are " + + "Kixel Quest's records rather than labels; QUEST_KIXEL_URL names another Kixel Quest. "; 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. "; + "QUEST_FORGE=github reads GitHub, and QUEST_KIXEL_URL names another Kixel Quest. A repository Kixel Quest " + + "hosts, named by a Kixel Quest PR URL or origin remote, is read there alone. "; const program = new Command("quest") .description(description) @@ -338,7 +368,8 @@ export function main(argv: string[], out: Output): number | Promise { (result) => done(result) ?? 0, (error: unknown) => { warn(error instanceof Error ? error.message : String(error)); - return error instanceof FixerAgentError ? error.exitCode : error instanceof Refusal ? 3 : 1; + if (error instanceof FixerAgentError) return error.exitCode; + return error instanceof Refusal ? 3 : error instanceof InputError ? 2 : 1; }, ); }; @@ -523,8 +554,9 @@ export function main(argv: string[], out: Output): number | Promise { "parents whose default branch has quest/README.md, or the remote's repository when its parent has " + "none, so a fork with its own quests claims on itself. A fork of that upstream pushes the branch to " + "itself and opens the PR on the upstream, and so does a remote that fetches from upstream but pushes " + - "to a fork. A failed lookup of a parent's README is an error. Off GitHub, only the branch is pushed, " + - "with a warning.\n\n" + + "to a fork. A failed lookup of a parent's README is an error. On a remote Kixel Quest hosts " + + "(//.git), the claim and its draft PR are Kixel Quest's, which refuses a second " + + "open PR on the branch. Elsewhere, only the branch is pushed, 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. " + @@ -594,11 +626,11 @@ export function main(argv: string[], out: Output): number | Promise { "$XDG_STATE_HOME/quest/waits for the session's record, named by the first activity's type, or by none on " + "timeout; a log it cannot write exits 1 after printing the activity.", ) - .argument("", "GitHub PR URL, or a PR number in origin") + .argument("", PR_ARGUMENT) .option("--since ", "ISO timestamp, branch-tip SHA, or resume cursor (default: current head push time)") .option("--timeout ", "Maximum wait in seconds", positiveSeconds) .action((value: string, options: { since?: string; timeout?: number }) => { - const pr = pullRequest(value, root()); + const { pull: pr, hosted } = locatePull(value, root(), process.env); const started = new Date().toISOString(); // An agent session's wait is logged for its record, named by the first activity, or by none on timeout. const logged = (until: string | null): boolean => { @@ -612,7 +644,7 @@ export function main(argv: string[], out: Output): number | Promise { }; const choice = { choose: (repository: Repository, deadline: number) => - forgeFor(repository, forgeDependencies("wait"), deadline), + forgeFor(repository, forgeDependencies("wait"), deadline, hosted), }; pending = waitForActivity(pr, options, choice, { now: Date.now, sleep }).then( (lines) => { @@ -662,11 +694,11 @@ export function main(argv: string[], out: Output): number | Promise { "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") + .argument("", PR_ARGUMENT) .option("--json", "Print a deterministic JSON object") .action((value: string, options: { json?: boolean }) => { - const pr = pullRequest(value, root()); - pending = forgeFor(pr, forgeDependencies()) + const { pull: pr, hosted } = locatePull(value, root(), process.env); + pending = forgeFor(pr, forgeDependencies(), Infinity, hosted) .then((forge) => forge.status(pr)) .then( ({ value: status }) => { @@ -691,9 +723,9 @@ export function main(argv: string[], out: Output): number | Promise { "unless the token is still the latest add of its label. When two sessions add the label at once, the " + "first added keeps the PR; GitHub records no event when a label already on the PR is added again, so two " + "takes within the same moment are not told apart.\n\n" + - "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. Exits 0 when done, 3 when refused, 2 for invalid " + - "arguments, and 1 for other failures."; - const printToken = (work: Promise) => settle(work, (hold) => print(hold.token)); + FORGE_WRITES + + "Exits 0 when done, 3 when refused, 2 for invalid arguments, and 1 for other failures."; + const printToken = (work: Promise) => settle(work, (hold) => (hold ? print(hold.token) : undefined)); program .command("iterate") @@ -702,10 +734,11 @@ export function main(argv: string[], out: Output): number | Promise { "Take a PR to work on it, such as to settle its decisions, fix CI and review findings, and push. " + `Given the token of a hold this session already has, it keeps that hold.\n\n${OWNERSHIP}`, ) - .argument("", "GitHub PR URL, or a PR number in origin") + .argument("", PR_ARGUMENT) .argument("[token]", "Hold token this session already has") .action((value: string, token: string | undefined) => { - printToken(take(pullRequest(value, root()), token, gitHubDependencies(warn))); + const { pull, writes } = located(value); + printToken(writes.hold(pull, token ?? null)); }); program @@ -713,12 +746,14 @@ export function main(argv: string[], out: Output): number | Promise { .summary("Hand a PR this session holds to reviewers") .description( "Hand a PR this session holds to reviewers: remove the body's Waiting section and mark a " + - `draft ready for review. The hold stays; it prints the token again.\n\n${OWNERSHIP}`, + "draft ready for review. The hold stays; it prints the token again. Without a token, it only marks " + + `a draft ready, refusing while any session holds the PR, and prints nothing.\n\n${OWNERSHIP}`, ) - .argument("", "GitHub PR URL, or a PR number in origin") - .argument("", "Hold token printed by iterate") - .action((value: string, token: string) => { - printToken(finish(pullRequest(value, root()), token, gitHubDependencies(warn))); + .argument("", PR_ARGUMENT) + .argument("[token]", "Hold token printed by iterate") + .action((value: string, token: string | undefined) => { + const { pull, writes } = located(value); + printToken(writes.ready(pull, token ?? null)); }); program @@ -747,25 +782,23 @@ export function main(argv: string[], out: Output): number | Promise { "AGENTS.md; never retry with --direct unless the user asks. GitHub keeps auto-merge across a " + "writer's push, so disable it before pushing to the PR; quest status and quest wait report a head " + "that moved since auto-merge was enabled.\n\n" + + "On a repository Kixel Quest hosts, it records a pick of that head instead, which Kixel Quest's queue " + + "lands by fast-forwarding the base and drops once the head moves; it takes no --squash, --rebase, or " + + "--direct, and refuses what Kixel Quest refuses.\n\n" + OWNERSHIP, ) - .argument("", "GitHub PR URL, or a PR number in origin") + .argument("", PR_ARGUMENT) .requiredOption("--land ", "Land this full 40-character head SHA") .addOption(new Option("--squash", "Squash and merge").conflicts("rebase")) .option("--rebase", "Rebase and merge") .option("--direct", "Merge at once when repository auto-merge is disabled; wait for checks to pass first") .action((value: string, options: { land: string; squash?: boolean; rebase?: boolean; direct?: boolean }) => { - const pr = pullRequest(value, root()); if (!/^[\da-f]{40}$/i.test(options.land)) throw new UsageError("--land needs a full 40-character SHA"); - const method = options.squash ? "squash" : options.rebase ? "rebase" : undefined; - settle( - land( - pr, - { sha: options.land, method, direct: options.direct, check: landingCheck(root()) }, - gitHubDependencies(warn), - ), - () => undefined, - ); + const { pull, writes } = located(value); + const method = options.squash ? "squash" : options.rebase ? "rebase" : null; + // Kixel Quest's wire takes a lowercase SHA; GitHub compares either case. + const head = options.land.toLowerCase(); + settle(writes.pick(pull, { head, method, direct: options.direct ?? false }), () => undefined); }); const landCommand = program.command("land").summary("Land queued PRs through a host daemon"); @@ -907,11 +940,113 @@ export function main(argv: string[], out: Output): number | Promise { "released, with a warning. Unlike the other PR state commands, it works on a merged or closed PR.\n\n" + OWNERSHIP, ) - .argument("", "GitHub PR URL, or a PR number in origin") + .argument("", PR_ARGUMENT) .argument("", "Hold token printed when the label was taken") .action((value: string, token: string) => { - settle(release(pullRequest(value, root()), token, gitHubDependencies(warn)), (label) => - print(`released ${label}`), + const { pull, writes } = located(value); + settle(writes.release(pull, token), (hold) => print(`released ${hold.label}`)); + }); + + const pr = program + .command("pr") + .summary("Open, edit, and comment on pull requests, and resolve their review threads") + .description( + "Open, edit, and comment on pull requests, and resolve their review threads, on GitHub or on a " + + "repository Kixel Quest hosts, where gh cannot reach. Flags follow gh pr's.\n\n" + + FORGE_WRITES + + "Exits 0 when done, 3 when refused, 2 for invalid arguments, and 1 for other failures.", + ); + const bodyOptions = (command: Command) => + command + .addOption(new Option("-b, --body ", "Body text").conflicts("bodyFile")) + .option("-F, --body-file ", "Read the body from a file, or - for stdin"); + /** The body the options give, `null` when they give none. */ + const body = (options: { body?: string; bodyFile?: string }): string | null => + options.body ?? + (options.bodyFile === undefined ? null : readFileSync(options.bodyFile === "-" ? 0 : options.bodyFile, "utf8")); + bodyOptions( + pr + .command("create") + .description( + "Open a PR from a branch already pushed to the remote, onto its default branch unless --base names " + + "another, and print its URL. The remote's upstream holds it, as quest start finds it: on GitHub, a " + + "fork's PR opens on the repository it came from.", + ) + .requiredOption("-t, --title ", "Title") + .option("-B, --base <branch>", "Branch to merge into (default: the upstream's default branch)") + .option("-H, --head <branch>", "Branch to merge from (default: the current branch)") + .option("-d, --draft", "Open it as a draft") + .option("--remote <name>", "Remote the branch was pushed to", "origin"), + ).action( + (options: { + title: string; + body?: string; + bodyFile?: string; + base?: string; + head?: string; + draft?: boolean; + remote: string; + }) => { + const text = body(options); + if (text === null) throw new UsageError("pass --body or --body-file"); + const branch = options.head ?? currentBranch(root(), "--head"); + settle( + (async () => { + const up = await upstream(root(), requireRemote(root(), options.remote), claimDependencies()); + if (up.hosting === null) throw new Error(`${options.remote} is not on GitHub or Kixel Quest`); + const { repository, head, defaultBranch } = up.hosting; + return up.hosting.writes().open({ + repository, + head, + branch, + base: options.base ?? defaultBranch, + title: options.title, + body: text, + draft: options.draft ?? false, + }); + })(), + (opened) => print(opened.url), + ); + }, + ); + bodyOptions( + pr + .command("edit") + .description("Replace a PR's title, body, or both.") + .argument("<pr>", PR_ARGUMENT) + .option("-t, --title <title>", "New title"), + ).action((value: string, options: { title?: string; body?: string; bodyFile?: string }) => { + const change = { title: options.title ?? null, body: body(options) }; + if (change.title === null && change.body === null) throw new UsageError("pass --title, --body, or --body-file"); + const { pull, writes } = located(value); + settle(writes.edit(pull, change), () => undefined); + }); + bodyOptions( + pr + .command("comment") + .description( + "Comment on a PR, or reply in a review thread with --thread, naming the thread's ID as quest status " + + "prints it, and print the comment's URL.", + ) + .argument("<pr>", PR_ARGUMENT) + .option("--thread <id>", "Reply in this review thread"), + ).action((value: string, options: { thread?: string; body?: string; bodyFile?: string }) => { + const text = body(options); + if (text === null) throw new UsageError("pass --body or --body-file"); + const { pull, writes } = located(value); + settle(writes.comment(pull, { body: text, thread: options.thread ?? null }), (url) => print(url)); + }); + pr.command("resolve") + .description("Resolve review threads, each named by its ID as quest status prints it.") + .argument("<pr>", PR_ARGUMENT) + .argument("<threads...>", "Review thread IDs") + .action((value: string, threads: string[]) => { + const { pull, writes } = located(value); + settle( + (async () => { + for (const thread of threads) await writes.resolve(pull, thread); + })(), + () => undefined, ); }); diff --git a/src/cli/review-record.ts b/src/cli/review-record.ts index d45800ad..43ab9fa4 100644 --- a/src/cli/review-record.ts +++ b/src/cli/review-record.ts @@ -3,10 +3,9 @@ import { DEFAULT, PATHS, reviewSection } from "../core"; import { recorded } from "./models-record"; import { type ClaimDependencies, upstream } from "./claims"; -import { repositoryPath } from "../github/client"; +import { pullsFrom } from "../github/claims"; import { git } from "./git"; import { requireRemote } from "./github"; -import { string } from "../github/client"; import { type PullModels, type Reviewed, @@ -293,27 +292,31 @@ export type Recorded = { url: string } | { skipped: string }; /** * The open PR from `branch` into the base `<remote>/<branch>` names, found among the upstream's PRs from the - * repository the base's remote pushes to, as claims find a branch's PR; or why there is none. + * repository the base's remote pushes to, as claims find a branch's PR; or why there is none. It reads the forge + * itself, never an index that may lag, since its body is rewritten. */ -async function openPull(root: string, baseRef: string, branch: string, deps: ClaimDependencies) { +async function openPull( + root: string, + baseRef: string, + branch: string, + deps: ClaimDependencies, +): Promise<{ url: string; body: string; edit(body: string): Promise<void> } | { skipped: string }> { // The checkout's top level: a subdirectory would look for the quest tree below it. const top = git(root, ["rev-parse", "--show-toplevel"]); const { remote, branch: base } = parseBase(top, baseRef); const up = await upstream(top, requireRemote(top, remote), deps); - if (up.github === null) return { skipped: `${remote} is not on GitHub` }; - const { client, repository, head } = up.github; - const from = `${head.owner}:${branch}`; - const query = `state=open&head=${encodeURIComponent(from)}&base=${encodeURIComponent(base)}&per_page=100`; - const [pull] = await client.all(`${repositoryPath(repository)}/pulls?${query}`); - if (pull === undefined) return { skipped: `no open PR from ${from} into ${base}` }; - const path = `${repositoryPath(repository)}/pulls/${Number(pull.number)}`; + const hosting = up.hosting; + if (hosting === null) return { skipped: `${remote} is not on GitHub or Kixel Quest` }; + const { repository, head } = hosting; + const name = `${head.owner}/${head.repo}`.toLowerCase(); + const pull = pullsFrom((await hosting.live().pulls(repository)).value, branch).find( + (each) => each.base === base && each.head?.toLowerCase() === name, + ); + if (pull === undefined) return { skipped: `no open PR from ${head.owner}:${branch} into ${base}` }; return { - client, - path, - number: Number(pull.number), - repository, - url: string(pull.html_url), - body: typeof pull.body === "string" ? pull.body : "", + url: pull.url, + body: pull.body, + edit: (body) => hosting.writes().edit({ ...repository, number: pull.number }, { title: null, body }), }; } @@ -335,6 +338,6 @@ export async function recordRounds(root: string, reviewed: Reviewed, deps: Claim const pull = await openPull(root, shared!.base.ref, shared!.branch, deps); if ("skipped" in pull) return pull; const next = withReview(pull.body, reviewRecord(reviewed)); - if (next !== pull.body) await pull.client.request(pull.path, { method: "PATCH", body: { body: next } }); + if (next !== pull.body) await pull.edit(next); return { url: pull.url }; } diff --git a/src/cli/rules.ts b/src/cli/rules.ts index 59181d49..4ce09079 100644 --- a/src/cli/rules.ts +++ b/src/cli/rules.ts @@ -314,6 +314,11 @@ function shell(line: string, check: Check, inherited: ReadonlySet<string> = new } else if (name === "mktemp") mktemp(args, env, check); else if (name === "git") git(args, asked, input, check); else if (name === "gh") gh(args, input, literal, check); + // `quest pr` posts as `gh pr` does, to GitHub or Kixel Quest, with the same flags, after any `--root`. + else if (name === "quest") { + const command = questCommand(args); + if (command[0] === "pr") gh(command, input, literal, check); + } } } @@ -462,7 +467,14 @@ function values(args: string[], names: string[], { attached = [] as string[] } = return found; } -/** `gh` subcommands that post text, by group and command, and whether each authors a new post. */ +/** `quest`'s arguments past its global options: `--root <path>` or `--root=<path>`. */ +function questCommand(args: string[]): string[] { + let i = 0; + while (args[i] === "--root" || args[i]?.startsWith("--root=")) i += args[i] === "--root" ? 2 : 1; + return args.slice(i); +} + +/** `gh` and `quest pr` subcommands that post text, by group and command, and whether each authors a new post. */ const POSTS: Record<string, Record<string, boolean>> = { pr: { create: true, comment: true, review: true, edit: false }, issue: { create: true, comment: true, edit: false }, diff --git a/src/cli/start.ts b/src/cli/start.ts index 454d2f06..836abf43 100644 --- a/src/cli/start.ts +++ b/src/cli/start.ts @@ -3,9 +3,10 @@ // while nothing but the claim commit is on the branch. import { randomBytes } from "node:crypto"; -import { type OpenPull, questBranch } from "../core"; +import { type OpenPull, Refusal, questBranch } from "../core"; import { type ClaimDependencies, + type Hosting, type Target, type Upstream, ensure, @@ -16,12 +17,8 @@ import { } from "./claims"; import { GitError, git } from "./git"; import { requireRemote } from "./github"; -import { object, repositoryPath, string } from "../github/client"; import { ago } from "../github/hold"; -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 {} +import { mergedPull, pullsFrom } from "../github/claims"; export interface Started { branch: string; @@ -80,10 +77,10 @@ export async function startQuest( } let url: string | null = null; - if (up.github === null) { - deps.warn(`${remote} is not on GitHub, so the claim branch was pushed without a PR`); + if (up.hosting === null) { + deps.warn(`${remote} is not on GitHub or Kixel Quest, so the claim branch was pushed without a PR`); } else { - url = await openDraft(root, up, remote, path, title, branch, sha); + url = await openDraft(root, up.hosting, remote, path, title, branch, sha); } checkout(root, branch, sha, deps.warn); @@ -167,54 +164,40 @@ function checkout(root: string, branch: string, sha: string, warn: (message: str /** Open the draft PR, then keep it only if it is the earliest open PR on the branch. */ async function openDraft( root: string, - up: Upstream, + hosting: Hosting, remote: string, path: string, title: string, branch: string, sha: string, ): Promise<string> { - const github = up.github!; - const { owner, repo } = github.repository; - const fork = github.head.owner !== owner || github.head.repo !== repo; - // The quest's path in the repository, which differs from `path` when the tree sits below the top level. - const file = encodeURI(github.prefix + path); - const body = `Claims [${path}](https://github.com/${owner}/${repo}/blob/${github.defaultBranch}/${file}).`; + const { repository, head, defaultBranch } = hosting; + const link = hosting.link(path); + const body = link === null ? `Claims \`${path}\`.` : `Claims [${path}](${link}).`; + const writes = hosting.writes(); let created: OpenPull; try { - const response = await github.client.request(`${repositoryPath(github.repository)}/pulls`, { - body: { - title: title.replace(/^\[(XS|S|M|L|XL)\] /, ""), - head: fork ? `${github.head.owner}:${branch}` : branch, - base: github.defaultBranch, - draft: true, - body, - }, - }); - const row = object(await response.json()); - created = { - number: Number(row.number), - url: string(row.html_url), + created = await writes.open({ + repository, + head, branch, - head: `${github.head.owner}/${github.head.repo}`, - draft: true, - created: Date.parse(string(row.created_at)), - updated: Date.parse(string(row.created_at)), - handedBack: false, + base: defaultBranch, + title: title.replace(/^\[(XS|S|M|L|XL)\] /, ""), body, - }; + draft: true, + }); } catch (error) { - // Without its PR the claim is invisible on GitHub, so take the branch back. + // Without its PR the claim is invisible on the forge, so take the branch back. deleteBranch(root, remote, branch, sha); throw error; } // Two claimers on different repositories, such as forks, both push; the earliest PR wins. - const open = pullsFrom(await openPullRequests(github.client, github.repository), branch); + const open = pullsFrom((await hosting.live().pulls(repository)).value, branch); const first = pullsFrom([...open.filter((pull) => pull.number !== created.number), created], branch)[0]; if (first.number !== created.number) { deleteBranch(root, remote, branch, sha); - await close(up, created.number); + await writes.close({ ...repository, number: created.number }); throw new Refusal(`${first.url} claimed ${path} first; closed ${created.url}`); } return created.url; @@ -255,14 +238,15 @@ export async function releaseQuest( } const pulls: OpenPull[] = []; - if (up.github) { - const head = `${up.github.head.owner}/${up.github.head.repo}`.toLowerCase(); - const open = await openPullRequests(up.github.client, up.github.repository); + const hosting = up.hosting; + if (hosting) { + const head = `${hosting.head.owner}/${hosting.head.repo}`.toLowerCase(); + const open = (await hosting.live().pulls(hosting.repository)).value; pulls.push(...pullsFrom(open, branch).filter((pull) => pull.head?.toLowerCase() === head)); } // Deleting first means the lease decides: a push since the check keeps both the branch and its PR. deleteBranch(root, remote, branch, tip); - for (const pull of pulls) await close(up, pull.number); + for (const pull of pulls) await hosting!.writes().close({ ...hosting!.repository, number: pull.number }); return { branch, closed: pulls.map((pull) => pull.url) }; } @@ -274,14 +258,6 @@ export function describe(branch: string, pull: OpenPull | null, now: number): st return `${pull.url} (${state}, last active ${ago(now, pull.updated)})`; } -/** Close a PR on the upstream repository. */ -async function close(up: Upstream, number: number): Promise<void> { - await up.github!.client.request(`${repositoryPath(up.github!.repository)}/pulls/${number}`, { - method: "PATCH", - body: { state: "closed" }, - }); -} - /** Delete `branch` on `remote` only while its tip is still `sha`. */ function deleteBranch(root: string, remote: string, branch: string, sha: string): void { push( diff --git a/src/cli/writes.ts b/src/cli/writes.ts new file mode 100644 index 00000000..0e335dc6 --- /dev/null +++ b/src/cli/writes.ts @@ -0,0 +1,127 @@ +// GitHub's backend for the forge writes: REST and GraphQL for opening, editing, commenting, and threads, and the +// label holds and landing `quest iterate`, `ready`, `release`, and `merge` already make. +import { + type ForgeWrites, + type Hold, + type OpenPull, + type Opening, + type Pick, + type PullRequest, + Refusal, + handedBack, +} from "../core"; +import { GitHub, type GitHubDependencies, object, repositoryPath, string } from "../github/client"; +import { finish, land, release, take } from "./hold"; +import type { LandingCheck } from "./landed"; + +/** The review thread a node ID names, with the PR it belongs to. */ +const THREAD = `query($id: ID!) { + node(id: $id) { __typename ... on PullRequestReviewThread { pullRequest { number repository { nameWithOwner } } } } +}`; + +/** Writes to GitHub, as the token in `deps` may. */ +export class GitHubWrites implements ForgeWrites { + readonly #github: GitHub; + + /** `check` is the quest check a pick runs on the head first; see `land`. */ + constructor( + private readonly deps: GitHubDependencies, + private readonly check: LandingCheck, + ) { + this.#github = new GitHub(deps); + } + + async open({ repository, head, branch, base, title, body, draft }: Opening): Promise<OpenPull> { + const fork = head.owner !== repository.owner || head.repo !== repository.repo; + // GitHub needs `head_repo` to tell apart two repositories of one owner, such as an organization's fork. + const from = fork + ? { head: `${head.owner}:${branch}`, head_repo: `${head.owner}/${head.repo}` } + : { head: branch }; + const response = await this.#github.request(`${repositoryPath(repository)}/pulls`, { + body: { title, ...from, base, draft, body }, + }); + const row = object(await response.json()); + return { + number: Number(row.number), + url: string(row.html_url), + branch, + base, + head: `${head.owner}/${head.repo}`, + draft, + created: Date.parse(string(row.created_at)), + updated: Date.parse(string(row.created_at)), + handedBack: handedBack(body), + body, + }; + } + + async close(pull: PullRequest): Promise<void> { + await this.#github.request(this.#path(pull), { method: "PATCH", body: { state: "closed" } }); + } + + async edit(pull: PullRequest, { title, body }: { title: string | null; body: string | null }): Promise<void> { + await this.#github.request(this.#path(pull), { + method: "PATCH", + body: { ...(title === null ? {} : { title }), ...(body === null ? {} : { body }) }, + }); + } + + async comment(pull: PullRequest, { body, thread }: { body: string; thread: string | null }): Promise<string> { + if (thread === null) { + const response = await this.#github.request(`${repositoryPath(pull)}/issues/${pull.number}/comments`, { + body: { body }, + }); + return string(object(await response.json()).html_url); + } + await this.#thread(pull, thread); + const data = await this.#github.graphql( + `mutation($id: ID!, $body: String!) { + addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $id, body: $body }) { comment { url } } + }`, + { id: thread, body }, + ); + return string(object(object(data.addPullRequestReviewThreadReply).comment).url); + } + + async resolve(pull: PullRequest, thread: string): Promise<void> { + await this.#thread(pull, thread); + await this.#github.graphql( + "mutation($id: ID!) { resolveReviewThread(input: { threadId: $id }) { thread { id } } }", + { id: thread }, + ); + } + + hold(pull: PullRequest, token: string | null): Promise<Hold> { + return take(pull, token, this.deps); + } + + ready(pull: PullRequest, token: string | null): Promise<Hold | null> { + return finish(pull, token, this.deps); + } + + release(pull: PullRequest, token: string): Promise<Hold> { + return release(pull, token, this.deps); + } + + pick(pull: PullRequest, { head, method, direct }: Pick): Promise<void> { + return land(pull, { sha: head, method: method ?? undefined, direct, check: this.check }, this.deps); + } + + #path(pull: PullRequest): string { + return `${repositoryPath(pull)}/pulls/${pull.number}`; + } + + /** Refuse a thread ID that names no review thread on `pull`, as one copied from another PR would. */ + async #thread(pull: PullRequest, id: string): Promise<void> { + const node = (await this.#github.graphql(THREAD, { id })).node; + const on = node === null || node === undefined ? null : object(node); + const owner = on?.__typename === "PullRequestReviewThread" ? object(on.pullRequest) : null; + const name = `${pull.owner}/${pull.repo}`.toLowerCase(); + if ( + owner === null || + Number(owner.number) !== pull.number || + string(object(owner.repository).nameWithOwner).toLowerCase() !== name + ) + throw new Refusal(`${id} is not a review thread on ${name}#${pull.number}`); + } +} diff --git a/src/core/forge.ts b/src/core/forge.ts index eec5632d..b0219ebb 100644 --- a/src/core/forge.ts +++ b/src/core/forge.ts @@ -1,6 +1,7 @@ -// 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. +// What quest reads from and writes to a forge, as interfaces with a backend per forge: pull request, check, review, +// hold, and queue state, claims, and activity to wait on; and opening, editing, readying, commenting on, holding, +// and picking PRs. 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. */ @@ -17,6 +18,9 @@ export interface PullRequest extends Repository { /** A bad argument, such as a malformed PR or wait point, reported as a usage error. */ export class InputError extends Error {} +/** The forge or a claim refused the request, such as someone else holding the PR; distinct from a failure. */ +export class Refusal extends Error {} + /** A check run or commit status on the head, as `quest status` prints it. */ export interface Check { name: string; @@ -143,6 +147,8 @@ export interface OpenPull { number: number; url: string; branch: string; + /** The branch it merges into. */ + base: string; /** The head repository as `owner/repo`, or `null` once a fork is deleted. */ head: string | null; draft: boolean; @@ -243,20 +249,107 @@ export interface Forge { watch(pull: PullRequest, options: WatchOptions): Watch; } -/** Each read Kixel Quest serves at `POST /forge/<call>`: the request it takes and the value it answers. */ +/** A PR to open: `branch` in `head` (the repository itself, or a fork of it) onto `base` in `repository`. */ +export interface Opening { + repository: Repository; + head: Repository; + branch: string; + base: string; + title: string; + body: string; + draft: boolean; +} + +/** A session's hold on a PR: what it is called, such as its label, and the opaque token naming it. */ +export interface Hold { + label: string; + token: string; +} + +/** How a merge method is named; a forge whose queue fast-forwards its base takes none. */ +export type Method = "merge" | "squash" | "rebase"; + +/** What `quest merge` picks: the head the person saw, and how to land it where the forge offers a choice. */ +export interface Pick { + /** The full head SHA, which must still be the PR's head. */ + head: string; + /** Null for the forge's default. */ + method: Method | null; + /** Merge at once, past an ungated base's disabled auto-merge. */ + direct: boolean; +} + +/** + * The writes quest makes to a forge. A refusal the caller should report rather than retry, such as another session + * holding the PR, is a `Refusal`. + */ +export interface ForgeWrites { + /** Open a PR, returned as `pulls` lists it. A forge that keeps claims refuses a second open PR on a quest branch. */ + open(opening: Opening): Promise<OpenPull>; + /** Close a PR without merging it. */ + close(pull: PullRequest): Promise<void>; + /** Replace a PR's title, body, or both; null keeps one. */ + edit(pull: PullRequest, change: { title: string | null; body: string | null }): Promise<void>; + /** Comment on a PR, or reply in the review thread `thread` names; returns the comment's URL. */ + comment(pull: PullRequest, comment: { body: string; thread: string | null }): Promise<string>; + /** Resolve the review thread `thread` names, as `quest status` lists its ID. */ + resolve(pull: PullRequest, thread: string): Promise<void>; + /** + * Take a PR for this session, or with `token` keep the hold it names. Refuses while the PR is merged or closed, + * another session holds it, or it is a draft its starter still holds. + */ + hold(pull: PullRequest, token: string | null): Promise<Hold>; + /** + * Mark a draft ready for review. With `token`, as the session holding it: also drop its body's `## Waiting` + * section, keeping the hold it returns. Without one, it refuses while any session holds the PR. + */ + ready(pull: PullRequest, token: string | null): Promise<Hold | null>; + /** Give up the hold `token` names; one already gone counts as given up. Works on a merged or closed PR too. */ + release(pull: PullRequest, token: string): Promise<Hold>; + /** Queue the PR's head to land, refusing once it moved or while a session holds the PR. */ + pick(pull: PullRequest, pick: Pick): Promise<void>; +} + +/** Each call Kixel Quest serves at `POST /forge/<call>`: 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 }; + open: { request: { opening: Opening }; value: OpenPull }; + close: { request: { pull: PullRequest }; value: null }; + edit: { request: { pull: PullRequest; title: string | null; body: string | null }; value: null }; + comment: { request: { pull: PullRequest; body: string; thread: string | null }; value: { url: string } }; + resolve: { request: { pull: PullRequest; thread: string }; value: null }; + hold: { request: { pull: PullRequest; token: string | null }; value: Hold }; + ready: { request: { pull: PullRequest; token: string | null }; value: Hold | null }; + release: { request: { pull: PullRequest; token: string }; value: Hold }; + /** Kixel Quest's queue fast-forwards the base, so a pick names only the head. */ + pick: { request: { pull: PullRequest; head: string }; value: null }; } -/** A read Kixel Quest serves. */ +/** A call 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"]; +/** The reads, as their paths name them. */ +export const FORGE_READS = ["status", "pulls", "held", "watch"] as const satisfies readonly ForgeCall[]; + +/** The writes, as their paths name them; Kixel Quest serves them only for a repository it hosts. */ +export const FORGE_WRITES = [ + "open", + "close", + "edit", + "comment", + "resolve", + "hold", + "ready", + "release", + "pick", +] as const satisfies readonly ForgeCall[]; + +/** Every call, reads first. */ +export const FORGE_CALLS: readonly ForgeCall[] = [...FORGE_READS, ...FORGE_WRITES]; /** `GET /forge`: the person a token names and the repositories, as lowercase `owner/repo`, read through Kixel Quest. */ export interface ForgeInfo { @@ -428,6 +521,7 @@ const openPull = shape<OpenPull>({ number: count, url: string, branch: name, + base: name, head: nullable(name), draft: boolean, created: count, @@ -458,6 +552,9 @@ const info = shape<ForgeInfo>({ ), }); +const hold = shape<Hold>({ label: name, token: name }); +const none: Parse<null> = (value, at) => (value === null ? null : fail(at, "null")); + const REQUESTS: { [C in ForgeCall]: Parse<ForgeCalls[C]["request"]> } = { status: shape({ pull: pullRequest }), pulls: shape({ repository }), @@ -466,6 +563,25 @@ const REQUESTS: { [C in ForgeCall]: Parse<ForgeCalls[C]["request"]> } = { branches: list(branch), }), watch: shape({ pull: pullRequest, from: nullable(name) }), + open: shape({ + opening: shape<Opening>({ + repository, + head: repository, + branch: name, + base: name, + title: name, + body: string, + draft: boolean, + }), + }), + close: shape({ pull: pullRequest }), + edit: shape({ pull: pullRequest, title: nullable(name), body: nullable(string) }), + comment: shape({ pull: pullRequest, body: name, thread: nullable(name) }), + resolve: shape({ pull: pullRequest, thread: name }), + hold: shape({ pull: pullRequest, token: nullable(name) }), + ready: shape({ pull: pullRequest, token: nullable(name) }), + release: shape({ pull: pullRequest, token: name }), + pick: shape({ pull: pullRequest, head: sha }), }; const VALUES: { [C in ForgeCall]: Parse<ForgeCalls[C]["value"]> } = { @@ -473,6 +589,15 @@ const VALUES: { [C in ForgeCall]: Parse<ForgeCalls[C]["value"]> } = { pulls: list(openPull), held: holdings, watch: watchPoll, + open: openPull, + close: none, + edit: none, + comment: shape({ url: name }), + resolve: none, + hold, + ready: nullable(hold), + release: hold, + pick: none, }; const answer = <T>(value: Parse<T>): Parse<Answer<T>> => shape<Answer<T>>({ value, asOf: nullable(time) }); diff --git a/src/core/index.ts b/src/core/index.ts index 59559928..56d6dcaa 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -136,6 +136,14 @@ export { type HoldFact, type Holdings, InputError, + Refusal, + type ForgeWrites, + type Hold, + type Method, + type Opening, + type Pick, + FORGE_READS, + FORGE_WRITES, type OpenPull, type PullRequest, type Reaction, diff --git a/src/github/claims.ts b/src/github/claims.ts index 81a8bf3a..055de43c 100644 --- a/src/github/claims.ts +++ b/src/github/claims.ts @@ -22,6 +22,7 @@ export async function openPullRequests(github: GitHub, repository: Repository): number: Number(row.number), url: string(row.html_url), branch: string(head.ref), + base: string(object(row.base).ref), head: repo === null ? null : string(repo.full_name), draft: row.draft === true, created: Date.parse(string(row.created_at)), diff --git a/test/claims.test.ts b/test/claims.test.ts index fcf52cbc..fcb0bb51 100644 --- a/test/claims.test.ts +++ b/test/claims.test.ts @@ -43,6 +43,7 @@ function github(world: { const pull = (n: number, ref: string, created: string) => ({ number: n, head: { ref, repo: { full_name: "someone/project" } }, + base: { ref: "main" }, draft: true, body: null, created_at: created, diff --git a/test/forge-writes.test.ts b/test/forge-writes.test.ts new file mode 100644 index 00000000..ac1795aa --- /dev/null +++ b/test/forge-writes.test.ts @@ -0,0 +1,385 @@ +// The forge writes on a repository Kixel Quest hosts, through the CLI against a fake Kixel Quest that never lets a +// request reach GitHub, and the wire their requests and answers travel in. +import { execFileSync } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { forgeJson, parseForgeAnswer, parseForgeRequest } from "../src/core"; +import { upstream } from "../src/cli/claims"; +import { hostedRepository, locate } from "../src/cli/forge"; +import { type Output, main } from "../src/cli/main"; +import { GitHubWrites } from "../src/cli/writes"; +import type { GitHubDependencies } from "../src/github/client"; +import { FakeKixelQuest, HEAD, KIXEL, REPOSITORY, kixelEnv } from "./kixel-fakes"; +import { tempDir } from "./fixture"; + +let kixel: FakeKixelQuest; +beforeEach(() => { + kixel = new FakeKixelQuest(); + for (const [name, value] of Object.entries(kixelEnv())) vi.stubEnv(name, value); + vi.stubEnv("QUEST_FORGE", ""); + // A GitHub call fails the test: none is expected, and no token is set to make one. + vi.stubEnv("GH_TOKEN", ""); + vi.stubEnv("GITHUB_TOKEN", ""); + vi.stubGlobal("fetch", kixel.fetch); +}); +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +async function cli(...args: string[]): Promise<{ code: number; stdout: string; stderr: string }> { + let stdout = ""; + let stderr = ""; + const out: Output = { stdout: (text) => void (stdout += text), stderr: (text) => void (stderr += text) }; + const code = await main(args, out); + return { code, stdout, stderr }; +} + +describe("a PR on a repository Kixel Quest hosts", () => { + test("is edited, commented on, held, readied, has a thread resolved, released, and picked", async () => { + const pull = kixel.add({ + branch: "quest/m0/one", + draft: true, + body: "Claims it.\n\n## Waiting\n\n- Maintainer: pick one.", + threads: new Map([["thread-1", false]]), + }); + const url = kixel.url(pull.number); + + expect( + await cli("pr", "edit", url, "--title", "One", "--body", "Done.\n\n## Waiting\n\n- Maintainer: x"), + ).toEqual({ code: 0, stdout: "", stderr: "" }); + expect([pull.title, pull.body]).toEqual(["One", "Done.\n\n## Waiting\n\n- Maintainer: x"]); + + const iterated = await cli("iterate", url); + expect(iterated).toEqual({ code: 0, stdout: "hold-1\n", stderr: "" }); + // A second session is refused while the first holds it, and holds nothing. + const second = await cli("iterate", url); + expect(second.code).toBe(3); + expect(second.stderr).toBe(`quest: ${url} is held by quest:active\n`); + expect(await cli("iterate", url, "hold-1")).toEqual({ code: 0, stdout: "hold-1\n", stderr: "" }); + + const reply = await cli("pr", "comment", url, "--thread", "thread-1", "--body", "Fixed in the head."); + expect(reply).toEqual({ code: 0, stdout: `${url}#comment-1\n`, stderr: "" }); + expect(await cli("pr", "resolve", url, "thread-1")).toEqual({ code: 0, stdout: "", stderr: "" }); + expect(pull.threads.get("thread-1")).toBe(true); + const stray = await cli("pr", "resolve", url, "thread-9"); + expect(stray.code).toBe(3); + expect(stray.stderr).toContain("thread-9 is not a review thread"); + + expect(await cli("ready", url, "hold-1")).toEqual({ code: 0, stdout: "hold-1\n", stderr: "" }); + expect([pull.draft, pull.body]).toEqual([false, "Done."]); + + // A pick waits for the session's own hold to go. + const held = await cli("merge", url, "--land", HEAD); + expect(held.code).toBe(3); + expect(pull.picked).toBeNull(); + expect(await cli("release", url, "hold-1")).toEqual({ code: 0, stdout: "released quest:active\n", stderr: "" }); + expect(await cli("merge", url, "--land", HEAD)).toEqual({ code: 0, stdout: "", stderr: "" }); + expect(pull.picked).toBe(HEAD); + + expect(kixel.calls.map(({ call }) => call)).toEqual([ + "edit", + "hold", + "hold", + "hold", + "comment", + "resolve", + "resolve", + "ready", + "pick", + "release", + "pick", + ]); + }); + + test("a pick names the head the person saw, and one that moved is refused", async () => { + const pull = kixel.add({ branch: "feature", sha: "b".repeat(40) }); + const moved = await cli("merge", kixel.url(pull.number), "--land", HEAD); + expect(moved.code).toBe(3); + expect(moved.stderr).toContain(`head moved to ${"b".repeat(40)}`); + expect(pull.picked).toBeNull(); + // An uppercase SHA, which `--land` accepts, picks the same head. + const same = kixel.add({ branch: "other" }); + expect(await cli("merge", kixel.url(same.number), "--land", HEAD.toUpperCase())).toMatchObject({ code: 0 }); + expect(same.picked).toBe(HEAD); + }); + + test.each([["--squash"], ["--rebase"], ["--direct"]])("a pick takes no %s", async (flag) => { + const pull = kixel.add({ branch: "feature" }); + const out = await cli("merge", kixel.url(pull.number), "--land", HEAD, flag); + expect(out.code).toBe(2); + expect(out.stderr).toContain(`takes no ${flag}`); + expect(kixel.calls).toEqual([]); + }); + + test("ready without a token marks a draft ready only while no session holds it", async () => { + const pull = kixel.add({ branch: "feature", draft: true, body: "Notes.\n\n## Waiting\n\n- x" }); + const url = kixel.url(pull.number); + expect(await cli("ready", url)).toEqual({ code: 0, stdout: "", stderr: "" }); + expect([pull.draft, pull.body]).toEqual([false, "Notes.\n\n## Waiting\n\n- x"]); + pull.hold = { label: "quest:active", token: "hold-9" }; + expect((await cli("ready", url)).code).toBe(3); + }); + + test("a comment reads its body from a file or stdin's file descriptor", async () => { + const pull = kixel.add({ branch: "feature" }); + const file = join(tempDir(), "body.md"); + writeFileSync(file, "From a file.\n"); + expect((await cli("pr", "comment", kixel.url(pull.number), "--body-file", file)).code).toBe(0); + expect(pull.comments).toEqual([{ body: "From a file.\n", thread: null }]); + const neither = await cli("pr", "comment", kixel.url(pull.number)); + expect(neither.code).toBe(2); + expect(neither.stderr).toContain("pass --body or --body-file"); + const nothing = await cli("pr", "edit", kixel.url(pull.number)); + expect(nothing.code).toBe(2); + }); + + test("a malformed request is a usage error, and a failure names no GitHub override", async () => { + const pull = kixel.add({ branch: "feature" }); + const url = kixel.url(pull.number); + const empty = await cli("pr", "comment", url, "--body", ""); + expect(empty.code).toBe(2); + expect(empty.stderr).toContain("Kixel Quest refused POST /forge/comment, malformed forge request.body"); + kixel.fail = { status: 503, error: "down" }; + const down = await cli("pr", "edit", url, "--title", "x"); + expect(down).toEqual({ + code: 1, + stdout: "", + stderr: `quest: Kixel Quest (${KIXEL}) failed POST /forge/edit: HTTP 503, down\n`, + }); + }); + + test("QUEST_FORGE=github cannot reach it, and without a token it names the file to pair one in", async () => { + const pull = kixel.add({ branch: "feature" }); + vi.stubEnv("QUEST_FORGE", "github"); + const forced = await cli("status", kixel.url(pull.number)); + expect(forced.stderr).toBe("quest: Kixel Quest hosts example/project, so QUEST_FORGE=github cannot reach it\n"); + vi.stubEnv("QUEST_FORGE", ""); + vi.stubEnv("XDG_CONFIG_HOME", tempDir()); + const unpaired = await cli("iterate", kixel.url(pull.number)); + expect(unpaired.code).toBe(1); + expect(unpaired.stderr).toContain(`Kixel Quest (${KIXEL}) hosts example/project; pair a token with it in`); + expect(kixel.calls).toEqual([]); + }); +}); + +describe("where a PR lives", () => { + const env = { QUEST_KIXEL_URL: KIXEL }; + + test("a Kixel Quest PR URL, and a GitHub one", () => { + expect(locate(`${KIXEL}/example/project/pull/12/`, ".", env)).toEqual({ + pull: { ...REPOSITORY, number: 12 }, + hosted: true, + }); + expect(locate("https://github.com/example/project/pull/12", ".", env)).toEqual({ + pull: { ...REPOSITORY, number: 12 }, + hosted: false, + }); + expect(() => locate(`${KIXEL}/example/project/issues/12`, ".", env)).toThrow("expected a Kixel Quest PR URL"); + }); + + test("a number in an origin on Kixel Quest", () => { + const work = tempDir(); + const run = (...args: string[]) => execFileSync("git", args, { cwd: work, stdio: "ignore" }); + run("init", "-q"); + run("remote", "add", "origin", `${KIXEL}/example/project.git`); + expect(locate("7", work, env)).toEqual({ pull: { ...REPOSITORY, number: 7 }, hosted: true }); + run("remote", "set-url", "origin", "https://github.com/example/project.git"); + expect(locate("7", work, env)).toEqual({ pull: { ...REPOSITORY, number: 7 }, hosted: false }); + }); + + // A rewrite to the other forge's mirror never moves a number's writes there: the configured URL wins. + test("a number in an origin rewritten to the other forge names the configured one", async () => { + const work = tempDir(); + const run = (...args: string[]) => execFileSync("git", args, { cwd: work, stdio: "ignore" }); + run("init", "-q"); + run("remote", "add", "origin", `${KIXEL}/example/project.git`); + run("config", `url.https://github.com/example/.insteadOf`, `${KIXEL}/example/`); + expect(locate("7", work, env)).toEqual({ pull: { ...REPOSITORY, number: 7 }, hosted: true }); + const pull = kixel.add({ branch: "feature" }); + // The fake fails the test on any request to GitHub. + expect(await cli("--root", work, "pr", "comment", String(pull.number), "--body", "Hi")).toMatchObject({ + code: 0, + }); + expect(kixel.calls.map(({ call }) => call)).toEqual(["comment"]); + + run("remote", "set-url", "origin", "https://github.com/example/project.git"); + run("config", "--unset", `url.https://github.com/example/.insteadOf`); + run("config", `url.${KIXEL}/example/.insteadOf`, "https://github.com/example/"); + expect(locate("7", work, env)).toEqual({ pull: { ...REPOSITORY, number: 7 }, hosted: false }); + }); + + test("a claim's upstream is the configured Kixel Quest repository, never a GitHub mirror a rewrite names", async () => { + const work = tempDir(); + const run = (...args: string[]) => execFileSync("git", args, { cwd: work, stdio: "ignore" }); + run("init", "-q", "-b", "main"); + run("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "init"); + // git reaches the checkout itself, so the default branch is read without a network. + run("remote", "add", "origin", work); + const mirror = "https://github.com/example/project.git"; + const remote = { + name: "origin", + configured: { fetch: `${KIXEL}/example/project.git`, push: null }, + used: () => ({ fetch: mirror, push: mirror }), + }; + const github = () => { + throw new Error("asked GitHub"); + }; + const found = await upstream(work, remote, { + github, + forge: github, + kixel: { hosted: (url) => hostedRepository(KIXEL, url), forge: github }, + warn: () => undefined, + }); + expect([found.hosting?.repository, found.github]).toEqual([REPOSITORY, null]); + }); + + test("a remote on Kixel Quest names its repository, with or without credentials or .git", () => { + for (const url of [ + `${KIXEL}/example/project.git`, + `${KIXEL}/example/project`, + "http://agent:secret@localhost:8787/example/project.git/", + ]) + expect(hostedRepository(KIXEL, url)).toEqual(REPOSITORY); + for (const url of [ + "https://kixel.quest/example/project.git", + `${KIXEL}/example`, + `${KIXEL}/example/project/extra`, + "git@github.com:example/project.git", + ]) + expect(hostedRepository(KIXEL, url)).toBeNull(); + expect(hostedRepository("https://kixel.quest", "https://kixel.quest/kixel-ai/kixel.ai.git")).toEqual({ + owner: "kixel-ai", + repo: "kixel.ai", + }); + expect(hostedRepository("https://example.com/kq", "https://example.com/kq/example/project.git")).toEqual( + REPOSITORY, + ); + expect(hostedRepository("https://example.com/kq", "https://example.com/example/project.git")).toBeNull(); + }); +}); + +describe("the write wire", () => { + const pull = { ...REPOSITORY, number: 3 }; + + test("requests round-trip, and their parsers refuse what Kixel Quest would", () => { + const opening = { + repository: REPOSITORY, + head: REPOSITORY, + branch: "quest/m0/one", + base: "main", + title: "One", + body: "", + draft: true, + }; + for (const [call, request] of [ + ["open", { opening }], + ["edit", { pull, title: null, body: "x" }], + ["comment", { pull, body: "x", thread: null }], + ["hold", { pull, token: null }], + ["pick", { pull, head: HEAD }], + ] as const) + expect(parseForgeRequest(call, JSON.parse(forgeJson(request)))).toEqual(request); + expect(() => parseForgeRequest("pick", { pull, head: "abc" })).toThrow("a full commit SHA"); + expect(() => parseForgeRequest("release", { pull, token: "" })).toThrow("a name"); + expect(() => parseForgeRequest("open", { opening: { ...opening, title: "" } })).toThrow("a name"); + expect(() => parseForgeRequest("resolve", { pull, thread: "t", extra: 1 })).toThrow("no such field"); + }); + + test("answers parse strictly", () => { + const hold = { label: "quest:active", token: "hold-1" }; + expect(parseForgeAnswer("ready", { value: null, asOf: null }).value).toBeNull(); + expect(parseForgeAnswer("ready", { value: hold, asOf: null }).value).toEqual(hold); + expect(() => parseForgeAnswer("close", { value: {}, asOf: null })).toThrow("expected null"); + expect(() => parseForgeAnswer("hold", { value: { label: "quest:active" }, asOf: null })).toThrow( + "answer.value.token", + ); + }); +}); + +describe("GitHub's writes", () => { + /** A GitHub answering `graphql` by the mutation or query it names, recording each request. */ + function github(node: unknown) { + const requests: { path: string; body: any }[] = []; + const deps: GitHubDependencies = { + fetch: async (input, init) => { + const url = new URL(String(input)); + const body = init?.body === undefined ? undefined : JSON.parse(String(init.body)); + requests.push({ path: `${init?.method ?? "GET"} ${url.pathname}`, body }); + if (url.pathname === "/graphql") { + const query = String(body.query); + if (query.includes("node(id")) return Response.json({ data: { node } }); + if (query.includes("addPullRequestReviewThreadReply")) + return Response.json({ + data: { addPullRequestReviewThreadReply: { comment: { url: "https://github.com/c/1" } } }, + }); + return Response.json({ data: { resolveReviewThread: { thread: { id: "T" } } } }); + } + // The client lists the comments already there, to tell its own from a repeat's. + if (url.pathname.endsWith("/comments") && init?.method === undefined) return Response.json([]); + if (url.pathname.endsWith("/comments")) + return Response.json({ html_url: "https://github.com/example/project/pull/3#issuecomment-1" }); + return Response.json({}); + }, + now: () => 0, + sleep: async () => undefined, + token: "token", + quota: "fail", + warn: () => undefined, + }; + return { writes: new GitHubWrites(deps, async () => []), requests }; + } + const onPull = { + __typename: "PullRequestReviewThread", + pullRequest: { number: 3, repository: { nameWithOwner: "Example/Project" } }, + }; + + test("comments on the PR, replies in a thread on it, and resolves it", async () => { + const { writes, requests } = github(onPull); + expect(await writes.comment(pull(), { body: "Hi", thread: null })).toBe( + "https://github.com/example/project/pull/3#issuecomment-1", + ); + expect(await writes.comment(pull(), { body: "Fixed", thread: "T" })).toBe("https://github.com/c/1"); + await writes.resolve(pull(), "T"); + await writes.edit(pull(), { title: null, body: "New" }); + expect(requests.map(({ path }) => path)).toEqual([ + "GET /repos/example/project/issues/3/comments", + "POST /repos/example/project/issues/3/comments", + "POST /graphql", + "POST /graphql", + "POST /graphql", + "POST /graphql", + "PATCH /repos/example/project/pulls/3", + ]); + expect(requests.at(-1)!.body).toEqual({ body: "New" }); + }); + + test.each([ + ["another PR's", { ...onPull, pullRequest: { number: 4, repository: { nameWithOwner: "example/project" } } }], + ["a missing", null], + ["a non-thread", { __typename: "IssueComment" }], + ])("refuses %s thread before writing", async (_, node) => { + const { writes, requests } = github(node); + await expect(writes.resolve(pull(), "T")).rejects.toThrow("T is not a review thread on example/project#3"); + expect(requests).toHaveLength(1); + }); + + test("opens a PR from a fork, naming its repository for one owner's two repositories", async () => { + const { writes, requests } = github(onPull); + const opening = { repository: REPOSITORY, branch: "b", base: "main", title: "T", body: "", draft: true }; + // The fake answers `{}`, which the PR row's parse refuses; only the request matters here. + await writes.open({ ...opening, head: { owner: "example", repo: "fork" } }).catch(() => undefined); + await writes.open({ ...opening, head: REPOSITORY }).catch(() => undefined); + expect(requests.map(({ body }) => [body.head, body.head_repo])).toEqual([ + ["example:b", "example/fork"], + ["b", undefined], + ]); + }); + + function pull() { + return { ...REPOSITORY, number: 3 }; + } +}); diff --git a/test/forge.test.ts b/test/forge.test.ts index 5b2138a0..dcc85f59 100644 --- a/test/forge.test.ts +++ b/test/forge.test.ts @@ -239,6 +239,7 @@ function claimsGitHub(): GitHubDependencies { number, html_url: `https://github.com/example/project/pull/${number}`, head: { ref, sha: "c".repeat(40), repo: { full_name: "example/project" } }, + base: { ref: "main" }, draft: true, created_at: `2026-10-0${number}T00:00:00Z`, updated_at: `2026-10-0${number}T01:00:00Z`, @@ -442,7 +443,12 @@ describe("wait deadlines and arguments", () => { expect(viewers).toBe(2); const server = kixelQuest(unreachableGitHub); let now = 0; - const kixel = new KixelQuest(URL_, TOKEN, { ...dependencies(server.fetch, unreachableGitHub), now: () => now }); + const kixel = new KixelQuest( + URL_, + TOKEN, + { ...dependencies(server.fetch, unreachableGitHub), now: () => now }, + false, + ); now = 10; await expect(kixel.info(5)).rejects.toThrow("its deadline passed"); expect((await kixel.info()).login).toBe("waiter"); @@ -531,7 +537,7 @@ 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 kixel = new KixelQuest(URL_, TOKEN, dependencies(server.fetch, unreachable), false); const error = await new KixelQuestForge(kixel).pulls(repository).catch((e: unknown) => e); expect(error).not.toBeInstanceOf(InputError); expect((error as Error).message).toBe( @@ -541,7 +547,7 @@ describe("choosing the forge", () => { 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))); + const forge = new KixelQuestForge(new KixelQuest(URL_, TOKEN, dependencies(server.fetch, unreachable), false)); expect(await forge.viewer()).toBe("kixelated"); expect(await new GitHubForge(claimsGitHub(), "kixelated").viewer()).toBe("kixelated"); }); diff --git a/test/hold.test.ts b/test/hold.test.ts index 740a27d9..94d680d4 100644 --- a/test/hold.test.ts +++ b/test/hold.test.ts @@ -6,7 +6,7 @@ import type { GitHubDependencies, ObjectValue } from "../src/github/client"; import { finish, land, release, take } from "../src/cli/hold"; import { withoutHandBack } from "../src/core"; import { type Output, main } from "../src/cli/main"; -import { Refusal } from "../src/cli/start"; +import { Refusal } from "../src/core"; // `quest merge` through main would fetch the PR from GitHub to check it; these PRs exist only in memory. vi.mock("../src/cli/landed", async (original) => ({ @@ -251,7 +251,7 @@ async function refused(work: Promise<unknown>): Promise<string> { describe("taking a PR", () => { test("labels it quest:active and prints the event that added the label as the token", async () => { const pull = new FakePull(); - const hold = await take(PR, undefined, pull.deps()); + const hold = await take(PR, null, pull.deps()); expect(hold).toEqual({ label: "quest:active", token: "LabeledEvent_1" }); expect(pull.labels).toEqual(["quest:active"]); }); @@ -259,18 +259,18 @@ describe("taking a PR", () => { test("refuses a draft its starter still holds, and takes one handed back", async () => { const pull = new FakePull(); pull.draft = true; - expect(await refused(take(PR, undefined, pull.deps()))).toContain("its starter still holds"); + expect(await refused(take(PR, null, pull.deps()))).toContain("its starter still holds"); expect(pull.writes).toEqual([]); pull.body = "Summary.\r\n\r\n## Waiting\r\n\r\n1. Pick one.\r\n"; - expect((await take(PR, undefined, pull.deps())).label).toBe("quest:active"); + expect((await take(PR, null, pull.deps())).label).toBe("quest:active"); }); test("refuses a merged or closed PR", async () => { for (const state of ["MERGED", "CLOSED"]) { const pull = new FakePull(); pull.state = state; - expect(await refused(take(PR, undefined, pull.deps()))).toContain( + expect(await refused(take(PR, null, pull.deps()))).toContain( `is ${state.toLowerCase()}; a push now would bring its branch back`, ); expect(pull.writes).toEqual([]); @@ -279,8 +279,8 @@ describe("taking a PR", () => { test("refuses a second session without handing it the holder's token", async () => { const pull = new FakePull(); - const first = await take(PR, undefined, pull.deps()); - const message = await refused(take(PR, undefined, pull.deps())); + const first = await take(PR, null, pull.deps()); + const message = await refused(take(PR, null, pull.deps())); expect(message).toContain("held by quest:active, added just now, so stop and report it"); expect(message).not.toContain(first.token); expect(pull.labels).toEqual(["quest:active"]); @@ -289,13 +289,13 @@ describe("taking a PR", () => { test("ignores the quest:merge label older quest versions left on queued PRs", async () => { const pull = new FakePull(); pull.label("quest:merge"); - expect((await take(PR, undefined, pull.deps())).label).toBe("quest:active"); + expect((await take(PR, null, pull.deps())).label).toBe("quest:active"); expect(pull.labels).toEqual(["quest:merge", "quest:active"]); }); test("keeps the hold its token names", async () => { const pull = new FakePull(); - const hold = await take(PR, undefined, pull.deps()); + const hold = await take(PR, null, pull.deps()); expect(await take(PR, hold.token, pull.deps())).toEqual(hold); expect(pull.writes).toEqual(["add quest:active"]); }); @@ -309,9 +309,9 @@ describe("taking a PR", () => { test("refuses a token once another session holds the label", async () => { const pull = new FakePull(); - const stale = await take(PR, undefined, pull.deps()); + const stale = await take(PR, null, pull.deps()); pull.labels = []; - const current = await take(PR, undefined, pull.deps()); + const current = await take(PR, null, pull.deps()); expect(await refused(take(PR, stale.token, pull.deps()))).toContain( `quest:active was added to ${URL_} again after ${stale.token}`, ); @@ -326,13 +326,33 @@ describe("ready", () => { const pull = new FakePull(); pull.draft = true; pull.body = "Summary.\n\n## Waiting\n\n1. Pick one.\n\n## Validation\n\nTests pass."; - const hold = await take(PR, undefined, pull.deps()); + const hold = await take(PR, null, pull.deps()); expect(await finish(PR, hold.token, pull.deps())).toEqual(hold); expect(pull.body).toBe("Summary.\n\n## Validation\n\nTests pass."); expect(pull.draft).toBe(false); expect(pull.labels).toEqual(["quest:active"]); expect(pull.writes.slice(-2)).toEqual(["edit body", "markPullRequestReadyForReview"]); }); + + test("without a token, marks a draft ready and leaves its body, while no session holds it", async () => { + const pull = new FakePull(); + pull.draft = true; + pull.body = "Summary.\n\n## Waiting\n\n1. Pick one."; + expect(await finish(PR, null, pull.deps())).toBeNull(); + expect(pull.draft).toBe(false); + expect(pull.body).toBe("Summary.\n\n## Waiting\n\n1. Pick one."); + expect(pull.writes).toEqual(["markPullRequestReadyForReview"]); + }); + + test("without a token, refuses while a session holds it", async () => { + const pull = new FakePull(); + await take(PR, null, pull.deps()); + pull.draft = true; + const writes = pull.writes.length; + expect(await refused(finish(PR, null, pull.deps()))).toContain("is held by quest:active"); + expect(pull.draft).toBe(true); + expect(pull.writes).toHaveLength(writes); + }); }); describe("merge --land", () => { @@ -494,7 +514,7 @@ describe("merge --land", () => { test("takes no label, and refuses while a session holds the PR", async () => { const pull = new FakePull(); - const { token } = await take(PR, undefined, pull.deps()); + const { token } = await take(PR, null, pull.deps()); const message = await refused(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps())); expect(message).toContain("held by quest:active, added just now"); expect(message).not.toContain(token); @@ -895,20 +915,20 @@ describe("merge --land", () => { describe("release", () => { test("removes the label its token holds", async () => { const pull = new FakePull(); - const { token } = await take(PR, undefined, pull.deps()); - expect(await release(PR, token, pull.deps())).toBe("quest:active"); + const { token } = await take(PR, null, pull.deps()); + expect(await release(PR, token, pull.deps())).toEqual({ label: "quest:active", token }); expect(pull.labels).toEqual([]); }); test("refuses a stale token and treats a label already off as released", async () => { const pull = new FakePull(); - const stale = await take(PR, undefined, pull.deps()); + const stale = await take(PR, null, pull.deps()); pull.labels = []; const warnings: string[] = []; - expect(await release(PR, stale.token, pull.deps(warnings))).toBe("quest:active"); + expect((await release(PR, stale.token, pull.deps(warnings))).label).toBe("quest:active"); expect(warnings).toEqual([`quest:active is already off ${URL_}`]); - await take(PR, undefined, pull.deps()); + await take(PR, null, pull.deps()); expect(await refused(release(PR, stale.token, pull.deps()))).toContain("another session holds it"); expect(pull.labels).toEqual(["quest:active"]); }); @@ -933,7 +953,7 @@ describe("arguments", () => { } test.each([ - [["ready", URL_], "missing required argument 'token'"], + [["ready"], "missing required argument 'pr'"], [["merge", URL_], "required option '--land <sha>' not specified"], [["merge", URL_, "--land", "abc"], "--land needs a full 40-character SHA"], [["merge", URL_, "token", "--land", HEAD], "too many arguments"], diff --git a/test/kixel-fakes.ts b/test/kixel-fakes.ts new file mode 100644 index 00000000..d2fafca6 --- /dev/null +++ b/test/kixel-fakes.ts @@ -0,0 +1,231 @@ +// A fake Kixel Quest hosting one repository: its PRs, holds, picks, and review threads in memory, served over the +// forge wire. It parses every request with quest's own wire parsers, so a request the CLI shapes wrongly fails here +// as it would on Kixel Quest, and answers refusals with 409 as Kixel Quest does. +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { + type Claim, + type ForgeCall, + FORGE_CALLS, + type Hold, + type OpenPull, + forgeJson, + handedBack, + parseForgeRequest, + withoutHandBack, +} from "../src/core"; + +export const KIXEL = "http://localhost:8787"; +export const KIXEL_TOKEN = "kq-token"; +export const REPOSITORY = { owner: "example", repo: "project" }; +export const HEAD = "a".repeat(40); + +export interface KixelPull { + number: number; + branch: string; + base: string; + draft: boolean; + title: string; + body: string; + state: "open" | "closed" | "merged"; + created: number; + sha: string; + /** Review threads by ID, and whether each is resolved. */ + threads: Map<string, boolean>; + comments: { body: string; thread: string | null }[]; + hold: Hold | null; + /** The head a pick named, while it stands. */ + picked: string | null; +} + +/** The env a CLI run reads: the fake's URL, and a config directory pairing its token with it. */ +export function kixelEnv(): Record<string, string> { + const config = mkdtempSync(join(tmpdir(), "quest-kixel-")); + mkdirSync(join(config, "quest")); + writeFileSync(join(config, "quest", "records.json"), JSON.stringify({ [KIXEL]: KIXEL_TOKEN })); + return { QUEST_KIXEL_URL: KIXEL, XDG_CONFIG_HOME: config }; +} + +export class FakeKixelQuest { + readonly pulls: KixelPull[] = []; + /** Each call served, by name, with its request. */ + readonly calls: { call: string; request: unknown }[] = []; + /** What a call, or every call without `call`, answers instead, such as an outage. */ + fail: { status: number; error: string; call?: ForgeCall } | undefined; + #holds = 0; + #released = new Set<string>(); + #clock = Date.parse("2026-11-17T00:00:00Z"); + + /** Open a PR as another person did. */ + add(pull: Partial<KixelPull> & { branch: string }): KixelPull { + const number = this.pulls.length + 1; + const added: KixelPull = { + number, + base: "main", + draft: false, + title: `PR ${number}`, + body: "", + state: "open", + created: this.#clock++, + sha: HEAD, + threads: new Map(), + comments: [], + hold: null, + picked: null, + ...pull, + }; + this.pulls.push(added); + return added; + } + + url(number: number): string { + return `${KIXEL}/${REPOSITORY.owner}/${REPOSITORY.repo}/pull/${number}`; + } + + /** The fetch Kixel Quest answers; any other host is a test failure, since nothing may reach GitHub. */ + readonly fetch = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => { + const url = new URL(String(input)); + if (url.origin !== KIXEL) throw new Error(`unexpected request to ${url.origin}${url.pathname}`); + if (new Headers(init?.headers).get("authorization") !== `Bearer ${KIXEL_TOKEN}`) + return Response.json({ error: "unknown token" }, { status: 401 }); + if (url.pathname === "/forge") return Response.json({ login: "agent", repositories: [] }); + const call = /^\/forge\/(\w+)$/.exec(url.pathname)?.[1] as ForgeCall | undefined; + if (init?.method !== "POST" || call === undefined || !FORGE_CALLS.includes(call)) + return Response.json({ error: "no such call" }, { status: 404 }); + let request: any; + try { + request = parseForgeRequest(call, JSON.parse(String(init.body))); + } catch (error) { + return Response.json({ error: (error as Error).message }, { status: 400 }); + } + this.calls.push({ call, request }); + if (this.fail && (this.fail.call ?? call) === call) + return Response.json({ error: this.fail.error }, { status: this.fail.status }); + try { + const value = this.#serve(call, request); + return new Response(forgeJson({ value, asOf: null }), { headers: { "content-type": "application/json" } }); + } catch (error) { + if (error instanceof Refused) return Response.json({ error: error.message }, { status: 409 }); + throw error; + } + }; + + #serve(call: ForgeCall, request: any): unknown { + const repository = request.pull ?? request.repository ?? request.opening?.repository; + if (repository !== undefined && `${repository.owner}/${repository.repo}` !== "example/project") + throw new Refused("Kixel Quest does not host that repository"); + const pull = request.pull === undefined ? undefined : this.#pull(request.pull.number); + switch (call) { + case "pulls": + return this.pulls.filter((each) => each.state === "open").map((each) => this.#open(each)); + case "held": { + const claims = [...new Set<string>(request.branches)].sort().flatMap((branch): Claim[] => { + const open = this.pulls.find((each) => each.state === "open" && each.branch === branch); + if (open) return [{ branch, url: this.url(open.number), pull: this.#open(open) }]; + return request.sources.upstream.tips?.has(branch) ? [{ branch, url: null, pull: null }] : []; + }); + return { claims, landed: new Map() }; + } + case "open": { + const { branch, base, title, body, draft } = request.opening; + const taken = this.pulls.find((each) => each.state === "open" && each.branch === branch); + if (taken) throw new Refused(`${this.url(taken.number)} already claims ${branch}`); + return this.#open(this.add({ branch, base, title, body, draft })); + } + case "close": + pull!.state = "closed"; + return null; + case "edit": + if (request.title !== null) pull!.title = request.title; + if (request.body !== null) pull!.body = request.body; + return null; + case "comment": + if (request.thread !== null) this.#thread(pull!, request.thread); + pull!.comments.push({ body: request.body, thread: request.thread }); + return { url: `${this.url(pull!.number)}#comment-${pull!.comments.length}` }; + case "resolve": + this.#thread(pull!, request.thread); + pull!.threads.set(request.thread, true); + return null; + case "hold": + return this.#hold(pull!, request.token); + case "ready": { + if (request.token === null) { + this.#unheld(pull!); + pull!.draft = false; + return null; + } + const hold = this.#hold(pull!, request.token); + pull!.body = withoutHandBack(pull!.body); + pull!.draft = false; + return hold; + } + case "release": { + if (pull!.hold?.token === request.token) pull!.hold = null; + else if (!this.#released.has(request.token)) + throw new Refused(`${request.token} names no hold on ${this.url(pull!.number)}`); + this.#released.add(request.token); + return { label: "quest:active", token: request.token }; + } + case "pick": + this.#live(pull!); + if (pull!.sha !== request.head) + throw new Refused(`${this.url(pull!.number)} head moved to ${pull!.sha}`); + this.#unheld(pull!); + pull!.picked = request.head; + return null; + default: + throw new Error(`the fake serves no ${call}`); + } + } + + #pull(number: number): KixelPull { + const pull = this.pulls.find((each) => each.number === number); + if (!pull) throw new Refused(`no PR ${number}`); + return pull; + } + + #open(pull: KixelPull): OpenPull { + return { + number: pull.number, + url: this.url(pull.number), + branch: pull.branch, + base: pull.base, + head: "example/project", + draft: pull.draft, + created: pull.created, + updated: pull.created, + handedBack: handedBack(pull.body), + body: pull.body, + }; + } + + #thread(pull: KixelPull, id: string): void { + if (!pull.threads.has(id)) throw new Refused(`${id} is not a review thread on ${this.url(pull.number)}`); + } + + #live(pull: KixelPull): void { + if (pull.state !== "open") throw new Refused(`${this.url(pull.number)} is ${pull.state}`); + } + + #unheld(pull: KixelPull): void { + if (pull.hold !== null) throw new Refused(`${this.url(pull.number)} is held by ${pull.hold.label}`); + } + + #hold(pull: KixelPull, token: string | null): Hold { + this.#live(pull); + if (token !== null) { + if (pull.hold?.token !== token) throw new Refused(`${token} no longer holds ${this.url(pull.number)}`); + return pull.hold; + } + this.#unheld(pull); + if (pull.draft && !handedBack(pull.body)) + throw new Refused(`${this.url(pull.number)} is a draft its starter still holds`); + pull.hold = { label: "quest:active", token: `hold-${++this.#holds}` }; + return pull.hold; + } +} + +class Refused extends Error {} diff --git a/test/move.test.ts b/test/move.test.ts index a4339a5f..62649985 100644 --- a/test/move.test.ts +++ b/test/move.test.ts @@ -273,7 +273,9 @@ describe("quest mv", () => { const out = await quest(tree, "mv", "quest/m0/epic", "quest/m0/feature"); expect(out.code).toBe(1); expect(out.stdout).toBe(""); - expect(out.stderr).toContain("quest: origin is not on GitHub, so only its branches were checked for claims\n"); + expect(out.stderr).toContain( + "quest: origin is not on GitHub or Kixel Quest, so only its branches were checked for claims\n", + ); expect(out.stderr).toContain("quest: refusing to move claimed quests: quest/m0/epic/two;"); expect(existsSync(join(tree.path, "quest/m0/epic/two.md"))).toBe(true); expect(staged(tree)).toEqual([]); @@ -542,6 +544,7 @@ test("open pull requests come from every page, by head branch", async () => { const pull = (ref: string, n: number, body: string | null) => ({ number: n, head: { ref, repo: n === 1 ? { full_name: "someone/project" } : null }, + base: { ref: "main" }, draft: n === 1, body, created_at: "2026-10-21T12:00:00Z", @@ -563,6 +566,7 @@ test("open pull requests come from every page, by head branch", async () => { number: 1, url: "https://github.com/example/project/pull/1", branch: "quest/m0/a", + base: "main", head: "someone/project", draft: true, ...times, @@ -573,6 +577,7 @@ test("open pull requests come from every page, by head branch", async () => { number: 2, url: "https://github.com/example/project/pull/2", branch: "feature", + base: "main", head: null, draft: false, ...times, diff --git a/test/review.test.ts b/test/review.test.ts index b228e61a..8cc8db73 100644 --- a/test/review.test.ts +++ b/test/review.test.ts @@ -701,7 +701,7 @@ fakes("codex reviews read-only with the base's instructions, then reports in the "2. high src/lib.ts:2 Off by one", " average([3]) is 0.", // The fixture's origin is a local path, which can have no PR. - "record skipped: origin is not on GitHub", + "record skipped: origin is not on GitHub or Kixel Quest", "next respond: fix each finding or refute it with evidence the reviewer cannot rebut, commit, rerun the checks, then run the next round with --responses, one response per finding by its number", "", ].join("\n"), @@ -999,13 +999,21 @@ function onGitHub(repo: string, pulls: FakePull[], fork = false): { body: string return url.pathname.endsWith("/contents/quest/README.md") ? json({}) : json({}, 404); if (url.pathname === `/repos/${owner}/widget/pulls`) { expect(url.searchParams.get("state")).toBe("open"); - expect(url.searchParams.get("base")).toBe("main"); - const head = url.searchParams.get("head"); - return json( - head === "acme:feature" - ? pulls.map((p) => ({ ...p, html_url: `https://github.com/${owner}/widget/pull/${p.number}` })) - : [], - ); + const row = (p: FakePull, ref: string, base: string) => ({ + ...p, + html_url: `https://github.com/${owner}/widget/pull/${p.number}`, + head: { ref, repo: { full_name: "acme/widget" } }, + base: { ref: base }, + draft: false, + created_at: "2026-10-01T00:00:00Z", + updated_at: "2026-10-01T00:00:00Z", + }); + // The record's PR among others: one from another branch, and one from the same branch into another base. + return json([ + ...pulls.map((p) => row(p, "feature", "main")), + row({ number: 90, body: "other" }, "other", "main"), + row({ number: 91, body: "other" }, "feature", "release"), + ]); } const patched = new RegExp(`^/repos/${owner}/widget/pulls/(\\d+)$`).exec(url.pathname); if (patched && init?.method === "PATCH") { diff --git a/test/rules.test.ts b/test/rules.test.ts index 72b2ed71..195b86de 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -197,6 +197,14 @@ test("a new GitHub post needs the footer and no em dashes; edits and bodies off expect(bash("gh api -XPATCH repos/o/r/pulls/5 -fbody=Done")).toEqual([]); expect(bash("gh pr comment 5 --edit-last --create-if-none --body Done")).toEqual([]); expect(bash("gh pr review 5 --approve")).toEqual([]); + // quest pr posts the same way, on GitHub or Kixel Quest. + expect(bash('quest pr comment 5 --body "Done."')).toEqual([RULES.footer]); + expect(bash('quest --root .worktrees/a pr comment 5 --body "Done."')).toEqual([RULES.footer]); + expect(bash('quest --root=. pr comment 5 --body "Done."')).toEqual([RULES.footer]); + expect(bash(`quest pr comment 5 --thread T -b "Done ${DASH} mostly.\n\n${FOOTER}"`)).toEqual([RULES.emDash]); + expect(bash(`quest pr create -t "a ${DASH} b" -b "Body\n\n${FOOTER}"`)).toEqual([RULES.emDash]); + expect(bash("quest pr edit 5 --body Done")).toEqual([]); + expect(bash("quest pr resolve 5 T")).toEqual([]); expect(bash("cat .tmp/body.md | gh pr comment 5 --body-file -")).toEqual([]); expect(bash('gh pr comment 5 --body "$body"')).toEqual([]); expect(bash("gh pr comment 5 --body-file - <<EOF\n$(cat .tmp/body.md)\nEOF")).toEqual([]); diff --git a/test/start.test.ts b/test/start.test.ts index b8ae8dce..799985ec 100644 --- a/test/start.test.ts +++ b/test/start.test.ts @@ -6,16 +6,18 @@ import { execFileSync } from "node:child_process"; import { appendFileSync, cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { describe, expect, test, vi } from "vitest"; +import { afterEach, 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 { Refusal } from "../src/core"; +import { releaseQuest, startQuest } from "../src/cli/start"; import { ago } from "../src/github/hold"; import { EPIC_README, GIT_SETTINGS, TWO, Tree, configure, initRepository, template, tempDir } from "./fixture"; +import { FakeKixelQuest, KIXEL, kixelEnv } from "./kixel-fakes"; const ONE = "quest/m0/epic/one.md"; const BRANCH = "quest/m0/epic/one"; @@ -171,7 +173,12 @@ class FakeGitHub { return json(status, status === 200 ? { type: "file", path: match[2] } : { message: "Not Found" }); } match = /^\/repos\/([^/]+\/[^/]+)\/pulls$/.exec(url.pathname); - if (match && method === "GET") return json(200, this.list(match[1], url.searchParams)); + // GitHub names the base branch where this fake keeps the base repository. + if (match && method === "GET") + return json( + 200, + this.list(match[1], url.searchParams).map((pull) => ({ ...pull, base: { ref: "main" } })), + ); if (match && method === "POST") { const [owner, ref] = String(body.head).includes(":") ? String(body.head).split(":") : [null, body.head]; const headRepo = owner ? `${owner}/${match[1].split("/")[1]}` : match[1]; @@ -609,6 +616,65 @@ describe("start on GitHub", () => { }); }); +describe("start on Kixel Quest", () => { + const REMOTE = `${KIXEL}/example/project.git`; + + /** A clone whose origin is on the fake Kixel Quest, reaching a bare repository, with GitHub out of reach. */ + function hosted(): { bare: string; work: string; kixel: FakeKixelQuest } { + const kixel = new FakeKixelQuest(); + for (const [name, value] of Object.entries(kixelEnv())) vi.stubEnv(name, value); + vi.stubEnv("GH_TOKEN", ""); + vi.stubEnv("GITHUB_TOKEN", ""); + vi.stubGlobal("fetch", kixel.fetch); + const bare = upstream(); + return { bare, work: clone(REMOTE, { [REMOTE]: bare }), kixel }; + } + afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + }); + + test("claims with a draft PR there, refuses a second claim, and releases it", async () => { + const { bare, work, kixel } = hosted(); + const first = await cli("--root", work, "start", ONE); + expect(first).toEqual({ code: 0, stdout: `${kixel.url(1)}\n`, stderr: "" }); + expect(tip(bare)).toBe(git(work, "rev-parse", BRANCH)); + const [pull] = kixel.pulls; + expect(pull).toMatchObject({ branch: BRANCH, base: "main", draft: true, title: "One" }); + expect(pull!.body).toBe(`Claims \`${ONE}\`.`); + + const second = await cli("--root", work, "start", ONE); + expect(second.code).toBe(3); + expect(second.stderr).toContain(`quest: ${ONE} is held by ${kixel.url(1)} (draft, last active`); + + const released = await cli("--root", work, "start", "--release", ONE); + expect(released).toEqual({ + code: 0, + stdout: `deleted ${BRANCH}\nclosed ${kixel.url(1)}\n`, + stderr: "", + }); + expect([tip(bare), pull!.state]).toEqual(["", "closed"]); + }); + + test("a refused open takes the claim branch back", async () => { + const { bare, work, kixel } = hosted(); + // Kixel Quest refuses an open PR that another claim took in the moment since the held check. + kixel.fail = { status: 409, error: "someone claimed it first", call: "open" }; + const out = await cli("--root", work, "start", ONE); + expect(out).toEqual({ code: 3, stdout: "", stderr: "quest: someone claimed it first\n" }); + expect(tip(bare)).toBe(""); + }); + + test("pr create opens a PR from a pushed branch onto the default branch", async () => { + const { work, kixel } = hosted(); + git(work, "switch", "-q", "-c", "quest-plan/forge"); + git(work, "push", "-q", "origin", "refs/heads/quest-plan/forge:refs/heads/quest-plan/forge"); + const out = await cli("--root", work, "pr", "create", "--title", "Plan", "--body", "Why.", "--draft"); + expect(out).toEqual({ code: 0, stdout: `${kixel.url(1)}\n`, stderr: "" }); + expect(kixel.pulls[0]).toMatchObject({ branch: "quest-plan/forge", base: "main", title: "Plan", body: "Why." }); + }); +}); + describe("start on another forge", () => { /** A clone whose origin is a plain bare repository path. */ function plain(): { bare: string; work: string } { @@ -622,7 +688,7 @@ describe("start on another forge", () => { expect(first).toEqual({ code: 0, stdout: `${BRANCH}\n`, - stderr: "quest: origin is not on GitHub, so the claim branch was pushed without a PR\n", + stderr: "quest: origin is not on GitHub or Kixel Quest, so the claim branch was pushed without a PR\n", }); expect(tip(bare)).not.toBe(""); @@ -701,7 +767,7 @@ describe("start on another forge", () => { code: 0, stdout: "0\tquest/m0/epic/three.md\n", stderr: - "quest: origin is not on GitHub, so only its branches were checked for claims\n" + + "quest: origin is not on GitHub or Kixel Quest, so only its branches were checked for claims\n" + `quest: skipped ${ONE}: held by branch ${BRANCH}, with no open PR\n`, }); expect((await cli("--root", work, "unblocked", "--unclaimed", "--remote", "nope")).stderr).toBe( @@ -723,7 +789,7 @@ describe("start on another forge", () => { expect(await cli("--root", behind, "unblocked", "--unclaimed")).toEqual({ code: 0, stdout: "0\tquest/m0/epic/two.md\n", - stderr: "quest: origin is not on GitHub, so only its branches were checked for claims\n", + stderr: "quest: origin is not on GitHub or Kixel Quest, so only its branches were checked for claims\n", }); const finished = await cli("--root", behind, "start", ONE); expect(finished.code).toBe(3); @@ -791,7 +857,7 @@ test("openDrafts skips drafts with a warning when GitHub cannot be read", async expect(await openDrafts(work, "nope", offline)).toEqual([]); expect(warnings).toEqual([ "draft PRs were skipped: set GH_TOKEN or GITHUB_TOKEN, or sign in with gh auth login", - "origin is not on GitHub, so draft PRs were skipped", + "origin is not on GitHub or Kixel Quest, so draft PRs were skipped", "no nope remote, so draft PRs were skipped", ]); });