From a2d27e0951dddade40dc1a1859571e1588b02ef9 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 26 Oct 2026 13:40:03 +0000 Subject: [PATCH 1/3] stewards: wake a deployment watch for a named workflow's failed run (BB-61) --- plugins/github-watcher/hooks-client.test.ts | 19 +++++-- plugins/github-watcher/hooks-client.ts | 20 ++++--- plugins/github-watcher/server.test.ts | 22 +++++++- plugins/github-watcher/server.ts | 39 +++++++++++-- plugins/github-watcher/source-contract.ts | 35 ++++++++++-- plugins/linear/source-contract.ts | 35 ++++++++++-- plugins/stewards/DESIGN.md | 17 +++++- plugins/stewards/config.test.ts | 16 ++++++ plugins/stewards/config.ts | 10 ++++ plugins/stewards/deploy.test.ts | 53 +++++++++++++++++- plugins/stewards/deploy.ts | 62 ++++++++++++++++++++- plugins/stewards/server.test.ts | 61 ++++++++++++++++++++ plugins/stewards/server.ts | 49 +++++++++++++++- plugins/stewards/source-contract.ts | 35 ++++++++++-- plugins/stewards/wake.ts | 18 +++++- 15 files changed, 446 insertions(+), 45 deletions(-) diff --git a/plugins/github-watcher/hooks-client.test.ts b/plugins/github-watcher/hooks-client.test.ts index 70ece820..3da9c325 100644 --- a/plugins/github-watcher/hooks-client.test.ts +++ b/plugins/github-watcher/hooks-client.test.ts @@ -165,6 +165,8 @@ describe("the loop", () => { const doorbells: string[] = []; const doorbellKinds: string[] = []; const units: Array = []; + const deployments: unknown[] = []; + const workflowRuns: unknown[] = []; const rejected: Rejection[][] = []; let token = "tok-1"; let refreshes = 0; @@ -180,10 +182,12 @@ describe("the loop", () => { return token; }, watchIds: over.watchIds ?? (() => [{ kind: "issue", id: "i-1" }, { kind: "issue", id: "i-2" }]), - onDoorbell: (kind, id, unit) => { + onDoorbell: (kind, id, unit, deployment, workflowRun) => { doorbellKinds.push(kind); doorbells.push(id); units.push(unit); + deployments.push(deployment); + workflowRuns.push(workflowRun); }, onRejected: async (r) => { rejected.push(r); @@ -195,7 +199,7 @@ describe("the loop", () => { }); const controller = new AbortController(); const done = loop.run(controller.signal); - return { loop, logs, sweeps, doorbells, doorbellKinds, units, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes }; + return { loop, logs, sweeps, doorbells, doorbellKinds, units, deployments, workflowRuns, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes }; } it("subscribes every watch on hello with the current token, sweeps, then rings on doorbells for issues only", async () => { @@ -214,14 +218,17 @@ describe("the loop", () => { hooks.last().send(hooks.doorbell("i-1")); hooks.last().send(hooks.doorbell("acme/widgets", { kind: "repo" })); hooks.last().send(hooks.doorbell("acme/widgets#4", { kind: "dependabot_alert" })); + const workflowRun = { workflow: ".github/workflows/bb-server.yaml", name: "bb-server", conclusion: "failure", url: "https://github.com/acme/bb-gate/actions/runs/42", sha: "abc123", run_attempt: 1 }; + hooks.last().send(hooks.doorbell("acme/bb-gate#42", { kind: "workflow_run", unit: "acme/bb-gate", workflow_run: workflowRun })); hooks.last().send(hooks.doorbell("i-9", { source: "linear" })); hooks.last().send("event: doorbell\ndata: not json\n\n"); hooks.last().send(hooks.doorbell("i-2", { action: "remove", unit: "" })); await tick(); - expect(s.doorbells).toEqual(["i-1", "acme/widgets#4", "i-2"]); - expect(s.doorbellKinds).toEqual(["issue", "dependabot_alert", "issue"]); - // The unit comes along when the service names one. - expect(s.units).toEqual(["acme/widgets", "acme/widgets", null]); + expect(s.doorbells).toEqual(["i-1", "acme/widgets#4", "acme/bb-gate#42", "i-2"]); + expect(s.doorbellKinds).toEqual(["issue", "dependabot_alert", "workflow_run", "issue"]); + // The unit comes along when the service names one, and the run object with it. + expect(s.units).toEqual(["acme/widgets", "acme/widgets", "acme/bb-gate", null]); + expect(s.workflowRuns).toEqual([undefined, undefined, workflowRun, undefined]); expect(s.logs.join("\n")).not.toContain("tok-1"); s.controller.abort(); diff --git a/plugins/github-watcher/hooks-client.ts b/plugins/github-watcher/hooks-client.ts index 4a58e58b..e3b471b6 100644 --- a/plugins/github-watcher/hooks-client.ts +++ b/plugins/github-watcher/hooks-client.ts @@ -119,7 +119,7 @@ export async function* readSse(body: ReadableStream, signal: AbortSi // ---- the wire shapes --------------------------------------------------------- export const helloSchema = z.object({ connection: z.string().min(1), leaseSeconds: z.number().positive().optional() }); -export const doorbellSchema = z.object({ source: z.string(), kind: z.string(), id: z.string().min(1), unit: z.string().optional(), deployment: z.unknown().optional() }).loose(); +export const doorbellSchema = z.object({ source: z.string(), kind: z.string(), id: z.string().min(1), unit: z.string().optional(), deployment: z.unknown().optional(), workflow_run: z.unknown().optional() }).loose(); export const subscribeResponseSchema = z.object({ leases: z.array(z.object({ kind: z.string(), id: z.string() }).loose()).default([]), rejected: z.array(z.object({ kind: z.string(), id: z.string(), reason: z.string() }).loose()).default([]), @@ -217,12 +217,12 @@ export interface HooksLoopDeps { /** Every lease to hold, right now: watched issues, and whatever stewards asked for. */ watchIds: () => Lease[]; /** - * A doorbell: the kind (`issue`, `dependabot_alert` or `deployment`), the - * entity id, the unit (the repository) when the service named one, and, on - * a `deployment` doorbell, the deployment object the doorbell carries. The - * caller decides what to look at. + * A doorbell: the kind (`issue`, `dependabot_alert`, `deployment` or + * `workflow_run`), the entity id, the unit (the repository) when the + * service named one, and, on a `deployment` or `workflow_run` doorbell, the + * object the doorbell carries. The caller decides what to look at. */ - onDoorbell: (kind: string, id: string, unit: string | null, deployment?: unknown) => void; + onDoorbell: (kind: string, id: string, unit: string | null, deployment?: unknown, workflowRun?: unknown) => void; /** Leases the service refused. The caller decides what that means for each watch. */ onRejected: (rejected: Rejection[]) => Promise; /** Check every watch against its cursor. */ @@ -427,10 +427,14 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop { // `action` and `at` are for the service's logs; the reaction to any // doorbell is the same check. The unit is passed on so a repository // lease can tell which of its doorbells it was rung for. - if (doorbell.success && doorbell.data.source === SOURCE && (doorbell.data.kind === "issue" || doorbell.data.kind === "dependabot_alert" || doorbell.data.kind === "deployment")) { + if ( + doorbell.success && + doorbell.data.source === SOURCE && + (doorbell.data.kind === "issue" || doorbell.data.kind === "dependabot_alert" || doorbell.data.kind === "deployment" || doorbell.data.kind === "workflow_run") + ) { doorbells.push(); const unit = doorbell.data.unit?.trim() ?? ""; - deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit, doorbell.data.deployment); + deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit, doorbell.data.deployment, doorbell.data.workflow_run); } } } diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index 5f9b9154..a0904bdd 100644 --- a/plugins/github-watcher/server.test.ts +++ b/plugins/github-watcher/server.test.ts @@ -697,9 +697,27 @@ describe("stewards' source contract", () => { // A refused deployment_repo lease is a skip, logged as one. w.hooks.state.answer = (body) => Response.json({ leases: [], rejected: body.watches.map((x) => ({ ...x, reason: "forbidden" })) }); await tick(30 * 60_000); - expect(w.harness.logEntries.some((l) => l.message.includes("this server skips deployment doorbells there"))).toBe(true); + expect(w.harness.logEntries.some((l) => l.message.includes("this server skips deployment and workflow-run doorbells there"))).toBe(true); const interest = ((await w.harness.callRpc("watches", null)) as { interest: { unleased: Array<{ key: string; reason: string }> } }).interest; - expect(interest.unleased).toEqual([{ key: "acme/bb-gate", reason: "refused by bb-gate-hooks (forbidden); deployment doorbells are skipped" }]); + expect(interest.unleased).toEqual([{ key: "acme/bb-gate", reason: "refused by bb-gate-hooks (forbidden); deployment and workflow-run doorbells are skipped" }]); + service.controller.abort(); + await service.done; + }); + + it("hands stewards a workflow_run doorbell's run object for a leased deployment repository (BB-61)", async () => { + const w = await setup(WITH_HOOKS); + const service = w.harness.runService("watches"); + await tick(); + w.hooks.last().send(w.hooks.hello("c_1")); + await tick(); + expect(await w.harness.callRpc("sourceSetInterest", { units: [], entities: [], dependabot: [], deployment: ["acme/bb-gate"] }, STEWARDS)).toEqual({ ok: true }); + await tick(); + expect(w.hooks.subscribes.map((s) => s.watches)).toEqual([[{ kind: "deployment_repo", id: "acme/bb-gate" }]]); + const workflow_run = { workflow: ".github/workflows/bb-server.yaml", name: "bb-server", conclusion: "failure", url: "https://github.com/acme/bb-gate/actions/runs/42", sha: "abc123", run_attempt: 1 }; + w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "workflow_run", id: "Acme/bb-gate#42", unit: "Acme/bb-gate", workflow_run })}\n\n`); + w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "workflow_run", id: "Acme/Other#42", unit: "Acme/Other", workflow_run })}\n\n`); + await tick(3000); + expect(w.rpcs()).toEqual([{ pluginId: "stewards", method: "stewardsRing", input: { source: "github", id: "Acme/bb-gate#42", workflow_run } }]); service.controller.abort(); await service.done; }); diff --git a/plugins/github-watcher/server.ts b/plugins/github-watcher/server.ts index 83d68252..b0842cca 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -48,7 +48,7 @@ import { type Target, } from "./github.js"; import { createHooksLoop, HOOKS_URL_ENV, type Lease, type Rejection } from "./hooks-client.js"; -import { deploymentSchema, ringStewards, sourceContract, STEWARDS_PLUGIN_ID, type AdoptableEntity, type Deployment } from "./source-contract.js"; +import { deploymentSchema, ringStewards, sourceContract, STEWARDS_PLUGIN_ID, workflowRunSchema, type AdoptableEntity, type Deployment, type WorkflowRun } from "./source-contract.js"; import { buildUsage, createRefusals, formatUsage, usageViewSchema, type InterestView } from "./usage.js"; import { compare, createCheckQueue, createWatchStore, initialCursors, snapshotOf, WATCH_MIGRATIONS, type WatchRow } from "./watch.js"; @@ -299,7 +299,9 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => function interesting(kind: string, key: string, unit: string | null): boolean { const repo = unit ?? parseRefKey(key)?.repo ?? null; if (kind === "dependabot_alert") return repo !== null && interestDependabot.has(repo.toLowerCase()); - if (kind === "deployment") return repo !== null && interestDeployment.has(repo.toLowerCase()); + // A workflow_run doorbell shares the deployment_repo lease: only a + // project that names a deployment target cares about a failed run. + if (kind === "deployment" || kind === "workflow_run") return repo !== null && interestDeployment.has(repo.toLowerCase()); if (interestEntities.has(key.toLowerCase())) return true; return repo !== null && interestRepos.has(repo.toLowerCase()); } @@ -327,6 +329,21 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => ); bb.onDispose(() => deploymentRings.stop()); + // A workflow_run doorbell carries its run object the same way. It is keyed + // by the run id and attempt, so a re-run that fails again is its own ring + // rather than being coalesced into the first. + const pendingWorkflowRuns = new Map(); + const workflowRunRings = createCheckQueue( + (eventKey) => { + const pending = pendingWorkflowRuns.get(eventKey); + pendingWorkflowRuns.delete(eventKey); + if (pending === undefined) return Promise.resolve(); + return ringStewards(callStewards, { source: "github", id: pending.id, workflow_run: pending.run }, warn); + }, + { onError: (eventKey, error) => warn(`ringing stewards for workflow run ${eventKey} failed: ${errorMessage(error)}`) }, + ); + bb.onDispose(() => workflowRunRings.stop()); + // The service refusing a lease is not proof the developer lost access: // with GitHub rate-limiting the service, or briefly down, every watch // would come back `forbidden`. The developer's own read is the ground @@ -359,7 +376,7 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => // Reading a repository's deployments needs `deployments:read` (or // the `repo` scope); a token without it is refused here, which is a // skip: the server keeps running without deployment doorbells. - if (interestDeployment.has(r.id.toLowerCase())) bb.log.info(`bb-gate-hooks refused a deployment_repo lease on ${r.id} (${r.reason}); this server skips deployment doorbells there`); + if (interestDeployment.has(r.id.toLowerCase())) bb.log.info(`bb-gate-hooks refused a deployment_repo lease on ${r.id} (${r.reason}); this server skips deployment and workflow-run doorbells there`); continue; } if (r.kind === "repo" || (watching.length === 0 && interestEntities.has(r.id.toLowerCase()))) { @@ -390,8 +407,20 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => token: accessToken, refreshToken: () => refreshToken("was refused by bb-gate-hooks"), watchIds: leases, - onDoorbell: (kind, key, unit, deployment) => { + onDoorbell: (kind, key, unit, deployment, workflowRun) => { if (kind === "issue") checks.ring(key); + if (kind === "workflow_run") { + if (!interesting(kind, key, unit)) return; + const parsed = workflowRunSchema.safeParse(workflowRun); + if (!parsed.success) { + bb.log.warn(`GitHub workflow_run doorbell ${key} carried no readable run; nothing to hand stewards`); + return; + } + const eventKey = `${key.toLowerCase()}#${parsed.data.run_attempt}`; + pendingWorkflowRuns.set(eventKey, { id: key, run: parsed.data }); + workflowRunRings.ring(eventKey); + return; + } if (kind === "deployment") { if (!interesting(kind, key, unit)) return; const parsed = deploymentSchema.safeParse(deployment); @@ -461,7 +490,7 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => } for (const repo of interest.deployment) { const reason = refused.get(`deployment_repo ${repo.toLowerCase()}`); - if (reason !== undefined) unleased.push({ key: repo, reason: `refused by bb-gate-hooks (${reason}); deployment doorbells are skipped` }); + if (reason !== undefined) unleased.push({ key: repo, reason: `refused by bb-gate-hooks (${reason}); deployment and workflow-run doorbells are skipped` }); } return { nouns: { unit: ["repository", "repositories"], entity: ["pull request", "pull requests"] }, diff --git a/plugins/github-watcher/source-contract.ts b/plugins/github-watcher/source-contract.ts index d722a573..02f2333d 100644 --- a/plugins/github-watcher/source-contract.ts +++ b/plugins/github-watcher/source-contract.ts @@ -51,6 +51,29 @@ export const deploymentSchema = z .loose(); export type Deployment = z.infer; +/** + * A GitHub Actions workflow run, as bb-gate-hooks forwards it on a + * `workflow_run` doorbell (bb-gate/docs/hooks.md). The doorbell's entity id + * is `owner/repo#` and its unit is the repository, leased the same + * way as a deployment (`deployment_repo`). `workflow` is the workflow's file + * path and `name` its name, either of which a playbook may match; + * `conclusion` is failure, cancelled or timed_out -- the only conclusions + * that ring the doorbell. `sha` is the run's head commit, which is usually + * the deploying repository's commit, not the merge's, so a subscriber must + * not match on it. `run_attempt` tells a re-run from the first attempt. + */ +export const workflowRunSchema = z + .object({ + workflow: z.string().default(""), + name: z.string().default(""), + conclusion: z.string().default(""), + url: z.string().nullable().default(null), + sha: z.string().default(""), + run_attempt: z.number().int().positive().default(1), + }) + .loose(); +export type WorkflowRun = z.infer; + /** How much of a comment or description crosses the contract. */ export const SNAPSHOT_COMMENT_CHARS = 4000; export const SNAPSHOT_DESCRIPTION_CHARS = 20_000; @@ -275,7 +298,9 @@ export const sourceContract = { * stewards wants: the deployment targets the project's playbooks name. It * is separate from `units` for the same reason as `dependabot`: a * repository lease does not receive deployment doorbells, so the github - * plugin leases each as a `deployment_repo`. Linear ignores it. + * plugin leases each as a `deployment_repo`. A `workflow_run` doorbell + * shares that lease, because only a project that names a deployment target + * cares about a workflow run. Linear ignores it. */ sourceSetInterest: { input: z.object({ @@ -373,11 +398,11 @@ export const stewardsContract = { /** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */ stewardsRing: { /** - * A `deployment` doorbell carries its deployment object, which is the one - * doorbell whose ref and state are not in the entity name. Every other - * doorbell leaves it out. + * A `deployment` doorbell carries its deployment object, and a + * `workflow_run` doorbell its run object: the two doorbells whose facts + * are not in the entity name. Every other doorbell leaves both out. */ - input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional() }), + input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional(), workflow_run: workflowRunSchema.optional() }), output: z.object({ ok: z.boolean() }), }, /** diff --git a/plugins/linear/source-contract.ts b/plugins/linear/source-contract.ts index d722a573..02f2333d 100644 --- a/plugins/linear/source-contract.ts +++ b/plugins/linear/source-contract.ts @@ -51,6 +51,29 @@ export const deploymentSchema = z .loose(); export type Deployment = z.infer; +/** + * A GitHub Actions workflow run, as bb-gate-hooks forwards it on a + * `workflow_run` doorbell (bb-gate/docs/hooks.md). The doorbell's entity id + * is `owner/repo#` and its unit is the repository, leased the same + * way as a deployment (`deployment_repo`). `workflow` is the workflow's file + * path and `name` its name, either of which a playbook may match; + * `conclusion` is failure, cancelled or timed_out -- the only conclusions + * that ring the doorbell. `sha` is the run's head commit, which is usually + * the deploying repository's commit, not the merge's, so a subscriber must + * not match on it. `run_attempt` tells a re-run from the first attempt. + */ +export const workflowRunSchema = z + .object({ + workflow: z.string().default(""), + name: z.string().default(""), + conclusion: z.string().default(""), + url: z.string().nullable().default(null), + sha: z.string().default(""), + run_attempt: z.number().int().positive().default(1), + }) + .loose(); +export type WorkflowRun = z.infer; + /** How much of a comment or description crosses the contract. */ export const SNAPSHOT_COMMENT_CHARS = 4000; export const SNAPSHOT_DESCRIPTION_CHARS = 20_000; @@ -275,7 +298,9 @@ export const sourceContract = { * stewards wants: the deployment targets the project's playbooks name. It * is separate from `units` for the same reason as `dependabot`: a * repository lease does not receive deployment doorbells, so the github - * plugin leases each as a `deployment_repo`. Linear ignores it. + * plugin leases each as a `deployment_repo`. A `workflow_run` doorbell + * shares that lease, because only a project that names a deployment target + * cares about a workflow run. Linear ignores it. */ sourceSetInterest: { input: z.object({ @@ -373,11 +398,11 @@ export const stewardsContract = { /** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */ stewardsRing: { /** - * A `deployment` doorbell carries its deployment object, which is the one - * doorbell whose ref and state are not in the entity name. Every other - * doorbell leaves it out. + * A `deployment` doorbell carries its deployment object, and a + * `workflow_run` doorbell its run object: the two doorbells whose facts + * are not in the entity name. Every other doorbell leaves both out. */ - input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional() }), + input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional(), workflow_run: workflowRunSchema.optional() }), output: z.object({ ok: z.boolean() }), }, /** diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index dad5c955..17696b3b 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -734,6 +734,7 @@ deployment: # where a merge is confirmed live (BB-53); omi environment: production carries: "The pinned BB_PLUGINS_REF contains the merge commit." # the steward's rule timeout: 6h + workflows: [bb-server.yaml, image.yaml] # a failed run of one wakes the steward (BB-61) ``` - **Phases are the entity's own states**, so the playbook needs no state @@ -748,6 +749,16 @@ deployment: # where a merge is confirmed live (BB-53); omi comment once every pull request is merged and deployed. A failure/error deployment or a timeout wakes the steward with the run URL. No `deployment` is exactly today's behaviour. +- **`deployment.workflows` names the builds that must not fail while a merge + waits (BB-61).** Each entry is matched, ignoring case, against a + `workflow_run` doorbell's file path, basename or name. A run of a named + workflow that ends in failure, cancellation or timeout wakes every binding + on that repo still awaiting a deployment, once per run id and attempt, with + the run's URL, conclusion and head sha and the open watches; the watch's + state is not moved, and the steward applies its playbook as for a timeout. + The plugin assumes nothing about images, tags or pins and never matches the + run's `sha`, which is usually the deploying repository's commit. Empty, or + absent, wakes nobody: no `workflows` is exactly today's behaviour. - **A deployment that predates its watch is read, not waited for (BB-59).** A doorbell can be missed, most obviously across the server restart every `bb-plugins` merge causes, and a deployment that landed before the watch was @@ -1430,7 +1441,11 @@ own server behind bb-gate, so it is per developer in practice. through as before. A deployment that already exists is read through the github plugin's source contract on the first watch and on the sweep (BB-59), so a missed doorbell costs a sweep, not the timeout; the read - never evaluates `carries`. + never evaluates `carries`. A build that fails, is cancelled or times out + between merge and deployment is forwarded from a `workflow_run` doorbell + when the playbook names it in `deployment.workflows` (BB-61); the plugin + only forwards the fact, and a `bb-gate` without the doorbell kind falls + back to the timeout as before. - **One developer's server and machine watch production.** An ops binding runs on the server of the developer who runs the project's stewards, and looks with kubectl on their machine, as them, like everything else here diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 7b968c70..f9ebc4ce 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -185,6 +185,20 @@ describe("playbooks", () => { expect(p.version).toMatch(/^[0-9a-f]{12}$/u); }); + it("takes a deployment target's optional workflows list, defaulting to none (BB-61)", () => { + const withDeployment = (extra: string) => + LINEAR_TICKETS.replace( + "requeue-default: 2d", + `requeue-default: 2d\ndeployment:\n source: github\n repo: bitcomplete/bb-gate\n environment: production\n carries: "the pin contains the merge"\n timeout: 6h${extra}`, + ); + const none = parsePlaybook(withDeployment(""), "linear-tickets"); + if (!none.ok) throw new Error(none.error); + expect(none.value.deployment).toMatchObject({ repo: "bitcomplete/bb-gate", environment: "production", workflows: [] }); + const named = parsePlaybook(withDeployment("\n workflows: [bb-server.yaml, image.yaml]"), "linear-tickets"); + if (!named.ok) throw new Error(named.error); + expect(named.value.deployment?.workflows).toEqual(["bb-server.yaml", "image.yaml"]); + }); + it("refuses what would misbehave", () => { expect(parsePlaybook("no front matter", "x")).toMatchObject({ ok: false }); expect(parsePlaybook(LINEAR_TICKETS, "other-name")).toMatchObject({ ok: false }); @@ -196,6 +210,8 @@ describe("playbooks", () => { if (!r.ok) expect(r.error).toMatch(/needs a ready gate/u); const overlap = GITHUB_PRS.replace("terminal: [merged, closed]", "terminal: [merged, closed, open]"); expect(parsePlaybook(overlap, "github-prs")).toMatchObject({ ok: false }); + const emptyWorkflow = LINEAR_TICKETS.replace("requeue-default: 2d", 'requeue-default: 2d\ndeployment:\n source: github\n repo: bitcomplete/bb-gate\n environment: production\n carries: "x"\n workflows: [""]'); + expect(parsePlaybook(emptyWorkflow, "linear-tickets")).toMatchObject({ ok: false }); }); }); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index d7d4e58b..b08f564f 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -399,6 +399,16 @@ export const deploymentTargetSchema = z carries: z.string().trim().min(1).max(2000), /** No matching deployment within this long wakes the steward. */ timeout: durationSchema.default(DEFAULT_FOLLOW_THROUGH_MS), + /** + * The GitHub Actions workflows whose failure matters while a merge waits + * for a deployment (BB-61). Each entry is matched, ignoring case, against + * a run's file path (`.github/workflows/bb-server.yaml`), its basename + * (`bb-server.yaml`) or its name (`bb-server`). Empty, or absent, wakes + * nobody for a `workflow_run` doorbell: today's behaviour exactly. The + * plugin forwards the fact that a named workflow failed and leaves what + * that means to the playbook; it reads no image, tag or pin. + */ + workflows: z.array(z.string().trim().min(1).max(200)).max(50).default([]), }) .strict(); export type DeploymentTarget = z.infer; diff --git a/plugins/stewards/deploy.test.ts b/plugins/stewards/deploy.test.ts index a055b7a5..5f9d4667 100644 --- a/plugins/stewards/deploy.test.ts +++ b/plugins/stewards/deploy.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it } from "vitest"; import { pull } from "./fixtures.js"; import type { DeploymentTarget } from "./config.js"; -import { allDeployed, applyDeployment, applyDeploymentRead, deploymentLines, deploymentsSchema, matchesTarget, mergedPulls, recordMerged, reportDeployment, timeOut, timeoutsDue, type Deployments } from "./deploy.js"; -import type { Deployment } from "./source-contract.js"; +import { allDeployed, applyDeployment, applyDeploymentRead, applyWorkflowRun, awaitingOnRepo, deploymentLines, deploymentsSchema, matchesTarget, matchesWorkflow, mergedPulls, recordMerged, reportDeployment, timeOut, timeoutsDue, workflowRunKey, type Deployments } from "./deploy.js"; +import type { Deployment, WorkflowRun } from "./source-contract.js"; import type { Observed } from "./store.js"; -const target: DeploymentTarget = { source: "github", repo: "acme/bb-gate", environment: "production", carries: "the pinned ref contains the merge", timeout: 3_600_000 }; +const target: DeploymentTarget = { source: "github", repo: "acme/bb-gate", environment: "production", carries: "the pinned ref contains the merge", timeout: 3_600_000, workflows: [] }; +const named: DeploymentTarget = { ...target, workflows: ["bb-server.yaml"] }; const NOW = Date.parse("2026-10-14T15:00:00Z"); const observed = (over: { entity?: ReturnType; pulls?: Array> } = {}): Observed => ({ @@ -33,6 +34,7 @@ describe("recording merged pull requests", () => { at: NOW, deadlineAt: NOW + target.timeout, note: null, + workflowRuns: [], }, }); // A second read does not reset the deadline or the merge sha. @@ -172,6 +174,51 @@ describe("confirming from a deployment read (BB-59)", () => { }); }); +// BB-61: a failed (or cancelled/timed-out) run of a workflow a deployment +// target names wakes every watch still awaiting a deployment, once per run +// and attempt, without moving the watch's state. +describe("a failed workflow run (BB-61)", () => { + const run = (over: Partial = {}): WorkflowRun => ({ workflow: ".github/workflows/bb-server.yaml", name: "bb-server", conclusion: "failure", url: "https://github.com/acme/bb-gate/actions/runs/42", sha: "ccccccc3", run_attempt: 1, ...over }); + const mergedWatch = () => recordMerged({}, observed(), target, NOW); + + it("matches a workflow by path, basename or name, ignoring case, and nothing when the list is empty", () => { + expect(matchesWorkflow(named, run())).toBe(true); + expect(matchesWorkflow({ workflows: [".github/workflows/bb-server.yaml"] }, run())).toBe(true); + expect(matchesWorkflow({ workflows: ["BB-SERVER.YAML"] }, run())).toBe(true); + expect(matchesWorkflow({ workflows: ["bb-server"] }, run())).toBe(true); + expect(matchesWorkflow({ workflows: ["image.yaml"] }, run())).toBe(false); + expect(matchesWorkflow(target, run())).toBe(false); + }); + + it("wakes an awaiting watch once per run and attempt, leaving its state alone", () => { + const first = applyWorkflowRun(mergedWatch(), "acme/bb-gate#42", "acme/bb-gate", run(), NOW + 1000); + expect(first.woken).toEqual(["acme/web#7"]); + expect(first.deployments["acme/web#7"]).toMatchObject({ state: "merged", workflowRuns: ["acme/bb-gate#42#1"] }); + // The same run and attempt is not news, however often it is delivered. + const repeat = applyWorkflowRun(first.deployments, "acme/bb-gate#42", "acme/bb-gate", run(), NOW + 2000); + expect(repeat.woken).toEqual([]); + expect(repeat.deployments).toEqual(first.deployments); + // A re-run (a higher attempt) wakes again. + const again = applyWorkflowRun(first.deployments, "acme/bb-gate#42", "acme/bb-gate", run({ run_attempt: 2 }), NOW + 3000); + expect(again.woken).toEqual(["acme/web#7"]); + }); + + it("skips another repo, a settled watch, and a watch recorded after the doorbell arrived", () => { + const deployments = mergedWatch(); + expect(applyWorkflowRun(deployments, "acme/other#42", "acme/other", run(), NOW).woken).toEqual([]); + const settled: Deployments = { "acme/web#7": { ...deployments["acme/web#7"]!, state: "deployed" } }; + expect(applyWorkflowRun(settled, "acme/bb-gate#42", "acme/bb-gate", run(), NOW).woken).toEqual([]); + // The watch was recorded after the doorbell arrived: the run cannot concern it. + expect(applyWorkflowRun(deployments, "acme/bb-gate#42", "acme/bb-gate", run(), NOW - 1).woken).toEqual([]); + }); + + it("lists the watches still awaiting a deployment on a repo, and keys an event by run and attempt", () => { + const deployments = recordMerged(recordMerged({}, observed(), target, NOW), observed({ entity: pull({ key: "acme/web#8" }, { merged: true }) }), target, NOW); + expect(awaitingOnRepo(deployments, "Acme/BB-Gate").map((w) => w.key)).toEqual(["acme/web#7", "acme/web#8"]); + expect(workflowRunKey("Acme/BB-Gate#42", 2)).toBe("acme/bb-gate#42#2"); + }); +}); + describe("the show lines", () => { it("names each watch's state, target, deployment facts and note", () => { const deployments = applyDeployment(recordMerged({}, observed(), target, NOW), target, deployment({ state: "failure" }), NOW).deployments; diff --git a/plugins/stewards/deploy.ts b/plugins/stewards/deploy.ts index 5db9316d..2461d6c8 100644 --- a/plugins/stewards/deploy.ts +++ b/plugins/stewards/deploy.ts @@ -5,7 +5,7 @@ // is the steward's, from the playbook's rule, and it reports the verdict. import { z } from "zod"; import type { DeploymentTarget } from "./config.js"; -import type { Deployment, EntitySnapshot } from "./source-contract.js"; +import type { Deployment, EntitySnapshot, WorkflowRun } from "./source-contract.js"; import type { Observed } from "./store.js"; /** @@ -38,6 +38,12 @@ export const deploymentWatchSchema = z.object({ deadlineAt: z.number().nullable().default(null), /** Why, in words: a failure state, or a steward's "does not carry this merge yet". */ note: z.string().nullable().default(null), + /** + * The `workflow_run` events this watch has been woken for, as + * `#`, so a repeat delivery of one run and + * attempt is not news (BB-61). The watch's state is not moved by a run. + */ + workflowRuns: z.array(z.string()).default([]), }); export type DeploymentWatch = z.infer; @@ -75,6 +81,7 @@ export function recordMerged(deployments: Deployments, observed: Observed, targe at: now, deadlineAt: now + target.timeout, note: null, + workflowRuns: [], }; changed = true; } @@ -120,6 +127,59 @@ export function applyDeployment(deployments: Deployments, target: Pick, run: WorkflowRun): boolean { + if (target.workflows.length === 0) return false; + const file = run.workflow.trim().toLowerCase(); + const base = file.split("/").pop() ?? ""; + const name = run.name.trim().toLowerCase(); + return target.workflows.some((w) => { + const want = w.trim().toLowerCase(); + return want !== "" && (want === file || want === base || want === name); + }); +} + +/** One workflow-run event's dedupe key: the run's entity id and its attempt. */ +export const workflowRunKey = (id: string, runAttempt: number): string => `${id.toLowerCase()}#${runAttempt}`; + +/** The watches on a repository that are still awaiting a deployment, for a run wake's list. */ +export const awaitingOnRepo = (deployments: Deployments, repo: string): DeploymentWatch[] => + Object.values(deployments).filter((w) => (w.state === "merged" || w.state === "deploying") && w.repo.toLowerCase() === repo.toLowerCase()); + +/** + * Apply a `workflow_run` doorbell to a binding's watches (BB-61): every watch + * for the run's repository that is still awaiting a deployment is recorded as + * having heard this run and attempt, and the steward is woken once for it. + * The watch's deployment state is not moved: the plugin forwards only the + * fact that a named workflow failed, and the steward applies its playbook as + * for a timeout. `receivedAt` is when the doorbell reached the server; a + * watch recorded after that (its merge came later) is left alone, since the + * run cannot concern it. The doorbell carries no run start or completion + * time, so arrival is the only clock there is, and the run's `sha` is never + * matched: it is usually the deploying repository's commit, not the merge's. + * Returns the watches this event is news for. + */ +export function applyWorkflowRun(deployments: Deployments, id: string, repo: string, run: WorkflowRun, receivedAt: number): { deployments: Deployments; woken: string[] } { + const key = workflowRunKey(id, run.run_attempt); + const next = { ...deployments }; + const woken: string[] = []; + for (const watch of Object.values(next)) { + if (watch.state !== "merged" && watch.state !== "deploying") continue; + if (watch.repo.toLowerCase() !== repo.toLowerCase()) continue; + if (watch.at > receivedAt) continue; + if (watch.workflowRuns.includes(key)) continue; + next[watch.key] = { ...watch, workflowRuns: [...watch.workflowRuns, key] }; + woken.push(watch.key); + } + return { deployments: next, woken }; +} + /** * Apply the newest deployment from a source read (BB-59). A merge carried by a * deployment that already exists is confirmed on the steward's next read, not diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 62b52b14..9c32b241 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -6052,4 +6052,65 @@ describe("deployment watching (BB-53)", () => { const wake = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; expect(wake).toMatch(/Deployment 7 \(success\) for acme\/bb-gate production/u); }); + + // BB-61: a named workflow's failure, cancellation or timeout wakes the + // steward once per (run id, attempt), without moving the watch's state. + const workflowPlaybook = () => + LINEAR_TICKETS.replace( + "requeue-default: 2d", + 'requeue-default: 2d\ndeployment:\n source: github\n repo: acme/bb-gate\n environment: production\n carries: "The pinned BB_PLUGINS_REF contains the merge commit."\n timeout: 1h\n workflows: [bb-server.yaml]', + ); + const workflowRun = (over: Record = {}) => ({ workflow: ".github/workflows/bb-server.yaml", name: "bb-server", conclusion: "failure", url: "https://github.com/acme/bb-gate/actions/runs/42", sha: "ccccccc3", run_attempt: 1, ...over }); + const runDoorbell = async (t: Awaited>, id: string, workflow_run: Record) => { + await t.harness.callRpc("stewardsRing", { source: "github", id, workflow_run }, { experimental_caller: { kind: "plugin", pluginId: "github-watcher" } }); + await t.flush(); + }; + + it("wakes the steward once for a named workflow run, listing the run and the open watch (BB-61)", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = workflowPlaybook(); + t.entities.set("uuid-12", issue({ id: "uuid-12", key: "ENG-12", state: "In Progress", linkedPulls: [{ url: "https://github.com/acme/web/pull/7", key: "acme/web#7" }] })); + t.entities.set("acme/web#7", pull({ key: "acme/web#7" }, { merged: true })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + const before = t.sends.filter((s) => s.threadId === steward).length; + await runDoorbell(t, "acme/bb-gate#42", workflowRun()); + // The watch stays awaiting a deployment: the plugin forwards the fact only. + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "merged" }); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before + 1); + const wake = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; + expect(wake).toMatch(/bb-server/u); + expect(wake).toMatch(/failure/u); + expect(wake).toMatch(/https:\/\/github.com\/acme\/bb-gate\/actions\/runs\/42/u); + expect(wake).toMatch(/head ccccccc/u); + expect(wake).toMatch(/acme\/web#7/u); + // A repeat delivery of the same run and attempt is not news. + await runDoorbell(t, "acme/bb-gate#42", workflowRun()); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before + 1); + // A re-run (a higher attempt) wakes again. + await runDoorbell(t, "acme/bb-gate#42", workflowRun({ run_attempt: 2 })); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before + 2); + }); + + it("ignores a workflow the playbook does not name (BB-61)", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = workflowPlaybook(); + t.entities.set("uuid-12", issue({ id: "uuid-12", key: "ENG-12", state: "In Progress", linkedPulls: [{ url: "https://github.com/acme/web/pull/7", key: "acme/web#7" }] })); + t.entities.set("acme/web#7", pull({ key: "acme/web#7" }, { merged: true })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + const before = t.sends.filter((s) => s.threadId === steward).length; + await runDoorbell(t, "acme/bb-gate#42", workflowRun({ workflow: ".github/workflows/image.yaml", name: "image" })); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before); + }); + + it("wakes nobody for a workflow run when the deployment target names no workflows (BB-61)", async () => { + const t = await setup(); + merged(t); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + const before = t.sends.filter((s) => s.threadId === steward).length; + await runDoorbell(t, "acme/bb-gate#42", workflowRun()); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before); + }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 40f51889..0321cd00 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -63,14 +63,16 @@ import { signatureLine, sourceContract, stewardsContract, + workflowRunSchema, type DependabotAlert, type DependabotSeverity, type Deployment, type EntitySnapshot, type SessionWake, type Source, + type WorkflowRun, } from "./source-contract.js"; -import { allDeployed, applyDeployment, applyDeploymentRead, deploymentLines, deploymentReportSchema, recordMerged, reportDeployment, timeOut, timeoutsDue } from "./deploy.js"; +import { allDeployed, applyDeployment, applyDeploymentRead, applyWorkflowRun, awaitingOnRepo, deploymentLines, deploymentReportSchema, matchesWorkflow, recordMerged, reportDeployment, timeOut, timeoutsDue } from "./deploy.js"; import { ACTORS, MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store, type Worker } from "./store.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { allPullsMerged, atWork, conflictsOf, finished, normalizeTouches, overlapping, touchesOverlap, type Conflict } from "./schedule.js"; @@ -78,7 +80,7 @@ import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PRO import { NEEDS_YOU_CHANGED } from "./channels.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; import type { DeploymentTarget } from "./config.js"; -import { PROJECT_STEWARD_INTRO, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerQuestion, workerReportedError, workerWaiting, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerQuestion, workerReportedError, workerWaiting, workflowRunLine, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; export const MULTI_REPO_PLUGIN_ID = "multi-repo"; /** multi-repo's environment provider: where every thread of a stewards project works. */ @@ -2873,6 +2875,38 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } + /** + * A GitHub `workflow_run` doorbell (BB-61). The entity id is + * "owner/repo#" and the object carries the workflow, conclusion, + * URL, head sha and attempt. A run of a workflow the playbook's + * deployment target names wakes every binding on that repo awaiting a + * deployment, once per (run id, attempt). The watch's state is not moved: + * the plugin forwards the fact that a named workflow failed, and the + * steward applies its playbook as for a timeout. The plugin assumes + * nothing about images, tags or pins, and never matches the run's sha. + */ + async function onWorkflowRunDoorbell(id: string, run: WorkflowRun, receivedAt: number): Promise { + const hash = id.lastIndexOf("#"); + const repo = hash === -1 ? "" : id.slice(0, hash); + if (repo === "") return; + const projects = await stewardedProjects(); + for (const config of projects) { + for (const b of store.open(config.projectId)) { + const playbook = bindingPlaybook(config, b); + const target = playbook?.deployment; + if (target === null || target === undefined) continue; + if (lc(target.repo) !== lc(repo)) continue; + if (!matchesWorkflow(target, run)) continue; + const applied = applyWorkflowRun(b.deployments, id, repo, run, receivedAt); + if (applied.woken.length === 0) continue; + store.patch(b.id, { deployments: applied.deployments }); + store.note(b.id, workflowRunLine(repo, run, awaitingOnRepo(applied.deployments, repo)), false); + bb.log.info(`stewards: workflow run ${id} (${run.conclusion}) on ${repo} concerns ${applied.woken.join(", ")}`); + scheduleReconcile(b.id); + } + } + } + /** A ring from a source: look at the binding(s) it concerns, or consider adopting. */ async function onRing(source: Source, id: string): Promise { const bound = store.byEntity(source, id); @@ -4092,8 +4126,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // ---- the RPC ------------------------------------------------------------------------------------- bb.rpc.register(rpcContract, { - async stewardsRing({ source, id, deployment }, { experimental_caller: caller }) { + async stewardsRing({ source, id, deployment, workflow_run }, { experimental_caller: caller }) { if (caller.kind !== "plugin" || caller.pluginId !== SOURCE_PLUGIN_IDS[source]) throw new Error("only the linear and github-watcher plugins ring stewards, each for its own source"); + if (workflow_run !== undefined) { + if (source !== "github") throw new Error("only the github-watcher plugin sends workflow_run doorbells"); + // Arrival is the only clock a workflow_run doorbell has (it carries + // no run start time), so capture it here, before the debounce, and + // let the handler skip a watch recorded after it (BB-61). + const at = now(); + debounce(`run:${lc(id)}`, () => serial(`run:${lc(id)}`, () => onWorkflowRunDoorbell(id, workflow_run, at))); + return { ok: true }; + } if (deployment !== undefined) { if (source !== "github") throw new Error("only the github-watcher plugin sends deployment doorbells"); debounce(`deploy:${lc(id)}`, () => serial(`deploy:${lc(id)}`, () => onDeploymentDoorbell(id, deployment))); diff --git a/plugins/stewards/source-contract.ts b/plugins/stewards/source-contract.ts index d722a573..02f2333d 100644 --- a/plugins/stewards/source-contract.ts +++ b/plugins/stewards/source-contract.ts @@ -51,6 +51,29 @@ export const deploymentSchema = z .loose(); export type Deployment = z.infer; +/** + * A GitHub Actions workflow run, as bb-gate-hooks forwards it on a + * `workflow_run` doorbell (bb-gate/docs/hooks.md). The doorbell's entity id + * is `owner/repo#` and its unit is the repository, leased the same + * way as a deployment (`deployment_repo`). `workflow` is the workflow's file + * path and `name` its name, either of which a playbook may match; + * `conclusion` is failure, cancelled or timed_out -- the only conclusions + * that ring the doorbell. `sha` is the run's head commit, which is usually + * the deploying repository's commit, not the merge's, so a subscriber must + * not match on it. `run_attempt` tells a re-run from the first attempt. + */ +export const workflowRunSchema = z + .object({ + workflow: z.string().default(""), + name: z.string().default(""), + conclusion: z.string().default(""), + url: z.string().nullable().default(null), + sha: z.string().default(""), + run_attempt: z.number().int().positive().default(1), + }) + .loose(); +export type WorkflowRun = z.infer; + /** How much of a comment or description crosses the contract. */ export const SNAPSHOT_COMMENT_CHARS = 4000; export const SNAPSHOT_DESCRIPTION_CHARS = 20_000; @@ -275,7 +298,9 @@ export const sourceContract = { * stewards wants: the deployment targets the project's playbooks name. It * is separate from `units` for the same reason as `dependabot`: a * repository lease does not receive deployment doorbells, so the github - * plugin leases each as a `deployment_repo`. Linear ignores it. + * plugin leases each as a `deployment_repo`. A `workflow_run` doorbell + * shares that lease, because only a project that names a deployment target + * cares about a workflow run. Linear ignores it. */ sourceSetInterest: { input: z.object({ @@ -373,11 +398,11 @@ export const stewardsContract = { /** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */ stewardsRing: { /** - * A `deployment` doorbell carries its deployment object, which is the one - * doorbell whose ref and state are not in the entity name. Every other - * doorbell leaves it out. + * A `deployment` doorbell carries its deployment object, and a + * `workflow_run` doorbell its run object: the two doorbells whose facts + * are not in the entity name. Every other doorbell leaves both out. */ - input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional() }), + input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional(), workflow_run: workflowRunSchema.optional() }), output: z.object({ ok: z.boolean() }), }, /** diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 89b9b79e..7e8534cf 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -14,7 +14,7 @@ import { dueDate } from "./deps.js"; import { NO_TOKEN, TOKEN_PAGE, TOKEN_SCOPES, TOKEN_SETTING, type SentryFinding, type SentryLook, type SentryReason } from "./sentry.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 { EntitySnapshot, SessionWake, SnapshotComment, WorkflowRun } from "./source-contract.js"; import { needChoices, ESCALATED_NEED_KINDS, RESOLUTION_KINDS, STEWARD_NEED_KINDS, type Binding, type Escalation, type Lesson, type Need, type Observed, type Question, type Worker } from "./store.js"; /** A wake longer than this is cut in its snapshot, never in what changed or what to do. */ @@ -320,6 +320,22 @@ function deploymentLines(input: WakeInput): string[] { return out; } +/** + * The wake line for a failed workflow run (BB-61): the run's workflow, + * conclusion, URL and head sha, and every open watch on the repository it + * names. The plugin forwards the fact only, as it does for a deployment + * timeout; the playbook says what a failed build means. + */ +export function workflowRunLine(repo: string, run: WorkflowRun, watches: readonly DeploymentWatch[]): string { + const workflow = run.workflow.trim() === "" ? "a workflow" : `workflow ${run.workflow.trim()}`; + const name = run.name.trim() === "" ? "" : ` (${run.name.trim()})`; + const conclusion = run.conclusion.trim() === "" ? "completed" : run.conclusion.trim(); + const url = run.url === null || run.url === "" ? "" : ` — ${run.url}`; + const sha = run.sha.trim() === "" ? "" : `, head ${run.sha.slice(0, 7)}`; + const names = watches.map((w) => w.key).join(", "); + return `${workflow}${name} ${conclusion} on ${repo}${sha}${url}. Merges awaiting deployment: ${names}. Treat this as a deployment timeout: look once, comment on the pull requests, and escalate a decision if the work cannot ship.`; +} + function gateLines(input: Pick): string[] { const { gate, binding, playbook } = input; if (gate.none) return ["No ready gate in this playbook."]; From b1ca22bb17b1abb1b3a0ebe514a04bc6f58f7b4e Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 26 Oct 2026 13:45:50 +0000 Subject: [PATCH 2/3] stewards: record a workflow-run event on an arrival-skipped watch (BB-61) --- plugins/stewards/deploy.test.ts | 9 +++++++-- plugins/stewards/deploy.ts | 15 ++++++++------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/plugins/stewards/deploy.test.ts b/plugins/stewards/deploy.test.ts index 5f9d4667..6e808b5f 100644 --- a/plugins/stewards/deploy.test.ts +++ b/plugins/stewards/deploy.test.ts @@ -208,8 +208,13 @@ describe("a failed workflow run (BB-61)", () => { expect(applyWorkflowRun(deployments, "acme/other#42", "acme/other", run(), NOW).woken).toEqual([]); const settled: Deployments = { "acme/web#7": { ...deployments["acme/web#7"]!, state: "deployed" } }; expect(applyWorkflowRun(settled, "acme/bb-gate#42", "acme/bb-gate", run(), NOW).woken).toEqual([]); - // The watch was recorded after the doorbell arrived: the run cannot concern it. - expect(applyWorkflowRun(deployments, "acme/bb-gate#42", "acme/bb-gate", run(), NOW - 1).woken).toEqual([]); + // The watch was recorded after the doorbell arrived: the run cannot concern + // it, so it is not woken, but the event is recorded on it so a repeat + // delivery of the same run and attempt does not wake it later. + const late = applyWorkflowRun(deployments, "acme/bb-gate#42", "acme/bb-gate", run(), NOW - 1); + expect(late.woken).toEqual([]); + expect(late.deployments["acme/web#7"]!.workflowRuns).toEqual(["acme/bb-gate#42#1"]); + expect(applyWorkflowRun(late.deployments, "acme/bb-gate#42", "acme/bb-gate", run(), NOW).woken).toEqual([]); }); it("lists the watches still awaiting a deployment on a repo, and keys an event by run and attempt", () => { diff --git a/plugins/stewards/deploy.ts b/plugins/stewards/deploy.ts index 2461d6c8..52741521 100644 --- a/plugins/stewards/deploy.ts +++ b/plugins/stewards/deploy.ts @@ -159,11 +159,13 @@ export const awaitingOnRepo = (deployments: Deployments, repo: string): Deployme * The watch's deployment state is not moved: the plugin forwards only the * fact that a named workflow failed, and the steward applies its playbook as * for a timeout. `receivedAt` is when the doorbell reached the server; a - * watch recorded after that (its merge came later) is left alone, since the - * run cannot concern it. The doorbell carries no run start or completion - * time, so arrival is the only clock there is, and the run's `sha` is never - * matched: it is usually the deploying repository's commit, not the merge's. - * Returns the watches this event is news for. + * watch recorded after that (its merge came later) is not woken, since the + * run cannot concern it, but the event is still recorded on it so a repeat + * delivery of the same run and attempt does not wake it later. The doorbell + * carries no run start or completion time, so arrival is the only clock there + * is, and the run's `sha` is never matched: it is usually the deploying + * repository's commit, not the merge's. Returns the watches this event is + * news for. */ export function applyWorkflowRun(deployments: Deployments, id: string, repo: string, run: WorkflowRun, receivedAt: number): { deployments: Deployments; woken: string[] } { const key = workflowRunKey(id, run.run_attempt); @@ -172,10 +174,9 @@ export function applyWorkflowRun(deployments: Deployments, id: string, repo: str for (const watch of Object.values(next)) { if (watch.state !== "merged" && watch.state !== "deploying") continue; if (watch.repo.toLowerCase() !== repo.toLowerCase()) continue; - if (watch.at > receivedAt) continue; if (watch.workflowRuns.includes(key)) continue; next[watch.key] = { ...watch, workflowRuns: [...watch.workflowRuns, key] }; - woken.push(watch.key); + if (watch.at <= receivedAt) woken.push(watch.key); } return { deployments: next, woken }; } From 0f0a5caaa545d86ef29eae60f017b986937c938e Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 26 Oct 2026 13:50:25 +0000 Subject: [PATCH 3/3] stewards: persist a workflow-run event recorded without a wake (BB-61) --- plugins/stewards/deploy.test.ts | 3 +++ plugins/stewards/deploy.ts | 12 ++++++++---- plugins/stewards/server.test.ts | 21 +++++++++++++++++++++ plugins/stewards/server.ts | 6 +++++- 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/plugins/stewards/deploy.test.ts b/plugins/stewards/deploy.test.ts index 6e808b5f..46bfb33b 100644 --- a/plugins/stewards/deploy.test.ts +++ b/plugins/stewards/deploy.test.ts @@ -193,10 +193,12 @@ describe("a failed workflow run (BB-61)", () => { it("wakes an awaiting watch once per run and attempt, leaving its state alone", () => { const first = applyWorkflowRun(mergedWatch(), "acme/bb-gate#42", "acme/bb-gate", run(), NOW + 1000); expect(first.woken).toEqual(["acme/web#7"]); + expect(first.recorded).toEqual(["acme/web#7"]); expect(first.deployments["acme/web#7"]).toMatchObject({ state: "merged", workflowRuns: ["acme/bb-gate#42#1"] }); // The same run and attempt is not news, however often it is delivered. const repeat = applyWorkflowRun(first.deployments, "acme/bb-gate#42", "acme/bb-gate", run(), NOW + 2000); expect(repeat.woken).toEqual([]); + expect(repeat.recorded).toEqual([]); expect(repeat.deployments).toEqual(first.deployments); // A re-run (a higher attempt) wakes again. const again = applyWorkflowRun(first.deployments, "acme/bb-gate#42", "acme/bb-gate", run({ run_attempt: 2 }), NOW + 3000); @@ -213,6 +215,7 @@ describe("a failed workflow run (BB-61)", () => { // delivery of the same run and attempt does not wake it later. const late = applyWorkflowRun(deployments, "acme/bb-gate#42", "acme/bb-gate", run(), NOW - 1); expect(late.woken).toEqual([]); + expect(late.recorded).toEqual(["acme/web#7"]); expect(late.deployments["acme/web#7"]!.workflowRuns).toEqual(["acme/bb-gate#42#1"]); expect(applyWorkflowRun(late.deployments, "acme/bb-gate#42", "acme/bb-gate", run(), NOW).woken).toEqual([]); }); diff --git a/plugins/stewards/deploy.ts b/plugins/stewards/deploy.ts index 52741521..9a2ae48e 100644 --- a/plugins/stewards/deploy.ts +++ b/plugins/stewards/deploy.ts @@ -164,21 +164,25 @@ export const awaitingOnRepo = (deployments: Deployments, repo: string): Deployme * delivery of the same run and attempt does not wake it later. The doorbell * carries no run start or completion time, so arrival is the only clock there * is, and the run's `sha` is never matched: it is usually the deploying - * repository's commit, not the merge's. Returns the watches this event is - * news for. + * repository's commit, not the merge's. `woken` is the watches this event is + * news for; `recorded` is every watch that now carries the key, which the + * caller must persist even when nothing is woken, or a repeat delivery would + * wake an arrival-skipped watch later. */ -export function applyWorkflowRun(deployments: Deployments, id: string, repo: string, run: WorkflowRun, receivedAt: number): { deployments: Deployments; woken: string[] } { +export function applyWorkflowRun(deployments: Deployments, id: string, repo: string, run: WorkflowRun, receivedAt: number): { deployments: Deployments; woken: string[]; recorded: string[] } { const key = workflowRunKey(id, run.run_attempt); const next = { ...deployments }; const woken: string[] = []; + const recorded: string[] = []; for (const watch of Object.values(next)) { if (watch.state !== "merged" && watch.state !== "deploying") continue; if (watch.repo.toLowerCase() !== repo.toLowerCase()) continue; if (watch.workflowRuns.includes(key)) continue; next[watch.key] = { ...watch, workflowRuns: [...watch.workflowRuns, key] }; + recorded.push(watch.key); if (watch.at <= receivedAt) woken.push(watch.key); } - return { deployments: next, woken }; + return { deployments: next, woken, recorded }; } /** diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 9c32b241..a2df570c 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -6092,6 +6092,27 @@ describe("deployment watching (BB-53)", () => { expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before + 2); }); + it("persists a workflow run on an arrival-skipped watch so a repeat delivery does not wake it (BB-61)", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = workflowPlaybook(); + t.entities.set("uuid-12", issue({ id: "uuid-12", key: "ENG-12", state: "In Progress", linkedPulls: [{ url: "https://github.com/acme/web/pull/7", key: "acme/web#7" }] })); + t.entities.set("acme/web#7", pull({ key: "acme/web#7" }, { merged: true })); + await t.ring("linear", "uuid-12"); + const binding = t.hooks.store.find("ENG-12")!; + const steward = t.spawns[1]!.id; + const before = t.sends.filter((s) => s.threadId === steward).length; + // The watch is recorded after the doorbell arrives: the run cannot concern + // it, so it must not wake, but the event must persist on it so a repeat + // delivery of the same run and attempt cannot wake it later. + const watch = binding.deployments["acme/web#7"]!; + t.hooks.store.patch(binding.id, { deployments: { "acme/web#7": { ...watch, at: t.now() + 100_000 } } }); + await runDoorbell(t, "acme/bb-gate#42", workflowRun()); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]!.workflowRuns).toEqual(["acme/bb-gate#42#1"]); + await runDoorbell(t, "acme/bb-gate#42", workflowRun()); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before); + }); + it("ignores a workflow the playbook does not name (BB-61)", async () => { const t = await setup(); t.files[playbookPath("linear-tickets")] = workflowPlaybook(); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 0321cd00..257908fb 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -2898,8 +2898,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (lc(target.repo) !== lc(repo)) continue; if (!matchesWorkflow(target, run)) continue; const applied = applyWorkflowRun(b.deployments, id, repo, run, receivedAt); - if (applied.woken.length === 0) continue; + if (applied.recorded.length === 0) continue; + // Persist the event even when it wakes nobody (an arrival-skipped + // watch): a repeat delivery of the same run and attempt must not + // wake that watch later (BB-61). store.patch(b.id, { deployments: applied.deployments }); + if (applied.woken.length === 0) continue; store.note(b.id, workflowRunLine(repo, run, awaitingOnRepo(applied.deployments, repo)), false); bb.log.info(`stewards: workflow run ${id} (${run.conclusion}) on ${repo} concerns ${applied.woken.join(", ")}`); scheduleReconcile(b.id);