From 7e5ea17d6cb22b4c1b9268c083248dba6559fd99 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 17 Nov 2026 04:12:29 +0100 Subject: [PATCH] fix(server): match terminal pull requests by workspace commit ancestry Branch-name fallback attached historical closed requests to reused workspaces. Share containment between forge lookup and auto-archive so remote branch updates remain eligible without accepting unrelated requests. Fetch missing Git objects without consuming the batched GitHub API budget or moving refs. --- docs/forge-providers.md | 18 ++-- .../archive-if-safe.test.ts | 2 +- .../auto-archive-on-merge/archive-if-safe.ts | 22 ++--- .../auto-archive-on-merge/behavior.test.ts | 25 +++++- .../server/src/services/gitea-service.test.ts | 11 ++- packages/server/src/services/gitea-service.ts | 30 ++++--- .../src/services/github-service.test.ts | 85 +++++++++++++++++-- .../server/src/services/github-service.ts | 43 +++++++--- .../src/services/gitlab-service.test.ts | 11 ++- .../server/src/services/gitlab-service.ts | 25 ++++-- .../services/pull-request-contains-commit.ts | 44 ++++++++++ .../src/test-utils/pull-request-history.ts | 44 ++++++++++ 12 files changed, 294 insertions(+), 66 deletions(-) create mode 100644 packages/server/src/services/pull-request-contains-commit.ts create mode 100644 packages/server/src/test-utils/pull-request-history.ts diff --git a/docs/forge-providers.md b/docs/forge-providers.md index 62c91611f8..4039549db2 100644 --- a/docs/forge-providers.md +++ b/docs/forge-providers.md @@ -97,12 +97,18 @@ Register the adapter in `defaultForgeRegistry` with: - `matchesHost` from manifest `cloudHosts` - `probeHost` when self-hosted/Enterprise detection is supported -Current change-request lookup matches the branch and repository for both open and -terminal requests. Prefer an open request, then a terminal request at the local -HEAD, then the most recently updated terminal request. A reused branch can show -its previous request until a new one opens. Auto-archive separately requires an -observed open-to-merged transition and a fresh exact match between checkout HEAD -and the PR head, along with the existing workspace safety checks. +Current change-request lookup prefers an open request for the branch and repository. +Closed and merged requests belong to a checkout only when their head contains the +checkout commit. Display and auto-archive share this ancestry rule. This retains a +request after a server-side branch update while rejecting historical requests on +reused branch names. Auto-archive still requires an observed open-to-merged +transition and fresh workspace safety checks; being behind the remote alone does +not block archive when the merged request contains the checkout commit. + +Containment uses Git objects, fetching a missing PR head from origin without +moving refs or writing FETCH_HEAD. This keeps ancestry reads outside the GitHub +GraphQL budget. If history or remote access cannot establish containment, hide +the terminal request and leave the workspace active. Keep checkout HEAD in adapter cache and poll identities so checkout changes refresh the facts used by archive eligibility. diff --git a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.test.ts b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.test.ts index 6fd3484ca3..8aba573bfb 100644 --- a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.test.ts +++ b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.test.ts @@ -349,7 +349,7 @@ afterEach(() => { describe("archiveIfSafe", () => { test("denies archive when checkout facts do not establish safety", async () => { - for (const git of [{ headSha: undefined }, { behindOfOrigin: 1 }, { isDirty: null }]) { + for (const git of [{ headSha: undefined }, { isDirty: null }]) { const harness = createHarness({ snapshot: createSnapshot({ git }) }); await runArchiveIfSafe(harness); expect(harness.deps.archiveByScope).not.toHaveBeenCalled(); diff --git a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts index 7ea7604b3e..02a1c2140b 100644 --- a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts +++ b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts @@ -1,3 +1,4 @@ +import { pullRequestContainsCommit } from "../../services/pull-request-contains-commit.js"; import type { Logger } from "pino"; import type { AgentManager } from "../agent/agent-manager.js"; @@ -63,24 +64,25 @@ export async function archiveIfSafe(input: { const cwd = snapshot.cwd; const pullRequest = snapshot.forge.pullRequest; - if ( - !pullRequest?.isMerged || - !snapshot.git.headSha || - snapshot.git.headSha !== pullRequest.headSha || - snapshot.forge.error - ) { + if (!pullRequest?.isMerged || !snapshot.git.headSha || snapshot.forge.error) { return; } if (snapshot.git.isDirty !== false) { return; } - if ( - (snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) || - (snapshot.git.behindOfOrigin !== null && snapshot.git.behindOfOrigin !== 0) - ) { + if (snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) { return; } + if ( + !(await pullRequestContainsCommit({ + cwd, + workspaceCommit: snapshot.git.headSha, + pullRequestCommit: pullRequest.headSha, + })) + ) + return; + const ownership = await deps.isPaseoOwnedWorktreeCwd(cwd, { paseoHome: options.paseoHome, worktreesRoot: options.paseoWorktreesBaseRoot, diff --git a/packages/server/src/server/auto-archive-on-merge/behavior.test.ts b/packages/server/src/server/auto-archive-on-merge/behavior.test.ts index 6d24506d36..005bdffb8b 100644 --- a/packages/server/src/server/auto-archive-on-merge/behavior.test.ts +++ b/packages/server/src/server/auto-archive-on-merge/behavior.test.ts @@ -260,7 +260,23 @@ async function createUnobservedWorkspace(journeyOptions?: { metrics: () => service.getMetrics(), isActive: () => active, advanceRemoteHead: () => { - remoteHeadSha = "a".repeat(40); + remoteHeadSha = execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit-tree", + "HEAD^{tree}", + "-p", + "HEAD", + "-m", + "remote update", + ], + { cwd, encoding: "utf8" }, + ).trim(); + run(cwd, ["update-ref", "refs/remotes/origin/workspace", remoteHeadSha]); }, makeDirty: () => writeFileSync(path.join(cwd, "README.md"), "uncommitted work\n"), commitUnpushed: () => { @@ -307,7 +323,7 @@ describe("workspace auto-archive behavior", () => { expect(workspace.isActive()).toBe(true); }); - test("keeps a merged PR visible and the workspace active when its remote head advances", async () => { + test("archives a clean workspace contained in the advanced merged PR head", async () => { const workspace = await createUnobservedWorkspace(); const open = await workspace.observe("open"); workspace.advanceRemoteHead(); @@ -315,8 +331,9 @@ describe("workspace auto-archive behavior", () => { await vi.waitFor(() => expect(workspace.archiveDecisions()).toBe(1)); expect(merged.forge.pullRequest?.url).toBe(open.forge.pullRequest?.url); expect(merged.forge.pullRequest?.headSha).not.toBe(merged.git.headSha); - expect(workspace.isActive()).toBe(true); - expect(workspace.archives).toEqual([]); + expect(merged.git.behindOfOrigin).toBe(1); + expect(workspace.isActive()).toBe(false); + expect(workspace.archives).toHaveLength(1); }); test("archives a clean owned workspace on an unobserved open-to-merged transition only once", async () => { diff --git a/packages/server/src/services/gitea-service.test.ts b/packages/server/src/services/gitea-service.test.ts index 174e870839..7bc1e7983b 100644 --- a/packages/server/src/services/gitea-service.test.ts +++ b/packages/server/src/services/gitea-service.test.ts @@ -1,3 +1,5 @@ +import { createPullRequestHistory } from "../test-utils/pull-request-history.js"; +import { onTestFinished } from "vitest"; import { describe, expect, it } from "vitest"; import type { PullRequestCommandStatus, PullRequestTimelineItem } from "./forge-service.js"; @@ -2100,11 +2102,14 @@ describe("createGiteaService", () => { }); it("keeps a merged PR when its remote head advances beyond the checkout", async () => { + const history = createPullRequestHistory(); + onTestFinished(history.dispose); + const { cwd, workspaceCommit, pullRequestCommit } = history; const stale = currentPullRequestApi({ number: 8, state: "closed", headRef: "dev", - headSha: "1111111111111111111111111111111111111111", + headSha: pullRequestCommit, merged: true, }); const { service } = makeService((args) => { @@ -2117,9 +2122,9 @@ describe("createGiteaService", () => { await expect( service.getCurrentPullRequestStatus({ - cwd: "/repo", + cwd, headRef: "dev", - headSha: "2222222222222222222222222222222222222222", + headSha: workspaceCommit, }), ).resolves.toMatchObject({ number: 8, state: "merged" }); }); diff --git a/packages/server/src/services/gitea-service.ts b/packages/server/src/services/gitea-service.ts index f1148c655e..55a198a650 100644 --- a/packages/server/src/services/gitea-service.ts +++ b/packages/server/src/services/gitea-service.ts @@ -1,3 +1,4 @@ +import { pullRequestContainsCommit } from "./pull-request-contains-commit.js"; import { z } from "zod"; import { CHECK_TRAIT_ACTION_REQUIRED, CHECK_TRAIT_WARNING } from "@getpaseo/protocol/check-traits"; import { mapGiteaCommitState } from "@getpaseo/protocol/gitea-status"; @@ -1656,17 +1657,24 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For // owner gate. return input.headSha !== undefined && item.head.sha === input.headSha; }); - const match = - candidates.find((item) => mapGiteaState(item.state) === "open") ?? - candidates.find( - (item) => - mapGiteaState(item.state) !== "open" && - input.headSha !== undefined && - item.head.sha === input.headSha, - ) ?? - candidates[0] ?? - null; - return match ? currentPullRequestApiToListItem(match) : null; + const open = candidates.find((candidate) => mapGiteaState(candidate.state) === "open"); + if (open) return currentPullRequestApiToListItem(open); + candidates.sort( + (left, right) => + Number(right.head.sha === input.headSha) - Number(left.head.sha === input.headSha), + ); + for (const item of candidates) { + if ( + await pullRequestContainsCommit({ + cwd: input.cwd, + workspaceCommit: input.headSha, + pullRequestCommit: item.head.sha, + }) + ) { + return currentPullRequestApiToListItem(item); + } + } + return null; } async function findOpenPullRequestForHeadRef( diff --git a/packages/server/src/services/github-service.test.ts b/packages/server/src/services/github-service.test.ts index 02aa8d4993..7dc9f9a467 100644 --- a/packages/server/src/services/github-service.test.ts +++ b/packages/server/src/services/github-service.test.ts @@ -1,3 +1,5 @@ +import { createPullRequestHistory } from "../test-utils/pull-request-history.js"; +import { onTestFinished } from "vitest"; import { execFileSync } from "node:child_process"; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -1111,6 +1113,45 @@ describe("ForgeService", () => { expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1); }); + it("filters terminal PRs by containment in a batched poll without per-target API calls", async () => { + vi.useRealTimers(); + const history = createPullRequestHistory(); + onTestFinished(history.dispose); + const { cwd, workspaceCommit, pullRequestCommit } = history; + const runner = createScriptedRunner([ + batchPollStatusJson({ + t0: batchPollRepositoryJson([ + batchPollPrNodeJson({ headRefName: "feature", headRefOid: pullRequestCommit }), + ]), + }), + batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }), + ]); + const service = createGitHubService({ + runner: runner.runner, + resolveGhPath: async () => "/usr/bin/gh", + resolveRepoHost: async () => null, + resolveRepoSlug: async () => "acme/widgets", + }); + onTestFinished(() => service.dispose?.()); + const statuses: Array = []; + const subscription = service.retainCurrentPullRequestStatusPoll?.({ + cwd, + headRef: "feature", + headSha: workspaceCommit, + onStatus: (status) => statuses.push(status), + }); + onTestFinished(() => subscription?.unsubscribe()); + await vi.waitFor(() => expect(statuses).toHaveLength(1)); + expect(statuses[0]).toMatchObject({ state: "merged", headSha: pullRequestCommit }); + expect(runner.calls).toHaveLength(2); + expect(runner.calls.every((call) => call.args[0] === "api" && call.args[1] === "graphql")).toBe( + true, + ); + expect(history.git(["rev-parse", "HEAD"])).toBe(workspaceCommit); + expect(history.git(["rev-parse", "@{upstream}"])).toBe(workspaceCommit); + expect(() => history.git(["rev-parse", "--verify", "FETCH_HEAD"])).toThrow(); + }); + it("batches PR status polls across workspaces into one GraphQL request", async () => { let now = 0; const runner = createScriptedRunner([ @@ -3303,11 +3344,14 @@ describe("ForgeService", () => { }); it("keeps a merged PR when its remote head advances beyond the checkout", async () => { + const history = createPullRequestHistory(); + onTestFinished(history.dispose); + const { cwd, workspaceCommit, pullRequestCommit } = history; const stale = currentPullRequestJson({ headRepositoryOwner: { login: "parentOwner" }, state: "MERGED", mergedAt: "2026-07-17T12:00:00Z", - headRefOid: "1111111111111111111111111111111111111111", + headRefOid: pullRequestCommit, }); const runner = createScriptedRunner([ stale, @@ -3321,9 +3365,9 @@ describe("ForgeService", () => { await expect( service.getCurrentPullRequestStatus({ - cwd: "/repo", + cwd, headRef: "feature/fork", - headSha: "2222222222222222222222222222222222222222", + headSha: workspaceCommit, }), ).resolves.toMatchObject({ state: "merged" }); expect(runner.calls.some((call) => call.args[0] === "pr" && call.args[1] === "list")).toBe( @@ -3331,7 +3375,36 @@ describe("ForgeService", () => { ); }); - it("prefers an exact terminal head and otherwise the most recently updated terminal PR", async () => { + it.each(["CLOSED", "MERGED"])( + "hides a %s PR when a reused branch is ahead of its head", + async (state) => { + const history = createPullRequestHistory(); + onTestFinished(history.dispose); + const candidate = JSON.parse( + currentPullRequestJson({ + state, + mergedAt: state === "MERGED" ? "2026-07-17T12:00:00Z" : null, + headRefOid: history.workspaceCommit, + headRepositoryOwner: { login: "forkOwner" }, + }), + ); + const runner = createScriptedRunner([JSON.stringify(candidate), JSON.stringify([candidate])]); + const service = createGitHubService({ + runner: runner.runner, + resolveGhPath: async () => "/usr/bin/gh", + }); + await expect( + service.getCurrentPullRequestStatus({ + cwd: history.remote, + headRef: "feature/fork", + headRepositoryOwner: "forkOwner", + headSha: history.pullRequestCommit, + }), + ).resolves.toBeNull(); + }, + ); + + it("rejects an unrelated terminal PR on a reused branch", async () => { const owner = { login: "forkOwner" }; const terminal = ({ number, @@ -3368,7 +3441,7 @@ describe("ForgeService", () => { }); for (const [headSha, expected] of [ ["old", 41], - ["other", 42], + ["other", undefined], ] as const) { const runner = createScriptedRunner([JSON.stringify(older), JSON.stringify([older, newer])]); const service = createGitHubService({ @@ -3510,7 +3583,7 @@ describe("ForgeService", () => { for (const [state, headSha, updatedAt, expected] of [ ["OPEN", "other", "2026-07-16T12:00:00Z", 8], ["CLOSED", "other", "2026-07-18T12:00:00Z", 7], - ["CLOSED", "other", "2026-07-18T12:00:00Z", 8], + ["CLOSED", "other", "2026-07-18T12:00:00Z", undefined], ] as const) { const parent = { ...local, diff --git a/packages/server/src/services/github-service.ts b/packages/server/src/services/github-service.ts index 189d53de5b..c5c6d6988f 100644 --- a/packages/server/src/services/github-service.ts +++ b/packages/server/src/services/github-service.ts @@ -1,3 +1,4 @@ +import { pullRequestContainsCommit } from "./pull-request-contains-commit.js"; import { z } from "zod"; import { isGitHubHost, @@ -1661,7 +1662,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G return; } - const distribution = distributeGitHubPollBatch({ + const distribution = await distributeGitHubPollBatch({ entries: addressedEntries, aliases: response.aliases, args, @@ -1702,12 +1703,12 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G } } - function distributeGitHubPollBatch(input: { + async function distributeGitHubPollBatch(input: { entries: GitHubBatchPollEntry[]; aliases: Record; args: string[]; startedAt: number; - }): GitHubBatchDistribution { + }): Promise { const distribution: GitHubBatchDistribution = { pendingChecks: [], legacyFallback: [], @@ -1738,7 +1739,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G distribution.redirected.push(entry); continue; } - const node = selectBatchPollNode(entry, repository.data); + const node = await selectBatchPollNode(entry, repository.data); if (!node) { // Legacy fallback covers the two ways "no match" can be wrong: a fork // whose PR lives in the parent repository, and a full candidate page — @@ -1802,10 +1803,10 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G return `${entry.host}\n${entry.originOwner}/${entry.originName}`; } - function selectBatchPollNode( + async function selectBatchPollNode( entry: GitHubBatchPollEntry, repository: BatchPollRepository, - ): BatchPollPrNode | null { + ): Promise { // Prefer the canonical owner from the response: the origin slug can carry // stale casing or a pre-transfer owner that repository() redirects from. const selfOwner = (repository.owner?.login ?? entry.owner).toLowerCase(); @@ -1830,7 +1831,8 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G nodeByCandidate.set(candidate, node); candidates.push(candidate); } - const match = pickPullRequestCandidate({ + const match = await pickPullRequestCandidate({ + cwd: entry.target.cwd, candidates, headRef: entry.target.headRef, headSha: entry.target.headSha, @@ -2993,7 +2995,8 @@ async function resolveCurrentPullRequestView(options: { }): Promise { const viewCandidate = await tryCurrentPullRequestView(options); const viewMatch = viewCandidate - ? pickPullRequestCandidate({ + ? await pickPullRequestCandidate({ + cwd: options.cwd, candidates: [viewCandidate], headRef: options.headRef, headSha: options.headSha, @@ -3030,7 +3033,8 @@ async function resolveCurrentPullRequestView(options: { headRef: options.headRef, run: options.run, }); - const match = pickPullRequestCandidate({ + const match = await pickPullRequestCandidate({ + cwd: options.cwd, candidates: viewMatch ? [...candidates, viewMatch] : candidates, headRef: options.headRef, headSha: options.headSha, @@ -3067,7 +3071,8 @@ async function resolveForkPullRequestView(options: { }), ), ); - const match = pickPullRequestCandidate({ + const match = await pickPullRequestCandidate({ + cwd: options.cwd, candidates: [ ...candidates.filter( (candidate): candidate is ResolvedPullRequestCandidate => @@ -3442,12 +3447,13 @@ function hasResolvedRepoIdentity(status: CurrentPullRequestStatus): boolean { return Boolean(status.repoOwner && status.repoName); } -function pickPullRequestCandidate(options: { +async function pickPullRequestCandidate(options: { + cwd: string; candidates: ResolvedPullRequestCandidate[]; headRef: string; headSha?: string; headRepositoryOwner?: string; -}): ResolvedPullRequestCandidate | null { +}): Promise { const matching = options.candidates.filter((candidate) => { if (!isCandidateForHeadRef(candidate, options.headRef)) { return false; @@ -3460,7 +3466,18 @@ function pickPullRequestCandidate(options: { matching.sort((left, right) => comparePullRequestCandidatePreference(left, right, options.headSha), ); - return matching[0] ?? null; + for (const candidate of matching) { + if ( + candidate.status.state === "open" || + (await pullRequestContainsCommit({ + cwd: options.cwd, + workspaceCommit: options.headSha, + pullRequestCommit: candidate.headSha, + })) + ) + return candidate; + } + return null; } function comparePullRequestCandidatePreference( diff --git a/packages/server/src/services/gitlab-service.test.ts b/packages/server/src/services/gitlab-service.test.ts index 2e6df284c9..a1af27b963 100644 --- a/packages/server/src/services/gitlab-service.test.ts +++ b/packages/server/src/services/gitlab-service.test.ts @@ -1,3 +1,5 @@ +import { createPullRequestHistory } from "../test-utils/pull-request-history.js"; +import { onTestFinished } from "vitest"; import { describe, expect, it } from "vitest"; import type { PullRequestCommandStatus } from "./forge-service.js"; @@ -390,11 +392,14 @@ describe("createGitLabService", () => { }); it("keeps a merged MR when its remote head advances beyond the checkout", async () => { + const history = createPullRequestHistory(); + onTestFinished(history.dispose); + const { cwd, workspaceCommit, pullRequestCommit } = history; const stale = { ...OPEN_MR, state: "merged", source_branch: "dev", - sha: "1111111111111111111111111111111111111111", + sha: pullRequestCommit, }; const { service, calls } = makeService((args) => ok(JSON.stringify(args[1] === "list" ? [stale] : stale)), @@ -402,9 +407,9 @@ describe("createGitLabService", () => { await expect( service.getCurrentPullRequestStatus({ - cwd: "/repo", + cwd, headRef: "dev", - headSha: "2222222222222222222222222222222222222222", + headSha: workspaceCommit, }), ).resolves.toMatchObject({ state: "merged" }); expect(calls[0]).toEqual(currentMrListArgs("dev")); diff --git a/packages/server/src/services/gitlab-service.ts b/packages/server/src/services/gitlab-service.ts index 3e0111a439..9ae9f65282 100644 --- a/packages/server/src/services/gitlab-service.ts +++ b/packages/server/src/services/gitlab-service.ts @@ -1,3 +1,4 @@ +import { pullRequestContainsCommit } from "./pull-request-contains-commit.js"; import { z } from "zod"; import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote"; import { findExecutable } from "../executable-resolution/executable-resolution.js"; @@ -992,15 +993,21 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F ): Promise { const mergeRequests = await listMergeRequestsBySourceBranch(cwd, headRef); const candidates = mergeRequests.filter((mr) => mr.source_branch === headRef); - const match = - candidates.find((mr) => mapMergeRequestState(mr.state) === "open") ?? - candidates.find( - (mr) => - mapMergeRequestState(mr.state) !== "open" && headSha !== undefined && mr.sha === headSha, - ) ?? - candidates[0] ?? - null; - return match ? viewMergeRequest(cwd, String(match.iid)) : null; + const open = candidates.find((candidate) => mapMergeRequestState(candidate.state) === "open"); + if (open) return viewMergeRequest(cwd, String(open.iid)); + candidates.sort((left, right) => Number(right.sha === headSha) - Number(left.sha === headSha)); + for (const mr of candidates) { + if ( + await pullRequestContainsCommit({ + cwd, + workspaceCommit: headSha, + pullRequestCommit: mr.sha, + }) + ) { + return viewMergeRequest(cwd, String(mr.iid)); + } + } + return null; } /** diff --git a/packages/server/src/services/pull-request-contains-commit.ts b/packages/server/src/services/pull-request-contains-commit.ts new file mode 100644 index 0000000000..91b17e0dda --- /dev/null +++ b/packages/server/src/services/pull-request-contains-commit.ts @@ -0,0 +1,44 @@ +import { execCommand } from "../utils/spawn.js"; + +/** A terminal request belongs to a checkout only when its head contains that commit. */ +export async function pullRequestContainsCommit(input: { + cwd: string; + workspaceCommit?: string; + pullRequestCommit?: string; +}): Promise { + const { cwd, workspaceCommit, pullRequestCommit } = input; + if (!workspaceCommit || !pullRequestCommit) return false; + if (workspaceCommit === pullRequestCommit) return true; + // Only object IDs cross the git command boundary, never remote-supplied revisions/options. + if (![workspaceCommit, pullRequestCommit].every((sha) => /^[a-f0-9]{40,64}$/i.test(sha))) { + return false; + } + const git = (args: string[]) => + execCommand("git", args, { + cwd, + timeout: 15_000, + envOverlay: { GIT_TERMINAL_PROMPT: "0" }, + }); + try { + try { + await git(["cat-file", "-e", `${pullRequestCommit}^{commit}`]); + } catch { + // A server-side branch update need not have been fetched by this checkout. + // Fetch objects only: preserve FETCH_HEAD and all local/tracking refs. + await git([ + "fetch", + "--no-tags", + "--no-write-fetch-head", + "--no-recurse-submodules", + "--no-auto-maintenance", + "origin", + pullRequestCommit, + ]); + } + await git(["merge-base", "--is-ancestor", workspaceCommit, pullRequestCommit]); + return true; + } catch { + // Missing objects, shallow history and unavailable remotes cannot prove ownership. + return false; + } +} diff --git a/packages/server/src/test-utils/pull-request-history.ts b/packages/server/src/test-utils/pull-request-history.ts new file mode 100644 index 0000000000..18ba9a9acc --- /dev/null +++ b/packages/server/src/test-utils/pull-request-history.ts @@ -0,0 +1,44 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { resolve, join } from "node:path"; + +export function createPullRequestHistory() { + const root = resolve(import.meta.dirname, "../../../../.artifacts"); + mkdirSync(root, { recursive: true }); + const directory = mkdtempSync(join(root, "pr-history-")); + const remote = join(directory, "remote"); + const cwd = join(directory, "checkout"); + const git = (path: string, args: string[]) => + execFileSync("git", args, { + cwd: path, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }).trim(); + git(directory, ["init", remote]); + const commit = (message: string) => + git(remote, [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-m", + message, + ]); + commit("workspace"); + const workspaceCommit = git(remote, ["rev-parse", "HEAD"]); + git(directory, ["clone", remote, cwd]); + commit("remote branch update"); + const pullRequestCommit = git(remote, ["rev-parse", "HEAD"]); + return { + cwd, + remote, + workspaceCommit, + pullRequestCommit, + git: (args: string[]) => git(cwd, args), + dispose: () => rmSync(directory, { recursive: true, force: true }), + }; +}