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
25 changes: 23 additions & 2 deletions plugins/stewards/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,17 @@ At the project file's time, 01:00 US Eastern by default:

1. Every open binding gets one judgment turn whether or not anything changed,
staggered and capped per night.
2. The project steward's pass follows, over the fresh status records; its
2. The live half of `bb stewards check` runs — the reads against Linear,
GitHub and the ops targets and the hooks leases — and its `warning:` and
`problem:` lines are recorded per project, together with the parse half's
`warning:` lines (the template lag and unknown-origin warnings, which no
wake otherwise carries; its `problem:` lines already appear on every wake
under "Configuration problems"). They are compared with the last pass
by fingerprint; the findings new or changed since then ride in the digest
and the project steward's wake, so an unchanged finding is said once and
again only when it changes, or clears and returns (BB-328). `check` and
this pass are read-only and need no credential.
3. The project steward's pass follows, over the fresh status records; its
reply is kept as the morning digest.

All of it must finish before 03:00, when bb-gate's quiet window restarts
Expand Down Expand Up @@ -981,6 +991,17 @@ deployment: # where a merge is confirmed live (BB-53); omi

- **Phases are the entity's own states**, so the playbook needs no state
machine. A ticket moved by hand is followed.
- **A copied playbook carries a template stamp (BB-328).** `bb stewards init`
writes a `template: <name>@<hash>` front-matter line into each playbook it
copies, where the hash is of the shipped template text, so a project's own
edits leave it alone. `check` compares the stamp with the current template
and reports a lag as a `warning:` (never a `problem:`, and never a changed
exit status): `warning: ops-watch was copied from template <old>; current is
<new>.` A playbook with no stamp gets one "unknown origin" warning, and a
stamp naming a template that no longer exists is a warning too.
`bb stewards template <name>` prints the current shipped text, and an
unknown name lists the valid names and exits non-zero. A refresh is a
reviewed change, never a mechanical overwrite; Part 2 queues it.
- **A phase may be keyed on a label too (BB-248).** A `label:<name>` key in
`phases` matches a present label on the entity, ignoring case, and wins over
the state-keyed phase; with no matching label the state decides as before.
Expand Down Expand Up @@ -1111,7 +1132,7 @@ deployment: # where a merge is confirmed live (BB-53); omi
- **Threads:** spawning stewards, recognizing workers, building wake messages.
- **Agent tools:** `steward_report` and `steward_update` (which also
records and completes lessons, §20).
- **CLI:** `bb stewards init | check | list | show | needs | done | detach | pass | digest | lessons | drop-lesson`.
- **CLI:** `bb stewards init | check | template | list | show | needs | done | detach | pass | digest | lessons | drop-lesson`.
- **UI:** the Stewards page, a nav panel (BB-85): `board/<project>` is the
project view — the project name and project-steward link, **Waiting on you**
(the needs-you items with no open binding: project-level questions and items
Expand Down
24 changes: 22 additions & 2 deletions plugins/stewards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,8 +450,11 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run.
stalls.
- **The nightly pass** (01:00 in the project's time zone by default, done by
02:45 so bb-gate's 03:00 restarts do not cut a turn) gives every open
binding a turn, then wakes the project steward for the morning digest.
A half-hourly mechanical sweep is the adoption and stuck backstop.
binding a turn, runs the live half of `bb stewards check` (teams, states,
labels, repos, target readability and hooks leases), then wakes the project
steward for the morning digest, which carries the check findings new or
changed since the last pass. A half-hourly mechanical sweep is the adoption
and stuck backstop.
- **The Stewards page** (a nav panel, [app.tsx](app.tsx)) is no longer the
list (BB-85). `board/<project>` is the project view: project name and
project-steward link, **Waiting on you** (the needs-you items with no open
Expand Down Expand Up @@ -660,6 +663,23 @@ version. Project file fields beyond the design: `nightly.until`,
defaults in [config.ts](config.ts)) and `deps` (below). `project.json` holds
conventions only; the watches that need an owner live in `roles.json`.

**Template stamps and drift (BB-328).** `init` writes a
`template: <name>@<hash>` front-matter line into each playbook it copies,
where the hash is of the shipped template text, so a project's own edits
leave it alone. `check` reports a copy whose stamp hash differs from the
current template as a `warning:` (never a `problem:`, and never a changed
exit status): `warning: ops-watch was copied from template <old>; current is
<new>.` A playbook with no stamp gets one "unknown origin" warning, and a
stamp naming a template that no longer exists is a warning too. A refresh is
never a mechanical overwrite: `bb stewards template <name>` prints the
current shipped text, and an unknown name lists the valid names and exits
non-zero. The nightly pass runs the live half of `check` and records its
warnings and problems — plus the parse half's warnings, which no wake
otherwise carries — in the morning digest and the project steward's wake,
deduplicated by fingerprint so an unchanged finding is said once and again
only when it changes (or clears and returns). `check` and the nightly pass
are read-only and need no new credential.

`roles.json` (BB-105, version 2 in BB-163) assigns what each person's server
runs. Version 2 names each role once under `roles` and lists its holders
under `holders`:
Expand Down
50 changes: 49 additions & 1 deletion plugins/stewards/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ import {
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";
import { DEPS_ALERTS, DEPS_PRS, GITHUB_ISSUES, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, PLAYBOOK_TEMPLATES, projectFileTemplate, stampedTemplate, templateHashes } from "./templates.js";
import { parseTemplateStamp, templateHash, templateWarnings } from "./template-stamp.js";

describe("the project file", () => {
it("parses the template with defaults filled in", () => {
Expand Down Expand Up @@ -1028,3 +1029,50 @@ describe("project-level ticket watches (BB-246)", () => {
expect(parsed.value.tickets.map((w) => ticketWatchId(w))).toEqual(["initiative@ticket"]);
});
});

// BB-328: a playbook copied from a shipped template carries a
// `template: <name>@<hash>` stamp. The parser tolerates it (with or without
// one, a playbook parses and runs exactly as before), and `check` turns a
// stamp into a lag warning rather than a problem.
describe("template stamps (BB-328)", () => {
it("parses a playbook with or without a stamp the same way", () => {
const hash = templateHash(LINEAR_TICKETS);
const stamped = parsePlaybook(stampedTemplate("linear-tickets", LINEAR_TICKETS), "linear-tickets");
const plain = parsePlaybook(LINEAR_TICKETS, "linear-tickets");
if (!stamped.ok) throw new Error(stamped.error);
if (!plain.ok) throw new Error(plain.error);
expect(stamped.value.template).toEqual({ name: "linear-tickets", hash });
expect(plain.value.template).toBeNull();
// Everything but the stamp (and the text hash it changes) is identical.
expect({ ...stamped.value, template: null, version: plain.value.version }).toEqual(plain.value);
});

it("refuses a stamp that is not <name>@<hash>", () => {
expect(parsePlaybook(LINEAR_TICKETS.replace("name: linear-tickets", "name: linear-tickets\ntemplate: not-a-stamp"), "linear-tickets")).toMatchObject({ ok: false });
});

it("writes a stamp whose hash is of the shipped template, unchanged by edits to the copy", () => {
const stamped = stampedTemplate("ops-watch", OPS_WATCH);
const hash = templateHash(OPS_WATCH);
expect(stamped).toContain(`template: ops-watch@${hash}\n`);
// The hash is of the shipped text, never the project copy: editing the
// copy leaves the stamp's hash exactly where it was.
const edited = stamped.replace("# You watch one production target", "# edited by the project");
expect(parseTemplateStamp(/template: (\S+)/u.exec(edited)![1]!)).toEqual({ name: "ops-watch", hash });
});

it("warns on lag, unknown origin and a template that no longer exists, once per playbook", () => {
const hashes = new Map([["ops-watch", "aaaa"]]);
const p = (name: string, template: { name: string; hash: string } | null) => ({ name, template });
expect(templateWarnings([p("ops-watch", { name: "ops-watch", hash: "bbbb" })], hashes)).toEqual(["ops-watch was copied from template bbbb; current is aaaa."]);
expect(templateWarnings([p("ops-watch", null)], hashes)).toEqual(["ops-watch has no template stamp, so its origin is unknown"]);
expect(templateWarnings([p("ops-watch", { name: "gone", hash: "aaaa" })], hashes)).toEqual(["ops-watch was copied from template gone, which no longer exists"]);
expect(templateWarnings([p("ops-watch", null), p("ops-watch", null)], hashes)).toHaveLength(1);
});

it("has a current hash for every shipped template", () => {
const hashes = templateHashes();
expect([...hashes.keys()].sort()).toEqual(Object.keys(PLAYBOOK_TEMPLATES).sort());
for (const [name, hash] of hashes) expect(parseTemplateStamp(`${name}@${hash}`)).toEqual({ name, hash });
});
});
11 changes: 11 additions & 0 deletions plugins/stewards/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { z } from "zod";
import { decideEntrySchema, defaultDecideList, globError } from "./decisions.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";
import { parseTemplateStamp, TEMPLATE_STAMP } from "./template-stamp.js";

export const STEWARDS_DIR = "stewards";
export const PROJECT_FILE = `${STEWARDS_DIR}/project.json`;
Expand Down Expand Up @@ -815,6 +816,13 @@ export const frontMatterSchema = z
"max-assumptions": z.number().int().min(0).max(50).default(5),
/** Reviews: pull request authors no review steward is made for (bots). */
"skip-authors": z.array(z.string().trim().min(1).max(100)).default([]),
/**
* BB-328: the shipped template this playbook was copied from, as
* `<name>@<hash>`. `init` writes it and a refresh updates it; a playbook
* with or without it parses and runs exactly as before. The name need not
* still exist: `check` reports a stamp naming a gone template as a warning.
*/
template: z.string().trim().regex(TEMPLATE_STAMP, "a template stamp <name>@<hash>").optional(),
/**
* Reviews: file the owner's Merge item on a teammate's pull request too
* (BB-170). Off by default: the owner's approval is their last step and
Expand Down Expand Up @@ -851,6 +859,8 @@ export type Playbook = {
ownerMerges: boolean;
/** Where a merge is confirmed live, or empty when the playbook names no deployment target. */
deployments: DeploymentTarget[];
/** BB-328: the shipped template this playbook was copied from, or null when it carries no stamp. */
template: { name: string; hash: string } | null;
/** Alias warnings the front matter raised, surfaced by `bb stewards check` (BB-209). */
warnings: string[];
/** The text before the first `## ` heading: instructions for every phase. */
Expand Down Expand Up @@ -932,6 +942,7 @@ export function parsePlaybook(text: string, expectedName: string): Parsed<Playbo
skipAuthors: fm["skip-authors"],
ownerMerges: fm["owner-merges"],
deployments: fm.deployment === undefined ? [] : Array.isArray(fm.deployment) ? fm.deployment : [fm.deployment],
template: fm.template === undefined ? null : parseTemplateStamp(fm.template),
warnings,
general,
sections,
Expand Down
3 changes: 2 additions & 1 deletion plugins/stewards/migrations.snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -135,5 +135,6 @@
"8a61e3594b695ff3b5f2f58573155bd59f7209142643e4f212fe3485a4ae80f9",
"c7dcc1c8ee819162947a9965a7fb0cb7129900a4d68f5f7f91a99184a225dea9",
"ad2a7b244faee5792ca77b1f36cd80488de8f787360d03f1569e60c869845beb",
"b268ed66797e2953f8b175fa1cdf506531a2fc5e30c52ef43480d81b9efb7c1b"
"b268ed66797e2953f8b175fa1cdf506531a2fc5e30c52ef43480d81b9efb7c1b",
"c1377801bd4fe44be9cc5fc10c5aca75c9455359b3d5d646d0fb23318a032124"
]
59 changes: 58 additions & 1 deletion plugins/stewards/nightly.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Database from "better-sqlite3";
import { describe, expect, it } from "vitest";
import { createBriefing, localParts, nightOf, nightlyDue, stillNight, toDigestRecords } from "./nightly.js";
import { createBriefing, checkFindingFingerprint, freshCheckFindings, localParts, nightOf, nightlyDue, stillNight, toDigestRecords } from "./nightly.js";
import { MIGRATIONS, createStore } from "./store.js";
import { formatRecords, type DigestRecords } from "./wake.js";

Expand Down Expand Up @@ -148,3 +148,60 @@ describe("briefing", () => {
expect(store.lastStandup("p1")).toBe(333);
});
});

// BB-328: the nightly pass runs the live half of `check` and records findings
// deduplicated by fingerprint: an unchanged finding is said once, and again
// only when it changes (or clears and returns).
describe("check findings deduplicated by fingerprint (BB-328)", () => {
const problem = (text: string) => ({ level: "problem" as const, text });
const warning = (text: string) => ({ level: "warning" as const, text });

it("says an unchanged finding once, and a changed one again", () => {
const first = freshCheckFindings([problem("ENG is not visible"), warning("ops-watch lag")], []);
expect(first.fresh.map((f) => f.text)).toEqual(["ENG is not visible", "ops-watch lag"]);
expect(first.next.every((f) => f.fingerprint === checkFindingFingerprint(f))).toBe(true);

// The same two findings again: nothing fresh, the recorded set unchanged.
const second = freshCheckFindings([problem("ENG is not visible"), warning("ops-watch lag")], first.next);
expect(second.fresh).toEqual([]);
expect(second.next.map((f) => f.fingerprint).sort()).toEqual(first.next.map((f) => f.fingerprint).sort());

// One changed: only that one is fresh.
const third = freshCheckFindings([problem("ENG has no state Todo"), warning("ops-watch lag")], first.next);
expect(third.fresh.map((f) => f.text)).toEqual(["ENG has no state Todo"]);
});

it("says a finding again after it clears and returns", () => {
const first = freshCheckFindings([problem("ENG is not visible")], []);
const cleared = freshCheckFindings([], first.next);
expect(cleared.fresh).toEqual([]);
expect(cleared.next).toEqual([]);
const returned = freshCheckFindings([problem("ENG is not visible")], cleared.next);
expect(returned.fresh.map((f) => f.text)).toEqual(["ENG is not visible"]);
});

it("collapses duplicate findings within one pass", () => {
const pass = freshCheckFindings([problem("same"), problem("same")], []);
expect(pass.fresh).toHaveLength(1);
expect(pass.next).toHaveLength(1);
});

it("records the current set in the store and reads it back", () => {
const db = new Database(":memory:");
for (const sql of MIGRATIONS) db.exec(sql);
let clock = 1_000_000;
const store = createStore(db, () => clock);
const now = () => clock;
expect(store.checkFindings("p1")).toEqual([]);
const { next } = freshCheckFindings([problem("ENG is not visible")], []);
store.setCheckFindings("p1", next, now());
expect(store.checkFindings("p1")).toEqual([{ ...next[0]!, firstSeenAt: now() }]);
// Re-recording an unchanged finding keeps its first-seen time.
store.setCheckFindings("p1", next, now() + 1000);
expect(store.checkFindings("p1")[0]!.firstSeenAt).toBe(now());
// A finding that is gone is dropped, and one that returns is fresh again.
store.setCheckFindings("p1", [], now() + 2000);
expect(store.checkFindings("p1")).toEqual([]);
expect(freshCheckFindings([problem("ENG is not visible")], store.checkFindings("p1")).fresh).toHaveLength(1);
});
});
26 changes: 26 additions & 0 deletions plugins/stewards/nightly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,32 @@
// sections the stand-up needs.
import type { Assumption, Binding, Escalation, Need, Question, Store } from "./store.js";
import type { DigestRecords } from "./wake.js";
import { createHash } from "node:crypto";
import type { CheckFinding } from "./template-stamp.js";

/** A finding as recorded, with the fingerprint that decides whether it was said before (BB-328). */
export type StoredCheckFinding = CheckFinding & { fingerprint: string };

/** The fingerprint of a finding: its level and text, so a changed finding has a new one. */
export function checkFindingFingerprint(f: CheckFinding): string {
return createHash("sha256").update(`${f.level}\n${f.text}`).digest("hex").slice(0, 16);
}

/**
* The findings to say now, and the set to record. A finding not in `stored`
* (never seen, changed, or back after clearing) is fresh; one unchanged since
* the last pass is not. The caller persists `next` and reports `fresh`.
*/
export function freshCheckFindings(current: CheckFinding[], stored: StoredCheckFinding[]): { fresh: StoredCheckFinding[]; next: StoredCheckFinding[] } {
const byFingerprint = new Map<string, StoredCheckFinding>();
for (const f of current) {
const fingerprint = checkFindingFingerprint(f);
if (!byFingerprint.has(fingerprint)) byFingerprint.set(fingerprint, { ...f, fingerprint });
}
const next = [...byFingerprint.values()];
const known = new Set(stored.map((f) => f.fingerprint));
return { fresh: next.filter((f) => !known.has(f.fingerprint)), next };
}

const minutesOf = (clock: string): number => {
const [h, m] = clock.split(":").map(Number);
Expand Down
Loading
Loading