From 6c857e761998c0fad46cb2e4cedf4e459f4ec07a Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sun, 25 Oct 2026 20:05:54 +0000 Subject: [PATCH 1/2] stewards: fewer project steward turns (BB-54) Add a steward_report noMorePulls field and a finished() notion, so a hold lifts silently (a note on the held binding and the project steward's next digest) only when the work waited on is finished; any other lift wakes the project steward as before. When one lift frees overlapping waiters, release the first by priority then age and re-hold the rest behind it. Re-read the conflicting bindings' pull requests from GitHub before filing a schedule request, treat merged-with-more-to-come as still at work, and re-run the overlap check when a ticket past its ready gate links a new pull request. Show the project's standing-rules list (a new optional standingRules key in .bb/stewards/project.json) in the approval wake, and carry a spec decline's objections to the ticket steward as a checklist, forwarding a repeated objection to the user. Additive, nullable migrations: no_more_pulls, declined_spec_objections and project_stewards.pending_notes; an old row reads as not reported. --- plugins/stewards/README.md | 34 ++++-- plugins/stewards/config.test.ts | 11 ++ plugins/stewards/config.ts | 6 + plugins/stewards/schedule.test.ts | 8 +- plugins/stewards/schedule.ts | 48 ++++++-- plugins/stewards/server.test.ts | 120 ++++++++++++++++++- plugins/stewards/server.ts | 134 ++++++++++++++++++++-- plugins/stewards/skills/stewards/SKILL.md | 21 +++- plugins/stewards/store.ts | 39 ++++++- plugins/stewards/wake.test.ts | 14 +++ plugins/stewards/wake.ts | 20 ++++ 11 files changed, 416 insertions(+), 39 deletions(-) diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 5e1fe526..39adcd2f 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -117,14 +117,24 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. or lets it start (guidance + resolve, not asked again until a new overlap appears). A hold placed `behind` lifts itself once every binding named has merged its pull requests or ended: the held steward is woken with a - note to rebase, and the project steward is told. A binding reaching a - terminal state, or detached, releases what waits behind it as its ending - begins, so a steward that follows through for hours holds nobody up. A - hold that would form a cycle is refused. Work whose pull requests have all - merged no longer counts as in flight; a ticket whose gate has passed with - nothing holding or scheduling it counts as in flight already, so two - tickets going ready in the same minute schedule against each other rather - than racing to In Progress. `bb stewards show` prints + note to rebase. The project steward is told only when the work waited on + is not finished — its ticket not terminal and its steward not reporting + `steward_report { noMorePulls: true }` after every linked pull request + merged; a finished-work lift is a note on the held binding and the + project steward's next digest, and starts no turn. When one lift frees + two waiters that overlap each other, the first by priority then age is + released and the rest are held behind it. A binding reaching a terminal + state, or detached, releases what waits behind it as its ending begins, + so a steward that follows through for hours holds nobody up. A hold that + would form a cycle is refused. Work whose pull requests have all merged + and whose steward reported no more are coming no longer counts as in + flight; merged with no such report is still at work, because the next + pull request would conflict. Before filing a request the plugin re-reads + the conflicting bindings' pull requests from GitHub, and a ticket past + its ready gate that links a new pull request re-runs the check. A ticket + whose gate has passed with nothing holding or scheduling it counts as in + flight already, so two tickets going ready in the same minute schedule + against each other rather than racing to In Progress. `bb stewards show` prints what a binding touches and overlaps; the project steward's wake lists both for every binding. Everything else is the tools every thread has: `linear_*`, `gh`, and `bb thread spawn` / `tell` for workers, which stewards recognizes as @@ -218,7 +228,13 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. the approver declines is not made again until the spec changes, and while one is open the steward is told not to ask the user again: the request is on the Stewards page, and a report that asks anyway shows as a playbook - violation in `bb stewards show`. When the entity changes while one of its + violation in `bb stewards show`. The project file's optional + `standingRules` list is shown in the approval wake, so the project + steward adds only the limits a change needs, in at most three points, + instead of restating rules that already bind every pull request. A + decline's objections are carried to the ticket steward as a checklist; + the same objection declined twice is forwarded to the user rather than a + third round. When the entity changes while one of its escalations is with you, the project steward is woken with the change too, since you may have answered on the ticket rather than in its thread. A status blocked on the project steward or the user with no open diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index a2ff66ff..7b968c70 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -46,6 +46,17 @@ describe("the project file", () => { expect(badDuration).toMatchObject({ ok: false }); if (!badDuration.ok) expect(badDuration.error).toMatch(/deps\.sla\.high/u); }); + + it("takes the standing-rules list, and rejects an unknown key (BB-54)", () => { + const defaults = parseProjectFile(JSON.stringify({ version: 1 })); + if (!defaults.ok) throw new Error(defaults.error); + expect(defaults.value.standingRules).toEqual([]); + const withRules = parseProjectFile(JSON.stringify({ version: 1, standingRules: ["Migrations are append-only.", "No secrets in logs."] })); + if (!withRules.ok) throw new Error(withRules.error); + expect(withRules.value.standingRules).toEqual(["Migrations are append-only.", "No secrets in logs."]); + expect(parseProjectFile(JSON.stringify({ version: 1, standingRule: ["typo"] }))).toMatchObject({ ok: false }); + expect(parseProjectFile(JSON.stringify({ version: 1, standingRules: [""] }))).toMatchObject({ ok: false }); + }); }); describe("ops in the project file", () => { diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index 3ac5de14..d7d4e58b 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -250,6 +250,12 @@ export const projectFileSchema = z * stewards and the project steward, from the project's own guidance. */ bigDecisions: z.array(decideEntrySchema).max(60).default(() => defaultDecideList()), + /** + * The limits that already bind every pull request in this project, shown + * in an approval wake so the project steward adds only what they do not + * cover. Short rule lines; the plugin hard-codes none. + */ + standingRules: z.array(z.string().trim().min(1).max(400)).max(40).default([]), /** * Production to watch: one ops binding per target, which files a Linear * ticket for each problem it finds and escalates it to the project diff --git a/plugins/stewards/schedule.test.ts b/plugins/stewards/schedule.test.ts index e2166dd9..88062615 100644 --- a/plugins/stewards/schedule.test.ts +++ b/plugins/stewards/schedule.test.ts @@ -40,19 +40,23 @@ describe("conflicts", () => { const held = s.patch(bind("ENG-13", { touches: ["web/src"] }).id, { hold: "Later." }); bind("ENG-14", { stage: "spec", touches: ["web/src"] }); bind("ENG-15", { touches: ["api"] }); - const landed = s.patch(bind("ENG-16", { touches: ["web/src"] }).id, { lastSnapshot: { entity: issue({ linkedPulls: [{ key: "acme/web#7", url: "u" }] }), pulls: [pull({ state: "merged" }, { merged: true })] } }); + const landed = s.patch(bind("ENG-16", { touches: ["web/src"] }).id, { noMorePulls: true, lastSnapshot: { entity: issue({ linkedPulls: [{ key: "acme/web#7", url: "u" }] }), pulls: [pull({ state: "merged" }, { merged: true })] } }); + // Merged but not reported finished: a next pull request may still come, so it is still at work (BB-54). + const landedNoReport = s.patch(bind("ENG-21", { touches: ["web/src"] }).id, { lastSnapshot: { entity: issue({ linkedPulls: [{ key: "acme/web#8", url: "u" }] }), pulls: [pull({ state: "merged" }, { merged: true })] } }); const child = bind("ENG-17", { touches: ["web/src"], parent: me.id }); bind("ENG-18", { touches: ["web/src"], project: "p2" }); const ended = s.patch(bind("ENG-19", { touches: ["web/src"] }).id, { endedAt: T, endReason: "terminal" }); expect(atWork(held)).toBe(false); expect(atWork(landed)).toBe(false); + expect(atWork(landedNoReport)).toBe(true); expect(atWork(ended)).toBe(false); expect(atWork(child)).toBe(true); expect(conflictsOf(me, s.open()).map((c) => [c.with.entityKey, c.on])).toEqual([ ["ENG-11", ["web/src/login"]], ["ENG-12", ["web/src/signup"]], + ["ENG-21", ["web/src"]], ]); - expect(conflictsOf(building, s.open()).map((c) => c.with.entityKey)).toEqual(["ENG-17"]); + expect(conflictsOf(building, s.open()).map((c) => c.with.entityKey)).toEqual(["ENG-21", "ENG-17"]); expect(conflictsOf(s.patch(me.id, { touches: [] }), s.open())).toEqual([]); }); diff --git a/plugins/stewards/schedule.ts b/plugins/stewards/schedule.ts index 28024075..09cabf1e 100644 --- a/plugins/stewards/schedule.ts +++ b/plugins/stewards/schedule.ts @@ -35,39 +35,67 @@ export function touchesOverlap(a: readonly string[], b: readonly string[]): stri return [...hits].sort(); } +/** + * Whether a binding's work is finished: every pull request it links has + * merged, and either the entity reached a terminal state or its steward + * reported no more are coming. A merged pull request is the whole work for a + * `pr` binding. Unreported means not finished, so the project steward is + * woken rather than a hold lifting silently. + */ +export function finished(b: Binding, observed: Observed): boolean { + if (!allPullsMerged(b, observed)) return false; + if (b.kind === "pr") return true; + return b.endedAt !== null || b.ending === "terminal" || b.noMorePulls === true; +} + +/** What a caller knows beyond the binding's last snapshot: whether a worker is still running. */ +export type AtWorkOptions = { runningWorker?: boolean }; + /** * Whether a binding is at work on its touches: being built or reviewed, or * cleared to start (its gate passed, nothing holds or schedules it: the * steward is moving it and starting a worker, and Linear's state reaches the - * plugin a look later); not held, not ending, not ended, and its pull - * requests not all merged yet (work that has landed is what the next ticket - * rebases onto, not a conflict). + * plugin a look later); not held, not ending, not ended, and not finished + * with no worker still running. A ticket whose pull requests have merged but + * whose steward has not reported that no more are coming is still at work: + * the next pull request is a conflict, not a rebase. */ -export const atWork = (b: Binding): boolean => +export const atWork = (b: Binding, opts: AtWorkOptions = {}): boolean => b.endedAt === null && b.ending === null && b.hold === null && (b.stage === "build" || b.stage === "review" || b.clearedToStart) && b.touches.length > 0 && - !(b.lastSnapshot !== null && allPullsMerged(b, b.lastSnapshot)); + !(b.lastSnapshot !== null && finished(b, b.lastSnapshot) && opts.runningWorker !== true); export type Conflict = { with: Binding; on: string[] }; /** - * The open bindings of the same project already at work on what `b` touches, - * oldest first. `b` itself, its ancestors and descendants are left out: a - * promoted sub-issue shares its parent's paths by design. + * The open bindings of the same project whose touches overlap `b`'s, oldest + * first, without judging whether they are at work. `b` itself, its ancestors + * and descendants are left out: a promoted sub-issue shares its parent's + * paths by design. The server filters these with a fresh GitHub read before + * filing a schedule request. */ -export function conflictsOf(b: Binding, open: readonly Binding[]): Conflict[] { +export function overlapping(b: Binding, open: readonly Binding[]): Conflict[] { if (b.touches.length === 0) return []; const related = (other: Binding) => other.id === b.id || other.parentBindingId === b.id || b.parentBindingId === other.id; return open - .filter((other) => other.projectId === b.projectId && !related(other) && atWork(other)) + .filter((other) => other.projectId === b.projectId && !related(other)) .map((other) => ({ with: other, on: touchesOverlap(b.touches, other.touches) })) .filter((c) => c.on.length > 0) .sort((x, y) => x.with.createdAt - y.with.createdAt); } +/** + * The open bindings of the same project already at work on what `b` touches, + * oldest first, judged from the last snapshot alone. Rendering and tests use + * this; the schedule request path re-reads GitHub first (BB-54). + */ +export function conflictsOf(b: Binding, open: readonly Binding[]): Conflict[] { + return overlapping(b, open).filter((c) => atWork(c.with)); +} + /** * Whether a binding's pull requests have all merged: at least one is * observed, and every one is merged. A ticket with no pull request yet is not diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 7d0e207b..e7654089 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -1188,7 +1188,9 @@ describe("scheduling overlapping work", () => { expect(toSecond().length).toBe(stewardWakes + 1); expect(toSecond().at(-1)!.text).toMatch(/Hold lifted: ENG-12, which it waited behind, merged its pull requests\. Rebase anything already branched before building on\./u); expect(toSecond().at(-1)!.text).toMatch(/- Hold: none/u); - expect(toSecond().at(-1)!.text).not.toMatch(/In flight on the same paths/u); + // Merged but with no "no more pull requests" report: still at work, so the + // overlap is shown and the project steward is woken, not a silent lift (BB-54). + expect(toSecond().at(-1)!.text).toMatch(/In flight on the same paths: ENG-12/u); expect(toProject().at(-1)!.text).toMatch(/^# Project steward: ENG-12 merged its pull requests\n\n- Lifted the hold on ENG-13: ENG-12, which it waited behind, merged its pull requests\./u); // Landed work is no longer a conflict, so nothing asks again. await t.tool("steward_report", ready, second); @@ -1225,13 +1227,17 @@ describe("scheduling overlapping work", () => { // Done and the merge arrive in one ring: the hold lifts as the ending begins, not after a wrap-up turn that may follow through for hours. t.entities.set("acme/web#7", pull({ state: "merged" }, { merged: true })); t.entities.set("uuid-12", issue({ state: "Done", stateType: "completed", ...linked })); + const projectWakes = toProject().length; await t.ring("linear", "uuid-12"); expect(t.hooks.store.find("ENG-12")!.ending).toBe("terminal"); expect(t.hooks.store.find("ENG-13")!.hold).toBeNull(); - expect(toProject().at(-1)!.text).toMatch(/Lifted the hold on ENG-13: ENG-12, which it waited behind, reached Done/u); + // Terminal with its pull requests merged: finished, so the lift is silent + // and written to the project steward's record for the next digest (BB-54). + expect(toProject().length).toBe(projectWakes); + expect(t.hooks.store.project("p1").pendingNotes.join("\n")).toMatch(/Lifted the hold on ENG-13: ENG-12, which it waited behind, reached Done/u); await t.idle(t.spawns[1]!.id, "Done."); expect(t.hooks.store.find("ENG-12")!.endedAt).not.toBeNull(); - expect(toProject().filter((s) => /Lifted the hold on ENG-13/u.test(s.text))).toHaveLength(1); + expect(toProject().filter((s) => /Lifted the hold on ENG-13/u.test(s.text))).toHaveLength(0); }); it("asks from a look, without a turn of the steward's, when the overlap appears after the gate passed", async () => { @@ -1305,6 +1311,114 @@ describe("scheduling overlapping work", () => { await t.flush(); expect(t.hooks.store.find("ENG-12")!.clearedToStart).toBe(false); }); + + // BB-54: the lift is silent only when the work waited on is finished; a lift + // that leaves it unfinished wakes the project steward, as today. + it("wakes the project steward when a hold lifts because the work ended without merging", async () => { + const { t, project, second, toProject } = await two(); + await t.tool("steward_report", ready, second); + await t.tool("steward_update", { binding: "ENG-13", hold: "After ENG-12", behind: ["ENG-12"] }, project); + await t.flush(); + const wakes = toProject().length; + t.entities.set("uuid-12", issue({ state: "Canceled", stateType: "canceled" })); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.find("ENG-13")!.hold).toBeNull(); + expect(toProject().length).toBeGreaterThan(wakes); + expect(toProject().at(-1)!.text).toMatch(/Lifted the hold on ENG-13: ENG-12, which it waited behind, reached Canceled/u); + }); + + // BB-54: one lift that frees two waiters overlapping each other releases the + // first by priority then age and re-holds the rest behind it. + it("re-holds the second of two overlapping waiters released by one lift behind the first", async () => { + const { t, project, second, toProject } = await two(); + t.entities.set("uuid-14", issue({ id: "uuid-14", key: "ENG-14", title: "Audit log", state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-14"); + const third = t.spawns[3]!.id; + await t.tool("steward_report", { ...building, touches: ["web/src/audit"] }, third); + await t.tool("steward_report", ready, second); + await t.tool("steward_update", { binding: "ENG-13", hold: "After ENG-12", behind: ["ENG-12"] }, project); + await t.tool("steward_update", { binding: "ENG-14", hold: "After ENG-12", behind: ["ENG-12"] }, project); + await t.flush(); + t.entities.set("acme/web#7", pull({ state: "merged" }, { merged: true })); + await t.ring("github", "acme/web#7"); + const b13 = t.hooks.store.find("ENG-13")!; + const b14 = t.hooks.store.find("ENG-14")!; + expect(b13.hold).toBeNull(); + expect(b14.hold).toBe("After ENG-12"); + expect(b14.holdBehind).toEqual(["ENG-13"]); + expect(toProject().at(-1)!.text).toMatch(/Lifted the hold on ENG-13/u); + }); + + // BB-54: a schedule request re-reads the conflicting binding's pull requests + // from GitHub; merged and finished is no conflict, merged with more to come is. + it("does not file a schedule request when the conflicting work is merged on GitHub and finished, but does when more is coming", async () => { + const { t, second, toProject } = await two(); + // GitHub says #7 merged; ENG-12's last snapshot still shows it open. + t.entities.set("acme/web#7", pull({ state: "merged" }, { merged: true })); + t.hooks.store.patch(t.hooks.store.find("ENG-12")!.id, { noMorePulls: true }); + expect((await t.harness.behavior.runCli(["show", "ENG-12"])).stdout).toContain("no more pull requests"); + const finished = await t.tool("steward_report", ready, second); + expect(finished.text).toMatch(/Ready gate: passed\. You will be woken/u); + expect(toProject()).toHaveLength(0); + // The same merged PR, but no "no more coming": still at work, so it asks. + t.hooks.store.patch(t.hooks.store.find("ENG-12")!.id, { noMorePulls: null }); + const more = await t.tool("steward_report", ready, second); + expect(more.text).toMatch(/Scheduling is with the project steward/u); + expect(toProject()).toHaveLength(1); + }); + + // BB-54 item 4: a new linked pull request re-runs the overlap check even + // though the ticket was told to start, and files a schedule request again. + it("re-runs the overlap check when a ticket past its ready gate links a new pull request", async () => { + const { t, project, second, toProject } = await two(); + await t.tool("steward_report", ready, second); + expect(toProject()).toHaveLength(1); + const id = /(esc_[\w-]+) from ENG-13 \(schedule\)/u.exec(toProject()[0]!.text)![1]!; + await t.tool("steward_update", { binding: "ENG-13", guidance: "Start now: different files.", resolve: id }, project); + await t.flush(); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO", state: "In Progress", stateType: "started", linkedPulls: [{ key: "acme/web#9", url: "https://github.com/acme/web/pull/9" }] })); + t.entities.set("acme/web#9", pull({ state: "open" }, { merged: false })); + await t.ring("linear", "uuid-13"); + expect(toProject()).toHaveLength(2); + expect(toProject()[1]!.text).toMatch(/Schedule ENG-13/u); + }); +}); + +describe("declined specs converge (BB-54)", () => { + const met = { checklist: [1, 2, 3, 4].map((item) => ({ item, met: true })), substantial: true }; + const base = { phase: "Todo", summary: "Spec posted.", nextAction: "Wait", actor: "other" }; + + async function requested() { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; + await t.tool("steward_report", { ...base, ready: met }, steward); + const esc = /(esc_[\w-]+) from ENG-12 \(approval\)/u.exec(t.sends.filter((s) => s.threadId === project).at(-1)!.text)![1]!; + const toSteward = () => t.sends.filter((s) => s.threadId === steward).map((s) => s.text); + return { ...t, project, steward, esc, toSteward }; + } + + it("lists a decline's objections as a checklist and forwards a repeated one to the user", async () => { + const t = await requested(); + await t.tool("steward_update", { binding: "ENG-12", guidance: "Name the migration.\nAdd a rollback.", resolve: t.esc }, t.project); + await t.flush(); + expect(t.hooks.store.find("ENG-12")!.declinedSpecObjections).toEqual(["Name the migration.", "Add a rollback."]); + const wake = t.toSteward().at(-1)!; + expect(wake).toMatch(/Address each objection in one revision/u); + expect(wake).toContain("- [ ] Name the migration."); + expect(wake).toContain("- [ ] Add a rollback."); + + // The spec changes; the steward revises; the same objection is declined again. + t.entities.set("uuid-12", issue({ description: "Users cannot log in. Migration: add users.mfa." })); + await t.ring("linear", "uuid-12"); + await t.tool("steward_report", { ...base, ready: met }, t.steward); + const esc2 = /(esc_[\w-]+) from ENG-12 \(approval\)/u.exec(t.sends.filter((s) => s.threadId === t.project).at(-1)!.text)![1]!; + await t.tool("steward_update", { binding: "ENG-12", guidance: "Name the migration.", resolve: esc2 }, t.project); + const q = t.hooks.store.openQuestions("p1").find((x) => /twice on the same objection/u.test(x.question)); + expect(q).toBeDefined(); + expect(q!.question).toContain("Name the migration."); + }); }); describe("escalations delivered once, updates safe to retry", () => { diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index e3210064..4254ef78 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -73,7 +73,7 @@ import { import { allDeployed, applyDeployment, deploymentLines, deploymentReportSchema, recordMerged, reportDeployment, timeOut, timeoutsDue } from "./deploy.js"; import { ACTORS, MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store, type Worker } from "./store.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; -import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; +import { allPullsMerged, atWork, conflictsOf, finished, normalizeTouches, overlapping, touchesOverlap, type Conflict } from "./schedule.js"; import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY } from "./sidebar-provider.js"; import { NEEDS_YOU_CHANGED } from "./channels.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; @@ -481,6 +481,21 @@ type ProjectConfig = { const PRIORITY_ORDER: Record = { urgent: 0, high: 1, normal: 2, low: 3 }; +/** + * A spec decline's objections, one per line or `;`, with list markers + * stripped. A single line with no break is one objection (BB-54). + */ +function objectionLines(text: string): string[] { + const lines = text + .split(/\r?\n|;\s+/u) + .map((l) => l.replace(/^\s*(?:[-*•]|\d+[.)])\s*/u, "").trim()) + .filter((l) => l !== ""); + return lines; +} + +/** An objection compared for "the same objection": case and punctuation ignored. */ +const normObjection = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/gu, " ").trim(); + /** Authors whose pull requests the dependency watch adopts under deps-prs. */ export const DEPENDENCY_BOTS = new Set(["dependabot", "dependabot[bot]"]); @@ -908,6 +923,36 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return pulls; } + /** + * A binding's pull requests, re-read from GitHub rather than from its last + * snapshot (BB-54): a schedule request must not ask about work that has + * already merged. When the read fails the snapshot is used, so the plugin + * still asks rather than silently skipping. + */ + async function freshObserved(b: Binding): Promise { + if (b.lastSnapshot === null) return null; + if (b.source === "ops") return b.lastSnapshot; + const entity = await snapshot(b.source, b.entityId).catch(() => null); + if (entity === null) return b.lastSnapshot; + return { entity, pulls: b.kind === "ticket" ? await linkedPulls(entity) : [] }; + } + + /** Whether `b` is at work, judged from a fresh GitHub read and its running workers (BB-54). */ + async function atWorkFresh(b: Binding): Promise { + const running = store.workers(b.id).some((w) => w.status === "running"); + const observed = await freshObserved(b); + return atWork(observed === null ? b : { ...b, lastSnapshot: observed }, { runningWorker: running }); + } + + /** The overlapping open bindings at work on `b`'s paths, from a fresh GitHub read (BB-54). */ + async function conflictsFresh(b: Binding): Promise { + const conflicts: Conflict[] = []; + for (const c of overlapping(b, store.open(b.projectId))) { + if (await atWorkFresh(c.with)) conflicts.push(c); + } + return conflicts; + } + /** * The pull requests linked to a ticket that are leased for it: those * still open. One with no snapshot yet (not read, or the read failed) is @@ -1853,6 +1898,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } b = store.patch(b.id, { lastSnapshot: observed, phase, stage, title: entity.title, url: entity.url, entityKey: entity.key, playbookVersion: playbook.version, ready }); + // BB-54 item 4: a ticket that links a new pull request re-runs the + // overlap check, even past its ready gate, and a new pull request clears + // a "no more coming" report. The report path clears it too, when a + // steward reports more are coming. + const linkedBefore = new Set((prev?.entity.linkedPulls ?? []).map((l) => lc(l.key ?? l.url ?? ""))); + const linkedNew = observed.entity.linkedPulls.some((l) => { + const k = lc(l.key ?? l.url ?? ""); + return k !== "" && !linkedBefore.has(k); + }); + if (linkedNew) { + const clear: { noMorePulls?: null; scheduleAsked?: string[] } = {}; + if (b.noMorePulls === true) clear.noMorePulls = null; + if (b.scheduleAsked.length > 0) clear.scheduleAsked = []; + if (Object.keys(clear).length > 0) b = store.patch(b.id, clear); + } await syncNeeds(b, observed, playbook, workerInFlight); // The work this binding was holding others behind has landed: lift them. if (allPullsMerged(b, observed) && (prev === null || !allPullsMerged(b, prev))) await releaseBehind(b, "merged its pull requests"); @@ -2818,7 +2878,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const bindings = open.map((binding) => ({ binding, openEscalations: store.openEscalations(binding.id) })); const questions = store.openQuestions(projectId).map((question) => ({ question, about: question.bindingId === null ? null : store.binding(question.bindingId) })); const needs = open.flatMap((b) => store.openNeeds(b.id).map((need) => ({ need, binding: b }))); - const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, questions, needs, lessons: store.lessons(projectId), timeZone: config.file.nightly.timezone, label: config.file.label, ...(records === undefined ? {} : { records }) }); + const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, standingRules: config.file.standingRules, questions, needs, lessons: store.lessons(projectId), timeZone: config.file.nightly.timezone, label: config.file.label, ...(records === undefined ? {} : { records }) }); const delivered = { ids: routed.filter((r) => r.escalation.deliveredAt === null).map((r) => r.escalation.id), at: 0 }; delivered.at = store.markDelivered(delivered.ids); // A wake can be the thing that pushes the transcript over the limit. @@ -2838,6 +2898,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return { previous: row.digest === null ? null : { text: row.digest, at: row.digestAt ?? 0 }, since, + notes: store.takeProjectNotes(projectId), moved: open.filter((b) => b.advancedAt !== null && b.advancedAt >= since), ended: all.filter((b) => b.endedAt !== null && b.endedAt >= since), answered: store.answeredSince(projectId, since), @@ -3068,8 +3129,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b.hold !== null) return withdraw("Held.", false); const gate = gateState(playbook, b.ready, specHashFor(b, b.lastSnapshot.entity)); if (!gate.passed) return withdraw("Withdrawn: the ready gate no longer passes.", false); + // Finished work is not scheduled against anything: there is nothing left to start. + if (b.lastSnapshot !== null && finished(b, b.lastSnapshot)) return withdraw("Withdrawn: the work is finished.", false); if (b.stage === "review" || store.workers(b.id).some((w) => w.status === "running")) return withdraw("Withdrawn: the work has started.", true); - const conflicts = conflictsOf(b, store.open(b.projectId)); + const conflicts = await conflictsFresh(b); if (conflicts.length === 0) return withdraw("Withdrawn: nothing in flight overlaps it now.", true); const keys = conflicts.map((c) => c.with.entityKey); if (open.length > 0) { @@ -3108,7 +3171,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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; - const lifted: string[] = []; + const fullyLifted: Binding[] = []; for (const h of waiting) { const rest = h.holdBehind.filter((k) => lc(k) !== key); if (rest.length > 0) { @@ -3116,13 +3179,42 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P store.note(h.id, `${b.entityKey} ${how}; your hold stays until ${rest.join(", ")} ${rest.length === 1 ? "does" : "do"} too.`, true); continue; } + fullyLifted.push(h); + } + // One lift can free several waiters that overlap each other. Release the + // first by priority, then age; re-hold the rest behind it, so two + // branches do not start into the same files in one tick (BB-54). + const order = [...fullyLifted].sort((x, y) => (PRIORITY_ORDER[x.priority ?? "normal"] ?? 2) - (PRIORITY_ORDER[y.priority ?? "normal"] ?? 2) || x.createdAt - y.createdAt); + const released: Binding[] = []; + const reheld: string[] = []; + for (const h of order) { + const blocker = released.find((r) => touchesOverlap(r.touches, h.touches).length > 0); + if (blocker !== undefined) { + store.patch(h.id, { holdBehind: [blocker.entityKey] }); + store.note(h.id, `Hold lifted from ${b.entityKey}, but it overlaps ${blocker.entityKey}, which is starting first: the hold now waits behind ${blocker.entityKey} and lifts itself when that work lands.`); + reheld.push(h.entityKey); + continue; + } store.patch(h.id, { hold: null, holdBehind: [] }); store.note(h.id, `Hold lifted: ${b.entityKey}, which it waited behind, ${how}. Rebase anything already branched before building on.`); - lifted.push(h.entityKey); + released.push(h); scheduleReconcile(h.id); } - bb.log.info(`stewards: ${b.entityKey} ${how}; ${lifted.length === 0 ? "nothing lifted" : `lifted the hold on ${lifted.join(", ")}`}`); - if (lifted.length > 0) await wakeProject(b.projectId, `${b.entityKey} ${how}`, { digestDue: false, notes: [`Lifted the hold on ${lifted.join(", ")}: ${b.entityKey}, which ${lifted.length === 1 ? "it" : "they"} waited behind, ${how}. Each is woken; one that still overlaps other work asks you to schedule it again.`] }); + const lifted = released.map((h) => h.entityKey); + bb.log.info(`stewards: ${b.entityKey} ${how}; ${lifted.length === 0 ? "nothing lifted" : `lifted the hold on ${lifted.join(", ")}`}${reheld.length === 0 ? "" : `; re-held ${reheld.join(", ")}`}`); + if (lifted.length === 0) return; + // Silent only when the work waited on is finished (its ticket is + // terminal with its PRs merged, or every linked PR merged and its + // steward reported no more coming). Anything else wakes the project + // steward, as today: the plugin cannot tell, so it asks. + if (b.lastSnapshot !== null && finished(b, b.lastSnapshot)) { + store.noteProject( + b.projectId, + `Lifted the hold on ${lifted.join(", ")}: ${b.entityKey}, which ${lifted.length === 1 ? "it" : "they"} waited behind, ${how}, and its work is finished. No turn needed; this is the record.`, + ); + return; + } + await wakeProject(b.projectId, `${b.entityKey} ${how}`, { digestDue: false, notes: [`Lifted the hold on ${lifted.join(", ")}: ${b.entityKey}, which ${lifted.length === 1 ? "it" : "they"} waited behind, ${how}. Each is woken; one that still overlaps other work asks you to schedule it again.`] }); } const shortSha = (sha: string | null | undefined) => (sha === null || sha === undefined ? "?" : sha.slice(0, 7)); @@ -4567,6 +4659,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .max(40) .optional() .describe('The repo-relative paths this work changes, repo directory first ("bb-plugins/plugins/stewards", "bb-gate/docker/bb-server"); the whole set, replacing what was reported before. The project steward schedules tickets that touch the same paths one after another. Report it once the spec names the affected repos; refine it as pull requests open.'), + noMorePulls: z + .boolean() + .optional() + .describe('Ticket stewards: true once no more pull requests are coming for this ticket, so its work is finished when its linked pull requests have merged and its hold can lift silently. Set it again as more pull requests open: reporting false (more are coming), or a new linked pull request, clears it.'), needs: z .array( z.object({ @@ -4737,6 +4833,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ready, deployments, ...(input.touches === undefined ? {} : { touches: normalizeTouches(input.touches) }), + ...(input.noMorePulls === undefined ? {} : { noMorePulls: input.noMorePulls ? true : null }), + ...(input.noMorePulls === false && b.scheduleAsked.length > 0 ? { scheduleAsked: [] } : {}), ...(b.ending === "terminal" ? { followThrough: input.followThrough ?? null, followThroughUntil } : {}), }); const requested = playbook === null ? null : await syncApprovalRequest(b, playbook); @@ -5261,7 +5359,25 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P done.push(`remembered the decline of ${shortSha(resolving.headSha)} so the same head and reviewer marker are not asked again`); } else if (resolving.kind === "approval" && resolving.status === "open" && approval === null && target.lastSnapshot !== null) { const fresh = store.binding(target.id)!; - store.patch(target.id, { ready: { ...fresh.ready, declinedSpecHash: specHashFor(fresh, fresh.lastSnapshot!.entity) } }); + const objections = objectionLines(guidance ?? ""); + const previous = fresh.declinedSpecObjections; + const repeated = previous.length > 0 && objections.some((o) => previous.some((p) => normObjection(p) === normObjection(o))); + store.patch(target.id, { ready: { ...fresh.ready, declinedSpecHash: specHashFor(fresh, fresh.lastSnapshot!.entity) }, declinedSpecObjections: objections }); + if (repeated) { + // The same objection came back after a revision: a third round + // would only repeat it, so the user decides (BB-54). + const q = store.ask({ + projectId: target.projectId, + bindingId: target.id, + escalationId: resolving.id, + question: `The project steward declined ${target.entityKey}'s spec twice on the same objection: ${objections.join("; ")}. Decide how to proceed.`, + context: `First declined on: ${previous.join("; ")}. The revision did not answer it, so it is forwarded to you instead of a third round.`, + resolutionKind: "text", + }); + done.push(`forwarded the repeated objection to the user as question ${q.id}`); + } else if (objections.length > 0) { + done.push(`recorded the decline's ${objections.length} objection(s) for the steward's checklist`); + } } if (resolving.status === "open") done.push(`resolved ${resolving.id}${isProjectSteward(threadId, target) ? "; if this is a general judgement the playbook should carry, record it with steward_update { lesson: { text, file, scope } }" : ""}`); else if (outcome === "appended") done.push(`recorded the answer on ${resolving.id}, which was already resolved (${resolving.resolution ?? "no answer"})`); @@ -5371,7 +5487,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.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.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.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(", ")})`}`, ...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 ?? "?"}${b.threadId === null ? "" : `, thread ${b.threadId}`}\n ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${s.blockedOn === null ? "" : `; blocked on ${s.blockedOn}`}`}${flags.length > 0 ? `\n [${flags.join("; ")}]` : ""}`; }) .join("\n"); diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index db8f0e69..1242a551 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -152,7 +152,12 @@ Two tools are yours; everything else you do with the tools every thread has. soon as the spec names the repos and paths the work changes, report them with `steward_report { touches: ["/", …] }` (repo directory first, the whole set each time), and refine the list as pull requests - open. The wake shows what is in flight on the same paths. When your + open. When no more pull requests are coming for the ticket, report it + with `steward_report { noMorePulls: true }`; a new linked pull request, + or a later `noMorePulls: false`, clears it. A hold behind this ticket + lifts silently (no project steward turn) only once its pull requests + have merged and you have reported that. The wake shows what is in flight + on the same paths. When your ready gate passes and such work exists, the plugin asks the project steward to schedule you: start no workers and do not move the ticket into a build state until it holds you behind that work or tells you to @@ -244,7 +249,12 @@ transcripts. Turn the user's focus ("hold everything touching billing") into `steward_update` calls. A substantial spec whose checklist is met reaches you as an `approval` escalation the plugin files: approve it with `steward_update { binding, approve: true }`, which closes it, or decline -with `guidance` + `resolve` saying what must change. You also schedule the +with `guidance` + `resolve` saying what must change. Your approval wake +shows the project's `standingRules` from `.bb/stewards/project.json`; add +only the limits the change needs that they do not cover, in at most three +points, or approve with none. A decline's objections go to the ticket +steward as a checklist; the same objection declined twice is forwarded to +the user rather than a third round. You also schedule the work so two tickets do not change the same files at once, which is what makes rebases pile up. Every binding reports what it touches; a ready ticket that touches what another is building or reviewing reaches you as a @@ -252,7 +262,12 @@ ticket that touches what another is building or reviewing reaches you as a `steward_update { binding, hold: "", behind: [] }` holds it behind that work and closes the request, and the hold lifts itself, waking the steward, once every binding named has merged its pull requests or -ended. When the overlap is harmless, or the new ticket matters more (then +ended. The lift wakes you only when that work is not finished; when its +ticket is terminal with its pull requests merged, or its steward reported +`noMorePulls`, it is a note on the held binding and your next digest +instead. If one lift frees two waiters that overlap each other, the first +by priority then age is released and the rest wait behind it. When the +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 diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 648de807..00ef3339 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -356,7 +356,17 @@ export const DECLINED_PR_MIGRATIONS = [ // binding with no deployment target keeps an empty map and behaves as before. export const DEPLOYMENT_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN deployments TEXT NOT NULL DEFAULT '{}'`]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS]; +// BB-54: a ticket steward's "no more pull requests are coming" report, the +// objections of the last spec decline, and the silent hold-lift notes waiting +// for the project steward's next digest. All additive and defaulted: an old +// row reads as "not reported", no objections, no notes. +export const FINISHED_AND_DIGEST_MIGRATIONS = [ + `ALTER TABLE bindings ADD COLUMN no_more_pulls INTEGER`, + `ALTER TABLE bindings ADD COLUMN declined_spec_objections TEXT NOT NULL DEFAULT '[]'`, + `ALTER TABLE project_stewards ADD COLUMN pending_notes 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]; // ---- values kept as JSON ------------------------------------------------------------ @@ -481,6 +491,10 @@ export type Binding = { declinedPrHeadSha: string | null; /** The reviewer marker in force when that head was declined, so a new round asks again. */ declinedPrMarker: string | null; + /** True once the steward reported no more pull requests are coming; null until reported. Cleared by a new PR or a "more coming" report. */ + noMorePulls: boolean | null; + /** The exact objections of the last spec decline, so the ticket steward's wake can list them as a checklist and a repeat forwards. */ + declinedSpecObjections: string[]; /** An ops binding's last look; null for every other kind. */ opsLook: OpsLook | null; /** A Dependabot alert binding's last look; null for every other kind. */ @@ -545,6 +559,8 @@ function rowToBinding(r: BindingRow): Binding { manualDetach: Number(r.manual_detach) === 1, declinedPrHeadSha: str("declined_pr_head_sha"), declinedPrMarker: str("declined_pr_marker"), + noMorePulls: r.no_more_pulls === null || r.no_more_pulls === undefined ? null : Number(r.no_more_pulls) === 1, + declinedSpecObjections: json(z.array(z.string()), str("declined_spec_objections"), []), opsLook: json(opsLookSchema.nullable(), str("ops_look"), null), depsLook: json(depsLookSchema.nullable(), str("deps_look"), null), sentryLook: json(sentryLookSchema.nullable(), str("sentry_look"), null), @@ -595,6 +611,8 @@ const COLUMNS = { manualDetach: "manual_detach", declinedPrHeadSha: "declined_pr_head_sha", declinedPrMarker: "declined_pr_marker", + noMorePulls: "no_more_pulls", + declinedSpecObjections: "declined_spec_objections", opsLook: "ops_look", depsLook: "deps_look", sentryLook: "sentry_look", @@ -808,7 +826,7 @@ export type Fingerprint = FingerprintRow & { projectId: string; bindingId: strin /** What a steward reports doing about a fingerprint: filing a ticket, commenting on one, or reopening one. */ export type TicketAction = "filed" | "commented" | "reopened"; -export type ProjectStewardRow = { projectId: string; threadId: string | null; digest: string | null; digestAt: number | null; nightlyDate: string | null; digestPending: boolean; title: string | null; sectionId: string | null }; +export type ProjectStewardRow = { projectId: string; threadId: string | null; digest: string | null; digestAt: number | null; nightlyDate: string | null; digestPending: boolean; title: string | null; sectionId: string | null; pendingNotes: string[] }; /** Guidance repeated within this window is a retry, not new guidance. */ export const GUIDANCE_DEDUPE_MS = 5 * 60_000; @@ -1066,6 +1084,7 @@ export function createStore(db: Database.Database, now: () => number, options: S digestPending: Number(r.digest_pending) === 1, title: r.title === null || r.title === undefined ? null : String(r.title), sectionId: r.section_id === null || r.section_id === undefined ? null : String(r.section_id), + pendingNotes: json(z.array(z.string()), r.pending_notes === null || r.pending_notes === undefined ? null : String(r.pending_notes), []), }); const toLesson = (r: Record): Lesson => ({ id: String(r.id), @@ -1774,7 +1793,7 @@ export function createStore(db: Database.Database, now: () => number, options: S }, patchProject(projectId: string, fields: Partial>): ProjectStewardRow { upsertProject.run(projectId); - const map: Record = { threadId: "thread_id", digest: "digest", digestAt: "digest_at", nightlyDate: "nightly_date", digestPending: "digest_pending", title: "title", sectionId: "section_id" }; + const map: Record = { threadId: "thread_id", digest: "digest", digestAt: "digest_at", nightlyDate: "nightly_date", digestPending: "digest_pending", title: "title", sectionId: "section_id", pendingNotes: "pending_notes" }; const entries = Object.entries(fields).filter(([, v]) => v !== undefined); if (entries.length > 0) db.prepare(`UPDATE project_stewards SET ${entries.map(([k]) => `${map[k]} = ?`).join(", ")} WHERE project_id = ?`).run(...entries.map(([, v]) => toColumn(v)), projectId); return toProject(getProject.get(projectId)!); @@ -1782,6 +1801,20 @@ export function createStore(db: Database.Database, now: () => number, options: S projects(): ProjectStewardRow[] { return db.prepare<[], Record>("SELECT * FROM project_stewards").all().map(toProject); }, + /** Queue a silent note for the project steward's next digest; it starts no turn. */ + noteProject(projectId: string, text: string): void { + upsertProject.run(projectId); + const row = toProject(getProject.get(projectId)!); + db.prepare("UPDATE project_stewards SET pending_notes = ? WHERE project_id = ?").run(JSON.stringify([...row.pendingNotes, text]), projectId); + }, + /** Read and clear the queued digest notes, so each appears in exactly one digest. */ + takeProjectNotes(projectId: string): string[] { + upsertProject.run(projectId); + const row = toProject(getProject.get(projectId)!); + if (row.pendingNotes.length === 0) return []; + db.prepare("UPDATE project_stewards SET pending_notes = ? WHERE project_id = ?").run("[]", projectId); + return row.pendingNotes; + }, // threads put in their project's section placed(threadId: string): boolean { diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index bbb518e4..4bb61a3a 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -214,4 +214,18 @@ describe("the nightly prompt", () => { const escalation = formatProjectWake({ reason: "escalation", bindings: [], routed: [], problems: [], digestDue: false, notes: [], bigDecisions: [], questions: [], records: empty }); expect(escalation).not.toContain("## The record since"); }); + + it("shows the project's standing-rules list in an approval wake, and works with none configured (BB-54)", () => { + const { s, bind } = world(); + const b = bind("ENG-12"); + const x = s.escalate({ bindingId: b.id, kind: "approval", question: "Approve ENG-12's spec?", meanwhile: "Waiting.", route: "project", recommendation: null }); + const withRules = formatProjectWake({ reason: "approval", bindings: [], routed: [{ escalation: x, from: b }], problems: [], digestDue: false, notes: [], bigDecisions: [], questions: [], standingRules: ["Migrations are append-only.", "The PR body carries the restart note."] }); + expect(withRules).toContain("- Migrations are append-only."); + expect(withRules).toContain("- The PR body carries the restart note."); + expect(withRules).toMatch(/Add only the limits this change needs that this list does not cover, in at most three points/u); + expect(withRules).toMatch(/The guidance written to the binding is your additions only/u); + const none = formatProjectWake({ reason: "approval", bindings: [], routed: [{ escalation: x, from: b }], problems: [], digestDue: false, notes: [], bigDecisions: [], questions: [] }); + expect(none).toMatch(/no standing-rules list configured/u); + expect(none).toMatch(/Add only the limits this change needs, in at most three points/u); + }); }); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 9d3df471..bdfff1a1 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -426,6 +426,9 @@ export function formatWake(input: WakeInput): string { out.push(`- Priority: ${binding.priority ?? "normal"}`); out.push(holdLine(binding, "take no new actions and start no workers until it is lifted.")); out.push(...schedulingLines(binding, input.conflicts ?? [], input.escalations)); + if (binding.ready.declinedSpecHash !== null && binding.declinedSpecObjections.length > 0) { + out.push("", "**Spec declined.** Address each objection in one revision, so the next review can close them all:", "", ...binding.declinedSpecObjections.map((o) => `- [ ] ${o}`)); + } // The deployment block goes in the head, not the snapshot: a clipped wake // must not lose the deployment's ref and sha, which the rule decides on. out.push(...deploymentLines(input)); @@ -883,6 +886,8 @@ export function formatProjectWake(input: { timeZone?: string; /** The adoption label, for adopting what an ops steward filed. */ label?: string; + /** The project's standing-rules list from `.bb/stewards/project.json`, shown in an approval wake; empty when none is configured. */ + standingRules?: string[]; }): string { const day = dayIn(input.timeZone ?? "UTC"); const out: string[] = [`# Project steward: ${input.reason}`, ""]; @@ -917,9 +922,20 @@ export function formatProjectWake(input: { ); } if (input.routed.some((r) => r.escalation.kind === "approval")) { + const rules = input.standingRules ?? []; out.push( "An approval escalation is the plugin's: the ticket's ready gate waits on you. Judge the spec (`bb stewards show `, and the ticket itself) against the project's guidance. Approve it with steward_update { binding, approve: true }, or with approving words in the guidance that resolves it, such as steward_update { binding, guidance: \"Approved\", resolve }; either closes the request. Decline with steward_update { binding, guidance: what must change, resolve }. If the steward also escalated asking for this approval, resolve that one too.", "", + rules.length === 0 + ? "This project has no standing-rules list configured. Add only the limits this change needs, in at most three points, as the guidance; approve with none when nothing needs adding. The guidance written to the binding is your additions only." + : [ + "The project's standing rules already bind every pull request, so do not restate them:", + "", + ...rules.map((r) => `- ${r}`), + "", + "Add only the limits this change needs that this list does not cover, in at most three points, as the guidance; approve with none when nothing needs adding. The guidance written to the binding is your additions only.", + ].join("\n"), + "", ); } } @@ -1094,6 +1110,8 @@ export type DigestRecords = { stuck: Array<{ escalation: Escalation; from: Binding }>; /** Open bindings on hold. */ held: Binding[]; + /** Silent notes queued for this digest (a hold that lifted on finished work), one line each. */ + notes?: string[]; /** Lessons that reached `.bb` HEAD in the window. */ lessonsMerged?: Lesson[]; }; @@ -1130,6 +1148,8 @@ export function formatRecords(r: DigestRecords, questions: Array<{ question: Que ]; out.push("### What moved", "", ...capped(moved, "Nothing moved."), ""); + if ((r.notes ?? []).length > 0) out.push("### Notes", "", ...capped((r.notes ?? []).map((n) => `- ${n}`), "Nothing."), ""); + // A question or a need covers the escalation it was made for: list the // question or the item, never the raw escalation too. const asked = new Set( From e45fb8bd61b0ddf72c07d5e2bd2faada185ffc34 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sun, 25 Oct 2026 20:16:13 +0000 Subject: [PATCH 2/2] stewards: address BB-54 review round 1 - freshObserved marks a per-pull read failure incomplete, so atWorkFresh drops noMorePulls for that judgement and asks rather than skipping. - Digest notes are peeked at and cleared only after a successful send, so a failed digest does not lose them. - Clear declinedSpecObjections when an approval ends the decline episode. - A noMorePulls: false report clears scheduleAsked only when the binding had reported true. - Tests for the steward_report noMorePulls path (silent non-terminal lift) and the more-PRs-after-none re-ask. --- plugins/stewards/server.test.ts | 38 +++++++++++++++++++++++++++++++++ plugins/stewards/server.ts | 35 ++++++++++++++++++++---------- plugins/stewards/store.ts | 14 ++++++------ 3 files changed, 70 insertions(+), 17 deletions(-) diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index e7654089..75760d2e 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -1382,6 +1382,44 @@ describe("scheduling overlapping work", () => { expect(toProject()).toHaveLength(2); expect(toProject()[1]!.text).toMatch(/Schedule ENG-13/u); }); + + // BB-54: a hold behind a ticket whose steward reported noMorePulls lifts + // silently on the merge, without waiting for a terminal state, and the tool + // path records it. + it("lifts a hold silently when the steward reported noMorePulls and the pull requests merged", async () => { + const { t, project, first, second, toProject } = await two(); + await t.tool("steward_report", ready, second); + await t.tool("steward_update", { binding: "ENG-13", hold: "After ENG-12", behind: ["ENG-12"] }, project); + await t.flush(); + const reported = await t.tool("steward_report", { ...building, noMorePulls: true }, first); + expect(reported.error).toBe(false); + expect(t.hooks.store.find("ENG-12")!.noMorePulls).toBe(true); + expect((await t.harness.behavior.runCli(["show", "ENG-12"])).stdout).toContain("no more pull requests"); + const wakes = toProject().length; + t.entities.set("acme/web#7", pull({ state: "merged" }, { merged: true })); + await t.ring("github", "acme/web#7"); + expect(t.hooks.store.find("ENG-13")!.hold).toBeNull(); + // Silent: no project steward turn, but the note is on the digest record. + expect(toProject().length).toBe(wakes); + expect(t.hooks.store.project("p1").pendingNotes.join("\n")).toMatch(/Lifted the hold on ENG-13: ENG-12, which it waited behind, merged its pull requests, and its work is finished/u); + }); + + // BB-54 item 5: reporting more pull requests after "none coming" clears the + // report and re-runs the overlap check, through the tool. + it("re-files a schedule request when a steward reports more pull requests after saying none were coming", async () => { + const { t, project, second, toProject } = await two(); + await t.tool("steward_report", ready, second); + const id = /(esc_[\w-]+) from ENG-13 \(schedule\)/u.exec(toProject()[0]!.text)![1]!; + await t.tool("steward_update", { binding: "ENG-13", guidance: "Start now: different files.", resolve: id }, project); + await t.flush(); + expect(toProject()).toHaveLength(1); + await t.tool("steward_report", { ...ready, noMorePulls: true }, second); + expect(t.hooks.store.find("ENG-13")!.noMorePulls).toBe(true); + await t.tool("steward_report", { ...ready, noMorePulls: false }, second); + expect(t.hooks.store.find("ENG-13")!.noMorePulls).toBeNull(); + expect(toProject()).toHaveLength(2); + expect(toProject()[1]!.text).toMatch(/Schedule ENG-13/u); + }); }); describe("declined specs converge (BB-54)", () => { diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 4254ef78..224ed3b2 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -926,22 +926,32 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** * A binding's pull requests, re-read from GitHub rather than from its last * snapshot (BB-54): a schedule request must not ask about work that has - * already merged. When the read fails the snapshot is used, so the plugin - * still asks rather than silently skipping. + * already merged. `complete` is false when the entity or any linked pull + * request could not be read fresh, so the caller treats the binding as + * still at work: when the plugin cannot tell, it asks rather than skips. */ - async function freshObserved(b: Binding): Promise { + async function freshObserved(b: Binding): Promise<{ observed: Observed; complete: boolean } | null> { if (b.lastSnapshot === null) return null; - if (b.source === "ops") return b.lastSnapshot; + if (b.source === "ops") return { observed: b.lastSnapshot, complete: true }; const entity = await snapshot(b.source, b.entityId).catch(() => null); - if (entity === null) return b.lastSnapshot; - return { entity, pulls: b.kind === "ticket" ? await linkedPulls(entity) : [] }; + if (entity === null) return { observed: b.lastSnapshot, complete: false }; + if (b.kind !== "ticket") return { observed: { entity, pulls: [] }, complete: true }; + const keys = [...new Set(entity.linkedPulls.map((l) => l.key).filter((k): k is string => k !== null))].slice(0, 5); + const pulls = await linkedPulls(entity); + return { observed: { entity, pulls }, complete: pulls.length >= keys.length }; } /** Whether `b` is at work, judged from a fresh GitHub read and its running workers (BB-54). */ async function atWorkFresh(b: Binding): Promise { const running = store.workers(b.id).some((w) => w.status === "running"); - const observed = await freshObserved(b); - return atWork(observed === null ? b : { ...b, lastSnapshot: observed }, { runningWorker: running }); + const fresh = await freshObserved(b); + if (fresh === null) return atWork(b, { runningWorker: running }); + // An incomplete read cannot prove the work is finished (a linked pull + // request may be open and unread), so drop a "no more coming" report for + // this judgement: the project steward is woken rather than a request + // skipped. + const base = { ...b, lastSnapshot: fresh.observed, ...(fresh.complete ? {} : { noMorePulls: null }) }; + return atWork(base, { runningWorker: running }); } /** The overlapping open bindings at work on `b`'s paths, from a fresh GitHub read (BB-54). */ @@ -2885,6 +2895,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await compactIfLarge(threadId, text.length); const sent = await send(threadId, text); if (sent !== "sent") store.undeliver(delivered.ids, delivered.at); + // The notes were only peeked at, so a failed or skipped send leaves them + // queued for the next digest rather than losing them. + else if (opts.digestDue) store.clearProjectNotes(projectId); } /** What the digest is written from, since the last one (or a day back): read from the tables, never from the project steward's memory. */ @@ -2898,7 +2911,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return { previous: row.digest === null ? null : { text: row.digest, at: row.digestAt ?? 0 }, since, - notes: store.takeProjectNotes(projectId), + notes: store.peekProjectNotes(projectId), moved: open.filter((b) => b.advancedAt !== null && b.advancedAt >= since), ended: all.filter((b) => b.endedAt !== null && b.endedAt >= since), answered: store.answeredSince(projectId, since), @@ -4834,7 +4847,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P deployments, ...(input.touches === undefined ? {} : { touches: normalizeTouches(input.touches) }), ...(input.noMorePulls === undefined ? {} : { noMorePulls: input.noMorePulls ? true : null }), - ...(input.noMorePulls === false && b.scheduleAsked.length > 0 ? { scheduleAsked: [] } : {}), + ...(input.noMorePulls === false && b.noMorePulls === true && b.scheduleAsked.length > 0 ? { scheduleAsked: [] } : {}), ...(b.ending === "terminal" ? { followThrough: input.followThrough ?? null, followThroughUntil } : {}), }); const requested = playbook === null ? null : await syncApprovalRequest(b, playbook); @@ -5331,7 +5344,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (approval !== null) { const by = approval.byUser ? ` by the user: "${input.quote}"` : " by the project steward"; - store.patch(target.id, { ready: { ...target.ready, approval: { at: now(), specHash: specHashFor(target, approval.entity), by: threadId }, voidedAt: null, declinedSpecHash: null } }); + store.patch(target.id, { ready: { ...target.ready, approval: { at: now(), specHash: specHashFor(target, approval.entity), by: threadId }, voidedAt: null, declinedSpecHash: null }, declinedSpecObjections: [] }); store.closeNeeds(target.id, "approve-spec", "Approved."); for (const x of store.openEscalations(target.id).filter((e) => e.kind === "approval" && e.resolutionKind !== "approve-decline")) store.resolve(x.id, `Approved${by}.`); const others = store.openEscalations(target.id).filter((x) => x.id !== resolve); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 00ef3339..7c2e3b3b 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -1312,7 +1312,7 @@ export function createStore(db: Database.Database, now: () => number, options: S coalescing(() => db.transaction(() => { const b = rowToBinding(getBinding.get(bindingId)!); - patch(bindingId, { ready: { ...b.ready, approval, voidedAt: null, declinedSpecHash: null } }); + patch(bindingId, { ready: { ...b.ready, approval, voidedAt: null, declinedSpecHash: null }, declinedSpecObjections: [] }); closeNeedKindStmt.run("Approved.", now(), bindingId, "approve-spec"); for (const x of openEscalations.all(bindingId).map(toEscalation).filter((e) => e.kind === "approval" && e.resolutionKind !== "approve-decline")) resolve(x.id, resolution, by); needsYouChanged(projectIdForBinding(bindingId)); @@ -1807,13 +1807,15 @@ export function createStore(db: Database.Database, now: () => number, options: S const row = toProject(getProject.get(projectId)!); db.prepare("UPDATE project_stewards SET pending_notes = ? WHERE project_id = ?").run(JSON.stringify([...row.pendingNotes, text]), projectId); }, - /** Read and clear the queued digest notes, so each appears in exactly one digest. */ - takeProjectNotes(projectId: string): string[] { + /** The queued digest notes, without clearing them: a failed digest send must not lose them. */ + peekProjectNotes(projectId: string): string[] { + upsertProject.run(projectId); + return toProject(getProject.get(projectId)!).pendingNotes; + }, + /** Drop the queued digest notes once the digest that carried them was sent. */ + clearProjectNotes(projectId: string): void { upsertProject.run(projectId); - const row = toProject(getProject.get(projectId)!); - if (row.pendingNotes.length === 0) return []; db.prepare("UPDATE project_stewards SET pending_notes = ? WHERE project_id = ?").run("[]", projectId); - return row.pendingNotes; }, // threads put in their project's section