From b06db46a5b907844b59e8f82ca9b54d689b28f2a Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Tue, 20 Oct 2026 02:20:51 +0000 Subject: [PATCH 1/2] stewards: schedule overlapping tickets one after another Two tickets changing the same files on two branches end in a rebase for whichever merges second. The project steward now sequences them: - steward_report takes `touches`, the repo-relative paths the work changes; two bindings overlap when a touch of one is, or is inside, a touch of the other (schedule.ts). - When a ticket's ready gate passes while another binding is building or reviewing on the same paths, the plugin files a `schedule` escalation with the project steward, like the approval request, and the ticket steward is told to start no workers until it is decided. A decided request is not made again until a new overlap appears. - steward_update takes `behind` with a hold: the keys the hold waits behind. The hold lifts itself, waking the steward and telling the project steward, once every binding named has merged its pull requests or ended. Work whose pull requests have all merged no longer counts as in flight. - Wakes, `bb stewards list` and `show` print touches, overlaps and what a hold waits behind; the default playbook, skill and README say how to use it. Store: three new binding columns (touches, hold_behind, schedule_asked). Co-Authored-By: Claude Fable 5.1 --- plugins/stewards/README.md | 19 ++- plugins/stewards/config.ts | 4 +- plugins/stewards/schedule.test.ts | 69 ++++++++++ plugins/stewards/schedule.ts | 71 +++++++++++ plugins/stewards/server.test.ts | 147 ++++++++++++++++++++++ plugins/stewards/server.ts | 138 ++++++++++++++++++-- plugins/stewards/skills/stewards/SKILL.md | 26 +++- plugins/stewards/store.ts | 18 +++ plugins/stewards/templates.ts | 17 ++- plugins/stewards/wake.ts | 45 ++++++- 10 files changed, 531 insertions(+), 23 deletions(-) create mode 100644 plugins/stewards/schedule.test.ts create mode 100644 plugins/stewards/schedule.ts diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 3811adf9..7b7b02d0 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -81,7 +81,24 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. - **Two tools.** `steward_report` ends a turn with the status record and, when needed, an escalation; `steward_update` steers a binding (guidance, deciding or forwarding escalations, priority, holds, models, approving a - spec). Everything else is the tools every thread has: `linear_*`, `gh`, + spec). +- **Scheduling.** Two tickets changing the same files at once end in a + rebase for whichever merges second, so the project steward sequences + them. Each steward reports the repo-relative paths its work changes + (`steward_report { touches }`); two bindings overlap when a touch of one + is, or is inside, a touch of the other. When a ticket's ready gate passes + while another binding is building or reviewing on the same paths, the + plugin files a `schedule` escalation with the project steward, like the + approval request, and the ticket steward is told to start no workers + until it is decided. The project steward holds the ticket behind that + work (`steward_update { hold, behind: [keys] }`, which closes the request) + 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. Work whose pull requests + have all merged no longer counts as in flight. `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 children of a steward thread. - **Lifecycle.** A terminal state gets a wrap-up turn with its workers diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index ecff5400..87e224b7 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -278,8 +278,8 @@ export type Stage = (typeof STAGES)[number]; /** What a steward raises. */ export const ESCALATION_KINDS = ["blocked", "decision", "scope", "conflict", "stuck"] as const; -/** Those, and the plugin's own: a ready gate waiting on its approver. */ -export type EscalationKind = (typeof ESCALATION_KINDS)[number] | "approval"; +/** Those, and the plugin's own: a ready gate waiting on its approver, and a ready ticket waiting to be scheduled against work already under way. */ +export type EscalationKind = (typeof ESCALATION_KINDS)[number] | "approval" | "schedule"; const phaseSchema = z .object({ diff --git a/plugins/stewards/schedule.test.ts b/plugins/stewards/schedule.test.ts new file mode 100644 index 00000000..e2166dd9 --- /dev/null +++ b/plugins/stewards/schedule.test.ts @@ -0,0 +1,69 @@ +import Database from "better-sqlite3"; +import { describe, expect, it } from "vitest"; +import { issue, pull } from "./fixtures.js"; +import { allPullsMerged, atWork, conflictsOf, normalizeTouches, touchesOverlap } from "./schedule.js"; +import { MIGRATIONS, createStore, type Binding } from "./store.js"; + +const T = Date.parse("2026-10-18T05:00:00Z"); + +function world() { + const db = new Database(":memory:"); + for (const sql of MIGRATIONS) db.exec(sql); + const s = createStore(db, () => T); + let n = 0; + const bind = (key: string, over: { stage?: "spec" | "build" | "review"; touches?: string[]; parent?: string | null; project?: string } = {}): Binding => { + const b = s.create({ projectId: over.project ?? "p1", source: "linear", entityId: `uuid-${++n}`, entityKey: key, url: null, title: null, kind: "ticket", playbook: "linear-tickets", playbookVersion: "v1", parentBindingId: over.parent ?? null, phase: "In Progress", stage: over.stage ?? "build" }); + return s.patch(b.id, { touches: over.touches ?? [] }); + }; + return { s, bind }; +} + +describe("touches", () => { + it("are normalized and deduplicated", () => { + expect(normalizeTouches([" ./Web/src/login/ ", "web\\src\\login", "", "bb-gate//docker", "/x/"])).toEqual(["web/src/login", "bb-gate/docker", "x"]); + }); + + it("overlap when one is the other or a directory above it, never on a shared prefix of a name", () => { + expect(touchesOverlap(["web/src"], ["web/src/login"])).toEqual(["web/src/login"]); + expect(touchesOverlap(["web/src/login/form.ts"], ["web"])).toEqual(["web/src/login/form.ts"]); + expect(touchesOverlap(["web/src"], ["web/srcs", "api/src"])).toEqual([]); + expect(touchesOverlap(["bb-plugins/plugins/stewards", "bb-gate"], ["bb-gate/docker", "bb-plugins/plugins/linear"])).toEqual(["bb-gate/docker"]); + }); +}); + +describe("conflicts", () => { + it("name the open bindings at work on the same paths, oldest first, leaving out held, spec-stage, landed and related ones", () => { + const { s, bind } = world(); + const me = bind("ENG-20", { stage: "spec", touches: ["web/src"] }); + const building = bind("ENG-11", { touches: ["web/src/login"] }); + const reviewing = bind("ENG-12", { stage: "review", touches: ["web/src/signup"] }); + 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 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(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"]], + ]); + expect(conflictsOf(building, s.open()).map((c) => c.with.entityKey)).toEqual(["ENG-17"]); + expect(conflictsOf(s.patch(me.id, { touches: [] }), s.open())).toEqual([]); + }); + + it("count pull requests as landed only when there is one and every one merged", () => { + const { bind } = world(); + const ticket = bind("ENG-1"); + expect(allPullsMerged(ticket, { entity: issue(), pulls: [] })).toBe(false); + expect(allPullsMerged(ticket, { entity: issue(), pulls: [pull({}, { merged: true }), pull()] })).toBe(false); + expect(allPullsMerged(ticket, { entity: issue(), pulls: [pull({}, { merged: true })] })).toBe(true); + const pr = { ...ticket, kind: "pr" as const }; + expect(allPullsMerged(pr, { entity: pull({}, { merged: true }), pulls: [] })).toBe(true); + expect(allPullsMerged(pr, { entity: pull(), pulls: [] })).toBe(false); + }); +}); diff --git a/plugins/stewards/schedule.ts b/plugins/stewards/schedule.ts new file mode 100644 index 00000000..25022ab0 --- /dev/null +++ b/plugins/stewards/schedule.ts @@ -0,0 +1,71 @@ +// Scheduling: what each binding's work touches, and which open bindings would +// change the same files at the same time. Pure; the plugin feeds it bindings +// and acts on what it says (a `schedule` escalation to the project steward, a +// hold placed behind the binding already at work). +// +// A touch is a repo-relative path with the repo directory first, as the +// steward reports it: "bb-plugins/plugins/stewards", "bb-gate/docker". Two +// bindings overlap when one touch is the other or a parent directory of it, +// so "bb-plugins" overlaps everything in that repo and +// "bb-plugins/plugins/stewards/wake.ts" overlaps "bb-plugins/plugins/stewards". +import type { Binding, Observed } from "./store.js"; + +/** A touch as compared: lower case, forward slashes, no leading "./" or surrounding slashes, inner runs of slashes collapsed. */ +export function normalizeTouch(raw: string): string { + return raw + .trim() + .replace(/\\/gu, "/") + .replace(/^(?:\.\/)+/u, "") + .replace(/\/{2,}/gu, "/") + .replace(/^\/+|\/+$/gu, "") + .toLowerCase(); +} + +/** The touches a steward reported, normalized, deduplicated, empty strings dropped. */ +export function normalizeTouches(raw: readonly string[]): string[] { + return [...new Set(raw.map(normalizeTouch).filter((t) => t !== ""))]; +} + +const under = (path: string, dir: string) => path === dir || path.startsWith(`${dir}/`); + +/** Whether two touch sets name the same place: a touch of one is, or is inside, a touch of the other. */ +export function touchesOverlap(a: readonly string[], b: readonly string[]): string[] { + const hits = new Set(); + for (const x of a) for (const y of b) if (under(x, y) || under(y, x)) hits.add(x.length >= y.length ? x : y); + return [...hits].sort(); +} + +/** + * Whether a binding is at work on its touches: being built or reviewed, 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). + */ +export const atWork = (b: Binding): boolean => + b.endedAt === null && b.ending === null && b.hold === null && (b.stage === "build" || b.stage === "review") && b.touches.length > 0 && !(b.lastSnapshot !== null && allPullsMerged(b, b.lastSnapshot)); + +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. + */ +export function conflictsOf(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)) + .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); +} + +/** + * 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 + * "all merged"; its ending is the other way a hold behind it lifts. + */ +export function allPullsMerged(b: Binding, observed: Observed): boolean { + const pulls = b.kind === "ticket" ? observed.pulls : observed.entity.pull === null ? [] : [observed.entity]; + return pulls.length > 0 && pulls.every((p) => p.pull?.merged === true); +} diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index a36ed5f1..6af822dc 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -826,6 +826,153 @@ describe("a Linear ticket steward", () => { // HUB-195/196: two escalations seconds apart, and the second prompt listed // the first as if new. HUB-183: a retried steward_update recorded its answer // twice, and the escalation kept "The binding ended." instead. +describe("scheduling overlapping work", () => { + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + const met = { checklist: [1, 2, 3, 4].map((item) => ({ item, met: true })), substantial: false, why: "one repo, small" }; + const building = { phase: "In Progress", summary: "Worker building.", nextAction: "Wait for the pull request", actor: "steward" }; + const ready = { phase: "Todo", summary: "Spec posted.", nextAction: "Start a worker", actor: "steward", ready: met, touches: ["web/src"] }; + + async function two() { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("acme/web#7", pull()); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO", url: "https://linear.app/acme/issue/ENG-13" })); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + const [project, first, second] = t.spawns.map((x) => x.id); + const toProject = () => t.sends.filter((s) => s.threadId === project); + const toSecond = () => t.sends.filter((s) => s.threadId === second); + await t.tool("steward_report", { ...building, touches: ["web/src/login", "./Web/src/login/"] }, first!); + expect(t.hooks.store.find("ENG-12")!.touches).toEqual(["web/src/login"]); + return { t, project: project!, first: first!, second: second!, toProject, toSecond }; + } + + it("asks the project steward to schedule a ready ticket that touches what another is building, holds it behind that work, and lifts the hold when it merges", async () => { + const { t, project, second, toProject, toSecond } = await two(); + expect(toProject()).toHaveLength(0); + + // ENG-13's gate passes with no approval needed: it would start now, into ENG-12's files. + const reported = await t.tool("steward_report", ready, second); + expect(reported.text).toMatch(/Ready gate: passed\. Scheduling is with the project steward \(esc_[\w-]+\): ENG-13 touches what ENG-12 is already changing\. Start no workers and do not move the ticket into a build state until it decides/u); + expect(toProject()).toHaveLength(1); + const wake = toProject()[0]!.text; + expect(wake).toMatch(/^# Project steward: scheduling requested for ENG-13/u); + expect(wake).toMatch(/from ENG-13 \(schedule\): Schedule ENG-13 \(Add SSO\)\? Its ready gate has passed, and it touches what is already being changed by ENG-12 \(In Progress\) on web\/src\/login\. Hold it behind that work with steward_update \{ binding: "ENG-13", hold: "", behind: \["ENG-12"\] \}/u); + expect(wake).toMatch(/A schedule escalation is the plugin's/u); + expect(wake).toMatch(/- ENG-12 \(ticket, In Progress\): .*\[touches web\/src\/login\]/u); + expect(wake).toMatch(/- ENG-13 \(ticket, Todo\): .*\[touches web\/src; overlaps ENG-12 on web\/src\/login; 1 escalation\(s\): schedule→project\]/u); + const id = /(esc_[\w-]+) from ENG-13 \(schedule\)/u.exec(wake)![1]!; + + // Asked once, however often the steward reports; its own wake carries the overlap and the wait. + await t.tool("steward_report", ready, second); + expect(toProject()).toHaveLength(1); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO", description: "SSO login. Out of scope: SAML." })); + await t.ring("linear", "uuid-13"); + const own = toSecond().at(-1)!.text; + expect(own).toMatch(/## 3\. Guidance, priority, holds and scheduling/u); + expect(own).toMatch(/- Touches: web\/src \(steward_report \{ touches \} replaces it\)/u); + expect(own).toMatch(/- In flight on the same paths: ENG-12 \(In Progress\) on web\/src\/login\./u); + expect(own).toMatch(new RegExp(`\\*\\*Scheduling is with the project steward \\(${id}\\)\\.\\*\\* Start no workers`, "u")); + expect(own).toMatch(/- Gate: PASSED — but scheduling is with the project steward/u); + expect((await t.harness.behavior.runCli(["show", "ENG-13"])).stdout).toContain("Touches: web/src; overlaps ENG-12 on web/src/login"); + + // The project steward holds it behind ENG-12, by key in any case: the request is answered. + const held = await t.tool("steward_update", { binding: "ENG-13", hold: "Overlaps ENG-12's login work", behind: ["eng-12"] }, project); + expect(held).toMatchObject({ error: false, text: "ENG-13: on hold: Overlaps ENG-12's login work (behind ENG-12: lifts itself once its pull requests merge or it ends)." }); + await t.flush(); + expect(t.hooks.store.find("ENG-13")!.holdBehind).toEqual(["ENG-12"]); + expect(t.hooks.store.escalation(id)!.resolution).toBe("Held behind ENG-12."); + expect(toSecond().at(-1)!.text).toMatch(/\*\*HOLD: Overlaps ENG-12's login work\*\* \(behind ENG-12: it lifts itself, and you are woken, once that binding has merged its pull requests or ended\)/u); + expect((await t.harness.behavior.runCli(["list"])).stdout).toContain("HOLD: Overlaps ENG-12's login work (behind ENG-12)"); + + // ENG-12's pull request merges: the hold lifts, ENG-13 is woken, the project steward is told. + const stewardWakes = toSecond().length; + 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")!; + expect(b13.hold).toBeNull(); + expect(b13.holdBehind).toEqual([]); + 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); + 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); + expect(toProject().filter((s) => /scheduling requested/u.test(s.text))).toHaveLength(1); + }); + + it("lets a ticket start on the project steward's word, asks again only for a new overlap, and lifts a hold when the work it waits behind ends", 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: the login form and SSO are different files.", resolve: id }, project); + await t.flush(); + const again = await t.tool("steward_report", ready, second); + expect(again.text).toMatch(/Ready gate: passed\. You will be woken/u); + expect(toProject()).toHaveLength(1); + + // A third ticket starts building on the same paths: a new overlap, asked about once more. + 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); + expect(toProject()).toHaveLength(2); + expect(toProject()[1]!.text).toMatch(/Schedule ENG-13 \(Add SSO\)\? .* already being changed by ENG-12 \(In Progress\) on web\/src\/login; ENG-14 \(In Progress\) on web\/src\/audit\. Hold it behind that work with steward_update \{ binding: "ENG-13", hold: "", behind: \["ENG-12", "ENG-14"\] \}, and it starts by itself once their pull requests merge or they end/u); + + // Held behind both; ENG-14 is canceled, ENG-12 ends: the hold lifts when the last one goes. + await t.tool("steward_update", { binding: "ENG-13", hold: "After the login and audit work", behind: ["ENG-12", "ENG-14"] }, project); + await t.flush(); + t.entities.set("uuid-14", issue({ id: "uuid-14", key: "ENG-14", title: "Audit log", state: "Canceled", stateType: "canceled" })); + await t.ring("linear", "uuid-14"); + await t.idle(third, "Done."); + expect(t.hooks.store.find("ENG-13")!.holdBehind).toEqual(["ENG-12"]); + expect(t.hooks.store.find("ENG-13")!.hold).toBe("After the login and audit work"); + t.entities.set("uuid-12", issue({ state: "Done", stateType: "completed", ...linked })); + await t.ring("linear", "uuid-12"); + await t.idle(t.spawns[1]!.id, "Done."); + expect(t.hooks.store.find("ENG-12")!.endedAt).not.toBeNull(); + 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, ended \(terminal\)/u); + }); + + it("asks from a look, without a turn of the steward's, when the overlap appears after the gate passed", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("acme/web#7", pull()); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO" })); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + const [project, first, second] = t.spawns.map((x) => x.id); + const toProject = () => t.sends.filter((s) => s.threadId === project); + // ENG-13 is ready while ENG-12 has not said what it touches: nothing to schedule against. + const reported = await t.tool("steward_report", ready, second!); + expect(reported.text).toBe("Reported. Ready gate: passed. You will be woken when something actionable changes, or in 2d. End the turn now."); + expect(toProject()).toHaveLength(0); + // ENG-12 reports its paths; ENG-13's next look (a label touch, nothing actionable) files the request and wakes nobody else. + await t.tool("steward_report", { ...building, touches: ["web/src/login"] }, first!); + const sentToSecond = t.sends.filter((s) => s.threadId === second).length; + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO", labels: ["bb-managed", "sso"] })); + await t.ring("linear", "uuid-13"); + expect(toProject()).toHaveLength(1); + expect(toProject()[0]!.text).toMatch(/^# Project steward: scheduling requested for ENG-13/u); + expect(t.sends.filter((s) => s.threadId === second)).toHaveLength(sentToSecond); + expect((await t.list()).find((b) => b.key === "ENG-13")!.escalations).toBe(1); + }); + + it("refuses behind without a hold or naming what is not an open binding here", async () => { + const { t, project } = await two(); + expect(await t.tool("steward_update", { binding: "ENG-13", behind: ["ENG-12"] }, project)).toMatchObject({ error: true, text: expect.stringMatching(/behind goes with a hold/u) }); + expect(await t.tool("steward_update", { binding: "ENG-13", hold: "Later", behind: ["ENG-99", "ENG-13"] }, project)).toMatchObject({ error: true, text: expect.stringMatching(/Not an open binding in this project to wait behind: ENG-99, ENG-13\./u) }); + expect(t.hooks.store.find("ENG-13")!.hold).toBeNull(); + // Lifting a hold by hand clears what it waited behind. + await t.tool("steward_update", { binding: "ENG-13", hold: "Later", behind: ["ENG-12"] }, project); + await t.tool("steward_update", { binding: "ENG-13", hold: "" }, project); + expect(t.hooks.store.find("ENG-13")).toMatchObject({ hold: null, holdBehind: [] }); + }); +}); + describe("escalations delivered once, updates safe to retry", () => { /** Two tickets with their stewards, and a way for each to escalate. */ async function two() { diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 77c6398e..c337c39a 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -65,6 +65,7 @@ import { } from "./source-contract.js"; import { ACTORS, MIGRATIONS, NEEDS_KINDS, createStore, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Need, type Observed, type Question, type ReadyState, type Store } from "./store.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; +import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; import { PROJECT_STEWARD_INTRO, formatDepsWake, formatOpsWake, formatProjectWake, formatSessionWake, formatWake, workerQuestion, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; @@ -1002,6 +1003,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P needs: store.openNeeds(b.id), own: ownThreads(b), label: config.file.label, + conflicts: conflictsOf(b, store.open(b.projectId)), now: now(), }); if (!(await deliverWake(b, config, playbook, text))) return; @@ -1142,6 +1144,9 @@ 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 }); 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"); + const scheduling = await syncScheduleRequest(b, playbook); /** * Keep news for the next turn: what is actionable as a reason for it, the * rest as quiet notes. A quiet comment count is not kept: the next wake @@ -1161,9 +1166,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // No turn is coming to report the gate, so look at it here: a gate // left waiting on its approver (a report from before this check, a // request declined, then the spec changed) is asked for now. - if (!b.awaitingReport && (await syncApprovalRequest(b, playbook)) !== null) await wakeProject(b.projectId, `approval requested for ${b.entityKey}`, { digestDue: false }); + const approvalAsked = !b.awaitingReport && (await syncApprovalRequest(b, playbook)) !== null; + const asked = [approvalAsked ? `approval requested for ${b.entityKey}` : null, scheduling === null ? null : `scheduling requested for ${b.entityKey}`].filter((r) => r !== null); + if (asked.length > 0) await wakeProject(b.projectId, asked.join(" and "), { digestDue: false }); return; } + if (scheduling !== null) await wakeProject(b.projectId, `scheduling requested for ${b.entityKey}`, { digestDue: false }); const lines = [...new Set(changes.map((c) => c.text))]; // Not now: keep the news as notes, delivered at the next turn. A held @@ -1553,6 +1561,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P async function finishEnding(b: Binding, reason: string): Promise { b = store.patch(b.id, { ending: null, endingAt: null, followThrough: null, followThroughUntil: null, endedAt: now(), endReason: reason, awaitingReport: false, requeueAt: null }); for (const x of store.openEscalations(b.id)) store.resolve(x.id, "The binding ended."); + await releaseBehind(b, `ended (${reason})`); await stopWorkers(b); const info = b.threadId === null ? null : await threadInfo(b.threadId).catch(() => null); if (info !== null && info.deletedAt === null && info.archivedAt === null) { @@ -1863,6 +1872,79 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return x; } + /** + * Keep the scheduling request in step with the world. A ticket whose ready + * gate has passed, with no worker running yet, that touches what another + * binding is already building or reviewing, is the project steward's to + * schedule: one `schedule` escalation is open with it, naming the overlap. + * It is the plugin's, like the approval request, so the ticket steward + * waits rather than starting a worker into a rebase. The project steward + * either holds the ticket behind that work (`steward_update { hold, behind }`, + * which resolves the request and lifts itself when the work lands) or lets + * it start (guidance + resolve). A decided request is not made again for + * the same bindings; a new overlap asks again. + * + * Returns a request just filed, for the caller to wake the project steward. + */ + async function syncScheduleRequest(b: Binding, playbook: Playbook): Promise { + const open = store.openEscalations(b.id).filter((x) => x.kind === "schedule"); + const withdraw = (why: string) => { + for (const x of open) store.resolve(x.id, why); + return null; + }; + if (b.kind !== "ticket" || b.endedAt !== null || b.ending !== null || b.lastSnapshot === null) return withdraw("Withdrawn."); + if (b.hold !== null) return withdraw("Held."); + const gate = gateState(playbook, b.ready, specHashFor(b, b.lastSnapshot.entity)); + if (!gate.passed) return withdraw("Withdrawn: the ready gate no longer passes."); + if (b.stage === "review" || store.workers(b.id).some((w) => w.status === "running")) return withdraw("Withdrawn: the work has started."); + const conflicts = conflictsOf(b, store.open(b.projectId)); + if (conflicts.length === 0) return withdraw("Withdrawn: nothing in flight overlaps it now."); + const keys = conflicts.map((c) => c.with.entityKey); + if (open.length > 0 || keys.every((k) => b.scheduleAsked.includes(k))) return null; + store.patch(b.id, { scheduleAsked: keys }); + const overlap = conflicts.map((c) => `${c.with.entityKey} (${c.with.phase ?? "?"}) on ${c.on.join(", ")}`).join("; "); + const x = store.escalate({ + bindingId: b.id, + kind: "schedule", + question: + `Schedule ${b.entityKey}${b.title === null ? "" : ` (${b.title})`}? Its ready gate has passed, and it touches what is already being changed by ${overlap}. ` + + `Hold it behind that work with steward_update { binding: "${b.entityKey}", hold: "", behind: [${keys.map((k) => JSON.stringify(k)).join(", ")}] }, and it starts by itself once ${keys.length === 1 ? "that ticket's pull requests merge or it ends" : "their pull requests merge or they end"}; or let it start now with steward_update { binding: "${b.entityKey}", guidance: "Start now: ", resolve: "" }.`, + meanwhile: "Waiting: no implementation workers start until it is scheduled.", + route: "project", + recommendation: null, + }); + bb.log.info(`stewards: ${b.entityKey} overlaps ${keys.join(", ")}; asked the project steward to schedule it (${x.id})`); + return x; + } + + /** + * 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 + * it, lift the holds with nothing left to wait for, wake those stewards, + * and tell the project steward. A lifted binding that now overlaps other + * work asks to be scheduled again on its next look. + */ + async function releaseBehind(b: Binding, how: string): Promise { + 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[] = []; + for (const h of waiting) { + const rest = h.holdBehind.filter((k) => lc(k) !== key); + if (rest.length > 0) { + store.patch(h.id, { holdBehind: rest }); + store.note(h.id, `${b.entityKey} ${how}; your hold stays until ${rest.join(", ")} ${rest.length === 1 ? "does" : "do"} too.`, true); + 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); + 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 shortSha = (sha: string | null | undefined) => (sha === null || sha === undefined ? "?" : sha.slice(0, 7)); /** Every pull request a binding observes: a pr binding's own entity, and a ticket's linked pulls. */ @@ -2748,6 +2830,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .optional() .describe("The ready gate as you judge it now: every checklist item from the wake, by its number, met or not, and whether the ticket is substantial."), voidApproval: z.boolean().optional().describe("The spec changed materially since approval: void it and ask again."), + touches: z + .array(z.string().trim().min(1).max(200)) + .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.'), needs: z .array( z.object({ @@ -2878,9 +2965,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P awaitingReport: false, missedReports: 0, ready, + ...(input.touches === undefined ? {} : { touches: normalizeTouches(input.touches) }), ...(b.ending === "terminal" ? { followThrough: input.followThrough ?? null, followThroughUntil } : {}), }); const requested = playbook === null ? null : await syncApprovalRequest(b, playbook); + const scheduling = playbook === null ? null : await syncScheduleRequest(b, playbook); for (const n of input.needs ?? []) { store.fileNeed({ bindingId: b.id, @@ -2898,8 +2987,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); } if (playbook !== null && b.lastSnapshot !== null) await syncNeeds(b, b.lastSnapshot, playbook, anyWorkerInFlight(store.workers(b.id))); - if (raised !== null && !(raised.route === "project" && requested !== null)) await deliver(b, raised); - if (requested !== null) await wakeProject(b.projectId, raised === null ? `approval requested for ${b.entityKey}` : `escalation and approval request from ${b.entityKey}`, { digestDue: false }); + const requests = [requested === null ? null : "approval", scheduling === null ? null : "scheduling"].filter((r) => r !== null); + if (raised !== null && !(raised.route === "project" && requests.length > 0)) await deliver(b, raised); + if (requests.length > 0) await wakeProject(b.projectId, raised !== null && raised.route === "project" ? `escalation and ${requests.join(" and ")} request from ${b.entityKey}` : `${requests.join(" and ")} requested for ${b.entityKey}`, { digestDue: false }); if (moved && b.parentBindingId !== null) { const parent = store.binding(b.parentBindingId); if (parent !== null && parent.endedAt === null) tell(threadId, parent, `Child ${b.entityKey}: ${status.summary} Next: ${status.nextAction} (${status.actor})`); @@ -2924,6 +3014,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P gateNote += " Do not ask the user again; it is listed on the Stewards page."; if (asksForOpenApproval(status, store.openEscalations(b.id), store.openNeeds(b.id)) !== null) gateNote += " This report asks for an approval that is already open: a playbook violation, shown by bb stewards show."; } + const schedule = store.openEscalations(b.id).find((x) => x.kind === "schedule"); + const askedAbout = store.binding(b.id)?.scheduleAsked ?? b.scheduleAsked; + if (schedule !== undefined) gateNote += ` Scheduling is with the project steward (${schedule.id}): ${b.entityKey} touches what ${askedAbout.join(", ")} ${askedAbout.length === 1 ? "is" : "are"} already changing. Start no workers and do not move the ticket into a build state until it decides; wait for its guidance or hold.`; if (b.ending === "terminal") { if (b.followThrough === null) return `Reported.${escalated} The binding ends when this turn does: running workers are stopped and the thread is archived. End the turn now.`; return `Reported.${escalated} The binding stays open to follow through until ${iso(followThroughUntil!)}; running workers keep going. You will be woken when a worker finishes or something actionable changes, or in ${formatDuration(requeueMs)}. End the turn now.`; @@ -2959,6 +3052,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P recommendation: z.string().trim().max(1500).optional().describe("Your recommendation, when forwarding."), priority: z.enum(["urgent", "high", "normal", "low"]).optional(), hold: z.string().trim().max(300).optional().describe('Why it is held; "" lifts the hold. A held steward takes no new actions and starts no workers.'), + behind: z + .array(z.string().trim().min(1).max(100)) + .max(10) + .optional() + .describe("With hold: the open bindings (entity keys) this hold waits behind. The hold lifts itself, and the steward is woken, once every one has merged its pull requests or ended. Use it to schedule a ticket after the work it overlaps."), stewardModel: modelSpecSchema.optional().describe("The steward thread's model, provider/model/level."), workerModel: modelSpecSchema.optional().describe("The model for workers it starts from now."), approve: z.boolean().optional().describe("Approve the ticket's current spec for the ready gate."), @@ -3026,7 +3124,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const target = bindingRef === undefined ? (projectOf !== null ? null : ownBinding(threadId)) : store.find(bindingRef); if (bindingRef !== undefined && target === null) return toolError(new Error(`No binding for ${bindingRef}.`)); if (target === null) { - const forBinding = [guidance, resolve, input.forward, input.recommendation, input.priority, input.hold, input.stewardModel, input.workerModel, input.approve, input.quote]; + const forBinding = [guidance, resolve, input.forward, input.recommendation, input.priority, input.hold, input.behind, input.stewardModel, input.workerModel, input.approve, input.quote]; if (forBinding.some((v) => v !== undefined)) return toolError(new Error("Name the binding (binding: ENG-12 or owner/repo#3) for that.")); if (closing === null && input.ask === undefined) return toolError(new Error("Nothing to update: name a binding, ask a question, or close one.")); return `${questionWrites(closing, null).join("; ")}.`; @@ -3095,9 +3193,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const info = await threadInfo(target.threadId); if (info !== null && info.providerId !== "" && info.providerId !== input.stewardModel.providerId) return toolError(new Error(`${target.entityKey}'s steward runs on ${info.providerId}; a model can be changed, the provider cannot.`)); } - const asked = [guidance, resolve, input.forward, input.priority, input.hold, input.stewardModel, input.workerModel, input.approve === true ? true : undefined, input.ask, closing ?? undefined]; + const asked = [guidance, resolve, input.forward, input.priority, input.hold, input.behind, input.stewardModel, input.workerModel, input.approve === true ? true : undefined, input.ask, closing ?? undefined]; if (asked.every((v) => v === undefined)) return toolError(new Error("Nothing to update: give guidance, resolve, forward, priority, hold, a model, approve, or ask.")); } + const behind: Binding[] = []; + if (input.behind !== undefined) { + if (input.hold === undefined || input.hold === "") return toolError(new Error("behind goes with a hold: say why it is held, and name the bindings it waits behind.")); + const missing: string[] = []; + for (const k of input.behind) { + const other = store.find(k, target.projectId); + if (other === null || other.endedAt !== null || other.id === target.id) missing.push(k); + else if (!behind.some((x) => x.id === other.id)) behind.push(other); + } + if (missing.length > 0) return toolError(new Error(`Not an open binding in this project to wait behind: ${missing.join(", ")}.`)); + } done.push(...questionWrites(closing, target)); if (forwarding !== null) { @@ -3151,10 +3260,19 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (outcome !== "unchanged") notes.push(`Escalation ${resolving.id} decided: ${guidance}`); } if (input.priority !== undefined || input.hold !== undefined) { - store.patch(target.id, { ...(input.priority === undefined ? {} : { priority: input.priority }), ...(input.hold === undefined ? {} : { hold: input.hold === "" ? null : input.hold }) }); - const what = [input.priority === undefined ? null : `priority ${input.priority}`, input.hold === undefined ? null : input.hold === "" ? "hold lifted" : `on hold: ${input.hold}`].filter((s) => s !== null).join("; "); + const behindKeys = behind.map((x) => x.entityKey); + store.patch(target.id, { + ...(input.priority === undefined ? {} : { priority: input.priority }), + ...(input.hold === undefined ? {} : { hold: input.hold === "" ? null : input.hold, holdBehind: behindKeys }), + }); + const behindNote = behindKeys.length === 0 ? "" : ` (behind ${behindKeys.join(", ")}: lifts itself once ${behindKeys.length === 1 ? "its pull requests merge or it ends" : "their pull requests merge or they end"})`; + const what = [input.priority === undefined ? null : `priority ${input.priority}`, input.hold === undefined ? null : input.hold === "" ? "hold lifted" : `on hold: ${input.hold}${behindNote}`].filter((s) => s !== null).join("; "); done.push(what); notes.push(`Set by your ${isProjectSteward(threadId, target) ? "project" : "parent"} steward: ${what}`); + // A hold answers an open scheduling request. A hold lifted by hand closes it too; the next look asks again if it must. + if (input.hold !== undefined) { + for (const x of store.openEscalations(target.id).filter((e) => e.kind === "schedule")) store.resolve(x.id, input.hold === "" ? "Hold lifted." : behindKeys.length === 0 ? `Held: ${input.hold}` : `Held behind ${behindKeys.join(", ")}.`); + } } if (input.stewardModel !== undefined && target.threadId !== null) { await bb.sdk.threads.update({ threadId: target.threadId, ...(input.stewardModel.model === null ? {} : { model: input.stewardModel.model }), ...(input.stewardModel.reasoningLevel === null ? {} : { reasoningLevel: input.stewardModel.reasoningLevel }) }); @@ -3205,7 +3323,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const look = b.opsLook; const watch = look === null ? null : look.error !== null ? `cannot read the target: ${look.error}` : `looked ${iso(look.at)}: ${look.findings.length === 0 ? "nothing failing" : `${look.findings.length} problem(s) failing`}`; 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}`, ...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.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"); @@ -3472,6 +3590,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (input.options.json) return { exitCode: 0, stdout: JSON.stringify(detail) }; const lines = [formatBindings([b]), "", `Playbook ${b.playbook}@${b.playbookVersion}; stage ${b.stage ?? "?"}; created ${iso(b.createdAt)}${b.requeueAt === null ? "" : `; requeue ${iso(b.requeueAt)}`}`]; if (b.kind !== "ops") lines.push(`Ready: ${b.ready.checklist.map((c) => `[${c.met ? "x" : " "}] ${c.item}`).join("; ") || "not reported"}; substantial ${b.ready.substantial ?? "?"}; approval ${b.ready.approval === null ? "none" : iso(b.ready.approval.at)}`); + if (b.kind !== "ops") { + const conflicts = conflictsOf(b, store.open(b.projectId)); + lines.push(`Touches: ${b.touches.join(", ") || "not reported"}${conflicts.length === 0 ? "" : `; overlaps ${conflicts.map((c) => `${c.with.entityKey} on ${c.on.join(", ")}`).join("; ")}`}`); + } for (const g of b.guidance) lines.push(`Guidance ${iso(g.at)}: ${g.text}`); for (const x of detail.escalations) lines.push(`Escalation ${x.id} ${x.kind} (${x.status}, ${x.route}): ${x.question}${x.resolution === null ? "" : ` → ${x.resolution}`}`); for (const n of store.needs(b.id, true)) lines.push(`Need ${n.id} ${n.kind} (${n.status}): ${n.what}${n.url === "" ? "" : ` — ${n.url}`}${n.resolution === null ? "" : ` → ${n.resolution}`}`); diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 7731bde3..82b036c1 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -115,7 +115,17 @@ Two tools are yours; everything else you do with the tools every thread has. - **Holds.** A held binding takes no new actions and starts no workers. You may put your own binding on hold (`steward_update { hold }`), for instance when the user says to halt, but only your parent or the project - steward lifts it. + steward lifts it. A hold placed `behind` other bindings lifts itself, and + wakes you, once each has merged its pull requests or ended. +- **Report what you touch, and let the project steward schedule you.** As + 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 + 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 + start. Do not escalate for it. - **@bb mentions.** A wake headed "Linear mention" is someone's `@bb` on your issue. Do what it says, end with exactly one `linear_session_reply` for its session, and then `steward_report`. If it is marked untrusted, it @@ -175,7 +185,19 @@ 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. When the user acts on +with `guidance` + `resolve` saying what must change. 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 +`schedule` escalation the plugin files. Usually it waits: +`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 +hold the other one instead), let it start with `guidance` ("Start now: …") ++ `resolve`; it is not asked again until a new overlap appears. The +bindings list in every wake shows touches and overlaps, so the same hold +sequences any two tickets, asked or not. When the user acts on an entity whose escalation you forwarded to them — edits the ticket, comments, moves it — you are woken with the change: if it answers the escalation, record it with `guidance` + `resolve`; if not, leave it open. diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 3a7279a8..68d973f8 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -163,6 +163,12 @@ export const MIGRATIONS = [ // alert can be batched against the open ticket for its repo and ecosystem. `ALTER TABLE ops_fingerprints ADD COLUMN severity TEXT`, `ALTER TABLE ops_fingerprints ADD COLUMN ecosystem TEXT`, + // Scheduling: the paths a binding's work changes (steward_report touches), the open + // bindings a hold waits behind (steward_update hold + behind), and the conflicts + // the project steward was last asked to schedule it against. + `ALTER TABLE bindings ADD COLUMN touches TEXT NOT NULL DEFAULT '[]'`, + `ALTER TABLE bindings ADD COLUMN hold_behind TEXT NOT NULL DEFAULT '[]'`, + `ALTER TABLE bindings ADD COLUMN schedule_asked TEXT NOT NULL DEFAULT '[]'`, ]; // ---- values kept as JSON ------------------------------------------------------------ @@ -245,6 +251,12 @@ export type Binding = { ready: ReadyState; priority: string | null; hold: string | null; + /** The repo-relative paths this binding's work changes, as reported; what scheduling compares. */ + 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 the project steward was last asked to schedule this binding against; asked again only for a new one. */ + scheduleAsked: string[]; modelSteward: string | null; modelWorker: string | null; status: StatusRecord | null; @@ -305,6 +317,9 @@ function rowToBinding(r: BindingRow): Binding { ready: json(readyStateSchema, str("ready"), readyDefault()), priority: str("priority"), hold: str("hold"), + touches: json(z.array(z.string()), str("touches"), []), + holdBehind: json(z.array(z.string()), str("hold_behind"), []), + scheduleAsked: json(z.array(z.string()), str("schedule_asked"), []), modelSteward: str("model_steward"), modelWorker: str("model_worker"), status: json(statusRecordSchema.nullable(), str("status"), null), @@ -347,6 +362,9 @@ const COLUMNS = { ready: "ready", priority: "priority", hold: "hold", + touches: "touches", + holdBehind: "hold_behind", + scheduleAsked: "schedule_asked", modelSteward: "model_steward", modelWorker: "model_worker", status: "status", diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index 220c6625..c2ca3356 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -93,10 +93,15 @@ Specify the ticket against the ready checklist. Work out what you can — acceptance criteria, affected repos, a plan — from the code and the project's docs, and post it as spec comments. Ask only what you cannot work out, as a decision escalation, one question at a time. Report the checklist on every -turn. When it is all met and the ticket is substantial, the plugin asks the -project steward to approve the spec: wait for it, and do not escalate for -it. Otherwise, or once approved, move the ticket to In Progress. A new spec -needs approval again, and is asked for the same way. +turn, and the paths the work changes (steward_report touches, repo directory +first) as soon as the spec names them. When it is all met and the ticket is +substantial, the plugin asks the project steward to approve the spec: wait +for it, and do not escalate for it. When the gate passes but the wake says +scheduling is with the project steward (the paths overlap work in flight), +wait for that too: it holds you behind that work, and the hold lifts itself +when the work lands, or it tells you to start. Otherwise, or once approved +and scheduled, move the ticket to In Progress. A new spec needs approval +again, and is asked for the same way. If the plan is several slices, file sub-issues. Promote one (label it) only when it fits the promote rule; otherwise your workers do it here. @@ -104,7 +109,9 @@ when it fits the promote rule; otherwise your workers do it here. ## In Progress If the ready gate has not passed, start no workers: escalate a conflict and -wait. Otherwise start one worker per pull request with a precise task: the +wait. If scheduling is with the project steward or the binding is held, start +no workers either; you are woken when it decides or the hold lifts. Otherwise +start one worker per pull request with a precise task: the repo, the branch, the acceptance criteria, and "open a draft pull request, link it to the ticket, and stop when checks pass". When the pull requests are ready, request review and move the ticket to In Review. diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index b2455496..68bc757a 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -11,6 +11,7 @@ import { FINDING_CLASSES, type FindingClass, type OpsFinding, type OpsLook } fro import type { DepsFinding, DepsLook } from "./deps.js"; import { dueDate } from "./deps.js"; import { newHumanComments, prGate, reportedItem, unheardWait, type GateState } from "./reconcile.js"; +import { conflictsOf, type Conflict } from "./schedule.js"; import type { EntitySnapshot, SessionWake, SnapshotComment } from "./source-contract.js"; import type { Binding, Escalation, Need, Observed, Question, Worker } from "./store.js"; @@ -148,6 +149,8 @@ export type WakeInput = { own: ReadonlySet; /** The project's adoption label. */ label: string; + /** Open bindings already at work on what this one touches. */ + conflicts?: Conflict[]; now: number; }; @@ -220,7 +223,29 @@ function gateLines(input: WakeInput): string[] { if (!gate.approvalNeeded) lines.push("- Approval: not needed"); else if (!gate.approved) lines.push(`- Approval: not given (given by ${how})${binding.ready.voidedAt === null ? "" : `; the last one was voided ${iso(binding.ready.voidedAt)}`}.${asked}`); else lines.push(`- Approval: given ${iso(binding.ready.approval!.at)}${gate.approvalStale ? ` — the spec has changed since, so the gate needs it again.${asked}` : ""}`); - lines.push(`- Gate: ${gate.passed ? "PASSED" : "not passed — start no implementation workers"}`); + const scheduling = input.escalations.find((x) => x.status === "open" && x.kind === "schedule"); + lines.push(`- Gate: ${gate.passed ? (scheduling === undefined ? "PASSED" : `PASSED — but scheduling is with the project steward (${scheduling.id}, see 3): start no implementation workers and do not move the ticket into a build state until it decides`) : "not passed — start no implementation workers"}`); + return lines; +} + +/** The hold line of a wake: the reason, and what it waits behind when it was placed to schedule. */ +const holdLine = (binding: Binding, then: string): string => + binding.hold === null + ? "- Hold: none" + : `- **HOLD: ${binding.hold}**${binding.holdBehind.length === 0 ? "" : ` (behind ${binding.holdBehind.join(", ")}: it lifts itself, and you are woken, once ${binding.holdBehind.length === 1 ? "that binding has merged its pull requests or ended" : "each of them has merged its pull requests or ended"})`} — ${then}`; + +/** Section 3's scheduling lines for a ticket or pull request binding: what it touches, and what is in flight on the same paths. */ +function schedulingLines(binding: Binding, conflicts: Conflict[], escalations: Escalation[]): string[] { + if (binding.kind !== "ticket" && binding.kind !== "pr") return []; + const lines = [ + binding.touches.length === 0 + ? "- Touches: not reported. Report the repo-relative paths the work changes, repo directory first, with steward_report { touches: [\"/\", …] } as soon as the spec names them, and refine it as pull requests open: the project steward schedules tickets that touch the same paths one after another." + : `- Touches: ${binding.touches.join(", ")} (steward_report { touches } replaces it)`, + ]; + if (conflicts.length > 0) lines.push(`- In flight on the same paths: ${conflicts.map((c) => `${c.with.entityKey} (${c.with.phase ?? "?"}) on ${c.on.join(", ")}`).join("; ")}.`); + const scheduling = escalations.find((x) => x.status === "open" && x.kind === "schedule"); + if (scheduling !== undefined) lines.push(`- **Scheduling is with the project steward (${scheduling.id}).** Start no workers and do not move the ticket into a build state until it decides: it holds you behind that work (the hold lifts itself when the work lands) or tells you to start. Do not escalate for it.`); + else if (conflicts.length > 0 && binding.hold === null) lines.push("- Once your ready gate passes, the plugin asks the project steward to schedule you against that work; do not escalate for it."); return lines; } @@ -272,11 +297,12 @@ export function formatWake(input: WakeInput): string { out.push("", "These are on the Stewards page with their own buttons. Do not ask the user about them in prose; the page is where they act."); } - out.push("", "## 3. Guidance, priority and holds", ""); + out.push("", "## 3. Guidance, priority, holds and scheduling", ""); if (binding.guidance.length === 0) out.push("No standing guidance."); for (const g of binding.guidance) out.push(`- ${iso(g.at)} (${g.by}): ${g.text}`); out.push(`- Priority: ${binding.priority ?? "normal"}`); - out.push(binding.hold === null ? "- Hold: none" : `- **HOLD: ${binding.hold}** — take no new actions and start no workers until it is lifted.`); + out.push(holdLine(binding, "take no new actions and start no workers until it is lifted.")); + out.push(...schedulingLines(binding, input.conflicts ?? [], input.escalations)); const head = out.splice(0); out.push("", "## 4. Snapshot", ""); @@ -556,6 +582,12 @@ export function formatProjectWake(input: { "", ); } + if (input.routed.some((r) => r.escalation.kind === "schedule")) { + out.push( + "A schedule escalation is the plugin's: the ticket's ready gate has passed, and it touches paths another binding is already building or reviewing, so starting it now means two branches changing the same files and a rebase for whichever merges second. Decide the order from the project's guidance and priorities. Usually the ticket waits: steward_update { binding, hold: \"\", behind: [] } holds it behind that work and resolves the request; the hold lifts itself, and the steward is woken, once every binding named has merged its pull requests or ended. When the overlap is harmless or the new ticket matters more (then consider holding the other one instead), let it start: steward_update { binding, guidance: \"Start now: \", resolve }. A hold is also how you sequence any two tickets, asked or not.", + "", + ); + } if (input.routed.some((r) => r.escalation.kind === "approval")) { 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.", @@ -590,9 +622,11 @@ export function formatProjectWake(input: { } const head = out.splice(0); out.push(`## Bindings (${input.bindings.length} open)`, ""); + const allOpen = input.bindings.map((x) => x.binding); for (const { binding: b, openEscalations } of input.bindings.slice(0, 200)) { const s = b.status; - const flags = [b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}`, openEscalations.length > 0 ? `${openEscalations.length} escalation(s): ${openEscalations.map((x) => `${x.kind}→${x.route}`).join(", ")}` : null, unheardWait(s, openEscalations)].filter((f): f is string => f !== null); + const conflicts = conflictsOf(b, allOpen); + const flags = [b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}`, b.touches.length === 0 ? null : `touches ${b.touches.join(", ")}`, conflicts.length === 0 ? null : `overlaps ${conflicts.map((c) => `${c.with.entityKey} on ${c.on.join(", ")}`).join("; ")}`, openEscalations.length > 0 ? `${openEscalations.length} escalation(s): ${openEscalations.map((x) => `${x.kind}→${x.route}`).join(", ")}` : null, unheardWait(s, openEscalations)].filter((f): f is string => f !== null); out.push(`- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}): ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${s.blockedOn === null ? "" : `; blocked on ${s.blockedOn}`}`}${flags.length > 0 ? ` [${flags.join("; ")}]` : ""}`); } const bindings = out.splice(0); @@ -780,7 +814,7 @@ export function formatRecords(r: DigestRecords, questions: Array<{ question: Que const stuck = [ ...r.stuck.map(({ escalation: x, from }) => `- ${from.entityKey}: stuck escalation ${x.id} with ${x.route}, since ${day(x.createdAt)}: ${oneLine(x.question)}`), - ...r.held.map((b) => `- ${b.entityKey}: on hold: ${oneLine(b.hold ?? "")}`), + ...r.held.map((b) => `- ${b.entityKey}: on hold: ${oneLine(b.hold ?? "")}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}`), ]; out.push("### Stuck or held", "", ...capped(stuck, "Nothing.")); return out; @@ -793,6 +827,7 @@ export const PROJECT_STEWARD_INTRO = `You are this project's steward. Every Line - steward_update sets guidance, priority, holds and models on any binding, approves a substantial ticket's spec, and resolves or forwards escalations. - Before you ask the user something in a reply, record it with steward_update { ask: { question, context } } (with binding when it concerns one); close it with steward_update { resolve: "", answer } when they answer. Every wake lists the questions still open, so list them from there, not from memory. - You are woken by escalations, at the end of each nightly pass to write the morning digest, and by the user. When the user says something like "hold everything touching billing", turn it into steward_update calls on the bindings it concerns, and say what you changed. +- You schedule the work so that two tickets do not change the same files at once. Every binding reports what it touches; when a ready ticket overlaps work in flight, the plugin asks you with a schedule escalation. Hold it behind that work (steward_update { binding, hold, behind: [keys] }: the hold lifts itself when the work lands) or let it start (guidance + resolve). Use the same hold to sequence any two tickets whose overlap you can see in the bindings list. - Budget is advisory: keep the total work sensible through priority and holds. Wait for the user or a wake; there is nothing to do right now.`; From c510b3d15b260d8bd94ece01634108cd1ce9160b Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Tue, 20 Oct 2026 12:40:22 +0000 Subject: [PATCH 2/2] stewards: close the scheduling races - A ticket whose gate has passed with nothing holding or scheduling it is cleared to start and counts as in flight at once, so a second ticket going ready before Linear shows the first In Progress schedules against it instead of racing it. - A binding reaching a terminal state, or detached, releases the holds waiting behind it as its ending begins, not when it finishes: a wrap-up turn that follows through for hours no longer delays the lift. - A hold that would wait, directly or through other holds, behind the binding being held is refused as a cycle. Co-Authored-By: Claude Fable 5.1 --- plugins/stewards/README.md | 10 +++++-- plugins/stewards/schedule.ts | 16 ++++++++--- plugins/stewards/server.test.ts | 45 ++++++++++++++++++++++++++++-- plugins/stewards/server.ts | 49 +++++++++++++++++++++++++++------ plugins/stewards/store.ts | 6 ++++ 5 files changed, 110 insertions(+), 16 deletions(-) diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 7b7b02d0..9be7c5ec 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -95,8 +95,14 @@ 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. Work whose pull requests - have all merged no longer counts as in flight. `bb stewards show` prints + 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 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 diff --git a/plugins/stewards/schedule.ts b/plugins/stewards/schedule.ts index 25022ab0..28024075 100644 --- a/plugins/stewards/schedule.ts +++ b/plugins/stewards/schedule.ts @@ -36,12 +36,20 @@ export function touchesOverlap(a: readonly string[], b: readonly string[]): stri } /** - * Whether a binding is at work on its touches: being built or reviewed, 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). + * 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). */ export const atWork = (b: Binding): boolean => - b.endedAt === null && b.ending === null && b.hold === null && (b.stage === "build" || b.stage === "review") && b.touches.length > 0 && !(b.lastSnapshot !== null && allPullsMerged(b, b.lastSnapshot)); + 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)); export type Conflict = { with: Binding; on: string[] }; diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 6af822dc..89fb1b1e 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -929,12 +929,16 @@ describe("scheduling overlapping work", () => { await t.idle(third, "Done."); expect(t.hooks.store.find("ENG-13")!.holdBehind).toEqual(["ENG-12"]); expect(t.hooks.store.find("ENG-13")!.hold).toBe("After the login and audit 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 })); 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); await t.idle(t.spawns[1]!.id, "Done."); expect(t.hooks.store.find("ENG-12")!.endedAt).not.toBeNull(); - 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, ended \(terminal\)/u); + expect(toProject().filter((s) => /Lifted the hold on ENG-13/u.test(s.text))).toHaveLength(1); }); it("asks from a look, without a turn of the steward's, when the overlap appears after the gate passed", async () => { @@ -970,6 +974,43 @@ describe("scheduling overlapping work", () => { await t.tool("steward_update", { binding: "ENG-13", hold: "Later", behind: ["ENG-12"] }, project); await t.tool("steward_update", { binding: "ENG-13", hold: "" }, project); expect(t.hooks.store.find("ENG-13")).toMatchObject({ hold: null, holdBehind: [] }); + // No cycles, direct or through a third binding. + t.entities.set("uuid-14", issue({ id: "uuid-14", key: "ENG-14", title: "Audit log" })); + await t.ring("linear", "uuid-14"); + await t.tool("steward_update", { binding: "ENG-13", hold: "Later", behind: ["ENG-12"] }, project); + expect(await t.tool("steward_update", { binding: "ENG-12", hold: "Later", behind: ["ENG-13"] }, project)).toMatchObject({ error: true, text: expect.stringMatching(/ENG-12 cannot wait behind ENG-13: ENG-13 already waits behind ENG-12, so neither hold would ever lift\./u) }); + await t.tool("steward_update", { binding: "ENG-14", hold: "Later", behind: ["ENG-13"] }, project); + expect(await t.tool("steward_update", { binding: "ENG-12", hold: "Later", behind: ["ENG-14"] }, project)).toMatchObject({ error: true, text: expect.stringMatching(/ENG-12 cannot wait behind ENG-14: ENG-13 already waits behind ENG-12/u) }); + expect(t.hooks.store.find("ENG-12")!.hold).toBeNull(); + }); + + it("schedules against a ticket that is cleared to start before Linear shows it In Progress", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO" })); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + const [project, first, second] = t.spawns.map((x) => x.id); + const toProject = () => t.sends.filter((s) => s.threadId === project); + // Both still Todo in Linear. ENG-12's gate passes with nothing in flight: it is cleared, and about to move itself. + await t.tool("steward_report", { ...ready, touches: ["web/src/login"] }, first!); + expect(t.hooks.store.find("ENG-12")!.clearedToStart).toBe(true); + expect(toProject()).toHaveLength(0); + // ENG-13's gate passes a moment later: it schedules against ENG-12 rather than racing it. + const reported = await t.tool("steward_report", ready, second!); + expect(reported.text).toMatch(/Scheduling is with the project steward \(esc_[\w-]+\): ENG-13 touches what ENG-12 is already changing/u); + expect(t.hooks.store.find("ENG-13")!.clearedToStart).toBe(false); + expect(toProject()).toHaveLength(1); + expect(toProject()[0]!.text).toMatch(/already being changed by ENG-12 \(Todo\) on web\/src\/login/u); + // Held, it stops counting as in flight; told to start, it counts again. + 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(); + await t.tool("steward_report", ready, second!); + expect(t.hooks.store.find("ENG-13")!.clearedToStart).toBe(true); + await t.tool("steward_update", { binding: "ENG-12", hold: "Not yet" }, project!); + await t.flush(); + expect(t.hooks.store.find("ENG-12")!.clearedToStart).toBe(false); }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index c337c39a..190c1352 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -1535,7 +1535,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * watch, production to verify); they are stopped when it ends. */ async function beginEnding(b: Binding, config: ProjectConfig, playbook: Playbook, kind: "terminal" | "detach", observed: Observed): Promise { - b = store.patch(b.id, { ending: kind, endingAt: now(), followThrough: null, followThroughUntil: null, lastSnapshot: observed }); + b = store.patch(b.id, { ending: kind, endingAt: now(), followThrough: null, followThroughUntil: null, lastSnapshot: observed, clearedToStart: false }); + // Whatever its work was holding back can go now: landed, canceled or no longer managed, it is not merging later. + await releaseBehind(b, kind === "terminal" ? `reached ${observed.entity.state}` : "was detached"); if (kind === "detach") await stopWorkers(b); bb.log.info(`stewards: ${b.entityKey} ${kind === "terminal" ? `reached ${observed.entity.state}` : "was detached"}; one last turn`); if (b.threadId === null) { @@ -1888,19 +1890,34 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P */ async function syncScheduleRequest(b: Binding, playbook: Playbook): Promise { const open = store.openEscalations(b.id).filter((x) => x.kind === "schedule"); - const withdraw = (why: string) => { + // Cleared: the gate has passed and nothing holds or schedules it, so it + // is starting now, and the next ticket to pass its gate, before Linear + // shows this one In Progress, schedules against it rather than racing it. + const cleared = (v: boolean) => { + if (b.clearedToStart !== v) store.patch(b.id, { clearedToStart: v }); + }; + const withdraw = (why: string, startable: boolean) => { for (const x of open) store.resolve(x.id, why); + cleared(startable); return null; }; - if (b.kind !== "ticket" || b.endedAt !== null || b.ending !== null || b.lastSnapshot === null) return withdraw("Withdrawn."); - if (b.hold !== null) return withdraw("Held."); + if (b.kind !== "ticket" || b.endedAt !== null || b.ending !== null || b.lastSnapshot === null) return withdraw("Withdrawn.", false); + 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."); - if (b.stage === "review" || store.workers(b.id).some((w) => w.status === "running")) return withdraw("Withdrawn: the work has started."); + if (!gate.passed) return withdraw("Withdrawn: the ready gate no longer passes.", 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)); - if (conflicts.length === 0) return withdraw("Withdrawn: nothing in flight overlaps it now."); + 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 || keys.every((k) => b.scheduleAsked.includes(k))) return null; + if (open.length > 0) { + cleared(false); + return null; + } + if (keys.every((k) => b.scheduleAsked.includes(k))) { + cleared(true); + return null; + } + cleared(false); store.patch(b.id, { scheduleAsked: keys }); const overlap = conflicts.map((c) => `${c.with.entityKey} (${c.with.phase ?? "?"}) on ${c.on.join(", ")}`).join("; "); const x = store.escalate({ @@ -3206,6 +3223,22 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P else if (!behind.some((x) => x.id === other.id)) behind.push(other); } if (missing.length > 0) return toolError(new Error(`Not an open binding in this project to wait behind: ${missing.join(", ")}.`)); + // No cycles: a hold behind something that, through its own holds, waits behind this binding would never lift. + const waitsOn = (from: Binding, seen = new Set()): string | null => { + for (const k of from.holdBehind) { + const next = store.find(k, from.projectId); + if (next === null || next.endedAt !== null || seen.has(next.id)) continue; + if (next.id === target.id) return from.entityKey; + seen.add(next.id); + const via = waitsOn(next, seen); + if (via !== null) return via; + } + return null; + }; + for (const other of behind) { + const via = other.id === target.id ? null : waitsOn(other); + if (via !== null) return toolError(new Error(`${target.entityKey} cannot wait behind ${other.entityKey}: ${via} already waits behind ${target.entityKey}, so neither hold would ever lift.`)); + } } done.push(...questionWrites(closing, target)); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 68d973f8..4af7b229 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -169,6 +169,8 @@ export const MIGRATIONS = [ `ALTER TABLE bindings ADD COLUMN touches TEXT NOT NULL DEFAULT '[]'`, `ALTER TABLE bindings ADD COLUMN hold_behind TEXT NOT NULL DEFAULT '[]'`, `ALTER TABLE bindings ADD COLUMN schedule_asked TEXT NOT NULL DEFAULT '[]'`, + // A ticket whose gate has passed and that nothing holds or schedules: about to start, so it counts as in flight before Linear says so. + `ALTER TABLE bindings ADD COLUMN cleared_to_start INTEGER NOT NULL DEFAULT 0`, ]; // ---- values kept as JSON ------------------------------------------------------------ @@ -257,6 +259,8 @@ export type Binding = { holdBehind: string[]; /** Entity keys the project steward was last asked to schedule this binding against; asked again only for a new one. */ scheduleAsked: string[]; + /** The gate has passed and nothing holds or schedules it: it is starting, whatever Linear still says, so others schedule against it. */ + clearedToStart: boolean; modelSteward: string | null; modelWorker: string | null; status: StatusRecord | null; @@ -320,6 +324,7 @@ function rowToBinding(r: BindingRow): Binding { touches: json(z.array(z.string()), str("touches"), []), holdBehind: json(z.array(z.string()), str("hold_behind"), []), scheduleAsked: json(z.array(z.string()), str("schedule_asked"), []), + clearedToStart: Number(r.cleared_to_start ?? 0) === 1, modelSteward: str("model_steward"), modelWorker: str("model_worker"), status: json(statusRecordSchema.nullable(), str("status"), null), @@ -365,6 +370,7 @@ const COLUMNS = { touches: "touches", holdBehind: "hold_behind", scheduleAsked: "schedule_asked", + clearedToStart: "cleared_to_start", modelSteward: "model_steward", modelWorker: "model_worker", status: "status",