Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion plugins/stewards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run.
exiting 0 when met and 1 when not. `bb stewards merge <owner/repo#N>` runs
the page's Merge action through one shared function: it re-reads the pull
request, re-checks the gate, refuses with the gate's reason when it is
unmet or another worker is in flight, and otherwise squash-merges, posts
unmet or another worker is mid-turn, and otherwise squash-merges, posts
the "Merged:" comment (lane, approved sha, a "since then" line when the
head moved past it, an escalation line when the reviewer escalated it to
the owner, the merge commit, and a restart note when the project's
Expand Down
135 changes: 124 additions & 11 deletions plugins/stewards/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1671,23 +1671,30 @@ describe("a Linear ticket steward", () => {
await t.idle("thr_w1", "Opened acme/web#7; waiting on the reviewer.");
expect(toSteward()).toHaveLength(before);

// The reviewer posts its marker as the developer (unsigned), checks
// finish, and the worker pushes: all the worker's, none of it wakes.
const marker = "<!-- bb-review round=1 sha=aaaaaaa verdict=approved lane=no-review -->";
t.entities.set("acme/web#7", pull({ author: "jane", comments: [comment({ id: "r1", author: "jane", body: marker, createdAt: "2026-10-14T16:00:00Z" })] }, { headAuthor: "jane", checks: { state: "success", failing: [] } }));
// Its own push is quiet too: the reviewer has not approved, so the gate is
// not met and nothing merges (BB-266 changed only the gate-met branch).
t.entities.set("acme/web#7", pull({ author: "jane" }, { headSha: "bbbbbbb2", headAuthor: "jane", checks: { state: "pending", failing: [] } }));
await t.ring("github", "acme/web#7");
expect(toSteward()).toHaveLength(before);

// The reviewer posts its marker as the developer (unsigned) and checks
// finish: the worker's own activity stays quiet, but the gate is now met,
// so the plugin merges (BB-266) and wakes the steward with the merge,
// carrying the quiet notes kept: the worker's finish and its own activity.
const marker = "<!-- bb-review round=1 sha=aaaaaaa verdict=approved lane=no-review -->";
t.entities.set("acme/web#7", pull({ author: "jane", comments: [comment({ id: "r1", author: "jane", body: marker, createdAt: "2026-10-14T16:00:00Z" })] }, { headSha: "bbbbbbb2", headAuthor: "jane", checks: { state: "success", failing: [] } }));
await t.ring("github", "acme/web#7");
expect(toSteward()).toHaveLength(before);
expect(t.githubMerges).toHaveLength(1);
const afterMerge = toSteward().slice(before);
const mergeWake = afterMerge.find((s) => /acme\/web#7 was merged by the plugin/u.test(s.text));
expect(mergeWake).toBeDefined();
expect(mergeWake!.text).toMatch(/Worker "ENG-12: Implement" finished its turn/u);
expect(mergeWake!.text).toMatch(/Opened acme\/web#7; waiting on the reviewer\./u);

// A teammate's comment is the wake, and it carries the quiet notes kept:
// the worker's finish and its own PR activity.
// A teammate's comment is the next wake.
t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked, comments: [comment({ createdAt: "2026-10-14T17:00:00Z" })] }));
await t.ring("linear", "uuid-12");
expect(toSteward()).toHaveLength(before + 1);
const wake = toSteward().at(-1)!.text;
expect(wake).toMatch(/Worker "ENG-12: Implement" finished its turn/u);
expect(wake).toMatch(/Opened acme\/web#7; waiting on the reviewer\./u);
expect(toSteward().length).toBeGreaterThan(before + afterMerge.length);
});

it("wakes for a reviewer round that changes the lane while a worker is in flight", async () => {
Expand Down Expand Up @@ -7201,6 +7208,112 @@ 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("a finished worker does not defer the plugin merge; a running one does (BB-266)", async () => {
// The reconcile pass: a worker parked "waiting on the owner's approval"
// (finished) cannot race a push, so the plugin merges.
const parked = await withPull([marker]);
await parked.created("thr_w1", parked.steward, "ENG-12: Implement");
parked.hooks.store.setWorker("thr_w1", "finished", "Waiting on the owner's approval.");
parked.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } }));
await parked.ring("linear", "uuid-12");
expect(parked.githubMerges).toHaveLength(1);

// The re-report path (syncNeedsFresh): the same parked worker does not
// hold the merge either.
const rereport = await withPull([marker]);
await rereport.created("thr_w1", rereport.steward, "ENG-12: Implement");
rereport.hooks.store.setWorker("thr_w1", "finished", "Waiting on the owner's approval.");
rereport.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } }));
await rereport.tool("steward_report", { phase: "In Progress", summary: "Watching the pull request.", nextAction: "Wait", actor: "steward" }, rereport.steward);
expect(rereport.githubMerges).toHaveLength(1);

// A running worker still defers it, at both call sites, and files no item.
const running = await withPull([marker]);
await running.created("thr_w1", running.steward, "ENG-12: Implement");
running.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } }));
await running.ring("linear", "uuid-12");
expect(running.githubMerges).toEqual([]);
expect(running.hooks.store.openNeeds(running.binding().id).some((n) => n.kind === "merge")).toBe(false);
await running.tool("steward_report", { phase: "In Progress", summary: "Watching the pull request.", nextAction: "Wait", actor: "steward" }, running.steward);
expect(running.githubMerges).toEqual([]);
});

it("the plugin merge archives the binding's parked workers (BB-266)", async () => {
const t = await withPull([marker]);
const b = t.binding();
await t.created("thr_parked", t.steward, "ENG-12: Implement");
t.hooks.store.setWorker("thr_parked", "finished", "Waiting on the owner's approval.");
// A finished worker's turn is over: its thread is idle, not active.
t.threads.get("thr_parked")!.status = "idle";
// A finished worker with an open question for the steward is left alone.
await t.created("thr_question", t.steward, "ENG-12: Ask");
t.hooks.store.setWorker("thr_question", "finished", "Should I open the follow-up ticket?");
t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } }));
await t.ring("linear", "uuid-12");
expect(t.githubMerges).toHaveLength(1);
// The parked worker is archived; the thread.archived event flips it stopped.
expect(t.threads.get("thr_parked")!.archivedAt).not.toBeNull();
await t.harness.behavior.emitThreadEvent("thread.archived", { thread: makeThreadResponse({ id: "thr_parked" }) });
await t.flush();
expect(t.hooks.store.worker("thr_parked")).toMatchObject({ status: "stopped", stopReason: "archived" });
// The one that asked a question stays for the steward to answer.
expect(t.threads.get("thr_question")!.archivedAt).toBeNull();
expect(t.hooks.store.worker("thr_question")).toMatchObject({ status: "finished", result: "Should I open the follow-up ticket?" });
// The merge filed no item for the parked worker to have been waiting on.
expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false);
});

it("a finished worker keeps deferring the plugin merge while another own pull request is open (BB-266)", async () => {
const t = await setup();
t.entities.set("uuid-12", issue({ linkedPulls: [
{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" },
{ key: "acme/api#8", url: "https://github.com/acme/api/pull/8" },
] }));
// #7 is gate met once the owner approves; #8 is still waiting on the owner.
t.entities.set("acme/web#7", pull({ comments: [marker] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } }));
t.entities.set("acme/api#8", pull({ id: "acme/api#8", key: "acme/api#8", url: "https://github.com/acme/api/pull/8", title: "Add api retry (ENG-12)" }, { head: "bb/eng-12-api", checks: { state: "success", failing: [] } }));
await t.ring("linear", "uuid-12");
const steward = t.spawns[1]!.id;
await t.created("thr_w1", steward, "ENG-12: Implement both");
t.hooks.store.setWorker("thr_w1", "finished", "Waiting on the owner's approval of acme/web#7 and acme/api#8.");
t.threads.get("thr_w1")!.status = "idle";
// The owner approves #7. The plugin must not merge it while #8 is still
// open, and must not retire the worker that owns the landing order.
t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } }));
await t.ring("linear", "uuid-12");
expect(t.githubMerges).toEqual([]);
expect(t.hooks.store.worker("thr_w1")).toMatchObject({ status: "finished" });
expect(t.threads.get("thr_w1")!.archivedAt).toBeNull();
// #7 has landed; #8 is now the only open own pull request, so the plugin
// merges it and retires the parked worker.
t.entities.set("acme/web#7", pull({ comments: [marker, owner], state: "merged" }, { head: "bb/eng-12-retry", merged: true, checks: { state: "success", failing: [] } }));
t.entities.set("acme/api#8", pull({ id: "acme/api#8", key: "acme/api#8", url: "https://github.com/acme/api/pull/8", title: "Add api retry (ENG-12)", comments: [marker, owner] }, { head: "bb/eng-12-api", checks: { state: "success", failing: [] } }));
await t.ring("linear", "uuid-12");
expect(t.githubMerges).toHaveLength(1);
expect(t.githubMerges[0]).toMatchObject({ repo: "acme/api", number: 8 });
expect(t.threads.get("thr_w1")!.archivedAt).not.toBeNull();
});

it("a finished worker does not suppress the fallback Merge item when the playbook omits merge (BB-266)", async () => {
const t = await setup();
t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] } });
t.files[playbookPath("deps-prs")] = DEPS_PRS;
t.entities.set("acme/web#9", pull({ id: "acme/web#9", key: "acme/web#9", url: "https://github.com/acme/web/pull/9", title: "deps: bump the npm group", author: "dependabot[bot]", labels: [] }, { head: "dependabot/npm/group", headAuthor: "dependabot[bot]" }));
await t.hooks.sweep();
await t.flush();
const b = t.hooks.store.find("acme/web#9")!;
expect(b).toMatchObject({ kind: "pr", playbook: "deps-prs" });
// A parked worker, waiting on the owner's approval, must not suppress the
// fallback Merge item: the playbook omits merge, so a person merges.
t.hooks.store.addWorker("thr_parked", b.id, "Watch the dependency bump");
t.hooks.store.setWorker("thr_parked", "finished", "Waiting on the owner's approval.");
const noReview = comment({ id: "r1", author: "jane", body: `<!-- bb-review round=1 sha=${head} verdict=approved lane=no-review -->`, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" });
t.entities.set("acme/web#9", pull({ id: "acme/web#9", key: "acme/web#9", url: "https://github.com/acme/web/pull/9", title: "deps: bump the npm group", author: "dependabot[bot]", labels: [], comments: [noReview] }, { head: "dependabot/npm/group", headAuthor: "dependabot[bot]", checks: { state: "success", failing: [] } }));
await t.ring("github", "acme/web#9");
expect(t.githubMerges).toEqual([]);
expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(true);
});

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();
Expand Down
55 changes: 43 additions & 12 deletions plugins/stewards/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2905,15 +2905,32 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
*/
async function archiveFinishedWorkers(b: Binding): Promise<void> {
if (needsUser(b)) return;
const candidates = store.workers(b.id).filter((w) => w.status === "finished" && workerQuestion(w.result) === null && !workerWaiting(w.result));
await archiveWorkers(store.workers(b.id).filter((w) => w.status === "finished" && workerQuestion(w.result) === null && !workerWaiting(w.result)));
}

/**
* Retire the binding's parked `finished` workers (BB-266). The plugin's
* own merge consumed the approval they were waiting on, so they are done,
* not parked; only one that asked the steward a question stays visible.
* Unlike `archiveFinishedWorkers` this does not wait for the binding to
* need nobody: the merge has settled their reason to stay.
*/
async function archiveParkedWorkers(b: Binding): Promise<void> {
await archiveWorkers(store.workers(b.id).filter((w) => w.status === "finished" && workerQuestion(w.result) === null));
}

/**
* Archive the given finished workers unless one still has an unarchived
* child. A worker whose reviewer is still unarchived must stay: bb core
* releases a thread's unarchived children from it when it is archived,
* so archiving the worker would clear the reviewer's parent: it could
* no longer wake the worker, and no later pass could find it to archive
* it. One batched descendant lookup covers every candidate (BB-100); a
* listing that failed is "unknown", so all the workers wait rather than
* risking an orphan (BB-47).
*/
async function archiveWorkers(candidates: readonly Worker[]): Promise<void> {
if (candidates.length === 0) return;
// A worker whose reviewer is still unarchived must stay. bb core
// releases a thread's unarchived children from it when it is archived,
// so archiving the worker would clear the reviewer's parent: it could
// no longer wake the worker, and no later pass could find it to archive
// it. One batched descendant lookup covers every candidate (BB-100); a
// listing that failed is "unknown", so all the workers wait rather than
// risking an orphan (BB-47).
const descendants = await descendantsOfMany(candidates.map((w) => w.threadId));
if (descendants === null) return;
for (const w of candidates) {
Expand Down Expand Up @@ -4035,7 +4052,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
if (b.scheduleAsked.length > 0) clear.scheduleAsked = [];
if (Object.keys(clear).length > 0) b = store.patch(b.id, clear);
}
const approvalEvents = await syncNeeds(b, observed, playbook, workerInFlight, changes);
const approvalEvents = await syncNeeds(b, observed, playbook, 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;
Expand Down Expand Up @@ -6841,7 +6858,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
* every look, so the page only offers a button while it is true. The
* `approve-pr` half lives in approvals.ts (BB-153).
*/
async function syncNeeds(b: Binding, observed: Observed, playbook: Playbook, workerInFlight: boolean, changes: Change[] = []): Promise<MechanicalEvent[]> {
async function syncNeeds(b: Binding, observed: Observed, playbook: Playbook, changes: Change[] = []): Promise<MechanicalEvent[]> {
// BB-203: an `approve-pr` item this call closes because an approval is
// present is a mechanical status event. The page and project-steward
// paths write it at once; this catches an approval observed on GitHub.
Expand Down Expand Up @@ -6876,6 +6893,13 @@ 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-266: the binding's open own pull requests. A finished worker keeps
// deferring the plugin merge while more than one is open: a parked
// worker that still owns another pull request is mid-sequence (a
// cross-repo ticket lands the consumed repo first), so the plugin must
// not merge out of order or retire the worker that owns the rest.
const openOwnPulls = observedPulls(b, observed).filter((p) => (ownPulls === null || pullBelongsToTicket(b, p, ownPulls)) && p.pull?.merged !== true && lc(p.state) !== "closed");
const parkedWorkerOwnsAnother = openOwnPulls.length > 1 && store.workers(b.id).some((w) => w.status === "finished");
// 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
Expand Down Expand Up @@ -6981,7 +7005,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
// 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) {
} else if (runningWorkerReason(store.workers(b.id)) === null && !parkedWorkerOwnsAnother) {
// 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;
Expand All @@ -7003,6 +7027,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
store.note(b.id, note);
changes.push({ text: note, actionable: true });
scheduleReconcile(b.id);
// BB-266: the approval this merge consumed was what the
// binding's parked workers waited on, so retire them the way
// a consumed finish is retired; one that asked the steward a
// question stays visible. Only when no other own pull
// request is still open, so the worker that owns the rest is
// not retired mid-sequence.
if (openOwnPulls.length <= 1) await archiveParkedWorkers(b);
} else if (isHeadMovedRefusal(result.message)) {
// A push landed between the look and the merge. GitHub
// refused it with 409; the next look judges the new head.
Expand Down Expand Up @@ -7071,7 +7102,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
// falling back to the stored snapshot when the read fails (BB-54).
const fresh = await freshObserved(b);
const observed = fresh?.observed ?? b.lastSnapshot;
if (observed !== null) await syncNeeds(b, observed, playbook, anyWorkerInFlight(store.workers(b.id)));
if (observed !== null) await syncNeeds(b, observed, playbook);
}

/**
Expand Down
Loading
Loading