diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index df0042ed..a2ff66ff 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -127,10 +127,11 @@ describe("playbooks", () => { } }); - it("tells the default playbooks to file credentials as provide-secret needs and to escalate build-time blockers", () => { + it("tells the default playbooks to raise credentials as a secret escalation and to escalate build-time blockers", () => { const linear = parsePlaybook(LINEAR_TICKETS, "linear-tickets"); if (!linear.ok) throw new Error(linear.error); - expect(phaseInstructions(linear.value, "In Progress")).toMatch(/provide-secret/u); + expect(phaseInstructions(linear.value, "In Progress")).toMatch(/steward_report \{ escalate/u); + expect(phaseInstructions(linear.value, "In Progress")).toMatch(/resolution: "secret"/u); expect(phaseInstructions(linear.value, "In Progress")).toMatch(/writeEnv/u); expect(phaseInstructions(linear.value, "In Progress")).toMatch(/changes what the ticket needs/u); expect(phaseInstructions(linear.value, "In Progress")).toMatch(/escalated as a `decision`/u); diff --git a/plugins/stewards/decisions.test.ts b/plugins/stewards/decisions.test.ts index 964e3e15..edadc45a 100644 --- a/plugins/stewards/decisions.test.ts +++ b/plugins/stewards/decisions.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { defaultDecideList, parseProjectFile, type BigDecision } from "./config.js"; -import { decideFor, decideForEntry, isSelfWidening, SELF_WIDENING_PATHS, touchesAny } from "./decisions.js"; +import { decideFor, decideForEntry, decideForPull, decideForRefusal, isSelfWidening, SELF_WIDENING_PATHS, touchesAny } from "./decisions.js"; const decisions: BigDecision[] = [ { text: "Changing what a ticket's requester asked for", decide: "user", paths: [] }, @@ -49,6 +49,27 @@ describe("the decide list fails closed", () => { expect(decideFor([], null, decisions)).toBe("user"); expect(decideFor(["bb-plugins/plugins/linear/foo.ts"], null, decisions)).toBe("user"); }); + + it("places a pull request by matching its files to a project entry (BB-51)", () => { + // A file under a project entry's paths is the project steward's. + expect(decideForPull(["bb-plugins/plugins/linear/store.ts"], decisions)).toBe("project"); + // A user entry, no matching entry, an empty or unreadable file list, and a + // self-widening change are all the user's. + expect(decideForPull(["bb-plugins/plugins/linear/source-contract.ts"], decisions)).toBe("user"); + expect(decideForPull(["bb-plugins/plugins/linear/wake.ts"], decisions)).toBe("user"); + expect(decideForPull([], decisions)).toBe("user"); + expect(decideForPull(null, decisions)).toBe("user"); + expect(decideForPull(["bb-plugins/plugins/stewards/store.ts"], decisions)).toBe("user"); + }); + + it("gives the failed files fetch its own refusal text, not the self-widening one (BB-51)", () => { + expect(decideForRefusal(null, "A store migration", decisions)).toBe("the changed files could not be read"); + expect(decideForRefusal([], "A store migration", decisions)).toBe("the pull request changes no files"); + expect(decideForRefusal(["bb-plugins/plugins/stewards/store.ts"], "A store migration", decisions)).toBe("the change touches the decide list or the code that enforces it"); + expect(decideForRefusal(["bb-plugins/plugins/linear/store.ts"], "A store migration", decisions)).toBeNull(); + expect(decideForRefusal(["bb-plugins/plugins/linear/wake.ts"], "A store migration", decisions)).toMatch(/do not touch/u); + expect(decideForRefusal(["bb-plugins/plugins/linear/source-contract.ts"], null, decisions)).toBe("no decide-list entry was given"); + }); }); describe("no self-widening", () => { diff --git a/plugins/stewards/decisions.ts b/plugins/stewards/decisions.ts index c569d0ac..5f58633f 100644 --- a/plugins/stewards/decisions.ts +++ b/plugins/stewards/decisions.ts @@ -72,3 +72,35 @@ export function decideFor(files: readonly string[] | null | undefined, entry: st if (isSelfWidening(files)) return "user"; return decideForEntry(entry, decisions, files); } + +/** + * The mark for a pull request the plugin has to place itself, from its changed + * files: a `project` entry whose paths they touch is the project steward's, + * and everything else — no matching entry, a `user` entry, an entry with no + * paths, a self-widening change, or a file list that could not be read — is + * the user's (fail closed). This is the rule the project steward's own + * `approve` applies, so the page and the gate agree (BB-51). + */ +export function decideForPull(files: readonly string[] | null | undefined, decisions: readonly BigDecision[]): DecideMark { + if (files === null || files === undefined || files.length === 0) return "user"; + if (isSelfWidening(files)) return "user"; + const match = decisions.find((d) => d.decide === "project" && d.paths.length > 0 && touchesAny(files, d.paths)); + return match === undefined ? "user" : decideForEntry(match.text, decisions, files); +} + +/** + * Why a pull request is the user's to approve, in words, or null when a + * project-steward approval may be recorded. The null/empty file list gets its + * own text: it is not the self-widening refusal, it is a failed read (BB-51). + */ +export function decideForRefusal(files: readonly string[] | null | undefined, entry: string | null | undefined, decisions: readonly BigDecision[]): string | null { + if (files === null || files === undefined) return "the changed files could not be read"; + if (files.length === 0) return "the pull request changes no files"; + if (isSelfWidening(files)) return "the change touches the decide list or the code that enforces it"; + const wanted = (entry ?? "").trim(); + if (wanted === "") return "no decide-list entry was given"; + const found = decisions.find((d) => d.text === wanted || d.text.toLowerCase() === wanted.toLowerCase()); + if (found === undefined) return `the entry ${JSON.stringify(entry)} is not in the decide list`; + if (found.paths.length > 0 && !touchesAny(files, found.paths)) return `the changed files do not touch ${JSON.stringify(found.text)}'s paths`; + return found.decide === "project" ? null : `the entry ${JSON.stringify(found.text)} is not marked project`; +} diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index acaa6b21..4bbccc17 100644 --- a/plugins/stewards/reconcile.test.ts +++ b/plugins/stewards/reconcile.test.ts @@ -390,6 +390,21 @@ describe("the pull request gate (build-tickets)", () => { expect(prGate(project, { projectApproved: false }).needsOwnerApproval).toBe(true); }); + it("makes the decide mark the whole gate: a project entry the project steward, everything else the owner (BB-51)", () => { + const project = pull({ comments: [marker(head, "approved", "owner-reviewed")] }, green); + const projectWaiting = prGate(project, { decision: "project", projectApproved: false }); + expect(projectWaiting).toMatchObject({ decision: "project", needsProjectApproval: true, needsOwnerApproval: false, gateMet: false, missing: "project steward approval needed" }); + expect(prGate(project, { decision: "project", projectApproved: true })).toMatchObject({ gateMet: true, needsProjectApproval: false }); + // A user entry needs the owner, and a project-steward approval is not the gate. + const userWaiting = prGate(project, { decision: "user", projectApproved: false }); + expect(userWaiting).toMatchObject({ decision: "user", needsOwnerApproval: true, needsProjectApproval: false, gateMet: false, missing: "owner approval needed" }); + expect(prGate(project, { decision: "user", projectApproved: true })).toMatchObject({ projectApproved: false, gateMet: false, needsOwnerApproval: true }); + // An owner approval satisfies the user lane, not the project lane. + const ownerApproved = pull({ comments: [marker(head, "approved", "owner-reviewed"), owner("LGTM")] }, green); + expect(prGate(ownerApproved, { decision: "user" }).gateMet).toBe(true); + expect(prGate(ownerApproved, { decision: "project", projectApproved: false }).gateMet).toBe(false); + }); + it("fails closed on a lane the plugin cannot read (BB-30)", () => { // An unknown lane is treated as owner-reviewed, not no-review. const unknown = prGate(pull({ comments: [marker(head, "approved", "something-else")] }, green)); diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index 14100fe3..695310c2 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -326,8 +326,10 @@ export type PrGate = { gateMet: boolean; /** What is missing, in words; null when the gate is met. */ missing: string | null; - /** The plugin's `approve-pr` condition: owner lane, marker approved, checks green, no owner approval yet. */ + /** The plugin's `approve-pr` condition: user lane, marker approved, checks green, no owner approval yet. */ needsOwnerApproval: boolean; + /** The project steward's side: a `decide: project` entry, marker approved, checks green, no project approval yet. */ + needsProjectApproval: boolean; /** The decide mark applied to this pull request; `user` unless the project steward classified it under a `project` entry. */ decision: "project" | "user"; /** Whether the project steward recorded an approval bound to this head sha. */ @@ -354,9 +356,14 @@ export function prGate(entity: EntitySnapshot, opts: PrGateOptions = {}): PrGate // Only an explicit `no-review` marker skips the owner; a marker the plugin // cannot read, or an unknown lane, is the user's (fail closed). const ownerLane = lane !== "no-review"; + // The gate belongs to whoever the decide list names. An explicit decision + // wins; without one, a recorded project approval means the project steward + // (a project approval is only ever recorded for a `project` entry), and + // everything else is the user's (fail closed). const decision: "project" | "user" = opts.decision === "project" || (opts.decision === undefined && opts.projectApproved === true) ? "project" : "user"; const projectApproved = opts.projectApproved === true && decision === "project"; - const approved = owner.approved || projectApproved; + const approved = decision === "project" ? projectApproved : owner.approved; + const approvalNeeded = ownerLane && markerApproved && checksGreen && !approved; const gateMet = pull !== null && markerApproved && checksGreen && (!ownerLane || approved); const missing = gateMet ? null @@ -383,7 +390,8 @@ export function prGate(entity: EntitySnapshot, opts: PrGateOptions = {}): PrGate ownerApprovalAt: owner.at, gateMet, missing, - needsOwnerApproval: ownerLane && markerApproved && checksGreen && !approved, + needsOwnerApproval: approvalNeeded && decision === "user", + needsProjectApproval: approvalNeeded && decision === "project", decision, projectApproved, }; diff --git a/plugins/stewards/sentry.ts b/plugins/stewards/sentry.ts index b0250f02..b5125a3e 100644 --- a/plugins/stewards/sentry.ts +++ b/plugins/stewards/sentry.ts @@ -16,9 +16,9 @@ import { redactLine, type FingerprintRow, type OpsTarget, type SentryTarget, typ import type { Change } from "./reconcile.js"; export const SENTRY_API_URL = "https://sentry.io"; -/** The look's error when the plugin has no Sentry token to read with; the steward files the provide-secret need for it. */ +/** The look's error when the plugin has no Sentry token to read with; the steward escalates for it. */ export const NO_TOKEN = "no Sentry token is configured"; -/** The setting the token lives in, named so the steward's provide-secret need says where it goes. */ +/** The setting the token lives in, named so the steward's escalation says where it goes. */ export const TOKEN_SETTING = "sentryToken"; /** Where a Sentry user creates an auth token. */ export const TOKEN_PAGE = "https://sentry.io/settings/account/api/auth-tokens/"; diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index e8f35535..8db11ea6 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -7,8 +7,9 @@ import { comment, crashingPod, issue, pull, warningEvent } from "./fixtures.js"; import { kubectlRefusal, type KubectlResult } from "./kubectl.js"; import { createStewardsPlugin, parseDotenvValue, SECRET_SETTING_NAMES, secretVariable, testHooks, type StewardsDeps } from "./server.js"; import { SOURCE_PLUGIN_IDS, type EntitySnapshot } from "./source-contract.js"; -import { MIGRATIONS } from "./store.js"; +import { MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, STEWARD_NEED_KINDS } from "./store.js"; import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, DEPS_ALERTS, DEPS_PRS, projectFileTemplate } from "./templates.js"; +import { STANDING_RULES } from "./wake.js"; type Call = { pluginId: string; method: string; input: Record }; @@ -2825,11 +2826,10 @@ describe("needs you items", () => { it("files approve-pr in the owner lane; the page action posts the unsigned approval and the merge item follows", async () => { const t = await withPull([marker]); const b = t.binding(); - // The owner-reviewed lane is the project steward's to decide (BB-30); it - // forwards to the user, which files the approve-pr item. + // The user's lane is filed on the page at once, with no project-steward + // turn (BB-51); the escalation is with the user. const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval" && x.resolutionKind === "approve-decline")!; - expect(esc).toMatchObject({ route: "project" }); - await t.tool("steward_update", { binding: "ENG-12", forward: esc.id }, t.project); + expect(esc).toMatchObject({ route: "me" }); const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "approve-pr")!; expect(need).toMatchObject({ what: "Approve acme/web#7 on GitHub", filedBy: "plugin" }); expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); @@ -2881,9 +2881,7 @@ describe("needs you items", () => { it("files an approve-pr the owner-lane gate holds (BB-21)", async () => { const t = await withPull([marker]); const b = t.binding(); - const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval" && x.resolutionKind === "approve-decline")!; - const report = await t.tool("steward_update", { binding: "ENG-12", forward: esc.id }, t.project); - expect(report.error).toBe(false); + // No project-steward turn is needed: the plugin files the item itself (BB-51). expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "approve-pr")).toBe(true); expect((await t.harness.behavior.runCli(["needs", "--project", "p1"])).stdout).toMatch(/approve-pr, ENG-12/u); }); @@ -2891,8 +2889,6 @@ describe("needs you items", () => { it("records the gate's missing text when sync closes an approve-pr need (BB-21)", async () => { const t = await withPull([marker]); const b = t.binding(); - const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval" && x.resolutionKind === "approve-decline")!; - await t.tool("steward_update", { binding: "ENG-12", forward: esc.id }, t.project); expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "approve-pr")).toBe(true); // The reviewer's round goes away, so the open item no longer holds; the // closure records what the gate is missing, not the generic line. @@ -3358,6 +3354,176 @@ describe("needs you items", () => { expect(t.hooks.store.openNeeds(b().id).map((n) => n.kind)).toEqual(["merge"]); expect(project).toBeDefined(); }); + + // BB-51: a close on the page resolves the escalation the question was + // forwarded from, in the same write, and tells the origin and the project + // steward. + it("Done on a forwarded question resolves the escalation it came from, wakes the origin, and tells the project steward (BB-51)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; + await t.created("thr_w1", steward, "ENG-12: Implement"); + const b = t.hooks.store.find("ENG-12")!; + await t.harness.behavior.runCli(["escalate", "Add the client secret?"], { threadId: "thr_w1", projectId: "p1" }); + const esc = t.hooks.store.openEscalations(b.id).find((x) => x.question === "Add the client secret?")!; + await t.tool("steward_update", { binding: "ENG-12", forward: esc.id, recommendation: "Yes." }, steward); + await t.tool("steward_update", { binding: "ENG-12", forward: esc.id, resolution: "done" }, project); + const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "configure")!; + expect(need.what).toBe("Add the client secret?"); + const projectWakes = t.sends.filter((s) => s.threadId === project).length; + const res = await t.harness.callRpc("stewardsNeedAction", { needId: need.id, action: "done" }, client); + expect(res).toMatchObject({ ok: true }); + // The escalation the question was forwarded from resolves in the same write. + expect(t.hooks.store.escalation(esc.id)!.status).toBe("resolved"); + expect(t.hooks.store.escalation(need.id)!.status).toBe("resolved"); + await t.hooks.sweep(); + await t.flush(); + // The originating worker hears the answer. + expect(t.sends.find((s) => s.threadId === "thr_w1")!.text).toMatch(/answered/u); + // The project steward's next wake says it was answered, not open. + expect(t.sends.filter((s) => s.threadId === project).length).toBeGreaterThan(projectWakes); + expect(t.sends.filter((s) => s.threadId === project).at(-1)!.text).toMatch(/are resolved|is resolved/u); + }); + + it("a finished requester resolves the escalation the secret question came from (BB-51)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; + await t.created("thr_w1", steward, "ENG-12: Implement"); + const b = t.hooks.store.find("ENG-12")!; + await t.harness.behavior.runCli(["escalate", "Provide API_TOKEN."], { threadId: "thr_w1", projectId: "p1" }); + const esc = t.hooks.store.openEscalations(b.id).find((x) => x.question === "Provide API_TOKEN.")!; + await t.tool("steward_update", { binding: "ENG-12", forward: esc.id, recommendation: "Yes." }, steward); + await t.tool("steward_update", { binding: "ENG-12", forward: esc.id, resolution: "secret", variable: "API_TOKEN", purpose: "deploys" }, project); + const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "provide-secret")!; + const res = (await t.harness.callRpc("stewardsNeedAction", { needId: need.id, action: "provide" }, client)) as { ok: boolean; threadId: string }; + expect(res.ok).toBe(true); + await t.idle(res.threadId, "Provided API_TOKEN."); + await t.flush(); + expect(t.hooks.store.escalation(esc.id)!.status).toBe("resolved"); + expect(t.hooks.store.escalation(need.id)!.status).toBe("resolved"); + await t.hooks.sweep(); + await t.flush(); + expect(t.sends.find((s) => s.threadId === "thr_w1")!.text).toMatch(/answered/u); + }); + + // BB-51 criterion 3: declined heads are remembered, and a checks-state + // change never resolves a request as Approved. + it("does not ask again for a project-lane approval declined on the same head (BB-51)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] } })); + t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t.ring("linear", "uuid-12"); + const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; + const b = t.hooks.store.find("ENG-12")!; + const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval" && x.resolutionKind === "approve-decline")!; + expect(esc).toMatchObject({ route: "project", headSha: "aaaaaaa1" }); + await t.tool("steward_update", { binding: "ENG-12", guidance: "Needs a test first.", resolve: esc.id }, project); + expect(t.hooks.store.escalation(esc.id)!.status).toBe("resolved"); + expect(t.hooks.store.find("ENG-12")!.declinedPrHeadSha).toBe("aaaaaaa1"); + // A report on the same head does not raise a new request. + await t.tool("steward_report", { phase: "In Progress", summary: "Waiting.", nextAction: "Wait", actor: "other" }, steward); + expect(t.hooks.store.openEscalations(b.id).filter((x) => x.kind === "approval")).toEqual([]); + // A new reviewer marker on the same head raises a new request. + const marker2 = comment({ id: "m2", author: "trotterdylan", body: "", signedBy: "thr_reviewer", createdAt: "2026-10-14T16:30:00Z" }); + t.entities.set("acme/web#7", pull({ comments: [marker, marker2] }, { checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + const again = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval")!; + expect(again).toMatchObject({ route: "project", headSha: "aaaaaaa1" }); + // A new head raises a new request too. + await t.tool("steward_update", { binding: "ENG-12", guidance: "Still no.", resolve: again.id }, project); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] }, headSha: "bbbbbbb2" })); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.openEscalations(b.id).some((x) => x.kind === "approval" && x.headSha === "bbbbbbb2")).toBe(true); + }); + + it("leaves an approval request open when checks go pending and never resolves it as Approved (BB-51)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] } })); + t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval")!; + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "pending", failing: [] }, headSha: "bbbbbbb2" })); + await t.ring("linear", "uuid-12"); + const still = t.hooks.store.escalation(esc.id)!; + expect(still.status).toBe("open"); + expect(still.headSha).toBe("bbbbbbb2"); + expect(still.resolution).toBeNull(); + }); + + it("keeps the approve-pr item's identity across a push (BB-51)", async () => { + const t = await withPull([marker]); + const b = t.binding(); + const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "approve-pr")!; + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "pending", failing: [] }, headSha: "bbbbbbb2" })); + await t.ring("linear", "uuid-12"); + const after = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "approve-pr")!; + expect(after.id).toBe(need.id); + expect(after.data.sha).toBe("bbbbbbb2"); + expect(t.hooks.store.openNeeds(b.id).filter((n) => n.kind === "approve-pr")).toHaveLength(1); + }); + + // BB-51 criterion 4: the decide list places the pull request, and a failed + // files fetch gets its own refusal text. + it("gives a failed files fetch its own refusal text, not the self-widening one (BB-51)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] } })); + t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t.ring("linear", "uuid-12"); + const [project] = t.spawns as Array<{ id: string }>; + // The files fetch fails from now on. + t.github.files = async () => { + throw new Error("boom"); + }; + const res = await t.tool("steward_update", { binding: "ENG-12", approve: true, entry: "A cross-repo contract other repos implement" }, project.id); + expect(res.error).toBe(true); + expect(res.text).toMatch(/the changed files could not be read/u); + expect(res.text).not.toMatch(/touches the decide list/u); + }); + + it("routes a project-entry pull request to the project steward and a user-entry one to the page (BB-51)", async () => { + const t1 = await setup(); + t1.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t1.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] } })); + t1.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t1.ring("linear", "uuid-12"); + const b1 = t1.hooks.store.find("ENG-12")!; + expect(t1.hooks.store.openEscalations(b1.id).find((x) => x.kind === "approval")).toMatchObject({ route: "project" }); + expect(t1.hooks.store.openNeeds(b1.id).some((n) => n.kind === "approve-pr")).toBe(false); + + const t2 = await withPull([marker]); + const b2 = t2.binding(); + expect(t2.hooks.store.openEscalations(b2.id).find((x) => x.kind === "approval")).toMatchObject({ route: "me" }); + expect(t2.hooks.store.openNeeds(b2.id).some((n) => n.kind === "approve-pr")).toBe(true); + }); + + // BB-51 criterion 5: one list feeds the standing rules and the refusal. + it("derives the needs a steward may file from one list, so the rules and the refusal cannot drift (BB-51)", async () => { + expect([...ESCALATED_NEED_KINDS, ...STEWARD_NEED_KINDS].sort()).toEqual([...NEEDS_KINDS].sort()); + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + const rules = STANDING_RULES.join("\n"); + for (const kind of ESCALATED_NEED_KINDS) { + expect(rules).toContain(kind); + const res = (await t.harness.behavior.callAgentTool( + "steward_report", + { phase: "Todo", summary: "Specifying.", nextAction: "Wait", actor: "steward", needs: [{ kind, what: `A ${kind}` }] }, + { threadId: steward, projectId: "p1" }, + )) as string | { content: Array<{ text?: string }> }; + const text = typeof res === "string" ? res : res.content.map((c) => c.text ?? "").join(""); + expect(text).toContain(`${kind} for`); + expect(text).toContain("that is an escalation now"); + } + for (const kind of STEWARD_NEED_KINDS) expect(rules).toContain(kind); + }); }); // BB-20: a decide item or forwarded decision question can carry fixed @@ -4751,13 +4917,17 @@ describe("Sentry stewards", () => { expect(wake).toContain("#### 2"); }); - it("without a token, wakes the steward once to file the provide-secret need, and check says so", async () => { + it("without a token, wakes the steward once to escalate for it, and check says so", async () => { const { t, steward, wakes } = await watching({ token: "" }); expect(steward()).toBeDefined(); const first = wakes()[0]!; expect(first).toMatch(/The plugin has no Sentry token, so it cannot read this project/u); - expect(first).toMatch(/File one provide-secret need for it with steward_report: variable `SENTRY_TOKEN`, setting `sentryToken`, url https:\/\/sentry\.io\/settings\/account\/api\/auth-tokens\//u); + expect(first).toMatch(/steward_report \{ escalate: \{ kind: "decision", question: "Provide a Sentry auth token for/u); + expect(first).toMatch(/variable SENTRY_TOKEN, setting sentryToken/u); expect(first).toMatch(/project:read and event:read and event:write/u); + // It does not instruct a refused `needs` filing (BB-51). + expect(first).not.toMatch(/File one provide-secret need/u); + expect(first).not.toMatch(/steward_report \{ needs/u); expect(first).toMatch(/Cannot read sentry-project\/acme\/web: no Sentry token is configured/u); // Said once: the next looks are quiet until a token appears. await t.hooks.sweep(); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 85e8b77c..961fb638 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -46,7 +46,7 @@ import { type Playbook, type ProjectFile, } from "./config.js"; -import { decideFor, decideForEntry } from "./decisions.js"; +import { decideFor, decideForPull, decideForRefusal } from "./decisions.js"; import { alertFingerprint, batchAlert, deadlineAt, depsLookSchema, isBatchable, priorityFor, repoOfFingerprint, sightingOf, type DepsFinding, type DepsLook, type DepsTicket } from "./deps.js"; import { hostContract } from "./host-contract.js"; import { KUBECTL_VERBS, createKubectlReader, kubectlRefusal, type KubectlResult, type OpsAccess, type OpsReader } from "./kubectl.js"; @@ -54,7 +54,7 @@ import { HOOKS_URL_ENV, createHooksLoop, type Lease, type Rejection } from "./ho import { nightlyDue, stillNight } from "./nightly.js"; import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type DependabotTarget, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; import { EVENTS_PER_LOOK, NO_TOKEN, RECENT_PER_LOOK, SENTRY_API_URL, TOKEN_SCOPES, createSentryReader, emptySentryLook, issueInOrg, recentLine, sentryChanges, sentryResolveTargets, sentrySightings, sentrySummary, type SentryFinding, type SentryLook, type SentryReader } from "./sentry.js"; -import { advanced, answerDiffers, anyWorkerInFlight, approvalWanted, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, lifecycle, namesUserAsBlocker, newHumanComments, newestCommentAt, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, type Change } from "./reconcile.js"; +import { advanced, answerDiffers, anyWorkerInFlight, approvalWanted, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, latestReviewMarker, lifecycle, namesUserAsBlocker, newHumanComments, newestCommentAt, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, STEWARDS_PLUGIN_ID, @@ -68,7 +68,7 @@ import { type SessionWake, type Source, } from "./source-contract.js"; -import { ACTORS, MIGRATIONS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store, type Worker } from "./store.js"; +import { ACTORS, MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store, type Worker } from "./store.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY } from "./sidebar-provider.js"; @@ -1474,12 +1474,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } /** Close the provide-secret need a requester was spawned for, once it has finished. */ - function closeRequesterNeed(threadId: string): void { + async function closeRequesterNeed(threadId: string): Promise { const requester = store.secretRequester(threadId); if (requester === null) return; const need = store.need(requester.needId); if (need === null || need.status !== "open") return; - store.closeNeed(need.id, "The requester thread finished; the secret was provided through bb's secure form."); + const b = store.binding(need.bindingId); + const forwarded = forwardedFor(need); + const closure = "The requester thread finished; the secret was provided through bb's secure form."; + store.closeNeed(need.id, closure); + // Criterion 2: the escalation the question was forwarded from resolves in + // the same write, and the project steward is told it is answered. + if (b !== null) await wakeProjectOnForwardedAnswer(b, closure, forwarded); } // ---- the reconcile loop ------------------------------------------------------------------ @@ -2972,6 +2978,44 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return { closure: `The user declined ${b.entityKey}'s spec ${where}${text === null ? "" : `: ${text}`}.`, forwarded }; } + /** + * File or refresh the user's `approve-pr` item: the owner approves on + * GitHub from the Stewards page. Deduped by (binding, kind, url), so a push + * updates the same item's sha rather than closing and refiling it (BB-51). + */ + function fileApprovePrNeed(b: Binding, pull: EntitySnapshot, escalationId: string, headSha: string | null): void { + store.fileNeed({ + bindingId: b.id, + kind: "approve-pr", + url: pull.url ?? pull.key, + what: `Approve ${pull.key} on GitHub`, + how: `Post the unsigned comment "Approved ${shortSha(headSha)} from the Stewards page" as you; that is what counts as your approval.`, + data: { sha: headSha, escalationId }, + filedBy: "plugin", + }); + } + + /** A reviewer marker's identity: a new round on the same head is a new marker (BB-51). */ + const markerKey = (m: ReturnType): string | null => (m === null ? null : `${m.round}:${m.sha}`); + + /** + * The escalation a page close of `need` resolves: the row itself, and the + * escalation the project steward forwarded it from when it is a question + * (BB-51). Gathered before the close so the project steward's wake names + * both. + */ + function forwardedFor(need: Need): Escalation[] { + const x = store.escalation(need.id); + if (x === null) return []; + const out: Escalation[] = []; + if (x.forwardedFrom !== null) { + const parent = store.escalation(x.forwardedFrom); + if (parent !== null) out.push(parent); + } + out.push(x); + return out; + } + /** * The project steward forwarded an escalation to the user, so it holds it * until the user answers. Tell it when the answer lands on the page or from @@ -3017,11 +3061,23 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } let approvalRaised = false; + const config = await loadConfig(b.projectId); + const decisions = config?.file.bigDecisions ?? []; for (const pull of observedPulls(b, observed)) { const url = pull.url ?? pull.key; - const g = prGate(pull, { projectApproved: projectApprovedFor(b, pull) }); + // The decide list places the pull request: a `project` entry whose paths + // the change touches is the project steward's, and everything else is + // the user's, filed on the page at once (BB-51). The files are read only + // when the lane actually waits on an approval. + const preliminary = prGate(pull, { projectApproved: projectApprovedFor(b, pull) }); + let g = preliminary; + if (preliminary.lane !== "no-review" && preliminary.marker?.verdict === "approved" && preliminary.checksGreen && !preliminary.ownerApproved && !preliminary.projectApproved) { + const files = await pullChangedFiles(pull); + g = prGate(pull, { decision: decideForPull(files, decisions), projectApproved: projectApprovedFor(b, pull) }); + } const closed = pull.pull?.merged === true || pull.state === "merged" || pull.state === "closed"; const approvalEsc = store.openEscalations(b.id).find((x) => x.kind === "approval" && x.url === url && x.resolutionKind === "approve-decline") ?? null; + const markerSha = markerKey(g.marker); if (closed) { store.closeNeedByKey(b.id, "approve-pr", url, "The pull request is closed."); store.closeNeedByKey(b.id, "merge", url, "The pull request is closed."); @@ -3029,28 +3085,56 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P continue; } if (g.needsOwnerApproval) { - // The owner-reviewed lane is the project steward's list to decide - // from (BB-30), not the user's page. Raise one escalation per pull - // request and let the project steward approve or forward it. Once - // the project steward has forwarded it to the user, the approve-pr - // item is the page's and is left alone. - if (approvalEsc !== null && approvalEsc.route === "me" && approvalEsc.headSha === g.headSha) { - // With the user; the page's approve-pr item stays. + // The user's lane: the page item is filed as soon as the reviewer's + // marker is approved and checks are green, with no project-steward + // turn (BB-51). Deduped by (binding, kind, url), so a push updates the + // same item rather than closing and refiling it. + if (approvalEsc === null) { + const x = store.escalate({ bindingId: b.id, kind: "approval", question: `Approve ${pull.key}`, meanwhile: "Waiting: the owner approves on GitHub from the Stewards page.", route: "me", recommendation: null, resolutionKind: "approve-decline", url, headSha: g.headSha, projectId: b.projectId }); + fileApprovePrNeed(b, pull, x.id, g.headSha); } else { - store.closeNeedByKey(b.id, "approve-pr", url, "Owner review is the project steward's to decide."); - if (approvalEsc === null) { + if (approvalEsc.headSha !== g.headSha) store.setEscalationHead(approvalEsc.id, g.headSha); + if (approvalEsc.route !== "me") store.reroute(approvalEsc.id, "me", approvalEsc.recommendation); + fileApprovePrNeed(b, pull, approvalEsc.id, g.headSha); + } + } else if (g.needsProjectApproval) { + // The project steward's lane: one escalation, no page item. + store.closeNeedByKey(b.id, "approve-pr", url, "Owner review is the project steward's to decide."); + if (approvalEsc === null) { + // A decline of this head and reviewer marker is not asked again. + if (b.declinedPrHeadSha === g.headSha && b.declinedPrMarker === markerSha) { + // Declined already; wait for a new head or a new marker. + } else { store.escalate({ bindingId: b.id, kind: "approval", question: `Approve ${pull.key}`, meanwhile: "Wait for the project steward's decision.", route: "project", recommendation: null, resolutionKind: "approve-decline", url, headSha: g.headSha, projectId: b.projectId }); approvalRaised = true; - } else { - // A new push is a new sha: the old approval (if any) is void and - // the request is re-pointed at the head to decide. - store.setEscalationHead(approvalEsc.id, g.headSha); + } + } else { + if (approvalEsc.headSha !== g.headSha) store.setEscalationHead(approvalEsc.id, g.headSha); + if (approvalEsc.route === "me") { + // A change from the user's lane to the project steward's: ask it. store.reroute(approvalEsc.id, "project", null); + approvalRaised = true; } } + } else if (approvalEsc !== null) { + if (g.checksGreen === false) { + // Checks went pending or failing: never resolve the request as + // approved. Keep it and the page item open, re-pointed at the head. + if (approvalEsc.headSha !== g.headSha) store.setEscalationHead(approvalEsc.id, g.headSha); + if (approvalEsc.route === "me") fileApprovePrNeed(b, pull, approvalEsc.id, g.headSha); + store.note(b.id, `${pull.key}'s checks are ${g.checksState ?? "not run"}; its approval request stays open.`, true); + } else if (g.ownerApproved || g.projectApproved) { + store.closeNeedByKey(b.id, "approve-pr", url, "Approval is present."); + store.resolve(approvalEsc.id, g.projectApproved ? "Approved by the project steward." : "Approved by the owner."); + } else { + // The marker is no longer approved (or gone): withdraw the request + // with the gate's words, never "Approved.". + const why = g.missing ?? "The pull request is not waiting for an owner approval."; + store.closeNeedByKey(b.id, "approve-pr", url, why); + store.resolve(approvalEsc.id, why); + } } else { - store.closeNeedByKey(b.id, "approve-pr", url, g.ownerApproved || g.projectApproved ? "Approval is present." : `${g.missing ?? "The pull request is not waiting for an owner approval."}`); - if (approvalEsc !== null) store.resolve(approvalEsc.id, g.projectApproved ? "Approved by the project steward." : "Approved."); + store.closeNeedByKey(b.id, "approve-pr", url, `${g.missing ?? "The pull request is not waiting for an owner approval."}`); } if (g.gateMet) { // A steward's own merge item (a refused merge) is left alone while a @@ -3223,7 +3307,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (worker !== null) { if (worker.status === "stopped") return; store.setWorker(thread.id, "finished", lastAssistantText === null ? null : clip(lastAssistantText, 4000)); - closeRequesterNeed(thread.id); + await closeRequesterNeed(thread.id); // Its turn is over: the reviewers it read (or started and then waited // on) have had their round consumed (BB-47). await archiveConsumedReviewers(thread.id); @@ -3404,11 +3488,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } }); - bb.events.on("thread.failed", ({ thread, error }) => { + bb.events.on("thread.failed", async ({ thread, error }) => { const worker = store.worker(thread.id); if (worker === null || !workerInFlight(worker)) return; store.setWorker(thread.id, "failed", error); - closeRequesterNeed(thread.id); + await closeRequesterNeed(thread.id); store.note(worker.bindingId, `Worker "${worker.title}" failed: ${error ?? "no detail"}`); scheduleReconcile(worker.bindingId); }); @@ -3894,6 +3978,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (need === null || need.status !== "open") return { ok: false, message: "That item is already closed." }; const b = store.binding(need.bindingId); if (b === null) return { ok: false, message: "That binding is gone." }; + // The escalation this item resolves, and the escalation it was forwarded + // from: gathered before the close so the project steward's wake names + // both (BB-51). + const forwarded = forwardedFor(need); if (action === "choose" && need.kind !== "decide") return { ok: false, message: `Choices are for a decide item; this is ${need.kind}.` }; const text = note === undefined || note === null || note.trim() === "" ? null : note.trim(); /** Close the item and wake the steward with what happened. */ @@ -3961,8 +4049,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (need.kind === "configure") { if (action !== "done") return { ok: false, message: "Press Done once the step is finished." }; + const closure = `The user did ${need.what}${text === null ? "" : `: ${text}`}.`; store.closeNeed(need.id, text === null ? "Done on the Stewards page." : `Done on the Stewards page: ${text}`, "user"); - after(`The user did ${need.what}${text === null ? "" : `: ${text}`}.`); + after(closure); + await wakeProjectOnForwardedAnswer(b, closure, forwarded); return { ok: true, message: `Marked done; ${b.entityKey}'s steward has been told.` }; } @@ -3971,8 +4061,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const named = typeof need.data.variable === "string" && need.data.variable.trim() !== "" ? need.data.variable.trim() : need.what; // Done is the manual escape hatch: the value was entered another way. if (action === "done") { + const closure = `The user marked ${named} done on the Stewards page${text === null ? "" : `: ${text}`}; the value was entered another way.`; store.closeNeed(need.id, text === null ? "Marked done on the Stewards page." : `Marked done on the Stewards page: ${text}`, "user"); - after(`The user marked ${named} done on the Stewards page${text === null ? "" : `: ${text}`}; the value was entered another way.`); + after(closure); + await wakeProjectOnForwardedAnswer(b, closure, forwarded); return { ok: true, message: `Recorded; ${b.entityKey}'s steward has been told.`, threadId: null }; } // Provide opens bb's secure form in a requester thread the plugin @@ -4053,12 +4145,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } store.note(b.id, `The user chose ${label} for ${need.what}${text === null ? "" : `: ${text}`}.`); scheduleReconcile(b.id); + await wakeProjectOnForwardedAnswer(b, `The user chose ${label} for ${need.what}${text === null ? "" : `: ${text}`}.`, forwarded); return { ok: true, message: `Recorded; ${b.entityKey}'s steward has been told.` }; } // `decide` is the question mechanism; a raw item of that kind just closes. + const closure = `${need.kind} item ${need.id} was closed on the Stewards page${text === null ? "" : `: ${text}`}.`; store.closeNeed(need.id, text === null ? "Closed on the Stewards page." : `Closed on the Stewards page: ${text}`, "user"); - after(`${need.kind} item ${need.id} was closed on the Stewards page${text === null ? "" : `: ${text}`}.`); + after(closure); + await wakeProjectOnForwardedAnswer(b, closure, forwarded); return { ok: true, message: `Closed; ${b.entityKey}'s steward has been told.` }; }, }); @@ -4326,7 +4421,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // Fixed choices are for a decision, as a `decide` need is: they are // what a forwarded escalation turns into a question with buttons. if (input.escalate !== undefined && input.escalate.choices !== undefined && input.escalate.kind !== "decision") { - return toolError(new Error("choices are for a decision escalation: escalate a decision, or file a decide need.")); + return toolError(new Error("choices are for a decision escalation: escalate a decision with choices.")); } const config = await loadConfig(b.projectId); const playbook = config === null ? null : bindingPlaybook(config, b); @@ -4362,7 +4457,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (input.blockedOn !== undefined && namesUserAsBlocker(input.blockedOn) && store.openNeeds(b.id).length === 0 && (input.needs ?? []).length === 0) { return toolError( new Error( - `blockedOn names the user, the owner or a human, but nothing is filed for them. File it as a needs item (steward_report { needs: [{ kind, url, what, how }] }) and it appears on the Stewards page; blockedOn stays for third parties.`, + `blockedOn names the user, the owner or a human, but nothing is filed for them. File it as a needs item (steward_report { needs: [{ kind, url, what, how }] }) — or, for a credential, a step outside the repos or a decision, raise it with steward_report { escalate: { kind, question, meanwhile } } — and it appears on the Stewards page; blockedOn stays for third parties.`, ), ); } @@ -4416,10 +4511,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const refused: string[] = []; for (const n of input.needs ?? []) { // The plugin files the gate items (approve-spec, approve-pr, merge); - // a steward-filed decide, configure or provide-secret is an + // a credential, a step outside the repos or a decision is an // escalation now (BB-30), so it is refused here and pointed at - // steward_report { escalate }. - if (n.kind === "decide" || n.kind === "configure" || n.kind === "provide-secret") { + // steward_report { escalate }. The list is one constant, so the + // refusal cannot drift from the standing rules (BB-51). + if ((ESCALATED_NEED_KINDS as readonly string[]).includes(n.kind)) { refused.push(`${n.kind} for ${n.what} not filed: that is an escalation now. Raise it with steward_report { escalate: { kind, question, meanwhile } } and the project steward forwards it, or answers it itself.`); continue; } @@ -4427,7 +4523,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const url = n.url ?? n.worker ?? b.url ?? ""; const wanted = lc(url); const pull = b.lastSnapshot === null ? undefined : observedPulls(b, b.lastSnapshot).find((p) => [p.url, p.key, p.id].some((v) => v !== null && lc(v) === wanted)); - const gate = pull === undefined ? null : prGate(pull, { projectApproved: projectApprovedFor(b, pull) }); + // The decide list places the pull request, so a steward cannot + // file the user's item for the project steward's lane (BB-51). + const decision = pull === undefined ? "user" : decideForPull(await pullChangedFiles(pull), config?.file.bigDecisions ?? []); + const gate = pull === undefined ? null : prGate(pull, { decision, projectApproved: projectApprovedFor(b, pull) }); const holdable = gate !== null && (n.kind === "approve-pr" ? gate.needsOwnerApproval : gate.gateMet); if (!holdable) { refused.push(`${n.kind} for ${url === "" ? "the pull request" : url} not filed: ${gate?.missing ?? "the pull request has not been observed yet"}. The owner is asked only once the reviewer's marker says approved; the worker must run the build-tickets review loop first.`); @@ -4731,7 +4830,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const files = pull === null ? null : await pullChangedFiles(pull); const decision = decideFor(files, input.entry ?? null, config.file.bigDecisions); if (decision !== "project") { - const why = input.entry === undefined ? "no decide-list entry was given" : decideForEntry(input.entry, config.file.bigDecisions) === "user" ? `the entry ${JSON.stringify(input.entry)} is not marked project` : "the change touches the decide list or the code that enforces it"; + const why = decideForRefusal(files, input.entry ?? null, config.file.bigDecisions) ?? "the change is not the project steward's to approve"; return toolError(new Error(`That pull request is the user's to approve: ${why}. Forward it with steward_update { binding: "${target.entityKey}", forward: "${prApproval.id}", resolution: "approve-decline", recommendation } instead.`)); } store.recordProjectApproval({ bindingId: target.id, headSha: prApproval.headSha ?? "", entry: input.entry ?? null, byThread: threadId }); @@ -4914,7 +5013,16 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (resolving !== null) { // Already resolved (the binding ended, a retry) is no error: the answer is added to the record. const outcome = store.answerEscalation(resolving.id, guidance!, threadId); - if (resolving.kind === "approval" && resolving.status === "open" && approval === null && target.lastSnapshot !== null) { + if (resolving.kind === "approval" && resolving.resolutionKind === "approve-decline" && resolving.status === "open" && approval === null && classifyApproval(guidance) !== "approve") { + // A declined pull-request approval: remember the head and the + // reviewer marker so the same one is not asked again (BB-51). + const pull = target.lastSnapshot === null ? null : observedPulls(target, target.lastSnapshot).find((p) => (p.url ?? p.key) === resolving.url) ?? null; + store.patch(target.id, { + declinedPrHeadSha: resolving.headSha ?? pull?.pull?.headSha ?? null, + declinedPrMarker: pull === null ? null : markerKey(latestReviewMarker(pull.comments)), + }); + done.push(`remembered the decline of ${shortSha(resolving.headSha)} so the same head and reviewer marker are not asked again`); + } else if (resolving.kind === "approval" && resolving.status === "open" && approval === null && target.lastSnapshot !== null) { const fresh = store.binding(target.id)!; store.patch(target.id, { ready: { ...fresh.ready, declinedSpecHash: specHashFor(fresh, fresh.lastSnapshot!.entity) } }); } @@ -5615,6 +5723,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (choices.length === 0) throw new PluginCliError(`Item ${id} has no choices; close it without --choice.`, { code: "no_choices" }); if (!choices.includes(choice)) throw new PluginCliError(`"${choice}" is not one of ${id}'s choices: ${choices.join(", ")}.`, { code: "bad_choice", hint: `bb stewards needs prints them.` }); const guidance = note === null ? choice : `${choice} — ${note}`; + const forwarded = forwardedFor(n); store.closeNeed(n.id, `Chose: ${choice}${note === null ? "" : ` — ${note}`}`, "user"); const b = store.binding(n.bindingId); if (b !== null) { @@ -5626,10 +5735,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (escalation !== null && escalation.status === "open") store.answerEscalation(escalationId, guidance, "user"); } scheduleReconcile(b.id); + await wakeProjectOnForwardedAnswer(b, `The user chose ${choice} for ${n.what}${note === null ? "" : `: ${note}`}.`, forwarded); } return { exitCode: 0, stdout: `Chose ${choice} for ${id}.` }; } const b = store.binding(n.bindingId); + const forwarded = forwardedFor(n); // An `approve-spec` item is a decision, not a step to tick off: // `done` records the approval through the same path the page's // Approve button and `steward_update { approve }` use, so the @@ -5650,6 +5761,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (note !== null) store.addGuidance(b.id, note, "user"); store.note(b.id, note === null ? `${n.kind} item ${n.id} was closed from a thread.` : `${n.kind} item ${n.id} was answered from a thread: ${note}.`); scheduleReconcile(b.id); + await wakeProjectOnForwardedAnswer(b, note === null ? `${n.kind} item ${n.id} was closed from a thread.` : `${n.kind} item ${n.id} was answered from a thread: ${note}.`, forwarded); } return { exitCode: 0, stdout: `Closed ${id}.` }; }, @@ -5744,6 +5856,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P throw new PluginCliError(`Could not write the ${setting} setting; the value was not saved.`, { code: "write_failed" }); } await bb.sdk.files.remove({ hostId, path: from }).catch(() => undefined); + // Criterion 2: importing the secret closes the item and the + // escalation it was forwarded from in one write, and the project + // steward is told it is answered. + const b = store.binding(need.bindingId); + const forwarded = forwardedFor(need); + const closure = `The secret ${variable} was imported into ${setting}${b === null ? "" : ` for ${b.entityKey}`}.`; + store.closeNeed(need.id, closure, "user"); + if (b !== null) await wakeProjectOnForwardedAnswer(b, closure, forwarded); return { exitCode: 0, stdout: `Imported ${setting}; the dotenv is gone.` }; }, }), diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 085946fd..144b9c2e 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -139,8 +139,8 @@ Two tools are yours; everything else you do with the tools every thread has. project steward or the user reaches nobody; with no open escalation it is flagged in `bb stewards list` and the digest. A `blockedOn` naming the user, the owner or a human is refused unless an open needs item says so: - file it (`configure`, `provide-secret`, `decide`) instead of only saying - it. `blockedOn` stays for third parties. + raise it with `steward_report { escalate }` (or file a gate item) instead + of only saying it. `blockedOn` stays for third parties. - **Do not repeat yourself.** Before acting, look for evidence it is done: a signed comment, a worker, a pull request, a review. - **Holds.** A held binding takes no new actions and starts no workers. @@ -210,9 +210,9 @@ is the plugin's, so diagnose from the wake and the code in your workspace. duplicate. - **All healthy:** the wake says so every requeue; report it with `actor: other` and end the turn. -- **No Sentry token** (the wake says so): file the one `provide-secret` - need it describes (variable `sentryToken`, the Sentry auth-tokens page, - the scopes), report with `actor: me`, and end the turn. +- **No Sentry token** (the wake says so): raise the escalation it describes + (variable `SENTRY_TOKEN`, setting `sentryToken`, the Sentry auth-tokens + page, the scopes), report with `actor: me`, and end the turn. - **No logs** (the wake says so): diagnose from status and events, and say in the ticket that logs were not available. diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 29d2c5bc..1f3f5517 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -342,7 +342,15 @@ export const WORKER_CHECK_MIGRATIONS = [ `ALTER TABLE workers ADD COLUMN model_check_pending INTEGER NOT NULL DEFAULT 0`, ]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS]; +// BB-51: the pull-request head (and reviewer marker) a project-steward approval +// request was declined on, so the same head is not asked again. Additive and +// defaulted: existing rows keep asking as before. +export const DECLINED_PR_MIGRATIONS = [ + `ALTER TABLE bindings ADD COLUMN declined_pr_head_sha TEXT`, + `ALTER TABLE bindings ADD COLUMN declined_pr_marker TEXT`, +]; + +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -463,6 +471,10 @@ export type Binding = { /** When follow-through runs out, whatever the steward says: set when it is first declared. */ followThroughUntil: number | null; manualDetach: boolean; + /** The pull-request head a project-steward approval request was declined on; not asked again until the head (or the reviewer marker) changes. */ + declinedPrHeadSha: string | null; + /** The reviewer marker in force when that head was declined, so a new round asks again. */ + declinedPrMarker: string | null; /** An ops binding's last look; null for every other kind. */ opsLook: OpsLook | null; /** A Dependabot alert binding's last look; null for every other kind. */ @@ -523,6 +535,8 @@ function rowToBinding(r: BindingRow): Binding { followThrough: str("follow_through"), followThroughUntil: num("follow_through_until"), manualDetach: Number(r.manual_detach) === 1, + declinedPrHeadSha: str("declined_pr_head_sha"), + declinedPrMarker: str("declined_pr_marker"), opsLook: json(opsLookSchema.nullable(), str("ops_look"), null), depsLook: json(depsLookSchema.nullable(), str("deps_look"), null), sentryLook: json(sentryLookSchema.nullable(), str("sentry_look"), null), @@ -570,6 +584,8 @@ const COLUMNS = { followThrough: "follow_through", followThroughUntil: "follow_through_until", manualDetach: "manual_detach", + declinedPrHeadSha: "declined_pr_head_sha", + declinedPrMarker: "declined_pr_marker", opsLook: "ops_look", depsLook: "deps_look", sentryLook: "sentry_look", @@ -681,6 +697,18 @@ export type Question = { export const NEEDS_KINDS = ["approve-spec", "approve-pr", "merge", "decide", "provide-secret", "configure"] as const; export type NeedKind = (typeof NEEDS_KINDS)[number]; +/** + * The steward-filed `needs` kinds that are escalations since BB-30: a + * credential, a step outside the repos, or a decision is raised with + * `steward_report { escalate }`, and `steward_report { needs }` refuses it. + * One list feeds the standing rules and the refusal text, so they cannot + * drift (BB-51). + */ +export const ESCALATED_NEED_KINDS = ["decide", "configure", "provide-secret"] as const; + +/** The `needs` kinds a steward may still file directly: the plugin's gate items. */ +export const STEWARD_NEED_KINDS = NEEDS_KINDS.filter((k): k is NeedKind => !(ESCALATED_NEED_KINDS as readonly NeedKind[]).includes(k)); + /** * One "needs you" item: a structured thing the user must do, filed by the * plugin from a snapshot or by a steward through `steward_report`. `url` is the @@ -843,6 +871,7 @@ export function createStore(db: Database.Database, now: () => number, options: S // the question's resolution, so the page and wakes show the question/item once. const openQuestionCovered = db.prepare<[string], { forwarded_from: string }>("SELECT DISTINCT forwarded_from FROM escalations WHERE project_id = ? AND is_question = 1 AND status = 'open' AND forwarded_from IS NOT NULL"); const answerQuestion = db.prepare("UPDATE escalations SET status = 'resolved', resolution = ?, answered_by = ?, resolved_at = ? WHERE id = ? AND is_question = 1 AND status = 'open'"); + const forwardedFromOf = db.prepare<[string], Record>("SELECT * FROM escalations WHERE id = (SELECT forwarded_from FROM escalations WHERE id = ?)"); const answerForEscalation = db.prepare("UPDATE escalations SET status = 'resolved', resolution = ?, answered_by = ?, resolved_at = ? WHERE forwarded_from = ? AND is_question = 1 AND status = 'open'"); const appendAnswerForEscalation = db.prepare("UPDATE escalations SET resolution = ? WHERE forwarded_from = ? AND is_question = 1 AND status = 'resolved'"); @@ -1093,7 +1122,13 @@ export function createStore(db: Database.Database, now: () => number, options: S } } - /** Resolve an open escalation, and close the question forwarding it made, if any. `by` is who answered it. */ + /** + * Resolve an open escalation. The question made from it closes with it, and + * the escalation a question was forwarded from closes too, so a close on the + * page (answer, Done, a finished requester, a secret import) resolves the + * whole pair in one write and the originator hears the answer (BB-51). `by` + * is who answered it. + */ function resolve(id: string, resolution: string, by = "plugin"): boolean { return coalescing(() => { const resolved = db.transaction(() => { @@ -1102,6 +1137,14 @@ export function createStore(db: Database.Database, now: () => number, options: S answerForEscalation.run(resolution, by, at, id); const x = getEscalation.get(id); if (x !== undefined) recordResolutionDelivery(toEscalation(x), resolution, by); + // Follow the link up: a question resolved on the page also resolves the + // escalation the project steward forwarded it from. + const parent = forwardedFromOf.get(id); + if (parent !== undefined && String(parent.status) === "open") { + resolveEscalation.run(resolution, at, String(parent.id)); + recordResolutionDelivery(toEscalation(parent), resolution, by); + answerForEscalation.run(resolution, by, at, String(parent.id)); + } return true; })(); if (resolved) { diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index 557b85bd..c8af3367 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -9,7 +9,7 @@ import { DEFAULT_BIG_DECISIONS, DEFAULT_LABEL, defaultDecideList } from "./confi * user sees. */ const SECRET_REQUEST = - "A credential the work needs is a `provide-secret` need, not a worker's job to prompt: file it with `steward_report { needs: [{ kind: \"provide-secret\", url, what, how, variable, purpose }] }` and the plugin opens bb's secure form in a requester thread. Name the `writeEnv` dotenv path (or `worker`) for a worker's machine, or the `setting` for one of the stewards plugin's own secret settings. Never paste the secret, and never a script for the user to run."; + "A credential the work needs is a decision escalation, not a worker's job to prompt: raise it with `steward_report { escalate: { kind: \"decision\", question, meanwhile } }`, naming the variable and what it is for. The project steward forwards it with `resolution: \"secret\"` and either the `writeEnv` dotenv path (or `worker`) for a worker's machine, or the `setting` for one of the stewards plugin's own secret settings; the plugin then opens bb's secure form in a requester thread. Never paste the secret, and never a script for the user to run."; /** * A build-time blocker is a `decision` in the same turn, never a follow-up, @@ -262,7 +262,7 @@ look, with the title, culprit, permalink, event and user counts, first and last seen, and the latest event's stack trace. Your thread holds no Sentry token, so you cannot query Sentry: diagnose from that evidence and the code in your workspace (the in-app frames name it), and link the permalink. When -the wake says there is no token, file the provide-secret need it describes +the wake says there is no token, raise the escalation it describes and nothing else. Each problem has a fingerprint: for a namespace the workload, the container diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index 2dd9fe17..bbb518e4 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -3,9 +3,10 @@ import { describe, expect, it } from "vitest"; import { parsePlaybook } from "./config.js"; import { comment, issue, pull } from "./fixtures.js"; import { gateState } from "./reconcile.js"; -import { MIGRATIONS, createStore } from "./store.js"; +import { MIGRATIONS, RESOLUTION_KINDS, createStore } from "./store.js"; +import { ESCALATED_NEED_KINDS } from "./store.js"; import { LINEAR_TICKETS } from "./templates.js"; -import { formatProjectWake, formatWake, workerQuestion, type DigestRecords, type WakeInput } from "./wake.js"; +import { STANDING_RULES, formatProjectWake, formatWake, workerQuestion, type DigestRecords, type WakeInput } from "./wake.js"; const T = Date.parse("2026-10-18T05:00:00Z"); const DAY = 86_400_000; @@ -47,13 +48,16 @@ function wakeInput(over: Partial = {}): WakeInput { } describe("a steward's wake", () => { - it("carries the standing rules: credentials as provide-secret needs, one ask, and build-time decisions", () => { + it("carries the standing rules: a credential is an escalation, not a provide-secret need (BB-51)", () => { const wake = formatWake(wakeInput()); - expect(wake).toContain("provide-secret"); + expect(wake).toContain("steward_report { escalate"); + for (const kind of ESCALATED_NEED_KINDS) expect(wake).toContain(kind); expect(wake).toContain("writeEnv"); expect(wake).toMatch(/never paste a secret/iu); expect(wake).toContain("One ask per reply"); expect(wake).toContain("escalated as a `decision` in the same turn"); + // The old contradiction is gone: no rule tells a steward to file one. + expect(wake).not.toMatch(/File it with `steward_report \{ needs/); }); it("names the worker and reviewer models as flags that are not the steward's to choose", () => { @@ -174,6 +178,19 @@ describe("the nightly prompt", () => { expect(wake).toMatch(/forward, recommendation, cites: \[lesson ids\]/u); }); + it("names the five resolution kinds and how a credential is forwarded (BB-51)", () => { + const { s, bind } = world(); + const b = bind("ENG-12"); + const x = s.escalate({ bindingId: b.id, kind: "decision", question: "Provide API_TOKEN.", meanwhile: "Wait.", route: "project", recommendation: null }); + const wake = formatProjectWake({ reason: "escalation", bindings: [], routed: [{ escalation: x, from: b }], problems: [], digestDue: false, notes: [], bigDecisions: [], questions: [] }); + for (const kind of RESOLUTION_KINDS) expect(wake).toContain(`\`${kind}\``); + expect(wake).toMatch(/resolution: "secret"/u); + expect(wake).toContain("variable"); + expect(wake).toContain("purpose"); + expect(wake).toContain("writeEnv"); + expect(wake).toContain("setting"); + }); + it("gives dates in the project's nightly time zone", () => { const { s } = world(); const q = s.ask({ projectId: "p1", bindingId: null, escalationId: null, question: "Freeze on Friday?", context: null }); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index f8592ad5..c013029f 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -14,7 +14,7 @@ import { NO_TOKEN, TOKEN_PAGE, TOKEN_SCOPES, TOKEN_SETTING, type SentryFinding, import { newHumanComments, prGate, reportedItem, unheardWait, type GateState } from "./reconcile.js"; import { conflictsOf, type Conflict } from "./schedule.js"; import type { EntitySnapshot, SessionWake, SnapshotComment } from "./source-contract.js"; -import { needChoices, type Binding, type Escalation, type Lesson, type Need, type Observed, type Question, type Worker } from "./store.js"; +import { needChoices, ESCALATED_NEED_KINDS, RESOLUTION_KINDS, STEWARD_NEED_KINDS, type Binding, type Escalation, type Lesson, type Need, type Observed, type Question, type Worker } from "./store.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; @@ -29,11 +29,15 @@ const OPEN_REQUESTS_NOTE = "These are listed for the user on the Stewards page. * The rules that hold on every wake, whatever the playbook: the generic things * a steward got wrong without them. They mirror the `stewards` skill and the * default playbooks, so a change here belongs there too. + * + * The escalated need kinds are named from one list (BB-51): the standing rules + * and `steward_report`'s refusal derive from `ESCALATED_NEED_KINDS`, so a + * steward is never told to file what the tool refuses. */ -const STANDING_RULES = [ +export const STANDING_RULES = [ "- **One ask per reply.** Ask the user at most one thing, and only what the playbook, the project's guidance or the `stewards` skill leaves open. Anything they settle — models, flags, lanes, who merges — is never asked.", - "- **What only the user can do is a `needs` item.** File it with `steward_report { needs: [{ kind, url, what, how }] }` — a step outside the repos (`configure`), a secret (`provide-secret`), or a decision (`decide`). A `decide` item that is really a pick between fixed options carries `choices` (2-6 short labels, e.g. `choices: [\"Merge\", \"Close\", \"Verify first\"]`), and the page shows one button each; never write \"reply with your choice\" in prose. It is on the Stewards page with its button; do not ask for it in prose, and do not name the user in `blockedOn` without one.", - "- **A credential is a `provide-secret` need, not a worker's job to prompt.** File it with `steward_report { needs: [{ kind: \"provide-secret\", url, what, how, variable, purpose }] }`; the plugin spawns a requester thread and opens bb's secure form there. For a dotenv on a worker's machine name `writeEnv` (or `worker`); for one of the stewards plugin's own settings name `setting` (only a declared secret setting is accepted). Never paste a secret, and never route the user to a script to run.", + `- **What only the user can do is an escalation, not a need.** A credential, a step outside the repos, or a decision — ${ESCALATED_NEED_KINDS.map((k) => `\`${k}\``).join(", ")} — is raised with \`steward_report { escalate: { kind, question, meanwhile } }\`: the project steward decides it or forwards it to the user. Since BB-30 \`steward_report { needs }\` refuses exactly those ("that is an escalation now"); it still takes the plugin's gate items (${STEWARD_NEED_KINDS.map((k) => `\`${k}\``).join(", ")}). A decision that is really a pick between fixed options carries \`choices\` (2-6 short labels, e.g. \`choices: ["Merge", "Close", "Verify first"]\`), and the page shows one button each; never write "reply with your choice" in prose.`, + "- **A credential is a decision escalation, and the project steward forwards it as a secret.** Raise it with `steward_report { escalate: { kind: \"decision\", question, meanwhile } }`, naming the variable and what it is for in the question. The project steward forwards it with `resolution: \"secret\"` and either `writeEnv`/`worker` (the dotenv a worker reads) or `setting` (a declared secret setting of the stewards plugin); the plugin then spawns a requester thread and opens bb's secure form there. Never paste a secret, and never route the user to a script to run.", "- **A finding that would stop the feature working once it ships**, or that changes what the ticket needs (a credential, an access, a contract), is escalated as a `decision` in the same turn, quoting the worker's words — never relayed as a follow-up. An escalation that asks the user to pick between fixed options carries `choices` (2-6 short labels) so the page shows one button each.", ]; /** @@ -731,7 +735,7 @@ export function formatSentryWake(input: SentryWakeInput): string { if (look.error === NO_TOKEN) { out.push( `**The plugin has no Sentry token, so it cannot read this project.** The token is the \`${TOKEN_SETTING}\` setting of the stewards plugin on this bb server (Settings → Plugins → Stewards), entered by the user, never pasted into a thread. ` + - `File one provide-secret need for it with steward_report: variable \`SENTRY_TOKEN\`, setting \`${TOKEN_SETTING}\`, url ${TOKEN_PAGE}, what "Create a Sentry auth token with the scopes ${TOKEN_SCOPES.join(" and ")} and enter it as the stewards plugin's Sentry token setting", and the steps in how. ` + + `Raise one escalation for it with steward_report { escalate: { kind: "decision", question: "Provide a Sentry auth token for ${look.target}: variable SENTRY_TOKEN, setting ${TOKEN_SETTING}, url ${TOKEN_PAGE}; create it with the scopes ${TOKEN_SCOPES.join(" and ")} and enter it as the stewards plugin's Sentry token setting.", meanwhile: "Wait: this project cannot be read until the token is provided." } }. The project steward forwards it with resolution "secret", variable "SENTRY_TOKEN" and setting "${TOKEN_SETTING}", and the plugin opens bb's secure form. ` + "Then report with actor me and end the turn; the first look that reads the project wakes you.", ); } else if (look.error !== null) out.push(`The project could not be read: ${look.error}. Nothing to do until it can; \`bb stewards check\` says why.`); @@ -805,6 +809,8 @@ export function formatProjectWake(input: { "", ...input.bigDecisions.map((d) => `- ${d.text}${d.decide === "user" ? " [user]" : " [project]"}`), "", + `A forward to the user carries a \`resolution\` saying how the page asks: ${RESOLUTION_KINDS.map((k) => `\`${k}\``).join(", ")}. A credential is forwarded with \`resolution: "secret"\`, naming \`variable\` and \`purpose\`, and either \`writeEnv\`/\`worker\` (the dotenv a worker reads) or \`setting\` (a declared secret setting of the stewards plugin); the plugin then opens bb's secure form in a requester thread.`, + "", ); if (input.routed.some((r) => r.from.kind === "ops")) { out.push(