diff --git a/plugins/stewards/migrations.snapshot.json b/plugins/stewards/migrations.snapshot.json index 3895b5cc..8bdf1d61 100644 --- a/plugins/stewards/migrations.snapshot.json +++ b/plugins/stewards/migrations.snapshot.json @@ -114,5 +114,6 @@ "d2ea8392b2f6d6ebdef23695c874c327f5de8948e7df1d7429e88783e1f14614", "a4c47117eadbd16a6521f838e277fe6b56dd463a81bcf64e26907ea56ae68361", "dab0f2a29dd1b4d8d65a58fb712c4d6689105d6c5bbe90e95dc3accff924c3f1", - "699df5c091ae8f12adf16a45faad54c866cd28c58963b3a9132ab6708617d35b" + "699df5c091ae8f12adf16a45faad54c866cd28c58963b3a9132ab6708617d35b", + "0cb5723b6d354beb4c2e6e60fabb5b5e3ddf0245bc755b3b4bcd3cbce6b6fd56" ] diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index bc1ff798..015709a8 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -8233,6 +8233,82 @@ describe("needs you items", () => { const b = t.hooks.store.find("acme/web#14", "p1")!; expect(t.hooks.store.openNeeds(b.id).filter((n) => n.kind === "merge").map((n) => n.url)).toEqual(["https://github.com/acme/web/pull/7"]); }); + + // BB-256: a steward can hold its own merge behind another binding. While the + // hold stands the plugin files no Merge item, the effort shows as held, and + // the hold lifts itself, waking the steward, once every named binding has + // merged its pull requests or ended. + describe("a steward's merge hold (BB-256)", () => { + const waitReport = (waitingOn: string, mergeBehind: string[]) => ({ ...base, waitingOn, mergeBehind }); + const blockedPull = (t: Awaited>, over: Record = {}) => { + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Blocker", labels: ["bb-managed"], author: "jane", ...over })); + }; + + it("stores the hold, refuses an unknown, self or ended key, and clears it with []", async () => { + 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) }); + // 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(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("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, owner]); + const b = t.binding(); + const pluginNeed = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "merge")!; + expect(pluginNeed.filedBy).toBe("plugin"); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Blocker" })); + await t.ring("linear", "uuid-13"); + const report = await t.tool("steward_report", waitReport("ENG-13 to be Done", ["ENG-13"]), t.steward); + expect(report.error, report.text).toBe(false); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["ENG-13"]); + expect(t.hooks.store.need(pluginNeed.id)).toMatchObject({ status: "done", resolution: "held behind ENG-13" }); + // The row shows as held, not "needs you", with the steward's wait text. + const sidebar = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as { bindings: Array<{ key: string; needsUser: boolean; hold: string | null; holdBehind: string[] }> }; + expect(sidebar.bindings.find((x) => x.key === "ENG-12")).toMatchObject({ needsUser: false, hold: "ENG-13 to be Done", holdBehind: ["ENG-13"] }); + // `bb stewards show` lists the merge hold alongside the start hold. + expect((await t.harness.behavior.runCli(["show", "ENG-12", "--project", "p1"])).stdout).toContain("MERGE HOLD: behind ENG-13"); + // The board row carries the same derived hold. + const board = (await t.harness.callRpc("stewardsBoard", { projectId: "p1" })) as { board: { stewards: Array<{ key: string; hold: string | null; holdBehind: string[]; needsUser: boolean }> } }; + expect(board.board.stewards.find((x) => x.key === "ENG-12")).toMatchObject({ hold: "ENG-13 to be Done", holdBehind: ["ENG-13"], needsUser: false }); + // The steward's own item (a refused merge) survives a fresh look. + const stewardNeed = t.hooks.store.fileNeed({ bindingId: b.id, kind: "merge", url: "https://github.com/acme/web/pull/7", what: "Merge acme/web#7", how: null, filedBy: "steward" }); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.need(stewardNeed.id)!.status).toBe("open"); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(false); + }); + + it("lifts when the target merges, notes it, wakes the steward, and files the Merge item on the next look", async () => { + const t = await withPull([marker, owner]); + const b = t.binding(); + blockedPull(t); + await t.ring("github", "acme/web#8"); + expect(t.hooks.store.find("acme/web#8")!.kind).toBe("pr"); + await t.tool("steward_report", waitReport("acme/web#8", ["acme/web#8"]), t.steward); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["acme/web#8"]); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); + const wakes = t.sends.filter((s) => s.threadId === t.steward).length; + // The target merges: the hold clears and the steward is woken with the note. + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Blocker", labels: ["bb-managed"], author: "jane", state: "merged" }, { merged: true, mergeCommit: "b".repeat(40) })); + await t.ring("github", "acme/web#8"); + expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual([]); + expect(t.sends.filter((s) => s.threadId === t.steward).length).toBeGreaterThan(wakes); + expect(t.sends.filter((s) => s.threadId === t.steward).at(-1)!.text).toMatch(/Merge hold lifted: acme\/web#8, which it waited behind, reached merged\./u); + // The next look files the Merge item again, so a stuck loop still surfaces. + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(true); + }); + }); }); // BB-69: the CLI lists the same "waiting on you" set the Stewards page and the @@ -13177,6 +13253,23 @@ describe("a wait with no wake source (BB-154)", () => { expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(false); }); + it("counts a merge hold as a live source: no mark and no stall across two requeues (BB-256)", async () => { + const { t, steward } = await bound(); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Blocker" })); + await t.ring("linear", "uuid-13"); + const report = { ...waitReport("ENG-13"), mergeBehind: ["ENG-13"] }; + await t.tool("steward_report", report, steward); + const b = t.hooks.store.find("ENG-12")!; + expect(b.mergeBehind).toEqual(["ENG-13"]); + expect(b.noWakeSource).toBe(false); + await requeue(t); + await t.tool("steward_report", report, steward); + await requeue(t); + await t.tool("steward_report", report, steward); + expect(t.hooks.store.find("ENG-12")!.requeueWakeCount).toBe(0); + expect(t.hooks.store.openEscalations(b.id).filter((x) => x.kind === "stall")).toHaveLength(0); + }); + it("raises one stall at the threshold, not again while it is open, and resets on a changed wake", async () => { const { t, steward } = await bound(); await t.tool("steward_report", waitReport("the vendor's reply"), steward); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 3d35f0a7..5ed7ab30 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -2324,6 +2324,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const sources: WakeSourceInput = { hold: b.hold, holdBehind: b.holdBehind, + mergeBehind: b.mergeBehind, holdStack: b.holdStack, deployments: b.deployments, runningWorkers: store.workers(b.id).filter((w) => w.status === "running").length, @@ -2334,6 +2335,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return hasLiveWakeSource(sources); } + /** + * The entity keys a binding's merge hold still waits on (BB-256): every + * named binding that has not yet merged its pull requests or ended. Used + * for the "held behind" close text; the hold itself stands while + * `mergeBehind` is non-empty, and the reconcile pass clears it once every + * target is finished. + */ + function mergeHoldKeys(b: Binding): string[] { + return b.mergeBehind.filter((k) => { + const target = store.find(k, b.projectId); + return target === null || target.lastSnapshot === null || !finished(target, target.lastSnapshot); + }); + } + /** * A thread's workspace branch, from its environment, or null when the * environment or its branch cannot be read. Cached once known: a thread's @@ -4018,6 +4033,19 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P b = store.binding(b.id) ?? b; } } + // BB-256: a merge hold is level-triggered the same way, so a hold placed + // after its targets finished lifts on this look rather than waiting for + // an edge that has already passed. Every target must satisfy `finished`; + // the release goes through releaseMergeBehind, so the wake and the note + // are the same as any other lift. + if (b.mergeBehind.length > 0) { + const projectId = b.projectId; + const targets = b.mergeBehind.map((k) => store.find(k, projectId)).filter((t): t is Binding => t !== null); + if (targets.length === b.mergeBehind.length && targets.every((t) => t.lastSnapshot !== null && finished(t, t.lastSnapshot))) { + for (const t of targets) await releaseMergeBehind(t, howFinished(t)); + b = store.binding(b.id) ?? b; + } + } // BB-215: a stack-wait lifts the moment the work it waits for opens a // pull request, or when that work ends without one. Both directions are // checked here: this binding's own open pull request (or ending) releases @@ -6396,6 +6424,31 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return "merged its pull requests"; } + /** + * The work a merge hold waits on has landed (BB-256): take `b`'s key off + * every merge hold that names it, and where nothing is left to wait for, + * clear the hold, note it on the held binding and wake its steward. The + * next look files the Merge item again if the pull request is still open + * with its gate met, so a stuck loop still surfaces. + */ + async function releaseMergeBehind(b: Binding, how: string): Promise { + const key = lc(b.entityKey); + const waiting = store.open(b.projectId).filter((h) => h.id !== b.id && h.mergeBehind.some((k) => lc(k) === key)); + if (waiting.length === 0) return; + for (const h of waiting) { + const rest = h.mergeBehind.filter((k) => lc(k) !== key); + if (rest.length > 0) { + store.patch(h.id, { mergeBehind: rest }); + store.note(h.id, `${b.entityKey} ${how}; your merge hold stays until ${rest.join(", ")} ${rest.length === 1 ? "does" : "do"} too.`, true); + continue; + } + store.patch(h.id, { mergeBehind: [] }); + store.note(h.id, `Merge hold lifted: ${b.entityKey}, which it waited behind, ${how}. The plugin files the Merge item again on the next look if the pull request is still open with its gate met.`); + scheduleReconcile(h.id); + } + bb.log.info(`stewards: ${b.entityKey} ${how}; released the merge hold on ${waiting.map((h) => h.entityKey).join(", ")}`); + } + /** * The work `b` was holding others behind has landed (`how`: its pull * requests merged, or it ended): take it off every hold that waits behind @@ -6407,6 +6460,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // A stack-wait on this binding lifts on the same endings: the work it // waited to stack on will not open a pull request now. await releaseStack(b, b.lastSnapshot, how); + // A merge hold on this binding lifts on the same endings (BB-256). + await releaseMergeBehind(b, how); const key = lc(b.entityKey); const waiting = store.open(b.projectId).filter((h) => h.id !== b.id && h.holdBehind.some((k) => lc(k) === key)); if (waiting.length === 0) return; @@ -6820,9 +6875,19 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (g.gateMet) { // A steward's own merge item (a refused merge) is left alone while a // worker still runs; the plugin files its own only when none does. + // 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; 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."); + } else if (mergeHeld) { + 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(", ")}`); + } } else if (!workerInFlight) { store.fileNeed({ bindingId: b.id, @@ -7880,8 +7945,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P noWakeSource: b.noWakeSource, wakeFailure: b.wakeFailure, priority: b.priority, - hold: b.hold, - holdBehind: b.holdBehind, + ...presentationHold(b), holdStack: b.holdStack, needsUser: needsUser(b), stuck: store.openEscalations(b.id).some((x) => x.kind === "stuck"), @@ -7982,8 +8046,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P noWakeSource: b.noWakeSource, wakeFailure: b.wakeFailure, priority: b.priority, - hold: b.hold, - holdBehind: b.holdBehind, + ...presentationHold(b), holdStack: b.holdStack, needsUser: needsUser(b), stuck: store.openEscalations(b.id).some((x) => x.kind === "stuck"), @@ -8087,8 +8150,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // child stays top-level (the client decides from the tab's own // list). parentKey: b.parentBindingId === null ? null : (store.binding(b.parentBindingId)?.entityKey ?? null), - hold: b.hold, - holdBehind: b.holdBehind, + ...presentationHold(b), holdStack: b.holdStack, waitingOn: b.status?.waitingOn ?? null, noWakeSource: b.noWakeSource, @@ -8810,6 +8872,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .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) + .optional() + .describe('A merge hold: entity keys of open bindings in this project whose work must finish before this binding\'s pull request is merged, like steward_update\'s behind. While it stands the plugin files no Merge item (so the page does not read as "needs you"), the binding shows as held, and it is a live wake source. Report it when a spec says "do not merge before X is Done"; the hold lifts itself, and you are woken, once every named binding has merged its pull requests or ended. Each report replaces the set; `mergeBehind: []` clears it.'), needs: z .array( z.object({ @@ -8919,6 +8986,22 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // 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. + let mergeBehind: string[] | undefined; + if (input.mergeBehind !== undefined) { + const missing: string[] = []; + const named: Binding[] = []; + 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 (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); + } // 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 // plugin's gate item. The pairwise judgement is forced here; no @@ -9136,6 +9219,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ...(input.touches === undefined ? {} : { touches: normalizeTouches(input.touches) }), ...(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 } : {}), }); @@ -9248,7 +9332,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bindingId: b.id, kind: "stall", question: `${b.entityKey} has woken by requeue ${count} time${count === 1 ? "" : "s"} with the same wait (${JSON.stringify(waitText)}), first reported ${iso(firstAt)}, and nothing the plugin tracks will deliver it.`, - context: `The steward's waitingOn is free text and no structured source is live on the binding: no open holdBehind, no deployment watch in merged/deploying, no running worker, no open escalation or need, no pull-request watch. It will keep waking by requeue alone.`, + context: `The steward's waitingOn is free text and no structured source is live on the binding: no open holdBehind, no merge hold, no deployment watch in merged/deploying, no running worker, no open escalation or need, no pull-request watch. It will keep waking by requeue alone.`, meanwhile: "Waiting: the steward keeps reporting the same wait and is woken only by another requeue.", route: "project", recommendation: null, @@ -10131,6 +10215,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P */ const rolesForBinding = (roleMap: Map, b: Binding): string[] => roleMap.get(b.entityId) ?? (b.adoptedBy === null ? [] : roleMap.get(b.adoptedBy)) ?? []; + /** + * The hold a row shows for a binding (BB-256): its start hold, or, when it + * has none but a merge hold stands, a merge hold behind the same keys. A + * merge hold ranks the effort as held (the existing hold tier) with the + * steward's `waitingOn` text rather than filing a Merge item, so the page + * does not read as "needs you". The stored field drives the plugin; this is + * presentation only. + */ + function presentationHold(b: Binding): { hold: string | null; holdBehind: string[] } { + if (b.hold !== null) return { hold: b.hold, holdBehind: b.holdBehind }; + if (b.mergeBehind.length > 0) return { hold: b.status?.waitingOn ?? "merge hold", holdBehind: b.mergeBehind }; + return { hold: null, holdBehind: [] }; + } + /** `rolesFor` names the role(s) whose definition owns a binding's target, for `bb stewards list` (BB-163). */ function formatBindings(rows: Binding[], rolesFor?: (b: Binding) => string[]): string { if (rows.length === 0) return "No bindings."; @@ -10152,7 +10250,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ? `cannot read the target: ${sentry.error}` : `looked ${iso(sentry.at)}: ${sentry.findings.length === 0 ? "nothing new" : `${sentry.findings.length} issue(s) new, regressed or rung`}`; const needs = store.openNeeds(b.id); - const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, watch, b.adoptedBy === null ? null : `adopted by ${b.adoptedBy}`, b.priority === null ? null : `priority ${b.priority}`, b.noMorePulls === true ? "no more pull requests" : null, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), ...needs.map((n) => `${n.kind} need ${n.id}${n.url === "" ? "" : ` (${n.url})`}`), unheardWait(s, open, needs), asksForOpenApproval(s, open, needs)].filter((f) => f !== null); + const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, watch, b.adoptedBy === null ? null : `adopted by ${b.adoptedBy}`, b.priority === null ? null : `priority ${b.priority}`, b.noMorePulls === true ? "no more pull requests" : null, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}`, b.mergeBehind.length === 0 ? null : `MERGE HOLD: behind ${b.mergeBehind.join(", ")}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), ...needs.map((n) => `${n.kind} need ${n.id}${n.url === "" ? "" : ` (${n.url})`}`), unheardWait(s, open, needs), asksForOpenApproval(s, open, needs)].filter((f) => f !== null); return `${b.entityKey} — ${b.kind}, ${b.phase ?? "?"}${roles.length === 0 ? "" : `, role ${roles.join(", ")}`}${b.threadId === null ? "" : `, thread ${b.threadId}`}\n ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${b.noWakeSource ? "; waiting, no wake source" : s.waitingOn === null ? "" : `; waiting on ${s.waitingOn}${b.requeueUntil === null ? "" : ` until ${iso(b.requeueUntil).slice(0, 10)}`}`}`}${flags.length > 0 ? `\n [${flags.join("; ")}]` : ""}`; }) .join("\n"); diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index 72b943c9..e0ae7afc 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, 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, 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,7 +485,8 @@ 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). - const groups = [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. + 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]; let end = MIGRATIONS.length; for (const group of groups) { expect(MIGRATIONS.slice(end - group.length, end)).toEqual([...group]); @@ -572,10 +573,12 @@ describe("the escalation route rename migration (BB-209)", () => { // The deps-decision group (the adoption-decision table and the fingerprint // 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, and BB-255's wake-retry - // columns after that. - const withWakeRetry = MIGRATIONS.slice(0, -WAKE_RETRY_MIGRATIONS.length); - expect(MIGRATIONS.slice(-WAKE_RETRY_MIGRATIONS.length)).toEqual([...WAKE_RETRY_MIGRATIONS]); + // 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]); + 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); expect(withWakeRetry.slice(-DATED_WAIT_MIGRATIONS.length)).toEqual([...DATED_WAIT_MIGRATIONS]); const withAssumptions = withDated.slice(0, -ASSUMPTION_MIGRATIONS.length); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 6dc992ab..9571f8df 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -607,7 +607,17 @@ export const DATED_WAIT_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN requeue_u // old row reads as no retry and no failure. export const WAKE_RETRY_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN wake_retry TEXT NOT NULL DEFAULT '{}'`, `ALTER TABLE bindings ADD COLUMN wake_failure TEXT`]; -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]; +// BB-256: a merge hold a steward reports with `steward_report { mergeBehind }`: +// entity keys of open bindings whose work must finish before this binding's +// pull request is merged. While it stands the plugin files no Merge item, so a +// deliberate wait is not read as a stuck loop; it lifts itself, waking the +// steward, once every named binding has merged its pull requests or ended. It +// is a live wake source (BB-154), so removing the Merge item does not leave the +// wait with nothing the plugin tracks. Additive and defaulted: an old row reads +// 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]; // ---- values kept as JSON ------------------------------------------------------------ @@ -767,6 +777,14 @@ export type Binding = { touches: string[]; /** Entity keys of the bindings this hold waits behind: the hold lifts itself when every one has merged its pull requests or ended. */ holdBehind: string[]; + /** + * Entity keys of the bindings whose work must finish before this binding's + * pull request is merged (BB-256), reported with `steward_report + * { mergeBehind }`. While it stands the plugin files no Merge item; it lifts + * itself, waking the steward, once every named binding has merged its pull + * requests or ended. + */ + mergeBehind: 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. */ @@ -876,6 +894,7 @@ function rowToBinding(r: BindingRow): Binding { hold: str("hold"), 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"), []), holdStack: json(z.array(z.string()), str("hold_stack"), []), landedIn: str("landed_in"), scheduleAsked: json(z.array(z.string()), str("schedule_asked"), []), @@ -945,6 +964,7 @@ const COLUMNS = { hold: "hold", touches: "touches", holdBehind: "hold_behind", + mergeBehind: "merge_behind", holdStack: "hold_stack", landedIn: "landed_in", scheduleAsked: "schedule_asked", @@ -1011,6 +1031,7 @@ const VISIBLE_COLUMNS = [ "phase", "hold", "hold_behind", + "merge_behind", "hold_stack", "status", "pending", diff --git a/plugins/stewards/wake-source.test.ts b/plugins/stewards/wake-source.test.ts index 7f16380c..87bccf0d 100644 --- a/plugins/stewards/wake-source.test.ts +++ b/plugins/stewards/wake-source.test.ts @@ -4,6 +4,7 @@ import { NO_STALL, STALL_WAKE_THRESHOLD, advanceStall, hasLiveWakeSource, parseU const noSources: WakeSourceInput = { hold: null, holdBehind: [], + mergeBehind: [], holdStack: [], deployments: {}, runningWorkers: 0, @@ -23,6 +24,11 @@ describe("a binding's live wake sources (BB-154)", () => { expect(hasLiveWakeSource(watch({ hold: "behind ENG-9", holdBehind: ["ENG-9"] }))).toBe(true); }); + it("is true for a merge hold (BB-256), with or without a start hold", () => { + expect(hasLiveWakeSource(watch({ mergeBehind: ["ENG-9"] }))).toBe(true); + expect(hasLiveWakeSource(watch({ hold: "Later", mergeBehind: ["ENG-9"] }))).toBe(true); + }); + it("is true for an open stack-wait (BB-215)", () => { expect(hasLiveWakeSource(watch({ hold: "stacked on ENG-9", holdStack: ["ENG-9"] }))).toBe(true); }); diff --git a/plugins/stewards/wake-source.ts b/plugins/stewards/wake-source.ts index 1f918bfe..23713e79 100644 --- a/plugins/stewards/wake-source.ts +++ b/plugins/stewards/wake-source.ts @@ -23,6 +23,8 @@ export type WakeSourceInput = { hold: string | null; /** Entity keys the hold waits behind; a hold with entries lifts itself when they land. */ holdBehind: readonly string[]; + /** Entity keys whose work must finish before this binding's pull request merges (BB-256); a merge hold with entries lifts itself when they land. */ + mergeBehind: readonly string[]; /** Entity keys whose open pull request the hold waits for (a stack-wait, BB-215); it lifts when one opens. */ holdStack: readonly string[]; /** Per-pull-request deployment watches; `merged` and `deploying` are the live ones. */ @@ -39,13 +41,15 @@ export type WakeSourceInput = { /** * Whether anything the plugin tracks will wake this binding. The list is the - * one in the ticket's criterion 1: an open `holdBehind` entry, a deployment - * watch in `merged`/`deploying`, a running worker, an open escalation or need, - * or a pull-request watch. A free-text `waitingOn` is not on it. + * one in the ticket's criterion 1: an open `holdBehind` entry, an open + * `mergeBehind` entry (BB-256), a deployment watch in `merged`/`deploying`, a + * running worker, an open escalation or need, or a pull-request watch. A + * free-text `waitingOn` is not on it. */ export function hasLiveWakeSource(s: WakeSourceInput): boolean { return ( (s.hold !== null && (s.holdBehind.length > 0 || s.holdStack.length > 0)) || + s.mergeBehind.length > 0 || Object.values(s.deployments).some((d) => d.state === "merged" || d.state === "deploying") || s.runningWorkers > 0 || s.openEscalations > 0 || diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index 1cc8f671..e80f9345 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -385,6 +385,17 @@ describe("the nightly prompt", () => { expect(STANDING_RULES.join("\n")).toMatch(/even when the ticket or spec says the owner produces or seals it by hand/u); }); + it("carries the merge hold rule and its line (BB-256)", () => { + expect(STANDING_RULES.join("\n")).toMatch(/do not merge before X is Done/u); + expect(STANDING_RULES.join("\n")).toMatch(/mergeBehind/u); + const { s, bind } = world(); + const b = bind("ENG-12"); + s.patch(b.id, { mergeBehind: ["ENG-13"] }); + const wake = formatWake(wakeInput({ binding: s.binding(b.id)! })); + expect(wake).toMatch(/MERGE HOLD: behind ENG-13/u); + expect(wake).toMatch(/files no Merge item while it stands/u); + }); + it("gives dates in the project's nightly time zone", () => { const { s } = world(); const q = s.ask({ projectId: "p1", bindingId: null, escalationId: null, question: "Freeze on Friday?", context: null }); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index caec5a6b..cd1c5fc4 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -43,6 +43,7 @@ export const STANDING_RULES = [ `- **What only the user can do is an escalation, not a need.** A credential, a step outside the repos, or a decision — ${ESCALATED_NEED_KINDS.map((k) => `\`${k}\``).join(", ")} — is raised with \`steward_report { escalate: { kind, question, context, meanwhile } }\`: the question is one line, as the sidebar row shows it, and the evidence and reasoning go in \`context\` (a longer question is refused). The project steward decides it or forwards it to the user. Since BB-30 \`steward_report { needs }\` refuses exactly those ("that is an escalation now"); it still takes the plugin's gate items (${STEWARD_NEED_KINDS.map((k) => `\`${k}\``).join(", ")}). A decision that is really a pick between fixed options carries \`choices\` (2-6 short labels, e.g. \`choices: ["Merge", "Close", "Verify first"]\`), and the page shows one button each; never write "reply with your choice" in prose.`, "- **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 fixed first line of every brief, and of the per-turn system context the @@ -464,6 +465,17 @@ const holdLine = (binding: Binding, then: string): string => { return `- **HOLD: ${binding.hold}**${why === "" ? "" : ` (${why})`} — ${then}`; }; +/** + * The merge-hold line of a wake (BB-256): no Merge item is filed while it + * stands, and the plugin wakes the steward once every named binding has merged + * its pull requests or ended. A separate line from `holdLine`, because a + * binding may carry both holds. + */ +const mergeHoldLine = (binding: Binding): string => { + const keys = binding.mergeBehind; + return `- **MERGE HOLD: behind ${keys.join(", ")}** — the plugin files no Merge item while it stands, so the effort shows as held. It lifts itself, and you are woken, once ${keys.length === 1 ? "that binding has" : "each of them has"} merged its pull requests or ended.`; +}; + /** * The sentence a no-wake-source paragraph carries when a `failed` watch is * holding the binding (BB-194): a settled watch will not wake the steward on @@ -490,7 +502,7 @@ function noWakeSourceLines(binding: Binding): string[] { const lines = [ "**Waiting with no wake source.** Nothing the plugin tracks will deliver this wait" + (wait === null ? "" : ` (${JSON.stringify(wait)})`) + - ": no hold behind anything, no deployment watch in merged/deploying, no running worker, no open escalation or need, and no pull-request watch. Name what will — a binding to hold behind, a pull request, a deployment target, a worker — or, if nothing can, the condition is your own to re-examine.", + ": no hold behind anything, no merge hold, no deployment watch in merged/deploying, no running worker, no open escalation or need, and no pull-request watch. Name what will — a binding to hold behind, a pull request, a deployment target, a worker — or, if nothing can, the condition is your own to re-examine.", ]; const failed = Object.values(binding.deployments) .filter((w) => w.state === "failed") @@ -592,6 +604,7 @@ export function formatWake(input: WakeInput): string { for (const g of binding.guidance) out.push(`- ${iso(g.at)} (${g.by}): ${g.text}`); out.push(`- Priority: ${binding.priority ?? "normal"}`); out.push(holdLine(binding, "take no new actions and start no workers until it is lifted.")); + if (binding.mergeBehind.length > 0) out.push(mergeHoldLine(binding)); out.push(...schedulingLines(binding, input.conflicts ?? [], input.escalations)); out.push(...trialLessonsLines(input.lessons ?? [])); out.push(...assumptionLines(input.assumptions ?? []));