diff --git a/plugins/stewards/carries.ts b/plugins/stewards/carries.ts index f985abc6..e052dc4f 100644 --- a/plugins/stewards/carries.ts +++ b/plugins/stewards/carries.ts @@ -170,7 +170,7 @@ export async function evaluateCarries(target: DeploymentTarget, context: Carries // only settle a watch whose merge is already on the default branch. Require // the deployment's ref to contain the merge, exactly as ref-contains-merge // does: a stacked pull request's squash merge is not on main, so it stays - // not-yet until the BB-215 override re-points the watch. The record path + // not-yet until it reaches the default branch. The record path // (`liveAtMergeVerdict`) settles a normal merge at merge time, so this read // only runs for a watch left awaiting a deployment. if (rule.strategy.kind === "live-at-merge") { diff --git a/plugins/stewards/deploy.test.ts b/plugins/stewards/deploy.test.ts index 5872298f..8d9acc70 100644 --- a/plugins/stewards/deploy.test.ts +++ b/plugins/stewards/deploy.test.ts @@ -83,28 +83,6 @@ describe("recording merged pull requests", () => { expect(recordMerged(first, observed(), [target], NOW + 1000)).toBe(first); }); - it("carries a stacked pull request by the base pull request's merge on the default branch (BB-215)", () => { - const stacked = pull({ key: "acme/web#20" }, { merged: true, mergeCommit: "stacked1", files: ["plugins/stewards/a.ts"] }); - const first = recordMerged({}, { entity: stacked, pulls: [] }, [target], NOW); - expect(first["acme/web#20"]).toMatchObject({ mergeSha: "stacked1", prRepo: "acme/web", files: ["plugins/stewards/a.ts"] }); - // The base pull request's merge lands on the default branch: the override - // re-points the watch to it, so a carries check finds it on main. - const base = { mergeSha: "base0001", prRepo: "acme/web", files: ["plugins/stewards/a.ts", "plugins/stewards/b.ts"] }; - const after = recordMerged(first, { entity: stacked, pulls: [] }, [target], NOW + 1000, () => base); - expect(after["acme/web#20"]).toMatchObject({ mergeSha: "base0001", prRepo: "acme/web", files: ["plugins/stewards/a.ts", "plugins/stewards/b.ts"] }); - }); - - it("applies the landedIn override only to the pull request that merged into the base (BB-215)", () => { - const stacked = pull({ key: "acme/web#20" }, { merged: true, mergeCommit: "stacked1", base: "feature-base", head: "feature-stacked" }); - const direct = pull({ key: "acme/web#21" }, { merged: true, mergeCommit: "direct1", base: "main", head: "feature-direct" }); - const first = recordMerged({}, { entity: stacked, pulls: [direct] }, [target], NOW); - const base = { mergeSha: "base0001", prRepo: "acme/web", files: ["plugins/stewards/a.ts"] }; - const after = recordMerged(first, { entity: stacked, pulls: [direct] }, [target], NOW + 1000, (p) => (p.pull?.base === "feature-base" ? base : null)); - // The stacked pull request follows the base; the direct one keeps its own merge. - expect(after["acme/web#20"]).toMatchObject({ mergeSha: "base0001" }); - expect(after["acme/web#21"]).toMatchObject({ mergeSha: "direct1" }); - }); - it("stores the merge commit, not the head, and notes an unknown oid", () => { const merged = pull({ key: "acme/web#9" }, { merged: true, headSha: "headsha1", mergeCommit: "mergesha" }); const deployments = recordMerged({}, { entity: merged, pulls: [] }, [target], NOW); @@ -267,35 +245,16 @@ describe("recording merged pull requests", () => { }); // BB-260: a stacked pull request merged into its base branch is not on main, - // so it is not live at merge. The BB-215 override re-points it once the base - // lands, and the live check is re-run against the base's files. + // so it is not live at merge. Under bottom-up (BB-264) it is retargeted and + // merged to main rather than carried by the base's merge, so the live check + // reads its own base. it("does not mark a stacked .bb-only merge deployed before it reaches the default branch", () => { const stacked = pull({ key: "bitcomplete/bb-gate#20", unit: "bitcomplete/bb-gate" }, { merged: true, mergeCommit: "stacked1", base: "feature-base", head: "feature-stacked", files: [".bb/AGENTS.md"] }); const isDefaultBase = (_repo: string, base: string | null) => base === "main"; - const recorded = recordMerged({}, { entity: stacked, pulls: [] }, [liveAtMergeTarget], NOW, undefined, isDefaultBase); + const recorded = recordMerged({}, { entity: stacked, pulls: [] }, [liveAtMergeTarget], NOW, isDefaultBase); expect(recorded["bitcomplete/bb-gate#20::bb-gate"]).toMatchObject({ state: "merged", mergeSha: "stacked1", deadlineAt: NOW + liveAtMergeTarget.timeout }); }); - it("keeps a stacked watch merged when the override's base is not live at merge", () => { - const stacked = pull({ key: "bitcomplete/bb-gate#21", unit: "bitcomplete/bb-gate" }, { merged: true, mergeCommit: "stacked2", base: "feature-base", head: "feature-stacked", files: [".bb/AGENTS.md"] }); - const isDefaultBase = (_repo: string, base: string | null) => base === "main"; - const first = recordMerged({}, { entity: stacked, pulls: [] }, [liveAtMergeTarget], NOW, undefined, isDefaultBase); - expect(first["bitcomplete/bb-gate#21::bb-gate"]).toMatchObject({ state: "merged" }); - const base = { mergeSha: "base0001", prRepo: "bitcomplete/bb-gate", files: [".bb/AGENTS.md", "cmd/router/main.go"] }; - const after = recordMerged(first, { entity: stacked, pulls: [] }, [liveAtMergeTarget], NOW + 1000, () => base, isDefaultBase); - expect(after["bitcomplete/bb-gate#21::bb-gate"]).toMatchObject({ state: "merged", mergeSha: "base0001", files: [".bb/AGENTS.md", "cmd/router/main.go"] }); - }); - - it("marks a stacked watch deployed when the override's base is live at merge", () => { - const stacked = pull({ key: "bitcomplete/bb-gate#22", unit: "bitcomplete/bb-gate" }, { merged: true, mergeCommit: "stacked3", base: "feature-base", head: "feature-stacked", files: ["cmd/router/main.go"] }); - const isDefaultBase = (_repo: string, base: string | null) => base === "main"; - const first = recordMerged({}, { entity: stacked, pulls: [] }, [liveAtMergeTarget], NOW, undefined, isDefaultBase); - expect(first["bitcomplete/bb-gate#22::bb-gate"]).toMatchObject({ state: "merged" }); - const base = { mergeSha: "base0002", prRepo: "bitcomplete/bb-gate", files: [".bb/AGENTS.md"] }; - const after = recordMerged(first, { entity: stacked, pulls: [] }, [liveAtMergeTarget], NOW + 1000, () => base, isDefaultBase); - expect(after["bitcomplete/bb-gate#22::bb-gate"]).toMatchObject({ state: "deployed", mergeSha: "base0002", deadlineAt: null, note: "live-at-merge: nothing deploys .bb/**, docs/**, **.md" }); - }); - it("does not record an open pull request, and reads a ticket's linked merged ones", () => { expect(recordMerged({}, observed({ entity: pull({ key: "acme/web#7" }, { merged: false }) }), [target], NOW)).toEqual({}); const linked = recordMerged({}, observed({ entity: pull({ key: "acme/web#7", kind: "pull" }, { merged: false }), pulls: [pull({ key: "acme/web#8" }, { merged: true })] }), [target], NOW); diff --git a/plugins/stewards/deploy.ts b/plugins/stewards/deploy.ts index b3edd874..2dd58a0a 100644 --- a/plugins/stewards/deploy.ts +++ b/plugins/stewards/deploy.ts @@ -124,13 +124,11 @@ export function recordMerged( observed: Observed, targets: readonly DeploymentTarget[], now: number, - overrideFor?: (p: EntitySnapshot) => { mergeSha: string | null; prRepo: string; files: string[] } | null, /** * Whether a merged pull request's base is its repo's default branch, so its * merge is already on `main`. A stacked pull request merged into its base - * branch is not live yet; the BB-215 override re-points it once the base - * lands. Omitted, every base is treated as the default (the pre-BB-260 - * behaviour, for callers with no default-branch read). + * branch is not live yet. Omitted, every base is treated as the default + * (the pre-BB-260 behaviour, for callers with no default-branch read). */ isDefaultBase?: (prRepo: string, base: string | null) => boolean, ): Deployments { @@ -140,26 +138,20 @@ export function recordMerged( const next = { ...deployments }; let changed = false; for (const p of pulls) { - // A stacked pull request that landed in a base pull request (BB-215) is - // carried by the base's merge on the default branch, not by the stacked - // merge a squash rewrote: the override supplies that merge's commit and - // the base's repo and files, so the carries rule matches what is on main. - const over = overrideFor?.(p) ?? null; - const merge = over === null ? p.pull?.mergeCommit ?? null : over.mergeSha; - const files = over === null ? p.pull?.files ?? [] : over.files; - const prRepo = over === null ? p.unit : over.prRepo; + const merge = p.pull?.mergeCommit ?? null; + const files = p.pull?.files ?? []; + const prRepo = p.unit; // BB-260: a live-at-merge merge is only live once it is on the default // branch. A stacked pull request merged into its base branch is not live - // yet; the override, when it lands, re-points the watch to the base's - // merge on main. A base the read could not name is not treated as default. - const onDefault = over !== null || (isDefaultBase?.(p.unit, p.pull?.base ?? null) ?? true); + // yet. A base the read could not name is not treated as default. + const onDefault = isDefaultBase?.(p.unit, p.pull?.base ?? null) ?? true; // An existing watch's own recorded repo and files decide applicability // when it has them: a snapshot whose files read came back empty must not // drop an in-flight watch. The fresh snapshot is the fallback. const contextFor = (target: DeploymentTarget): { prRepo: string; files: readonly string[] } => { const id = watchId(p.key, target, multiple); const existing = next[id] ?? (id === p.key ? undefined : next[p.key]); - if (over === null && existing !== undefined && existing.prRepo !== "" && matchesTarget(target, existing.repo, existing.environment)) return { prRepo: existing.prRepo, files: existing.files }; + if (existing !== undefined && existing.prRepo !== "" && matchesTarget(target, existing.repo, existing.environment)) return { prRepo: existing.prRepo, files: existing.files }; return { prRepo, files }; }; const applicable = targets.filter((t) => { @@ -193,32 +185,14 @@ export function recordMerged( if (merge !== null && existing.mergeSha !== merge) { const resolved = `Merge commit re-resolved to ${merge.slice(0, 7)}`; // A `merged` watch that already holds a success deployment was judged - // against the old sha (BB-215): moving it back to `deploying` lets the + // against the old sha (BB-259): moving it back to `deploying` lets the // reconcile's carries re-evaluation loop settle it against the // re-resolved sha in the same pass, rather than waiting for a new // deployment or timing out. Its stale not-yet note is replaced, so it // never says a pin does not contain the sha it was re-resolved to. const reevaluate = existing.state === "merged" && existing.deploymentId !== null && existing.deploymentState === "success"; const note = reevaluate ? resolved : existing.note === null || existing.note === undefined || existing.note === "" ? resolved : `${existing.note} (${resolved})`; - // BB-260: when the BB-215 override re-points the watch to the base - // merge on the default branch, re-run the live check against the - // base's files. A live rule marks it deployed; a watch live-marked - // on a stacked merge whose base is not live goes back to `merged` - // and awaits a deployment. - const live = over === null ? null : liveVerdict(target, prRepo, files); - let state = reevaluate ? "deploying" : existing.state; - let deadlineAt = existing.deadlineAt; - let finalNote = note; - if (live !== null) { - state = "deployed"; - deadlineAt = null; - finalNote = live.note; - } else if (over !== null && existing.state === "deployed" && existing.deploymentId === null) { - state = "merged"; - deadlineAt = now + target.timeout; - finalNote = resolved; - } - next[id] = { ...existing, state, mergeSha: merge, deadlineAt, ...(over === null ? {} : { prRepo, files }), note: finalNote }; + next[id] = { ...existing, state: reevaluate ? "deploying" : existing.state, mergeSha: merge, note }; changed = true; } continue; diff --git a/plugins/stewards/github.ts b/plugins/stewards/github.ts index 33c2d32b..a901bb59 100644 --- a/plugins/stewards/github.ts +++ b/plugins/stewards/github.ts @@ -105,6 +105,13 @@ export interface GithubWriter { dispatchWorkflow(repo: string, workflow: string, ref: string, inputs: Record): Promise; /** A repository's default branch, for the base of a lesson's pull request (BB-108). */ defaultBranch(repo: string): Promise; + /** + * The newest pull request in `repo` whose head branch is `head`, across + * every state, or null when none is visible. A stacked pull request's base + * names the branch of the pull request it is stacked on; the plugin reads + * this to tell an open base (a merge hold) from a merged one (a retarget). + */ + pullByHead(repo: string, head: string): Promise<{ number: number; key: string; state: string; merged: boolean } | null>; /** Open a pull request and return its URL and number (BB-108). */ createPull(repo: string, args: { head: string; base: string; title: string; body: string }): Promise<{ url: string; number: number }>; /** Close a pull request without merging it (BB-108 Drop). */ @@ -185,6 +192,24 @@ export function createGhWriter(token: TokenReader = createGhTokenReader(), doFet const body = (await response.json().catch(() => null)) as { default_branch?: unknown } | null; return typeof body?.default_branch === "string" && body.default_branch !== "" ? body.default_branch : null; }, + async pullByHead(repo, head) { + // GitHub's `head` filter is `user:ref-name` and only matches same-repo + // pull requests when `user` is the repository owner. The list is newest + // first; the first match is the pull request the base branch belongs to. + const owner = repo.split("/")[0] ?? ""; + const query = `head=${encodeURIComponent(`${owner}:${head}`)}&state=all&sort=created&direction=desc&per_page=100`; + const response = await request("GET", `/repos/${repo}/pulls?${query}`, undefined); + const body = (await response.json().catch(() => null)) as unknown; + if (!Array.isArray(body)) return null; + for (const item of body) { + if (item === null || typeof item !== "object") continue; + const pr = item as { number?: unknown; state?: unknown; merged_at?: unknown; head?: { ref?: unknown } }; + if (typeof pr.number !== "number") continue; + if (typeof pr.head?.ref === "string" && pr.head.ref !== head) continue; + return { number: pr.number, key: `${repo}#${pr.number}`, state: typeof pr.state === "string" ? pr.state : "", merged: pr.merged_at !== null && pr.merged_at !== undefined }; + } + return null; + }, async dispatchWorkflow(repo, workflow, ref, inputs) { await request("POST", `/repos/${repo}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, { ref, inputs }); }, diff --git a/plugins/stewards/migrations.snapshot.json b/plugins/stewards/migrations.snapshot.json index 8bdf1d61..71187085 100644 --- a/plugins/stewards/migrations.snapshot.json +++ b/plugins/stewards/migrations.snapshot.json @@ -115,5 +115,6 @@ "a4c47117eadbd16a6521f838e277fe6b56dd463a81bcf64e26907ea56ae68361", "dab0f2a29dd1b4d8d65a58fb712c4d6689105d6c5bbe90e95dc3accff924c3f1", "699df5c091ae8f12adf16a45faad54c866cd28c58963b3a9132ab6708617d35b", - "0cb5723b6d354beb4c2e6e60fabb5b5e3ddf0245bc755b3b4bcd3cbce6b6fd56" + "0cb5723b6d354beb4c2e6e60fabb5b5e3ddf0245bc755b3b4bcd3cbce6b6fd56", + "a8f6be062abc53e51ea5b4acd27627cf915242aa1b0a60e7e32dc3184ab65b13" ] diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index d3ce5822..91a7fa0f 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -180,6 +180,18 @@ function world() { return m === null || path !== `.bb/${m[1]}` ? null : pr.body; }, defaultBranch: async (repo: string) => githubDefaultBranches.get(repo) ?? "main", + // The real writer lists a repo's pull requests filtered by head branch + // (BB-264); the fake scans the entities the test registered. + pullByHead: async (repo: string, head: string) => { + for (const e of entities.values()) { + if (e.pull === null || e.pull.head !== head) continue; + if (e.unit.toLowerCase() !== repo.toLowerCase()) continue; + const number = Number(/(\d+)$/u.exec(e.key)?.[1] ?? ""); + if (!Number.isInteger(number) || number <= 0) continue; + return { number, key: e.key, state: e.state, merged: e.pull.merged === true || e.state.toLowerCase() === "merged" }; + } + return null; + }, dispatchWorkflow: async (repo: string, workflow: string, ref: string, inputs: Record) => { if (mergeDispatchError !== null) throw new Error(mergeDispatchError); githubDispatches.push({ repo, workflow, ref, inputs }); @@ -7189,12 +7201,12 @@ describe("needs you items", () => { expect(t.sends.filter((s) => s.threadId === t.steward).some((s) => /What changed[\s\S]*merged by the plugin/u.test(s.text))).toBe(true); }); - it("does not merge a gate-met stacked pull request; it files the Merge item for a person (BB-257)", async () => { + it("does not merge a gate-met pull request on an unknown base branch; it files the Merge item (BB-257)", async () => { const t = await withPull([marker]); const b = t.binding(); - // The pull request's base is another pull request's branch, not the repo's - // default branch. A person or worker merges it into its parent; the plugin - // must not squash it into a branch that may already be merged and dead. + // The base is a branch no open or merged pull request is based on (BB-264), + // so the plugin cannot tell it is stacked: it must not squash-merge into a + // branch that may already be dead, and files the Merge item instead. t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "bb/bb-256-parent", checks: { state: "success", failing: [] } })); await t.ring("linear", "uuid-12"); expect(t.githubMerges).toEqual([]); @@ -7204,14 +7216,88 @@ describe("needs you items", () => { it("merges a gate-met pull request once its base is the default branch again", async () => { const t = await withPull([marker]); const b = t.binding(); - // Stacked first: the plugin files the item. Retargeted to `main`: the next - // look merges and closes the item through the shared path. + // An unknown base first: the plugin files the item. Retargeted to `main`: + // the next look merges and closes the item through the shared path. + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "bb/bb-256-parent", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "main", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toHaveLength(1); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); + }); + + it("holds a gate-met pull request behind an open base pull request and files no Merge item (BB-264)", async () => { + const t = await withPull([marker]); + const b = t.binding(); + // The base pull request is open on the branch this pull request is based + // on. The plugin must not merge into it and must not file a Merge item; + // the effort shows as held behind the base. + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Base" }, { head: "bb/bb-256-parent", base: "main" })); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "bb/bb-256-parent", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + await t.flush(); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["acme/web#8"]); + expect(t.sends.filter((s) => s.threadId === t.steward).some((s) => /Merge held: acme\/web#7 is stacked on acme\/web#8/u.test(s.text))).toBe(true); + expect(t.sends.filter((s) => s.threadId === t.steward).some((s) => /MERGE HOLD: behind acme\/web#8/u.test(s.text))).toBe(true); + // Nothing changed: the derived hold is already recorded, so no new wake. + const wakes = t.sends.filter((s) => s.threadId === t.steward).length; + await t.ring("linear", "uuid-12"); + await t.flush(); + expect(t.sends.filter((s) => s.threadId === t.steward).length).toBe(wakes); + }); + + it("wakes the steward to retarget a gate-met pull request whose base pull request has merged (BB-264)", async () => { + const t = await withPull([marker]); + const b = t.binding(); + // GitHub does not retarget the stacked pull request when its base merges + // (delete_branch_on_merge is off), so its base is still the merged branch. + // The plugin files no Merge item and wakes the steward to retarget. + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Base", state: "merged" }, { merged: true, mergeCommit: "b".repeat(40), head: "bb/bb-256-parent", base: "main" })); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "bb/bb-256-parent", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + await t.flush(); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual([]); + expect(t.sends.filter((s) => s.threadId === t.steward).some((s) => /Retarget acme\/web#7: its base acme\/web#8 has merged/u.test(s.text))).toBe(true); + // The retarget wake is once per base pull request, not on every look. + expect(t.hooks.store.find("ENG-12")!.retargetPulls).toEqual(["acme/web#8"]); + const wakes = t.sends.filter((s) => s.threadId === t.steward).length; + await t.ring("linear", "uuid-12"); + await t.flush(); + expect(t.sends.filter((s) => s.threadId === t.steward).length).toBe(wakes); + }); + + it("treats a gate-met pull request whose base pull request closed unmerged as an ordinary pull request (BB-264)", async () => { + const t = await withPull([marker]); + const b = t.binding(); + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Base", state: "closed" }, { merged: false, head: "bb/bb-256-parent", base: "main" })); t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "bb/bb-256-parent", checks: { state: "success", failing: [] } })); await t.ring("linear", "uuid-12"); + await t.flush(); expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(true); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual([]); + }); + + it("merges a held stacked pull request once its base merges and it is retargeted (BB-264)", async () => { + const t = await withPull([marker]); + const b = t.binding(); + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Base" }, { head: "bb/bb-256-parent", base: "main" })); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "bb/bb-256-parent", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + await t.flush(); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["acme/web#8"]); + // The base merges; the stacked pull request is retargeted to main. + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Base", state: "merged" }, { merged: true, mergeCommit: "b".repeat(40), head: "bb/bb-256-parent", base: "main" })); t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "main", checks: { state: "success", failing: [] } })); await t.ring("linear", "uuid-12"); expect(t.githubMerges).toHaveLength(1); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual([]); expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); }); @@ -8426,21 +8512,32 @@ describe("needs you items", () => { const t = await withPull([marker, owner]); t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Blocker" })); await t.ring("linear", "uuid-13"); - expect(await t.tool("steward_report", { ...base, mergeBehind: ["ENG-99"] }, t.steward)).toMatchObject({ error: true, text: expect.stringMatching(/Not an open binding in this project to hold the merge behind: ENG-99\./u) }); - expect(await t.tool("steward_report", { ...base, mergeBehind: ["ENG-12"] }, t.steward)).toMatchObject({ error: true, text: expect.stringMatching(/Not an open binding in this project to hold the merge behind: ENG-12\./u) }); + expect(await t.tool("steward_report", { ...base, mergeBehind: ["ENG-99"] }, t.steward)).toMatchObject({ error: true, text: expect.stringMatching(/Not an open binding or pull request in this project to hold the merge behind: ENG-99\./u) }); + expect(await t.tool("steward_report", { ...base, mergeBehind: ["ENG-12"] }, t.steward)).toMatchObject({ error: true, text: expect.stringMatching(/Not an open binding or pull request in this project to hold the merge behind: ENG-12\./u) }); // A key in any case is stored canonically, like `behind`. const ok = await t.tool("steward_report", { ...base, mergeBehind: ["eng-13"] }, t.steward); expect(ok.error, ok.text).toBe(false); expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["ENG-13"]); // An ended key is refused with a reason. t.hooks.store.patch(t.hooks.store.find("ENG-13")!.id, { endedAt: 1, endReason: "terminal" }); - expect(await t.tool("steward_report", { ...base, mergeBehind: ["ENG-13"] }, t.steward)).toMatchObject({ error: true, text: expect.stringMatching(/Not an open binding in this project to hold the merge behind: ENG-13\./u) }); + expect(await t.tool("steward_report", { ...base, mergeBehind: ["ENG-13"] }, t.steward)).toMatchObject({ error: true, text: expect.stringMatching(/Not an open binding or pull request in this project to hold the merge behind: ENG-13\./u) }); expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["ENG-13"]); // [] clears it. await t.tool("steward_report", { ...base, mergeBehind: [] }, t.steward); expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual([]); }); + it("accepts an open base pull request key for a stack, and refuses a closed one (BB-264)", async () => { + const t = await withPull([marker, owner]); + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Base" }, { head: "bb/bb-256-parent", base: "main" })); + const ok = await t.tool("steward_report", { ...base, mergeBehind: ["acme/web#8"] }, t.steward); + expect(ok.error, ok.text).toBe(false); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["acme/web#8"]); + // A closed base pull request is refused: there is nothing to hold behind. + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Base", state: "closed" }, { head: "bb/bb-256-parent", base: "main" })); + expect(await t.tool("steward_report", { ...base, mergeBehind: ["acme/web#8"] }, t.steward)).toMatchObject({ error: true, text: expect.stringMatching(/Not an open binding or pull request in this project to hold the merge behind: acme\/web#8\./u) }); + }); + it("files no plugin Merge item while it stands, closes an open one, and leaves a steward-filed one alone", async () => { const t = await withPull([marker]); const b = t.binding(); @@ -11799,57 +11896,47 @@ describe("deployment watching (BB-53)", () => { expect(wake).toMatch(/evaluated by the plugin/); }); - // BB-215: a stacked pull request's own merge is not on the default branch - // after a squash, so the ticket reports the base pull request it landed in - // and the carries check follows that merge instead. - it("follows a stacked pull request's base pull request for the carries check (BB-215)", async () => { + // BB-264: `landedIn` is retired. The `landed_in` column stays so an + // existing binding still loads; the tolerant reader ignores the stored value + // and the watch follows the pull request's own merge. + it("ignores a stored landed_in value on an existing binding (BB-264)", async () => { const t = await setup(); t.files[playbookPath("linear-tickets")] = structuredPlaybook(' - when: { repo: acme/web }\n strategy: { kind: ref-contains-merge }'); t.entities.set("uuid-12", issue({ id: "uuid-12", key: "ENG-12", state: "In Progress", linkedPulls: [{ url: "https://github.com/acme/web/pull/7", key: "acme/web#7" }] })); - t.entities.set("acme/web#7", pull({ key: "acme/web#7" }, { merged: true, mergeCommit: "stacked1", base: "feature-base", head: "feature-stacked" })); - t.entities.set("acme/web#9", pull({ key: "acme/web#9" }, { merged: true, mergeCommit: "aaaaaaa1", base: "main", head: "feature-base" })); + t.entities.set("acme/web#7", pull({ key: "acme/web#7" }, { merged: true, mergeCommit: "aaaaaaa1", base: "main", head: "feature-stacked" })); await t.ring("linear", "uuid-12"); - const steward = t.spawns[1]!.id; - // Before the report the watch carries the stacked merge. - expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ mergeSha: "stacked1" }); - await t.tool("steward_report", { phase: "In Review", summary: "Stacked PR merged into the base.", nextAction: "Await the base deployment.", actor: "other", landedIn: "acme/web#9" }, steward); - await t.ring("linear", "uuid-12"); - expect(t.hooks.store.find("ENG-12")!.landedIn).toBe("acme/web#9"); - // The watch now carries the base pull request's merge on main. - expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ mergeSha: "aaaaaaa1" }); - t.sourceCompares.set("acme/bb-gate aaaaaaa1 main", "identical"); - await doorbell(t, "acme/bb-gate#7", deployment()); - expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "deployed", note: expect.stringMatching(/contains merge aaaaaaa/u) }); + const b = t.hooks.store.find("ENG-12")!; + // A binding written by an older build still carries the retired column. + t.hooks.db.prepare("UPDATE bindings SET landed_in = ? WHERE id = ?").run("acme/web#9", b.id); + const loaded = t.hooks.store.find("ENG-12")!; + expect(loaded).not.toHaveProperty("landedIn"); + // The watch carries the pull request's own merge, not a base's. + expect(loaded.deployments["acme/web#7"]).toMatchObject({ mergeSha: "aaaaaaa1" }); }); - // BB-259: a `merged` watch judged not-yet against a stacked pull request's - // sha, then re-resolved to the base pull request's squash commit while it - // already holds the success deployment that pins that commit, must be - // re-evaluated in the same reconcile and settle deployed, not time out. - it("re-evaluates a re-resolved stacked watch against its existing success deployment (BB-259)", async () => { + // BB-259: a `merged` watch judged not-yet against one sha, then re-resolved + // to another while it already holds the success deployment that pins that + // commit, must be re-evaluated in the same reconcile and settle deployed, + // not time out. + it("re-evaluates a re-resolved watch against its existing success deployment (BB-259)", async () => { const t = await setup(); t.files[playbookPath("linear-tickets")] = structuredPlaybook(' - when: { repo: acme/web }\n strategy: { kind: ref-contains-merge }'); t.entities.set("uuid-12", issue({ id: "uuid-12", key: "ENG-12", state: "In Progress", linkedPulls: [{ url: "https://github.com/acme/web/pull/7", key: "acme/web#7" }] })); t.entities.set("acme/web#7", pull({ key: "acme/web#7" }, { merged: true, mergeCommit: "stacked1", base: "feature-base", head: "feature-stacked" })); - // The base pull request is not merged when the steward reports it, so the - // override does not apply and the watch keeps the stacked sha. - t.entities.set("acme/web#9", pull({ key: "acme/web#9" }, { merged: false, base: "main", head: "feature-base" })); await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; - await t.tool("steward_report", { phase: "In Review", summary: "Stacked PR merged into the base.", nextAction: "Await the base deployment.", actor: "other", landedIn: "acme/web#9" }, steward); - await t.ring("linear", "uuid-12"); expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ mergeSha: "stacked1" }); - // A success deployment pins the stacked sha's absence: the carries check - // says not-yet and the watch goes back to `merged` holding deployment 7. + // A success deployment pins the sha's absence: the carries check says + // not-yet and the watch goes back to `merged` holding deployment 7. t.sourceCompares.set("acme/bb-gate stacked1 main", "behind"); await doorbell(t, "acme/bb-gate#7", deployment()); expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "merged", mergeSha: "stacked1", deploymentId: 7, deploymentState: "success", note: expect.stringMatching(/does not contain merge/u) }); - // The base pull request is now observed merged with squash commit X, and - // the same success deployment pins X. The next reconcile re-resolves the - // watch and settles it deployed in the same pass. - t.entities.set("acme/web#9", pull({ key: "acme/web#9" }, { merged: true, mergeCommit: "aaaaaaa1", base: "main", head: "feature-base" })); + // A rebase rewrote the merge, so the source now reports a different merge + // commit; the same success deployment pins it. The next reconcile + // re-resolves the watch and settles it deployed in the same pass. + t.entities.set("acme/web#7", pull({ key: "acme/web#7" }, { merged: true, mergeCommit: "aaaaaaa1", base: "main", head: "feature-stacked" })); t.sourceCompares.set("acme/bb-gate aaaaaaa1 main", "identical"); await t.ring("linear", "uuid-12"); expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "deployed", mergeSha: "aaaaaaa1", deploymentId: 7, deploymentState: "success", note: expect.stringMatching(/contains merge aaaaaaa/u) }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index f3caa7da..00126ff1 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -3751,22 +3751,6 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P let deployments = b.deployments; if (deployTargets.length > 0) { const beforeDeploy = deployments; - // BB-215: a stacked pull request whose ticket reported the base pull - // request it landed in is carried by the base's merge on the default - // branch, because a squash rewrote the stacked merge. Read the base - // fresh so the watch re-points as soon as the base merges, and apply - // the override only to the pull request that actually merged into the - // base branch, never to another merged pull request on the ticket. - let landedOverride: ((p: EntitySnapshot) => { mergeSha: string | null; prRepo: string; files: string[] } | null) | undefined; - if (b.landedIn !== null) { - const base = await snapshot("github", b.landedIn).catch(() => null); - if (base !== null && base.pull !== null && base.pull.merged && base.pull.head !== null && base.pull.head !== "") { - const baseUnit = base.unit; - const baseHead = base.pull.head; - const override = { mergeSha: base.pull.mergeCommit ?? null, prRepo: base.unit, files: base.pull.files ?? [] }; - landedOverride = (p) => (p.unit === baseUnit && p.pull?.base === baseHead ? override : null); - } - } // BB-260: a live-at-merge rule is only live on the default branch, so // the record needs to know each merged pull's default branch. Read it // only when a target actually has a live rule, and once per repo. A @@ -3782,7 +3766,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } isDefaultBase = (prRepo, base) => base !== null && branches.get(prRepo) === base; } - deployments = recordMerged(deployments, observed, deployTargets, now(), landedOverride, isDefaultBase); + deployments = recordMerged(deployments, observed, deployTargets, now(), isDefaultBase); if (deployments !== beforeDeploy) { const fresh = Object.keys(deployments).filter((k) => beforeDeploy[k] === undefined); // A reconcile can also only drop a not-applicable watch (BB-132 @@ -4052,6 +4036,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (Object.keys(clear).length > 0) b = store.patch(b.id, clear); } const approvalEvents = await syncNeeds(b, observed, playbook, workerInFlight, changes); + // BB-264: `syncNeeds` records a derived stacked-PR merge hold on the + // binding; re-read it so the status below and the wake see the hold. + b = store.binding(b.id) ?? b; // BB-203: write the status the plugin observed itself, without a steward // turn, before the wake, so the page and sidebar are current within one // refetch. Checks fold into the phrase; approved, merged and deployed @@ -6889,6 +6876,31 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // A ticket's other linked pull requests (GitHub cross-references) only // mention it and must not file gate items here. const ownPulls = b.kind === "ticket" ? await ownPullKeys(b, store.workers(b.id), observed) : null; + // BB-264: the steward's own merge holds name open bindings in this + // project, or a stacked base pull request by its key; the plugin's + // derived stacked-PR holds are recomputed from the base pull requests on + // every look. An entry that names neither an open binding nor an open + // pull request is dropped, so a stale hold lifts itself. + const userMergeBehind: string[] = []; + for (const k of b.mergeBehind) { + const target = store.find(k, b.projectId); + if (target !== null && target.endedAt === null && target.id !== b.id) { + userMergeBehind.push(k); + continue; + } + const ref = parsePullRef(k); + const pull = ref === null ? null : await snapshot("github", `${ref.repo}#${ref.number}`).catch(() => null); + if (pull !== null && pull.kind === "pull" && lc(pull.state) !== "closed" && pull.pull?.merged !== true) userMergeBehind.push(k); + } + const derivedMergeBehind: string[] = []; + // A hold already on the binding is not news: the "Merge held" wake fires + // only on the look that first derives it, so an open base that stays open + // does not wake the steward on every doorbell and sweep. + const heldBefore = new Set(b.mergeBehind.map((k) => lc(k))); + // The base pull requests a retarget wake has already been sent for + // (BB-264), so the retarget wake is once per base pull request. + const retargetPulls = [...b.retargetPulls]; + const retargetBefore = new Set(retargetPulls.map((k) => lc(k))); for (const pull of observedPulls(b, observed)) { const url = pull.url ?? pull.key; if (ownPulls !== null && !pullBelongsToTicket(b, pull, ownPulls)) { @@ -6928,7 +6940,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // BB-256: a standing merge hold is not a stuck loop, so the plugin // files no Merge item and closes its own if one is open. A // steward-filed item (a refused merge) is always left alone. - const mergeHeld = b.mergeBehind.length > 0; + // BB-264: an open base pull request is the same hold, derived from + // the pull request's base rather than reported. + const ref = parsePullRef(pull.url ?? pull.key) ?? parsePullRef(url); + const base = bindingMayMerge(b, playbook) && ref !== null && !foreignOwner ? await pullBaseDisposition(ref, pull) : null; + const openBase = base !== null && base.kind === "open" ? base : null; + const mergedBase = base !== null && base.kind === "merged" ? base : null; + if (openBase !== null) derivedMergeBehind.push(openBase.key); + const mergeHeld = userMergeBehind.length > 0 || openBase !== null; if (foreignOwner) { const open = store.openNeeds(b.id).find((n) => n.kind === "merge" && n.url === url && n.filedBy === "plugin"); if (open !== undefined) store.closeNeed(open.id, "A teammate's pull request: its author merges after the owner's approval."); @@ -6936,24 +6955,40 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const open = store.openNeeds(b.id).find((n) => n.kind === "merge" && n.url === url && n.filedBy === "plugin"); if (open !== undefined) { const keys = mergeHoldKeys(b); - store.closeNeed(open.id, `held behind ${(keys.length > 0 ? keys : b.mergeBehind).join(", ")}`); + const held = [...userMergeBehind, ...(openBase === null ? [] : [openBase.key])]; + store.closeNeed(open.id, `held behind ${(keys.length > 0 ? keys : held).join(", ")}`); + } + if (openBase !== null && !heldBefore.has(lc(openBase.key))) { + changes.push({ text: `Merge held: ${pull.key} is stacked on ${openBase.key}, which is still open. The plugin files no Merge item; it merges once the base lands and the pull request is retargeted to the default branch.`, actionable: true }); + } + } else if (mergedBase !== null) { + // BB-264: GitHub does not retarget a stacked pull request when its + // base merges (the branch survives), so the base is the head of a + // merged pull request. File no Merge item and wake the steward once + // per base pull request to retarget it; the next look sees the + // default branch and merges. The rebase and push come first so the + // plugin never merges an un-rebased head while the checks of the + // old one are still green. + const open = store.openNeeds(b.id).find((n) => n.kind === "merge" && n.url === url && n.filedBy === "plugin"); + if (open !== undefined) store.closeNeed(open.id, `The base ${mergedBase.key} has merged; retarget to the default branch.`); + if (!retargetBefore.has(lc(mergedBase.key))) { + const prRef = ref === null ? pull.key : `${ref.repo}#${ref.number}`; + changes.push({ text: `Retarget ${pull.key}: its base ${mergedBase.key} has merged. Rebase it onto the default branch (\`git fetch origin && git rebase --onto origin/ \`), push, then retarget it (\`gh pr edit ${prRef} --base \`); the plugin merges it once the default branch is its base and the checks on the new head are green.`, actionable: true }); + retargetPulls.push(mergedBase.key); + retargetBefore.add(lc(mergedBase.key)); } } else if (store.openNeeds(b.id).some((n) => n.kind === "merge" && n.url === url && n.filedBy !== "plugin")) { // A steward-filed Merge item is a hand-off to a person (a worker // whose permission system refused the merge, or a refused plugin // merge): leave it alone and do not merge over it (BB-170/BB-257). } else if (!workerInFlight) { - const ref = parsePullRef(pull.url ?? pull.key) ?? parsePullRef(url); // Pause stewards is the kill switch: while it is on, the plugin // files the item a person can press but never merges (BB-257). const paused = (await settings.get()).paused; - // BB-257: only the repository's default branch. A stacked pull - // request's base is another pull request's branch, which may - // already be merged and left dead; the plugin must not squash-merge - // into it (that is how #290/#291/#293 were stranded). A stacked - // pull request keeps the plugin-filed Merge item and a person or - // worker merges it into its parent. - if (bindingMayMerge(b, playbook) && ref !== null && !paused && (await pullBaseIsDefault(ref, pull))) { + // BB-257: only the repository's default branch is merged by the + // plugin. A stacked pull request is held above, so it never + // squash-merges into a base branch that may be dead. + if (ref !== null && base !== null && base.kind === "default" && !paused) { // BB-257: the plugin takes the step the Merge item used to ask a // person for. A refusal for this exact gate is recorded on the // binding and not retried until the head or a gate input changes. @@ -6996,6 +7031,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P store.closeNeedByKey(b.id, "merge", url, `The gate is not met: ${g.missing ?? "unknown"}.`); } } + // BB-264: keep the derived stacked-PR holds in `mergeBehind` so the wake + // and the sidebar show them like a reported hold, and drop one the look + // no longer derives (the base landed, closed, or was retargeted). + const nextMergeBehind = [...new Set([...userMergeBehind, ...derivedMergeBehind])]; + if (nextMergeBehind.length !== b.mergeBehind.length || nextMergeBehind.some((k, i) => k !== b.mergeBehind[i])) { + b = store.patch(b.id, { mergeBehind: nextMergeBehind }); + } + const nextRetargetPulls = retargetPulls.slice(-20); + if (nextRetargetPulls.length !== b.retargetPulls.length || nextRetargetPulls.some((k, i) => k !== b.retargetPulls[i])) { + b = store.patch(b.id, { retargetPulls: nextRetargetPulls }); + } if (approvalRaised) await wakeProject(b.projectId, `an owner-reviewed pull request from ${b.entityKey}`, { digestDue: false }); // BB-231: a gate item filed this look may cover an open route-`user` // escalation or question; ask the project steward once, per new item. @@ -7884,21 +7930,32 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return /failed: 409\b/u.test(message) || /Head branch was modified/iu.test(message); } + /** Where a pull request's base branch points, for the stacked-PR hold (BB-264). */ + type BaseDisposition = + | { kind: "default" } + | { kind: "open"; key: string } + | { kind: "merged"; key: string } + | { kind: "other" }; + /** - * Whether a pull request targets its repository's default branch - * (BB-257). A stacked pull request's base is another pull request's - * branch, which may already be merged and dead; the plugin must not - * auto-merge into it, because the change would be off the default branch - * with no one involved. A stacked pull request keeps the plugin-filed - * Merge item and a person or worker merges it into its parent. A read of - * the default branch that fails is not the default (fail closed), so the - * item is filed. + * Where a pull request's base branch points (BB-264). The default branch + * merges through BB-257; the head branch of another open pull request is a + * merge hold behind that pull request; the head branch of a merged pull + * request means the stacked pull request must be retargeted to the default + * branch (GitHub does not retarget it here); a closed or unknown branch is + * an ordinary pull request. A read of the default branch that fails is not + * the default (fail closed), so a Merge item is filed. */ - async function pullBaseIsDefault(ref: { repo: string; number: number }, pull: EntitySnapshot): Promise { + async function pullBaseDisposition(ref: { repo: string; number: number }, pull: EntitySnapshot): Promise { const base = pull.pull?.base ?? null; - if (base === null || base === "") return false; + if (base === null || base === "") return { kind: "other" }; const def = await github.defaultBranch(ref.repo).catch(() => null); - return def !== null && def === base; + if (def !== null && def === base) return { kind: "default" }; + const basePull = await github.pullByHead(ref.repo, base).catch(() => null); + if (basePull === null) return { kind: "other" }; + if (basePull.merged) return { kind: "merged", key: basePull.key }; + if (lc(basePull.state) === "open") return { kind: "open", key: basePull.key }; + return { kind: "other" }; } /** @@ -9036,13 +9093,6 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .max(500) .optional() .describe('Pull-request stewards: the open pull request that replaces this one (owner/repo#N or its URL), opened on its own branch when this one could not merge as is. The binding moves to it: the gate, the Merge item and every later wake are about the replacement, and this pull request is closed by whoever opened the replacement. Report it once, as soon as the replacement is open.'), - landedIn: z - .string() - .trim() - .min(1) - .max(500) - .optional() - .describe('Ticket stewards: the base pull request (owner/repo#N or its URL) a stacked pull request landed in, when its own merge went into that pull request\'s branch rather than the default branch. The deployment carries-check then follows the base pull request\'s merge on the default branch, because a squash rewrote the stacked merge. Report it once the stacked pull request has merged into the base branch.'), mergeBehind: z .array(z.string().trim().min(1).max(100)) .max(20) @@ -9153,25 +9203,34 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P replacedNote = ` ${moved.binding.entityKey} replaces ${b.entityKey}: the gate, the Merge item and your wakes now follow it.`; b = moved.binding; } - // A stacked pull request that landed in a base pull request names it - // so the deployment carries-check follows that merge (BB-215). - const landedIn = input.landedIn === undefined ? undefined : parsePullRef(input.landedIn); - if (input.landedIn !== undefined && landedIn === null) return toolError(new Error(`landedIn must name a pull request as owner/repo#N or its URL; ${JSON.stringify(input.landedIn)} does not.`)); // BB-256: a merge hold names open bindings in this project, validated // the way steward_update's `behind` is: an unknown or ended key, or - // the binding itself, is refused whole. Each report replaces the set, - // and `mergeBehind: []` clears it. + // the binding itself, is refused whole. BB-264 also accepts the base + // pull request of a stack by its key (`owner/repo#N`), which may not + // be an adopted binding, when it is an open pull request. Each report + // replaces the set, and `mergeBehind: []` clears it. let mergeBehind: string[] | undefined; if (input.mergeBehind !== undefined) { const missing: string[] = []; const named: Binding[] = []; + const prKeys: string[] = []; for (const k of input.mergeBehind) { const other = store.find(k, b.projectId); - if (other === null || other.endedAt !== null || other.id === b.id) missing.push(k); - else if (!named.some((x) => x.id === other.id)) named.push(other); + if (other !== null && other.endedAt === null && other.id !== b.id) { + if (!named.some((x) => x.id === other.id)) named.push(other); + continue; + } + const ref = parsePullRef(k); + const pull = ref === null ? null : await snapshot("github", `${ref.repo}#${ref.number}`).catch(() => null); + if (pull !== null && pull.kind === "pull" && lc(pull.state) !== "closed" && pull.pull?.merged !== true) { + const key = `${ref!.repo}#${ref!.number}`; + if (!prKeys.some((x) => lc(x) === lc(key))) prKeys.push(key); + continue; + } + missing.push(k); } - if (missing.length > 0) return toolError(new Error(`Not an open binding in this project to hold the merge behind: ${missing.join(", ")}.`)); - mergeBehind = named.map((x) => x.entityKey); + if (missing.length > 0) return toolError(new Error(`Not an open binding or pull request in this project to hold the merge behind: ${missing.join(", ")}.`)); + mergeBehind = [...named.map((x) => x.entityKey), ...prKeys]; } // BB-231: a free-form escalation must say how it differs from every // open user-facing item on the binding, or it can duplicate the @@ -9391,7 +9450,6 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ...(input.noMorePulls === undefined ? {} : { noMorePulls: input.noMorePulls ? true : null }), ...(input.noMorePulls === false && b.noMorePulls === true && b.scheduleAsked.length > 0 ? { scheduleAsked: [] } : {}), ...(mergeBehind === undefined ? {} : { mergeBehind }), - ...(landedIn === undefined || landedIn === null ? {} : { landedIn: `${landedIn.repo}#${landedIn.number}` }), ...(b.ending === "terminal" ? { followThrough, followThroughUntil } : {}), }); // BB-255: the report supersedes any retry the plugin had pending, diff --git a/plugins/stewards/skill.test.ts b/plugins/stewards/skill.test.ts index a2a0915c..2884a454 100644 --- a/plugins/stewards/skill.test.ts +++ b/plugins/stewards/skill.test.ts @@ -61,3 +61,27 @@ describe("the shipped stewards skill's GitHub child filing (BB-250)", () => { expect(stewardsSkill).toContain("-F sub_issue_id="); }); }); + +// BB-264: a stack merges bottom-up, and the rule lives in the shipped skills +// rather than in each project's `.bb`. +const buildTicketsSkill = readFileSync(fileURLToPath(new URL("./skills/build-tickets/SKILL.md", import.meta.url)), "utf8"); + +describe("the shipped skills' stacked-PR rule (BB-264)", () => { + it("build-tickets waits for the base, then retargets and rebases --onto before the normal gate", () => { + expect(buildTicketsSkill).toContain("Wait for the base pull request to merge into the default branch"); + expect(buildTicketsSkill).toContain("gh pr edit --base "); + expect(buildTicketsSkill).toContain("git rebase --onto origin/ "); + expect(buildTicketsSkill).toContain("approval carry across the rebase"); + // The retired `landedIn` instruction is gone. + expect(buildTicketsSkill).not.toContain("landedIn"); + }); + + it("stewards has the ticket steward report mergeBehind and the project steward's bottom-up note", () => { + expect(stewardsSkill).toContain("A stacked pull request merges bottom-up"); + expect(stewardsSkill).toContain('steward_report { mergeBehind: ["owner/repo#"] }'); + expect(stewardsSkill).toContain("rebase it onto the default branch"); + expect(stewardsSkill).toContain("--onto origin/ "); + expect(stewardsSkill).toContain("A stack resolves bottom-up"); + expect(stewardsSkill).toContain("Never answer a schedule escalation by telling a stacked ticket"); + }); +}); diff --git a/plugins/stewards/skills/build-tickets/SKILL.md b/plugins/stewards/skills/build-tickets/SKILL.md index 19538f70..61c58139 100644 --- a/plugins/stewards/skills/build-tickets/SKILL.md +++ b/plugins/stewards/skills/build-tickets/SKILL.md @@ -100,19 +100,20 @@ the default branch: - Keep your own lane gate. The reviewer's verdict and, on an owner-reviewed change, the owner's approval are for your pull request; the base pull request's approval is not yours and never counts for it. -- When your own review approves and your checks are green, merge your pull - request into the base branch — not into the default branch — with - `bb stewards merge ` on your own gate. The base pull request - then lands on the default branch as one landing. +- **Wait for the base pull request to merge into the default branch.** While + it is open the plugin files no Merge item for yours: it is held behind the + base pull request, and the steward is woken with that hold. Do not merge + yours into the base branch, and do not merge the base pull request. +- When the base pull request merges, rebase yours onto the default branch + with `git rebase --onto origin/ ` (the squash + rewrote the base's commits), resolve any conflicts, and push; then retarget + it (`gh pr edit --base `). Rebase and push first, so the + plugin never merges the un-rebased head while the old head's checks are + still green. The plugin then merges yours through the normal gate; your + reviewer's verdict and the owner's approval carry across the rebase. - If the base pull request closes without merging, retarget yours to the default branch (`gh pr edit --base `, rebasing or merging the default branch as needed) and carry on as an ordinary pull request. -- When your stacked pull request merges into the base branch, say in your - final message that it landed in the base pull request - (`owner/repo#`). A squash rewrote your merge, so it is not an ancestor - of the default branch; the steward reports it with - `steward_report { landedIn: "owner/repo#" }` so the deployment - carries-check follows the base pull request's merge on the default branch. ## Test diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 55f040ca..7487289c 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -222,6 +222,24 @@ Two tools are yours; everything else you do with the tools every thread has. a line what they changed. A review steward treats a small follow-up push to a pull request it already approved as a short check of the new commits, not a full round, and does not turn the approval into a new verdict. +- **A stacked pull request merges bottom-up (BB-264).** When the ticket's + pull request is based on another pull request's branch rather than the + default branch, it is stacked: the base pull request merges to the default + branch first, and the stacked one is rebased onto the default branch and + merged after it. While the base is open, report the wait with + `steward_report { mergeBehind: ["owner/repo#"] }`; the plugin also + recognises a gate-met pull request whose base is another open pull + request's branch as held behind it, so it files no Merge item either way. + When the base merges, GitHub does not retarget the stacked pull request in + these repos: have the worker rebase it onto the default branch (`git rebase + --onto origin/ `), resolve conflicts and push, then + retarget it (`gh pr edit --base `). Rebase and push first, so + the plugin never merges the un-rebased head while the old head's checks are + still green. The reviewer's verdict and the owner's approval carry across + the rebase; the plugin then merges it through the normal gate. If the base pull request + closes without merging, retarget to the default branch and carry on as an + ordinary pull request. Never merge the stacked pull request into the base + branch. - **When a human must approve** (default; the project's guidance overrides it). A change that significantly modifies or removes existing behaviour, or is risky in kind — a cross-repo contract, auth, a migration, a secret, @@ -554,7 +572,11 @@ overlap is harmless, or the new ticket matters more (then hold the other one instead), let it start with `guidance` ("Start now: …") + `resolve`; it is not asked again until a new overlap appears. The bindings list in every wake shows touches and overlaps, so the same hold -sequences any two tickets, asked or not. A `stall` escalation is the +sequences any two tickets, asked or not. A stack resolves bottom-up: the +base pull request merges to the default branch first, and the stacked one is +retargeted and rebased onto the default branch after, then merged through the +normal gate. Never answer a schedule escalation by telling a stacked ticket +to merge into its base branch. A `stall` escalation is the plugin's too: a binding has woken by requeue several times with the same free-text `waitingOn` and no source the plugin tracks will deliver it. Answer it the way the wait needs: hold the binding behind something real diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index e0ae7afc..f6bab618 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -1,7 +1,7 @@ import Database from "better-sqlite3"; import { describe, expect, it } from "vitest"; import { z } from "zod"; -import { ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS, ASSUMPTION_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, DATED_WAIT_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_PR_MIGRATIONS, LESSON_TIER_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, MIGRATIONS, PULL_WATCH_MIGRATIONS, RATIONALE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, STACK_MIGRATIONS, VALIDATION_MIGRATIONS, WAKE_RETRY_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, WORKER_CHECK_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, createStore, lessonScope, statusRecordSchema, type Binding } from "./store.js"; +import { ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS, ASSUMPTION_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, DATED_WAIT_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_PR_MIGRATIONS, LESSON_TIER_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, MIGRATIONS, PULL_WATCH_MIGRATIONS, RATIONALE_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, STACK_MIGRATIONS, VALIDATION_MIGRATIONS, WAKE_RETRY_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, WORKER_CHECK_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, createStore, lessonScope, statusRecordSchema, type Binding } from "./store.js"; /** MIGRATIONS without the groups appended after the ones these order tests assert. */ const beforeActorMigrations = MIGRATIONS.slice(0, MIGRATIONS.indexOf(ACTOR_MIGRATIONS[0]!)); @@ -485,8 +485,9 @@ describe("the actor rename migration (BB-97)", () => { // it. BB-164 appended the pull-watch group after BB-184's server settings, // and BB-215's stack group follows it (migrations.test.ts pins the whole // list, this only checks the group order). - // BB-256 appended the merge-hold group after BB-255's wake-retry group. - const groups = [MERGE_BEHIND_MIGRATIONS, WAKE_RETRY_MIGRATIONS, DATED_WAIT_MIGRATIONS, ASSUMPTION_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, STACK_MIGRATIONS, PULL_WATCH_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, LESSON_PR_MIGRATIONS, ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS]; + // BB-256 appended the merge-hold group after BB-255's wake-retry group, + // and BB-264 appended the retarget-pulls column after that. + const groups = [RETARGET_PULLS_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, WAKE_RETRY_MIGRATIONS, DATED_WAIT_MIGRATIONS, ASSUMPTION_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, STACK_MIGRATIONS, PULL_WATCH_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, LESSON_PR_MIGRATIONS, ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS]; let end = MIGRATIONS.length; for (const group of groups) { expect(MIGRATIONS.slice(end - group.length, end)).toEqual([...group]); @@ -574,9 +575,12 @@ describe("the escalation route rename migration (BB-209)", () => { // provenance column) was appended after this one, BB-242's // worker-stop-reason column after that, BB-251's assumptions table after // that, BB-247's dated-wait columns after that, BB-255's wake-retry - // columns after that, and BB-256's merge-hold column after that. - const withMergeBehind = MIGRATIONS.slice(0, -MERGE_BEHIND_MIGRATIONS.length); - expect(MIGRATIONS.slice(-MERGE_BEHIND_MIGRATIONS.length)).toEqual([...MERGE_BEHIND_MIGRATIONS]); + // columns after that, BB-256's merge-hold column after that, and BB-264's + // retarget-pulls column after that. + const withRetarget = MIGRATIONS.slice(0, -RETARGET_PULLS_MIGRATIONS.length); + expect(MIGRATIONS.slice(-RETARGET_PULLS_MIGRATIONS.length)).toEqual([...RETARGET_PULLS_MIGRATIONS]); + const withMergeBehind = withRetarget.slice(0, -MERGE_BEHIND_MIGRATIONS.length); + expect(withRetarget.slice(-MERGE_BEHIND_MIGRATIONS.length)).toEqual([...MERGE_BEHIND_MIGRATIONS]); const withWakeRetry = withMergeBehind.slice(0, -WAKE_RETRY_MIGRATIONS.length); expect(withMergeBehind.slice(-WAKE_RETRY_MIGRATIONS.length)).toEqual([...WAKE_RETRY_MIGRATIONS]); const withDated = withWakeRetry.slice(0, -DATED_WAIT_MIGRATIONS.length); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 9571f8df..e11a9f7f 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -504,9 +504,10 @@ export const SERVER_SETTINGS_MIGRATIONS = [ export const PULL_WATCH_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN adopted_by TEXT`]; // Stack scheduling (BB-215): the open bindings whose pull request this hold -// waits for (a stack-wait; `hold_behind` waits for a merge or an end), and -// the base pull request a stacked pull request landed in, so the deployment -// carries-check follows that merge on the default branch. +// waits for (a stack-wait; `hold_behind` waits for a merge or an end). The +// `landed_in` column the same group adds is retired (BB-264) but kept: a +// tolerant reader ignores a value an existing binding already recorded, so no +// destructive migration is needed. // // The SDK records each migration's hash by index and refuses to start the // plugin when an index no longer matches, so a new group goes at the END of @@ -617,7 +618,14 @@ export const WAKE_RETRY_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN wake_retr // as no merge hold and behaves exactly as before. export const MERGE_BEHIND_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN merge_behind TEXT NOT NULL DEFAULT '[]'`]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS, ...ACTOR_MIGRATIONS, ...LESSON_PR_MIGRATIONS, ...REVIEWER_MODEL_MIGRATIONS, ...WAKE_SOURCE_MIGRATIONS, ...SERVER_SETTINGS_MIGRATIONS, ...PULL_WATCH_MIGRATIONS, ...STACK_MIGRATIONS, ...ESCALATION_ROUTE_MIGRATIONS, ...DEPS_DECISION_MIGRATIONS, ...WORKER_STOP_REASON_MIGRATIONS, ...ASSUMPTION_MIGRATIONS, ...DATED_WAIT_MIGRATIONS, ...WAKE_RETRY_MIGRATIONS, ...MERGE_BEHIND_MIGRATIONS]; +// BB-264: a stacked pull request whose base pull request has merged is woken +// once to retarget and rebase it onto the default branch. `retarget_pulls` +// holds the base pull request keys already woken about, so a base that stays +// merged until the worker acts does not wake the steward on every look. +// Additive and defaulted: an old row reads as nothing woken yet. +export const RETARGET_PULLS_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN retarget_pulls TEXT NOT NULL DEFAULT '[]'`]; + +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS, ...ACTOR_MIGRATIONS, ...LESSON_PR_MIGRATIONS, ...REVIEWER_MODEL_MIGRATIONS, ...WAKE_SOURCE_MIGRATIONS, ...SERVER_SETTINGS_MIGRATIONS, ...PULL_WATCH_MIGRATIONS, ...STACK_MIGRATIONS, ...ESCALATION_ROUTE_MIGRATIONS, ...DEPS_DECISION_MIGRATIONS, ...WORKER_STOP_REASON_MIGRATIONS, ...ASSUMPTION_MIGRATIONS, ...DATED_WAIT_MIGRATIONS, ...WAKE_RETRY_MIGRATIONS, ...MERGE_BEHIND_MIGRATIONS, ...RETARGET_PULLS_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -785,10 +793,10 @@ export type Binding = { * requests or ended. */ mergeBehind: string[]; + /** Base pull request keys this binding has already been woken to retarget (BB-264), so a stacked pull request whose base has merged is retargeted once. */ + retargetPulls: string[]; /** Entity keys of the bindings whose open pull request this hold waits for (a stack-wait, BB-215): it lifts when every one has opened a pull request, not when they merge. */ holdStack: string[]; - /** The base pull request a stacked pull request landed in (owner/repo#N, BB-215): the deployment carries-check follows its merge on the default branch, since a squash rewrote the stacked merge. Null when the work did not stack. */ - landedIn: string | null; /** Entity keys the project steward was last asked to schedule this binding against; asked again only for a new one. */ scheduleAsked: string[]; /** The gate has passed and nothing holds or schedules it: it is starting, whatever Linear still says, so others schedule against it. */ @@ -895,8 +903,8 @@ function rowToBinding(r: BindingRow): Binding { touches: json(z.array(z.string()), str("touches"), []), holdBehind: json(z.array(z.string()), str("hold_behind"), []), mergeBehind: json(z.array(z.string()), str("merge_behind"), []), + retargetPulls: json(z.array(z.string()), str("retarget_pulls"), []), holdStack: json(z.array(z.string()), str("hold_stack"), []), - landedIn: str("landed_in"), scheduleAsked: json(z.array(z.string()), str("schedule_asked"), []), clearedToStart: Number(r.cleared_to_start ?? 0) === 1, modelSteward: str("model_steward"), @@ -965,8 +973,8 @@ const COLUMNS = { touches: "touches", holdBehind: "hold_behind", mergeBehind: "merge_behind", + retargetPulls: "retarget_pulls", holdStack: "hold_stack", - landedIn: "landed_in", scheduleAsked: "schedule_asked", clearedToStart: "cleared_to_start", modelSteward: "model_steward", diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index 00c9ff90..08ee9350 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -391,7 +391,8 @@ describe("the nightly prompt", () => { expect(rules).toMatch(/targets the default branch/u); expect(rules).toMatch(/a ticket binding always does/u); expect(rules).toMatch(/`may` includes `merge`/u); - expect(rules).toMatch(/stacked pull request/u); + expect(rules).toMatch(/a stacked pull request is held behind its base pull request until that merges/u); + expect(rules).toMatch(/retargeted to the default branch and rebased/u); expect(rules).toMatch(/Do not file a Merge item/u); }); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 59427203..3390e4f9 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -44,7 +44,7 @@ export const STANDING_RULES = [ "- **A credential is a decision escalation the project steward forwards as a secret.** Raise it with `steward_report { escalate }`, naming the variable and purpose in `context`. Forward it with `resolution: \"secret\"` and either `writeEnv`/`worker` (the dotenv a worker reads) or `setting` (a plugin secret setting); the plugin spawns a requester thread that opens bb's secure form. `secret` is the only resolution even when the ticket or spec says the owner produces or seals it by hand, corrected at spec approval. Never paste a secret or route the user to a script.", "- **A finding that would stop the feature working once it ships**, or that changes what the ticket needs (a credential, an access, a contract), is escalated as a `decision` in the same turn, quoting the worker's words — never relayed as a follow-up. An escalation that asks the user to pick between fixed options carries `choices` (2-6 short labels) so the page shows one button each.", '- **A spec that says "do not merge before X is Done" is a merge hold.** Report it with `steward_report { mergeBehind: ["X"] }`, never as a `merge` need or as free text alone: while it stands the plugin files no Merge item (so the effort shows as held, not "needs you"), it is a live wake source, and it lifts itself, waking you, once every named binding has merged its pull requests or ended. Each report replaces the set, and `mergeBehind: []` clears it.', - "- **The plugin merges once the lane gate is met, when the pull request targets the default branch.** When a pull request's gate is met, no worker is in flight, and its base is the repository's default branch, the plugin squash-merges it if the binding's playbook permits `merge` — a ticket binding always does, a `pr` binding when its `may` includes `merge` — and wakes you with the merge so you proceed to the deployment watch. Do not file a Merge item for such a pull request: the item on the page is for a playbook that does not permit `merge`, for a stacked pull request whose base is another pull request's branch (the worker or a person merges it into its parent's branch while that pull request is open), or for a merge the plugin attempted and GitHub refused (a conflict or branch protection), which is also raised to the project steward.", + "- **The plugin merges once the lane gate is met, when the pull request targets the default branch.** When a pull request's gate is met, no worker is in flight, and its base is the repository's default branch, the plugin squash-merges it if the binding's playbook permits `merge` — a ticket binding always does, a `pr` binding when its `may` includes `merge` — and wakes you with the merge so you proceed to the deployment watch. Do not file a Merge item for such a pull request: the item on the page is for a playbook that does not permit `merge`, for a stacked pull request whose base is another pull request's branch (a stacked pull request is held behind its base pull request until that merges; it is then retargeted to the default branch and rebased, and the plugin merges it), or for a merge the plugin attempted and GitHub refused (a conflict or branch protection), which is also raised to the project steward.", ]; /** * The fixed first line of every brief, and of the per-turn system context the