From 4aefce561fa4b109da339ad86e7fd677d4f55f02 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Thu, 22 Oct 2026 17:06:28 +0000 Subject: [PATCH] stewards: resolve a Sentry issue when its ticket reaches Done (BB-37) --- plugins/stewards/DESIGN.md | 24 ++++++--- plugins/stewards/README.md | 14 +++-- plugins/stewards/config.test.ts | 14 ++++- plugins/stewards/config.ts | 9 +++- plugins/stewards/sentry.test.ts | 50 ++++++++++++++++- plugins/stewards/sentry.ts | 51 ++++++++++++++++-- plugins/stewards/server.test.ts | 96 ++++++++++++++++++++++++++++++--- plugins/stewards/server.ts | 25 +++++++-- 8 files changed, 256 insertions(+), 27 deletions(-) diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 16deb08e..98a49934 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -933,9 +933,10 @@ 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 + the stewards plugin holds a Sentry *user auth token* with `project:read`, + `event:read` and `event:write`, 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 @@ -992,9 +993,20 @@ what a wake carries. 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. +- **The plugin writes exactly one thing in Sentry.** With + `ops.sentry.resolveOnDone` on (it defaults off, so a project opts in), + the look resolves a mapped issue whose ticket is in a completed state + (Done) while Sentry still shows the issue unresolved, with one + `PUT /api/0/issues//` carrying `{ "status": "resolved" }` and one + quiet note in the look ("Resolved WEB-12 in Sentry: BB-N is Done"). + Canceled tickets (won't fix), open tickets and issues Sentry has already + resolved are left alone; no last-seen or deploy-timing guard is added, + since Sentry's own regression detection reopens the issue if it fires + again, and the existing Returned path handles that. The write needs the + token's `event:write` scope: a 403 is one note per look naming the + missing scope, and the look skips the rest of its resolves and otherwise + completes. Assigning or commenting on a Sentry issue is not in the `may` + list, and the token's scopes are the wall. ## 18. Needs you items and one-click actions diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 281379f0..607dad68 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -316,11 +316,15 @@ when left out) and `autoAdopt` (Linear priorities, `urgent`, `high`, `medium`, ` tickets the ops steward labels for a steward itself when it files them). 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). +`project:read`, `event:read` and `event:write`; `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). With `ops.sentry.resolveOnDone` on (it defaults off), the look +resolves a mapped issue whose ticket is Done while Sentry still shows it +unresolved — the plugin's only Sentry write — and notes it in the look; +`event:write` is the scope that write needs. `ops-watch.md` is read only when `ops.targets` lists a k8s namespace or a Sentry project. diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 1ca0bbab..df0042ed 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -13,7 +13,7 @@ describe("the project file", () => { expect(parsed.value.projectSteward.model).toMatchObject({ providerId: "claude-code", model: "claude-opus-5-5", reasoningLevel: "high" }); expect(parsed.value.reviews.enabled).toBe(true); expect(parsed.value.github.exclude).toEqual([]); - expect(parsed.value.ops).toEqual({ targets: [], autoAdopt: [] }); + expect(parsed.value.ops).toEqual({ targets: [], autoAdopt: [], sentry: { resolveOnDone: false } }); expect(usesKind(parsed.value, "ops")).toBe(false); }); @@ -59,7 +59,7 @@ describe("ops in the project file", () => { it("takes namespace targets, a team and the priorities to adopt at once", () => { const r = file({ targets: [{ kind: "k8s-namespace", name: "bb-gate-production" }, { kind: "k8s-namespace", name: "devbox-production" }], team: "ops", autoAdopt: ["urgent"] }); if (!r.ok) throw new Error(r.error); - expect(r.value.ops).toEqual({ targets: [{ kind: "k8s-namespace", name: "bb-gate-production" }, { kind: "k8s-namespace", name: "devbox-production" }], team: "OPS", autoAdopt: ["urgent"] }); + expect(r.value.ops).toEqual({ targets: [{ kind: "k8s-namespace", name: "bb-gate-production" }, { kind: "k8s-namespace", name: "devbox-production" }], team: "OPS", autoAdopt: ["urgent"], sentry: { resolveOnDone: false } }); expect(usesKind(r.value, "ops")).toBe(true); expect(opsTeam(r.value)).toBe("OPS"); }); @@ -96,6 +96,16 @@ describe("ops in the project file", () => { 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("takes ops.sentry.resolveOnDone, off by default", () => { + const off = file({ targets: [{ kind: "sentry-project", org: "acme", project: "web" }] }); + if (!off.ok) expect.fail(off.error); + expect(off.value.ops.sentry.resolveOnDone).toBe(false); + const on = file({ targets: [{ kind: "sentry-project", org: "acme", project: "web" }], sentry: { resolveOnDone: true } }); + if (!on.ok) expect.fail(on.error); + expect(on.value.ops.sentry.resolveOnDone).toBe(true); + expect(error({ targets: [], sentry: { resolve: true } })).toMatch(/ops\.sentry/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); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index 5e90fd54..cd525d88 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -265,9 +265,16 @@ export const projectFileSchema = z /** The kubeconfig context kubectl uses on the developer's machine; its current context when left out. */ context: z.string().trim().min(1).max(200).regex(/^[^\s-][^\s]*$/u, "a kubeconfig context name").optional(), autoAdopt: z.array(z.enum(LINEAR_PRIORITIES)).max(4).default([]), + /** + * The Sentry write, off by default. On, the Sentry look resolves a + * mapped issue whose ticket is Done and which Sentry still shows as + * unresolved; Sentry's own regression detection reopens it if it fires + * again. The token needs `event:write` for it. + */ + sentry: z.object({ resolveOnDone: z.boolean().default(false) }).strict().default({ resolveOnDone: false }), }) .strict() - .default({ targets: [], autoAdopt: [] }), + .default({ targets: [], autoAdopt: [], sentry: { resolveOnDone: false } }), /** The dependency watch: per-severity SLA, the batch window, and what auto-adopts. */ deps: depsSchema, }) diff --git a/plugins/stewards/sentry.test.ts b/plugins/stewards/sentry.test.ts index e132a255..b94d8c40 100644 --- a/plugins/stewards/sentry.test.ts +++ b/plugins/stewards/sentry.test.ts @@ -1,6 +1,6 @@ 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"; +import { NO_TOKEN, TOKEN_SCOPES, SentryApiError, createSentryReader, eventOf, issueInOrg, issueOf, issuesOf, recentLine, sentryChanges, sentryResolveTargets, 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; @@ -114,6 +114,34 @@ describe("the reader", () => { // 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).authorization).startsWith("Bearer "))).toBe(true); }); + + it("resolves an issue with one PUT and returns a failure rather than throwing", async () => { + const calls: Array<{ url: string; method: string; body: string | null }> = []; + const fetchImpl = vi.fn(async (url: string | URL, init: RequestInit) => { + calls.push({ url: String(url), method: String(init.method), body: typeof init.body === "string" ? init.body : null }); + if ((init.headers as Record).authorization !== "Bearer tok-1") return new Response("", { status: 401 }); + if (String(url).endsWith("/issues/1/")) return new Response("", { status: 403 }); + return Response.json({ id: "6081234567", status: "resolved" }); + }); + const reader = createSentryReader(fetchImpl, { apiUrl: "https://sentry.io/", token: async () => "tok-1" }); + expect(await reader.resolve("6081234567")).toEqual({ ok: true }); + expect(calls.at(-1)).toEqual({ url: "https://sentry.io/api/0/issues/6081234567/", method: "PUT", body: '{"status":"resolved"}' }); + // A 403 is returned, so the look can name the missing event:write scope and carry on. + expect(await reader.resolve("1")).toMatchObject({ ok: false, status: 403 }); + // A network failure is returned too, never thrown; no token means no request at all. + const down = createSentryReader( + vi.fn(async () => { + throw new Error("socket hang up"); + }), + { apiUrl: "https://sentry.io", token: async () => "tok-1" }, + ); + expect(await down.resolve("1")).toEqual({ ok: false, status: 0, error: "socket hang up" }); + const noRequest = vi.fn(); + const without = createSentryReader(noRequest as unknown as typeof fetch, { apiUrl: "https://sentry.io", token: async () => null }); + expect(await without.resolve("1")).toEqual({ ok: false, status: 0, error: NO_TOKEN }); + expect(noRequest).not.toHaveBeenCalled(); + expect(TOKEN_SCOPES).toContain("event:write"); + }); }); describe("sightings", () => { @@ -149,6 +177,26 @@ describe("sightings", () => { }); }); +describe("what the look resolves in Sentry", () => { + const row = (fingerprint: string, ticketKey: string | null) => ({ fingerprint, ticketKey, firstSeenAt: 1, lastCommentedAt: null }); + const ticket = (stateType: string | null) => ({ state: "Done", stateType }); + + it("is the rows whose ticket is completed and whose issue Sentry still shows unresolved", () => { + const rows = [row("1", "ENG-1"), row("2", "ENG-2"), row("3", "ENG-3"), row("4", null), row("5", "ENG-5"), row("6", "ENG-6")]; + const tickets = new Map | null>([ + ["ENG-1", ticket("completed")], + ["ENG-2", ticket("canceled")], + ["ENG-3", ticket("started")], + ["ENG-5", ticket("completed")], + ["ENG-6", null], + ]); + expect(sentryResolveTargets(rows, tickets, new Set(["1", "2", "3", "5"])).map((t) => t.fingerprint)).toEqual(["1", "5"]); + // Canceled (won't fix) is not completed; an already-resolved issue is not in the unresolved set. + expect(sentryResolveTargets([row("2", "ENG-2")], tickets, new Set(["2"]))).toEqual([]); + expect(sentryResolveTargets([row("1", "ENG-1")], tickets, new Set())).toEqual([]); + }); +}); + describe("what changed between two looks", () => { const finding = (over: Partial = {}): SentryFinding => ({ fingerprint: "6081234567", diff --git a/plugins/stewards/sentry.ts b/plugins/stewards/sentry.ts index 8973990f..b0250f02 100644 --- a/plugins/stewards/sentry.ts +++ b/plugins/stewards/sentry.ts @@ -12,7 +12,7 @@ // (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 { redactLine, type FingerprintRow, type OpsTarget, type SentryTarget, type TicketState } from "./ops.js"; import type { Change } from "./reconcile.js"; export const SENTRY_API_URL = "https://sentry.io"; @@ -22,8 +22,8 @@ export const NO_TOKEN = "no Sentry token is configured"; 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; +/** The scopes the token needs: read the project (admission, the list), its events (stack traces), and write one thing (resolve a Done ticket's issue). */ +export const TOKEN_SCOPES = ["project:read", "event:read", "event:write"] as const; /** Unresolved issues read per look, newest activity first. */ export const ISSUES_PER_LOOK = 50; @@ -155,6 +155,9 @@ export class SentryApiError extends Error { } } +/** What a Sentry write answered: done, or the status and message when it did not. Never thrown. */ +export type SentryResolveResult = { ok: true } | { ok: false; status: number; error: string }; + export interface SentryReader { /** The project's unresolved issues, most recent activity first. Throws when the project cannot be read. */ issues(target: SentryTarget): Promise; @@ -162,6 +165,8 @@ export interface SentryReader { issue(id: string): Promise; /** The latest event of an issue; null when there is none to read. */ latestEvent(id: string): Promise; + /** The one write: resolve an issue. A failure is returned, never thrown, so a look reports it and carries on. */ + resolve(id: string): Promise; /** 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 }>; } @@ -205,6 +210,24 @@ export function createSentryReader(fetchImpl: FetchLike, opts: { apiUrl: string; throw error; } }, + async resolve(id) { + const token = (await opts.token())?.trim() ?? ""; + if (token === "") return { ok: false, status: 0, error: NO_TOKEN }; + const path = `/api/0/issues/${encodeURIComponent(id)}/`; + let response: Response; + try { + response = await fetchImpl(`${base}${path}`, { + method: "PUT", + headers: { authorization: `Bearer ${token}`, accept: "application/json", "content-type": "application/json" }, + body: JSON.stringify({ status: "resolved" }), + signal: AbortSignal.timeout(opts.timeoutMs ?? 20_000), + }); + } catch (error) { + return { ok: false, status: 0, error: error instanceof Error ? error.message : String(error) }; + } + if (response.ok) return { ok: true }; + return { ok: false, status: response.status, error: response.status === 403 ? `Sentry refused the write (403) to PUT ${path}` : `Sentry answered HTTP ${response.status} to PUT ${path}` }; + }, async access(target) { try { const project = obj(await get(projectPath(target))); @@ -277,6 +300,28 @@ export const recentLine = (issue: SentryIssue): string => `${issue.shortId} · $ // ---- the look ------------------------------------------------------------------------------ +/** + * The fingerprint rows the look resolves in Sentry: its ticket is in a + * completed state (Done), and the issue Sentry still shows as unresolved. + * A canceled ticket (won't fix), an open ticket, a ticket whose state could + * not be read, and an issue Sentry has already resolved are all left alone. + * `unresolved` is the set of issue ids the look read as unresolved. + */ +export function sentryResolveTargets( + rows: Iterable, + tickets: ReadonlyMap, + unresolved: ReadonlySet, +): { fingerprint: string; ticket: string; state: string }[] { + const out: { fingerprint: string; ticket: string; state: string }[] = []; + for (const row of rows) { + if (row.ticketKey === null || !unresolved.has(row.fingerprint)) continue; + const state = tickets.get(row.ticketKey) ?? null; + if (state === null || state.stateType !== "completed") continue; + out.push({ fingerprint: row.fingerprint, ticket: row.ticketKey, state: state.state }); + } + return out; +} + export const sentryFindingSchema = z.object({ /** The Sentry issue id. */ fingerprint: z.string(), diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 6ef49279..e80156f9 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -4152,7 +4152,10 @@ describe("Sentry stewards", () => { function fakeSentry() { const issues = new Map>(); const calls: string[] = []; + /** The one write: each PUT, with the body it carried. */ + const writes: Array<{ path: string; body: string | null }> = []; let status = 200; + let putStatus = 200; const fetchImpl = (async (url: string | URL, init?: RequestInit) => { const u = new URL(String(url)); calls.push(u.pathname); @@ -4162,18 +4165,29 @@ describe("Sentry stewards", () => { // 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 (issue !== null) { + if (init?.method === "PUT") { + writes.push({ path: u.pathname, body: typeof init.body === "string" ? init.body : null }); + if (putStatus !== 200) return new Response("", { status: putStatus }); + return Response.json({ ...(issues.get(issue[1]!) ?? { id: issue[1] }), status: "resolved" }); + } + 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) }; + return { issues, calls, writes, fetchImpl, setStatus: (s: number) => (status = s), setPutStatus: (s: number) => (putStatus = s) }; } - async function watching(options: { token?: string; issues?: Array>; env?: Record } = {}) { + async function watching(options: { token?: string; issues?: Array>; env?: Record; resolveOnDone?: boolean } = {}) { 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[PROJECT_FILE] = JSON.stringify({ + version: 1, + linear: { teams: ["ENG"] }, + ops: { targets: [{ kind: "sentry-project", org: "acme", project: "web" }], autoAdopt: ["urgent"], ...(options.resolveOnDone === undefined ? {} : { sentry: { resolveOnDone: options.resolveOnDone } }) }, + }); t.files[playbookPath("ops-watch")] = OPS_WATCH; await t.hooks.sweep(); await t.flush(); @@ -4306,13 +4320,83 @@ describe("Sentry stewards", () => { expect(wakes()).toHaveLength(before + 1); }); + it("resolves a mapped issue in Sentry when its ticket is Done and the switch is on", async () => { + const { t, sentry, wakes, doorbell, report } = await watching({ resolveOnDone: true }); + 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: "Done", stateType: "completed" })); + // The issue is still unresolved and firing; the look resolves it and notes that it did. + 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(sentry.writes).toEqual([{ path: `/api/0/issues/${ISSUE_ID}/`, body: '{"status":"resolved"}' }]); + expect(wakes().at(-1)).toMatch(/Resolved WEB-12 in Sentry: ENG-50 is Done/u); + }); + + it("makes no Sentry write when ops.sentry.resolveOnDone is off (the default)", async () => { + const { t, sentry, 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: "Done", stateType: "completed" })); + 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(sentry.writes).toEqual([]); + }); + + it("leaves a Canceled ticket's issue, an open ticket's and one Sentry already resolved untouched", async () => { + const { t, sentry, doorbell, report } = await watching({ + resolveOnDone: true, + issues: [ + sentryIssue(), + sentryIssue({ id: "2", shortId: "WEB-13", title: "Boom", permalink: "https://acme.sentry.io/issues/2/", count: "5" }), + sentryIssue({ id: "3", shortId: "WEB-14", title: "Timeout", permalink: "https://acme.sentry.io/issues/3/", count: "2" }), + ], + }); + for (const [fingerprint, ticket] of [[ISSUE_ID, "ENG-50"], ["2", "ENG-51"], ["3", "ENG-52"]] as const) { + expect((await report([{ fingerprint, ticket, did: "filed" }])).error).toBe(false); + } + t.entities.set("ENG-50", issue({ id: "ENG-50", key: "ENG-50", state: "Canceled", stateType: "canceled" })); + t.entities.set("ENG-51", issue({ id: "ENG-51", key: "ENG-51", state: "In Progress", stateType: "started" })); + t.entities.set("ENG-52", issue({ id: "ENG-52", key: "ENG-52", state: "Done", stateType: "completed" })); + t.advance(60_000); + sentry.issues.set(ISSUE_ID, sentryIssue({ count: "18", lastSeen: "2026-10-14T15:02:00Z", substatus: "ongoing" })); + sentry.issues.set("2", sentryIssue({ id: "2", shortId: "WEB-13", title: "Boom", permalink: "https://acme.sentry.io/issues/2/", count: "6", lastSeen: "2026-10-14T15:02:00Z", substatus: "ongoing" })); + // Sentry resolved the third one itself before its ticket reached Done. + sentry.issues.set("3", sentryIssue({ id: "3", shortId: "WEB-14", title: "Timeout", permalink: "https://acme.sentry.io/issues/3/", status: "resolved" })); + await doorbell(ISSUE_ID); + await doorbell("2"); + await doorbell("3"); + expect(sentry.writes).toEqual([]); + }); + + it("gives one note naming event:write when a resolve is refused, and skips the rest of the look's resolves", async () => { + const { t, sentry, wakes, doorbell, report } = await watching({ + resolveOnDone: true, + issues: [sentryIssue(), sentryIssue({ id: "2", shortId: "WEB-13", title: "Boom", permalink: "https://acme.sentry.io/issues/2/", count: "5" })], + }); + for (const [fingerprint, ticket] of [[ISSUE_ID, "ENG-50"], ["2", "ENG-51"]] as const) { + expect((await report([{ fingerprint, ticket, did: "filed" }])).error).toBe(false); + } + t.entities.set("ENG-50", issue({ id: "ENG-50", key: "ENG-50", state: "Done", stateType: "completed" })); + t.entities.set("ENG-51", issue({ id: "ENG-51", key: "ENG-51", state: "Done", stateType: "completed" })); + t.advance(60_000); + sentry.issues.set(ISSUE_ID, sentryIssue({ count: "18", lastSeen: "2026-10-14T15:02:00Z", substatus: "ongoing" })); + sentry.issues.set("2", sentryIssue({ id: "2", shortId: "WEB-13", title: "Boom", permalink: "https://acme.sentry.io/issues/2/", count: "6", lastSeen: "2026-10-14T15:02:00Z", substatus: "ongoing" })); + sentry.setPutStatus(403); + await doorbell(ISSUE_ID); + expect(sentry.writes).toHaveLength(1); + const wake = wakes().at(-1)!; + expect(wake).toMatch(/the token is missing the event:write scope/u); + // The look otherwise completes: both Done issues are still in it. + expect(wake).toContain("#### 2"); + }); + 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 `SENTRY_TOKEN`, setting `sentryToken`, url https:\/\/sentry\.io\/settings\/account\/api\/auth-tokens\//u); - expect(first).toMatch(/project:read and event:read/u); + expect(first).toMatch(/project:read and event:read and event:write/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(); @@ -4321,7 +4405,7 @@ describe("Sentry stewards", () => { 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).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 and event:write)"); 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" }]); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 6576d554..327fbe5f 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -53,7 +53,7 @@ import { KUBECTL_VERBS, createKubectlReader, kubectlRefusal, type KubectlResult, 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 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 { EVENTS_PER_LOOK, NO_TOKEN, RECENT_PER_LOOK, SENTRY_API_URL, TOKEN_SCOPES, createSentryReader, emptySentryLook, issueInOrg, recentLine, sentryChanges, sentryResolveTargets, sentrySightings, sentrySummary, type SentryFinding, type SentryLook, type SentryReader } from "./sentry.js"; import { advanced, answerDiffers, anyWorkerInFlight, approvalWanted, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, lifecycle, namesUserAsBlocker, newHumanComments, newestCommentAt, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, @@ -1823,7 +1823,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); /** 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 { + async function lookAtSentry(b: Binding, target: SentryTarget, playbook: Playbook, resolveOnDone: boolean): Promise { const at = now(); const key = opsTargetKey(target); const since = b.sentryLook !== null && b.sentryLook.error === null ? b.sentryLook.at : at - playbook.requeueDefaultMs; @@ -1853,6 +1853,25 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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)); + // The one write: with ops.sentry.resolveOnDone on, a mapped ticket + // that is Done while its issue is still unresolved is resolved in + // Sentry. Canceled and open tickets, and issues Sentry has already + // resolved, are left alone. A 403 (the token lacks event:write) is + // one note per look, and the rest of the look's resolves are skipped. + const unresolvedById = new Map(issues.filter((i) => i.status === "unresolved").map((i) => [i.id, i])); + if (resolveOnDone) { + let refused = false; + for (const t of sentryResolveTargets(rows.values(), tickets, new Set(unresolvedById.keys()))) { + if (refused) break; + const issue = unresolvedById.get(t.fingerprint)!; + const resolved = await reader.resolve(t.fingerprint); + if (resolved.ok) notes.push(`Resolved ${issue.shortId} in Sentry: ${t.ticket} is ${t.state}`); + else if (resolved.status === 403) { + notes.push(`Sentry refused to resolve ${issue.shortId} (403): the token is missing the event:write scope, so the rest of this look's resolves were skipped`); + refused = true; + } else notes.push(`Could not resolve ${issue.shortId} in Sentry (${resolved.error})`); + } + } 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[] = []; @@ -1907,7 +1926,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P */ async function reconcileSentry(b: Binding, config: ProjectConfig, playbook: Playbook, target: SentryTarget, force: WakeReason | null): Promise { const before = b.sentryLook; - const look = await lookAtSentry(b, target, playbook); + const look = await lookAtSentry(b, target, playbook, config.file.ops.sentry.resolveOnDone); 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 });