diff --git a/bin/gstack-ship-queue b/bin/gstack-ship-queue index fcc4359c9..d02e38285 100755 --- a/bin/gstack-ship-queue +++ b/bin/gstack-ship-queue @@ -22,7 +22,7 @@ * gstack-ship-queue train build|status|verdict|bisect|rebuild|watch|prune ... (merge trains; train --help) * gstack-ship-queue wave plan|build|status|settle ... (wave PRs: 3-6 same-area PRs in one train slot; wave --help) * - * Every subcommand takes --base (default lib/default-base.ts) and + * Every subcommand takes --base (default: ready's --pr PR base, else lib/default-base.ts) and * ends with GSTACK_RESULT: skill=ship-queue status=complete|refused run=. * gstack-restamp stays the primitive. Nothing here pushes, except land, ready * under changelog_fragments (its READY receipt note), and under a @@ -92,7 +92,7 @@ const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (doc wave plan|build|status|settle ... wave PRs under a train policy: 3-6 same-area PRs in one slot and one version (wave --help; docs/ship-policy.md#wave-prs) ---base : base branch (default: origin/HEAD unless it names the checked-out branch, else the PR's base, origin/main). Nothing here pushes, except land (the stamp commit and the +--base : base branch (default: for ready, the base of the PR --pr names; otherwise origin/HEAD unless it names the checked-out branch, else the PR's base, origin/main; ready refuses a --base that is not its PR's base). Nothing here pushes, except land (the stamp commit and the refs/notes/gstack-land lock), ready under changelog_fragments (its READY receipt note) and merge trains. ${exitTableHelp()}`; @@ -201,8 +201,14 @@ async function main(argv: string[]): Promise { if (probe.status !== 0) return usage('not inside a git repository'); const repoRoot = probe.stdout.trim(); const gh = (a: string[]) => { const r = ghSpawnSync(a, { cwd: repoRoot, encoding: 'utf8', timeout: 60_000 }); return { ok: r.status === 0, out: r.stdout ?? '', err: r.stderr ?? (r.error ? String(r.error.message) : '') }; }; - const ctx: QueueContext = { repoRoot, base: resolveBaseBranch(repoRoot, flag(args, '--base')), gh }; const pr = flag(args, '--pr'); + const explicitBase = flag(args, '--base'); + let prBase: string | undefined; + if (pr && /^\d+$/.test(pr) && cmd === 'ready') { + const view = gh(['pr', 'view', pr, '--json', 'baseRefName']); + try { prBase = view.ok ? JSON.parse(view.out).baseRefName || undefined : undefined; } catch {} + } + const ctx: QueueContext = { repoRoot, base: resolveBaseBranch(repoRoot, explicitBase ?? prBase), gh }; if (cmd === 'gate-ahead') return gateAhead(ctx, args); if (cmd === 'train') { const train = await import('../crew/lib/ship-queue-train-cli'); @@ -234,6 +240,7 @@ async function main(argv: string[]): Promise { if (gateExit !== undefined && !/^-?\d+$/.test(gateExit)) return usage('--gate-exit needs an exit code'); const gate = { gateExit: gateExit === undefined ? undefined : Number(gateExit), gateLog: flag(args, '--gate-log') }; if (cmd === 'ready') { + if (explicitBase && prBase && prBase !== ctx.base) return finish('ready', { ok: false, lines: [], run: 'none', failure: { code: 'QUEUE_NOT_READY', message: `#${pr} targets ${prBase}, not ${ctx.base}, so a receipt reviewed against ${ctx.base} does not cover it`, fix: `rerun ready without --base, or with --base ${prBase}` } }); const unfetched = refreshBase(ctx); const loaded = loadBasePolicy(ctx); if (!('message' in loaded) && loaded.policy.train) return (await import('../crew/lib/ship-queue-train-cli')).readyMain(ctx, args, { pr, pregate: flag(args, '--pregate'), trail: flag(args, '--trail'), ...gate }); diff --git a/changelog.d/ship-queue-uses-the-pr-base.md b/changelog.d/ship-queue-uses-the-pr-base.md new file mode 100644 index 000000000..5c8ebbc42 --- /dev/null +++ b/changelog.d/ship-queue-uses-the-pr-base.md @@ -0,0 +1 @@ +**`gstack-ship-queue ready` now checks a pull request against the branch it targets, not the repository's default branch.** Without `--base`, it takes the base from the pull request `--pr` names, so a pull request into a branch like `garrytan/v0.2-plan-wip` is no longer refused with QUEUE_RECEIPT_BASE_MISMATCH when its /ship receipt names that branch. A receipt reviewed against any other branch is still refused, `ready` now refuses an explicit `--base` that isn't the pull request's base, and `land` still uses the default branch unless `--base` names another, so it keeps refusing a stacked pull request. (GST-3445) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index aa5abfc74..2b53a8c07 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -7125,7 +7125,12 @@ the parent's commits the PR carries were never reviewed under it. `ready`, landing the parent's commits past the parent's own receipt and READY. A receipt whose `base` is the queue's base (`main` or `origin/main`), including a stacked child reviewed against the base (GST-1199), is -unaffected. +unaffected. For `ready` without `--base`, the queue's base is the branch the +pull request targets, so a pull request into a non-default branch whose +receipt names that branch passes; `land` still uses the default branch unless +`--base` names another (GST-3445). `ready` refuses an explicit `--base` that +is not the pull request's base, and any base that differs from the one GitHub +reports, with QUEUE_NOT_READY. **Fix.** Land the parent first, merge the base into this branch and push. Then run `gstack-ship-receipt carry --pr --base `: it moves the receipt to the base when the parent fully landed diff --git a/lib/ship-queue.ts b/lib/ship-queue.ts index 1e790f502..32e8abb7f 100644 --- a/lib/ship-queue.ts +++ b/lib/ship-queue.ts @@ -360,11 +360,12 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate const head = git(ctx.repoRoot, ['rev-parse', 'HEAD']).out; const dirty = git(ctx.repoRoot, ['status', '--porcelain', '--untracked-files=no']).out; if (dirty) return fail({ code: 'QUEUE_NOT_READY', message: `uncommitted tracked changes: ${dirty.split('\n').map(l => l.slice(3)).slice(0, 8).join(', ')}` }, [], run); - const view = ctx.gh(['pr', 'view', o.pr, '--json', 'headRefOid,url,body,mergeable,headRefName,isCrossRepository']); - let info: { headRefOid?: string; url?: string; body?: string; mergeable?: string; headRefName?: string; isCrossRepository?: boolean } = {}; + const view = ctx.gh(['pr', 'view', o.pr, '--json', 'headRefOid,url,body,mergeable,headRefName,isCrossRepository,baseRefName']); + let info: { headRefOid?: string; url?: string; body?: string; mergeable?: string; headRefName?: string; isCrossRepository?: boolean; baseRefName?: string } = {}; try { info = view.ok ? JSON.parse(view.out) : {}; } catch {} if (!info.headRefOid) return fail({ code: 'QUEUE_NOT_READY', message: `cannot read PR #${o.pr}'s head through gh (${(view.err ?? view.out).trim().slice(0, 120)})` }, [], run); if (info.headRefOid !== head) return fail({ code: 'QUEUE_NOT_READY', message: `HEAD ${head.slice(0, 12)} is not PR #${o.pr}'s pushed head ${info.headRefOid.slice(0, 12)}` }, [], run); + if (info.baseRefName && info.baseRefName !== ctx.base) return fail({ code: 'QUEUE_NOT_READY', message: `#${o.pr} targets ${info.baseRefName}, not ${ctx.base}` }, [], run); const atHead = versionAtRef(ctx.repoRoot, head); const baseSha = git(ctx.repoRoot, ['rev-parse', `origin/${ctx.base}`]).out; const atFork = versionAtRef(ctx.repoRoot, git(ctx.repoRoot, ['merge-base', baseSha, head]).out || baseSha); diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index c015e403e..18162ab9d 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -326,6 +326,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'test/ship-queue-ready-fresh-base.test.ts', reason: 'spawns bin/gstack-ship-queue (shebang) and a #!/bin/sh gh shim through test/helpers/restamp-fixture.ts and test/helpers/ship-queue-fixture.ts (windows-scoped-shard, run 42720453184)', }, + { + file: 'test/ship-queue-ready-pr-base.test.ts', + reason: 'spawns bin/gstack-ship-queue (shebang) and a #!/bin/sh gh shim through test/helpers/restamp-fixture.ts and test/helpers/ship-queue-fixture.ts, as test/ship-queue-ready-fresh-base.test.ts does', + }, { file: 'crew/test/release-gate-workflow.test.ts', reason: 'the gate-step case splices a native temp-path stub into the step\'s bash -e script in place of crew/bin/gstack-release-gate, and on windows-latest its gated case exits non-zero (expected 0; windows-scoped-shard, run 42421330820); release-gate.yml itself runs only on ubuntu-latest', diff --git a/test/ship-queue-land-direct.test.ts b/test/ship-queue-land-direct.test.ts index 6674ae31d..8a4d498f4 100644 --- a/test/ship-queue-land-direct.test.ts +++ b/test/ship-queue-land-direct.test.ts @@ -801,6 +801,28 @@ describe('land --pin: refusals (nothing merged)', () => { expect(ok.status).toBe(EXIT.ok); }, 90_000); + // Value: protects=land --pin with no --base keeps the default base, so a stacked PR reviewed against its parent branch is refused instead of merged into that branch; fails_when=land takes its base from the PR's own baseRefName; why_new=every other land test passes --base main; seam=none; no_claim=ready's base resolution + test('QUEUE_NOT_READY: land --pin with no --base still refuses a stacked PR shipped against its parent branch', () => { + const fx = setup(); + const { repo } = fx; + openPr(fx, '18'); + repo.git('checkout', '-q', 'origin/pr-18', '-B', 'pr-181'); + fs.writeFileSync(path.join(repo.work, 'pr-181.txt'), '181\n'); + fs.writeFileSync(path.join(repo.work, 'changelog.d', 'pr-181.md'), '- #181 change\n'); + repo.git('add', '-A'); + repo.git('commit', '-q', '-m', 'pr 181'); + repo.git('push', '-q', '-f', 'origin', 'HEAD:refs/heads/pr-181'); + const pin = repo.git('rev-parse', 'HEAD'); + fx.write(d => { d.prs['181'] = { state: 'OPEN', baseRefName: 'pr-18', headRefName: 'pr-181', isCrossRepository: false, title: 'PR 181', body: shippedBody('181', pin, { base: 'pr-18' }) }; }); + markReady(fx, '181', pin); + repo.git('checkout', '-q', '--detach', 'origin/main'); + const parent = remote(fx, 'pr-18'); + const r = runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', '181', '--pin', pin], fx.env); + refused(fx, r, 'QUEUE_NOT_READY'); + expect(r.err).toContain('#181 targets pr-18, not main'); + expect(remote(fx, 'pr-18')).toBe(parent); + }, 90_000); + test('QUEUE_NOT_READY: no READY note at the pin', () => { const fx = setup(); const pin = openPr(fx, '16', { ready: false }); diff --git a/test/ship-queue-ready-pr-base.test.ts b/test/ship-queue-ready-pr-base.test.ts new file mode 100644 index 000000000..fbd981c44 --- /dev/null +++ b/test/ship-queue-ready-pr-base.test.ts @@ -0,0 +1,100 @@ +/** + * gstack-ship-queue ready takes the base from the PR it is given (GST-3445): a PR into a branch other than the + * repository's default branch binds its /ship receipt against that branch, not origin/HEAD. Founderstar #1024 targets + * garrytan/v0.2-plan-wip and ready refused its correct receipt with QUEUE_RECEIPT_BASE_MISMATCH against main. + * Real fixture repos (bare origin plus working clone) and an offline gh. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { CHECK_IDS } from '../lib/pregate/index'; +import { BASE_POLICY, cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; +import { ghQueueShim } from './helpers/ship-queue-fixture'; +import { shippedBody } from './helpers/ship-queue-train-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); + +const green = { check_runs: [{ status: 'completed', conclusion: 'success' }] }; +const FULL_CHECKS = CHECK_IDS.map(id => ({ id, status: 'pass' })); +const WIP = 'garrytan/v0.2-plan-wip'; + +function commit(repo: FixtureRepo, rel: string, text: string): string { + fs.mkdirSync(path.dirname(path.join(repo.work, rel)), { recursive: true }); + fs.writeFileSync(path.join(repo.work, rel), text); + repo.git('add', '-A'); + repo.git('commit', '-q', '-m', rel); + return repo.git('rev-parse', 'HEAD'); +} + +/** + * origin/HEAD names main; PR #2 is a branch off `branch` (default ${WIP}), which has a commit main lacks. GitHub reports the PR's + * base as `baseRefName` (default the branch). With failBaseLookup, gh fails the bin's own `pr view --json baseRefName` lookup and + * answers every other call. + */ +function prIntoWip(o: { branch?: string; baseRefName?: string; failBaseLookup?: boolean } = {}) { + const branch = o.branch ?? WIP; + const repo = makeFixtureRepo({ prefix: 'gstack-ready-pr-base-', policy: BASE_POLICY }); + repos.push(repo); + repo.git('checkout', '-q', '-b', 'wip', 'origin/main'); + commit(repo, 'plan.txt', 'wip plan\n'); + repo.git('push', '-q', 'origin', `HEAD:refs/heads/${branch}`); + repo.git('fetch', '-q', 'origin'); + repo.git('checkout', '-q', '-b', 'pr-2', `origin/${branch}`); + const head = commit(repo, 'feature.txt', 'feature\n'); + const pregate = path.join(repo.root, 'pregate.json'); + fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree: runBin(repo, 'gstack-wtree', []).out.trim(), head, verdict: 'pass', checks: FULL_CHECKS })); + const ready = (receiptBase: string, extra: string[] = []) => { + const shim = ghQueueShim(repo, { prs: { '2': { headRefOid: head, url: 'https://github.com/o/r/pull/2', baseRefName: o.baseRefName ?? branch, isCrossRepository: false, headRefName: 'pr-2', body: shippedBody('2', head, { base: receiptBase }) } }, checks: { [head]: green } }); + if (!o.failBaseLookup) return runBin(repo, 'gstack-ship-queue', ['ready', '--pr', '2', '--pregate', pregate, ...extra], shim); + const dir = path.join(repo.root, 'gh-flaky-base'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'gh'), `#!/bin/sh\nif [ "$1" = pr ] && [ "$2" = view ] && [ "$4" = --json ] && [ "$5" = baseRefName ]; then echo 'HTTP 502: Bad Gateway' >&2; exit 1; fi\nexec "${path.join(repo.root, 'gh-queue-shim', 'gh')}" "$@"\n`, { mode: 0o755 }); + return runBin(repo, 'gstack-ship-queue', ['ready', '--pr', '2', '--pregate', pregate, ...extra], { PATH: `${dir}:${shim.PATH}` }); + }; + return { repo, ready }; +} + +describe('ready binds the receipt to the PR base, not the default branch (GST-3445)', () => { + // Value: protects=a PR into a non-default branch READYs with the receipt /ship wrote against that branch (Founderstar #1024); + // fails_when=ready without --base resolves origin/HEAD (main) and refuses QUEUE_RECEIPT_BASE_MISMATCH; why_new=every ready + // test passes --base main or opens its PR into main; seam=bin/gstack-ship-queue's base resolution -> bindShippedReceipt; + // no_claim=a PR from a fork into a branch origin does not hold + test('with no --base, a receipt for the PR base binds; a receipt for the default branch is still refused', () => { + const { ready } = prIntoWip(); + const ok = ready(WIP); + expect([ok.status, ok.err]).toEqual([EXIT.ok, '']); + expect(ok.out).toMatch(new RegExp(`^base: origin/${WIP}@[0-9a-f]{40}$`, 'm')); + const wrong = ready('main'); + expect(wrong.status).toBe(EXIT.refused); + expect(wrong.err).toContain('QUEUE_RECEIPT_BASE_MISMATCH'); + }, 180_000); + + // Value: protects=an explicit --base that is not the PR's base never binds a receipt reviewed against the wrong branch; + // fails_when=ready trusts --base over the PR and READYs a main receipt for a PR into another branch; why_new=ready never + // read the PR's base; seam=bin/gstack-ship-queue ready; no_claim=land, which already refuses a PR on another base + test('an explicit --base other than the PR base refuses before any receipt is read', () => { + const { ready } = prIntoWip(); + const r = ready('main', ['--base', 'main']); + expect(r.status).toBe(EXIT.refused); + expect(r.err).toContain(`#2 targets ${WIP}, not main`); + expect(r.err).toContain('QUEUE_NOT_READY'); + expect(r.err).not.toContain('QUEUE_RECEIPT_BASE_MISMATCH'); + }, 180_000); + + // Value: protects=ready never prints READY for a PR whose GitHub base is not the base ready checked the receipt against; + // fails_when=ready trusts the bin's base lookup, so a failed lookup (falls back to main) or a base named origin/foo (stripped + // to foo) binds the wrong receipt; why_new=the cases above only cover a lookup that succeeds with a plain name; + // seam=lib/ship-queue.ts ready()'s own pr view; no_claim=land, which refuses a PR on another base by itself + test("ready refuses when the PR's base differs from the checked base: a failed base lookup, or a base named origin/", () => { + const lookupFailed = prIntoWip({ failBaseLookup: true }).ready('main'); + expect(lookupFailed.status).toBe(EXIT.refused); + expect(lookupFailed.err).toContain(`#2 targets ${WIP}, not main`); + expect(lookupFailed.err).toContain('QUEUE_NOT_READY'); + const stripped = prIntoWip({ branch: 'foo', baseRefName: 'origin/foo' }).ready('foo'); + expect(stripped.status).toBe(EXIT.refused); + expect(stripped.err).toContain('#2 targets origin/foo, not foo'); + expect(stripped.err).toContain('QUEUE_NOT_READY'); + }, 180_000); +});