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
98 changes: 89 additions & 9 deletions plugins/stewards/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>`, with the source `ops`: there is no source plugin
behind it, and `source-contract.ts` does not change. It has no phases
`k8s-namespace/<name>` or `sentry-project/<org>/<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.
Expand Down Expand Up @@ -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: <title> (<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,
Expand Down Expand Up @@ -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).
Expand Down
14 changes: 11 additions & 3 deletions plugins/stewards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
16 changes: 14 additions & 2 deletions plugins/stewards/config.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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, "");
Expand Down
26 changes: 18 additions & 8 deletions plugins/stewards/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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]);
Expand Down Expand Up @@ -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);
});
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}` };
}
Expand Down
Loading
Loading