diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index eb0578c3..db6b77b3 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -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 @@ -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: @` 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 ; current is + .` 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 ` 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:` 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. @@ -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/` 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 diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index c1178a37..23097024 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -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/` is the project view: project name and project-steward link, **Waiting on you** (the needs-you items with no open @@ -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: @` 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 ; current is +.` 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 ` 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`: diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 228e92f2..0065d712 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -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", () => { @@ -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: @` 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 @", () => { + 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 }); + }); +}); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index ba611d1a..a1d1d9b2 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -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`; @@ -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 + * `@`. `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 @").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 @@ -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. */ @@ -932,6 +942,7 @@ export function parsePlaybook(text: string, expectedName: string): Parsed { 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); + }); +}); diff --git a/plugins/stewards/nightly.ts b/plugins/stewards/nightly.ts index 319b7243..25b1a0e3 100644 --- a/plugins/stewards/nightly.ts +++ b/plugins/stewards/nightly.ts @@ -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(); + 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); diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 4ceb76d4..57af4436 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -11,7 +11,8 @@ import { guidanceUnitId } from "./guidance.js"; import { needActions, parseDotenvValue, secretVariable } from "./server.js"; import { SOURCE_PLUGIN_IDS, type EntitySnapshot } from "./source-contract.js"; import { MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, STEWARD_NEED_KINDS, type Binding } from "./store.js"; -import { GITHUB_ISSUES, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, DEPS_ALERTS, DEPS_PRS, PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; +import { GITHUB_ISSUES, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, DEPS_ALERTS, DEPS_PRS, PLAYBOOK_TEMPLATES, projectFileTemplate, stampedTemplate } from "./templates.js"; +import { parseTemplateStamp, templateHash } from "./template-stamp.js"; import { DEFAULT_ALERTMANAGER_URL } from "./alertmanager.js"; import { STANDING_RULES } from "./wake.js"; import { setup } from "./test-world.js"; @@ -3876,7 +3877,9 @@ describe("project-level ticket watches (BB-246)", () => { await t.ring("linear", "uuid-12"); expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "initiatives", endedAt: null }); const check = await t.harness.behavior.runCli(["check", "--project", "p1"]); - expect(check.stdout).not.toMatch(/initiatives/u); + // The removed watch is not a problem. (The playbook itself has no template + // stamp, so `check` does carry its one unknown-origin warning.) + expect(check.stdout).not.toMatch(/problem:.*initiatives/u); // With the playbook file gone too, and no last-good copy, it ends. delete t.files[playbookPath("initiatives")]; await t.bb.storage.kv.delete("good/p1/playbook/initiatives"); @@ -16328,3 +16331,104 @@ describe("the stand-up (BB-300)", () => { expect(t.hooks.store.lastCompletedStandup("p1")).toBe(t.now() - 120_000); }); }); + +// BB-328: a playbook copied from a shipped template carries a stamp; `init` +// writes it, `check` reports drift as a warning (never a problem), the +// `template` command prints the shipped text, and the nightly pass runs the +// live half of `check`, recording findings deduplicated by fingerprint. +describe("template stamps and the nightly live check (BB-328)", () => { + it("init writes a stamp into each copied playbook, whose hash is of the shipped text", async () => { + const t = await setup(); + delete t.files[PROJECT_FILE]; + for (const name of Object.keys(PLAYBOOK_TEMPLATES)) delete t.files[playbookPath(name)]; + await t.harness.behavior.runCli(["init", "--teams", "ENG"], { threadId: "thr_me", projectId: "p1", cwd: "/w" }); + const written = new Map([...t.writtenContent].filter(([p]) => p.startsWith("/w/.bb/")).map(([p, c]) => [p.slice("/w/.bb/".length), c])); + for (const [name, text] of Object.entries(PLAYBOOK_TEMPLATES)) { + if (name === "github-issues") continue; + const content = written.get(playbookPath(name)); + expect(content, `${name} was written`).toBeDefined(); + expect(content).toContain(`template: ${name}@${templateHash(text)}\n`); + } + // Editing the copy never changes the stamp's hash: it is of the shipped text. + const edited = written.get(playbookPath("linear-tickets"))!.replace("# What", "# edited"); + expect(parseTemplateStamp(/template: (\S+)/u.exec(edited)![1]!)).toEqual({ name: "linear-tickets", hash: templateHash(LINEAR_TICKETS) }); + }); + + it("check warns, without failing, on a lagging, unstamped or gone-template playbook", async () => { + const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); + const plain = await t.harness.behavior.runCli(["check", "--project", "p1"]); + expect(plain.exitCode).toBe(0); + expect(plain.stdout).toMatch(/warning: linear-tickets has no template stamp, so its origin is unknown/u); + expect(plain.stdout.match(/linear-tickets has no template stamp/gu)).toHaveLength(1); + + t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace("name: linear-tickets", "name: linear-tickets\ntemplate: linear-tickets@deadbeef"); + const lag = await t.harness.behavior.runCli(["check", "--project", "p1"]); + expect(lag.exitCode).toBe(0); + expect(lag.stdout).toContain(`warning: linear-tickets was copied from template deadbeef; current is ${templateHash(LINEAR_TICKETS)}.`); + + t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace("name: linear-tickets", "name: linear-tickets\ntemplate: gone@deadbeef"); + const gone = await t.harness.behavior.runCli(["check", "--project", "p1"]); + expect(gone.exitCode).toBe(0); + expect(gone.stdout).toMatch(/warning: linear-tickets was copied from template gone, which no longer exists/u); + }); + + it("prints a shipped template, and an unknown name lists the valid ones and exits non-zero", async () => { + const t = await setup(); + const known = await t.harness.behavior.runCli(["template", "ops-watch"]); + expect(known.exitCode).toBe(0); + expect(known.stdout).toBe(OPS_WATCH); + const unknown = await t.harness.behavior.runCli(["template", "nope"]); + expect(unknown.exitCode).toBe(1); + expect(unknown.stdout).toContain('Unknown template "nope"'); + expect(unknown.stdout).toContain("ops-watch"); + // A name on Object's prototype is not a template either. + const proto = await t.harness.behavior.runCli(["template", "toString"]); + expect(proto.exitCode).toBe(1); + expect(proto.stdout).toContain('Unknown template "toString"'); + }); + + it("runs the live check nightly and records a finding once, repeating only when it changes", async () => { + const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); + t.setMissingStates("linear", "ENG", ["Todo"]); + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + const thread = t.hooks.store.project("p1").threadId!; + const texts = () => t.sends.filter((s) => s.threadId === thread).map((s) => s.text); + expect(texts().some((x) => x.includes("problem: linear: ENG has no state Todo"))).toBe(true); + + // Unchanged: not said again. + const before = texts().length; + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + expect(texts().slice(before).join("\n")).not.toContain("ENG has no state Todo"); + + // Changed: said again with the new text. + t.setMissingStates("linear", "ENG", ["Todo", "In Progress"]); + const before2 = texts().length; + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + expect(texts().slice(before2).join("\n")).toContain("linear: ENG has no state Todo, In Progress"); + }); + + it("records a finding only once the digest is delivered, so a failed send says it next pass", async () => { + const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); + // A first, clean pass spawns the project steward. + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + const thread = t.hooks.store.project("p1").threadId!; + // The next digest cannot be delivered. + t.threads.get(thread)!.sendError = { code: "internal", status: 500, message: "boom" }; + t.setMissingStates("linear", "ENG", ["Todo"]); + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + // It was never said, so it is not recorded as said. + expect(t.hooks.store.checkFindings("p1").some((f) => f.text.includes("ENG has no state Todo"))).toBe(false); + // The send works again: the finding is said. + t.threads.get(thread)!.sendError = undefined; + const before = t.sends.filter((s) => s.threadId === thread).length; + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + expect(t.sends.filter((s) => s.threadId === thread).slice(before).map((s) => s.text).join("\n")).toContain("ENG has no state Todo"); + expect(t.hooks.store.checkFindings("p1").some((f) => f.text.includes("ENG has no state Todo"))).toBe(true); + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 5a6ee742..58fc61c6 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, nightlyDue, stillNight, toDigestRecords } from "./nightly.js"; +import { createBriefing, freshCheckFindings, 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 BacklogLook, type BacklogTarget, type DependabotTarget, type FingerprintRow, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; @@ -138,7 +138,8 @@ import { AUTOMATIC_NAVIGATION_PROVIDER, AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_ import { waitingOnNamesWorker } from "./sidebar.js"; import { advanceStall, parseUntil, pullWatchCounts, type WakeSourceInput } from "./wake-source.js"; import { PROJECT_CHANGED } from "./channels.js"; -import { LINEAR_TICKETS, PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; +import { LINEAR_TICKETS, PLAYBOOK_TEMPLATES, projectFileTemplate, stampedTemplate, templateHashes } from "./templates.js"; +import { templateWarnings, type CheckFinding } from "./template-stamp.js"; import type { DeploymentTarget } from "./config.js"; import { PROJECT_STEWARD_INTRO, bindingMayMerge, choicesNote, formatAlertmanagerWake, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerFinishNote, workerQuestion, workflowRunLine, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; import { KNOWN_PLAYBOOKS, buildSurvey, formatSurvey, surveyWantedPaths, type Available, type SurveyBb, type SurveyLinear, type SurveyRepoInput, type SurveyReport } from "./survey.js"; @@ -2680,11 +2681,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // alias parses as `user`; surface one warning per playbook, however many // of the load paths reached it. const warnedPlaybooks = new Set(); + const loadedPlaybooks: Playbook[] = []; for (const p of [...Object.values(playbooks), depsAlerts, depsPrs, ...watchPlaybooks.values()]) { - if (p === undefined || p === null || warnedPlaybooks.has(p.name)) continue; + if (p === undefined || p === null) continue; + loadedPlaybooks.push(p); + if (warnedPlaybooks.has(p.name)) continue; warnedPlaybooks.add(p.name); for (const w of p.warnings) warnings.push(`${p.name}: ${w}`); } + // BB-328: a playbook copied from a shipped template carries a + // `template: @` stamp. `check` reports one warning per + // playbook: lag behind the current template, a stamp naming a template + // that no longer exists, or no stamp at all (unknown origin). Warnings + // never fail the check; a binding keeps running exactly as before. + warnings.push(...templateWarnings(loadedPlaybooks, templateHashes())); return { projectId, source, file, roles, rolesPresent, rolesUnreadable, githubLogin, linearLogin, role, roleNames, playbooks, ticketPlaybooks, depsAlerts, depsPrs, watchPlaybooks, repos, enabled, problems, warnings, hints, loadedAt: now() }; } @@ -7101,12 +7111,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // project steward asking them in its own thread; thread-briefs shows that // thread as waiting on them, so nothing here asks for attention itself. - async function wakeProject(projectId: string, reason: string, opts: { digestDue: boolean; notes?: string[] }): Promise { + async function wakeProject(projectId: string, reason: string, opts: { digestDue: boolean; notes?: string[]; checkFindings?: CheckFinding[]; onSent?: () => void }): Promise { const config = await loadConfig(projectId); if (config === null) return; const threadId = await ensureProjectSteward(config); if (threadId === null) return; const records = opts.digestDue ? digestRecords(projectId) : undefined; + // 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; if (opts.digestDue) store.patchProject(projectId, { digestPending: true }); const info = await threadInfo(threadId).catch(() => null); if (info === null || info.deletedAt !== null) return; @@ -7151,7 +7164,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (sent !== "sent") store.undeliver(delivered.ids, delivered.at); // The notes were only peeked at, so a failed or skipped send leaves them // queued for the next digest rather than losing them. - else if (opts.digestDue) store.clearProjectNotes(projectId); + else { + // 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); + } } /** What the digest is written from, since the last one (or a day back): read from the tables, never from the project steward's memory. */ @@ -12897,14 +12915,41 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // Mark only once the wake is really sent, so a disposed pass leaves // the follow-up for the next one. for (const x of followUps) store.markEscalationRationaleAsked(x.id); + // BB-328: the live half of `check` (teams, states, labels, repos, + // target readability, hooks leases) runs on the project steward's + // server only, whose digest is the only place its findings are read. + // `check` is read-only and needs no credential, and a read that + // throws is logged, never allowed to skip the digest. The findings + // are recorded only once the digest is really sent, so a skipped or + // failed send leaves them to be said on the next pass. + let freshFindings: CheckFinding[] = []; + let nextFindings: Array<{ fingerprint: string; level: "warning" | "problem"; text: string }> | null = null; + if (config.role?.projectSteward === true) { + let liveFindings: CheckFinding[] = []; + try { + liveFindings = (await check(config.projectId)).findings; + } catch (error) { + bb.log.warn(`stewards: nightly check for ${config.projectId}: ${errorMessage(error)}`); + } + const current: CheckFinding[] = [...config.warnings.map((text): CheckFinding => ({ level: "warning", text })), ...liveFindings]; + const diff = freshCheckFindings(current, store.checkFindings(config.projectId)); + freshFindings = diff.fresh; + nextFindings = diff.next; + } + let digestSent = false; await wakeProject(config.projectId, `nightly pass ${night}`, { digestDue: true, + checkFindings: freshFindings, + onSent: () => { + digestSent = true; + }, notes: [ `${woken.length} binding(s) had a turn tonight.`, ...adoption.unassigned.map((t) => `labelled, no assignee: ${t.key}${t.title === null ? "" : ` ${t.title}`}${t.url === null ? "" : ` — ${t.url}`}. Assign it in Linear to the server that should own it; this one does not adopt it.`), ...followUps.map((x) => `The user's answer on ${x.id} went against your recommendation. Ask them once, in this thread, why — one follow-up — then record their reasoning as a lesson candidate with steward_update { lesson: { text, file, scope } }.`), ], }); + if (digestSent && nextFindings !== null) store.setCheckFindings(config.projectId, nextFindings, now()); } } finally { running.delete(config.projectId); @@ -13151,12 +13196,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } - async function check(projectId: string, options: { createLabels?: boolean } = {}): Promise<{ ok: boolean; lines: string[] }> { + async function check(projectId: string, options: { createLabels?: boolean } = {}): Promise<{ ok: boolean; lines: string[]; findings: Array<{ level: "warning" | "problem"; text: string }> }> { const config = await loadConfig(projectId, true); if (config === null) { const error = configErrors.get(projectId); - if (error !== undefined) return { ok: false, lines: [`problem: could not read the configuration: ${error}`] }; - return { ok: false, lines: [`No ${PROJECT_FILE} on the project's .bb. Run bb stewards init.`] }; + if (error !== undefined) return { ok: false, lines: [`problem: could not read the configuration: ${error}`], findings: [] }; + return { ok: false, lines: [`No ${PROJECT_FILE} on the project's .bb. Run bb stewards init.`], findings: [] }; } const lines: string[] = [...config.problems.map((p) => `problem: ${p}`), ...config.warnings.map((w) => `warning: ${w}`), ...config.hints]; if (!config.enabled) lines.push(`Stewards are off for this project on this server; nothing is adopted and no steward is woken. Switch on with bb stewards enable --project ${projectId}.`); @@ -13251,6 +13296,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } }; + // BB-328: everything from here on is the live half of `check` — the + // reads against Linear, GitHub, the ops targets and the hooks leases. + // The nightly pass records these lines (with `config.warnings`) as + // findings, deduplicated by fingerprint; `check` prints them all. + const liveStart = lines.length; 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); @@ -13271,7 +13321,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const a = await sentryApi.access(target); lines.push(a.ok ? `sentry: ${key} is readable (${a.name})` : `problem: sentry: cannot read the target ${key}: ${a.error}`); const refused = sentryRefused.get(`project ${target.org}/${target.project}`); - if (refused !== undefined) lines.push(`sentry: ${key}: bb-gate-hooks refused its project lease (${refused}); only the periodic look sees it`); + if (refused !== undefined) lines.push(`warning: sentry: ${key}: bb-gate-hooks refused its project lease (${refused}); only the periodic look sees it`); } const status = sentryHooks.status(); lines.push(hooksUrl === "" ? "sentry: no bb-gate-hooks here (BB_HOOKS_URL is not set), so Sentry issues are seen by the periodic look only" : `sentry: doorbells from bb-gate-hooks: ${status.state}${status.state === "connected" ? (status.leased ? ", leased" : ", not leased") : ""}`); @@ -13285,7 +13335,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const a = await alertmanagerApi.access(target); lines.push(a.ok ? `alertmanager: ${key} is readable (${a.name})` : `problem: alertmanager: cannot read the target ${key}: ${a.error}`); const refused = alertmanagerRefused.get(`namespace ${target.namespace}`); - if (refused !== undefined) lines.push(`alertmanager: ${key}: bb-gate-hooks refused its namespace lease (${refused}); only the periodic look sees it`); + if (refused !== undefined) lines.push(`warning: alertmanager: ${key}: bb-gate-hooks refused its namespace lease (${refused}); only the periodic look sees it`); } const status = alertmanagerHooks.status(); if (hooksUrl === "") lines.push("alertmanager: no bb-gate-hooks here (BB_HOOKS_URL is not set), so alerts are seen by the periodic look only"); @@ -13332,7 +13382,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P lines.push(`problem: deps: could not read alerts: ${errorMessage(error)}`); } } - return { ok: !lines.some((l) => l.startsWith("problem:")), lines }; + const findings = lines.slice(liveStart).flatMap((l): Array<{ level: "warning" | "problem"; text: string }> => { + if (l.startsWith("problem: ")) return [{ level: "problem", text: l.slice("problem: ".length) }]; + if (l.startsWith("warning: ")) return [{ level: "warning", text: l.slice("warning: ".length) }]; + return []; + }); + return { ok: !lines.some((l) => l.startsWith("problem:")), lines, findings }; } /** Whether a project file names a project steward in roles.json, so it needs no onboarding. */ @@ -13542,7 +13597,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // init writes the github-issues ticket playbook too. A project // with Linear teams keeps the Linear ticket playbook alone. const templates = Object.entries(PLAYBOOK_TEMPLATES).filter(([name]) => name !== DEFAULT_GITHUB_TICKET_PLAYBOOK || teams.length === 0); - const files: Array<[string, string]> = [[PROJECT_FILE, projectFileTemplate(teams)], ...templates.map(([name, text]) => [playbookPath(name), text] as [string, string])]; + const files: Array<[string, string]> = [[PROJECT_FILE, projectFileTemplate(teams)], ...templates.map(([name, text]) => [playbookPath(name), stampedTemplate(name, text)] as [string, string])]; const lines: string[] = []; for (const [rel, content] of files) { const path = `${dir}/${rel}`; @@ -13669,6 +13724,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }, }), + template: cliCommand({ + summary: "Print the current shipped text of a playbook template", + description: "The text `bb stewards init` copies into a project's .bb, and the text a `template:` stamp's hash is taken from. A refresh is never a mechanical overwrite: this prints the template so a steward or a person can see what moved. An unknown name lists the valid names and exits non-zero.", + positionals: [{ name: "name", description: "The template name (a PLAYBOOK_TEMPLATES key)", required: true }], + async run(input) { + const name = input.positionals.name ?? ""; + if (!Object.hasOwn(PLAYBOOK_TEMPLATES, name)) return { exitCode: 1, stdout: `Unknown template ${JSON.stringify(name)}. Valid names: ${Object.keys(PLAYBOOK_TEMPLATES).join(", ")}` }; + return { exitCode: 0, stdout: PLAYBOOK_TEMPLATES[name]! }; + }, + }), + enable: cliCommand({ summary: "Switch this server's stewards on for a project, and sweep it now", description: "Local to this server, keyed by project id, and off by default. `.bb`'s stewards/project.json still has to exist. Turning on reopens the bindings the last switch-off ended and sweeps the project at once.", diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index 01dc40ec..c2f606d6 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, 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, 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]!)); @@ -742,8 +742,9 @@ describe("the actor rename migration (BB-97)", () => { // 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, 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]; + // 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]; let end = MIGRATIONS.length; for (const group of groups) { expect(MIGRATIONS.slice(end - group.length, end)).toEqual([...group]); @@ -839,9 +840,12 @@ describe("the escalation route rename migration (BB-209)", () => { // 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, 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]); + // 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]); + 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); expect(withoutBacklogLook.slice(-WORKER_PARK_MIGRATIONS.length)).toEqual([...WORKER_PARK_MIGRATIONS]); const withoutReviewerRequests = withoutWorkerPark.slice(0, -REVIEWER_REQUEST_MIGRATIONS.length); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 45a26fee..feea41c3 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -739,7 +739,24 @@ export const ALERTMANAGER_LOOK_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN al // 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]; +// BB-328: the live half of `check` recorded as findings, deduplicated by +// fingerprint so an unchanged finding is said once and repeated only when it +// changes (or clears and returns). A new table, so a store from before this +// step reads back exactly as before. Appended after BB-334's backlog look +// column, which merged first, so no recorded index moves. +export const CHECK_FINDING_MIGRATIONS = [ + `CREATE TABLE IF NOT EXISTS check_findings ( + project_id TEXT NOT NULL, + fingerprint TEXT NOT NULL, + level TEXT NOT NULL, + text TEXT NOT NULL, + first_seen_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + PRIMARY KEY (project_id, fingerprint) + )`, +]; + +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]; // ---- values kept as JSON ------------------------------------------------------------ @@ -3422,6 +3439,29 @@ export function createStore(db: Database.Database, now: () => number, options: S db.prepare("INSERT INTO server_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(`stewards:last-standup:${projectId}`, String(at)); }, + // BB-328: the live half of `check`, recorded per project as findings keyed + // by fingerprint, so the nightly pass says an unchanged finding once and + // again only when it changes (or clears and returns). + /** The check findings currently recorded for a project, by fingerprint. */ + checkFindings(projectId: string): Array<{ fingerprint: string; level: "warning" | "problem"; text: string; firstSeenAt: number }> { + return db + .prepare<[string], { fingerprint: string; level: string; text: string; first_seen_at: number }>("SELECT fingerprint, level, text, first_seen_at FROM check_findings WHERE project_id = ?") + .all(projectId) + .map((r) => ({ fingerprint: r.fingerprint, level: r.level === "problem" ? "problem" : "warning", text: r.text, firstSeenAt: r.first_seen_at })); + }, + /** Replace a project's recorded findings with the current set, keeping an unchanged finding's first-seen time. */ + setCheckFindings(projectId: string, findings: ReadonlyArray<{ fingerprint: string; level: "warning" | "problem"; text: string }>, at: number): void { + const keep = new Set(findings.map((f) => f.fingerprint)); + const existing = db.prepare<[string], { fingerprint: string }>("SELECT fingerprint FROM check_findings WHERE project_id = ?").all(projectId); + const remove = db.prepare("DELETE FROM check_findings WHERE project_id = ? AND fingerprint = ?"); + const upsert = db.prepare( + `INSERT INTO check_findings (project_id, fingerprint, level, text, first_seen_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(project_id, fingerprint) DO UPDATE SET level = excluded.level, text = excluded.text, last_seen_at = excluded.last_seen_at`, + ); + for (const row of existing) if (!keep.has(row.fingerprint)) remove.run(projectId, row.fingerprint); + for (const f of findings) upsert.run(projectId, f.fingerprint, f.level, f.text, at, at); + }, + // BB-300 slice 4: the durable stand-up record. The server opens one when a // stand-up starts, saves the model's notes as tools take and retract them, // confirms each item the owner confirms, and reads it back for the page and diff --git a/plugins/stewards/template-stamp.ts b/plugins/stewards/template-stamp.ts new file mode 100644 index 00000000..88f5fa95 --- /dev/null +++ b/plugins/stewards/template-stamp.ts @@ -0,0 +1,57 @@ +// The template stamp (BB-328): the `@` a playbook copied from a +// shipped template carries in its front matter, and the warnings `check` +// raises when the copy has drifted from the template it came from. +// +// The hash is of the shipped template text, never of the project copy, so a +// project's own edits leave the stamp's hash alone. Pure, and deliberately +// free of imports, so both `config.ts` (which parses the key) and +// `templates.ts` (which writes it) can use it without a cycle. +import { createHash } from "node:crypto"; + +/** The short hash of a shipped template's text, as the stamp records it. */ +export function templateHash(text: string): string { + return createHash("sha256").update(text).digest("hex").slice(0, 12); +} + +/** A `template: @` stamp: a playbook name, an `@`, and a hex hash. */ +export const TEMPLATE_STAMP = /^([a-z0-9][a-z0-9-]{0,62})@([0-9a-f]{6,64})$/u; + +/** A parsed stamp, or null when the value is not one. */ +export function parseTemplateStamp(value: string): { name: string; hash: string } | null { + const m = TEMPLATE_STAMP.exec(value.trim()); + return m === null ? null : { name: m[1]!, hash: m[2]! }; +} + +/** A finding `check` reports: a `warning:` (does not fail the check) or a `problem:` (does). */ +export type CheckFinding = { level: "warning" | "problem"; text: string }; + +/** + * The template warnings for a project's playbooks (BB-328). One line per + * playbook, however many load paths reached it: a stamp whose hash differs + * from the shipped template's is lag; a stamp naming a template that no + * longer exists is a warning; a playbook with no stamp is "unknown origin". + * `templateHashes` maps a template name to the current hash of its shipped + * text, so the reader stays injectable for tests. + */ +export function templateWarnings( + playbooks: Iterable<{ name: string; template: { name: string; hash: string } | null }>, + templateHashes: ReadonlyMap, +): string[] { + const warnings: string[] = []; + const seen = new Set(); + for (const p of playbooks) { + if (seen.has(p.name)) continue; + seen.add(p.name); + if (p.template === null) { + warnings.push(`${p.name} has no template stamp, so its origin is unknown`); + continue; + } + const current = templateHashes.get(p.template.name); + if (current === undefined) { + warnings.push(`${p.name} was copied from template ${p.template.name}, which no longer exists`); + continue; + } + if (p.template.hash !== current) warnings.push(`${p.name} was copied from template ${p.template.hash}; current is ${current}.`); + } + return warnings; +} diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index d2839468..24b9ae92 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -3,6 +3,7 @@ // and reviewed like any other change to `.bb`. import { DEFAULT_LABEL } from "./config.js"; import { DEFAULT_BIG_DECISIONS, defaultDecideList } from "./decisions.js"; +import { templateHash } from "./template-stamp.js"; /** * A credential a worker needs, in the linear-tickets build section. The worker @@ -692,3 +693,18 @@ export const PLAYBOOK_TEMPLATES: Record = { "deps-alerts": DEPS_ALERTS, "deps-prs": DEPS_PRS, }; + +/** The current hash of every shipped template's text, so `check` can compare it with a stamp. */ +export const templateHashes = (): Map => new Map(Object.entries(PLAYBOOK_TEMPLATES).map(([name, text]) => [name, templateHash(text)])); + +/** + * A template's text with the stamp `init` writes into the copy: a + * `template: @` front-matter line after the opening fence. The + * hash is of the shipped text, so a project's own edits never change it. + */ +export function stampedTemplate(name: string, text: string): string { + const hash = templateHash(text); + const m = /^---\r?\n/u.exec(text); + if (m === null) return text; + return `${text.slice(0, m[0].length)}template: ${name}@${hash}\n${text.slice(m[0].length)}`; +} diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 5f219df3..16756a31 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -22,6 +22,7 @@ import { currentStoredGate, type StoredGate } from "./assessed-gate.js"; import { conflictsOf, openPull, type Conflict } from "./schedule.js"; import { SNAPSHOT_COMMENTS_MAX, type EntitySnapshot, type SessionWake, type SnapshotComment, type WorkflowRun } from "./source-contract.js"; import { needChoices, ESCALATED_NEED_KINDS, RESOLUTION_KINDS, STEWARD_NEED_KINDS, type Assumption, type Binding, type DepsDecision, type Escalation, type Lesson, type Need, type Observed, type Question, type Worker } from "./store.js"; +import type { CheckFinding } from "./template-stamp.js"; /** A wake longer than this is cut in its snapshot, never in what changed or what to do. */ export const WAKE_MAX_CHARS = 30_000; @@ -1797,6 +1798,11 @@ export type DigestRecords = { held: Binding[]; /** Silent notes queued for this digest (a hold that lifted on finished work), one line each. */ notes?: string[]; + /** + * BB-328: the live-check findings new or changed since the last nightly + * pass, deduplicated by fingerprint. An unchanged finding is not repeated. + */ + checkFindings?: CheckFinding[]; }; function capped(lines: string[], none: string): string[] { @@ -1845,6 +1851,11 @@ export function formatRecords(r: DigestRecords, questions: Array<{ question: Que if ((r.notes ?? []).length > 0) out.push("### Notes", "", ...capped((r.notes ?? []).map((n) => `- ${n}`), "Nothing."), ""); + // BB-328: the live half of `check`, new or changed since the last nightly + // pass. Deduplicated by fingerprint, so an unchanged finding is said once. + const checkFindings = r.checkFindings ?? []; + if (checkFindings.length > 0) out.push("### Check findings", "", ...capped(checkFindings.map((f) => `- ${f.level}: ${f.text}`), "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(