From 51191ad288ad9d48bbaf990be7fbe6939ab8d86c Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 19 Oct 2026 21:01:36 +0000 Subject: [PATCH 1/3] stewards: one spec approval from any surface (BB-13) An approval was recorded only from the project steward's approve: true or from a message in the steward's own thread, and resolving an approval escalation with approving words marked the spec declined. The page answer recorded nothing, so syncApprovalRequest filed a fresh request, and a spec comment the user wrote from their own thread was not part of the spec. Record the approval wherever the approver's words are: the project steward's approving guidance resolving the request, an affirmative answer on the Stewards page (which records it and resolves the escalation in one transaction), an unsigned approving comment on the entity, or the user's own spec comment with approval: me. A page answer that is neither an approval nor a clear refusal goes back to the project steward to interpret, not a decline. A spec comment signed by a thread the user runs counts toward the spec hash, and while an approval request is open the report and wake say not to ask the user again; a report that does shows as a playbook violation in bb stewards show. --- plugins/stewards/README.md | 14 ++- plugins/stewards/reconcile.test.ts | 34 +++++- plugins/stewards/reconcile.ts | 72 ++++++++++-- plugins/stewards/server.test.ts | 178 +++++++++++++++++++++++++++++ plugins/stewards/server.ts | 117 ++++++++++++++++--- plugins/stewards/store.ts | 28 +++++ plugins/stewards/wake.ts | 4 +- 7 files changed, 415 insertions(+), 32 deletions(-) diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index d563e072..aa4776b9 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -86,8 +86,18 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. substantial and the current spec has no approval, it files an `approval` escalation with the approver (the project steward, or the user in the steward's thread), whatever the steward's report says, and closes it once - approved or no longer needed. A request the approver declines is not made - again until the spec changes. When the entity changes while one of its + approved or no longer needed. An approval is recorded from the approver's + words wherever they are: the project steward's guidance that resolves the + request, the user's answer on the Stewards page, their message in the + steward's thread, or their unsigned approving comment on the entity. A + page answer that is neither an approval nor a clear refusal goes back to + the project steward to interpret, rather than being remembered as a + decline. A spec comment the user writes from their own thread counts + toward the spec and, with `approval: me`, is its own approval. A request + the approver declines is not made again until the spec changes, and while + one is open the steward is told not to ask the user again: the request is + on the Stewards page, and a report that asks anyway shows as a playbook + violation in `bb stewards show`. When the entity changes while one of its escalations is with you, the project steward is woken with the change too, since you may have answered on the ticket rather than in its thread. A status blocked on the project steward or the user with no open diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index b6aed99a..a8d50370 100644 --- a/plugins/stewards/reconcile.test.ts +++ b/plugins/stewards/reconcile.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { parsePlaybook } from "./config.js"; import { comment, issue, pull } from "./fixtures.js"; -import { approvalWanted, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, lifecycle, resolveChecklistItem, specHash, stuckDue, unheardWait } from "./reconcile.js"; +import { approvalWanted, asksForOpenApproval, classifyApproval, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, lifecycle, resolveChecklistItem, specHash, stuckDue, unheardWait } from "./reconcile.js"; import { readyStateSchema } from "./store.js"; import { GITHUB_REVIEWS, LINEAR_TICKETS } from "./templates.js"; @@ -128,6 +128,22 @@ describe("waits nobody hears", () => { }); }); +describe("approval words", () => { + it("tells approval, refusal and ambiguity apart", () => { + for (const text of ["LGTM", "Approved", "approved, it is fully specified", "ship it", "go ahead", "Looks good", "yes", "signed off"]) expect(classifyApproval(text), text).toBe("approve"); + for (const text of ["no", "No.", "not approved", "declined", "reject", "changes needed", "don't", "do not approve"]) expect(classifyApproval(text), text).toBe("decline"); + for (const text of ["", "maybe", "name the migration in the spec", "what about SSO?"]) expect(classifyApproval(text), text).toBe("ambiguous"); + }); + + it("flags a report that asks for an approval already open, and only that", () => { + const status = (summary: string, nextAction: string) => ({ phase: "Todo", summary, nextAction, actor: "me" as const, blockedOn: null, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at: 1 }); + const open = [{ kind: "approval" } as never]; + expect(asksForOpenApproval(status("Spec posted.", "Ask the user to approve the spec"), open)).toMatch(/already open/u); + expect(asksForOpenApproval(status("Spec posted.", "Wait for the project steward's approval"), open)).toBeNull(); + expect(asksForOpenApproval(status("Spec posted.", "Ask the user to approve the spec"), [])).toBeNull(); + }); +}); + describe("the ready gate", () => { const ready = (over: object) => readyStateSchema.parse(over); const allMet = tickets.ready!.checklist.map((item) => ({ item, met: true })); @@ -188,6 +204,22 @@ describe("the ready gate", () => { expect(specHash(issue({ comments: [comment({ body: "Spec: mine" })] }), "thr_s")).toBe(hash); expect(specHash(issue({ description: "Users cannot log in.\n\n_— from bb thread thr_s_" }), "thr_s")).toBe(hash); }); + + it("counts a spec comment the user wrote, and tells it apart from the steward's", () => { + const base = specHash(issue(), "thr_s"); + const user = (tid: string) => tid === "thr_user"; + const amended = issue({ comments: [comment({ id: "u1", author: "Jane", body: "**Spec:** narrower scope", signedBy: "thr_user", createdAt: "2026-10-14T16:00:00Z" })] }); + // Without the predicate the signing thread is unknown, so it is not spec. + expect(specHash(amended, "thr_s")).toBe(base); + expect(specHash(amended, "thr_s", user)).not.toBe(base); + }); + + it("marks a spec comment the user wrote as the user's, and wakes for it", () => { + const before = { entity: issue(), pulls: [] }; + const after = { entity: issue({ comments: [comment({ id: "u1", author: "Jane", body: "**Spec:** narrower scope", signedBy: "thr_user" })] }), pulls: [] }; + const changes = diffObserved(before, after, { ...ctx, userThread: (tid) => tid === "thr_user" }); + expect(changes).toContainEqual({ text: "Spec comment added by the user", actionable: true, byUser: true }); + }); }); describe("lifecycle", () => { diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index dc65184b..c2861203 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -15,11 +15,18 @@ import type { Binding, Escalation, Observed, ReadyState } from "./store.js"; * `own` marks the steward's own doing (its signed description edit), which is * news to nobody above it. */ -export type Change = { text: string; actionable: boolean; own?: boolean }; +export type Change = { text: string; actionable: boolean; own?: boolean; byUser?: boolean }; -/** A spec comment is one of the steward's own signed comments that starts by saying so. */ -export const isSpecComment = (c: SnapshotComment, stewardThreadId: string | null): boolean => - stewardThreadId !== null && c.signedBy === stewardThreadId && /^\s*(\*\*)?spec\b/iu.test(c.body); +/** + * A spec comment is a signed comment that starts by saying so. The steward's + * own count, and so do the user's: a thread the user runs themselves is + * treated as the user's own words (an amendment carries its own approval + * when the approver is `me`). `isUserThread` says whether a signing thread is + * the user's rather than a steward, worker or the project steward; without it + * only the steward's own comments count. + */ +export const isSpecComment = (c: SnapshotComment, stewardThreadId: string | null, isUserThread?: (threadId: string) => boolean): boolean => + c.signedBy !== null && /^\s*(\*\*)?spec\b/iu.test(c.body) && (c.signedBy === stewardThreadId || (isUserThread?.(c.signedBy) ?? false)); /** * What an approval is pinned to: the description and the steward's spec @@ -32,9 +39,9 @@ const DESCRIPTION_SIGNATURE = /\s*_— from bb thread ([A-Za-z0-9_-]+)_\s*$/u; /** The thread that signed the description, when its last edit was signed. */ export const descriptionSignedBy = (entity: EntitySnapshot): string | null => DESCRIPTION_SIGNATURE.exec(entity.description ?? "")?.[1] ?? null; -export function specHash(entity: EntitySnapshot, stewardThreadId: string | null): string { +export function specHash(entity: EntitySnapshot, stewardThreadId: string | null, isUserThread?: (threadId: string) => boolean): string { const description = (entity.description ?? "").replace(DESCRIPTION_SIGNATURE, "").trim(); - const specs = entity.comments.filter((c) => isSpecComment(c, stewardThreadId)).map((c) => `${c.id}\n${c.body}`); + const specs = entity.comments.filter((c) => isSpecComment(c, stewardThreadId, isUserThread)).map((c) => `${c.id}\n${c.body}`); return createHash("sha256").update([description, ...specs].join("\n\u0000\n")).digest("hex").slice(0, 16); } @@ -66,7 +73,7 @@ const lc = (s: string | null | undefined) => (s ?? "").toLowerCase(); * for checks; none of that is news to the steward, which hears from the * worker when it finishes. People and terminal states still wake it. */ -type DiffContext = { prefix: string; own: ReadonlySet; stewardThreadId: string | null; approved: boolean; viewer: string | null; workerRunning: boolean }; +type DiffContext = { prefix: string; own: ReadonlySet; stewardThreadId: string | null; approved: boolean; viewer: string | null; workerRunning: boolean; userThread?: (threadId: string) => boolean }; /** * The changes between two observations of one entity, each marked whether it @@ -92,9 +99,15 @@ export function diffEntity(before: EntitySnapshot, after: EntitySnapshot, ctx: D // A spec comment the steward just posted is its own doing; it only matters // once an approval is pinned to the spec it changes. - const beforeSpecs = new Set(before.comments.filter((c) => isSpecComment(c, ctx.stewardThreadId)).map((c) => c.id)); - const addedSpecs = after.comments.filter((c) => isSpecComment(c, ctx.stewardThreadId) && !beforeSpecs.has(c.id)); - if (addedSpecs.length > 0) changes.push({ text: `${p}Spec comment${addedSpecs.length === 1 ? "" : "s"} added`, actionable: ctx.approved }); + const beforeSpecs = new Set(before.comments.filter((c) => isSpecComment(c, ctx.stewardThreadId, ctx.userThread)).map((c) => c.id)); + const addedSpecs = after.comments.filter((c) => isSpecComment(c, ctx.stewardThreadId, ctx.userThread) && !beforeSpecs.has(c.id)); + if (addedSpecs.length > 0) { + const byUser = addedSpecs.some((c) => c.signedBy !== null && (ctx.userThread?.(c.signedBy) ?? false)); + // A spec comment the user wrote is news on its own: it carries its own + // approval when the approver is `me`, and when it is the project steward + // the steward should know the user authored it, not wait on them. + changes.push({ text: `${p}Spec comment${addedSpecs.length === 1 ? "" : "s"} added${byUser ? " by the user" : ""}`, actionable: ctx.approved || byUser, ...(byUser ? { byUser } : {}) }); + } const beforeChildren = new Map(before.children.map((c) => [c.id, c])); for (const child of after.children) { @@ -150,7 +163,7 @@ export const isCommentNews = (text: string): boolean => /^(?:\S+: )?\d+ new comm * request. `workerRunning` quiets the steward's own work on pull requests * (see DiffContext). */ -export function diffObserved(before: Observed, after: Observed, ctx: { own: ReadonlySet; stewardThreadId: string | null; approved: boolean; cursor: string; workerRunning: boolean }): Change[] { +export function diffObserved(before: Observed, after: Observed, ctx: { own: ReadonlySet; stewardThreadId: string | null; approved: boolean; cursor: string; workerRunning: boolean; userThread?: (threadId: string) => boolean }): Change[] { const viewer = after.entity.viewer; const changes = diffEntity(before.entity, after.entity, { ...ctx, prefix: "", viewer }); const beforePulls = new Map(before.pulls.map((p) => [p.key.toLowerCase(), p])); @@ -174,6 +187,43 @@ export function diffObserved(before: Observed, after: Observed, ctx: { own: Read return changes; } +// ---- approval words ------------------------------------------------------------------- + +/** + * How a piece of text answers an approval request. Explicit approval words + * approve; explicit refusal words decline; anything else is ambiguous and is + * the project steward's to interpret. The page answer uses all three; a + * project steward's own guidance + resolve is a decision, so anything that + * does not approve declines (as before). + */ +export type ApprovalVerdict = "approve" | "decline" | "ambiguous"; + +const APPROVE_WORDS = /(?:^|[^\p{L}\p{N}])(?:lgtm|approv(?:e|es|ed|al)|ship\s*it|go\s*ahead|looks?\s+good|sign(?:ed)?\s*off|:shipit:|yes|yep|yeah)(?:[^\p{L}\p{N}]|$)/iu; +const DECLINE_WORDS = /(?:^|[^\p{L}\p{N}])(?:no|nope|don'?t|do\s+not|not\s+approv(?:e|ed)|reject(?:ed)?|declin(?:e|ed)|changes?\s+(?:are\s+)?(?:needed|requested)|needs?\s+changes?)(?:[^\p{L}\p{N}]|$)/iu; + +export function classifyApproval(text: string | null | undefined): ApprovalVerdict { + const flat = (text ?? "").replace(/\s+/gu, " ").trim(); + if (flat === "") return "ambiguous"; + if (DECLINE_WORDS.test(flat)) return "decline"; + if (APPROVE_WORDS.test(flat)) return "approve"; + return "ambiguous"; +} + +/** + * A steward that asks for an approval that is already open. The plugin files + * the request and lists it on the Stewards page, so the playbook says not to + * ask the user again; a report whose next action asks them anyway is a + * violation `bb stewards show` points at. + */ +export function asksForOpenApproval(status: Binding["status"], open: readonly Escalation[]): string | null { + if (status === null || !open.some((x) => x.kind === "approval")) return null; + const text = [status.summary, status.nextAction, status.blockedOn ?? ""].join(" "); + if (!/\b(?:ask|asks|asking|request|requests|requested)\b/iu.test(text)) return null; + if (!/\b(?:approv\w*|lgtm|sign[- ]?off)\b/iu.test(text)) return null; + if (!/\b(?:user|you|your)\b/iu.test(text)) return null; + return "asks for an approval that is already open"; +} + // ---- the ready gate ------------------------------------------------------------------ export type GateState = { diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 445f3e7c..ffd21f7d 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -1424,6 +1424,184 @@ describe("questions to the user", () => { expect((await t.board()).questions).toEqual([]); }); + // BB-13: one spec approval, from any surface. The page answer, the project + // steward's words, an unsigned comment on the entity, and the user's own + // amendment all approve the same gate. + describe("one spec approval from any surface (BB-13)", () => { + const met = { checklist: [1, 2, 3, 4].map((item) => ({ item, met: true })), substantial: true }; + const base = { phase: "Todo", summary: "Spec posted.", nextAction: "Wait", actor: "other" }; + + /** A bound, specified ticket whose approval request is with the project steward. */ + async function requested() { + const t = await adopted(); + await t.tool("steward_report", { ...base, ready: met }, t.steward); + const esc = /(esc_[\w-]+) from ENG-12 \(approval\)/u.exec(t.sends.filter((s) => s.threadId === t.project).at(-1)!.text)![1]!; + const qst = t.qid((await t.tool("steward_update", { binding: "ENG-12", forward: esc }, t.project)).text); + const stewardWakes = () => t.sends.filter((s) => s.threadId === t.steward).length; + const projectWakes = () => t.sends.filter((s) => s.threadId === t.project).length; + return { ...t, esc, qst, stewardWakes, projectWakes }; + } + + it("records a page answer that approves, resolving the escalation in one step", async () => { + const t = await requested(); + const answered = await t.harness.callRpc("stewardsAnswerQuestion", { questionId: t.qst, answer: "Approved" }, client); + expect(answered).toMatchObject({ ok: true, message: expect.stringMatching(/Approved/u) }); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).not.toBeNull(); + expect(b.ready.approval!.by).toBe("user"); + expect(b.ready.declinedSpecHash).toBeNull(); + expect(t.hooks.store.escalation(t.esc)).toMatchObject({ status: "resolved" }); + expect(t.hooks.store.question(t.qst)!.status).toBe("answered"); + expect((await t.list())[0]!.escalations).toBe(0); + // No fresh request is filed for the same spec. + const before = t.projectWakes(); + await t.tool("steward_report", { ...base, ready: met }, t.steward); + expect(t.projectWakes()).toBe(before); + }); + + it("declines a page answer that clearly refuses", async () => { + const t = await requested(); + expect(await t.harness.callRpc("stewardsAnswerQuestion", { questionId: t.qst, answer: "No, not yet" }, client)).toMatchObject({ ok: true, message: expect.stringMatching(/Declined/u) }); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).toBeNull(); + expect(b.ready.declinedSpecHash).not.toBeNull(); + expect(t.hooks.store.escalation(t.esc)!.status).toBe("resolved"); + }); + + it("hands an ambiguous page answer to the project steward, not a decline", async () => { + const t = await requested(); + const before = t.projectWakes(); + expect(await t.harness.callRpc("stewardsAnswerQuestion", { questionId: t.qst, answer: "What about SSO?" }, client)).toMatchObject({ ok: true, message: expect.stringMatching(/project steward/u) }); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).toBeNull(); + expect(b.ready.declinedSpecHash).toBeNull(); + const x = t.hooks.store.escalation(t.esc)!; + expect(x).toMatchObject({ status: "open", route: "project" }); + expect(t.projectWakes()).toBeGreaterThan(before); + expect(t.sends.filter((s) => s.threadId === t.project).at(-1)!.text).toMatch(/ambiguous/u); + }); + + it("records approval when the project steward resolves with approving words, no approve: true", async () => { + const t = await requested(); + const resolved = await t.tool("steward_update", { binding: "ENG-12", guidance: "Approved, the spec is complete.", resolve: t.esc }, t.project); + expect(resolved.error).toBe(false); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).not.toBeNull(); + expect(b.ready.declinedSpecHash).toBeNull(); + expect(t.hooks.store.escalation(t.esc)!.status).toBe("resolved"); + }); + + it("still declines when the project steward resolves without approving words", async () => { + const t = await requested(); + await t.tool("steward_update", { binding: "ENG-12", guidance: "Name the migration in the spec.", resolve: t.esc }, t.project); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).toBeNull(); + expect(b.ready.declinedSpecHash).not.toBeNull(); + }); + + it("takes the user's unsigned approving comment on the entity as the quote", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace("approval: project", "approval: me"); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.tool("steward_report", { ...base, ready: met }, steward); + const spec = comment({ id: "s1", author: "Jane", body: "**Spec:** acceptance criteria", signedBy: steward, createdAt: "2026-10-14T15:10:00Z" }); + t.entities.set("uuid-12", issue({ comments: [spec, comment({ id: "u1", author: "Jane", body: "LGTM", signedBy: null, createdAt: "2026-10-14T15:20:00Z" })] })); + await t.ring("linear", "uuid-12"); + expect((await t.tool("steward_update", { approve: true, quote: "LGTM" }, steward)).error).toBe(false); + expect(t.hooks.store.find("ENG-12")!.ready.approval).not.toBeNull(); + }); + + it("does not take an approving comment from before the latest spec comment", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace("approval: project", "approval: me"); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.tool("steward_report", { ...base, ready: met }, steward); + t.entities.set( + "uuid-12", + issue({ + comments: [comment({ id: "u1", author: "Jane", body: "LGTM", signedBy: null, createdAt: "2026-10-14T15:10:00Z" }), comment({ id: "s1", author: "Jane", body: "**Spec:** acceptance criteria", signedBy: steward, createdAt: "2026-10-14T15:20:00Z" })], + }), + ); + await t.ring("linear", "uuid-12"); + expect((await t.tool("steward_update", { approve: true, quote: "LGTM" }, steward)).error).toBe(true); + expect(t.hooks.store.find("ENG-12")!.ready.approval).toBeNull(); + }); + + it("takes the user's own spec comment as approval when the approver is me", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace("approval: project", "approval: me"); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.tool("steward_report", { ...base, ready: met }, steward); + t.entities.set("uuid-12", issue({ comments: [comment({ id: "u1", author: "Jane", body: "**Spec:** narrower scope", signedBy: "thr_design", createdAt: "2026-10-14T15:30:00Z" })] })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).not.toBeNull(); + expect(b.ready.declinedSpecHash).toBeNull(); + expect(t.sends.filter((s) => s.threadId === steward).at(-1)!.text).toMatch(/user's spec comment approves/u); + }); + + it("files a fresh request and tells the steward the user authored the spec (approver project)", async () => { + const t = await adopted(); + await t.tool("steward_report", { ...base, ready: met }, t.steward); + await t.tool("steward_update", { binding: "ENG-12", approve: true }, t.project); + const before = t.sends.filter((s) => s.threadId === t.project).length; + t.entities.set("uuid-12", issue({ comments: [comment({ id: "u1", author: "Jane", body: "**Spec:** narrower scope", signedBy: "thr_design", createdAt: "2026-10-14T15:40:00Z" })] })); + await t.ring("linear", "uuid-12"); + expect(t.sends.filter((s) => s.threadId === t.steward).at(-1)!.text).toMatch(/Spec comment added by the user/u); + await t.tool("steward_report", { ...base, ready: met }, t.steward); + expect(t.sends.filter((s) => s.threadId === t.project).length).toBeGreaterThan(before); + expect(t.sends.filter((s) => s.threadId === t.project).at(-1)!.text).toMatch(/the spec has changed since its last approval/u); + }); + + it("says not to ask the user again, and flags a report that does", async () => { + const t = await requested(); + expect((await t.tool("steward_report", { ...base, ready: met }, t.steward)).text).toMatch(/Do not ask the user again; it is listed on the Stewards page/u); + t.entities.set("uuid-12", issue({ comments: [comment({ createdAt: "2026-10-14T16:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + expect(t.sends.filter((s) => s.threadId === t.steward).at(-1)!.text).toMatch(/Do not ask the user again; it is listed on the Stewards page/u); + const bad = await t.tool("steward_report", { ...base, nextAction: "Ask the user to approve the spec", actor: "me", ready: met }, t.steward); + expect(bad.text).toMatch(/playbook violation/u); + expect((await t.harness.behavior.runCli(["show", "ENG-12"])).stdout).toMatch(/asks for an approval that is already open/u); + }); + + it("passes the BB-11 sequence: page answer, amendment, page answer again, no duplicate request", async () => { + const t = await adopted(); + const answer = async (esc: string, text: string) => { + const qst = t.qid((await t.tool("steward_update", { binding: "ENG-12", forward: esc }, t.project)).text); + await t.harness.callRpc("stewardsAnswerQuestion", { questionId: qst, answer: text }, client); + }; + const projectWakes = () => t.sends.filter((s) => s.threadId === t.project).length; + + await t.tool("steward_report", { ...base, ready: met }, t.steward); + const first = /(esc_[\w-]+) from ENG-12 \(approval\)/u.exec(t.sends.filter((s) => s.threadId === t.project).at(-1)!.text)![1]!; + await answer(first, "Approved"); + expect(t.hooks.store.find("ENG-12")!.ready.approval).not.toBeNull(); + const afterFirst = projectWakes(); + await t.tool("steward_report", { ...base, ready: met }, t.steward); + expect(projectWakes()).toBe(afterFirst); + + // The user amends the spec from their own thread: a fresh request, once. + t.entities.set("uuid-12", issue({ comments: [comment({ id: "u1", author: "Jane", body: "**Spec:** narrower scope", signedBy: "thr_design", createdAt: "2026-10-14T16:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + await t.tool("steward_report", { ...base, ready: met }, t.steward); + const second = /(esc_[\w-]+) from ENG-12 \(approval\)/u.exec(t.sends.filter((s) => s.threadId === t.project).at(-1)!.text)![1]!; + expect(second).not.toBe(first); + + // And approves the amended spec on the page again. + await answer(second, "LGTM"); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).not.toBeNull(); + expect(b.ready.declinedSpecHash).toBeNull(); + expect(t.hooks.store.openEscalations(b.id).filter((x) => x.kind === "approval")).toEqual([]); + }); + }); + it("the page shows a project's board: waiting on you, in flight by stage with workers, stuck or held, ended, and the digest", async () => { const t = await adopted(); await t.tool("steward_update", { ask: { question: "Should I file an a11y ticket?" } }, t.project); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 9c474021..09e40ab6 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -37,7 +37,7 @@ import { type ProjectFile, } from "./config.js"; import { nightlyDue, stillNight } from "./nightly.js"; -import { advanced, approvalWanted, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, lifecycle, newestCommentAt, phaseAndStage, resolveChecklistItem, specHash, stuckDue, unheardWait, type Change } from "./reconcile.js"; +import { advanced, approvalWanted, asksForOpenApproval, classifyApproval, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, lifecycle, newestCommentAt, phaseAndStage, resolveChecklistItem, specHash, stuckDue, unheardWait, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, STEWARDS_PLUGIN_ID, @@ -839,6 +839,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // ---- the reconcile loop ------------------------------------------------------------------ + /** + * A thread the plugin does not know as a steward, a worker or the project + * steward is one the user runs themselves. Its signed comments count as + * the user's own words, including for the spec (criterion 4). + */ + function isUserThread(threadId: string): boolean { + return store.byThread(threadId) === null && store.worker(threadId) === null && store.projectByThread(threadId) === null; + } + + /** The spec hash a binding's approval is pinned to, counting the user's own spec comments. */ + const specHashFor = (b: Pick, entity: EntitySnapshot): string => specHash(entity, b.threadId, isUserThread); + const ownThreads = (b: Binding) => new Set([b.threadId, ...store.workers(b.id).map((w) => w.threadId)].filter((t): t is string => t !== null)); function routedTo(b: Binding): Array<{ escalation: Escalation; from: Binding }> { @@ -847,7 +859,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** Wake the steward, spawning its thread on the first wake. */ async function wake(b: Binding, config: ProjectConfig, playbook: Playbook, observed: Observed, changes: string[], reason: WakeReason): Promise { - const gate = gateState(playbook, b.ready, specHash(observed.entity, b.threadId)); + const gate = gateState(playbook, b.ready, specHashFor(b, observed.entity)); const text = formatWake({ reason, binding: b, @@ -961,7 +973,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } const { phase, stage } = phaseAndStage(playbook, entity.state); - const currentSpec = specHash(entity, b.threadId); + const currentSpec = specHashFor(b, entity); const changes: Change[] = []; let ready = b.ready; const approval = playbook.ready?.approval; @@ -970,8 +982,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P changes.push({ text: `Approved in Linear (now ${entity.state})`, actionable: true }); } const workerRunning = store.workers(b.id).some((w) => w.status === "running"); - const fresh = prev === null ? [] : diffObserved(prev, observed, { own: ownThreads(b), stewardThreadId: b.threadId, approved: ready.approval !== null, cursor: b.commentCursor, workerRunning }); + const fresh = prev === null ? [] : diffObserved(prev, observed, { own: ownThreads(b), stewardThreadId: b.threadId, approved: ready.approval !== null, cursor: b.commentCursor, workerRunning, userThread: isUserThread }); changes.push(...fresh); + // Criterion 4: a spec comment the user wrote from their own thread is + // the user's own words. With approval: me it carries its own approval, + // pinned to the spec it just changed. + if (approval === "me" && ready.approval === null && fresh.some((c) => c.byUser === true)) { + ready = { ...ready, approval: { at: now(), specHash: currentSpec, by: "user" }, voidedAt: null, declinedSpecHash: null }; + changes.push({ text: "The user's spec comment approves the spec (approval: me)", actionable: true }); + } // Only an entry into build from spec: review → build is the worker's // normal loop, and an unreported checklist is not an unmet one. if (stage === "build" && b.stage === "spec" && prev !== null && gateKnownUnmet(playbook, ready, currentSpec)) { @@ -1333,7 +1352,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const mode = playbook.ready?.approval ?? null; if (mode === null || typeof mode === "object" || b.lastSnapshot === null) return null; const open = store.openEscalations(b.id).filter((x) => x.kind === "approval"); - const current = specHash(b.lastSnapshot.entity, b.threadId); + const current = specHashFor(b, b.lastSnapshot.entity); const gate = gateState(playbook, b.ready, current); const wanted = approvalWanted(gate) && b.endedAt === null && b.ending === null && b.ready.declinedSpecHash !== current; if (!wanted) { @@ -1672,9 +1691,43 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (q === null || q.status !== "open") return { ok: false, message: "That question is already closed." }; const text = answer === null || answer === "" ? null : answer; const x = q.escalationId === null ? null : store.escalation(q.escalationId); + const b = x === null ? null : store.binding(x.bindingId); + // Criterion 1: an approval request answered on the page approves or + // declines the current spec and closes the request in one + // transaction. Ambiguous words are not a decline: the project steward + // decides, so the request goes back to it with the answer. + if (x !== null && b !== null && b.endedAt === null && x.kind === "approval" && text !== null) { + const entity = (await snapshot(b.source, b.entityId).catch(() => null)) ?? b.lastSnapshot?.entity ?? null; + const verdict = classifyApproval(text); + if (verdict === "approve" && entity !== null) { + store.approve(b.id, { at: now(), specHash: specHashFor(b, entity), by: "user" }, `Approved by the user on the stewards page: "${text}"`, "user"); + store.addGuidance(b.id, text, "user"); + store.note(b.id, `Approval ${x.id} was answered by the user on the stewards page: ${text}`); + scheduleReconcile(b.id); + return { ok: true, message: `Approved; ${b.entityKey}'s steward has been told.` }; + } + if (verdict === "decline" && entity !== null) { + store.decline(b.id, specHashFor(b, entity), `Declined by the user on the stewards page: "${text}"`, "user"); + store.addGuidance(b.id, text, "user"); + store.note(b.id, `Approval ${x.id} was declined by the user on the stewards page: ${text}`); + scheduleReconcile(b.id); + return { ok: true, message: `Declined; ${b.entityKey}'s steward has been told.` }; + } + // Ambiguous: close the question, keep the escalation, and send it + // back to the project steward to interpret. + store.answerQuestionOnly(q.id, text, "user"); + store.addGuidance(b.id, text, "user"); + store.reroute(x.id, "project", x.recommendation); + store.note(b.id, `The user answered approval ${x.id} on the stewards page, but not clearly enough to approve or decline: ${text}`); + scheduleReconcile(b.id); + await wakeProject(b.projectId, `ambiguous approval answer for ${b.entityKey}`, { + digestDue: false, + notes: [`The user answered ${b.entityKey}'s approval request on the Stewards page: ${JSON.stringify(text)}. It is not clearly an approval or a decline, so interpret it: approve with steward_update { binding, approve: true }, or decline with explicit words.`, `The escalation ${x.id} is open with you again.`], + }); + return { ok: true, message: `Closed; the project steward will interpret the answer.` }; + } // Closes the escalation it was forwarded for, too. store.answer(q.id, text ?? "Closed by the user on the stewards page, without an answer.", "user"); - const b = x === null ? null : store.binding(x.bindingId); if (x !== null && b !== null && b.endedAt === null) { if (text !== null) store.addGuidance(b.id, text, "user"); store.note(b.id, text === null ? `Escalation ${x.id} was closed by the user without an answer: carry on as you said you would meanwhile, or escalate again if you still need it.` : `Escalation ${x.id} decided by the user: ${text}`); @@ -1774,6 +1827,26 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return false; } + /** + * Whether the connected user approved in an unsigned comment on the + * entity, after the latest spec comment (criterion 3). `quote` is matched + * against the comment's text, so the steward can quote it back. + */ + function userApprovedOnEntity(entity: EntitySnapshot | null, stewardThreadId: string | null, quote: string): boolean { + if (entity === null || entity.viewer === null) return false; + const viewer = entity.viewer.toLowerCase(); + const latestSpec = entity.comments.filter((c) => isSpecComment(c, stewardThreadId, isUserThread)).reduce((max, c) => (c.createdAt > max ? c.createdAt : max), ""); + const want = quote.replace(/\s+/gu, " ").trim().toLowerCase(); + return entity.comments.some( + (c) => + c.signedBy === null && + c.author.toLowerCase() === viewer && + c.createdAt > latestSpec && + classifyApproval(c.body) === "approve" && + c.body.replace(/\s+/gu, " ").toLowerCase().includes(want), + ); + } + bb.agents.registerTool({ name: "steward_report", description: @@ -1901,7 +1974,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // Where the gate stands after this report, so a miss shows now and not at the next wake. let gateNote = ""; if (input.ready !== undefined && playbook !== null && playbook.ready !== null) { - const gate = gateState(playbook, ready, b.lastSnapshot === null ? "" : specHash(b.lastSnapshot.entity, b.threadId)); + const gate = gateState(playbook, ready, b.lastSnapshot === null ? "" : specHashFor(b, b.lastSnapshot.entity)); const unmet = gate.unmet.map((item) => playbook.ready!.checklist.indexOf(item) + 1); const why = !gate.checklistMet ? `unmet: ${unmet.join(", ")}` : gate.approvalStale ? "the approval is stale" : "approval is needed"; gateNote = gate.passed ? " Ready gate: passed." : ` Ready gate: not passed (${why}).`; @@ -1912,6 +1985,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P request.route === "me" ? ` Approval of the spec is requested from the user (${request.id}): they approve in this thread, and you record it with steward_update { approve: true, quote }.` : ` Approval of the spec is requested from the project steward (${request.id}); wait for it, and do not escalate for it.`; + gateNote += " Do not ask the user again; it is listed on the Stewards page."; + if (asksForOpenApproval(status, store.openEscalations(b.id)) !== null) gateNote += " This report asks for an approval that is already open: a playbook violation, shown by bb stewards show."; } if (b.ending === "terminal") { if (b.followThrough === null) return `Reported.${escalated} The binding ends when this turn does: running workers are stopped and the thread is archived. End the turn now.`; @@ -2031,7 +2106,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const directs = mayDirect(threadId, target); if (!directs && forwarding === null) return toolError(new Error(`This thread does not steer ${target.entityKey}: only its own steward, a steward above it, or the project steward does.`)); - let approval: { entity: EntitySnapshot; byUser: boolean } | null = null; + let approval: { entity: EntitySnapshot; byUser: boolean; by?: string } | null = null; let resolving: Escalation | null = null; if (directs) { if (self && (input.priority !== undefined || input.hold !== undefined || input.stewardModel !== undefined)) { @@ -2044,25 +2119,35 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (mode === null) return toolError(new Error(`${target.entityKey}'s playbook has no ready gate to approve.`)); if (typeof mode === "object") return toolError(new Error(`${target.entityKey} is approved by moving it to ${mode["linear-state"]} in Linear.`)); if (target.lastSnapshot === null) return toolError(new Error("Nothing has been observed for this binding yet.")); + const entity = (await snapshot(target.source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity; const byProject = mode === "project" && isProjectSteward(threadId, target); - const byUser = input.quote !== undefined && (await userSaid(threadId, input.quote)); + // Criterion 3: the user's words may be an unsigned comment on the entity itself, not only a message in this thread. + const byUser = input.quote !== undefined && ((await userSaid(threadId, input.quote)) || userApprovedOnEntity(entity, target.threadId, input.quote)); if (!byProject && !byUser) { return toolError( new Error( mode === "me" - ? "This spec is approved by the user: quote their words from a message they sent in this thread." + ? "This spec is approved by the user: quote their words from a message in this thread, or from their unsigned approving comment on the entity." : "This spec is approved by the project steward (or by the user, quoting their words from this thread). Escalate a decision instead.", ), ); } // Pinned to the spec as it is now, not as last observed: a spec // comment posted since the last ring is part of what was read. - approval = { entity: (await snapshot(target.source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity, byUser }; + approval = { entity, byUser }; } if (resolve !== undefined) { if (guidance === undefined) return toolError(new Error("Give the answer as guidance when resolving.")); resolving = store.escalation(resolve); if (resolving === null || resolving.bindingId !== target.id) return toolError(new Error(`No escalation ${resolve} on ${target.entityKey}.`)); + // Criterion 2: the project steward's approving words are the + // approval; approve: true is no longer needed as well. + if (approval === null && resolving.kind === "approval" && resolving.status === "open" && target.lastSnapshot !== null && classifyApproval(guidance) === "approve") { + const config = await loadConfig(target.projectId); + const playbook = config === null ? null : playbookFor(config, target.kind); + const mode = playbook?.ready?.approval ?? null; + if (mode !== null && typeof mode !== "object") approval = { entity: (await snapshot(target.source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity, byUser: false, by: isProjectSteward(threadId, target) ? "the project steward" : "your parent steward" }; + } } if (input.stewardModel !== undefined && target.threadId !== null) { const info = await threadInfo(target.threadId); @@ -2096,8 +2181,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (!directs) return `${target.entityKey}: ${done.join("; ")}.`; if (approval !== null) { - const by = approval.byUser ? ` by the user: "${input.quote}"` : " by the project steward"; - store.patch(target.id, { ready: { ...target.ready, approval: { at: now(), specHash: specHash(approval.entity, target.threadId), by: threadId }, voidedAt: null, declinedSpecHash: null } }); + const by = approval.byUser ? ` by the user: "${input.quote}"` : ` by ${approval.by ?? "the project steward"}`; + store.patch(target.id, { ready: { ...target.ready, approval: { at: now(), specHash: specHashFor(target, approval.entity), by: threadId }, voidedAt: null, declinedSpecHash: null } }); for (const x of store.openEscalations(target.id).filter((e) => e.kind === "approval")) store.resolve(x.id, `Approved${by}.`); const others = store.openEscalations(target.id).filter((x) => x.id !== resolve); done.push(others.length === 0 ? "spec approved" : `spec approved; still open on it: ${others.map((x) => `${x.id} (${x.kind}, with ${x.route}): ${x.question}`).join(" | ")} — resolve any this approval answers`); @@ -2113,9 +2198,9 @@ 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" && input.approve !== true && target.lastSnapshot !== null) { + 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: specHash(fresh.lastSnapshot!.entity, fresh.threadId) } }); + store.patch(target.id, { ready: { ...fresh.ready, declinedSpecHash: specHashFor(fresh, fresh.lastSnapshot!.entity) } }); } if (resolving.status === "open") done.push(`resolved ${resolving.id}`); else if (outcome === "appended") done.push(`recorded the answer on ${resolving.id}, which was already resolved (${resolving.resolution ?? "no answer"})`); @@ -2149,7 +2234,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .map((b) => { const s = b.status; const open = store.openEscalations(b.id); - const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), unheardWait(s, open)].filter((f) => f !== null); + const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), unheardWait(s, open), asksForOpenApproval(s, open)].filter((f) => f !== null); return `${b.entityKey} — ${b.kind}, ${b.phase ?? "?"}${b.threadId === null ? "" : `, thread ${b.threadId}`}\n ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${s.blockedOn === null ? "" : `; blocked on ${s.blockedOn}`}`}${flags.length > 0 ? `\n [${flags.join("; ")}]` : ""}`; }) .join("\n"); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 9cd686fa..4497f636 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -571,6 +571,26 @@ export function createStore(db: Database.Database, now: () => number) { patch(id, { guidance: [...b.guidance, { at: now(), text, by }].slice(-50) }); return true; }, + /** + * Record an approval on the gate and resolve the binding's open approval + * escalations, in one transaction: answering an approval request approves + * the current spec and closes the request together. + */ + approve(bindingId: string, approval: NonNullable, resolution: string, by: string): void { + db.transaction(() => { + const b = rowToBinding(getBinding.get(bindingId)!); + patch(bindingId, { ready: { ...b.ready, approval, voidedAt: null, declinedSpecHash: null } }); + for (const x of openEscalations.all(bindingId).map(toEscalation).filter((e) => e.kind === "approval")) resolve(x.id, resolution, by); + })(); + }, + /** Remember the current spec as declined and close its approval request, in one transaction. */ + decline(bindingId: string, specHash: string, resolution: string, by: string): void { + db.transaction(() => { + const b = rowToBinding(getBinding.get(bindingId)!); + patch(bindingId, { ready: { ...b.ready, declinedSpecHash: specHash } }); + for (const x of openEscalations.all(bindingId).map(toEscalation).filter((e) => e.kind === "approval")) resolve(x.id, resolution, by); + })(); + }, // escalations escalate(fields: { bindingId: string; kind: EscalationKind; question: string; meanwhile: string; route: EscalationRoute; recommendation: string | null }): Escalation { @@ -649,6 +669,14 @@ export function createStore(db: Database.Database, now: () => number) { return true; })(); }, + /** + * Close an open question with its answer, leaving the escalation it was + * forwarded for open. Used when the user's answer is ambiguous: the + * project steward, not the plugin, decides what it means. + */ + answerQuestionOnly(id: string, answer: string, by: string): boolean { + return answerQuestion.run(answer, by, now(), id).changes > 0; + }, // workers addWorker(threadId: string, bindingId: string, title: string): void { diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 40b2f2ef..02e4a695 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -147,8 +147,8 @@ function gateLines(input: WakeInput): string[] { ? ` It is asked for automatically once the checklist is met; do not escalate for it.` : "" : request.route === "me" - ? ` Requested from the user (${request.id}): they approve in this thread, and you record it with steward_update { approve: true, quote }.` - : ` Requested from the project steward (${request.id}): wait for it; do not escalate for it.`; + ? ` Requested from the user (${request.id}): they approve in this thread, and you record it with steward_update { approve: true, quote }. Do not ask the user again; it is listed on the Stewards page.` + : ` Requested from the project steward (${request.id}): wait for it; do not escalate for it. Do not ask the user again; it is listed on the Stewards page.`; if (!gate.approvalNeeded) lines.push("- Approval: not needed"); else if (!gate.approved) lines.push(`- Approval: not given (given by ${how})${binding.ready.voidedAt === null ? "" : `; the last one was voided ${iso(binding.ready.voidedAt)}`}.${asked}`); else lines.push(`- Approval: given ${iso(binding.ready.approval!.at)}${gate.approvalStale ? ` — the spec has changed since, so the gate needs it again.${asked}` : ""}`); From d6feadb399c708d3b2cbcb2cedc14f1094b77104 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 19 Oct 2026 21:37:58 +0000 Subject: [PATCH 2/3] stewards: address review round 1 (BB-13) - classifyApproval: a clear refusal ("not approved", "don't ship it", reject, declined) declines first, then approval words win over a bare "no", so "LGTM, no concerns" and "ship it, no further changes needed" approve instead of declining. - steward_update: approving words in the guidance only approve when the gate names the project steward and the caller is it, mirroring approve: true; a steward cannot approve its own spec, and mode me still needs the user's quote. - reconcileOnce: the user's own spec comment carries its approval when the prior approval is stale, not only when there never was one. - asksForOpenApproval: only an imperative next action ("Ask the user to approve") counts, so a status that waits on the request is not flagged. - wake: the project steward is told approving words in guidance work too. --- plugins/stewards/reconcile.test.ts | 6 +++- plugins/stewards/reconcile.ts | 35 +++++++++++++++-------- plugins/stewards/server.test.ts | 45 ++++++++++++++++++++++++++++++ plugins/stewards/server.ts | 17 ++++++----- plugins/stewards/wake.ts | 2 +- 5 files changed, 84 insertions(+), 21 deletions(-) diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index a8d50370..e7b3db78 100644 --- a/plugins/stewards/reconcile.test.ts +++ b/plugins/stewards/reconcile.test.ts @@ -131,7 +131,9 @@ describe("waits nobody hears", () => { describe("approval words", () => { it("tells approval, refusal and ambiguity apart", () => { for (const text of ["LGTM", "Approved", "approved, it is fully specified", "ship it", "go ahead", "Looks good", "yes", "signed off"]) expect(classifyApproval(text), text).toBe("approve"); - for (const text of ["no", "No.", "not approved", "declined", "reject", "changes needed", "don't", "do not approve"]) expect(classifyApproval(text), text).toBe("decline"); + // Approving words with a bare "no" beside them still approve. + for (const text of ["LGTM, no concerns from me", "Ship it, no further changes needed", "Approved, no notes"]) expect(classifyApproval(text), text).toBe("approve"); + for (const text of ["no", "No.", "not approved", "don't ship it", "declined", "reject", "changes needed", "don't", "do not approve", "No, not yet"]) expect(classifyApproval(text), text).toBe("decline"); for (const text of ["", "maybe", "name the migration in the spec", "what about SSO?"]) expect(classifyApproval(text), text).toBe("ambiguous"); }); @@ -139,7 +141,9 @@ describe("approval words", () => { const status = (summary: string, nextAction: string) => ({ phase: "Todo", summary, nextAction, actor: "me" as const, blockedOn: null, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at: 1 }); const open = [{ kind: "approval" } as never]; expect(asksForOpenApproval(status("Spec posted.", "Ask the user to approve the spec"), open)).toMatch(/already open/u); + // Waiting on the request, or on the project steward, is not asking again. expect(asksForOpenApproval(status("Spec posted.", "Wait for the project steward's approval"), open)).toBeNull(); + expect(asksForOpenApproval(status("Approval requested from the user; waiting.", "Wait for the user to approve the spec"), open)).toBeNull(); expect(asksForOpenApproval(status("Spec posted.", "Ask the user to approve the spec"), [])).toBeNull(); }); }); diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index c2861203..963fbe41 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -29,10 +29,11 @@ export const isSpecComment = (c: SnapshotComment, stewardThreadId: string | null c.signedBy !== null && /^\s*(\*\*)?spec\b/iu.test(c.body) && (c.signedBy === stewardThreadId || (isUserThread?.(c.signedBy) ?? false)); /** - * What an approval is pinned to: the description and the steward's spec - * comments. Any change to either changes the hash. The signature line is - * left out of the description, so the steward's own signed edit hashes the - * same as the text it wrote. + * What an approval is pinned to: the description and the spec comments. The + * steward's own and the user's (a thread the user runs) both count. Any + * change to either changes the hash. The signature line is left out of the + * description, so the steward's own signed edit hashes the same as the text + * it wrote. */ const DESCRIPTION_SIGNATURE = /\s*_— from bb thread ([A-Za-z0-9_-]+)_\s*$/u; @@ -198,29 +199,39 @@ export function diffObserved(before: Observed, after: Observed, ctx: { own: Read */ export type ApprovalVerdict = "approve" | "decline" | "ambiguous"; +const NEGATED_APPROVE = /(?:^|[^\p{L}\p{N}])(?:not|do\s+not|don'?t)\s+(?:\w+\s+){0,2}?(?:approv\w*|ship|lgtm|go\s+ahead|looks?\s+good|sign\s*off|yes)(?:[^\p{L}\p{N}]|$)/iu; +const REFUSAL = /(?:^|[^\p{L}\p{N}])(?:reject(?:ed)?|declin(?:e|ed)|hold\s+off)(?:[^\p{L}\p{N}]|$)/iu; const APPROVE_WORDS = /(?:^|[^\p{L}\p{N}])(?:lgtm|approv(?:e|es|ed|al)|ship\s*it|go\s*ahead|looks?\s+good|sign(?:ed)?\s*off|:shipit:|yes|yep|yeah)(?:[^\p{L}\p{N}]|$)/iu; -const DECLINE_WORDS = /(?:^|[^\p{L}\p{N}])(?:no|nope|don'?t|do\s+not|not\s+approv(?:e|ed)|reject(?:ed)?|declin(?:e|ed)|changes?\s+(?:are\s+)?(?:needed|requested)|needs?\s+changes?)(?:[^\p{L}\p{N}]|$)/iu; +const DECLINE_WORDS = /(?:^|[^\p{L}\p{N}])(?:no|nope|don'?t|do\s+not|not\s+yet|changes?\s+(?:are\s+)?(?:needed|requested)|needs?\s+changes?)(?:[^\p{L}\p{N}]|$)/iu; +/** + * A clear refusal first, so "not approved" and "don't ship it" decline rather + * than matching the approval word inside them; then approval words, so + * "LGTM, no concerns" and "ship it, no further changes needed" approve; then + * a bare no or a request for changes declines; anything else is ambiguous. + */ export function classifyApproval(text: string | null | undefined): ApprovalVerdict { const flat = (text ?? "").replace(/\s+/gu, " ").trim(); if (flat === "") return "ambiguous"; - if (DECLINE_WORDS.test(flat)) return "decline"; + if (NEGATED_APPROVE.test(flat) || REFUSAL.test(flat)) return "decline"; if (APPROVE_WORDS.test(flat)) return "approve"; + if (DECLINE_WORDS.test(flat)) return "decline"; return "ambiguous"; } /** * A steward that asks for an approval that is already open. The plugin files * the request and lists it on the Stewards page, so the playbook says not to - * ask the user again; a report whose next action asks them anyway is a - * violation `bb stewards show` points at. + * ask the user again; a report whose next action is to ask them anyway is a + * violation `bb stewards show` points at. Only an imperative next action + * counts, so merely waiting on the request is not flagged. */ export function asksForOpenApproval(status: Binding["status"], open: readonly Escalation[]): string | null { if (status === null || !open.some((x) => x.kind === "approval")) return null; - const text = [status.summary, status.nextAction, status.blockedOn ?? ""].join(" "); - if (!/\b(?:ask|asks|asking|request|requests|requested)\b/iu.test(text)) return null; - if (!/\b(?:approv\w*|lgtm|sign[- ]?off)\b/iu.test(text)) return null; - if (!/\b(?:user|you|your)\b/iu.test(text)) return null; + const next = status.nextAction.trim(); + if (!/^(?:ask|asks|asking|request|requests|requesting|remind|reminds|reminding|tell|tells|telling|prompt|prompts|prompting)\b/iu.test(next)) return null; + if (!/\b(?:approv\w*|lgtm|sign[- ]?off)\b/iu.test(next)) return null; + if (!/\b(?:user|you|your)\b/iu.test(next)) return null; return "asks for an approval that is already open"; } diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index ffd21f7d..f054c648 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -443,6 +443,7 @@ describe("a Linear ticket steward", () => { expect(wake).toMatch(/approval requested for ENG-12/u); expect(wake).toMatch(/(esc_[\w-]+) from ENG-12 \(approval\): Approve ENG-12's spec \(Fix login\)\? .*substantial \(two repos\)/u); expect(wake).toMatch(/steward_update \{ binding, approve: true \}/u); + expect(wake).toMatch(/approving words in the guidance/u); const id = /(esc_[\w-]+) from ENG-12 \(approval\)/u.exec(wake)![1]!; // A second report asks nothing twice, and the steward's next wake says it is asked for. @@ -1499,6 +1500,24 @@ describe("questions to the user", () => { expect(b.ready.declinedSpecHash).not.toBeNull(); }); + it("does not let a steward approve its own spec with approving words", async () => { + const t = await requested(); + expect((await t.tool("steward_update", { binding: "ENG-12", guidance: "Approved, the spec is complete.", resolve: t.esc }, t.steward)).error).toBe(false); + expect(t.hooks.store.find("ENG-12")!.ready.approval).toBeNull(); + }); + + it("does not let the project steward approve for the user when the approver is me", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace("approval: project", "approval: me"); + 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.tool("steward_report", { ...base, ready: met }, steward); + const esc = t.hooks.store.openEscalations(t.hooks.store.find("ENG-12")!.id).find((x) => x.kind === "approval")!.id; + expect((await t.tool("steward_update", { binding: "ENG-12", guidance: "Approved", resolve: esc }, project)).error).toBe(false); + expect(t.hooks.store.find("ENG-12")!.ready.approval).toBeNull(); + }); + it("takes the user's unsigned approving comment on the entity as the quote", async () => { const t = await setup(); t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace("approval: project", "approval: me"); @@ -1546,6 +1565,32 @@ describe("questions to the user", () => { expect(t.sends.filter((s) => s.threadId === steward).at(-1)!.text).toMatch(/user's spec comment approves/u); }); + it("carries the user's own amendment's approval even after a stale one (approver me)", async () => { + const t = await setup(); + t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace("approval: project", "approval: me"); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.tool("steward_report", { ...base, ready: met }, steward); + const s1 = comment({ id: "s1", author: "Jane", body: "**Spec:** acceptance criteria", signedBy: steward, createdAt: "2026-10-14T15:10:00Z" }); + const u1 = comment({ id: "u1", author: "Jane", body: "LGTM", signedBy: null, createdAt: "2026-10-14T15:20:00Z" }); + t.entities.set("uuid-12", issue({ comments: [s1, u1] })); + await t.ring("linear", "uuid-12"); + expect((await t.tool("steward_update", { approve: true, quote: "LGTM" }, steward)).error).toBe(false); + const approved = t.hooks.store.find("ENG-12")!.ready.approval!.specHash; + // The steward amends the spec: the approval is stale but still pinned to the old hash. + const s2 = comment({ id: "s2", author: "Jane", body: "**Spec:** narrower scope", signedBy: steward, createdAt: "2026-10-14T15:30:00Z" }); + t.entities.set("uuid-12", issue({ comments: [s1, u1, s2] })); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.find("ENG-12")!.ready.approval!.specHash).toBe(approved); + // The user amends from their own thread: it carries its own approval for the new spec. + t.entities.set("uuid-12", issue({ comments: [s1, u1, s2, comment({ id: "u2", author: "Jane", body: "**Spec:** even narrower", signedBy: "thr_design", createdAt: "2026-10-14T15:40:00Z" })] })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).not.toBeNull(); + expect(b.ready.approval!.specHash).not.toBe(approved); + }); + it("files a fresh request and tells the steward the user authored the spec (approver project)", async () => { const t = await adopted(); await t.tool("steward_report", { ...base, ready: met }, t.steward); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 09e40ab6..e405d6cf 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -986,8 +986,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P changes.push(...fresh); // Criterion 4: a spec comment the user wrote from their own thread is // the user's own words. With approval: me it carries its own approval, - // pinned to the spec it just changed. - if (approval === "me" && ready.approval === null && fresh.some((c) => c.byUser === true)) { + // pinned to the spec it just changed, whether or not an earlier + // approval has gone stale. + if (approval === "me" && (ready.approval === null || ready.approval.specHash !== currentSpec) && fresh.some((c) => c.byUser === true)) { ready = { ...ready, approval: { at: now(), specHash: currentSpec, by: "user" }, voidedAt: null, declinedSpecHash: null }; changes.push({ text: "The user's spec comment approves the spec (approval: me)", actionable: true }); } @@ -2106,7 +2107,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const directs = mayDirect(threadId, target); if (!directs && forwarding === null) return toolError(new Error(`This thread does not steer ${target.entityKey}: only its own steward, a steward above it, or the project steward does.`)); - let approval: { entity: EntitySnapshot; byUser: boolean; by?: string } | null = null; + let approval: { entity: EntitySnapshot; byUser: boolean } | null = null; let resolving: Escalation | null = null; if (directs) { if (self && (input.priority !== undefined || input.hold !== undefined || input.stewardModel !== undefined)) { @@ -2141,12 +2142,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P resolving = store.escalation(resolve); if (resolving === null || resolving.bindingId !== target.id) return toolError(new Error(`No escalation ${resolve} on ${target.entityKey}.`)); // Criterion 2: the project steward's approving words are the - // approval; approve: true is no longer needed as well. + // approval; approve: true is no longer needed as well. Only the + // approver the gate names may do it, as with approve: true: the + // project steward for mode project, and never a steward's own + // words for mode me (there the user's quote is required). if (approval === null && resolving.kind === "approval" && resolving.status === "open" && target.lastSnapshot !== null && classifyApproval(guidance) === "approve") { const config = await loadConfig(target.projectId); const playbook = config === null ? null : playbookFor(config, target.kind); - const mode = playbook?.ready?.approval ?? null; - if (mode !== null && typeof mode !== "object") approval = { entity: (await snapshot(target.source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity, byUser: false, by: isProjectSteward(threadId, target) ? "the project steward" : "your parent steward" }; + if (playbook?.ready?.approval === "project" && isProjectSteward(threadId, target)) approval = { entity: (await snapshot(target.source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity, byUser: false }; } } if (input.stewardModel !== undefined && target.threadId !== null) { @@ -2181,7 +2184,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (!directs) return `${target.entityKey}: ${done.join("; ")}.`; if (approval !== null) { - const by = approval.byUser ? ` by the user: "${input.quote}"` : ` by ${approval.by ?? "the project steward"}`; + const by = approval.byUser ? ` by the user: "${input.quote}"` : " by the project steward"; store.patch(target.id, { ready: { ...target.ready, approval: { at: now(), specHash: specHashFor(target, approval.entity), by: threadId }, voidedAt: null, declinedSpecHash: null } }); for (const x of store.openEscalations(target.id).filter((e) => e.kind === "approval")) store.resolve(x.id, `Approved${by}.`); const others = store.openEscalations(target.id).filter((x) => x.id !== resolve); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 02e4a695..deb3142f 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -276,7 +276,7 @@ export function formatProjectWake(input: { ); if (input.routed.some((r) => r.escalation.kind === "approval")) { out.push( - "An approval escalation is the plugin's: the ticket's ready gate waits on you. Judge the spec (`bb stewards show `, and the ticket itself) against the project's guidance. Approve it with steward_update { binding, approve: true }, which closes the request; or decline with steward_update { binding, guidance: what must change, resolve }. If the steward also escalated asking for this approval, resolve that one too.", + "An approval escalation is the plugin's: the ticket's ready gate waits on you. Judge the spec (`bb stewards show `, and the ticket itself) against the project's guidance. Approve it with steward_update { binding, approve: true }, or with approving words in the guidance that resolves it, such as steward_update { binding, guidance: \"Approved\", resolve }; either closes the request. Decline with steward_update { binding, guidance: what must change, resolve }. If the steward also escalated asking for this approval, resolve that one too.", "", ); } From acdd3baa8fd031dfda08fb2f82d718759e961ceb Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 19 Oct 2026 21:52:05 +0000 Subject: [PATCH 3/3] stewards: generic negation prefix in classifyApproval (BB-13) Review round 2: "won't approve", "can't approve", "cannot approve", "shouldn't approve" and "never approve" matched the approval word inside them. The negation prefix now covers not, never, cannot, do not and any n't contraction (with a straight or curly apostrophe), while a word merely ending in "nt" ("want to approve") still approves. --- plugins/stewards/reconcile.test.ts | 4 +++- plugins/stewards/reconcile.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index e7b3db78..3aaa7829 100644 --- a/plugins/stewards/reconcile.test.ts +++ b/plugins/stewards/reconcile.test.ts @@ -133,7 +133,9 @@ describe("approval words", () => { for (const text of ["LGTM", "Approved", "approved, it is fully specified", "ship it", "go ahead", "Looks good", "yes", "signed off"]) expect(classifyApproval(text), text).toBe("approve"); // Approving words with a bare "no" beside them still approve. for (const text of ["LGTM, no concerns from me", "Ship it, no further changes needed", "Approved, no notes"]) expect(classifyApproval(text), text).toBe("approve"); - for (const text of ["no", "No.", "not approved", "don't ship it", "declined", "reject", "changes needed", "don't", "do not approve", "No, not yet"]) expect(classifyApproval(text), text).toBe("decline"); + for (const text of ["no", "No.", "not approved", "don't ship it", "declined", "reject", "changes needed", "don't", "do not approve", "No, not yet", "won't approve until the migration is named", "can't approve without SSO", "cannot approve this spec yet", "shouldn't approve until naming is fixed", "never approve this as-is"]) expect(classifyApproval(text), text).toBe("decline"); + // A word ending in "nt" is not a contraction: wanting to approve approves. + expect(classifyApproval("I want to approve")).toBe("approve"); for (const text of ["", "maybe", "name the migration in the spec", "what about SSO?"]) expect(classifyApproval(text), text).toBe("ambiguous"); }); diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index 963fbe41..760c15aa 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -199,7 +199,7 @@ export function diffObserved(before: Observed, after: Observed, ctx: { own: Read */ export type ApprovalVerdict = "approve" | "decline" | "ambiguous"; -const NEGATED_APPROVE = /(?:^|[^\p{L}\p{N}])(?:not|do\s+not|don'?t)\s+(?:\w+\s+){0,2}?(?:approv\w*|ship|lgtm|go\s+ahead|looks?\s+good|sign\s*off|yes)(?:[^\p{L}\p{N}]|$)/iu; +const NEGATED_APPROVE = /(?:^|[^\p{L}\p{N}])(?:not|never|cannot|do\s+not|[a-z]+n['’]t)\s+(?:\w+\s+){0,2}?(?:approv\w*|ship|lgtm|go\s+ahead|looks?\s+good|sign\s*off|yes)(?:[^\p{L}\p{N}]|$)/iu; const REFUSAL = /(?:^|[^\p{L}\p{N}])(?:reject(?:ed)?|declin(?:e|ed)|hold\s+off)(?:[^\p{L}\p{N}]|$)/iu; const APPROVE_WORDS = /(?:^|[^\p{L}\p{N}])(?:lgtm|approv(?:e|es|ed|al)|ship\s*it|go\s*ahead|looks?\s+good|sign(?:ed)?\s*off|:shipit:|yes|yep|yeah)(?:[^\p{L}\p{N}]|$)/iu; const DECLINE_WORDS = /(?:^|[^\p{L}\p{N}])(?:no|nope|don'?t|do\s+not|not\s+yet|changes?\s+(?:are\s+)?(?:needed|requested)|needs?\s+changes?)(?:[^\p{L}\p{N}]|$)/iu;