From f36e3ee6b2097e1fd26bdf34ca011997f1baf4cd Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Tue, 20 Oct 2026 05:25:26 +0000 Subject: [PATCH 1/2] stewards: Dependabot alerts with a severity SLA, and deps-prs (BB-12) Dependabot alerts reach stewards as doorbells and become Linear tickets by severity. A new dependabot_alert entity in source-contract.ts (three copies), the github plugin reads alerts through a new sourceDependabotAlerts RPC, leases each watched repo as a dependabot_repo (a plain repo lease does not receive alert doorbells), and rings stewards on dependabot_alert. stewards watches every repo in repos.json not in github.exclude (or the explicit { kind: dependabot, repo } targets) as an ops binding running the new deps-alerts playbook. Severity maps onto Linear priority and a due date from deps.sla; critical and high get their own ticket, medium and low coalesce into one open ticket per repo per ecosystem, and a new alert joins or tightens it. A fixed or dismissed alert trims or closes the ticket, and the nightly pass re-lists open alerts as the backstop. deps-prs adopts dependabot[bot] version-update pull requests, reviews them, and escalates for a human merge; it never merges. linear_update_issue and linear_create_issue gain a dueDate parameter so the SLA can be recorded. The dependency watch is off until bb stewards init writes deps-alerts.md and deps-prs.md; bb stewards check validates deps.sla, deps.batch and deps.autoAdopt and says which repos the gh login cannot read. --- plugins/github-watcher/README.md | 21 +- plugins/github-watcher/github.test.ts | 48 ++- plugins/github-watcher/github.ts | 58 +++- plugins/github-watcher/hooks-client.test.ts | 12 +- plugins/github-watcher/hooks-client.ts | 20 +- plugins/github-watcher/server.test.ts | 82 +++++- plugins/github-watcher/server.ts | 105 ++++++- plugins/github-watcher/source-contract.ts | 57 ++++ plugins/github-watcher/usage.test.ts | 2 +- plugins/github-watcher/usage.ts | 5 +- plugins/linear/server.test.ts | 10 +- plugins/linear/server.ts | 18 +- plugins/linear/source-contract.ts | 57 ++++ plugins/stewards/DESIGN.md | 57 ++++ plugins/stewards/README.md | 28 +- plugins/stewards/config.test.ts | 64 +++- plugins/stewards/config.ts | 86 +++++- plugins/stewards/deps.test.ts | 106 +++++++ plugins/stewards/deps.ts | 159 ++++++++++ plugins/stewards/kubectl.ts | 6 +- plugins/stewards/ops.ts | 14 +- plugins/stewards/reconcile.ts | 7 +- plugins/stewards/server.test.ts | 159 +++++++++- plugins/stewards/server.ts | 306 ++++++++++++++++++-- plugins/stewards/source-contract.ts | 57 ++++ plugins/stewards/store.ts | 25 +- plugins/stewards/templates.ts | 112 +++++++ plugins/stewards/wake.ts | 94 ++++++ 28 files changed, 1671 insertions(+), 104 deletions(-) create mode 100644 plugins/stewards/deps.test.ts create mode 100644 plugins/stewards/deps.ts diff --git a/plugins/github-watcher/README.md b/plugins/github-watcher/README.md index 034358dc..b6d5e285 100644 --- a/plugins/github-watcher/README.md +++ b/plugins/github-watcher/README.md @@ -36,12 +36,21 @@ copy shared with stewards and linear; edit all three or none): A `gh` that is not signed in is reported in `error`, not thrown. - `sourceAdoptable`: every open pull request in the repositories, oldest first, up to the limit. -- `sourceSetInterest`: the repositories and entities stewards wants to hear - about. Only stewards may call it. Kept in kv, leased on bb-gate-hooks - beside the watches (`repo` leases for repositories, `issue` leases for - entities), and every doorbell for one of them is debounced and rung over - to stewards as `stewardsRing` (`ringStewards`, quiet when stewards is not -installed). A refused lease is logged. +- `sourceDependabotAlerts`: a repository's Dependabot alerts, read with the + token from `GET /repos/{owner}/{repo}/dependabot/alerts` and named the way + the shared contract wants them. Reading alerts needs the token's alert + access (the `security_events` scope, or Dependabot alerts read), more than + read access to the repository; a repo the token cannot read is named in + `errors` and the rest are still returned. +- `sourceSetInterest`: the repositories, entities and Dependabot + repositories stewards wants to hear about. Only stewards may call it. Kept + in kv, leased on bb-gate-hooks beside the watches (`repo` leases for + repositories, `issue` leases for entities, `dependabot_repo` leases for + Dependabot repositories; a `repo` lease does not receive alert doorbells), + and every doorbell for one of them is debounced and rung over to stewards + as `stewardsRing` (`ringStewards`, quiet when stewards is not installed). + A refused lease is logged; a refused `dependabot_repo` is a skip, since a + login that cannot read alerts simply does not get those doorbells. There are no write tools: a steward comments and reviews with `gh` like any thread, and signs what it posts as the skill asks, which is how diff --git a/plugins/github-watcher/github.test.ts b/plugins/github-watcher/github.test.ts index f2cd680b..5e0fc568 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 { parseOpenPulls, parseRef, parseRefKey, parseRepo, parseRepoCheck, parseSnapshot, parseTarget, refKey, TARGET_QUERY } from "./github.js"; +import { parseDependabotAlerts, 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", () => { @@ -262,3 +262,49 @@ describe("repositories", () => { expect(parseOpenPulls({ data: { viewer: { login: "dev" }, repository: null }, errors: [{ type: "NOT_FOUND", message: "Could not resolve" }] })).toBeNull(); }); }); + +describe("Dependabot alerts", () => { + const node = (over: Record = {}) => ({ + number: 4, + state: "open", + dependency: { package: { ecosystem: "npm", name: "lodash" }, manifest_path: "package-lock.json" }, + security_advisory: { ghsa_id: "GHSA-xxxx-yyyy-zzzz", severity: "high", summary: "Prototype pollution" }, + security_vulnerability: { severity: "high", first_patched_version: { identifier: "4.17.21" } }, + html_url: "https://github.com/Acme/Widgets/security/dependabot/4", + url: "https://api.github.com/repos/Acme/Widgets/dependabot/alerts/4", + created_at: "2026-10-01T00:00:00Z", + updated_at: "2026-10-02T00:00:00Z", + ...over, + }); + + it("reads a page as the shared contract wants it, with the alert's own number", () => { + expect(parseDependabotAlerts([node()], "Acme/Widgets")).toEqual([ + { + id: "Acme/Widgets#4", + repo: "Acme/Widgets", + number: 4, + severity: "high", + package: "lodash", + ecosystem: "npm", + manifestPath: "package-lock.json", + state: "open", + ghsaId: "GHSA-xxxx-yyyy-zzzz", + fixedVersion: "4.17.21", + summary: "Prototype pollution", + url: "https://github.com/Acme/Widgets/security/dependabot/4", + createdAt: "2026-10-01T00:00:00Z", + updatedAt: "2026-10-02T00:00:00Z", + }, + ]); + }); + + it("falls back to the vulnerability's severity, and to low for anything unexpected, and tolerates a bare alert", () => { + const bare = parseDependabotAlerts([node({ dependency: null, security_advisory: null, security_vulnerability: { severity: "medium", first_patched_version: null } })], "Acme/Widgets")[0]!; + expect(bare).toMatchObject({ severity: "medium", package: "(unknown)", ecosystem: "unknown", ghsaId: null, fixedVersion: null }); + expect(parseDependabotAlerts([node({ security_advisory: { severity: "banana" } })], "Acme/Widgets")[0]!.severity).toBe("low"); + }); + + it("throws on anything that is not an alert list", () => { + expect(() => parseDependabotAlerts({ message: "Not Found" }, "Acme/Widgets")).toThrow(/Dependabot alert list/u); + }); +}); diff --git a/plugins/github-watcher/github.ts b/plugins/github-watcher/github.ts index 68470702..b636eacf 100644 --- a/plugins/github-watcher/github.ts +++ b/plugins/github-watcher/github.ts @@ -4,12 +4,16 @@ // function that talks to the network takes its fetch as an argument, and no // token appears in anything this module returns or throws. import { z } from "zod"; -import { SNAPSHOT_COMMENT_CHARS, SNAPSHOT_COMMENTS_MAX, SNAPSHOT_DESCRIPTION_CHARS, signedBy, type AdoptableEntity, type EntitySnapshot } from "./source-contract.js"; +import { DEPENDABOT_SEVERITIES, SNAPSHOT_COMMENT_CHARS, SNAPSHOT_COMMENTS_MAX, SNAPSHOT_DESCRIPTION_CHARS, signedBy, type AdoptableEntity, type DependabotAlert, type DependabotSeverity, type EntitySnapshot } from "./source-contract.js"; export const GITHUB_URL = "https://github.com"; export const GITHUB_API_URL = "https://api.github.com"; export const GRAPHQL_PATH = "/graphql"; +/** The Dependabot alerts REST path for one repository, and one alert's. */ +export const dependabotAlertsPath = (repo: string, state: string, perPage = 100): string => `/repos/${repo}/dependabot/alerts?state=${encodeURIComponent(state)}&per_page=${perPage}`; +export const dependabotAlertPath = (repo: string, number: number): string => `/repos/${repo}/dependabot/alerts/${number}`; + export class GitHubRequestError extends Error { constructor( message: string, @@ -486,3 +490,55 @@ export function parseOpenPulls(payload: unknown): { viewer: string | null; entit /** "pull request" or "issue", for prose. */ export const kindName = (kind: Target["kind"]): string => (kind === "pull" ? "pull request" : "issue"); + +// ---- Dependabot alerts ------------------------------------------------------------- + +const dependabotAlertNode = z.object({ + number: z.number(), + state: z.string(), + dependency: z + .object({ + package: z.object({ ecosystem: z.string(), name: z.string() }), + manifest_path: z.string().nullish(), + }) + .nullish(), + security_advisory: z.object({ ghsa_id: z.string().nullish(), severity: z.string().nullish(), summary: z.string().nullish() }).nullish(), + security_vulnerability: z.object({ severity: z.string().nullish(), first_patched_version: z.object({ identifier: z.string() }).nullish() }).nullish(), + html_url: z.string().nullish(), + url: z.string().nullish(), + created_at: z.string().nullish(), + updated_at: z.string().nullish(), +}); + +/** GitHub's severity is one of the four; anything unexpected is read as low rather than thrown away. */ +const severityOf = (value: string | null | undefined): DependabotSeverity => { + const s = (value ?? "").toLowerCase(); + return (DEPENDABOT_SEVERITIES as readonly string[]).includes(s) ? (s as DependabotSeverity) : "low"; +}; + +/** + * One page of `GET /repos/{owner}/{repo}/dependabot/alerts`, as the shared + * contract wants it. `repo` is the name the caller asked with; GitHub's + * answer does not repeat it. The alert number is the repository's own alert + * numbering, which is what the entity id and fingerprint use. + */ +export function parseDependabotAlerts(payload: unknown, repo: string): DependabotAlert[] { + const parsed = z.array(dependabotAlertNode).safeParse(payload); + if (!parsed.success) throw new Error("GitHub answered with something that is not a Dependabot alert list"); + return parsed.data.map((a) => ({ + id: `${repo}#${a.number}`, + repo, + number: a.number, + severity: severityOf(a.security_advisory?.severity ?? a.security_vulnerability?.severity), + package: a.dependency?.package.name ?? "(unknown)", + ecosystem: a.dependency?.package.ecosystem ?? "unknown", + manifestPath: a.dependency?.manifest_path ?? null, + state: a.state, + ghsaId: a.security_advisory?.ghsa_id ?? null, + fixedVersion: a.security_vulnerability?.first_patched_version?.identifier ?? null, + summary: a.security_advisory?.summary ?? null, + url: a.html_url ?? null, + createdAt: a.created_at ?? null, + updatedAt: a.updated_at ?? null, + })); +} diff --git a/plugins/github-watcher/hooks-client.test.ts b/plugins/github-watcher/hooks-client.test.ts index b28d744f..70ece820 100644 --- a/plugins/github-watcher/hooks-client.test.ts +++ b/plugins/github-watcher/hooks-client.test.ts @@ -163,6 +163,7 @@ describe("the loop", () => { const logs: string[] = []; const sweeps: string[] = []; const doorbells: string[] = []; + const doorbellKinds: string[] = []; const units: Array = []; const rejected: Rejection[][] = []; let token = "tok-1"; @@ -179,7 +180,8 @@ describe("the loop", () => { return token; }, watchIds: over.watchIds ?? (() => [{ kind: "issue", id: "i-1" }, { kind: "issue", id: "i-2" }]), - onDoorbell: (id, unit) => { + onDoorbell: (kind, id, unit) => { + doorbellKinds.push(kind); doorbells.push(id); units.push(unit); }, @@ -193,7 +195,7 @@ describe("the loop", () => { }); const controller = new AbortController(); const done = loop.run(controller.signal); - return { loop, logs, sweeps, doorbells, units, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes }; + return { loop, logs, sweeps, doorbells, doorbellKinds, units, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes }; } it("subscribes every watch on hello with the current token, sweeps, then rings on doorbells for issues only", async () => { @@ -211,13 +213,15 @@ describe("the loop", () => { hooks.last().send(hooks.doorbell("i-1")); hooks.last().send(hooks.doorbell("acme/widgets", { kind: "repo" })); + hooks.last().send(hooks.doorbell("acme/widgets#4", { kind: "dependabot_alert" })); hooks.last().send(hooks.doorbell("i-9", { source: "linear" })); hooks.last().send("event: doorbell\ndata: not json\n\n"); hooks.last().send(hooks.doorbell("i-2", { action: "remove", unit: "" })); await tick(); - expect(s.doorbells).toEqual(["i-1", "i-2"]); + expect(s.doorbells).toEqual(["i-1", "acme/widgets#4", "i-2"]); + expect(s.doorbellKinds).toEqual(["issue", "dependabot_alert", "issue"]); // The unit comes along when the service names one. - expect(s.units).toEqual(["acme/widgets", null]); + expect(s.units).toEqual(["acme/widgets", "acme/widgets", null]); expect(s.logs.join("\n")).not.toContain("tok-1"); s.controller.abort(); diff --git a/plugins/github-watcher/hooks-client.ts b/plugins/github-watcher/hooks-client.ts index 068f27dc..885b4ca0 100644 --- a/plugins/github-watcher/hooks-client.ts +++ b/plugins/github-watcher/hooks-client.ts @@ -20,9 +20,13 @@ export const SUBSCRIBE_BATCH = 100; /** * What a lease hangs off. `issue` is one issue or pull request, * "owner/repo#12"; `repo` is a whole repository, "owner/repo", and receives - * every doorbell whose unit it is. Doorbells themselves are always `issue`. + * every issue doorbell whose unit it is; `dependabot_repo` is a whole + * repository and receives every `dependabot_alert` doorbell in it. Doorbells + * are always `issue` or `dependabot_alert`; the unit lease kinds are + * separate because reading a repository does not entitle a token to its + * alerts (bb-gate/docs/hooks.md). */ -export type LeaseKind = "issue" | "repo"; +export type LeaseKind = "issue" | "repo" | "dependabot_repo"; export type Lease = { kind: LeaseKind; id: string }; // ---- server-sent events ---------------------------------------------------- @@ -212,8 +216,12 @@ export interface HooksLoopDeps { refreshToken: () => Promise; /** Every lease to hold, right now: watched issues, and whatever stewards asked for. */ watchIds: () => Lease[]; - /** A doorbell for an issue, with the unit (the repository) it fell in when the service named one: look at it again. */ - onDoorbell: (issueId: string, unit: string | null) => void; + /** + * 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. + */ + onDoorbell: (kind: string, id: string, unit: string | null) => void; /** Leases the service refused. The caller decides what that means for each watch. */ onRejected: (rejected: Rejection[]) => Promise; /** Check every watch against its cursor. */ @@ -418,10 +426,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") { + if (doorbell.success && doorbell.data.source === SOURCE && (doorbell.data.kind === "issue" || doorbell.data.kind === "dependabot_alert")) { doorbells.push(); const unit = doorbell.data.unit?.trim() ?? ""; - deps.onDoorbell(doorbell.data.id, unit === "" ? null : unit); + deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit); } } } diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index 216268d9..3f49b64b 100644 --- a/plugins/github-watcher/server.test.ts +++ b/plugins/github-watcher/server.test.ts @@ -38,11 +38,19 @@ 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> }; + const state = { node: pullNode() as Record | null, fail: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array>, dependabotAlerts: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden" }; 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, ""); - if (String(url) !== `${API_URL}/graphql`) return new Response("not found", { status: 404 }); + const u = String(url); + const dependabot = /\/repos\/([^/]+)\/([^/]+)\/dependabot\/alerts(?:\?|$)/u.exec(u); + if (dependabot !== null) { + if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); + if (`${dependabot[1]}/${dependabot[2]}`.toLowerCase() !== "acme/widgets") return Response.json({ message: "Not Found" }, { status: 404 }); + if (state.dependabotStatus !== 200) return Response.json({ message: state.dependabotMessage }, { status: state.dependabotStatus }); + return Response.json(state.dependabotAlerts); + } + if (u !== `${API_URL}/graphql`) return new Response("not found", { status: 404 }); const body = JSON.parse(String(init?.body)) as { query: string; variables: Record }; calls.push({ token, variables: body.variables }); if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); @@ -498,6 +506,52 @@ describe("stewards' source contract", () => { expect(w.github.calls.find((c) => c.variables.first !== undefined)!.variables).toMatchObject({ owner: "Acme", name: "Widgets", first: 1, after: null }); }); + it("reads a repository's Dependabot alerts, naming a repository or a repo the token cannot read rather than failing", async () => { + const w = await setup(); + w.github.state.dependabotAlerts = [ + { + number: 4, + state: "open", + dependency: { package: { ecosystem: "npm", name: "lodash" }, manifest_path: "package-lock.json" }, + security_advisory: { ghsa_id: "GHSA-x", severity: "high", summary: "Prototype pollution" }, + security_vulnerability: { severity: "high", first_patched_version: { identifier: "4.17.21" } }, + html_url: "https://github.com/Acme/Widgets/security/dependabot/4", + created_at: "2026-10-01T00:00:00Z", + updated_at: "2026-10-02T00:00:00Z", + }, + ]; + expect(await w.harness.callRpc("sourceDependabotAlerts", { units: ["Acme/Widgets"], state: "open" }, STEWARDS)).toEqual({ + viewer: "dev", + alerts: [ + { + id: "Acme/Widgets#4", + repo: "Acme/Widgets", + number: 4, + severity: "high", + package: "lodash", + ecosystem: "npm", + manifestPath: "package-lock.json", + state: "open", + ghsaId: "GHSA-x", + fixedVersion: "4.17.21", + summary: "Prototype pollution", + url: "https://github.com/Acme/Widgets/security/dependabot/4", + createdAt: "2026-10-01T00:00:00Z", + updatedAt: "2026-10-02T00:00:00Z", + }, + ], + errors: [], + }); + expect(await w.harness.callRpc("sourceDependabotAlerts", { units: ["acme/gone", "widgets"], state: "open" }, STEWARDS)).toMatchObject({ alerts: [], errors: ["acme/gone: GitHub answered HTTP 404: Not Found", "widgets: not owner/repo"] }); + }); + + it("names a repository whose alerts the token cannot read (403) without failing the whole call", async () => { + const w = await setup(); + w.github.state.dependabotStatus = 403; + w.github.state.dependabotMessage = "Resource not accessible by integration"; + expect(await w.harness.callRpc("sourceDependabotAlerts", { units: ["Acme/Widgets"], state: "open" }, STEWARDS)).toMatchObject({ alerts: [], errors: ["Acme/Widgets: GitHub answered HTTP 403: Resource not accessible by integration"] }); + }); + describe("interest", () => { beforeEach(() => vi.useFakeTimers()); afterEach(() => vi.useRealTimers()); @@ -516,7 +570,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"] }); + expect(await w.bb.storage.kv.get("stewards/interest")).toEqual({ units: ["acme/gadgets"], entities: ["Acme/Widgets#12"], dependabot: [] }); 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: [] }); @@ -552,6 +606,28 @@ describe("stewards' source contract", () => { await service.done; }); + it("leases Dependabot repositories and rings stewards for dependabot_alert doorbells, skipping a refused lease", 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: ["acme/widgets"] }, STEWARDS)).toEqual({ ok: true }); + await tick(); + expect(w.hooks.subscribes.map((s) => s.watches)).toEqual([[{ kind: "dependabot_repo", id: "acme/widgets" }]]); + // A dependabot_alert doorbell in the leased repository rings stewards; one elsewhere does not. + w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "dependabot_alert", id: "Acme/Widgets#4", unit: "Acme/Widgets" })}\n\n`); + w.hooks.last().send(`event: doorbell\ndata: ${JSON.stringify({ source: "github", kind: "dependabot_alert", id: "Acme/Other#4", unit: "Acme/Other" })}\n\n`); + await tick(3000); + expect(w.rpcs()).toEqual([{ pluginId: "stewards", method: "stewardsRing", input: { source: "github", id: "Acme/Widgets#4" } }]); + // A refused dependabot_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 Dependabot alerts 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 07386cee..e8b0b4bf 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -28,8 +28,10 @@ import { REPO_CHECK_QUERY, TARGET_QUERY, VIEWER_QUERY, + dependabotAlertsPath, graphql, kindName, + parseDependabotAlerts, parseOpenPulls, parseRef, parseRefKey, @@ -68,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()) }); +const interestSchema = z.object({ units: z.array(z.string()), entities: z.array(z.string()), dependabot: z.array(z.string()).default([]) }); type Interest = z.infer; /** How long a token read from gh is reused before gh is asked again. */ @@ -145,6 +147,28 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => return parseTarget(await readTargetPayload(ref, signal)); } + /** + * One REST call with the token, for what GraphQL does not expose: + * Dependabot alerts. A non-2xx answer throws with the status, so a 403 or + * 404 (no alert access, alerts off, not visible) can be told apart from a + * network failure and named per repository by the caller. + */ + async function rest(path: string, signal: AbortSignal): Promise { + return asDeveloper(async (token) => { + const response = await deps.fetch(new URL(path, apiUrl), { + method: "GET", + headers: { accept: "application/vnd.github+json", authorization: `Bearer ${token}`, "user-agent": "bb-plugin-github", "x-github-api-version": "2022-11-28" }, + signal, + }); + const body: unknown = await response.json().catch(() => null); + if (!response.ok) { + const message = body !== null && typeof body === "object" && typeof (body as { message?: unknown }).message === "string" ? (body as { message: string }).message : ""; + throw new GitHubRequestError(`GitHub answered HTTP ${response.status}${message === "" ? "" : `: ${message}`}`, response.status); + } + return body; + }); + } + // ---- watching ----------------------------------------------------------- // // The row is the truth: it carries what the thread last saw, and every @@ -235,15 +259,16 @@ 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: [] }; + let interest: Interest = storedInterest.success ? storedInterest.data : { units: [], entities: [], dependabot: [] }; // 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())); /** Stewards' leases bb-gate-hooks refused, by ` `. */ const refusals = createRefusals(deps.now); - /** Every lease to hold: the watches, then stewards' entities and repositories, each once. */ + /** Every lease to hold: the watches, then stewards' entities, repositories and Dependabot repositories, each once. */ function leases(): Lease[] { const seen = new Set(); const out: Lease[] = []; @@ -256,13 +281,15 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => for (const key of watches.keys()) add("issue", key); 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); return out; } /** Whether stewards cares about a doorbell for this key, in this repository. */ - function interesting(key: string, unit: string | null): boolean { - if (interestEntities.has(key.toLowerCase())) return true; + 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 (interestEntities.has(key.toLowerCase())) return true; return repo !== null && interestRepos.has(repo.toLowerCase()); } @@ -285,7 +312,14 @@ 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()) : interestEntities.has(r.id.toLowerCase())) refusals.add(`${r.kind} ${r.id.toLowerCase()}`, r.reason); + 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); + 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 + // doorbells, and `bb stewards check` says which repos it skips. + 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 === "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; @@ -314,9 +348,9 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => token: accessToken, refreshToken: () => refreshToken("was refused by bb-gate-hooks"), watchIds: leases, - onDoorbell: (key, unit) => { - checks.ring(key); - if (interesting(key, unit)) rings.ring(key); + onDoorbell: (kind, key, unit) => { + if (kind === "issue") checks.ring(key); + if (interesting(kind, key, unit)) rings.ring(key); }, onRejected, sweep, @@ -368,9 +402,14 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => const reason = refused.get(`issue ${key.toLowerCase()}`); if (reason !== undefined) unleased.push({ key, reason: `refused by bb-gate-hooks (${reason})` }); } + for (const repo of interest.dependabot) { + 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` }); + } return { nouns: { unit: ["repository", "repositories"], entity: ["pull request", "pull requests"] }, units: interest.units, + dependabot: [...interest.dependabot].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. @@ -459,24 +498,65 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => return { viewer, entities: entities.slice(0, limit), errors }; }, + // A repository's Dependabot alerts, read with the token through the + // REST API. Each repository the token cannot read (no alert access, + // alerts disabled, not visible) is named in `errors`; the rest are + // still returned. Reading alerts needs more than read access to the + // repository (bb-gate/docs/hooks.md, "Admission, alerts"). + async sourceDependabotAlerts({ units, state }) { + let viewer: string; + try { + viewer = parseViewer(await query(VIEWER_QUERY, {}, checkSignal())); + } catch (error) { + return { viewer: null, alerts: [], errors: [errorMessage(error)] }; + } + const alerts: ReturnType = []; + const errors: string[] = []; + for (const unit of units) { + const repo = parseRepo(unit); + if (repo === null) { + errors.push(`${unit}: not owner/repo`); + continue; + } + const name = `${repo.owner}/${repo.name}`; + try { + alerts.push(...parseDependabotAlerts(await rest(dependabotAlertsPath(name, state ?? "open"), checkSignal()), name)); + } catch (error) { + errors.push(`${unit}: ${errorMessage(error)}`); + } + } + return { viewer, alerts, errors }; + }, + // 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 }, { experimental_caller: caller }) { + async sourceSetInterest({ units, entities, dependabot }, { 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); - if (badUnits.length > 0 || badEntities.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)`)].slice(0, 10).join(", ")}`); + const badDependabot = dependabot.filter((r) => parseRepo(r) === null); + if (badUnits.length > 0 || badEntities.length > 0 || badDependabot.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)`), + ] + .slice(0, 10) + .join(", ")}`, + ); } const before = new Set(leases().map((l) => `${l.kind} ${l.id.toLowerCase()}`)); const next: Interest = { 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()))], }; 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())); announceWatches(); const fresh = leases().filter((l) => !before.has(`${l.kind} ${l.id.toLowerCase()}`)); const lease = (kind: Lease["kind"]) => { @@ -485,6 +565,7 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => }; lease("repo"); lease("issue"); + lease("dependabot_repo"); return { ok: true }; }, }); diff --git a/plugins/github-watcher/source-contract.ts b/plugins/github-watcher/source-contract.ts index 3ed7a034..ba95c6ee 100644 --- a/plugins/github-watcher/source-contract.ts +++ b/plugins/github-watcher/source-contract.ts @@ -155,6 +155,39 @@ export const adoptableEntitySchema = z.object({ }); export type AdoptableEntity = z.infer; +// ---- Dependabot alerts ------------------------------------------------------- + +/** The four Dependabot severities, as GitHub reports them. */ +export const DEPENDABOT_SEVERITIES = ["critical", "high", "medium", "low"] as const; +export type DependabotSeverity = (typeof DEPENDABOT_SEVERITIES)[number]; + +/** + * One Dependabot alert, as the github plugin reads it from + * `GET /repos/{owner}/{repo}/dependabot/alerts` (which needs the token's + * alert access, not just read access to the repository). The entity id + * doorbells carry is "owner/repo#", which is the alert's own + * numbering, unrelated to the issue numbering. `repo` is spelled as GitHub + * does, which is what the doorbell carries and the github plugin leases. + */ +export const dependabotAlertSchema = z.object({ + id: z.string(), + repo: z.string(), + number: z.number().int().positive(), + severity: z.enum(DEPENDABOT_SEVERITIES), + package: z.string(), + ecosystem: z.string(), + manifestPath: z.string().nullable(), + /** open, fixed, dismissed, auto_dismissed. */ + state: z.string(), + ghsaId: z.string().nullable(), + fixedVersion: z.string().nullable(), + summary: z.string().nullable(), + url: z.string().nullable(), + createdAt: z.string().nullable(), + updatedAt: z.string().nullable(), +}); +export type DependabotAlert = z.infer; + /** Served by linear and by github; stewards is the only caller. */ export const sourceContract = { /** One entity, by Linear key or UUID, or by GitHub "owner/repo#12". Null when it does not exist or is not visible. */ @@ -211,14 +244,38 @@ export const sourceContract = { * previous set. The source leases them on bb-gate-hooks and rings stewards * for every doorbell that names one of the entities or falls in one of the * units. Only stewards may call it. + * + * `dependabot` names repositories whose Dependabot alert doorbells stewards + * 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. */ 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([]), }), output: z.object({ ok: z.boolean() }), }, + /** + * A repository's Dependabot alerts, for stewards' dependency watches. The + * github plugin reads them with the developer's token from the REST API; + * each repository the token cannot read (no alert access, alerts disabled, + * not visible) is named in `errors` rather than failing the whole call. + */ + sourceDependabotAlerts: { + input: z.object({ + units: z.array(z.string().min(1).max(200)).max(100), + /** GitHub's alert state: open (the default), fixed, dismissed, auto_dismissed. */ + state: z.string().min(1).max(60).optional(), + }), + output: z.object({ + viewer: z.string().nullable(), + alerts: z.array(dependabotAlertSchema), + errors: z.array(z.string()), + }), + }, } as const; // ---- what stewards serves --------------------------------------------------- diff --git a/plugins/github-watcher/usage.test.ts b/plugins/github-watcher/usage.test.ts index 3f1bb4bd..c96c1f3c 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: [], entities: [], unleased: [] }; +const none: InterestView = { nouns: { unit: ["team", "teams"], entity: ["issue", "issues"] }, units: [], dependabot: [], 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 8b26d21c..16cc43e8 100644 --- a/plugins/github-watcher/usage.ts +++ b/plugins/github-watcher/usage.ts @@ -73,6 +73,8 @@ export const interestViewSchema = z.object({ nouns: z.object({ unit: nounSchema, entity: nounSchema }), /** As a person names them. */ units: z.array(z.string()), + /** Repositories whose Dependabot alerts are leased, separate from `units`. */ + dependabot: 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() })), @@ -174,9 +176,10 @@ 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.unleased.length === 0) return ["Stewards: nothing asked for."]; + if (i.units.length === 0 && i.entities.length === 0 && (i.dependabot ?? []).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.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/server.test.ts b/plugins/linear/server.test.ts index f3641450..96967947 100644 --- a/plugins/linear/server.test.ts +++ b/plugins/linear/server.test.ts @@ -405,10 +405,10 @@ describe("tools", () => { expect(linear.calls.at(-1)!.body!.variables).toEqual({ id: "uuid-1", input: { stateId: "s-done", assigneeId: "u1" } }); // Handing it back: unassign, relabel, reprioritize. Labels are the issue's current set, minus removed, plus added. - expect(text(await tool("linear_update_issue", { key: "ENG-123", assignee: "Nobody", removeLabels: ["BUILD-READY"], addLabels: ["agent", "workspace"], priority: "high" }))).toBe( - "ENG-123: unassigned; labels bug, agent, ws; priority high.", + expect(text(await tool("linear_update_issue", { key: "ENG-123", assignee: "Nobody", removeLabels: ["BUILD-READY"], addLabels: ["agent", "workspace"], priority: "high", dueDate: "2026-10-20" }))).toBe( + "ENG-123: unassigned; labels bug, agent, ws; priority high; due 2026-10-20.", ); - expect(lastInput).toEqual({ assigneeId: null, labelIds: ["l-bug", "l-agent", "l-ws"], priority: 2 }); + expect(lastInput).toEqual({ assigneeId: null, labelIds: ["l-bug", "l-agent", "l-ws"], priority: 2, dueDate: "2026-10-20" }); // A person by email. expect(text(await tool("linear_update_issue", { key: "ENG-123", assignee: "bob@acme.test" }))).toBe("ENG-123: assigned to Bob."); @@ -450,11 +450,11 @@ describe("tools", () => { }, }); - const out = text(await tool("linear_create_issue", { team: "eng", title: "Add retries", description: "Calls fail once in a while.", state: "todo", labels: ["bug", "infra"], assignee: "me", priority: "high", parent: "ENG-123" })); + const out = text(await tool("linear_create_issue", { team: "eng", title: "Add retries", description: "Calls fail once in a while.", state: "todo", labels: ["bug", "infra"], assignee: "me", priority: "high", dueDate: "2026-11-01", parent: "ENG-123" })); expect(out).toBe("Filed ENG-124: Add retries\nhttps://linear.app/acme/issue/ENG-124"); const mutation = linear.calls.find((c) => c.body?.query.startsWith("mutation($input: IssueCreateInput!)"))!; const input = mutation.body!.variables!.input as Record; - expect(input).toMatchObject({ teamId: "t-eng", title: "Add retries", stateId: "s-todo", labelIds: ["l-bug", "l-infra"], assigneeId: "u1", priority: 2, parentId: "uuid-1" }); + expect(input).toMatchObject({ teamId: "t-eng", title: "Add retries", stateId: "s-todo", labelIds: ["l-bug", "l-infra"], assigneeId: "u1", priority: 2, dueDate: "2026-11-01", parentId: "uuid-1" }); expect(input.description).toMatch(/^Calls fail once in a while\.\n\n_— from bb thread .+_$/u); // Without a description the signature is the description. diff --git a/plugins/linear/server.ts b/plugins/linear/server.ts index be0816de..5c04a017 100644 --- a/plugins/linear/server.ts +++ b/plugins/linear/server.ts @@ -605,6 +605,11 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => sourceSnapshot: ({ id }) => sourceSnapshot(id), sourceValidate: (input) => sourceValidate(input), sourceAdoptable: (input) => sourceAdoptable(input), + // Dependabot alerts are a GitHub thing; linear has none. Stewards only + // asks github, so this is a plain answer rather than a throw. + async sourceDependabotAlerts() { + return { viewer: null, alerts: [], errors: ["Dependabot alerts 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. @@ -803,7 +808,7 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => bb.agents.registerTool({ name: "linear_update_issue", description: - "Change a Linear issue: its workflow state (for example In Progress, Done), assignee ('me' for the connected user, a name or email, or 'nobody' to clear), labels to add or remove, priority, and description. Give only the fields to change; they are applied together. A new description replaces the whole old one and is signed with this thread's id (do not sign it yourself); read the issue first and keep what still holds. A state, label or person that does not match is an error that lists the choices.", + "Change a Linear issue: its workflow state (for example In Progress, Done), assignee ('me' for the connected user, a name or email, or 'nobody' to clear), labels to add or remove, priority, due date, and description. Give only the fields to change; they are applied together. A new description replaces the whole old one and is signed with this thread's id (do not sign it yourself); read the issue first and keep what still holds. A state, label or person that does not match is an error that lists the choices.", presentation: { label: { pending: "Updating a Linear issue", completed: "Updated a Linear issue" } }, parameters: z .object({ @@ -813,12 +818,13 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => addLabels: z.array(z.string().trim().min(1).max(100)).max(20).optional().describe("Label names to add, matched ignoring case."), removeLabels: z.array(z.string().trim().min(1).max(100)).max(20).optional().describe("Label names to remove, matched ignoring case."), priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional().describe("The priority."), + dueDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/u, "a date such as 2026-10-20").optional().describe("The issue's due date, as YYYY-MM-DD."), description: z.string().trim().min(1).max(50_000).optional().describe("The whole new description, in Markdown. Replaces the old one."), account: accountParam, }) .refine( - (v) => v.state !== undefined || v.assignee !== undefined || (v.addLabels?.length ?? 0) > 0 || (v.removeLabels?.length ?? 0) > 0 || v.priority !== undefined || v.description !== undefined, - { message: "Give at least one of state, assignee, addLabels, removeLabels, priority or description." }, + (v) => v.state !== undefined || v.assignee !== undefined || (v.addLabels?.length ?? 0) > 0 || (v.removeLabels?.length ?? 0) > 0 || v.priority !== undefined || v.dueDate !== undefined || v.description !== undefined, + { message: "Give at least one of state, assignee, addLabels, removeLabels, priority, dueDate or description." }, ), async execute(input, { threadId, signal }) { try { @@ -863,6 +869,7 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => } if (input.priority !== undefined) update.priority = PRIORITIES[input.priority]; + if (input.dueDate !== undefined) update.dueDate = input.dueDate; if (input.description !== undefined) update.description = signed(input.description, threadId); const updated = parseIssueUpdate(await query(where.key, ISSUE_UPDATE, { id: ref.id, input: update }, signal)); @@ -870,6 +877,7 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => if (input.assignee !== undefined) changed.push(updated.assignee === null ? "unassigned" : `assigned to ${updated.assignee}`); if (update.labelIds !== undefined) changed.push(updated.labels.length === 0 ? "no labels" : `labels ${updated.labels.join(", ")}`); if (input.priority !== undefined) changed.push(`priority ${updated.priority === null ? input.priority : (PRIORITY_NAMES[updated.priority] ?? String(updated.priority))}`); + if (input.dueDate !== undefined) changed.push(`due ${input.dueDate}`); if (input.description !== undefined) changed.push("description replaced"); return `${updated.identifier}: ${changed.join("; ")}.`; } catch (error) { @@ -881,7 +889,7 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => bb.agents.registerTool({ name: "linear_create_issue", description: - "File a new Linear issue in a team, as the connected user. Give the team key and a title; optionally a Markdown description, a state name, an assignee ('me' for the connected user), label names, a priority, and a parent issue key. The description is signed with this thread's id; do not sign it yourself. Returns the new issue's key and URL.", + "File a new Linear issue in a team, as the connected user. Give the team key and a title; optionally a Markdown description, a state name, an assignee ('me' for the connected user), label names, a priority, a due date, and a parent issue key. The description is signed with this thread's id; do not sign it yourself. Returns the new issue's key and URL.", presentation: { label: { pending: "Filing a Linear issue", completed: "Filed a Linear issue" } }, parameters: z.object({ team: z.string().trim().min(1).max(20).describe("The team key, such as ENG."), @@ -891,6 +899,7 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => assignee: z.string().trim().max(100).optional().describe("A person's name or email, or 'me'."), labels: z.array(z.string().trim().min(1).max(100)).max(20).optional().describe("Label names, matched ignoring case."), priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional().describe("The priority."), + dueDate: z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/u, "a date such as 2026-10-20").optional().describe("The issue's due date, as YYYY-MM-DD."), parent: issueKey.optional().describe("The parent issue's key, to file this as a sub-issue."), account: accountParam, }), @@ -932,6 +941,7 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => } if (input.priority !== undefined) create.priority = PRIORITIES[input.priority]; + if (input.dueDate !== undefined) create.dueDate = input.dueDate; if (input.parent !== undefined) { const parent = parseIssueRef(await query(where.key, ISSUE_REF_QUERY, { id: input.parent }, signal)); diff --git a/plugins/linear/source-contract.ts b/plugins/linear/source-contract.ts index 3ed7a034..ba95c6ee 100644 --- a/plugins/linear/source-contract.ts +++ b/plugins/linear/source-contract.ts @@ -155,6 +155,39 @@ export const adoptableEntitySchema = z.object({ }); export type AdoptableEntity = z.infer; +// ---- Dependabot alerts ------------------------------------------------------- + +/** The four Dependabot severities, as GitHub reports them. */ +export const DEPENDABOT_SEVERITIES = ["critical", "high", "medium", "low"] as const; +export type DependabotSeverity = (typeof DEPENDABOT_SEVERITIES)[number]; + +/** + * One Dependabot alert, as the github plugin reads it from + * `GET /repos/{owner}/{repo}/dependabot/alerts` (which needs the token's + * alert access, not just read access to the repository). The entity id + * doorbells carry is "owner/repo#", which is the alert's own + * numbering, unrelated to the issue numbering. `repo` is spelled as GitHub + * does, which is what the doorbell carries and the github plugin leases. + */ +export const dependabotAlertSchema = z.object({ + id: z.string(), + repo: z.string(), + number: z.number().int().positive(), + severity: z.enum(DEPENDABOT_SEVERITIES), + package: z.string(), + ecosystem: z.string(), + manifestPath: z.string().nullable(), + /** open, fixed, dismissed, auto_dismissed. */ + state: z.string(), + ghsaId: z.string().nullable(), + fixedVersion: z.string().nullable(), + summary: z.string().nullable(), + url: z.string().nullable(), + createdAt: z.string().nullable(), + updatedAt: z.string().nullable(), +}); +export type DependabotAlert = z.infer; + /** Served by linear and by github; stewards is the only caller. */ export const sourceContract = { /** One entity, by Linear key or UUID, or by GitHub "owner/repo#12". Null when it does not exist or is not visible. */ @@ -211,14 +244,38 @@ export const sourceContract = { * previous set. The source leases them on bb-gate-hooks and rings stewards * for every doorbell that names one of the entities or falls in one of the * units. Only stewards may call it. + * + * `dependabot` names repositories whose Dependabot alert doorbells stewards + * 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. */ 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([]), }), output: z.object({ ok: z.boolean() }), }, + /** + * A repository's Dependabot alerts, for stewards' dependency watches. The + * github plugin reads them with the developer's token from the REST API; + * each repository the token cannot read (no alert access, alerts disabled, + * not visible) is named in `errors` rather than failing the whole call. + */ + sourceDependabotAlerts: { + input: z.object({ + units: z.array(z.string().min(1).max(200)).max(100), + /** GitHub's alert state: open (the default), fixed, dismissed, auto_dismissed. */ + state: z.string().min(1).max(60).optional(), + }), + output: z.object({ + viewer: z.string().nullable(), + alerts: z.array(dependabotAlertSchema), + errors: z.array(z.string()), + }), + }, } as const; // ---- what stewards serves --------------------------------------------------- diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index d8c225a1..86081c33 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -869,6 +869,63 @@ The rules that hold: names the user, the owner or a human with no open needs item is refused and told to file one, so the ask reaches the page instead of only the prose. +## 19. Dependency stewards + +Nothing kept dependencies current: a vulnerable or stale package was +noticed by a person reading a build log, or not at all. GitHub does the +scanning, and the stewards turn its findings into tickets. Two kinds of +binding do it. + +```jsonc +"deps": { + "sla": { "critical": "asap", "high": "1d", "medium": "7d", "low": "30d" }, + "autoAdopt": ["critical", "high"], + "batch": { "medium": "7d", "low": "30d" } +} +``` + +- **Dependabot alerts are an `ops` target kind**, `{ "kind": "dependabot", + "repo": "owner/repo" }`. The default is every repo in `repos.json` not in + `github.exclude`; the project file may list explicit targets instead. The + binding's key is `dependabot/owner/repo`, it runs the `deps-alerts` + playbook, and it is woken by the `dependabot_alert` doorbell rather than a + look interval. +- **The github plugin reads the alerts** with the developer's token from + `GET /repos/{owner}/{repo}/dependabot/alerts`, through the shared + `sourceDependabotAlerts` RPC. It leases each watched repo as a + `dependabot_repo` (a plain `repo` lease does not receive alert doorbells) + and rings stewards for each `dependabot_alert` doorbell. Reading alerts + needs the token's alert access; a `rejected: forbidden` lease is a skip, + not an error, and `bb stewards check` says which repos are skipped. +- **Severity maps onto priority and the deadline.** critical → urgent and + due now, high → high and due in a day, and so on. `asap` escalates at + once rather than waiting for the adopt pass. The alert's fingerprint is + `owner/repo#` (the alert's own numbering), recorded in the + ops fingerprint map so a recurrence is a comment, never a second ticket. +- **critical and high get their own ticket; medium and low coalesce** into + one open ticket per repo per ecosystem. A new alert joins that ticket + when its due date is inside the new alert's deadline, and otherwise + tightens the ticket's due date to the new deadline. The plugin computes + the plan (`new`, `join` or `tighten`) from the fingerprint map and gives + it to the steward in the wake; the steward files or comments. +- **A fixed or dismissed alert leaves the open list**, the look says so, + and the steward trims it from its ticket or moves the ticket to Done when + nothing is left. +- **The nightly pass re-lists every watched repo's open alerts**, so a + missed doorbell costs a night, not a deadline. +- **`deps-prs` adopts the bot's version-update pull requests.** A + `dependabot[bot]` pull request in a watched repo gets a `pr` binding under + the `deps-prs` playbook whether or not it is labelled. It reviews the bump + and escalates for a human merge; it never merges. A patch or minor bump + with green checks is escalated for a merge, and a major bump or anything + touching an owner-reviewed path is escalated with the reason. + +`bb stewards init` writes `deps-alerts.md` and `deps-prs.md`; a project +that has not written them runs no dependency watch, which is how the feature +is off until it is wanted. The dependency watch's targets are derived from +the repo set, so a repo added to `repos.json` is watched without a second +edit. + ## Known limits - **Multi-repo projects only.** A bb project whose source is a single diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 328f4801..3811adf9 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -40,6 +40,21 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. same; the developer's own rights are broad, so that is a convention, not a wall. Until kubectl can read a target, its binding waits and `bb stewards check` says "cannot read the target". DESIGN.md §18. +- **Dependency stewards.** GitHub scans; the stewards turn Dependabot alerts + into tickets. Every repo in `repos.json` not in `github.exclude` (or the + explicit `{ kind: "dependabot", repo }` targets in `ops.targets`) gets an + `ops` binding that runs `deps-alerts` and is woken by the + `dependabot_alert` doorbell; the github plugin reads the alerts with the + developer's token and leases each repo as a `dependabot_repo` (a `repo` + lease does not receive alert doorbells). Severity sets the Linear priority + and a due date from `deps.sla`; critical and high get their own ticket, + medium and low coalesce into one open ticket per repo per ecosystem, and a + new alert joins or tightens it. A fixed or dismissed alert trims or closes + its ticket, and the nightly pass re-lists open alerts as the backstop. A + `dependabot[bot]` version-update pull request is adopted under `deps-prs`, + reviewed, and escalated for a human merge; it is never merged. Reading + alerts needs the token's alert access; a server whose login cannot read + them skips the targets, and `bb stewards check` says which. DESIGN.md §19. - **The reconcile loop.** linear and github-watcher hold bb-gate-hooks leases for the project's teams and repos and for every bound entity, and ring this plugin on a doorbell. A ring is debounced, the entity is snapshotted, compared with @@ -198,6 +213,8 @@ stewards/ github-prs.md github-reviews.md ops-watch.md no phases; ## New, ## Recurring and ## Returned sections + deps-alerts.md the Dependabot alert side: file, batch, tighten, close + deps-prs.md adopts dependabot[bot] pull requests; escalates, never merges ``` `bb stewards init` writes starting points ([templates.ts](templates.ts)); @@ -212,7 +229,16 @@ first of `linear.teams` by default, and it must be one of them) and `context` (the kubeconfig context kubectl uses; the machine's current one when left out) and `autoAdopt` (Linear priorities, `urgent`, `high`, `medium`, `low`, whose tickets the ops steward labels for a steward itself when it files them). -`ops-watch.md` is read only when `ops.targets` lists something. +`ops-watch.md` is read only when `ops.targets` lists a k8s namespace. + +The `deps` object is the dependency watch: `sla` (a duration or `asap` per +severity; critical→urgent, high→high, medium→medium, low→low), `batch` (the +window a medium or low alert may wait for company), and `autoAdopt` (the +severities whose tickets are labelled and moved to Todo when filed). +`deps-alerts.md` and `deps-prs.md` are optional: a project that has not +written them runs no dependency watch. `bb stewards init` writes them, and +`bb stewards check` validates `deps.sla`, `deps.batch` and `deps.autoAdopt` +and reports each repo whose alerts the `gh` login cannot read. Playbook front matter: `name`, `kind` (`ticket`, `pr`, `review`, `ops`), `source` (`linear`, `github`, or `k8s` for `ops`), `phases` (state → `{ stage, diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 64afdb23..b259d2bb 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { isTerminal, opsTeam, usesKind, modelSpecSchema, parsePlaybook, parseProjectFile, phaseInstructions, phaseOf, playbookStates } from "./config.js"; -import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, projectFileTemplate } from "./templates.js"; +import { depsTargets, isTerminal, k8sTargets, opsTeam, usesKind, modelSpecSchema, parsePlaybook, parseProjectFile, phaseInstructions, phaseOf, playbookStates } from "./config.js"; +import { DEPS_ALERTS, DEPS_PRS, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, projectFileTemplate } from "./templates.js"; describe("the project file", () => { it("parses the template with defaults filled in", () => { @@ -27,6 +27,25 @@ describe("the project file", () => { if (!repo.ok) expect(repo.error).toMatch(/github\.exclude\.0: a repo such as acme\/web/u); else expect.fail("a URL is not owner/repo"); }); + + it("fills the dependency watch's SLA, batch and autoAdopt defaults, and takes explicit values", () => { + const defaults = parseProjectFile(JSON.stringify({ version: 1 })); + if (!defaults.ok) throw new Error(defaults.error); + expect(defaults.value.deps).toEqual({ sla: { critical: "asap", high: 86_400_000, medium: 7 * 86_400_000, low: 30 * 86_400_000 }, batch: { medium: 7 * 86_400_000, low: 30 * 86_400_000 }, autoAdopt: ["critical", "high"] }); + + const explicit = parseProjectFile(JSON.stringify({ version: 1, deps: { sla: { high: "2d" }, batch: { medium: "3d" }, autoAdopt: ["critical"] } })); + if (!explicit.ok) throw new Error(explicit.error); + expect(explicit.value.deps.sla).toEqual({ critical: "asap", high: 2 * 86_400_000, medium: 7 * 86_400_000, low: 30 * 86_400_000 }); + expect(explicit.value.deps.batch).toEqual({ medium: 3 * 86_400_000, low: 30 * 86_400_000 }); + expect(explicit.value.deps.autoAdopt).toEqual(["critical"]); + + const badSeverity = parseProjectFile(JSON.stringify({ version: 1, deps: { autoAdopt: ["catastrophic"] } })); + expect(badSeverity).toMatchObject({ ok: false }); + if (!badSeverity.ok) expect(badSeverity.error).toMatch(/deps\.autoAdopt\.0/u); + const badDuration = parseProjectFile(JSON.stringify({ version: 1, deps: { sla: { high: "soon" } } })); + expect(badDuration).toMatchObject({ ok: false }); + if (!badDuration.ok) expect(badDuration.error).toMatch(/deps\.sla\.high/u); + }); }); describe("ops in the project file", () => { @@ -51,6 +70,20 @@ describe("ops in the project file", () => { expect(r.ok && r.value.ops.autoAdopt).toEqual([]); }); + it("takes a dependabot target, and derives deps targets from the repo set when none is listed", () => { + const r = file({ targets: [{ kind: "dependabot", repo: "acme/web" }] }); + if (!r.ok) throw new Error(r.error); + expect(r.value.ops.targets).toEqual([{ kind: "dependabot", repo: "acme/web" }]); + expect(depsTargets(r.value, ["acme/other"])).toEqual([{ kind: "dependabot", repo: "acme/web" }]); + expect(k8sTargets(r.value)).toEqual([]); + // No explicit dependabot target: every repo in the set. + const d = file({ targets: [{ kind: "k8s-namespace", name: "prod" }] }); + if (!d.ok) throw new Error(d.error); + expect(depsTargets(d.value, ["acme/web", "acme/other"])).toEqual([{ kind: "dependabot", repo: "acme/web" }, { kind: "dependabot", repo: "acme/other" }]); + expect(k8sTargets(d.value)).toEqual([{ kind: "k8s-namespace", name: "prod" }]); + expect(error({ targets: [{ kind: "dependabot", repo: "not a repo" }] })).toMatch(/ops\.targets\.0\.repo/u); + }); + it("refuses what would watch nothing or file where nobody stewards", () => { expect(error({ targets: [{ kind: "k8s-namespace", name: "Prod_1" }] })).toMatch(/ops\.targets\.0\.name: a namespace name/u); expect(error({ targets: [{ kind: "pod", name: "prod" }] })).toMatch(/ops\.targets\.0\.kind/u); @@ -147,7 +180,7 @@ describe("the ops playbook", () => { const phased = OPS_WATCH.replace("may:", "phases:\n open: {}\nmay:"); expect(parsePlaybook(phased, "ops-watch")).toMatchObject({ ok: false, error: expect.stringMatching(/an ops playbook has no phases/u) }); expect(parsePlaybook(OPS_WATCH.replace("may:", "terminal: [Done]\nmay:"), "ops-watch")).toMatchObject({ ok: false }); - expect(parsePlaybook(OPS_WATCH.replace("source: k8s", "source: linear"), "ops-watch")).toMatchObject({ ok: false, error: expect.stringMatching(/an ops playbook reads k8s/u) }); + expect(parsePlaybook(OPS_WATCH.replace("source: k8s", "source: linear"), "ops-watch")).toMatchObject({ ok: false, error: expect.stringMatching(/an ops playbook watches k8s or github/u) }); expect(parsePlaybook(GITHUB_PRS.replace("terminal: [merged, closed]\n", ""), "github-prs")).toMatchObject({ ok: false, error: expect.stringMatching(/terminal: name at least one state/u) }); // A ticket, pr or review playbook still needs its phases, as before ops. const noPhases = GITHUB_PRS.replace(/phases:\n(?: {2}.*\n)+/u, ""); @@ -156,6 +189,31 @@ describe("the ops playbook", () => { }); }); +describe("the dependency playbooks", () => { + it("parses deps-alerts as an ops playbook and deps-prs as a pr playbook", () => { + const alerts = parsePlaybook(DEPS_ALERTS, "deps-alerts"); + if (!alerts.ok) throw new Error(alerts.error); + expect(alerts.value).toMatchObject({ kind: "ops", source: "github", phases: {}, terminal: [], ready: null }); + expect(phaseInstructions(alerts.value, "new")).toMatch(/File one ticket per problem/u); + expect(phaseInstructions(alerts.value, "recurring")).toMatch(/File nothing new/u); + expect(alerts.value.general).toMatch(/Fingerprint: `#`/u); + expect(alerts.value.general).toMatch(/batch plan/u); + + const prs = parsePlaybook(DEPS_PRS, "deps-prs"); + if (!prs.ok) throw new Error(prs.error); + expect(prs.value).toMatchObject({ kind: "pr", source: "github", terminal: ["merged", "closed"] }); + expect(prs.value.general).toMatch(/never merge/u); + expect(prs.value.general).toMatch(/patch or minor bump whose checks are green is escalated for a\s+human merge/u); + expect(prs.value.general).toMatch(/major bump/u); + expect(prs.value.general).toMatch(/owner-reviewed/u); + expect(prs.value.skipAuthors).toEqual(expect.arrayContaining(["dependabot[bot]"])); + }); + + it("keeps the deps playbooks in the init templates", () => { + expect(projectFileTemplate(["ENG"])).toContain('"deps"'); + }); +}); + describe("model specs", () => { it("takes a model id with slashes, and the level only when the last part names one", () => { const parse = (text: string) => modelSpecSchema.parse(text); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index 9a307048..ecff5400 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -7,7 +7,8 @@ import { createHash } from "node:crypto"; import { parse as parseYaml } from "yaml"; import { z } from "zod"; -import type { OpsTarget } from "./ops.js"; +import type { DependabotTarget, K8sTarget, OpsTarget } from "./ops.js"; +import { DEPENDABOT_SEVERITIES } from "./source-contract.js"; export const STEWARDS_DIR = "stewards"; export const PROJECT_FILE = `${STEWARDS_DIR}/project.json`; @@ -89,6 +90,10 @@ export type BindingKind = (typeof KINDS)[number]; export const DEFAULT_PLAYBOOKS: Record = { ticket: "linear-tickets", pr: "github-prs", review: "github-reviews", ops: "ops-watch" }; +/** The playbooks the dependency watch uses: one for alert targets, one for the bot's pull requests. */ +export const DEPS_ALERTS_PLAYBOOK = "deps-alerts"; +export const DEPS_PRS_PLAYBOOK = "deps-prs"; + const playbookName = z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/u, "a playbook name: lowercase letters, digits and dashes"); function validTimezone(tz: string): boolean { @@ -105,13 +110,45 @@ const teamKey = z.string().trim().regex(/^[A-Za-z][A-Za-z0-9]*$/u, "a team key s /** Linear's priorities, as `ops.autoAdopt` names them. */ export const LINEAR_PRIORITIES = ["urgent", "high", "medium", "low"] as const; -const opsTargetSchema = z +const k8sNamespaceTargetSchema = z .object({ kind: z.literal("k8s-namespace"), name: z.string().trim().regex(/^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$/u, "a namespace name such as bb-gate-production"), }) .strict(); +/** A repository whose Dependabot alerts an ops steward watches. */ +export const dependabotRepoSchema = z.string().trim().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u, "a repo such as acme/web"); + +const dependabotTargetSchema = z.object({ kind: z.literal("dependabot"), repo: dependabotRepoSchema }).strict(); + +const opsTargetSchema = z.discriminatedUnion("kind", [k8sNamespaceTargetSchema, dependabotTargetSchema]); + +/** The per-severity SLA and batch window for Dependabot alerts. */ +const slaValueSchema = z.union([z.literal("asap"), durationSchema]); + +export const depsSchema = z + .object({ + sla: z + .object({ + critical: slaValueSchema.default("asap"), + high: slaValueSchema.default(86_400_000), + medium: slaValueSchema.default(7 * 86_400_000), + low: slaValueSchema.default(30 * 86_400_000), + }) + .strict() + .default({ critical: "asap", high: 86_400_000, medium: 7 * 86_400_000, low: 30 * 86_400_000 }), + batch: z + .object({ medium: durationSchema.default(7 * 86_400_000), low: durationSchema.default(30 * 86_400_000) }) + .strict() + .default({ medium: 7 * 86_400_000, low: 30 * 86_400_000 }), + /** Severities whose tickets are labelled and moved to Todo when filed, without an escalation. */ + autoAdopt: z.array(z.enum(DEPENDABOT_SEVERITIES)).max(4).default(["critical", "high"]), + }) + .strict() + .default({ sla: { critical: "asap", high: 86_400_000, medium: 7 * 86_400_000, low: 30 * 86_400_000 }, batch: { medium: 7 * 86_400_000, low: 30 * 86_400_000 }, autoAdopt: ["critical", "high"] }); +export type DepsConfig = z.infer; + export const projectFileSchema = z .object({ version: z.literal(1), @@ -134,8 +171,18 @@ export const projectFileSchema = z .strict() .default({ at: "01:00", timezone: "America/New_York", until: "02:45", max: 100 }), projectSteward: z.object({ model: modelSpecSchema.optional() }).strict().default({}), - /** Which playbook governs each kind of binding. */ - playbooks: z.object({ ticket: playbookName.optional(), pr: playbookName.optional(), review: playbookName.optional(), ops: playbookName.optional() }).strict().default({}), + /** Which playbook governs each kind of binding, and the two the dependency watch uses. */ + playbooks: z + .object({ + ticket: playbookName.optional(), + pr: playbookName.optional(), + review: playbookName.optional(), + ops: playbookName.optional(), + [DEPS_ALERTS_PLAYBOOK]: playbookName.optional(), + [DEPS_PRS_PLAYBOOK]: playbookName.optional(), + }) + .strict() + .default({}), /** Reviews: on unless turned off. */ reviews: z.object({ enabled: z.boolean().default(true) }).strict().default({ enabled: true }), adoption: z.object({ perPass: z.number().int().min(1).max(100).default(10) }).strict().default({ perPass: 10 }), @@ -162,12 +209,14 @@ export const projectFileSchema = z }) .strict() .default({ targets: [], autoAdopt: [] }), + /** The dependency watch: per-severity SLA, the batch window, and what auto-adopts. */ + deps: depsSchema, }) .strict() .superRefine((file, ctx) => { const seen = new Set(); file.ops.targets.forEach((t, i) => { - const key = `${t.kind}/${t.name}`; + const key = t.kind === "k8s-namespace" ? `${t.kind}/${t.name}` : `${t.kind}/${t.repo.toLowerCase()}`; if (seen.has(key)) ctx.addIssue({ code: "custom", path: ["ops", "targets", i], message: `${key} is listed twice` }); seen.add(key); }); @@ -202,6 +251,23 @@ export const usesKind = (project: ProjectFile, kind: BindingKind): boolean => (k export const opsTargets = (project: ProjectFile): OpsTarget[] => project.ops.targets; +/** The k8s namespaces to watch, which are read with kubectl. */ +export const k8sTargets = (project: ProjectFile): K8sTarget[] => project.ops.targets.filter((t): t is K8sTarget => t.kind === "k8s-namespace"); + +/** + * The Dependabot alert targets: the project file's explicit `dependabot` + * targets, or every repo in `repos.json` not in `github.exclude` when it + * lists none. `repos` is the project's derived repo set. + */ +export function depsTargets(project: ProjectFile, repos: readonly string[]): DependabotTarget[] { + const explicit = project.ops.targets.filter((t): t is DependabotTarget => t.kind === "dependabot").map((t) => t.repo); + return (explicit.length > 0 ? explicit : [...repos]).map((repo) => ({ kind: "dependabot" as const, repo })); +} + +/** The playbook a binding runs under: the deps-alerts one for a Dependabot target, else its kind's. */ +export const depsAlertsPlaybookName = (project: ProjectFile): string => project.playbooks[DEPS_ALERTS_PLAYBOOK] ?? DEPS_ALERTS_PLAYBOOK; +export const depsPrsPlaybookName = (project: ProjectFile): string => project.playbooks[DEPS_PRS_PLAYBOOK] ?? DEPS_PRS_PLAYBOOK; + /** The Linear team an ops steward files in. */ export const opsTeam = (project: ProjectFile): string | null => project.ops.team ?? project.linear.teams[0] ?? null; @@ -299,7 +365,15 @@ export function parsePlaybook(text: string, expectedName: string): Parsed 0 || fm.terminal.length > 0 || fm.ready !== undefined || fm.promote !== undefined) { diff --git a/plugins/stewards/deps.test.ts b/plugins/stewards/deps.test.ts new file mode 100644 index 00000000..69b5d788 --- /dev/null +++ b/plugins/stewards/deps.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_BATCH, DEFAULT_SLA, alertFingerprint, alertLine, batchAlert, deadlineAt, dueDate, isBatchable, priorityFor, sightingOf } from "./deps.js"; +import type { DependabotAlert } from "./source-contract.js"; + +const alert = (over: Partial = {}): DependabotAlert => ({ + id: "acme/web#4", + repo: "acme/web", + number: 4, + severity: "high", + package: "lodash", + ecosystem: "npm", + manifestPath: "package-lock.json", + state: "open", + ghsaId: "GHSA-xxxx-yyyy-zzzz", + fixedVersion: "4.17.21", + summary: "Prototype pollution", + url: "https://github.com/acme/web/security/dependabot/4", + createdAt: "2026-10-01T00:00:00Z", + updatedAt: "2026-10-01T00:00:00Z", + ...over, +}); + +const now = Date.parse("2026-10-14T15:00:00Z"); + +describe("severity and the SLA", () => { + it("maps each severity to its Linear priority", () => { + expect(priorityFor("critical")).toBe("urgent"); + expect(priorityFor("high")).toBe("high"); + expect(priorityFor("medium")).toBe("medium"); + expect(priorityFor("low")).toBe("low"); + }); + + it("makes asap due now and a duration due first-seen plus the SLA", () => { + expect(deadlineAt("critical", DEFAULT_SLA, now)).toBe(now); + expect(deadlineAt("high", DEFAULT_SLA, now)).toBe(now + 86_400_000); + expect(deadlineAt("medium", DEFAULT_SLA, now)).toBe(now + 7 * 86_400_000); + expect(deadlineAt("low", DEFAULT_SLA, now)).toBe(now + 30 * 86_400_000); + expect(dueDate(now + 86_400_000)).toBe("2026-10-15"); + }); + + it("batches only medium and low", () => { + expect(isBatchable("critical")).toBe(false); + expect(isBatchable("high")).toBe(false); + expect(isBatchable("medium")).toBe(true); + expect(isBatchable("low")).toBe(true); + }); +}); + +describe("batching", () => { + const low = { repo: "acme/web", ecosystem: "npm", severity: "low" as const }; + const medium = { ...low, severity: "medium" as const }; + + it("gives a critical or high alert a ticket of its own", () => { + const open = [{ ticketKey: "ENG-1", repo: "acme/web", ecosystem: "npm", dueAt: now + 30 * 86_400_000 }]; + expect(batchAlert({ ...low, severity: "critical" }, now, open)).toEqual({ kind: "new" }); + expect(batchAlert({ ...low, severity: "high" }, now, open)).toEqual({ kind: "new" }); + }); + + it("joins an open ticket whose due date is inside the new alert's deadline", () => { + const due = now + 30 * 86_400_000; + const open = [{ ticketKey: "ENG-1", repo: "acme/web", ecosystem: "npm", dueAt: due }]; + // The second low alert has the same deadline: the ticket is already as urgent. + expect(batchAlert(low, due, open)).toEqual({ kind: "join", ticketKey: "ENG-1" }); + // A later alert with a longer deadline still joins. + expect(batchAlert(low, due + 86_400_000, open)).toEqual({ kind: "join", ticketKey: "ENG-1" }); + }); + + it("tightens the due date when the new alert is more urgent", () => { + const due = now + 30 * 86_400_000; + const open = [{ ticketKey: "ENG-1", repo: "acme/web", ecosystem: "npm", dueAt: due }]; + expect(batchAlert(medium, now + 7 * 86_400_000, open)).toEqual({ kind: "tighten", ticketKey: "ENG-1", dueAt: now + 7 * 86_400_000 }); + }); + + it("starts a ticket when nothing open matches the repo and ecosystem", () => { + const open = [{ ticketKey: "ENG-1", repo: "acme/web", ecosystem: "pip", dueAt: now }]; + expect(batchAlert(low, now + 30 * 86_400_000, open)).toEqual({ kind: "new" }); + expect(batchAlert({ ...low, repo: "acme/other" }, now + 30 * 86_400_000, open)).toEqual({ kind: "new" }); + }); + + it("picks the tightest of several open tickets", () => { + const open = [ + { ticketKey: "ENG-1", repo: "acme/web", ecosystem: "npm", dueAt: now + 30 * 86_400_000 }, + { ticketKey: "ENG-2", repo: "acme/web", ecosystem: "npm", dueAt: now + 7 * 86_400_000 }, + ]; + expect(batchAlert(low, now + 30 * 86_400_000, open)).toEqual({ kind: "join", ticketKey: "ENG-2" }); + }); +}); + +describe("alert rendering", () => { + it("names the fingerprint, the package, the fix and the link", () => { + expect(alertFingerprint(alert())).toBe("acme/web#4"); + expect(sightingOf(alert())).toMatchObject({ fingerprint: "acme/web#4", severity: "high", ecosystem: "npm" }); + const line = alertLine(alert()); + expect(line).toMatch(/GHSA-xxxx-yyyy-zzzz/u); + expect(line).toMatch(/lodash/u); + expect(line).toMatch(/fixed in 4\.17\.21/u); + expect(alertLine(alert({ fixedVersion: null, ghsaId: null }))).toMatch(/no fixed version yet/u); + }); +}); + +describe("the defaults", () => { + it("are the ticket's", () => { + expect(DEFAULT_SLA).toEqual({ critical: "asap", high: 86_400_000, medium: 7 * 86_400_000, low: 30 * 86_400_000 }); + expect(DEFAULT_BATCH).toEqual({ medium: 7 * 86_400_000, low: 30 * 86_400_000 }); + }); +}); diff --git a/plugins/stewards/deps.ts b/plugins/stewards/deps.ts new file mode 100644 index 00000000..eb3e93ae --- /dev/null +++ b/plugins/stewards/deps.ts @@ -0,0 +1,159 @@ +// The dependency watch's mechanical tier, as pure functions: a Dependabot +// alert's deadline from the project's per-severity SLA, the Linear priority +// its severity maps to, whether a new medium or low alert joins an open +// batched ticket or tightens its due date, and what changed between two looks +// at a repository's alerts. server.ts fetches and stores; nothing here talks +// to anything. +// +// The rules come from the ticket (BB-12): critical and high get their own +// ticket at once; medium and low coalesce into one open ticket per repo per +// ecosystem. `asap` is due now and escalates at once. A new alert joins the +// open ticket for its repo and ecosystem when that ticket's due date is +// inside the new alert's deadline; otherwise the due date tightens to the new +// deadline. A recurrence is a comment on the ticket, never a second ticket. +import { z } from "zod"; +import { DEPENDABOT_SEVERITIES, type DependabotAlert, type DependabotSeverity } from "./source-contract.js"; + +/** The default SLA: `asap` or a duration, per severity. */ +export const DEFAULT_SLA: Record = { + critical: "asap", + high: 86_400_000, + medium: 7 * 86_400_000, + low: 30 * 86_400_000, +}; + +/** The default batch window a medium or low alert may wait for company. */ +export const DEFAULT_BATCH: Record<"medium" | "low", number> = { medium: 7 * 86_400_000, low: 30 * 86_400_000 }; + +/** Severity maps one to one onto Linear priority. */ +export const PRIORITY_BY_SEVERITY: Record = { critical: "urgent", high: "high", medium: "medium", low: "low" }; + +/** Whether a severity coalesces rather than getting a ticket of its own. */ +export const isBatchable = (severity: DependabotSeverity): boolean => severity === "medium" || severity === "low"; + +/** The entity id doorbells carry and the fingerprint map keys on: "owner/repo#". */ +export const alertFingerprint = (alert: Pick): string => `${alert.repo}#${alert.number}`; + +/** + * When an alert is due: `asap` is due the moment it is first seen, otherwise + * first seen plus the severity's SLA. The clock is `firstSeenAt`, not the + * alert's GitHub `created_at`: a server that missed a doorbell must not + * inherit a deadline already spent, and an alert re-seen after a restart + * keeps the deadline it first got from the fingerprint map. + */ +export function deadlineAt(severity: DependabotSeverity, sla: Record, firstSeenAt: number): number { + const value = sla[severity]; + return value === "asap" ? firstSeenAt : firstSeenAt + value; +} + +/** An open ticket a batched alert may join: one per repo per ecosystem. */ +export type DepsTicket = { ticketKey: string; repo: string; ecosystem: string; dueAt: number }; + +export type BatchPlan = + | { kind: "new" } + | { kind: "join"; ticketKey: string } + | { kind: "tighten"; ticketKey: string; dueAt: number }; + +/** + * What a new alert does with the open tickets for its repo and ecosystem. + * Critical and high never batch. A medium or low alert joins the open ticket + * whose due date is inside (at or before) the new alert's deadline, since + * that ticket is already at least as urgent; otherwise the ticket's due date + * tightens to the new, earlier deadline. No open ticket means a new one. + * `open` should hold only batchable tickets; anything else is ignored. + */ +export function batchAlert(alert: Pick, deadline: number, open: readonly DepsTicket[]): BatchPlan { + if (!isBatchable(alert.severity)) return { kind: "new" }; + const candidates = open + .filter((t) => t.repo.toLowerCase() === alert.repo.toLowerCase() && t.ecosystem.toLowerCase() === alert.ecosystem.toLowerCase()) + .sort((a, b) => a.dueAt - b.dueAt); + const ticket = candidates[0]; + if (ticket === undefined) return { kind: "new" }; + return ticket.dueAt <= deadline ? { kind: "join", ticketKey: ticket.ticketKey } : { kind: "tighten", ticketKey: ticket.ticketKey, dueAt: deadline }; +} + +/** "urgent" for critical, "high" for high, and so on. */ +export const priorityFor = (severity: DependabotSeverity): string => PRIORITY_BY_SEVERITY[severity]; + +/** One alert as a Markdown bullet for a ticket body or a comment. */ +export function alertLine(alert: Pick): string { + const where = [alert.ecosystem, alert.manifestPath].filter((v): v is string => v !== null && v !== "").join(" / "); + const fixed = alert.fixedVersion === null ? "no fixed version yet" : `fixed in ${alert.fixedVersion}`; + const ghsa = alert.ghsaId === null ? "" : ` ${alert.ghsaId}`; + return `- **${alert.severity}**${ghsa} \`${alert.package}\`${where === "" ? "" : ` (${where})`} — ${fixed}${alert.url === null ? "" : ` — ${alert.url}`}`; +} + +/** A due date as Linear wants it: an ISO date, `asap` being today. */ +export function dueDate(deadline: number): string { + return new Date(deadline).toISOString().slice(0, 10); +} + +/** Whether an alert is still open. GitHub's fixed, dismissed and auto_dismissed states are not. */ +export const isOpen = (state: string): boolean => state === "open"; + +/** The part of an alert a look compares; the rest is evidence for the ticket. */ +export type AlertSighting = { fingerprint: string; summary: string; severity: DependabotSeverity; ecosystem: string }; + +export function sightingOf(alert: DependabotAlert): AlertSighting { + return { + fingerprint: alertFingerprint(alert), + summary: `${alert.severity} ${alert.package}${alert.ghsaId === null ? "" : ` (${alert.ghsaId})`}`, + severity: alert.severity, + ecosystem: alert.ecosystem, + }; +} + +// ---- the look ------------------------------------------------------------------ + +/** + * One alert in a dependency look, classified against the fingerprint map and + * with the batch plan for its repo and ecosystem. `class` mirrors the ops + * findings: new (no ticket), recurring (its ticket is open), returned (its + * ticket was resolved). + */ +export const depsFindingSchema = z.object({ + fingerprint: z.string(), + alertNumber: z.number().int(), + severity: z.enum(DEPENDABOT_SEVERITIES), + package: z.string(), + ecosystem: z.string(), + manifestPath: z.string().nullable(), + ghsaId: z.string().nullable(), + fixedVersion: z.string().nullable(), + summary: z.string(), + state: z.string(), + url: z.string().nullable(), + /** The SLA deadline, from the severity and when the alert was first seen. */ + dueAt: z.number(), + /** The Linear priority the severity maps to. */ + priority: z.string(), + class: z.enum(["new", "recurring", "returned"]), + ticket: z.string().nullable(), + ticketState: z.string().nullable(), + firstSeenAt: z.number(), + lastCommentedAt: z.number().nullable(), + /** For a medium or low alert, what to do with the open ticket for its repo and ecosystem. */ + batch: z.union([ + z.object({ kind: z.literal("new") }), + z.object({ kind: z.literal("join"), ticketKey: z.string() }), + z.object({ kind: z.literal("tighten"), ticketKey: z.string(), dueAt: z.number() }), + ]), +}); +export type DepsFinding = z.infer; + +/** A dependency watch's last look at one repository. */ +export const depsLookSchema = z.object({ + at: z.number(), + target: z.string(), + /** Set when the repository could not be read; `alerts` is then empty. */ + error: z.string().nullable(), + viewer: z.string().nullable(), + alerts: z.array(depsFindingSchema), +}); +export type DepsLook = z.infer; + +/** The repo a fingerprint names: "owner/repo#4" → "owner/repo". */ +export const repoOfFingerprint = (fingerprint: string): string | null => { + const i = fingerprint.lastIndexOf("#"); + return i <= 0 ? null : fingerprint.slice(0, i); +}; diff --git a/plugins/stewards/kubectl.ts b/plugins/stewards/kubectl.ts index 07715a44..3ec4daa9 100644 --- a/plugins/stewards/kubectl.ts +++ b/plugins/stewards/kubectl.ts @@ -9,7 +9,7 @@ // broad, so this and the playbook's `may` list are what keep the ops steward // read-only (DESIGN.md §11, §18). A real wall, such as a read-only identity, // would slot in behind the same function. -import { deploymentsOf, eventsOf, findingsOf, logTail, otherWarnings, podsOf, type OpsTarget, type RawLook } from "./ops.js"; +import { deploymentsOf, eventsOf, findingsOf, logTail, otherWarnings, podsOf, type K8sTarget, type RawLook } from "./ops.js"; /** What the ops kind may ask kubectl to do. Nothing else is run. */ export const KUBECTL_VERBS = ["get", "describe", "logs", "auth can-i"] as const; @@ -50,8 +50,8 @@ export type OpsAccess = { export interface OpsReader { /** One look at a target. Throws when its pods cannot be listed: then there is nothing to look at. */ - look(target: OpsTarget, at: { now: number; since: number }): Promise; - access(target: OpsTarget): Promise; + look(target: K8sTarget, at: { now: number; since: number }): Promise; + access(target: K8sTarget): Promise; } const REQUEST_TIMEOUT = "--request-timeout=20s"; diff --git a/plugins/stewards/ops.ts b/plugins/stewards/ops.ts index 2173bd8d..f23bea1e 100644 --- a/plugins/stewards/ops.ts +++ b/plugins/stewards/ops.ts @@ -11,14 +11,18 @@ import { z } from "zod"; import type { Change } from "./reconcile.js"; -export type OpsTarget = { kind: "k8s-namespace"; name: string }; +export type K8sTarget = { kind: "k8s-namespace"; name: string }; +export type DependabotTarget = { kind: "dependabot"; repo: string }; +export type OpsTarget = K8sTarget | DependabotTarget; -/** The binding's entity id and key for a target: "k8s-namespace/bb-gate-production". */ -export const opsTargetKey = (t: OpsTarget): string => `${t.kind}/${t.name}`; +/** The binding's entity id and key for a target: "k8s-namespace/bb-gate-production" or "dependabot/acme/web". */ +export const opsTargetKey = (t: OpsTarget): string => (t.kind === "k8s-namespace" ? `${t.kind}/${t.name}` : `${t.kind}/${t.repo}`); export function parseOpsTargetKey(key: string): OpsTarget | null { - const m = /^(k8s-namespace)\/([a-z0-9][-a-z0-9]*)$/u.exec(key); - return m === null ? null : { kind: m[1] as OpsTarget["kind"], name: m[2]! }; + const k8s = /^(k8s-namespace)\/([a-z0-9][-a-z0-9]*)$/u.exec(key); + if (k8s !== null) return { kind: "k8s-namespace", name: k8s[2]! }; + const dep = /^(dependabot)\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)$/u.exec(key); + return dep === null ? null : { kind: "dependabot", repo: dep[2]! }; } // ---- reading the Kubernetes API's JSON -------------------------------------------- diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index 4d9296f6..e45d32c7 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -505,9 +505,12 @@ const hasLabel = (entity: EntitySnapshot, label: string) => entity.labels.some(( * ending reopens it too: a ticket an automation moved to Done and someone * moved straight back should not cost its steward its workers. */ -export function lifecycle(binding: Pick, playbook: Playbook, entity: EntitySnapshot, label: string): Lifecycle { +export function lifecycle(binding: Pick, playbook: Playbook, entity: EntitySnapshot, label: string, opts: { labelRequired?: boolean } = {}): Lifecycle { const terminal = isTerminal(playbook, entity.state); - const labelled = binding.kind === "review" || hasLabel(entity, label); + // A review binding is not labelled; a binding the plugin adopts itself (a + // dependency bot's pull request) has no label to hold it, so its label is + // not required either. + const labelled = binding.kind === "review" || opts.labelRequired === false || hasLabel(entity, label); if (binding.endedAt !== null) { if (terminal || !labelled || binding.manualDetach) return { kind: "stay-ended" }; if (binding.endReason === "terminal") return { kind: "reopen", why: `reopened: now ${entity.state}` }; diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 6b43ca8c..99082c23 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -7,7 +7,7 @@ import { kubectlRefusal, type KubectlResult } from "./kubectl.js"; import { createStewardsPlugin, testHooks, type StewardsDeps } from "./server.js"; import { SOURCE_PLUGIN_IDS, type EntitySnapshot } from "./source-contract.js"; import { MIGRATIONS } from "./store.js"; -import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, projectFileTemplate } from "./templates.js"; +import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, DEPS_ALERTS, DEPS_PRS, projectFileTemplate } from "./templates.js"; type Call = { pluginId: string; method: string; input: Record }; @@ -22,6 +22,8 @@ function world() { }; const repos = [{ dir: "web", url: "https://github.com/acme/web.git" }]; const entities = new Map(); + /** Dependabot alerts the fake github serves, by lowercased repo. */ + const dependabotAlerts = new Map(); const rpcCalls: Call[] = []; const threads = new Map(); const writes: Array<{ path: string; hostId?: string }> = []; @@ -63,6 +65,10 @@ function world() { errors: [], }; } else if (args.method === "sourceValidate") out = { viewer: "Jane", units: (input.units as string[]).map((unit) => ({ unit, found: true, labelFound: true, missingStates: [] })), mine: [{ unit: "ENG", name: "Engineering" }], error: null }; + else if (args.method === "sourceDependabotAlerts") { + const units = input.units as string[]; + out = { viewer: "jane", alerts: units.flatMap((u) => dependabotAlerts.get(u.toLowerCase()) ?? []), errors: [] }; + } else throw Object.assign(new Error(`unknown ${args.pluginId}.${args.method}`), { status: 404 }); return args.outputSchema.parse(out); }; @@ -164,7 +170,7 @@ function world() { }, }; let now = Date.parse("2026-10-14T15:00:00Z"); - return { files, writes, repos, entities, rpcCalls, threads, sections, usage, metadata, spawns, sends, userTurns, githubComments, githubMerges, github, sdk, now: () => now, advance: (ms: number) => (now += ms) }; + return { files, writes, repos, entities, dependabotAlerts, rpcCalls, threads, sections, usage, metadata, spawns, sends, userTurns, githubComments, githubMerges, github, sdk, now: () => now, advance: (ms: number) => (now += ms) }; } async function setup(extra: Partial = {}) { @@ -235,8 +241,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"] }); - expect(interest.find((c) => c.pluginId === "github-watcher")?.input).toEqual({ units: ["acme/web"], entities: [] }); + 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: [] }); }); it("ignores unlabelled tickets, other teams, and rings from anyone but a source plugin", async () => { @@ -713,7 +719,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"] }); + expect(github).toEqual({ units: ["acme/web"], entities: ["acme/web#10", "acme/web#7"], dependabot: [] }); }); it("stops leasing a linked pull request once it merges", async () => { @@ -723,13 +729,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"] }); + expect(github().at(-1)?.input).toEqual({ units: ["acme/web"], entities: ["acme/web#7"], dependabot: [] }); 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: [] }); + expect(github().at(-1)?.input).toEqual({ units: ["acme/web"], entities: [], dependabot: [] }); }); it("counts a worker woken again (by a watch, a reviewer) as running", async () => { @@ -1496,7 +1502,7 @@ describe("bb stewards init", () => { const t = await setup(); t.threads.set("thr_me", { status: "active", archivedAt: null }); await t.harness.behavior.runCli(["init", "--teams", "ENG"], { threadId: "thr_me", projectId: "p1", cwd: "/w" }); - expect(t.writes.length).toBe(5); + expect(t.writes.length).toBe(7); expect(t.writes.every((w) => w.hostId === "host_on")).toBe(true); }); }); @@ -2557,3 +2563,140 @@ describe("ops stewards", () => { expect(r).toMatchObject({ error: true, text: expect.stringMatching(/opsTickets is for an ops steward's report/u) }); }); }); + +describe("dependency stewards", () => { + const DEPS_TARGET = "dependabot/acme/web"; + + const alert = (over: Record = {}) => ({ + id: "acme/web#4", + repo: "acme/web", + number: 4, + severity: "high", + package: "lodash", + ecosystem: "npm", + manifestPath: "package-lock.json", + state: "open", + ghsaId: "GHSA-xxxx-yyyy-zzzz", + fixedVersion: "4.17.21", + summary: "Prototype pollution", + url: "https://github.com/acme/web/security/dependabot/4", + createdAt: "2026-10-01T00:00:00Z", + updatedAt: "2026-10-01T00:00:00Z", + ...over, + }); + + async function watching(alerts: unknown[] = [alert()]) { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] } }); + t.files[playbookPath("deps-alerts")] = DEPS_ALERTS; + t.files[playbookPath("deps-prs")] = DEPS_PRS; + t.dependabotAlerts.set("acme/web", alerts); + await t.hooks.sweep(); + await t.flush(); + const steward = () => t.spawns.find((x) => String(x.title).startsWith("Deps watch")); + const wakes = () => { + const id = steward()?.id; + return id === undefined ? [] : [String(steward()!.prompt), ...t.sends.filter((x) => x.threadId === id).map((x) => x.text)]; + }; + return { t, steward, wakes }; + } + + it("watches every repo for alerts, with the SLA, priority and batch plan in the wake", async () => { + const { t, steward, wakes } = await watching(); + expect(await t.list()).toMatchObject([{ key: DEPS_TARGET, kind: "ops", threadId: steward()!.id, ended: false }]); + expect(steward()).toMatchObject({ title: "Deps watch: acme/web" }); + // The interest names the repo as a dependabot lease, separate from its repo lease. + const interest = t.rpcCalls.filter((c) => c.method === "sourceSetInterest" && c.pluginId === "github-watcher").at(-1)!.input as { units: string[]; dependabot: string[] }; + expect(interest.units).toEqual(["acme/web"]); + expect(interest.dependabot).toEqual(["acme/web"]); + + const first = wakes()[0]!; + expect(first).toMatch(/^# Deps watch: dependabot\/acme\/web/u); + expect(first).toMatch(/You have just been made the dependency steward/u); + expect(first).toContain("#### acme/web#4"); + expect(first).toMatch(/### New: no ticket yet/u); + expect(first).toMatch(/\*\*high\*\* priority high, due 2026-10-15/u); + expect(first).toMatch(/`lodash` \(npm\) — package-lock.json — GHSA-xxxx-yyyy-zzzz/u); + expect(first).toMatch(/Fixed in 4\.17\.21/u); + expect(first).toMatch(/This severity gets its own ticket\./u); + expect(first).toMatch(/File tickets in the Linear team ENG/u); + + // It files and reports, and the fingerprint map records the ticket. + const ops = steward()!.id; + const report = await t.tool("steward_report", { phase: "watching", summary: "Filed ENG-50.", nextAction: "Watch", actor: "steward", opsTickets: [{ fingerprint: "acme/web#4", ticket: "ENG-50", did: "filed" }] }, ops); + expect(report).toMatchObject({ error: false }); + expect(t.hooks.store.fingerprint("p1", "acme/web#4")).toMatchObject({ ticketKey: "ENG-50", severity: "high", ecosystem: "npm" }); + }); + + it("joins a second low alert to the open ticket and tightens its due date for a medium one", async () => { + const { t, steward, wakes } = await watching([alert({ number: 4, severity: "low", ghsaId: "GHSA-low-1" })]); + const ops = steward()!.id; + expect(wakes()[0]).toMatch(/### New: no ticket yet/u); + expect((await t.tool("steward_report", { phase: "watching", summary: "Filed ENG-50.", nextAction: "Watch", actor: "steward", opsTickets: [{ fingerprint: "acme/web#4", ticket: "ENG-50", did: "filed" }] }, ops)).error).toBe(false); + + // A second low alert: the open ticket's due date is inside its deadline, so it joins. + t.advance(86_400_000); + t.dependabotAlerts.set("acme/web", [alert({ number: 4, severity: "low", ghsaId: "GHSA-low-1" }), alert({ number: 5, severity: "low", ghsaId: "GHSA-low-2", package: "minimist" })]); + await t.hooks.sweep(); + await t.flush(); + const joined = wakes().at(-1)!; + expect(joined).toContain("#### acme/web#5"); + expect(joined).toMatch(/Batch: join the open ticket ENG-50/u); + expect(joined).not.toMatch(/Batch: tighten/u); + + // A medium alert is more urgent than the low ticket's due date, so it tightens it. + t.advance(86_400_000); + t.dependabotAlerts.set("acme/web", [alert({ number: 4, severity: "low", ghsaId: "GHSA-low-1" }), alert({ number: 6, severity: "medium", ghsaId: "GHSA-med", package: "axios" })]); + await t.hooks.sweep(); + await t.flush(); + const tightened = wakes().at(-1)!; + expect(tightened).toContain("#### acme/web#6"); + expect(tightened).toMatch(/Batch: tighten the open ticket ENG-50 to due \d{4}-\d{2}-\d{2}\./u); + }); + + it("wakes on a fixed alert so its ticket is trimmed, and rings on a dependabot_alert doorbell", async () => { + const { t, steward, wakes } = await watching(); + const ops = steward()!.id; + expect((await t.tool("steward_report", { phase: "watching", summary: "Filed ENG-50.", nextAction: "Watch", actor: "steward", opsTickets: [{ fingerprint: "acme/web#4", ticket: "ENG-50", did: "filed" }] }, ops)).error).toBe(false); + const before = wakes().length; + + // Fixed: the alert is gone from the open list, and the wake says so. + t.dependabotAlerts.set("acme/web", []); + await t.ring("github", "acme/web#4"); + expect(wakes()).toHaveLength(before + 1); + const trimmed = wakes().at(-1)!; + expect(trimmed).toMatch(/No longer open: acme\/web#4 \(ENG-50\)/u); + expect(trimmed).toMatch(/\*\*No open alerts\.\*\*/u); + + // A doorbell for an alert in the watched repo wakes the dependency steward, even with nothing new. + t.dependabotAlerts.set("acme/web", [alert({ number: 7, severity: "critical", ghsaId: "GHSA-crit", package: "tar" })]); + await t.ring("github", "acme/web#7"); + expect(wakes().at(-1)).toContain("#### acme/web#7"); + expect(wakes().at(-1)).toMatch(/\*\*critical\*\* priority urgent/u); + expect(wakes().at(-1)).toMatch(/deps\.autoAdopt: a ticket you file for a critical or high alert is adopted at once/u); + }); + + it("adopts a dependabot[bot] pull request under deps-prs", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] } }); + t.files[playbookPath("deps-prs")] = DEPS_PRS; + t.entities.set("acme/web#9", pull({ id: "acme/web#9", key: "acme/web#9", author: "dependabot[bot]", labels: [] })); + await t.hooks.sweep(); + await t.flush(); + const pr = t.spawns.find((x) => x.title === "acme/web#9: Add login retry"); + expect(pr).toBeDefined(); + const prompt = String(pr!.prompt); + expect(prompt).toMatch(/playbook deps-prs@/u); + expect(prompt).toMatch(/You steward one Dependabot version-update pull request/u); + expect(prompt).toMatch(/never merge it: you adopt it, review it, and escalate it for a\s+human merge/u); + }); + + it("checks the deps SLA, batch and autoAdopt, and says which repos the gh login cannot read", async () => { + const { t } = await watching(); + const check = await t.harness.behavior.runCli(["check"], { projectId: "p1" }); + expect(check.stdout).toMatch(/deps: sla critical=asap high=1d medium=7d low=30d; batch medium=7d low=30d; autoAdopt critical, high/u); + expect(check.stdout).toMatch(/deps-alerts: deps-alerts@/u); + expect(check.stdout).toMatch(/deps-prs: deps-prs@/u); + expect(check.stdout).toMatch(/deps: watching 1 repo for alerts: acme\/web/u); + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 7e7646ea..680d9237 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -17,14 +17,19 @@ import { z } from "zod"; import { DEFAULT_FOLLOW_THROUGH_MS, DEFAULT_PLAYBOOKS, + DEPS_ALERTS_PLAYBOOK, + DEPS_PRS_PLAYBOOK, ESCALATION_KINDS, KINDS, PROJECT_FILE, + depsAlertsPlaybookName, + depsPrsPlaybookName, + depsTargets, durationSchema, formatDuration, isTerminal, + k8sTargets, modelSpecSchema, - opsTargets, opsTeam, parsePlaybook, parseProjectFile, @@ -39,10 +44,11 @@ import { type Playbook, type ProjectFile, } from "./config.js"; +import { alertFingerprint, batchAlert, deadlineAt, depsLookSchema, isBatchable, priorityFor, repoOfFingerprint, sightingOf, type DepsFinding, type DepsLook, type DepsTicket } from "./deps.js"; import { hostContract } from "./host-contract.js"; import { KUBECTL_VERBS, createKubectlReader, kubectlRefusal, type KubectlResult, type OpsAccess, type OpsReader } from "./kubectl.js"; import { nightlyDue, stillNight } from "./nightly.js"; -import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type OpsLook, type OpsTarget, type TicketState } from "./ops.js"; +import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type DependabotTarget, type K8sTarget, type OpsLook, type OpsTarget, type Sighting, type TicketState } from "./ops.js"; import { advanced, anyWorkerInFlight, approvalWanted, asksForOpenApproval, classifyApproval, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, lifecycle, namesUserAsBlocker, newestCommentAt, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, @@ -51,14 +57,16 @@ import { signatureLine, sourceContract, stewardsContract, + type DependabotAlert, + type DependabotSeverity, type EntitySnapshot, type SessionWake, type Source, } from "./source-contract.js"; -import { ACTORS, MIGRATIONS, NEEDS_KINDS, createStore, type Binding, type Escalation, type EscalationRoute, type Need, type Observed, type Question, type ReadyState, type Store } from "./store.js"; +import { ACTORS, MIGRATIONS, NEEDS_KINDS, createStore, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Need, type Observed, type Question, type ReadyState, type Store } from "./store.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; -import { PROJECT_STEWARD_INTRO, formatOpsWake, formatProjectWake, formatSessionWake, formatWake, workerQuestion, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, formatDepsWake, formatOpsWake, formatProjectWake, formatSessionWake, formatWake, workerQuestion, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; export const MULTI_REPO_PLUGIN_ID = "multi-repo"; /** multi-repo's environment provider: where every thread of a stewards project works. */ @@ -300,6 +308,10 @@ type ProjectConfig = { projectId: string; file: ProjectFile; playbooks: Partial>; + /** The dependency watch's alert playbook, when it parses. */ + depsAlerts: Playbook | null; + /** The Dependabot pull request playbook, when it parses. */ + depsPrs: Playbook | null; /** GitHub repos from the project's repos.json, as owner/repo, less github.exclude. */ repos: string[]; /** What is wrong with the configuration, in sentences; bindings keep running under the last good playbook. */ @@ -309,6 +321,9 @@ type ProjectConfig = { const PRIORITY_ORDER: Record = { urgent: 0, high: 1, normal: 2, low: 3 }; +/** Authors whose pull requests the dependency watch adopts under deps-prs. */ +export const DEPENDENCY_BOTS = new Set(["dependabot", "dependabot[bot]"]); + export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => Promise { return async (bb) => { const timing: Timing = { ...DEFAULT_TIMING, ...deps.timing }; @@ -437,7 +452,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const kinds = KINDS.filter((k) => usesKind(file, k)); const names = new Map(kinds.map((k) => [k, playbookNameFor(file, k)] as const)); - const texts = await readFiles(projectId, [...new Set(names.values())].map(playbookPath)); + const depsAlertsName = depsAlertsPlaybookName(file); + const depsPrsName = depsPrsPlaybookName(file); + const texts = await readFiles(projectId, [...new Set([...names.values(), depsAlertsName, depsPrsName])].map(playbookPath)); const playbooks: Partial> = {}; for (const [kind, name] of names) { const text = texts.get(playbookPath(name)) ?? null; @@ -458,6 +475,33 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } + /** + * The dependency watch's two playbooks. They are optional: a project that + * has not written them runs no dependency watch, which is how the feature + * is off before `bb stewards init` writes them. One that is present but + * does not parse is a problem, like any other playbook. + */ + const loadOptional = async (name: string): Promise => { + const text = texts.get(playbookPath(name)) ?? null; + if (text === null) return null; + const goodKey = `good/${projectId}/playbook/${name}`; + let result = parsePlaybook(text, name); + if (result.ok) { + await bb.storage.kv.set(goodKey, text); + return result.value; + } + problems.push(result.error); + const last = await bb.storage.kv.get(goodKey); + const lastParsed = typeof last === "string" ? parsePlaybook(last, name) : null; + if (lastParsed !== null && lastParsed.ok) { + problems.push(`${name} keeps running under the last good version (${lastParsed.value.version}).`); + return lastParsed.value; + } + return null; + }; + const depsAlerts = await loadOptional(depsAlertsName); + const depsPrs = await loadOptional(depsPrsName); + let repos: string[] = []; try { const set = await rpc(MULTI_REPO_PLUGIN_ID, "repoSet", { projectId }, repoSetOutput); @@ -471,7 +515,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } catch (error) { problems.push(`could not read the repo set: ${errorMessage(error)}`); } - return { projectId, file, playbooks, repos, problems, loadedAt: now() }; + return { projectId, file, playbooks, depsAlerts, depsPrs, repos, problems, loadedAt: now() }; } /** Every project with a stewards configuration. */ @@ -487,6 +531,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const playbookFor = (config: ProjectConfig, kind: BindingKind) => config.playbooks[kind] ?? null; + /** + * The playbook a binding runs under. A Dependabot alert target uses the + * deps-alerts playbook; a pull request the dependency watch adopted uses + * deps-prs; everything else uses its kind's playbook. + */ + function bindingPlaybook(config: ProjectConfig, b: Pick): Playbook | null { + if (b.kind === "ops") { + const target = parseOpsTargetKey(b.entityId); + if (target?.kind === "dependabot") return config.depsAlerts; + } + if (b.kind === "pr" && b.playbook === depsPrsPlaybookName(config.file)) return config.depsPrs; + return playbookFor(config, b.kind); + } + // ---- the sources --------------------------------------------------------------------- async function snapshot(source: Source, id: string): Promise { @@ -535,10 +593,11 @@ 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: [], }, github: { units: [...new Set(projects.flatMap((p) => p.repos))].sort(), @@ -548,6 +607,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ...open.flatMap((b) => leasedPulls(b)), ]), ].sort(), + // Every repo the project watches for Dependabot alerts. A server + // 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(), }, }; for (const source of ["linear", "github"] as const) { @@ -978,7 +1041,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b === null) return; const config = await loadConfig(b.projectId); if (config === null) return; - const playbook = playbookFor(config, b.kind); + const playbook = bindingPlaybook(config, b); if (playbook === null) return; if (b.source === "ops") { await reconcileOps(b, config, playbook, force); @@ -999,10 +1062,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const observed: Observed = { entity, pulls: b.kind === "ticket" ? await linkedPulls(entity) : [] }; const prev = b.lastSnapshot; - const life = lifecycle(b, playbook, entity, config.file.label); + 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") { - const labelled = b.kind === "review" || hasLabel(entity, config.file.label); + const labelled = b.kind === "review" || b.playbook === depsPrsPlaybookName(config.file) || hasLabel(entity, config.file.label); store.patch(b.id, { lastSnapshot: observed, ...(b.manualDetach && !labelled ? { manualDetach: false } : {}) }); return; } @@ -1154,8 +1217,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return out; } + /** Every ops target a project watches: the k8s namespaces and the Dependabot repositories. */ + const allOpsTargets = (config: ProjectConfig): OpsTarget[] => [...k8sTargets(config.file), ...depsTargets(config.file, config.repos)]; + /** One look at an ops binding's target, its problems entered in the fingerprint map and classified against it. */ - async function lookAt(b: Binding, config: ProjectConfig, target: OpsTarget, playbook: Playbook): Promise { + async function lookAt(b: Binding, config: ProjectConfig, target: K8sTarget, playbook: Playbook): Promise { const at = now(); const since = b.opsLook !== null && b.opsLook.error === null ? b.opsLook.at : at - playbook.requeueDefaultMs; try { @@ -1168,11 +1234,110 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } + /** + * The open tickets a new medium or low alert may join, one per repo and + * ecosystem: grouped from the fingerprint map by ticket, each with the + * tightest deadline among its alerts. Only batchable (medium and low) + * fingerprints count, since critical and high never coalesce. + */ + function openBatchedTickets(rows: readonly Fingerprint[], sla: ProjectFile["deps"]["sla"]): DepsTicket[] { + const byTicket = new Map(); + for (const r of rows) { + if (r.ticketKey === null || r.severity === null || r.ecosystem === null) continue; + if (!isBatchable(r.severity as DependabotSeverity)) continue; + const repo = repoOfFingerprint(r.fingerprint); + if (repo === null) continue; + const dueAt = deadlineAt(r.severity as DependabotSeverity, sla, r.firstSeenAt); + const ticket = byTicket.get(r.ticketKey); + if (ticket === undefined) byTicket.set(r.ticketKey, { ticketKey: r.ticketKey, repo, ecosystem: r.ecosystem, dueAt }); + else ticket.dueAt = Math.min(ticket.dueAt, dueAt); + } + return [...byTicket.values()]; + } + + /** One look at a Dependabot alert target: the repository's open alerts, classified and batched. */ + async function lookAtDeps(b: Binding, config: ProjectConfig, target: DependabotTarget): Promise { + const at = now(); + try { + const out = await sourceRpc("github", "sourceDependabotAlerts", { units: [target.repo], state: "open" }, sourceContract.sourceDependabotAlerts.output); + const alerts: DependabotAlert[] = out.alerts; + const rows = store.sight( + b.projectId, + b.id, + alerts.map((a) => { + const s = sightingOf(a); + return { fingerprint: s.fingerprint, summary: s.summary, severity: s.severity, ecosystem: s.ecosystem }; + }), + ); + const sightings: Sighting[] = alerts.map((a) => ({ fingerprint: alertFingerprint(a), workload: a.package, pods: [], container: null, signature: a.severity, summary: `${a.severity} ${a.package}`, restarts: 0, events: [], logs: null, previous: false })); + const tickets = await ticketStates([...rows.values()].map((r) => r.ticketKey).filter((k): k is string => k !== null)); + const findings = classify(sightings, rows, tickets, at); + const open = openBatchedTickets(store.fingerprints(b.id), config.file.deps.sla); + const byFingerprint = new Map(alerts.map((a) => [alertFingerprint(a), a])); + const depsFindings: DepsFinding[] = []; + for (const f of findings) { + const a = byFingerprint.get(f.fingerprint); + if (a === undefined) continue; + const firstSeenAt = rows.get(f.fingerprint)?.firstSeenAt ?? at; + const dueAt = deadlineAt(a.severity, config.file.deps.sla, firstSeenAt); + depsFindings.push({ + fingerprint: f.fingerprint, + alertNumber: a.number, + severity: a.severity, + package: a.package, + ecosystem: a.ecosystem, + manifestPath: a.manifestPath, + ghsaId: a.ghsaId, + fixedVersion: a.fixedVersion, + summary: a.summary ?? f.summary, + state: a.state, + url: a.url, + dueAt, + priority: priorityFor(a.severity), + class: f.class, + ticket: f.ticket, + ticketState: f.ticketState, + firstSeenAt, + lastCommentedAt: f.lastCommentedAt, + batch: batchAlert(a, dueAt, open), + }); + } + return { at, target: opsTargetKey(target), error: null, viewer: out.viewer, alerts: depsFindings }; + } catch (error) { + return { at, target: opsTargetKey(target), error: errorMessage(error), viewer: null, alerts: [] }; + } + } + + /** What changed between two dependency looks, as the mechanical tier weighs it. */ + function depsChanges(before: DepsLook | null, after: DepsLook, ticketFor: (fingerprint: string) => string | null): Change[] { + if (after.error !== null) return before === null || before.error === null ? [{ text: `Cannot read ${after.target}: ${after.error}`, actionable: false }] : []; + const changes: Change[] = []; + if (before !== null && before.error !== null) changes.push({ text: `${after.target} is readable again`, actionable: false }); + const was = new Map((before?.alerts ?? []).map((a) => [a.fingerprint, a])); + for (const a of after.alerts) { + const prev = was.get(a.fingerprint); + if (a.class === "new" && (prev === undefined || prev.class !== "new")) changes.push({ text: `New alert: ${a.fingerprint} — ${a.summary}`, actionable: true }); + else if (a.class === "returned" && prev?.class !== "returned") changes.push({ text: `Back after ${a.ticket} was resolved (${a.ticketState ?? "closed"}): ${a.fingerprint}`, actionable: true }); + else if (a.class === "recurring" && prev === undefined) changes.push({ text: `Seen again under ${a.ticket}: ${a.fingerprint}`, actionable: false }); + } + const current = new Set(after.alerts.map((a) => a.fingerprint)); + for (const a of was.values()) { + if (current.has(a.fingerprint)) continue; + const ticket = a.ticket ?? ticketFor(a.fingerprint); + changes.push({ text: `No longer open: ${a.fingerprint}${ticket === null ? "" : ` (${ticket})`}`, actionable: true }); + } + return changes; + } + async function reconcileOps(b: Binding, config: ProjectConfig, playbook: Playbook, force: WakeReason | null): Promise { if (b.endedAt !== null || b.ending !== null) return; const target = parseOpsTargetKey(b.entityId); // A target no longer listed is ended by the sweep. - if (target === null || !opsTargets(config.file).some((t) => opsTargetKey(t) === b.entityId)) return; + if (target === null || !allOpsTargets(config).some((t) => opsTargetKey(t) === b.entityId)) return; + if (target.kind === "dependabot") { + await reconcileDeps(b, config, playbook, target, force); + return; + } const before = b.opsLook; const look = await lookAt(b, config, target, playbook); const requeueCame = b.requeueAt !== null && b.requeueAt <= now(); @@ -1227,14 +1392,72 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); } + /** The same turn for a Dependabot alert target: re-list the open alerts and wake on what changed. */ + async function reconcileDeps(b: Binding, config: ProjectConfig, playbook: Playbook, target: DependabotTarget, force: WakeReason | null): Promise { + const before = b.depsLook; + const look = await lookAtDeps(b, config, target); + const requeueCame = b.requeueAt !== null && b.requeueAt <= now(); + const requeueAt = requeueCame || b.requeueAt === null ? now() + playbook.requeueDefaultMs : b.requeueAt; + b = store.patch(b.id, { depsLook: look, requeueAt }); + if (look.error !== null) { + if (before?.error !== look.error) bb.log.warn(`stewards: cannot read ${b.entityKey}: ${look.error}`); + return; + } + + const changes = depsChanges(before, look, (fp) => store.fingerprint(b.projectId, fp)?.ticketKey ?? null); + if (requeueCame) changes.push({ text: look.alerts.length > 0 ? "Requeue time came, with alerts still open" : "Requeue time came: a scheduled look", actionable: true }); + if (b.playbookVersion !== playbook.version) changes.push({ text: `Playbook ${playbook.name} updated (${b.playbookVersion} → ${playbook.version})`, actionable: false }); + const queued = b.pending; + const loudQueued = queued.filter((n) => n.quiet !== true).length; + for (const n of queued) { + const same = changes.find((c) => c.text === n.text); + if (same !== undefined) same.actionable ||= n.quiet !== true; + else changes.push({ text: n.text, actionable: n.quiet !== true }); + } + b = store.patch(b.id, { playbookVersion: playbook.version }); + const keep = () => { + for (const c of changes) if (!queued.some((n) => n.text === c.text && (n.quiet === true) === !c.actionable)) store.note(b.id, c.text, !c.actionable); + }; + const reason = force ?? (b.threadId === null ? "adopted" : null); + if (reason === null && !changes.some((c) => c.actionable)) { + keep(); + return; + } + const deferred = (await settings.get()).paused || (b.hold !== null && reason === null && loudQueued === 0); + const info = b.threadId === null ? null : await threadInfo(b.threadId); + if (deferred || (info !== null && busy(info.status))) { + keep(); + if (reason !== null && reason !== "changed" && reason !== "adopted") store.note(b.id, `Due: ${reason}`); + return; + } + const text = formatDepsWake({ + reason: reason ?? (requeueCame && loudQueued === 0 ? "requeue" : "changed"), + binding: b, + playbook, + look, + team: opsTeam(config.file), + label: config.file.label, + autoAdopt: config.file.deps.autoAdopt, + escalations: store.openEscalations(b.id), + changes: [...new Set(changes.map((c) => c.text))], + }); + if (!(await deliverWake(b, config, playbook, text))) return; + store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); + } + /** * One ops binding per configured target. A target taken out of the * project file ends its binding; put back, the same binding and thread * resume. One detached by hand stays ended while its target is listed, - * as a ticket stays detached while it keeps its label. + * as a ticket stays detached while it keeps its label. The Dependabot + * targets come from the project's repos (or its explicit dependabot + * targets) and run the deps-alerts playbook. */ async function syncOpsBindings(config: ProjectConfig): Promise { - const wanted = new Map(opsTargets(config.file).map((t) => [opsTargetKey(t), t] as const)); + const wanted = new Map(); + const k8sPlaybook = playbookFor(config, "ops"); + if (k8sPlaybook !== null) for (const target of k8sTargets(config.file)) wanted.set(opsTargetKey(target), { target, playbook: k8sPlaybook }); + if (config.depsAlerts !== null) for (const target of depsTargets(config.file, config.repos)) wanted.set(opsTargetKey(target), { target, playbook: config.depsAlerts }); const existing = store.all(config.projectId).filter((b) => b.kind === "ops"); for (const b of existing) { if (wanted.has(b.entityId)) continue; @@ -1245,14 +1468,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); } else if (b.manualDetach) store.patch(b.id, { manualDetach: false }); } - const playbook = playbookFor(config, "ops"); - if (playbook === null || (await settings.get()).paused) return; - for (const [key, target] of wanted) { + if ((await settings.get()).paused) return; + for (const [key, { target, playbook }] of wanted) { const b = existing.find((x) => x.entityId === key); if (b === undefined) { let created: Binding; + const title = target.kind === "k8s-namespace" ? `Ops watch: ${target.name}` : `Deps watch: ${target.repo}`; try { - created = store.create({ projectId: config.projectId, source: "ops", entityId: key, entityKey: key, url: null, title: `Ops watch: ${target.name}`, kind: "ops", playbook: playbook.name, playbookVersion: playbook.version, parentBindingId: null, phase: "watching", stage: null }); + created = store.create({ projectId: config.projectId, source: "ops", entityId: key, entityKey: key, url: null, title, kind: "ops", playbook: playbook.name, playbookVersion: playbook.version, parentBindingId: null, phase: "watching", stage: null }); } catch { continue; // made concurrently } @@ -1262,7 +1485,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await serial(`b:${b.id}`, async () => { const fresh = store.binding(b.id); if (fresh === null || fresh.endedAt === null) return; - await reopen(fresh, `${key} is listed in ops.targets again`); + await reopen(fresh, `${key} is configured again`); await reconcileBinding(b.id, "reopen"); }); } @@ -1362,7 +1585,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P configs.find((c) => (entity.source === "linear" ? c.file.linear.teams.includes(entity.unit.toUpperCase()) : c.repos.some((r) => lc(r) === lc(entity.unit)))) ?? null; /** Which kind of binding an entity wants in this project, or null for none. */ - function adoptionKind(config: ProjectConfig, e: { source: Source; kind: "issue" | "pull"; state: string; labels: string[]; author: string | null; draft: boolean }, viewer: string | null): BindingKind | null { + function adoptionKind(config: ProjectConfig, e: { source: Source; kind: "issue" | "pull"; state: string; labels: string[]; author: string | null; draft: boolean; unit: string }, viewer: string | null): BindingKind | null { const labelled = e.labels.some((l) => lc(l) === lc(config.file.label)); if (e.source === "linear") { const playbook = playbookFor(config, "ticket"); @@ -1373,6 +1596,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const playbook = playbookFor(config, "pr"); return playbook !== null && !isTerminal(playbook, e.state) ? "pr" : null; } + // The dependency watch adopts the bot's version-update pull requests in + // the repos it watches, whether or not they are labelled. deps-prs + // reviews them and escalates for a human merge; it never merges. + if (config.depsPrs !== null && e.author !== null && DEPENDENCY_BOTS.has(lc(e.author)) && config.repos.some((r) => lc(r) === lc(e.unit))) return "pr"; const review = playbookFor(config, "review"); if (review === null || !config.file.reviews.enabled || e.draft || e.state !== "open") return null; if (e.author === null || viewer === null || lc(e.author) === lc(viewer)) return null; @@ -1400,7 +1627,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (store.byEntity(entity.source, entity.id) !== null) return null; const kind = adoptionKind(config, { ...entity, draft: entity.pull?.draft ?? false }, entity.viewer); if (kind === null) return null; - const playbook = playbookFor(config, kind)!; + const depBot = kind === "pr" && entity.author !== null && DEPENDENCY_BOTS.has(lc(entity.author)); + const playbook = (depBot ? config.depsPrs : null) ?? playbookFor(config, kind); + if (playbook === null) return null; const parent = kind === "ticket" ? await managedAncestor(entity) : null; const { phase, stage } = phaseAndStage(playbook, entity.state); let b: Binding; @@ -1437,6 +1666,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const bound = store.byEntity(source, id); if (bound !== null) scheduleReconcile(bound.id); if (source === "github") { + // A Dependabot alert doorbell names the alert, not the repository's + // ops binding; wake that repository's dependency watch. An id with a + // github binding is an issue or pull request, not an alert. + const repo = bound === null ? repoOfFingerprint(id) : null; + if (repo !== null) { + const deps = store.byEntity("ops", opsTargetKey({ kind: "dependabot", repo })); + if (deps !== null && deps.endedAt === null) scheduleReconcile(deps.id); + } for (const t of store.open()) { if (t.kind === "ticket" && (t.lastSnapshot?.entity.linkedPulls ?? []).some((l) => lc(l.key) === lc(id))) scheduleReconcile(t.id); } @@ -2533,7 +2770,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return toolError(new Error(`followThrough is only for after a terminal state, and ${b.entityKey} is not in one now. Report without it.`)); } const config = await loadConfig(b.projectId); - const playbook = config === null ? null : playbookFor(config, b.kind); + const playbook = config === null ? null : bindingPlaybook(config, b); // Follow-through has one deadline from when it was first declared; a // requeue past it is a requeue at it. const followThroughUntil = b.ending !== "terminal" ? null : (b.followThroughUntil ?? (input.followThrough === undefined ? null : now() + (playbook?.followThroughMs ?? DEFAULT_FOLLOW_THROUGH_MS))); @@ -2954,7 +3191,6 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (!(await settings.get()).paused) await adoptionPass(config); await keepProjectSteward(config.projectId); await syncOpsBindings(config); - const playbooks = config.playbooks; for (const b of store.open(config.projectId)) { if (b.threadId !== null) await keepSteward(config.projectId, b.threadId); const deadline = endingDeadline(b, timing.endingTimeoutMs); @@ -2967,8 +3203,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); continue; } - const playbook = playbooks[b.kind]; - if (playbook !== undefined) { + const playbook = bindingPlaybook(config, b); + if (playbook !== null) { const limit = stuckDue(b, playbook, store.openEscalations(b.id), now()); if (limit !== null) await raise(b, "stuck", `${b.entityKey}'s status has not moved in ${formatDuration(limit)} (phase ${b.phase}). What should happen?`, "Carrying on as before."); } @@ -3071,6 +3307,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const p = config.playbooks[kind]; lines.push(`${kind}: ${p === undefined ? `no usable playbook (${playbookNameFor(config.file, kind)})` : `${p.name}@${p.version}`}`); } + lines.push(`deps-alerts: ${config.depsAlerts === null ? `no playbook (${depsAlertsPlaybookName(config.file)}); the dependency watch is off` : `${config.depsAlerts.name}@${config.depsAlerts.version}`}`); + lines.push(`deps-prs: ${config.depsPrs === null ? `no playbook (${depsPrsPlaybookName(config.file)}); Dependabot pull requests are not adopted` : `${config.depsPrs.name}@${config.depsPrs.version}`}`); const validate = async (source: Source, units: string[], states: string[]) => { if (units.length === 0) return; try { @@ -3093,7 +3331,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const host = await projectHost(projectId); lines.push(`ops: kubectl runs on ${host ?? "no machine"}${config.file.ops.context === undefined ? ", in its current context" : `, in context ${config.file.ops.context}`}`); const reader = opsReaderFor(config); - for (const target of opsTargets(config.file)) lines.push(...opsAccessLines(opsTargetKey(target), await reader.access(target).catch((error: unknown): OpsAccess => ({ error: errorMessage(error), reads: [], logs: null, writes: [] })))); + for (const target of k8sTargets(config.file)) lines.push(...opsAccessLines(opsTargetKey(target), await reader.access(target).catch((error: unknown): OpsAccess => ({ error: errorMessage(error), reads: [], logs: null, writes: [] })))); + } + 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 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(", ")}`); + try { + const out = await sourceRpc("github", "sourceDependabotAlerts", { units: depsRepos.map((t) => t.repo), state: "open" }, sourceContract.sourceDependabotAlerts.output); + if (out.viewer !== null) lines.push(`deps: reading alerts as ${out.viewer}`); + for (const e of out.errors) lines.push(`deps: skipping ${e}: the gh login cannot read its alerts (a skip, not a problem)`); + } catch (error) { + lines.push(`problem: deps: could not read alerts: ${errorMessage(error)}`); + } } return { ok: !lines.some((l) => l.startsWith("problem:")), lines }; } @@ -3261,7 +3513,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b.endedAt !== null) return { exitCode: 0, stdout: `${b.entityKey} has already ended (${b.endReason}).` }; store.patch(b.id, { manualDetach: true }); const config = await loadConfig(b.projectId); - const playbook = config === null ? null : playbookFor(config, b.kind); + const playbook = config === null ? null : bindingPlaybook(config, b); await serial(`b:${b.id}`, async () => { const fresh = store.binding(b.id)!; if (config === null || playbook === null || fresh.lastSnapshot === null) await finishEnding(fresh, "detach"); diff --git a/plugins/stewards/source-contract.ts b/plugins/stewards/source-contract.ts index 3ed7a034..ba95c6ee 100644 --- a/plugins/stewards/source-contract.ts +++ b/plugins/stewards/source-contract.ts @@ -155,6 +155,39 @@ export const adoptableEntitySchema = z.object({ }); export type AdoptableEntity = z.infer; +// ---- Dependabot alerts ------------------------------------------------------- + +/** The four Dependabot severities, as GitHub reports them. */ +export const DEPENDABOT_SEVERITIES = ["critical", "high", "medium", "low"] as const; +export type DependabotSeverity = (typeof DEPENDABOT_SEVERITIES)[number]; + +/** + * One Dependabot alert, as the github plugin reads it from + * `GET /repos/{owner}/{repo}/dependabot/alerts` (which needs the token's + * alert access, not just read access to the repository). The entity id + * doorbells carry is "owner/repo#", which is the alert's own + * numbering, unrelated to the issue numbering. `repo` is spelled as GitHub + * does, which is what the doorbell carries and the github plugin leases. + */ +export const dependabotAlertSchema = z.object({ + id: z.string(), + repo: z.string(), + number: z.number().int().positive(), + severity: z.enum(DEPENDABOT_SEVERITIES), + package: z.string(), + ecosystem: z.string(), + manifestPath: z.string().nullable(), + /** open, fixed, dismissed, auto_dismissed. */ + state: z.string(), + ghsaId: z.string().nullable(), + fixedVersion: z.string().nullable(), + summary: z.string().nullable(), + url: z.string().nullable(), + createdAt: z.string().nullable(), + updatedAt: z.string().nullable(), +}); +export type DependabotAlert = z.infer; + /** Served by linear and by github; stewards is the only caller. */ export const sourceContract = { /** One entity, by Linear key or UUID, or by GitHub "owner/repo#12". Null when it does not exist or is not visible. */ @@ -211,14 +244,38 @@ export const sourceContract = { * previous set. The source leases them on bb-gate-hooks and rings stewards * for every doorbell that names one of the entities or falls in one of the * units. Only stewards may call it. + * + * `dependabot` names repositories whose Dependabot alert doorbells stewards + * 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. */ 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([]), }), output: z.object({ ok: z.boolean() }), }, + /** + * A repository's Dependabot alerts, for stewards' dependency watches. The + * github plugin reads them with the developer's token from the REST API; + * each repository the token cannot read (no alert access, alerts disabled, + * not visible) is named in `errors` rather than failing the whole call. + */ + sourceDependabotAlerts: { + input: z.object({ + units: z.array(z.string().min(1).max(200)).max(100), + /** GitHub's alert state: open (the default), fixed, dismissed, auto_dismissed. */ + state: z.string().min(1).max(60).optional(), + }), + output: z.object({ + viewer: z.string().nullable(), + alerts: z.array(dependabotAlertSchema), + errors: z.array(z.string()), + }), + }, } as const; // ---- what stewards serves --------------------------------------------------- diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 7f9780a8..3a7279a8 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -10,6 +10,7 @@ import type Database from "better-sqlite3"; 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 { opsLookSchema, type FingerprintRow, type OpsLook } from "./ops.js"; // Append-only: bb.storage.migrate records each statement's hash and refuses a @@ -155,6 +156,13 @@ export const MIGRATIONS = [ last_commented_at INTEGER, PRIMARY KEY (project_id, fingerprint) )`, + // A Dependabot alert binding's last look at its repository: the open alerts, + // classified against the fingerprint map. + `ALTER TABLE bindings ADD COLUMN deps_look TEXT`, + // A dependency fingerprint's severity and ecosystem, so a new medium or low + // alert can be batched against the open ticket for its repo and ecosystem. + `ALTER TABLE ops_fingerprints ADD COLUMN severity TEXT`, + `ALTER TABLE ops_fingerprints ADD COLUMN ecosystem TEXT`, ]; // ---- values kept as JSON ------------------------------------------------------------ @@ -264,6 +272,8 @@ export type Binding = { manualDetach: boolean; /** An ops binding's last look; null for every other kind. */ opsLook: OpsLook | null; + /** A Dependabot alert binding's last look; null for every other kind. */ + depsLook: DepsLook | null; createdAt: number; endedAt: number | null; endReason: string | null; @@ -315,6 +325,7 @@ function rowToBinding(r: BindingRow): Binding { followThroughUntil: num("follow_through_until"), manualDetach: Number(r.manual_detach) === 1, opsLook: json(opsLookSchema.nullable(), str("ops_look"), null), + depsLook: json(depsLookSchema.nullable(), str("deps_look"), null), createdAt: Number(r.created_at), endedAt: num("ended_at"), endReason: str("end_reason"), @@ -356,6 +367,7 @@ const COLUMNS = { followThroughUntil: "follow_through_until", manualDetach: "manual_detach", opsLook: "ops_look", + depsLook: "deps_look", endedAt: "ended_at", endReason: "end_reason", } as const satisfies Partial>; @@ -443,7 +455,7 @@ export type WorkerStatus = "running" | "finished" | "failed" | "stopped"; export type Worker = { threadId: string; bindingId: string; title: string; status: WorkerStatus; result: string | null; startedAt: number; endedAt: number | null }; /** One problem an ops steward has seen, and the ticket it is tracked under. */ -export type Fingerprint = FingerprintRow & { projectId: string; bindingId: string; summary: string; lastSeenAt: number; seenCount: number; filedAt: number | null }; +export type Fingerprint = FingerprintRow & { projectId: string; bindingId: string; summary: string; lastSeenAt: number; seenCount: number; filedAt: number | null; severity: string | null; ecosystem: string | null }; /** What a steward reports doing about a fingerprint: filing a ticket, commenting on one, or reopening one. */ export type TicketAction = "filed" | "commented" | "reopened"; @@ -505,8 +517,9 @@ export function createStore(db: Database.Database, now: () => number) { const getFingerprint = db.prepare<[string, string], Record>("SELECT * FROM ops_fingerprints WHERE project_id = ? AND fingerprint = ?"); const fingerprintsFor = db.prepare<[string], Record>("SELECT * FROM ops_fingerprints WHERE binding_id = ? ORDER BY first_seen_at"); const sight = db.prepare( - `INSERT INTO ops_fingerprints (project_id, fingerprint, binding_id, summary, first_seen_at, last_seen_at) VALUES (@project_id, @fingerprint, @binding_id, @summary, @at, @at) - ON CONFLICT (project_id, fingerprint) DO UPDATE SET binding_id = @binding_id, summary = @summary, last_seen_at = @at, seen_count = seen_count + 1`, + `INSERT INTO ops_fingerprints (project_id, fingerprint, binding_id, summary, severity, ecosystem, first_seen_at, last_seen_at) VALUES (@project_id, @fingerprint, @binding_id, @summary, @severity, @ecosystem, @at, @at) + ON CONFLICT (project_id, fingerprint) DO UPDATE SET binding_id = @binding_id, summary = @summary, last_seen_at = @at, seen_count = seen_count + 1, + severity = COALESCE(@severity, severity), ecosystem = COALESCE(@ecosystem, ecosystem)`, ); const setTicket = db.prepare("UPDATE ops_fingerprints SET ticket_key = ?, filed_at = ?, last_commented_at = ? WHERE project_id = ? AND fingerprint = ?"); const setCommented = db.prepare("UPDATE ops_fingerprints SET ticket_key = ?, last_commented_at = ? WHERE project_id = ? AND fingerprint = ?"); @@ -590,6 +603,8 @@ export function createStore(db: Database.Database, now: () => number) { seenCount: Number(r.seen_count), filedAt: r.filed_at === null ? null : Number(r.filed_at), lastCommentedAt: r.last_commented_at === null ? null : Number(r.last_commented_at), + severity: r.severity === null || r.severity === undefined ? null : String(r.severity), + ecosystem: r.ecosystem === null || r.ecosystem === undefined ? null : String(r.ecosystem), }); const toProject = (r: Record): ProjectStewardRow => ({ projectId: String(r.project_id), @@ -872,12 +887,12 @@ export function createStore(db: Database.Database, now: () => number) { return fingerprintsFor.all(bindingId).map(toFingerprint); }, /** Record that a look saw these problems: new ones enter the map with no ticket, known ones count another sighting. */ - sight(projectId: string, bindingId: string, seen: Array<{ fingerprint: string; summary: string }>): Map { + sight(projectId: string, bindingId: string, seen: Array<{ fingerprint: string; summary: string; severity?: string | null; ecosystem?: string | null }>): Map { return db.transaction(() => { const at = now(); const out = new Map(); for (const s of seen) { - sight.run({ project_id: projectId, fingerprint: s.fingerprint, binding_id: bindingId, summary: s.summary, at }); + sight.run({ project_id: projectId, fingerprint: s.fingerprint, binding_id: bindingId, summary: s.summary, severity: s.severity ?? null, ecosystem: s.ecosystem ?? null, at }); out.set(s.fingerprint, toFingerprint(getFingerprint.get(projectId, s.fingerprint)!)); } return out; diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index e6c40780..1c00204d 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -29,6 +29,9 @@ export function projectFileTemplate(teams: string[]): string { bigDecisions: DEFAULT_BIG_DECISIONS, // Add a target, such as { "kind": "k8s-namespace", "name": "bb-gate-production" }, to watch it. ops: { targets: [], autoAdopt: [] }, + // Dependabot alerts: a per-severity SLA, the batch window a medium or low + // alert may wait for company, and the severities adopted when filed. + deps: { sla: { critical: "asap", high: "1d", medium: "7d", low: "30d" }, batch: { medium: "7d", low: "30d" }, autoAdopt: ["critical", "high"] }, }, null, 2, @@ -279,9 +282,118 @@ a decision recommending it be reopened. Otherwise file a new ticket that links the old one, and escalate it as a new one. `; +export const DEPS_ALERTS = `--- +name: deps-alerts +kind: ops +source: github +may: [file-ticket, comment, escalate, set-state] +models: + steward: claude/claude-sonnet-5-5/medium +requeue-default: 1d +--- + +You watch one repository's Dependabot alerts and turn them into Linear +tickets. You never change code and start no workers: the ticket steward and +its worker make the upgrade pull request, reviewed and merged by lane. + +Each alert has a fingerprint, the alert's number in the repository's alert +numbering: put it in the ticket description on a line of its own, +"Fingerprint: \`#\`", so a person can match ticket and +alert. After acting, report every ticket you filed, commented on or closed in +steward_report's opsTickets: that is how the next look knows an alert is +already filed. When the wake says there are no open alerts, just report it, +with actor other, and end the turn. + +Severity decides the Linear priority and the due date: the wake gives each +alert's priority and deadline. critical and high get a ticket of their own +and are escalated at once; medium and low coalesce into one open ticket per +repository per ecosystem. The wake's batch plan says, for each new medium or +low alert, whether to file a new ticket, join an open one, or tighten an open +ticket's due date; follow it. When you file or comment, list every alert the +ticket covers, with its package, ecosystem, manifest path, GHSA id and fixed +version. A recurrence of an alert already on a ticket is a comment there, +never a second ticket. + +A ticket you file says: the repository and ecosystem; each alert's package, +severity, GHSA id and fixed version; the manifest path; the priority and due +date from the SLA; and the fingerprint lines. Search the team for an open +ticket about the same repository and ecosystem first (linear_search), and +comment there instead of filing a second one. A fixed or dismissed alert is +trimmed from its ticket's list; a ticket with no alerts left is moved to Done +with a comment saying why. + +## New + +File one ticket per problem, in the team the wake names, with the priority +and due date the wake gives. Then raise one decision escalation to the +project steward for every ticket filed this turn: "Filed BB-N (high): . Recommend adopting." A severity deps.autoAdopt names is labelled and +moved to Todo when filed, as the wake says; such a ticket needs no +escalation. For a medium or low alert whose plan is to join or tighten, do +that instead of filing. + +## Recurring + +The alert is still open and its ticket is open. Comment on that ticket when +the evidence moved (a new fixed version, a severity change, another alert on +the same ticket), and at most once a day otherwise. File nothing new. Follow +the wake's batch plan when a new alert tightens the ticket's due date. + +## Returned + +The alert is back after its ticket was resolved. If the ticket was closed +within the last two weeks, comment on it with the new evidence and escalate a +decision recommending it be reopened. Otherwise file a new ticket that links +the old one, and escalate it as a new one. +`; + +export const DEPS_PRS = `--- +name: deps-prs +kind: pr +source: github +phases: + draft: { stage: build } + open: { stage: review, stuck: 3d } +terminal: [merged, closed] +may: [comment, request-review, escalate, spawn-worker] +models: + steward: claude/claude-sonnet-5-5/medium + worker: claude/claude-opus-5-5/high +requeue-default: 2d +skip-authors: [dependabot, "dependabot[bot]", "renovate[bot]"] +--- + +You steward one Dependabot version-update pull request until it is merged or +closed. You never merge it: you adopt it, review it, and escalate it for a +human merge. A patch or minor bump whose checks are green is escalated for a +human merge. A major bump, or anything touching a path the project's +guidance (AGENTS.md) says is owner-reviewed, is escalated with the reason. + +Use gh for everything you do on GitHub, and sign what you write. A merge to +bb-plugins main rebuilds the bb-server image and stages a restart for every +developer, so the escalation and the eventual merge comment say so. + +## draft + +Get it ready: a worker fixes failing checks and finishes what the description +says is left. When checks pass, mark it ready (\`gh pr ready\`) and escalate +for a human merge as above. + +## open + +Review the bump against the project's guidance. When it is a patch or minor +bump with green checks, escalate a decision for a human merge, saying the +version and that a merge stages a restart. When it is a major bump, or it +touches an owner-reviewed path, escalate a decision with the reason and do +not ask for a merge. Address review comments with a worker and re-request +review after each round. Do not merge, and do not approve on GitHub. +`; + export const PLAYBOOK_TEMPLATES: Record = { "linear-tickets": LINEAR_TICKETS, "github-prs": GITHUB_PRS, "github-reviews": GITHUB_REVIEWS, "ops-watch": OPS_WATCH, + "deps-alerts": DEPS_ALERTS, + "deps-prs": DEPS_PRS, }; diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 652f47a7..ff7e5253 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -8,6 +8,7 @@ import { formatDuration, phaseInstructions, type Playbook } from "./config.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"; import { newHumanComments, prGate, reportedItem, unheardWait, type GateState } from "./reconcile.js"; import type { EntitySnapshot, SessionWake, SnapshotComment } from "./source-contract.js"; import type { Binding, Escalation, Need, Observed, Question, Worker } from "./store.js"; @@ -413,6 +414,99 @@ export function formatOpsWake(input: OpsWakeInput): string { return fit(head, snapshot, out); } +export type DepsWakeInput = { + reason: WakeReason; + binding: Binding; + playbook: Playbook; + look: DepsLook; + /** The Linear team tickets are filed in. */ + team: string | null; + label: string; + /** Severities whose tickets are labelled when filed (deps.autoAdopt). */ + autoAdopt: string[]; + escalations: Escalation[]; + changes: string[]; +}; + +const DEPS_LIFECYCLE: Partial> = { + adopted: "You have just been made the dependency steward for this repository. Read everything below, then act on the alerts.", + reopen: "This repository is watched again and its binding has resumed. Re-read everything below as if new.", + nightly: "This is the nightly reconcile pass: re-list the open alerts and check that every one is filed, batched or trimmed.", +}; + +const DEPS_CLASS_TITLES: Record = { new: "New: no ticket yet", recurring: "Recurring: its ticket is open", returned: "Returned: its ticket was resolved" }; + +const days = (ms: number) => new Date(ms).toISOString().slice(0, 10); + +function depsAlertLines(a: DepsFinding): string[] { + const lines: string[] = [`#### ${a.fingerprint}`, ""]; + const ticket = a.ticket === null ? "" : ` · ticket ${a.ticket}${a.ticketState === null ? "" : ` (${a.ticketState})`}${a.lastCommentedAt === null ? "" : `, your last word on it ${iso(a.lastCommentedAt)}`}`; + lines.push(`- **${a.severity}** priority ${a.priority}, due ${days(a.dueAt)}${ticket}`); + lines.push(`- \`${a.package}\` (${a.ecosystem})${a.manifestPath === null ? "" : ` — ${a.manifestPath}`}${a.ghsaId === null ? "" : ` — ${a.ghsaId}`}`); + lines.push(`- ${a.fixedVersion === null ? "No fixed version yet" : `Fixed in ${a.fixedVersion}`}; first seen ${iso(a.firstSeenAt)}${a.url === null ? "" : ` — ${a.url}`}`); + if (a.batch.kind === "join") lines.push(`- Batch: join the open ticket ${a.batch.ticketKey} (its due date is already inside this alert's).`); + else if (a.batch.kind === "tighten") lines.push(`- Batch: tighten the open ticket ${a.batch.ticketKey} to due ${days(a.batch.dueAt)}.`); + else if (a.severity === "medium" || a.severity === "low") lines.push("- Batch: no open ticket for this repo and ecosystem; file a new one."); + else lines.push("- This severity gets its own ticket."); + return [...lines, ""]; +} + +/** A dependency binding's wake: instructions, steering, the alerts, what changed. */ +export function formatDepsWake(input: DepsWakeInput): string { + const { binding, playbook, look } = input; + const out: string[] = []; + out.push(`# Deps watch: ${look.target}`); + out.push(`Binding ${binding.id} · deps · playbook ${playbook.name}@${playbook.version} · looked ${iso(look.at)}`); + out.push("", `${binding.threadId === null ? "Your thread id is in `$BB_THREAD_ID`." : `Your thread id is ${binding.threadId}.`} Use it wherever you name yourself, and never take one from your workspace's path: you share the project steward's workspace, and its path names that thread.`); + const special = DEPS_LIFECYCLE[input.reason]; + if (special !== undefined) out.push("", `**${special}**`); + + out.push("", "## 1. Instructions"); + if (playbook.general !== "") out.push("", playbook.general); + const present = FINDING_CLASSES.filter((c) => look.alerts.some((a) => a.class === c)); + for (const c of present) { + const section = phaseInstructions(playbook, c); + if (section !== null) out.push("", `### ${c.charAt(0).toUpperCase()}${c.slice(1)}`, "", section); + } + out.push("", `Allowed actions: ${playbook.may.join(", ") || "(none)"}.`); + out.push(input.team === null ? "No Linear team is configured to file in: escalate a blocked question instead of filing." : `File tickets in the Linear team ${input.team} with linear_create_issue, and set each ticket's due date to the deadline the alert names.`); + if (input.autoAdopt.length > 0) { + out.push(`deps.autoAdopt: a ticket you file for a ${input.autoAdopt.join(" or ")} alert is adopted at once: add the label \`${input.label}\` and move it to Todo when you file it, and raise no escalation for it. Say in your report that you did.`); + } + + out.push("", "## 2. Guidance, priority and holds", ""); + if (binding.guidance.length === 0) out.push("No standing guidance."); + for (const g of binding.guidance) out.push(`- ${iso(g.at)} (${g.by}): ${g.text}`); + out.push(`- Priority: ${binding.priority ?? "normal"}`); + out.push(binding.hold === null ? "- Hold: none" : `- **HOLD: ${binding.hold}** — file and comment nothing until it is lifted.`); + + const head = out.splice(0); + out.push("", "## 3. The alerts", ""); + if (look.error !== null) out.push(`The repository could not be read: ${look.error}. Nothing to do until it can; \`bb stewards check\` says why.`); + else if (look.alerts.length === 0) out.push("**No open alerts.** Nothing to file, comment on or close: report that with steward_report (actor other) and end the turn."); + for (const c of present) { + out.push("", `### ${DEPS_CLASS_TITLES[c]}`, ""); + for (const a of look.alerts.filter((x) => x.class === c)) out.push(...depsAlertLines(a)); + } + const open = input.escalations.filter((x) => x.status === "open"); + if (open.length > 0) { + out.push("", "### Open escalations", ""); + for (const x of open) out.push(`- ${x.id} (${x.kind}, with ${x.route === "me" ? "the user" : "the project steward"}): ${x.question}`); + } + + const snapshot = out.splice(0); + out.push("", "## 4. What changed since your last turn", ""); + if (input.changes.length === 0) out.push("Nothing new; this is a scheduled look."); + for (const c of input.changes) out.push(`- ${c}`); + out.push( + "", + "---", + "Before filing, look for evidence that you already did (a signed ticket or comment with the fingerprint). " + + `End your turn with steward_report, listing in opsTickets every ticket you filed, commented on or reopened, by fingerprint: { fingerprint, ticket: "${input.team ?? "ENG"}-123", did: "filed" | "commented" | "reopened" }. requeueAfter defaults to ${formatDuration(playbook.requeueDefaultMs)}.`, + ); + return fit(head, snapshot, out); +} + /** What the project steward is woken with, at the end of a nightly pass or when an escalation reaches it. */ export function formatProjectWake(input: { reason: string; From f9ff9b3abfc1017caa44595764c69e4f9f80b3d4 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Tue, 20 Oct 2026 05:36:25 +0000 Subject: [PATCH 2/2] stewards: address review round 1 on BB-12 - Batching joins only open tickets: openBatchedTickets now drops a ticket whose Linear state is completed or canceled, so a resolved batched ticket is not joined and a new alert files a new one. The ticket states are read for every fingerprint row, not just this look's alerts. - deps-alerts no longer contradicts itself: a severity in deps.autoAdopt is adopted and raises no escalation, and one it does not name raises one decision escalation. A test pins both. - sourceDependabotAlerts follows the Link header, so a repo with more than one page of alerts is read whole. - A tighten is phrased "no later than X (the earlier of its current due date and this deadline)", so it never loosens a ticket. - deps-prs adoption uses the same depsTargets list as alert watching, so an explicit dependabot target's bot PRs are adopted too. - Due dates are formatted in the project's nightly time zone. - A deps-prs binding ends when deps-prs.md disappears instead of falling back to the merge-capable github-prs playbook. --- plugins/github-watcher/server.test.ts | 16 ++++++++-- plugins/github-watcher/server.ts | 21 ++++++++++---- plugins/stewards/deps.test.ts | 4 ++- plugins/stewards/deps.ts | 6 ++-- plugins/stewards/server.test.ts | 42 +++++++++++++++++++++++++-- plugins/stewards/server.ts | 29 ++++++++++++++---- plugins/stewards/templates.ts | 16 +++++----- plugins/stewards/wake.ts | 13 +++++---- 8 files changed, 115 insertions(+), 32 deletions(-) diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index 3f49b64b..c9715210 100644 --- a/plugins/github-watcher/server.test.ts +++ b/plugins/github-watcher/server.test.ts @@ -38,7 +38,7 @@ 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[], 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" }; 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, ""); @@ -48,7 +48,10 @@ function fakeGitHub() { if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); if (`${dependabot[1]}/${dependabot[2]}`.toLowerCase() !== "acme/widgets") return Response.json({ message: "Not Found" }, { status: 404 }); if (state.dependabotStatus !== 200) return Response.json({ message: state.dependabotMessage }, { status: state.dependabotStatus }); - return Response.json(state.dependabotAlerts); + const page = new URL(u).searchParams.get("page"); + if (page === "2") return Response.json(state.dependabotPage2); + const headers = state.dependabotPage2.length > 0 ? { link: `<${API_URL}/repos/acme/widgets/dependabot/alerts?state=open&per_page=100&page=2>; rel="next"` } : undefined; + return Response.json(state.dependabotAlerts, headers === undefined ? undefined : { headers }); } if (u !== `${API_URL}/graphql`) return new Response("not found", { status: 404 }); const body = JSON.parse(String(init?.body)) as { query: string; variables: Record }; @@ -552,6 +555,15 @@ describe("stewards' source contract", () => { expect(await w.harness.callRpc("sourceDependabotAlerts", { units: ["Acme/Widgets"], state: "open" }, STEWARDS)).toMatchObject({ alerts: [], errors: ["Acme/Widgets: GitHub answered HTTP 403: Resource not accessible by integration"] }); }); + it("follows the Link header so a repository with more than one page of alerts is read whole", async () => { + const w = await setup(); + w.github.state.dependabotAlerts = [{ number: 1, state: "open", dependency: { package: { ecosystem: "npm", name: "a" } }, security_advisory: { severity: "low" }, security_vulnerability: { first_patched_version: null } }]; + w.github.state.dependabotPage2 = [{ number: 2, state: "open", dependency: { package: { ecosystem: "npm", name: "b" } }, security_advisory: { severity: "high" }, security_vulnerability: { first_patched_version: null } }]; + const out = (await w.harness.callRpc("sourceDependabotAlerts", { units: ["Acme/Widgets"], state: "open" }, STEWARDS)) as { alerts: Array<{ id: string }>; errors: string[] }; + expect(out.alerts.map((a) => a.id)).toEqual(["Acme/Widgets#1", "Acme/Widgets#2"]); + expect(out.errors).toEqual([]); + }); + describe("interest", () => { beforeEach(() => vi.useFakeTimers()); afterEach(() => vi.useRealTimers()); diff --git a/plugins/github-watcher/server.ts b/plugins/github-watcher/server.ts index e8b0b4bf..bdb5a3c2 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -148,12 +148,14 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => } /** - * One REST call with the token, for what GraphQL does not expose: + * One REST page with the token, for what GraphQL does not expose: * Dependabot alerts. A non-2xx answer throws with the status, so a 403 or * 404 (no alert access, alerts off, not visible) can be told apart from a - * network failure and named per repository by the caller. + * network failure and named per repository by the caller. The `next` URL + * is from the `Link` header, so a repository with more than one page of + * alerts is read whole. */ - async function rest(path: string, signal: AbortSignal): Promise { + async function restPage(path: string, signal: AbortSignal): Promise<{ body: unknown; next: string | null }> { return asDeveloper(async (token) => { const response = await deps.fetch(new URL(path, apiUrl), { method: "GET", @@ -165,7 +167,9 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => const message = body !== null && typeof body === "object" && typeof (body as { message?: unknown }).message === "string" ? (body as { message: string }).message : ""; throw new GitHubRequestError(`GitHub answered HTTP ${response.status}${message === "" ? "" : `: ${message}`}`, response.status); } - return body; + const link = response.headers.get("link") ?? ""; + const next = /<([^>]+)>;\s*rel="next"/u.exec(link)?.[1] ?? null; + return { body, next }; }); } @@ -520,7 +524,14 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => } const name = `${repo.owner}/${repo.name}`; try { - alerts.push(...parseDependabotAlerts(await rest(dependabotAlertsPath(name, state ?? "open"), checkSignal()), name)); + const seen = new Set(); + let next: string | null = dependabotAlertsPath(name, state ?? "open"); + while (next !== null && !seen.has(next)) { + seen.add(next); + const page = await restPage(next, checkSignal()); + alerts.push(...parseDependabotAlerts(page.body, name)); + next = page.next; + } } catch (error) { errors.push(`${unit}: ${errorMessage(error)}`); } diff --git a/plugins/stewards/deps.test.ts b/plugins/stewards/deps.test.ts index 69b5d788..48e01359 100644 --- a/plugins/stewards/deps.test.ts +++ b/plugins/stewards/deps.test.ts @@ -35,7 +35,9 @@ describe("severity and the SLA", () => { expect(deadlineAt("high", DEFAULT_SLA, now)).toBe(now + 86_400_000); expect(deadlineAt("medium", DEFAULT_SLA, now)).toBe(now + 7 * 86_400_000); expect(deadlineAt("low", DEFAULT_SLA, now)).toBe(now + 30 * 86_400_000); - expect(dueDate(now + 86_400_000)).toBe("2026-10-15"); + expect(dueDate(now + 86_400_000, "UTC")).toBe("2026-10-15"); + // The project's time zone decides the calendar day. + expect(dueDate(Date.parse("2026-10-15T01:00:00Z"), "America/New_York")).toBe("2026-10-14"); }); it("batches only medium and low", () => { diff --git a/plugins/stewards/deps.ts b/plugins/stewards/deps.ts index eb3e93ae..02027542 100644 --- a/plugins/stewards/deps.ts +++ b/plugins/stewards/deps.ts @@ -83,9 +83,9 @@ export function alertLine(alert: Pick { ...over, }); - async function watching(alerts: unknown[] = [alert()]) { + async function watching(alerts: unknown[] = [alert()], project: Record = {}) { const t = await setup(); - t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] } }); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] }, ...project }); t.files[playbookPath("deps-alerts")] = DEPS_ALERTS; t.files[playbookPath("deps-prs")] = DEPS_PRS; t.dependabotAlerts.set("acme/web", alerts); @@ -2651,7 +2651,28 @@ describe("dependency stewards", () => { await t.flush(); const tightened = wakes().at(-1)!; expect(tightened).toContain("#### acme/web#6"); - expect(tightened).toMatch(/Batch: tighten the open ticket ENG-50 to due \d{4}-\d{2}-\d{2}\./u); + expect(tightened).toMatch(/Batch: tighten the open ticket ENG-50's due date to no later than \d{4}-\d{2}-\d{2}/u); + + // Once the ticket is resolved, a new low alert files a new one instead of joining it. + t.entities.set("ENG-50", issue({ id: "ENG-50", key: "ENG-50", state: "Done", stateType: "completed" })); + t.advance(86_400_000); + t.dependabotAlerts.set("acme/web", [alert({ number: 7, severity: "low", ghsaId: "GHSA-low-3", package: "tar" })]); + await t.hooks.sweep(); + await t.flush(); + const afterDone = wakes().at(-1)!; + expect(afterDone).toContain("#### acme/web#7"); + expect(afterDone).toMatch(/Batch: no open ticket for this repo and ecosystem; file a new one\./u); + expect(afterDone).not.toMatch(/Batch: join the open ticket ENG-50/u); + }); + + it("suppresses the escalation only for the severities deps.autoAdopt names", async () => { + const adopted = await watching(); + expect(adopted.wakes()[0]).toMatch(/deps\.autoAdopt: a ticket you file for a critical or high alert is adopted at once/u); + expect(adopted.wakes()[0]).toMatch(/a severity it does not name\s+raises one decision escalation/u); + + const escalate = await watching([alert({ number: 4, severity: "high" })], { deps: { autoAdopt: [] } }); + expect(escalate.wakes()[0]).not.toMatch(/deps\.autoAdopt:/u); + expect(escalate.wakes()[0]).toMatch(/a severity it does not name\s+raises one decision escalation/u); }); it("wakes on a fixed alert so its ticket is trimmed, and rings on a dependabot_alert doorbell", async () => { @@ -2691,6 +2712,21 @@ describe("dependency stewards", () => { expect(prompt).toMatch(/never merge it: you adopt it, review it, and escalate it for a\s+human merge/u); }); + it("ends a deps-prs binding when the playbook disappears rather than falling back to a merge-capable one", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] } }); + t.files[playbookPath("deps-prs")] = DEPS_PRS; + t.entities.set("acme/web#9", pull({ id: "acme/web#9", key: "acme/web#9", author: "dependabot[bot]", labels: [] })); + await t.hooks.sweep(); + await t.flush(); + expect(await t.list()).toEqual(expect.arrayContaining([expect.objectContaining({ key: "acme/web#9", kind: "pr", ended: false })])); + + delete t.files[playbookPath("deps-prs")]; + await t.hooks.sweep(); + await t.flush(); + expect(await t.list()).toEqual(expect.arrayContaining([expect.objectContaining({ key: "acme/web#9", kind: "pr", ended: true })])); + }); + it("checks the deps SLA, batch and autoAdopt, and says which repos the gh login cannot read", async () => { const { t } = await watching(); const check = await t.harness.behavior.runCli(["check"], { projectId: "p1" }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 680d9237..d0be2e81 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -1042,7 +1042,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const config = await loadConfig(b.projectId); if (config === null) return; const playbook = bindingPlaybook(config, b); - if (playbook === null) return; + if (playbook === null) { + // A dependency bot's pull request runs under deps-prs only. With the + // playbook gone, the binding ends rather than falling back to a + // merge-capable playbook the ticket says must never merge. + if (b.kind === "pr" && b.playbook === depsPrsPlaybookName(config.file) && b.endedAt === null) await finishEnding(b, "unconfigured"); + return; + } if (b.source === "ops") { await reconcileOps(b, config, playbook, force); return; @@ -1238,13 +1244,19 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * The open tickets a new medium or low alert may join, one per repo and * ecosystem: grouped from the fingerprint map by ticket, each with the * tightest deadline among its alerts. Only batchable (medium and low) - * fingerprints count, since critical and high never coalesce. + * fingerprints count, since critical and high never coalesce, and a + * ticket that is completed or canceled is not open: a new alert for its + * repo and ecosystem files a new ticket rather than commenting on a + * resolved one. A ticket whose state cannot be read counts as open, as + * in `classify`. */ - function openBatchedTickets(rows: readonly Fingerprint[], sla: ProjectFile["deps"]["sla"]): DepsTicket[] { + function openBatchedTickets(rows: readonly Fingerprint[], sla: ProjectFile["deps"]["sla"], tickets: ReadonlyMap): DepsTicket[] { const byTicket = new Map(); for (const r of rows) { if (r.ticketKey === null || r.severity === null || r.ecosystem === null) continue; if (!isBatchable(r.severity as DependabotSeverity)) continue; + const state = tickets.get(r.ticketKey) ?? null; + if (state !== null && (state.stateType === "completed" || state.stateType === "canceled")) continue; const repo = repoOfFingerprint(r.fingerprint); if (repo === null) continue; const dueAt = deadlineAt(r.severity as DependabotSeverity, sla, r.firstSeenAt); @@ -1269,10 +1281,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return { fingerprint: s.fingerprint, summary: s.summary, severity: s.severity, ecosystem: s.ecosystem }; }), ); + // Every fingerprint row, not just this look's: a batched ticket that + // is no longer in the open alerts still has rows, and whether it is + // open decides if a new medium or low alert may join it. + const allRows = store.fingerprints(b.id); const sightings: Sighting[] = alerts.map((a) => ({ fingerprint: alertFingerprint(a), workload: a.package, pods: [], container: null, signature: a.severity, summary: `${a.severity} ${a.package}`, restarts: 0, events: [], logs: null, previous: false })); - const tickets = await ticketStates([...rows.values()].map((r) => r.ticketKey).filter((k): k is string => k !== null)); + const tickets = await ticketStates([...allRows].map((r) => r.ticketKey).filter((k): k is string => k !== null)); const findings = classify(sightings, rows, tickets, at); - const open = openBatchedTickets(store.fingerprints(b.id), config.file.deps.sla); + const open = openBatchedTickets(allRows, config.file.deps.sla, tickets); const byFingerprint = new Map(alerts.map((a) => [alertFingerprint(a), a])); const depsFindings: DepsFinding[] = []; for (const f of findings) { @@ -1438,6 +1454,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P team: opsTeam(config.file), label: config.file.label, autoAdopt: config.file.deps.autoAdopt, + timeZone: config.file.nightly.timezone, escalations: store.openEscalations(b.id), changes: [...new Set(changes.map((c) => c.text))], }); @@ -1599,7 +1616,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // The dependency watch adopts the bot's version-update pull requests in // the repos it watches, whether or not they are labelled. deps-prs // reviews them and escalates for a human merge; it never merges. - if (config.depsPrs !== null && e.author !== null && DEPENDENCY_BOTS.has(lc(e.author)) && config.repos.some((r) => lc(r) === lc(e.unit))) return "pr"; + if (config.depsPrs !== null && e.author !== null && DEPENDENCY_BOTS.has(lc(e.author)) && depsTargets(config.file, config.repos).some((t) => lc(t.repo) === lc(e.unit))) return "pr"; const review = playbookFor(config, "review"); if (review === null || !config.file.reviews.enabled || e.draft || e.state !== "open") return null; if (e.author === null || viewer === null || lc(e.author) === lc(viewer)) return null; diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index 1c00204d..220c6625 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -306,13 +306,15 @@ with actor other, and end the turn. Severity decides the Linear priority and the due date: the wake gives each alert's priority and deadline. critical and high get a ticket of their own -and are escalated at once; medium and low coalesce into one open ticket per -repository per ecosystem. The wake's batch plan says, for each new medium or -low alert, whether to file a new ticket, join an open one, or tighten an open -ticket's due date; follow it. When you file or comment, list every alert the -ticket covers, with its package, ecosystem, manifest path, GHSA id and fixed -version. A recurrence of an alert already on a ticket is a comment there, -never a second ticket. +at once; medium and low coalesce into one open ticket per repository per +ecosystem. A severity deps.autoAdopt names is adopted when filed (labelled +and moved to Todo) and raises no escalation; a severity it does not name +raises one decision escalation. The wake's batch plan says, for each new +medium or low alert, whether to file a new ticket, join an open one, or +tighten an open ticket's due date; follow it. When you file or comment, list +every alert the ticket covers, with its package, ecosystem, manifest path, +GHSA id and fixed version. A recurrence of an alert already on a ticket is a +comment there, never a second ticket. A ticket you file says: the repository and ecosystem; each alert's package, severity, GHSA id and fixed version; the manifest path; the priority and due diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index ff7e5253..b2455496 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -9,6 +9,7 @@ import { formatDuration, phaseInstructions, type Playbook } from "./config.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"; +import { dueDate } from "./deps.js"; import { newHumanComments, prGate, reportedItem, unheardWait, type GateState } from "./reconcile.js"; import type { EntitySnapshot, SessionWake, SnapshotComment } from "./source-contract.js"; import type { Binding, Escalation, Need, Observed, Question, Worker } from "./store.js"; @@ -424,6 +425,8 @@ export type DepsWakeInput = { label: string; /** Severities whose tickets are labelled when filed (deps.autoAdopt). */ autoAdopt: string[]; + /** The project's time zone, which due dates are given in. */ + timeZone: string; escalations: Escalation[]; changes: string[]; }; @@ -436,16 +439,16 @@ const DEPS_LIFECYCLE: Partial> = { const DEPS_CLASS_TITLES: Record = { new: "New: no ticket yet", recurring: "Recurring: its ticket is open", returned: "Returned: its ticket was resolved" }; -const days = (ms: number) => new Date(ms).toISOString().slice(0, 10); -function depsAlertLines(a: DepsFinding): string[] { + +function depsAlertLines(a: DepsFinding, timeZone: string): string[] { const lines: string[] = [`#### ${a.fingerprint}`, ""]; const ticket = a.ticket === null ? "" : ` · ticket ${a.ticket}${a.ticketState === null ? "" : ` (${a.ticketState})`}${a.lastCommentedAt === null ? "" : `, your last word on it ${iso(a.lastCommentedAt)}`}`; - lines.push(`- **${a.severity}** priority ${a.priority}, due ${days(a.dueAt)}${ticket}`); + lines.push(`- **${a.severity}** priority ${a.priority}, due ${dueDate(a.dueAt, timeZone)}${ticket}`); lines.push(`- \`${a.package}\` (${a.ecosystem})${a.manifestPath === null ? "" : ` — ${a.manifestPath}`}${a.ghsaId === null ? "" : ` — ${a.ghsaId}`}`); lines.push(`- ${a.fixedVersion === null ? "No fixed version yet" : `Fixed in ${a.fixedVersion}`}; first seen ${iso(a.firstSeenAt)}${a.url === null ? "" : ` — ${a.url}`}`); if (a.batch.kind === "join") lines.push(`- Batch: join the open ticket ${a.batch.ticketKey} (its due date is already inside this alert's).`); - else if (a.batch.kind === "tighten") lines.push(`- Batch: tighten the open ticket ${a.batch.ticketKey} to due ${days(a.batch.dueAt)}.`); + else if (a.batch.kind === "tighten") lines.push(`- Batch: tighten the open ticket ${a.batch.ticketKey}'s due date to no later than ${dueDate(a.batch.dueAt, timeZone)} (the earlier of its current due date and this deadline).`); else if (a.severity === "medium" || a.severity === "low") lines.push("- Batch: no open ticket for this repo and ecosystem; file a new one."); else lines.push("- This severity gets its own ticket."); return [...lines, ""]; @@ -486,7 +489,7 @@ export function formatDepsWake(input: DepsWakeInput): string { else if (look.alerts.length === 0) out.push("**No open alerts.** Nothing to file, comment on or close: report that with steward_report (actor other) and end the turn."); for (const c of present) { out.push("", `### ${DEPS_CLASS_TITLES[c]}`, ""); - for (const a of look.alerts.filter((x) => x.class === c)) out.push(...depsAlertLines(a)); + for (const a of look.alerts.filter((x) => x.class === c)) out.push(...depsAlertLines(a, input.timeZone)); } const open = input.escalations.filter((x) => x.status === "open"); if (open.length > 0) {