diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 49e0e136..2398365c 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -1,8 +1,10 @@ import { describe, expect, it } from "vitest"; import { + DEFAULT_LOCAL_PREFIX, DEFAULT_WAIT_BUDGETS, DEPENDENCY_BOTS, depsTargets, + filingTargetOf, githubStateLabels, isTerminal, k8sTargets, @@ -328,6 +330,61 @@ describe("ops in the project file", () => { }); }); +describe("the local filing target (BB-367)", () => { + const file = (over: Record) => parseProjectFile(JSON.stringify({ version: 1, ...over })); + + it("resolves a target by its shape and the project's local prefix", () => { + // The regression: a Linear team key and a GitHub repo resolve as before. + expect(filingTargetOf("ENG")).toEqual({ target: "ENG", source: "linear" }); + expect(filingTargetOf("acme/web")).toEqual({ target: "acme/web", source: "github" }); + // The local prefix, matched case-insensitively; the default is LOCAL. + expect(DEFAULT_LOCAL_PREFIX).toBe("LOCAL"); + expect(filingTargetOf("LOCAL")).toEqual({ target: "LOCAL", source: "local" }); + expect(filingTargetOf("local")).toEqual({ target: "local", source: "local" }); + expect(filingTargetOf("TICKET", "TICKET")).toEqual({ target: "TICKET", source: "local" }); + // A team key that is not the prefix is still Linear. + expect(filingTargetOf("LOCAL", "TICKET")).toEqual({ target: "LOCAL", source: "linear" }); + }); + + it("accepts the local prefix as ops.team with no linear.teams, and still checks a non-local key", () => { + const local = file({ linear: { teams: [] }, ops: { targets: [{ kind: "k8s-namespace", name: "prod" }], team: "LOCAL" } }); + if (!local.ok) throw new Error(local.error); + expect(local.value.ops.team).toBe("LOCAL"); + expect(opsTeam(local.value)).toEqual({ target: "LOCAL", source: "local" }); + // A custom prefix is accepted, and `opsTeam` reads it. + const custom = file({ linear: { teams: [] }, localPrefix: "ticket", ops: { targets: [{ kind: "k8s-namespace", name: "prod" }], team: "TICKET" } }); + if (!custom.ok) throw new Error(custom.error); + expect(opsTeam(custom.value)).toEqual({ target: "TICKET", source: "local" }); + // A non-local key still must be in linear.teams. + expect(file({ linear: { teams: ["ENG"] }, ops: { targets: [{ kind: "k8s-namespace", name: "prod" }], team: "SALES" } })).toMatchObject({ ok: false }); + // With no linear.teams and no ops.team, the "needs a filing target" error stands. + expect(file({ linear: { teams: [] }, ops: { targets: [{ kind: "k8s-namespace", name: "prod" }] } })).toMatchObject({ ok: false }); + }); + + it("accepts the local prefix for a project and a role, and still checks a non-local role key", () => { + const project = file({ linear: { teams: [] }, ops: { targets: [{ kind: "k8s-namespace", name: "prod" }], team: "LOCAL" } }); + if (!project.ok) throw new Error(project.error); + const roleLocal = parseRolesFile(JSON.stringify({ version: 2, roles: { ops: { team: "LOCAL" } }, holders: { jane: ["ops"] } })); + if (!roleLocal.ok) throw new Error(roleLocal.error); + expect(roleOpsTeam(roleLocal.value.roles["jane"]!, project.value)).toEqual({ target: "LOCAL", source: "local" }); + expect(filingTargetProblems(project.value, roleLocal.value, [])).toEqual([]); + const roleLinear = parseRolesFile(JSON.stringify({ version: 2, roles: { ops: { team: "OPS" } }, holders: { jane: ["ops"] } })); + if (!roleLinear.ok) throw new Error(roleLinear.error); + expect(filingTargetProblems(project.value, roleLinear.value, [])).toEqual([expect.stringMatching(/roles\.json jane's ops\.team: OPS is not one of linear\.teams/u)]); + }); + + it("keeps a Linear team key and a GitHub repo resolving as before", () => { + const linear = file({ linear: { teams: ["ENG"] }, ops: { targets: [{ kind: "k8s-namespace", name: "prod" }], team: "ENG" } }); + if (!linear.ok) throw new Error(linear.error); + expect(opsTeam(linear.value)).toEqual({ target: "ENG", source: "linear" }); + const github = file({ linear: { teams: [] }, ops: { targets: [{ kind: "k8s-namespace", name: "prod" }], team: "acme/web" } }); + if (!github.ok) throw new Error(github.error); + expect(opsTeam(github.value)).toEqual({ target: "acme/web", source: "github" }); + expect(filingTargetProblems(github.value, null, ["acme/web"])).toEqual([]); + expect(filingTargetProblems(github.value, null, ["acme/other"])).toEqual([expect.stringMatching(/ops\.team: acme\/web is not in repos\.json/u)]); + }); +}); + describe("playbooks", () => { it("parses the four defaults", () => { for (const [name, text] of [["linear-tickets", LINEAR_TICKETS], ["github-prs", GITHUB_PRS], ["github-reviews", GITHUB_REVIEWS], ["ops-watch", OPS_WATCH]] as const) { diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index f722008a..fa9d3201 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -209,12 +209,14 @@ export function validTimezone(tz: string): boolean { export const teamKey = z.string().trim().regex(/^[A-Za-z][A-Za-z0-9]*$/u, "a team key such as ENG").transform((s) => s.toUpperCase()); /** - * A filing target (BB-235): where an ops or dependency watch files its - * tickets, either a Linear team key or a GitHub `owner/repo`. A repo is kept - * as GitHub spells it; a team key is folded to upper case. The source is read - * from the shape; membership in `linear.teams` (checked here) or in the repo - * set (`filingTargetProblems`, where the repo set is known) is a separate - * question. This is what `ops.team` and a role's `ops.team` accept. + * A filing target (BB-235, BB-367): where an ops or dependency watch files + * its tickets — a Linear team key, a GitHub `owner/repo`, or the project's + * local prefix. A repo is kept as GitHub spells it; a team key is folded to + * upper case. The source is read from the shape and the project's + * `localPrefix`; membership in `linear.teams` (checked here, except for the + * local prefix) or in the repo set (`filingTargetProblems`, where the repo + * set is known) is a separate question. This is what `ops.team` and a role's + * `ops.team` accept. */ export const filingTargetSchema = z .string() @@ -228,12 +230,16 @@ export const filingTargetSchema = z return z.NEVER; }); -/** Where a filing target lives: a Linear team or a GitHub repo. */ -export type FilingTargetSource = "linear" | "github"; +/** Where a filing target lives: a Linear team, a GitHub repo, or this project's local source. */ +export type FilingTargetSource = "linear" | "github" | "local"; export type FilingTarget = { target: string; source: FilingTargetSource }; -/** The source of a filing target from its shape: a repo has a slash, a team key does not. */ -export const filingTargetOf = (target: string): FilingTarget => ({ target, source: REPO_NAME.test(target) ? "github" : "linear" }); +/** + * The source of a filing target from its shape and the project's local prefix + * (BB-367): the prefix is the local source, a repo has a slash, anything else + * is a Linear team key. + */ +export const filingTargetOf = (target: string, prefix: string = DEFAULT_LOCAL_PREFIX): FilingTarget => ({ target, source: REPO_NAME.test(target) ? "github" : target.toUpperCase() === prefix.toUpperCase() ? "local" : "linear" }); /** Linear's priorities, as `ops.autoAdopt` names them. */ export const LINEAR_PRIORITIES = ["urgent", "high", "medium", "low"] as const; @@ -534,9 +540,10 @@ export const projectFileSchema = z */ standingRules: z.array(z.string().trim().min(1).max(400)).max(40).default([]), /** - * Production to watch: one ops binding per target, which files a Linear - * ticket for each problem it finds and escalates it to the project - * steward. `team` is where tickets are filed (the first of linear.teams + * Production to watch: one ops binding per target, which files a ticket + * for each problem it finds and escalates it to the project steward. + * `team` is where tickets are filed — a Linear team key, a GitHub + * `owner/repo`, or the project's local prefix (the first of linear.teams * when left out); `context` is the kubeconfig context kubectl reads it * with; `autoAdopt` names the priorities whose tickets are labelled for * a steward when filed, without asking. @@ -586,8 +593,9 @@ export const projectFileSchema = z if (file.ops.team === undefined && file.linear.teams.length === 0) ctx.addIssue({ code: "custom", path: ["ops", "team"], message: "ops needs a filing target to file tickets in: set ops.team to a Linear team key, a GitHub owner/repo, or a local unit" }); // A repo target (BB-235) is checked against the repo set by // `filingTargetProblems`, which the caller runs where repos are known; a - // team key is checked here against the project's own teams. - if (file.ops.team !== undefined && !REPO_NAME.test(file.ops.team) && !file.linear.teams.includes(file.ops.team)) ctx.addIssue({ code: "custom", path: ["ops", "team"], message: `${file.ops.team} is not one of linear.teams, so a ticket filed there would never be stewarded` }); + // team key is checked here against the project's own teams. The project's + // local prefix is accepted as the local filing target (BB-367). + if (file.ops.team !== undefined && !REPO_NAME.test(file.ops.team) && file.ops.team.toUpperCase() !== prefix.toUpperCase() && !file.linear.teams.includes(file.ops.team)) ctx.addIssue({ code: "custom", path: ["ops", "team"], message: `${file.ops.team} is not one of linear.teams, so a ticket filed there would never be stewarded` }); }); export type ProjectFile = z.infer; @@ -715,10 +723,10 @@ export const depsAlertsPlaybookName = (project: ProjectFile): string => project. export const backlogPlaybookName = (project: ProjectFile): string => project.playbooks[BACKLOG_PLAYBOOK] ?? BACKLOG_PLAYBOOK; export const depsPrsPlaybookName = (project: ProjectFile): string => project.playbooks[DEPS_PRS_PLAYBOOK] ?? DEPS_PRS_PLAYBOOK; -/** The Linear team or GitHub repo an ops steward files in, with its source. */ +/** The Linear team, GitHub repo or local source an ops steward files in, with its source. */ export const opsTeam = (project: ProjectFile): FilingTarget | null => { const target = project.ops.team ?? project.linear.teams[0] ?? null; - return target === null ? null : filingTargetOf(target); + return target === null ? null : filingTargetOf(target, project.localPrefix ?? DEFAULT_LOCAL_PREFIX); }; // ---- migration --------------------------------------------------------------------- diff --git a/plugins/stewards/deps.ts b/plugins/stewards/deps.ts index ef351589..bb507f3b 100644 --- a/plugins/stewards/deps.ts +++ b/plugins/stewards/deps.ts @@ -247,13 +247,22 @@ export function adoptionQuestion(ticketKey: string, repo: string, alerts: Readon return `Adopt ${ticketKey}? ${severities.join("/")} Dependabot alert${alerts.length === 1 ? "" : `s (${alerts.length})`} on ${repo}: ${packages.join(", ")} (${ecosystems.join(", ")}), ${fix}${dueDate === null ? "" : `, due ${dueDate}`}.${overdue}`; } -/** What each choice means, for the item's `how` and the steward's wake. */ -export function adoptionHow(dismissAllowed: boolean): string { +/** What each choice means, for the item's `how` and the steward's wake. `local` is a project whose filing target is the local source (BB-367), where the plugin moves the ticket itself because it has no labels. */ +export function adoptionHow(dismissAllowed: boolean, local = false): string { const parts = [ - `${ADOPTION_CHOICES.adopt}: the ticket is labelled and moved to Todo, and a ticket steward builds the upgrade.`, - `${ADOPTION_CHOICES.keep}: the ticket stays open and unadopted; the steward moves its due date out, and the plugin asks again when that date arrives.`, + local + ? `${ADOPTION_CHOICES.adopt}: the plugin moves the ticket out of Backlog to Ready, and a ticket steward builds the upgrade.` + : `${ADOPTION_CHOICES.adopt}: the ticket is labelled and moved to Todo, and a ticket steward builds the upgrade.`, + local + ? `${ADOPTION_CHOICES.keep}: the ticket stays open and unadopted in Backlog; the plugin asks again when the deadline arrives.` + : `${ADOPTION_CHOICES.keep}: the ticket stays open and unadopted; the steward moves its due date out, and the plugin asks again when that date arrives.`, ]; - if (dismissAllowed) parts.push(`${ADOPTION_CHOICES.dismiss}: the ticket's alerts are dismissed on GitHub as "vulnerable code is not actually used" and the ticket is closed with the reason.`); + if (dismissAllowed) + parts.push( + local + ? `${ADOPTION_CHOICES.dismiss}: the ticket's alerts are dismissed on GitHub as "vulnerable code is not actually used" and the plugin moves the ticket to Canceled.` + : `${ADOPTION_CHOICES.dismiss}: the ticket's alerts are dismissed on GitHub as "vulnerable code is not actually used" and the ticket is closed with the reason.`, + ); return parts.join(" "); } diff --git a/plugins/stewards/roles.ts b/plugins/stewards/roles.ts index 15347cef..095ccf2c 100644 --- a/plugins/stewards/roles.ts +++ b/plugins/stewards/roles.ts @@ -9,7 +9,7 @@ import { z } from "zod"; import { globError } from "./decisions.js"; import { opsTargetKey, type AlertmanagerTarget, type DependabotTarget, type K8sTarget, type OpsTarget, type SentryTarget } from "./ops.js"; import { REPO_NAME } from "./source-contract.js"; -import { alertmanagerTargets, DEPENDENCY_BOTS, dependabotRepoSchema, filingTargetSchema, filingTargetOf, k8sTargets, LINEAR_PRIORITIES, playbookName, PROJECT_FILE, roleAlertmanagerSchema, sentrySlug, sentryTargets, STEWARDS_DIR, teamKey, zodMessage, type BindingKind, type FilingTarget, type Parsed, type Playbook, type ProjectFile } from "./config.js"; +import { alertmanagerTargets, DEFAULT_LOCAL_PREFIX, DEPENDENCY_BOTS, dependabotRepoSchema, filingTargetSchema, filingTargetOf, k8sTargets, LINEAR_PRIORITIES, playbookName, PROJECT_FILE, roleAlertmanagerSchema, sentrySlug, sentryTargets, STEWARDS_DIR, teamKey, zodMessage, type BindingKind, type FilingTarget, type Parsed, type Playbook, type ProjectFile } from "./config.js"; /** The per-person roles: which watches and the project stewardship a GitHub login's server runs. */ export const ROLES_FILE = `${STEWARDS_DIR}/roles.json`; @@ -92,7 +92,7 @@ export const roleOpsSchema = z k8sNamespaces: z.array(z.string().trim().regex(/^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$/u, "a namespace name such as web-production")).max(50).default([]), /** The kubeconfig context kubectl uses on this person'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(), - /** Where this person's ops tickets are filed (the first of linear.teams when left out): a Linear team key or a GitHub owner/repo. */ + /** Where this person's ops tickets are filed (the first of linear.teams when left out): a Linear team key, a GitHub owner/repo, or the project's local prefix. */ team: filingTargetSchema.optional(), autoAdopt: z.array(z.enum(LINEAR_PRIORITIES)).max(4).default([]), sentry: roleSentrySchema, @@ -321,10 +321,10 @@ export function rolePullWatches(role: Role | null, repos: readonly string[], dep return [...synthesized, ...rolePulls(role)]; } -/** The Linear team a role's ops steward files in (the first of linear.teams when the role names none), with its source. */ +/** The Linear team, GitHub repo or local source a role's ops steward files in (the first of linear.teams when the role names none), with its source. */ export const roleOpsTeam = (role: Role | null, project: ProjectFile): FilingTarget | null => { const target = role?.ops?.team ?? project.linear.teams[0] ?? null; - return target === null ? null : filingTargetOf(target); + return target === null ? null : filingTargetOf(target, project.localPrefix ?? DEFAULT_LOCAL_PREFIX); }; /** @@ -563,14 +563,18 @@ export function roleWarnings(roles: RolesFile): string[] { * that is not in the project's repo set, and a role's Linear team key that is * not one of `linear.teams`. A project file's team key is checked by the * schema itself; this adds the repo case the schema cannot see (the repo set - * comes from `repos.json`) and the role cases the schema never checks. + * comes from `repos.json`) and the role cases the schema never checks. The + * project's local prefix (BB-367) is the local filing target, so it needs no + * `linear.teams` entry. */ export function filingTargetProblems(project: ProjectFile, roles: RolesFile | null, repos: readonly string[]): string[] { const out: string[] = []; + const prefix = project.localPrefix ?? DEFAULT_LOCAL_PREFIX; const repoProblem = (where: string, target: string) => { if (!repos.some((r) => r.toLowerCase() === target.toLowerCase())) out.push(`${where}: ${target} is not in repos.json, so a ticket filed there would never be stewarded`); }; const teamProblem = (where: string, target: string) => { + if (target.toUpperCase() === prefix.toUpperCase()) return; if (!project.linear.teams.includes(target)) out.push(`${where}: ${target} is not one of linear.teams, so a ticket filed there would never be stewarded`); }; const projectTarget = project.ops.team; diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 0ca7fc72..9931129e 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -10651,6 +10651,98 @@ describe("ops stewards", () => { const r = await t.tool("steward_report", { phase: "Todo", summary: "x", nextAction: "y", actor: "steward", opsTickets: [{ fingerprint: FP, ticket: "ENG-50", did: "filed" }] }, ticketSteward); expect(r).toMatchObject({ error: true, text: expect.stringMatching(/opsTickets is for an ops steward's report/u) }); }); + + // BB-367: the local source is a filing target, so an ops steward on a + // project with no Linear files locally and `check` names no Linear. + const localOnly = async () => { + const c = cluster(); + const t = await setup({ kubectl: c.kubectl }); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: [] } }); + delete t.files[playbookPath("linear-tickets")]; + t.files[playbookPath("ops-watch")] = OPS_WATCH; + t.files[ROLES_FILE] = JSON.stringify({ version: 2, roles: { ops: { team: "LOCAL", k8sNamespaces: ["web-production"] } }, holders: { "github-jane": ["projectSteward", "ops"] } }); + t.viewers.github = "github-jane"; + t.viewers.linear = null; + t.repos.splice(0); + c.state.pods = [crashingPod()]; + c.state.events = [warningEvent("web-router-6d4f9c7b8-x2k4q")]; + return { t, c }; + }; + + it("passes check with no problem line and no Linear on a local-only project, and the ops wake files locally (BB-367)", async () => { + const { t } = await localOnly(); + const check = await t.harness.behavior.runCli(["check", "--project", "p1"]); + expect(check.stdout.split("\n").filter((l) => l.startsWith("problem:"))).toEqual([]); + expect(check.stdout).not.toMatch(/linear/i); + expect(check.stdout).toMatch(/ops: tickets filed in LOCAL \(local\)/u); + + await t.hooks.sweep(); + await t.flush(); + const ops = t.spawns.find((x) => String(x.title).startsWith("Ops watch"))!; + const first = String(ops.prompt); + // The filing target and owner the wake carries: the local unit, and the + // server's GitHub login, never a Linear login. + expect(first).toMatch(/File tickets in this project's local source with ticket_file \{ unit: "local"/u); + expect(first).toMatch(/this server's owner, github-jane/u); + expect(first).not.toMatch(/Assignee: unassigned/u); + }); + + it("dedups an ops look through the local source (BB-367)", async () => { + const { t } = await localOnly(); + // A local ticket already carries the fingerprint line, so the look adopts it. + t.hooks.localSource.create({ unit: "p1", title: "Router crash-loop", description: `Crash-looping.\nFingerprint: \`${FP}\`\n\n_— from bb thread thr_prior_` }, null); + await t.hooks.sweep(); + await t.flush(); + const ops = t.spawns.find((x) => String(x.title).startsWith("Ops watch"))!; + const first = String(ops.prompt); + expect(first).toMatch(/### Recurring: its ticket is open/u); + expect(first).toMatch(/Recurring on LOCAL-1/u); + expect(first).not.toMatch(/### New: no ticket yet/u); + expect(t.hooks.store.fingerprint("p1", FP)).toMatchObject({ ticketKey: "LOCAL-1" }); + }); + + it("moves the local ticket when the owner answers a forwarded local ops escalation (BB-367)", async () => { + const { t } = await localOnly(); + await t.hooks.sweep(); + await t.flush(); + const ops = t.spawns.find((x) => String(x.title).startsWith("Ops watch"))!; + t.hooks.localSource.create({ unit: "p1", title: "Router crash-loop", description: `Fingerprint: \`${FP}\`\n\n_— from bb thread ${ops.id}_` }, null); + const report = await t.tool("steward_report", { phase: "watching", summary: "Filed LOCAL-1.", nextAction: "Watch", actor: "steward", opsTickets: [{ fingerprint: FP, ticket: "LOCAL-1", did: "filed" }], escalate: { kind: "decision", question: "Filed LOCAL-1 (high): adopt it?", meanwhile: "Keep watching." } }, ops.id); + expect(report.error).toBe(false); + // The project steward's wake names the local filing and tells it to forward, not label. + const project = t.hooks.store.project("p1").threadId!; + const wake = t.sends.filter((s) => s.threadId === project).at(-1)!.text; + expect(wake).toMatch(/This project files in its local source/u); + expect(wake).toMatch(/Forward the decision to the owner with steward_update \{ binding, forward, resolution: "choice"/u); + expect(wake).not.toMatch(/add the label `bb-managed` and move it to Todo/u); + // The project steward forwards with the escalation's Adopt/Keep/Dismiss choices. + const esc = /(esc_[\w-]+)/u.exec(wake)![1]!; + const forwarded = await t.tool("steward_update", { binding: TARGET, forward: esc, resolution: "choice" }, project); + expect(forwarded.error).toBe(false); + const qst = /(qst_[\w-]+)/u.exec(forwarded.text)![1]!; + // The owner answers Adopt; the plugin moves the local ticket to Ready. + expect(await t.harness.callRpc("stewardsAnswerQuestion", { questionId: qst, choice: "Adopt", answer: null }, { experimental_caller: { kind: "client" } })).toMatchObject({ ok: true }); + expect(t.hooks.localSource.get("LOCAL-1")).toMatchObject({ state: "Ready" }); + }); + + it("moves the local ticket when the owner answers a forwarded local ops escalation with bb stewards done (BB-367)", async () => { + const { t } = await localOnly(); + await t.hooks.sweep(); + await t.flush(); + const ops = t.spawns.find((x) => String(x.title).startsWith("Ops watch"))!; + t.hooks.localSource.create({ unit: "p1", title: "Router crash-loop", description: `Fingerprint: \`${FP}\`\n\n_— from bb thread ${ops.id}_` }, null); + const report = await t.tool("steward_report", { phase: "watching", summary: "Filed LOCAL-1.", nextAction: "Watch", actor: "steward", opsTickets: [{ fingerprint: FP, ticket: "LOCAL-1", did: "filed" }], escalate: { kind: "decision", question: "Filed LOCAL-1 (high): adopt it?", meanwhile: "Keep watching." } }, ops.id); + expect(report.error).toBe(false); + const project = t.hooks.store.project("p1").threadId!; + const wake = t.sends.filter((s) => s.threadId === project).at(-1)!.text; + const esc = /(esc_[\w-]+)/u.exec(wake)![1]!; + const forwarded = await t.tool("steward_update", { binding: TARGET, forward: esc, resolution: "choice" }, project); + expect(forwarded.error).toBe(false); + const qst = /(qst_[\w-]+)/u.exec(forwarded.text)![1]!; + // The owner answers Adopt from a thread; the plugin moves the local ticket to Ready. + expect(await t.harness.behavior.runCli(["done", qst, "--choice", "Adopt", "--project", "p1"])).toMatchObject({ exitCode: 0, stdout: expect.stringMatching(/Chose Adopt/u) }); + expect(t.hooks.localSource.get("LOCAL-1")).toMatchObject({ state: "Ready" }); + }); }); describe("dependency stewards", () => { @@ -10960,6 +11052,25 @@ describe("dependency stewards", () => { expect(t.hooks.store.depsDecision("p1", "ENG-60")).toMatchObject({ status: "resolved", resolution: "ENG-60 was closed (Canceled)." }); }); + it("raises the owner's decision for a local autoAdopt ticket and moves it when the owner adopts (BB-367)", async () => { + const { t, steward } = await watching([alert({ number: 4, severity: "critical", ghsaId: "GHSA-crit" })], { linear: { teams: [] }, ops: { team: "LOCAL" } }); + const ops = steward()!.id; + // The steward files a local ticket in Backlog. + t.hooks.localSource.create({ unit: "p1", title: "Critical alert", description: `Fingerprint: \`acme/web#4\`\n\n_— from bb thread ${ops}_` }, null); + expect((await t.tool("steward_report", { phase: "watching", summary: "Filed LOCAL-1.", nextAction: "Watch", actor: "steward", opsTickets: [{ fingerprint: "acme/web#4", ticket: "LOCAL-1", did: "filed" }] }, ops)).error).toBe(false); + // Critical is in autoAdopt, but a local ticket is never auto-adopted: the owner's decision is raised. + const decision = t.hooks.store.depsDecision("p1", "LOCAL-1")!; + expect(decision).toMatchObject({ status: "pending", severity: "critical" }); + expect(t.hooks.store.need(decision.needId!)!.how).toMatch(/the plugin moves the ticket out of Backlog to Ready/u); + // The owner answers Adopt; the plugin moves the local ticket to Ready. + expect(await t.harness.behavior.runCli(["done", decision.needId!, "--choice", "Adopt", "--project", "p1"])).toMatchObject({ exitCode: 0, stdout: expect.stringMatching(/Chose Adopt/u) }); + t.advance(60_000); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.localSource.get("LOCAL-1")).toMatchObject({ state: "Ready" }); + expect(t.hooks.store.depsDecision("p1", "LOCAL-1")).toMatchObject({ status: "resolved", resolution: "Chose: Adopt" }); + }); + it("snoozes Keep tracking to the note's date and re-raises the same decision when it arrives", async () => { const { t, steward } = await watching([alert({ number: 4, severity: "medium", ghsaId: "GHSA-med", fixedVersion: null, createdAt: "2026-10-10T00:00:00Z" })]); const ops = steward()!.id; diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 7dd52582..2381fa6c 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -6238,18 +6238,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * or was partial (an older source, a read error), so the caller marks the * new findings "dedup unavailable" and the wake tells the steward to * search itself rather than risk a duplicate. It only reads; it never - * files, comments or reassigns. + * files, comments or reassigns. The local source (BB-367) searches by this + * project's id, which is its unit. */ - async function dedupFingerprints(target: FilingTarget | null, fingerprints: string[]): Promise | null> { + async function dedupFingerprints(target: FilingTarget | null, fingerprints: string[], config: ProjectConfig): Promise | null> { const adopted = new Map(); if (fingerprints.length === 0) return adopted; // No target to search is not "nothing found": dedup did not run, so the // caller marks the new findings unavailable rather than risk a duplicate. if (target === null) return null; + const units = [target.source === "local" ? config.projectId : target.target]; for (const fingerprint of fingerprints) { let out: z.infer; try { - out = await sourceRpc(target.source, "sourceSearchIssues", { units: [target.target], query: fingerprint, limit: DEDUP_LIMIT }, sourceContract.sourceSearchIssues.output); + out = await sourceRpc(target.source, "sourceSearchIssues", { units, query: fingerprint, limit: DEDUP_LIMIT }, sourceContract.sourceSearchIssues.output); } catch (error) { if (!sourceRpcMissing(error)) bb.log.warn(`stewards: the dedup search for ${fingerprint} failed: ${errorMessage(error)}`); return null; @@ -6279,8 +6281,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** Where a project's ops and dependency watches file: the role's target, or the first Linear team (BB-235). */ const filingTargetFor = (config: ProjectConfig): FilingTarget | null => roleOpsTeam(config.role, config.file); - /** The login a filing target files under: this server's GitHub login for a repo, its Linear login for a team. */ - const filingLogin = (target: FilingTarget | null, config: ProjectConfig): string | null => (target?.source === "github" ? config.githubLogin : config.linearLogin); + /** + * The login a filing target files under: this server's GitHub login for a + * repo or the local source (BB-367), its Linear login for a team. + */ + const filingLogin = (target: FilingTarget | null, config: ProjectConfig): string | null => (target?.source === "github" || target?.source === "local" ? config.githubLogin : config.linearLogin); /** Every ops target a project watches: the k8s namespaces, the Sentry projects, the Alertmanager namespaces, the Dependabot repositories and the role's backlog teams. */ const allOpsTargets = (config: ProjectConfig): OpsTarget[] => [...roleK8sTargets(config.role), ...roleSentryTargets(config.role), ...roleAlertmanagerTargets(config.role), ...roleDepsTargets(config.role, config.repos), ...roleBacklogTargets(config.role)]; @@ -6293,7 +6298,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P try { const { sightings, ...rest } = await opsReaderFor(config).look(target, { now: at, since }); const rows = store.sight(b.projectId, b.id, sightings.map((s) => ({ fingerprint: s.fingerprint, summary: s.summary }))); - const adopted = await dedupFingerprints(filing, unmappedFingerprints(rows)); + const adopted = await dedupFingerprints(filing, unmappedFingerprints(rows), config); if (adopted !== null) adoptTickets(b, rows, adopted); const tickets = await ticketStates(filing, [...rows.values()].map((r) => r.ticketKey).filter((k): k is string => k !== null)); const findings = classify(sightings, rows, tickets, at, filingLogin(filing, config)).map((f) => (adopted === null && f.class === "new" ? { ...f, dedupUnavailable: true } : f)); @@ -6355,7 +6360,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // adopted here, exactly as in the ops look, before the batch plan reads // the map: an adopted medium or low alert then joins its ticket like // any mapped one. - const adopted = await dedupFingerprints(filing, unmappedFingerprints(rows)); + const adopted = await dedupFingerprints(filing, unmappedFingerprints(rows), config); if (adopted !== null) adoptTickets(b, rows, adopted); // Every fingerprint row, not just this look's: a batched ticket that // is no longer in the open alerts still has rows, and whether it is @@ -6427,8 +6432,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // owner once the deadline (or a snooze) has passed, and resolves it when // the owner answers, the ticket is labelled, or the ticket closes. - /** Whether a ticket's severity is one deps.autoAdopt names: such a ticket is adopted when filed and needs no decision. */ - const autoAdopted = (severity: string | null, config: ProjectConfig): boolean => severity !== null && (config.file.deps.autoAdopt as string[]).includes(severity); + /** + * Whether a ticket's severity is one deps.autoAdopt names: such a ticket + * is adopted when filed and needs no decision. The local source (BB-367) + * has no labels or priority, so a local ticket is never auto-adopted: the + * owner's decision is always raised, and the plugin moves the ticket when + * the owner answers. + */ + const autoAdopted = (severity: string | null, config: ProjectConfig): boolean => filingTargetFor(config)?.source !== "local" && severity !== null && (config.file.deps.autoAdopt as string[]).includes(severity); /** Whether the deps-alerts playbook's `may` list lets a steward dismiss an alert on GitHub. */ const dismissAllowed = (config: ProjectConfig): boolean => config.depsAlerts?.may.includes("dismiss-alert") === true; @@ -6465,7 +6476,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P kind: "decide", url: ticket?.url ?? ticketKey, what: adoptionNeedLine(ticketKey, repo, severities), - how: adoptionHow(allowDismiss), + how: adoptionHow(allowDismiss, filingTargetFor(config)?.source === "local"), why: ADOPTION_WHY, details: adoptionQuestion(ticketKey, repo, alerts, due, overdueBy), data: { adoption: true, ticket: ticketKey, fingerprints, choices: adoptionChoices(hasFix, allowDismiss), dueDate: due }, @@ -6550,7 +6561,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } // The owner answered on the Stewards page or with `bb stewards done`. // Only that answer snoozes a decision; the plugin never snoozes or - // dismisses on a steward's word. + // dismisses on a steward's word. For a local target (BB-367) the + // owner's answer is the act: the local source has no label to adopt + // with, so the plugin moves the ticket itself (Ready, or Canceled), + // exactly as the page's own owner-turn RPC does. if (need !== null && need.status === "done") { const resolution = need.resolution ?? "Answered."; if (resolution.startsWith(`Chose: ${ADOPTION_CHOICES.keep}`)) { @@ -6560,6 +6574,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P store.note(b.id, `${ticketKey} is snoozed until ${dueDate(until, config.file.nightly.timezone)}; the plugin asks again then.`, true); } } else { + if (filingTargetFor(config)?.source === "local") { + if (resolution.startsWith(`Chose: ${ADOPTION_CHOICES.adopt}`)) localSource?.update({ key: ticketKey, state: "Ready", ownerTurn: true }); + else if (resolution.startsWith(`Chose: ${ADOPTION_CHOICES.dismiss}`)) localSource?.update({ key: ticketKey, state: "Canceled", ownerTurn: true }); + } settleAdoption(b, decision, resolution); continue; } @@ -8427,7 +8445,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const questions = store.openQuestions(projectId).map((question) => ({ question, about: question.bindingId === null ? null : store.binding(question.bindingId) })); const needs = open.flatMap((b) => store.openNeeds(b.id).map((need) => ({ need, binding: b }))); const assumptions = store.openAssumptionsForProject(projectId).map((assumption) => ({ assumption, binding: assumption.bindingId === null ? null : (store.binding(assumption.bindingId) ?? null) })); - const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, standingRules: config.file.standingRules, questions, needs, assumptions, lessons: store.allLessons(projectId), refreshes: store.playbookRefreshes(projectId), guidance: await wakeGuidance(projectId, null), lessonRules: config.file.lessons, timeZone: config.file.nightly.timezone, label: config.file.label, ...(records === undefined ? {} : { records }) }); + const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, standingRules: config.file.standingRules, questions, needs, assumptions, lessons: store.allLessons(projectId), refreshes: store.playbookRefreshes(projectId), guidance: await wakeGuidance(projectId, null), lessonRules: config.file.lessons, timeZone: config.file.nightly.timezone, label: config.file.label, localFiling: filingTargetFor(config)?.source === "local", ...(records === undefined ? {} : { records }) }); const delivered = { ids: routed.filter((r) => r.escalation.deliveredAt === null).map((r) => r.escalation.id), at: 0 }; delivered.at = store.markDelivered(delivered.ids); // A wake can be the thing that pushes the transcript over the limit. @@ -9514,6 +9532,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); } + /** + * BB-367: move the local tickets an ops escalation filed when the owner's + * answer is Adopt or Dismiss. The local source has no label to adopt with, + * so the plugin moves the ticket itself (Ready, or Canceled), as the page's + * own owner-turn RPC does. Called from both forwarded-answer paths, the + * page and `bb stewards done`. + */ + function moveLocalTickets(x: Escalation, label: string): void { + const keys = x.data.localTickets; + if (!Array.isArray(keys)) return; + const state = label === ADOPTION_CHOICES.adopt ? "Ready" : label === ADOPTION_CHOICES.dismiss ? "Canceled" : null; + if (state === null) return; + for (const key of keys) if (typeof key === "string") localSource?.update({ key, state, ownerTurn: true }); + } + /** * BB-231: a gate item (approve-spec, approve-pr, merge) filed on a binding * that already has an open route-`user` escalation or question may be the @@ -12330,6 +12363,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P store.addGuidance(b.id, guidance, "user"); countCorrections(x, guidance); store.note(b.id, `The user chose ${chosen} for ${q.question}${text === null ? "" : `: ${text}`}.`); + // BB-367: the owner's answer to a local ops escalation is the act. + moveLocalTickets(x, chosen); scheduleReconcile(b.id); await wakeProjectOnForwardedAnswer(b, closure, [x]); return { ok: true, message: `Recorded; ${b.entityKey}'s steward has been told.` }; @@ -13796,7 +13831,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // 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. - const raised = input.escalate === undefined ? null : store.escalate({ bindingId: b.id, kind: input.escalate.kind, question: input.escalate.question, context: input.escalate.context ?? null, meanwhile: input.escalate.meanwhile, why: input.escalate.why ?? null, route: nextRoute(escalationsCtx, b, null), recommendation: null, projectId: b.projectId, origin: { threadId, bindingId: b.id, chain: [] }, ...(input.escalate.choices === undefined ? {} : { choices: input.escalate.choices }) }); + // BB-367: a local ticket has no labels or priority, so the owner's + // answer is the act. The escalation carries the filed local ticket + // keys and the Adopt/Keep/Dismiss choices, and the plugin moves the + // ticket when the owner answers the forwarded question. + const localFiling = config !== null && filingTargetFor(config)?.source === "local" && input.escalate?.kind === "decision"; + const localTickets = localFiling ? [...new Set(opsTickets.filter((t) => t.did === "filed" || t.did === "reopened").map((t) => t.ticket))] : []; + const localChoices = localTickets.length > 0 ? [ADOPTION_CHOICES.adopt, ADOPTION_CHOICES.keep, ADOPTION_CHOICES.dismiss] : []; + const raised = input.escalate === undefined ? null : store.escalate({ bindingId: b.id, kind: input.escalate.kind, question: input.escalate.question, context: input.escalate.context ?? null, meanwhile: input.escalate.meanwhile, why: input.escalate.why ?? null, route: nextRoute(escalationsCtx, b, null), recommendation: null, projectId: b.projectId, origin: { threadId, bindingId: b.id, chain: [] }, ...(input.escalate.choices !== undefined ? { choices: input.escalate.choices } : localChoices.length > 0 ? { choices: localChoices } : {}), ...(localTickets.length === 0 ? {} : { data: { localTickets } }) }); const open = store.openEscalations(b.id); const status = { phase: input.phase, @@ -16809,6 +16851,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P store.addGuidance(b.id, guidance, "user"); countCorrections(x, guidance); store.note(b.id, `The user chose ${choice} for ${q.question}${note === null ? "" : `: ${note}`}.`); + // BB-367: the owner's answer to a local ops escalation is the act. + moveLocalTickets(x, choice); scheduleReconcile(b.id); await wakeProjectOnForwardedAnswer(b, closure, [x]); } diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 13a49da8..71a5aae0 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -833,6 +833,7 @@ function assignInstruction(owner: string | null): string { function filingInstruction(target: FilingTarget | null, due: boolean): string { if (target === null) return "No filing target is configured: escalate a blocked question instead of filing."; if (target.source === "github") return `File issues in the GitHub repo ${target.target} with ticket_file { unit: "${target.target}", ... }, and put the fingerprint${due ? " and a `Due: YYYY-MM-DD` line" : ""} in the body.`; + if (target.source === "local") return `File tickets in this project's local source with ticket_file { unit: "local", ... }, and put the fingerprint${due ? " and a `Due: YYYY-MM-DD` line" : ""} in the body.`; if (!due) return `File tickets in the Linear team ${target.target} with ticket_file { unit: "${target.target}", ... }.`; return `File tickets in the Linear team ${target.target} with ticket_file { unit: "${target.target}", ... }, then set each ticket's due date to the deadline the alert names with linear_update_issue (ticket_file carries no due date).`; } @@ -851,6 +852,7 @@ function ticketExample(target: FilingTarget | null): string { * (BB-235). */ function autoAdoptInstruction(target: FilingTarget | null, autoAdopt: string[], label: string, kind: "ops" | "deps"): string { + if (target?.source === "local") return `${kind}.autoAdopt: a local ticket has no labels or priority, so autoAdopt cannot adopt it. File it in Backlog and report it: the plugin raises the owner's adoption decision for a dependency ticket, and an ops ticket is escalated as usual; the owner adopts it on the Stewards page.`; const what = kind === "deps" ? `a ticket you file for a ${autoAdopt.join(" or ")} alert` : `a ticket you file at ${autoAdopt.join(" or ")} priority`; const adopt = target?.source === "github" @@ -1032,11 +1034,14 @@ export function formatDepsWake(input: DepsWakeInput): string { if (input.autoAdopt.length > 0) out.push(autoAdoptInstruction(input.target, input.autoAdopt, input.label, "deps")); const allowDismiss = playbook.may.includes("dismiss-alert"); const githubTarget = input.target?.source === "github"; - const adoptAction = githubTarget ? `add the labels \`${input.label}\` and \`${GITHUB_TODO_LABEL}\`` : `add the label \`${input.label}\` and move the ticket to Todo`; - const dismissAction = githubTarget ? "close the issue with a comment saying why" : "move the ticket to Done with a comment saying why"; + const localTarget = input.target?.source === "local"; + const adoptAction = githubTarget ? `add the labels \`${input.label}\` and \`${GITHUB_TODO_LABEL}\`` : localTarget ? "the plugin moves the ticket out of Backlog to Ready, and a ticket steward builds the upgrade" : `add the label \`${input.label}\` and move the ticket to Todo`; + const dismissAction = githubTarget ? "close the issue with a comment saying why" : localTarget ? "the plugin moves the ticket to Canceled" : "move the ticket to Done with a comment saying why"; const keepAction = githubTarget ? "keep the issue open and unadopted and update the due date in the body to the one the note gives, or by one SLA window from today when it gives none" - : "keep the ticket open and unadopted and move its due date to the one the note gives, or by one SLA window from today when it gives none, with a comment on the ticket saying so"; + : localTarget + ? "the ticket stays open and unadopted in Backlog; the plugin asks again when the deadline arrives" + : "keep the ticket open and unadopted and move its due date to the one the note gives, or by one SLA window from today when it gives none, with a comment on the ticket saying so"; out.push( `Adoption of any other ticket is the owner's decision, and the plugin asks it: once your report lists the ticket as filed, a decide item appears on the Stewards page and in \`bb stewards needs\`, kept by ticket until the owner answers, the ticket is labelled \`${input.label}\`, or it closes. Do not raise a decision escalation for it yourself, and do not ask the owner in prose. ` + `The answer arrives under "What changed" as "The user chose for …". ${ADOPTION_CHOICES.adopt}: ${adoptAction}. ` + @@ -1086,7 +1091,7 @@ export function formatDepsWake(input: DepsWakeInput): string { } } } - out.push("", `These are on the Stewards page; the plugin reminds the owner once a deadline has passed. Do not ask again, and never dismiss or snooze on a steward's own initiative. ${adoptionHow(allowDismiss)}`); + out.push("", `These are on the Stewards page; the plugin reminds the owner once a deadline has passed. Do not ask again, and never dismiss or snooze on a steward's own initiative. ${adoptionHow(allowDismiss, localTarget)}`); } const snapshot = out.splice(0); @@ -1710,6 +1715,13 @@ export function formatProjectWake(input: { timeZone?: string; /** The adoption label, for adopting what an ops steward filed. */ label?: string; + /** + * BB-367: whether this project files tickets in its local source. A local + * ticket has no labels or priority and only the owner may move it out of + * Backlog, so an ops escalation about one is the owner's to adopt on the + * Stewards page, never a label to add. + */ + localFiling?: boolean; /** The project's standing-rules list from `.bb/stewards/project.json`, shown in an approval wake; empty when none is configured. */ standingRules?: string[]; }): string { @@ -1738,7 +1750,9 @@ export function formatProjectWake(input: { ); if (input.routed.some((r) => r.from.kind === "ops")) { out.push( - `An escalation from an ops steward is a ticket it filed about production, with a priority and a recommendation. Adopt it when the project's guidance says the problem is worth working: add the label \`${input.label ?? "bb-managed"}\` and move it to Todo (ticket_update), and a ticket steward picks it up; then resolve the escalation with guidance saying so. Otherwise decline: resolve it with guidance giving the reason.`, + input.localFiling === true + ? "An escalation from an ops steward is a ticket it filed about production, with a priority and a recommendation. This project files in its local source, where a ticket has no labels or priority and only the owner may move it out of Backlog: do not add a label or move it yourself. Forward the decision to the owner with steward_update { binding, forward, resolution: \"choice\", recommendation, cites: [ids] } — the escalation carries Adopt/Keep/Dismiss, and the plugin moves the ticket to Ready or Canceled when the owner answers." + : `An escalation from an ops steward is a ticket it filed about production, with a priority and a recommendation. Adopt it when the project's guidance says the problem is worth working: add the label \`${input.label ?? "bb-managed"}\` and move it to Todo (ticket_update), and a ticket steward picks it up; then resolve the escalation with guidance saying so. Otherwise decline: resolve it with guidance giving the reason.`, "", ); }