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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion plugins/stewards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,30 @@ 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. 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
children of a steward thread.
- **Lifecycle.** A terminal state gets a wrap-up turn with its workers
Expand Down
4 changes: 2 additions & 2 deletions plugins/stewards/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
69 changes: 69 additions & 0 deletions plugins/stewards/schedule.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
79 changes: 79 additions & 0 deletions plugins/stewards/schedule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// 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<string>();
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, 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.clearedToStart) &&
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);
}
Loading
Loading