From f7d9767991338d8fec3b31a707452c26f60fdf45 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sun, 25 Oct 2026 18:44:05 +0000 Subject: [PATCH 1/2] stewards, github-watcher: a deployment source, and deployment-agnostic stewards (BB-53) The github plugin leases a project's deployment-target repos as deployment_repo and hands stewards each deployment doorbell's object. The stewards plugin records a merged pull request as awaiting deployment when its playbook names a target, wakes the binding on a doorbell, and lets the steward decide from the playbook's rule whether it carries the merge; a failure or a timeout wakes it with the run URL. Once every pull request is merged and deployed the steward posts the one closing comment. A project with no deployment target behaves exactly as before. --- plugins/github-watcher/hooks-client.ts | 17 +- plugins/github-watcher/server.test.ts | 24 ++- plugins/github-watcher/server.ts | 59 ++++++- plugins/github-watcher/source-contract.ts | 35 +++- plugins/github-watcher/usage.test.ts | 2 +- plugins/github-watcher/usage.ts | 5 +- plugins/linear/source-contract.ts | 35 +++- plugins/stewards/DESIGN.md | 27 ++- plugins/stewards/README.md | 14 +- plugins/stewards/config.ts | 31 ++++ plugins/stewards/deploy.test.ts | 136 +++++++++++++++ plugins/stewards/deploy.ts | 196 ++++++++++++++++++++++ plugins/stewards/server.test.ts | 141 +++++++++++++++- plugins/stewards/server.ts | 148 +++++++++++++++- plugins/stewards/skills/stewards/SKILL.md | 13 ++ plugins/stewards/source-contract.ts | 35 +++- plugins/stewards/store.ts | 12 +- plugins/stewards/wake.ts | 58 +++++++ 18 files changed, 948 insertions(+), 40 deletions(-) create mode 100644 plugins/stewards/deploy.test.ts create mode 100644 plugins/stewards/deploy.ts diff --git a/plugins/github-watcher/hooks-client.ts b/plugins/github-watcher/hooks-client.ts index 885b4ca0..4a58e58b 100644 --- a/plugins/github-watcher/hooks-client.ts +++ b/plugins/github-watcher/hooks-client.ts @@ -26,7 +26,7 @@ export const SUBSCRIBE_BATCH = 100; * separate because reading a repository does not entitle a token to its * alerts (bb-gate/docs/hooks.md). */ -export type LeaseKind = "issue" | "repo" | "dependabot_repo"; +export type LeaseKind = "issue" | "repo" | "dependabot_repo" | "deployment_repo"; export type Lease = { kind: LeaseKind; id: string }; // ---- server-sent events ---------------------------------------------------- @@ -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() }).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() }).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,11 +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` or `dependabot_alert`), the entity id, and - * the unit (the repository) when the service named one. The caller decides - * what to look at. + * 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. */ - onDoorbell: (kind: string, id: string, unit: string | null) => void; + onDoorbell: (kind: string, id: string, unit: string | null, deployment?: 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. */ @@ -426,10 +427,10 @@ 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")) { + if (doorbell.success && doorbell.data.source === SOURCE && (doorbell.data.kind === "issue" || doorbell.data.kind === "dependabot_alert" || doorbell.data.kind === "deployment")) { doorbells.push(); const unit = doorbell.data.unit?.trim() ?? ""; - deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit); + deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit, doorbell.data.deployment); } } } diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index c9715210..e5b52c1c 100644 --- a/plugins/github-watcher/server.test.ts +++ b/plugins/github-watcher/server.test.ts @@ -582,7 +582,7 @@ describe("stewards' source contract", () => { expect(w.hooks.subscribes).toEqual([]); expect(await w.harness.callRpc("sourceSetInterest", { units: ["acme/gadgets"], entities: ["https://github.com/Acme/Widgets/pull/12"] }, STEWARDS)).toEqual({ ok: true }); - expect(await w.bb.storage.kv.get("stewards/interest")).toEqual({ units: ["acme/gadgets"], entities: ["Acme/Widgets#12"], dependabot: [] }); + expect(await w.bb.storage.kv.get("stewards/interest")).toEqual({ units: ["acme/gadgets"], entities: ["Acme/Widgets#12"], dependabot: [], deployment: [] }); type Interest = { units: string[]; entities: Array<{ key: string; url: string | null }>; unleased: Array<{ key: string; reason: string }> }; const interestOf = async () => ((await w.harness.callRpc("watches", null)) as { interest: Interest }).interest; expect(await interestOf()).toMatchObject({ units: ["acme/gadgets"], entities: [{ key: "Acme/Widgets#12", url: "https://github.com/Acme/Widgets/issues/12" }], unleased: [] }); @@ -640,6 +640,28 @@ describe("stewards' source contract", () => { await service.done; }); + it("leases deployment repositories and hands stewards a deployment doorbell's object", 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 deployment = { id: 7, environment: "production", ref: "main", sha: "abc123", state: "success", url: "https://github.com/acme/bb-gate/actions/runs/9" }; + w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "deployment", id: "Acme/bb-gate#7", unit: "Acme/bb-gate", deployment })}\n\n`); + w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "deployment", id: "Acme/Other#7", unit: "Acme/Other", deployment })}\n\n`); + await tick(3000); + expect(w.rpcs()).toEqual([{ pluginId: "stewards", method: "stewardsRing", input: { source: "github", id: "Acme/bb-gate#7", deployment } }]); + // 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); + service.controller.abort(); + await service.done; + }); + it("leases what stewards asked for after a restart, beside the watches", async () => { const w = await setup({ ...WITH_HOOKS, kv: { "stewards/interest": { units: ["acme/gadgets"], entities: ["acme/widgets#12"] } } }); await w.tool({ ref: "Acme/Widgets#12" }); diff --git a/plugins/github-watcher/server.ts b/plugins/github-watcher/server.ts index bdb5a3c2..d5387873 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -44,7 +44,7 @@ import { type Target, } from "./github.js"; import { createHooksLoop, HOOKS_URL_ENV, type Lease, type Rejection } from "./hooks-client.js"; -import { ringStewards, sourceContract, STEWARDS_PLUGIN_ID, type AdoptableEntity } from "./source-contract.js"; +import { deploymentSchema, ringStewards, sourceContract, STEWARDS_PLUGIN_ID, type AdoptableEntity, type Deployment } 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"; @@ -70,7 +70,7 @@ export const rpcContract = defineRpcContract({ /** Where the units and entities stewards wants to hear about are kept, so a restart keeps leasing them. */ export const INTEREST_KEY = "stewards/interest"; -const interestSchema = z.object({ units: z.array(z.string()), entities: z.array(z.string()), dependabot: z.array(z.string()).default([]) }); +const interestSchema = z.object({ units: z.array(z.string()), entities: z.array(z.string()), dependabot: z.array(z.string()).default([]), deployment: z.array(z.string()).default([]) }); type Interest = z.infer; /** How long a token read from gh is reused before gh is asked again. */ @@ -263,12 +263,13 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => // Kept in kv so a restart leases them again before stewards next says. const storedInterest = interestSchema.safeParse(await bb.storage.kv.get(INTEREST_KEY)); - let interest: Interest = storedInterest.success ? storedInterest.data : { units: [], entities: [], dependabot: [] }; + let interest: Interest = storedInterest.success ? storedInterest.data : { units: [], entities: [], dependabot: [], deployment: [] }; // GitHub's names are case-insensitive, and a doorbell spells them as // GitHub does, which need not be how a project file does. let interestRepos = new Set(interest.units.map((u) => u.toLowerCase())); let interestEntities = new Set(interest.entities.map((e) => e.toLowerCase())); let interestDependabot = new Set(interest.dependabot.map((r) => r.toLowerCase())); + let interestDeployment = new Set(interest.deployment.map((r) => r.toLowerCase())); /** Stewards' leases bb-gate-hooks refused, by ` `. */ const refusals = createRefusals(deps.now); @@ -286,6 +287,7 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => for (const key of interest.entities) add("issue", key); for (const repo of interest.units) add("repo", repo); for (const repo of interest.dependabot) add("dependabot_repo", repo); + for (const repo of interest.deployment) add("deployment_repo", repo); return out; } @@ -293,6 +295,7 @@ 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()); if (interestEntities.has(key.toLowerCase())) return true; return repo !== null && interestRepos.has(repo.toLowerCase()); } @@ -304,6 +307,22 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => const rings = createCheckQueue((key) => ringStewards(callStewards, { source: "github", id: key }, warn), { onError: (key, error) => warn(`ringing stewards for ${key} failed: ${errorMessage(error)}`) }); bb.onDispose(() => rings.stop()); + // A deployment doorbell carries its deployment object, which a plain ring + // does not; the queue holds the latest per deployment id and the ring + // hands it on. A doorbell with no readable object is dropped: there is + // nothing to decide carries from. + const pendingDeployments = new Map(); + const deploymentRings = createCheckQueue( + (id) => { + const deployment = pendingDeployments.get(id); + pendingDeployments.delete(id); + if (deployment === undefined) return Promise.resolve(); + return ringStewards(callStewards, { source: "github", id, deployment }, warn); + }, + { onError: (id, error) => warn(`ringing stewards for deployment ${id} failed: ${errorMessage(error)}`) }, + ); + bb.onDispose(() => deploymentRings.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 @@ -324,6 +343,13 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => if (interestDependabot.has(r.id.toLowerCase())) bb.log.info(`bb-gate-hooks refused a dependabot_repo lease on ${r.id} (${r.reason}); this server skips Dependabot alerts there`); continue; } + if (r.kind === "deployment_repo") { + // 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`); + continue; + } if (r.kind === "repo" || (watching.length === 0 && interestEntities.has(r.id.toLowerCase()))) { bb.log.warn(`bb-gate-hooks refused a lease on ${r.kind === "repo" ? `repository ${r.id}` : r.id} for stewards (${r.reason}); stewards will not be rung for it`); continue; @@ -352,8 +378,19 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => token: accessToken, refreshToken: () => refreshToken("was refused by bb-gate-hooks"), watchIds: leases, - onDoorbell: (kind, key, unit) => { + onDoorbell: (kind, key, unit, deployment) => { if (kind === "issue") checks.ring(key); + if (kind === "deployment") { + if (!interesting(kind, key, unit)) return; + const parsed = deploymentSchema.safeParse(deployment); + if (!parsed.success) { + bb.log.warn(`GitHub deployment doorbell ${key} carried no readable deployment; nothing to hand stewards`); + return; + } + pendingDeployments.set(key, parsed.data); + deploymentRings.ring(key); + return; + } if (interesting(kind, key, unit)) rings.ring(key); }, onRejected, @@ -410,10 +447,15 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => const reason = refused.get(`dependabot_repo ${repo.toLowerCase()}`); if (reason !== undefined) unleased.push({ key: repo, reason: `refused by bb-gate-hooks (${reason}); Dependabot alerts are skipped` }); } + 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` }); + } return { nouns: { unit: ["repository", "repositories"], entity: ["pull request", "pull requests"] }, units: interest.units, dependabot: [...interest.dependabot].sort((a, b) => a.localeCompare(b)), + deployment: [...interest.deployment].sort((a, b) => a.localeCompare(b)), entities: [...interest.entities].sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).map((key) => { const ref = parseRefKey(key); // GitHub sends /issues/N on to the pull request when it is one. @@ -541,17 +583,19 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => // Replaces the previous set. Anything new is leased right away; what // was dropped is simply not renewed and lapses within the hour. - async sourceSetInterest({ units, entities, dependabot }, { experimental_caller: caller }) { + async sourceSetInterest({ units, entities, dependabot, deployment }, { experimental_caller: caller }) { if (caller.kind !== "plugin" || caller.pluginId !== STEWARDS_PLUGIN_ID) throw new Error(`sourceSetInterest is for the ${STEWARDS_PLUGIN_ID} plugin only`); const badUnits = units.filter((u) => parseRepo(u) === null); const badEntities = entities.filter((e) => parseRef(e) === null); const badDependabot = dependabot.filter((r) => parseRepo(r) === null); - if (badUnits.length > 0 || badEntities.length > 0 || badDependabot.length > 0) { + const badDeployment = deployment.filter((r) => parseRepo(r) === null); + if (badUnits.length > 0 || badEntities.length > 0 || badDependabot.length > 0 || badDeployment.length > 0) { throw new Error( `not GitHub names: ${[ ...badUnits.map((u) => `${JSON.stringify(u)} (want owner/repo)`), ...badEntities.map((e) => `${JSON.stringify(e)} (want owner/repo#12)`), ...badDependabot.map((r) => `${JSON.stringify(r)} (want owner/repo)`), + ...badDeployment.map((r) => `${JSON.stringify(r)} (want owner/repo)`), ] .slice(0, 10) .join(", ")}`, @@ -562,12 +606,14 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => units: [...new Set(units.map((u) => u.trim()))], entities: [...new Set(entities.map((e) => refKey(parseRef(e)!)))], dependabot: [...new Set(dependabot.map((r) => r.trim()))], + deployment: [...new Set(deployment.map((r) => r.trim()))], }; await bb.storage.kv.set(INTEREST_KEY, next); interest = next; interestRepos = new Set(next.units.map((u) => u.toLowerCase())); interestEntities = new Set(next.entities.map((e) => e.toLowerCase())); interestDependabot = new Set(next.dependabot.map((r) => r.toLowerCase())); + interestDeployment = new Set(next.deployment.map((r) => r.toLowerCase())); announceWatches(); const fresh = leases().filter((l) => !before.has(`${l.kind} ${l.id.toLowerCase()}`)); const lease = (kind: Lease["kind"]) => { @@ -577,6 +623,7 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => lease("repo"); lease("issue"); lease("dependabot_repo"); + lease("deployment_repo"); return { ok: true }; }, }); diff --git a/plugins/github-watcher/source-contract.ts b/plugins/github-watcher/source-contract.ts index 25c59e04..3714bbb7 100644 --- a/plugins/github-watcher/source-contract.ts +++ b/plugins/github-watcher/source-contract.ts @@ -30,6 +30,27 @@ export type Source = z.infer; */ export const SOURCE_PLUGIN_IDS: Record = { linear: "linear", github: "github-watcher" }; +/** + * A GitHub Deployment, as bb-gate-hooks forwards it on a `deployment` + * doorbell (bb-gate/docs/hooks.md). The doorbell's entity id is + * `owner/repo#` and its unit is the repository; this object is the one + * piece of a doorbell that is not in the entity name, because a deployment's + * ref and state are what a subscriber decides on. `state` is empty on a bare + * `deployment` event and one of queued, in_progress, success, failure, error, + * inactive or pending on a `deployment_status` event. + */ +export const deploymentSchema = z + .object({ + id: z.number().int().nonnegative(), + environment: z.string().default(""), + ref: z.string().default(""), + sha: z.string().default(""), + state: z.string().default(""), + url: z.string().nullable().default(null), + }) + .loose(); +export type Deployment = 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; @@ -249,12 +270,19 @@ export const sourceContract = { * wants. It is separate from `units` because a repository lease does not * receive alert doorbells (bb-gate/docs/hooks.md): the github plugin leases * each as a `dependabot_repo`. Linear ignores it. + * + * `deployment` names repositories whose GitHub Deployment doorbells + * 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. */ sourceSetInterest: { input: z.object({ units: z.array(z.string().min(1).max(200)).max(200), entities: z.array(z.string().min(1).max(300)).max(2000), dependabot: z.array(z.string().min(1).max(200)).max(200).default([]), + deployment: z.array(z.string().min(1).max(200)).max(200).default([]), }), output: z.object({ ok: z.boolean() }), }, @@ -324,7 +352,12 @@ export type SessionWake = z.infer; export const stewardsContract = { /** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */ stewardsRing: { - input: z.object({ source: sourceSchema, id: z.string().min(1).max(300) }), + /** + * 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. + */ + input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional() }), output: z.object({ ok: z.boolean() }), }, /** diff --git a/plugins/github-watcher/usage.test.ts b/plugins/github-watcher/usage.test.ts index c96c1f3c..0dc23603 100644 --- a/plugins/github-watcher/usage.test.ts +++ b/plugins/github-watcher/usage.test.ts @@ -41,7 +41,7 @@ const row = (threadId: string, key: string, over: Partial = {}): Watch const target = (r: WatchRow) => ({ id: r.key, key: r.key, kind: r.kind, title: r.snapshot.title, url: `https://github.test/acme/pull/${r.key}` }); -const none: InterestView = { nouns: { unit: ["team", "teams"], entity: ["issue", "issues"] }, units: [], dependabot: [], entities: [], unleased: [] }; +const none: InterestView = { nouns: { unit: ["team", "teams"], entity: ["issue", "issues"] }, units: [], dependabot: [], deployment: [], entities: [], unleased: [] }; describe("buildUsage", () => { it("puts flagged watches first, noisy before idle before expiring, then the busiest, and sums per thread", () => { diff --git a/plugins/github-watcher/usage.ts b/plugins/github-watcher/usage.ts index 16cc43e8..1709089c 100644 --- a/plugins/github-watcher/usage.ts +++ b/plugins/github-watcher/usage.ts @@ -75,6 +75,8 @@ export const interestViewSchema = z.object({ units: z.array(z.string()), /** Repositories whose Dependabot alerts are leased, separate from `units`. */ dependabot: z.array(z.string()).default([]), + /** Repositories whose GitHub Deployment doorbells are leased, separate from `units` and `dependabot`. */ + deployment: z.array(z.string()).default([]), entities: z.array(z.object({ key: z.string(), url: z.string().nullable() })), /** What stewards asked for and is not leased, and why. Empty when all is well. */ unleased: z.array(z.object({ key: z.string(), reason: z.string() })), @@ -176,10 +178,11 @@ const ENTITIES_NAMED = 20; /** What stewards has leased, one line, then a line per thing it asked for that is not leased. */ export function describeInterest(i: InterestView): string[] { - if (i.units.length === 0 && i.entities.length === 0 && (i.dependabot ?? []).length === 0 && i.unleased.length === 0) return ["Stewards: nothing asked for."]; + if (i.units.length === 0 && i.entities.length === 0 && (i.dependabot ?? []).length === 0 && (i.deployment ?? []).length === 0 && i.unleased.length === 0) return ["Stewards: nothing asked for."]; const parts: string[] = []; if (i.units.length > 0) parts.push(`${i.units.length === 1 ? i.nouns.unit[0] : i.nouns.unit[1]} ${i.units.join(", ")}`); if ((i.dependabot ?? []).length > 0) parts.push(`Dependabot alerts for ${(i.dependabot ?? []).join(", ")}`); + if ((i.deployment ?? []).length > 0) parts.push(`deployment doorbells for ${(i.deployment ?? []).join(", ")}`); if (i.entities.length > 0) { const named = i.entities.slice(0, ENTITIES_NAMED).map((e) => e.key); const more = i.entities.length - named.length; diff --git a/plugins/linear/source-contract.ts b/plugins/linear/source-contract.ts index 25c59e04..3714bbb7 100644 --- a/plugins/linear/source-contract.ts +++ b/plugins/linear/source-contract.ts @@ -30,6 +30,27 @@ export type Source = z.infer; */ export const SOURCE_PLUGIN_IDS: Record = { linear: "linear", github: "github-watcher" }; +/** + * A GitHub Deployment, as bb-gate-hooks forwards it on a `deployment` + * doorbell (bb-gate/docs/hooks.md). The doorbell's entity id is + * `owner/repo#` and its unit is the repository; this object is the one + * piece of a doorbell that is not in the entity name, because a deployment's + * ref and state are what a subscriber decides on. `state` is empty on a bare + * `deployment` event and one of queued, in_progress, success, failure, error, + * inactive or pending on a `deployment_status` event. + */ +export const deploymentSchema = z + .object({ + id: z.number().int().nonnegative(), + environment: z.string().default(""), + ref: z.string().default(""), + sha: z.string().default(""), + state: z.string().default(""), + url: z.string().nullable().default(null), + }) + .loose(); +export type Deployment = 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; @@ -249,12 +270,19 @@ export const sourceContract = { * wants. It is separate from `units` because a repository lease does not * receive alert doorbells (bb-gate/docs/hooks.md): the github plugin leases * each as a `dependabot_repo`. Linear ignores it. + * + * `deployment` names repositories whose GitHub Deployment doorbells + * 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. */ sourceSetInterest: { input: z.object({ units: z.array(z.string().min(1).max(200)).max(200), entities: z.array(z.string().min(1).max(300)).max(2000), dependabot: z.array(z.string().min(1).max(200)).max(200).default([]), + deployment: z.array(z.string().min(1).max(200)).max(200).default([]), }), output: z.object({ ok: z.boolean() }), }, @@ -324,7 +352,12 @@ export type SessionWake = z.infer; export const stewardsContract = { /** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */ stewardsRing: { - input: z.object({ source: sourceSchema, id: z.string().min(1).max(300) }), + /** + * 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. + */ + input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional() }), output: z.object({ ok: z.boolean() }), }, /** diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 5677e553..a6343ca5 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -725,10 +725,26 @@ may: [comment, edit-description, set-state, set-labels, create-sub-issue, open-p models: { ... } # §13 requeue-default: 2d follow-through: 6h # how long a terminal binding may be kept open (§5) +deployment: # where a merge is confirmed live (BB-53); omit and nothing changes + source: github + repo: bitcomplete/bb-gate + environment: production + carries: "The pinned BB_PLUGINS_REF contains the merge commit." # the steward's rule + timeout: 6h ``` - **Phases are the entity's own states**, so the playbook needs no state machine. A ticket moved by hand is followed. +- **`deployment` is where a merge is confirmed live (BB-53).** It names the + source (`github`), the target repo and environment, the rule the steward + applies to decide whether a deployment carries a merge, and the timeout. A + merged pull request is recorded as awaiting deployment, the github plugin + leases the repo as a `deployment_repo`, and a `deployment` doorbell wakes + the binding with the deployment and the rule. The plugin never evaluates the + rule: the steward reports the verdict, and the ticket closes with one + 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. - **Stages** — `spec`, `build`, `review` — are what the plugin acts on (the ready gate blocks `build`). State names are what a person sees. - **Validation.** Phases must be workflow states of every listed team, labels @@ -1390,11 +1406,12 @@ own server behind bb-gate, so it is per developer in practice. - **One developer per project.** Nothing stops a teammate's server from stewarding the same ticket. - **`may` is not a wall.** See §11. -- **Deploys are not observed.** "Merged" is the terminal state for pull - requests. A deploy event source (GitHub deployment or workflow-run events - through bb-gate-hooks, and the deploy in the snapshot) would be new work in - three repos. Until then, a playbook that wants a deploy watched has the - steward follow through (§5) while a worker watches and verifies it. +- **Deploys are observed through the playbook's `deployment` target (BB-53).** + A merged pull request whose playbook names one is recorded as awaiting + deployment; a GitHub Deployment doorbell wakes the binding, and the steward + decides from the playbook's rule whether it carries the merge. A project + that names no target keeps "merged" as the terminal state and follows + through 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/README.md b/plugins/stewards/README.md index 72172a8d..340df45d 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -441,7 +441,19 @@ stuck }`; none for `ops`), `terminal` (at least one; none for `ops`), `ready` (` slashes, as Pi's `pi/fireworks/accounts/fireworks/models/…` do, and the last part is the level only when it names one), `requeue-default`, `follow-through` (how long a terminal binding may be kept open, 6h by -default), `skip-authors`. +default), `skip-authors`, `deployment`. + +`deployment` names where a merge is confirmed live (BB-53): `source` +(`github`), `repo` (the repo the deployment is created on, e.g. +`bitcomplete/bb-gate`), `environment`, `carries` (the rule the steward applies +to decide whether a deployment carries a merge; free text, shown in the wake +alongside the deployment) and `timeout` (how long to wait for one, 6h by +default). With it, a merged pull request is recorded as awaiting deployment, +the github plugin leases the repo as a `deployment_repo` and a `deployment` +doorbell for the repo and environment wakes the binding, and the steward +reports the verdict with `steward_report { deployment: { state } }`; a +failure/error deployment or a timeout wakes it with the run URL. With no +`deployment`, the playbook behaves exactly as before. The wake numbers the ready checklist, and `steward_report` takes each item by its number (or the playbook's exact words). It stores the playbook's wording, diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index cd525d88..3ac5de14 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -371,6 +371,32 @@ export type ReadyConfig = z.infer; /** The default cap on follow-through: a deploy and its verification, with room to spare. */ export const DEFAULT_FOLLOW_THROUGH_MS = 6 * 3_600_000; +/** + * Where a merge is confirmed live: the deployment source, the target repo and + * environment, the rule the steward applies to decide whether a deployment + * carries its merge, and how long to wait for one. A playbook with no + * `deployment` behaves exactly as before; the plugin records nothing and the + * steward follows through however its playbook says. + */ +export const deploymentTargetSchema = z + .object({ + source: z.literal("github"), + /** The repo the deployment is created on, as GitHub spells it, e.g. bitcomplete/bb-gate. */ + repo: z.string().trim().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u, "a repo such as bitcomplete/bb-gate"), + /** The deployment environment that confirms it, matched ignoring case. */ + environment: z.string().trim().min(1).max(100), + /** + * The rule the steward applies to decide whether a deployment carries a + * merge. Free text, shown in the wake beside the deployment; the plugin + * does not evaluate it. + */ + carries: z.string().trim().min(1).max(2000), + /** No matching deployment within this long wakes the steward. */ + timeout: durationSchema.default(DEFAULT_FOLLOW_THROUGH_MS), + }) + .strict(); +export type DeploymentTarget = z.infer; + export const PLAYBOOK_SOURCES = ["linear", "github", "k8s", "sentry"] as const; const SOURCE_OF: Record = { ticket: "linear", pr: "github", review: "github", ops: "k8s" }; @@ -393,6 +419,8 @@ export const frontMatterSchema = z "follow-through": durationSchema.default(DEFAULT_FOLLOW_THROUGH_MS), /** Reviews: pull request authors no review steward is made for (bots). */ "skip-authors": z.array(z.string().trim().min(1).max(100)).default([]), + /** Where a merge is confirmed live, when the project has a deployment source (BB-53). */ + deployment: deploymentTargetSchema.optional(), }) .strict(); @@ -409,6 +437,8 @@ export type Playbook = { requeueDefaultMs: number; followThroughMs: number; skipAuthors: string[]; + /** Where a merge is confirmed live, or null when the playbook names no deployment target. */ + deployment: DeploymentTarget | null; /** The text before the first `## ` heading: instructions for every phase. */ general: string; /** Each `## Phase` section's text, keyed by heading as written. */ @@ -477,6 +507,7 @@ export function parsePlaybook(text: string, expectedName: string): Parsed; pulls?: Array> } = {}): Observed => ({ + entity: over.entity ?? pull({ key: "acme/web#7" }, { merged: true }), + pulls: over.pulls ?? [], +}); + +const deployment = (over: Partial = {}): Deployment => ({ id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", state: "success", url: "https://github.com/acme/bb-gate/actions/runs/9", ...over }); + +describe("recording merged pull requests", () => { + it("records a merged pull request once, with the target and a deadline", () => { + const first = recordMerged({}, observed(), target, NOW); + expect(first).toEqual({ + "acme/web#7": { + key: "acme/web#7", + state: "merged", + mergeSha: "aaaaaaa1", + repo: "acme/bb-gate", + environment: "production", + deploymentId: null, + ref: null, + sha: null, + url: null, + at: NOW, + deadlineAt: NOW + target.timeout, + note: null, + }, + }); + // A second read does not reset the deadline or the merge sha. + expect(recordMerged(first, observed(), target, NOW + 1000)).toBe(first); + }); + + it("does not record an open pull request, and reads a ticket's linked merged ones", () => { + expect(recordMerged({}, observed({ entity: pull({ key: "acme/web#7" }, { merged: false }) }), target, NOW)).toEqual({}); + const linked = recordMerged({}, observed({ entity: pull({ key: "acme/web#7", kind: "pull" }, { merged: false }), pulls: [pull({ key: "acme/web#8" }, { merged: true })] }), target, NOW); + expect(Object.keys(linked)).toEqual(["acme/web#8"]); + }); + + it("treats a pull request whose state is merged as merged", () => { + expect(mergedPulls({ entity: pull({ state: "merged" }, { merged: false }), pulls: [] })).toHaveLength(1); + }); +}); + +describe("applying a deployment doorbell", () => { + it("matches the target repo and environment, ignoring case, and moves the watch to deploying", () => { + const deployments = recordMerged({}, observed(), target, NOW); + expect(matchesTarget(target, "Acme/BB-Gate", "Production")).toBe(true); + expect(matchesTarget(target, "acme/other", "production")).toBe(false); + const applied = applyDeployment(deployments, target, deployment(), NOW + 60_000); + expect(applied.changed).toEqual(["acme/web#7"]); + expect(applied.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentId: 7, ref: "main", sha: "bbbbbbb2", url: "https://github.com/acme/bb-gate/actions/runs/9", deadlineAt: null }); + }); + + it("marks a failure or error deployment failed, with the deployment's URL", () => { + const deployments = recordMerged({}, observed(), target, NOW); + for (const state of ["failure", "error"]) { + const applied = applyDeployment(deployments, target, deployment({ state }), NOW); + expect(applied.deployments["acme/web#7"]).toMatchObject({ state: "failed", note: `Deployment 7 reported ${state}` }); + } + }); + + it("ignores a doorbell for another repo or environment, and one for a settled watch", () => { + const deployments = recordMerged({}, observed(), target, NOW); + expect(applyDeployment(deployments, target, deployment({ environment: "staging" }), NOW).changed).toEqual([]); + expect(applyDeployment(deployments, { ...target, repo: "acme/other" }, deployment(), NOW).changed).toEqual([]); + const settled: Deployments = { "acme/web#7": { ...deployments["acme/web#7"]!, state: "deployed" } }; + expect(applyDeployment(settled, target, deployment(), NOW).changed).toEqual([]); + }); +}); + +describe("the no-deployment timeout", () => { + it("reports a watch past its deadline, and marking it failed is idempotent", () => { + const deployments = recordMerged({}, observed(), target, NOW); + expect(timeoutsDue(deployments, NOW + target.timeout - 1)).toEqual([]); + expect(timeoutsDue(deployments, NOW + target.timeout)).toEqual(["acme/web#7"]); + const failed = timeOut(deployments, ["acme/web#7"], NOW + target.timeout); + expect(failed["acme/web#7"]).toMatchObject({ state: "failed", deadlineAt: null }); + expect(timeoutsDue(failed, NOW + target.timeout + 1000)).toEqual([]); + }); + + it("does not time out a watch that already has a deployment", () => { + const applied = applyDeployment(recordMerged({}, observed(), target, NOW), target, deployment(), NOW); + expect(timeoutsDue(applied.deployments, NOW + target.timeout * 10)).toEqual([]); + }); +}); + +describe("the steward's verdict", () => { + const deploying = () => applyDeployment(recordMerged({}, observed(), target, NOW), target, deployment(), NOW).deployments; + + it("settles a watch on deployed, and reports all deployed", () => { + const result = reportDeployment(deploying(), { state: "deployed" }, NOW + 1000); + expect(result.changed).toMatchObject({ key: "acme/web#7", state: "deployed", deadlineAt: null }); + expect(allDeployed(result.deployments)).toBe(true); + expect(allDeployed({})).toBe(false); + }); + + it("puts a deployment that does not carry the merge back to awaiting", () => { + const result = reportDeployment(deploying(), { state: "not-yet", note: "ref does not pin the merge" }, NOW + 1000); + expect(result.changed).toMatchObject({ state: "merged", note: "ref does not pin the merge" }); + expect(allDeployed(result.deployments)).toBe(false); + }); + + it("marks a failed deployment failed", () => { + const result = reportDeployment(deploying(), { state: "failed", note: "run 9 red" }, NOW + 1000); + expect(result.changed).toMatchObject({ state: "failed", note: "run 9 red" }); + }); + + it("picks the watch a report names, by key or deployment id", () => { + const two = recordMerged(recordMerged({}, observed(), target, NOW), observed({ entity: pull({ key: "acme/web#8" }, { merged: true }) }), target, NOW); + expect(reportDeployment(two, { state: "deployed", key: "ACME/WEB#8" }, NOW).changed?.key).toBe("acme/web#8"); + const withDeployment = applyDeployment(two, target, deployment(), NOW).deployments; + expect(reportDeployment(withDeployment, { state: "deployed", deploymentId: 7 }, NOW).changed?.key).toBe("acme/web#7"); + // No key and more than one unsettled watch: nothing is picked. + expect(reportDeployment(two, { state: "deployed" }, NOW).changed).toBeNull(); + }); +}); + +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; + expect(deploymentLines(deployments)).toEqual(["acme/web#7: failed → acme/bb-gate production (deployment 7, ref main, sha bbbbbbb, https://github.com/acme/bb-gate/actions/runs/9) — Deployment 7 reported failure"]); + }); + + it("round-trips through the store schema", () => { + const deployments = recordMerged({}, observed(), target, NOW); + expect(deploymentsSchema.parse(JSON.parse(JSON.stringify(deployments)))).toEqual(deployments); + }); +}); diff --git a/plugins/stewards/deploy.ts b/plugins/stewards/deploy.ts new file mode 100644 index 00000000..87729647 --- /dev/null +++ b/plugins/stewards/deploy.ts @@ -0,0 +1,196 @@ +// Deployment watching: the per-pull-request state a binding keeps between a +// merge and the deployment that confirms it is live (BB-53). Pure: the store +// holds the state, and server.ts feeds in the snapshots and the deployment +// doorbells. Nothing here decides whether a deployment carries a merge; that +// 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 { Observed } from "./store.js"; + +/** + * A pull request's deployment state, as `bb stewards show` prints it: + * `merged` is merged and awaiting a deployment, `deploying` is a matching + * deployment seen but not yet confirmed to carry the merge, `deployed` is + * confirmed live, and `failed` is a failure/error deployment or a timeout. + */ +export const DEPLOY_STATES = ["merged", "deploying", "deployed", "failed"] as const; +export type DeployState = (typeof DEPLOY_STATES)[number]; + +export const deploymentWatchSchema = z.object({ + /** The pull request's key, e.g. "acme/web#12"; the map's key as well. */ + key: z.string(), + state: z.enum(DEPLOY_STATES), + /** The merged commit the deployment must carry. */ + mergeSha: z.string().nullable().default(null), + /** The playbook's target, recorded with the watch so a later playbook edit does not move it. */ + repo: z.string(), + environment: z.string(), + deploymentId: z.number().int().nullable().default(null), + ref: z.string().nullable().default(null), + sha: z.string().nullable().default(null), + url: z.string().nullable().default(null), + /** When the state last changed. */ + at: z.number(), + /** No matching deployment by then wakes the steward; null once there is one. */ + 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), +}); +export type DeploymentWatch = z.infer; + +export const deploymentsSchema = z.record(z.string(), deploymentWatchSchema); +export type Deployments = Record; + +/** The merged pull requests a binding should watch: its own entity when it is a pull request, and a ticket's linked ones. */ +export function mergedPulls(observed: Observed): EntitySnapshot[] { + return [observed.entity, ...observed.pulls].filter((e) => e.pull !== null && (e.pull.merged || e.state.toLowerCase() === "merged")); +} + +/** + * Add a `merged` watch for every merged pull request the binding does not + * already watch. The target's timeout is the deadline; a watch that already + * exists is left alone, so a re-read does not reset it. + */ +export function recordMerged(deployments: Deployments, observed: Observed, target: DeploymentTarget, now: number): Deployments { + const pulls = mergedPulls(observed); + if (pulls.length === 0) return deployments; + const next = { ...deployments }; + let changed = false; + for (const p of pulls) { + if (next[p.key] !== undefined) continue; + next[p.key] = { + key: p.key, + state: "merged", + mergeSha: p.pull?.headSha ?? null, + repo: target.repo, + environment: target.environment, + deploymentId: null, + ref: null, + sha: null, + url: null, + at: now, + deadlineAt: now + target.timeout, + note: null, + }; + changed = true; + } + return changed ? next : deployments; +} + +/** Whether a deployment doorbell's repo/environment is the one this target names. */ +export const matchesTarget = (target: Pick, repo: string, environment: string): boolean => + target.repo.toLowerCase() === repo.toLowerCase() && target.environment.toLowerCase() === environment.toLowerCase(); + +/** + * Apply a deployment doorbell to a binding's watches: every watch for the + * target that is not settled moves to `deploying` with the deployment's facts + * (or `failed` on a failure/error state). Returns the keys that moved. + */ +export function applyDeployment(deployments: Deployments, target: Pick, deployment: Deployment, now: number): { deployments: Deployments; changed: string[] } { + const next = { ...deployments }; + const changed: string[] = []; + const failed = deployment.state === "failure" || deployment.state === "error"; + for (const watch of Object.values(next)) { + if (watch.state === "deployed" || watch.state === "failed") continue; + if (!matchesTarget(target, watch.repo, watch.environment)) continue; + // The doorbell's own environment has to be the target's too; the caller + // matched the repo already, and a doorbell for another environment is not + // this target's. + if (deployment.environment.toLowerCase() !== watch.environment.toLowerCase()) continue; + next[watch.key] = { + ...watch, + state: failed ? "failed" : "deploying", + deploymentId: deployment.id, + ref: deployment.ref === "" ? null : deployment.ref, + sha: deployment.sha === "" ? null : deployment.sha, + url: deployment.url, + at: now, + deadlineAt: null, + note: failed ? `Deployment ${deployment.id} reported ${deployment.state}` : watch.note, + }; + changed.push(watch.key); + } + return { deployments: next, changed }; +} + +/** The watches still awaiting a deployment whose deadline has passed. */ +export const timeoutsDue = (deployments: Deployments, now: number): string[] => + Object.values(deployments) + .filter((w) => (w.state === "merged" || w.state === "deploying") && w.deadlineAt !== null && now >= w.deadlineAt) + .map((w) => w.key); + +/** Mark timed-out watches failed, so the steward is woken once and the state does not flap. */ +export function timeOut(deployments: Deployments, keys: readonly string[], now: number): Deployments { + const next = { ...deployments }; + for (const key of keys) { + const watch = next[key]; + if (watch === undefined) continue; + next[key] = { ...watch, state: "failed", at: now, deadlineAt: null, note: watch.note ?? "No matching deployment within the playbook's timeout" }; + } + return next; +} + +/** What a steward reports about a deployment: whether it carries the merge, or that it failed. */ +export const deploymentReportSchema = z.object({ + state: z.enum(["deployed", "failed", "not-yet"]), + /** The pull request key, when the binding watches more than one. */ + key: z.string().trim().min(1).max(300).optional(), + /** The deployment id, when the steward is answering a specific doorbell. */ + deploymentId: z.number().int().nonnegative().optional(), + note: z.string().trim().max(2000).optional(), +}); +export type DeploymentReport = z.infer; + +/** The watch a report names: by key, by deployment id, or the only unsettled one. */ +export function pickWatch(deployments: Deployments, report: DeploymentReport): DeploymentWatch | null { + const all = Object.values(deployments); + if (report.key !== undefined) return all.find((w) => w.key.toLowerCase() === report.key!.toLowerCase()) ?? null; + if (report.deploymentId !== undefined) return all.find((w) => w.deploymentId === report.deploymentId) ?? null; + const unsettled = all.filter((w) => w.state === "merged" || w.state === "deploying"); + return unsettled.length === 1 ? unsettled[0]! : null; +} + +/** + * Apply a steward's verdict. `deployed` settles the watch; `failed` marks it + * failed; `not-yet` puts it back to `merged` with the note, so a later + * deployment for the same target can still carry it. + */ +export function reportDeployment(deployments: Deployments, report: DeploymentReport, now: number): { deployments: Deployments; changed: DeploymentWatch | null } { + const watch = pickWatch(deployments, report); + if (watch === null) return { deployments, changed: null }; + const next = { ...deployments }; + const note = report.note ?? null; + if (report.state === "deployed") next[watch.key] = { ...watch, state: "deployed", at: now, deadlineAt: null, note }; + else if (report.state === "failed") next[watch.key] = { ...watch, state: "failed", at: now, deadlineAt: null, note: note ?? watch.note }; + else next[watch.key] = { ...watch, state: "merged", at: now, note: note ?? "The deployment does not carry this merge yet" }; + return { deployments: next, changed: next[watch.key]! }; +} + +/** Whether every watched pull request is deployed and there is at least one. */ +export const allDeployed = (deployments: Deployments): boolean => { + const all = Object.values(deployments); + return all.length > 0 && all.every((w) => w.state === "deployed"); +}; + +/** Whether any watch is still unsettled: merged, deploying, or failed (a failure needs a person too). */ +export const anyPending = (deployments: Deployments): boolean => Object.values(deployments).some((w) => w.state !== "deployed"); + +/** The watches still awaiting a first deployment, for the wake's "awaiting" line. */ +export const awaitingDeployment = (deployments: Deployments): DeploymentWatch[] => Object.values(deployments).filter((w) => w.state === "merged" || w.state === "deploying"); + +/** One line per watch, as `bb stewards show` prints them. */ +export function deploymentLines(deployments: Deployments): string[] { + return Object.values(deployments) + .sort((a, b) => a.key.localeCompare(b.key)) + .map((w) => { + const where = `→ ${w.repo} ${w.environment}`; + const facts = [ + w.deploymentId === null ? null : `deployment ${w.deploymentId}`, + w.ref === null ? null : `ref ${w.ref}`, + w.sha === null ? null : `sha ${w.sha.slice(0, 7)}`, + w.url === null ? null : w.url, + ].filter((x): x is string => x !== null); + return `${w.key}: ${w.state} ${where}${facts.length === 0 ? "" : ` (${facts.join(", ")})`}${w.note === null ? "" : ` — ${w.note}`}`; + }); +} diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index cfc6d398..9cfcaa3d 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -417,8 +417,8 @@ describe("a Linear ticket steward", () => { expect(await t.list()).toMatchObject([{ key: "ENG-12", kind: "ticket", threadId: steward!.id, ended: false }]); const interest = t.rpcCalls.filter((c) => c.method === "sourceSetInterest"); - expect(interest.find((c) => c.pluginId === "linear")?.input).toEqual({ units: ["ENG"], entities: ["uuid-12"], dependabot: [] }); - expect(interest.find((c) => c.pluginId === "github-watcher")?.input).toEqual({ units: ["acme/web"], entities: [], dependabot: [] }); + expect(interest.find((c) => c.pluginId === "linear")?.input).toEqual({ units: ["ENG"], entities: ["uuid-12"], dependabot: [], deployment: [] }); + expect(interest.find((c) => c.pluginId === "github-watcher")?.input).toEqual({ units: ["acme/web"], entities: [], dependabot: [], deployment: [] }); }); it("ignores unlabelled tickets, other teams, and rings from anyone but a source plugin", async () => { @@ -1012,7 +1012,7 @@ describe("a Linear ticket steward", () => { // acme/web#10 has no snapshot: it cannot be read yet. await t.ring("linear", "uuid-12"); const github = t.rpcCalls.filter((c) => c.method === "sourceSetInterest" && c.pluginId === "github-watcher").at(-1)?.input; - expect(github).toEqual({ units: ["acme/web"], entities: ["acme/web#10", "acme/web#7"], dependabot: [] }); + expect(github).toEqual({ units: ["acme/web"], entities: ["acme/web#10", "acme/web#7"], dependabot: [], deployment: [] }); }); it("stops leasing a linked pull request once it merges", async () => { @@ -1022,13 +1022,13 @@ describe("a Linear ticket steward", () => { t.entities.set("acme/web#7", pull()); await t.ring("linear", "uuid-12"); const github = () => t.rpcCalls.filter((c) => c.method === "sourceSetInterest" && c.pluginId === "github-watcher"); - expect(github().at(-1)?.input).toEqual({ units: ["acme/web"], entities: ["acme/web#7"], dependabot: [] }); + expect(github().at(-1)?.input).toEqual({ units: ["acme/web"], entities: ["acme/web#7"], dependabot: [], deployment: [] }); const sent = github().length; t.entities.set("acme/web#7", pull({ state: "merged" }, { merged: true })); await t.ring("github", "acme/web#7"); expect(github()).toHaveLength(sent + 1); - expect(github().at(-1)?.input).toEqual({ units: ["acme/web"], entities: [], dependabot: [] }); + expect(github().at(-1)?.input).toEqual({ units: ["acme/web"], entities: [], dependabot: [], deployment: [] }); }); it("counts a worker woken again (by a watch, a reviewer) as running", async () => { @@ -5409,3 +5409,134 @@ describe("the load-time sidebar thread-list pin (BB-45)", () => { } }); }); + +// BB-53: a merged pull request whose playbook names a deployment target is +// recorded as awaiting one; a GitHub Deployment doorbell wakes the bindings +// awaiting it, and the steward decides from the playbook's rule whether it +// carries the merge. +describe("deployment watching (BB-53)", () => { + const deploymentPlaybook = () => + 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', + ); + const merged = (t: Awaited>, id = "uuid-12", key = "ENG-12", pullKey = "acme/web#7") => { + t.files[playbookPath("linear-tickets")] = deploymentPlaybook(); + t.entities.set(id, issue({ id, key, state: "In Progress", linkedPulls: [{ url: `https://github.com/acme/web/pull/${pullKey.split("#")[1]}`, key: pullKey }] })); + t.entities.set(pullKey, pull({ key: pullKey }, { merged: true })); + }; + const doorbell = async (t: Awaited>, id: string, deployment: Record) => { + await t.harness.callRpc("stewardsRing", { source: "github", id, deployment }, { experimental_caller: { kind: "plugin", pluginId: "github-watcher" } }); + await t.flush(); + }; + const deployment = (over: Record = {}) => ({ id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", state: "success", url: "https://github.com/acme/bb-gate/actions/runs/9", ...over }); + const githubInterest = (t: Awaited>) => t.rpcCalls.filter((c) => c.method === "sourceSetInterest" && c.pluginId === "github-watcher").at(-1)!.input as { deployment: string[] }; + + it("records a merge as awaiting deployment, leases the target repo, and shows the state in the wake", async () => { + const t = await setup(); + merged(t); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "merged", repo: "acme/bb-gate", environment: "production" }); + expect(githubInterest(t).deployment).toEqual(["acme/bb-gate"]); + const prompt = String(t.spawns[1]!.prompt); + expect(prompt).toMatch(/### Deployment \(acme\/bb-gate production\)/u); + expect(prompt).toMatch(/The pinned BB_PLUGINS_REF contains the merge commit\./u); + expect(prompt).toMatch(/Awaiting deployment: acme\/web#7/u); + }); + + it("routes a deployment doorbell to the awaiting binding and shows the deployment in the wake", 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 doorbell(t, "acme/bb-gate#7", deployment()); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentId: 7, sha: "bbbbbbb2" }); + 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(/Deployment 7 \(success\) for acme\/bb-gate production/u); + expect(wake).toMatch(/### Deployment \(acme\/bb-gate production\)/u); + expect(wake).toMatch(/The pinned BB_PLUGINS_REF contains the merge commit\./u); + // The rule's inputs: the merged commit and the deployment's ref and sha. + expect(wake).toMatch(/merge aaaaaaa/u); + expect(wake).toMatch(/ref main/u); + expect(wake).toMatch(/sha bbbbbbb/u); + }); + + it("marks the pull request deployed when the steward reports the rule carried, and wakes for the closing comment", async () => { + const t = await setup(); + merged(t); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await doorbell(t, "acme/bb-gate#7", deployment()); + const reported = await t.tool("steward_report", { phase: "In Review", summary: "The deployment pins the merge.", nextAction: "Close the ticket", actor: "steward", deployment: { state: "deployed" } }, steward); + expect(reported.error).toBe(false); + await t.flush(); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "deployed" }); + expect(t.sends.filter((s) => s.threadId === steward).at(-1)!.text).toMatch(/Every pull request is merged and deployed/u); + }); + + it("keeps the pull request awaiting when the steward reports the deployment does not carry the merge", async () => { + const t = await setup(); + merged(t); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await doorbell(t, "acme/bb-gate#7", deployment()); + await t.tool("steward_report", { phase: "In Review", summary: "The pin is behind.", nextAction: "Wait", actor: "other", deployment: { state: "not-yet", note: "BB_PLUGINS_REF does not contain aaaaaaa1" } }, steward); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "merged", note: "BB_PLUGINS_REF does not contain aaaaaaa1" }); + }); + + it("wakes the steward with the run URL on a failure deployment", async () => { + const t = await setup(); + merged(t); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await doorbell(t, "acme/bb-gate#7", deployment({ state: "failure", url: "https://github.com/acme/bb-gate/actions/runs/12" })); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "failed" }); + const wake = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; + expect(wake).toMatch(/Deployment 7 \(failure\) for acme\/bb-gate production/u); + expect(wake).toMatch(/https:\/\/github.com\/acme\/bb-gate\/actions\/runs\/12/u); + }); + + it("wakes the steward with the run URL when no deployment arrives within the playbook's timeout", async () => { + const t = await setup(); + merged(t); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + t.advance(61 * 60_000); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "failed" }); + const wake = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; + expect(wake).toMatch(/No matching deployment for acme\/web#7 within 1h/u); + expect(wake).toMatch(/https:\/\/github.com\/acme\/bb-gate\/actions/u); + }); + + it("releases two tickets with one deployment", async () => { + const t = await setup(); + merged(t); + merged(t, "uuid-13", "ENG-13", "acme/web#8"); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + const stewards = t.spawns.filter((s) => s.title === "ENG-12: Fix login" || s.title === "ENG-13: Add SSO").map((s) => s.id); + await doorbell(t, "acme/bb-gate#7", deployment()); + for (const key of ["ENG-12", "ENG-13"]) { + const deployments = t.hooks.store.find(key)!.deployments; + expect(Object.values(deployments)).toEqual([expect.objectContaining({ state: "deploying", deploymentId: 7 })]); + } + // One doorbell wakes both bindings. + for (const id of stewards) expect(t.sends.filter((s) => s.threadId === id).at(-1)!.text).toMatch(/Deployment 7 \(success\) for acme\/bb-gate production/u); + }); + + it("behaves exactly as before for a project with no deployment target", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ 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"); + expect(t.hooks.store.find("ENG-12")!.deployments).toEqual({}); + expect(githubInterest(t).deployment).toEqual([]); + const before = t.sends.length; + await doorbell(t, "acme/bb-gate#7", deployment()); + expect(t.sends).toHaveLength(before); + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 4d4f1552..ec548db7 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -65,16 +65,19 @@ import { stewardsContract, type DependabotAlert, type DependabotSeverity, + type Deployment, type EntitySnapshot, type SessionWake, type Source, } from "./source-contract.js"; +import { allDeployed, applyDeployment, deploymentLines, deploymentReportSchema, recordMerged, reportDeployment, timeOut, timeoutsDue } from "./deploy.js"; import { ACTORS, MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store, type Worker } from "./store.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY } from "./sidebar-provider.js"; import { NEEDS_YOU_CHANGED } from "./channels.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; +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"; export const MULTI_REPO_PLUGIN_ID = "multi-repo"; @@ -852,6 +855,37 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return playbookFor(config, b.kind); } + /** + * Every deployment target a project's playbooks name, each once, by + * repo/environment. The repos are what the github plugin leases as + * `deployment_repo`; the environments are matched on a doorbell (BB-53). + */ + function deploymentTargets(config: ProjectConfig): DeploymentTarget[] { + const seen = new Set(); + const out: DeploymentTarget[] = []; + for (const playbook of Object.values(config.playbooks)) { + const target = playbook?.deployment; + if (target === undefined || target === null) continue; + const key = `${target.repo.toLowerCase()}\u0000${target.environment.toLowerCase()}`; + if (seen.has(key)) continue; + seen.add(key); + out.push(target); + } + return out; + } + + /** + * The earliest deadline among a binding's unsettled deployment watches, + * so the requeue wakes the steward at the playbook's timeout even if + * nothing else does. Null when nothing is waiting. + */ + function deploymentDeadline(deployments: Binding["deployments"]): number | null { + const deadlines = Object.values(deployments) + .filter((w) => (w.state === "merged" || w.state === "deploying") && w.deadlineAt !== null) + .map((w) => w.deadlineAt!); + return deadlines.length === 0 ? null : Math.min(...deadlines); + } + // ---- the sources --------------------------------------------------------------------- async function snapshot(source: Source, id: string): Promise { @@ -959,11 +993,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P async function sendInterest(): Promise { const projects = [...configs.values()].map((c) => c.value).filter((c): c is ProjectConfig => c !== null); const open = store.open(); - const sets: Record = { + const sets: Record = { linear: { units: [...new Set(projects.flatMap((p) => p.file.linear.teams))].sort(), entities: [...new Set(open.filter((b) => b.source === "linear").map((b) => b.entityId))].sort(), dependabot: [], + deployment: [], }, github: { units: [...new Set(projects.flatMap((p) => p.repos))].sort(), @@ -977,6 +1012,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // whose gh login cannot read alerts has each lease refused as // `forbidden`, which it skips; stewards check says so. dependabot: [...new Set(projects.flatMap((p) => (p.depsAlerts === null ? [] : depsTargets(p.file, p.repos).map((t) => t.repo))))].sort(), + // Every repo a playbook names as a deployment target. A login + // without `deployments:read` has each lease refused as `forbidden`, + // which it skips; stewards check says so. + deployment: [...new Set(projects.flatMap((p) => deploymentTargets(p).map((t) => t.repo)))].sort(), }, }; for (const source of ["linear", "github"] as const) { @@ -1632,10 +1671,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ), label: config.file.label, conflicts: conflictsOf(b, store.open(b.projectId)), + deployments: b.deployments, now: now(), }); if (!(await deliverWake(b, config, playbook, text))) return false; const cursor = newestCommentAt(observed); + const deployDeadline = deploymentDeadline(b.deployments); store.patch(b.id, { awaitingReport: true, wokeAt: now(), @@ -1643,8 +1684,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P commentCursor: cursor > b.commentCursor ? cursor : b.commentCursor, pending: [], archiveWhenIdle: false, - // A fallback until the report names its own. - requeueAt: now() + playbook.requeueDefaultMs, + // A fallback until the report names its own; never later than a + // deployment's timeout, so the no-deployment wake is not missed. + requeueAt: deployDeadline === null ? now() + playbook.requeueDefaultMs : Math.min(now() + playbook.requeueDefaultMs, deployDeadline), }); return true; } @@ -1699,6 +1741,29 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const observed: Observed = { entity, pulls: b.kind === "ticket" ? await linkedPulls(entity) : [] }; const prev = b.lastSnapshot; + // BB-53: a merged pull request whose playbook names a deployment target + // is recorded as awaiting one. The plugin never decides whether a + // deployment carries the merge; it records what it sees and wakes the + // steward with the playbook's rule. + const deployTarget = playbook.deployment; + const deploymentChanges: Change[] = []; + let deployments = b.deployments; + if (deployTarget !== null) { + const beforeDeploy = deployments; + deployments = recordMerged(deployments, observed, deployTarget, now()); + if (deployments !== beforeDeploy) { + const fresh = Object.keys(deployments).filter((k) => beforeDeploy[k] === undefined); + deploymentChanges.push({ text: `Awaiting deployment: ${fresh.join(", ")} via ${deployTarget.repo} ${deployTarget.environment}`, actionable: true }); + } + const late = timeoutsDue(deployments, now()); + if (late.length > 0) { + deployments = timeOut(deployments, late, now()); + deploymentChanges.push({ text: `No matching deployment for ${late.join(", ")} within ${formatDuration(deployTarget.timeout)}; check the run: https://github.com/${deployTarget.repo}/actions`, actionable: true }); + } + if (deployments !== b.deployments) b = store.patch(b.id, { deployments }); + } + const awaitingDeploy = deployTarget !== null && Object.values(deployments).some((w) => w.state === "merged" || w.state === "deploying"); + const life = lifecycle(b, playbook, entity, config.file.label, { labelRequired: b.playbook !== depsPrsPlaybookName(config.file) }); let reason: WakeReason | null = force; if (life.kind === "stay-ended") { @@ -1710,7 +1775,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P b = await reopen(b, life.why); reason = "reopen"; } - if (life.kind === "terminal" || life.kind === "detach") { + if ((life.kind === "terminal" || life.kind === "detach") && !(life.kind === "terminal" && awaitingDeploy)) { if (b.ending === null) { await beginEnding(b, config, playbook, life.kind, observed); return; @@ -1747,6 +1812,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const ownPulls = workerInFlight ? await ownPullKeys(b, workers, observed) : new Set(); const fresh = prev === null ? [] : diffObserved(prev, observed, { own: ownThreads(b), stewardThreadId: b.threadId, approved: ready.approval !== null, cursor: b.commentCursor, workerInFlight, ownPulls, stageOf: (state) => phaseOf(playbook, state)?.stage ?? null, userThread: isUserThread }); changes.push(...fresh); + changes.push(...deploymentChanges); // BB-35 step 2: a fresh unsigned comment by the owner that differs from // the recommendation on a decision that cited lessons is a correction, // counted once. Anyone else's words never count. Only from the second @@ -2629,6 +2695,38 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return b; } + /** + * A GitHub Deployment doorbell (BB-53). The entity id is + * "owner/repo#" and the deployment object carries the + * environment and state. Every open binding whose playbook names that repo + * and environment as a deployment target and is awaiting one hears it; the + * steward decides from the playbook's rule whether it carries the merge. + */ + async function onDeploymentDoorbell(id: string, deployment: Deployment): 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) { + const target = deploymentTargets(config).find((t) => t.repo.toLowerCase() === repo.toLowerCase() && t.environment.toLowerCase() === lc(deployment.environment)); + if (target === undefined) continue; + for (const b of store.open(config.projectId)) { + const playbook = bindingPlaybook(config, b); + const named = playbook?.deployment; + if (named === undefined || named === null || lc(named.repo) !== lc(target.repo) || lc(named.environment) !== lc(target.environment)) continue; + const watches = Object.values(b.deployments).filter((w) => lc(w.repo) === lc(target.repo) && lc(w.environment) === lc(target.environment) && w.state !== "deployed" && w.state !== "failed"); + if (watches.length === 0) continue; + const applied = applyDeployment(b.deployments, target, deployment, now()); + if (applied.changed.length === 0) continue; + store.patch(b.id, { deployments: applied.deployments }); + const state = deployment.state === "" ? "created" : deployment.state; + store.note(b.id, `Deployment ${deployment.id} (${state}) for ${repo} ${target.environment}${deployment.url === null ? "" : ` — ${deployment.url}`}; the playbook's rule: ${target.carries}`, false); + bb.log.info(`stewards: deployment ${deployment.id} (${state}) on ${repo} ${target.environment} concerns ${applied.changed.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); @@ -3797,8 +3895,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // ---- the RPC ------------------------------------------------------------------------------------- bb.rpc.register(rpcContract, { - async stewardsRing({ source, id }, { experimental_caller: caller }) { + async stewardsRing({ source, id, deployment }, { 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 (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))); + return { ok: true }; + } debounce(`ring:${source}:${lc(id)}`, () => serial(`ring:${source}:${lc(id)}`, () => onRing(source, id))); return { ok: true }; }, @@ -4495,6 +4598,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .max(600) .optional() .describe("Only after a terminal state (a wrap-up or follow-through turn): what remains to finish, such as a worker watching the deploy and verifying it. The binding stays open, its workers keep running, and you are woken as usual. Leave it out once the work is done, and the binding ends after this turn."), + deployment: deploymentReportSchema + .optional() + .describe("After a deployment doorbell (BB-53): whether the deployment carries this merge. Use the playbook's rule to decide: `deployed` when it carries it, `not-yet` when it does not, `failed` when it failed. Name the pull request with `key` when the binding watches more than one."), opsTickets: z .array( z.object({ @@ -4566,6 +4672,24 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ); } for (const t of opsTickets) store.recordTicket(b.projectId, t.fingerprint, t.ticket, t.did); + // BB-53: a deployment verdict the steward reached from the playbook's + // rule. `deployed` settles the watch; `not-yet` puts it back to + // awaiting; `failed` marks it failed. Once every watch is deployed + // the plugin notes it, so the next reconcile wakes the steward for + // the one closing comment. + let deployments = b.deployments; + let deploymentNote = ""; + if (input.deployment !== undefined) { + if (playbook?.deployment === null || playbook?.deployment === undefined) return toolError(new Error(`${b.entityKey}'s playbook names no deployment target, so there is no deployment to report.`)); + const result = reportDeployment(b.deployments, input.deployment, now()); + if (result.changed === null) return toolError(new Error(`No deployment is awaiting a verdict for ${b.entityKey}${input.deployment.key === undefined ? "" : ` (${input.deployment.key})`}. A deployment doorbell must arrive first.`)); + deployments = result.deployments; + deploymentNote = ` ${result.changed.key} is ${result.changed.state}.`; + if (allDeployed(deployments)) { + store.note(b.id, `Every pull request is merged and deployed (${playbook.deployment.repo} ${playbook.deployment.environment})`, false); + scheduleReconcile(b.id); + } + } // A Sentry issue with a ticket is leased by itself, so its next event rings even outside the project lease. if (opsTickets.length > 0 && parseOpsTargetKey(b.entityId)?.kind === "sentry-project") { sentryHooks.added("issue", ...opsTickets.map((t) => t.fingerprint)).catch((error: unknown) => bb.log.warn(`stewards: could not lease a Sentry issue right away: ${errorMessage(error)}`)); @@ -4599,10 +4723,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P status, statusAt: now(), ...(moved ? { advancedAt: now() } : {}), - requeueAt: now() + requeueMs, + requeueAt: (() => { + const at = now() + requeueMs; + const deadline = deploymentDeadline(deployments); + return deadline === null ? at : Math.min(at, deadline); + })(), awaitingReport: false, missedReports: 0, ready, + deployments, ...(input.touches === undefined ? {} : { touches: normalizeTouches(input.touches) }), ...(b.ending === "terminal" ? { followThrough: input.followThrough ?? null, followThroughUntil } : {}), }); @@ -4694,8 +4823,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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.${refusalNote}${escalated} The binding ends when this turn does: running workers are stopped and the thread is archived. End the turn now.`; - return `Reported.${refusalNote}${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.`; + if (b.followThrough === null) return `Reported.${refusalNote}${escalated}${deploymentNote} The binding ends when this turn does: running workers are stopped and the thread is archived. End the turn now.`; + return `Reported.${refusalNote}${escalated}${deploymentNote} 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.`; } const hidden = archiveWhenIdle && !needsUser(b) ? " Your thread is hidden when the turn ends, and comes back on that wake." : ""; const recorded = opsTickets.length === 0 ? "" : ` Recorded ${opsTickets.map((t) => `${t.ticket} (${t.did})`).join(", ")} against ${opsTickets.length === 1 ? "its fingerprint" : "their fingerprints"}.`; @@ -5495,6 +5624,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const deps = config.file.deps; const slaText = (v: number | "asap") => (v === "asap" ? "asap" : formatDuration(v)); lines.push(`deps: sla critical=${slaText(deps.sla.critical)} high=${slaText(deps.sla.high)} medium=${slaText(deps.sla.medium)} low=${slaText(deps.sla.low)}; batch medium=${formatDuration(deps.batch.medium)} low=${formatDuration(deps.batch.low)}; autoAdopt ${deps.autoAdopt.join(", ") || "(none)"}`); + const deployTargets = deploymentTargets(config); + if (deployTargets.length > 0) lines.push(`deployment: ${deployTargets.map((t) => `${t.repo} ${t.environment} (timeout ${formatDuration(t.timeout)})`).join(", ")}`); const depsRepos = depsTargets(config.file, config.repos); if (config.depsAlerts !== null && depsRepos.length > 0) { lines.push(`deps: watching ${depsRepos.length} repo${depsRepos.length === 1 ? "" : "s"} for alerts: ${depsRepos.map((t) => t.repo).join(", ")}`); @@ -5672,6 +5803,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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 line of deploymentLines(b.deployments)) lines.push(`Deployment ${line}`); for (const g of b.guidance) lines.push(`Guidance ${iso(g.at)}: ${g.text}`); for (const n of b.pending) lines.push(`Pending${n.quiet === true ? " (quiet)" : ""}: ${n.text}`); for (const x of detail.escalations) lines.push(`Escalation ${x.id} ${x.kind} (${x.status}, ${x.route}): ${x.question}${choicesNote(x.choices)}${x.resolution === null ? "" : ` → ${x.resolution}`}`); diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 144b9c2e..c8ba383b 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -164,6 +164,19 @@ Two tools are yours; everything else you do with the tools every thread has. theirs to act on too: the plugin held the words until the owner named that request. There is no untrusted form any more: words from anyone else are answered by the plugin, never by you. +- **Deployments (BB-53).** When the playbook names a `deployment` target, a + merged pull request is recorded as awaiting one, and a GitHub Deployment + doorbell for the target repo and environment wakes you with the deployment + (repo, environment, id, ref, sha, state, URL) and the playbook's `carries` + rule. Decide from that rule whether the deployment carries the merge and + report it with `steward_report { deployment: { state: "deployed" } }` when + it does, `"not-yet"` when it does not, or `"failed"` when it failed. Do not + start a worker to watch the deploy. A failure/error deployment, or no + matching deployment within the playbook's `timeout`, wakes you with the run + URL. Once every pull request is merged and deployed you are woken to post + one closing comment and move the ticket to its terminal state; report + without `followThrough` then. A playbook with no `deployment` has none of + this. - **Ending.** When the entity is detached you get one last turn, with your workers already stopped: say the work is done here. When it reaches a terminal state (Done, merged) you get a wrap-up turn with your workers diff --git a/plugins/stewards/source-contract.ts b/plugins/stewards/source-contract.ts index 25c59e04..3714bbb7 100644 --- a/plugins/stewards/source-contract.ts +++ b/plugins/stewards/source-contract.ts @@ -30,6 +30,27 @@ export type Source = z.infer; */ export const SOURCE_PLUGIN_IDS: Record = { linear: "linear", github: "github-watcher" }; +/** + * A GitHub Deployment, as bb-gate-hooks forwards it on a `deployment` + * doorbell (bb-gate/docs/hooks.md). The doorbell's entity id is + * `owner/repo#` and its unit is the repository; this object is the one + * piece of a doorbell that is not in the entity name, because a deployment's + * ref and state are what a subscriber decides on. `state` is empty on a bare + * `deployment` event and one of queued, in_progress, success, failure, error, + * inactive or pending on a `deployment_status` event. + */ +export const deploymentSchema = z + .object({ + id: z.number().int().nonnegative(), + environment: z.string().default(""), + ref: z.string().default(""), + sha: z.string().default(""), + state: z.string().default(""), + url: z.string().nullable().default(null), + }) + .loose(); +export type Deployment = 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; @@ -249,12 +270,19 @@ export const sourceContract = { * wants. It is separate from `units` because a repository lease does not * receive alert doorbells (bb-gate/docs/hooks.md): the github plugin leases * each as a `dependabot_repo`. Linear ignores it. + * + * `deployment` names repositories whose GitHub Deployment doorbells + * 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. */ sourceSetInterest: { input: z.object({ units: z.array(z.string().min(1).max(200)).max(200), entities: z.array(z.string().min(1).max(300)).max(2000), dependabot: z.array(z.string().min(1).max(200)).max(200).default([]), + deployment: z.array(z.string().min(1).max(200)).max(200).default([]), }), output: z.object({ ok: z.boolean() }), }, @@ -324,7 +352,12 @@ export type SessionWake = z.infer; export const stewardsContract = { /** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */ stewardsRing: { - input: z.object({ source: sourceSchema, id: z.string().min(1).max(300) }), + /** + * 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. + */ + input: z.object({ source: sourceSchema, id: z.string().min(1).max(300), deployment: deploymentSchema.optional() }), output: z.object({ ok: z.boolean() }), }, /** diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 1f3f5517..648de807 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -11,6 +11,7 @@ import { z } from "zod"; import { entitySnapshotSchema, type Source } from "./source-contract.js"; import type { BindingKind, EscalationKind, Stage } from "./config.js"; import { depsLookSchema, type DepsLook } from "./deps.js"; +import { deploymentsSchema, type Deployments } from "./deploy.js"; import { opsLookSchema, type FingerprintRow, type OpsLook } from "./ops.js"; import { sentryLookSchema, type SentryLook } from "./sentry.js"; @@ -350,7 +351,12 @@ export const DECLINED_PR_MIGRATIONS = [ `ALTER TABLE bindings ADD COLUMN declined_pr_marker TEXT`, ]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS]; +// BB-53: the per-pull-request deployment state a binding keeps between a merge +// and the deployment that confirms it is live. Additive and defaulted: a +// binding with no deployment target keeps an empty map and behaves as before. +export const DEPLOYMENT_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN deployments TEXT NOT NULL DEFAULT '{}'`]; + +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -481,6 +487,8 @@ export type Binding = { depsLook: DepsLook | null; /** A Sentry project binding's last look; null for every other kind. */ sentryLook: SentryLook | null; + /** Per-pull-request deployment state, keyed by the pull request's key (BB-53). Empty with no deployment target. */ + deployments: Deployments; createdAt: number; endedAt: number | null; endReason: string | null; @@ -540,6 +548,7 @@ function rowToBinding(r: BindingRow): Binding { opsLook: json(opsLookSchema.nullable(), str("ops_look"), null), depsLook: json(depsLookSchema.nullable(), str("deps_look"), null), sentryLook: json(sentryLookSchema.nullable(), str("sentry_look"), null), + deployments: json(deploymentsSchema, str("deployments"), {}), createdAt: Number(r.created_at), endedAt: num("ended_at"), endReason: str("end_reason"), @@ -589,6 +598,7 @@ const COLUMNS = { opsLook: "ops_look", depsLook: "deps_look", sentryLook: "sentry_look", + deployments: "deployments", endedAt: "ended_at", endReason: "end_reason", } as const satisfies Partial>; diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 32dad04a..1e7ff87f 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -6,6 +6,7 @@ // it ever saw can act correctly from one wake alone, which is what lets its // transcript stop being the source of truth. import { formatDuration, phaseInstructions, type BigDecision, type Playbook } from "./config.js"; +import { anyPending, type Deployments, type DeploymentWatch } from "./deploy.js"; import { localParts } from "./nightly.js"; import { FINDING_CLASSES, type FindingClass, type OpsFinding, type OpsLook } from "./ops.js"; import type { DepsFinding, DepsLook } from "./deps.js"; @@ -156,6 +157,8 @@ const LIFECYCLE_INSTRUCTIONS: Partial> = { */ function lifecycleInstructions(input: WakeInput): string | undefined { const { binding: b, playbook, observed } = input; + const deployment = deploymentInstructions(input); + if (deployment !== undefined) return deployment; if (input.reason === "terminal") { return ( `The entity has reached a terminal state (${observed.entity.state}). This is your wrap-up turn. Running workers have not been stopped. ` + @@ -174,6 +177,33 @@ function lifecycleInstructions(input: WakeInput): string | undefined { return LIFECYCLE_INSTRUCTIONS[input.reason]; } +/** + * What to do about a deployment, when the playbook names a target and a merge + * is waiting on one. The plugin does not decide whether a deployment carries a + * merge: it hands the steward the deployment and the playbook's rule, and the + * steward reports the verdict (BB-53). + */ +function deploymentInstructions(input: WakeInput): string | undefined { + const target = input.playbook.deployment; + const watches = Object.values(input.deployments ?? {}); + if (target === null || watches.length === 0) return undefined; + const settled = watches.every((w) => w.state === "deployed"); + if (settled) { + return ( + `Every pull request is merged and deployed (${target.repo} ${target.environment}). This is the last turn of the work: post one closing comment saying it is live and move the ticket to its terminal state, then end with steward_report without followThrough. ` + + `If a playbook says otherwise, keep it open with followThrough as usual.` + ); + } + const pending = watches.filter((w) => w.state === "merged" || w.state === "deploying"); + if (pending.length === 0) return undefined; + const names = pending.map((w) => w.key).join(", "); + return ( + `A merge is awaiting deployment (${names}) through ${target.repo} ${target.environment}. Decide from the playbook's rule whether the deployment carries the merge — ${JSON.stringify(target.carries)} — and report it with ` + + `steward_report { deployment: { state: "deployed" } } when it does, "not-yet" when it does not, or "failed" when it failed. ` + + `Do not start a worker to watch the deploy, and do not move the ticket on until every pull request is deployed.` + ); +} + export type ChildView = { binding: Binding; openEscalations: Escalation[] }; /** A worker's final message that asked something, to answer before anything else. */ @@ -205,6 +235,8 @@ export type WakeInput = { projectApprovedShas?: ReadonlySet; /** The project's adoption label. */ label: string; + /** Per-pull-request deployment state (BB-53); empty when the playbook names no deployment target. */ + deployments?: Deployments; /** Open bindings already at work on what this one touches. */ conflicts?: Conflict[]; now: number; @@ -254,6 +286,29 @@ function entityLines(e: EntitySnapshot, cursor: string, own: ReadonlySet return lines; } +const DEPLOY_STATE_LABEL: Record = { merged: "merged, awaiting deployment", deploying: "deploying", deployed: "deployed", failed: "failed" }; + +/** The deployment block of a wake: the playbook's target and rule, then each watched pull request. */ +function deploymentLines(input: WakeInput): string[] { + const target = input.playbook.deployment; + const watches = Object.values(input.deployments ?? {}).sort((a, b) => a.key.localeCompare(b.key)); + if (target === null || watches.length === 0) return []; + const out = ["", `### Deployment (${target.repo} ${target.environment})`, ""]; + out.push(`- Rule (from the playbook): ${target.carries}`); + out.push(`- No matching deployment within ${formatDuration(target.timeout)} wakes you with the run URL.`); + for (const w of watches) { + const facts = [ + w.mergeSha === null ? null : `merge ${w.mergeSha.slice(0, 7)}`, + w.deploymentId === null ? null : `deployment ${w.deploymentId}`, + w.ref === null ? null : `ref ${w.ref}`, + w.sha === null ? null : `sha ${w.sha.slice(0, 7)}`, + w.url === null ? null : w.url, + ].filter((x): x is string => x !== null); + out.push(`- ${w.key}: ${DEPLOY_STATE_LABEL[w.state]}${facts.length === 0 ? "" : ` (${facts.join(", ")})`}${w.note === null ? "" : ` — ${w.note}`}`); + } + return out; +} + function gateLines(input: Pick): string[] { const { gate, binding, playbook } = input; if (gate.none) return ["No ready gate in this playbook."]; @@ -360,6 +415,9 @@ export function formatWake(input: WakeInput): string { out.push(`- Priority: ${binding.priority ?? "normal"}`); out.push(holdLine(binding, "take no new actions and start no workers until it is lifted.")); out.push(...schedulingLines(binding, input.conflicts ?? [], input.escalations)); + // The deployment block goes in the head, not the snapshot: a clipped wake + // must not lose the deployment's ref and sha, which the rule decides on. + out.push(...deploymentLines(input)); const head = out.splice(0); out.push("", "## 4. Snapshot", ""); From 2756abf6d068daa8d464f2f88605bb6a55ebcedf Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sun, 25 Oct 2026 18:56:05 +0000 Subject: [PATCH 2/2] stewards, github-watcher: address review round 1 (BB-53) - github-watcher: record a refused deployment_repo lease so the watches view reports it, and assert the unleased entry. - stewards: a terminal binding already following through keeps falling through to the wake while a deployment is outstanding, so the deployment is not swallowed; test the Done-then-merged case. - deploy: keep a fresh deadline while deploying and on a not-yet verdict, so a deployment with no final status still wakes within the playbook's timeout. - wake: append the deployment instruction to the lifecycle instruction rather than replacing it, so adopted/reopened turns keep their own text. - docs: the wake's merge sha is the pull request head, so decide ancestry from the deployment's ref/sha. --- plugins/github-watcher/server.test.ts | 2 ++ plugins/github-watcher/server.ts | 10 +++++++++- plugins/stewards/README.md | 5 ++++- plugins/stewards/deploy.test.ts | 23 ++++++++++++----------- plugins/stewards/deploy.ts | 13 +++++++++---- plugins/stewards/server.test.ts | 22 ++++++++++++++++++++++ plugins/stewards/server.ts | 8 ++++++-- plugins/stewards/skills/stewards/SKILL.md | 5 ++++- plugins/stewards/wake.ts | 17 ++++++++++++++--- 9 files changed, 82 insertions(+), 23 deletions(-) diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index e5b52c1c..7e3cf006 100644 --- a/plugins/github-watcher/server.test.ts +++ b/plugins/github-watcher/server.test.ts @@ -658,6 +658,8 @@ describe("stewards' source contract", () => { 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); + 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" }]); service.controller.abort(); await service.done; }); diff --git a/plugins/github-watcher/server.ts b/plugins/github-watcher/server.ts index d5387873..dacc2b55 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -335,7 +335,15 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => async function onRejected(rejected: Rejection[]): Promise { for (const r of rejected) { const watching = r.kind === "issue" ? watches.forKey(r.id) : []; - if (r.kind === "repo" ? interestRepos.has(r.id.toLowerCase()) : r.kind === "dependabot_repo" ? interestDependabot.has(r.id.toLowerCase()) : interestEntities.has(r.id.toLowerCase())) refusals.add(`${r.kind} ${r.id.toLowerCase()}`, r.reason); + const leased = + r.kind === "repo" + ? interestRepos.has(r.id.toLowerCase()) + : r.kind === "dependabot_repo" + ? interestDependabot.has(r.id.toLowerCase()) + : r.kind === "deployment_repo" + ? interestDeployment.has(r.id.toLowerCase()) + : interestEntities.has(r.id.toLowerCase()); + if (leased) refusals.add(`${r.kind} ${r.id.toLowerCase()}`, r.reason); if (r.kind === "dependabot_repo") { // A login that cannot read alerts gets `forbidden` here. That is a // skip, not an error: the server keeps running without Dependabot diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 340df45d..5e1fe526 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -452,7 +452,10 @@ default). With it, a merged pull request is recorded as awaiting deployment, the github plugin leases the repo as a `deployment_repo` and a `deployment` doorbell for the repo and environment wakes the binding, and the steward reports the verdict with `steward_report { deployment: { state } }`; a -failure/error deployment or a timeout wakes it with the run URL. With no +failure/error deployment or a timeout wakes it with the run URL. The wake's +`merge ` is the pull request's head, and a squash or rebase merge +rewrites it, so decide ancestry from the deployment's own `ref`/`sha` and the +repository rather than the head sha alone. With no `deployment`, the playbook behaves exactly as before. The wake numbers the ready checklist, and `steward_report` takes each item by diff --git a/plugins/stewards/deploy.test.ts b/plugins/stewards/deploy.test.ts index 9d4b78fb..4655a10a 100644 --- a/plugins/stewards/deploy.test.ts +++ b/plugins/stewards/deploy.test.ts @@ -56,7 +56,7 @@ describe("applying a deployment doorbell", () => { expect(matchesTarget(target, "acme/other", "production")).toBe(false); const applied = applyDeployment(deployments, target, deployment(), NOW + 60_000); expect(applied.changed).toEqual(["acme/web#7"]); - expect(applied.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentId: 7, ref: "main", sha: "bbbbbbb2", url: "https://github.com/acme/bb-gate/actions/runs/9", deadlineAt: null }); + expect(applied.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentId: 7, ref: "main", sha: "bbbbbbb2", url: "https://github.com/acme/bb-gate/actions/runs/9", deadlineAt: NOW + 60_000 + target.timeout }); }); it("marks a failure or error deployment failed, with the deployment's URL", () => { @@ -86,9 +86,10 @@ describe("the no-deployment timeout", () => { expect(timeoutsDue(failed, NOW + target.timeout + 1000)).toEqual([]); }); - it("does not time out a watch that already has a deployment", () => { + it("keeps a deadline while deploying, so a deployment with no final status still times out", () => { const applied = applyDeployment(recordMerged({}, observed(), target, NOW), target, deployment(), NOW); - expect(timeoutsDue(applied.deployments, NOW + target.timeout * 10)).toEqual([]); + expect(timeoutsDue(applied.deployments, NOW + target.timeout - 1)).toEqual([]); + expect(timeoutsDue(applied.deployments, NOW + target.timeout)).toEqual(["acme/web#7"]); }); }); @@ -96,30 +97,30 @@ describe("the steward's verdict", () => { const deploying = () => applyDeployment(recordMerged({}, observed(), target, NOW), target, deployment(), NOW).deployments; it("settles a watch on deployed, and reports all deployed", () => { - const result = reportDeployment(deploying(), { state: "deployed" }, NOW + 1000); + const result = reportDeployment(deploying(), { state: "deployed" }, NOW + 1000, target.timeout); expect(result.changed).toMatchObject({ key: "acme/web#7", state: "deployed", deadlineAt: null }); expect(allDeployed(result.deployments)).toBe(true); expect(allDeployed({})).toBe(false); }); - it("puts a deployment that does not carry the merge back to awaiting", () => { - const result = reportDeployment(deploying(), { state: "not-yet", note: "ref does not pin the merge" }, NOW + 1000); - expect(result.changed).toMatchObject({ state: "merged", note: "ref does not pin the merge" }); + it("puts a deployment that does not carry the merge back to awaiting, with a fresh deadline", () => { + const result = reportDeployment(deploying(), { state: "not-yet", note: "ref does not pin the merge" }, NOW + 1000, target.timeout); + expect(result.changed).toMatchObject({ state: "merged", note: "ref does not pin the merge", deadlineAt: NOW + 1000 + target.timeout }); expect(allDeployed(result.deployments)).toBe(false); }); it("marks a failed deployment failed", () => { - const result = reportDeployment(deploying(), { state: "failed", note: "run 9 red" }, NOW + 1000); + const result = reportDeployment(deploying(), { state: "failed", note: "run 9 red" }, NOW + 1000, target.timeout); expect(result.changed).toMatchObject({ state: "failed", note: "run 9 red" }); }); it("picks the watch a report names, by key or deployment id", () => { const two = recordMerged(recordMerged({}, observed(), target, NOW), observed({ entity: pull({ key: "acme/web#8" }, { merged: true }) }), target, NOW); - expect(reportDeployment(two, { state: "deployed", key: "ACME/WEB#8" }, NOW).changed?.key).toBe("acme/web#8"); + expect(reportDeployment(two, { state: "deployed", key: "ACME/WEB#8" }, NOW, target.timeout).changed?.key).toBe("acme/web#8"); const withDeployment = applyDeployment(two, target, deployment(), NOW).deployments; - expect(reportDeployment(withDeployment, { state: "deployed", deploymentId: 7 }, NOW).changed?.key).toBe("acme/web#7"); + expect(reportDeployment(withDeployment, { state: "deployed", deploymentId: 7 }, NOW, target.timeout).changed?.key).toBe("acme/web#7"); // No key and more than one unsettled watch: nothing is picked. - expect(reportDeployment(two, { state: "deployed" }, NOW).changed).toBeNull(); + expect(reportDeployment(two, { state: "deployed" }, NOW, target.timeout).changed).toBeNull(); }); }); diff --git a/plugins/stewards/deploy.ts b/plugins/stewards/deploy.ts index 87729647..2a9c8eeb 100644 --- a/plugins/stewards/deploy.ts +++ b/plugins/stewards/deploy.ts @@ -87,7 +87,7 @@ export const matchesTarget = (target: Pick, deployment: Deployment, now: number): { deployments: Deployments; changed: string[] } { +export function applyDeployment(deployments: Deployments, target: Pick, deployment: Deployment, now: number): { deployments: Deployments; changed: string[] } { const next = { ...deployments }; const changed: string[] = []; const failed = deployment.state === "failure" || deployment.state === "error"; @@ -106,7 +106,9 @@ export function applyDeployment(deployments: Deployments, target: Pick { await doorbell(t, "acme/bb-gate#7", deployment()); expect(t.sends).toHaveLength(before); }); + + it("holds a following-through binding open and wakes it when its pull request merges and a deployment is outstanding", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = deploymentPlaybook(); + t.entities.set("uuid-12", issue({ 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" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + // The ticket reaches Done while the pull request is still open: the + // wrap-up keeps the binding open to watch the deploy. + t.entities.set("uuid-12", issue({ state: "Done", stateType: "completed", linkedPulls: [{ url: "https://github.com/acme/web/pull/7", key: "acme/web#7" }] })); + await t.ring("linear", "uuid-12"); + await t.tool("steward_report", { phase: "Done", summary: "Merged, watching the deploy.", nextAction: "Watch the deploy", actor: "steward", followThrough: "watch the deploy" }, steward); + expect(t.hooks.store.find("ENG-12")!.ending).toBe("terminal"); + expect(t.hooks.store.find("ENG-12")!.followThrough).toBe("watch the deploy"); + // The pull request merges: the deployment is recorded and the + // following-through steward is woken, not swallowed by the ending. + t.entities.set("acme/web#7", pull({ key: "acme/web#7" }, { merged: true })); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "merged" }); + expect(t.sends.filter((s) => s.threadId === steward).at(-1)!.text).toMatch(/A merge is awaiting deployment/u); + }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index ec548db7..e3210064 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -1775,7 +1775,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P b = await reopen(b, life.why); reason = "reopen"; } - if ((life.kind === "terminal" || life.kind === "detach") && !(life.kind === "terminal" && awaitingDeploy)) { + // A terminal binding holds open while a deployment is outstanding, but + // only one that has not begun ending: one already following through (a + // ticket Done with its pull request still open) must keep falling + // through to the wake, so the deployment is not swallowed. + if ((life.kind === "terminal" || life.kind === "detach") && !(life.kind === "terminal" && awaitingDeploy && b.ending === null)) { if (b.ending === null) { await beginEnding(b, config, playbook, life.kind, observed); return; @@ -4681,7 +4685,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P let deploymentNote = ""; if (input.deployment !== undefined) { if (playbook?.deployment === null || playbook?.deployment === undefined) return toolError(new Error(`${b.entityKey}'s playbook names no deployment target, so there is no deployment to report.`)); - const result = reportDeployment(b.deployments, input.deployment, now()); + const result = reportDeployment(b.deployments, input.deployment, now(), playbook.deployment.timeout); if (result.changed === null) return toolError(new Error(`No deployment is awaiting a verdict for ${b.entityKey}${input.deployment.key === undefined ? "" : ` (${input.deployment.key})`}. A deployment doorbell must arrive first.`)); deployments = result.deployments; deploymentNote = ` ${result.changed.key} is ${result.changed.state}.`; diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index c8ba383b..db8f0e69 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -175,7 +175,10 @@ Two tools are yours; everything else you do with the tools every thread has. matching deployment within the playbook's `timeout`, wakes you with the run URL. Once every pull request is merged and deployed you are woken to post one closing comment and move the ticket to its terminal state; report - without `followThrough` then. A playbook with no `deployment` has none of + without `followThrough` then. The wake's `merge ` is the pull + request's head, and a squash or rebase merge rewrites it, so decide + ancestry from the deployment's own `ref`/`sha` and the repository rather + than the head sha alone. A playbook with no `deployment` has none of this. - **Ending.** When the entity is detached you get one last turn, with your workers already stopped: say the work is done here. When it reaches a diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 1e7ff87f..9d3df471 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -155,10 +155,8 @@ const LIFECYCLE_INSTRUCTIONS: Partial> = { * is done: merged is not deployed, and Done set by an automation is not * verified. Running workers are left alone until then. */ -function lifecycleInstructions(input: WakeInput): string | undefined { +function baseLifecycleInstruction(input: WakeInput): string | undefined { const { binding: b, playbook, observed } = input; - const deployment = deploymentInstructions(input); - if (deployment !== undefined) return deployment; if (input.reason === "terminal") { return ( `The entity has reached a terminal state (${observed.entity.state}). This is your wrap-up turn. Running workers have not been stopped. ` + @@ -177,6 +175,19 @@ function lifecycleInstructions(input: WakeInput): string | undefined { return LIFECYCLE_INSTRUCTIONS[input.reason]; } +/** + * The lifecycle instruction for this wake, with the deployment text appended + * rather than replacing it: an adopted or reopened binding keeps its own + * instruction and still hears about the deployment it awaits. + */ +function lifecycleInstructions(input: WakeInput): string | undefined { + const base = baseLifecycleInstruction(input); + const deployment = deploymentInstructions(input); + if (deployment === undefined) return base; + if (base === undefined) return deployment; + return `${base}\n\n${deployment}`; +} + /** * What to do about a deployment, when the playbook names a target and a merge * is waiting on one. The plugin does not decide whether a deployment carries a