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
34 changes: 29 additions & 5 deletions plugins/stewards/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,26 @@ Plugin code. No model turn.
terminal state the steward's own last report already named ends the
binding from the mechanical tier, with the wrap-up written from that
report and no wrap-up wake; a terminal state someone else set still wakes.
Rule 3 has a missing premise, and BB-83 adds it: a quiet finish assumes a
louder event follows — a merge doorbell, a deployment, a terminal state.
When none exists the binding sits with nothing able to wake it, so the
plugin supplies the clock. A binding whose playbook stage is `build` or
`review`, which is not ending or held, with no worker running, no own pull
request open, no deployment watch `merged` or `deploying`, and no
escalation or need waiting on the user, is idle in an active stage. The
reconcile, the requeue tick and the sweep all evaluate that predicate; once
it has held for the playbook's `idle-grace` (15m by default), the steward is
woken with "Nothing is running and nothing is being waited on…" and that
idle period is spent: the wake fires once per idle period, not once per
grace. A worker finish that leaves such a
binding is loud at once, without the grace, because the worker's final
message is what the steward must read; a finish that leaves an open pull
request, a pending deployment or a message that says it is waiting stays
quiet as before. The wake fires once per idle period, not once per grace: a
worker ending, an own pull request closing or a deployment watch changing
starts a new period, and a steward that waits on something the plugin
cannot observe is not woken every fifteen minutes. `idleInActiveStage` in
`reconcile.ts` is the whole rule.
4. Otherwise the snapshot is recorded and the ring ends. Most rings end here:
the steward's own comments, label churn, its workers at work. What
changed is kept as a quiet note and shown with the next turn something
Expand Down Expand Up @@ -1511,11 +1531,15 @@ project steward footer row is the grey ring.
else `on hold`; `stuck` for an open stuck escalation; `N worker(s) running`
counting only workers whose worker-table status is `running` (a busy steward or
reviewer with no running worker falls through, rather than reading `0 workers
running`); the newest deployment watch's state (`deploying`, `deployed`,
`deploy failed`), ahead of the free-text `nextAction` whatever the actor (BB-86);
the status `nextAction` verbatim, with `the other party` standing in for an
`other` actor that has no report (an external wait is not a block, so its colour
follows the glyph); otherwise `no report yet`. The phrase's colour follows the
running`); `worker finished, next look <time>` when the binding has a pending
quiet worker-finish note and no running worker (BB-83 — the status summary a
finished worker left behind must not keep the row, and the time is the
binding's `requeueAt`); the newest deployment watch's state (`deploying`,
`deployed`, `deploy failed`), ahead of the free-text `nextAction` whatever the
actor (BB-86); the status `nextAction` verbatim, with `the other party`
standing in for an `other` actor that has no report (an external wait is not a
block, so its colour follows the glyph); otherwise `no report yet`. The
phrase's colour follows the
glyph's. `sidebar.ts` derives `state`, `section`
and `phrase` as pure functions and sorts by the section rules; `sidebar.test.ts`
covers every rule and the precedence.
Expand Down
4 changes: 4 additions & 0 deletions plugins/stewards/app.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,8 @@ const sidebarBinding = (over: Record<string, unknown>) => ({
stuck: false,
status: null,
deployment: null,
pending: [],
requeueAt: null,
advancedAt: null,
workers: [],
reviewers: [],
Expand Down Expand Up @@ -531,6 +533,8 @@ const boardSteward = (over: Record<string, unknown> = {}) => ({
needsUser: false,
stuck: false,
deployment: null,
pending: [],
requeueAt: null,
ending: null,
statusAt: null,
createdAt: 1_000,
Expand Down
10 changes: 7 additions & 3 deletions plugins/stewards/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,8 @@ function overviewEffortStatus(s: Steward): EffortStatus {
statusActor: s.actor,
statusNextAction: s.nextAction,
deployment: s.deployment,
pending: s.pending,
requeueAt: s.requeueAt,
};
}

Expand Down Expand Up @@ -343,7 +345,7 @@ function StewardRow({ steward: s, now }: { steward: Steward; now: number }) {
const mine = s.escalations.filter((x) => x.route === "me");
const status = overviewEffortStatus(s);
const state = effortState(status);
const phrase = effortPhrase(status);
const phrase = effortPhrase(status, now);
return (
<li className="flex flex-col gap-1 p-3">
<StewardHeader
Expand Down Expand Up @@ -506,6 +508,8 @@ function boardEffortStatus(s: BoardSteward): EffortStatus {
statusActor: s.actor,
statusNextAction: s.nextAction,
deployment: s.deployment,
pending: s.pending,
requeueAt: s.requeueAt,
};
}

Expand Down Expand Up @@ -564,7 +568,7 @@ function ProjectBoard({ board: b, refetch }: { board: Board; refetch: () => void
const efforts: BoardEffort[] = b.stewards.map((s) => {
const status = boardEffortStatus(s);
const state = effortState(status);
return { steward: s, state, section: effortSection({ state, kind: s.kind }), phrase: effortPhrase(status), items: itemsByKey.get(s.key) ?? [] };
return { steward: s, state, section: effortSection({ state, kind: s.kind }), phrase: effortPhrase(status, now), items: itemsByKey.get(s.key) ?? [] };
});
const blocked = efforts.filter((e) => e.section === "blocked").sort((a, b) => compareBlocked(boardOrder(a), boardOrder(b)));
const inflight = efforts.filter((e) => e.section === "inflight").sort((a, b) => compareInflight(boardOrder(a), boardOrder(b)));
Expand Down Expand Up @@ -1440,7 +1444,7 @@ function StewardsSidebar({ activeProjectId, onNavigate }: PluginThreadListProps)
const navigate = useBbNavigate();
const { status, threads, projects } = experimental_useSidebarThreads();
const { data, error, refetch } = usePolled(useCallback(() => rpc.call("stewardsSidebar", null), [rpc]));
const tabs = useMemo(() => buildSidebar({ projects, threads, data: data?.projects ?? [] }), [projects, threads, data]);
const tabs = useMemo(() => buildSidebar({ projects, threads, data: data?.projects ?? [], now: Date.now() }), [projects, threads, data]);
const needsByProject = useMemo(() => new Map((data?.projects ?? []).map((p) => [p.projectId, p.needs] as const)), [data]);
// The picker counts the yellow rows, so the pill and the sections cannot disagree (BB-76).
const counts = useMemo(() => new Map(tabs.map((t) => [t.projectId, t.blocked.filter((e) => e.state === "you").length] as const)), [tabs]);
Expand Down
4 changes: 4 additions & 0 deletions plugins/stewards/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,12 @@ describe("playbooks", () => {
expect(p.general).toMatch(/You steward one Linear ticket/u);
expect(p.requeueDefaultMs).toBe(2 * 86_400_000);
expect(p.followThroughMs).toBe(6 * 3_600_000);
// BB-83: the idle grace defaults to 15m and a playbook may override it.
expect(p.idleGraceMs).toBe(15 * 60_000);
const shorter = parsePlaybook(LINEAR_TICKETS.replace("requeue-default: 2d", "requeue-default: 2d\nfollow-through: 90m"), "linear-tickets");
expect(shorter.ok && shorter.value.followThroughMs).toBe(90 * 60_000);
const idleGrace = parsePlaybook(LINEAR_TICKETS.replace("requeue-default: 2d", "requeue-default: 2d\nidle-grace: 5m"), "linear-tickets");
expect(idleGrace.ok && idleGrace.value.idleGraceMs).toBe(5 * 60_000);
expect(p.ready?.approval).toBe("project");
expect(playbookStates(p)).toEqual(expect.arrayContaining(["Todo", "In Review", "Done", "Canceled"]));
expect(p.version).toMatch(/^[0-9a-f]{12}$/u);
Expand Down
9 changes: 9 additions & 0 deletions plugins/stewards/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,12 @@ export const frontMatterSchema = z
may: z.array(z.string().trim().min(1).max(60)).default([]),
models: z.object({ steward: modelSpecSchema.optional(), worker: modelSpecSchema.optional() }).strict().default({}),
"requeue-default": durationSchema.default(2 * 86_400_000),
/**
* How long a binding in a build or review stage may sit with nothing to
* wait on before the plugin wakes its steward (BB-83). The idle wake fires
* once per idle period, so this is a grace, not a poll interval.
*/
"idle-grace": durationSchema.default(15 * 60_000),
/** How long a steward may keep a binding open past a terminal state to finish its work. */
"follow-through": durationSchema.default(DEFAULT_FOLLOW_THROUGH_MS),
/** Reviews: pull request authors no review steward is made for (bots). */
Expand All @@ -513,6 +519,8 @@ export type Playbook = {
may: string[];
models: { steward: ModelSpec | null; worker: ModelSpec | null };
requeueDefaultMs: number;
/** How long a binding may sit idle in an active stage before its steward is woken (BB-83). */
idleGraceMs: number;
followThroughMs: number;
skipAuthors: string[];
/** Where a merge is confirmed live, or null when the playbook names no deployment target. */
Expand Down Expand Up @@ -583,6 +591,7 @@ export function parsePlaybook(text: string, expectedName: string): Parsed<Playbo
may: fm.may,
models: { steward: fm.models.steward ?? null, worker: fm.models.worker ?? null },
requeueDefaultMs: fm["requeue-default"],
idleGraceMs: fm["idle-grace"],
followThroughMs: fm["follow-through"],
skipAuthors: fm["skip-authors"],
deployment: fm.deployment ?? null,
Expand Down
54 changes: 53 additions & 1 deletion plugins/stewards/reconcile.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { parsePlaybook, phaseOf } from "./config.js";
import { comment, issue, pull } from "./fixtures.js";
import { approvalWanted, answerDiffers, anyWorkerInFlight, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, isOwnStageMove, lifecycle, markerLaneChange, namesUserAsBlocker, ownerApproval, prGate, resolveChecklistItem, reviewMarker, specHash, stuckDue, UNREADABLE_VERDICT, unheardWait, workerInFlight, workerReportedTerminal } from "./reconcile.js";
import { approvalWanted, answerDiffers, anyWorkerInFlight, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, idleInActiveStage, isCommentNews, isOwnStageMove, lifecycle, markerLaneChange, namesUserAsBlocker, ownPullClosed, ownerApproval, prGate, resolveChecklistItem, reviewMarker, specHash, stuckDue, UNREADABLE_VERDICT, unheardWait, workerInFlight, workerReportedTerminal, type IdleBinding } from "./reconcile.js";
import { readyStateSchema } from "./store.js";
import { GITHUB_REVIEWS, LINEAR_TICKETS } from "./templates.js";

Expand Down Expand Up @@ -545,3 +545,55 @@ describe("a correction from a comment", () => {
expect(answerDiffers("Don't do it.", "Do it.")).toBe(true);
});
});

// BB-83: a binding in a build or review stage with nothing left to wait on is
// idle. The predicate is the whole mechanical rule; the server measures the
// grace and keeps it to one wake per idle period.
describe("idle in an active stage (BB-83)", () => {
const own = new Set(["acme/web#7", "https://github.com/acme/web/pull/7"]);
const binding = (over: Partial<IdleBinding> = {}): IdleBinding => ({
stage: "review",
ending: null,
hold: null,
deployments: {},
workers: [{ status: "finished" }],
ownPulls: own,
escalations: [],
needs: [],
...over,
});
const merged = { entity: issue({ state: "In Review" }), pulls: [pull({ state: "merged" })] };

it("is true with nothing left to wait on", () => {
expect(idleInActiveStage(binding(), merged)).toBe(true);
// No worker at all, a build stage, and an open pull request that is not
// the worker's own are each still idle.
expect(idleInActiveStage(binding({ workers: [], stage: "build" }), merged)).toBe(true);
expect(idleInActiveStage(binding(), { entity: issue({ state: "In Review" }), pulls: [pull({ key: "acme/web#9", url: "https://github.com/acme/web/pull/9", state: "open" })] })).toBe(true);
// A wait on the project steward is not a wait on the user.
expect(idleInActiveStage(binding({ escalations: [{ status: "open", route: "project" }] }), merged)).toBe(true);
});

it("is false when any of the waits is present", () => {
expect(idleInActiveStage(binding({ workers: [{ status: "running" }] }), merged)).toBe(false);
expect(idleInActiveStage(binding(), { entity: issue({ state: "In Review" }), pulls: [pull({ state: "open" })] })).toBe(false);
expect(idleInActiveStage(binding({ deployments: { "acme/web#7": { state: "merged" } as never } }), merged)).toBe(false);
expect(idleInActiveStage(binding({ deployments: { "acme/web#7": { state: "deploying" } as never } }), merged)).toBe(false);
expect(idleInActiveStage(binding({ hold: "a freeze" }), merged)).toBe(false);
expect(idleInActiveStage(binding({ ending: "terminal" }), merged)).toBe(false);
expect(idleInActiveStage(binding({ escalations: [{ status: "open", route: "me" }] }), merged)).toBe(false);
expect(idleInActiveStage(binding({ needs: [{ kind: "approve-pr" }] }), merged)).toBe(false);
// The spec stage is not active, and a deployment that is already deployed
// is nothing to wait on.
expect(idleInActiveStage(binding({ stage: "spec" }), merged)).toBe(false);
expect(idleInActiveStage(binding({ deployments: { "acme/web#7": { state: "deployed" } as never } }), merged)).toBe(true);
});

it("starts a new idle period when an own pull request closes", () => {
const before = { entity: issue({ state: "In Review" }), pulls: [pull({ state: "open" })] };
expect(ownPullClosed(before, merged, own)).toBe(true);
expect(ownPullClosed(merged, merged, own)).toBe(false);
// A foreign pull request closing is not the binding's own event.
expect(ownPullClosed(before, { entity: issue({ state: "In Review" }), pulls: [pull({ key: "acme/web#9", url: "https://github.com/acme/web/pull/9", state: "merged" })] }, own)).toBe(false);
});
});
62 changes: 62 additions & 0 deletions plugins/stewards/reconcile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,68 @@ export function unheardWait(status: Binding["status"], open: readonly Escalation
return null;
}

// ---- idle in an active stage (BB-83) --------------------------------------------

/**
* The binding facts the idle rule reads beyond the snapshot: its workers, the
* pull requests its own workers opened (BB-52 rule 0), and what waits on the
* user. `server.ts` assembles these from the store; nothing here reads one.
*/
export type IdleBinding = Pick<Binding, "stage" | "ending" | "hold" | "deployments"> & {
workers: readonly Pick<Worker, "status">[];
ownPulls: ReadonlySet<string>;
escalations: readonly Pick<Escalation, "status" | "route">[];
needs: readonly unknown[];
};

/** The wake text for a binding idle in an active stage (BB-83). */
export const IDLE_WAKE_TEXT =
"Nothing is running and nothing is being waited on: no worker, no open pull request, no pending deployment. Close the ticket, start the next slice, or report what remains and who does it.";

/** A pull request the plugin can see is not yet merged or closed. */
const pullOpen = (e: EntitySnapshot): boolean => e.pull !== null && e.state !== "merged" && e.state !== "closed";

/**
* Whether a binding in an active stage has nothing left to wait on (BB-83):
* its playbook stage is `build` or `review`, it is not ending or held, no
* worker is running, no own pull request (BB-52 rule 0) is open, no deployment
* watch is merged or deploying, and no escalation or need waits on the user.
* It says nothing about the grace or the once-per-idle-period guard; the
* server measures those.
*/
export function idleInActiveStage(b: IdleBinding, observed: Observed): boolean {
if (b.stage !== "build" && b.stage !== "review") return false;
if (b.ending !== null || b.hold !== null) return false;
if (b.workers.some((w) => w.status === "running")) return false;
if ([observed.entity, ...observed.pulls].some((e) => pullOpen(e) && ownPull(e.key, e.url, b.ownPulls))) return false;
if (Object.values(b.deployments).some((w) => w.state === "merged" || w.state === "deploying")) return false;
if (b.escalations.some((x) => x.status === "open" && x.route === "me")) return false;
if (b.needs.length > 0) return false;
return true;
}

/**
* Whether an own pull request closed between two observations. A close starts
* a new idle period, so a steward woken for the previous one is looked at
* again rather than the close reading as the same period's news.
*/
export function ownPullClosed(before: Observed, after: Observed, ownPulls: ReadonlySet<string>): boolean {
const wasOpen = new Map<string, boolean>();
for (const e of [before.entity, ...before.pulls]) {
if (e.pull === null) continue;
if (e.key !== "") wasOpen.set(e.key.toLowerCase(), pullOpen(e));
if (e.url !== null && e.url !== "") wasOpen.set(e.url.toLowerCase(), pullOpen(e));
}
for (const e of [after.entity, ...after.pulls]) {
if (e.pull === null || pullOpen(e)) continue;
const own = (e.key !== "" && ownPulls.has(e.key.toLowerCase())) || (e.url !== null && e.url !== "" && ownPulls.has(e.url.toLowerCase()));
if (!own) continue;
const was = (e.key !== "" ? wasOpen.get(e.key.toLowerCase()) : undefined) ?? (e.url !== null && e.url !== "" ? wasOpen.get(e.url.toLowerCase()) : undefined);
if (was === true) return true;
}
return false;
}

// ---- lifecycle -----------------------------------------------------------------------

export type Lifecycle =
Expand Down
Loading
Loading