diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index d24fa85c..bd11429c 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -731,15 +731,19 @@ goes wrong there into Linear tickets for the project steward to adopt. ```jsonc "ops": { - "targets": [{ "kind": "k8s-namespace", "name": "bb-gate-production" }], + "targets": [ + { "kind": "k8s-namespace", "name": "bb-gate-production" }, + { "kind": "sentry-project", "org": "acme", "project": "web" } + ], "team": "BB", // where tickets are filed; the first linear.teams entry when left out "autoAdopt": ["urgent"] // priorities labelled when filed, without asking; empty by default } ``` - **The entity is the target.** One binding per target, keyed - `k8s-namespace/`, with the source `ops`: there is no source plugin - behind it, and `source-contract.ts` does not change. It has no phases + `k8s-namespace/` or `sentry-project//`, with the + source `ops`: there is no source plugin behind it, and + `source-contract.ts` does not change. It has no phases keyed on entity state and no terminal state. It lives while the project file lists its target: taken out, the binding ends (`unconfigured`) and its thread is archived; put back, the same binding and thread resume. @@ -809,18 +813,93 @@ goes wrong there into Linear tickets for the project steward to adopt. then filing, commenting and escalating), and like every `may` list it is advisory (§11): nothing stops the steward's shell. A real wall, such as a read-only identity for kubectl, would slot in behind that one function. -- **`bb stewards check`** validates `ops` (namespace names, duplicates, - that the team is one of `linear.teams`), then runs kubectl on the - project's machine for each target: `get` its pods, events and +- **`bb stewards check`** validates `ops` (namespace names, Sentry slugs, + duplicates, that the team is one of `linear.teams`), then runs kubectl + on the project's machine for each namespace: `get` its pods, events and deployments, and `auth can-i` for its logs. A target kubectl cannot reach — no kubectl, the machine not on the tailnet as the developer, no kubeconfig or context for the cluster, pods forbidden — is a problem, "cannot read the target". Writes the identity holds there are said, not - counted as a problem: they are expected of a developer. + counted as a problem: they are expected of a developer. For each Sentry + project it reads the project with the plugin's token (no token, or a + refusal, is a problem) and says how doorbells arrive: the bb-gate-hooks + stream's state, or that there is no service here. - **When kubectl cannot read the target**, the binding is made but its steward is not spawned or woken; `bb stewards list` shows `cannot read the target`, and the first look that succeeds wakes it. +### Sentry projects + +A `sentry-project` target is the push source the k8s look lacks: an error +that does not crash a pod is still an issue in Sentry, and Sentry knows of +it the moment it happens. The target runs the same `ops-watch` playbook +and the same fingerprint map; what differs is how the plugin looks and +what a wake carries. + +- **The credential is the plugin's, a secret setting.** `sentryToken` on + the stewards plugin holds a Sentry *user auth token* with `project:read` + and `event:read`, entered by the user in the plugin's settings and never + pasted into a thread; `sentryApiUrl` points at a self-hosted Sentry. The + ticket's decision: no `sentry` plugin, because the source contract has no + use for one and a new plugin would mean the three plugin lists in the + `bb-server` Dockerfile. The steward's thread holds no token: it diagnoses + from the wake's evidence and the code in its workspace. **Until a token + is set, the look fails with "no Sentry token is configured"; that one + failure wakes the steward**, which files the `provide-secret` need naming + the setting (variable `sentryToken`, the Sentry auth-tokens page, the + scopes) and does nothing else; later looks are quiet until the token + appears. Any other read failure (403, a wrong URL) is logged and shown by + `bb stewards check`, and wakes nobody, as a namespace kubectl cannot read + does not. +- **Doorbells come from bb-gate-hooks directly** (`hooks-client.ts`, a copy + of github-watcher's without the GitHub parts), since there is no source + plugin to lease through. The plugin holds one stream for the `sentry` + source, opened once a project lists a Sentry target, and leases a + `project` per target, sent as `org/slug` and leased under the slug that + doorbells carry as their unit, plus an `issue` per issue in the + fingerprint map that has a ticket and was seen within thirty days, so a + resolved ticket's issue still rings when it regresses. Every lease is + proven with the token; without one nothing is leased, and bb-gate-hooks + refusing the token is said once per token. A doorbell names an issue id + and, usually, the project slug: every open Sentry binding whose target is + that slug, or whose fingerprint map holds that id, notes the id as *rung* + and looks (bb-gate/docs/hooks.md, "Sentry"). The loop's sweeps (on + connect, after a failed or late renewal, every ten minutes, and every two + minutes while the stream is down) have every Sentry binding look for + itself, and the plugin's own sweep and requeue do the same, so **the + periodic look is the backstop**: with bb-gate-hooks down, a new issue is + seen at the next look. +- **The look** reads the project's unresolved issues, newest activity + first (fifty), and each rung id the list does not carry. The sightings + are the issues *first seen* since the last look, *regressed* or + escalating in Sentry and active since, *rung* by a doorbell, and *known* + (in the fingerprint map) and still firing since; an issue Sentry has + resolved is never one, even when rung. Twenty at most, regressions + first. For the first five the latest event is read for its stack trace. + The rest of the unresolved list is shown for context, ten lines. +- **The fingerprint is the Sentry issue id**: it is what the doorbell + carries, what the API is keyed on, and stable across events, so one + issue is one ticket however often it fires. The map's summary is + `WEB-12: (<culprit>)`. +- **The wake** (`formatSentryWake`) carries, per finding, the short id, + title, level, culprit, permalink, event and user counts, first and last + seen, Sentry's substatus, why it is in the look, and the latest event's + stack trace — each exception as a header, frames innermost last, in-app + frames marked `*` with their source line — all redacted by the same rule + as the kubectl look's log lines (`redactLine`): a bearer token or an + `api_key=` in an error message does not reach a ticket. +- **What wakes the steward** (`sentryChanges`): a new issue, one back after + its ticket was resolved, and one Sentry marks regressed under an open + ticket, at once; a doorbell for an issue under an open ticket only when + the steward has not filed or commented within a `requeue-default`, so a + noisy issue is one comment per interval, not one per event (the + playbook's "a second event on the same Sentry issue is a comment, never a + second ticket"); and the requeue, as for every ops binding. A known issue + seen again, and one no longer seen, are noted quietly. +- **What the plugin never does with Sentry:** write to it. Resolving, + assigning or commenting on a Sentry issue is not in the `may` list, and + the token's read scopes are the wall. + ## 18. Needs you items and one-click actions Everything a person had to do on a ticket used to exist only as prose, @@ -981,8 +1060,9 @@ edit. developer's own rights (§18); a steward that ignored its `may` list could use them. - **Healthy pods' logs are never scanned**, so an error that does not - crash, restart or unready a pod goes unseen. Push sources (Sentry, alerts - through bb-gate-hooks) would cover that, and are separate work. + crash, restart or unready a pod goes unseen. A `sentry-project` target + covers the errors Sentry sees (§18); Alertmanager or Prometheus alerts + through bb-gate-hooks remain separate work. - **Comments and the team lease.** bb-gate-hooks does not always know a Linear comment's team, so a team lease alone misses some comments. That is why every binding also holds an issue lease for its own entity (§16). diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 0243b207..85ad0661 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -19,7 +19,7 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. stewards share one sidebar section, named after the project, with each steward's workers nested under it; see DESIGN.md §15. - **Ops stewards.** Each target in the project file's `ops.targets` (a - Kubernetes namespace) gets an `ops` steward, reporting to the project + Kubernetes namespace or a Sentry project) gets an `ops` steward, reporting to the project steward, for as long as it is listed. The plugin looks at the target with `kubectl` on the project's machine, the developer's own, as them (through its host entry, [host.ts](host.ts), and [kubectl.ts](kubectl.ts)): pods, @@ -260,7 +260,15 @@ 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 a k8s namespace. +A `{ kind: "sentry-project", org, project }` target watches a Sentry +project with the plugin's **Sentry token** setting (a user auth token with +`project:read` and `event:read`; `Sentry API` for a self-hosted server), +rung by bb-gate-hooks the moment an issue is created or regresses and +backed by the same periodic look; the Sentry issue id is the fingerprint, +and the wake carries the issue's title, culprit, permalink, counts and +latest stack trace ([sentry.ts](sentry.ts), DESIGN.md §18). +`ops-watch.md` is read only when `ops.targets` lists a k8s namespace or a +Sentry project. The `deps` object is the dependency watch: `sla` (a duration or `asap` per severity; critical→urgent, high→high, medium→medium, low→low), `batch` (the @@ -272,7 +280,7 @@ written them runs no dependency watch. `bb stewards init` writes them, and 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, +`source` (`linear`, `github`, or `k8s` or `sentry` for `ops`), `phases` (state → `{ stage, stuck }`; none for `ops`), `terminal` (at least one; none for `ops`), `ready` (`checklist`, `substantial`, `approval: project` (default), `me` or `{ linear-state: … }`), `promote`, `may` (policy stated in every wake), `models` (`steward`, `worker` as diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index b259d2bb..1fa69a03 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { depsTargets, isTerminal, k8sTargets, opsTeam, usesKind, modelSpecSchema, parsePlaybook, parseProjectFile, phaseInstructions, phaseOf, playbookStates } from "./config.js"; +import { depsTargets, isTerminal, k8sTargets, opsTeam, sentryTargets, 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", () => { @@ -84,6 +84,18 @@ describe("ops in the project file", () => { expect(error({ targets: [{ kind: "dependabot", repo: "not a repo" }] })).toMatch(/ops\.targets\.0\.repo/u); }); + it("accepts a Sentry project by organization and project slug, folded to Sentry's lower case", () => { + const r = file({ targets: [{ kind: "sentry-project", org: " Acme ", project: "Web-API" }] }); + if (!r.ok) expect.fail(r.error); + expect(r.value.ops.targets).toEqual([{ kind: "sentry-project", org: "acme", project: "web-api" }]); + expect(sentryTargets(r.value)).toEqual([{ kind: "sentry-project", org: "acme", project: "web-api" }]); + expect(k8sTargets(r.value)).toEqual([]); + expect(usesKind(r.value, "ops")).toBe(true); + expect(error({ targets: [{ kind: "sentry-project", org: "acme", project: "web api" }] })).toMatch(/ops\.targets\.0\.project: a Sentry slug/u); + expect(error({ targets: [{ kind: "sentry-project", org: "acme" }] })).toMatch(/ops\.targets\.0\.project/u); + expect(error({ targets: [{ kind: "sentry-project", org: "acme", project: "web" }, { kind: "sentry-project", org: "ACME", project: "web" }] })).toMatch(/ops\.targets\.1: sentry-project\/acme\/web is listed twice/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); @@ -180,7 +192,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 watches k8s or github/u) }); + expect(parsePlaybook(OPS_WATCH.replace("source: k8s", "source: linear"), "ops-watch")).toMatchObject({ ok: false, error: expect.stringMatching(/an ops playbook watches k8s, sentry 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, ""); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index 87e224b7..8f7e09d2 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -7,7 +7,7 @@ import { createHash } from "node:crypto"; import { parse as parseYaml } from "yaml"; import { z } from "zod"; -import type { DependabotTarget, K8sTarget, OpsTarget } from "./ops.js"; +import { SENTRY_SLUG, type DependabotTarget, type K8sTarget, type OpsTarget, type SentryTarget } from "./ops.js"; import { DEPENDABOT_SEVERITIES } from "./source-contract.js"; export const STEWARDS_DIR = "stewards"; @@ -122,7 +122,13 @@ export const dependabotRepoSchema = z.string().trim().regex(/^[A-Za-z0-9_.-]+\/[ const dependabotTargetSchema = z.object({ kind: z.literal("dependabot"), repo: dependabotRepoSchema }).strict(); -const opsTargetSchema = z.discriminatedUnion("kind", [k8sNamespaceTargetSchema, dependabotTargetSchema]); +/** A Sentry slug as Sentry spells it in URLs; upper case is folded, since Sentry's are always lower. */ +const sentrySlug = z.string().trim().toLowerCase().regex(SENTRY_SLUG, "a Sentry slug such as acme or web-api"); + +/** A Sentry project whose issues an ops steward watches, read with the plugin's Sentry token. */ +const sentryProjectTargetSchema = z.object({ kind: z.literal("sentry-project"), org: sentrySlug, project: sentrySlug }).strict(); + +const opsTargetSchema = z.discriminatedUnion("kind", [k8sNamespaceTargetSchema, dependabotTargetSchema, sentryProjectTargetSchema]); /** The per-severity SLA and batch window for Dependabot alerts. */ const slaValueSchema = z.union([z.literal("asap"), durationSchema]); @@ -216,7 +222,7 @@ export const projectFileSchema = z .superRefine((file, ctx) => { const seen = new Set<string>(); file.ops.targets.forEach((t, i) => { - const key = t.kind === "k8s-namespace" ? `${t.kind}/${t.name}` : `${t.kind}/${t.repo.toLowerCase()}`; + const key = t.kind === "k8s-namespace" ? `${t.kind}/${t.name}` : t.kind === "dependabot" ? `${t.kind}/${t.repo.toLowerCase()}` : `${t.kind}/${t.org}/${t.project}`; if (seen.has(key)) ctx.addIssue({ code: "custom", path: ["ops", "targets", i], message: `${key} is listed twice` }); seen.add(key); }); @@ -254,6 +260,9 @@ export const opsTargets = (project: ProjectFile): OpsTarget[] => project.ops.tar /** 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 Sentry projects to watch, which are read with the plugin's Sentry token and rung by bb-gate-hooks. */ +export const sentryTargets = (project: ProjectFile): SentryTarget[] => project.ops.targets.filter((t): t is SentryTarget => t.kind === "sentry-project"); + /** * The Dependabot alert targets: the project file's explicit `dependabot` * targets, or every repo in `repos.json` not in `github.exclude` when it @@ -302,7 +311,7 @@ export type ReadyConfig = z.infer<typeof readySchema>; /** The default cap on follow-through: a deploy and its verification, with room to spare. */ export const DEFAULT_FOLLOW_THROUGH_MS = 6 * 3_600_000; -export const PLAYBOOK_SOURCES = ["linear", "github", "k8s"] as const; +export const PLAYBOOK_SOURCES = ["linear", "github", "k8s", "sentry"] as const; const SOURCE_OF: Record<BindingKind, (typeof PLAYBOOK_SOURCES)[number]> = { ticket: "linear", pr: "github", review: "github", ops: "k8s" }; export const frontMatterSchema = z @@ -367,10 +376,11 @@ export function parsePlaybook(text: string, expectedName: string): Parsed<Playbo const expectedSource = SOURCE_OF[fm.kind]; if (fm.kind === "ops") { // An ops binding watches a target, not an entity in a source plugin: a - // Kubernetes namespace reads k8s, and a Dependabot alert target reads - // github. The playbook says which so its sections can be about the right - // thing; either is valid. - if (fm.source !== "k8s" && fm.source !== "github") return { ok: false, error: `${file}: an ops playbook watches k8s or github, not ${fm.source}` }; + // Kubernetes namespace reads k8s, a Dependabot alert target reads + // github, and a Sentry project reads sentry. The playbook says which so + // its sections can be about the right thing; any is valid, and the + // ops-watch playbook serves k8s and Sentry targets alike. + if (fm.source === "linear") return { ok: false, error: `${file}: an ops playbook watches k8s, sentry or github, not ${fm.source}` }; } else if (fm.source !== expectedSource) { return { ok: false, error: `${file}: a ${fm.kind} playbook reads ${expectedSource}, not ${fm.source}` }; } diff --git a/plugins/stewards/hooks-client.test.ts b/plugins/stewards/hooks-client.test.ts new file mode 100644 index 00000000..e3e59948 --- /dev/null +++ b/plugins/stewards/hooks-client.test.ts @@ -0,0 +1,476 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createHooksLoop, HooksRequestError, readSse, SseParser, StreamIdleError, subscribe, type Lease, type Rejection } from "./hooks-client.js"; + +const BASE = "http://hooks.test:8081"; +const MINUTE = 60_000; + +// A bb-gate-hooks whose stream and subscribe endpoint a test drives. +function fakeHooks() { + const encoder = new TextEncoder(); + type Stream = { send(text: string): void; end(): void; closed: boolean }; + const streams: Stream[] = []; + const subscribes: Array<{ connection: string; source: string; token: string; watches: Array<{ kind: string; id: string }> }> = []; + const state = { + eventsStatus: 200, + silent: false, + answer: (body: (typeof subscribes)[number]): Response => Response.json({ leases: body.watches.map((w) => ({ ...w, unit: "web", expiresAt: "2026-10-10T18:00:00Z" })), rejected: [] }), + }; + const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise<Response> => { + const u = String(url); + if (u === `${BASE}/v1/events`) { + if (state.eventsStatus !== 200) return new Response("", { status: state.eventsStatus }); + let controller!: ReadableStreamDefaultController<Uint8Array>; + const entry: Stream = { + closed: false, + send: (text) => controller.enqueue(encoder.encode(text)), + end: () => { + entry.closed = true; + controller.close(); + }, + }; + const body = new ReadableStream<Uint8Array>({ + start: (c) => { + controller = c; + }, + cancel: () => { + entry.closed = true; + }, + }); + // The service guarantees a keepalive every 20 s; so does the fake, unless a test mutes it. + const keepalive = setInterval(() => { + if (!entry.closed && !state.silent) entry.send(": keepalive\n\n"); + }, 20_000); + init?.signal?.addEventListener("abort", () => { + entry.closed = true; + clearInterval(keepalive); + }); + streams.push(entry); + return new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } }); + } + if (u === `${BASE}/v1/subscribe`) { + const body = JSON.parse(String(init?.body)) as (typeof subscribes)[number]; + subscribes.push(body); + return state.answer(body); + } + return new Response("not found", { status: 404 }); + }) as unknown as typeof fetch; + const hello = (connection: string, leaseSeconds = 3600) => `event: hello\ndata: ${JSON.stringify({ connection, leaseSeconds })}\n\n`; + const doorbell = (id: string, over: Record<string, unknown> = {}) => + `id: 1\nevent: doorbell\ndata: ${JSON.stringify({ source: "sentry", kind: "issue", id, unit: "web", action: "created", at: "2026-10-10T17:02:11Z", ...over })}\n\n`; + return { fetchImpl, streams, subscribes, state, hello, doorbell, last: () => streams.at(-1)! }; +} + +describe("SSE parsing", () => { + it("handles chunks split anywhere, CRLF, comments, several data lines, ids and the default event", () => { + const parser = new SseParser(); + const text = ": keepalive\r\nevent: hello\r\ndata: {\"a\":1}\r\n\r\nid: 42\nevent: doorbell\ndata: one\ndata:two\n\ndata: bare\n\n"; + const events = []; + for (const ch of text) events.push(...parser.push(ch)); + expect(events).toEqual([ + { event: "hello", data: '{"a":1}', id: null }, + { event: "doorbell", data: "one\ntwo", id: "42" }, + { event: "message", data: "bare", id: "42" }, + ]); + expect(parser.push(": only a comment\n\n")).toEqual([]); + }); + + it("reads a stream until it ends, and stops when aborted", async () => { + const encoder = new TextEncoder(); + const body = new ReadableStream<Uint8Array>({ + start(c) { + c.enqueue(encoder.encode("event: a\ndata: 1\n\nevent: b\n")); + c.enqueue(encoder.encode("data: 2\n\n")); + c.close(); + }, + }); + const seen = []; + for await (const e of readSse(body, new AbortController().signal)) seen.push(e.event); + expect(seen).toEqual(["a", "b"]); + + const controller = new AbortController(); + let cancelled = false; + const open = new ReadableStream<Uint8Array>({ cancel: () => void (cancelled = true) }); + const reading = (async () => { + const got = []; + for await (const e of readSse(open, controller.signal)) got.push(e); + return got; + })(); + controller.abort(); + expect(await reading).toEqual([]); + expect(cancelled).toBe(true); + }); + + it("gives up on a stream that sends nothing for the idle time", async () => { + vi.useFakeTimers(); + try { + let cancelled = false; + const silent = new ReadableStream<Uint8Array>({ cancel: () => void (cancelled = true) }); + const reading = (async () => { + for await (const _ of readSse(silent, new AbortController().signal, 5000)) void _; + })(); + const settled = reading.then(() => "ended", (e: unknown) => e); + await vi.advanceTimersByTimeAsync(5000); + expect(await settled).toBeInstanceOf(StreamIdleError); + expect(cancelled).toBe(true); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe("subscribe", () => { + it("posts the connection, source, token and watches of either kind, in batches of 100, and merges the answers", async () => { + const hooks = fakeHooks(); + const ids: Lease[] = [{ kind: "project", id: "acme/web" }, ...Array.from({ length: 149 }, (_, i) => ({ kind: "issue" as const, id: `i-${i + 1}` }))]; + hooks.state.answer = (body) => Response.json({ leases: body.watches.slice(1), rejected: [{ ...body.watches[0], reason: "forbidden" }] }); + const result = await subscribe(hooks.fetchImpl, BASE, "c_1", "tok-1", ids, new AbortController().signal); + expect(hooks.subscribes).toHaveLength(2); + expect(hooks.subscribes[0]).toMatchObject({ connection: "c_1", source: "sentry", token: "tok-1" }); + expect(hooks.subscribes[0]!.watches).toHaveLength(100); + expect(hooks.subscribes[0]!.watches.slice(0, 2)).toEqual([{ kind: "project", id: "acme/web" }, { kind: "issue", id: "i-1" }]); + expect(hooks.subscribes[1]!.watches).toHaveLength(50); + expect(result.leases).toHaveLength(148); + expect(result.rejected.map((r) => r.id)).toEqual(["acme/web", "i-100"]); + }); + + it("throws with the status and body when the connection is unknown, without the token in the message", async () => { + const hooks = fakeHooks(); + hooks.state.answer = () => Response.json({ error: "unknown-connection" }, { status: 404 }); + const error = await subscribe(hooks.fetchImpl, BASE, "c_gone", "tok-secret", [{ kind: "issue", id: "i" }], new AbortController().signal).catch((e: unknown) => e); + expect(error).toBeInstanceOf(HooksRequestError); + expect((error as HooksRequestError).status).toBe(404); + expect((error as HooksRequestError).unknownConnection).toBe(true); + expect((error as Error).message + (error as HooksRequestError).body).not.toContain("tok-secret"); + expect(new HooksRequestError("x", 404, "not found").unknownConnection).toBe(false); + expect(new HooksRequestError("x", 200, JSON.stringify({ error: "unknown-connection" })).unknownConnection).toBe(false); + }); +}); + +describe("the loop", () => { + let now = 1_000_000_000_000; + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(now); + now = 1_000_000_000_000; + }); + afterEach(() => vi.useRealTimers()); + const tick = async (ms = 0) => { + now += ms; + await vi.advanceTimersByTimeAsync(ms); + }; + + function start(hooks: ReturnType<typeof fakeHooks>, over: { watchIds?: () => Lease[]; token?: () => Promise<string | null>; idleMs?: number } = {}) { + const logs: string[] = []; + const sweeps: string[] = []; + const doorbells: string[] = []; + const doorbellKinds: string[] = []; + const units: Array<string | null> = []; + const rejected: Rejection[][] = []; + let token: string | null = "tok-1"; + const loop = createHooksLoop({ + fetch: hooks.fetchImpl, + baseUrl: BASE, + now: () => now, + log: { info: (m) => logs.push(`info ${m}`), warn: (m) => logs.push(`warn ${m}`) }, + token: over.token ?? (async () => token), + watchIds: over.watchIds ?? (() => [{ kind: "issue", id: "i-1" }, { kind: "issue", id: "i-2" }]), + onDoorbell: (kind, id, unit) => { + doorbellKinds.push(kind); + doorbells.push(id); + units.push(unit); + }, + onRejected: async (r) => { + rejected.push(r); + }, + sweep: async (reason) => { + sweeps.push(reason); + }, + timing: { backoffMinMs: 1000, backoffMaxMs: 8000, ...(over.idleMs === undefined ? {} : { idleMs: over.idleMs }) }, + }); + const controller = new AbortController(); + const done = loop.run(controller.signal); + return { loop, logs, sweeps, doorbells, doorbellKinds, units, rejected, controller, done, setToken: (t: string | null) => (token = t) }; + } + + it("subscribes every watch on hello with the current token, sweeps, then rings on doorbells for issues only", async () => { + const hooks = fakeHooks(); + const s = start(hooks); + await tick(); + expect(hooks.streams).toHaveLength(1); + expect(s.loop.connected).toBe(false); + hooks.last().send(": keepalive\n\n"); + hooks.last().send(hooks.hello("c_1")); + await tick(); + expect(hooks.subscribes).toEqual([{ connection: "c_1", source: "sentry", token: "tok-1", watches: [{ kind: "issue", id: "i-1" }, { kind: "issue", id: "i-2" }] }]); + expect(s.sweeps).toEqual(["connected"]); + expect(s.loop.connected).toBe(true); + + hooks.last().send(hooks.doorbell("i-1")); + hooks.last().send(hooks.doorbell("web", { kind: "project" })); + hooks.last().send(hooks.doorbell("i-9", { source: "github" })); + hooks.last().send("event: doorbell\ndata: not json\n\n"); + hooks.last().send(hooks.doorbell("i-2", { action: "resolved", unit: "" })); + await tick(); + expect(s.doorbells).toEqual(["i-1", "i-2"]); + expect(s.doorbellKinds).toEqual(["issue", "issue"]); + // The unit comes along when the service names one. + expect(s.units).toEqual(["web", null]); + expect(s.logs.join("\n")).not.toContain("tok-1"); + + s.controller.abort(); + await s.done; + expect(hooks.last().closed).toBe(true); + }); + + it("renews at half the lease with whatever token it holds, and sweeps after a failed or late renewal", async () => { + const hooks = fakeHooks(); + const s = start(hooks); + await tick(); + hooks.last().send(hooks.hello("c_1", 3600)); + await tick(); + expect(hooks.subscribes).toHaveLength(1); + + s.setToken("tok-2"); + await tick(30 * MINUTE); + expect(hooks.subscribes).toHaveLength(2); + expect(hooks.subscribes[1]!.token).toBe("tok-2"); + // A renewal on time is quiet; the 10-minute baseline is what sweeps meanwhile. + expect(s.sweeps).toEqual(["connected", "baseline", "baseline", "baseline"]); + + hooks.state.answer = () => new Response("", { status: 500 }); + await tick(30 * MINUTE); + expect(hooks.subscribes).toHaveLength(3); + expect(s.sweeps.filter((r) => r === "failed renewal")).toHaveLength(1); + expect(s.logs.at(-1)).toContain("HTTP 500"); + + // The lease ran out during the failure; the next renewal that works is late. + hooks.state.answer = (body) => Response.json({ leases: body.watches, rejected: [] }); + await tick(30 * MINUTE); + expect(hooks.subscribes).toHaveLength(4); + expect(s.sweeps.filter((r) => r === "late renewal")).toHaveLength(1); + expect(s.loop.connected).toBe(true); + + s.controller.abort(); + await s.done; + }); + + it("reconnects when the service forgets the connection, and hands rejected leases back", async () => { + const hooks = fakeHooks(); + const s = start(hooks); + await tick(); + hooks.last().send(hooks.hello("c_1")); + await tick(); + hooks.state.answer = () => Response.json({ error: "unknown-connection" }, { status: 404 }); + await tick(30 * MINUTE); + expect(hooks.streams[0]!.closed).toBe(true); + expect(s.loop.connected).toBe(false); + await tick(1000); + expect(hooks.streams).toHaveLength(2); + hooks.state.answer = (body) => Response.json({ leases: [body.watches[1]], rejected: [{ ...body.watches[0], reason: "forbidden" }] }); + hooks.last().send(hooks.hello("c_2")); + await tick(); + expect(hooks.subscribes.at(-1)!.connection).toBe("c_2"); + expect(s.rejected).toEqual([[{ kind: "issue", id: "i-1", reason: "forbidden" }]]); + expect(s.sweeps.filter((r) => r === "connected")).toHaveLength(2); + s.controller.abort(); + await s.done; + }); + + it("while the service is unreachable, retries with backoff and sweeps every two minutes", async () => { + const hooks = fakeHooks(); + hooks.state.eventsStatus = 503; + const s = start(hooks); + await tick(); + expect(s.sweeps).toEqual(["stream down"]); + // 1s, 2s, 4s, 8s, 8s ... attempts; the sweep waits for the 2-minute mark. + await tick(1000 + 2000 + 4000 + 8000 + 8000); + expect(hooks.fetchImpl).toHaveBeenCalledTimes(6); + expect(s.sweeps).toEqual(["stream down"]); + await tick(2 * MINUTE); + expect(s.sweeps).toEqual(["stream down", "stream down"]); + expect(s.logs.filter((l) => l.includes("HTTP 503")).length).toBeGreaterThan(5); + + hooks.state.eventsStatus = 200; + await tick(8000); + hooks.last().send(hooks.hello("c_3")); + await tick(); + expect(hooks.subscribes).toHaveLength(1); + expect(s.sweeps.at(-1)).toBe("connected"); + + // A stream that ends is reconnected the same way. + hooks.last().end(); + await tick(1000); + expect(hooks.streams).toHaveLength(2); + s.controller.abort(); + await s.done; + }); + + it("reports its state and how busy it has been, and says when the state changes", async () => { + const hooks = fakeHooks(); + hooks.state.eventsStatus = 503; + const s = start(hooks); + const changes: string[] = []; + s.loop.onStateChange(() => changes.push(s.loop.status().state)); + await tick(); + expect(s.loop.status()).toMatchObject({ state: "connecting", since: now, leased: false, leasedUntil: 0, doorbells: 0, sweeps: 1, lastSweepAt: now, lastSweepReason: "stream down" }); + + hooks.state.eventsStatus = 200; + await tick(1000); + const connectedAt = now; + hooks.last().send(hooks.hello("c_1")); + await tick(); + expect(changes).toEqual(["connected"]); + expect(s.loop.status()).toMatchObject({ state: "connected", since: connectedAt, leased: true, leasedUntil: connectedAt + 60 * MINUTE, sweeps: 2, lastSweepReason: "connected" }); + + hooks.last().send(hooks.doorbell("i-1")); + hooks.last().send(hooks.doorbell("i-2")); + hooks.last().send(hooks.doorbell("web", { kind: "project" })); + await tick(); + expect(s.loop.status()).toMatchObject({ doorbells: 2, lastDoorbellAt: now }); + // Counts are over the last hour; the last time is kept. + const lastDoorbellAt = now; + await tick(61 * MINUTE); + expect(s.loop.status()).toMatchObject({ doorbells: 0, lastDoorbellAt }); + + hooks.last().end(); + await tick(); + expect(changes).toEqual(["connected", "connecting"]); + expect(s.loop.status().state).toBe("connecting"); + s.controller.abort(); + await s.done; + expect(changes).toEqual(["connected", "connecting", "stopped"]); + expect(s.loop.status()).toMatchObject({ state: "stopped", leased: false }); + }); + + it("leases a newly added issue or project right away when connected, and leaves it to the next hello otherwise", async () => { + const hooks = fakeHooks(); + const s = start(hooks, { watchIds: () => [] }); + await s.loop.added("issue", "i-new"); + await tick(); + expect(hooks.subscribes).toEqual([]); + hooks.last().send(hooks.hello("c_1")); + await tick(); + // No watches: nothing to subscribe, but the connection still counts as leased and swept. + expect(hooks.subscribes).toEqual([]); + expect(s.sweeps).toEqual(["connected"]); + expect(s.loop.connected).toBe(true); + await s.loop.added("issue", "i-new"); + expect(hooks.subscribes).toEqual([{ connection: "c_1", source: "sentry", token: "tok-1", watches: [{ kind: "issue", id: "i-new" }] }]); + // Several at once are one call; none is no call. + await s.loop.added("project", "acme/web", "acme/api"); + await s.loop.added("project"); + expect(hooks.subscribes.slice(1)).toEqual([{ connection: "c_1", source: "sentry", token: "tok-1", watches: [{ kind: "project", id: "acme/web" }, { kind: "project", id: "acme/api" }] }]); + s.controller.abort(); + await s.done; + }); + + it("leases nothing without a token, and leases as soon as one is set", async () => { + const hooks = fakeHooks(); + const s = start(hooks, { token: async () => null }); + await tick(); + hooks.last().send(hooks.hello("c_1")); + await tick(); + // The stream is up but unproven: the connected sweep still runs, and every renewal sweeps again until there is a token. + expect(hooks.subscribes).toEqual([]); + expect(s.loop.connected).toBe(false); + expect(s.sweeps).toEqual(["connected"]); + expect(s.logs.filter((l) => l.startsWith("warn"))).toEqual([]); + await tick(30 * MINUTE); + expect(hooks.subscribes).toEqual([]); + expect(s.sweeps.filter((r) => r === "failed renewal")).toHaveLength(1); + s.controller.abort(); + await s.done; + + const later = fakeHooks(); + const t = start(later); + await tick(); + later.last().send(later.hello("c_2")); + await tick(); + expect(later.subscribes.map((b) => b.token)).toEqual(["tok-1"]); + expect(t.loop.connected).toBe(true); + t.controller.abort(); + await t.done; + }); + + it("says once when the service reports Sentry refused the token, and tries again at the next renewal", async () => { + const hooks = fakeHooks(); + hooks.state.answer = (body) => (body.token === "tok-good" ? Response.json({ leases: body.watches, rejected: [] }) : new Response("", { status: 401 })); + const s = start(hooks); + await tick(); + hooks.last().send(hooks.hello("c_1")); + await tick(); + expect(hooks.subscribes.map((b) => b.token)).toEqual(["tok-1"]); + expect(s.loop.connected).toBe(false); + expect(s.sweeps).toEqual(["connected"]); + expect(s.logs.filter((l) => l.includes("Sentry refused the token"))).toHaveLength(1); + expect(s.logs.join("\n")).not.toMatch(/tok-/u); + + // Still refused at the renewal: a failed renewal, said no second time. + await tick(30 * MINUTE); + expect(hooks.subscribes).toHaveLength(2); + expect(s.logs.filter((l) => l.includes("Sentry refused the token"))).toHaveLength(1); + expect(s.sweeps.filter((r) => r === "failed renewal")).toHaveLength(1); + expect(s.rejected).toEqual([]); + expect(hooks.streams).toHaveLength(1); + + // A new token in the setting is used as it is, no restart needed. + s.setToken("tok-good"); + await tick(30 * MINUTE); + expect(hooks.subscribes.map((b) => b.token)).toEqual(["tok-1", "tok-1", "tok-good"]); + expect(s.loop.connected).toBe(true); + s.controller.abort(); + await s.done; + }); + + it("treats a 404 without the unknown-connection body as a wrong URL: logged once, no tight reconnect", async () => { + const hooks = fakeHooks(); + hooks.state.answer = () => new Response("not found", { status: 404 }); + const s = start(hooks); + await tick(); + hooks.last().send(hooks.hello("c_1")); + await tick(); + await tick(60 * MINUTE); + expect(hooks.streams).toHaveLength(1); + expect(hooks.streams[0]!.closed).toBe(false); + expect(hooks.subscribes).toHaveLength(3); + expect(s.logs.filter((l) => l.includes("BB_HOOKS_URL looks wrong"))).toHaveLength(1); + expect(s.sweeps.filter((r) => r === "failed renewal")).toHaveLength(2); + s.controller.abort(); + await s.done; + }); + + it("drops a stream silent for a minute and reconnects; keepalives count as life", async () => { + const hooks = fakeHooks(); + const s = start(hooks); + await tick(); + hooks.last().send(hooks.hello("c_1")); + await tick(); + await tick(5 * MINUTE); + expect(hooks.streams).toHaveLength(1); + expect(hooks.streams[0]!.closed).toBe(false); + hooks.state.silent = true; + await tick(59_999); + expect(hooks.streams[0]!.closed).toBe(false); + await tick(1); + expect(hooks.streams[0]!.closed).toBe(true); + expect(s.loop.connected).toBe(false); + expect(s.logs.some((l) => l.includes("no bytes from bb-gate-hooks for 60 s"))).toBe(true); + await tick(1000); + expect(hooks.streams).toHaveLength(2); + s.controller.abort(); + await s.done; + }); + + it("keeps a token problem out of the log and treats it as a failed renewal", async () => { + const hooks = fakeHooks(); + const s = start(hooks, { token: async () => { throw new Error("the settings store is unavailable"); } }); + await tick(); + hooks.last().send(hooks.hello("c_1")); + await tick(); + expect(hooks.subscribes).toEqual([]); + expect(s.sweeps).toEqual(["connected"]); + expect(s.logs.some((l) => l.startsWith("warn") && l.includes("settings store is unavailable"))).toBe(true); + s.controller.abort(); + await s.done; + }); +}); diff --git a/plugins/stewards/hooks-client.ts b/plugins/stewards/hooks-client.ts new file mode 100644 index 00000000..edbde555 --- /dev/null +++ b/plugins/stewards/hooks-client.ts @@ -0,0 +1,502 @@ +// The subscriber side of bb-gate-hooks (bb-gate/docs/hooks.md) for Sentry: +// one SSE stream for doorbells, a lease per watched Sentry project (and per +// issue with an open ticket) proven with the plugin's Sentry token, renewed +// at half-life, and a re-check of every watch whenever coverage cannot be +// proven. The service promises nothing beyond "something about this entity +// changed while you were leased", so this module never decides anything +// about an issue; it only says when to look. +// +// A copy of github-watcher's hooks-client.ts with the GitHub parts taken +// out: stewards has no sentry plugin to lease through (the token is its own +// secret setting), so it subscribes itself. Everything that touches the +// world is injected: fetch, the clock, the token, the watch list, and what +// to do on a doorbell or a rejected lease. The token goes into one request +// body and nowhere else: not a log line, not an error message. +import { z } from "zod"; + +export const HOOKS_URL_ENV = "BB_HOOKS_URL"; +export const SOURCE = "sentry"; +/** The service refuses more watches than this in one call (413). */ +export const SUBSCRIBE_BATCH = 100; + +/** + * What a lease hangs off. `issue` is one Sentry issue, by its id; `project` + * is a whole project, sent as "org/slug" (Sentry needs the organization to + * read it) and leased under the slug, which is what doorbells carry as the + * unit. Doorbells are always `issue` (bb-gate/docs/hooks.md, "Sentry"). + */ +export type LeaseKind = "issue" | "project"; +export type Lease = { kind: LeaseKind; id: string }; + +// ---- server-sent events ---------------------------------------------------- + +export type SseEvent = { event: string; data: string; id: string | null }; + +/** + * Incremental parser for text/event-stream: feed it chunks, get the events + * that completed. Comment lines (`: keepalive`) are dropped, a field's single + * leading space is stripped, several `data:` lines join with newlines, and a + * blank line dispatches. `retry:` is ignored; reconnect timing is ours. + */ +export class SseParser { + private buffer = ""; + private event = ""; + private data: string[] = []; + private id: string | null = null; + + push(chunk: string): SseEvent[] { + this.buffer += chunk; + const out: SseEvent[] = []; + let newline: number; + while ((newline = this.buffer.indexOf("\n")) !== -1) { + let line = this.buffer.slice(0, newline); + this.buffer = this.buffer.slice(newline + 1); + if (line.endsWith("\r")) line = line.slice(0, -1); + if (line === "") { + if (this.data.length > 0 || this.event !== "") out.push({ event: this.event === "" ? "message" : this.event, data: this.data.join("\n"), id: this.id }); + this.event = ""; + this.data = []; + continue; + } + if (line.startsWith(":")) continue; + const colon = line.indexOf(":"); + const field = colon === -1 ? line : line.slice(0, colon); + let value = colon === -1 ? "" : line.slice(colon + 1); + if (value.startsWith(" ")) value = value.slice(1); + if (field === "event") this.event = value; + else if (field === "data") this.data.push(value); + else if (field === "id") this.id = value; + } + return out; + } +} + +/** The events of a stream body, until it ends or the signal aborts. */ +export class StreamIdleError extends Error { + constructor(idleMs: number) { + super(`no bytes from bb-gate-hooks for ${Math.round(idleMs / 1000)} s`); + this.name = "StreamIdleError"; + } +} + +/** + * The events of a stream body, until it ends or the signal aborts. A stream + * silent for `idleMs` (keepalives included: any bytes count) throws + * StreamIdleError, because a half-open connection would otherwise look + * leased forever. + */ +export async function* readSse(body: ReadableStream<Uint8Array>, signal: AbortSignal, idleMs = STREAM_IDLE_MS): AsyncGenerator<SseEvent> { + const reader = body.getReader(); + const decoder = new TextDecoder(); + const parser = new SseParser(); + const cancel = () => void reader.cancel().catch(() => undefined); + signal.addEventListener("abort", cancel, { once: true }); + try { + while (!signal.aborted) { + let idle: ReturnType<typeof setTimeout> | null = null; + const timedOut = new Promise<never>((_, reject) => { + idle = setTimeout(() => reject(new StreamIdleError(idleMs)), idleMs); + }); + let chunk: ReadableStreamReadResult<Uint8Array>; + try { + chunk = await Promise.race([reader.read(), timedOut]); + } catch (error) { + if (error instanceof StreamIdleError) cancel(); + throw error; + } finally { + if (idle !== null) clearTimeout(idle); + } + if (chunk.done) break; + for (const event of parser.push(decoder.decode(chunk.value, { stream: true }))) yield event; + } + } finally { + signal.removeEventListener("abort", cancel); + reader.releaseLock(); + } +} + +// ---- the wire shapes --------------------------------------------------------- + +export const helloSchema = z.object({ connection: z.string().min(1), leaseSeconds: z.number().positive().optional() }); +export const doorbellSchema = z.object({ source: z.string(), kind: z.string(), id: z.string().min(1), unit: z.string().optional() }).loose(); +export const subscribeResponseSchema = z.object({ + leases: z.array(z.object({ kind: z.string(), id: z.string() }).loose()).default([]), + rejected: z.array(z.object({ kind: z.string(), id: z.string(), reason: z.string() }).loose()).default([]), +}); +export type SubscribeResponse = z.infer<typeof subscribeResponseSchema>; +export type Rejection = SubscribeResponse["rejected"][number]; + +export class HooksRequestError extends Error { + constructor( + message: string, + readonly status: number, + /** The answer's body, for the one 404 that means something (`{"error":"unknown-connection"}`). Never the request. */ + readonly body: string = "", + ) { + super(message); + this.name = "HooksRequestError"; + } + + /** The service forgot the connection the request named; any other 404 is a wrong URL. */ + get unknownConnection(): boolean { + if (this.status !== 404) return false; + try { + return (JSON.parse(this.body) as { error?: unknown }).error === "unknown-connection"; + } catch { + return false; + } + } +} + +/** The service guarantees a keepalive every 20 s; this much silence means the stream is dead. */ +export const STREAM_IDLE_MS = 60_000; + +type FetchLike = (url: string | URL, init: RequestInit) => Promise<Response>; + +/** + * POST /v1/subscribe for these leases, in batches the service accepts. + * A 404 means the connection is gone and is thrown as such so the caller + * reconnects; nothing about the request body is ever put in an error. + */ +export async function subscribe(fetchImpl: FetchLike, baseUrl: string, connection: string, token: string, leases: Lease[], signal: AbortSignal): Promise<SubscribeResponse> { + const merged: SubscribeResponse = { leases: [], rejected: [] }; + for (let i = 0; i < leases.length; i += SUBSCRIBE_BATCH) { + const watches = leases.slice(i, i + SUBSCRIBE_BATCH).map(({ kind, id }) => ({ kind, id })); + const response = await fetchImpl(new URL("/v1/subscribe", baseUrl), { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json" }, + body: JSON.stringify({ connection, source: SOURCE, token, watches }), + signal, + }); + if (!response.ok) throw new HooksRequestError(`bb-gate-hooks answered HTTP ${response.status} to subscribe`, response.status, await response.text().catch(() => "")); + const parsed = subscribeResponseSchema.parse(await response.json()); + merged.leases.push(...parsed.leases); + merged.rejected.push(...parsed.rejected); + } + return merged; +} + +// ---- the loop ---------------------------------------------------------------- + +export interface HooksTiming { + /** Renew at this fraction of the lease. */ + renewFraction: number; + /** Lease length assumed until the hello says otherwise. */ + defaultLeaseMs: number; + /** Re-check everything this often while leased. */ + baselineMs: number; + /** Re-check everything this often while the stream is down. */ + downSweepMs: number; + /** Reconnect backoff, doubled from the first to the cap. */ + backoffMinMs: number; + backoffMaxMs: number; + /** Silence on the stream that counts as a dead connection. */ + idleMs: number; +} + +export const DEFAULT_TIMING: HooksTiming = { + renewFraction: 0.5, + defaultLeaseMs: 60 * 60 * 1000, + baselineMs: 10 * 60 * 1000, + downSweepMs: 2 * 60 * 1000, + backoffMinMs: 1000, + backoffMaxMs: 60 * 1000, + idleMs: STREAM_IDLE_MS, +}; + +export interface HooksLoopDeps { + fetch: FetchLike; + baseUrl: string; + now: () => number; + log: { info(message: string): void; warn(message: string): void }; + /** The plugin's Sentry token; null when none is configured, and then nothing is leased. */ + token: () => Promise<string | null>; + /** Every lease to hold, right now: the projects the project files list, and the issues with open tickets. */ + watchIds: () => Lease[]; + /** + * A doorbell: the kind (`issue`), the issue id, and the unit (the project + * slug) 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<void>; + /** Check every watch against its cursor. */ + sweep: (reason: string) => Promise<void>; + timing?: Partial<HooksTiming>; +} + +/** + * The loop as a usage view sees it. `stopped`: `run` is not running (no + * service, or nothing to prove a lease with). `connecting`: running, no + * stream with a hello on it yet, so checks fall back to the slow down-sweep. + * `connected`: a stream is up; `leased` says whether the leases on it are + * current. Counts are over the last `windowMs`. + */ +export type HooksStatus = { + state: "stopped" | "connecting" | "connected"; + /** When the state last changed. */ + since: number; + leased: boolean; + /** When the current leases run out; 0 while there are none. */ + leasedUntil: number; + windowMs: number; + doorbells: number; + lastDoorbellAt: number; + sweeps: number; + lastSweepAt: number; + lastSweepReason: string | null; +}; + +/** The window the status counts doorbells and sweeps over. */ +export const STATUS_WINDOW_MS = 60 * 60 * 1000; + +export interface HooksLoop { + /** Run until the signal aborts. Never throws for a network reason; it retries. */ + run(signal: AbortSignal): Promise<void>; + /** A watch or an interest was just added: lease it now if there is a connection. The next hello covers it otherwise. */ + added(kind: LeaseKind, ...ids: string[]): Promise<void>; + /** Whether a connection is up and leased; for status lines and tests. */ + readonly connected: boolean; + /** What the loop is doing and how busy it has been; for the usage view. */ + status(): HooksStatus; + /** Called whenever `status().state` changes. */ + onStateChange(listener: () => void): void; +} + +/** How many events fell in the window ending now, and when the last one was (however long ago). */ +function createWindowCounter(windowMs: number, now: () => number) { + let stamps: number[] = []; + let lastAt = 0; + return { + push() { + lastAt = now(); + stamps.push(lastAt); + stamps = stamps.filter((t) => t > lastAt - windowMs); + }, + count: () => { + const at = now(); + stamps = stamps.filter((t) => t > at - windowMs); + return stamps.length; + }, + last: () => lastAt, + }; +} + +function sleep(ms: number, signal: AbortSignal): Promise<void> { + return new Promise((resolve) => { + if (signal.aborted) return resolve(); + const timer = setTimeout(done, ms); + function done() { + clearTimeout(timer); + signal.removeEventListener("abort", done); + resolve(); + } + signal.addEventListener("abort", done, { once: true }); + }); +} + +const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error)); + +export function createHooksLoop(deps: HooksLoopDeps): HooksLoop { + const timing: HooksTiming = { ...DEFAULT_TIMING, ...deps.timing }; + let connection: string | null = null; + let leaseMs = timing.defaultLeaseMs; + /** When the current leases run out; 0 while there are none. */ + let leasedUntil = 0; + /** Aborting this drops the current stream so the outer loop reconnects. */ + let stream: AbortController | null = null; + let lastSweepAt = 0; + let lastSweepReason: string | null = null; + let wrongUrlLogged = false; + + const doorbells = createWindowCounter(STATUS_WINDOW_MS, deps.now); + const sweeps = createWindowCounter(STATUS_WINDOW_MS, deps.now); + let state: HooksStatus["state"] = "stopped"; + let stateSince = deps.now(); + const stateListeners = new Set<() => void>(); + function setState(next: HooksStatus["state"]): void { + if (next === state) return; + state = next; + stateSince = deps.now(); + for (const listener of stateListeners) listener(); + } + + function runSweep(reason: string): void { + lastSweepAt = deps.now(); + lastSweepReason = reason; + sweeps.push(); + deps.sweep(reason).catch((error: unknown) => deps.log.warn(`Sentry watch sweep (${reason}) failed: ${errorMessage(error)}`)); + } + + /** + * Lease these on the current connection. Returns whether the service + * accepted the call; a 404 means the connection is gone and drops the + * stream. Without a token nothing can be proven, so nothing is sent and + * the loop counts as unleased: the sweeps carry the watch until one is + * set. A 401 is the token itself, refused by Sentry on the service's side; + * there is no refresh path, so it is said (once per token) and the next + * renewal tries again with whatever the setting holds then. + */ + let refusedLogged = false; + async function lease(ids: Lease[], signal: AbortSignal): Promise<boolean> { + if (connection === null) return false; + const current = connection; + const started = deps.now(); + try { + const token = (await deps.token())?.trim() ?? ""; + if (token === "") return false; + const result = await subscribe(deps.fetch, deps.baseUrl, current, token, ids, signal); + refusedLogged = false; + if (connection === current) leasedUntil = Math.max(leasedUntil, started + leaseMs); + if (result.rejected.length > 0) await deps.onRejected(result.rejected); + return true; + } catch (error) { + if (signal.aborted) return false; + if (error instanceof HooksRequestError && error.status === 401) { + if (!refusedLogged) deps.log.warn("bb-gate-hooks says Sentry refused the token; check the Sentry token setting of the stewards plugin"); + refusedLogged = true; + return false; + } + if (error instanceof HooksRequestError && error.status === 404) { + if (error.unknownConnection) { + if (connection === current) { + deps.log.warn("bb-gate-hooks forgot our connection; reconnecting"); + stream?.abort(); + } + return false; + } + // A 404 from the path itself: the URL is wrong. Say so once; the + // normal renewal and reconnect cadence keeps trying. + if (!wrongUrlLogged) { + wrongUrlLogged = true; + deps.log.warn(`${HOOKS_URL_ENV} looks wrong: ${deps.baseUrl} answers 404 to /v1/subscribe without naming the connection`); + } + return false; + } + deps.log.warn(`Sentry watch lease failed: ${errorMessage(error)}`); + return false; + } + } + + /** Renew every lease; a failed or late renewal means a gap, so everything is checked. Never throws: it runs from timers. */ + async function renew(reason: "hello" | "renewal", signal: AbortSignal): Promise<void> { + try { + const ids = deps.watchIds(); + const late = reason === "renewal" && leasedUntil !== 0 && deps.now() >= leasedUntil; + let ok = true; + if (ids.length === 0) leasedUntil = deps.now() + leaseMs; + else ok = await lease(ids, signal); + if (reason === "hello" || !ok || late) runSweep(reason === "hello" ? "connected" : ok ? "late renewal" : "failed renewal"); + } catch (error) { + if (!signal.aborted) deps.log.warn(`Sentry watch renewal failed: ${errorMessage(error)}`); + } + } + + async function consume(body: ReadableStream<Uint8Array>, signal: AbortSignal): Promise<void> { + let renewTimer: ReturnType<typeof setInterval> | null = null; + let baselineTimer: ReturnType<typeof setInterval> | null = null; + try { + for await (const event of readSse(body, signal, timing.idleMs)) { + if (event.event === "hello") { + const hello = helloSchema.safeParse(JSON.parse(event.data)); + if (!hello.success) { + deps.log.warn("bb-gate-hooks sent a hello this plugin does not understand; reconnecting"); + return; + } + connection = hello.data.connection; + setState("connected"); + leaseMs = hello.data.leaseSeconds === undefined ? timing.defaultLeaseMs : hello.data.leaseSeconds * 1000; + deps.log.info(`Sentry watches: connected to bb-gate-hooks as ${connection}`); + // Not awaited: doorbells behind the hello must not wait for Sentry. + void renew("hello", signal); + if (renewTimer !== null) clearInterval(renewTimer); + if (baselineTimer !== null) clearInterval(baselineTimer); + renewTimer = setInterval(() => void renew("renewal", signal), Math.max(1000, leaseMs * timing.renewFraction)); + baselineTimer = setInterval(() => runSweep("baseline"), timing.baselineMs); + } else if (event.event === "doorbell") { + let parsed: unknown; + try { + parsed = JSON.parse(event.data); + } catch { + continue; + } + const doorbell = doorbellSchema.safeParse(parsed); + // `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 project + // lease can tell which of its doorbells it was rung for. + if (doorbell.success && doorbell.data.source === SOURCE && doorbell.data.kind === "issue") { + doorbells.push(); + const unit = doorbell.data.unit?.trim() ?? ""; + deps.onDoorbell(doorbell.data.kind, doorbell.data.id, unit === "" ? null : unit); + } + } + } + } finally { + if (renewTimer !== null) clearInterval(renewTimer); + if (baselineTimer !== null) clearInterval(baselineTimer); + connection = null; + leasedUntil = 0; + } + } + + return { + get connected() { + return connection !== null && leasedUntil > deps.now(); + }, + + status() { + return { + state, + since: stateSince, + leased: connection !== null && leasedUntil > deps.now(), + leasedUntil: connection === null ? 0 : leasedUntil, + windowMs: STATUS_WINDOW_MS, + doorbells: doorbells.count(), + lastDoorbellAt: doorbells.last(), + sweeps: sweeps.count(), + lastSweepAt, + lastSweepReason, + }; + }, + + onStateChange(listener) { + stateListeners.add(listener); + }, + + async added(kind, ...ids) { + if (connection === null || stream === null || ids.length === 0) return; + await lease(ids.map((id) => ({ kind, id })), stream.signal); + }, + + async run(signal) { + let backoff = timing.backoffMinMs; + setState("connecting"); + while (!signal.aborted) { + const controller = new AbortController(); + const onAbort = () => controller.abort(); + signal.addEventListener("abort", onAbort, { once: true }); + stream = controller; + try { + const response = await deps.fetch(new URL("/v1/events", deps.baseUrl), { headers: { accept: "text/event-stream" }, signal: controller.signal }); + if (!response.ok || response.body === null) throw new HooksRequestError(`bb-gate-hooks answered HTTP ${response.status} to the event stream`, response.status); + backoff = timing.backoffMinMs; + await consume(response.body, controller.signal); + if (!signal.aborted) deps.log.warn("bb-gate-hooks event stream ended; reconnecting"); + } catch (error) { + if (!signal.aborted && !controller.signal.aborted) deps.log.warn(`bb-gate-hooks event stream: ${errorMessage(error)}`); + } finally { + signal.removeEventListener("abort", onAbort); + controller.abort(); + stream = null; + setState(signal.aborted ? "stopped" : "connecting"); + } + if (signal.aborted) break; + // Down: nobody is ringing, so look for ourselves, slowly. + if (deps.now() - lastSweepAt >= timing.downSweepMs) runSweep("stream down"); + await sleep(backoff, signal); + backoff = Math.min(backoff * 2, timing.backoffMaxMs); + } + setState("stopped"); + }, + }; +} diff --git a/plugins/stewards/ops.test.ts b/plugins/stewards/ops.test.ts index 1c0ef1cd..5c7e354b 100644 --- a/plugins/stewards/ops.test.ts +++ b/plugins/stewards/ops.test.ts @@ -12,6 +12,12 @@ describe("targets", () => { expect(opsTargetKey(target)).toBe("k8s-namespace/bb-gate-production"); expect(parseOpsTargetKey("k8s-namespace/bb-gate-production")).toEqual(target); expect(parseOpsTargetKey("acme/web#3")).toBeNull(); + // A Sentry project is keyed by organization and project slug. + const sentry = { kind: "sentry-project", org: "acme", project: "web-api" } as const; + expect(opsTargetKey(sentry)).toBe("sentry-project/acme/web-api"); + expect(parseOpsTargetKey("sentry-project/acme/web-api")).toEqual(sentry); + expect(parseOpsTargetKey("sentry-project/acme")).toBeNull(); + expect(parseOpsTargetKey("sentry-project/Acme/web")).toBeNull(); }); }); diff --git a/plugins/stewards/ops.ts b/plugins/stewards/ops.ts index f23bea1e..cf7a5926 100644 --- a/plugins/stewards/ops.ts +++ b/plugins/stewards/ops.ts @@ -13,16 +13,23 @@ import type { Change } from "./reconcile.js"; export type K8sTarget = { kind: "k8s-namespace"; name: string }; export type DependabotTarget = { kind: "dependabot"; repo: string }; -export type OpsTarget = K8sTarget | DependabotTarget; +/** A Sentry project, by organization and project slug, read with the plugin's Sentry token (sentry.ts). */ +export type SentryTarget = { kind: "sentry-project"; org: string; project: string }; +export type OpsTarget = K8sTarget | DependabotTarget | SentryTarget; -/** 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}`); +/** The binding's entity id and key for a target: "k8s-namespace/bb-gate-production", "dependabot/acme/web" or "sentry-project/acme/web". */ +export const opsTargetKey = (t: OpsTarget): string => (t.kind === "k8s-namespace" ? `${t.kind}/${t.name}` : t.kind === "dependabot" ? `${t.kind}/${t.repo}` : `${t.kind}/${t.org}/${t.project}`); + +/** A Sentry slug: what Sentry puts in URLs for an organization or a project. */ +export const SENTRY_SLUG = /^[a-z0-9][a-z0-9._-]*$/u; export function parseOpsTargetKey(key: string): OpsTarget | null { 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]! }; + if (dep !== null) return { kind: "dependabot", repo: dep[2]! }; + const sentry = /^(sentry-project)\/([a-z0-9][a-z0-9._-]*)\/([a-z0-9][a-z0-9._-]*)$/u.exec(key); + return sentry === null ? null : { kind: "sentry-project", org: sentry[2]!, project: sentry[3]! }; } // ---- reading the Kubernetes API's JSON -------------------------------------------- @@ -230,6 +237,12 @@ export const LOG_LINES = 30; const LOG_LINE_CHARS = 400; const SECRET = /((?:authorization|token|secret|password|passwd|api[_-]?key|cookie|set-cookie)["']?\s*[:=]\s*["']?(?:bearer\s+)?|bearer\s+)([^\s"',;]+)/giu; +/** One line of evidence with obvious credentials replaced and its length clipped. Everything that goes into a ticket passes here. */ +export const redactLine = (line: string, max = LOG_LINE_CHARS): string => { + const clean = line.replace(SECRET, "$1[redacted]"); + return clean.length <= max ? clean : `${clean.slice(0, max)}…`; +}; + /** * The last lines of a log, clipped and with obvious credentials replaced. * They go into a Linear ticket, so a token printed by a crashing process @@ -240,8 +253,7 @@ export function logTail(text: string, lines = LOG_LINES): string[] { .split(/\r?\n/u) .filter((l) => l.trim() !== "") .slice(-lines) - .map((l) => l.replace(SECRET, "$1[redacted]")) - .map((l) => (l.length <= LOG_LINE_CHARS ? l : `${l.slice(0, LOG_LINE_CHARS)}…`)); + .map((l) => redactLine(l)); } // ---- the look, compared with the fingerprint map ---------------------------------------- diff --git a/plugins/stewards/sentry.test.ts b/plugins/stewards/sentry.test.ts new file mode 100644 index 00000000..e132a255 --- /dev/null +++ b/plugins/stewards/sentry.test.ts @@ -0,0 +1,214 @@ +import { describe, expect, it, vi } from "vitest"; +import { classify } from "./ops.js"; +import { NO_TOKEN, SentryApiError, createSentryReader, eventOf, issueInOrg, issueOf, issuesOf, recentLine, sentryChanges, sentrySightings, sentrySummary, stackTraceOf, type SentryFinding, type SentryIssue, type SentryLook } from "./sentry.js"; + +const now = Date.parse("2026-10-20T15:00:00Z"); +const since = now - 3_600_000; + +/** An issue as Sentry's API serializes it. */ +const apiIssue = (over: Record<string, unknown> = {}) => ({ + id: "6081234567", + shortId: "WEB-12", + title: "TypeError: Cannot read properties of undefined (reading 'id')", + culprit: "handler(src/api/users.ts)", + permalink: "https://acme.sentry.io/issues/6081234567/", + level: "error", + status: "unresolved", + substatus: "new", + count: "17", + userCount: 3, + firstSeen: "2026-10-20T14:30:00Z", + lastSeen: "2026-10-20T14:58:00Z", + project: { id: "1", slug: "web", name: "Web" }, + ...over, +}); + +const apiEvent = { + eventID: "abc123", + dateCreated: "2026-10-20T14:58:00Z", + message: "", + title: "TypeError: Cannot read properties of undefined (reading 'id')", + entries: [ + { + type: "exception", + data: { + values: [ + { + type: "TypeError", + value: "Cannot read properties of undefined (reading 'id') token=sk_live_abc", + stacktrace: { + frames: [ + { filename: "node_modules/express/lib/router/index.js", function: "next", lineNo: 280, inApp: false }, + { filename: "src/api/users.ts", function: "handler", lineNo: 42, colNo: 7, inApp: true, context: [[41, " const user = await load(req.params.id);"], [42, " return res.json({ id: user.id });"], [43, "}"]] }, + ], + }, + }, + ], + }, + }, + ], +}; + +describe("reading Sentry's JSON", () => { + it("reduces an issue to what a look reads, with the id as a string and credentials redacted", () => { + const issue = issueOf(apiIssue({ id: 6081234567, title: "Boom: Authorization: Bearer eyJabc" })); + expect(issue).toMatchObject({ id: "6081234567", shortId: "WEB-12", title: "Boom: Authorization: Bearer [redacted]", culprit: "handler(src/api/users.ts)", count: 17, userCount: 3, status: "unresolved", substatus: "new", project: "web" }); + expect(issueOf({ shortId: "no id" })).toBeNull(); + expect(issuesOf([apiIssue(), { nope: true }, apiIssue({ id: "2" })]).map((i) => i.id)).toEqual(["6081234567", "2"]); + expect(issuesOf({ not: "a list" })).toEqual([]); + expect(sentrySummary(issueOf(apiIssue())!)).toBe("WEB-12: TypeError: Cannot read properties of undefined (reading 'id') (handler(src/api/users.ts))"); + expect(recentLine(issueOf(apiIssue())!)).toBe("WEB-12 · TypeError: Cannot read properties of undefined (reading 'id') · handler(src/api/users.ts) · 17 events, last 2026-10-20T14:58:00Z"); + }); + + it("formats a stack trace innermost last, marking in-app frames with their source line, redacted", () => { + expect(stackTraceOf(apiEvent)).toEqual([ + "TypeError: Cannot read properties of undefined (reading 'id') token=[redacted]", + " node_modules/express/lib/router/index.js:280 in next", + " * src/api/users.ts:42 in handler", + " return res.json({ id: user.id });", + ]); + // A message event has no exception: its message is the trace. + expect(stackTraceOf({ entries: [{ type: "message", data: { formatted: "disk full on /var" } }] })).toEqual(["disk full on /var"]); + expect(stackTraceOf({})).toEqual([]); + const event = eventOf(apiEvent); + expect(event).toMatchObject({ id: "abc123", at: "2026-10-20T14:58:00Z", message: "TypeError: Cannot read properties of undefined (reading 'id')" }); + expect(event.stack).toHaveLength(4); + }); +}); + +describe("the reader", () => { + const fetchFor = (routes: Record<string, () => Response>) => + vi.fn(async (url: string | URL, init: RequestInit) => { + const path = new URL(String(url)).pathname + new URL(String(url)).search; + const headers = init.headers as Record<string, string>; + if (headers.authorization !== "Bearer tok-1") return new Response("", { status: 401 }); + const route = Object.entries(routes).find(([p]) => path.startsWith(p)); + return route === undefined ? new Response("", { status: 404 }) : route[1](); + }); + + it("reads the project, its unresolved issues and an issue's latest event with the token, and says when there is none", async () => { + const fetchImpl = fetchFor({ + "/api/0/projects/acme/web/issues/": () => Response.json([apiIssue()]), + "/api/0/projects/acme/web/": () => Response.json({ slug: "web", name: "Web" }), + "/api/0/issues/6081234567/events/latest/": () => Response.json(apiEvent), + "/api/0/issues/6081234567/": () => Response.json(apiIssue()), + }); + let token: string | null = "tok-1"; + const reader = createSentryReader(fetchImpl, { apiUrl: "https://sentry.io/", token: async () => token }); + expect(await reader.access({ kind: "sentry-project", org: "acme", project: "web" })).toEqual({ ok: true, name: "Web" }); + const issues = await reader.issues({ kind: "sentry-project", org: "acme", project: "web" }); + expect(issues.map((i) => i.shortId)).toEqual(["WEB-12"]); + expect(String(fetchImpl.mock.calls.at(-1)![0])).toBe("https://sentry.io/api/0/projects/acme/web/issues/?query=is%3Aunresolved&sort=date&limit=50&statsPeriod="); + expect((await reader.latestEvent("6081234567"))?.stack).toHaveLength(4); + expect((await reader.issue("6081234567"))?.id).toBe("6081234567"); + expect(await reader.issue("1")).toBeNull(); + expect(await reader.latestEvent("1")).toBeNull(); + expect(await reader.access({ kind: "sentry-project", org: "acme", project: "other" })).toEqual({ ok: false, error: "Sentry answered HTTP 404 to GET /api/0/projects/acme/other/" }); + + token = "wrong"; + await expect(reader.issues({ kind: "sentry-project", org: "acme", project: "web" })).rejects.toThrow(/Sentry refused the token \(401\)/u); + token = null; + const noToken = await reader.issues({ kind: "sentry-project", org: "acme", project: "web" }).catch((e: unknown) => e); + expect(noToken).toBeInstanceOf(SentryApiError); + expect((noToken as Error).message).toBe(NO_TOKEN); + // The token never leaves the header: no call was made without one, and no error names it. + expect(fetchImpl.mock.calls.every(([, init]) => String((init.headers as Record<string, string>).authorization).startsWith("Bearer "))).toBe(true); + }); +}); + +describe("sightings", () => { + const issue = (over: Partial<SentryIssue> = {}): SentryIssue => ({ ...issueOf(apiIssue())!, ...over }); + const old = { firstSeen: "2026-10-01T00:00:00Z" }; + + it("are the issues first seen, regressed, rung or known and still firing since the last look, ordered by why", () => { + const fresh = issue(); + const regressed = issue({ id: "2", shortId: "WEB-2", ...old, substatus: "regressed", lastSeen: "2026-10-20T14:59:00Z" }); + const rung = issue({ id: "3", shortId: "WEB-3", ...old, substatus: "ongoing", lastSeen: "2026-10-20T14:50:00Z" }); + const known = issue({ id: "4", shortId: "WEB-4", ...old, substatus: "ongoing", lastSeen: "2026-10-20T14:40:00Z" }); + const quiet = issue({ id: "5", shortId: "WEB-5", ...old, substatus: "ongoing", lastSeen: "2026-10-20T13:00:00Z" }); + const knownButQuiet = issue({ id: "6", shortId: "WEB-6", ...old, substatus: "ongoing", lastSeen: "2026-10-20T13:00:00Z" }); + const resolved = issue({ id: "7", shortId: "WEB-7", status: "resolved" }); + const out = sentrySightings([quiet, known, rung, fresh, regressed, knownButQuiet, resolved], { since }, new Set(["3", "7"]), new Set(["4", "6"])); + expect(out.map((s) => [s.issue.shortId, s.reasons])).toEqual([ + ["WEB-2", ["regressed"]], + ["WEB-12", ["new"]], + ["WEB-3", ["rung"]], + ["WEB-4", ["ongoing"]], + ]); + // A new issue that is also rung is both; "ongoing" is not said of it. + expect(sentrySightings([fresh], { since }, new Set(["6081234567"]), new Set(["6081234567"]))[0]!.reasons).toEqual(["new", "rung"]); + // An issue read by id is the target's organization's only when its permalink says so; one without a permalink is taken on trust. + expect(issueInOrg({ permalink: "https://acme.sentry.io/issues/1/" }, "acme")).toBe(true); + expect(issueInOrg({ permalink: "https://sentry.example.com/organizations/acme/issues/1/" }, "acme")).toBe(true); + expect(issueInOrg({ permalink: "https://other.sentry.io/issues/1/" }, "acme")).toBe(false); + expect(issueInOrg({ permalink: "https://sentry.example.com/organizations/other/issues/1/" }, "acme")).toBe(false); + expect(issueInOrg({ permalink: null }, "acme")).toBe(true); + expect(issueInOrg({ permalink: "not a url" }, "acme")).toBe(true); + // An old regression Sentry still labels regressed is not news again once it was seen before the last look. + expect(sentrySightings([issue({ ...old, substatus: "regressed", lastSeen: "2026-10-20T12:00:00Z" })], { since }, new Set(), new Set())).toEqual([]); + }); +}); + +describe("what changed between two looks", () => { + const finding = (over: Partial<SentryFinding> = {}): SentryFinding => ({ + fingerprint: "6081234567", + shortId: "WEB-12", + title: "TypeError", + culprit: null, + permalink: "https://acme.sentry.io/issues/6081234567/", + level: "error", + substatus: "new", + count: 17, + userCount: 3, + firstSeen: "2026-10-20T14:30:00Z", + lastSeen: "2026-10-20T14:58:00Z", + reasons: ["new"], + event: null, + class: "new", + ticket: null, + ticketState: null, + firstSeenAt: now, + lastCommentedAt: null, + ...over, + }); + const look = (findings: SentryFinding[], error: string | null = null): SentryLook => ({ at: now, target: "sentry-project/acme/web", error, unresolved: findings.length, recent: [], notes: [], findings }); + const hour = 3_600_000; + + it("makes a new, returned or regressed issue worth a turn at once, and a rung one once per requeue", () => { + const fresh = look([finding()]); + expect(sentryChanges(null, fresh, hour)).toEqual([{ text: "New Sentry issue: WEB-12 TypeError (https://acme.sentry.io/issues/6081234567/)", actionable: true }]); + expect(sentryChanges(fresh, fresh, hour)).toEqual([]); + const filed = look([finding({ class: "recurring", ticket: "OPS-5", ticketState: "In Progress", reasons: ["ongoing"] })]); + expect(sentryChanges(fresh, filed, hour)).toEqual([]); + // A second event under the open ticket: a comment is due when the steward has not spoken within a requeue. + const rung = look([finding({ class: "recurring", ticket: "OPS-5", reasons: ["rung"], count: 18 })]); + expect(sentryChanges(filed, rung, hour)).toEqual([{ text: "Sentry rang for WEB-12 under OPS-5: 18 events, last 2026-10-20T14:58:00Z", actionable: true }]); + const commented = look([finding({ class: "recurring", ticket: "OPS-5", reasons: ["rung"], count: 19, lastCommentedAt: now - 10 * 60_000 })]); + expect(sentryChanges(rung, commented, hour)).toEqual([{ text: "Sentry rang for WEB-12 under OPS-5: 19 events, last 2026-10-20T14:58:00Z", actionable: false }]); + // Sentry marking it regressed while the ticket is open is evidence that moved. + const regressed = look([finding({ class: "recurring", ticket: "OPS-5", reasons: ["regressed"], substatus: "regressed" })]); + expect(sentryChanges(filed, regressed, hour)).toEqual([{ text: "Regressed in Sentry under OPS-5: WEB-12 TypeError (https://acme.sentry.io/issues/6081234567/)", actionable: true }]); + expect(sentryChanges(regressed, regressed, hour)).toEqual([]); + // Back after its ticket was Done. + const back = look([finding({ class: "returned", ticket: "OPS-5", ticketState: "Done", reasons: ["ongoing"] })]); + expect(sentryChanges(filed, back, hour)).toEqual([{ text: "Back after OPS-5 was resolved (Done): WEB-12 TypeError (https://acme.sentry.io/issues/6081234567/)", actionable: true }]); + expect(sentryChanges(filed, look([]), hour)).toEqual([{ text: "No longer seen: WEB-12 (OPS-5)", actionable: false }]); + // A known issue seen again for the first time by this look is quiet. + expect(sentryChanges(null, filed, hour)).toEqual([{ text: "Seen again under OPS-5: WEB-12 TypeError (https://acme.sentry.io/issues/6081234567/)", actionable: false }]); + }); + + it("wakes once for a missing token, and is quiet about any other read failure", () => { + const noToken = look([], NO_TOKEN); + expect(sentryChanges(null, noToken, hour)).toEqual([{ text: `Cannot read sentry-project/acme/web: ${NO_TOKEN}`, actionable: true }]); + expect(sentryChanges(noToken, noToken, hour)).toEqual([]); + const forbidden = look([], "Sentry answered HTTP 403 to GET /api/0/projects/acme/web/issues/"); + expect(sentryChanges(noToken, forbidden, hour)).toEqual([{ text: "Cannot read sentry-project/acme/web: Sentry answered HTTP 403 to GET /api/0/projects/acme/web/issues/", actionable: false }]); + expect(sentryChanges(forbidden, look([]), hour)).toEqual([{ text: "sentry-project/acme/web is readable again", actionable: false }]); + }); + + it("classifies against the fingerprint map like any ops sighting", () => { + const sighting = { fingerprint: "6081234567", workload: "WEB-12", pods: [], container: null, signature: "new", summary: "WEB-12: TypeError", restarts: 0, events: [], logs: null, previous: false }; + const rows = new Map([["6081234567", { fingerprint: "6081234567", ticketKey: "OPS-5", firstSeenAt: 1, lastCommentedAt: null }]]); + expect(classify([sighting], rows, new Map([["OPS-5", { state: "Done", stateType: "completed" }]]), now)[0]).toMatchObject({ class: "returned", ticket: "OPS-5" }); + }); +}); diff --git a/plugins/stewards/sentry.ts b/plugins/stewards/sentry.ts new file mode 100644 index 00000000..8973990f --- /dev/null +++ b/plugins/stewards/sentry.ts @@ -0,0 +1,359 @@ +// The ops kind's Sentry source: a Sentry project read with the plugin's own +// Sentry token (a secret setting), turned into sightings an ops steward +// files tickets for. The issue id Sentry assigns is the fingerprint: it is +// what a doorbell from bb-gate-hooks carries, what the Sentry API is keyed +// on, and stable across events, so one issue is one ticket however often it +// fires. +// +// Two halves. The reader (`createSentryReader`) is the only thing that talks +// to Sentry: the project's unresolved issues, one issue by id, and the +// latest event of an issue (its stack trace). Everything else is pure: +// which issues count as sightings for a look, what the wake shows of each +// (with credentials redacted as the kubectl look's logs are), and what +// changed between two looks. server.ts stores and wakes. +import { z } from "zod"; +import { redactLine, type OpsTarget, type SentryTarget } from "./ops.js"; +import type { Change } from "./reconcile.js"; + +export const SENTRY_API_URL = "https://sentry.io"; +/** The look's error when the plugin has no Sentry token to read with; the steward files the provide-secret need for it. */ +export const NO_TOKEN = "no Sentry token is configured"; +/** The setting the token lives in, named so the steward's provide-secret need says where it goes. */ +export const TOKEN_SETTING = "sentryToken"; +/** Where a Sentry user creates an auth token. */ +export const TOKEN_PAGE = "https://sentry.io/settings/account/api/auth-tokens/"; +/** The scopes the token needs: read the project (admission, the list) and its events (stack traces). */ +export const TOKEN_SCOPES = ["project:read", "event:read"] as const; + +/** Unresolved issues read per look, newest activity first. */ +export const ISSUES_PER_LOOK = 50; +/** Stack traces are fetched for at most this many findings per look. */ +export const EVENTS_PER_LOOK = 5; +/** At most this many findings a look reports; the rest are counted. */ +export const FINDINGS_PER_LOOK = 20; +/** Frames kept per exception, innermost last. */ +export const FRAMES_PER_EXCEPTION = 25; +/** Lines of stack trace kept in all. */ +export const STACK_LINES = 80; +/** Unresolved issues listed for context beside the findings. */ +export const RECENT_PER_LOOK = 10; + +// ---- reading Sentry's JSON --------------------------------------------------------------- + +type Json = Record<string, unknown>; +const obj = (v: unknown): Json => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Json) : {}); +const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []); +const str = (v: unknown): string | null => (typeof v === "string" && v !== "" ? v : null); +const num = (v: unknown): number | null => { + if (typeof v === "number" && Number.isFinite(v)) return v; + if (typeof v === "string" && /^\d+$/u.test(v)) return Number(v); + return null; +}; + +/** One issue as the Sentry API serializes it, reduced to what a look reads. Text fields are redacted. */ +export type SentryIssue = { + /** Sentry's issue id, a string of digits: the fingerprint and the doorbell id. */ + id: string; + /** The human one, "WEB-12". */ + shortId: string; + title: string; + culprit: string | null; + permalink: string | null; + level: string | null; + /** unresolved, resolved, ignored. */ + status: string; + /** new, regressed, ongoing, escalating, archived_until_escalating, ... ; null on older servers. */ + substatus: string | null; + /** Lifetime events, as Sentry counts them. */ + count: number; + userCount: number; + firstSeen: string | null; + lastSeen: string | null; + /** The project slug Sentry reports, which is what doorbells carry as the unit. */ + project: string | null; +}; + +export function issueOf(json: unknown): SentryIssue | null { + const issue = obj(json); + const id = str(issue.id) ?? (num(issue.id) === null ? null : String(num(issue.id))); + if (id === null) return null; + return { + id, + shortId: str(issue.shortId) ?? id, + title: redactLine(str(issue.title) ?? "(untitled)"), + culprit: str(issue.culprit) === null ? null : redactLine(str(issue.culprit)!), + permalink: str(issue.permalink), + level: str(issue.level), + status: str(issue.status) ?? "unresolved", + substatus: str(issue.substatus), + count: num(issue.count) ?? 0, + userCount: num(issue.userCount) ?? 0, + firstSeen: str(issue.firstSeen), + lastSeen: str(issue.lastSeen), + project: str(obj(issue.project).slug), + }; +} + +export const issuesOf = (json: unknown): SentryIssue[] => arr(json).map(issueOf).filter((i): i is SentryIssue => i !== null); + +/** The latest event of an issue, as the wake shows it: when, what it said, and its stack trace. */ +export type SentryEvent = { id: string | null; at: string | null; message: string | null; stack: string[] }; + +/** + * An event's stack trace as lines: each exception value as a header, then + * its frames innermost last, in-app frames marked with `*` and shown with + * their source line when the event carries it. A message event with no + * exception gives its message. Everything is redacted and clipped: it goes + * into a Linear ticket. + */ +export function stackTraceOf(event: unknown): string[] { + const e = obj(event); + const lines: string[] = []; + for (const entry of arr(e.entries).map(obj)) { + if (entry.type !== "exception") continue; + for (const value of arr(obj(entry.data).values).map(obj)) { + const type = str(value.type) ?? "Error"; + const message = str(value.value); + lines.push(redactLine(message === null ? type : `${type}: ${message}`)); + const frames = arr(obj(value.stacktrace).frames).map(obj).slice(-FRAMES_PER_EXCEPTION); + for (const f of frames) { + const where = str(f.filename) ?? str(f.module) ?? str(f.absPath) ?? "?"; + const line = num(f.lineNo); + const inApp = f.inApp === true; + lines.push(redactLine(` ${inApp ? "*" : " "} ${where}${line === null ? "" : `:${line}`} in ${str(f.function) ?? "?"}`)); + if (inApp) { + const context = arr(f.context).map(arr).find((c) => num(c[0]) === line); + const source = context === undefined ? null : str(context[1]); + if (source !== null && source.trim() !== "") lines.push(redactLine(` ${source.trim()}`)); + } + } + } + } + if (lines.length === 0) { + const message = arr(e.entries).map(obj).find((entry) => entry.type === "message"); + const formatted = message === undefined ? null : (str(obj(message.data).formatted) ?? str(obj(message.data).message)); + if (formatted !== null) lines.push(redactLine(formatted)); + } + return lines.slice(0, STACK_LINES); +} + +export function eventOf(json: unknown): SentryEvent { + const e = obj(json); + const message = str(e.message) ?? str(e.title); + return { id: str(e.eventID) ?? str(e.id), at: str(e.dateCreated), message: message === null ? null : redactLine(message), stack: stackTraceOf(json) }; +} + +// ---- the reader --------------------------------------------------------------------------- + +export class SentryApiError extends Error { + constructor( + message: string, + readonly status: number, + ) { + super(message); + this.name = "SentryApiError"; + } +} + +export interface SentryReader { + /** The project's unresolved issues, most recent activity first. Throws when the project cannot be read. */ + issues(target: SentryTarget): Promise<SentryIssue[]>; + /** One issue by id; null when Sentry does not have it (or will not show it). */ + issue(id: string): Promise<SentryIssue | null>; + /** The latest event of an issue; null when there is none to read. */ + latestEvent(id: string): Promise<SentryEvent | null>; + /** What `bb stewards check` reports: the project read with the token, or why not. */ + access(target: SentryTarget): Promise<{ ok: true; name: string } | { ok: false; error: string }>; +} + +type FetchLike = (url: string | URL, init: RequestInit) => Promise<Response>; + +/** + * A reader of one server's Sentry, through one token. The token goes into + * one request header and nowhere else: not a log line, not an error. + */ +export function createSentryReader(fetchImpl: FetchLike, opts: { apiUrl: string; token: () => Promise<string | null>; timeoutMs?: number }): SentryReader { + const base = opts.apiUrl.replace(/\/+$/u, ""); + const get = async (path: string): Promise<unknown> => { + const token = (await opts.token())?.trim() ?? ""; + if (token === "") throw new SentryApiError(NO_TOKEN, 0); + const response = await fetchImpl(`${base}${path}`, { method: "GET", headers: { authorization: `Bearer ${token}`, accept: "application/json" }, signal: AbortSignal.timeout(opts.timeoutMs ?? 20_000) }); + if (response.status === 401) throw new SentryApiError("Sentry refused the token (401): it is wrong, revoked or lacks a scope", 401); + if (!response.ok) throw new SentryApiError(`Sentry answered HTTP ${response.status} to GET ${path}`, response.status); + return response.json(); + }; + const notFound = (error: unknown) => error instanceof SentryApiError && (error.status === 404 || error.status === 403); + const projectPath = (t: SentryTarget) => `/api/0/projects/${encodeURIComponent(t.org)}/${encodeURIComponent(t.project)}/`; + return { + async issues(target) { + const query = new URLSearchParams({ query: "is:unresolved", sort: "date", limit: String(ISSUES_PER_LOOK), statsPeriod: "" }); + return issuesOf(await get(`${projectPath(target)}issues/?${query}`)); + }, + async issue(id) { + try { + return issueOf(await get(`/api/0/issues/${encodeURIComponent(id)}/`)); + } catch (error) { + if (notFound(error)) return null; + throw error; + } + }, + async latestEvent(id) { + try { + return eventOf(await get(`/api/0/issues/${encodeURIComponent(id)}/events/latest/`)); + } catch (error) { + if (notFound(error)) return null; + throw error; + } + }, + async access(target) { + try { + const project = obj(await get(projectPath(target))); + return { ok: true, name: str(project.name) ?? str(project.slug) ?? target.project }; + } catch (error) { + return { ok: false, error: error instanceof Error ? error.message : String(error) }; + } + }, + }; +} + +// ---- sightings ---------------------------------------------------------------------------- + +/** Why an issue is in a look: first seen since the last look, regressed or escalating in Sentry, rung by a doorbell, or known and still firing. */ +export const SENTRY_REASONS = ["new", "regressed", "rung", "ongoing"] as const; +export type SentryReason = (typeof SENTRY_REASONS)[number]; + +export type SentrySighting = { fingerprint: string; issue: SentryIssue; reasons: SentryReason[] }; + +const REGRESSED = new Set(["regressed", "escalating"]); +const REASON_ORDER: Record<SentryReason, number> = { regressed: 0, new: 1, rung: 2, ongoing: 3 }; + +/** + * Which issues a look reports, and why. `since` is the last look; `rung` + * the issue ids doorbells named since it; `known` the fingerprints already + * in the map (a known issue still firing is a sighting, so its ticket gets + * the comment the playbook asks for). An issue Sentry has resolved is not a + * sighting even when rung: its disappearance is what the look says of it. + */ +export function sentrySightings(issues: readonly SentryIssue[], at: { since: number }, rung: ReadonlySet<string>, known: ReadonlySet<string>): SentrySighting[] { + const out: SentrySighting[] = []; + const seenAfter = (iso: string | null) => iso !== null && Date.parse(iso) >= at.since; + for (const issue of issues) { + if (issue.status !== "unresolved") continue; + const reasons: SentryReason[] = []; + if (issue.substatus !== null && REGRESSED.has(issue.substatus) && seenAfter(issue.lastSeen)) reasons.push("regressed"); + if (seenAfter(issue.firstSeen)) reasons.push("new"); + if (rung.has(issue.id)) reasons.push("rung"); + if (known.has(issue.id) && seenAfter(issue.lastSeen) && !reasons.includes("new")) reasons.push("ongoing"); + if (reasons.length === 0) continue; + out.push({ fingerprint: issue.id, issue, reasons }); + } + out.sort((a, b) => REASON_ORDER[a.reasons[0]!] - REASON_ORDER[b.reasons[0]!] || (b.issue.lastSeen ?? "").localeCompare(a.issue.lastSeen ?? "")); + return out.slice(0, FINDINGS_PER_LOOK); +} + +/** + * Whether an issue belongs to this organization, as far as its permalink + * says: `https://<org>.sentry.io/issues/<id>/` on sentry.io, and + * `/organizations/<org>/issues/<id>/` on a self-hosted server. The issue + * JSON names its project by slug only, and a slug is unique only within an + * organization, so a rung issue read by id is checked here before it joins + * a look; an issue with no permalink is taken as the target's. + */ +export function issueInOrg(issue: Pick<SentryIssue, "permalink">, org: string): boolean { + if (issue.permalink === null) return true; + try { + const url = new URL(issue.permalink); + return url.hostname.toLowerCase().startsWith(`${org}.`) || url.pathname.toLowerCase().includes(`/organizations/${org}/`); + } catch { + return true; + } +} + +/** The one-line summary the fingerprint map keeps for an issue. */ +export const sentrySummary = (issue: SentryIssue): string => `${issue.shortId}: ${issue.title}${issue.culprit === null ? "" : ` (${issue.culprit})`}`; + +/** One unresolved issue as a context line beside the findings. */ +export const recentLine = (issue: SentryIssue): string => `${issue.shortId} · ${issue.title}${issue.culprit === null ? "" : ` · ${issue.culprit}`} · ${issue.count} event${issue.count === 1 ? "" : "s"}, last ${issue.lastSeen ?? "?"}`; + +// ---- the look ------------------------------------------------------------------------------ + +export const sentryFindingSchema = z.object({ + /** The Sentry issue id. */ + fingerprint: z.string(), + shortId: z.string(), + title: z.string(), + culprit: z.string().nullable(), + permalink: z.string().nullable(), + level: z.string().nullable(), + substatus: z.string().nullable(), + count: z.number(), + userCount: z.number(), + firstSeen: z.string().nullable(), + lastSeen: z.string().nullable(), + reasons: z.array(z.enum(SENTRY_REASONS)), + /** The latest event, when it was read; null when it was not (the cap, or Sentry had none). */ + event: z.object({ id: z.string().nullable(), at: z.string().nullable(), message: z.string().nullable(), stack: z.array(z.string()) }).nullable(), + /** new: no ticket yet. recurring: its ticket is open. returned: its ticket was resolved and it is back. */ + class: z.enum(["new", "recurring", "returned"]), + ticket: z.string().nullable(), + ticketState: z.string().nullable(), + firstSeenAt: z.number(), + lastCommentedAt: z.number().nullable(), +}); +export type SentryFinding = z.infer<typeof sentryFindingSchema>; + +export const sentryLookSchema = z.object({ + at: z.number(), + target: z.string(), + /** Set when the project could not be read; the rest is then empty. NO_TOKEN when there is no token to read with. */ + error: z.string().nullable(), + /** Unresolved issues in the project, as many as the look read. */ + unresolved: z.number(), + /** The most recently active unresolved issues the findings do not cover, as lines. */ + recent: z.array(z.string()), + /** What could not be read, in sentences: an event, a rung issue. */ + notes: z.array(z.string()), + findings: z.array(sentryFindingSchema), +}); +export type SentryLook = z.infer<typeof sentryLookSchema>; + +export const emptySentryLook = (at: number, target: string, error: string | null): SentryLook => ({ at, target, error, unresolved: 0, recent: [], notes: [], findings: [] }); + +export const isSentryTarget = (t: OpsTarget): t is SentryTarget => t.kind === "sentry-project"; + +const line = (f: SentryFinding) => `${f.shortId} ${f.title}${f.permalink === null ? "" : ` (${f.permalink})`}`; + +/** + * What changed between two looks, as the mechanical tier weighs it. A new + * issue, one back after its ticket was resolved, and one Sentry says has + * regressed are worth a turn at once. A doorbell for an issue under an open + * ticket is worth one when the steward has not commented within a requeue, + * so a noisy issue is one comment per interval, not one per event. A look + * that cannot read Sentry for want of a token is worth a turn once, so the + * steward can file the need for it; any other read failure is quiet, and + * `bb stewards check` says why. + */ +export function sentryChanges(before: SentryLook | null, after: SentryLook, requeueMs: number): Change[] { + if (after.error !== null) { + if (before !== null && before.error === after.error) return []; + return [{ text: `Cannot read ${after.target}: ${after.error}`, actionable: after.error === NO_TOKEN }]; + } + const changes: Change[] = []; + if (before !== null && before.error !== null) changes.push({ text: `${after.target} is readable again`, actionable: false }); + const was = new Map((before?.findings ?? []).map((f) => [f.fingerprint, f])); + for (const f of after.findings) { + const prev = was.get(f.fingerprint); + if (f.class === "new" && (prev === undefined || prev.class !== "new")) changes.push({ text: `New Sentry issue: ${line(f)}`, actionable: true }); + else if (f.class === "returned" && prev?.class !== "returned") changes.push({ text: `Back after ${f.ticket} was resolved (${f.ticketState ?? "closed"}): ${line(f)}`, actionable: true }); + else if (f.class === "recurring" && f.reasons.includes("regressed") && !(prev?.reasons.includes("regressed") ?? false)) changes.push({ text: `Regressed in Sentry under ${f.ticket}: ${line(f)}`, actionable: true }); + else if (f.class === "recurring" && f.reasons.includes("rung")) { + const quiet = f.lastCommentedAt !== null && after.at - f.lastCommentedAt < requeueMs; + changes.push({ text: `Sentry rang for ${f.shortId} under ${f.ticket}: ${f.count} event${f.count === 1 ? "" : "s"}, last ${f.lastSeen ?? "?"}`, actionable: !quiet }); + } else if (f.class === "recurring" && prev === undefined) changes.push({ text: `Seen again under ${f.ticket}: ${line(f)}`, actionable: false }); + } + const now = new Set(after.findings.map((f) => f.fingerprint)); + for (const f of was.values()) { + if (!now.has(f.fingerprint)) changes.push({ text: `No longer seen: ${f.shortId}${f.ticket === null ? "" : ` (${f.ticket})`}`, actionable: false }); + } + return changes; +} diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 8cb843ac..21582506 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -173,9 +173,9 @@ function world() { 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<StewardsDeps> = {}) { +async function setup(extra: Partial<StewardsDeps> = {}, settings: Record<string, string> = {}) { const w = world(); - const { bb, harness } = createFakePluginHost({ pluginId: "stewards", sdk: w.sdk as never, agentSkillIds: ["stewards"] }); + const { bb, harness } = createFakePluginHost({ pluginId: "stewards", sdk: w.sdk as never, agentSkillIds: ["stewards"], settings }); await createStewardsPlugin({ now: w.now, timing: { debounceMs: 1, nightlyStaggerMs: 0 }, github: w.github, ...extra })(bb); const hooks = testHooks.get("stewards")!; /** Let debounced work run to completion. */ @@ -3273,3 +3273,224 @@ describe("dependency stewards", () => { expect(check.stdout).toMatch(/deps: watching 1 repo for alerts: acme\/web/u); }); }); + +describe("Sentry stewards", () => { + const TARGET = "sentry-project/acme/web"; + const ISSUE_ID = "6081234567"; + + const sentryIssue = (over: Record<string, unknown> = {}) => ({ + id: ISSUE_ID, + shortId: "WEB-12", + title: "TypeError: Cannot read properties of undefined (reading 'id')", + culprit: "handler(src/api/users.ts)", + permalink: `https://acme.sentry.io/issues/${ISSUE_ID}/`, + level: "error", + status: "unresolved", + substatus: "new", + count: "17", + userCount: 3, + firstSeen: "2026-10-14T14:30:00Z", + lastSeen: "2026-10-14T14:58:00Z", + project: { id: "1", slug: "web", name: "Web" }, + ...over, + }); + const sentryEvent = { + eventID: "abc123", + dateCreated: "2026-10-14T14:58:00Z", + title: "TypeError: Cannot read properties of undefined (reading 'id')", + entries: [{ type: "exception", data: { values: [{ type: "TypeError", value: "Cannot read properties of undefined (reading 'id')", stacktrace: { frames: [{ filename: "src/api/users.ts", function: "handler", lineNo: 42, inApp: true, context: [[42, " return res.json({ id: user.id });"]] }] } }] } }], + }; + + /** A fake Sentry: the project's unresolved issues, each issue by id, and one latest event for all. */ + function fakeSentry() { + const issues = new Map<string, Record<string, unknown>>(); + const calls: string[] = []; + let status = 200; + const fetchImpl = (async (url: string | URL, init?: RequestInit) => { + const u = new URL(String(url)); + calls.push(u.pathname); + if ((init?.headers as Record<string, string>).authorization !== "Bearer tok-1") return new Response("", { status: 401 }); + if (status !== 200) return new Response("", { status }); + if (u.pathname === "/api/0/projects/acme/web/") return Response.json({ slug: "web", name: "Web" }); + // The list is the organization's own, as the real one is by its URL; an issue whose permalink names another organization is not in it. + if (u.pathname === "/api/0/projects/acme/web/issues/") return Response.json([...issues.values()].filter((i) => i.status === "unresolved" && !String(i.permalink).startsWith("https://other."))); + const issue = /^\/api\/0\/issues\/(\d+)\/$/u.exec(u.pathname); + if (issue !== null) return issues.has(issue[1]!) ? Response.json(issues.get(issue[1]!)) : new Response("", { status: 404 }); + if (/^\/api\/0\/issues\/\d+\/events\/latest\/$/u.test(u.pathname)) return Response.json(sentryEvent); + return new Response("", { status: 404 }); + }) as typeof fetch; + return { issues, calls, fetchImpl, setStatus: (s: number) => (status = s) }; + } + + async function watching(options: { token?: string; issues?: Array<Record<string, unknown>>; env?: Record<string, string> } = {}) { + const sentry = fakeSentry(); + for (const i of options.issues ?? [sentryIssue()]) sentry.issues.set(String(i.id), i); + const t = await setup({ fetch: sentry.fetchImpl, env: options.env ?? {} }, { sentryToken: options.token ?? "tok-1" }); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] }, ops: { targets: [{ kind: "sentry-project", org: "acme", project: "web" }], autoAdopt: ["urgent"] } }); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + await t.hooks.sweep(); + await t.flush(); + const steward = () => t.spawns.find((x) => String(x.title).startsWith("Sentry watch")); + const wakes = () => { + const id = steward()?.id; + return id === undefined ? [] : [String(steward()!.prompt), ...t.sends.filter((x) => x.threadId === id).map((x) => x.text)]; + }; + const doorbell = async (id: string, unit: string | null = "web") => { + t.hooks.sentryDoorbell(id, unit); + await t.flush(); + }; + const report = (opsTickets: Array<{ fingerprint: string; ticket: string; did: "filed" | "commented" | "reopened" }>, summary = "Filed.") => + t.tool("steward_report", { phase: "watching", summary, nextAction: "Watch", actor: "steward", opsTickets }, steward()!.id); + return { t, sentry, steward, wakes, doorbell, report }; + } + + it("watches the project under the ops playbook, with the issue, its culprit, permalink, counts and stack trace in the wake", async () => { + const { t, steward, wakes, report } = await watching(); + expect(await t.list()).toMatchObject([{ key: TARGET, kind: "ops", threadId: steward()!.id, ended: false }]); + expect(steward()).toMatchObject({ title: "Sentry watch: acme/web" }); + // The project is leased on bb-gate-hooks as org/slug; no issue yet, none has a ticket. + expect(t.hooks.sentryLeases()).toEqual([{ kind: "project", id: "acme/web" }]); + + const first = wakes()[0]!; + expect(first).toMatch(/^# Sentry watch: sentry-project\/acme\/web/u); + expect(first).toMatch(/You have just been made the ops steward for this Sentry project/u); + expect(first).toMatch(/### New: no ticket yet/u); + expect(first).toContain(`#### ${ISSUE_ID}`); + expect(first).toMatch(/\*\*WEB-12\*\* TypeError: Cannot read properties of undefined \(reading 'id'\) \(error\)/u); + expect(first).toMatch(/Culprit: handler\(src\/api\/users\.ts\)/u); + expect(first).toContain(`https://acme.sentry.io/issues/${ISSUE_ID}/`); + expect(first).toMatch(/17 events, 3 users; first seen 2026-10-14T14:30:00Z, last seen 2026-10-14T14:58:00Z; Sentry says new/u); + expect(first).toMatch(/Why it is here: first seen since the last look/u); + expect(first).toMatch(/Latest event abc123 at 2026-10-14T14:58:00Z/u); + expect(first).toContain(" * src/api/users.ts:42 in handler\n return res.json({ id: user.id });"); + expect(first).toMatch(/1 unresolved issue in the project; 1 below/u); + expect(first).toMatch(/File tickets in the Linear team ENG/u); + expect(first).toMatch(/ops\.autoAdopt: a ticket you file at urgent priority/u); + expect(first).toMatch(/The fingerprint is the Sentry issue id/u); + expect(first).toMatch(/New Sentry issue: WEB-12 TypeError/u); + // The playbook's text covers the Sentry case, and the thread is told it holds no token. + expect(first).toMatch(/For a Sentry project, the plugin reads it with its own Sentry token/u); + expect(first).toMatch(/you cannot query Sentry yourself/u); + + // Filing records the issue id against the ticket, and the issue is leased by itself from then on. + expect((await report([{ fingerprint: ISSUE_ID, ticket: "ENG-50", did: "filed" }])).error).toBe(false); + expect(t.hooks.store.fingerprint("p1", ISSUE_ID)).toMatchObject({ ticketKey: "ENG-50", summary: expect.stringMatching(/^WEB-12: TypeError/u) }); + expect(t.hooks.sentryLeases()).toEqual([{ kind: "project", id: "acme/web" }, { kind: "issue", id: ISSUE_ID }]); + }); + + it("rings on a doorbell for a new issue, treats a second event as a comment under the open ticket, and a regression after Done as returned", async () => { + const { t, sentry, wakes, doorbell, report } = await watching(); + expect((await report([{ fingerprint: ISSUE_ID, ticket: "ENG-50", did: "filed" }])).error).toBe(false); + t.entities.set("ENG-50", issue({ id: "ENG-50", key: "ENG-50", state: "In Progress", stateType: "started" })); + const before = wakes().length; + + // A doorbell for another organization's issue with the same project slug is read by id and left out. + t.advance(60_000); + sentry.issues.set("66", sentryIssue({ id: "66", shortId: "WEB-66", title: "Not ours", permalink: "https://other.sentry.io/issues/66/", firstSeen: "2026-10-14T15:00:30Z", lastSeen: "2026-10-14T15:00:30Z" })); + await doorbell("66"); + expect(wakes()).toHaveLength(before); + + // A new issue created after the last look: the doorbell names it and the look lists it as new. + sentry.issues.set("7", sentryIssue({ id: "7", shortId: "WEB-13", title: "Boom", firstSeen: "2026-10-14T15:00:30Z", lastSeen: "2026-10-14T15:00:30Z" })); + await doorbell("7"); + expect(wakes()).toHaveLength(before + 1); + expect(wakes().at(-1)).not.toContain("#### 66"); + expect(wakes().at(-1)).toContain("#### 7"); + expect(wakes().at(-1)).toMatch(/New Sentry issue: WEB-13 Boom/u); + // The filed one is not news: quiet, with its ticket. + expect(wakes().at(-1)).not.toMatch(/### Recurring/u); + + // Another event minutes after filing is noted, not a wake: filing was a word on it, and a comment is due once per requeue. + t.advance(60_000); + sentry.issues.set(ISSUE_ID, sentryIssue({ count: "18", lastSeen: "2026-10-14T15:02:00Z", substatus: "ongoing" })); + await doorbell(ISSUE_ID); + expect(wakes()).toHaveLength(before + 1); + + // A second event on the filed issue an hour on: Sentry rings for it, the wake shows it recurring under ENG-50, and no new ticket is asked for. + t.advance(2 * 3_600_000); + sentry.issues.set(ISSUE_ID, sentryIssue({ count: "19", lastSeen: "2026-10-14T17:02:00Z", substatus: "ongoing" })); + await doorbell(ISSUE_ID); + const second = wakes().at(-1)!; + expect(wakes()).toHaveLength(before + 2); + expect(second).toMatch(/### Recurring: its ticket is open/u); + expect(second).toMatch(/\*\*WEB-12\*\*.*· ticket ENG-50 \(In Progress\)/u); + expect(second).toMatch(/Why it is here: Sentry rang for it; known and still firing/u); + expect(second).toMatch(/Sentry rang for WEB-12 under ENG-50: 19 events/u); + expect(second).not.toMatch(/New Sentry issue/u); + expect((await report([{ fingerprint: ISSUE_ID, ticket: "ENG-50", did: "commented" }], "Commented.")).error).toBe(false); + + // Another event right after the comment is noted, not a wake. + t.advance(60_000); + sentry.issues.set(ISSUE_ID, sentryIssue({ count: "20", lastSeen: "2026-10-14T17:03:00Z", substatus: "ongoing" })); + await doorbell(ISSUE_ID); + expect(wakes()).toHaveLength(before + 2); + + // Resolved on Linear, then Sentry sees it again: returned, worth a turn at once. + t.entities.set("ENG-50", issue({ id: "ENG-50", key: "ENG-50", state: "Done", stateType: "completed" })); + t.advance(2 * 3_600_000); + sentry.issues.set(ISSUE_ID, sentryIssue({ count: "21", lastSeen: "2026-10-14T19:03:00Z", substatus: "regressed" })); + await doorbell(ISSUE_ID); + const back = wakes().at(-1)!; + expect(back).toMatch(/### Returned: its ticket was resolved/u); + expect(back).toMatch(/Back after ENG-50 was resolved \(Done\): WEB-12/u); + expect(back).toMatch(/regressed in Sentry/u); + }); + + it("lists new and regressed issues from the periodic look alone, with no doorbell", async () => { + const { t, sentry, wakes } = await watching(); + const before = wakes().length; + t.advance(10 * 60_000); + sentry.issues.set("8", sentryIssue({ id: "8", shortId: "WEB-14", title: "Timeout", firstSeen: "2026-10-14T15:05:00Z", lastSeen: "2026-10-14T15:05:00Z" })); + sentry.issues.set("9", sentryIssue({ id: "9", shortId: "WEB-15", title: "Old one back", firstSeen: "2026-10-01T00:00:00Z", lastSeen: "2026-10-14T15:06:00Z", substatus: "regressed" })); + await t.hooks.sweep(); + await t.flush(); + expect(wakes()).toHaveLength(before + 1); + const look = wakes().at(-1)!; + expect(look).toContain("#### 8"); + expect(look).toContain("#### 9"); + expect(look).toMatch(/Why it is here: regressed in Sentry/u); + expect(look).toMatch(/3 unresolved issues in the project; 2 below/u); + // The one already seen and unfiled is still in the map and shown among the others for context. + expect(look).toMatch(/### Other unresolved issues, most recent first\n\n- WEB-12/u); + // A look that finds nothing new wakes nobody. + t.advance(10 * 60_000); + await t.hooks.sweep(); + await t.flush(); + expect(wakes()).toHaveLength(before + 1); + }); + + it("without a token, wakes the steward once to file the provide-secret need, and check says so", async () => { + const { t, steward, wakes } = await watching({ token: "" }); + expect(steward()).toBeDefined(); + const first = wakes()[0]!; + expect(first).toMatch(/The plugin has no Sentry token, so it cannot read this project/u); + expect(first).toMatch(/File one provide-secret need for it with steward_report: variable `sentryToken`, url https:\/\/sentry\.io\/settings\/account\/api\/auth-tokens\//u); + expect(first).toMatch(/project:read and event:read/u); + expect(first).toMatch(/Cannot read sentry-project\/acme\/web: no Sentry token is configured/u); + // Said once: the next looks are quiet until a token appears. + await t.hooks.sweep(); + await t.flush(); + expect(wakes()).toHaveLength(1); + expect((await t.list())[0]!.summary).toBeNull(); + const check = (await t.harness.callRpc("stewardsCheck", { projectId: "p1" })) as { ok: boolean; lines: string[] }; + expect(check.ok).toBe(false); + expect(check.lines).toContain("problem: sentry: no Sentry token is configured: set the Sentry token in the stewards plugin's settings (a user auth token with project:read and event:read)"); + expect(check.lines.find((l) => l.startsWith("problem: sentry: cannot read the target sentry-project/acme/web"))).toBeDefined(); + expect(check.lines).toContain("sentry: no bb-gate-hooks here (BB_HOOKS_URL is not set), so Sentry issues are seen by the periodic look only"); + expect(t.hooks.sentryLeases()).toEqual([{ kind: "project", id: "acme/web" }]); + }); + + it("with a token, check reads the project and says how doorbells arrive; a refused project is a problem", async () => { + const { t, sentry } = await watching({ env: { BB_HOOKS_URL: "http://hooks.test:8081" } }); + const ok = (await t.harness.callRpc("stewardsCheck", { projectId: "p1" })) as { ok: boolean; lines: string[] }; + expect(ok.ok).toBe(true); + expect(ok.lines).toContain("sentry: sentry-project/acme/web is readable (Web)"); + expect(ok.lines).toContain("sentry: doorbells from bb-gate-hooks: stopped"); + sentry.setStatus(403); + const bad = (await t.harness.callRpc("stewardsCheck", { projectId: "p1" })) as { ok: boolean; lines: string[] }; + expect(bad.ok).toBe(false); + expect(bad.lines).toContain("problem: sentry: cannot read the target sentry-project/acme/web: Sentry answered HTTP 403 to GET /api/0/projects/acme/web/"); + // A project that stops reading is logged, not woken about: nothing new until it reads again. + expect(sentry.calls.every((c) => c.startsWith("/api/0/"))).toBe(true); + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 537bdefd..fc2a7c1b 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -36,6 +36,7 @@ import { playbookNameFor, playbookPath, playbookStates, + sentryTargets, STAGES, usesKind, type BindingKind, @@ -47,8 +48,10 @@ import { 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 { HOOKS_URL_ENV, createHooksLoop, type Lease, type Rejection } from "./hooks-client.js"; import { nightlyDue, stillNight } from "./nightly.js"; -import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type DependabotTarget, type K8sTarget, type OpsLook, type OpsTarget, type Sighting, type TicketState } from "./ops.js"; +import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type DependabotTarget, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; +import { EVENTS_PER_LOOK, NO_TOKEN, RECENT_PER_LOOK, SENTRY_API_URL, TOKEN_SCOPES, createSentryReader, emptySentryLook, issueInOrg, recentLine, sentryChanges, sentrySightings, sentrySummary, type SentryFinding, type SentryLook, type SentryReader } from "./sentry.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, @@ -67,7 +70,7 @@ import { ACTORS, MIGRATIONS, NEEDS_KINDS, createStore, needChoices, type Binding import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; -import { PROJECT_STEWARD_INTRO, choicesNote, formatDepsWake, formatOpsWake, formatProjectWake, formatSessionWake, formatWake, workerQuestion, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, choicesNote, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, 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. */ @@ -127,6 +130,10 @@ export interface StewardsDeps { kubectl?: (args: string[], where: { projectId: string; hostId: string | null }) => Promise<KubectlResult>; /** The GitHub writer the page's Approve and Merge buttons use; the server's gh login by default. */ github?: GithubWriter; + /** What reads Sentry and subscribes to bb-gate-hooks for it; global fetch by default. */ + fetch?: typeof fetch; + /** Where BB_HOOKS_URL is read from; the process environment by default. */ + env?: Record<string, string | undefined>; } const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error)); @@ -367,7 +374,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P description: "After a steward's or the project steward's turn, and before a wake that would push it over, its context is compacted when it holds more than this. Every wake is self-contained, so little is lost. 0 leaves compaction to the provider.", default: 120_000, }, + sentryToken: { + type: "string", + secret: true, + label: "Sentry token", + description: `A Sentry user auth token with the scopes ${TOKEN_SCOPES.join(" and ")}, for the ops stewards of sentry-project targets: the plugin reads each project's issues with it and proves its bb-gate-hooks leases with it. Created at Settings → Account → API → Auth Tokens in Sentry.`, + }, + sentryApiUrl: { + type: "string", + label: "Sentry API", + description: "Where Sentry is read; change it for a self-hosted Sentry.", + default: SENTRY_API_URL, + }, }); + const fetchImpl = deps.fetch ?? globalThis.fetch; + const env = deps.env ?? process.env; const db = bb.storage.database(); bb.storage.migrate(db, MIGRATIONS); @@ -1249,8 +1270,8 @@ 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)]; + /** Every ops target a project watches: the k8s namespaces, the Sentry projects and the Dependabot repositories. */ + const allOpsTargets = (config: ProjectConfig): OpsTarget[] => [...k8sTargets(config.file), ...sentryTargets(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: K8sTarget, playbook: Playbook): Promise<OpsLook> { @@ -1380,6 +1401,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await reconcileDeps(b, config, playbook, target, force); return; } + if (target.kind === "sentry-project") { + await reconcileSentry(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(); @@ -1488,6 +1513,241 @@ 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 }); } + // ---- Sentry targets ---------------------------------------------------------------------------- + // + // A sentry-project target is read with the plugin's own Sentry token (a + // secret setting), not through a source plugin: there is no sentry plugin, + // and the source contract has no use for one. bb-gate-hooks rings the + // binding the moment Sentry sees a new issue or a regression (the loop + // below holds a `project` lease per target and an `issue` lease per issue + // with a ticket); the look at every sweep and requeue is the backstop + // when hooks are down, listing what is new or regressed since the last + // look. The Sentry issue id is the fingerprint. + + const sentryToken = async (): Promise<string | null> => { + const value = (await settings.get()).sentryToken; + const token = typeof value === "string" ? value.trim() : ""; + return token === "" ? null : token; + }; + const sentryReader = async (): Promise<SentryReader> => { + const value = (await settings.get()).sentryApiUrl; + const apiUrl = typeof value === "string" && value.trim() !== "" ? value.trim() : SENTRY_API_URL; + return createSentryReader(fetchImpl, { apiUrl, token: sentryToken }); + }; + /** Issue ids doorbells named since each binding's last look. */ + const sentryRung = new Map<string, Set<string>>(); + /** At most this many rung issues are read one by one when the list does not carry them. */ + const RUNG_PER_LOOK = 10; + /** An issue with a ticket is leased while it was seen within this long. */ + const ISSUE_LEASE_WINDOW_MS = 30 * 86_400_000; + + const openSentryBindings = (): Array<{ binding: Binding; target: SentryTarget }> => + store + .open() + .filter((b) => b.kind === "ops") + .flatMap((b) => { + const target = parseOpsTargetKey(b.entityId); + return target?.kind === "sentry-project" ? [{ binding: b, target }] : []; + }); + + /** One look at a Sentry project: the issues new, regressed, rung or still firing since the last look, classified against the fingerprint map. */ + async function lookAtSentry(b: Binding, target: SentryTarget, playbook: Playbook): Promise<SentryLook> { + const at = now(); + const key = opsTargetKey(target); + const since = b.sentryLook !== null && b.sentryLook.error === null ? b.sentryLook.at : at - playbook.requeueDefaultMs; + const rung = sentryRung.get(b.id) ?? new Set<string>(); + const notes: string[] = []; + try { + const reader = await sentryReader(); + const issues = await reader.issues(target); + const byId = new Set(issues.map((i) => i.id)); + // A rung issue the list does not carry (older activity, or more than a page away) is read by itself. + for (const id of [...rung].filter((x) => !byId.has(x)).slice(0, RUNG_PER_LOOK)) { + try { + const issue = await reader.issue(id); + // Gone (resolved, or not this token's to see), or another organization's project with the same slug. + if (issue === null || (issue.project !== null && issue.project !== target.project) || !issueInOrg(issue, target.org)) continue; + issues.push(issue); + } catch (error) { + notes.push(`Issue ${id}, which Sentry rang for, could not be read (${errorMessage(error)})`); + } + } + const known = new Set(store.fingerprints(b.id).map((r) => r.fingerprint)); + const sightings = sentrySightings(issues, { since }, rung, known); + sentryRung.delete(b.id); + const rows = store.sight( + b.projectId, + b.id, + sightings.map((s) => ({ fingerprint: s.fingerprint, summary: sentrySummary(s.issue) })), + ); + const tickets = await ticketStates([...rows.values()].map((r) => r.ticketKey).filter((k): k is string => k !== null)); + const asSightings: Sighting[] = sightings.map((s) => ({ fingerprint: s.fingerprint, workload: s.issue.shortId, pods: [], container: null, signature: s.reasons[0] ?? "ongoing", summary: sentrySummary(s.issue), restarts: 0, events: [], logs: null, previous: false })); + const classified = classify(asSightings, rows, tickets, at); + const findings: SentryFinding[] = []; + let eventsRead = 0; + for (const [i, s] of sightings.entries()) { + const c = classified[i]!; + let event: SentryFinding["event"] = null; + if (eventsRead < EVENTS_PER_LOOK) { + eventsRead += 1; + try { + event = await reader.latestEvent(s.issue.id); + } catch (error) { + notes.push(`The latest event of ${s.issue.shortId} could not be read (${errorMessage(error)})`); + } + } + const { issue } = s; + findings.push({ + fingerprint: s.fingerprint, + shortId: issue.shortId, + title: issue.title, + culprit: issue.culprit, + permalink: issue.permalink, + level: issue.level, + substatus: issue.substatus, + count: issue.count, + userCount: issue.userCount, + firstSeen: issue.firstSeen, + lastSeen: issue.lastSeen, + reasons: s.reasons, + event, + class: c.class, + ticket: c.ticket, + ticketState: c.ticketState, + firstSeenAt: c.firstSeenAt, + lastCommentedAt: c.lastCommentedAt, + }); + } + const covered = new Set(findings.map((f) => f.fingerprint)); + const unresolved = issues.filter((i) => i.status === "unresolved"); + const recent = unresolved.filter((i) => !covered.has(i.id)).slice(0, RECENT_PER_LOOK).map(recentLine); + return { at, target: key, error: null, unresolved: unresolved.length, recent, notes, findings }; + } catch (error) { + return emptySentryLook(at, key, errorMessage(error)); + } + } + + /** + * The same turn for a Sentry project: look, compare with the last look, + * and wake on what changed. A look that fails for want of a token wakes + * the steward once, so it files the provide-secret need; any other + * failure is logged, and `bb stewards check` says why. + */ + async function reconcileSentry(b: Binding, config: ProjectConfig, playbook: Playbook, target: SentryTarget, force: WakeReason | null): Promise<void> { + const before = b.sentryLook; + const look = await lookAtSentry(b, target, playbook); + const requeueCame = b.requeueAt !== null && b.requeueAt <= now(); + const requeueAt = requeueCame || b.requeueAt === null ? now() + playbook.requeueDefaultMs : b.requeueAt; + b = store.patch(b.id, { sentryLook: look, requeueAt }); + if (look.error !== null && before?.error !== look.error) bb.log.warn(`stewards: cannot read ${b.entityKey}: ${look.error}`); + if (look.error !== null && look.error !== NO_TOKEN) return; + + const changes = sentryChanges(before, look, playbook.requeueDefaultMs); + if (requeueCame && look.error === null) changes.push({ text: look.findings.length > 0 ? "Requeue time came, with issues to act on" : "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); + }; + // A steward that has never been woken is due its first turn as soon as the project can be read, or the need for a token can be filed. + 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 = formatSentryWake({ + reason: reason ?? (requeueCame && loudQueued === 0 ? "requeue" : "changed"), + binding: b, + playbook, + look, + team: opsTeam(config.file), + label: config.file.label, + autoAdopt: config.file.ops.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 }); + } + + // The subscriber: one stream to bb-gate-hooks for the `sentry` source, + // proven with the plugin's token (bb-gate/docs/hooks.md, "Sentry"). A + // project lease is sent as org/slug and leased under the slug, which is + // what a doorbell carries as its unit; an issue lease is the issue id. + // Without BB_HOOKS_URL, or without a token, nothing is leased and the + // sweeps carry the watch. + const hooksUrl = env[HOOKS_URL_ENV]?.trim() ?? ""; + /** The leases bb-gate-hooks refused at the last renewal, by `<kind> <id>`, for `bb stewards check`. */ + let sentryRefused = new Map<string, string>(); + + function sentryLeases(): Lease[] { + const seen = new Set<string>(); + const out: Lease[] = []; + const add = (kind: Lease["kind"], id: string) => { + const k = `${kind} ${id}`; + if (seen.has(k)) return; + seen.add(k); + out.push({ kind, id }); + }; + for (const c of configs.values()) { + if (c.value === null) continue; + for (const t of sentryTargets(c.value.file)) add("project", `${t.org}/${t.project}`); + } + const recent = now() - ISSUE_LEASE_WINDOW_MS; + for (const { binding } of openSentryBindings()) { + for (const r of store.fingerprints(binding.id)) if (r.ticketKey !== null && r.lastSeenAt >= recent) add("issue", r.fingerprint); + } + return out; + } + + /** A Sentry doorbell: the issue id, and the project slug when the service named one. Every binding it concerns looks. */ + function onSentryDoorbell(id: string, unit: string | null): void { + for (const { binding, target } of openSentryBindings()) { + const byUnit = unit !== null && unit === target.project; + const byIssue = store.fingerprint(binding.projectId, id)?.bindingId === binding.id; + if (!byUnit && !byIssue) continue; + const rung = sentryRung.get(binding.id) ?? new Set<string>(); + rung.add(id); + sentryRung.set(binding.id, rung); + scheduleReconcile(binding.id); + } + } + + const sentryHooks = createHooksLoop({ + fetch: fetchImpl, + baseUrl: hooksUrl, + now, + log: bb.log, + token: sentryToken, + watchIds: sentryLeases, + onDoorbell: (kind, id, unit) => { + if (kind === "issue") onSentryDoorbell(id, unit); + }, + async onRejected(rejected: Rejection[]) { + sentryRefused = new Map(rejected.map((r) => [`${r.kind} ${r.id}`, r.reason])); + for (const r of rejected) bb.log.warn(`stewards: bb-gate-hooks refused a Sentry ${r.kind} lease on ${r.id} (${r.reason}); only the periodic look sees it`); + }, + async sweep() { + // Coverage cannot be proven: every Sentry binding looks for itself. + for (const { binding } of openSentryBindings()) scheduleReconcile(binding.id); + }, + }); + const sentryWanted = () => [...configs.values()].some((c) => c.value !== null && sentryTargets(c.value.file).length > 0); + /** * One ops binding per configured target. A target taken out of the * project file ends its binding; put back, the same binding and thread @@ -1498,8 +1758,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P */ async function syncOpsBindings(config: ProjectConfig): Promise<void> { const wanted = new Map<string, { target: OpsTarget; playbook: Playbook }>(); - const k8sPlaybook = playbookFor(config, "ops"); - if (k8sPlaybook !== null) for (const target of k8sTargets(config.file)) wanted.set(opsTargetKey(target), { target, playbook: k8sPlaybook }); + const opsPlaybook = playbookFor(config, "ops"); + if (opsPlaybook !== null) for (const target of [...k8sTargets(config.file), ...sentryTargets(config.file)]) wanted.set(opsTargetKey(target), { target, playbook: opsPlaybook }); 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) { @@ -1516,13 +1776,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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}`; + const title = target.kind === "k8s-namespace" ? `Ops watch: ${target.name}` : target.kind === "dependabot" ? `Deps watch: ${target.repo}` : `Sentry watch: ${target.org}/${target.project}`; try { 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 } bb.log.info(`stewards: watching ${key} with an ops binding (${playbook.name})`); + // A Sentry project is leased as soon as it is watched; the next renewal would otherwise be up to half a lease away. + if (target.kind === "sentry-project") sentryHooks.added("project", `${target.org}/${target.project}`).catch((error: unknown) => bb.log.warn(`stewards: could not lease ${key} right away: ${errorMessage(error)}`)); await serial(`b:${created.id}`, () => reconcileBinding(created.id, "adopted")); } else if (b.endedAt !== null && !b.manualDetach) { await serial(`b:${b.id}`, async () => { @@ -2843,12 +3105,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } const b = role.binding; if (b.kind === "ops") { + const sentry = parseOpsTargetKey(b.entityId)?.kind === "sentry-project"; return { tools: ["steward_report", "steward_update"], skills: ["stewards"], instructions: `You are the ops steward watching ${JSON.stringify(b.entityKey)} (binding ${b.id}, playbook ${JSON.stringify(b.playbook)}), and your thread id is ${context.thread.id}. ` + - "The plugin looks at the target for you and every wake carries what it found; you never change production and start no workers. To dig further, run kubectl on the target yourself, but only get, describe, logs and auth can-i: it acts as the user, whose rights are broad. " + + (sentry + ? "The plugin reads this Sentry project for you with its own token and every wake carries the issues that are new, regressed or rung, with their stack traces; you never change production and start no workers. Your thread holds no Sentry token, so diagnose from the wake and the code in your workspace. " + : "The plugin looks at the target for you and every wake carries what it found; you never change production and start no workers. To dig further, run kubectl on the target yourself, but only get, describe, logs and auth can-i: it acts as the user, whose rights are broad. ") + "File and comment on Linear tickets with the linear_ tools, which sign for you; escalate each ticket you file to the project steward with steward_report, as the playbook says. " + "End every turn you were woken for with steward_report, listing in opsTickets every ticket you filed, commented on or reopened. Read the stewards skill for the protocol.", }; @@ -3014,7 +3279,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b.kind !== "ops") return toolError(new Error("opsTickets is for an ops steward's report. Report without it.")); const unknown = opsTickets.filter((t) => store.fingerprint(b.projectId, t.fingerprint) === null).map((t) => JSON.stringify(t.fingerprint)); if (unknown.length > 0) { - const known = (b.opsLook?.findings ?? []).map((f) => `- ${f.fingerprint}`).join("\n"); + const known = [...(b.opsLook?.findings ?? []), ...(b.sentryLook?.findings ?? []), ...(b.depsLook?.alerts ?? [])].map((f) => `- ${f.fingerprint}`).join("\n"); return toolError(new Error(`Nothing was recorded: ${unknown.join(", ")} ${unknown.length === 1 ? "is not a fingerprint" : "are not fingerprints"} this project has seen. Use them as the wake gives them${known === "" ? "." : `:\n${known}`}`)); } } @@ -3065,6 +3330,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ); } for (const t of opsTickets) store.recordTicket(b.projectId, t.fingerprint, t.ticket, t.did); + // A Sentry issue with a ticket is leased by itself, so its next event rings even outside the project lease. + if (opsTickets.length > 0 && parseOpsTargetKey(b.entityId)?.kind === "sentry-project") { + sentryHooks.added("issue", ...opsTickets.map((t) => t.fingerprint)).catch((error: unknown) => bb.log.warn(`stewards: could not lease a Sentry issue right away: ${errorMessage(error)}`)); + } // Delivered after the status is written, together with any approval // request this report makes due, so the project steward reads the // new status and is woken once. @@ -3500,7 +3769,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const s = b.status; const open = store.openEscalations(b.id); const look = b.opsLook; - const watch = look === null ? null : look.error !== null ? `cannot read the target: ${look.error}` : `looked ${iso(look.at)}: ${look.findings.length === 0 ? "nothing failing" : `${look.findings.length} problem(s) failing`}`; + const sentry = b.sentryLook; + const watch = + look !== null + ? look.error !== null + ? `cannot read the target: ${look.error}` + : `looked ${iso(look.at)}: ${look.findings.length === 0 ? "nothing failing" : `${look.findings.length} problem(s) failing`}` + : sentry === null + ? null + : sentry.error !== null + ? `cannot read the target: ${sentry.error}` + : `looked ${iso(sentry.at)}: ${sentry.findings.length === 0 ? "nothing new" : `${sentry.findings.length} issue(s) new, regressed or rung`}`; const needs = store.openNeeds(b.id); const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, watch, b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), ...needs.map((n) => `${n.kind} need ${n.id}${n.url === "" ? "" : ` (${n.url})`}`), unheardWait(s, open, needs), asksForOpenApproval(s, open, needs)].filter((f) => f !== null); return `${b.entityKey} — ${b.kind}, ${b.phase ?? "?"}${b.threadId === null ? "" : `, thread ${b.threadId}`}\n ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${s.blockedOn === null ? "" : `; blocked on ${s.blockedOn}`}`}${flags.length > 0 ? `\n [${flags.join("; ")}]` : ""}`; @@ -3598,6 +3877,28 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } bb.background.schedule("nightly", "*/5 * * * *", nightlyTick); + if (hooksUrl !== "") { + // The stream is opened only once a project lists a Sentry target; a + // server with none holds no stream for a source it never leases on. + bb.background.service("sentry-hooks", { + async start(signal) { + while (!signal.aborted && !sentryWanted()) { + await new Promise<void>((resolve) => { + const timer = setTimeout(resolve, 60_000); + signal.addEventListener( + "abort", + () => { + clearTimeout(timer); + resolve(); + }, + { once: true }, + ); + }); + } + if (!signal.aborted) await sentryHooks.run(signal); + }, + }); + } bb.background.service("loop", { async start(signal) { const requeue = setInterval(() => void requeueTick().catch((e: unknown) => bb.log.warn(`stewards: requeue: ${errorMessage(e)}`)), timing.requeueTickMs); @@ -3666,6 +3967,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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 k8sTargets(config.file)) lines.push(...opsAccessLines(opsTargetKey(target), await reader.access(target).catch((error: unknown): OpsAccess => ({ error: errorMessage(error), reads: [], logs: null, writes: [] })))); + const sentry = sentryTargets(config.file); + if (sentry.length > 0) { + if ((await sentryToken()) === null) lines.push(`problem: sentry: ${NO_TOKEN}: set the Sentry token in the stewards plugin's settings (a user auth token with ${TOKEN_SCOPES.join(" and ")})`); + const sentryApi = await sentryReader(); + for (const target of sentry) { + const key = opsTargetKey(target); + const a = await sentryApi.access(target); + lines.push(a.ok ? `sentry: ${key} is readable (${a.name})` : `problem: sentry: cannot read the target ${key}: ${a.error}`); + const refused = sentryRefused.get(`project ${target.org}/${target.project}`); + if (refused !== undefined) lines.push(`sentry: ${key}: bb-gate-hooks refused its project lease (${refused}); only the periodic look sees it`); + } + const status = sentryHooks.status(); + lines.push(hooksUrl === "" ? "sentry: no bb-gate-hooks here (BB_HOOKS_URL is not set), so Sentry issues are seen by the periodic look only" : `sentry: doorbells from bb-gate-hooks: ${status.state}${status.state === "connected" ? (status.leased ? ", leased" : ", not leased") : ""}`); + } } const deps = config.file.deps; const slaText = (v: number | "asap") => (v === "asap" ? "asap" : formatDuration(v)); @@ -3951,12 +4266,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P tagged.clear(); kept.clear(); }; - testHooks.set(bb.pluginId, { sweep, store, db, forgetTags, nightlyPass: (projectId: string, night: string) => loadConfig(projectId, true).then((c) => (c === null ? undefined : nightlyPass(c, night, true))), settle: () => Promise.all([...chains.values()]).then(() => undefined) }); + testHooks.set(bb.pluginId, { sweep, store, db, forgetTags, nightlyPass: (projectId: string, night: string) => loadConfig(projectId, true).then((c) => (c === null ? undefined : nightlyPass(c, night, true))), settle: () => Promise.all([...chains.values()]).then(() => undefined), sentryDoorbell: onSentryDoorbell, sentryLeases }); }; } /** Test seams, keyed by plugin id. Not part of any contract. */ -export const testHooks = new Map<string, { sweep(): Promise<void>; store: Store; db: { prepare(sql: string): { run(...args: unknown[]): unknown } }; forgetTags(): void; nightlyPass(projectId: string, night: string): Promise<void>; settle(): Promise<void> }>(); +export const testHooks = new Map<string, { sweep(): Promise<void>; store: Store; db: { prepare(sql: string): { run(...args: unknown[]): unknown } }; forgetTags(): void; nightlyPass(projectId: string, night: string): Promise<void>; settle(): Promise<void>; sentryDoorbell(id: string, unit: string | null): void; sentryLeases(): Lease[] }>(); export { DEFAULT_PLAYBOOKS, STEWARDS_PLUGIN_ID }; diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 57fca30f..ec38522d 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -15,7 +15,7 @@ steward** per project sits above all of them. | `ticket` | the project's label (default `bb-managed`) is on a Linear issue in a listed team | `linear-tickets` | | `pr` | the label is on a pull request in one of the project's repos | `github-prs` | | `review` | a teammate opens, or marks ready, a pull request in one of the project's repos | `github-reviews` | -| `ops` | `project.json` lists a target in `ops.targets` (a Kubernetes namespace) | `ops-watch` | +| `ops` | `project.json` lists a target in `ops.targets` (a Kubernetes namespace or a Sentry project) | `ops-watch` | ## If you are a steward @@ -154,12 +154,16 @@ Two tools are yours; everything else you do with the tools every thread has. ## If you are an ops steward -You watch one production target; the wake is the plugin's look at it (pods, -Warning events, and log lines where the server may read them), with each -problem's fingerprint marked new, recurring or returned. You never change -production and start no workers. To dig further you may run kubectl on the -target yourself, but only `get`, `describe`, `logs` and `auth can-i`: it -acts as the user, whose rights are broad, and nothing else stops a write. +You watch one production target; the wake is the plugin's look at it (for +a namespace: pods, Warning events, and log lines where the server may read +them; for a Sentry project: the issues new, regressed or rung since the +last look, with the title, culprit, permalink, counts and latest stack +trace), with each problem's fingerprint marked new, recurring or returned. +You never change production and start no workers. To dig further into a +namespace you may run kubectl on the target yourself, but only `get`, +`describe`, `logs` and `auth can-i`: it acts as the user, whose rights are +broad, and nothing else stops a write. You cannot query Sentry: the token +is the plugin's, so diagnose from the wake and the code in your workspace. - **New:** search the team for an open ticket about it, then file one ticket per problem with `linear_create_issue`: pod and container, since when, the @@ -177,6 +181,9 @@ acts as the user, whose rights are broad, and nothing else stops a write. duplicate. - **All healthy:** the wake says so every requeue; report it with `actor: other` and end the turn. +- **No Sentry token** (the wake says so): file the one `provide-secret` + need it describes (variable `sentryToken`, the Sentry auth-tokens page, + the scopes), report with `actor: me`, and end the turn. - **No logs** (the wake says so): diagnose from status and events, and say in the ticket that logs were not available. @@ -249,7 +256,9 @@ The project must be a multi-repo project: configuration is read from its `.bb/stewards/project.json` (Linear teams you belong to, or `--teams ENG,OPS`) and the four default playbooks into the workspace's `.bb`. To watch production, list targets in `ops.targets`, such as - `{ "kind": "k8s-namespace", "name": "bb-gate-production" }`. + `{ "kind": "k8s-namespace", "name": "bb-gate-production" }` or + `{ "kind": "sentry-project", "org": "acme", "project": "web" }` (the + latter needs the plugin's Sentry token setting). 2. Review them, commit inside `.bb`, publish with `workspace_publish_guidance`, and merge the `guidance-<thread>` branch. Edits take effect only once merged. @@ -287,7 +296,9 @@ above which a steward is compacted after its turn. target` and `bb stewards check` says why: kubectl on the project's machine cannot reach the cluster (not installed, the machine not on the tailnet as the developer or a tagged node, no kubeconfig or context for - it; `ops.context` picks one), or it may not list pods there. + it; `ops.context` picks one), or it may not list pods there. For a Sentry + project: no token in the plugin's settings (the steward is woken once to + ask for it), or the token cannot read the project. Otherwise it takes a turn every `requeue-default`, healthy or not. - **A repo should not be stewarded.** Every GitHub repo in `repos.json` is, unless `project.json` lists it in `github.exclude` (`owner/repo`). Bindings diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index cab0f0e4..03063ef1 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -12,6 +12,7 @@ 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"; +import { sentryLookSchema, type SentryLook } from "./sentry.js"; // Append-only: bb.storage.migrate records each statement's hash and refuses a // changed one, so a schema change is a new statement at the end. @@ -174,6 +175,9 @@ export const MIGRATIONS = [ // Fixed choices on a decide item's escalation and on the question a forwarded one makes: short labels, JSON, so the page can offer a button each (BB-20). `ALTER TABLE escalations ADD COLUMN choices TEXT`, `ALTER TABLE questions ADD COLUMN choices TEXT`, + // A Sentry project binding's last look: the issues new, regressed or rung + // since the look before, classified against the fingerprint map. + `ALTER TABLE bindings ADD COLUMN sentry_look TEXT`, ]; // ---- values kept as JSON ------------------------------------------------------------ @@ -293,6 +297,8 @@ export type Binding = { opsLook: OpsLook | null; /** A Dependabot alert binding's last look; null for every other kind. */ depsLook: DepsLook | null; + /** A Sentry project binding's last look; null for every other kind. */ + sentryLook: SentryLook | null; createdAt: number; endedAt: number | null; endReason: string | null; @@ -349,6 +355,7 @@ function rowToBinding(r: BindingRow): Binding { manualDetach: Number(r.manual_detach) === 1, opsLook: json(opsLookSchema.nullable(), str("ops_look"), null), depsLook: json(depsLookSchema.nullable(), str("deps_look"), null), + sentryLook: json(sentryLookSchema.nullable(), str("sentry_look"), null), createdAt: Number(r.created_at), endedAt: num("ended_at"), endReason: str("end_reason"), @@ -395,6 +402,7 @@ const COLUMNS = { manualDetach: "manual_detach", opsLook: "ops_look", depsLook: "deps_look", + sentryLook: "sentry_look", endedAt: "ended_at", endReason: "end_reason", } as const satisfies Partial<Record<keyof Binding, string>>; diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index c2ca3356..4a5105c5 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -244,28 +244,43 @@ tickets. You never change production: no restarts, no scaling, no edits, no workers. You read what each wake shows, file tickets, comment on them, and escalate to the project steward, which decides whether a ticket is worked. -The plugin looks at the target for you, with kubectl on this machine as the -user: pod health, Warning events, and the last log lines of a failing -container. To dig further you may run kubectl yourself, but only get, -describe, logs and auth can-i, against the target. The user's own rights -are broad; nothing but this list stops a delete, an exec, a restart or an -edit, so never run one. Where logs could not be read, diagnose from status -and events, and say so in the ticket. - -Each problem has a fingerprint: the workload, the container and an error -signature. Put it in the ticket description on a line of its own, -"Fingerprint: \`<fingerprint>\`", so a person can match ticket and problem. -After acting, report every ticket you filed, commented on or reopened in -steward_report's opsTickets: that is how the next look knows a problem is -already filed. When the wake says all is healthy, just report it, with actor -other, and end the turn. - -A ticket you file says: which pod and container, since when and how often; -the evidence (status, events, log lines) quoted; your diagnosis, the likely -cause and what would confirm it; and a priority: urgent when users cannot -work, high when a service is degraded, medium otherwise. Search the team for -an open ticket about the same problem first (linear_search), and comment -there instead of filing a second one. +The target is a Kubernetes namespace or a Sentry project; the wake's title +says which. + +For a namespace, the plugin looks at it for you, with kubectl on this +machine as the user: pod health, Warning events, and the last log lines of +a failing container. To dig further you may run kubectl yourself, but only +get, describe, logs and auth can-i, against the target. The user's own +rights are broad; nothing but this list stops a delete, an exec, a restart +or an edit, so never run one. Where logs could not be read, diagnose from +status and events, and say so in the ticket. + +For a Sentry project, the plugin reads it with its own Sentry token and +bb-gate-hooks rings it the moment an issue is created or regresses; each +wake carries the issues that are new, regressed or rung since the last +look, with the title, culprit, permalink, event and user counts, first and +last seen, and the latest event's stack trace. Your thread holds no Sentry +token, so you cannot query Sentry: diagnose from that evidence and the code +in your workspace (the in-app frames name it), and link the permalink. When +the wake says there is no token, file the provide-secret need it describes +and nothing else. + +Each problem has a fingerprint: for a namespace the workload, the container +and an error signature; for a Sentry project the Sentry issue id. Put it in +the ticket description on a line of its own, "Fingerprint: \`<fingerprint>\`", +so a person can match ticket and problem. After acting, report every ticket +you filed, commented on or reopened in steward_report's opsTickets: that is +how the next look knows a problem is already filed. When the wake says all +is healthy, or nothing is new, just report it, with actor other, and end the +turn. + +A ticket you file says: which pod and container, or which Sentry issue and +where in the code; since when and how often; the evidence (status, events, +log lines, or the stack trace) quoted; your diagnosis, the likely cause and +what would confirm it; and a priority: urgent when users cannot work, high +when a service is degraded or an error hits many users, medium otherwise. +Search the team for an open ticket about the same problem first +(linear_search), and comment there instead of filing a second one. ## New @@ -279,14 +294,18 @@ wake says; such a ticket needs no escalation. The problem is still there and its ticket is open. Comment on that ticket when the evidence moved since your last comment (more restarts, a new error, -a new pod), and at most once every few hours otherwise. File nothing new. +a new pod; for a Sentry issue, more events or users, a different stack +trace, or Sentry marking it regressed), and at most once every few hours +otherwise. File nothing new: a second event on the same Sentry issue is a +comment, never a second ticket. ## Returned The problem 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. +links the old one, and escalate it as a new one. A Sentry issue that +regressed after its ticket was Done is the usual case here. `; export const DEPS_ALERTS = `--- diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 61161ee8..327b324f 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -10,6 +10,7 @@ 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 { NO_TOKEN, TOKEN_PAGE, TOKEN_SCOPES, TOKEN_SETTING, type SentryFinding, type SentryLook, type SentryReason } from "./sentry.js"; import { newHumanComments, prGate, reportedItem, unheardWait, type GateState } from "./reconcile.js"; import { conflictsOf, type Conflict } from "./schedule.js"; import type { EntitySnapshot, SessionWake, SnapshotComment } from "./source-contract.js"; @@ -541,6 +542,121 @@ export function formatDepsWake(input: DepsWakeInput): string { return fit(head, snapshot, out); } +export type SentryWakeInput = { + reason: WakeReason; + binding: Binding; + playbook: Playbook; + look: SentryLook; + /** The Linear team tickets are filed in. */ + team: string | null; + label: string; + /** Priorities whose tickets are labelled when filed (ops.autoAdopt). */ + autoAdopt: string[]; + escalations: Escalation[]; + changes: string[]; +}; + +const SENTRY_LIFECYCLE: Partial<Record<WakeReason, string>> = { + adopted: "You have just been made the ops steward for this Sentry project. Read everything below, then act on what the look found.", + reopen: "This project is watched again and its binding has resumed. Re-read everything below as if new.", + nightly: "This is the nightly reconcile pass: check that every issue below is filed, and report.", +}; + +const SENTRY_REASON_TEXT: Record<SentryReason, string> = { + new: "first seen since the last look", + regressed: "regressed in Sentry (it was resolved there and fired again)", + rung: "Sentry rang for it", + ongoing: "known and still firing", +}; + +function sentryFindingLines(f: SentryFinding): string[] { + const lines = [`#### ${f.fingerprint}`, ""]; + const ticket = f.ticket === null ? "" : ` · ticket ${f.ticket}${f.ticketState === null ? "" : ` (${f.ticketState})`}${f.lastCommentedAt === null ? "" : `, your last word on it ${iso(f.lastCommentedAt)}`}`; + lines.push(`- **${f.shortId}** ${f.title}${f.level === null ? "" : ` (${f.level})`}${ticket}`); + if (f.culprit !== null) lines.push(`- Culprit: ${f.culprit}`); + if (f.permalink !== null) lines.push(`- ${f.permalink}`); + lines.push(`- ${f.count} event${f.count === 1 ? "" : "s"}, ${f.userCount} user${f.userCount === 1 ? "" : "s"}; first seen ${f.firstSeen ?? "?"}, last seen ${f.lastSeen ?? "?"}${f.substatus === null ? "" : `; Sentry says ${f.substatus}`}; first seen by this watch ${iso(f.firstSeenAt)}`); + lines.push(`- Why it is here: ${f.reasons.map((r) => SENTRY_REASON_TEXT[r]).join("; ")}`); + if (f.event !== null) { + lines.push(`- Latest event${f.event.id === null ? "" : ` ${f.event.id}`}${f.event.at === null ? "" : ` at ${f.event.at}`}${f.event.message === null ? "" : `: ${f.event.message}`}`); + if (f.event.stack.length > 0) lines.push("- Stack trace, innermost last; `*` marks in-app frames:", "", "```", ...f.event.stack, "```"); + else lines.push("- No stack trace on the latest event."); + } else lines.push("- Latest event: not read this look."); + return [...lines, ""]; +} + +/** A Sentry project binding's wake: instructions, steering, the look, what changed. */ +export function formatSentryWake(input: SentryWakeInput): string { + const { binding, playbook, look } = input; + const out: string[] = []; + out.push(`# Sentry watch: ${look.target}`); + out.push(`Binding ${binding.id} · ops · 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 = SENTRY_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.findings.some((f) => f.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( + "This target is a Sentry project, not a Kubernetes namespace: the plugin reads it with its own Sentry token, which your thread does not hold, so you cannot query Sentry yourself. Diagnose from the evidence below (the stack trace names the code) and the code in your workspace, and link the issue's permalink in the ticket. The fingerprint is the Sentry issue id.", + ); + 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.`); + if (input.autoAdopt.length > 0) { + out.push( + `ops.autoAdopt: a ticket you file at ${input.autoAdopt.join(" or ")} priority 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 look", ""); + if (look.error === NO_TOKEN) { + out.push( + `**The plugin has no Sentry token, so it cannot read this project.** The token is the \`${TOKEN_SETTING}\` setting of the stewards plugin on this bb server (Settings → Plugins → Stewards), entered by the user, never pasted into a thread. ` + + `File one provide-secret need for it with steward_report: variable \`${TOKEN_SETTING}\`, url ${TOKEN_PAGE}, what "Create a Sentry auth token with the scopes ${TOKEN_SCOPES.join(" and ")} and enter it as the stewards plugin's Sentry token setting", and the steps in how. ` + + "Then report with actor me and end the turn; the first look that reads the project wakes you.", + ); + } else if (look.error !== null) out.push(`The project could not be read: ${look.error}. Nothing to do until it can; \`bb stewards check\` says why.`); + else { + out.push(`- ${look.unresolved} unresolved issue${look.unresolved === 1 ? "" : "s"} in the project${look.findings.length === 0 ? "" : `; ${look.findings.length} below`}`); + for (const n of look.notes) out.push(`- ${n}`); + if (look.findings.length === 0) out.push("", "**Nothing new: no issue is new, regressed or rung since the last look.** There is nothing to file or comment on: report that with steward_report (actor other) and end the turn."); + } + for (const c of present) { + out.push("", `### ${CLASS_TITLES[c]}`, ""); + for (const f of look.findings.filter((x) => x.class === c)) out.push(...sentryFindingLines(f)); + } + if (look.recent.length > 0) out.push("", "### Other unresolved issues, most recent first", "", ...look.recent.map((r) => `- ${r}`)); + 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;