From 2a8e1c17d9cafd2f807039449a048d418e549723 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sat, 14 Nov 2026 20:38:38 +0000 Subject: [PATCH] stewards: add the project.json backlog block and the ops-linear backlog source (BB-334) --- plugins/stewards/config.test.ts | 35 ++++++++- plugins/stewards/config.ts | 49 +++++++++--- plugins/stewards/migrations.snapshot.json | 3 +- plugins/stewards/ops.ts | 41 +++++++++- plugins/stewards/server.test.ts | 96 +++++++++++++++++++++++ plugins/stewards/server.ts | 91 +++++++++++++++++++-- plugins/stewards/store.test.ts | 18 +++-- plugins/stewards/store.ts | 14 +++- plugins/stewards/test-world.ts | 14 +++- 9 files changed, 326 insertions(+), 35 deletions(-) diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index c990e95e..228e92f2 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -16,6 +16,7 @@ import { playbookLabels, playbookNameFor, playbookStates, + roleBacklogTargets, sentryTargets, ticketWatchId, ticketWatchProblems, @@ -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", () => { @@ -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); @@ -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, ""); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index 38c945e9..ba611d1a 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -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"; @@ -330,6 +330,26 @@ export type TicketWatch = z.infer; */ export const ticketWatchId = (watch: Pick): 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; + export const projectFileSchema = z .object({ version: z.literal(1), @@ -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, /** @@ -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"); @@ -739,7 +769,7 @@ export const deploymentsFieldSchema = z }); export const PLAYBOOK_SOURCES = ["linear", "github", "k8s", "sentry", "alertmanager"] as const; -const SOURCES_OF: Record = { ticket: ["linear", "github"], pr: ["github"], review: ["github"], ops: ["k8s", "github", "sentry", "alertmanager"] }; +const SOURCES_OF: Record = { ticket: ["linear", "github"], pr: ["github"], review: ["github"], ops: ["k8s", "github", "sentry", "alertmanager", "linear"] }; export const frontMatterSchema = z .object({ @@ -847,16 +877,13 @@ export function parsePlaybook(text: string, expectedName: string): Parsed - 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; @@ -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]! }; } @@ -329,6 +342,28 @@ export type OpsLook = z.infer; /** What a reader returns for one target, before the fingerprint map. */ export type RawLook = Omit & { 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; + /** A fingerprint map row, as classification needs it. */ export type FingerprintRow = { fingerprint: string; ticketKey: string | null; firstSeenAt: number; lastCommentedAt: number | null; filedByThread?: string | null }; diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index fd761a56..4ceb76d4 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -11958,6 +11958,102 @@ describe("Alertmanager stewards (BB-314)", () => { }); }); +describe("the backlog watch (BB-334)", () => { + const backlogIssue = (over: Record = {}) => ({ + id: "uuid-1", + key: "BB-1", + title: "Fix login", + state: "Backlog", + stateType: "backlog", + unit: "BB", + labels: [], + assignees: [], + priority: null, + estimate: null, + createdAt: "2026-10-01T00:00:00Z", + updatedAt: "2026-10-01T00:00:00Z", + ...over, + }); + + /** A project with one backlog role, one ops playbook and one read of team BB. */ + async function watching(options: { roleTeam?: string; projectTeam?: string; noBlock?: boolean; issues?: Array> } = {}) { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["BB"] }, ...(options.noBlock === true ? {} : { backlog: { ...(options.projectTeam === undefined ? {} : { team: options.projectTeam }) } }) }); + t.files[ROLES_FILE] = JSON.stringify({ version: 2, roles: { backlog: { backlog: { team: options.roleTeam ?? "BB" } } }, holders: { jane: ["backlog"] } }); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + t.setBacklog(options.issues ?? [backlogIssue()]); + await t.hooks.sweep(); + await t.flush(); + const binding = () => t.hooks.store.byEntity("ops", "backlog/BB"); + return { t, binding }; + } + + it("creates exactly one ops binding for the role's team and reads the whole backlog through sourceBacklog", async () => { + const { t, binding } = await watching(); + expect(binding()).toMatchObject({ kind: "ops", entityKey: "backlog/BB", title: "Backlog watch: BB", threadId: null, endedAt: null }); + expect(t.hooks.store.openOfKind("p1", "ops").filter((b) => b.entityId === "backlog/BB")).toHaveLength(1); + expect(t.hooks.store.binding(binding()!.id)!.backlogLook).toMatchObject({ team: "BB", error: null, unsupported: false, issues: [expect.objectContaining({ key: "BB-1" })] }); + }); + + it("reads only: the backlog path makes no Linear write call", async () => { + const { t } = await watching(); + t.rpcCalls.length = 0; + await t.hooks.sweep(); + await t.flush(); + const methods = t.rpcCalls.filter((c) => c.pluginId === "linear").map((c) => c.method); + expect(methods).toContain("sourceBacklog"); + expect(methods).not.toContain("sourceEnsureLabel"); + // Every linear call the path makes is a read (or the lease interest). + expect(methods.every((m) => ["sourceBacklog", "sourceSnapshot", "sourceSearchIssues", "sourceAdoptable", "sourceValidate", "sourceSetInterest"].includes(m))).toBe(true); + }); + + it("shows an unsupported sourceBacklog as a problem line, not an empty backlog", async () => { + const { t, binding } = await watching(); + t.setBacklogUnsupported(true); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.binding(binding()!.id)!.backlogLook).toMatchObject({ error: expect.stringMatching(/does not support sourceBacklog/u), unsupported: true, issues: [] }); + expect(t.hooks.store.peekProjectNotes("p1")).toEqual(expect.arrayContaining([expect.stringMatching(/Backlog BB could not be read/u)])); + }); + + it("shows a sourceBacklog read error as a problem line, not an empty backlog", async () => { + const { t, binding } = await watching(); + t.setBacklogError("Linear rate limited the read"); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.binding(binding()!.id)!.backlogLook).toMatchObject({ error: "Linear rate limited the read", issues: [] }); + }); + + it("wakes the binding on a Linear doorbell for its team", async () => { + const { t, binding } = await watching(); + const before = t.hooks.store.binding(binding()!.id)!.backlogLook!.at; + t.advance(60_000); + t.entities.set("uuid-9", issue({ id: "uuid-9", key: "BB-9", unit: "BB", labels: [] })); + await t.ring("linear", "uuid-9"); + expect(t.hooks.store.binding(binding()!.id)!.backlogLook!.at).toBeGreaterThan(before); + }); + + it("reports a block no role watches as one problem, and never picks a team", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["BB"] }, backlog: { team: "BB" } }); + t.files[ROLES_FILE] = JSON.stringify({ version: 2, roles: { ops: { k8sNamespaces: ["prod"] } }, holders: { jane: ["ops"] } }); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + await t.flush(); + const check = (await t.harness.callRpc("stewardsCheck", { projectId: "p1" })) as { ok: boolean; lines: string[] }; + expect(check.lines.filter((l) => l.startsWith("problem:") && l.includes("backlog"))).toEqual(["problem: stewards/project.json: backlog is configured but no role watches a backlog; add a backlog role or remove the block"]); + }); + + it("reports a backlog.team no role watches as one problem", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["BB", "OPS"] }, backlog: { team: "OPS" } }); + t.files[ROLES_FILE] = JSON.stringify({ version: 2, roles: { backlog: { backlog: { team: "BB" } } }, holders: { jane: ["backlog"] } }); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + await t.flush(); + const check = (await t.harness.callRpc("stewardsCheck", { projectId: "p1" })) as { ok: boolean; lines: string[] }; + expect(check.lines.filter((l) => l.startsWith("problem:") && l.includes("backlog.team"))).toEqual(["problem: stewards/project.json: backlog.team is OPS but no role watches that team (BB); they must name the same team"]); + }); +}); + describe("the dotenv a requester imports", () => { it("reads the named variable, quoted or not, and strips a trailing comment", () => { expect(parseDotenvValue("OTHER='x'\nSENTRY_TOKEN='s3cr3t'\n", "SENTRY_TOKEN")).toBe("s3cr3t"); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index e52f0c9a..5a6ee742 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -49,6 +49,7 @@ import { playbookNameFor, playbookPath, playbookStates, + roleBacklogTargets, STAGES, ticketWatchId, ticketWatchProblems, @@ -98,7 +99,7 @@ import { HOOKS_URL_ENV, createHooksLoop, type Lease, type Rejection } from "./ho import { createBriefing, nightlyDue, stillNight, toDigestRecords } from "./nightly.js"; import { STANDUP_TOOLS, buildStandupBrief, buildStandupInstructions, readbackLine, runStandupTool, samePullRef, type StandupDelegation, type StandupEndOutcome, type StandupEntityFacts, type StandupNote, type StandupNoteType, type StandupRecord, type StandupToolContext, type StandupToolReply } from "./standup.js"; import { EntityCache, type EntityRecord } from "./entity-cache.js"; -import { classify, hasFingerprintLine, lookChanges, opsTargetKey, parseOpsTargetKey, redactLine, scrubCredentials, ticketResolved, type AlertmanagerTarget, type DependabotTarget, type FingerprintRow, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; +import { classify, hasFingerprintLine, lookChanges, opsTargetKey, parseOpsTargetKey, redactLine, scrubCredentials, ticketResolved, type AlertmanagerTarget, type BacklogLook, type BacklogTarget, type DependabotTarget, type FingerprintRow, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; import { EVENTS_PER_LOOK, NO_TOKEN, RECENT_PER_LOOK, SENTRY_API_URL, TOKEN_SCOPES, createSentryReader, emptySentryLook, issueInOrg, recentLine, sentryChanges, sentryResolveTargets, sentrySightings, sentrySummary, type SentryFinding, type SentryLook, type SentryReader } from "./sentry.js"; import { ALERTMANAGER_URL_ENV, alertmanagerChanges, alertmanagerSightings, alertmanagerSummary, createAlertmanagerReader, emptyAlertmanagerLook, resolveAlertmanagerUrl, type AlertmanagerFinding, type AlertmanagerLook, type AlertmanagerReader, type AlertmanagerRung } from "./alertmanager.js"; import { advanced, answerDiffers, asksForOpenApproval, commentDiffersFromRecommendation, compactDue, deploymentSettled, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, hasLabel, IDLE_WAKE_TEXT, isCommentNews, isOwnStageChange, lifecycle, mechanicalStatus, namesUserAsBlocker, newHumanComments, newestCommentAt, openUserFacingItems, ownChecksFinished, ownPullClosed, ownPullMerged, phaseAndStage, productGateOptions, newestEditComment, specDiff, specHash, specText, stuckDue, unheardWait, workerInFlight, workerReportedTerminal, type Change, type MechanicalEvent, type OpenUserItem } from "./reconcile.js"; @@ -2318,6 +2319,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return promise; } + /** + * Whether a kind is in use, with BB-334's backlog role counted as an ops + * watch. `usesKind` reads roles.ts's ops targets, which do not include the + * `backlog` field a role carries, so it is added here rather than by + * changing roles.ts. + */ + const usesKindFor = (file: ProjectFile, kind: BindingKind, role: StewardRole | null): boolean => + kind === "ops" && role?.ops?.backlog !== undefined ? true : usesKind(file, kind, role); + /** * The project's stewards configuration, or null when the project has none. * A file that fails to parse falls back to the last good copy, kept in kv, @@ -2450,8 +2460,16 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // legacy ops no longer runs once roles.json wins, but the watch is not // moved until the project file drops it. if (legacyOpsPresent(file)) problems.push(`ops now belongs in ${ROLES_FILE}`); + // BB-334: the project's backlog block must name a team a role actually + // watches. A block with no matching role, or a `team` naming a different + // team, is one problem line; the binding never silently picks one. + if (file.backlog !== undefined) { + const backlogTeams = [...new Set(Object.values(roles?.roles ?? {}).flatMap((r) => (r.ops?.backlog === undefined ? [] : [r.ops.backlog.team])))]; + if (backlogTeams.length === 0) problems.push(`${PROJECT_FILE}: backlog is configured but no role watches a backlog; add a backlog role or remove the block`); + else if (file.backlog.team !== undefined && !backlogTeams.includes(file.backlog.team)) problems.push(`${PROJECT_FILE}: backlog.team is ${file.backlog.team} but no role watches that team (${backlogTeams.join(", ")}); they must name the same team`); + } - const kinds = KINDS.filter((k) => usesKind(file, k, role)); + const kinds = KINDS.filter((k) => usesKindFor(file, k, role)); const names = new Map(kinds.filter((k) => k !== "ticket").map((k) => [k, playbookNameFor(file, k)] as const)); const depsAlertsName = depsAlertsPlaybookName(file); const depsPrsName = depsPrsPlaybookName(file); @@ -5334,8 +5352,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** 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); - /** Every ops target a project watches: the k8s namespaces, the Sentry projects, the Alertmanager namespaces and the Dependabot repositories. */ - const allOpsTargets = (config: ProjectConfig): OpsTarget[] => [...roleK8sTargets(config.role), ...roleSentryTargets(config.role), ...roleAlertmanagerTargets(config.role), ...roleDepsTargets(config.role, config.repos)]; + /** 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)]; /** One look at an ops binding's target, its problems entered in the fingerprint map and classified against it. */ async function lookAt(b: Binding, config: ProjectConfig, target: K8sTarget, playbook: Playbook): Promise { @@ -5679,6 +5697,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await reconcileAlertmanager(b, config, playbook, target, force); return; } + if (target.kind === "backlog") { + await reconcileBacklog(b, config, playbook, target); + return; + } const before = b.opsLook; const look = await lookAt(b, config, target, playbook); const requeueCame = b.requeueAt !== null && b.requeueAt <= now(); @@ -5738,6 +5760,43 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await archiveFinishedWorkers(store.binding(b.id) ?? b); } + /** + * One read of a backlog binding's Linear team through `sourceBacklog` + * (BB-334). It is read-only: no Linear write is ever made on this path. + * An unsupported capability or a read error is an `error` look, never an + * empty one; `issues: []` with a null `error` is the only empty report. + */ + async function lookAtBacklog(target: BacklogTarget): Promise { + const at = now(); + try { + const out = await sourceRpc("linear", "sourceBacklog", { team: target.team }, sourceContract.sourceBacklog.output); + const error = out.unsupported ? "the linear source does not support sourceBacklog" : out.errors.length > 0 ? out.errors.join("; ") : null; + return { at, target: opsTargetKey(target), team: target.team, error, issues: out.issues, unsupported: out.unsupported, truncated: out.truncated }; + } catch (error) { + return { at, target: opsTargetKey(target), team: target.team, error: errorMessage(error), issues: [], unsupported: false, truncated: false }; + } + } + + /** + * The backlog binding's look: read the team's whole backlog and keep it for + * the digest. It wakes no steward thread in Stage 1, and writes nothing to + * Linear. A failure is logged once and queued as a project note, so the + * project steward sees a problem line rather than an empty report. + */ + async function reconcileBacklog(b: Binding, config: ProjectConfig, playbook: Playbook, target: BacklogTarget): Promise { + const before = b.backlogLook; + const look = await lookAtBacklog(target); + store.patch(b.id, { backlogLook: look, playbookVersion: playbook.version, requeueAt: now() + playbook.requeueDefaultMs }); + if (look.error !== null) { + if (before?.error !== look.error) { + bb.log.warn(`stewards: cannot read the backlog of ${target.team}: ${look.error}`); + store.noteProject(b.projectId, `Backlog ${target.team} could not be read: ${look.error}`); + } + return; + } + if (look.truncated) bb.log.warn(`stewards: the backlog of ${target.team} was truncated by the source's hard cap`); + } + /** The same turn for a Dependabot alert target: re-list the open alerts and wake on what changed. */ async function reconcileDeps(b: Binding, config: ProjectConfig, playbook: Playbook, target: DependabotTarget, force: WakeReason | null): Promise { const before = b.depsLook; @@ -6280,6 +6339,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const wanted = new Map(); const opsPlaybook = playbookFor(config, "ops"); if (opsPlaybook !== null) for (const target of roleOpsTargets(config.role)) wanted.set(opsTargetKey(target), { target, playbook: opsPlaybook }); + if (opsPlaybook !== null) for (const target of roleBacklogTargets(config.role)) wanted.set(opsTargetKey(target), { target, playbook: opsPlaybook }); if (config.depsAlerts !== null) for (const target of roleDepsTargets(config.role, config.repos)) wanted.set(opsTargetKey(target), { target, playbook: config.depsAlerts }); // BB-295: only this project's ops bindings, open and ended, read narrow. // `store.all(config.projectId).filter(kind === "ops")` parsed every @@ -6300,7 +6360,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const b = existing.find((x) => x.entityId === key); if (b === undefined) { let created: Binding; - const title = target.kind === "k8s-namespace" ? `Ops watch: ${target.name}` : target.kind === "dependabot" ? `Deps watch: ${target.repo}` : target.kind === "alertmanager" ? `Alertmanager watch: ${target.namespace}` : `Sentry watch: ${target.org}/${target.project}`; + const title = target.kind === "k8s-namespace" ? `Ops watch: ${target.name}` : target.kind === "dependabot" ? `Deps watch: ${target.repo}` : target.kind === "alertmanager" ? `Alertmanager watch: ${target.namespace}` : target.kind === "backlog" ? `Backlog watch: ${target.team}` : `Sentry watch: ${target.org}/${target.project}`; try { created = store.create({ projectId: config.projectId, source: "ops", entityId: key, entityKey: key, url: null, title, kind: "ops", playbook: playbook.name, playbookVersion: playbook.version, parentBindingId: null, phase: "watching", stage: null }); } catch { @@ -6959,6 +7019,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (t.kind === "ticket" && (t.lastSnapshot?.entity.linkedPulls ?? []).some((l) => lc(l.key) === lc(id))) scheduleReconcile(t.id); } } + // BB-334: a Linear issue doorbell also wakes the backlog binding of the + // issue's team, so a new or moved ticket reaches the backlog report + // between nightly passes. The ring carries only the issue id, so the + // team is read from its snapshot. + if (source === "linear") { + const backlogs = store.open().filter((b) => b.kind === "ops" && parseOpsTargetKey(b.entityId)?.kind === "backlog"); + if (backlogs.length > 0) { + const entity = await snapshot(source, id); + const team = entity === null ? null : entity.unit.toUpperCase(); + for (const b of backlogs) { + const target = parseOpsTargetKey(b.entityId); + if (target?.kind === "backlog" && (team === null || target.team === team)) scheduleReconcile(b.id); + } + } + } if (bound !== null && bound.endedAt === null) return; const projects = await stewardedProjects(); if (projects.length === 0) return; @@ -9730,7 +9805,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const overviewPlaybooks = (config: ProjectConfig | null): Array<{ kind: BindingKind; name: string; version: string | null; source: Source | null }> => { if (config === null) return []; const out: Array<{ kind: BindingKind; name: string; version: string | null; source: Source | null }> = []; - for (const kind of KINDS.filter((k) => usesKind(config.file, k, config.role))) { + for (const kind of KINDS.filter((k) => usesKindFor(config.file, k, config.role))) { if (kind !== "ticket") { out.push({ kind, name: playbookNameFor(config.file, kind), version: config.playbooks[kind]?.version ?? null, source: null }); continue; @@ -13090,7 +13165,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const githubTicket = config.ticketPlaybooks.github ?? null; lines.push(`Linear teams: ${config.file.linear.teams.join(", ") || "(none)"}; repos: ${config.repos.join(", ") || "(none)"}${config.file.github.exclude.length > 0 ? ` (excluded: ${config.file.github.exclude.join(", ")})` : ""}; label ${config.file.label}`); lines.push(`roles: ${roleSummary(config)}`); - for (const kind of KINDS.filter((k) => usesKind(config.file, k, config.role))) { + for (const kind of KINDS.filter((k) => usesKindFor(config.file, k, config.role))) { if (kind === "ticket") { // BB-234: name each source's ticket playbook, so a project that // carries both does not hide the GitHub one behind the Linear one. @@ -13179,7 +13254,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await validate("linear", config.file.linear.teams, linearTicket === null ? [] : playbookStates(linearTicket), linearTicket === null ? [] : playbookLabels(linearTicket)); await validate("github", config.repos, githubTicket === null ? [] : githubStateLabels(githubTicket), githubTicket === null ? [] : playbookLabels(githubTicket)); if (filingGithub !== null && priorityLabels.length > 0) await validate("github", [filingGithub], priorityLabels); - if (usesKind(config.file, "ops", config.role)) { + if (usesKindFor(config.file, "ops", config.role)) { const auto = config.role?.ops?.autoAdopt ?? []; const context = config.role?.ops?.context; lines.push(`ops: tickets filed in ${filing === null ? "(no target)" : `${filing.target} (${filing.source})`}${auto.length > 0 ? `, adopted when filed at ${auto.join(", ")}` : ""}`); diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index c5388cd8..01dc40ec 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -1,7 +1,7 @@ import Database from "better-sqlite3"; import { describe, expect, it } from "vitest"; import { z } from "zod"; -import { ACTOR_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, HUDDLE_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS, ASSESSMENT_MIGRATIONS, ASSUMPTION_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, DATED_WAIT_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ENDED_READ_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_PR_MIGRATIONS, LESSON_TIER_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, MIGRATIONS, PULL_REQUESTER_MIGRATIONS, PULL_WATCH_MIGRATIONS, RATIONALE_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, STACK_MIGRATIONS, STACKED_PULLS_MIGRATIONS, VALIDATION_MIGRATIONS, WAKE_RETRY_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, WORKER_CHECK_MIGRATIONS, STANDUP_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, WORKER_PARK_MIGRATIONS, createStore, lessonScope, statusRecordSchema, type Binding } from "./store.js"; +import { ACTOR_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, BACKLOG_LOOK_MIGRATIONS, HUDDLE_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS, ASSESSMENT_MIGRATIONS, ASSUMPTION_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, DATED_WAIT_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ENDED_READ_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_PR_MIGRATIONS, LESSON_TIER_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, MIGRATIONS, PULL_REQUESTER_MIGRATIONS, PULL_WATCH_MIGRATIONS, RATIONALE_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, STACK_MIGRATIONS, STACKED_PULLS_MIGRATIONS, VALIDATION_MIGRATIONS, WAKE_RETRY_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, WORKER_CHECK_MIGRATIONS, STANDUP_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, WORKER_PARK_MIGRATIONS, createStore, lessonScope, statusRecordSchema, type Binding } from "./store.js"; /** MIGRATIONS without the groups appended after the ones these order tests assert. */ const beforeActorMigrations = MIGRATIONS.slice(0, MIGRATIONS.indexOf(ACTOR_MIGRATIONS[0]!)); @@ -741,9 +741,9 @@ describe("the actor rename migration (BB-97)", () => { // after that, BB-307 appended the delegation log after that, BB-312 // appended the completed flag after that, BB-314 appended the // Alertmanager look column after that, BB-327 appended the delegate-set - // and reviewer-request tables after that, and BB-329 appended the - // worker park column after that. - const groups = [WORKER_PARK_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS, PULL_REQUESTER_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_MIGRATIONS, HUDDLE_MIGRATIONS, ENDED_READ_MIGRATIONS, ASSESSMENT_MIGRATIONS, STACKED_PULLS_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, WAKE_RETRY_MIGRATIONS, DATED_WAIT_MIGRATIONS, ASSUMPTION_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, STACK_MIGRATIONS, PULL_WATCH_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, LESSON_PR_MIGRATIONS, ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS]; + // and reviewer-request tables after that, BB-329 appended the worker park + // column after that, and BB-334 appended the backlog look column after that. + const groups = [BACKLOG_LOOK_MIGRATIONS, WORKER_PARK_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS, PULL_REQUESTER_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_MIGRATIONS, HUDDLE_MIGRATIONS, ENDED_READ_MIGRATIONS, ASSESSMENT_MIGRATIONS, STACKED_PULLS_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, WAKE_RETRY_MIGRATIONS, DATED_WAIT_MIGRATIONS, ASSUMPTION_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, STACK_MIGRATIONS, PULL_WATCH_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, LESSON_PR_MIGRATIONS, ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS]; let end = MIGRATIONS.length; for (const group of groups) { expect(MIGRATIONS.slice(end - group.length, end)).toEqual([...group]); @@ -838,10 +838,12 @@ describe("the escalation route rename migration (BB-209)", () => { // its rename to the stand-up table after that, BB-303's scope column // after that, BB-307's delegation log after that, BB-312's completed // flag after that, BB-314's Alertmanager look column after that, - // BB-327's delegate-set and reviewer-request tables after that, and - // BB-329's worker park column after that. - const withoutWorkerPark = MIGRATIONS.slice(0, -WORKER_PARK_MIGRATIONS.length); - expect(MIGRATIONS.slice(-WORKER_PARK_MIGRATIONS.length)).toEqual([...WORKER_PARK_MIGRATIONS]); + // BB-327's delegate-set and reviewer-request tables after that, BB-329's + // worker park column after that, and BB-334's backlog look column after that. + const withoutBacklogLook = MIGRATIONS.slice(0, -BACKLOG_LOOK_MIGRATIONS.length); + expect(MIGRATIONS.slice(-BACKLOG_LOOK_MIGRATIONS.length)).toEqual([...BACKLOG_LOOK_MIGRATIONS]); + const withoutWorkerPark = withoutBacklogLook.slice(0, -WORKER_PARK_MIGRATIONS.length); + expect(withoutBacklogLook.slice(-WORKER_PARK_MIGRATIONS.length)).toEqual([...WORKER_PARK_MIGRATIONS]); const withoutReviewerRequests = withoutWorkerPark.slice(0, -REVIEWER_REQUEST_MIGRATIONS.length); expect(withoutWorkerPark.slice(-REVIEWER_REQUEST_MIGRATIONS.length)).toEqual([...REVIEWER_REQUEST_MIGRATIONS]); const withoutPullRequesters = withoutReviewerRequests.slice(0, -PULL_REQUESTER_MIGRATIONS.length); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 1dd96940..45a26fee 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -13,7 +13,7 @@ import { entitySnapshotSchema, type Source } from "./source-contract.js"; import type { BindingKind, EscalationKind, Stage } from "./config.js"; import { depsLookSchema, type DepsLook } from "./deps.js"; import { deploymentsSchema, type Deployments } from "./deploy.js"; -import { opsLookSchema, type FingerprintRow, type OpsLook } from "./ops.js"; +import { backlogLookSchema, opsLookSchema, type BacklogLook, type FingerprintRow, type OpsLook } from "./ops.js"; import { sentryLookSchema, type SentryLook } from "./sentry.js"; import { alertmanagerLookSchema, type AlertmanagerLook } from "./alertmanager.js"; import type { GuidanceCitation } from "./guidance.js"; @@ -733,7 +733,13 @@ export const STANDUP_COMPLETED_MIGRATIONS = [`ALTER TABLE standups ADD COLUMN co // a store from before the step reads back exactly as before. export const ALERTMANAGER_LOOK_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN alertmanager_look TEXT`]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS, ...ACTOR_MIGRATIONS, ...LESSON_PR_MIGRATIONS, ...REVIEWER_MODEL_MIGRATIONS, ...WAKE_SOURCE_MIGRATIONS, ...SERVER_SETTINGS_MIGRATIONS, ...PULL_WATCH_MIGRATIONS, ...STACK_MIGRATIONS, ...ESCALATION_ROUTE_MIGRATIONS, ...DEPS_DECISION_MIGRATIONS, ...WORKER_STOP_REASON_MIGRATIONS, ...ASSUMPTION_MIGRATIONS, ...DATED_WAIT_MIGRATIONS, ...WAKE_RETRY_MIGRATIONS, ...MERGE_BEHIND_MIGRATIONS, ...RETARGET_PULLS_MIGRATIONS, ...STACKED_PULLS_MIGRATIONS, ...ASSESSMENT_MIGRATIONS, ...ENDED_READ_MIGRATIONS, ...HUDDLE_MIGRATIONS, ...STANDUP_MIGRATIONS, ...STANDUP_BINDING_MIGRATIONS, ...STANDUP_DELEGATION_MIGRATIONS, ...STANDUP_COMPLETED_MIGRATIONS, ...ALERTMANAGER_LOOK_MIGRATIONS, ...PULL_REQUESTER_MIGRATIONS, ...REVIEWER_REQUEST_MIGRATIONS, ...WORKER_PARK_MIGRATIONS]; +// BB-334: a backlog binding's last read of its Linear team's whole open backlog. +// Additive and nullable: an old row reads as no look, and a pre-migration build +// never reads the column. It is appended after every group already shipped, +// including BB-329's worker park column, so no recorded index moves. +export const BACKLOG_LOOK_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN backlog_look TEXT`]; + +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS, ...ACTOR_MIGRATIONS, ...LESSON_PR_MIGRATIONS, ...REVIEWER_MODEL_MIGRATIONS, ...WAKE_SOURCE_MIGRATIONS, ...SERVER_SETTINGS_MIGRATIONS, ...PULL_WATCH_MIGRATIONS, ...STACK_MIGRATIONS, ...ESCALATION_ROUTE_MIGRATIONS, ...DEPS_DECISION_MIGRATIONS, ...WORKER_STOP_REASON_MIGRATIONS, ...ASSUMPTION_MIGRATIONS, ...DATED_WAIT_MIGRATIONS, ...WAKE_RETRY_MIGRATIONS, ...MERGE_BEHIND_MIGRATIONS, ...RETARGET_PULLS_MIGRATIONS, ...STACKED_PULLS_MIGRATIONS, ...ASSESSMENT_MIGRATIONS, ...ENDED_READ_MIGRATIONS, ...HUDDLE_MIGRATIONS, ...STANDUP_MIGRATIONS, ...STANDUP_BINDING_MIGRATIONS, ...STANDUP_DELEGATION_MIGRATIONS, ...STANDUP_COMPLETED_MIGRATIONS, ...ALERTMANAGER_LOOK_MIGRATIONS, ...PULL_REQUESTER_MIGRATIONS, ...REVIEWER_REQUEST_MIGRATIONS, ...WORKER_PARK_MIGRATIONS, ...BACKLOG_LOOK_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -965,6 +971,8 @@ export type Binding = { sentryLook: SentryLook | null; /** An Alertmanager namespace binding's last look; null for every other kind. */ alertmanagerLook: AlertmanagerLook | null; + /** A backlog binding's last read of its Linear team's whole open backlog; null for every other kind. */ + backlogLook: BacklogLook | null; /** Per-pull-request deployment state, keyed by the pull request's key (BB-53). Empty with no deployment target. */ deployments: Deployments; /** When the binding became idle in an active stage, or null (BB-83). */ @@ -1060,6 +1068,7 @@ function rowToBinding(r: BindingRow): Binding { depsLook: json(depsLookSchema.nullable(), str("deps_look"), null), sentryLook: json(sentryLookSchema.nullable(), str("sentry_look"), null), alertmanagerLook: json(alertmanagerLookSchema.nullable(), str("alertmanager_look"), null), + backlogLook: json(backlogLookSchema.nullable(), str("backlog_look"), null), deployments: json(deploymentsSchema, str("deployments"), {}), idleSince: num("idle_since"), idleWokenAt: num("idle_woken_at"), @@ -1133,6 +1142,7 @@ const COLUMNS = { depsLook: "deps_look", sentryLook: "sentry_look", alertmanagerLook: "alertmanager_look", + backlogLook: "backlog_look", deployments: "deployments", idleSince: "idle_since", idleWokenAt: "idle_woken_at", diff --git a/plugins/stewards/test-world.ts b/plugins/stewards/test-world.ts index d433cb52..d21340f2 100644 --- a/plugins/stewards/test-world.ts +++ b/plugins/stewards/test-world.ts @@ -32,6 +32,11 @@ export function world() { /** The fake linear dedup search: unsupported (github-style decline) or an error, for BB-136. */ let searchUnsupported = false; let searchError: string | null = null; + /** The fake `sourceBacklog` read: issues, an unsupported capability, an error, or a truncated read (BB-334). */ + let backlog: Array> = []; + let backlogUnsupported = false; + let backlogError: string | null = null; + let backlogTruncated = false; /** The login `sourceValidate` reports, per source; tests override one to make it unreadable (BB-105). */ const viewers: Partial> = {}; /** Labels a fake source reports missing for a unit, by `${source}:${lowercased unit}` (BB-235). */ @@ -301,6 +306,13 @@ export function world() { unsupported: false, errors: [], }; + } else if (args.method === "sourceBacklog") { + const team = String(input.team).toUpperCase(); + out = backlogUnsupported + ? { issues: [], unsupported: true, truncated: false, errors: [] } + : backlogError !== null + ? { issues: [], unsupported: false, truncated: false, errors: [backlogError] } + : { issues: backlog.filter((i) => String(i.unit).toUpperCase() === team), unsupported: false, truncated: backlogTruncated, errors: [] }; } else if (args.method === "sourceValidate") { // The real plugins validate the input; an empty label was once accepted here and rejected there. sourceContract.sourceValidate.input.parse(input); @@ -605,7 +617,7 @@ export function world() { }, }; let now = Date.parse("2026-10-14T15:00:00Z"); - return { files, writes, writtenContent, fileContents, repos, primary, entities, projectList, dependabotAlerts, dependabotGraphEmpty, sourceDeployments, sourceFiles, sourceCommits, sourceRuns, sourceCompares, labelEnsureCalls, labelsEnsured, labelEnsureFailures, setLabelEnsureUnavailable: (value: boolean) => { labelEnsureUnavailable = value; }, setPushUnavailable: (value: boolean) => { pushUnavailable = value; }, setLabelEnsureThrow: (value: string | null) => { labelEnsureThrow = value; }, setLayout: (value: "primary" | "directory") => { layout = value; primary = value === "directory" ? null : { dir: "bb", url: "https://github.com/acme/bb.git" }; }, viewers, setLinearMine: (teams: Array<{ unit: string; name: string }>) => { linearMine = teams; }, setMissingStates: (source: "linear" | "github", unit: string, states: string[]) => { missingStates.set(`${source}:${unit.toLowerCase()}`, states); }, setMissingLabel: (source: "linear" | "github", unit: string, labels: string[]) => { missingLabels.set(`${source}:${unit.toLowerCase()}`, labels); }, rpcCalls, githubTrees, githubBranchProtection, githubLabels, setSnapshotError: (id: string, fail: boolean) => { if (fail) snapshotErrors.add(id); else snapshotErrors.delete(id); }, setSearchUnsupported: (value: boolean) => { searchUnsupported = value; }, setSearchError: (value: string | null) => { searchError = value; }, setCreatePullError: (value: string | null) => { createPullError = value; }, setMergePullError: (value: string | null) => { mergePullError = value; }, setSpawnError: (value: string | null) => { spawnError = value; }, setSpawnDelayMs: (value: number) => { spawnDelayMs = value; }, setMoveHeadOnMerge: (value: boolean) => { moveHeadOnMerge = value; }, setPullDetailsError: (value: string | null) => { pullDetailsError = value; }, setRetryConflict: (value: boolean) => { retryConflict = value; }, setRetryQueued: (value: boolean) => { retryQueued = value; }, threads, deletes, sections, usage, metadata, spawns, sends, retries, retryEvents, queuedDeletes, userTurns, githubComments, githubReviews, githubReviewerRequests, githubMerges, githubPulls, githubClosedPulls, githubDefaultBranches, githubBranches, githubFiles, githubFileContents, githubDispatches, setMergeDispatchError: (value: string | null) => { mergeDispatchError = value; }, github, sdk, uiPreferences, uiPreferencesWrites, realtimeOpens, setVoiceBaseUrl: (value: string) => { voiceBaseUrl = value; }, setVoiceServicePresent: (value: boolean) => { voiceServicePresent = value; }, setVoiceServiceReady: (value: boolean, message?: string) => { voiceServiceReady = value; if (message !== undefined) voiceServiceMessage = message; }, setVoiceSettingsThrow: (value: string | null) => { voiceSettingsThrow = value; }, setVoiceRealtimeRefusal: (value: string | null) => { voiceRealtimeRefusal = value; }, now: () => now, advance: (ms: number) => (now += ms) }; + return { files, writes, writtenContent, fileContents, repos, primary, entities, projectList, dependabotAlerts, dependabotGraphEmpty, sourceDeployments, sourceFiles, sourceCommits, sourceRuns, sourceCompares, labelEnsureCalls, labelsEnsured, labelEnsureFailures, setLabelEnsureUnavailable: (value: boolean) => { labelEnsureUnavailable = value; }, setPushUnavailable: (value: boolean) => { pushUnavailable = value; }, setLabelEnsureThrow: (value: string | null) => { labelEnsureThrow = value; }, setLayout: (value: "primary" | "directory") => { layout = value; primary = value === "directory" ? null : { dir: "bb", url: "https://github.com/acme/bb.git" }; }, viewers, setLinearMine: (teams: Array<{ unit: string; name: string }>) => { linearMine = teams; }, setMissingStates: (source: "linear" | "github", unit: string, states: string[]) => { missingStates.set(`${source}:${unit.toLowerCase()}`, states); }, setMissingLabel: (source: "linear" | "github", unit: string, labels: string[]) => { missingLabels.set(`${source}:${unit.toLowerCase()}`, labels); }, rpcCalls, githubTrees, githubBranchProtection, githubLabels, setSnapshotError: (id: string, fail: boolean) => { if (fail) snapshotErrors.add(id); else snapshotErrors.delete(id); }, setSearchUnsupported: (value: boolean) => { searchUnsupported = value; }, setSearchError: (value: string | null) => { searchError = value; }, setCreatePullError: (value: string | null) => { createPullError = value; }, setMergePullError: (value: string | null) => { mergePullError = value; }, setSpawnError: (value: string | null) => { spawnError = value; }, setSpawnDelayMs: (value: number) => { spawnDelayMs = value; }, setMoveHeadOnMerge: (value: boolean) => { moveHeadOnMerge = value; }, setPullDetailsError: (value: string | null) => { pullDetailsError = value; }, setRetryConflict: (value: boolean) => { retryConflict = value; }, setRetryQueued: (value: boolean) => { retryQueued = value; }, threads, deletes, sections, usage, metadata, spawns, sends, retries, retryEvents, queuedDeletes, userTurns, githubComments, githubReviews, githubReviewerRequests, githubMerges, githubPulls, githubClosedPulls, githubDefaultBranches, githubBranches, githubFiles, githubFileContents, githubDispatches, setMergeDispatchError: (value: string | null) => { mergeDispatchError = value; }, github, sdk, uiPreferences, uiPreferencesWrites, realtimeOpens, setVoiceBaseUrl: (value: string) => { voiceBaseUrl = value; }, setVoiceServicePresent: (value: boolean) => { voiceServicePresent = value; }, setVoiceServiceReady: (value: boolean, message?: string) => { voiceServiceReady = value; if (message !== undefined) voiceServiceMessage = message; }, setVoiceSettingsThrow: (value: string | null) => { voiceSettingsThrow = value; }, setVoiceRealtimeRefusal: (value: string | null) => { voiceRealtimeRefusal = value; }, now: () => now, advance: (ms: number) => (now += ms), backlog, setBacklog: (issues: Array>) => { backlog = issues; }, setBacklogUnsupported: (value: boolean) => { backlogUnsupported = value; }, setBacklogError: (value: string | null) => { backlogError = value; }, setBacklogTruncated: (value: boolean) => { backlogTruncated = value; } }; } export async function setup(extra: Partial = {}, settings: Record = {}, seedProvider?: string | null | "fail-list" | "fail-set", seedNavigation?: string | null | "fail-list" | "fail-set") {