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
35 changes: 34 additions & 1 deletion plugins/stewards/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
playbookLabels,
playbookNameFor,
playbookStates,
roleBacklogTargets,
sentryTargets,
ticketWatchId,
ticketWatchProblems,
Expand All @@ -42,6 +43,7 @@ import {
usesKind,
watchProblems,
} from "./roles.js";
import { opsTargetKey, parseOpsTargetKey } from "./ops.js";
import { DEPS_ALERTS, DEPS_PRS, GITHUB_ISSUES, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, projectFileTemplate } from "./templates.js";

describe("the project file", () => {
Expand Down Expand Up @@ -106,6 +108,34 @@ describe("the project file", () => {
else expect.fail("a URL is not owner/repo");
});

it("parses the optional backlog block with its defaults, and refuses unknown keys, non-positive numbers and a bad team (BB-334)", () => {
const absent = parseProjectFile(JSON.stringify({ version: 1 }));
if (!absent.ok) throw new Error(absent.error);
expect(absent.value.backlog).toBeUndefined();

const explicit = parseProjectFile(JSON.stringify({ version: 1, backlog: { team: " bb ", wipLimit: 3, staleDays: 21, commentsPerWeek: 2 } }));
if (!explicit.ok) throw new Error(explicit.error);
expect(explicit.value.backlog).toEqual({ team: "BB", wipLimit: 3, staleDays: 21, commentsPerWeek: 2 });

const defaults = parseProjectFile(JSON.stringify({ version: 1, backlog: {} }));
if (!defaults.ok) throw new Error(defaults.error);
expect(defaults.value.backlog).toEqual({ wipLimit: 5, staleDays: 14, commentsPerWeek: 1 });

expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { bogus: true } }))).toMatchObject({ ok: false });
expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { wipLimit: 0 } }))).toMatchObject({ ok: false });
expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { staleDays: -1 } }))).toMatchObject({ ok: false });
expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { commentsPerWeek: 0 } }))).toMatchObject({ ok: false });
expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { team: "bad key" } }))).toMatchObject({ ok: false });
});

it("reads a role's backlog team as a target, and round-trips its key (BB-334)", () => {
expect(roleBacklogTargets({ ops: { backlog: { team: "BB" } } })).toEqual([{ kind: "backlog", team: "BB" }]);
expect(roleBacklogTargets({ ops: {} })).toEqual([]);
expect(roleBacklogTargets(null)).toEqual([]);
expect(opsTargetKey({ kind: "backlog", team: "BB" })).toBe("backlog/BB");
expect(parseOpsTargetKey("backlog/BB")).toEqual({ kind: "backlog", team: "BB" });
});

it("fills the dependency watch's SLA, batch and autoAdopt defaults, and takes explicit values", () => {
const defaults = parseProjectFile(JSON.stringify({ version: 1 }));
if (!defaults.ok) throw new Error(defaults.error);
Expand Down Expand Up @@ -574,7 +604,10 @@ 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, sentry, alertmanager or github/u) });
// BB-334: an ops playbook may read linear too (the backlog binding); an
// unknown source is still refused.
expect(parsePlaybook(OPS_WATCH.replace("source: k8s", "source: linear"), "ops-watch")).toMatchObject({ ok: true });
expect(parsePlaybook(OPS_WATCH.replace("source: k8s", "source: bogus"), "ops-watch")).toMatchObject({ ok: false, error: expect.stringMatching(/source: Invalid option/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
49 changes: 38 additions & 11 deletions plugins/stewards/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { createHash } from "node:crypto";
import { parse as parseYaml } from "yaml";
import { z } from "zod";
import { decideEntrySchema, defaultDecideList, globError } from "./decisions.js";
import { ALERTMANAGER_NAMESPACE, SENTRY_SLUG, type AlertmanagerTarget, type DependabotTarget, type K8sTarget, type OpsTarget, type SentryTarget } from "./ops.js";
import { ALERTMANAGER_NAMESPACE, SENTRY_SLUG, type AlertmanagerTarget, type BacklogTarget, type DependabotTarget, type K8sTarget, type OpsTarget, type SentryTarget } from "./ops.js";
import { DEPENDABOT_SEVERITIES, REPO_NAME } from "./source-contract.js";

export const STEWARDS_DIR = "stewards";
Expand Down Expand Up @@ -330,6 +330,26 @@ export type TicketWatch = z.infer<typeof ticketWatchSchema>;
*/
export const ticketWatchId = (watch: Pick<TicketWatch, "playbook">): string => `${watch.playbook}@ticket`;

/**
* The backlog steward's block (BB-334): the Linear team whose whole open
* backlog is reported, and the limits the report uses. `team` is optional;
* the role's `backlog.team` decides which binding exists, and a `team` here
* that names a different team is one `check` problem, never a silent pick.
* Every number is a positive integer; the defaults are the design's.
*/
export const backlogSchema = z
.object({
team: teamKey.optional(),
/** Stage 3's Todo + In Progress ceiling. */
wipLimit: z.number().int().positive().max(1000).default(5),
/** A ticket untouched for this long is stale. */
staleDays: z.number().int().positive().max(3650).default(14),
/** Stage 2's comment budget: at most this many comments per ticket per week. */
commentsPerWeek: z.number().int().positive().max(7).default(1),
})
.strict();
export type BacklogConfig = z.infer<typeof backlogSchema>;

export const projectFileSchema = z
.object({
version: z.literal(1),
Expand Down Expand Up @@ -434,6 +454,8 @@ export const projectFileSchema = z
.default({ targets: [], autoAdopt: [], sentry: { resolveOnDone: false } }),
/** The dependency watch: per-severity SLA, the batch window, and what auto-adopts. */
deps: depsSchema,
/** The backlog steward's block (BB-334); absent, the feature is off exactly as before. */
backlog: backlogSchema.optional(),
/** The mechanical lesson lifecycle's thresholds and caps (BB-35 step 3). */
lessons: lessonRulesSchema,
/**
Expand Down Expand Up @@ -488,6 +510,14 @@ export const playbookNameFor = (project: ProjectFile, kind: BindingKind): string

export const opsTargets = (project: ProjectFile): OpsTarget[] => project.ops.targets;

/**
* The backlog targets a server's role watches (BB-334): one per declared
* `backlog.team`. It reads the role's parsed shape; roles.ts itself is not
* changed, and the role's team is what decides which binding exists.
*/
export const roleBacklogTargets = (role: { ops?: { backlog?: { team: string } } } | null | undefined): BacklogTarget[] =>
role?.ops?.backlog === undefined ? [] : [{ kind: "backlog", team: role.ops.backlog.team }];

/** 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");

Expand Down Expand Up @@ -739,7 +769,7 @@ export const deploymentsFieldSchema = z
});

export const PLAYBOOK_SOURCES = ["linear", "github", "k8s", "sentry", "alertmanager"] as const;
const SOURCES_OF: Record<BindingKind, readonly (typeof PLAYBOOK_SOURCES)[number][]> = { ticket: ["linear", "github"], pr: ["github"], review: ["github"], ops: ["k8s", "github", "sentry", "alertmanager"] };
const SOURCES_OF: Record<BindingKind, readonly (typeof PLAYBOOK_SOURCES)[number][]> = { ticket: ["linear", "github"], pr: ["github"], review: ["github"], ops: ["k8s", "github", "sentry", "alertmanager", "linear"] };

export const frontMatterSchema = z
.object({
Expand Down Expand Up @@ -847,16 +877,13 @@ export function parsePlaybook(text: string, expectedName: string): Parsed<Playbo
if (!parsed.success) return { ok: false, error: `${file}: ${zodMessage(parsed.error)}` };
const fm = parsed.data;
if (fm.name !== expectedName) return { ok: false, error: `${file} names itself ${JSON.stringify(fm.name)}; the file name says ${JSON.stringify(expectedName)}` };
// An ops binding watches a target, not an entity in a source plugin: a
// Kubernetes namespace reads k8s, a Dependabot alert target reads github, a
// Sentry project reads sentry, an Alertmanager namespace reads alertmanager,
// and a backlog binding (BB-334) reads linear. The playbook says which so
// its sections can be about the right thing; any listed source is valid.
const expectedSources = SOURCES_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, a Dependabot alert target reads
// github, a Sentry project reads sentry, and an Alertmanager namespace
// reads alertmanager. The playbook says which so its sections can be
// about the right thing; any is valid, and the ops-watch playbook serves
// k8s, Sentry and Alertmanager targets alike.
if (fm.source === "linear") return { ok: false, error: `${file}: an ops playbook watches k8s, sentry, alertmanager or github, not ${fm.source}` };
} else if (!expectedSources.includes(fm.source)) {
if (!expectedSources.includes(fm.source)) {
return { ok: false, error: `${file}: a ${fm.kind} playbook reads ${expectedSources.join(" or ")}, not ${fm.source}` };
}
if (fm.kind === "ops") {
Expand Down
3 changes: 2 additions & 1 deletion plugins/stewards/migrations.snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,6 @@
"dac7694ca870936e15df9f4c6837973e8d1191b271743b386b1db36427577937",
"8a61e3594b695ff3b5f2f58573155bd59f7209142643e4f212fe3485a4ae80f9",
"c7dcc1c8ee819162947a9965a7fb0cb7129900a4d68f5f7f91a99184a225dea9",
"ad2a7b244faee5792ca77b1f36cd80488de8f787360d03f1569e60c869845beb"
"ad2a7b244faee5792ca77b1f36cd80488de8f787360d03f1569e60c869845beb",
"b268ed66797e2953f8b175fa1cdf506531a2fc5e30c52ef43480d81b9efb7c1b"
]
41 changes: 38 additions & 3 deletions plugins/stewards/ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// container, and an error signature built from the container's status, never
// from log text, which changes on every line.
import { z } from "zod";
import { backlogIssueSchema } from "./source-contract.js";
import type { Change } from "./reconcile.js";

export type K8sTarget = { kind: "k8s-namespace"; name: string };
Expand All @@ -17,11 +18,21 @@ export type DependabotTarget = { kind: "dependabot"; repo: string };
export type SentryTarget = { kind: "sentry-project"; org: string; project: string };
/** A Kubernetes namespace watched for Prometheus Alertmanager alerts, read with no token through the plugin's Alertmanager URL (alertmanager.ts). */
export type AlertmanagerTarget = { kind: "alertmanager"; namespace: string };
export type OpsTarget = K8sTarget | DependabotTarget | SentryTarget | AlertmanagerTarget;
/** A Linear team's whole open backlog, read through `sourceBacklog` (BB-334); read-only. */
export type BacklogTarget = { kind: "backlog"; team: string };
export type OpsTarget = K8sTarget | DependabotTarget | SentryTarget | AlertmanagerTarget | BacklogTarget;

/** The binding's entity id and key for a target: "k8s-namespace/bb-gate-production", "dependabot/acme/web", "sentry-project/acme/web" or "alertmanager/bb-gate-production". */
/** The binding's entity id and key for a target: "k8s-namespace/bb-gate-production", "dependabot/acme/web", "sentry-project/acme/web", "alertmanager/bb-gate-production" or "backlog/BB". */
export const opsTargetKey = (t: OpsTarget): string =>
t.kind === "k8s-namespace" ? `${t.kind}/${t.name}` : t.kind === "alertmanager" ? `${t.kind}/${t.namespace}` : t.kind === "dependabot" ? `${t.kind}/${t.repo}` : `${t.kind}/${t.org}/${t.project}`;
t.kind === "k8s-namespace"
? `${t.kind}/${t.name}`
: t.kind === "alertmanager"
? `${t.kind}/${t.namespace}`
: t.kind === "dependabot"
? `${t.kind}/${t.repo}`
: t.kind === "backlog"
? `${t.kind}/${t.team}`
: `${t.kind}/${t.org}/${t.project}`;

/** A Kubernetes namespace name, as the Alertmanager target's id: an RFC 1123 label. */
export const ALERTMANAGER_NAMESPACE = /^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$/u;
Expand All @@ -36,6 +47,8 @@ export function parseOpsTargetKey(key: string): OpsTarget | null {
if (dep !== null) return { kind: "dependabot", repo: dep[2]! };
const alertmanager = /^(alertmanager)\/([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)$/u.exec(key);
if (alertmanager !== null) return { kind: "alertmanager", namespace: alertmanager[2]! };
const backlog = /^(backlog)\/([A-Za-z][A-Za-z0-9]*)$/u.exec(key);
if (backlog !== null) return { kind: "backlog", team: backlog[2]!.toUpperCase() };
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]! };
}
Expand Down Expand Up @@ -329,6 +342,28 @@ export type OpsLook = z.infer<typeof opsLookSchema>;
/** What a reader returns for one target, before the fingerprint map. */
export type RawLook = Omit<OpsLook, "at" | "target" | "error" | "findings"> & { sightings: Sighting[] };

/**
* One read of a Linear team's whole open backlog (BB-334), stored on the
* binding so the digest can report it without a second read. `error` is set
* when the read failed, the capability is unsupported, or the source reported
* errors; an empty `issues` with a null `error` is a genuinely empty backlog,
* never a failure. Nothing here writes to Linear.
*/
export const backlogLookSchema = z.object({
at: z.number(),
target: z.string(),
/** The team key read, as the binding names it. */
team: z.string(),
/** Set when the read failed, was unsupported, or reported errors; the issues are then empty. */
error: z.string().nullable(),
issues: z.array(backlogIssueSchema),
/** Set when the source does not offer `sourceBacklog` at all. */
unsupported: z.boolean().default(false),
/** True when the source's hard cap cut the list short. */
truncated: z.boolean().default(false),
});
export type BacklogLook = z.infer<typeof backlogLookSchema>;

/** A fingerprint map row, as classification needs it. */
export type FingerprintRow = { fingerprint: string; ticketKey: string | null; firstSeenAt: number; lastCommentedAt: number | null; filedByThread?: string | null };

Expand Down
Loading
Loading