diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 40e864b9..bec4c2dc 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -685,10 +685,13 @@ entry marked `decide: project | user`. The plugin raises an marker puts a pull request in the owner-reviewed lane. The project steward classifies it into an entry and either records a project-steward approval for a `project` entry (`steward_update { binding, approve, -entry }`, bound to the pull request's head sha so a new push voids it and -kept only in the store, never as a GitHub comment or review) or forwards -it to you for a `user` one. A missing entry, an unknown mark, a `user` -entry, or a change to the decide list, `bigDecisions`, `prGate` or the +entry }`), which posts a signed `bb-approval` marker on the pull request, +keeps its comment id in the store and wakes the worker, or forwards it to +you for a `user` one. Only a marker whose comment id the store recorded +counts, so a hand-typed lookalike never does, and an approval is of the +pull request, so a later head is covered unless the worker added scope. +A missing entry, an unknown mark, a `user` entry, or a change to the +decide list, `bigDecisions`, `prGate` or the approval code is always yours, whatever the list says; a signed comment never satisfies either. `prGate` accepts the project-steward approval for a `project` entry, and the user's unsigned GitHub approval is unchanged. @@ -1166,9 +1169,10 @@ The rules that hold: gate: the reviewer's latest marker has verdict `approved`, every check has passed, and, in the owner-reviewed lane, the owner has approved — an unsigned approving comment or an APPROVED review by the - connected user, or, for an entry the decide list marks `project`, a - project-steward approval recorded in the store and bound to the head sha - (BB-30); a signed comment is a thread's, never the owner's. An unknown + connected user, or, for an entry the decide list marks `project`, the + `bb-approval` marker the project steward posted, whose comment id the + store records (BB-30, BB-77); a signed comment is a thread's, never the + owner's. An unknown lane is owner-reviewed, not no-review. Any comment whose first line opens a `bb-review` marker is a round, however it is spelled: a marker missing `verdict=` reads its verdict from a bare word (`changes-requested`) or as diff --git a/plugins/stewards/decisions.test.ts b/plugins/stewards/decisions.test.ts index edadc45a..0708ce8e 100644 --- a/plugins/stewards/decisions.test.ts +++ b/plugins/stewards/decisions.test.ts @@ -60,6 +60,14 @@ describe("the decide list fails closed", () => { expect(decideForPull([], decisions)).toBe("user"); expect(decideForPull(null, decisions)).toBe("user"); expect(decideForPull(["bb-plugins/plugins/stewards/store.ts"], decisions)).toBe("user"); + // An identity path no project entry names is already the user's, whether or + // not a `user` entry lists it (BB-77). + const identity: BigDecision[] = [ + { text: "Identity and access", decide: "user", paths: ["bb-gate/router/**"] }, + { text: "A cross-repo contract", decide: "project", paths: ["bb-gate/docs/hooks.md"] }, + ]; + expect(decideForPull(["bb-gate/router/routes.go"], identity)).toBe("user"); + expect(decideForPull(["bb-gate/docs/hooks.md"], identity)).toBe("project"); }); it("gives the failed files fetch its own refusal text, not the self-widening one (BB-51)", () => { diff --git a/plugins/stewards/github.ts b/plugins/stewards/github.ts index f7596aed..64a4fcfe 100644 --- a/plugins/stewards/github.ts +++ b/plugins/stewards/github.ts @@ -47,8 +47,12 @@ export function createGhTokenReader(): TokenReader { } export interface GithubWriter { - /** Post an unsigned comment as the connected user. */ - comment(repo: string, number: number, body: string): Promise; + /** + * Post a comment as the connected user and return GitHub's node id for it. + * The id ties the plugin's own approval record to the marker it posted, so a + * hand-typed lookalike never satisfies the lane gate. + */ + comment(repo: string, number: number, body: string): Promise; /** Squash-merge the pull request, with the given commit title and message. */ squashMerge(repo: string, number: number, title: string, body: string): Promise; /** @@ -89,7 +93,11 @@ export function createGhWriter(token: TokenReader = createGhTokenReader(), doFet }; return { async comment(repo, number, body) { - await request("POST", `/repos/${repo}/issues/${number}/comments`, { body }); + const response = await request("POST", `/repos/${repo}/issues/${number}/comments`, { body }); + const created = (await response.json().catch(() => null)) as { node_id?: unknown; id?: unknown } | null; + const nodeId = created?.node_id ?? created?.id; + if (nodeId === undefined || nodeId === null || String(nodeId) === "") throw new GithubApiError("GitHub created the comment but returned no id, so the approval marker cannot be recorded."); + return String(nodeId); }, async squashMerge(repo, number, title, body) { await request("PUT", `/repos/${repo}/pulls/${number}/merge`, { merge_method: "squash", commit_title: title, commit_message: body }); diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index ed4f56e5..4f703f4e 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, phaseOf } from "./config.js"; import { comment, issue, pull } from "./fixtures.js"; -import { approvalWanted, answerDiffers, anyWorkerInFlight, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, idleInActiveStage, isCommentNews, isOwnStageMove, lifecycle, markerLaneChange, namesUserAsBlocker, ownPullClosed, ownerApproval, prGate, resolveChecklistItem, reviewMarker, specHash, stuckDue, UNREADABLE_VERDICT, unheardWait, workerInFlight, workerReportedTerminal, type IdleBinding } from "./reconcile.js"; +import { approvalMarkerLine, approvalWanted, answerDiffers, anyWorkerInFlight, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, idleInActiveStage, isCommentNews, isOwnStageMove, lifecycle, markerLaneChange, namesUserAsBlocker, ownPullClosed, ownerApproval, prGate, projectApprovalMarker, resolveChecklistItem, reviewMarker, reviewWorkerThread, specHash, stuckDue, UNREADABLE_VERDICT, unheardWait, workerInFlight, workerReportedTerminal, type IdleBinding, type ProjectApprovalRecord } from "./reconcile.js"; import { readyStateSchema } from "./store.js"; import { GITHUB_REVIEWS, LINEAR_TICKETS } from "./templates.js"; @@ -408,6 +408,9 @@ describe("the pull request gate (build-tickets)", () => { const marker = (sha: string, verdict: string, lane: string) => comment({ id: `m-${sha}-${verdict}-${lane}`, author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); const owner = (body: string) => comment({ id: `oa-${body}`, author: "jane", body, signedBy: null, createdAt: "2026-10-14T17:00:00Z" }); + const approval = (sha: string, entry: string | null, verdict: "approved" | "declined" = "approved", id = `ap-${sha}-${verdict}`, createdAt = "2026-10-14T16:10:00Z") => + comment({ id, author: "trotterdylan", body: approvalMarkerLine({ sha, entry, verdict }), signedBy: "thr_project", createdAt }); + const record = (commentId: string, verdict: "approved" | "declined" = "approved"): ProjectApprovalRecord => ({ commentId, verdict }); const green = { checks: { state: "success", failing: [] } }; it("is met with the reviewer's approval on the head and green checks in the no-review lane", () => { @@ -460,39 +463,91 @@ describe("the pull request gate (build-tickets)", () => { }); it("accepts a project-steward approval for a project entry, and only the user's for a user entry (BB-30)", () => { - const project = pull({ comments: [marker(head, "approved", "owner-reviewed")] }, green); - expect(prGate(project, { decision: "project", projectApproved: true })).toMatchObject({ decision: "project", projectApproved: true, gateMet: true, needsOwnerApproval: false }); + const ap = approval(head, "A cross-repo contract"); + const project = pull({ comments: [marker(head, "approved", "owner-reviewed"), ap] }, green); + expect(prGate(project, { decision: "project", projectApprovals: [record(ap.id)] })).toMatchObject({ decision: "project", projectApproved: true, gateMet: true, needsOwnerApproval: false }); // The same approval on a `user` entry is ignored: the user's unsigned GitHub approval is required. - expect(prGate(project, { decision: "user", projectApproved: true })).toMatchObject({ decision: "user", projectApproved: false, gateMet: false, needsOwnerApproval: true, missing: "owner approval needed" }); + expect(prGate(project, { decision: "user", projectApprovals: [record(ap.id)] })).toMatchObject({ decision: "user", projectApproved: false, gateMet: false, needsOwnerApproval: true, missing: "owner approval needed" }); // The user's unsigned approval satisfies it either way. const ownerApproved = pull({ comments: [marker(head, "approved", "owner-reviewed"), owner("LGTM")] }, green); - expect(prGate(ownerApproved, { decision: "user", projectApproved: false }).gateMet).toBe(true); + expect(prGate(ownerApproved, { decision: "user" }).gateMet).toBe(true); // No project approval means the owner's. - expect(prGate(project, { projectApproved: false }).needsOwnerApproval).toBe(true); + expect(prGate(pull({ comments: [marker(head, "approved", "owner-reviewed")] }, green), { projectApprovals: [] }).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 }); + const ap = approval(head, "A cross-repo contract"); + const project = pull({ comments: [marker(head, "approved", "owner-reviewed"), ap] }, green); + const projectWaiting = prGate(project, { decision: "project", projectApprovals: [] }); 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 }); + expect(prGate(project, { decision: "project", projectApprovals: [record(ap.id)] })).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 }); + const userWaiting = prGate(project, { decision: "user", projectApprovals: [] }); 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 }); + expect(prGate(project, { decision: "user", projectApprovals: [record(ap.id)] })).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); + expect(prGate(ownerApproved, { decision: "project", projectApprovals: [] }).gateMet).toBe(false); + }); + + it("honours a project-steward marker only when the plugin recorded its comment id (BB-77)", () => { + // A hand-typed lookalike: the marker text is right, the comment id is not in the store. + const fake = approval(head, "A cross-repo contract", "approved", "typed-by-hand"); + const project = pull({ comments: [marker(head, "approved", "owner-reviewed"), fake] }, green); + expect(prGate(project, { decision: "project", projectApprovals: [record("IC_1")] })).toMatchObject({ projectApproved: false, gateMet: false, missing: "project steward approval needed" }); + // The record alone, with the marker gone from the snapshot, is not an approval either. + expect(prGate(pull({ comments: [marker(head, "approved", "owner-reviewed")] }, green), { decision: "project", projectApprovals: [record(fake.id)] })).toMatchObject({ projectApproved: false, gateMet: false }); + // A declined marker is not an approval even when its record matches. + const declined = approval(head, "A cross-repo contract", "declined", "IC_declined"); + expect(prGate(pull({ comments: [marker(head, "approved", "owner-reviewed"), declined] }, green), { decision: "project", projectApprovals: [record(declined.id, "declined")] })).toMatchObject({ projectApproved: false, gateMet: false, missing: "project steward approval needed" }); + }); + + it("lets a decline at a later sha revoke an earlier approval, and a later approval revoke the decline (BB-77)", () => { + const sha1 = "aaaaaaa1"; + const sha2 = "bbbbbbb2"; + const sha3 = "ccccccc3"; + const approved = approval(sha1, "A cross-repo contract", "approved", "IC_approved", "2026-10-14T16:10:00Z"); + const declined = approval(sha2, "A cross-repo contract", "declined", "IC_declined", "2026-10-14T16:20:00Z"); + const records: ProjectApprovalRecord[] = [record(approved.id), record(declined.id, "declined")]; + const declinedPull = pull({ comments: [marker(sha1, "approved", "owner-reviewed"), approved, declined] }, { ...green, headSha: sha3 }); + expect(prGate(declinedPull, { decision: "project", projectApprovals: records })).toMatchObject({ projectApproved: false, gateMet: false, missing: "project steward approval needed" }); + const approvedAgain = approval(sha3, "A cross-repo contract", "approved", "IC_approved_again", "2026-10-14T16:30:00Z"); + const reapproved = pull({ comments: [marker(sha1, "approved", "owner-reviewed"), approved, declined, approvedAgain] }, { ...green, headSha: sha3 }); + expect(prGate(reapproved, { decision: "project", projectApprovals: [...records, record(approvedAgain.id)] })).toMatchObject({ projectApproved: true, gateMet: true }); + }); + + it("covers a later head with an approval recorded on an earlier one (BB-77)", () => { + const earlier = "bbbbbbb2"; + const ap = approval(earlier, "A cross-repo contract"); + const moved = pull({ comments: [marker(earlier, "approved", "owner-reviewed"), ap] }, { ...green, headSha: head }); + expect(moved.pull?.headSha).toBe(head); + expect(prGate(moved, { decision: "project", projectApprovals: [record(ap.id)] })).toMatchObject({ projectApproved: true, gateMet: true, headSha: head }); + }); + + it("renders and parses the approval marker, quoting an entry with spaces (BB-77)", () => { + const line = approvalMarkerLine({ sha: head, entry: "A cross-repo contract other repos implement", verdict: "approved" }); + expect(line).toBe(``); + expect(projectApprovalMarker(line)).toEqual({ by: "project-steward", sha: head, entry: "A cross-repo contract other repos implement", verdict: null }); + expect(projectApprovalMarker(approvalMarkerLine({ sha: head, entry: null, verdict: "declined" }))).toEqual({ by: "project-steward", sha: head, entry: null, verdict: "declined" }); + expect(projectApprovalMarker("")).toBeNull(); + }); + + it("finds the worker that posted build-tickets' review comment (BB-77)", () => { + const c = comment({ id: "w", body: "Independent review running in bb thread thr_w.", signedBy: "thr_w" }); + expect(reviewWorkerThread([c])).toBe("thr_w"); + expect(reviewWorkerThread([comment({ id: "u", body: "Independent review running.", signedBy: null })])).toBeNull(); }); 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)); + const unknown = prGate(pull({ comments: [marker(head, "approved", "something-else")] }, green), { projectApprovals: [] }); expect(unknown).toMatchObject({ lane: "something-else", gateMet: false, needsOwnerApproval: true }); // With a project approval it is satisfied as owner-reviewed, not as no-review. - expect(prGate(pull({ comments: [marker(head, "approved", "something-else")] }, green), { decision: "project", projectApproved: true }).gateMet).toBe(true); - expect(prGate(pull({ comments: [marker(head, "approved", "something-else")] }, green), { projectApproved: false }).gateMet).toBe(false); + const ap = approval(head, "A cross-repo contract"); + const withAp = pull({ comments: [marker(head, "approved", "something-else"), ap] }, green); + expect(prGate(withAp, { decision: "project", projectApprovals: [record(ap.id)] }).gateMet).toBe(true); + expect(prGate(withAp, { projectApprovals: [] }).gateMet).toBe(false); }); it("is not met when the verdict is not approved, checks are not green, or there is no round", () => { diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index 08e185d9..319d7191 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -421,6 +421,94 @@ export function ownerApproval(entity: EntitySnapshot): { approved: boolean; at: return { approved: at !== null, at }; } +// ---- the project steward's approval marker -------------------------------------------- + +/** + * A project steward's `bb-approval` marker, as the plugin posts it on a pull + * request: ``. + * `entry` is quoted when it contains whitespace. `verdict` is null on an + * approval and `declined` on a decline. + */ +export type ProjectApprovalMarker = { by: string; sha: string; entry: string | null; verdict: string | null }; + +/** + * The plugin's own record of an approval marker it posted: the GitHub comment + * id of the marker and the verdict it carried. A marker on the pull request + * counts only when its comment id is in the store's records, so a hand-typed + * lookalike (a different comment id) never satisfies the gate. + */ +export type ProjectApprovalRecord = { commentId: string | null; verdict: string }; + +const APPROVAL_MARKER = /^/u; +const MARKER_ATTR = /([A-Za-z][A-Za-z0-9_-]*)=(?:"((?:[^"\\]|\\.)*)"|(\S+))/gu; + +/** Quote a marker attribute value when it contains whitespace or a delimiter. */ +function markerAttr(value: string): string { + return /[\s"<>]/u.test(value) ? JSON.stringify(value) : value; +} + +function unescapeMarker(value: string): string { + try { + return JSON.parse(`"${value}"`) as string; + } catch { + return value; + } +} + +/** The first line of a project-steward approval marker, as the plugin posts it. */ +export function approvalMarkerLine(fields: { sha: string; entry: string | null; verdict: "approved" | "declined" }): string { + const attrs = ["by=project-steward", `sha=${fields.sha}`]; + if (fields.entry !== null && fields.entry.trim() !== "") attrs.push(`entry=${markerAttr(fields.entry.trim())}`); + if (fields.verdict === "declined") attrs.push("verdict=declined"); + return ``; +} + +/** + * The project-steward approval marker on a comment, or null for any other + * comment. Any first line that opens a `bb-approval` comment is read, however + * its keys are spelled; an unreadable one is still a marker (with no verdict), + * so it never counts as an approval. + */ +export function projectApprovalMarker(body: string): ProjectApprovalMarker | null { + const first = body.split("\n", 1)[0]!.trim(); + const m = APPROVAL_MARKER.exec(first); + if (m === null) return null; + const attrs = new Map(); + for (const t of m[1]!.matchAll(MARKER_ATTR)) attrs.set(t[1]!.toLowerCase(), t[2] !== undefined ? unescapeMarker(t[2]) : t[3]!); + return { by: attrs.get("by") ?? "", sha: attrs.get("sha") ?? "", entry: attrs.get("entry") ?? null, verdict: attrs.get("verdict") ?? null }; +} + +/** + * The newest `bb-approval` marker whose comment id the plugin itself recorded, + * by comment time. A marker with an id the store does not hold is a lookalike + * someone typed and is skipped. + */ +export function latestProjectApprovalMarker(comments: readonly SnapshotComment[], recordedCommentIds: ReadonlySet): { marker: ProjectApprovalMarker; comment: SnapshotComment } | null { + let at = ""; + let latest: { marker: ProjectApprovalMarker; comment: SnapshotComment } | null = null; + for (const c of comments) { + if (!recordedCommentIds.has(c.id)) continue; + const marker = projectApprovalMarker(c.body); + if (marker === null) continue; + if (c.createdAt >= at) { + at = c.createdAt; + latest = { marker, comment: c }; + } + } + return latest; +} + +/** + * The worker thread that posted build-tickets' "Independent review running" + * comment, or null. The worker is told the approval landed so it merges + * without a `github_watch` on the owner. + */ +export function reviewWorkerThread(comments: readonly SnapshotComment[]): string | null { + let found: string | null = null; + for (const c of comments) if (c.signedBy !== null && c.body.includes("Independent review running")) found = c.signedBy; + return found; +} + /** * The lane gate from the build-tickets skill, in one place: the reviewer's * latest marker has verdict `approved`, every check has passed, and, in the @@ -449,16 +537,16 @@ export type PrGate = { 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. */ + /** Whether the plugin posted a project-steward approval marker on this pull request. */ projectApproved: boolean; }; -/** The project steward's side of the gate: the decide mark and the recorded approval. */ +/** The project steward's side of the gate: the decide mark and the plugin's own approval records. */ export type PrGateOptions = { /** The mark for the entry the project steward classified the pull request under; omitted is `user` (fail closed). */ decision?: "project" | "user"; - /** Whether a project-steward approval exists in the store for this head sha. */ - projectApproved?: boolean; + /** The plugin's own `project_approvals` records for this binding, matched to the marker by comment id. */ + projectApprovals?: readonly ProjectApprovalRecord[]; }; export function prGate(entity: EntitySnapshot, opts: PrGateOptions = {}): PrGate { @@ -473,12 +561,25 @@ 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 project steward's decision is the plugin's own record AND the marker + // it posted: only a `bb-approval` comment whose id the plugin recorded + // counts, so a hand-typed lookalike (a different comment id) never does. + // Every record is kept, declines included: the newest matching marker's + // verdict decides, so a decline at a later sha revokes an earlier approval + // rather than leaving its marker as the latest word. The record's head sha + // is not compared with the current head: a decision is of the pull request, + // and a later head is covered unless the worker added scope (AGENTS.md, + // "What counts as an approval"). + const recorded = new Map((opts.projectApprovals ?? []).filter((r) => r.commentId !== null).map((r) => [r.commentId!, r.verdict] as const)); + const approval = latestProjectApprovalMarker(entity.comments, new Set(recorded.keys())); + const approvalVerdict = approval === null ? null : (approval.marker.verdict ?? recorded.get(approval.comment.id) ?? "approved"); + const projectApprovedRaw = approvalVerdict !== null && approvalVerdict !== "declined"; // 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 + // wins; without one, a 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 decision: "project" | "user" = opts.decision === "project" || (opts.decision === undefined && projectApprovedRaw) ? "project" : "user"; + const projectApproved = projectApprovedRaw && decision === "project"; const approved = decision === "project" ? projectApproved : owner.approved; const approvalNeeded = ownerLane && markerApproved && checksGreen && !approved; const gateMet = pull !== null && markerApproved && checksGreen && (!ownerLane || approved); diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 03ca8792..90130ea9 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -60,6 +60,7 @@ function world() { const github = { comment: async (repo: string, number: number, body: string) => { githubComments.push({ repo, number, body }); + return `IC_${githubComments.length}`; }, squashMerge: async (repo: string, number: number, title: string, body: string) => { githubMerges.push({ repo, number, title, body }); @@ -3697,16 +3698,80 @@ describe("needs you items", () => { const userEntry = await t.tool("steward_update", { binding: "ENG-12", approve: true, entry: "Granting a new credential, token or cluster access, or widening what an existing one can reach" }, t.project); expect(userEntry.error).toBe(true); expect(userEntry.text).toMatch(/forward/u); - // A `project` entry is recorded, bound to the head sha, only in the store. + // A `project` entry is recorded, bound to the head sha, and the plugin + // posts the signed marker on the pull request (BB-77). const approved = await t.tool("steward_update", { binding: "ENG-12", approve: true, entry: "A cross-repo contract other repos implement" }, t.project); expect(approved.error).toBe(false); - expect(t.hooks.store.projectApproval(b.id, "aaaaaaa1")).toMatchObject({ entry: "A cross-repo contract other repos implement", byThread: t.project }); - expect(t.githubComments).toEqual([]); - // A new push is a new sha: there is no approval for it. + expect(t.hooks.store.projectApproval(b.id, "aaaaaaa1")).toMatchObject({ entry: "A cross-repo contract other repos implement", byThread: t.project, verdict: "approved" }); + expect(t.githubComments).toHaveLength(1); + expect(t.githubComments[0]!.body).toMatch(/^/u); + expect(t.githubComments[0]!.body).toMatch(/_— from bb thread .+_/u); + // The record is tied to the marker's comment id, so a hand-typed lookalike never counts. + expect(t.hooks.store.projectApproval(b.id, "aaaaaaa1")).toMatchObject({ commentId: "IC_1" }); + // A new push is a new sha: the store's exact-sha lookup is null again (the + // marker survives, so the lane gate still reads it as approved). t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] }, headSha: "bbbbbbb2" })); expect(t.hooks.store.projectApproval(b.id, "bbbbbbb2")).toBeNull(); }); + it("wakes the pull request's worker when the project steward approves, so it merges without the owner (BB-77)", async () => { + const workerComment = comment({ id: "w1", author: "trotterdylan", body: "Independent review running in bb thread @thread:thr_w1.", signedBy: "thr_w1", createdAt: "2026-10-14T16:05:00Z" }); + const t = await withPull([marker, workerComment]); + t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t.ring("linear", "uuid-12"); + await t.created("thr_w1", t.steward, "ENG-12: Implement"); + await t.idle("thr_w1", "Waiting on the owner's approval."); + const before = t.sends.filter((s) => s.threadId === "thr_w1").length; + const b = t.binding(); + const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval")!; + const res = await t.tool("steward_update", { binding: "ENG-12", approve: true, entry: "A cross-repo contract other repos implement" }, t.project); + expect(res.error).toBe(false); + const sent = t.sends.filter((s) => s.threadId === "thr_w1"); + expect(sent).toHaveLength(before + 1); + expect(sent.at(-1)!.text).toMatch(/The project steward approved acme\/web#7/u); + expect(sent.at(-1)!.text).toMatch(/merge it now/u); + expect(t.hooks.store.escalation(esc.id)!.status).toBe("resolved"); + }); + + it("wakes the ticket steward when the worker has ended before the approval lands (BB-77)", async () => { + const workerComment = comment({ id: "w1", author: "trotterdylan", body: "Independent review running in bb thread @thread:thr_w1.", signedBy: "thr_w1", createdAt: "2026-10-14T16:05:00Z" }); + const t = await withPull([marker, workerComment]); + t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t.ring("linear", "uuid-12"); + await t.created("thr_w1", t.steward, "ENG-12: Implement"); + await t.idle("thr_w1", "Done for now."); + t.threads.get("thr_w1")!.archivedAt = 1; + const before = t.sends.filter((s) => s.threadId === t.steward).length; + const res = await t.tool("steward_update", { binding: "ENG-12", approve: true, entry: "A cross-repo contract other repos implement" }, t.project); + expect(res.error).toBe(false); + expect(t.sends.filter((s) => s.threadId === "thr_w1")).toHaveLength(0); + await t.flush(); + const wakes = t.sends.filter((s) => s.threadId === t.steward); + expect(wakes.length).toBeGreaterThan(before); + expect(wakes.at(-1)!.text).toMatch(/The project steward approved acme\/web#7/u); + expect(wakes.at(-1)!.text).toMatch(/section 4c/u); + }); + + it("posts a declined marker and tells the worker to treat it as a change request (BB-77)", async () => { + const workerComment = comment({ id: "w1", author: "trotterdylan", body: "Independent review running in bb thread @thread:thr_w1.", signedBy: "thr_w1", createdAt: "2026-10-14T16:05:00Z" }); + const t = await withPull([marker, workerComment]); + t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t.ring("linear", "uuid-12"); + await t.created("thr_w1", t.steward, "ENG-12: Implement"); + await t.idle("thr_w1", "Waiting on the project steward."); + const b = t.binding(); + const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval" && x.resolutionKind === "approve-decline")!; + const res = await t.tool("steward_update", { binding: "ENG-12", guidance: "Needs a test for the contract first.", resolve: esc.id }, t.project); + expect(res.error).toBe(false); + const posted = t.githubComments.at(-1)!; + expect(posted.body).toMatch(/^/u); + expect(posted.body).toMatch(/Needs a test for the contract first\./u); + expect(t.hooks.store.projectApprovals(b.id).at(-1)).toMatchObject({ verdict: "declined", commentId: "IC_1" }); + const sent = t.sends.filter((s) => s.threadId === "thr_w1"); + expect(sent.at(-1)!.text).toMatch(/The project steward declined acme\/web#7/u); + expect(sent.at(-1)!.text).toMatch(/change request/u); + }); + it("bb stewards escalate from a worker files an escalation on its binding and wakes the steward (BB-30)", async () => { const t = await setup(); t.entities.set("uuid-12", issue()); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index df29cb0e..587d896b 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -56,7 +56,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, IDLE_WAKE_TEXT, idleInActiveStage, isCommentNews, isSpecComment, latestReviewMarker, lifecycle, namesUserAsBlocker, newHumanComments, newestCommentAt, ownPullClosed, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, workerReportedTerminal, type Change } from "./reconcile.js"; +import { advanced, answerDiffers, anyWorkerInFlight, approvalMarkerLine, approvalWanted, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, IDLE_WAKE_TEXT, idleInActiveStage, isCommentNews, isSpecComment, latestReviewMarker, lifecycle, namesUserAsBlocker, newHumanComments, newestCommentAt, ownPullClosed, phaseAndStage, prGate, resolveChecklistItem, reviewWorkerThread, specHash, stuckDue, unheardWait, workerInFlight, workerReportedTerminal, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, STEWARDS_PLUGIN_ID, @@ -745,11 +745,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const sourceRpc = (source: Source, method: string, input: unknown, outputSchema: z.ZodType): Promise => rpc(SOURCE_PLUGIN_IDS[source], method, input, outputSchema); - /** Whether the project steward recorded an approval for this binding's current pull-request head. */ - const projectApprovedFor = (b: Binding, entity: EntitySnapshot): boolean => { - const sha = entity.pull?.headSha ?? null; - return sha !== null && store.projectApproval(b.id, sha) !== null; - }; + /** The plugin's own project-steward approval records for a binding; the gate matches a posted marker to one by comment id. */ + const projectApprovalsFor = (b: Binding) => store.projectApprovals(b.id); /** The repo-relative paths a pull request changes, or null when they cannot be read (which fails closed to the user). */ async function pullChangedFiles(entity: EntitySnapshot): Promise { @@ -1871,11 +1868,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P changes, needs: store.openNeeds(b.id), own: ownThreads(b), - projectApprovedShas: new Set( - [observed.entity, ...observed.pulls] - .map((e) => e.pull?.headSha) - .filter((sha): sha is string => sha !== null && sha !== undefined && store.projectApproval(b.id, sha) !== null), - ), + projectApprovals: projectApprovalsFor(b), label: config.file.label, conflicts: conflictsOf(b, store.open(b.projectId)), deployments: b.deployments, @@ -3750,6 +3743,46 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const shortSha = (sha: string | null | undefined) => (sha === null || sha === undefined ? "?" : sha.slice(0, 7)); + /** + * Post the plugin's `bb-approval` marker on a pull request as `byThread` + * and return the GitHub comment id. The marker is signed, so + * `ownerApproval` never reads it as the owner's unsigned approval, and the + * returned id is what the lane gate matches the store's record against. + */ + async function postApprovalMarker(entity: EntitySnapshot, byThread: string, fields: { headSha: string; entry: string | null; verdict: "approved" | "declined"; reasoning: string }): Promise { + const ref = parsePullRef(entity.url ?? entity.key); + if (ref === null) throw new Error(`I cannot tell which pull request ${entity.key} is.`); + if (fields.headSha.trim() === "") throw new Error("The pull request's head sha is not known yet, so the marker cannot name it. Retry once the pull request has been observed."); + const body = [approvalMarkerLine({ sha: fields.headSha, entry: fields.entry, verdict: fields.verdict }), "", fields.reasoning.trim(), "", signatureLine(byThread)].join("\n"); + return github.comment(ref.repo, ref.number, body); + } + + /** + * Tell the pull request's worker the project steward's decision landed, so + * it merges (or reworks) without a `github_watch` on the owner. The worker + * is the thread that posted build-tickets' "Independent review running" + * comment, or the newest worker still in flight. When it has ended and + * cannot be reached, the ticket steward is woken with the decision under + * "What changed" and starts a fresh worker at section 4c. + */ + async function deliverProjectApproval(b: Binding, entity: EntitySnapshot, decision: { verdict: "approved" | "declined"; sha: string; entry: string | null; reasoning: string }): Promise<"worker" | "steward"> { + const signed = reviewWorkerThread(entity.comments); + const thread = (signed !== null && store.worker(signed)?.bindingId === b.id ? signed : null) ?? [...store.workers(b.id)].reverse().find((w) => workerInFlight(w))?.threadId ?? null; + const info = thread === null ? null : await threadInfo(thread).catch(() => null); + const label = decision.verdict === "approved" ? "approved" : "declined"; + const entry = decision.entry === null ? "" : ` (entry ${JSON.stringify(decision.entry)})`; + const next = decision.verdict === "approved" ? "the lane gate is met: merge it now (build-tickets section 4c), do not wait for the owner" : "the lane gate is not met: treat this as a change request and address it"; + if (info !== null && info.deletedAt === null && info.archivedAt === null) { + if ((await sendTo(thread!, `The project steward ${label} ${entity.key}${entry} at ${shortSha(decision.sha)}: ${decision.reasoning}\n\n${next}.`)) === "sent") { + store.note(b.id, `The project steward ${label} ${entity.key}${entry} at ${shortSha(decision.sha)}; its worker was told.`, true); + return "worker"; + } + } + store.note(b.id, `The project steward ${label} ${entity.key}${entry} at ${shortSha(decision.sha)}: ${decision.reasoning} Start a worker at build-tickets section 4c ${decision.verdict === "approved" ? "to merge it" : "to address the change request"}.`, false); + scheduleReconcile(b.id); + return "steward"; + } + /** Every pull request a binding observes: a pr binding's own entity, and a ticket's linked pulls. */ function observedPulls(b: Binding, observed: Observed): EntitySnapshot[] { const own = observed.entity.pull === null ? [] : [observed.entity]; @@ -3898,11 +3931,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // 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) }); + const preliminary = prGate(pull, { projectApprovals: projectApprovalsFor(b) }); 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) }); + g = prGate(pull, { decision: decideForPull(files, decisions), projectApprovals: projectApprovalsFor(b) }); } 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; @@ -4971,7 +5004,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const ref = parsePullRef(need.url); if (ref === null) return { ok: false, message: `I cannot tell which pull request ${need.url} is.` }; const pull = await freshPull(); - const gate = pull === null ? null : prGate(pull, { projectApproved: pull === null ? false : projectApprovedFor(b, pull) }); + const gate = pull === null ? null : prGate(pull, { projectApprovals: projectApprovalsFor(b) }); if (pull === null || gate === null || !gate.gateMet) return { ok: false, message: `The gate is not met: ${gate?.missing ?? "the pull request could not be read"}.` }; if (anyWorkerInFlight(store.workers(b.id))) return { ok: false, message: "A worker is still running on this pull request." }; const lane = gate.lane ?? "no-review"; @@ -5620,7 +5653,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // 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 gate = pull === undefined ? null : prGate(pull, { decision, projectApprovals: projectApprovalsFor(b) }); 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.`); @@ -5974,11 +6007,19 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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 }); const answer = guidance ?? `Approved as ${JSON.stringify(input.entry)}.`; + if (pull === null) return toolError(new Error("The pull request could not be read, so the approval marker cannot be posted.")); + let commentId: string; + try { + commentId = await postApprovalMarker(pull, threadId, { headSha: prApproval.headSha ?? "", entry: input.entry ?? null, verdict: "approved", reasoning: answer }); + } catch (error) { + return toolError(error); + } + store.recordProjectApproval({ bindingId: target.id, headSha: prApproval.headSha ?? "", entry: input.entry ?? null, byThread: threadId, commentId, verdict: "approved" }); store.addGuidance(target.id, answer, threadId); store.answerEscalation(prApproval.id, answer, threadId); - done.push(`recorded the project steward's approval of ${prApproval.url} bound to ${shortSha(prApproval.headSha)}`); + const reached = await deliverProjectApproval(target, pull, { verdict: "approved", sha: prApproval.headSha ?? "", entry: input.entry ?? null, reasoning: answer }); + done.push(`posted the project steward's approval marker on ${prApproval.url} at ${shortSha(prApproval.headSha)} and ${reached === "worker" ? "told its worker" : "woke the steward"}`); return `${target.entityKey}: ${done.join("; ")}.`; } if (input.approve === true) { @@ -6186,9 +6227,25 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (saved && resolve === undefined) notes.push(`New guidance: ${guidance}`); } if (resolving !== null) { + // A declined pull-request approval posts its marker before the + // escalation is resolved, so a GitHub failure leaves the request + // open to retry rather than recording a decision nobody can see. + const isDecline = resolving.kind === "approval" && resolving.resolutionKind === "approve-decline" && resolving.status === "open" && approval === null && classifyApproval(guidance) !== "approve"; + const declinePull = isDecline && target.lastSnapshot !== null ? observedPulls(target, target.lastSnapshot).find((p) => (p.url ?? p.key) === resolving.url) ?? null : null; + const declineSha = resolving.headSha ?? declinePull?.pull?.headSha ?? null; + if (isDecline && declinePull !== null) { + const entry = input.entry ?? null; + try { + const commentId = await postApprovalMarker(declinePull, threadId, { headSha: declineSha ?? "", entry, verdict: "declined", reasoning: guidance ?? "" }); + store.recordProjectApproval({ bindingId: target.id, headSha: declineSha ?? "", entry, byThread: threadId, commentId, verdict: "declined" }); + } catch (error) { + return toolError(error); + } + await deliverProjectApproval(target, declinePull, { verdict: "declined", sha: declineSha ?? "", entry, reasoning: guidance ?? "" }); + } // 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.resolutionKind === "approve-decline" && resolving.status === "open" && approval === null && classifyApproval(guidance) !== "approve") { + if (isDecline) { // 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; @@ -6262,7 +6319,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (n.kind === "approve-pr" || n.kind === "merge") { const observed = b.lastSnapshot; const target = observed === null ? null : [observed.entity, ...observed.pulls].find((e) => (e.url ?? e.key) === n.url || e.key === n.url) ?? null; - const gate = target === null ? null : prGate(target, { projectApproved: projectApprovedFor(b, target) }); + const gate = target === null ? null : prGate(target, { projectApprovals: projectApprovalsFor(b) }); if (n.kind === "approve-pr") { actionable = gate?.needsOwnerApproval ?? false; why = actionable ? null : (gate?.missing ?? "the pull request has not been observed yet"); diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index a9cf6d13..5cba0d07 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -1,6 +1,6 @@ import Database from "better-sqlite3"; import { describe, expect, it } from "vitest"; -import { BASE_MIGRATIONS, CHAIN_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_TIER_MIGRATIONS, MIGRATIONS, RATIONALE_MIGRATIONS, VALIDATION_MIGRATIONS, WORKER_CHECK_MIGRATIONS, createStore, lessonScope } from "./store.js"; +import { APPROVAL_MARKER_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_TIER_MIGRATIONS, MIGRATIONS, RATIONALE_MIGRATIONS, VALIDATION_MIGRATIONS, WORKER_CHECK_MIGRATIONS, createStore, lessonScope } from "./store.js"; function store() { const db = new Database(":memory:"); @@ -242,6 +242,7 @@ describe("lesson citation counts (BB-35 step 2)", () => { for (const sql of RATIONALE_MIGRATIONS) db.exec(sql); for (const sql of VALIDATION_MIGRATIONS) db.exec(sql); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); const s = createStore(db, () => 2000); expect(s.lesson("lsn_old")).toMatchObject({ id: "lsn_old", @@ -283,6 +284,7 @@ describe("the lesson tier migration (BB-35 step 3)", () => { for (const sql of RATIONALE_MIGRATIONS) db.exec(sql); for (const sql of VALIDATION_MIGRATIONS) db.exec(sql); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); return db; }; @@ -309,11 +311,13 @@ describe("the lesson tier migration (BB-35 step 3)", () => { // `bb.storage.migrate` records each statement by index and refuses a changed // one; a group spliced in mid-array would fail every live database on load. // BB-35 step 4 appended the rationale group, step 5 the validation group, - // step 6 the guidance group, and BB-83 the idle group, after this one. - expect(MIGRATIONS.slice(-IDLE_MIGRATIONS.length)).toEqual([...IDLE_MIGRATIONS]); - expect(MIGRATIONS.slice(-(IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length), -IDLE_MIGRATIONS.length)).toEqual([...GUIDANCE_MIGRATIONS]); - expect(MIGRATIONS.slice(-(IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length + VALIDATION_MIGRATIONS.length), -(IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length))).toEqual([...VALIDATION_MIGRATIONS]); - const afterTier = IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length + VALIDATION_MIGRATIONS.length + RATIONALE_MIGRATIONS.length; + // step 6 the guidance group, BB-83 the idle group, and BB-77 the approval + // marker group, after this one. + expect(MIGRATIONS.slice(-APPROVAL_MARKER_MIGRATIONS.length)).toEqual([...APPROVAL_MARKER_MIGRATIONS]); + expect(MIGRATIONS.slice(-(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length), -APPROVAL_MARKER_MIGRATIONS.length)).toEqual([...IDLE_MIGRATIONS]); + expect(MIGRATIONS.slice(-(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length), -(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length))).toEqual([...GUIDANCE_MIGRATIONS]); + expect(MIGRATIONS.slice(-(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length + VALIDATION_MIGRATIONS.length), -(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length))).toEqual([...VALIDATION_MIGRATIONS]); + const afterTier = APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length + VALIDATION_MIGRATIONS.length + RATIONALE_MIGRATIONS.length; expect(MIGRATIONS.slice(-(afterTier + LESSON_TIER_MIGRATIONS.length), -afterTier)).toEqual([...LESSON_TIER_MIGRATIONS]); }); }); @@ -331,6 +335,7 @@ describe("the rationale migration (BB-35 step 4)", () => { for (const sql of RATIONALE_MIGRATIONS) db.exec(sql); for (const sql of VALIDATION_MIGRATIONS) db.exec(sql); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); return db; }; @@ -376,6 +381,7 @@ describe("the validation migration (BB-35 step 5)", () => { VALUES ('lsn_1', 'p1', 'bnd_1', NULL, 'AGENTS.md', 'A rule.', 'procedure', 'pending', 'trial', 1000, 2, 1, 1000, 1000)`); for (const sql of VALIDATION_MIGRATIONS) db.exec(sql); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); return db; }; @@ -437,6 +443,7 @@ describe("the guidance-citation migration (BB-35 step 6)", () => { db.exec(`INSERT INTO escalations (id, binding_id, kind, question, meanwhile, route, status, created_at, project_id) VALUES ('esc_1', 'bnd_1', 'decision', 'Include SSO?', 'Wait.', 'me', 'open', 1000, 'p1')`); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); const s = createStore(db, () => 2000); expect(s.escalation("esc_1")).toMatchObject({ id: "esc_1", question: "Include SSO?", projectId: "p1" }); expect(s.guidanceCitations("p1")).toEqual([]); @@ -448,6 +455,7 @@ describe("the guidance-citation migration (BB-35 step 6)", () => { it("counts a guidance unit once per distinct binding, refreshing last cited on a repeat", () => { const db = legacy(); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); let now = 2000; const s = createStore(db, () => now); const unit = { id: "gu_aaaaaaaaaaaaaaaa", file: "AGENTS.md", text: "A rule." }; @@ -468,6 +476,7 @@ describe("the guidance-citation migration (BB-35 step 6)", () => { it("settles a cluster for good and links the lesson that answers it", () => { const db = legacy(); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); const s = createStore(db, () => 2000); db.exec(`INSERT INTO escalations (id, binding_id, kind, question, meanwhile, route, status, created_at, project_id, cluster_key) VALUES ('esc_1', 'bnd_1', 'decision', 'Include SSO?', 'Wait.', 'me', 'open', 1000, 'p1', 'k1'), @@ -483,6 +492,7 @@ describe("the guidance-citation migration (BB-35 step 6)", () => { it("reads a binding's unanswered after-the-fact asks, newest first", () => { const db = legacy(); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); const s = createStore(db, () => 2000); db.exec(`INSERT INTO escalations (id, binding_id, kind, question, meanwhile, route, status, created_at, project_id, rationale_asked, rationale_given) VALUES ('esc_old', 'bnd_1', 'decision', 'Old?', 'Wait.', 'me', 'open', 1000, 'p1', 1, 0), @@ -494,9 +504,10 @@ describe("the guidance-citation migration (BB-35 step 6)", () => { }); it("is appended at the end of MIGRATIONS, so a shipped statement index is never reused", () => { - expect(MIGRATIONS.slice(-IDLE_MIGRATIONS.length)).toEqual([...IDLE_MIGRATIONS]); - expect(MIGRATIONS.slice(-(IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length), -IDLE_MIGRATIONS.length)).toEqual([...GUIDANCE_MIGRATIONS]); - expect(MIGRATIONS.slice(-(IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length + VALIDATION_MIGRATIONS.length), -(IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length))).toEqual([...VALIDATION_MIGRATIONS]); + expect(MIGRATIONS.slice(-APPROVAL_MARKER_MIGRATIONS.length)).toEqual([...APPROVAL_MARKER_MIGRATIONS]); + expect(MIGRATIONS.slice(-(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length), -APPROVAL_MARKER_MIGRATIONS.length)).toEqual([...IDLE_MIGRATIONS]); + expect(MIGRATIONS.slice(-(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length), -(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length))).toEqual([...GUIDANCE_MIGRATIONS]); + expect(MIGRATIONS.slice(-(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length + VALIDATION_MIGRATIONS.length), -(APPROVAL_MARKER_MIGRATIONS.length + IDLE_MIGRATIONS.length + GUIDANCE_MIGRATIONS.length))).toEqual([...VALIDATION_MIGRATIONS]); }); }); @@ -518,7 +529,7 @@ describe("a worker's pending model check", () => { it("reads workers from before the column existed as not pending", () => { const db = new Database(":memory:"); - for (const sql of [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS]) db.exec(sql); + for (const sql of [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS]) db.exec(sql); db.exec(`INSERT INTO bindings (id, project_id, source, entity_id, entity_key, kind, playbook, playbook_version, created_at) VALUES ('bnd_1', 'p1', 'linear', 'uuid-12', 'ENG-12', 'ticket', 'linear-tickets', 'v1', 1000)`); db.exec(`INSERT INTO workers (thread_id, binding_id, title, status, started_at) VALUES ('thr_old', 'bnd_1', 'ENG-12: Implement', 'running', 1000)`); @@ -560,6 +571,7 @@ describe("the escalation-chain migration (BB-30)", () => { for (const sql of RATIONALE_MIGRATIONS) db.exec(sql); for (const sql of VALIDATION_MIGRATIONS) db.exec(sql); for (const sql of GUIDANCE_MIGRATIONS) db.exec(sql); + for (const sql of APPROVAL_MARKER_MIGRATIONS) db.exec(sql); let now = 2000; return { db, s: createStore(db, () => now) }; } diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index e3ae8c18..7a8e7127 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -442,7 +442,18 @@ export const IDLE_MIGRATIONS = [ `ALTER TABLE bindings ADD COLUMN idle_wake_now INTEGER NOT NULL DEFAULT 0`, ]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS]; +// BB-77: the project-steward approval marker. The approval record gains the +// GitHub comment id of the `bb-approval` marker the plugin posted (the lane +// gate honours a marker only when its id is recorded, so a hand-typed lookalike +// never counts) and the verdict it carried (approved or declined). Additive and +// defaulted: a record made before this step reads as an approval with no marker +// id, which the gate ignores. +export const APPROVAL_MARKER_MIGRATIONS = [ + `ALTER TABLE project_approvals ADD COLUMN comment_id TEXT`, + `ALTER TABLE project_approvals ADD COLUMN verdict TEXT NOT NULL DEFAULT 'approved'`, +]; + +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -787,13 +798,23 @@ export type Escalation = { clusterKey: string | null; }; -/** A project steward's approval of an owner-reviewed pull request, bound to its head sha. */ +/** + * A project steward's approval (or decline) of an owner-reviewed pull request, + * bound to its head sha. `commentId` is the GitHub comment id of the + * `bb-approval` marker the plugin posted for it; the lane gate honours a marker + * only when its comment id is recorded here, so a hand-typed lookalike never + * counts. + */ export type ProjectApproval = { bindingId: string; headSha: string; /** The decide-list entry the project steward classified it under. */ entry: string | null; byThread: string; + /** The GitHub comment id of the marker the plugin posted, or null for a record made before markers. */ + commentId: string | null; + /** The marker's verdict. */ + verdict: "approved" | "declined"; createdAt: number; }; @@ -1030,9 +1051,10 @@ export function createStore(db: Database.Database, now: () => number, options: S const markDeliveryDoneStmt = db.prepare("UPDATE pending_deliveries SET delivered_at = ? WHERE id = ?"); const insertProjectApproval = db.prepare( - "INSERT INTO project_approvals (binding_id, head_sha, entry, by_thread, created_at) VALUES (@binding_id, @head_sha, @entry, @by_thread, @created_at) ON CONFLICT (binding_id, head_sha) DO UPDATE SET entry = @entry, by_thread = @by_thread, created_at = @created_at", + "INSERT INTO project_approvals (binding_id, head_sha, entry, by_thread, comment_id, verdict, created_at) VALUES (@binding_id, @head_sha, @entry, @by_thread, @comment_id, @verdict, @created_at) ON CONFLICT (binding_id, head_sha) DO UPDATE SET entry = @entry, by_thread = @by_thread, comment_id = @comment_id, verdict = @verdict, created_at = @created_at", ); const getProjectApproval = db.prepare<[string, string], Record>("SELECT * FROM project_approvals WHERE binding_id = ? AND head_sha = ?"); + const projectApprovalsFor = db.prepare<[string], Record>("SELECT * FROM project_approvals WHERE binding_id = ? ORDER BY created_at"); const deleteProjectApproval = db.prepare("DELETE FROM project_approvals WHERE binding_id = ? AND head_sha = ?"); const insertWorker = db.prepare("INSERT INTO workers (thread_id, binding_id, title, status, started_at) VALUES (?, ?, ?, 'running', ?)"); @@ -1208,6 +1230,15 @@ export function createStore(db: Database.Database, now: () => number, options: S resolvedAt: x.resolvedAt, }); + const toProjectApproval = (r: Record): ProjectApproval => ({ + bindingId: String(r.binding_id), + headSha: String(r.head_sha), + entry: r.entry === null || r.entry === undefined ? null : String(r.entry), + byThread: String(r.by_thread), + commentId: r.comment_id === null || r.comment_id === undefined ? null : String(r.comment_id), + verdict: String(r.verdict ?? "approved") === "declined" ? "declined" : "approved", + createdAt: Number(r.created_at), + }); const toWorker = (r: Record): Worker => ({ threadId: String(r.thread_id), bindingId: String(r.binding_id), @@ -1636,19 +1667,21 @@ export function createStore(db: Database.Database, now: () => number, options: S */ projectApproval(bindingId: string, headSha: string): ProjectApproval | null { const r = getProjectApproval.get(bindingId, headSha); - return r === undefined - ? null - : { bindingId: String(r.binding_id), headSha: String(r.head_sha), entry: r.entry === null || r.entry === undefined ? null : String(r.entry), byThread: String(r.by_thread), createdAt: Number(r.created_at) }; + return r === undefined ? null : toProjectApproval(r); + }, + /** Every approval or decline the plugin recorded for a binding, oldest first; the gate matches a marker to one by comment id. */ + projectApprovals(bindingId: string): ProjectApproval[] { + return projectApprovalsFor.all(bindingId).map(toProjectApproval); }, /** - * Record a project-steward approval, bound to the pull request's head sha. - * The caller is responsible for checking that the approver is the project + * Record a project-steward approval or decline, bound to the pull + * request's head sha and to the marker comment the plugin posted. The + * caller is responsible for checking that the approver is the project * steward's thread; this is the store half. */ - recordProjectApproval(fields: { bindingId: string; headSha: string; entry: string | null; byThread: string }): ProjectApproval { - insertProjectApproval.run({ binding_id: fields.bindingId, head_sha: fields.headSha, entry: fields.entry, by_thread: fields.byThread, created_at: now() }); - const r = getProjectApproval.get(fields.bindingId, fields.headSha)!; - return { bindingId: String(r.binding_id), headSha: String(r.head_sha), entry: r.entry === null || r.entry === undefined ? null : String(r.entry), byThread: String(r.by_thread), createdAt: Number(r.created_at) }; + recordProjectApproval(fields: { bindingId: string; headSha: string; entry: string | null; byThread: string; commentId?: string | null; verdict?: "approved" | "declined" }): ProjectApproval { + insertProjectApproval.run({ binding_id: fields.bindingId, head_sha: fields.headSha, entry: fields.entry, by_thread: fields.byThread, comment_id: fields.commentId ?? null, verdict: fields.verdict ?? "approved", created_at: now() }); + return toProjectApproval(getProjectApproval.get(fields.bindingId, fields.headSha)!); }, /** Drop a recorded approval (a new push voids it by sha; this is for an explicit retraction). */ clearProjectApproval(bindingId: string, headSha: string): boolean { diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 060021c2..c7887a19 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -12,7 +12,7 @@ import { FINDING_CLASSES, type FindingClass, type OpsFinding, type OpsLook } fro import type { DepsFinding, DepsLook } from "./deps.js"; import { dueDate } from "./deps.js"; import { NO_TOKEN, TOKEN_PAGE, TOKEN_SCOPES, TOKEN_SETTING, type SentryFinding, type SentryLook, type SentryReason } from "./sentry.js"; -import { newHumanComments, prGate, reportedItem, unheardWait, type GateState } from "./reconcile.js"; +import { newHumanComments, prGate, reportedItem, unheardWait, type GateState, type ProjectApprovalRecord } from "./reconcile.js"; import { conflictsOf, type Conflict } from "./schedule.js"; import type { EntitySnapshot, SessionWake, SnapshotComment, WorkflowRun } from "./source-contract.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"; @@ -242,8 +242,8 @@ export type WakeInput = { needs?: Need[]; /** The steward's thread and its workers': their comments are not news. */ own: ReadonlySet; - /** Head shas the project steward has approved in the store, so the lane gate reads the same as the button. */ - projectApprovedShas?: ReadonlySet; + /** The plugin's own project-steward approval records, so the lane gate reads the same as the button. */ + projectApprovals?: readonly ProjectApprovalRecord[]; /** The project's adoption label. */ label: string; /** Per-pull-request deployment state (BB-53); empty when the playbook names no deployment target. */ @@ -265,7 +265,7 @@ function commentLines(comments: SnapshotComment[]): string[] { return lines; } -function entityLines(e: EntitySnapshot, cursor: string, own: ReadonlySet, heading: string, projectApprovedShas?: ReadonlySet): string[] { +function entityLines(e: EntitySnapshot, cursor: string, own: ReadonlySet, heading: string, projectApprovals?: readonly ProjectApprovalRecord[]): string[] { const lines = [`### ${heading}`, ""]; lines.push(`- ${e.key}: ${e.title ?? "(untitled)"}${e.url === null ? "" : ` — ${e.url}`}`); lines.push(`- State: ${e.state}${e.stateType === null ? "" : ` (${e.stateType})`}`); @@ -277,7 +277,7 @@ function entityLines(e: EntitySnapshot, cursor: string, own: ReadonlySet lines.push(`- Branch: ${p.head ?? "?"} → ${p.base ?? "?"} at ${p.headSha?.slice(0, 7) ?? "?"}${p.headAuthor === null ? "" : ` (by ${p.headAuthor})`}`); lines.push(`- Checks: ${p.checks === null ? "none" : `${p.checks.state}${p.checks.failing.length > 0 ? ` — failing: ${p.checks.failing.join(", ")}` : ""}`}`); lines.push(`- Review decision: ${p.reviewDecision ?? "(none)"}; requested: ${p.requestedReviewers.join(", ") || "(none)"}`); - const gate = prGate(e, { projectApproved: e.pull?.headSha !== null && e.pull?.headSha !== undefined && projectApprovedShas?.has(e.pull.headSha) === true }); + const gate = prGate(e, { projectApprovals }); const lane = gate.lane === null ? "" : `lane ${gate.lane}`; if (gate.gateMet) { const approved = gate.marker === null ? "?" : gate.marker.sha.slice(0, 7); @@ -459,8 +459,8 @@ export function formatWake(input: WakeInput): string { const head = out.splice(0); out.push("", "## 4. Snapshot", ""); - out.push(...entityLines(e, binding.commentCursor, input.own, "The entity", input.projectApprovedShas)); - for (const pull of observed.pulls) out.push("", ...entityLines(pull, binding.commentCursor, input.own, `Linked pull request ${pull.key}`, input.projectApprovedShas)); + out.push(...entityLines(e, binding.commentCursor, input.own, "The entity", input.projectApprovals)); + for (const pull of observed.pulls) out.push("", ...entityLines(pull, binding.commentCursor, input.own, `Linked pull request ${pull.key}`, input.projectApprovals)); if (input.workers.length > 0) { out.push("", "### Workers", ""); for (const w of input.workers) {