Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions plugins/stewards/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/<id>/` 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

Expand Down
14 changes: 9 additions & 5 deletions plugins/stewards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
14 changes: 12 additions & 2 deletions plugins/stewards/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down Expand Up @@ -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");
});
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 8 additions & 1 deletion plugins/stewards/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
Expand Down
50 changes: 49 additions & 1 deletion plugins/stewards/sentry.test.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<string, string>).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<string, string>).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", () => {
Expand Down Expand Up @@ -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<string, ReturnType<typeof ticket> | 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> = {}): SentryFinding => ({
fingerprint: "6081234567",
Expand Down
51 changes: 48 additions & 3 deletions plugins/stewards/sentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;
Expand Down Expand Up @@ -155,13 +155,18 @@ 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<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>;
/** The one write: resolve an issue. A failure is returned, never thrown, so a look reports it and carries on. */
resolve(id: string): Promise<SentryResolveResult>;
/** 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 }>;
}
Expand Down Expand Up @@ -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)));
Expand Down Expand Up @@ -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<FingerprintRow>,
tickets: ReadonlyMap<string, TicketState>,
unresolved: ReadonlySet<string>,
): { 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(),
Expand Down
Loading
Loading