diff --git a/plugins/stewards/migrations.snapshot.json b/plugins/stewards/migrations.snapshot.json index 5c6fe0d7..f4acd1a1 100644 --- a/plugins/stewards/migrations.snapshot.json +++ b/plugins/stewards/migrations.snapshot.json @@ -136,5 +136,6 @@ "c7dcc1c8ee819162947a9965a7fb0cb7129900a4d68f5f7f91a99184a225dea9", "ad2a7b244faee5792ca77b1f36cd80488de8f787360d03f1569e60c869845beb", "b268ed66797e2953f8b175fa1cdf506531a2fc5e30c52ef43480d81b9efb7c1b", - "c1377801bd4fe44be9cc5fc10c5aca75c9455359b3d5d646d0fb23318a032124" + "c1377801bd4fe44be9cc5fc10c5aca75c9455359b3d5d646d0fb23318a032124", + "d856f2127e2c5788a01c5ca80b216d1dc9be2a67bb273ad9082bbc69a279ce9a" ] diff --git a/plugins/stewards/nightly.test.ts b/plugins/stewards/nightly.test.ts index a473215b..5cc8b004 100644 --- a/plugins/stewards/nightly.test.ts +++ b/plugins/stewards/nightly.test.ts @@ -1,8 +1,10 @@ import Database from "better-sqlite3"; import { describe, expect, it } from "vitest"; -import { createBriefing, checkFindingFingerprint, freshCheckFindings, localParts, nightOf, nightlyDue, stillNight, toDigestRecords } from "./nightly.js"; +import { backlogDigest, checkFindingFingerprint, createBriefing, duplicateBacklog, freshCheckFindings, localParts, nightOf, nightlyDue, stillNight, toDigestRecords } from "./nightly.js"; import { MIGRATIONS, createStore } from "./store.js"; import { formatRecords, type DigestRecords } from "./wake.js"; +import type { BacklogLook } from "./ops.js"; +import type { BacklogIssue } from "./source-contract.js"; const NY = { at: "01:00", until: "02:45", timezone: "America/New_York" }; // 2026-10-14 05:30Z is 01:30 in New York (EDT, UTC-4). @@ -205,3 +207,105 @@ describe("check findings deduplicated by fingerprint (BB-328)", () => { expect(freshCheckFindings([problem("ENG is not visible")], store.checkFindings("p1")).fresh).toHaveLength(1); }); }); + +// BB-334: the backlog report is pure — the stored look plus the previous +// digest's snapshot in, the digest's metrics and lines out. +describe("the backlog report (BB-334)", () => { + const NOW = at("2026-10-14T15:00:00Z"); + const issue = (over: Partial = {}): BacklogIssue => ({ + id: "i1", + 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, + }); + const look = (issues: BacklogIssue[], over: Partial = {}): BacklogLook => ({ at: NOW, target: "backlog/BB", team: "BB", error: null, issues, unsupported: false, truncated: false, ...over }); + const emptyRecords = (backlog: DigestRecords["backlog"]): DigestRecords => ({ previous: null, since: NOW, moved: [], ended: [], answered: [], withUser: [], stuck: [], noWakeSource: [], stall: [], held: [], backlog }); + + it("counts size, age buckets and inflow/outflow against the previous digest's snapshot", () => { + const issues = [ + issue({ id: "a", key: "BB-1", createdAt: "2026-10-13T00:00:00Z" }), + issue({ id: "b", key: "BB-2", createdAt: "2026-10-01T00:00:00Z" }), + issue({ id: "c", key: "BB-3", createdAt: "2026-08-01T00:00:00Z" }), + issue({ id: "d", key: "BB-4", createdAt: "2026-01-01T00:00:00Z" }), + ]; + const report = backlogDigest(look(issues), { at: NOW - 86_400_000, ids: ["a", "gone"] }, { staleDays: 14 }, NOW); + expect(report.size).toBe(4); + expect(report.ages).toEqual([ + { label: "<1w", count: 1 }, + { label: "1-4w", count: 1 }, + { label: "1-3m", count: 1 }, + { label: ">3m", count: 1 }, + ]); + expect(report.inflow).toBe(3); + expect(report.outflow).toBe(1); + expect(report.since).toBe(NOW - 86_400_000); + }); + + it("reports the first digest with no inflow or outflow", () => { + expect(backlogDigest(look([issue()]), null, { staleDays: 14 }, NOW)).toMatchObject({ since: null, inflow: 0, outflow: 0 }); + }); + + it("flags likely duplicates by normalised title, and never merges them", () => { + const groups = duplicateBacklog([issue({ id: "a", key: "BB-1", title: "Fix the login page" }), issue({ id: "b", key: "BB-2", title: "Fix login page!" }), issue({ id: "c", key: "BB-3", title: "Add SSO" })]); + expect(groups).toEqual([{ keys: ["BB-1", "BB-2"], title: "Fix the login page" }]); + }); + + it("lists stale tickets oldest first and proposes the next three with reasoning", () => { + const issues = [ + issue({ id: "a", key: "BB-1", priority: "Low", createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-10-01T00:00:00Z" }), + issue({ id: "b", key: "BB-2", priority: "Urgent", createdAt: "2026-10-10T00:00:00Z", updatedAt: "2026-09-29T00:00:00Z", estimate: 3 }), + issue({ id: "c", key: "BB-3", priority: "High", createdAt: "2026-09-01T00:00:00Z", updatedAt: "2026-09-01T00:00:00Z" }), + issue({ id: "d", key: "BB-4", priority: "Medium", createdAt: "2026-08-01T00:00:00Z", updatedAt: "2026-08-01T00:00:00Z" }), + ]; + const report = backlogDigest(look(issues), null, { staleDays: 14 }, NOW); + expect(report.stale).toEqual([ + { key: "BB-4", days: 74 }, + { key: "BB-3", days: 43 }, + { key: "BB-2", days: 15 }, + ]); + expect(report.next.map((n) => n.key)).toEqual(["BB-2", "BB-3", "BB-4"]); + expect(report.next[0]!.reason).toBe("Urgent, 4d old, estimate 3"); + }); + + it("ranks Linear's priority label ignoring case and leaves a started ticket out of the proposal", () => { + const issues = [ + issue({ id: "a", key: "BB-1", priority: "Medium", createdAt: "2026-01-01T00:00:00Z" }), + issue({ id: "b", key: "BB-2", priority: "Urgent", createdAt: "2026-10-13T00:00:00Z", stateType: "started" }), + issue({ id: "c", key: "BB-3", priority: "No priority", createdAt: "2026-09-01T00:00:00Z" }), + ]; + const report = backlogDigest(look(issues), null, { staleDays: 14 }, NOW); + // The started ticket is proposed never, and the medium outranks the unranked one. + expect(report.next.map((n) => n.key)).toEqual(["BB-1", "BB-3"]); + expect(report.next[0]!.reason).toMatch(/^Medium, /u); + // It still counts in size and ages. + expect(report.size).toBe(3); + expect(report.ages.reduce((n, a) => n + a.count, 0)).toBe(3); + }); + + it("renders the section beside the record, and omits it when no role carries a backlog", () => { + const report = backlogDigest(look([issue({ title: "Fix login" })]), null, { staleDays: 14 }, NOW); + const withBacklog = formatRecords(emptyRecords([report]), []).join("\n"); + expect(withBacklog).toContain("### Backlog"); + expect(withBacklog).toContain("- BB: 1 open; age <1w 0, 1-4w 1, 1-3m 0, >3m 0; first digest"); + expect(withBacklog).toContain("- Proposed next: BB-1 (no priority, 13d old)"); + expect(formatRecords(emptyRecords([]), []).join("\n")).not.toContain("### Backlog"); + expect(formatRecords(emptyRecords(undefined), []).join("\n")).not.toContain("### Backlog"); + }); + + it("shows a failed read as one problem line, never an empty backlog", () => { + const failed = backlogDigest(look([], { error: "Linear rate limited the read" }), null, { staleDays: 14 }, NOW); + const text = formatRecords(emptyRecords([failed]), []).join("\n"); + expect(text).toContain("### Backlog"); + expect(text).toContain("- BB: unavailable — Linear rate limited the read"); + expect(text).not.toContain("0 open"); + }); +}); diff --git a/plugins/stewards/nightly.ts b/plugins/stewards/nightly.ts index 25b1a0e3..1d908cfe 100644 --- a/plugins/stewards/nightly.ts +++ b/plugins/stewards/nightly.ts @@ -13,6 +13,8 @@ // the nightly's rendering byte-identical while the briefing carries the four // sections the stand-up needs. import type { Assumption, Binding, Escalation, Need, Question, Store } from "./store.js"; +import type { BacklogIssue } from "./source-contract.js"; +import type { BacklogLook, BacklogSnapshot } from "./ops.js"; import type { DigestRecords } from "./wake.js"; import { createHash } from "node:crypto"; import type { CheckFinding } from "./template-stamp.js"; @@ -204,3 +206,170 @@ export function toDigestRecords(briefing: Briefing): DigestRecords { held: briefing.stuck.held, }; } + +// ---- the backlog report (BB-334) --------------------------------------------------- + +/** + * The age buckets the backlog report uses, oldest last. A ticket is counted in + * the first bucket whose `maxDays` its age is under, so the buckets partition + * every ticket with a readable `createdAt`. + */ +export const BACKLOG_AGE_BUCKETS = [ + { label: "<1w", maxDays: 7 }, + { label: "1-4w", maxDays: 30 }, + { label: "1-3m", maxDays: 90 }, + { label: ">3m", maxDays: Number.POSITIVE_INFINITY }, +] as const; + +export type BacklogAgeBucket = { label: string; count: number }; +/** A group of tickets whose normalised titles are similar; flagged only, never merged. */ +export type BacklogDuplicate = { keys: string[]; title: string }; +export type BacklogStale = { key: string; days: number }; +export type BacklogNext = { key: string; reason: string }; + +/** + * One team's backlog report, computed from a stored read and the previous + * digest's snapshot. It is pure: the caller passes the clock, and nothing here + * reads the store or a source. An `error` report carries no metrics, so a + * failed read is a problem line rather than an empty backlog. + */ +export type BacklogDigest = { + team: string; + error: string | null; + truncated: boolean; + size: number; + ages: BacklogAgeBucket[]; + /** The previous digest's time, or null before the first report. */ + since: number | null; + /** Issue ids present now and not at the previous digest; 0 before the first. */ + inflow: number; + /** Issue ids present at the previous digest and not now; 0 before the first. */ + outflow: number; + duplicates: BacklogDuplicate[]; + stale: BacklogStale[]; + next: BacklogNext[]; +}; + +const daysSince = (from: string | null, now: number): number | null => { + if (from === null) return null; + const t = Date.parse(from); + return Number.isNaN(t) ? null : Math.max(0, Math.floor((now - t) / 86_400_000)); +}; + +/** A title folded for duplicate detection: lower case, punctuation to spaces, collapsed. */ +export const normalizeBacklogTitle = (title: string | null): string => + (title ?? "") + .toLowerCase() + .replace(/[^a-z0-9]+/gu, " ") + .trim() + .replace(/\s+/gu, " "); + +/** The Jaccard similarity of two normalised titles' word sets; 0 when either is empty. */ +export function titleSimilarity(a: string, b: string): number { + if (a === "" || b === "") return 0; + if (a === b) return 1; + const left = new Set(a.split(" ").filter((t) => t !== "")); + const right = new Set(b.split(" ").filter((t) => t !== "")); + let shared = 0; + for (const token of left) if (right.has(token)) shared += 1; + return shared / (left.size + right.size - shared); +} + +/** Titles at or above this similarity are flagged as likely duplicates. */ +export const BACKLOG_DUPLICATE_SIMILARITY = 0.6; + +/** Groups of tickets whose normalised titles are similar (BB-334). Flagged only, never merged. */ +export function duplicateBacklog(issues: readonly BacklogIssue[]): BacklogDuplicate[] { + const parent = new Map(issues.map((i) => [i.id, i.id])); + const find = (x: string): string => { + let root = x; + while (parent.get(root) !== root) root = parent.get(root)!; + while (parent.get(x) !== root) { + const next = parent.get(x)!; + parent.set(x, root); + x = next; + } + return root; + }; + const union = (a: string, b: string): void => { + const ra = find(a); + const rb = find(b); + if (ra !== rb) parent.set(ra, rb); + }; + const normalised = issues.map((i) => ({ id: i.id, title: normalizeBacklogTitle(i.title) })); + for (let i = 0; i < normalised.length; i += 1) { + for (let j = i + 1; j < normalised.length; j += 1) { + if (titleSimilarity(normalised[i]!.title, normalised[j]!.title) >= BACKLOG_DUPLICATE_SIMILARITY) union(normalised[i]!.id, normalised[j]!.id); + } + } + const byRoot = new Map(); + for (const issue of issues) { + const root = find(issue.id); + byRoot.set(root, [...(byRoot.get(root) ?? []), issue]); + } + return [...byRoot.values()] + .filter((group) => group.length > 1) + .map((group) => ({ keys: group.map((i) => i.key).sort(), title: group[0]!.title ?? "" })); +} + +/** Tickets whose `updatedAt` is at least `staleDays` old, oldest first. */ +export function staleBacklog(issues: readonly BacklogIssue[], staleDays: number, now: number): BacklogStale[] { + return issues + .map((issue) => ({ key: issue.key, days: daysSince(issue.updatedAt, now) })) + .filter((x): x is { key: string; days: number } => x.days !== null && x.days >= staleDays) + .sort((a, b) => b.days - a.days || a.key.localeCompare(b.key)); +} + +const BACKLOG_PRIORITY_RANK: Record = { urgent: 0, high: 1, medium: 2, low: 3 }; + +/** + * The next tickets to work, by priority then age, each with one line of + * reasoning. A ticket already `started` is being built, so it is never + * proposed as next; it still counts in size, ages and stale. + */ +export function nextBacklog(issues: readonly BacklogIssue[], now: number, limit = 3): BacklogNext[] { + const created = (i: BacklogIssue): number => { + const t = i.createdAt === null ? Number.NaN : Date.parse(i.createdAt); + return Number.isNaN(t) ? Number.POSITIVE_INFINITY : t; + }; + // The source sends Linear's label unchanged ("Urgent", "High", …, "No priority"), so match ignoring case; anything else is unranked. + const rank = (i: BacklogIssue): number => BACKLOG_PRIORITY_RANK[(i.priority ?? "").toLowerCase()] ?? 4; + return [...issues] + .filter((i) => (i.stateType ?? "").toLowerCase() !== "started") + .sort((a, b) => rank(a) - rank(b) || created(a) - created(b) || a.key.localeCompare(b.key)) + .slice(0, limit) + .map((issue) => { + const age = daysSince(issue.createdAt, now); + const reason = [issue.priority ?? "no priority", age === null ? "age unknown" : `${age}d old`, ...(issue.estimate === null ? [] : [`estimate ${issue.estimate}`])].join(", "); + return { key: issue.key, reason }; + }); +} + +/** + * One team's report from its stored look and the previous digest's snapshot. + * `previous` null is the first digest: inflow and outflow are 0 and `since` is + * null. The read's `error` is carried through, so the renderer shows a problem + * line and never an empty backlog. + */ +export function backlogDigest(look: BacklogLook, previous: BacklogSnapshot | null, opts: { staleDays: number }, now: number): BacklogDigest { + const issues = look.issues; + const previousIds = new Set(previous?.ids ?? []); + const currentIds = new Set(issues.map((i) => i.id)); + const ages = BACKLOG_AGE_BUCKETS.map((bucket, index) => { + const min = index === 0 ? 0 : BACKLOG_AGE_BUCKETS[index - 1]!.maxDays; + return { label: bucket.label, count: issues.filter((i) => { const days = daysSince(i.createdAt, now); return days !== null && days >= min && days < bucket.maxDays; }).length }; + }); + return { + team: look.team, + error: look.error, + truncated: look.truncated, + size: issues.length, + ages, + since: previous?.at ?? null, + inflow: previous === null ? 0 : [...currentIds].filter((id) => !previousIds.has(id)).length, + outflow: previous === null ? 0 : [...previousIds].filter((id) => !currentIds.has(id)).length, + duplicates: duplicateBacklog(issues), + stale: staleBacklog(issues, opts.staleDays, now), + next: nextBacklog(issues, now), + }; +} diff --git a/plugins/stewards/ops.ts b/plugins/stewards/ops.ts index 79756a62..e911d1ce 100644 --- a/plugins/stewards/ops.ts +++ b/plugins/stewards/ops.ts @@ -364,6 +364,15 @@ export const backlogLookSchema = z.object({ }); export type BacklogLook = z.infer; +/** + * The backlog as of the last digest that reported it (BB-334): the issue ids + * the next digest compares against for inflow and outflow. `at` is when that + * digest was sent. It is written only when a digest really went out, so a + * failed send compares against the same snapshot again. + */ +export const backlogSnapshotSchema = z.object({ at: z.number(), ids: z.array(z.string()) }); +export type BacklogSnapshot = 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 57af4436..358b0bba 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -12055,6 +12055,48 @@ describe("the backlog watch (BB-334)", () => { 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"]); }); + + it("puts the backlog in the project steward's digest and snapshots the ids after the send (BB-334)", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["BB"] }, backlog: { staleDays: 14 } }); + t.files[ROLES_FILE] = JSON.stringify({ version: 2, roles: { backlog: { backlog: { team: "BB" } } }, holders: { jane: ["backlog", "projectSteward"] } }); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + t.setBacklog([backlogIssue({ id: "i1", key: "BB-1" })]); + await t.hooks.sweep(); + await t.flush(); + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + const project = t.spawns[0]!.id; + const digest = t.sends.filter((s) => s.threadId === project).at(-1)!.text; + expect(digest).toContain("### Backlog"); + expect(digest).toContain("- BB: 1 open"); + // The snapshot is recorded once the digest really went out, so the next + // digest can count inflow and outflow. + const binding = t.hooks.store.byEntity("ops", "backlog/BB")!; + expect(t.hooks.store.binding(binding.id)!.backlogSnapshot).toMatchObject({ ids: ["i1"] }); + }); + + it("snapshots the ids the digest reported, not a look that moved before the send (BB-334)", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["BB"] }, backlog: { staleDays: 14 } }); + t.files[ROLES_FILE] = JSON.stringify({ version: 2, roles: { backlog: { backlog: { team: "BB" } } }, holders: { jane: ["backlog", "projectSteward"] } }); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + t.setBacklog([backlogIssue({ id: "i1", key: "BB-1" })]); + await t.hooks.sweep(); + await t.flush(); + const binding = t.hooks.store.byEntity("ops", "backlog/BB")!; + // A sweep stores a newer look while the digest is being assembled and sent. + const originalSend = t.sdk.threads.send; + t.harness.sdk.stub("threads.send", async (args: { threadId: string; input: Array<{ text: string }> }) => { + const current = t.hooks.store.binding(binding.id)!; + t.hooks.store.patch(binding.id, { backlogLook: { ...current.backlogLook!, issues: [...current.backlogLook!.issues, backlogIssue({ id: "i2", key: "BB-2" })] } }); + return originalSend(args); + }); + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + // The snapshot is the report's ids, so BB-2 is not silently counted as already seen. + expect(t.hooks.store.binding(binding.id)!.backlogSnapshot).toMatchObject({ ids: ["i1"] }); + }); }); describe("the dotenv a requester imports", () => { diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 58fc61c6..a196a18f 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -96,7 +96,7 @@ import { hostContract } from "./host-contract.js"; import { MULTI_REPO_ENVIRONMENT_PROVIDER_ID, MULTI_REPO_PLUGIN_ID, multiRepoEnvironmentFlags, multiRepoFreshEnvironment, multiRepoSource, nativeSource, projectSourceLabel, sourceRpcMissing, type FreshEnvironment, type NativeGitRead, type ProjectSource } from "./project-source.js"; import { KUBECTL_VERBS, createKubectlReader, kubectlRefusal, type KubectlResult, type OpsAccess, type OpsReader } from "./kubectl.js"; import { HOOKS_URL_ENV, createHooksLoop, type Lease, type Rejection } from "./hooks-client.js"; -import { createBriefing, freshCheckFindings, nightlyDue, stillNight, toDigestRecords } from "./nightly.js"; +import { backlogDigest, createBriefing, freshCheckFindings, nightlyDue, stillNight, toDigestRecords, type BacklogDigest } 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 BacklogLook, type BacklogTarget, type DependabotTarget, type FingerprintRow, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; @@ -7117,6 +7117,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const threadId = await ensureProjectSteward(config); if (threadId === null) return; const records = opts.digestDue ? digestRecords(projectId) : undefined; + // BB-334: one backlog report per backlog binding, from its stored look + // and the previous digest's snapshot. Empty without a backlog role. The + // ids are the ones the report was computed from, written only after the + // send, so a look that moves in between does not move the snapshot. + const backlog = records === undefined ? null : backlogReports(projectId, config); + if (records !== undefined && backlog !== null) records.backlog = backlog.digests; // BB-328: the live-check findings new or changed since the last nightly // pass ride in the digest record, so the project steward reads them once. if (records !== undefined && opts.checkFindings !== undefined && opts.checkFindings.length > 0) records.checkFindings = opts.checkFindings; @@ -7168,7 +7174,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // BB-328: let the caller record a finding only once its digest really // went out, so a failed send says it on the next pass. opts.onSent?.(); - if (opts.digestDue) store.clearProjectNotes(projectId); + if (opts.digestDue) { + store.clearProjectNotes(projectId); + if (backlog !== null) recordBacklogSnapshots(backlog.snapshots, now()); + } } } @@ -7179,6 +7188,31 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return toDigestRecords(briefing(projectId, since)); } + /** The backlog reports for a digest, and the issue ids each was computed from (BB-334). */ + function backlogReports(projectId: string, config: ProjectConfig): { digests: BacklogDigest[]; snapshots: Array<{ bindingId: string; ids: string[] }> } { + const staleDays = config.file.backlog?.staleDays ?? 14; + const at = now(); + const digests: BacklogDigest[] = []; + const snapshots: Array<{ bindingId: string; ids: string[] }> = []; + for (const b of store.open(projectId)) { + if (b.kind !== "ops" || b.backlogLook === null || parseOpsTargetKey(b.entityId)?.kind !== "backlog") continue; + digests.push(backlogDigest(b.backlogLook, b.backlogSnapshot, { staleDays }, at)); + // A failed read keeps the previous snapshot: the next digest still + // compares against the last good one. + if (b.backlogLook.error === null) snapshots.push({ bindingId: b.id, ids: b.backlogLook.issues.map((i) => i.id) }); + } + return { digests, snapshots }; + } + + /** Record the ids the digest reported, once it really went out (BB-334). */ + function recordBacklogSnapshots(snapshots: ReadonlyArray<{ bindingId: string; ids: string[] }>, at: number): void { + for (const { bindingId, ids } of snapshots) { + const b = store.binding(bindingId); + if (b === null || b.endedAt !== null) continue; + store.patch(b.id, { backlogSnapshot: { at, ids } }); + } + } + // ---- lessons ------------------------------------------------------------------------------- // // A lesson is a general rule the project steward drew from an escalation diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index c2f606d6..afb2ebf7 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, BACKLOG_LOOK_MIGRATIONS, CHECK_FINDING_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, BACKLOG_SNAPSHOT_MIGRATIONS, CHECK_FINDING_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]!)); @@ -743,8 +743,9 @@ describe("the actor rename migration (BB-97)", () => { // Alertmanager look column after that, BB-327 appended the delegate-set // and reviewer-request tables after that, BB-329 appended the worker park // column after that, BB-334 appended the backlog look column after that, - // and BB-328 appended the check-findings table after that. - const groups = [CHECK_FINDING_MIGRATIONS, 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]; + // and BB-328 appended the check-findings table after that. BB-334's + // snapshot column is the newest. + const groups = [BACKLOG_SNAPSHOT_MIGRATIONS, CHECK_FINDING_MIGRATIONS, 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]); @@ -841,9 +842,12 @@ describe("the escalation route rename migration (BB-209)", () => { // flag after that, BB-314's Alertmanager look column after that, // BB-327's delegate-set and reviewer-request tables after that, BB-329's // worker park column after that, BB-334's backlog look column after that, - // and BB-328's check-findings table after that. - const withoutCheckFindings = MIGRATIONS.slice(0, -CHECK_FINDING_MIGRATIONS.length); - expect(MIGRATIONS.slice(-CHECK_FINDING_MIGRATIONS.length)).toEqual([...CHECK_FINDING_MIGRATIONS]); + // BB-328's check-findings table after that, and BB-334's backlog snapshot + // column last. + const withoutBacklogSnapshot = MIGRATIONS.slice(0, -BACKLOG_SNAPSHOT_MIGRATIONS.length); + expect(MIGRATIONS.slice(-BACKLOG_SNAPSHOT_MIGRATIONS.length)).toEqual([...BACKLOG_SNAPSHOT_MIGRATIONS]); + const withoutCheckFindings = withoutBacklogSnapshot.slice(0, -CHECK_FINDING_MIGRATIONS.length); + expect(withoutBacklogSnapshot.slice(-CHECK_FINDING_MIGRATIONS.length)).toEqual([...CHECK_FINDING_MIGRATIONS]); const withoutBacklogLook = withoutCheckFindings.slice(0, -BACKLOG_LOOK_MIGRATIONS.length); expect(withoutCheckFindings.slice(-BACKLOG_LOOK_MIGRATIONS.length)).toEqual([...BACKLOG_LOOK_MIGRATIONS]); const withoutWorkerPark = withoutBacklogLook.slice(0, -WORKER_PARK_MIGRATIONS.length); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index feea41c3..7b16a798 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 { backlogLookSchema, opsLookSchema, type BacklogLook, type FingerprintRow, type OpsLook } from "./ops.js"; +import { backlogLookSchema, backlogSnapshotSchema, opsLookSchema, type BacklogLook, type BacklogSnapshot, 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"; @@ -756,7 +756,13 @@ export const CHECK_FINDING_MIGRATIONS = [ )`, ]; -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, ...CHECK_FINDING_MIGRATIONS]; +// BB-334: the issue ids as of the last digest that reported the backlog, so +// the next digest can count inflow and outflow. Additive and nullable: an old +// row reads as no snapshot (the first digest reports no inflow or outflow). +// Appended after BB-328's check-findings table, the last shipped group. +export const BACKLOG_SNAPSHOT_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN backlog_snapshot 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, ...CHECK_FINDING_MIGRATIONS, ...BACKLOG_SNAPSHOT_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -990,6 +996,8 @@ export type Binding = { 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; + /** The issue ids as of the last digest that reported this backlog; null before the first. */ + backlogSnapshot: BacklogSnapshot | 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). */ @@ -1086,6 +1094,7 @@ function rowToBinding(r: BindingRow): Binding { sentryLook: json(sentryLookSchema.nullable(), str("sentry_look"), null), alertmanagerLook: json(alertmanagerLookSchema.nullable(), str("alertmanager_look"), null), backlogLook: json(backlogLookSchema.nullable(), str("backlog_look"), null), + backlogSnapshot: json(backlogSnapshotSchema.nullable(), str("backlog_snapshot"), null), deployments: json(deploymentsSchema, str("deployments"), {}), idleSince: num("idle_since"), idleWokenAt: num("idle_woken_at"), @@ -1160,6 +1169,7 @@ const COLUMNS = { sentryLook: "sentry_look", alertmanagerLook: "alertmanager_look", backlogLook: "backlog_look", + backlogSnapshot: "backlog_snapshot", deployments: "deployments", idleSince: "idle_since", idleWokenAt: "idle_woken_at", diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 16756a31..4a359cec 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -10,7 +10,7 @@ import { landLessonInstruction } from "./lessons.js"; import type { GuidanceUnit } from "./guidance.js"; import type { BigDecision } from "./decisions.js"; import { anyPending, type Deployments, type DeploymentWatch } from "./deploy.js"; -import { localParts } from "./nightly.js"; +import { localParts, type BacklogDigest } from "./nightly.js"; import { FINDING_CLASSES, type FindingClass, type OpsFinding, type OpsLook } from "./ops.js"; import type { DepsFinding, DepsLook } from "./deps.js"; import { ADOPTION_CHOICES, adoptionHow, dueDate } from "./deps.js"; @@ -1796,6 +1796,12 @@ export type DigestRecords = { datedWaits?: Binding[]; /** Open bindings on hold. */ held: Binding[]; + /** + * BB-334: one backlog report per backlog binding, from its stored look and + * the previous digest's snapshot. Empty or absent when no role carries a + * backlog, so the digest is byte-identical for every project without one. + */ + backlog?: BacklogDigest[]; /** Silent notes queued for this digest (a hold that lifted on finished work), one line each. */ notes?: string[]; /** @@ -1805,6 +1811,22 @@ export type DigestRecords = { checkFindings?: CheckFinding[]; }; +/** + * The digest's backlog block (BB-334): one heading line per team, then the + * likely duplicates, the stale tickets and the proposed next three. A failed + * read is one problem line, never an empty report. + */ +function backlogLines(b: BacklogDigest): string[] { + if (b.error !== null) return [`- ${b.team}: unavailable — ${b.error}`]; + const ages = b.ages.map((a) => `${a.label} ${a.count}`).join(", "); + const window = b.since === null ? "first digest" : `inflow ${b.inflow}, outflow ${b.outflow} since ${iso(b.since)}`; + const out = [`- ${b.team}: ${b.size} open${b.truncated ? " (truncated by the source's cap)" : ""}; age ${ages}; ${window}`]; + if (b.duplicates.length > 0) out.push(` - Likely duplicates: ${b.duplicates.map((d) => d.keys.join(" / ")).join("; ")}`); + if (b.stale.length > 0) out.push(` - Stale: ${b.stale.map((s) => `${s.key} (${s.days}d)`).join(", ")}`); + if (b.next.length > 0) out.push(` - Proposed next: ${b.next.map((n) => `${n.key} (${n.reason})`).join("; ")}`); + return out; +} + function capped(lines: string[], none: string): string[] { if (lines.length === 0) return [none]; return lines.length <= RECORD_LINES ? lines : [...lines.slice(0, RECORD_LINES), `- … and ${lines.length - RECORD_LINES} more`]; @@ -1856,6 +1878,11 @@ export function formatRecords(r: DigestRecords, questions: Array<{ question: Que const checkFindings = r.checkFindings ?? []; if (checkFindings.length > 0) out.push("### Check findings", "", ...capped(checkFindings.map((f) => `- ${f.level}: ${f.text}`), "Nothing."), ""); + // BB-334: the backlog report, omitted entirely when no role carries a + // backlog, so a project without one keeps the byte-identical digest. + const backlog = r.backlog ?? []; + if (backlog.length > 0) out.push("### Backlog", "", ...capped(backlog.flatMap((b) => backlogLines(b)), "Nothing."), ""); + // A question or a need covers the escalation it was made for: list the // question or the item, never the raw escalation too. const asked = new Set(