Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion plugins/stewards/migrations.snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -136,5 +136,6 @@
"c7dcc1c8ee819162947a9965a7fb0cb7129900a4d68f5f7f91a99184a225dea9",
"ad2a7b244faee5792ca77b1f36cd80488de8f787360d03f1569e60c869845beb",
"b268ed66797e2953f8b175fa1cdf506531a2fc5e30c52ef43480d81b9efb7c1b",
"c1377801bd4fe44be9cc5fc10c5aca75c9455359b3d5d646d0fb23318a032124"
"c1377801bd4fe44be9cc5fc10c5aca75c9455359b3d5d646d0fb23318a032124",
"d856f2127e2c5788a01c5ca80b216d1dc9be2a67bb273ad9082bbc69a279ce9a"
]
106 changes: 105 additions & 1 deletion plugins/stewards/nightly.test.ts
Original file line number Diff line number Diff line change
@@ -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).
Expand Down Expand Up @@ -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> = {}): 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> = {}): 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");
});
});
169 changes: 169 additions & 0 deletions plugins/stewards/nightly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string, BacklogIssue[]>();
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<string, number> = { 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),
};
}
9 changes: 9 additions & 0 deletions plugins/stewards/ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,15 @@ export const backlogLookSchema = z.object({
});
export type BacklogLook = z.infer<typeof backlogLookSchema>;

/**
* 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<typeof backlogSnapshotSchema>;

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

Expand Down
42 changes: 42 additions & 0 deletions plugins/stewards/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
Loading
Loading