diff --git a/plugins/github-watcher/github.test.ts b/plugins/github-watcher/github.test.ts index 4cbca785..fc9a3c8a 100644 --- a/plugins/github-watcher/github.test.ts +++ b/plugins/github-watcher/github.test.ts @@ -54,7 +54,7 @@ const pull = (over: Record = {}) => ({ headRefName: "feature/widgets", headRefOid: "0123456789abcdef", baseRefName: "main", - reviewRequests: { nodes: [{ requestedReviewer: { __typename: "User", login: "carol" } }, { requestedReviewer: { __typename: "Team", name: "backend" } }, { requestedReviewer: null }] }, + reviewRequests: { nodes: [{ requestedReviewer: { __typename: "User", login: "carol" } }, { requestedReviewer: { __typename: "Team", combinedSlug: "acme/backend" } }, { requestedReviewer: null }] }, latestReviews: { nodes: [{ author: { login: "bob" }, state: "COMMENTED" }, { author: { login: "jane" }, state: "PENDING" }] }, reviews: { nodes: [ @@ -109,7 +109,7 @@ describe("parseTarget", () => { head: "feature/widgets", headSha: "0123456789abcdef", reviewDecision: "review required", - requestedReviewers: ["backend", "carol"], + requestedReviewers: ["acme/backend", "carol"], reviews: ["bob: commented"], checks: { state: "failure", failing: ["ci/deploy (https://ci/deploy)", "test (https://ci/test)"] }, }); @@ -201,7 +201,7 @@ describe("parseSnapshot", () => { headSha: "0123456789abcdef", headAuthor: "jane", reviewDecision: "review required", - requestedReviewers: ["backend", "carol"], + requestedReviewers: ["acme/backend", "carol"], reviews: [ { author: "bob", state: "commented", submittedAt: "2026-10-09T08:30:00Z", commit: "aaaa" }, { author: "carol", state: "approved", submittedAt: "2026-10-09T10:00:00Z", commit: "bbbb" }, diff --git a/plugins/github-watcher/github.ts b/plugins/github-watcher/github.ts index 85f1b550..b2598a65 100644 --- a/plugins/github-watcher/github.ts +++ b/plugins/github-watcher/github.ts @@ -155,7 +155,7 @@ const targetDocument = (issueRelations: string) => `query($owner: String!, $name mergeCommit { oid } files(first: 100) { nodes { path } } timelineItems(last: 1, itemTypes: [BASE_REF_CHANGED_EVENT]) { nodes { ... on BaseRefChangedEvent { createdAt } } } - reviewRequests(first: 20) { nodes { requestedReviewer { __typename ... on User { login } ... on Team { name } ... on Bot { login } ... on Mannequin { login } } } } + reviewRequests(first: 20) { nodes { requestedReviewer { __typename ... on User { login } ... on Team { combinedSlug } ... on Bot { login } ... on Mannequin { login } } } } latestReviews(first: 50) { nodes { author ${ACTOR} state } } reviews(last: 50) { nodes { id author ${ACTOR} state body createdAt submittedAt url commit { oid } comments(first: 50) { nodes { ${COMMENT_FIELDS} path } } } } commits(last: 1) { nodes { commit { oid author { user { login } } statusCheckRollup { state contexts(first: 100) { nodes { __typename ... on CheckRun { name status conclusion detailsUrl } ... on StatusContext { context state targetUrl } } } } } } } } } } }`; @@ -239,7 +239,7 @@ const pullNode = z.object({ headRefName: z.string().nullish(), headRefOid: z.string().nullish(), baseRefName: z.string().nullish(), - reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({ __typename: z.string(), login: z.string().nullish(), name: z.string().nullish() }).nullish() })) }).nullish(), + reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({ __typename: z.string(), login: z.string().nullish(), combinedSlug: z.string().nullish(), name: z.string().nullish() }).nullish() })) }).nullish(), latestReviews: z.object({ nodes: z.array(z.object({ author: actor, state: z.string() })) }).nullish(), reviews: z.object({ nodes: z.array(reviewNode) }).nullish(), commits: z.object({ nodes: z.array(z.object({ commit: z.object({ oid: z.string(), author: z.object({ user: actor }).nullish(), statusCheckRollup: z.object({ state: z.string(), contexts: z.object({ nodes: z.array(contextNode) }).nullish() }).nullish() }) })) }).nullish(), @@ -395,7 +395,10 @@ function targetOf({ repo, node }: TargetRead, comments: Comment[]): Target { head: node.headRefName ?? null, headSha: commit?.oid ?? node.headRefOid ?? null, reviewDecision: lower(node.reviewDecision), - requestedReviewers: (node.reviewRequests?.nodes ?? []).map((r) => r.requestedReviewer?.login ?? r.requestedReviewer?.name ?? "").filter((s) => s !== "").sort(), + // A user (and a bot or mannequin) is its login; a team is its + // `combinedSlug` (`org/slug`), which a login-shape test rejects so a team + // request is never read as a delegate (BB-327). + requestedReviewers: (node.reviewRequests?.nodes ?? []).map((r) => r.requestedReviewer?.login ?? r.requestedReviewer?.combinedSlug ?? r.requestedReviewer?.name ?? "").filter((s) => s !== "").sort(), reviews: (node.latestReviews?.nodes ?? []) .filter((r) => r.state !== "PENDING") .map((r) => `${r.author?.login ?? "someone"}: ${lower(r.state)}`) diff --git a/plugins/stewards/approvals-store.ts b/plugins/stewards/approvals-store.ts index c47cff03..e1b8ff04 100644 --- a/plugins/stewards/approvals-store.ts +++ b/plugins/stewards/approvals-store.ts @@ -37,6 +37,37 @@ export const APPROVAL_MARKER_MIGRATIONS = [ `ALTER TABLE project_approvals ADD COLUMN verdict TEXT NOT NULL DEFAULT 'approved'`, ]; +// BB-327: every login seen in a pull request's requested-reviewers list, for +// the binding and URL. GitHub drops a reviewer from the live list once they +// submit a review, and the snapshot carries no request history, so the gate +// remembers the logins it has seen and counts a delegate's later APPROVED +// review against this set as well as the live list. A new table, so a store +// from before this step reads back exactly as before. +export const PULL_REQUESTER_MIGRATIONS = [ + `CREATE TABLE IF NOT EXISTS pull_requesters ( + binding_id TEXT NOT NULL, + url TEXT NOT NULL, + login TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (binding_id, url, login) + )`, +]; + +// BB-327: the (delegate, head) pairs the plugin has re-requested review from +// after a changes-requested review, so a repeated look does not re-request and +// the status can say the delegate was re-solicited for the current head. A new +// table, so a store from before this step reads back exactly as before. +export const REVIEWER_REQUEST_MIGRATIONS = [ + `CREATE TABLE IF NOT EXISTS reviewer_requests ( + binding_id TEXT NOT NULL, + url TEXT NOT NULL, + login TEXT NOT NULL, + head_sha TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (binding_id, url, login, 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 @@ -69,6 +100,17 @@ export function createApprovalsStore(db: Database.Database, now: () => number) { 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 = ?"); + // Prepared on first use: the migration tests open stores on partial schemas + // from before this group, and `pull_requesters` is the newest table. + const lazy =

(sql: string): (() => Database.Statement) => { + let prepared: Database.Statement | null = null; + return () => (prepared ??= db.prepare(sql)); + }; + const insertPullRequester = lazy<[string, string, string, number], unknown>("INSERT OR IGNORE INTO pull_requesters (binding_id, url, login, created_at) VALUES (?, ?, ?, ?)"); + const pullRequestersFor = lazy<[string, string], Record>("SELECT login FROM pull_requesters WHERE binding_id = ? AND url = ? ORDER BY created_at, login"); + const deletePullRequester = lazy<[string, string, string], unknown>("DELETE FROM pull_requesters WHERE binding_id = ? AND url = ? AND login = ?"); + const insertReviewerRequest = lazy<[string, string, string, string, number], unknown>("INSERT OR IGNORE INTO reviewer_requests (binding_id, url, login, head_sha, created_at) VALUES (?, ?, ?, ?, ?)"); + const reviewerRequestsFor = lazy<[string, string, string], Record>("SELECT login FROM reviewer_requests WHERE binding_id = ? AND url = ? AND head_sha = ? ORDER BY created_at, login"); const toProjectApproval = (r: Record): ProjectApproval => ({ bindingId: String(r.binding_id), @@ -109,5 +151,36 @@ export function createApprovalsStore(db: Database.Database, now: () => number) { clearProjectApproval(bindingId: string, headSha: string): boolean { return deleteProjectApproval.run(bindingId, headSha).changes > 0; }, + // requested reviewers remembered for the delegate rule (BB-327) + /** + * Remember every login seen in a pull request's requested-reviewers list, + * for the binding and URL (BB-327). GitHub drops a reviewer from the live + * list once they submit, so the gate reads this set to count a delegate's + * later APPROVED review. + */ + rememberPullRequesters(bindingId: string, url: string, logins: readonly string[]): void { + const at = now(); + for (const raw of logins) { + const login = raw.trim().toLowerCase(); + if (login === "") continue; + insertPullRequester().run(bindingId, url, login, at); + } + }, + /** The logins remembered as requested reviewers for a binding and URL (BB-327). */ + pullRequesters(bindingId: string, url: string): string[] { + return pullRequestersFor().all(bindingId, url).map((r) => String(r.login)); + }, + /** Forget a remembered requester the owner removed while they had no review, ending that delegation (BB-327). */ + forgetPullRequester(bindingId: string, url: string, login: string): void { + deletePullRequester().run(bindingId, url, login.trim().toLowerCase()); + }, + /** Record that a delegate was re-requested for a head, so a repeated look does not re-request (BB-327). */ + recordReviewerRequest(bindingId: string, url: string, login: string, headSha: string): void { + insertReviewerRequest().run(bindingId, url, login.trim().toLowerCase(), headSha, now()); + }, + /** The delegates already re-requested for a binding, URL and head (BB-327). */ + reviewerRequests(bindingId: string, url: string, headSha: string): string[] { + return reviewerRequestsFor().all(bindingId, url, headSha).map((r) => String(r.login)); + }, }; } diff --git a/plugins/stewards/approvals.test.ts b/plugins/stewards/approvals.test.ts index 9be05e45..fb674745 100644 --- a/plugins/stewards/approvals.test.ts +++ b/plugins/stewards/approvals.test.ts @@ -6,8 +6,9 @@ // BB-279: an owner's page approval and the project steward's decision deliver // to a parked worker by the same path (`deliverProjectApproval`). import { describe, expect, it, vi } from "vitest"; -import { approvePrPageAction, deliverApproval, deliverProjectApproval, isUserThread, recordProjectDecision, userApprovedOnEntity, userSaid, type ApprovalsContext } from "./approvals.js"; +import { approvalRef, approvePrPageAction, deliverApproval, deliverProjectApproval, isDelegateWait, isUserThread, recordProjectDecision, syncPullApproval, userApprovedOnEntity, userSaid, type ApprovalsContext } from "./approvals.js"; import { isSelfWidening } from "./decisions.js"; +import { prGate } from "./gate.js"; import { comment, parkedWorker, pull } from "./fixtures.js"; import type { Binding, Need } from "./store.js"; @@ -26,7 +27,7 @@ const marker = (approver?: string) => function context() { const githubComment = vi.fn().mockResolvedValue("IC_1"); const recordProjectApproval = vi.fn(); - const ctx = { github: { comment: githubComment }, now: () => 0, store: { recordProjectApproval, assessment: () => null, recordAssessment: vi.fn(), projectApprovals: () => [] } } as unknown as ApprovalsContext; + const ctx = { github: { comment: githubComment }, now: () => 0, store: { recordProjectApproval, assessment: () => null, recordAssessment: vi.fn(), projectApprovals: () => [], pullRequesters: () => [], reviewerRequests: () => [] } } as unknown as ApprovalsContext; return { ctx, githubComment, recordProjectApproval }; } @@ -86,6 +87,8 @@ describe("an approval is delivered to a parked worker (BB-279)", () => { assessment: () => null, recordAssessment: vi.fn(), projectApprovals: () => [], + pullRequesters: () => [], + reviewerRequests: () => [], }, github: { comment: githubComment, review: githubReview }, now: () => 0, @@ -200,6 +203,162 @@ describe("an approval is delivered to a parked worker (BB-279)", () => { }); }); +// BB-327: a requested reviewer is the owner's delegation. The sync files no +// approve-pr need and routes no user escalation while one is outstanding; the +// delegate's APPROVED review meets the lane; a changes-requested delegate is +// re-solicited once per approved head. +const delegateLaneMarker = comment({ id: "m1", author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); +const delegateReview = (author: string, state: string, at: string, commit: string | null = head) => ({ + reviews: [{ author, state, submittedAt: at, commit }], + comments: [comment({ id: `rev-${author}-${state}`, author, did: state === "approved" ? "approved" : "requested changes", body: "", createdAt: at, signedBy: null })], +}); +const delegatePull = (reviewers: string[], extra: { comments?: ReturnType[]; reviews?: { author: string; state: string; submittedAt: string; commit: string | null }[] } = {}) => + pull({ comments: [delegateLaneMarker, ...(extra.comments ?? [])] }, { ...green, requestedReviewers: reviewers, ...(extra.reviews === undefined ? {} : { reviews: extra.reviews }) }); +const delegateUrl = "https://github.com/acme/web/pull/7"; + +/** A context whose store records what `syncPullApproval` does to it. */ +function syncContext(existing: Array> = [], remembered: string[] = []) { + const fileNeed = vi.fn(); + const escalate = vi.fn(() => ({ id: "esc_new" })); + const closeNeedByKey = vi.fn(); + const resolve = vi.fn(); + const setEscalationHead = vi.fn(); + const reroute = vi.fn(); + const setEscalationMeanwhile = vi.fn(); + const note = vi.fn(); + const rememberPullRequesters = vi.fn(); + const forgetPullRequester = vi.fn(); + const recordReviewerRequest = vi.fn(); + const requestReviewers = vi.fn().mockResolvedValue(undefined); + const store = { + rememberPullRequesters, + closeNeedByKey, + openNeeds: () => [], + fileNeed, + openEscalations: () => existing as never[], + escalate, + resolve, + setEscalationHead, + reroute, + setEscalationMeanwhile, + note, + forgetPullRequester, + recordReviewerRequest, + assessment: () => null, + recordAssessment: vi.fn(), + projectApprovals: () => [], + pullRequesters: () => remembered, + reviewerRequests: () => [], + }; + const ctx = { + store, + github: { comment: vi.fn(), review: vi.fn(), requestReviewers }, + now: () => 0, + shortSha: (sha: string | null | undefined) => (sha ?? "").slice(0, 7), + scheduleReconcile: vi.fn(), + snapshot: vi.fn().mockResolvedValue(null), + linkedPulls: vi.fn().mockResolvedValue([]), + threadInfo: vi.fn().mockResolvedValue(null), + sendTo: vi.fn(), + wakeProject: vi.fn(), + pullChangedFiles: vi.fn().mockResolvedValue([]), + loadDecisions: vi.fn().mockResolvedValue([]), + observedPulls: vi.fn().mockReturnValue([]), + mechanicalStatus: vi.fn(), + } as unknown as ApprovalsContext; + const b = { id: "b1", projectId: "p1", entityKey: "acme/web#7", source: "ops", kind: "pr", entityId: "acme/web#7", url: delegateUrl, lastSnapshot: null } as unknown as Binding; + return { ctx, b, fileNeed, escalate, closeNeedByKey, resolve, setEscalationHead, reroute, setEscalationMeanwhile, note, rememberPullRequesters, forgetPullRequester, recordReviewerRequest, requestReviewers }; +} + +describe("a requested reviewer is the owner's delegation (BB-327)", () => { + it("files no approve-pr need and routes no user escalation while one is outstanding (criterion 2)", async () => { + const { ctx, b, fileNeed, escalate, closeNeedByKey, rememberPullRequesters } = syncContext(); + const entity = delegatePull(["arashout"]); + const result = await syncPullApproval(ctx, b, entity, [], () => prGate(entity)); + expect(result.gate.delegatePending).toBe(true); + // The request list is remembered for the delegate set. + expect(rememberPullRequesters).toHaveBeenCalledWith("b1", delegateUrl, ["arashout"]); + // No page item, and the escalation waits on the delegate, not the user. + expect(fileNeed).not.toHaveBeenCalled(); + expect(escalate).toHaveBeenCalledTimes(1); + const fields = (escalate.mock.calls as unknown as Array<[{ route: string; meanwhile: string }]>)[0]![0]; + expect(fields.route).toBe("steward"); + expect(fields.meanwhile).toContain("arashout"); + expect(closeNeedByKey).toHaveBeenCalledWith("b1", "approve-pr", delegateUrl, expect.stringContaining("arashout")); + }); + + it("reroutes an existing owner escalation to the steward and names the delegate (criterion 2)", async () => { + const esc = { id: "esc1", kind: "approval", url: delegateUrl, resolutionKind: "approve-decline", route: "user", headSha: head, recommendation: null }; + const { ctx, b, fileNeed, escalate, reroute, setEscalationMeanwhile } = syncContext([esc]); + const entity = delegatePull(["arashout"]); + await syncPullApproval(ctx, b, entity, [], () => prGate(entity)); + expect(fileNeed).not.toHaveBeenCalled(); + expect(escalate).not.toHaveBeenCalled(); + expect(reroute).toHaveBeenCalledWith("esc1", "steward", null); + expect(setEscalationMeanwhile).toHaveBeenCalledWith("esc1", expect.stringContaining("arashout")); + }); + + it("forgets a requester the owner withdrew while they had no review (criterion 8)", async () => { + const { ctx, b, forgetPullRequester } = syncContext([], ["arashout"]); + // The request list no longer names arashout and they never reviewed. + const entity = delegatePull([]); + await syncPullApproval(ctx, b, entity, [], () => prGate(entity)); + expect(forgetPullRequester).toHaveBeenCalledWith("b1", delegateUrl, "arashout"); + }); + + it("does not forget a requester who has reviewed (criterion 8)", async () => { + const { ctx, b, forgetPullRequester } = syncContext([], ["arashout"]); + const review = delegateReview("arashout", "approved", "2026-10-14T17:00:00Z"); + const entity = delegatePull([], review); + await syncPullApproval(ctx, b, entity, [], () => prGate(entity)); + expect(forgetPullRequester).not.toHaveBeenCalled(); + }); + + it("marks the delegate wait as the plugin's, not the steward's (criterion 2)", () => { + expect(isDelegateWait({ kind: "approval", route: "steward" })).toBe(true); + expect(isDelegateWait({ kind: "approval", route: "user" })).toBe(false); + expect(isDelegateWait({ kind: "approval", route: "project" })).toBe(false); + expect(isDelegateWait({ kind: "stuck", route: "steward" })).toBe(false); + }); + + it("moves a withdrawn delegation's escalation back to the owner text (round 2 suggestion)", async () => { + const esc = { id: "esc1", kind: "approval", url: delegateUrl, resolutionKind: "approve-decline", route: "steward", headSha: head, recommendation: null }; + const { ctx, b, reroute, setEscalationMeanwhile, escalate, fileNeed } = syncContext([esc], ["arashout"]); + const entity = delegatePull([]); + await syncPullApproval(ctx, b, entity, [], () => prGate(entity)); + expect(escalate).not.toHaveBeenCalled(); + expect(reroute).toHaveBeenCalledWith("esc1", "user", null); + expect(setEscalationMeanwhile).toHaveBeenCalledWith("esc1", "Waiting: the owner approves on GitHub from the Stewards page."); + expect(fileNeed).toHaveBeenCalled(); + }); + + it("names the delegate's review in approvalRef (criterion 3)", () => { + const review = delegateReview("arashout", "approved", "2026-10-14T17:00:00Z"); + const entity = delegatePull(["arashout"], review); + const g = prGate(entity); + expect(g.gateMet).toBe(true); + expect(approvalRef(g)).toBe("review rev-arashout-approved"); + }); + + it("re-requests a changes-requested delegate once per approved head (criterion 7)", async () => { + const { ctx, b, requestReviewers, recordReviewerRequest } = syncContext(); + const review = delegateReview("arashout", "changes requested", "2026-10-14T17:00:00Z", "bbbbbbb2"); + const entity = delegatePull(["arashout"], review); + await syncPullApproval(ctx, b, entity, [], () => prGate(entity)); + expect(requestReviewers).toHaveBeenCalledTimes(1); + expect(requestReviewers).toHaveBeenCalledWith("acme/web", 7, ["arashout"]); + expect(recordReviewerRequest).toHaveBeenCalledWith("b1", delegateUrl, "arashout", head); + }); + + it("does not re-request a delegate already re-requested for the head (criterion 7)", async () => { + const { ctx, b, requestReviewers } = syncContext(); + const review = delegateReview("arashout", "changes requested", "2026-10-14T17:00:00Z", "bbbbbbb2"); + const entity = delegatePull(["arashout"], review); + await syncPullApproval(ctx, b, entity, [], () => prGate(entity, { reRequestedDelegates: ["arashout"] })); + expect(requestReviewers).not.toHaveBeenCalled(); + }); +}); + // BB-280: the approve/decline recording path lives in this module, so a change // to it must always be the user's, whatever the decide list matched. describe("the approval-recording files are self-widening (BB-280)", () => { diff --git a/plugins/stewards/approvals.ts b/plugins/stewards/approvals.ts index dce76022..97513c74 100644 --- a/plugins/stewards/approvals.ts +++ b/plugins/stewards/approvals.ts @@ -339,6 +339,13 @@ export async function fileForwardedApprovePrNeed(ctx: ApprovalsContext, b: Bindi }); } +/** + * Whether an open approval escalation is the plugin's delegate wait (BB-327): + * routed to the binding's steward and closed only by the delegate's review or + * a withdrawn request, never decided by the steward itself. + */ +export const isDelegateWait = (x: { kind: string; route: string }): boolean => x.kind === "approval" && x.route === "steward"; + /** A reviewer marker's identity: a new round on the same head is a new marker (BB-51). */ export const markerKey = (m: { round: number; sha: string } | null): string | null => (m === null ? null : `${m.round}:${m.sha}`); @@ -349,10 +356,12 @@ export const markerKey = (m: { round: number; sha: string } | null): string | nu * what closed it (BB-151). */ export function approvalRef(g: PrGate): string { - const id = g.projectApproved ? g.projectApprovalId : g.ownerApprovalId; + // A delegate's approval is a real GitHub review, so it names the review's id + // and URL (BB-327). + const id = g.projectApproved ? g.projectApprovalId : g.delegateApproved ? g.delegateApprovalId : g.ownerApprovalId; if (id === null) return ""; - const url = g.projectApproved ? g.projectApprovalUrl : g.ownerApprovalUrl; - const kind = g.projectApproved ? "comment" : (g.ownerApprovalKind ?? "comment"); + const url = g.projectApproved ? g.projectApprovalUrl : g.delegateApproved ? g.delegateApprovalUrl : g.ownerApprovalUrl; + const kind = g.projectApproved ? "comment" : g.delegateApproved ? "review" : (g.ownerApprovalKind ?? "comment"); return url === null ? `${kind} ${id}` : `${kind} ${id}, ${url}`; } @@ -368,6 +377,14 @@ export type PullApprovalResult = { gate: PrGate; closed: boolean; approvalRaised */ export async function syncPullApproval(ctx: ApprovalsContext, b: Binding, pull: EntitySnapshot, decisions: readonly BigDecision[], gateFor?: (pull: EntitySnapshot) => PrGate | null): Promise { const url = pull.url ?? pull.key; + // BB-327: remember every login seen in the request list, so a delegate's + // APPROVED review still counts after GitHub drops them from the live list. + ctx.store.rememberPullRequesters(b.id, url, pull.pull?.requestedReviewers ?? []); + // The owner ends a delegation by removing a requested reviewer who never + // reviewed; a delegate who submitted a review stays a delegate (BB-327). + const live = new Set((pull.pull?.requestedReviewers ?? []).map((l) => l.toLowerCase())); + const reviewed = new Set((pull.pull?.reviews ?? []).map((r) => r.author.toLowerCase())); + for (const login of ctx.store.pullRequesters(b.id, url)) if (!live.has(login) && !reviewed.has(login)) ctx.store.forgetPullRequester(b.id, url, login); // BB-322: the gate comes from the stored assessment (the reconcile passes // its in-memory copy through `gateFor`; otherwise the single `assessedGate` // site reads or refreshes it). The decide-list placement is already in it, @@ -390,6 +407,22 @@ export async function syncPullApproval(ctx: ApprovalsContext, b: Binding, pull: if (approvalEsc !== null) ctx.store.resolve(approvalEsc.id, "The pull request is closed."); return { gate: g, closed: true, approvalRaised: false }; } + // BB-327: a delegate who asked for changes is re-solicited once the + // independent reviewer approves the new head. The (delegate, head) record + // makes it once per head; the gate offers it only with an approved marker + // at this head and green checks, so an unreviewed push is never paged. + if (g.delegatesToReRequest.length > 0) { + const ref = parsePullRef(url); + if (ref !== null) { + try { + await ctx.github.requestReviewers(ref.repo, ref.number, g.delegatesToReRequest); + for (const login of g.delegatesToReRequest) ctx.store.recordReviewerRequest(b.id, url, login, g.headSha ?? ""); + ctx.store.note(b.id, `Re-requested review from ${g.delegatesToReRequest.join(", ")} on ${pull.key} for the approved head ${ctx.shortSha(g.headSha)}.`, true); + } catch (error) { + ctx.store.note(b.id, `Could not re-request review from ${g.delegatesToReRequest.join(", ")} on ${pull.key}: ${errorMessage(error)}`, false); + } + } + } if (g.needsOwnerApproval) { // The user's lane: the page item is filed as soon as the reviewer's // marker is approved and checks are green, with no project-steward @@ -405,9 +438,31 @@ export async function syncPullApproval(ctx: ApprovalsContext, b: Binding, pull: fileApprovePrNeed(ctx, b, pull, x.id, g.headSha, listing, g.reason); } else { if (approvalEsc.headSha !== g.headSha) ctx.store.setEscalationHead(approvalEsc.id, g.headSha); - if (approvalEsc.route !== "user") ctx.store.reroute(approvalEsc.id, "user", approvalEsc.recommendation); + if (approvalEsc.route !== "user") { + ctx.store.reroute(approvalEsc.id, "user", approvalEsc.recommendation); + // A delegation that ended moves the wait back to the owner: drop the + // delegate's `meanwhile` so the escalation does not keep naming them + // (BB-327). + ctx.store.setEscalationMeanwhile(approvalEsc.id, "Waiting: the owner approves on GitHub from the Stewards page."); + } fileApprovePrNeed(ctx, b, pull, approvalEsc.id, g.headSha, listing, g.reason); } + } else if (g.delegatePending) { + // BB-327: the owner delegated the review by requesting one. No page item + // is filed and the owner is not asked; one escalation stays open, routed + // to the binding's steward, whose `meanwhile` names the delegate. It + // resolves when the delegate's APPROVED review lands, or the request is + // withdrawn and the ordinary owner lane returns. + const names = g.delegates.join(", "); + ctx.store.closeNeedByKey(b.id, "approve-pr", url, `Waiting on the requested reviewer ${names}.`); + const meanwhile = `Waiting: approval from ${names} (a requested reviewer), not the owner.`; + if (approvalEsc === null) { + ctx.store.escalate({ bindingId: b.id, kind: "approval", question: `Approve ${pull.key}`, meanwhile, route: "steward", recommendation: null, resolutionKind: "approve-decline", url, headSha: g.headSha, projectId: b.projectId }); + } else { + if (approvalEsc.headSha !== g.headSha) ctx.store.setEscalationHead(approvalEsc.id, g.headSha); + if (approvalEsc.route !== "steward") ctx.store.reroute(approvalEsc.id, "steward", approvalEsc.recommendation); + ctx.store.setEscalationMeanwhile(approvalEsc.id, meanwhile); + } } else if (g.needsProjectApproval) { // The project steward's lane: one escalation, no page item. ctx.store.closeNeedByKey(b.id, "approve-pr", url, "Owner review is the project steward's to decide."); @@ -440,13 +495,14 @@ export async function syncPullApproval(ctx: ApprovalsContext, b: Binding, pull: const why = g.missing ?? "Rebase the head onto the default branch."; ctx.store.closeNeedByKey(b.id, "approve-pr", url, why); ctx.store.resolve(approvalEsc.id, why); - } else if (g.ownerApproved || g.projectApproved) { + } else if (g.ownerApproved || g.projectApproved || g.delegateApproved) { // The resolution names what approved, so a closed item can always // be traced to the comment or review that closed it (BB-151). const ref = approvalRef(g); const suffix = ref === "" ? "" : ` (${ref})`; + const who = g.projectApproved ? "the project steward" : g.delegateApproved ? `the requested reviewer ${g.delegateApprovalBy ?? ""}`.trimEnd() : "the owner"; ctx.store.closeNeedByKey(b.id, "approve-pr", url, `Approval is present${suffix}.`); - ctx.store.resolve(approvalEsc.id, `Approved by ${g.projectApproved ? "the project steward" : "the owner"}${suffix}.`); + ctx.store.resolve(approvalEsc.id, `Approved by ${who}${suffix}.`); } else { // The marker is no longer approved (or gone): withdraw the request // with the gate's words, never "Approved.". diff --git a/plugins/stewards/assessed-gate.ts b/plugins/stewards/assessed-gate.ts index 494893ad..a4172251 100644 --- a/plugins/stewards/assessed-gate.ts +++ b/plugins/stewards/assessed-gate.ts @@ -18,9 +18,9 @@ export function pullGate(entity: EntitySnapshot, options: PrGateOptions = {}): P return prGate(entity, options); } -/** The gate options for one own pull request: the decide-list mark and the product inputs. */ -function gateOptions(binding: Pick, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[]): PrGateOptions { - return { decision: mark, projectApprovals, ...productGateOptions(binding, entity) }; +/** The gate options for one own pull request: the decide-list mark, the product inputs and the delegate records (BB-327). */ +function gateOptions(binding: Pick, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[], rememberedRequesters: readonly string[] = [], reRequestedDelegates: readonly string[] = []): PrGateOptions { + return { decision: mark, projectApprovals, rememberedRequesters, reRequestedDelegates, ...productGateOptions(binding, entity) }; } /** @@ -29,8 +29,8 @@ function gateOptions(binding: Pick, entity: EntitySna * reviewer marker, an approval, a check result or the base state that changed * at the same head sha is never read as the old answer (BB-210). */ -export function gateInputKey(binding: Pick, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[]): string { - return createHash("sha1").update(JSON.stringify({ entity, options: gateOptions(binding, entity, mark, projectApprovals) })).digest("hex"); +export function gateInputKey(binding: Pick, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[], rememberedRequesters: readonly string[] = [], reRequestedDelegates: readonly string[] = []): string { + return createHash("sha1").update(JSON.stringify({ entity, options: gateOptions(binding, entity, mark, projectApprovals, rememberedRequesters, reRequestedDelegates) })).digest("hex"); } /** @@ -44,8 +44,8 @@ export function gateInputKey(binding: Pick, entity: E * fact that remains. A recorded project-steward approval keeps the pull * request the project steward's. */ -export function assessedPullGate(binding: Pick, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[]): PrGate { - const options = gateOptions(binding, entity, mark, projectApprovals); +export function assessedPullGate(binding: Pick, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[], rememberedRequesters: readonly string[] = [], reRequestedDelegates: readonly string[] = []): PrGate { + const options = gateOptions(binding, entity, mark, projectApprovals, rememberedRequesters, reRequestedDelegates); const probe = pullGate(entity, options); return mark === "project" && probe.ownerApproved && !probe.projectApproved ? pullGate(entity, { ...options, decision: "user" }) : probe; } @@ -67,6 +67,10 @@ export type AssessmentStore = { assessment(bindingId: string): { gate: unknown; worker: unknown; liveness: unknown } | null; recordAssessment(fields: { bindingId: string; at: number; gate: unknown; worker: unknown; liveness: unknown }): void; projectApprovals(bindingId: string): readonly ProjectApprovalRecord[]; + /** The logins remembered as requested reviewers for a binding and URL (BB-327). */ + pullRequesters(bindingId: string, url: string): readonly string[]; + /** The delegates already re-requested for a binding, URL and head (BB-327). */ + reviewerRequests(bindingId: string, url: string, headSha: string): readonly string[]; }; const lc = (s: string | null | undefined): string => (s ?? "").toLowerCase(); @@ -121,13 +125,17 @@ export function assessedGate(store: AssessmentStore, binding: Binding, pull: Ent const sameHead = known !== null && known.headSha === (pull.pull?.headSha ?? null); const mark: DecideMark = forceMark ?? (sameHead ? known!.decision : decideForPull(pull.pull?.files ?? null, bigDecisions)); const projectApprovals = store.projectApprovals(binding.id); - const key = gateInputKey(binding, pull, mark, projectApprovals); + // BB-327: the logins the store remembers as requested reviewers, so a + // delegate's APPROVED review still counts after GitHub drops them. + const rememberedRequesters = store.pullRequesters(binding.id, pull.url ?? pull.key); + const reRequestedDelegates = store.reviewerRequests(binding.id, pull.url ?? pull.key, pull.pull?.headSha ?? ""); + const key = gateInputKey(binding, pull, mark, projectApprovals, rememberedRequesters, reRequestedDelegates); // Reuse the stored answer only when it is for this pull request's current // head sha and every gate input is unchanged; otherwise recompute through // the single site and store it (fail closed: a missing or stale assessment // never counts as met). if (known !== null && known.headSha === (pull.pull?.headSha ?? null) && known.key === key) return known; - const gate = assessedPullGate(binding, pull, mark, projectApprovals); + const gate = assessedPullGate(binding, pull, mark, projectApprovals, rememberedRequesters, reRequestedDelegates); const entry: StoredGate = { ...gate, pull: pull.key, met: gate.gateMet, key }; const stored = (row?.gate as StoredAssessmentGate | null | undefined) ?? {}; const pulls = Array.isArray(stored.pulls) ? [...stored.pulls] : []; diff --git a/plugins/stewards/assessment.ts b/plugins/stewards/assessment.ts index b4381f1d..cfca9838 100644 --- a/plugins/stewards/assessment.ts +++ b/plugins/stewards/assessment.ts @@ -107,6 +107,20 @@ export type AssessmentInput = { decisions: ReadonlyMap; /** The plugin's recorded project approvals for the binding. */ projectApprovals: readonly ProjectApprovalRecord[]; + /** + * The logins the store remembers as requested reviewers, keyed by a pull + * request's lowercased key and URL (BB-327). Read by the gate so a + * delegate's APPROVED review still counts after GitHub drops the reviewer + * from the live list; omitted reads as none, which leaves the live list in + * charge. + */ + rememberedRequesters?: ReadonlyMap; + /** + * The delegates already re-requested for a pull request's current head, + * keyed by its lowercased key and URL (BB-327). The gate reads it so a + * repeated look does not re-request and the status can say it was done. + */ + reRequestedDelegates?: ReadonlyMap; workers: readonly Worker[]; escalations: readonly Escalation[]; needs: readonly Need[]; @@ -120,6 +134,12 @@ export type AssessmentInput = { const lc = (s: string | null | undefined): string => (s ?? "").toLowerCase(); +/** The remembered requesters for one pull request, by its lowercased key or URL (BB-327). */ +function rememberedFor(map: ReadonlyMap | undefined, e: EntitySnapshot): readonly string[] { + if (map === undefined) return []; + return map.get(lc(e.key)) ?? (e.url === null ? [] : map.get(lc(e.url)) ?? []); +} + /** Whether an observed entity is one of the binding's own pull requests (BB-52 rule 0). */ const isOwn = (e: EntitySnapshot, own: ReadonlySet): boolean => (e.key !== "" && own.has(lc(e.key))) || (e.url !== null && e.url !== "" && own.has(lc(e.url))); @@ -164,8 +184,10 @@ export function assess(input: AssessmentInput): Assessment { // owner's approval and the reconcile reroutes the escalation back. const decideMark = decisions.get(lc(e.key)) ?? "user"; const mark: DecideMark = decideMark === "project" && forwardedToOwner(escalations, e) ? "user" : decideMark; - const g = assessedPullGate(binding, e, mark, projectApprovals); - pulls.push({ ...g, pull: e.key, met: g.gateMet, key: gateInputKey(binding, e, g.decision, projectApprovals) }); + const remembered = rememberedFor(input.rememberedRequesters, e); + const reRequested = rememberedFor(input.reRequestedDelegates, e); + const g = assessedPullGate(binding, e, mark, projectApprovals, remembered, reRequested); + pulls.push({ ...g, pull: e.key, met: g.gateMet, key: gateInputKey(binding, e, g.decision, projectApprovals, remembered, reRequested) }); } const idleBinding: IdleBinding = { stage: binding.stage, diff --git a/plugins/stewards/gate.test.ts b/plugins/stewards/gate.test.ts index c9ce5f7e..6d08da7a 100644 --- a/plugins/stewards/gate.test.ts +++ b/plugins/stewards/gate.test.ts @@ -88,3 +88,128 @@ describe("the merge gate's base-ref retarget rule (BB-279)", () => { expect(prGate(entity, { decision: "project", projectApprovals }).gateMet).toBe(true); }); }); + +// BB-327: a requested reviewer on an owner-lane pull request is the owner's +// delegation. While they are outstanding the owner is not asked; their +// APPROVED review meets the lane; the viewer's own approval stays an override; +// a changes-requested delegate is re-solicited once per approved head. +const ownerLaneMarker = (verdict = "approved", sha = head) => + comment({ id: "m1", author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); +const pageApproval = comment({ id: "o1", author: "jane", did: "commented", body: `Approved ${head} from the Stewards page`, signedBy: null, createdAt: "2026-10-14T16:30:00Z" }); +/** A delegate's review, as both the flattened comment and the `pull.reviews` entry the gate reads. */ +const delegateReview = (author: string, state: string, at: string, commit: string | null = head) => ({ + reviews: [{ author, state, submittedAt: at, commit }], + comments: [comment({ id: `rev-${author}-${state}`, author, did: state === "approved" ? "approved" : "requested changes", body: "", createdAt: at, signedBy: null })], +}); + +const delegatePull = (reviewers: string[], extra: { comments?: ReturnType[]; reviews?: { author: string; state: string; submittedAt: string; commit: string | null }[] } = {}) => + pull({ comments: [ownerLaneMarker(), ...(extra.comments ?? [])] }, { ...green, requestedReviewers: reviewers, ...(extra.reviews === undefined ? {} : { reviews: extra.reviews }) }); + +describe("a requested reviewer is the owner's delegation (BB-327)", () => { + it("does not ask the owner while a requested reviewer is outstanding, and names them (criterion 1)", () => { + const g = prGate(delegatePull(["arashout"])); + expect(g.gateMet).toBe(false); + expect(g.needsOwnerApproval).toBe(false); + expect(g.delegatePending).toBe(true); + expect(g.delegates).toEqual(["arashout"]); + expect(g.missing).toBe("approval needed from arashout"); + }); + + it("meets the owner lane on the delegate's APPROVED review (criterion 3)", () => { + const review = delegateReview("arashout", "approved", "2026-10-14T17:00:00Z"); + const g = prGate(delegatePull(["arashout"], review)); + expect(g.gateMet).toBe(true); + expect(g.delegateApproved).toBe(true); + expect(g.delegateApprovalBy).toBe("arashout"); + expect(g.delegateApprovalId).toBe("rev-arashout-approved"); + expect(g.needsOwnerApproval).toBe(false); + }); + + it("still accepts the viewer's own unsigned approval as an override (criterion 4)", () => { + const g = prGate(delegatePull(["arashout"], { comments: [pageApproval] })); + expect(g.gateMet).toBe(true); + expect(g.ownerApproved).toBe(true); + expect(g.needsOwnerApproval).toBe(false); + }); + + it("revokes a delegate's approval on their later changes-requested, and keeps not asking (criterion 5)", () => { + const approved = delegateReview("arashout", "approved", "2026-10-14T17:00:00Z"); + const changed = delegateReview("arashout", "changes requested", "2026-10-14T18:00:00Z", "bbbbbbb2"); + const g = prGate(delegatePull(["arashout"], { comments: [...approved.comments, ...changed.comments], reviews: [...approved.reviews, ...changed.reviews] })); + expect(g.gateMet).toBe(false); + expect(g.needsOwnerApproval).toBe(false); + expect(g.delegates).toEqual(["arashout"]); + // The delegate stays in the delegate set even after GitHub drops them from + // the live list, because they have submitted a review. + const remembered = prGate(delegatePull([], { comments: [...approved.comments, ...changed.comments], reviews: [...approved.reviews, ...changed.reviews] }), { rememberedRequesters: ["arashout"] }); + expect(remembered.needsOwnerApproval).toBe(false); + }); + + it("keeps a delegate's approval across a later COMMENTED review (criterion 3)", () => { + const approved = delegateReview("arashout", "approved", "2026-10-14T17:00:00Z"); + const commented = { + reviews: [{ author: "arashout", state: "commented", submittedAt: "2026-10-14T17:30:00Z", commit: head }], + comments: [comment({ id: "rev-arashout-commented", author: "arashout", did: "reviewed", body: "answered", createdAt: "2026-10-14T17:30:00Z", signedBy: null })], + }; + const g = prGate(delegatePull(["arashout"], { comments: [...approved.comments, ...commented.comments], reviews: [...approved.reviews, ...commented.reviews] })); + expect(g.gateMet).toBe(true); + expect(g.delegateApproved).toBe(true); + }); + + it("does not merge one delegate's approval over another's changes requested (criterion 5)", () => { + const approved = delegateReview("arashout", "approved", "2026-10-14T17:00:00Z"); + const changed = delegateReview("bob", "changes requested", "2026-10-14T17:30:00Z", "bbbbbbb2"); + const g = prGate(delegatePull(["arashout", "bob"], { comments: [...approved.comments, ...changed.comments], reviews: [...approved.reviews, ...changed.reviews] })); + expect(g.gateMet).toBe(false); + expect(g.needsOwnerApproval).toBe(false); + expect(g.delegates).toEqual(["bob"]); + }); + + it("finds a delegate's approval after GitHub dropped them from the live list (criterion 6)", () => { + const review = delegateReview("arashout", "approved", "2026-10-14T17:00:00Z"); + const entity = delegatePull([], review); + // The live list is empty, so only the remembered set can find the approval. + expect(prGate(entity).gateMet).toBe(false); + expect(prGate(entity, { rememberedRequesters: ["arashout"] }).gateMet).toBe(true); + }); + + it("offers a changes-requested delegate for one re-request per approved head (criterion 7)", () => { + // The delegate reviewed an earlier head; the current head is new. + const changed = delegateReview("arashout", "changes requested", "2026-10-14T17:00:00Z", "bbbbbbb2"); + const entity = delegatePull(["arashout"], changed); + expect(prGate(entity).delegatesToReRequest).toEqual(["arashout"]); + // A repeated look with the record does not re-request. + expect(prGate(entity, { reRequestedDelegates: ["arashout"] }).delegatesToReRequest).toEqual([]); + // A further push without a new approved marker at that head causes none. + const moved = pull({ comments: [ownerLaneMarker()] }, { ...green, requestedReviewers: ["arashout"], reviews: changed.reviews, headSha: "ccccccc3" }); + expect(prGate(moved).delegatesToReRequest).toEqual([]); + // A head the independent reviewer has not approved causes none. + const unapproved = pull({ comments: [ownerLaneMarker("changes-requested")] }, { ...green, requestedReviewers: ["arashout"], reviews: changed.reviews }); + expect(prGate(unapproved).delegatesToReRequest).toEqual([]); + }); + + it("names the re-request in the missing reason for the current head (criterion 10)", () => { + const changed = delegateReview("arashout", "changes requested", "2026-10-14T17:00:00Z", "bbbbbbb2"); + expect(prGate(delegatePull(["arashout"], changed), { reRequestedDelegates: ["arashout"] }).missing).toContain("re-requested for this head"); + }); + + it("does not treat bots, teams or the viewer as delegates (criterion 8)", () => { + // A team is `org/slug` as the source now emits it; a bot or the viewer is + // never a delegate either. + for (const reviewers of [["dependabot[bot]"], ["bitcomplete/backend"], ["Platform Team"], ["jane"]]) { + const g = prGate(delegatePull(reviewers)); + expect(g.delegates).toEqual([]); + expect(g.needsOwnerApproval).toBe(true); + expect(g.missing).toContain("owner approval needed"); + } + }); + + it("behaves exactly as today with no review requests (criterion 9)", () => { + const g = prGate(delegatePull([])); + expect(g.delegates).toEqual([]); + expect(g.delegatePending).toBe(false); + expect(g.delegateApproved).toBe(false); + expect(g.needsOwnerApproval).toBe(true); + expect(g.missing).toContain("owner approval needed"); + }); +}); diff --git a/plugins/stewards/gate.ts b/plugins/stewards/gate.ts index 03e2fe0d..875dba03 100644 --- a/plugins/stewards/gate.ts +++ b/plugins/stewards/gate.ts @@ -225,6 +225,110 @@ export function ownerApproval(entity: EntitySnapshot): OwnerApproval { return { approved: true, at: bestAt, id: bestId, url: bestUrl, kind: bestKind }; } +// ---- delegate approvals (BB-327) ------------------------------------------------------ + +/** + * A GitHub App or bot login, which is never a delegate. GitHub Apps' logins + * end in `[bot]`; a few bare names are also bots (the dependency watch's own + * matcher, BB-164). + */ +const BOT_LOGIN = /\[bot\]$/iu; +const KNOWN_BOTS = new Set(["dependabot", "renovate", "github-actions", "copilot"]); + +/** Whether a requested-reviewer entry is a bot account rather than a person. */ +export function isBotLogin(login: string): boolean { + const l = login.trim().toLowerCase(); + return l !== "" && (BOT_LOGIN.test(l) || KNOWN_BOTS.has(l)); +} + +/** + * Whether a requested-reviewer entry can be a GitHub user login rather than a + * team's display name. GitHub logins are letters, digits and single hyphens; a + * team's display name may contain spaces or other characters. A team name that + * happens to look like a login is indistinguishable in the snapshot, and a + * membership lookup is out of scope (BB-327): such a name is never an approval + * because a team cannot submit a review, and the outstanding-delegate state + * only names entries this test accepts. + */ +const USER_LOGIN = /^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/iu; +export function isUserLogin(login: string): boolean { + return USER_LOGIN.test(login.trim()); +} + +/** The delegate login a requested-reviewer entry names, or null when it is the viewer, a bot or a team. */ +function delegateLogin(entry: string, viewer: string | null): string | null { + const login = entry.trim(); + if (login === "" || (viewer !== null && login.toLowerCase() === viewer)) return null; + if (isBotLogin(login) || !isUserLogin(login)) return null; + return login; +} + +/** + * The delegates a pull request carries (BB-327): the requested reviewers that + * are users other than the viewer. `outstanding` are those still to approve, + * in the order seen; `approval` is the newest delegate APPROVED review, if + * any. A delegate's later "changes requested" revokes their approval, so each + * login is read by its latest review state. The remembered set is read too, so + * an APPROVED review still counts after GitHub drops the reviewer from the + * live list; a remembered login with no review was removed from the request + * list, so that delegation ended and it is not outstanding. + */ +export type DelegateState = { + outstanding: string[]; + approval: { by: string; at: string; id: string | null; url: string | null } | null; + /** + * Delegates whose latest review is "changes requested", with the commit + * they reviewed. The re-solicit rule fires only when a later head is + * approved, so the commit is what tells a new head from the reviewed one + * (BB-327). + */ + changesRequested: Array<{ login: string; commit: string | null }>; +}; + +export function delegateState(entity: EntitySnapshot, remembered: readonly string[] = []): DelegateState { + const viewer = entity.viewer === null ? null : entity.viewer.toLowerCase(); + const candidates = new Map(); + for (const entry of entity.pull?.requestedReviewers ?? []) { + const login = delegateLogin(entry, viewer); + if (login !== null) candidates.set(login.toLowerCase(), { login, live: true }); + } + for (const entry of remembered) { + const login = delegateLogin(entry, viewer); + if (login === null) continue; + const lower = login.toLowerCase(); + if (!candidates.has(lower)) candidates.set(lower, { login, live: false }); + } + // A COMMENTED review is GitHub's reply-thread review, not an opinion; a + // delegate who approves and then answers an inline comment keeps the + // approval, as GitHub's own `latestOpinionatedReviews` does (BB-327). + const latest = new Map(); + for (const r of entity.pull?.reviews ?? []) { + const lower = r.author.toLowerCase(); + if (!candidates.has(lower)) continue; + const state = r.state.toLowerCase(); + if (state === "commented") continue; + const at = r.submittedAt ?? ""; + const prev = latest.get(lower); + if (prev === undefined || at >= prev.at) latest.set(lower, { state, at, commit: r.commit }); + } + let approval: DelegateState["approval"] = null; + const outstanding: string[] = []; + const changesRequested: Array<{ login: string; commit: string | null }> = []; + for (const [lower, c] of candidates) { + const review = latest.get(lower) ?? null; + if (review !== null && review.state === "approved") { + if (approval === null || review.at > approval.at) { + const flat = entity.comments.find((x) => x.author.toLowerCase() === lower && x.createdAt === review.at && x.did.toLowerCase() === "approved"); + approval = { by: c.login, at: review.at, id: flat?.id ?? null, url: flat?.url ?? null }; + } + continue; + } + if (c.live || review !== null) outstanding.push(c.login); + if (review !== null && review.state === "changes requested") changesRequested.push({ login: c.login, commit: review.commit }); + } + return { outstanding, approval, changesRequested }; +} + // ---- the project steward's approval marker -------------------------------------------- /** @@ -336,6 +440,23 @@ export type PrGate = { ownerApprovalId: string | null; ownerApprovalUrl: string | null; ownerApprovalKind: "comment" | "review" | null; + /** The requested reviewers still to approve: the owner delegated the review to them (BB-327). */ + delegates: string[]; + /** Whether the owner lane is waiting on a requested reviewer rather than the owner (BB-327). */ + delegatePending: boolean; + /** Whether a requested reviewer's APPROVED review satisfies the owner lane (BB-327). */ + delegateApproved: boolean; + /** The delegate whose review approved, and its review, for the resolution text. */ + delegateApprovalBy: string | null; + delegateApprovalAt: string | null; + delegateApprovalId: string | null; + delegateApprovalUrl: string | null; + /** Delegates whose latest review is "changes requested" (BB-327). */ + delegateChangesRequested: string[]; + /** Delegates already re-requested for the current head (BB-327). */ + delegateReRequested: string[]; + /** Delegates to re-solicit now: changes-requested, an approved marker at this head, green checks, not yet re-requested (BB-327). */ + delegatesToReRequest: string[]; /** The project-steward marker that approved, when that is the gate. */ projectApprovalId: string | null; projectApprovalUrl: string | null; @@ -412,6 +533,19 @@ export type PrGateOptions = { * fails closed only when the base changed after the approval. */ headMergeBaseIsDefaultTip?: boolean | null; + /** + * Every login the store has seen in this pull request's requested-reviewers + * list (BB-327). GitHub drops a reviewer from the live list once they + * submit, so a delegate's later APPROVED review is counted against this + * remembered set as well as the live one. + */ + rememberedRequesters?: readonly string[]; + /** + * The delegates the plugin has already re-requested for the current head + * (BB-327). A delegate whose latest review is changes-requested is + * re-solicited once per head, once the reviewer marker approves it. + */ + reRequestedDelegates?: readonly string[]; }; export function prGate(entity: EntitySnapshot, opts: PrGateOptions = {}): PrGate { @@ -422,6 +556,11 @@ export function prGate(entity: EntitySnapshot, opts: PrGateOptions = {}): PrGate const checksState = pull?.checks?.state ?? null; const checksGreen = pull !== null && (pull.checks === null || pull.checks.state === "success"); const owner = ownerApproval(entity); + // BB-327: a requested reviewer is the owner's delegation. `delegates` are + // those still to approve; a delegate's APPROVED review meets the owner lane + // the same way the owner's own approval does. Identity stays the viewer's: + // only the viewer's comments and reviews are read for a signature. + const delegate = delegateState(entity, opts.rememberedRequesters ?? []); const markerApproved = marker !== null && marker.verdict === "approved"; // BB-207: a substantial pull request with no approved spec on a referenced // ticket is the owner's, whatever lane the reviewer assigned, and a @@ -468,17 +607,38 @@ export function prGate(entity: EntitySnapshot, opts: PrGateOptions = {}): PrGate // based on the default branch throughout that is merely behind keeps its // approval, because the base never changed. The approval time is the one the // gate is using: the project steward's marker or the owner's approval. - const approvalAt = decision === "project" ? (approval?.comment.createdAt ?? null) : owner.at; + // BB-327: the BB-279 base-change rule uses the approval's time whichever + // approver gave it; with both, the newest approval is the one the gate uses. + const approvalAt = decision === "project" ? (approval?.comment.createdAt ?? null) : owner.at === null ? (delegate.approval?.at ?? null) : delegate.approval === null ? owner.at : owner.at > delegate.approval.at ? owner.at : delegate.approval.at; const baseChangedAt = pull?.baseChangedAt ?? null; const baseChangedSinceApproval = opts.baseChangedSinceApproval ?? (baseChangedAt !== null && approvalAt !== null && baseChangedAt > approvalAt); const headOnDefaultTip = opts.headMergeBaseIsDefaultTip ?? pull?.headMergeBaseIsDefaultTip ?? null; const baseStale = baseChangedSinceApproval && headOnDefaultTip !== true; - const approved = (decision === "project" ? projectApproved : owner.approved) && !baseStale; + // BB-327: a delegate approval meets the lane only while no delegate has an + // open changes-requested. Latest-wins is per delegate, so one delegate's + // approval does not merge over another's outstanding changes request; the + // viewer's own approval is still the override. + const delegateApproved = delegate.approval !== null && delegate.changesRequested.length === 0; + const approved = (decision === "project" ? projectApproved : owner.approved || delegateApproved) && !baseStale; // A stale approval is not a request for another approval: the head must be // rebased onto the default branch first, and a fresh approval would only let // the un-rebased head merge. So neither approval is asked for while // `baseStale`, and `missing` names the rebase. const approvalNeeded = ownerLane && markerApproved && checksGreen && !approved && !baseStale; + // BB-327: while a requested reviewer is outstanding, the owner is not asked: + // the lane waits on the delegate, and `needsOwnerApproval` is false. The + // viewer's own approval is still an override, so this holds only until one + // approval (the viewer's or a delegate's) lands. + const delegatePending = approvalNeeded && decision === "user" && delegate.outstanding.length > 0; + // BB-327: a delegate whose latest review is changes-requested is re-solicited + // once per head, only once the independent reviewer's marker approves that + // head with green checks. The record stops a repeated look re-requesting. + const reRequested = new Set((opts.reRequestedDelegates ?? []).map((l) => l.toLowerCase())); + const delegateReRequested = delegate.outstanding.filter((login) => reRequested.has(login.toLowerCase())); + const delegatesToReRequest = + approvalNeeded && decision === "user" && marker !== null && marker.sha === headSha + ? delegate.changesRequested.filter((c) => c.commit !== null && c.commit !== headSha && !reRequested.has(c.login.toLowerCase())).map((c) => c.login) + : []; const gateMet = pull !== null && markerApproved && checksGreen && (!ownerLane || approved); const missing = gateMet ? null @@ -493,13 +653,15 @@ export function prGate(entity: EntitySnapshot, opts: PrGateOptions = {}): PrGate : ownerLane && !approved ? baseStale ? "rebase the head onto the default branch: the base changed since the approval" - : product - ? "owner approval needed (product)" - : escalated - ? "owner approval needed (the reviewer escalated it)" - : decision === "project" - ? "project steward approval needed" - : "owner approval needed" + : decision === "user" && delegate.outstanding.length > 0 + ? `approval needed from ${delegate.outstanding.join(", ")}${delegateReRequested.length > 0 ? ` (re-requested for this head: ${delegateReRequested.join(", ")})` : ""}` + : product + ? "owner approval needed (product)" + : escalated + ? "owner approval needed (the reviewer escalated it)" + : decision === "project" + ? "project steward approval needed" + : "owner approval needed" : "not met"; return { headSha, @@ -516,7 +678,17 @@ export function prGate(entity: EntitySnapshot, opts: PrGateOptions = {}): PrGate projectApprovalUrl: approval?.comment.url ?? null, gateMet, missing, - needsOwnerApproval: approvalNeeded && decision === "user", + delegates: delegate.outstanding, + delegatePending, + delegateApproved, + delegateApprovalBy: delegate.approval?.by ?? null, + delegateApprovalAt: delegate.approval?.at ?? null, + delegateApprovalId: delegate.approval?.id ?? null, + delegateApprovalUrl: delegate.approval?.url ?? null, + delegateChangesRequested: delegate.changesRequested.map((c) => c.login), + delegateReRequested, + delegatesToReRequest, + needsOwnerApproval: approvalNeeded && decision === "user" && !delegatePending, needsProjectApproval: approvalNeeded && decision === "project", baseStale, decision, diff --git a/plugins/stewards/github.ts b/plugins/stewards/github.ts index 565c0aa7..d4a27b1a 100644 --- a/plugins/stewards/github.ts +++ b/plugins/stewards/github.ts @@ -77,6 +77,12 @@ export interface GithubWriter { * changes-requested review, where the owner's own pull request cannot. */ review(repo: string, number: number, event: "APPROVE" | "REQUEST_CHANGES" | "COMMENT", body: string): Promise; + /** + * Request reviews from the given logins as the connected user (BB-327), + * the API equivalent of `gh pr edit --add-reviewer`. Used to re-solicit a + * delegate after they requested changes and a new head is approved. + */ + requestReviewers(repo: string, number: number, logins: readonly string[]): Promise; /** * Squash-merge the pull request, with the given commit title and message; * returns the merge commit sha when GitHub reports one. `sha` is the head @@ -184,6 +190,10 @@ export function createGhWriter(token: TokenReader = createGhTokenReader(), doFet async review(repo, number, event, body) { await request("POST", `/repos/${repo}/pulls/${number}/reviews`, { event, body }); }, + async requestReviewers(repo, number, logins) { + if (logins.length === 0) return; + await request("POST", `/repos/${repo}/pulls/${number}/requested_reviewers`, { reviewers: logins }); + }, async squashMerge(repo, number, title, body, headSha) { const response = await request("PUT", `/repos/${repo}/pulls/${number}/merge`, { merge_method: "squash", commit_title: title, commit_message: body, ...(headSha === undefined || headSha === null || headSha === "" ? {} : { sha: headSha }) }); const merged = (await response.json().catch(() => null)) as { sha?: unknown } | null; diff --git a/plugins/stewards/migrations.snapshot.json b/plugins/stewards/migrations.snapshot.json index f85da4a1..d4e37f72 100644 --- a/plugins/stewards/migrations.snapshot.json +++ b/plugins/stewards/migrations.snapshot.json @@ -131,5 +131,7 @@ "8f99fb907fbb234541fca066d9756d37c30dd28130678271a52c8b0b0d1a1e23", "faaf49705d6a094cfa5d468f3c5bf303ccaa7b58bc88582de8c6a407de719041", "3f683f67336499cdca7460d9106a2ab9f91a74e028a6f359e4ebb29a16bb8163", - "dac7694ca870936e15df9f4c6837973e8d1191b271743b386b1db36427577937" + "dac7694ca870936e15df9f4c6837973e8d1191b271743b386b1db36427577937", + "8a61e3594b695ff3b5f2f58573155bd59f7209142643e4f212fe3485a4ae80f9", + "c7dcc1c8ee819162947a9965a7fb0cb7129900a4d68f5f7f91a99184a225dea9" ] diff --git a/plugins/stewards/read-counts.test.ts b/plugins/stewards/read-counts.test.ts index e060bfdf..dfe22bf7 100644 --- a/plugins/stewards/read-counts.test.ts +++ b/plugins/stewards/read-counts.test.ts @@ -169,7 +169,12 @@ describe("a reconcile pass over a fixed binding set (BB-297)", () => { // `reviewersOf` for a finished worker's live reviewers as well as its // descendants, so a parentless reviewer keeps the worker unarchived. That // is the worker row and its binding, two store reads. - expect(reconcile).toEqual({ storeReads: 185, sourceCalls: 12, reconciles: 4, bindings: 4 }); + // BB-327 raised them 185 → 194: `assessBinding` reads the remembered + // delegate set and the reviewer-request record for each of the three own + // pull requests (web#7, web#8, web#9), two store reads each, and + // `syncPullApproval` reads the remembered set once per pull to forget a + // requester the owner withdrew without a review. + expect(reconcile).toEqual({ storeReads: 194, sourceCalls: 12, reconciles: 4, bindings: 4 }); expect(wake).toEqual({ storeReads: 15, sourceCalls: 0, wakes: 1 }); }); diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index ae6b408c..4949c06b 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -13718,6 +13718,25 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { return { ...t, project, steward, key, binding: () => t.hooks.store.find("ENG-12")! }; } + it("waits on a requested reviewer: blocked in the sidebar and not decidable by the steward (BB-327)", async () => { + const t = await withPull([reviewMarkerApprover("owner-reviewed", "owner")], { pullOver: { requestedReviewers: ["arashout"] } }); + const binding = t.binding(); + const esc = t.hooks.store.openEscalations(binding.id).find((x) => x.kind === "approval")!; + // The escalation waits on the delegate, and no owner item is filed. + expect(esc.route).toBe("steward"); + expect(esc.meanwhile).toContain("arashout"); + expect(t.hooks.store.openNeeds(binding.id).some((n) => n.kind === "approve-pr")).toBe(false); + // The sidebar row reads blocked, not "needs you". + const sidebar = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as { bindings: Array<{ key: string; stuck: boolean; needsUser: boolean }> }; + expect(sidebar.bindings.find((x) => x.key === "ENG-12")).toMatchObject({ stuck: true, needsUser: false }); + // The ticket steward cannot resolve the delegate wait into a decline. + const refused = await t.tool("steward_update", { binding: "ENG-12", guidance: "no", resolve: esc.id }, t.steward); + expect(refused.error).toBe(true); + expect(refused.text).toMatch(/waits on the requested reviewer/u); + // The escalation is still open. + expect(t.hooks.store.escalation(esc.id)!.status).toBe("open"); + }); + it("prints the reviewer spawn command from models.reviewer, and errors clearly with none", async () => { const t = await setup(); t.entities.set("uuid-12", issue()); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 0b9b8cbd..4195e73e 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -103,7 +103,7 @@ import { EVENTS_PER_LOOK, NO_TOKEN, RECENT_PER_LOOK, SENTRY_API_URL, TOKEN_SCOPE import { ALERTMANAGER_URL_ENV, alertmanagerChanges, alertmanagerSightings, alertmanagerSummary, createAlertmanagerReader, emptyAlertmanagerLook, resolveAlertmanagerUrl, type AlertmanagerFinding, type AlertmanagerLook, type AlertmanagerReader, type AlertmanagerRung } from "./alertmanager.js"; import { advanced, answerDiffers, anyWorkerInFlight, asksForOpenApproval, commentDiffersFromRecommendation, compactDue, deploymentSettled, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, hasLabel, IDLE_WAKE_TEXT, idleInActiveStage, isCommentNews, isOwnStageChange, lifecycle, mechanicalStatus, namesUserAsBlocker, newHumanComments, newestCommentAt, openUserFacingItems, ownChecksFinished, ownPullClosed, ownPullMerged, phaseAndStage, productGateOptions, runningWorkerReason, newestEditComment, specDiff, specHash, specText, stuckDue, unheardWait, workerInFlight, workerReportedTerminal, type Change, type MechanicalEvent, type OpenUserItem } from "./reconcile.js"; import { classifyApproval, latestProjectApprovalMarker, latestReviewMarker, prGate, reviewMarker } from "./gate.js"; -import { approveOwnerReviewedPull, approvePrPageAction, declineOwnerReviewedPull, deliverApproval, fileForwardedApprovePrNeed, isProjectSteward, isUserThread, markerKey, normalizeText, specApprovedByProject, syncPullApproval, userApprovedOnEntity, userSaid, type ApprovalsContext } from "./approvals.js"; +import { approveOwnerReviewedPull, approvePrPageAction, declineOwnerReviewedPull, deliverApproval, fileForwardedApprovePrNeed, isDelegateWait, isProjectSteward, isUserThread, markerKey, normalizeText, specApprovedByProject, syncPullApproval, userApprovedOnEntity, userSaid, type ApprovalsContext } from "./approvals.js"; import { deliverEscalation, nextRoute, routedTo, type EscalationsContext } from "./escalations.js"; import { approvalWanted, briefGate, gateState, resolveChecklistItem, syncApprovalRequest, type ReadyGateContext } from "./ready-gate.js"; import { @@ -4637,6 +4637,22 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // no extra GitHub read. Everything else is a row already in hand. const decisions = new Map(); for (const e of ownPullEntities(observed, gatePulls)) decisions.set(lc(e.key), decideForPull(e.pull?.files ?? null, config.file.bigDecisions)); + // BB-327: the logins the store remembers as requested reviewers, so a + // delegate's APPROVED review still counts after GitHub drops them. + const rememberedRequesters = new Map(); + const reRequestedDelegates = new Map(); + for (const e of ownPullEntities(observed, gatePulls)) { + const remembered = store.pullRequesters(b.id, e.url ?? e.key); + if (remembered.length > 0) { + rememberedRequesters.set(lc(e.key), remembered); + if (e.url !== null) rememberedRequesters.set(lc(e.url), remembered); + } + const reRequested = store.reviewerRequests(b.id, e.url ?? e.key, e.pull?.headSha ?? ""); + if (reRequested.length > 0) { + reRequestedDelegates.set(lc(e.key), reRequested); + if (e.url !== null) reRequestedDelegates.set(lc(e.url), reRequested); + } + } const input: AssessmentInput = { binding: b, observed, @@ -4644,6 +4660,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P gatePulls, decisions, projectApprovals: projectApprovalsFor(b), + rememberedRequesters, + reRequestedDelegates, workers, escalations: store.openEscalations(b.id), needs: store.openNeeds(b.id), @@ -9187,7 +9205,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P lane: string | null; marker: { round: number; sha: string; verdict: string } | null; decision: { entry: string | null; decide: "project" | "user"; why: string; listing: string; selfWidening: string[] }; - approval: { kind: "owner-comment" | "owner-review" | "project-marker"; sha: string | null; at: string | null } | null; + approval: { kind: "owner-comment" | "owner-review" | "delegate-review" | "project-marker"; sha: string | null; at: string | null; by?: string | null } | null; checks: { state: string | null; green: boolean }; openItems: string[]; /** Whether the reviewer's marker escalated the pull request to the owner (BB-192). */ @@ -9216,6 +9234,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const marker = latestProjectApprovalMarker(pull.comments, recorded); if (marker !== null) return { kind: "project-marker", sha: marker.marker.sha === "" ? null : marker.marker.sha, at: marker.comment.createdAt }; } + if (gate.delegateApproved) { + const at = gate.delegateApprovalAt; + const review = at === null ? undefined : (pull.pull?.reviews ?? []).find((r) => (r.submittedAt ?? "") === at && r.author.toLowerCase() === (gate.delegateApprovalBy ?? "").toLowerCase() && r.state.toLowerCase() === "approved"); + return { kind: "delegate-review", sha: review?.commit ?? null, at, by: gate.delegateApprovalBy }; + } if (gate.ownerApproved) { const at = gate.ownerApprovalAt; const review = at === null ? undefined : (pull.pull?.reviews ?? []).find((r) => (r.submittedAt ?? "") === at && r.state.toLowerCase() === "approved"); @@ -9272,7 +9295,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const marker = r.marker === null ? "none" : `round ${r.marker.round} at ${shortSha(r.marker.sha)} (${r.marker.verdict})`; const decision = r.decision.entry === null ? `no matching entry (${r.decision.decide}: ${r.decision.why})` : `"${r.decision.entry}" (${r.decision.decide})`; const listing = r.decision.listing.split("\n").map((l) => ` ${l}`).join("\n"); - const approval = r.approval === null ? "none" : `${r.approval.kind}${r.approval.sha === null ? "" : ` at ${shortSha(r.approval.sha)}`}${r.approval.at === null ? "" : ` (${r.approval.at})`}`; + const approval = r.approval === null ? "none" : `${r.approval.kind}${r.approval.sha === null ? "" : ` at ${shortSha(r.approval.sha)}`}${r.approval.at === null ? "" : ` (${r.approval.at})`}${r.approval.by === null || r.approval.by === undefined ? "" : ` by ${r.approval.by}`}`; // The reviewer's owner call is printed beside the decide-list winner: the // decide list may still name a `project` entry, but the escalation binds // the gate to the owner's approval (BB-192). @@ -9295,8 +9318,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P function mergeSummary(gate: ReturnType): string { const lane = gate.lane ?? "no-review"; const approved = gate.marker?.sha ?? gate.headSha; - const by = gate.projectApproved ? ", approved by the project steward" : gate.ownerApproved ? ", approved by the owner" : ""; - const escalation = gate.reason === "product" ? ", the owner acked the product" : gate.escalated ? ", escalated by the reviewer to the owner" : ""; + const by = gate.projectApproved + ? ", approved by the project steward" + : gate.delegateApproved + ? `, approved by the requested reviewer ${gate.delegateApprovalBy ?? ""}`.trimEnd() + : gate.ownerApproved + ? ", approved by the owner" + : ""; + // BB-327: a delegate's approval is not the owner's, so the product and + // escalation clauses only credit the owner when the owner approved. + const escalation = gate.reason === "product" + ? gate.ownerApproved ? ", the owner acked the product" : "" + : gate.escalated && gate.ownerApproved ? ", escalated by the reviewer to the owner" : ""; return `Merged: ${lane} lane, reviewer approved ${shortSha(approved)}, checks green${by}${escalation}.`; } @@ -9737,7 +9770,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ...presentationHold(b), holdStack: b.holdStack, needsUser: needsUser(b, projectQuestions, openIds), - stuck: store.openEscalations(b.id).some((x) => x.kind === "stuck"), + stuck: store.openEscalations(b.id).some((x) => x.kind === "stuck" || isDelegateWait(x)), deployment: (Object.values(b.deployments).sort((x, y) => y.at - x.at)[0] ?? null)?.state ?? null, pending: b.pending, requeueAt: b.requeueAt, @@ -9790,6 +9823,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const { questions, withUser, needs } = needsYou(projectId, open, projectQuestions); const stuck = open.flatMap((b) => [ ...store.openEscalations(b.id).filter((x) => x.kind === "stuck").map((x) => ({ b, why: `Stuck, with ${x.route === "user" ? "you" : x.route === "parent" ? "the parent steward" : "the project steward"}: ${x.question}`, since: x.createdAt })), + ...store.openEscalations(b.id).filter(isDelegateWait).map((x) => ({ b, why: `Waiting on the requested reviewer: ${x.meanwhile}`, since: x.createdAt })), ...(b.hold === null ? [] : [{ b, why: `On hold: ${b.hold}`, since: null }]), ]); const ended = store.endedSince(projectId, now() - ENDED_ON_BOARD_MS, 30); @@ -9839,7 +9873,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ...presentationHold(b), holdStack: b.holdStack, needsUser: needsUser(b, projectQuestions, openIds), - stuck: store.openEscalations(b.id).some((x) => x.kind === "stuck"), + stuck: store.openEscalations(b.id).some((x) => x.kind === "stuck" || isDelegateWait(x)), // The newest deployment watch, whatever its state; `merged` reads as deploying. deployment: (Object.values(b.deployments).sort((x, y) => y.at - x.at)[0] ?? null)?.state ?? null, pending: b.pending, @@ -11952,6 +11986,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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}.`)); + // BB-327: the delegate wait is the plugin's, not the steward's to + // decide; it closes when the delegate approves or the request is + // withdrawn. + if (isDelegateWait(resolving)) return toolError(new Error(`The approval of ${resolving.question.replace(/^Approve\s+/u, "")} waits on the requested reviewer, not you (${resolving.meanwhile}). It closes when they approve, or when the request is withdrawn; do not resolve it.`)); // Criterion 2: the project steward's approving words are the // approval; approve: true is no longer needed as well. Only the // approver the gate names may do it, as with approve: true: the @@ -12336,7 +12374,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // BB-296: the `stuck` flag shares the same grouped escalations, so the // sidebar and board do not re-query them per binding. const stuck = new Set(); - for (const [bindingId, list] of escalationsByBinding) if (list.some((x) => x.kind === "stuck")) stuck.add(bindingId); + for (const [bindingId, list] of escalationsByBinding) if (list.some((x) => x.kind === "stuck" || isDelegateWait(x))) stuck.add(bindingId); return { questions: questionViews, withUser, needs: opts.actionableOnly === true ? allNeeds.filter((n) => n.actionable) : allNeeds, needsUser, stuck }; } diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index b7f986cc..dfb772a7 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -1,7 +1,7 @@ import Database from "better-sqlite3"; import { describe, expect, it } from "vitest"; import { z } from "zod"; -import { ACTOR_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, HUDDLE_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS, ASSESSMENT_MIGRATIONS, ASSUMPTION_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, DATED_WAIT_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ENDED_READ_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_PR_MIGRATIONS, LESSON_TIER_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, MIGRATIONS, PULL_WATCH_MIGRATIONS, RATIONALE_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, STACK_MIGRATIONS, STACKED_PULLS_MIGRATIONS, VALIDATION_MIGRATIONS, WAKE_RETRY_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, WORKER_CHECK_MIGRATIONS, STANDUP_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, createStore, lessonScope, statusRecordSchema, type Binding } from "./store.js"; +import { ACTOR_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, HUDDLE_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS, ASSESSMENT_MIGRATIONS, ASSUMPTION_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, DATED_WAIT_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ENDED_READ_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_PR_MIGRATIONS, LESSON_TIER_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, MIGRATIONS, PULL_REQUESTER_MIGRATIONS, PULL_WATCH_MIGRATIONS, RATIONALE_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, STACK_MIGRATIONS, STACKED_PULLS_MIGRATIONS, VALIDATION_MIGRATIONS, WAKE_RETRY_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, WORKER_CHECK_MIGRATIONS, STANDUP_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, createStore, lessonScope, statusRecordSchema, type Binding } from "./store.js"; /** MIGRATIONS without the groups appended after the ones these order tests assert. */ const beforeActorMigrations = MIGRATIONS.slice(0, MIGRATIONS.indexOf(ACTOR_MIGRATIONS[0]!)); @@ -739,9 +739,10 @@ describe("the actor rename migration (BB-97)", () => { // ended-read index after that, BB-300 slice 4 appended the stand-up table // after that, its rename follows, BB-303 appended the scope column // after that, BB-307 appended the delegation log after that, BB-312 - // appended the completed flag after that, and BB-314 appended the - // Alertmanager look column after that. - const groups = [ALERTMANAGER_LOOK_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_MIGRATIONS, HUDDLE_MIGRATIONS, ENDED_READ_MIGRATIONS, ASSESSMENT_MIGRATIONS, STACKED_PULLS_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, WAKE_RETRY_MIGRATIONS, DATED_WAIT_MIGRATIONS, ASSUMPTION_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, STACK_MIGRATIONS, PULL_WATCH_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, LESSON_PR_MIGRATIONS, ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS]; + // appended the completed flag after that, BB-314 appended the + // Alertmanager look column after that, and BB-327 appended the delegate-set + // and reviewer-request tables after that. + const groups = [REVIEWER_REQUEST_MIGRATIONS, PULL_REQUESTER_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_MIGRATIONS, HUDDLE_MIGRATIONS, ENDED_READ_MIGRATIONS, ASSESSMENT_MIGRATIONS, STACKED_PULLS_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, WAKE_RETRY_MIGRATIONS, DATED_WAIT_MIGRATIONS, ASSUMPTION_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, STACK_MIGRATIONS, PULL_WATCH_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, LESSON_PR_MIGRATIONS, ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS]; let end = MIGRATIONS.length; for (const group of groups) { expect(MIGRATIONS.slice(end - group.length, end)).toEqual([...group]); @@ -835,9 +836,14 @@ describe("the escalation route rename migration (BB-209)", () => { // ended-read index after that, BB-300 slice 4's huddle table after that, // its rename to the stand-up table after that, BB-303's scope column // after that, BB-307's delegation log after that, BB-312's completed - // flag after that, and BB-314's Alertmanager look column after that. - const withoutAlertmanagerLook = MIGRATIONS.slice(0, -ALERTMANAGER_LOOK_MIGRATIONS.length); - expect(MIGRATIONS.slice(-ALERTMANAGER_LOOK_MIGRATIONS.length)).toEqual([...ALERTMANAGER_LOOK_MIGRATIONS]); + // flag after that, BB-314's Alertmanager look column after that, and + // BB-327's delegate-set and reviewer-request tables after that. + const withoutReviewerRequests = MIGRATIONS.slice(0, -REVIEWER_REQUEST_MIGRATIONS.length); + expect(MIGRATIONS.slice(-REVIEWER_REQUEST_MIGRATIONS.length)).toEqual([...REVIEWER_REQUEST_MIGRATIONS]); + const withoutPullRequesters = withoutReviewerRequests.slice(0, -PULL_REQUESTER_MIGRATIONS.length); + expect(withoutReviewerRequests.slice(-PULL_REQUESTER_MIGRATIONS.length)).toEqual([...PULL_REQUESTER_MIGRATIONS]); + const withoutAlertmanagerLook = withoutPullRequesters.slice(0, -ALERTMANAGER_LOOK_MIGRATIONS.length); + expect(withoutPullRequesters.slice(-ALERTMANAGER_LOOK_MIGRATIONS.length)).toEqual([...ALERTMANAGER_LOOK_MIGRATIONS]); const withoutCompleted = withoutAlertmanagerLook.slice(0, -STANDUP_COMPLETED_MIGRATIONS.length); expect(withoutAlertmanagerLook.slice(-STANDUP_COMPLETED_MIGRATIONS.length)).toEqual([...STANDUP_COMPLETED_MIGRATIONS]); const withoutDelegations = withoutCompleted.slice(0, -STANDUP_DELEGATION_MIGRATIONS.length); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 0cddbc1a..adb5109e 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -17,7 +17,7 @@ import { opsLookSchema, type FingerprintRow, type OpsLook } from "./ops.js"; import { sentryLookSchema, type SentryLook } from "./sentry.js"; import { alertmanagerLookSchema, type AlertmanagerLook } from "./alertmanager.js"; import type { GuidanceCitation } from "./guidance.js"; -import { APPROVAL_MARKER_MIGRATIONS, APPROVALS_CHAIN_MIGRATIONS, createApprovalsStore } from "./approvals-store.js"; +import { APPROVAL_MARKER_MIGRATIONS, APPROVALS_CHAIN_MIGRATIONS, createApprovalsStore, PULL_REQUESTER_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS } from "./approvals-store.js"; export type { ProjectApproval } from "./approvals-store.js"; /** @@ -471,7 +471,7 @@ export const IDLE_MIGRATIONS = [ // BB-77: the project-steward approval marker's migration group lives with the // table it alters, in approvals-store.ts, so the gate's own files can be named. -export { APPROVAL_MARKER_MIGRATIONS } from "./approvals-store.js"; +export { APPROVAL_MARKER_MIGRATIONS, PULL_REQUESTER_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS } from "./approvals-store.js"; // BB-97: the status report's actor `me` is renamed `user`, so all three values // name a party rather than a pronoun. A stored row keeps its meaning: this @@ -726,7 +726,7 @@ export const STANDUP_COMPLETED_MIGRATIONS = [`ALTER TABLE standups ADD COLUMN co // a store from before the step reads back exactly as before. export const ALERTMANAGER_LOOK_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN alertmanager_look TEXT`]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS, ...ACTOR_MIGRATIONS, ...LESSON_PR_MIGRATIONS, ...REVIEWER_MODEL_MIGRATIONS, ...WAKE_SOURCE_MIGRATIONS, ...SERVER_SETTINGS_MIGRATIONS, ...PULL_WATCH_MIGRATIONS, ...STACK_MIGRATIONS, ...ESCALATION_ROUTE_MIGRATIONS, ...DEPS_DECISION_MIGRATIONS, ...WORKER_STOP_REASON_MIGRATIONS, ...ASSUMPTION_MIGRATIONS, ...DATED_WAIT_MIGRATIONS, ...WAKE_RETRY_MIGRATIONS, ...MERGE_BEHIND_MIGRATIONS, ...RETARGET_PULLS_MIGRATIONS, ...STACKED_PULLS_MIGRATIONS, ...ASSESSMENT_MIGRATIONS, ...ENDED_READ_MIGRATIONS, ...HUDDLE_MIGRATIONS, ...STANDUP_MIGRATIONS, ...STANDUP_BINDING_MIGRATIONS, ...STANDUP_DELEGATION_MIGRATIONS, ...STANDUP_COMPLETED_MIGRATIONS, ...ALERTMANAGER_LOOK_MIGRATIONS]; +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS, ...ACTOR_MIGRATIONS, ...LESSON_PR_MIGRATIONS, ...REVIEWER_MODEL_MIGRATIONS, ...WAKE_SOURCE_MIGRATIONS, ...SERVER_SETTINGS_MIGRATIONS, ...PULL_WATCH_MIGRATIONS, ...STACK_MIGRATIONS, ...ESCALATION_ROUTE_MIGRATIONS, ...DEPS_DECISION_MIGRATIONS, ...WORKER_STOP_REASON_MIGRATIONS, ...ASSUMPTION_MIGRATIONS, ...DATED_WAIT_MIGRATIONS, ...WAKE_RETRY_MIGRATIONS, ...MERGE_BEHIND_MIGRATIONS, ...RETARGET_PULLS_MIGRATIONS, ...STACKED_PULLS_MIGRATIONS, ...ASSESSMENT_MIGRATIONS, ...ENDED_READ_MIGRATIONS, ...HUDDLE_MIGRATIONS, ...STANDUP_MIGRATIONS, ...STANDUP_BINDING_MIGRATIONS, ...STANDUP_DELEGATION_MIGRATIONS, ...STANDUP_COMPLETED_MIGRATIONS, ...ALERTMANAGER_LOOK_MIGRATIONS, ...PULL_REQUESTER_MIGRATIONS, ...REVIEWER_REQUEST_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -2757,6 +2757,10 @@ export function createStore(db: Database.Database, now: () => number, options: S setEscalationHead(id: string, headSha: string | null): void { db.prepare("UPDATE escalations SET head_sha = ? WHERE id = ?").run(headSha, id); }, + /** Replace an open escalation's `meanwhile` text, so a wait can name who it now waits on (BB-327). */ + setEscalationMeanwhile(id: string, meanwhile: string): void { + db.prepare("UPDATE escalations SET meanwhile = ? WHERE id = ?").run(meanwhile, id); + }, /** Record a forwarding hop on the escalation's chain, keeping its rewording. */ addHop(id: string, hop: { threadId: string; bindingId: string | null; rewording: string | null }): void { const x = getEscalation.get(id); diff --git a/plugins/stewards/test-world.ts b/plugins/stewards/test-world.ts index c07d6b53..d433cb52 100644 --- a/plugins/stewards/test-world.ts +++ b/plugins/stewards/test-world.ts @@ -98,6 +98,7 @@ export function world() { /** What the page's GitHub actions did. */ const githubComments: Array<{ repo: string; number: number; body: string }> = []; const githubReviews: Array<{ repo: string; number: number; event: string; body: string }> = []; + const githubReviewerRequests: Array<{ repo: string; number: number; logins: string[] }> = []; const githubMerges: Array<{ repo: string; number: number; title: string; body: string }> = []; /** Workflow dispatches the fake github serves, in order (BB-216). */ const githubDispatches: Array<{ repo: string; workflow: string; ref: string; inputs: Record }> = []; @@ -136,6 +137,9 @@ export function world() { review: async (repo: string, number: number, event: "APPROVE" | "REQUEST_CHANGES" | "COMMENT", body: string) => { githubReviews.push({ repo, number, event, body }); }, + requestReviewers: async (repo: string, number: number, logins: readonly string[]) => { + githubReviewerRequests.push({ repo, number, logins: [...logins] }); + }, squashMerge: async (repo: string, number: number, title: string, body: string, sha?: string | null) => { if (mergePullError !== null) throw new Error(mergePullError); const key = `${repo}#${number}`; @@ -601,7 +605,7 @@ export function world() { }, }; let now = Date.parse("2026-10-14T15:00:00Z"); - return { files, writes, writtenContent, fileContents, repos, primary, entities, projectList, dependabotAlerts, dependabotGraphEmpty, sourceDeployments, sourceFiles, sourceCommits, sourceRuns, sourceCompares, labelEnsureCalls, labelsEnsured, labelEnsureFailures, setLabelEnsureUnavailable: (value: boolean) => { labelEnsureUnavailable = value; }, setPushUnavailable: (value: boolean) => { pushUnavailable = value; }, setLabelEnsureThrow: (value: string | null) => { labelEnsureThrow = value; }, setLayout: (value: "primary" | "directory") => { layout = value; primary = value === "directory" ? null : { dir: "bb", url: "https://github.com/acme/bb.git" }; }, viewers, setLinearMine: (teams: Array<{ unit: string; name: string }>) => { linearMine = teams; }, setMissingStates: (source: "linear" | "github", unit: string, states: string[]) => { missingStates.set(`${source}:${unit.toLowerCase()}`, states); }, setMissingLabel: (source: "linear" | "github", unit: string, labels: string[]) => { missingLabels.set(`${source}:${unit.toLowerCase()}`, labels); }, rpcCalls, githubTrees, githubBranchProtection, githubLabels, setSnapshotError: (id: string, fail: boolean) => { if (fail) snapshotErrors.add(id); else snapshotErrors.delete(id); }, setSearchUnsupported: (value: boolean) => { searchUnsupported = value; }, setSearchError: (value: string | null) => { searchError = value; }, setCreatePullError: (value: string | null) => { createPullError = value; }, setMergePullError: (value: string | null) => { mergePullError = value; }, setSpawnError: (value: string | null) => { spawnError = value; }, setSpawnDelayMs: (value: number) => { spawnDelayMs = value; }, setMoveHeadOnMerge: (value: boolean) => { moveHeadOnMerge = value; }, setPullDetailsError: (value: string | null) => { pullDetailsError = value; }, setRetryConflict: (value: boolean) => { retryConflict = value; }, setRetryQueued: (value: boolean) => { retryQueued = value; }, threads, deletes, sections, usage, metadata, spawns, sends, retries, retryEvents, queuedDeletes, userTurns, githubComments, githubReviews, githubMerges, githubPulls, githubClosedPulls, githubDefaultBranches, githubBranches, githubFiles, githubFileContents, githubDispatches, setMergeDispatchError: (value: string | null) => { mergeDispatchError = value; }, github, sdk, uiPreferences, uiPreferencesWrites, realtimeOpens, setVoiceBaseUrl: (value: string) => { voiceBaseUrl = value; }, setVoiceServicePresent: (value: boolean) => { voiceServicePresent = value; }, setVoiceServiceReady: (value: boolean, message?: string) => { voiceServiceReady = value; if (message !== undefined) voiceServiceMessage = message; }, setVoiceSettingsThrow: (value: string | null) => { voiceSettingsThrow = value; }, setVoiceRealtimeRefusal: (value: string | null) => { voiceRealtimeRefusal = value; }, now: () => now, advance: (ms: number) => (now += ms) }; + return { files, writes, writtenContent, fileContents, repos, primary, entities, projectList, dependabotAlerts, dependabotGraphEmpty, sourceDeployments, sourceFiles, sourceCommits, sourceRuns, sourceCompares, labelEnsureCalls, labelsEnsured, labelEnsureFailures, setLabelEnsureUnavailable: (value: boolean) => { labelEnsureUnavailable = value; }, setPushUnavailable: (value: boolean) => { pushUnavailable = value; }, setLabelEnsureThrow: (value: string | null) => { labelEnsureThrow = value; }, setLayout: (value: "primary" | "directory") => { layout = value; primary = value === "directory" ? null : { dir: "bb", url: "https://github.com/acme/bb.git" }; }, viewers, setLinearMine: (teams: Array<{ unit: string; name: string }>) => { linearMine = teams; }, setMissingStates: (source: "linear" | "github", unit: string, states: string[]) => { missingStates.set(`${source}:${unit.toLowerCase()}`, states); }, setMissingLabel: (source: "linear" | "github", unit: string, labels: string[]) => { missingLabels.set(`${source}:${unit.toLowerCase()}`, labels); }, rpcCalls, githubTrees, githubBranchProtection, githubLabels, setSnapshotError: (id: string, fail: boolean) => { if (fail) snapshotErrors.add(id); else snapshotErrors.delete(id); }, setSearchUnsupported: (value: boolean) => { searchUnsupported = value; }, setSearchError: (value: string | null) => { searchError = value; }, setCreatePullError: (value: string | null) => { createPullError = value; }, setMergePullError: (value: string | null) => { mergePullError = value; }, setSpawnError: (value: string | null) => { spawnError = value; }, setSpawnDelayMs: (value: number) => { spawnDelayMs = value; }, setMoveHeadOnMerge: (value: boolean) => { moveHeadOnMerge = value; }, setPullDetailsError: (value: string | null) => { pullDetailsError = value; }, setRetryConflict: (value: boolean) => { retryConflict = value; }, setRetryQueued: (value: boolean) => { retryQueued = value; }, threads, deletes, sections, usage, metadata, spawns, sends, retries, retryEvents, queuedDeletes, userTurns, githubComments, githubReviews, githubReviewerRequests, githubMerges, githubPulls, githubClosedPulls, githubDefaultBranches, githubBranches, githubFiles, githubFileContents, githubDispatches, setMergeDispatchError: (value: string | null) => { mergeDispatchError = value; }, github, sdk, uiPreferences, uiPreferencesWrites, realtimeOpens, setVoiceBaseUrl: (value: string) => { voiceBaseUrl = value; }, setVoiceServicePresent: (value: boolean) => { voiceServicePresent = value; }, setVoiceServiceReady: (value: boolean, message?: string) => { voiceServiceReady = value; if (message !== undefined) voiceServiceMessage = message; }, setVoiceSettingsThrow: (value: string | null) => { voiceSettingsThrow = value; }, setVoiceRealtimeRefusal: (value: string | null) => { voiceRealtimeRefusal = value; }, now: () => now, advance: (ms: number) => (now += ms) }; } export async function setup(extra: Partial = {}, settings: Record = {}, seedProvider?: string | null | "fail-list" | "fail-set", seedNavigation?: string | null | "fail-list" | "fail-set") {