From 41b0269e8f330a79b45087b071ec2975a48a50ff Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 16:32:06 -0800 Subject: [PATCH 1/5] chore(quest): claim quest/m0/token-waste/merge-check.md Quest-Claim: fa850d9630e94b53 From 89c9b90e845e53c772baef85d5f1f854c8ec93ec Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 16:41:09 -0800 Subject: [PATCH 2/5] feat(merge): quest merge runs the landing check on the head itself quest merge --land fetches the base and the exact head into a temporary bare repository that borrows the local checkout's objects, and refuses a head on which quest check --no-stubs --base --branch finds anything the base lacks, reading git objects so nothing from the head runs. /quest-merge drops its hand check and keeps only: run a quest the PR cannot modify. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 ++-- assets/skills/merge.md | 5 +- quest/m0/token-waste/merge-check.md | 45 ----------- src/cli/hold.ts | 42 +++++++--- src/cli/land-bump.ts | 3 +- src/cli/landed.ts | 117 ++++++++++++++++++++++++---- src/cli/main.ts | 17 +++- test/hold.test.ts | 111 ++++++++++++++++---------- test/land-bump.test.ts | 8 +- test/landed.test.ts | 95 +++++++++++++++++++++- test/status.test.ts | 1 + 11 files changed, 327 insertions(+), 131 deletions(-) delete mode 100644 quest/m0/token-waste/merge-check.md diff --git a/README.md b/README.md index c6d3f8560..4c6a40af1 100644 --- a/README.md +++ b/README.md @@ -265,8 +265,8 @@ git fetch origin main quest check --base origin/main --branch quest/m0/export ``` -Fetch the base first, since a stale one can predate the quest. The -`quest-merge` skill runs this before landing a PR. A repository with +Fetch the base first, since a stale one can predate the quest. `quest merge` +runs this on the head it lands. A repository with `quest` installed in CI can also run it on pull requests, where the checkout is detached, so pass the head branch: @@ -284,8 +284,8 @@ still judge whether a rewrite matches what remains. binary carries, and reports a missing, outdated, or retired one. A job that checks a PR with a binary built from the base passes `--no-stubs`, since that binary's skills would reject a PR that changes a stub; the PR's own binary -checks them in its own `quest check`. This repository's merge queue and the -`quest-merge` skill's preflight do so. +checks them in its own `quest check`. This repository's merge queue and +`quest merge` do so. A link into a submodule that is not checked out, as in a fresh worktree or `actions/checkout` by default, resolves at the commit its gitlink pins when a @@ -563,7 +563,11 @@ it creates is the queue signal, so a queued PR shows no hold. It refuses while any session holds the PR, so release your own hold first. `--land` needs the full 40-character head SHA and refuses once the head moves, or while the latest run of any check on it failed, required or not, naming each; pending checks do not block. -It enables auto-merge bound to that SHA, or merges at once when nothing is +It also refuses a head that fails `quest check --no-stubs --base --branch +`, which it runs on git objects it fetches, so nothing from the +head runs, and ignores findings the base already has; run a `quest` the PR +cannot modify, since the head's own build could skip the check. A base without +quests skips it. It enables auto-merge bound to that SHA, or merges at once when nothing is left to wait for. `--squash` or `--rebase` picks the method, and it refuses one the repository disallows; otherwise it uses the only method the repository allows, or else a merge commit, and refuses when merge commits are off and more diff --git a/assets/skills/merge.md b/assets/skills/merge.md index 0ae0f840c..f17896e7d 100644 --- a/assets/skills/merge.md +++ b/assets/skills/merge.md @@ -31,11 +31,8 @@ Otherwise, the changes since the reviewed head need no new review only when they The repository's review policy decides whose record counts and may require more, such as a maintainer's review. Where it says nothing, only a record on a PR whose author has write access counts: anyone else writes their own PR body, so their head needs a local review that rewrites the record. -Before queueing, check the head with a `quest` the PR cannot modify: fetch the PR's base branch and its exact head, check the head out apart from your own checkout, such as in a detached worktree under `.tmp/`, and from a directory outside it run `quest --root check --no-stubs --base / --branch `. -The head's files are untrusted, and a stale local base can skip the check; `--no-stubs` is there because the PR's own checks verify its stubs. -A finding means the PR leaves its quest inaccurate: it needs `/quest-iterate`. - Queue the head with `quest merge --land `, adding `--squash` or `--rebase` when the repository's root instructions name that method for the PR's base. +Run a `quest` the PR cannot modify, such as an installed release rather than a build from the head's checkout: it refuses a head that leaves its quest inaccurate, a check the head's own code could skip. A refusal says what the head or the repository needs: follow it, sending a head that needs a fix or its base merged to `/quest-iterate`. Ask instead when it refuses a head `/quest-iterate` left unchanged, and never pass `--direct` unless the user explicitly asks. diff --git a/quest/m0/token-waste/merge-check.md b/quest/m0/token-waste/merge-check.md deleted file mode 100644 index cde747499..000000000 --- a/quest/m0/token-waste/merge-check.md +++ /dev/null @@ -1,45 +0,0 @@ -# [M] quest merge runs the landing check itself - -## Goal - -`quest merge --land` refuses a head whose diff leaves its quest -inaccurate, by running what `quest check --base --branch ` -checks against the exact head it is about to queue, so `/quest-merge` no -longer tells the agent to fetch the head, check it out apart, and run the -check by hand. Of the paragraph that describes those steps, -`assets/skills/merge.md` keeps only what a program cannot enforce on -itself: run `quest merge` with a `quest` the PR cannot modify. - -Non-goal: the other landable conditions `/quest-merge` judges, such as -whose review counts. - -## Plan - -Found 2026-11-12 while trimming the skills against five days of session -transcripts: 81 sessions ran the hand check 235 times, 219 passed, about 5 -found something, and 3 failed because the scratch checkout was missing. -The steps are also the kind of rule prose holds badly: the head's files are -untrusted, so the agent must use a `quest` the PR cannot modify, from a -directory outside the head's checkout, against a freshly fetched base. In -this repository `bun run quest` inside a head checkout would run the -head's own code. - -Agent's choices, for the implementer to revisit: - -- `quest merge` already reads the head and base from GitHub, so it - fetches both and checks the head's tree itself, without running anything - from it. Reading the tree from Git objects avoids a checkout; a - temporary detached worktree that it removes is the fallback if - `quest check` needs files on disk. -- The check is only as trusted as the `quest` that runs it. A session that - reviewed a PR sits in its head's checkout, where a PR that edits the CLI - or the repository's pin of it could skip the check, so the skill still - says to run `quest merge` with a `quest` the PR cannot modify, such as - an installed release from outside the head's checkout. Weigh having - `quest merge` refuse to run from a checkout of the head it lands. -- A finding is a refusal that names it and says the PR needs - `/quest-iterate`, like the refusal of a failed check - ([moq-dev/quest#601](https://github.com/moq-dev/quest/pull/601)). -- A base whose gate already runs the check, as this repository's - `queue-build.yml` does, still gets it: the refusal arrives before a queue - build is spent. diff --git a/src/cli/hold.ts b/src/cli/hold.ts index 8961bd6b6..1670222f3 100644 --- a/src/cli/hold.ts +++ b/src/cli/hold.ts @@ -2,7 +2,7 @@ // a time. It holds the `quest:active` label, and the ID of the timeline event // that added the label is its hold token, since sessions often share an account. // `quest merge` takes no label: the pinned auto-merge or merge-queue entry it creates is the queue signal. -import { ACTIVE_LABEL, handedBack, isHoldLabel, latestHold, heldToken, withoutHandBack } from "../core"; +import { ACTIVE_LABEL, formatFinding, handedBack, isHoldLabel, latestHold, heldToken, withoutHandBack } from "../core"; import { cleanAutoMergeRefusal, immediateMerge, queueHead } from "../github/merge"; import { repositoryPath } from "./claims"; import { @@ -19,6 +19,7 @@ import { import { latestContexts } from "../github/checks"; import { ALLOWS, LAND_CHECK, METHOD_NAMES, contexts, enqueue } from "./land"; import { QUEUE_CHECK } from "./land-queue"; +import type { LandingCheck } from "./landed"; import { classifyCheck } from "./status"; import { Refusal, ago } from "./start"; @@ -28,7 +29,7 @@ export type Method = "merge" | "squash" | "rebase"; const READ = `query HoldOwnership($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { - id url state isDraft body updatedAt baseRefName headRefOid mergeStateStatus isMergeQueueEnabled isInMergeQueue + id url state isDraft body updatedAt baseRefName headRefName headRefOid mergeStateStatus isMergeQueueEnabled isInMergeQueue labels(first: 100) { nodes { name } } timelineItems(last: 100, itemTypes: [LABELED_EVENT]) { nodes { __typename ... on LabeledEvent { id createdAt label { name } } } @@ -52,6 +53,8 @@ interface Snapshot { body: string; updatedAt: string; base: string; + /** The head branch's name. */ + branch: string; head: string; mergeState: string; queue: boolean; @@ -208,6 +211,17 @@ function signalMethod( return method; } +/** What `quest merge` lands, and how. */ +export interface LandRequest { + /** The full head SHA to land, which must still be the PR's head. */ + sha: string; + /** The method the caller asked for; otherwise {@link mergeMethod} picks one on an ungated base. */ + method?: Method; + /** Merge at once on an ungated base with auto-merge disabled. */ + direct?: boolean; + check: LandingCheck; +} + /** * Land `sha`, which must still be the head of `pr`, while no session holds it: * enable auto-merge bound to it, or merge at once when GitHub would refuse auto-merge because @@ -215,15 +229,11 @@ function signalMethod( * A base that requires the `quest land` check queues it for `quest land` instead: * auto-merge whose commit body pins `sha`, with a method {@link signalMethod} picks. * That request only signals the queue: `quest land` lands with its own method. It takes no label. - * `named` is the method the caller asked for; otherwise {@link mergeMethod} picks one on an ungated base. + * It first refuses a head whose quest check finds anything, so the refusal comes before a queue + * build is spent, even on a base whose gate checks it again. */ -export async function land( - pr: PullRequest, - sha: string, - named: Method | undefined, - deps: GitHubDependencies, - direct = false, -): Promise { +export async function land(pr: PullRequest, request: LandRequest, deps: GitHubDependencies): Promise { + const { sha, method: named, direct = false } = request; const labels = new Labels(pr, deps); const current = (snapshot: Snapshot) => headAt(snapshot, sha); const snapshot = await labels.read(); @@ -241,6 +251,17 @@ export async function land( } }; await passing(labels.github, pr, snapshot.url, sha); + const findings = await request.check({ + remote: `https://github.com/${pr.owner}/${pr.repo}.git`, + base: snapshot.base, + branch: snapshot.branch, + sha, + token: deps.token, + }); + if (findings.length > 0) + throw new Refusal( + `${snapshot.url} head ${sha} fails quest check against ${snapshot.base}:\n${findings.map(formatFinding).join("\n")}\nfix the PR, then land it again`, + ); const needs = await requirements(labels.github, pr, snapshot.base); if (needs.checks.some((check) => check.name === LAND_CHECK)) { if (named !== undefined) @@ -518,6 +539,7 @@ class Labels { body: typeof row.body === "string" ? row.body : "", updatedAt: string(row.updatedAt), base: string(row.baseRefName), + branch: string(row.headRefName), head: string(row.headRefOid), mergeState: string(row.mergeStateStatus), queue: row.isMergeQueueEnabled === true, diff --git a/src/cli/land-bump.ts b/src/cli/land-bump.ts index 9bcce2c9f..7c3969f58 100644 --- a/src/cli/land-bump.ts +++ b/src/cli/land-bump.ts @@ -453,7 +453,8 @@ async function settle(target: Repository, record: Bump, connection: BumpConnecti direct = object(await (await github.request(path)).json()).allow_auto_merge !== true; } try { - await land({ ...target, number: pr }, head, undefined, connection.deps, direct); + // The bump PR is this process's own commit of version files, so it has no quest to check. + await land({ ...target, number: pr }, { sha: head, direct, check: async () => [] }, connection.deps); } catch (error) { if (!(error instanceof Refusal)) throw error; return fail(`landing it was refused: ${error.message}`); diff --git a/src/cli/landed.ts b/src/cli/landed.ts index d20354567..724a34e82 100644 --- a/src/cli/landed.ts +++ b/src/cli/landed.ts @@ -4,28 +4,37 @@ // lives here rather than in the core. import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; -import { type Finding, branchQuest } from "../core"; +import { type Finding, branchQuest, check } from "../core"; import { discoveryEnv } from "./git"; +import { gitEnvironment } from "./land"; +import { snapshot } from "./tree"; /** * A finding when `branch` (default: the current branch) is a quest's branch - * and the working tree neither deletes nor modifies that quest relative to its - * merge base with `base`. Not a quest branch, or no such quest at the merge - * base, is no finding. + * and `head` (default: the working tree) neither deletes nor modifies that + * quest relative to its merge base with `base`. Not a quest branch, or no such + * quest at the merge base, is no finding. With `head`, `root` is the + * repository's top level, as in a bare repository. */ -export function landed(root: string, base: string, branch?: string): Finding[] { - const name = branch ?? currentBranch(root); - const mergeBase = git(root, ["merge-base", base, "HEAD"]); +export function landed(root: string, base: string, options: { branch?: string; head?: string } = {}): Finding[] { + const name = options.branch ?? currentBranch(root); + const mergeBase = git(root, ["merge-base", base, options.head ?? "HEAD"]); if (mergeBase.status !== 0) { throw new Error(`no merge base between ${base} and HEAD: ${mergeBase.stderr.trim() || "unrelated histories"}`); } const commit = mergeBase.stdout.trim(); - const path = questAt(root, commit, name); + // Without a head, the pathspec and `:./path` are relative to the root, + // which may sit below the repository's top level; a bare repository has no + // work tree to be relative to. + const relative = options.head === undefined ? "./" : ""; + const path = questAt(root, commit, name, relative); if (path === null) return []; - // The pathspec and `:./path` are relative to the root, which may sit - // below the repository's top level. - const diff = git(root, ["diff", "--quiet", "--no-ext-diff", commit, "--", `./${path}`]); + const heads = options.head === undefined ? [] : [options.head]; + const diff = git(root, ["diff", "--quiet", "--no-ext-diff", commit, ...heads, "--", `${relative}${path}`]); if (diff.status === 1) return []; if (diff.status !== 0) throw new Error(`git diff ${commit} -- ${path}: ${diff.stderr.trim()}`); return [ @@ -39,11 +48,93 @@ export function landed(root: string, base: string, branch?: string): Finding[] { ]; } +/** The PR head `quest merge` is about to land, and where to fetch it and its base. */ +export interface LandingHead { + /** The base repository's Git URL, which serves the head's commits even from a fork. */ + remote: string; + base: string; + branch: string; + sha: string; + token: string; +} + +/** Checks a head before `quest merge` queues it; resolves to its findings, empty when it may land. */ +export type LandingCheck = (head: LandingHead) => Promise; + +/** + * What `quest check --no-stubs --base --branch ` reports on `head.sha`, against a + * freshly fetched base. The head is untrusted, so nothing from it runs or is checked out: the + * check reads git objects in a temporary bare repository that borrows the objects of the + * checkout at `root`, if any, and fetches only what it lacks. A base without quests is a + * repository that does not use them, so it has no findings, and a finding the base already + * has is not the head's, as the land daemon screens a head. + */ +export function landingCheck(root: string): LandingCheck { + return async (head) => { + const dir = mkdtempSync(join(tmpdir(), "quest-merge-")); + try { + const run = (args: string[], env: Record = {}) => { + const result = spawnSync("git", ["-c", "core.hooksPath=/dev/null", "-C", dir, ...args], { + encoding: "utf8", + env: { ...gitEnvironment(), ...env }, + maxBuffer: 1 << 30, + }); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`git ${args[0]} failed: ${result.stderr.trim()}`); + return result.stdout.trim(); + }; + run(["init", "--quiet", "--bare"]); + const local = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]); + if (local.status === 0) + writeFileSync(join(dir, "objects/info/alternates"), `${local.stdout.trim()}/objects\n`); + // The token rides in the environment, never in arguments other processes can read. + const basic = Buffer.from(`x-access-token:${head.token}`).toString("base64"); + run( + [ + "fetch", + "--quiet", + "--no-tags", + head.remote, + `+refs/heads/${head.base}:refs/remotes/origin/${head.base}`, + `+${head.sha}:refs/quest/head`, + ], + { + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader", + GIT_CONFIG_VALUE_0: `Authorization: basic ${basic}`, + }, + ); + if (run(["ls-tree", "--name-only", `origin/${head.base}`, "quest"]) === "") return []; + const known = treeCheck(dir, `origin/${head.base}`); + // A finding the base already has is not this PR's, such as one a `quest` older than the tree's format reports. + const findings = treeCheck(dir, "refs/quest/head").filter( + (finding) => !known.some((old) => old.path === finding.path && old.message === finding.message), + ); + return [ + ...findings, + ...landed(dir, `origin/${head.base}`, { branch: head.branch, head: "refs/quest/head" }), + ]; + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }; +} + +/** `quest check`'s findings on `commit`; a tree it cannot read, such as one with no quests left, is one. */ +function treeCheck(dir: string, commit: string): Finding[] { + try { + const tree = snapshot(dir, commit, null); + return check(tree.docs, tree.exists); + } catch (error) { + return [{ path: "quest", line: null, message: error instanceof Error ? error.message : String(error) }]; + } +} + /** The quest file `branch` names, if it existed at `commit`. */ -function questAt(root: string, commit: string, branch: string): string | null { +function questAt(root: string, commit: string, branch: string, relative: string): string | null { if (!branch.startsWith("quest/") || branch.endsWith("/")) return null; const path = branchQuest(branch); - return git(root, ["cat-file", "-e", `${commit}:./${path}`]).status === 0 ? path : null; + return git(root, ["cat-file", "-e", `${commit}:${relative}${path}`]).status === 0 ? path : null; } function currentBranch(root: string): string { diff --git a/src/cli/main.ts b/src/cli/main.ts index 0c5a9c2bf..24113a609 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -41,7 +41,7 @@ import { apply, pushCommand } from "./land-apply"; import { EFFORT_VARIABLE, EFFORTS, fix, FixerAgentError } from "./land-fix"; import { serve, type ServeOptions } from "./land-serve"; import { watch, type WatchOptions } from "./land-watch"; -import { landed } from "./landed"; +import { landed, landingCheck } from "./landed"; import { type Report, fixHeadings, fixLinks, moveQuest, removeQuest } from "./move"; import { type ResolveOptions, resolveFile } from "./resolve"; import { hosts } from "../core/doc"; @@ -203,7 +203,7 @@ export function main(argv: string[], out: Output): number | Promise { } const tree = checkout(root(), warn); const findings = check(tree.docs, tree.exists); - if (options.base !== undefined) findings.push(...landed(root(), options.base, options.branch)); + if (options.base !== undefined) findings.push(...landed(root(), options.base, { branch: options.branch })); // A tree nested in another checkout, such as an example, has no stubs of its own. const stubs = options.stubs && questRoot(resolve(root())) === resolve(root()) ? stubFindings(root()) : []; if (findings.length === 0 && stubs.length === 0) { @@ -623,7 +623,9 @@ export function main(argv: string[], out: Output): number | Promise { "once when nothing is left to wait for. It takes no label: the auto-merge or merge-queue entry it " + "creates is the queue signal. It refuses while a session holds the PR, so release your own hold " + "first, once the head has moved, and while the latest run of any check on the head failed, required " + - "or not, naming each; a pending or absent check does not block. It uses the method --squash or --rebase names, refusing one " + + "or not, naming each; a pending or absent check does not block. It refuses a head on which quest check " + + "--no-stubs --base --branch finds anything, read from git objects fetched from the base repository, " + + "so nothing from the head runs, except findings the base already has; a base without quests skips it. It uses the method --squash or --rebase names, refusing one " + "the repository disallows; otherwise the only method the repository allows, or else a merge commit. " + "On a base with GitHub's merge queue, which applies its own method, it enqueues that head, or arms " + "auto-merge bound to it while required checks may be pending; a head behind the base is enqueued as " + @@ -647,7 +649,14 @@ export function main(argv: string[], out: Output): number | Promise { 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, options.land, method, gitHubDependencies(warn), options.direct), () => undefined); + settle( + land( + pr, + { sha: options.land, method, direct: options.direct, check: landingCheck(root()) }, + gitHubDependencies(warn), + ), + () => undefined, + ); }); const landCommand = program.command("land").summary("Land queued PRs through a host daemon"); diff --git a/test/hold.test.ts b/test/hold.test.ts index 59454cab8..1e1099a2d 100644 --- a/test/hold.test.ts +++ b/test/hold.test.ts @@ -8,10 +8,18 @@ import { withoutHandBack } from "../src/core"; import { type Output, main } from "../src/cli/main"; import { Refusal } from "../src/cli/start"; +// `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) => ({ + ...(await original()), + landingCheck: () => async () => [], +})); + const PR = { owner: "example", repo: "project", number: 7 }; const URL_ = "https://github.com/example/project/pull/7"; const HEAD = "a".repeat(40); const BASE = "b".repeat(40); +/** A landing check that finds nothing. */ +const clean = async () => []; interface Event { __typename: "LabeledEvent" | "AutoMergeEnabledEvent" | "AddedToMergeQueueEvent"; @@ -182,6 +190,7 @@ class FakePull { body: this.body, updatedAt: new Date(this.clock).toISOString(), baseRefName: this.baseRef, + headRefName: "quest/m0/example", headRefOid: this.head, mergeStateStatus: this.mergeState, isMergeQueueEnabled: this.queue, @@ -299,7 +308,9 @@ describe("merge --land", () => { const pull = new FakePull(); pull.allowAutoMerge = false; pull.mergeState = state; - expect(await refused(land(PR, HEAD, "squash", pull.deps()))).toContain("CONTRIBUTING.md or AGENTS.md"); + expect(await refused(land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps()))).toContain( + "CONTRIBUTING.md or AGENTS.md", + ); expect(pull.writes).toEqual([]); expect(pull.state).toBe("OPEN"); }); @@ -322,13 +333,13 @@ describe("merge --land", () => { run(2, "Lint", "IN_PROGRESS", null), run(4, "quest queue", "COMPLETED", "FAILURE"), ]; - expect(await refused(land(PR, HEAD, "merge", pull.deps()))).toContain( + expect(await refused(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()))).toContain( `head ${HEAD} failed a check: Check (https://ci.example/1)`, ); expect(pull.writes).toEqual([]); // A rerun that passed supersedes the failure; a pending check does not block. pull.checks.push(run(3, "Check", "COMPLETED", "SUCCESS")); - await land(PR, HEAD, "merge", pull.deps()); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()); expect(pull.writes).not.toEqual([]); }); @@ -336,21 +347,25 @@ describe("merge --land", () => { const pull = new FakePull(); pull.allowAutoMerge = null; pull.mergeState = "CLEAN"; - expect(await refused(land(PR, HEAD, "squash", pull.deps()))).toContain("not visible to this token"); + expect(await refused(land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps()))).toContain( + "not visible to this token", + ); expect(pull.writes).toEqual([]); }); 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 message = await refused(land(PR, HEAD, "merge", 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); await release(PR, token, pull.deps()); pull.label("quest:active"); - expect(await refused(land(PR, HEAD, "merge", pull.deps()))).toContain("held by quest:active"); + expect(await refused(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()))).toContain( + "held by quest:active", + ); pull.labels = ["quest:merge"]; - await land(PR, HEAD, "merge", pull.deps()); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} MERGE`); expect(pull.labels).toEqual(["quest:merge"]); }); @@ -362,16 +377,22 @@ describe("merge --land", () => { pull.afterRead = undefined; pull.baseRef = "release"; }; - expect(await refused(land(PR, HEAD, "squash", pull.deps()))).toContain("retargeted from main to release"); + expect(await refused(land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps()))).toContain( + "retargeted from main to release", + ); expect(pull.writes).toEqual([]); }); test("refuses a merged PR or a draft its starter still holds", async () => { const pull = new FakePull(); pull.draft = true; - expect(await refused(land(PR, HEAD, "merge", pull.deps()))).toContain("its starter still holds"); + expect(await refused(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()))).toContain( + "its starter still holds", + ); pull.state = "MERGED"; - expect(await refused(land(PR, HEAD, "merge", pull.deps()))).toContain("is merged"); + expect(await refused(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()))).toContain( + "is merged", + ); expect(pull.writes).toEqual([]); }); @@ -379,7 +400,7 @@ describe("merge --land", () => { const pull = new FakePull(); pull.allowAutoMerge = false; pull.queue = true; - await land(PR, HEAD, "merge", pull.deps()); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} MERGE`); }); @@ -391,7 +412,7 @@ describe("merge --land", () => { pull.mergeState = state; pull.comparison = "diverged"; const warnings: string[] = []; - await land(PR, HEAD, "merge", pull.deps(warnings)); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps(warnings)); expect(pull.writes).toEqual([`enqueuePullRequest ${HEAD}`]); expect(pull.queueEntry).not.toBeNull(); expect(pull.comparisons).toEqual([]); @@ -403,7 +424,7 @@ describe("merge --land", () => { const pull = new FakePull(); pull.queue = true; pull.mergeState = "BLOCKED"; - await land(PR, HEAD, "merge", pull.deps()); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()); expect(pull.writes).toEqual([`enablePullRequestAutoMerge ${HEAD} MERGE`]); }); @@ -412,7 +433,7 @@ describe("merge --land", () => { pull.queue = true; pull.mergeState = "UNKNOWN"; pull.beforeAutoMerge = () => "Pull request is in clean status"; - await land(PR, HEAD, "squash", pull.deps()); + await land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps()); expect(pull.writes).toEqual([`enablePullRequestAutoMerge ${HEAD} SQUASH`, `enqueuePullRequest ${HEAD}`]); }); @@ -421,7 +442,7 @@ describe("merge --land", () => { pull.queue = true; pull.mergeState = "DIRTY"; pull.beforeEnqueue = () => ({ message: "Pull request is not mergeable", type: "UNPROCESSABLE" }); - expect(await refused(land(PR, HEAD, "merge", pull.deps()))).toBe( + expect(await refused(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()))).toBe( `${URL_}: GitHub refused to enqueue ${HEAD} (GitHub GraphQL error: Pull request is not mergeable); fix the PR, for example with /quest-iterate, and land it again`, ); expect(pull.queueEntry).toBeNull(); @@ -436,7 +457,7 @@ describe("merge --land", () => { return { message: "Pull request is already queued" }; }; const warnings: string[] = []; - await land(PR, HEAD, "merge", pull.deps(warnings)); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps(warnings)); expect(warnings).toEqual([]); }); @@ -448,7 +469,9 @@ describe("merge --land", () => { pull.head = "c".repeat(40); return { message: "Head ref has moved" }; }; - expect(await refused(land(PR, HEAD, "merge", pull.deps()))).toContain(`head moved to ${"c".repeat(40)}`); + expect(await refused(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()))).toContain( + `head moved to ${"c".repeat(40)}`, + ); }); test("passes on an enqueue error that faults the token rather than the PR", async () => { @@ -456,7 +479,9 @@ describe("merge --land", () => { pull.queue = true; pull.mergeState = "CLEAN"; pull.beforeEnqueue = () => ({ message: "Resource not accessible by integration", type: "FORBIDDEN" }); - const error = await land(PR, HEAD, "merge", pull.deps()).catch((caught: unknown) => caught); + const error = await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()).catch( + (caught: unknown) => caught, + ); expect(error).not.toBeInstanceOf(Refusal); expect(error).toMatchObject({ message: "GitHub GraphQL error: Resource not accessible by integration" }); }); @@ -487,7 +512,7 @@ describe("merge --land", () => { const pull = new FakePull(); pull.allowAutoMerge = false; pull.mergeState = state; - await land(PR, HEAD, "squash", pull.deps(), true); + await land(PR, { sha: HEAD, method: "squash", direct: true, check: clean }, pull.deps()); expect(pull.writes).toEqual([`mergePullRequest ${HEAD} SQUASH`]); }); @@ -496,12 +521,12 @@ describe("merge --land", () => { async (status) => { const pull = new FakePull(); pull.comparison = status; - const refusal = await refused(land(PR, HEAD, "squash", pull.deps())); + const refusal = await refused(land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps())); expect(refusal).toContain(`head ${HEAD} does not contain main at ${BASE}`); expect(pull.writes).toEqual([]); pull.head = "c".repeat(40); pull.comparison = "ahead"; - await land(PR, pull.head, "squash", pull.deps()); + await land(PR, { sha: pull.head, method: "squash", check: clean }, pull.deps()); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${pull.head} SQUASH`); }, ); @@ -510,13 +535,13 @@ describe("merge --land", () => { const pull = new FakePull(); pull.comparison = "identical"; pull.base = HEAD; - await land(PR, HEAD, "merge", pull.deps()); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} MERGE`); }); test("enables auto-merge with a merge commit by default, bound to the head", async () => { const pull = new FakePull(); - await land(PR, HEAD, "merge", pull.deps()); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()); expect(pull.writes).toEqual([`enablePullRequestAutoMerge ${HEAD} MERGE`]); expect(pull.labels).toEqual([]); }); @@ -525,7 +550,7 @@ describe("merge --land", () => { for (const method of ["squash", "rebase"] as const) { const pull = new FakePull(); pull.mergeState = "CLEAN"; - await land(PR, HEAD, method, pull.deps()); + await land(PR, { sha: HEAD, method: method, check: clean }, pull.deps()); expect(pull.writes.at(-1)).toBe(`mergePullRequest ${HEAD} ${method.toUpperCase()}`); } }); @@ -544,14 +569,14 @@ describe("merge --land", () => { test("uses the only method allowed without a flag", async () => { for (const method of ["squash", "rebase"]) { const pull = allowing(method); - await land(PR, HEAD, undefined, pull.deps()); + await land(PR, { sha: HEAD, check: clean }, pull.deps()); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} ${method.toUpperCase()}`); } }); test("keeps a merge commit by default while one is allowed", async () => { const pull = allowing("merge", "squash"); - await land(PR, HEAD, undefined, pull.deps()); + await land(PR, { sha: HEAD, check: clean }, pull.deps()); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} MERGE`); }); @@ -559,7 +584,7 @@ describe("merge --land", () => { const pull = allowing("squash"); pull.allowAutoMerge = false; pull.mergeState = "CLEAN"; - await land(PR, HEAD, undefined, pull.deps(), true); + await land(PR, { sha: HEAD, direct: true, check: clean }, pull.deps()); expect(pull.writes).toEqual([`mergePullRequest ${HEAD} SQUASH`]); }); @@ -572,7 +597,9 @@ describe("merge --land", () => { ]; for (const [methods, named, refusal] of cases) { const pull = allowing(...methods); - expect(await refused(land(PR, HEAD, named, pull.deps()))).toContain(refusal); + expect(await refused(land(PR, { sha: HEAD, method: named, check: clean }, pull.deps()))).toContain( + refusal, + ); expect(pull.writes).toEqual([]); } }); @@ -588,7 +615,7 @@ describe("merge --land", () => { const gated = allowing(...methods); gated.required = ["quest land"]; if (ruled) gated.rules = [{ type: "pull_request", parameters: { allowed_merge_methods: [...ruled] } }]; - await land(PR, HEAD, undefined, gated.deps()); + await land(PR, { sha: HEAD, check: clean }, gated.deps()); expect(gated.writes.at(-1)).toBe( `enablePullRequestAutoMerge ${HEAD} ${signal} Quest-Land-Head: ${HEAD}`, ); @@ -596,11 +623,11 @@ describe("merge --land", () => { const refusing = allowing("merge", "squash"); refusing.required = ["quest land"]; refusing.rules = [{ type: "pull_request", parameters: { allowed_merge_methods: ["merge"] } }]; - expect(await refused(land(PR, HEAD, "squash", refusing.deps()))).toContain( + expect(await refused(land(PR, { sha: HEAD, method: "squash", check: clean }, refusing.deps()))).toContain( "cannot land with squash merges on main, by its repository settings or rulesets", ); refusing.rules.push({ type: "pull_request", parameters: { allowed_merge_methods: ["squash"] } }); - expect(await refused(land(PR, HEAD, undefined, refusing.deps()))).toContain( + expect(await refused(land(PR, { sha: HEAD, check: clean }, refusing.deps()))).toContain( "has no merge method its repository and main's rulesets both allow", ); expect(refusing.writes).toEqual([]); @@ -608,7 +635,7 @@ describe("merge --land", () => { const queued = allowing("squash"); queued.queue = true; const warnings: string[] = []; - await land(PR, HEAD, undefined, queued.deps(warnings)); + await land(PR, { sha: HEAD, check: clean }, queued.deps(warnings)); expect(queued.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} MERGE`); expect(warnings).toEqual([]); }); @@ -619,7 +646,7 @@ describe("merge --land", () => { pull.mergeState = "CLEAN"; pull.queue = true; const warnings: string[] = []; - await land(PR, HEAD, "squash", pull.deps(warnings)); + await land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps(warnings)); expect(pull.writes.at(-1)).toBe(`enqueuePullRequest ${HEAD}`); expect(warnings).toEqual([`${URL_} lands through a merge queue, which applies its own merge method`]); }); @@ -630,7 +657,7 @@ describe("merge --land", () => { pull.allowAutoMerge = false; // The host-gated path does not use the ungated pre-check. pull.comparison = "diverged"; const warnings: string[] = []; - await land(PR, HEAD, "merge", pull.deps(warnings)); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps(warnings)); expect(pull.writes).toEqual([`enablePullRequestAutoMerge ${HEAD} MERGE Quest-Land-Head: ${HEAD}`]); expect(warnings).toEqual([`${URL_} lands through quest land, which applies its own merge method`]); expect(pull.comparisons).toEqual([]); @@ -640,7 +667,7 @@ describe("merge --land", () => { const pull = new FakePull(); pull.required = ["test", "quest land"]; pull.autoMerge = { enabledAt: "2026-10-20T12:00:00Z", commitBody: `Quest-Land-Head: ${"0".repeat(40)}` }; - await land(PR, HEAD, "squash", pull.deps()); + await land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps()); expect(pull.writes.slice(-2)).toEqual([ "disablePullRequestAutoMerge", `enablePullRequestAutoMerge ${HEAD} SQUASH Quest-Land-Head: ${HEAD}`, @@ -652,7 +679,7 @@ describe("merge --land", () => { const pull = new FakePull(); pull.required = ["test", "quest land"]; pull.autoMerge = { enabledAt: "2026-10-20T12:00:00Z", commitBody: "" }; - await land(PR, HEAD, "squash", pull.deps()); + await land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps()); expect(pull.autoMerge?.commitBody).toBe(`Quest-Land-Head: ${HEAD}`); }); @@ -665,7 +692,7 @@ describe("merge --land", () => { pull.mergeState = state; return "Pull request is in clean status"; }; - await land(PR, HEAD, "squash", pull.deps()); + await land(PR, { sha: HEAD, method: "squash", check: clean }, pull.deps()); expect(pull.writes).toEqual([ `enablePullRequestAutoMerge ${HEAD} SQUASH`, `mergePullRequest ${HEAD} SQUASH`, @@ -678,7 +705,7 @@ describe("merge --land", () => { test("keeps UNKNOWN on auto-merge when GitHub accepts it", async () => { const pull = new FakePull(); pull.mergeState = "UNKNOWN"; - await land(PR, HEAD, "merge", pull.deps()); + await land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} MERGE`); expect(pull.reads).toBe(2); expect(pull.state).toBe("OPEN"); @@ -690,7 +717,7 @@ describe("merge --land", () => { const pull = new FakePull(); pull.mergeState = "UNKNOWN"; pull.beforeAutoMerge = () => reason; - await expect(land(PR, HEAD, "merge", pull.deps())).rejects.toThrow(reason); + await expect(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps())).rejects.toThrow(reason); expect(pull.reads).toBe(reason.includes("clean status") ? 3 : 2); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} MERGE`); }, @@ -710,7 +737,7 @@ describe("merge --land", () => { if (change === "queue") pull.queue = true; return "Pull request is in clean status"; }; - await expect(land(PR, HEAD, "merge", pull.deps())).rejects.toThrow(); + await expect(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps())).rejects.toThrow(); expect(pull.state).toBe("OPEN"); expect(pull.writes.at(-1)).toBe(`enablePullRequestAutoMerge ${HEAD} MERGE`); }, @@ -719,7 +746,9 @@ describe("merge --land", () => { test("refuses a head that moved", async () => { const pull = new FakePull(); pull.head = "b".repeat(40); - expect(await refused(land(PR, HEAD, "merge", pull.deps()))).toContain(`head moved to ${"b".repeat(40)}`); + expect(await refused(land(PR, { sha: HEAD, method: "merge", check: clean }, pull.deps()))).toContain( + `head moved to ${"b".repeat(40)}`, + ); expect(pull.writes).toEqual([]); }); }); diff --git a/test/land-bump.test.ts b/test/land-bump.test.ts index 5c46f7e36..22ea34cf9 100644 --- a/test/land-bump.test.ts +++ b/test/land-bump.test.ts @@ -317,10 +317,8 @@ describe("bumpPass", () => { expect(target.pulls[0].body).toContain("changed `stub.md`"); expect(landed).toHaveBeenCalledExactlyOnceWith( { ...target.target, number: 7 }, - head, - undefined, + { sha: head, direct: false, check: expect.any(Function) }, expect.anything(), - false, ); // The next pass at the same commit asks GitHub nothing. @@ -393,10 +391,8 @@ describe("bumpPass", () => { expect(await bumpPass(ctx, NEW)).toEqual(["bump landing moq-dev/widget 7"]); expect(landed).toHaveBeenCalledExactlyOnceWith( { ...target.target, number: 7 }, - head, - undefined, + { sha: head, direct: true, check: expect.any(Function) }, expect.anything(), - true, ); }); diff --git a/test/landed.test.ts b/test/landed.test.ts index 96422de89..0ef64c629 100644 --- a/test/landed.test.ts +++ b/test/landed.test.ts @@ -2,9 +2,13 @@ import { execFileSync } from "node:child_process"; -import { expect, test } from "vitest"; +import { readdirSync } from "node:fs"; +import { tmpdir } from "node:os"; -import { Tree } from "./fixture"; +import { describe, expect, test } from "vitest"; + +import { landingCheck } from "../src/cli/landed"; +import { Tree, initRepository, tempDir } from "./fixture"; const FINDING = "neither deletes nor edits its quest since main"; @@ -120,3 +124,90 @@ test("an unknown base fails", () => { test("--branch without --base is a usage error", () => { expect(Tree.baseline().run("check", "--branch", "quest/m0/epic/one").code).toBe(2); }); + +describe("quest merge's landing check", () => { + /** Check `branch`'s tip in `tree` as `quest merge` would, fetching from `tree` into `root`. */ + function inspect(tree: Tree, branch: string, root = tempDir()) { + const sha = git(tree, "rev-parse", branch).trim(); + return landingCheck(root)({ remote: tree.path, base: "main", branch, sha, token: "token" }); + } + + test("finds a head that leaves its quest untouched, against the fetched base", async () => { + const tree = repo("quest/m0/epic/one"); + tree.write("src.ts", "work\n"); + commit(tree, "work"); + const findings = await inspect(tree, "quest/m0/epic/one"); + expect(findings.map((finding) => [finding.path, finding.message])).toEqual([ + ["quest/m0/epic/one.md", expect.stringContaining("neither deletes nor edits its quest since origin/main")], + ]); + }); + + test("passes a head that edits its quest, borrowing a checkout's objects", async () => { + const tree = repo("quest/m0/epic/one"); + tree.append("quest/m0/epic/one.md", "\n## Plan\n\nWhat remains.\n"); + commit(tree, "trim one"); + expect(await inspect(tree, "quest/m0/epic/one", tree.path)).toEqual([]); + }); + + test("reads the committed head, not a working tree", async () => { + const tree = repo("quest/m0/epic/one"); + commit(tree, "nothing"); + // An uncommitted edit in the remote's own checkout is not part of the head. + tree.append("quest/m0/epic/one.md", "\nMore.\n"); + expect(await inspect(tree, "quest/m0/epic/one")).toHaveLength(1); + }); + + test("reports a structural finding in the head's tree", async () => { + const tree = repo("fix/link"); + tree.append("quest/m0/epic/one.md", "\n## Related\n\n- [Gone](/quest/m0/gone.md) - missing\n"); + commit(tree, "dangling link"); + const findings = await inspect(tree, "fix/link"); + expect(findings.map((finding) => finding.path)).toEqual(["quest/m0/epic/one.md"]); + }); + + test("skips a finding the base already has", async () => { + const tree = Tree.committed(); + tree.append("quest/m0/epic/one.md", "\n## Related\n\n- [Gone](/quest/m0/gone.md) - missing\n"); + commit(tree, "dangling link on main"); + git(tree, "switch", "--quiet", "-c", "fix/other"); + tree.append("quest/m0/epic/two.md", "\n## Related\n\n- [Lost](/quest/m0/lost.md) - missing\n"); + commit(tree, "another dangling link"); + const findings = await inspect(tree, "fix/other"); + expect(findings.map((finding) => finding.path)).toEqual(["quest/m0/epic/two.md"]); + }); + + test("a head that removes every quest is a finding", async () => { + const tree = repo("fix/purge"); + git(tree, "rm", "--quiet", "-r", "quest"); + commit(tree, "purge"); + const findings = await inspect(tree, "fix/purge"); + expect(findings).toEqual([ + { path: "quest", line: null, message: expect.stringContaining("no quest documents") }, + ]); + }); + + test("a base without quests does not use them", async () => { + const path = initRepository(); + const tree = new Tree(path); + tree.write("README.md", "hi\n"); + commit(tree, "init"); + git(tree, "switch", "--quiet", "-c", "quest/m0/anything"); + tree.write("src.ts", "work\n"); + commit(tree, "work"); + expect(await inspect(tree, "quest/m0/anything")).toEqual([]); + }); + + test("fails on a head the remote does not have, and leaves no scratch repository", async () => { + const tree = repo("quest/m0/epic/one"); + const before = readdirSync(tmpdir()).filter((name) => name.startsWith("quest-merge-")).length; + const check = landingCheck(tempDir())({ + remote: tree.path, + base: "main", + branch: "quest/m0/epic/one", + sha: "c".repeat(40), + token: "token", + }); + await expect(check).rejects.toThrow("git fetch failed"); + expect(readdirSync(tmpdir()).filter((name) => name.startsWith("quest-merge-")).length).toBe(before); + }); +}); diff --git a/test/status.test.ts b/test/status.test.ts index 51da6e172..586be66f9 100644 --- a/test/status.test.ts +++ b/test/status.test.ts @@ -35,6 +35,7 @@ function pull( body: "Summary.", updatedAt: "2026-10-07T12:00:00Z", baseRefName: "main", + headRefName: "quest/m0/example", isMergeQueueEnabled: false, labels: { nodes: [] }, state: "OPEN", From b6aeb105cac172aa51b3e6af5d01865046908b05 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 17:13:30 -0800 Subject: [PATCH 3/5] fix(merge): fetch the landing check into the checkout's repository Fetch under unique refs it then deletes, so Git negotiates and sends only what the checkout lacks; a shallow or absent checkout uses a scratch bare repository. Count base findings as a multiset, check a head that adopts quests, honor the user's Git network configuration, and keep scratch paths and refs out of refusals. Co-Authored-By: Claude Opus 5.5 --- src/cli/landed.ts | 112 ++++++++++++++++++++++++++++---------------- test/landed.test.ts | 42 +++++++++++++++++ 2 files changed, 114 insertions(+), 40 deletions(-) diff --git a/src/cli/landed.ts b/src/cli/landed.ts index 724a34e82..b24a31a88 100644 --- a/src/cli/landed.ts +++ b/src/cli/landed.ts @@ -4,13 +4,13 @@ // lives here rather than in the core. import { spawnSync } from "node:child_process"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { randomUUID } from "node:crypto"; +import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { type Finding, branchQuest, check } from "../core"; import { discoveryEnv } from "./git"; -import { gitEnvironment } from "./land"; import { snapshot } from "./tree"; /** @@ -22,9 +22,12 @@ import { snapshot } from "./tree"; */ export function landed(root: string, base: string, options: { branch?: string; head?: string } = {}): Finding[] { const name = options.branch ?? currentBranch(root); - const mergeBase = git(root, ["merge-base", base, options.head ?? "HEAD"]); + const head = options.head ?? "HEAD"; + const mergeBase = git(root, ["merge-base", base, head]); if (mergeBase.status !== 0) { - throw new Error(`no merge base between ${base} and HEAD: ${mergeBase.stderr.trim() || "unrelated histories"}`); + throw new Error( + `no merge base between ${base} and ${head}: ${mergeBase.stderr.trim() || "unrelated histories"}`, + ); } const commit = mergeBase.stdout.trim(); // Without a head, the pathspec and `:./path` are relative to the root, @@ -64,58 +67,87 @@ export type LandingCheck = (head: LandingHead) => Promise; /** * What `quest check --no-stubs --base --branch ` reports on `head.sha`, against a * freshly fetched base. The head is untrusted, so nothing from it runs or is checked out: the - * check reads git objects in a temporary bare repository that borrows the objects of the - * checkout at `root`, if any, and fetches only what it lacks. A base without quests is a - * repository that does not use them, so it has no findings, and a finding the base already - * has is not the head's, as the land daemon screens a head. + * check reads git objects. It fetches into the repository of the checkout at `root`, under refs of + * its own that it then deletes, so Git sends only what that repository lacks; with no checkout, or + * a shallow one whose history could hide the merge base, it uses a temporary bare repository. + * A finding the base already has is not the head's, as the land daemon screens a head, and a + * repository with no quests on either side does not use them. */ export function landingCheck(root: string): LandingCheck { return async (head) => { - const dir = mkdtempSync(join(tmpdir(), "quest-merge-")); + const local = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir", "--is-shallow-repository"]); + const [common, shallow] = local.stdout.trim().split("\n"); + const borrowed = local.status === 0 && shallow === "false"; + const dir = borrowed ? common : mkdtempSync(join(tmpdir(), "quest-merge-")); + const namespace = `refs/quest-merge/${randomUUID()}`; + const base = `${namespace}/base`; + const tip = `${namespace}/head`; + const run = (args: string[], env: Record = {}) => { + const result = spawnSync("git", ["-c", "core.hooksPath=/dev/null", "-C", dir, ...args], { + encoding: "utf8", + env: { ...discoveryEnv(), GIT_TERMINAL_PROMPT: "0", ...env }, + maxBuffer: 1 << 30, + }); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`git ${args[0]} failed: ${result.stderr.trim()}`); + return result.stdout.trim(); + }; + // Findings and errors name the scratch refs and directory, which the refusal need not show. + const tidy = (finding: Finding): Finding => ({ + ...finding, + message: finding.message + .replaceAll(`${dir}/`, "") + .replaceAll(base, `origin/${head.base}`) + .replaceAll(tip, head.sha), + }); try { - const run = (args: string[], env: Record = {}) => { - const result = spawnSync("git", ["-c", "core.hooksPath=/dev/null", "-C", dir, ...args], { - encoding: "utf8", - env: { ...gitEnvironment(), ...env }, - maxBuffer: 1 << 30, - }); - if (result.error) throw result.error; - if (result.status !== 0) throw new Error(`git ${args[0]} failed: ${result.stderr.trim()}`); - return result.stdout.trim(); - }; - run(["init", "--quiet", "--bare"]); - const local = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]); - if (local.status === 0) - writeFileSync(join(dir, "objects/info/alternates"), `${local.stdout.trim()}/objects\n`); - // The token rides in the environment, never in arguments other processes can read. + if (!borrowed) run(["init", "--quiet", "--bare"]); + // The token rides in the environment, after any configuration the user's environment already passes. + const count = Number(process.env.GIT_CONFIG_COUNT ?? 0) || 0; const basic = Buffer.from(`x-access-token:${head.token}`).toString("base64"); run( [ "fetch", "--quiet", "--no-tags", + "--no-write-fetch-head", head.remote, - `+refs/heads/${head.base}:refs/remotes/origin/${head.base}`, - `+${head.sha}:refs/quest/head`, + `+refs/heads/${head.base}:${base}`, + `+${head.sha}:${tip}`, ], { - GIT_CONFIG_COUNT: "1", - GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader", - GIT_CONFIG_VALUE_0: `Authorization: basic ${basic}`, + GIT_CONFIG_COUNT: String(count + 1), + [`GIT_CONFIG_KEY_${count}`]: "http.https://github.com/.extraheader", + [`GIT_CONFIG_VALUE_${count}`]: `Authorization: basic ${basic}`, }, ); - if (run(["ls-tree", "--name-only", `origin/${head.base}`, "quest"]) === "") return []; - const known = treeCheck(dir, `origin/${head.base}`); - // A finding the base already has is not this PR's, such as one a `quest` older than the tree's format reports. - const findings = treeCheck(dir, "refs/quest/head").filter( - (finding) => !known.some((old) => old.path === finding.path && old.message === finding.message), - ); - return [ - ...findings, - ...landed(dir, `origin/${head.base}`, { branch: head.branch, head: "refs/quest/head" }), - ]; + const quests = (ref: string) => run(["ls-tree", "--name-only", ref, "quest"]) !== ""; + const based = quests(base); + if (!based && !quests(tip)) return []; + // A finding the base already has is not this PR's, such as one a `quest` older than the tree's + // format reports; one more of the same in the head is. + const known = based ? treeCheck(dir, base) : []; + const findings = treeCheck(dir, tip).filter((finding) => { + const index = known.findIndex((old) => old.path === finding.path && old.message === finding.message); + if (index === -1) return true; + known.splice(index, 1); + return false; + }); + let accurate: Finding[]; + try { + accurate = landed(dir, base, { branch: head.branch, head: tip }); + } catch (error) { + throw new Error( + tidy({ path: "", line: null, message: String(error instanceof Error ? error.message : error) }) + .message, + ); + } + return [...findings, ...accurate].map(tidy); } finally { - rmSync(dir, { recursive: true, force: true }); + if (borrowed) { + for (const ref of [base, tip]) + spawnSync("git", ["-C", dir, "update-ref", "-d", ref], { env: discoveryEnv() }); + } else rmSync(dir, { recursive: true, force: true }); } }; } diff --git a/test/landed.test.ts b/test/landed.test.ts index 0ef64c629..530fcf816 100644 --- a/test/landed.test.ts +++ b/test/landed.test.ts @@ -176,6 +176,48 @@ describe("quest merge's landing check", () => { expect(findings.map((finding) => finding.path)).toEqual(["quest/m0/epic/two.md"]); }); + test("reports one more of a finding the base already has", async () => { + const tree = Tree.committed(); + tree.append("quest/m0/epic/one.md", "\n## Related\n\n- [Gone](/quest/m0/gone.md) - missing\n"); + commit(tree, "dangling link on main"); + git(tree, "switch", "--quiet", "-c", "fix/again"); + tree.append("quest/m0/epic/one.md", "- [Gone again](/quest/m0/gone.md) - missing\n"); + commit(tree, "the same dangling link"); + expect((await inspect(tree, "fix/again")).map((finding) => finding.path)).toEqual(["quest/m0/epic/one.md"]); + }); + + test("fetches into a checkout's repository, leaving none of its refs behind", async () => { + const tree = repo("quest/m0/epic/one"); + tree.write("src.ts", "work\n"); + commit(tree, "work"); + const local = Tree.committed(); + expect(await inspect(tree, "quest/m0/epic/one", local.path)).toHaveLength(1); + expect(git(local, "for-each-ref", "refs/quest-merge")).toBe(""); + // The head's objects arrived in the checkout's repository. + git(local, "cat-file", "-e", git(tree, "rev-parse", "quest/m0/epic/one").trim()); + }); + + test("does not borrow a shallow checkout's history", async () => { + const tree = repo("quest/m0/epic/one"); + tree.append("quest/m0/epic/one.md", "\nMore.\n"); + commit(tree, "edit"); + const shallow = tempDir(); + execFileSync("git", ["clone", "--quiet", "--depth=1", `file://${tree.path}`, shallow], { stdio: "ignore" }); + expect(await inspect(tree, "quest/m0/epic/one", shallow)).toEqual([]); + expect(git(new Tree(shallow), "for-each-ref", "refs/quest-merge")).toBe(""); + }); + + test("a head that adopts quests is checked", async () => { + const tree = new Tree(initRepository()); + tree.write("README.md", "hi\n"); + commit(tree, "init"); + git(tree, "switch", "--quiet", "-c", "adopt"); + Tree.baseline().copy(tree.path); + tree.append("quest/m0/epic/one.md", "\n## Related\n\n- [Gone](/quest/m0/gone.md) - missing\n"); + commit(tree, "adopt quests"); + expect((await inspect(tree, "adopt")).map((finding) => finding.path)).toEqual(["quest/m0/epic/one.md"]); + }); + test("a head that removes every quest is a finding", async () => { const tree = repo("fix/purge"); git(tree, "rm", "--quiet", "-r", "quest"); From 57a5098e8fd7f33ec2d1cf1a250bf251ab680fe1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 17:24:44 -0800 Subject: [PATCH 4/5] fix(merge): fetch the landing check's commits by SHA, writing no ref Fetch the base and head SHAs as objects alone, so an interrupted run leaves nothing in the checkout's repository, and use a scratch repository for a checkout this process cannot write. Co-Authored-By: Claude Opus 5.5 --- src/cli/hold.ts | 6 ++++- src/cli/landed.ts | 61 ++++++++++++++++++++------------------------- test/hold.test.ts | 1 + test/landed.test.ts | 28 +++++++++++++++++---- test/status.test.ts | 1 + 5 files changed, 57 insertions(+), 40 deletions(-) diff --git a/src/cli/hold.ts b/src/cli/hold.ts index 1670222f3..2e9e39e05 100644 --- a/src/cli/hold.ts +++ b/src/cli/hold.ts @@ -29,7 +29,7 @@ export type Method = "merge" | "squash" | "rebase"; const READ = `query HoldOwnership($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { - id url state isDraft body updatedAt baseRefName headRefName headRefOid mergeStateStatus isMergeQueueEnabled isInMergeQueue + id url state isDraft body updatedAt baseRefName baseRefOid headRefName headRefOid mergeStateStatus isMergeQueueEnabled isInMergeQueue labels(first: 100) { nodes { name } } timelineItems(last: 100, itemTypes: [LABELED_EVENT]) { nodes { __typename ... on LabeledEvent { id createdAt label { name } } } @@ -53,6 +53,8 @@ interface Snapshot { body: string; updatedAt: string; base: string; + /** The commit the base branch points at. */ + baseSha: string; /** The head branch's name. */ branch: string; head: string; @@ -254,6 +256,7 @@ export async function land(pr: PullRequest, request: LandRequest, deps: GitHubDe const findings = await request.check({ remote: `https://github.com/${pr.owner}/${pr.repo}.git`, base: snapshot.base, + baseSha: snapshot.baseSha, branch: snapshot.branch, sha, token: deps.token, @@ -539,6 +542,7 @@ class Labels { body: typeof row.body === "string" ? row.body : "", updatedAt: string(row.updatedAt), base: string(row.baseRefName), + baseSha: string(row.baseRefOid), branch: string(row.headRefName), head: string(row.headRefOid), mergeState: string(row.mergeStateStatus), diff --git a/src/cli/landed.ts b/src/cli/landed.ts index b24a31a88..8e9659bdb 100644 --- a/src/cli/landed.ts +++ b/src/cli/landed.ts @@ -4,8 +4,7 @@ // lives here rather than in the core. import { spawnSync } from "node:child_process"; -import { randomUUID } from "node:crypto"; -import { mkdtempSync, rmSync } from "node:fs"; +import { accessSync, constants, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -55,7 +54,9 @@ export function landed(root: string, base: string, options: { branch?: string; h export interface LandingHead { /** The base repository's Git URL, which serves the head's commits even from a fork. */ remote: string; + /** The base branch's name, and the commit it points at. */ base: string; + baseSha: string; branch: string; sha: string; token: string; @@ -67,9 +68,10 @@ export type LandingCheck = (head: LandingHead) => Promise; /** * What `quest check --no-stubs --base --branch ` reports on `head.sha`, against a * freshly fetched base. The head is untrusted, so nothing from it runs or is checked out: the - * check reads git objects. It fetches into the repository of the checkout at `root`, under refs of - * its own that it then deletes, so Git sends only what that repository lacks; with no checkout, or - * a shallow one whose history could hide the merge base, it uses a temporary bare repository. + * check reads git objects. It fetches both commits by SHA into the repository of the checkout at + * `root`, writing no ref, so Git sends only what that repository lacks and an interrupted run leaves + * nothing behind. A checkout it cannot write, or a shallow one whose history could hide the merge + * base, gives way to a temporary bare repository, as does no checkout. * A finding the base already has is not the head's, as the land daemon screens a head, and a * repository with no quests on either side does not use them. */ @@ -77,11 +79,9 @@ export function landingCheck(root: string): LandingCheck { return async (head) => { const local = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir", "--is-shallow-repository"]); const [common, shallow] = local.stdout.trim().split("\n"); - const borrowed = local.status === 0 && shallow === "false"; + const borrowed = local.status === 0 && shallow === "false" && writable(common); const dir = borrowed ? common : mkdtempSync(join(tmpdir(), "quest-merge-")); - const namespace = `refs/quest-merge/${randomUUID()}`; - const base = `${namespace}/base`; - const tip = `${namespace}/head`; + const { baseSha: base, sha: tip } = head; const run = (args: string[], env: Record = {}) => { const result = spawnSync("git", ["-c", "core.hooksPath=/dev/null", "-C", dir, ...args], { encoding: "utf8", @@ -92,35 +92,21 @@ export function landingCheck(root: string): LandingCheck { if (result.status !== 0) throw new Error(`git ${args[0]} failed: ${result.stderr.trim()}`); return result.stdout.trim(); }; - // Findings and errors name the scratch refs and directory, which the refusal need not show. + // Findings and errors name the scratch directory and the base's SHA, which the refusal need not show. const tidy = (finding: Finding): Finding => ({ ...finding, - message: finding.message - .replaceAll(`${dir}/`, "") - .replaceAll(base, `origin/${head.base}`) - .replaceAll(tip, head.sha), + message: finding.message.replaceAll(`${dir}/`, "").replaceAll(base, `origin/${head.base}`), }); try { if (!borrowed) run(["init", "--quiet", "--bare"]); // The token rides in the environment, after any configuration the user's environment already passes. const count = Number(process.env.GIT_CONFIG_COUNT ?? 0) || 0; const basic = Buffer.from(`x-access-token:${head.token}`).toString("base64"); - run( - [ - "fetch", - "--quiet", - "--no-tags", - "--no-write-fetch-head", - head.remote, - `+refs/heads/${head.base}:${base}`, - `+${head.sha}:${tip}`, - ], - { - GIT_CONFIG_COUNT: String(count + 1), - [`GIT_CONFIG_KEY_${count}`]: "http.https://github.com/.extraheader", - [`GIT_CONFIG_VALUE_${count}`]: `Authorization: basic ${basic}`, - }, - ); + run(["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", head.remote, base, tip], { + GIT_CONFIG_COUNT: String(count + 1), + [`GIT_CONFIG_KEY_${count}`]: "http.https://github.com/.extraheader", + [`GIT_CONFIG_VALUE_${count}`]: `Authorization: basic ${basic}`, + }); const quests = (ref: string) => run(["ls-tree", "--name-only", ref, "quest"]) !== ""; const based = quests(base); if (!based && !quests(tip)) return []; @@ -144,14 +130,21 @@ export function landingCheck(root: string): LandingCheck { } return [...findings, ...accurate].map(tidy); } finally { - if (borrowed) { - for (const ref of [base, tip]) - spawnSync("git", ["-C", dir, "update-ref", "-d", ref], { env: discoveryEnv() }); - } else rmSync(dir, { recursive: true, force: true }); + if (!borrowed) rmSync(dir, { recursive: true, force: true }); } }; } +/** Whether this process may write the objects of the Git directory `dir`. */ +function writable(dir: string): boolean { + try { + accessSync(join(dir, "objects"), constants.W_OK); + return true; + } catch { + return false; + } +} + /** `quest check`'s findings on `commit`; a tree it cannot read, such as one with no quests left, is one. */ function treeCheck(dir: string, commit: string): Finding[] { try { diff --git a/test/hold.test.ts b/test/hold.test.ts index 1e1099a2d..e240cc964 100644 --- a/test/hold.test.ts +++ b/test/hold.test.ts @@ -190,6 +190,7 @@ class FakePull { body: this.body, updatedAt: new Date(this.clock).toISOString(), baseRefName: this.baseRef, + baseRefOid: this.base, headRefName: "quest/m0/example", headRefOid: this.head, mergeStateStatus: this.mergeState, diff --git a/test/landed.test.ts b/test/landed.test.ts index 530fcf816..75feae723 100644 --- a/test/landed.test.ts +++ b/test/landed.test.ts @@ -2,8 +2,9 @@ import { execFileSync } from "node:child_process"; -import { readdirSync } from "node:fs"; +import { chmodSync, readdirSync } from "node:fs"; import { tmpdir } from "node:os"; +import { join } from "node:path"; import { describe, expect, test } from "vitest"; @@ -129,7 +130,8 @@ describe("quest merge's landing check", () => { /** Check `branch`'s tip in `tree` as `quest merge` would, fetching from `tree` into `root`. */ function inspect(tree: Tree, branch: string, root = tempDir()) { const sha = git(tree, "rev-parse", branch).trim(); - return landingCheck(root)({ remote: tree.path, base: "main", branch, sha, token: "token" }); + const baseSha = git(tree, "rev-parse", "main").trim(); + return landingCheck(root)({ remote: tree.path, base: "main", baseSha, branch, sha, token: "token" }); } test("finds a head that leaves its quest untouched, against the fetched base", async () => { @@ -186,13 +188,14 @@ describe("quest merge's landing check", () => { expect((await inspect(tree, "fix/again")).map((finding) => finding.path)).toEqual(["quest/m0/epic/one.md"]); }); - test("fetches into a checkout's repository, leaving none of its refs behind", async () => { + test("fetches into a checkout's repository, writing none of its refs", async () => { const tree = repo("quest/m0/epic/one"); tree.write("src.ts", "work\n"); commit(tree, "work"); const local = Tree.committed(); + const refs = git(local, "for-each-ref"); expect(await inspect(tree, "quest/m0/epic/one", local.path)).toHaveLength(1); - expect(git(local, "for-each-ref", "refs/quest-merge")).toBe(""); + expect(git(local, "for-each-ref")).toBe(refs); // The head's objects arrived in the checkout's repository. git(local, "cat-file", "-e", git(tree, "rev-parse", "quest/m0/epic/one").trim()); }); @@ -204,7 +207,21 @@ describe("quest merge's landing check", () => { const shallow = tempDir(); execFileSync("git", ["clone", "--quiet", "--depth=1", `file://${tree.path}`, shallow], { stdio: "ignore" }); expect(await inspect(tree, "quest/m0/epic/one", shallow)).toEqual([]); - expect(git(new Tree(shallow), "for-each-ref", "refs/quest-merge")).toBe(""); + // It fetched nothing into the shallow checkout. + expect(() => git(new Tree(shallow), "cat-file", "-e", git(tree, "rev-parse", "main").trim())).toThrow(); + }); + + test("does not write to a checkout it cannot write", async () => { + const tree = repo("quest/m0/epic/one"); + tree.append("quest/m0/epic/one.md", "\nMore.\n"); + commit(tree, "edit"); + const local = Tree.committed(); + chmodSync(join(local.path, ".git/objects"), 0o555); + try { + expect(await inspect(tree, "quest/m0/epic/one", local.path)).toEqual([]); + } finally { + chmodSync(join(local.path, ".git/objects"), 0o755); + } }); test("a head that adopts quests is checked", async () => { @@ -245,6 +262,7 @@ describe("quest merge's landing check", () => { const check = landingCheck(tempDir())({ remote: tree.path, base: "main", + baseSha: git(tree, "rev-parse", "main").trim(), branch: "quest/m0/epic/one", sha: "c".repeat(40), token: "token", diff --git a/test/status.test.ts b/test/status.test.ts index 586be66f9..7cec81179 100644 --- a/test/status.test.ts +++ b/test/status.test.ts @@ -35,6 +35,7 @@ function pull( body: "Summary.", updatedAt: "2026-10-07T12:00:00Z", baseRefName: "main", + baseRefOid: "b".repeat(40), headRefName: "quest/m0/example", isMergeQueueEnabled: false, labels: { nodes: [] }, From 4b7afac5230de1b612528da1d8fc696e6a09d192 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 17:34:01 -0800 Subject: [PATCH 5/5] quest: reset the checkout's extraheader before the borrowed fetch's token Co-Authored-By: Claude Opus 5.5 --- src/cli/landed.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cli/landed.ts b/src/cli/landed.ts index 8e9659bdb..200f3a887 100644 --- a/src/cli/landed.ts +++ b/src/cli/landed.ts @@ -103,9 +103,12 @@ export function landingCheck(root: string): LandingCheck { const count = Number(process.env.GIT_CONFIG_COUNT ?? 0) || 0; const basic = Buffer.from(`x-access-token:${head.token}`).toString("base64"); run(["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", head.remote, base, tip], { - GIT_CONFIG_COUNT: String(count + 1), + GIT_CONFIG_COUNT: String(count + 2), + // An empty value drops any header the checkout already sends, such as actions/checkout's, which GitHub would reject as a duplicate. [`GIT_CONFIG_KEY_${count}`]: "http.https://github.com/.extraheader", - [`GIT_CONFIG_VALUE_${count}`]: `Authorization: basic ${basic}`, + [`GIT_CONFIG_VALUE_${count}`]: "", + [`GIT_CONFIG_KEY_${count + 1}`]: "http.https://github.com/.extraheader", + [`GIT_CONFIG_VALUE_${count + 1}`]: `Authorization: basic ${basic}`, }); const quests = (ref: string) => run(["ls-tree", "--name-only", ref, "quest"]) !== ""; const based = quests(base);