diff --git a/plugins/stewards/approvals.test.ts b/plugins/stewards/approvals.test.ts index 4e29ec52..9be05e45 100644 --- a/plugins/stewards/approvals.test.ts +++ b/plugins/stewards/approvals.test.ts @@ -26,7 +26,7 @@ const marker = (approver?: string) => function context() { const githubComment = vi.fn().mockResolvedValue("IC_1"); const recordProjectApproval = vi.fn(); - const ctx = { github: { comment: githubComment }, store: { recordProjectApproval } } as unknown as ApprovalsContext; + const ctx = { github: { comment: githubComment }, now: () => 0, store: { recordProjectApproval, assessment: () => null, recordAssessment: vi.fn(), projectApprovals: () => [] } } as unknown as ApprovalsContext; return { ctx, githubComment, recordProjectApproval }; } @@ -83,6 +83,9 @@ describe("an approval is delivered to a parked worker (BB-279)", () => { closeNeedByKey, addGuidance, patch: vi.fn(), + assessment: () => null, + recordAssessment: vi.fn(), + projectApprovals: () => [], }, github: { comment: githubComment, review: githubReview }, now: () => 0, diff --git a/plugins/stewards/approvals.ts b/plugins/stewards/approvals.ts index 15c65b07..dce76022 100644 --- a/plugins/stewards/approvals.ts +++ b/plugins/stewards/approvals.ts @@ -9,7 +9,8 @@ // closure, so nothing here reads the plugin's config or snapshots on its own. import { type BigDecision, decideFor, decideForPull, decideForRefusal, explainDecision, formatDecisionListing, type DecideMark } from "./decisions.js"; import type { ApprovalMode } from "./config.js"; -import { approvalMarkerLine, classifyApproval, ESCALATED_APPROVAL_REFUSAL, prGate, productReason, PRODUCT_APPROVAL_REFUSAL, reviewWorkerThread, type PrGate } from "./gate.js"; +import { approvalMarkerLine, classifyApproval, ESCALATED_APPROVAL_REFUSAL, productReason, PRODUCT_APPROVAL_REFUSAL, reviewWorkerThread, type PrGate } from "./gate.js"; +import { assessedGate } from "./assessed-gate.js"; import { parsePullRef, type GithubWriter } from "./github.js"; import { isSpecComment, productGateOptions, workerInFlight, type MechanicalEvent } from "./reconcile.js"; import { signatureLine, type EntitySnapshot, type Source } from "./source-contract.js"; @@ -143,7 +144,7 @@ export async function deliverProjectApproval(ctx: ApprovalsContext, b: Binding, * decide list matched (BB-192). */ export async function recordProjectDecision(ctx: ApprovalsContext, b: Binding, pull: EntitySnapshot, threadId: string, fields: { headSha: string; entry: string | null; verdict: "approved" | "declined"; reasoning: string }): Promise<{ commentId: string }> { - const g = prGate(pull, productGateOptions(b, pull)); + const g = assessedGate(ctx.store, b, pull, ctx.now()); if (g.escalated) throw new Error(g.reason === "product" ? PRODUCT_APPROVAL_REFUSAL : ESCALATED_APPROVAL_REFUSAL); const commentId = await postApprovalMarker(ctx, pull, threadId, fields); ctx.store.recordProjectApproval({ bindingId: b.id, headSha: fields.headSha, entry: fields.entry, byThread: threadId, commentId, verdict: fields.verdict }); @@ -240,7 +241,7 @@ export async function approveOwnerReviewedPull(ctx: ApprovalsContext, b: Binding // A reviewer's owner call in the marker is binding: the project steward does // not decide it, whatever entry the decide list matched, and never posts a // `bb-approval` on it (BB-192). The product reason (BB-207) binds it the same way. - const approvalGate = pull === null ? null : prGate(pull, { projectApprovals: ctx.store.projectApprovals(b.id), ...productGateOptions(b, pull) }); + const approvalGate = pull === null ? null : assessedGate(ctx.store, b, pull, ctx.now(), decisions); if (approvalGate !== null && approvalGate.escalated) return { ok: false, error: approvalGate.reason === "product" ? PRODUCT_APPROVAL_REFUSAL : ESCALATED_APPROVAL_REFUSAL }; const files = pull === null ? null : await ctx.pullChangedFiles(pull); const decision = decideFor(files, fields.entry, decisions); @@ -365,22 +366,20 @@ export type PullApprovalResult = { gate: PrGate; closed: boolean; approvalRaised * once by the caller. The merge item is the caller's; this returns the gate so * it can file it. */ -export async function syncPullApproval(ctx: ApprovalsContext, b: Binding, pull: EntitySnapshot, decisions: readonly BigDecision[]): Promise { +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; - // The decide list places the pull request: a `project` entry whose paths - // the change touches is the project steward's, and everything else is - // the user's, filed on the page at once (BB-51). The files are read only - // when the lane actually waits on an approval. - const preliminary = prGate(pull, { projectApprovals: ctx.store.projectApprovals(b.id), ...productGateOptions(b, pull) }); - let g = preliminary; + // 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, + // so this no longer builds a second gate from the changed files. The files + // are still read for the listing the approval item carries (BB-135). + let g = gateFor?.(pull) ?? assessedGate(ctx.store, b, pull, ctx.now(), decisions); // The decide-list listing is fetched once, with the changed files, and // passed to whichever surface asks for the approval (BB-135). let listing: string | null = null; - if (preliminary.lane !== "no-review" && preliminary.marker?.verdict === "approved" && preliminary.checksGreen && !preliminary.ownerApproved && !preliminary.projectApproved) { + if (g.lane !== "no-review" && g.marker?.verdict === "approved" && g.checksGreen && !g.ownerApproved && !g.projectApproved) { const files = await ctx.pullChangedFiles(pull); - const explanation = explainDecision(files, decisions); - listing = formatDecisionListing(explanation); - g = prGate(pull, { decision: explanation.mark, projectApprovals: ctx.store.projectApprovals(b.id), ...productGateOptions(b, pull) }); + listing = formatDecisionListing(explainDecision(files, decisions)); } const closed = pull.pull?.merged === true || pull.state === "merged" || pull.state === "closed"; const approvalEsc = ctx.store.openEscalations(b.id).find((x) => x.kind === "approval" && x.url === url && x.resolutionKind === "approve-decline") ?? null; @@ -480,7 +479,7 @@ export async function approvePrPageAction(ctx: ApprovalsContext, b: Binding, nee const ref = parsePullRef(need.url); if (ref === null) return { ok: false, message: `I cannot tell which pull request ${need.url} is.` }; const pull = await freshPull(ctx, b, need.url); - const gate = pull === null ? null : prGate(pull, productGateOptions(b, pull)); + const gate = pull === null ? null : assessedGate(ctx.store, b, pull, ctx.now()); if (pull === null || gate === null || !gate.needsOwnerApproval) return { ok: false, message: `Not now: ${gate?.missing ?? "the pull request has not been observed yet"}.` }; const foreign = isForeignPull(pull); const after = (closure: string): void => { diff --git a/plugins/stewards/assessed-gate.test.ts b/plugins/stewards/assessed-gate.test.ts new file mode 100644 index 00000000..dcc42f98 --- /dev/null +++ b/plugins/stewards/assessed-gate.test.ts @@ -0,0 +1,264 @@ +// BB-322 (child of BB-291, criterion 1): the single read/refresh of the stored +// merge-gate assessment. These fixtures cover the cases the ticket names: +// project-mark approved, the owner's unsigned approval on a project-placed pull +// (BB-321), a declined reviewer marker, null/empty changed files, and a stale +// assessment after a head sha change. Each gate-met fixture carries a parked +// `finished` worker and a second open own pull request (the BB-291 rule). +import Database from "better-sqlite3"; +import { describe, expect, it } from "vitest"; +import { assess, type AssessmentInput } from "./assessment.js"; +import { assessedGate, assessedPullGate } from "./assessed-gate.js"; +import { parsePlaybook, type Playbook } from "./config.js"; +import { comment, issue, parkedWorker, pull } from "./fixtures.js"; +import { approvalMarkerLine, type PrGate } from "./gate.js"; +import type { BigDecision } from "./decisions.js"; +import { MIGRATIONS, createStore, readyStateSchema, type StatusRecord } from "./store.js"; +import { LINEAR_TICKETS } from "./templates.js"; +import type { EntitySnapshot } from "./source-contract.js"; +import type { WakeSourceInput } from "./wake-source.js"; + +const tickets: Playbook = (() => { + const p = parsePlaybook(LINEAR_TICKETS, "linear-tickets"); + if (!p.ok) throw new Error(p.error); + return p.value; +})(); + +const head = "aaaaaaa1"; +const green = { checks: { state: "success", failing: [] } }; +const noSources: WakeSourceInput = { hold: null, holdBehind: [], mergeBehind: [], holdStack: [], deployments: {}, runningWorkers: 0, openEscalations: 0, openNeeds: 0, pullRequestWatch: false }; + +const noReviewMarker = comment({ id: "m1", author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); +const ownerMarker = comment({ id: "m2", author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); +const declinedMarker = comment({ id: "m3", author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); +const projectApprovalMarker = (id: string) => comment({ id, author: "trotterdylan", body: approvalMarkerLine({ sha: head, entry: null, verdict: "approved" }), signedBy: "thr_project", createdAt: "2026-10-14T16:10:00Z" }); +const ownerUnsignedApproval = comment({ id: "oa", author: "jane", body: `Approved ${head} from the Stewards page`, signedBy: null, createdAt: "2026-10-14T17:00:00Z" }); + +/** A gate-met own pull request plus the second open own pull request the rule requires. */ +const gateMetPull = (key: string, url: string) => pull({ key, url, comments: [noReviewMarker] }, { headSha: head, ...green }); +const secondOpenPull = (key: string, url: string) => pull({ key, url }, { headSha: "bbbbbbb2" }); +const own = (...pulls: EntitySnapshot[]): Set => new Set(pulls.flatMap((p) => [p.key.toLowerCase(), (p.url ?? "").toLowerCase()]).filter((s) => s !== "")); + +const status = (waitingOn: string | null): StatusRecord => ({ phase: "In Progress", summary: "s", nextAction: "n", actor: "other", waitingOn, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at: 1 }); + +const binding = (over: Partial = {}): AssessmentInput["binding"] => ({ + id: "b1", + entityKey: "ENG-12", + kind: "ticket", + ready: readyStateSchema.parse({}), + stage: "build", + ending: null, + hold: null, + deployments: {}, + requeueUntil: null, + noWakeSource: false, + status: null, + createdAt: 1, + advancedAt: 1, + phase: "In Progress", + ...over, +}); + +function input(over: Partial = {}): AssessmentInput { + return { + binding: binding(), + observed: { entity: issue({ state: "In Progress" }), pulls: [] }, + ownPulls: new Set(), + decisions: new Map(), + projectApprovals: [], + workers: [], + escalations: [], + needs: [], + sources: { ...noSources }, + playbook: tickets, + currentSpecHash: "", + now: 1_000_000, + ...over, + }; +} + +/** An in-memory store with the assessment tables, as `assessment.test.ts` builds one. */ +function store() { + const db = new Database(":memory:"); + for (const sql of MIGRATIONS) db.exec(sql); + const s = createStore(db, () => 1_000_000); + const b = s.create({ + projectId: "p1", + source: "linear", + entityId: "uuid-12", + entityKey: "ENG-12", + url: null, + title: "Fix login", + kind: "ticket", + playbook: "linear-tickets", + playbookVersion: "v1", + parentBindingId: null, + phase: "In Progress", + stage: "build", + }); + return { s, b }; +} + +/** Store the assessment for a fixture, so `assessedGate` has a copy to read. */ +function storeAssessment(s: ReturnType["s"], i: AssessmentInput): void { + const a = assess(i); + s.recordAssessment({ bindingId: i.binding.id, at: i.now, gate: a.gate, worker: a.worker, liveness: a.liveness }); +} + +describe("the single stored-gate read (BB-322)", () => { + it("reads the stored gate when it is current, and computes and stores it when it is missing", () => { + const { s, b } = store(); + const first = gateMetPull("acme/web#7", "https://github.com/acme/web/pull/7"); + const second = secondOpenPull("acme/web#8", "https://github.com/acme/web/pull/8"); + const i = input({ + binding: binding({ id: b.id }), + observed: { entity: issue({ state: "In Progress" }), pulls: [first, second] }, + ownPulls: own(first, second), + decisions: new Map([ + ["acme/web#7", "user"], + ["acme/web#8", "user"], + ]), + workers: [parkedWorker()], + }); + // No stored assessment yet: the read computes and stores one. + expect(s.assessment(b.id)).toBeNull(); + const g = assessedGate(s, b, first, i.now); + expect(g).toMatchObject({ gateMet: true, lane: "no-review" }); + expect(s.assessment(b.id)).not.toBeNull(); + // The second read returns the stored copy, not a fresh computation. + expect(assessedGate(s, b, first, i.now + 1)).toMatchObject({ gateMet: true, lane: "no-review" }); + }); + + it("recomputes for the pull's current head sha and never returns a stale met gate", () => { + const { s, b } = store(); + const first = gateMetPull("acme/web#7", "https://github.com/acme/web/pull/7"); + const second = secondOpenPull("acme/web#8", "https://github.com/acme/web/pull/8"); + const i = input({ + binding: binding({ id: b.id }), + observed: { entity: issue({ state: "In Progress" }), pulls: [first, second] }, + ownPulls: own(first, second), + decisions: new Map([ + ["acme/web#7", "user"], + ["acme/web#8", "user"], + ]), + workers: [parkedWorker()], + }); + storeAssessment(s, i); + expect(assessedGate(s, b, first, i.now)).toMatchObject({ gateMet: true }); + // The head moves and its checks are still pending: the stored met answer is + // stale and must not count. + const moved = pull({ key: "acme/web#7", url: "https://github.com/acme/web/pull/7", comments: [noReviewMarker] }, { headSha: "ccccccc3", checks: { state: "pending", failing: [] } }); + expect(assessedGate(s, b, moved, i.now + 1)).toMatchObject({ gateMet: false, headSha: "ccccccc3" }); + }); + + // BB-322 owner review: a push can add a file that moves the pull from the + // project steward's lane to the owner's. The stored mark must not survive the + // head move, or a recorded project approval would let a merge path act on a + // change the owner should approve. + it("re-derives the decide mark from the changed files when the head moves", () => { + const { s, b } = store(); + const decisions: BigDecision[] = [ + { text: "A user entry", decide: "user", paths: ["bb-gate/hooks/hooks.go"] }, + { text: "A project entry", decide: "project", paths: ["bb-gate/docs/hooks.md"] }, + ]; + const entity = pull({ key: "acme/web#7", url: "https://github.com/acme/web/pull/7", comments: [ownerMarker, projectApprovalMarker("pa1")] }, { headSha: head, ...green, files: ["bb-gate/docs/hooks.md"] }); + s.recordProjectApproval({ bindingId: b.id, headSha: head, entry: null, byThread: "thr_project", commentId: "pa1", verdict: "approved" }); + const i = input({ + binding: binding({ id: b.id, kind: "review" }), + observed: { entity: issue({ state: "In Progress" }), pulls: [entity] }, + ownPulls: own(entity), + decisions: new Map([["acme/web#7", "project"]]), + projectApprovals: s.projectApprovals(b.id), + workers: [parkedWorker()], + }); + storeAssessment(s, i); + expect(assessedGate(s, b, entity, i.now, decisions)).toMatchObject({ gateMet: true, decision: "project" }); + // The head moves and the changed files now match a `user` entry: the mark + // is re-derived, the recorded project approval no longer counts, and the + // gate is not met. + const moved = pull({ key: "acme/web#7", url: "https://github.com/acme/web/pull/7", comments: [ownerMarker, projectApprovalMarker("pa1")] }, { headSha: "ccccccc3", ...green, files: ["bb-gate/hooks/hooks.go"] }); + expect(assessedGate(s, b, moved, i.now + 1, decisions)).toMatchObject({ gateMet: false, decision: "user" }); + }); + + it("covers a project-mark approved pull, with a parked worker and a second open own pull", () => { + const { s, b } = store(); + const entity = pull({ key: "acme/web#7", url: "https://github.com/acme/web/pull/7", comments: [ownerMarker, projectApprovalMarker("pa1")] }, { headSha: head, ...green }); + const second = secondOpenPull("acme/web#8", "https://github.com/acme/web/pull/8"); + const i = input({ + binding: binding({ id: b.id, kind: "review" }), + observed: { entity: issue({ state: "In Progress" }), pulls: [entity, second] }, + ownPulls: own(entity, second), + decisions: new Map([ + ["acme/web#7", "project"], + ["acme/web#8", "user"], + ]), + projectApprovals: [], + workers: [parkedWorker()], + }); + s.recordProjectApproval({ bindingId: b.id, headSha: head, entry: null, byThread: "thr_project", commentId: "pa1", verdict: "approved" }); + i.projectApprovals = s.projectApprovals(b.id); + storeAssessment(s, i); + expect(assessedGate(s, b, entity, i.now)).toMatchObject({ gateMet: true, decision: "project", projectApproved: true, lane: "owner-reviewed" }); + }); + + it("covers the owner's unsigned approval on a project-placed pull (BB-321), with a parked worker and a second open own pull", () => { + const { s, b } = store(); + const entity = pull({ key: "acme/web#7", url: "https://github.com/acme/web/pull/7", comments: [ownerMarker, ownerUnsignedApproval] }, { headSha: head, ...green }); + const second = secondOpenPull("acme/web#8", "https://github.com/acme/web/pull/8"); + const i = input({ + binding: binding({ id: b.id, kind: "review" }), + observed: { entity: issue({ state: "In Progress" }), pulls: [entity, second] }, + ownPulls: own(entity, second), + decisions: new Map([ + ["acme/web#7", "project"], + ["acme/web#8", "user"], + ]), + projectApprovals: [{ commentId: "pa-other", verdict: "approved" }], + workers: [parkedWorker()], + }); + storeAssessment(s, i); + expect(assessedGate(s, b, entity, i.now)).toMatchObject({ gateMet: true, decision: "user", ownerApproved: true, projectApproved: false }); + }); + + it("covers a declined reviewer marker, with a parked worker and a second open own pull", () => { + const { s, b } = store(); + const entity = pull({ key: "acme/web#7", url: "https://github.com/acme/web/pull/7", comments: [declinedMarker] }, { headSha: head, ...green }); + const second = secondOpenPull("acme/web#8", "https://github.com/acme/web/pull/8"); + const i = input({ + binding: binding({ id: b.id }), + observed: { entity: issue({ state: "In Progress" }), pulls: [entity, second] }, + ownPulls: own(entity, second), + decisions: new Map([ + ["acme/web#7", "user"], + ["acme/web#8", "user"], + ]), + workers: [parkedWorker()], + }); + storeAssessment(s, i); + const g: PrGate = assessedGate(s, b, entity, i.now); + expect(g.gateMet).toBe(false); + expect(g.missing).toContain("changes-requested"); + }); + + it("treats null/empty changed files as the user's, fail closed", () => { + const entity = pull({ comments: [ownerMarker] }, { headSha: head, ...green, files: [] }); + expect(assessedPullGate(binding(), entity, "user", []).decision).toBe("user"); + // `assessedGate`'s refresh has no decide list, so a never-assessed pull + // defaults to the owner's mark whatever its files; the gate is not met + // without the owner's approval. + const { s, b } = store(); + expect(assessedGate(s, b, entity, 1_000_000)).toMatchObject({ gateMet: false, decision: "user", needsOwnerApproval: true }); + }); + + it("keeps a dated wait from being read as a stall in the stored assessment it writes", () => { + // A small guard that the refresh writes the whole gate shape, not only the + // pull it was asked about. + const { s, b } = store(); + const entity = gateMetPull("acme/web#7", "https://github.com/acme/web/pull/7"); + const i = input({ binding: binding({ id: b.id, status: status("the vendor's reply"), requeueUntil: 2_000_000 }), observed: { entity: issue(), pulls: [entity] }, ownPulls: own(entity), decisions: new Map([["acme/web#7", "user"]]) }); + storeAssessment(s, i); + assessedGate(s, b, entity, i.now); + const stored = s.assessment(b.id)!.gate as { pulls: Array<{ pull: string; met: boolean }> }; + expect(stored.pulls).toHaveLength(1); + expect(stored.pulls[0]).toMatchObject({ pull: "acme/web#7", met: true }); + }); +}); diff --git a/plugins/stewards/assessed-gate.ts b/plugins/stewards/assessed-gate.ts new file mode 100644 index 00000000..494893ad --- /dev/null +++ b/plugins/stewards/assessed-gate.ts @@ -0,0 +1,147 @@ +// BB-322 (child of BB-291, criterion 1): the one place a pull request's merge +// gate is computed, and the read of the stored per-binding assessment every +// surface uses. `pullGate` is the single `prGate` call site outside the +// assessment module (`assessment.ts` calls `assessedPullGate`, never `prGate`); +// `assessedGate` reads the assessment the reconcile stored and, when it is +// missing or not for the pull's current head sha, computes the pull's gate and +// stores it rather than falling back to a surface's own predicate. A missing +// or stale assessment therefore never counts as met (fail closed). +import { createHash } from "node:crypto"; +import { decideForPull, type BigDecision, type DecideMark } from "./decisions.js"; +import { prGate, type PrGate, type PrGateOptions, type ProjectApprovalRecord } from "./gate.js"; +import { productGateOptions } from "./reconcile.js"; +import type { EntitySnapshot } from "./source-contract.js"; +import type { Binding } from "./store.js"; + +/** The single `prGate` call site outside `assessment.ts` (BB-322 criterion 1). */ +export function pullGate(entity: EntitySnapshot, options: PrGateOptions = {}): PrGate { + 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) }; +} + +/** + * A fingerprint of everything `prGate` reads for one pull request. The stored + * assessment is reused only when it carries this same fingerprint, so a + * 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"); +} + +/** + * The gate for one own pull request: the decide-list mark and the BB-321 + * forwarded-owner rule. The decide list places the pull request, but the + * project steward may forward a `project` entry's approval escalation to the + * owner (BB-192). The owner's unsigned approval is then the gate, so a gate + * that still demanded a project-steward approval would be stricter than the + * lane rules. The escalation is resolved once the owner answers and is no + * longer in the rows the reconcile holds, so the approval it produced is the + * 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); + const probe = pullGate(entity, options); + return mark === "project" && probe.ownerApproved && !probe.projectApproved ? pullGate(entity, { ...options, decision: "user" }) : probe; +} + +/** The full gate stored per own pull request, plus the key and input fingerprint it names. */ +export type StoredGate = PrGate & { pull: string; met: boolean; key: string }; + +/** The gate half of a stored assessment, as `store.assessment` returns it. */ +export type StoredAssessmentGate = { + pulls?: StoredGate[]; + met?: boolean; + decision?: DecideMark; + missing?: string | null; + readyPassed?: boolean | null; +}; + +/** The store reads the assessment read/refresh needs. */ +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[]; +}; + +const lc = (s: string | null | undefined): string => (s ?? "").toLowerCase(); + +/** The per-pull gates a stored assessment holds, or an empty list. */ +export function storedGates(gate: unknown): StoredGate[] { + const pulls = (gate as StoredAssessmentGate | null | undefined)?.pulls; + return Array.isArray(pulls) ? pulls : []; +} + +/** The stored gate entry for a pull request, whatever head sha it names, or null. */ +export function storedPullGate(gate: unknown, pull: EntitySnapshot): StoredGate | null { + const pulls = (gate as StoredAssessmentGate | null | undefined)?.pulls; + if (!Array.isArray(pulls)) return null; + const key = lc(pull.key); + const url = lc(pull.url); + return pulls.find((p) => lc(p.pull) === key || (url !== "" && lc(p.pull) === url)) ?? null; +} + +/** + * The stored gate entry for a pull request only when it is for the pull's + * current head sha; a missing or head-stale assessment returns null and never + * counts as met (BB-322 limit 3, fail closed). + */ +export function currentStoredGate(gate: unknown, pull: EntitySnapshot): StoredGate | null { + const found = storedPullGate(gate, pull); + if (found === null) return null; + return found.headSha === (pull.pull?.headSha ?? null) ? found : null; +} + +/** + * Read the binding's stored assessment's gate for one pull request, computing + * and storing it when there is none for the pull's current head sha. This is + * the single read/refresh site every merge-gate surface goes through; the + * decide-list mark is the one the last assessment recorded (a head that moved + * keeps its lane) and, when the pull request was never assessed, the mark its + * snapshot's changed files give under the binding's decide list (`bigDecisions`, + * empty means the owner's, fail closed). `forceMark` is the caller's own mark + * for a fact the stored assessment predates: the forward path passes `user` + * when the project steward has just forwarded a `project`-entry approval to + * the owner (BB-322 round 2), so the key changes and the read refreshes. + */ +export function assessedGate(store: AssessmentStore, binding: Binding, pull: EntitySnapshot, at: number, bigDecisions: readonly BigDecision[] = [], forceMark?: DecideMark): PrGate { + const row = store.assessment(binding.id); + const known = storedPullGate(row?.gate, pull); + // BB-322 owner review: the stored decide mark is reused only while the head + // is unchanged. A push can add a file that moves the pull between the owner's + // and the project steward's lane, so a moved head re-derives the mark from + // the snapshot's files. A caller without the decide list then gets the + // owner's mark (fail closed), never a stale `project` that a recorded project + // approval would let a merge path act on before the next reconcile. + 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); + // 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 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] : []; + const index = pulls.findIndex((p) => lc(p.pull) === lc(pull.key)); + if (index >= 0) pulls[index] = entry; + else pulls.push(entry); + const gateState: StoredAssessmentGate = { + ...stored, + pulls, + met: pulls.every((p) => p.met), + decision: pulls[0]?.decision ?? "user", + missing: pulls.find((p) => !p.met)?.missing ?? null, + readyPassed: stored.readyPassed ?? null, + }; + store.recordAssessment({ bindingId: binding.id, at, gate: gateState, worker: row?.worker ?? null, liveness: row?.liveness ?? null }); + return gate; +} diff --git a/plugins/stewards/assessment.test.ts b/plugins/stewards/assessment.test.ts index 04bf4475..51416b74 100644 --- a/plugins/stewards/assessment.test.ts +++ b/plugins/stewards/assessment.test.ts @@ -67,7 +67,6 @@ function input(over: Partial = {}): AssessmentInput { binding: binding(), observed: { entity: issue({ state: "In Progress" }), pulls: [] }, ownPulls: new Set(), - gateMetPulls: new Set(), decisions: new Map(), projectApprovals: [], workers: [], @@ -94,7 +93,6 @@ function bb266(secondOpen: boolean): AssessmentInput { return input({ observed: { entity: issue({ state: "In Progress" }), pulls }, ownPulls: own(...pulls), - gateMetPulls: new Set(["acme/web#7"]), decisions: new Map(pulls.map((p) => [p.key.toLowerCase(), "user" as const])), workers: [parkedWorker({ result: "Waiting on the owner's approval of acme/web#7." })], sources: { ...noSources }, @@ -224,7 +222,6 @@ describe("the shadow assessment: the page refusal text (BB-292 #3)", () => { const i = input({ observed: { entity: issue({ state: "In Progress" }), pulls: [first, second] }, ownPulls: own(first, second), - gateMetPulls: new Set(["acme/web#7"]), decisions: new Map([ ["acme/web#7", "user"], ["acme/web#8", "user"], diff --git a/plugins/stewards/assessment.ts b/plugins/stewards/assessment.ts index 8256c049..b4381f1d 100644 --- a/plugins/stewards/assessment.ts +++ b/plugins/stewards/assessment.ts @@ -10,7 +10,8 @@ // over the same rows and returns every place the old answer and the assessment // disagree, so the divergence log can be read for several days before any // consumer reads the assessment. -import { prGate, type ProjectApprovalRecord } from "./gate.js"; +import { assessedPullGate, gateInputKey, pullGate } from "./assessed-gate.js"; +import type { PrGate, ProjectApprovalRecord } from "./gate.js"; import { gateState } from "./ready-gate.js"; import { anyWorkerInFlight, idleInActiveStage, observedStall, productGateOptions, runningWorkerReason, stuckDue, type IdleBinding } from "./reconcile.js"; import { hasLiveWakeSource, type WakeSourceInput } from "./wake-source.js"; @@ -25,21 +26,18 @@ export const ASSESSMENT_DIVERGENCE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; /** The most divergence rows kept, newest first; the reconcile prunes the rest. */ export const ASSESSMENT_DIVERGENCE_MAX_ROWS = 500; -/** The merge gate for one own pull request, derived with every input the plugin has. */ -export type AssessedGate = { +/** + * The merge gate for one own pull request, derived with every input the + * plugin has. It is the full `PrGate` (BB-322: every surface reads it from + * the stored assessment) plus the pull request's key and the `met` shorthand + * the assessment's own callers use. + */ +export type AssessedGate = PrGate & { /** The pull request's key (owner/repo#N), an id, never free text. */ pull: string; met: boolean; - lane: string | null; - missing: string | null; - decision: DecideMark; - ownerApproved: boolean; - projectApproved: boolean; - checksGreen: boolean; - escalated: boolean; - reason: "product" | null; - needsOwnerApproval: boolean; - needsProjectApproval: boolean; + /** The fingerprint of the gate's inputs, so a stored answer is reused only when nothing changed (BB-210). */ + key: string; }; /** @@ -99,8 +97,12 @@ export type AssessmentInput = { observed: Observed; /** The binding's own pull keys and URLs, lowercased (BB-52 rule 0). */ ownPulls: ReadonlySet; - /** Own pull keys whose gate is met (BB-285). */ - gateMetPulls: ReadonlySet; + /** + * The pull requests to gate (BB-322): the binding's own plus every linked one + * that belongs to it, the same set `syncNeeds` acts on. Defaults to + * `ownPulls`, so a caller that does not need the broader set is unchanged. + */ + gatePulls?: ReadonlySet; /** The decide-list mark for each own pull, from the files the snapshot already carries. */ decisions: ReadonlyMap; /** The plugin's recorded project approvals for the binding. */ @@ -122,6 +124,17 @@ const lc = (s: string | null | undefined): string => (s ?? "").toLowerCase(); const isOwn = (e: EntitySnapshot, own: ReadonlySet): boolean => (e.key !== "" && own.has(lc(e.key))) || (e.url !== null && e.url !== "" && own.has(lc(e.url))); +/** + * Whether the project steward forwarded this pull request's approval escalation + * to the owner (BB-192): an open `approval` escalation for the pull, routed to + * the user with `resolutionKind: "approve-decline"`. A `project`-entry pull is + * the owner's from the forward on (BB-322 blocker 1). + */ +function forwardedToOwner(escalations: readonly Escalation[], e: EntitySnapshot): boolean { + const url = lc(e.url ?? e.key); + return escalations.some((x) => x.status === "open" && x.kind === "approval" && x.route === "user" && x.resolutionKind === "approve-decline" && lc(x.url) === url); +} + /** Every own pull request the binding's workers opened, the binding's own entity first. */ export function ownPullEntities(observed: Observed, own: ReadonlySet): EntitySnapshot[] { return [observed.entity, ...observed.pulls].filter((e) => e.pull !== null && isOwn(e, own)); @@ -140,33 +153,19 @@ export function assessWorker(workers: readonly Worker[]): AssessedWorker { export function assess(input: AssessmentInput): Assessment { const { binding, observed, ownPulls, decisions, projectApprovals, workers, escalations, needs, sources, playbook, currentSpecHash, now } = input; const pulls: AssessedGate[] = []; - for (const e of ownPullEntities(observed, ownPulls)) { - const mark = decisions.get(lc(e.key)) ?? "user"; - const options = { decision: mark, projectApprovals, ...productGateOptions(binding, e) }; - const probe = prGate(e, options); - // BB-321: the decide list places the pull request, but the project steward - // may forward a `project` entry's approval escalation to the owner - // (BB-192). The owner's unsigned approval is then the gate, so a gate that - // still demanded a project-steward approval would be stricter than the - // lane rules. The escalation is resolved once the owner answers and is no - // longer in the rows the reconcile holds, so the approval it produced is - // the fact that remains. A recorded project-steward approval keeps the - // pull request the project steward's. - const g = mark === "project" && probe.ownerApproved && !probe.projectApproved ? prGate(e, { ...options, decision: "user" }) : probe; - pulls.push({ - pull: e.key, - met: g.gateMet, - lane: g.lane, - missing: g.missing, - decision: g.decision, - ownerApproved: g.ownerApproved, - projectApproved: g.projectApproved, - checksGreen: g.checksGreen, - escalated: g.escalated, - reason: g.reason, - needsOwnerApproval: g.needsOwnerApproval, - needsProjectApproval: g.needsProjectApproval, - }); + const gatePulls = input.gatePulls ?? ownPulls; + for (const e of ownPullEntities(observed, gatePulls)) { + // BB-322 blocker 1: a `project` entry the project steward forwarded to the + // owner (BB-192) is the owner's from the moment of the forward, not only + // after they approve. The forward is an open `approval` escalation routed + // to the user with the pull's url and `resolutionKind: "approve-decline"` + // (a normal owner-lane approval is the same shape but the mark is already + // `user`). Without this the gate says `project`, the page refuses the + // 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 idleBinding: IdleBinding = { stage: binding.stage, @@ -176,7 +175,9 @@ export function assess(input: AssessmentInput): Assessment { requeueUntil: binding.requeueUntil, workers, ownPulls, - gateMetPulls: input.gateMetPulls, + // BB-322: derived from the one assessment, so no surface computes the gate + // again; the old `gateMetPulls` input is retired. + gateMetPulls: new Set(pulls.filter((p) => p.met).map((p) => p.pull.toLowerCase())), escalations, needs, }; @@ -224,12 +225,16 @@ const verdict = (met: boolean, missing: string | null): string => (met ? "met" : * - `workerInFlight`, `runningWorkerReason`, `idleInActiveStage`, * `hasLiveWakeSource`: a parked `finished` worker is in flight to the first * and not mid-turn, idle and not a live source to the others (BB-292 #1). - * - `approvals.gate`: `approvals.ts` builds `prGate` without the decide mark - * or the recorded project approvals (BB-292 #2). - * - `approvals.pageRefusal`: the page action's refusal falls through to its - * `??` fallback on a met gate and says "not observed yet" (BB-292 #3). + * - `approvals.gate`: the old surface gate, built without the decide mark or + * the recorded project approvals, against the assessment (BB-292 #2). + * - `approvals.pageRefusal`: the page action's refusal on a met gate (BB-292 #3). * - `noWakeSource`: the report-time flag against the stall recomputed from * the observable rows. + * + * BB-322 keeps the gate comparison as the soak's evidence that the consumer's + * answer still matches the predicate it retired; a new `approvals.gate` row is + * a real difference, not a fixture. It is read through `pullGate`, the same + * single `prGate` site, so no second call site appears. */ export function compare(input: AssessmentInput, assessment: Assessment): Divergence[] { const { binding, observed, ownPulls, projectApprovals, workers } = input; @@ -252,7 +257,7 @@ export function compare(input: AssessmentInput, assessment: Assessment): Diverge for (const e of ownPullEntities(observed, ownPulls)) { const assessed = assessment.gate.pulls.find((p) => lc(p.pull) === lc(e.key)); if (assessed === undefined) continue; - const oldGate = prGate(e, productGateOptions(binding, e)); + const oldGate = pullGate(e, productGateOptions(binding, e)); const gateInputs: Divergence["inputs"] = { binding: binding.id, pull: e.key, diff --git a/plugins/stewards/read-counts.test.ts b/plugins/stewards/read-counts.test.ts index 11d57b4d..28dd02ef 100644 --- a/plugins/stewards/read-counts.test.ts +++ b/plugins/stewards/read-counts.test.ts @@ -160,8 +160,13 @@ describe("a reconcile pass over a fixed binding set (BB-297)", () => { expect(reconcile.sourceCalls).toBe(sourceRpcCalls() - beforeSourceRpc + githubCalls.length); // The pinned baseline. Update these numbers only in a child that explains // the change in its pull request body; never loosen them to inequalities. - expect(reconcile).toEqual({ storeReads: 190, sourceCalls: 12, reconciles: 4, bindings: 4 }); - expect(wake).toEqual({ storeReads: 16, sourceCalls: 0, wakes: 1 }); + // BB-322 lowered the reconcile reads 190 → 183: `syncPullApproval` no + // longer re-reads the recorded project approvals (and no longer computes a + // second gate) because the reconcile hands it the one assessment it just + // built. The wake fell 16 → 15 for the same reason: `wakeInner` reads the + // assessment the reconcile passed in, not `projectApprovals` again. + expect(reconcile).toEqual({ storeReads: 183, sourceCalls: 12, reconciles: 4, bindings: 4 }); + expect(wake).toEqual({ storeReads: 15, sourceCalls: 0, wakes: 1 }); }); it("reports the pass in bb stewards stats, text and JSON (BB-297)", async () => { diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 9aca1c48..52946f46 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -8196,6 +8196,50 @@ describe("needs you items", () => { expect(t2.hooks.store.openNeeds(b2.id).some((n) => n.kind === "approve-pr")).toBe(true); }); + // BB-322 blocker 1: a project-entry pull the project steward forwards to the + // owner (BB-192) is the owner's from the forward on, so the page's Approve + // acts. The assessment keys on the open user-routed approval escalation. + it("lets the owner approve a project-entry pull the project steward forwarded (BB-322 blocker 1)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] } })); + t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + const project = t.spawns[0]!.id; + const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval" && x.resolutionKind === "approve-decline")!; + expect(esc.route).toBe("project"); + const forwarded = await t.tool("steward_update", { binding: "ENG-12", forward: esc.id }, project); + expect(forwarded.error, forwarded.text).toBe(false); + // The forward itself makes the gate the owner's: the item is actionable and + // the page approves as the owner, with no reconcile in between. + const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "approve-pr")!; + expect(need).toBeDefined(); + const board = (await t.harness.callRpc("stewardsBoard", { projectId: "p1" })) as { board: { needs: Array<{ id: string; actionable: boolean; why: string | null }> } }; + expect(board.board.needs.find((n) => n.id === need.id)).toMatchObject({ actionable: true, why: null }); + const approved = await t.harness.callRpc("stewardsNeedAction", { needId: need.id, action: "approve" }, client); + expect(approved).toMatchObject({ ok: true }); + }); + + // BB-322 blocker 2: a review binding's own entity is a pull request, not a + // linked one. It must be gated, or the project entry routes to the owner and + // every wake says the assessment is not available. + it("gates a review binding's own pull request, so a project entry routes to the project steward (BB-322 blocker 2)", async () => { + const t = await setup(); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] } })); + t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); + await t.ring("github", "acme/web#7"); + const b = t.hooks.store.find("acme/web#7")!; + expect(b.kind).toBe("review"); + expect(t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval")).toMatchObject({ route: "project" }); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "approve-pr")).toBe(false); + // The assessment holds the pull, so the steward's wake names the gate + // instead of the not-available fallback. + const wake = t.spawns.find((s) => s.id === b.threadId)?.prompt ?? ""; + expect(wake).toContain("Lane gate:"); + expect(wake).not.toContain("the assessment is not available for this head"); + }); + // BB-51 criterion 5: one list feeds the standing rules and the refusal. it("derives the needs a steward may file from one list, so the rules and the refusal cannot drift (BB-51)", async () => { expect([...ESCALATED_NEED_KINDS, ...STEWARD_NEED_KINDS].sort()).toEqual([...NEEDS_KINDS].sort()); @@ -14896,7 +14940,7 @@ describe("bb stewards divergences (BB-293)", () => { expect(rows.find((r) => r.surface === "workerInFlight")).toMatchObject({ old: "in-flight", new: "parked", count: 1 }); }); - it("swallows a failure inside the shadow assessment and keeps reconciling", async () => { + it("swallows a failure inside the assessment and keeps reconciling", async () => { const t = await setup(); t.entities.set("uuid-12", issue()); // Force the assessment write to fail: the lazy prepared statement throws @@ -14905,9 +14949,9 @@ describe("bb stewards divergences (BB-293)", () => { await t.ring("linear", "uuid-12"); await t.flush(); // The reconcile completed past the failure: the binding's snapshot was - // stored and the warning names the shadow assessment. + // stored and the warning names the assessment. expect(t.hooks.store.find("ENG-12")!.lastSnapshot).not.toBeNull(); - expect(t.harness.logEntries.some((e) => e.level === "warn" && e.message.includes("shadow assessment failed"))).toBe(true); + expect(t.harness.logEntries.some((e) => e.level === "warn" && e.message.includes("assessment failed"))).toBe(true); }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index f9c3304b..c62aa1f0 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -88,7 +88,8 @@ import { type RolesFile, } from "./roles.js"; import { decideForPull, explainDecision, formatDecisionListing, globMatches, type BigDecision } from "./decisions.js"; -import { ASSESSMENT_DIVERGENCE_MAX_AGE_MS, ASSESSMENT_DIVERGENCE_MAX_ROWS, assess, compare, ownPullEntities, type AssessmentInput } from "./assessment.js"; +import { ASSESSMENT_DIVERGENCE_MAX_AGE_MS, ASSESSMENT_DIVERGENCE_MAX_ROWS, assess, compare, ownPullEntities, type Assessment, type AssessmentInput } from "./assessment.js"; +import { assessedGate, currentStoredGate, storedGates } from "./assessed-gate.js"; import { ADOPTION_CHOICES, adoptionChoices, adoptionHow, adoptionQuestion, alertClockAt, alertFingerprint, batchAlert, deadlineAt, depsLookSchema, dueDate, isBatchable, overdue, priorityFor, priorityLabel, priorityLabelForSeverity, reminderText, repoOfFingerprint, sightingOf, snoozeUntil, type DepsFinding, type DepsLook, type DepsTicket } from "./deps.js"; import { hostContract } from "./host-contract.js"; import { MULTI_REPO_ENVIRONMENT_PROVIDER_ID, MULTI_REPO_PLUGIN_ID, multiRepoEnvironmentFlags, multiRepoFreshEnvironment, multiRepoSource, nativeSource, projectSourceLabel, sourceRpcMissing, type FreshEnvironment, type NativeGitRead, type ProjectSource } from "./project-source.js"; @@ -102,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, placeReportedPull, specApprovedByProject, syncPullApproval, userApprovedOnEntity, userSaid, type ApprovalsContext } from "./approvals.js"; +import { approveOwnerReviewedPull, approvePrPageAction, declineOwnerReviewedPull, deliverApproval, fileForwardedApprovePrNeed, 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 { @@ -3201,7 +3202,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .filter((p): p is EntitySnapshot => p !== undefined && p.pull !== null && p.pull.merged !== true && lc(p.state) !== "closed") .filter((p) => pullBelongsToTicket(b, p, ownPulls)); if (open.length === 0) return false; - const gateMet = open.every((p) => prGate(p, { projectApprovals: projectApprovalsFor(b), ...productGateOptions(b, p) }).gateMet); + const gateMet = open.every((p) => assessedGate(store, b, p, now()).gateMet); return pullWatchCounts(b.kind, open.length, gateMet); } @@ -4255,13 +4256,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } /** Wake the steward, spawning its thread on the first wake. */ - async function wake(b: Binding, config: ProjectConfig, playbook: Playbook, observed: Observed, changes: string[], reason: WakeReason): Promise { + async function wake(b: Binding, config: ProjectConfig, playbook: Playbook, observed: Observed, changes: string[], reason: WakeReason, assessment: Assessment | null = null): Promise { // BB-297: the wake's own store reads and source calls are counted // separately from the reconcile that may have triggered it. - return readCounts.runWake(() => wakeInner(b, config, playbook, observed, changes, reason)); + return readCounts.runWake(() => wakeInner(b, config, playbook, observed, changes, reason, assessment)); } - async function wakeInner(b: Binding, config: ProjectConfig, playbook: Playbook, observed: Observed, changes: string[], reason: WakeReason): Promise { + async function wakeInner(b: Binding, config: ProjectConfig, playbook: Playbook, observed: Observed, changes: string[], reason: WakeReason, assessment: Assessment | null = null): Promise { const gate = gateState(playbook, b.ready, specHashFor(b, observed.entity)); const workerQuestions = await collectWorkerQuestions(b); const text = formatWake({ @@ -4279,7 +4280,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P changes, needs: store.openNeeds(b.id), own: ownThreads(b), - projectApprovals: projectApprovalsFor(b), + // BB-322: the wake reads the one assessment. A reconcile that just + // computed it passes it in, so the wake adds no store read; any other + // caller reads the stored copy. + assessedGates: assessment !== null ? assessment.gate.pulls : storedGates(store.assessment(b.id)?.gate), label: config.file.label, conflicts: conflictsOf(b, store.open(b.projectId)), deployments: b.deployments, @@ -4557,30 +4561,51 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } /** - * BB-293: the shadow assessment. Computed from the rows this reconcile has - * already read, stored beside the predicates it will replace, and compared - * with them. It decides nothing; the caller wraps the call in a try/catch, - * so a failure here can never change the reconcile's own result. + * BB-293/BB-322: the binding's assessment. Computed from the rows this + * reconcile has already read and stored for every merge-gate surface to + * read. BB-322 made it the consumer-facing source: the reconcile derives + * its own gate-met set from it and passes it to `syncNeeds`, and the + * page, CLI, wake and approvals read the stored copy. It is still wrapped + * in a try/catch by the caller so a failure cannot crash the reconcile; + * an absent assessment fails closed everywhere it is read. */ - function recordShadowAssessment( + function assessBinding( b: Binding, observed: Observed, workers: readonly Worker[], ownPulls: ReadonlySet, - gateMetPulls: ReadonlySet, playbook: Playbook, currentSpecHash: string, config: ProjectConfig, - ): void { + ): Assessment { + // BB-322: gate every pull request that belongs to the binding, the same + // set `syncNeeds` acts on, not only the worker-reported own ones. A + // linked pull request whose head names the ticket is the binding's even + // before a worker reports it, and the old surfaces computed its gate + // anyway; the assessment must hold it so they read it here. + const gatePulls = new Set(ownPulls); + // BB-322 blocker 2: a `pr`/`review` binding's own entity is a pull + // request, not a linked one, so `pullBelongsToTicket` never matches it. + // Gate it too, or the assessment holds no entry for it and the approval + // sync falls back to the owner's mark, changing the routing. + if (observed.entity.pull !== null) { + gatePulls.add(lc(observed.entity.key)); + if (observed.entity.url !== null) gatePulls.add(lc(observed.entity.url)); + } + for (const e of [observed.entity, ...observed.pulls]) { + if (e.pull === null || !pullBelongsToTicket(b, e, ownPulls)) continue; + gatePulls.add(lc(e.key)); + if (e.url !== null) gatePulls.add(lc(e.url)); + } // The decide-list mark comes from the files the snapshot already carries; // no extra GitHub read. Everything else is a row already in hand. const decisions = new Map(); - for (const e of ownPullEntities(observed, ownPulls)) decisions.set(lc(e.key), decideForPull(e.pull?.files ?? null, config.file.bigDecisions)); + for (const e of ownPullEntities(observed, gatePulls)) decisions.set(lc(e.key), decideForPull(e.pull?.files ?? null, config.file.bigDecisions)); const input: AssessmentInput = { binding: b, observed, ownPulls, - gateMetPulls, + gatePulls, decisions, projectApprovals: projectApprovalsFor(b), workers, @@ -4595,6 +4620,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P store.recordAssessment({ bindingId: b.id, at: input.now, gate: assessment.gate, worker: assessment.worker, liveness: assessment.liveness }); store.recordDivergences(compare(input, assessment)); store.pruneDivergences(ASSESSMENT_DIVERGENCE_MAX_AGE_MS, ASSESSMENT_DIVERGENCE_MAX_ROWS, input.now); + return assessment; } /** @@ -4873,24 +4899,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // diff only quiets them while one is, and the idle rule (BB-83) needs the // set for a binding whose worker has finished its turn. const ownPulls = await ownPullKeys(b, workers, observed); - // BB-285: which of the binding's own pull requests are gate-met. A - // gate-met own pull request is the plugin's to act on, so it does not - // suppress the idle wake (BB-83) the way an open one otherwise does. - const gateMetPulls = new Set(); - for (const e of [observed.entity, ...observed.pulls]) { - if (e.pull === null) continue; - const own = ownPulls.has(lc(e.key)) || (e.url !== null && e.url !== "" && ownPulls.has(lc(e.url))); - if (!own) continue; - if (prGate(e, { projectApprovals: projectApprovalsFor(b), ...productGateOptions(b, e) }).gateMet) gateMetPulls.add(e.key.toLowerCase()); - } - // BB-293: the shadow assessment, computed from the rows above. It decides - // nothing; a failure is logged and swallowed so the reconcile's own - // result never changes. + // BB-293/BB-322: the binding's assessment, computed once from the rows + // above and stored. BB-322 made it the consumer-facing source: the + // gate-met set below and every later surface read it. A failure is + // logged and swallowed so the reconcile's own result never changes; an + // absent assessment fails closed. + let assessment: Assessment | null = null; try { - recordShadowAssessment(b, observed, workers, ownPulls, gateMetPulls, playbook, currentSpec, config); + assessment = assessBinding(b, observed, workers, ownPulls, playbook, currentSpec, config); } catch (error) { - bb.log.warn(`stewards: shadow assessment failed for ${b.entityKey}: ${errorMessage(error)}`); + bb.log.warn(`stewards: assessment failed for ${b.entityKey}: ${errorMessage(error)}`); } + // BB-285: which of the binding's own pull requests are gate-met. A + // gate-met own pull request is the plugin's to act on, so it does not + // suppress the idle wake (BB-83) the way an open one otherwise does. + const gateMetPulls = new Set((assessment?.gate.pulls ?? []).filter((p) => p.met).map((p) => p.pull.toLowerCase())); // BB-203: an open need or `user` escalation keeps the worker's own pull // request activity loud, so the steward can reconcile the user's item. const userWaiting = store.openNeeds(b.id).length > 0 || store.openEscalations(b.id).some((x) => x.status === "open" && x.route === "user"); @@ -5001,7 +5024,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b.scheduleAsked.length > 0) clear.scheduleAsked = []; if (Object.keys(clear).length > 0) b = store.patch(b.id, clear); } - const approvalEvents = await syncNeeds(b, observed, playbook, changes); + const approvalEvents = await syncNeeds(b, observed, playbook, changes, assessment); // BB-264: `syncNeeds` records a derived stacked-PR merge hold on the // binding; re-read it so the status below and the wake see the hold. b = store.binding(b.id) ?? b; @@ -5125,7 +5148,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // An idle wake is a `changed` turn: there is no lifecycle instruction // for it, and the line under What changed is the whole wake (BB-83). const idleDue = lines.includes(IDLE_WAKE_TEXT); - if (await wake(b, config, playbook, observed, lines, reason ?? (idleDue ? "changed" : followingThrough(b) ? "follow-through" : b.requeueAt !== null && b.requeueAt <= now() && loudQueued === 0 ? "requeue" : "changed"))) await archiveFinishedWorkers(store.binding(b.id) ?? b); + if (await wake(b, config, playbook, observed, lines, reason ?? (idleDue ? "changed" : followingThrough(b) ? "follow-through" : b.requeueAt !== null && b.requeueAt <= now() && loudQueued === 0 ? "requeue" : "changed"), assessment)) await archiveFinishedWorkers(store.binding(b.id) ?? b); } /** @@ -6908,7 +6931,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // A reviewer's owner call makes the approval the owner's, whatever // the decide list matched, so the wake says so and the project // steward forwards rather than approves (BB-192). - escalated: prGate(pull, { projectApprovals: projectApprovalsFor(r.from), ...productGateOptions(r.from, pull) }).escalated, + escalated: assessedGate(store, r.from, pull, now(), config.file.bigDecisions).escalated, }; }), ); @@ -8000,7 +8023,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * every look, so the page only offers a button while it is true. The * `approve-pr` half lives in approvals.ts (BB-153). */ - async function syncNeeds(b: Binding, observed: Observed, playbook: Playbook, changes: Change[] = []): Promise { + async function syncNeeds(b: Binding, observed: Observed, playbook: Playbook, changes: Change[] = [], assessment: Assessment | null = null): Promise { // BB-203: an `approve-pr` item this call closes because an approval is // present is a mechanical status event. The page and project-steward // paths write it at once; this catches an approval observed on GitHub. @@ -8085,6 +8108,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const stackedOnMe: string[] = []; const recoveredPulls = [...b.stackedRecovered]; const recoveredBefore = new Set(recoveredPulls.map((k) => lc(k))); + // BB-322: the gate for a pull request from the assessment this reconcile + // just computed, so the approval sync reads the one assessment and never + // falls back to its own `prGate`. A pull request the assessment does not + // hold for its current head sha reads null and `syncPullApproval` + // refreshes it through the single `assessedGate` site. + const gateFor = (pull: EntitySnapshot) => currentStoredGate(assessment?.gate, pull); for (const pull of observedPulls(b, observed)) { const url = pull.url ?? pull.key; if (ownPulls !== null && !pullBelongsToTicket(b, pull, ownPulls)) { @@ -8097,7 +8126,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P continue; } const hadApprove = store.openNeeds(b.id).some((n) => n.kind === "approve-pr" && n.url === url); - const { gate: g, closed, approvalRaised: raised } = await syncPullApproval(approvalsCtx, b, pull, decisions); + const { gate: g, closed, approvalRaised: raised } = await syncPullApproval(approvalsCtx, b, pull, decisions, gateFor); if (raised) approvalRaised = true; if (hadApprove && !closed && (g.ownerApproved || g.projectApproved) && !store.openNeeds(b.id).some((n) => n.kind === "approve-pr" && n.url === url)) { events.push({ kind: "approved", pull: pull.key }); @@ -9112,7 +9141,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // The verdict is `prGate` with the project's approvals, exactly as the // page's Merge item and the wake compute it; the decide-list entry above // is what the plugin asks the owner or project steward for (BB-133). - const gate = prGate(pull, { projectApprovals: projectApprovalsFor(b), ...productGateOptions(b, pull) }); + const gate = assessedGate(store, b, pull, now(), decisions); return { ref: `${ref.repo}#${ref.number}`, binding: b.entityKey, @@ -9411,7 +9440,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // The same `prGate` with the project's approvals the page's Merge item // and the wake use, so the page, `bb stewards gate` and `bb stewards // merge` cannot disagree. - const gate = prGate(pull, { projectApprovals: projectApprovalsFor(b), ...productGateOptions(b, pull) }); + const gate = assessedGate(store, b, pull, now()); if (!gate.gateMet) return { ok: false, message: `The gate is not met: ${gate.missing ?? "the pull request could not be read"}.` }; const busy = runningWorkerReason(store.workers(b.id).filter((w) => w.threadId !== opts.exceptThreadId)); if (busy !== null) return { ok: false, message: `${busy.charAt(0).toUpperCase()}${busy.slice(1)} on this pull request.` }; @@ -11260,8 +11289,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const pull = b.lastSnapshot === null ? undefined : observedPulls(b, b.lastSnapshot).find((p) => [p.url, p.key, p.id].some((v) => v !== null && lc(v) === wanted)); // The decide list places the pull request, so a steward cannot // file the user's item for the project steward's lane (BB-51). - const decision = pull === undefined ? "user" : await placeReportedPull(approvalsCtx, pull, config?.file.bigDecisions ?? []); - const gate = pull === undefined ? null : prGate(pull, { decision, projectApprovals: projectApprovalsFor(b), ...productGateOptions(b, pull) }); + const gate = pull === undefined ? null : assessedGate(store, b, pull, now(), config?.file.bigDecisions ?? []); const holdable = gate !== null && (n.kind === "approve-pr" ? gate.needsOwnerApproval : gate.gateMet); if (!holdable) { refused.push(`${n.kind} for ${url === "" ? "the pull request" : url} not filed: ${gate?.missing ?? "the pull request has not been observed yet"}. The owner is asked only once the reviewer's marker says approved; the worker must run the build-tickets review loop first.`); @@ -11981,6 +12009,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // (BB-135). const before = new Set(store.openNeeds(target.id).map((n) => n.id)); await fileForwardedApprovePrNeed(approvalsCtx, target, forwarding); + // BB-322 round 2: the forward makes a `project`-entry pull the + // owner's immediately, not only at the next reconcile. Refresh + // the stored assessment's gate for it with the owner's mark, so + // the page item the owner was just pushed is actionable now. + const forwardedPull = target.lastSnapshot === null ? undefined : observedPulls(target, target.lastSnapshot).find((p) => (p.url ?? p.key) === forwarding.url); + if (forwardedPull !== undefined) assessedGate(store, target, forwardedPull, now(), [], "user"); await pushNewGateNeeds(target, before); } // BB-213: a forward that reaches the user files the real item, so @@ -12106,7 +12140,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (n.kind === "approve-pr" || n.kind === "merge") { const observed = b.lastSnapshot; const target = observed === null ? null : [observed.entity, ...observed.pulls].find((e) => (e.url ?? e.key) === n.url || e.key === n.url) ?? null; - const gate = target === null ? null : prGate(target, { projectApprovals: projectApprovalsFor(b), ...productGateOptions(b, target) }); + const gate = target === null ? null : assessedGate(store, b, target, now()); if (n.kind === "approve-pr") { actionable = gate?.needsOwnerApproval ?? false; why = actionable ? null : (gate?.missing ?? "the pull request has not been observed yet"); diff --git a/plugins/stewards/test-world.ts b/plugins/stewards/test-world.ts index f186a975..fa7279b2 100644 --- a/plugins/stewards/test-world.ts +++ b/plugins/stewards/test-world.ts @@ -264,7 +264,13 @@ export function world() { else if (args.method === "repoSet") out = { repos, primary, layout, error: null }; else if (args.method === "sourceSnapshot") { if (snapshotErrors.has(String(input.id))) throw new Error("Linear rate limited the read"); - out = { snapshot: entities.get(String(input.id)) ?? null }; + const entity = entities.get(String(input.id)) ?? null; + // BB-322: the real source's snapshot carries the pull request's changed + // files; the test world keeps them beside the entity. Merge them so the + // assessment's decide-list mark reads the same files `pullChangedFiles` + // returns, exactly as production does. + const files = entity !== null && entity.pull !== null ? githubFiles.get(entity.key) : undefined; + out = { snapshot: entity === null || entity.pull === null || files === undefined ? entity : { ...entity, pull: { ...entity.pull, files } } }; } else if (args.method === "sourceSetInterest") out = { ok: true }; else if (args.method === "sourceAdoptable") { diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index c7ce6ab9..dd07d218 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -7,6 +7,7 @@ import { comment, issue, parkedWorker, pull } from "./fixtures.js"; import { gateState } from "./ready-gate.js"; import { MIGRATIONS, RESOLUTION_KINDS, createStore } from "./store.js"; import { DEPS_PRS, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, DEPS_ALERTS, PLAYBOOK_TEMPLATES } from "./templates.js"; +import { assessedPullGate } from "./assessed-gate.js"; import { STANDING_RULES, BRIEF_PREFIX, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatRecords, formatWake, initiativeProgress, initiativeProgressFlag, spawnCommand, WAKE_MAX_CHARS, workerFinishNote, workerQuestion, type DigestRecords, type WakeInput } from "./wake.js"; import { BRIEF_MAX_CHARS } from "./server.js"; import type { OpsFinding } from "./ops.js"; @@ -33,11 +34,19 @@ function wakeInput(over: Partial = {}): WakeInput { const parsed = parsePlaybook(LINEAR_TICKETS, "linear-tickets"); if (!parsed.ok) throw new Error(parsed.error); const playbook = parsed.value; + const observed = over.observed ?? { entity: issue(), pulls: [] }; + // BB-322: the wake reads the stored per-pull gates. A test that does not + // hand them in gets them from the one gate computation the plugin uses. + const assessedGates = over.assessedGates ?? [observed.entity, ...observed.pulls].filter((e) => e.pull !== null).map((e) => { + const g = assessedPullGate(binding, e, "user", []); + return { ...g, pull: e.key, met: g.gateMet, key: "test" }; + }); return { reason: "changed", binding, playbook, - observed: { entity: issue(), pulls: [] }, + observed, + assessedGates, gate: gateState(playbook, binding.ready, ""), escalations: [], routedToMe: [], diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index cb765890..0b76b1ff 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -16,9 +16,9 @@ import type { DepsFinding, DepsLook } from "./deps.js"; import { ADOPTION_CHOICES, adoptionHow, dueDate } from "./deps.js"; import { NO_TOKEN, TOKEN_PAGE, TOKEN_SCOPES, TOKEN_SETTING, type SentryFinding, type SentryLook, type SentryReason } from "./sentry.js"; import type { AlertmanagerFinding, AlertmanagerLook, AlertmanagerReason } from "./alertmanager.js"; -import { newHumanComments, productGateOptions, unheardWait } from "./reconcile.js"; +import { newHumanComments, unheardWait } from "./reconcile.js"; import { reportedItem, type GateState } from "./ready-gate.js"; -import { prGate, type ProjectApprovalRecord } from "./gate.js"; +import { currentStoredGate, type StoredGate } from "./assessed-gate.js"; import { conflictsOf, openPull, type Conflict } from "./schedule.js"; import { SNAPSHOT_COMMENTS_MAX, type EntitySnapshot, type SessionWake, type SnapshotComment, type WorkflowRun } from "./source-contract.js"; import { needChoices, ESCALATED_NEED_KINDS, RESOLUTION_KINDS, STEWARD_NEED_KINDS, type Assumption, type Binding, type DepsDecision, type Escalation, type Lesson, type Need, type Observed, type Question, type Worker } from "./store.js"; @@ -322,8 +322,8 @@ export type WakeInput = { needs?: Need[]; /** The steward's thread and its workers': their comments are not news. */ own: ReadonlySet; - /** The plugin's own project-steward approval records, so the lane gate reads the same as the button. */ - projectApprovals?: readonly ProjectApprovalRecord[]; + /** The stored per-pull gates from the binding's assessment (BB-322), so the wake reads the one gate. */ + assessedGates?: readonly StoredGate[]; /** The project's adoption label. */ label: string; /** Per-pull-request deployment state (BB-53); empty when the playbook names no deployment target. */ @@ -349,7 +349,7 @@ function commentLines(comments: SnapshotComment[]): string[] { return lines; } -function entityLines(e: EntitySnapshot, cursor: string, own: ReadonlySet, heading: string, projectApprovals?: readonly ProjectApprovalRecord[], product?: { substantial: boolean | null; ticketApprovedSpec: boolean }): string[] { +function entityLines(e: EntitySnapshot, cursor: string, own: ReadonlySet, heading: string, assessedGates?: readonly StoredGate[]): string[] { const lines = [`### ${heading}`, ""]; lines.push(`- ${e.key}: ${e.title ?? "(untitled)"}${e.url === null ? "" : ` — ${e.url}`}`); lines.push(`- State: ${e.state}${e.stateType === null ? "" : ` (${e.stateType})`}`); @@ -361,15 +361,19 @@ function entityLines(e: EntitySnapshot, cursor: string, own: ReadonlySet lines.push(`- Branch: ${p.head ?? "?"} → ${p.base ?? "?"} at ${p.headSha?.slice(0, 7) ?? "?"}${p.headAuthor === null ? "" : ` (by ${p.headAuthor})`}`); lines.push(`- Checks: ${p.checks === null ? "none" : `${p.checks.state}${p.checks.failing.length > 0 ? ` — failing: ${p.checks.failing.join(", ")}` : ""}`}`); lines.push(`- Review decision: ${p.reviewDecision ?? "(none)"}; requested: ${p.requestedReviewers.join(", ") || "(none)"}`); - const gate = prGate(e, { projectApprovals, ...(product ?? {}) }); - const lane = gate.lane === null ? "" : `lane ${gate.lane}`; - if (gate.gateMet) { - const approved = gate.marker === null ? "?" : gate.marker.sha.slice(0, 7); - const head = gate.headSha === null ? "?" : gate.headSha.slice(0, 7); - const detail = [`reviewer approved ${approved}`, ...(approved === head ? [] : [`head ${head}`]), "checks green", ...(lane === "" ? [] : [lane])]; - lines.push(`- Lane gate: met (${detail.join(", ")})`); + const gate = currentStoredGate({ pulls: assessedGates }, e); + if (gate === null) { + lines.push(`- Lane gate: not met — the assessment is not available for this head; the plugin recomputes it on the next look.`); } else { - lines.push(`- Lane gate: not met — ${gate.missing}${lane === "" ? "" : ` (${lane})`}`); + const lane = gate.lane === null ? "" : `lane ${gate.lane}`; + if (gate.gateMet) { + const approved = gate.marker === null ? "?" : gate.marker.sha.slice(0, 7); + const head = gate.headSha === null ? "?" : gate.headSha.slice(0, 7); + const detail = [`reviewer approved ${approved}`, ...(approved === head ? [] : [`head ${head}`]), "checks green", ...(lane === "" ? [] : [lane])]; + lines.push(`- Lane gate: met (${detail.join(", ")})`); + } else { + lines.push(`- Lane gate: not met — ${gate.missing}${lane === "" ? "" : ` (${lane})`}`); + } } const latest = new Map(); for (const r of p.reviews) latest.set(r.author, `${r.state}${r.commit === null ? "" : ` at ${r.commit.slice(0, 7)}`}`); @@ -655,8 +659,8 @@ export function formatWake(input: WakeInput): string { const head = out.splice(0); out.push("", "## 4. Snapshot", ""); - out.push(...entityLines(e, binding.commentCursor, input.own, "The entity", input.projectApprovals, productGateOptions(binding, e))); - for (const pull of observed.pulls) out.push("", ...entityLines(pull, binding.commentCursor, input.own, `Linked pull request ${pull.key}`, input.projectApprovals, productGateOptions(binding, pull))); + out.push(...entityLines(e, binding.commentCursor, input.own, "The entity", input.assessedGates)); + for (const pull of observed.pulls) out.push("", ...entityLines(pull, binding.commentCursor, input.own, `Linked pull request ${pull.key}`, input.assessedGates)); if (input.workers.length > 0) { out.push("", "### Workers", ""); for (const w of input.workers) {