diff --git a/plugins/github-watcher/github.test.ts b/plugins/github-watcher/github.test.ts index 5e0fc568..fc8b32c1 100644 --- a/plugins/github-watcher/github.test.ts +++ b/plugins/github-watcher/github.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { parseDependabotAlerts, parseOpenPulls, parseRef, parseRefKey, parseRepo, parseRepoCheck, parseSnapshot, parseTarget, refKey, TARGET_QUERY } from "./github.js"; +import { parseDependabotAlerts, parseDeploymentStatus, parseDeployments, parseOpenPulls, parseRef, parseRefKey, parseRepo, parseRepoCheck, parseSnapshot, parseTarget, refKey, TARGET_QUERY } from "./github.js"; import { entitySnapshotSchema, SNAPSHOT_COMMENT_CHARS, SNAPSHOT_COMMENTS_MAX, SNAPSHOT_DESCRIPTION_CHARS } from "./source-contract.js"; describe("refs", () => { @@ -308,3 +308,28 @@ describe("Dependabot alerts", () => { expect(() => parseDependabotAlerts({ message: "Not Found" }, "Acme/Widgets")).toThrow(/Dependabot alert list/u); }); }); + +describe("deployments", () => { + const node = (over: Record = {}) => ({ id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", url: "https://github.com/Acme/Widgets/actions/runs/9", ...over }); + + it("reads a page newest first, tolerating a bare deployment", () => { + expect(parseDeployments([node({ id: 6 }), node({ id: 7 })])).toEqual([ + { id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", url: "https://github.com/Acme/Widgets/actions/runs/9" }, + { id: 6, environment: "production", ref: "main", sha: "bbbbbbb2", url: "https://github.com/Acme/Widgets/actions/runs/9" }, + ]); + expect(parseDeployments([node({ environment: null, ref: null, sha: null, url: null })])[0]).toEqual({ id: 7, environment: "", ref: "", sha: "", url: null }); + }); + + it("throws on anything that is not a deployment list", () => { + expect(() => parseDeployments({ message: "Not Found" })).toThrow(/deployment list/u); + }); + + it("reads the newest status's state and the best link, with the doorbell's fallbacks", () => { + expect(parseDeploymentStatus([{ state: "success", log_url: "https://github.com/Acme/Widgets/actions/runs/9" }, { state: "in_progress" }])).toEqual({ state: "success", url: "https://github.com/Acme/Widgets/actions/runs/9" }); + expect(parseDeploymentStatus([{ state: "success", environment_url: "https://preview.example.com/7" }])).toEqual({ state: "success", url: "https://preview.example.com/7" }); + expect(parseDeploymentStatus([{ state: "failure", target_url: "https://target.example.com/7" }])).toEqual({ state: "failure", url: "https://target.example.com/7" }); + expect(parseDeploymentStatus([{ state: "failure", url: "https://api.github.com/repos/Acme/Widgets/deployments/7/statuses/9" }])).toEqual({ state: "failure", url: "https://api.github.com/repos/Acme/Widgets/deployments/7/statuses/9" }); + expect(parseDeploymentStatus([])).toEqual({ state: "", url: null }); + expect(() => parseDeploymentStatus({ message: "Not Found" })).toThrow(/deployment status list/u); + }); +}); diff --git a/plugins/github-watcher/github.ts b/plugins/github-watcher/github.ts index b636eacf..4ff923c2 100644 --- a/plugins/github-watcher/github.ts +++ b/plugins/github-watcher/github.ts @@ -542,3 +542,59 @@ export function parseDependabotAlerts(payload: unknown, repo: string): Dependabo updatedAt: a.updated_at ?? null, })); } + +// ---- deployments, for stewards ---------------------------------------------------- + +/** + * The REST path for a repository's recent deployments, newest first. The + * environment is filtered client-side because GitHub's `environment` query is + * an exact match; a page of 100 is assumed wide enough that the newest + * deployment for any one environment sits in it, which holds while a repo + * does not interleave a busier second environment. + */ +export const deploymentsPath = (repo: string, perPage = 100): string => `/repos/${repo}/deployments?per_page=${perPage}`; + +/** The REST path for one deployment's statuses, newest first. */ +export const deploymentStatusesPath = (repo: string, id: number, perPage = 1): string => `/repos/${repo}/deployments/${id}/statuses?per_page=${perPage}`; + +const deploymentNode = z.object({ + id: z.number(), + environment: z.string().nullish(), + ref: z.string().nullish(), + sha: z.string().nullish(), + url: z.string().nullish(), +}); + +/** + * The deployments GitHub returned, newest first. The list has no `state`; + * the latest status of each carries it, read separately. + */ +export function parseDeployments(payload: unknown): Array<{ id: number; environment: string; ref: string; sha: string; url: string | null }> { + const parsed = z.array(deploymentNode).safeParse(payload); + if (!parsed.success) throw new Error("GitHub answered with something that is not a deployment list"); + return parsed.data.map((d) => ({ id: d.id, environment: d.environment ?? "", ref: d.ref ?? "", sha: d.sha ?? "", url: d.url ?? null })).sort((a, b) => b.id - a.id); +} + +const deploymentStatusNode = z.object({ + state: z.string(), + url: z.string().nullish(), + log_url: z.string().nullish(), + environment_url: z.string().nullish(), + target_url: z.string().nullish(), +}); + +/** + * The newest deployment status's state and the best link a person can open, + * exactly as bb-gate-hooks builds a `deployment` doorbell's `url`: the + * status's `log_url`, then `environment_url`, then `target_url`, then the + * status's own API URL; null when it set none (the caller then falls back to + * the deployment's API URL). "" state when no status has been reported. + */ +export function parseDeploymentStatus(payload: unknown): { state: string; url: string | null } { + const parsed = z.array(deploymentStatusNode).safeParse(payload); + if (!parsed.success) throw new Error("GitHub answered with something that is not a deployment status list"); + const status = parsed.data[0]; + if (status === undefined) return { state: "", url: null }; + const url = [status.log_url, status.environment_url, status.target_url, status.url].find((u): u is string => typeof u === "string" && u !== "") ?? null; + return { state: status.state, url }; +} diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index 7e3cf006..5f9b9154 100644 --- a/plugins/github-watcher/server.test.ts +++ b/plugins/github-watcher/server.test.ts @@ -38,11 +38,22 @@ const comment = (body: string, createdAt: string, who = "bob") => ({ author: { l // A GitHub whose GraphQL endpoint a test scripts: one repository with one // pull request, whose bb-managed label validates. function fakeGitHub() { - const state = { node: pullNode() as Record | null, fail: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array>, dependabotAlerts: [] as unknown[], dependabotPage2: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden" }; + const state = { node: pullNode() as Record | null, fail: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array>, dependabotAlerts: [] as unknown[], dependabotPage2: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden", deployments: [] as unknown[], deploymentStatuses: {} as Record }; const calls: Array<{ token: string; variables: Record }> = []; const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit) => { const token = ((init?.headers as Record).authorization ?? "").replace(/^Bearer /u, ""); const u = String(url); + const deployments = /\/repos\/([^/]+)\/([^/]+)\/deployments(?:\?|$)/u.exec(u); + if (deployments !== null) { + if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); + if (`${deployments[1]}/${deployments[2]}`.toLowerCase() !== "acme/widgets") return Response.json({ message: "Not Found" }, { status: 404 }); + return Response.json(state.deployments); + } + const statuses = /\/repos\/([^/]+)\/([^/]+)\/deployments\/(\d+)\/statuses(?:\?|$)/u.exec(u); + if (statuses !== null) { + if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); + return Response.json(state.deploymentStatuses[Number(statuses[3])] ?? []); + } const dependabot = /\/repos\/([^/]+)\/([^/]+)\/dependabot\/alerts(?:\?|$)/u.exec(u); if (dependabot !== null) { if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); @@ -564,6 +575,35 @@ describe("stewards' source contract", () => { expect(out.errors).toEqual([]); }); + it("reads a repository's deployments for one environment, newest first, each with its latest status and a person's link (BB-59)", async () => { + const w = await setup(); + // GitHub's deployment object carries its own API URL; the link a person + // opens is on the status (`log_url`), exactly as bb-gate-hooks builds a + // doorbell. + w.github.state.deployments = [ + { id: 6, environment: "production", ref: "main", sha: "aaaaaaa1", url: "https://api.github.com/repos/Acme/Widgets/deployments/6" }, + { id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", url: "https://api.github.com/repos/Acme/Widgets/deployments/7" }, + ]; + w.github.state.deploymentStatuses = { + 7: [{ state: "success", url: "https://api.github.com/repos/Acme/Widgets/deployments/7/statuses/9", log_url: "https://github.com/Acme/Widgets/actions/runs/9" }], + 6: [{ state: "failure", environment_url: "https://preview.example.com/6" }], + }; + expect(await w.harness.callRpc("sourceDeployments", { repo: "Acme/Widgets", environment: "production", limit: 10 }, STEWARDS)).toEqual({ + deployments: [ + { id: 7, environment: "production", ref: "main", sha: "bbbbbbb2", state: "success", url: "https://github.com/Acme/Widgets/actions/runs/9" }, + { id: 6, environment: "production", ref: "main", sha: "aaaaaaa1", state: "failure", url: "https://preview.example.com/6" }, + ], + error: null, + }); + // The environment filter is case-insensitive, as the doorbell path is, and + // a limit keeps the newest. + const limited = (await w.harness.callRpc("sourceDeployments", { repo: "acme/widgets", environment: "Production", limit: 1 }, STEWARDS)) as { deployments: Array<{ id: number; state: string }> }; + expect(limited.deployments).toEqual([expect.objectContaining({ id: 7, state: "success" })]); + expect(await w.harness.callRpc("sourceDeployments", { repo: "Acme/Widgets", environment: "staging", limit: 10 }, STEWARDS)).toMatchObject({ deployments: [], error: null }); + expect(await w.harness.callRpc("sourceDeployments", { repo: "acme/gone", environment: "production", limit: 10 }, STEWARDS)).toMatchObject({ deployments: [], error: "acme/gone: GitHub answered HTTP 404: Not Found" }); + expect(await w.harness.callRpc("sourceDeployments", { repo: "widgets", environment: "production", limit: 10 }, STEWARDS)).toMatchObject({ deployments: [], error: "widgets: not owner/repo" }); + }); + describe("interest", () => { beforeEach(() => vi.useFakeTimers()); afterEach(() => vi.useRealTimers()); diff --git a/plugins/github-watcher/server.ts b/plugins/github-watcher/server.ts index dacc2b55..83d68252 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -29,9 +29,13 @@ import { TARGET_QUERY, VIEWER_QUERY, dependabotAlertsPath, + deploymentStatusesPath, + deploymentsPath, graphql, kindName, parseDependabotAlerts, + parseDeploymentStatus, + parseDeployments, parseOpenPulls, parseRef, parseRefKey, @@ -589,6 +593,42 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => return { viewer, alerts, errors }; }, + // A repository's recent deployments, newest first, read with the token + // through the REST API (GraphQL does not expose deployments) and + // filtered to the requested environment here: GitHub's `environment` + // query is an exact match, while the playbook's environment and the + // doorbell path match ignoring case. Each deployment's latest status is + // its `state` and its `url`, as a `deployment` doorbell builds them; a + // repository the token cannot read is named in `error` rather than + // failing the call. Stewards uses this to confirm a merge carried by a + // deployment that already exists, not only by a doorbell (BB-59). + async sourceDeployments({ repo, environment, limit }) { + const parsed = parseRepo(repo); + if (parsed === null) return { deployments: [], error: `${repo}: not owner/repo` }; + const name = `${parsed.owner}/${parsed.name}`; + try { + const page = await restPage(deploymentsPath(name), checkSignal()); + const nodes = parseDeployments(page.body) + .filter((d) => d.environment.toLowerCase() === environment.toLowerCase()) + .slice(0, limit); + const deployments: Deployment[] = []; + for (const node of nodes) { + const status = parseDeploymentStatus((await restPage(deploymentStatusesPath(name, node.id), checkSignal())).body); + deployments.push({ + id: node.id, + environment: node.environment === "" ? environment : node.environment, + ref: node.ref, + sha: node.sha, + state: status.state, + url: status.url ?? node.url, + }); + } + return { deployments, error: null }; + } catch (error) { + return { deployments: [], error: `${repo}: ${errorMessage(error)}` }; + } + }, + // 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, deployment }, { experimental_caller: caller }) { diff --git a/plugins/github-watcher/source-contract.ts b/plugins/github-watcher/source-contract.ts index 3714bbb7..d722a573 100644 --- a/plugins/github-watcher/source-contract.ts +++ b/plugins/github-watcher/source-contract.ts @@ -304,6 +304,26 @@ export const sourceContract = { errors: z.array(z.string()), }), }, + /** + * A repository's recent GitHub Deployments for one environment, newest + * first, each with its latest status as `state` (BB-59). Stewards reads + * this to confirm a merge carried by a deployment that already exists, not + * only by a `deployment` doorbell; the plugin never evaluates the + * playbook's `carries` rule. Linear has no deployments and answers with an + * error. `limit` caps how many are returned. + */ + sourceDeployments: { + input: z.object({ + repo: z.string().min(1).max(200), + environment: z.string().min(1).max(200), + limit: z.number().int().min(1).max(100).default(10), + }), + output: z.object({ + deployments: z.array(deploymentSchema), + /** Set when the repository could not be read (not visible, no access). */ + error: z.string().nullable(), + }), + }, } as const; // ---- what stewards serves --------------------------------------------------- diff --git a/plugins/linear/server.ts b/plugins/linear/server.ts index f3f1b4d6..c856094e 100644 --- a/plugins/linear/server.ts +++ b/plugins/linear/server.ts @@ -610,6 +610,11 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => async sourceDependabotAlerts() { return { viewer: null, alerts: [], errors: ["Dependabot alerts are read from github, not linear"] }; }, + // Deployments are a GitHub thing; linear has none. Stewards only asks + // github, so this is a plain answer rather than a throw. + async sourceDeployments() { + return { deployments: [], error: "deployments are read from github, not linear" }; + }, async sourceSetInterest({ units, entities }, { experimental_caller: caller }) { // The interest decides what this server leases and whom it rings, so // only stewards itself may set it; the app and the CLI are clients. diff --git a/plugins/linear/source-contract.ts b/plugins/linear/source-contract.ts index 3714bbb7..d722a573 100644 --- a/plugins/linear/source-contract.ts +++ b/plugins/linear/source-contract.ts @@ -304,6 +304,26 @@ export const sourceContract = { errors: z.array(z.string()), }), }, + /** + * A repository's recent GitHub Deployments for one environment, newest + * first, each with its latest status as `state` (BB-59). Stewards reads + * this to confirm a merge carried by a deployment that already exists, not + * only by a `deployment` doorbell; the plugin never evaluates the + * playbook's `carries` rule. Linear has no deployments and answers with an + * error. `limit` caps how many are returned. + */ + sourceDeployments: { + input: z.object({ + repo: z.string().min(1).max(200), + environment: z.string().min(1).max(200), + limit: z.number().int().min(1).max(100).default(10), + }), + output: z.object({ + deployments: z.array(deploymentSchema), + /** Set when the repository could not be read (not visible, no access). */ + error: z.string().nullable(), + }), + }, } as const; // ---- what stewards serves --------------------------------------------------- diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index a6343ca5..5e8ab62b 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -745,6 +745,19 @@ deployment: # where a merge is confirmed live (BB-53); omi comment once every pull request is merged and deployed. A failure/error deployment or a timeout wakes the steward with the run URL. No `deployment` is exactly today's behaviour. +- **A deployment that predates its watch is read, not waited for (BB-59).** + A doorbell can be missed, most obviously across the server restart every + `bb-plugins` merge causes, and a deployment that landed before the watch was + recorded never rings. So when a `merged` watch is first recorded, and on + every sweep for a watch still in `merged` or `deploying`, the plugin reads + the target repo's recent deployments for the playbook's environment through + the github plugin's source contract (`sourceDeployments`, never `gh` in the + server). The newest one is applied exactly as a doorbell would be: a success + moves the watch to `deploying` with its id, ref, sha and URL and wakes the + steward with the playbook's rule; a failure or error gives the failure wake. + A read that repeats what a watch already recorded is not news, so the sweep + does not re-wake for the same deployment. No deployments leaves the deadline + and the timeout path untouched. The plugin still never evaluates `carries`. - **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 @@ -1411,7 +1424,10 @@ own server behind bb-gate, so it is per developer in practice. 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. + through as before. A deployment that already exists is read through the + github plugin's source contract on the first watch and on the sweep + (BB-59), so a missed doorbell costs a sweep, not the timeout; the read + never evaluates `carries`. - **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/deploy.test.ts b/plugins/stewards/deploy.test.ts index 4655a10a..a055b7a5 100644 --- a/plugins/stewards/deploy.test.ts +++ b/plugins/stewards/deploy.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { pull } from "./fixtures.js"; import type { DeploymentTarget } from "./config.js"; -import { allDeployed, applyDeployment, deploymentLines, deploymentsSchema, matchesTarget, mergedPulls, recordMerged, reportDeployment, timeOut, timeoutsDue, type Deployments } from "./deploy.js"; +import { allDeployed, applyDeployment, applyDeploymentRead, deploymentLines, deploymentsSchema, matchesTarget, mergedPulls, recordMerged, reportDeployment, timeOut, timeoutsDue, type Deployments } from "./deploy.js"; import type { Deployment } from "./source-contract.js"; import type { Observed } from "./store.js"; @@ -26,6 +26,7 @@ describe("recording merged pull requests", () => { repo: "acme/bb-gate", environment: "production", deploymentId: null, + deploymentState: null, ref: null, sha: null, url: null, @@ -124,6 +125,53 @@ describe("the steward's verdict", () => { }); }); +describe("confirming from a deployment read (BB-59)", () => { + it("applies the newest deployment for the target and records its facts", () => { + const deployments = recordMerged({}, observed(), target, NOW); + const read = [deployment({ id: 6, state: "failure", url: "https://example.test/6" }), deployment({ id: 7, state: "success" })]; + const applied = applyDeploymentRead(deployments, target, read, NOW + 60_000); + expect(applied.changed).toEqual(["acme/web#7"]); + expect(applied.deployment).toMatchObject({ id: 7, state: "success" }); + expect(applied.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentId: 7, deploymentState: "success", ref: "main", sha: "bbbbbbb2", url: "https://github.com/acme/bb-gate/actions/runs/9", deadlineAt: NOW + 60_000 + target.timeout }); + }); + + it("treats a failed newest deployment as the failure it is", () => { + const deployments = recordMerged({}, observed(), target, NOW); + const applied = applyDeploymentRead(deployments, target, [deployment({ state: "failure", url: "https://example.test/12" })], NOW); + expect(applied.changed).toEqual(["acme/web#7"]); + expect(applied.deployments["acme/web#7"]).toMatchObject({ state: "failed", deploymentState: "failure", deadlineAt: null, note: "Deployment 7 reported failure" }); + }); + + it("changes nothing when the target's environment has no deployments", () => { + const deployments = recordMerged({}, observed(), target, NOW); + expect(applyDeploymentRead(deployments, target, [], NOW)).toEqual({ deployments, changed: [], deployment: null }); + expect(applyDeploymentRead(deployments, target, [deployment({ environment: "staging" })], NOW).changed).toEqual([]); + }); + + it("does not re-wake for a deployment it already recorded with the same state, but does for a new state", () => { + const first = applyDeploymentRead(recordMerged({}, observed(), target, NOW), target, [deployment({ state: "in_progress" })], NOW); + expect(first.changed).toEqual(["acme/web#7"]); + // The same deployment, same state: a repeat read is not news. + expect(applyDeploymentRead(first.deployments, target, [deployment({ state: "in_progress" })], NOW + 1000).changed).toEqual([]); + // The same deployment reaching success is news. + const second = applyDeploymentRead(first.deployments, target, [deployment({ state: "success" })], NOW + 2000); + expect(second.changed).toEqual(["acme/web#7"]); + expect(second.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentState: "success" }); + }); + + it("never moves a watch backwards to an older deployment", () => { + const held = applyDeploymentRead(recordMerged({}, observed(), target, NOW), target, [deployment({ id: 9, state: "success" })], NOW).deployments; + expect(applyDeploymentRead(held, target, [deployment({ id: 7, state: "success" })], NOW + 1000).changed).toEqual([]); + expect(held["acme/web#7"]).toMatchObject({ deploymentId: 9 }); + }); + + it("leaves a settled watch alone", () => { + const settled = applyDeployment(recordMerged({}, observed(), target, NOW), target, deployment(), NOW).deployments; + const done = reportDeployment(settled, { state: "deployed" }, NOW, target.timeout).deployments; + expect(applyDeploymentRead(done, target, [deployment({ id: 8, state: "success" })], NOW + 1000).changed).toEqual([]); + }); +}); + describe("the show lines", () => { it("names each watch's state, target, deployment facts and note", () => { const deployments = applyDeployment(recordMerged({}, observed(), target, NOW), target, deployment({ state: "failure" }), NOW).deployments; diff --git a/plugins/stewards/deploy.ts b/plugins/stewards/deploy.ts index 2a9c8eeb..5db9316d 100644 --- a/plugins/stewards/deploy.ts +++ b/plugins/stewards/deploy.ts @@ -27,6 +27,8 @@ export const deploymentWatchSchema = z.object({ repo: z.string(), environment: z.string(), deploymentId: z.number().int().nullable().default(null), + /** The deployment's own last status (success, failure, in_progress…), so a repeat read is not news. */ + deploymentState: z.string().nullable().default(null), ref: z.string().nullable().default(null), sha: z.string().nullable().default(null), url: z.string().nullable().default(null), @@ -66,6 +68,7 @@ export function recordMerged(deployments: Deployments, observed: Observed, targe repo: target.repo, environment: target.environment, deploymentId: null, + deploymentState: null, ref: null, sha: null, url: null, @@ -102,6 +105,7 @@ export function applyDeployment(deployments: Deployments, target: Pick, + read: readonly Deployment[], + now: number, +): { deployments: Deployments; changed: string[]; deployment: Deployment | null } { + const latest = read.filter((d) => d.environment.toLowerCase() === target.environment.toLowerCase()).sort((a, b) => b.id - a.id)[0]; + if (latest === undefined) return { deployments, changed: [], deployment: null }; + const failed = latest.state === "failure" || latest.state === "error"; + const next = { ...deployments }; + const changed: string[] = []; + for (const watch of Object.values(next)) { + if (watch.state === "deployed" || watch.state === "failed") continue; + if (!matchesTarget(target, watch.repo, watch.environment)) continue; + if (latest.environment.toLowerCase() !== watch.environment.toLowerCase()) continue; + // The read repeats; the same deployment in the same state is not news. + if (watch.deploymentId === latest.id && watch.deploymentState === latest.state) continue; + // A read can only move a watch forward; an older deployment is stale. + if (watch.deploymentId !== null && latest.id < watch.deploymentId) continue; + next[watch.key] = { + ...watch, + state: failed ? "failed" : "deploying", + deploymentId: latest.id, + deploymentState: latest.state, + ref: latest.ref === "" ? null : latest.ref, + sha: latest.sha === "" ? null : latest.sha, + url: latest.url, + at: now, + deadlineAt: failed ? null : now + target.timeout, + note: failed ? `Deployment ${latest.id} reported ${latest.state}` : watch.note, + }; + changed.push(watch.key); + } + return changed.length === 0 ? { deployments, changed, deployment: null } : { deployments: next, changed, deployment: latest }; +} + /** The watches still awaiting a deployment whose deadline has passed. */ export const timeoutsDue = (deployments: Deployments, now: number): string[] => Object.values(deployments) diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 26b6d1b8..2e45b1d8 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -26,6 +26,8 @@ function world() { const entities = new Map(); /** Dependabot alerts the fake github serves, by lowercased repo. */ const dependabotAlerts = new Map(); + /** Deployments the fake github serves, by `lowercased repo lowercased environment`. */ + const sourceDeployments = new Map(); const rpcCalls: Call[] = []; /** Every lesson merge the plugin asked multi-repo for, and what it answered. */ const mergeGuidanceCalls: Record[] = []; @@ -88,6 +90,10 @@ function world() { const units = input.units as string[]; out = { viewer: "jane", alerts: units.flatMap((u) => dependabotAlerts.get(u.toLowerCase()) ?? []), errors: [] }; } + else if (args.method === "sourceDeployments") { + const key = `${String(input.repo).toLowerCase()} ${String(input.environment).toLowerCase()}`; + out = { deployments: sourceDeployments.get(key) ?? [], error: null }; + } else if (args.method === "mergeGuidance") { mergeGuidanceCalls.push(input); out = mergeGuidanceResult ?? { ok: true, sha: "b".repeat(40), branch: `refs/heads/guidance-${String(input.threadId)}`, message: "merged" }; @@ -245,7 +251,7 @@ function world() { }, }; let now = Date.parse("2026-10-14T15:00:00Z"); - return { files, writes, fileContents, repos, entities, dependabotAlerts, rpcCalls, mergeGuidanceCalls, setMergeGuidanceResult: (value: typeof mergeGuidanceResult) => { mergeGuidanceResult = value; }, threads, sections, usage, metadata, spawns, sends, userTurns, githubComments, githubMerges, githubFiles, github, sdk, uiPreferences, uiPreferencesWrites, now: () => now, advance: (ms: number) => (now += ms) }; + return { files, writes, fileContents, repos, entities, dependabotAlerts, sourceDeployments, rpcCalls, mergeGuidanceCalls, setMergeGuidanceResult: (value: typeof mergeGuidanceResult) => { mergeGuidanceResult = value; }, threads, sections, usage, metadata, spawns, sends, userTurns, githubComments, githubMerges, githubFiles, github, sdk, uiPreferences, uiPreferencesWrites, now: () => now, advance: (ms: number) => (now += ms) }; } async function setup(extra: Partial = {}, settings: Record = {}, seedProvider?: string | null | "fail-list" | "fail-set") { @@ -5924,4 +5930,74 @@ describe("deployment watching (BB-53)", () => { 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); }); + + // BB-59: a deployment that already exists confirms the merge on the first + // read and on the sweep, so a doorbell missed across a restart (or any + // other miss) costs a sweep, not the timeout. + it("confirms a merge from a deployment that already exists when the watch is recorded (BB-59)", async () => { + const t = await setup(); + merged(t); + t.sourceDeployments.set("acme/bb-gate production", [deployment()]); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentId: 7, deploymentState: "success", sha: "bbbbbbb2" }); + const wake = String(t.spawns[1]!.prompt); + 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); + }); + + it("picks up a deployment whose doorbell was missed on the sweep (BB-59)", 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; + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "merged" }); + // The deployment lands, but its doorbell never reaches the server. + t.sourceDeployments.set("acme/bb-gate production", [deployment()]); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentId: 7 }); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before + 1); + expect(t.sends.filter((s) => s.threadId === steward).at(-1)!.text).toMatch(/Deployment 7 \(success\) for acme\/bb-gate production/u); + }); + + it("wakes nobody when the target has no deployments, and keeps the deadline (BB-59)", 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 t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "merged" }); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]!.deadlineAt).not.toBeNull(); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(before); + }); + + it("wakes with the failure when the latest deployment failed (BB-59)", async () => { + const t = await setup(); + merged(t); + t.sourceDeployments.set("acme/bb-gate production", [deployment({ state: "failure", url: "https://github.com/acme/bb-gate/actions/runs/12" })]); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "failed", deploymentState: "failure" }); + const wake = String(t.spawns[1]!.prompt); + 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("lets an existing deployment win over the deadline at the boundary (BB-59)", async () => { + const t = await setup(); + merged(t); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + // The deadline passes, but a carrying deployment is already there to be read. + t.advance(61 * 60_000); + t.sourceDeployments.set("acme/bb-gate production", [deployment()]); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.find("ENG-12")!.deployments["acme/web#7"]).toMatchObject({ state: "deploying", deploymentId: 7 }); + const wake = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; + expect(wake).toMatch(/Deployment 7 \(success\) for acme\/bb-gate production/u); + }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 8932f14e..700008dc 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -70,7 +70,7 @@ import { type SessionWake, type Source, } from "./source-contract.js"; -import { allDeployed, applyDeployment, deploymentLines, deploymentReportSchema, recordMerged, reportDeployment, timeOut, timeoutsDue } from "./deploy.js"; +import { allDeployed, applyDeployment, applyDeploymentRead, 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, atWork, conflictsOf, finished, normalizeTouches, overlapping, touchesOverlap, type Conflict } from "./schedule.js"; @@ -904,6 +904,25 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return deadlines.length === 0 ? null : Math.min(...deadlines); } + /** + * A deployment target's recent deployments, read through the github + * plugin's source contract (BB-59), never `gh` here. Null when the read + * failed, so the caller leaves the deadline and timeout path alone. + */ + async function readDeployments(target: DeploymentTarget): Promise { + try { + const out = await sourceRpc("github", "sourceDeployments", { repo: target.repo, environment: target.environment, limit: 10 }, sourceContract.sourceDeployments.output); + if (out.error !== null) { + bb.log.warn(`stewards: could not read deployments for ${target.repo} ${target.environment}: ${out.error}`); + return null; + } + return out.deployments; + } catch (error) { + bb.log.warn(`stewards: could not read deployments for ${target.repo} ${target.environment}: ${errorMessage(error)}`); + return null; + } + } + // ---- the sources --------------------------------------------------------------------- async function snapshot(source: Source, id: string): Promise { @@ -1813,6 +1832,26 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const fresh = Object.keys(deployments).filter((k) => beforeDeploy[k] === undefined); deploymentChanges.push({ text: `Awaiting deployment: ${fresh.join(", ")} via ${deployTarget.repo} ${deployTarget.environment}`, actionable: true }); } + if (deployments !== b.deployments) b = store.patch(b.id, { deployments }); + // BB-59: a deployment that already exists confirms a merge whose + // doorbell was missed, on the first read and on every sweep. Read + // before the timeout check so an existing deployment wins over the + // deadline; with none, the timeout path is exactly as before. The + // github plugin reads it through the source contract; the plugin + // never evaluates the playbook's carries rule. + if (Object.values(deployments).some((w) => w.state === "merged" || w.state === "deploying")) { + const read = await readDeployments(deployTarget); + if (read !== null) { + const applied = applyDeploymentRead(deployments, deployTarget, read, now()); + if (applied.changed.length > 0 && applied.deployment !== null) { + deployments = applied.deployments; + b = store.patch(b.id, { deployments }); + const state = applied.deployment.state === "" ? "created" : applied.deployment.state; + b = store.note(b.id, `Deployment ${applied.deployment.id} (${state}) for ${deployTarget.repo} ${deployTarget.environment}${applied.deployment.url === null ? "" : ` — ${applied.deployment.url}`}; the playbook's rule: ${deployTarget.carries}`, false); + bb.log.info(`stewards: deployment ${applied.deployment.id} (${state}) on ${deployTarget.repo} ${deployTarget.environment} concerns ${applied.changed.join(", ")} (read)`); + } + } + } const late = timeoutsDue(deployments, now()); if (late.length > 0) { deployments = timeOut(deployments, late, now()); diff --git a/plugins/stewards/source-contract.ts b/plugins/stewards/source-contract.ts index 3714bbb7..d722a573 100644 --- a/plugins/stewards/source-contract.ts +++ b/plugins/stewards/source-contract.ts @@ -304,6 +304,26 @@ export const sourceContract = { errors: z.array(z.string()), }), }, + /** + * A repository's recent GitHub Deployments for one environment, newest + * first, each with its latest status as `state` (BB-59). Stewards reads + * this to confirm a merge carried by a deployment that already exists, not + * only by a `deployment` doorbell; the plugin never evaluates the + * playbook's `carries` rule. Linear has no deployments and answers with an + * error. `limit` caps how many are returned. + */ + sourceDeployments: { + input: z.object({ + repo: z.string().min(1).max(200), + environment: z.string().min(1).max(200), + limit: z.number().int().min(1).max(100).default(10), + }), + output: z.object({ + deployments: z.array(deploymentSchema), + /** Set when the repository could not be read (not visible, no access). */ + error: z.string().nullable(), + }), + }, } as const; // ---- what stewards serves ---------------------------------------------------