Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

fix(app): review merged PRs via the head ref, diffed against the merge base (#279)

anirudhkumar-nanonets08ff9f77b501
diff --git a/docs/github-app.md b/docs/github-app.md
index 7dce891d..b4f78e9d 100644
--- a/docs/github-app.md
+++ b/docs/github-app.md
@@ -15,7 +15,10 @@ instead of a workflow file per repo.
1. Verifies the webhook signature, queues the job, answers `202` — GitHub gives
up on a delivery after ten seconds and a review takes longer.
-2. Fetches `refs/pull/<n>/merge` and the base branch, shallow.
+2. Fetches `refs/pull/<n>/merge` and the base branch, shallow — falling back to
+ `refs/pull/<n>/head` for a closed or merged pull request, whose merge ref
+ GitHub has deleted. The head ref is then diffed against the base branch as it
+ stood at the merge, so the radius is still the pull request's own change.
3. Builds the structural graph, computes the radius, renders the comment.
4. Stores the viewer page and links it with a signed URL.
5. Edits its existing comment rather than adding one per push.
diff --git a/src/app/checkout.ts b/src/app/checkout.ts
index 33cbcee0..f5c40a30 100644
--- a/src/app/checkout.ts
+++ b/src/app/checkout.ts
@@ -22,6 +22,16 @@ import { join } from "node:path";
/** Enough history for a merge base against the pull request's base branch. */
const FETCH_DEPTH = 50;
+/**
+ * One extra reach back, used only on the `/head` fallback below.
+ *
+ * An open PR's base tip is a commit or two from the merge base, so 50 is plenty.
+ * A pull request being re-reviewed weeks after it merged is the opposite case:
+ * the base branch has moved on by however many commits the repo lands in that
+ * time, and the commit the branch was actually merged on top of sits behind all
+ * of them. Deepening once is cheaper than raising `FETCH_DEPTH` for every review.
+ */
+const DEEPEN_DEPTH = 500;
const GIT_TIMEOUT_MS = 120_000;
export interface CheckoutRequest {
@@ -31,20 +41,28 @@ export interface CheckoutRequest {
baseRef: string;
token: string;
api?: string;
+ /** Where to say which of GitHub's two PR refs the review is actually using —
+ * the App's own log callback, so the two cases are told apart in the container
+ * logs rather than guessed at from the comment. */
+ log?: (msg: string) => void;
}
export interface Checkout {
- /** Working tree at the pull request's merge commit. */
+ /** Working tree at the pull request's merge commit, or at its head commit when
+ * the merge ref is gone (see {@link ref}). */
dir: string;
/** What `blast --base` should diff against. */
base: string;
+ /** Which ref the tree came from. `merge` is the normal case; `head` means the
+ * pull request is closed and GitHub has deleted its merge preview. */
+ ref: "merge" | "head";
/** Removes the tree. Always call it — the token's clone is not something to
* leave in /tmp. */
cleanup: () => void;
}
/** A git invocation with the dangerous parts of the environment removed. */
-function git(dir: string, args: string[], token?: string): { ok: boolean; err: string } {
+function git(dir: string, args: string[], token?: string): { ok: boolean; out: string; err: string } {
const auth = token
? [
"-c",
@@ -72,52 +90,166 @@ function git(dir: string, args: string[], token?: string): { ok: boolean; err: s
},
},
);
- return { ok: res.status === 0, err: `${res.stderr ?? ""}${res.error ? ` ${res.error.message}` : ""}`.trim() };
+ return {
+ ok: res.status === 0,
+ out: res.stdout ?? "",
+ err: `${res.stderr ?? ""}${res.error ? ` ${res.error.message}` : ""}`.trim(),
+ };
}
+/** First line of a git command's output, or null when it said nothing useful. */
+function line(dir: string, args: string[]): string | null {
+ const { ok, out } = git(dir, args);
+ const first = out.split("\n")[0]?.trim() ?? "";
+ return ok && first !== "" ? first : null;
+}
+
+const short = (sha: string): string => sha.slice(0, 7);
+
/**
- * Fetch the PR's merge ref and its base, shallow.
+ * Fetch the PR's code and its base, shallow, and land on it.
*
* `refs/pull/N/merge` is GitHub's own merge of the PR into its base — the same
* thing the checks see, and the right thing to review: it is what will land, not
- * what the contributor's branch says in isolation.
+ * what the contributor's branch says in isolation. It is preferred whenever it
+ * exists.
+ *
+ * But GitHub DELETES that ref the moment a pull request is closed or merged: it
+ * is only a preview of a merge, and there is nothing left to preview afterwards.
+ * Re-reviewing any merged PR therefore died at the fetch with `couldn't find
+ * remote ref refs/pull/N/merge` — 16 in a row on one installation — which is why
+ * `refs/pull/N/head` (the branch tip as the author pushed it, kept indefinitely
+ * in the BASE repository, so it survives even the fork being deleted) is fetched
+ * as a fallback. What changes with it is the diff basis, which
+ * {@link headDiffBase} is entirely about.
*/
export function checkoutPullRequest(req: CheckoutRequest): Checkout {
const host = (req.api ?? "https://github.com").replace(/\/$/, "");
const dir = mkdtempSync(join(tmpdir(), `graft-app-${req.owner}-${req.repo}-`));
const cleanup = (): void => rmSync(dir, { recursive: true, force: true });
+ const log = req.log ?? ((): void => {});
+ const tag = `${req.owner}/${req.repo}#${req.number}`;
+ const fail = (step: string, err: string): never => {
+ cleanup();
+ // A merge ref is absent while GitHub is still computing mergeability, and
+ // present-but-stale right after a push — worth saying which step failed so
+ // that case is distinguishable from a permissions problem.
+ throw new Error(`checkout ${tag} failed at ${step}: ${redact(err, req.token)}`);
+ };
- const steps: Array<[string, string[]]> = [
+ const setup: Array<[string, string[]]> = [
["init", ["init", "--quiet", "-b", "__graft_base"]],
["remote", ["remote", "add", "origin", `${host}/${req.owner}/${req.repo}.git`]],
- // Both refs in one fetch: the merge ref to review, the base to diff against.
- [
- "fetch",
- [
- "fetch",
- "--quiet",
- `--depth=${FETCH_DEPTH}`,
- "--no-recurse-submodules",
- "origin",
- `+refs/pull/${req.number}/merge:refs/graft/merge`,
- `+refs/heads/${req.baseRef}:refs/graft/base`,
- ],
- ],
- ["checkout", ["checkout", "--quiet", "--detach", "refs/graft/merge"]],
];
+ for (const [name, args] of setup) {
+ const { ok, err } = git(dir, args);
+ if (!ok) fail(name, err);
+ }
- for (const [name, args] of steps) {
- const { ok, err } = git(dir, args, name === "fetch" ? req.token : undefined);
- if (!ok) {
- cleanup();
- // A merge ref is absent while GitHub is still computing mergeability, and
- // present-but-stale right after a push — worth saying which step failed so
- // that case is distinguishable from a permissions problem.
- throw new Error(`checkout ${req.owner}/${req.repo}#${req.number} failed at ${name}: ${redact(err, req.token)}`);
+ // Both refs in one fetch: the ref to review, the base to diff against.
+ const merge = git(dir, fetchArgs(req, "merge"), req.token);
+ const ref: Checkout["ref"] = merge.ok ? "merge" : "head";
+ if (!merge.ok) {
+ const head = git(dir, fetchArgs(req, "head"), req.token);
+ // Neither ref: a base branch that has since been deleted, an installation
+ // that lost access, a repository that is gone. Both errors go out, because a
+ // bare "couldn't find refs/pull/N/merge" now means only "this PR is closed"
+ // and says nothing about why the fallback did not save it either.
+ if (!head.ok) {
+ fail("fetch", `${merge.err} | falling back to refs/pull/${req.number}/head: ${head.err}`);
}
}
- return { dir, base: "refs/graft/base", cleanup };
+ const co = git(dir, ["checkout", "--quiet", "--detach", `refs/graft/${ref}`]);
+ if (!co.ok) fail("checkout", co.err);
+
+ if (ref === "merge") {
+ log(`${tag}: reviewing refs/pull/${req.number}/merge against ${req.baseRef}`);
+ return { dir, base: "refs/graft/base", ref, cleanup };
+ }
+
+ const against = headDiffBase(dir, req);
+ if (against === null) {
+ fail(
+ "diff base",
+ `refs/pull/${req.number}/merge is gone and refs/pull/${req.number}/head gives no diff against ` +
+ `${req.baseRef}: within ${FETCH_DEPTH + DEEPEN_DEPTH} commits they share no history, or the branch ` +
+ `is already in ${req.baseRef} with no merge commit to diff against (a fast-forward merge)`,
+ );
+ }
+ // Not "the PR is closed": that is only the usual reason the merge ref is
+ // missing, and stating it as fact would send an operator chasing the wrong
+ // thing when the fetch failed for some other reason.
+ log(`${tag}: no refs/pull/${req.number}/merge (GitHub deletes it when a pull request closes), reviewing refs/pull/${req.number}/head against ${against}`);
+ return { dir, base: "refs/graft/base", ref, cleanup };
+}
+
+/** The one fetch each attempt makes: the PR ref to review plus the base branch. */
+function fetchArgs(req: CheckoutRequest, pull: "merge" | "head", deepen = false): string[] {
+ return [
+ "fetch",
+ "--quiet",
+ deepen ? `--deepen=${DEEPEN_DEPTH}` : `--depth=${FETCH_DEPTH}`,
+ "--no-recurse-submodules",
+ "origin",
+ `+refs/pull/${req.number}/${pull}:refs/graft/${pull}`,
+ `+refs/heads/${req.baseRef}:refs/graft/base`,
+ ];
+}
+
+/**
+ * Point `refs/graft/base` at the commit the head ref should be diffed against,
+ * and describe it for the log — or null when this history cannot answer.
+ *
+ * The two refs do NOT give the same diff, and the difference is not a detail:
+ *
+ * - `/merge` is a commit whose parents are the base tip and the head, so
+ * `refs/graft/base...HEAD` resolves its merge base to the base tip and the
+ * diff is exactly the pull request.
+ * - `/head` is the author's branch tip. While the branch is *not* in the base
+ * branch's history — an open PR, a closed-unmerged one, and also a squash or
+ * rebase merge, which land new commits with new shas — the three-dot diff
+ * still resolves to the fork point and still reports exactly the author's
+ * changes (that is what three dots is for; see `rangeArgs` in blast/diff.ts).
+ * - After a MERGE COMMIT, though, the head commit is an ancestor of the base
+ * branch, so the merge base of the two IS the head commit and
+ * `refs/graft/base...HEAD` reports that nothing changed. An empty blast
+ * radius posted with total confidence is worse than the fetch error it
+ * replaced, so that case is detected and given the basis `/merge` would have
+ * had: the first parent of the merge commit that brought the branch in, which
+ * is the base branch as it stood at the merge.
+ */
+function headDiffBase(dir: string, req: CheckoutRequest): string | null {
+ for (const deepen of [false, true]) {
+ // The shallow window is measured from each tip, so a base branch that moved
+ // on since the merge can leave the shared history out of it entirely: git
+ // then has no merge base at all and `git diff a...b` fails outright. One
+ // deepening is the difference between reviewing a months-old PR and not.
+ if (deepen && !git(dir, fetchArgs(req, "head", true), req.token).ok) return null;
+ const against = resolveHeadBase(dir, req);
+ if (against !== null) return against;
+ }
+ return null;
+}
+
+function resolveHeadBase(dir: string, req: CheckoutRequest): string | null {
+ const head = line(dir, ["rev-parse", "refs/graft/head"]);
+ const shared = line(dir, ["merge-base", "refs/graft/base", "refs/graft/head"]);
+ if (head === null || shared === null) return null;
+ if (shared !== head) return `${req.baseRef} (merge base ${short(shared)})`;
+
+ // The head commit is in the base branch: find the merge that put it there. The
+ // EARLIEST merge on the ancestry path is the one — a later one is some other
+ // branch's merge that happens to sit above it.
+ const merge = line(dir, ["rev-list", "--reverse", "--ancestry-path", "--merges", "refs/graft/head..refs/graft/base"]);
+ if (merge === null) return null;
+ const parent = line(dir, ["rev-parse", `${merge}^1`]);
+ if (parent === null) return null;
+ // Only worth using if it is diffable: a shallow boundary can hold the merge
+ // commit while leaving the fork point below it out of the repository.
+ if (line(dir, ["merge-base", parent, "refs/graft/head"]) === null) return null;
+ if (!git(dir, ["update-ref", "refs/graft/base", parent]).ok) return null;
+ return `${req.baseRef} as it stood at the merge (${short(parent)})`;
}
/** Never let a token reach a log line, even inside git's own error text. */
diff --git a/src/app/review.ts b/src/app/review.ts
index 8ee15f57..b2998923 100644
--- a/src/app/review.ts
+++ b/src/app/review.ts
@@ -45,7 +45,10 @@ export interface ReviewResult {
export async function reviewPullRequest(job: ReviewJob, deps: ReviewDeps): Promise<ReviewResult> {
const log = deps.log ?? (() => {});
const token = await deps.token(job.installationId);
- const checkout = checkoutPullRequest({ owner: job.owner, repo: job.repo, number: job.number, baseRef: job.baseRef, token });
+ // `log` goes into the checkout because a closed pull request is reviewed from
+ // `refs/pull/N/head` against a different basis than an open one, and the only
+ // place that difference is visible afterwards is this line.
+ const checkout = checkoutPullRequest({ owner: job.owner, repo: job.repo, number: job.number, baseRef: job.baseRef, token, log });
try {
log(`${job.owner}/${job.repo}#${job.number}: building`);
diff --git a/test/app-checkout.test.ts b/test/app-checkout.test.ts
index 23f5a4f5..6b61ae7d 100644
--- a/test/app-checkout.test.ts
+++ b/test/app-checkout.test.ts
@@ -6,6 +6,14 @@
* actually land — and reviewing the head branch instead would report a radius
* for code that was never going to exist. A local bare repository stands in for
* GitHub here, so this exercises the real git commands with no network.
+ *
+ * The other half of these tests is the closed pull request, where GitHub has
+ * deleted `refs/pull/N/merge` and `refs/pull/N/head` is all that is left. What
+ * has to be checked there is not that the fetch succeeds — it is that the diff
+ * is still the pull request's own change, because the obvious implementation
+ * (diff the head against the base tip) reports NOTHING for a PR that merged as a
+ * merge commit, and an empty blast radius posted confidently is worse than the
+ * fetch error it replaced.
*/
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -16,15 +24,31 @@ import { join } from "node:path";
import { checkoutPullRequest, redact } from "../src/app/checkout.js";
const git = (cwd: string, ...args: string[]): string =>
- execFileSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@e", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@e" } });
+ // stderr piped, not inherited: `git merge --squash` chats about the strategy it
+ // chose even under `--quiet`, and it lands in the middle of the TAP stream. A
+ // failure still carries it, on the thrown error.
+ execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@e", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@e" } });
+
+/**
+ * How the pull request stands on the fake GitHub.
+ *
+ * `open` is the only one with a merge ref: GitHub deletes it on close, which is
+ * exactly what the other three reproduce. They differ in how the branch landed,
+ * because that is what decides the diff:
+ * - `merged`: a merge commit, so the head commit is an ancestor of `main`.
+ * - `squashed`: new commits on `main`, so the head commit is not.
+ * - `merged-far-behind`: a merge commit, then more commits on `main` than the
+ * shallow fetch reaches back — the months-old pull request.
+ */
+type PrState = "open" | "merged" | "squashed" | "merged-far-behind";
/**
- * A stand-in for GitHub: a mirror holding `main` and the merge ref.
+ * A stand-in for GitHub: a mirror holding `main` and the PR's refs.
*
- * `--mirror`, not `--bare`: a bare clone copies branches and tags, and the ref
- * that matters here lives under `refs/pull/`.
+ * `--mirror`, not `--bare`: a bare clone copies branches and tags, and the refs
+ * that matter here live under `refs/pull/`.
*/
-function fakeGitHub(): { root: string; repo: string } {
+function fakeGitHub(state: PrState = "open"): { root: string; repo: string } {
const root = mkdtempSync(join(tmpdir(), "graft-origin-"));
const work = join(root, "work");
execFileSync("git", ["init", "--quiet", "-b", "main", work]);
@@ -38,49 +62,179 @@ function fakeGitHub(): { root: string; repo: string } {
writeFileSync(join(work, "feature.txt"), "feature\n");
git(work, "add", "-A");
git(work, "commit", "--quiet", "-m", "feature");
-
- // GitHub publishes the merge commit under refs/pull/N/merge; reproduce it.
git(work, "checkout", "--quiet", "main");
- git(work, "merge", "--quiet", "--no-ff", "-m", "merge", "feature");
- git(work, "update-ref", "refs/pull/7/merge", "HEAD");
- git(work, "checkout", "--quiet", "main");
- git(work, "reset", "--hard", "--quiet", "HEAD~1");
+ // The head ref exists in every state, in the BASE repository — which is why it
+ // outlives both the branch and the whole fork.
+ git(work, "update-ref", "refs/pull/7/head", "refs/heads/feature");
+
+ if (state === "open") {
+ // GitHub publishes the merge commit under refs/pull/N/merge; reproduce it.
+ git(work, "merge", "--quiet", "--no-ff", "-m", "merge", "feature");
+ git(work, "update-ref", "refs/pull/7/merge", "HEAD");
+ git(work, "checkout", "--quiet", "main");
+ git(work, "reset", "--hard", "--quiet", "HEAD~1");
+ execFileSync("git", ["clone", "--quiet", "--mirror", work, join(root, "demo.git")]);
+ return { root, repo: "demo" };
+ }
+
+ // Everything below is a landed pull request: `main` had moved on before it
+ // landed, it landed, and `main` moved on again afterwards. No merge ref.
+ writeFileSync(join(work, "base.txt"), "base\nmore\n");
+ git(work, "add", "-A");
+ git(work, "commit", "--quiet", "-m", "other work");
+
+ if (state === "squashed") {
+ git(work, "merge", "--quiet", "--squash", "feature");
+ git(work, "commit", "--quiet", "-m", "squashed #7");
+ } else {
+ git(work, "merge", "--quiet", "--no-ff", "-m", "Merge pull request #7", "feature");
+ }
+
+ // Empty commits: the point is only how FAR the merge is behind the tip.
+ const after = state === "merged-far-behind" ? 55 : 1;
+ for (let i = 0; i < after; i += 1) git(work, "commit", "--quiet", "--allow-empty", "-m", `after ${i}`);
+
+ // The branch is deleted on merge, as GitHub offers to do.
+ git(work, "branch", "-D", "feature");
execFileSync("git", ["clone", "--quiet", "--mirror", work, join(root, "demo.git")]);
return { root, repo: "demo" };
}
-test("checkout: lands on the merge ref, with the base fetched to diff against", () => {
- const origin = fakeGitHub();
- // The remote is built as `${api}/${owner}/${repo}.git`, so `api` points at the
- // directory holding the mirror and `owner` is a no-op path segment.
- const checkout = checkoutPullRequest({
+/** The remote is built as `${api}/${owner}/${repo}.git`, so `api` points at the
+ * directory holding the mirror and `owner` is a no-op path segment. */
+function checkout(origin: { root: string; repo: string }, number = 7): { logs: string[]; c: ReturnType<typeof checkoutPullRequest> } {
+ const logs: string[] = [];
+ const c = checkoutPullRequest({
owner: ".",
repo: origin.repo,
- number: 7,
+ number,
baseRef: "main",
token: "ghs_secret_token",
api: `file://${origin.root}`,
+ log: (msg) => logs.push(msg),
});
+ return { logs, c };
+}
+
+/** What `changedFiles` will ask git, run the same way: three dots, not two. */
+const changed = (dir: string, base: string): string =>
+ execFileSync("git", ["diff", "--name-only", `${base}...HEAD`], { cwd: dir, encoding: "utf8" }).trim();
+
+test("checkout: lands on the merge ref, with the base fetched to diff against", () => {
+ const origin = fakeGitHub();
+ const { c, logs } = checkout(origin);
try {
// The merge ref carries BOTH sides; the base branch alone carries neither.
- assert.equal(readFileSync(join(checkout.dir, "feature.txt"), "utf8"), "feature\n");
- assert.equal(readFileSync(join(checkout.dir, "base.txt"), "utf8"), "base\n");
+ assert.equal(readFileSync(join(c.dir, "feature.txt"), "utf8"), "feature\n");
+ assert.equal(readFileSync(join(c.dir, "base.txt"), "utf8"), "base\n");
- const diff = execFileSync("git", ["diff", "--name-only", checkout.base, "HEAD"], { cwd: checkout.dir, encoding: "utf8" });
+ const diff = execFileSync("git", ["diff", "--name-only", c.base, "HEAD"], { cwd: c.dir, encoding: "utf8" });
assert.equal(diff.trim(), "feature.txt", "the base ref is present and diffs to the PR's change");
+ // The head ref exists too, and must not have been preferred over the merge.
+ assert.equal(c.ref, "merge");
+ assert.deepEqual(logs, ["./demo#7: reviewing refs/pull/7/merge against main"]);
+
// The token must not be recoverable from the checkout it produced.
- const config = readFileSync(join(checkout.dir, ".git", "config"), "utf8");
+ const config = readFileSync(join(c.dir, ".git", "config"), "utf8");
assert.ok(!config.includes("ghs_secret_token"), "no token in .git/config");
assert.ok(!config.includes(Buffer.from("x-access-token:ghs_secret_token").toString("base64")), "nor encoded");
} finally {
- checkout.cleanup();
+ c.cleanup();
}
rmSync(origin.root, { recursive: true, force: true });
});
+test("checkout: falls back to the head ref once GitHub has deleted the merge ref", () => {
+ const origin = fakeGitHub("merged");
+ const { c, logs } = checkout(origin);
+
+ try {
+ assert.equal(c.ref, "head");
+ // The head ref is the branch as the author pushed it: their file, and the
+ // base file WITHOUT the "other work" commit that landed beside them.
+ assert.equal(readFileSync(join(c.dir, "feature.txt"), "utf8"), "feature\n");
+ assert.equal(readFileSync(join(c.dir, "base.txt"), "utf8"), "base\n");
+ assert.equal(logs.length, 1);
+ assert.match(logs[0], /^\.\/demo#7: no refs\/pull\/7\/merge .*reviewing refs\/pull\/7\/head against main as it stood at the merge \([0-9a-f]{7}\)$/);
+ } finally {
+ c.cleanup();
+ }
+ rmSync(origin.root, { recursive: true, force: true });
+});
+
+test("checkout: a merged pull request still diffs to its own change, not an empty diff", () => {
+ const origin = fakeGitHub("merged");
+ const { c } = checkout(origin);
+
+ try {
+ // The head commit is an ancestor of `main` now, so `main...HEAD` would resolve
+ // its merge base to the head commit itself and report nothing at all. The
+ // basis has to be the base branch as it stood at the merge instead.
+ assert.equal(changed(c.dir, "refs/graft/base"), "feature.txt");
+ const tip = execFileSync("git", ["rev-parse", "refs/graft/head"], { cwd: c.dir, encoding: "utf8" }).trim();
+ const base = execFileSync("git", ["rev-parse", c.base], { cwd: c.dir, encoding: "utf8" }).trim();
+ assert.notEqual(base, tip, "the base must not have been left where the merge base lands");
+ assert.equal(changed(c.dir, tip), "", "sanity: diffing against the head commit is the empty diff being avoided");
+ } finally {
+ c.cleanup();
+ }
+ rmSync(origin.root, { recursive: true, force: true });
+});
+
+test("checkout: a squash-merged pull request diffs against the fork point", () => {
+ const origin = fakeGitHub("squashed");
+ const { c, logs } = checkout(origin);
+
+ try {
+ // A squash lands NEW commits, so the head commit is not in `main`'s history
+ // and the ordinary three-dot diff against the base tip is already right —
+ // no rewriting of the base, and the log says so.
+ assert.equal(c.ref, "head");
+ assert.equal(changed(c.dir, c.base), "feature.txt");
+ assert.match(logs[0], /reviewing refs\/pull\/7\/head against main \(merge base [0-9a-f]{7}\)/);
+ } finally {
+ c.cleanup();
+ }
+ rmSync(origin.root, { recursive: true, force: true });
+});
+
+test("checkout: deepens when the base branch has moved past the shallow window", () => {
+ const origin = fakeGitHub("merged-far-behind");
+ const { c } = checkout(origin);
+
+ try {
+ // 55 commits landed on `main` after the merge, so the shallow fetch reaches
+ // no shared commit at all: without the deepening, git has no merge base and
+ // `git diff base...HEAD` fails outright.
+ assert.equal(c.ref, "head");
+ assert.equal(changed(c.dir, c.base), "feature.txt");
+ } finally {
+ c.cleanup();
+ }
+ rmSync(origin.root, { recursive: true, force: true });
+});
+
+test("checkout: with neither ref fetchable, the error names both attempts", () => {
+ const origin = fakeGitHub();
+ try {
+ // Pull request 8 has no refs at all — the shape of a repository whose base
+ // branch is gone, or an installation that lost access.
+ checkout(origin, 8);
+ assert.fail("expected the fetch to fail");
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ assert.match(msg, /failed at fetch/);
+ assert.match(msg, /refs\/pull\/8\/merge/, "the merge ref that was tried first");
+ assert.match(msg, /falling back to refs\/pull\/8\/head/, "and that the fallback was tried too");
+ assert.ok(!msg.includes("ghs_secret_token"), "git's error text is redacted before it is thrown");
+ } finally {
+ rmSync(origin.root, { recursive: true, force: true });
+ }
+});
+
test("checkout: a failure names the step and never leaks the token", () => {
const parent = mkdtempSync(join(tmpdir(), "graft-empty-"));
try {