diff --git a/plugins/stewards/assessment.ts b/plugins/stewards/assessment.ts index 1f8a9ca0..3bf28755 100644 --- a/plugins/stewards/assessment.ts +++ b/plugins/stewards/assessment.ts @@ -21,6 +21,7 @@ import { waitBudgetMs, type Playbook, type WaitBudgetKind } from "./config.js"; import type { EntitySnapshot } from "./source-contract.js"; import type { Binding, Escalation, Need, Observed, Worker } from "./store.js"; import type { Wait, WaitKind } from "./wait.js"; +import type { ComposedAssessment } from "./contribution.js"; export type DecideMark = "project" | "user"; @@ -172,7 +173,7 @@ 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[] { +export 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)) ?? []); } @@ -182,7 +183,7 @@ const isOwn = (e: EntitySnapshot, own: ReadonlySet): boolean => (e.key !== "" && own.has(lc(e.key))) || (e.url !== null && e.url !== "" && own.has(lc(e.url))); /** A pull request the plugin can see is still open (not merged or closed). */ -const pullIsOpen = (e: EntitySnapshot): boolean => e.pull !== null && e.state !== "merged" && e.state !== "closed" && e.pull.merged !== true; +export const pullIsOpen = (e: EntitySnapshot): boolean => e.pull !== null && e.state !== "merged" && e.state !== "closed" && e.pull.merged !== true; /** Whether a pull request's review has been given: an approved review or marker at its head (BB-333). */ function reviewGiven(e: EntitySnapshot): boolean { @@ -205,7 +206,7 @@ function waitPullKey(ref: string): string | null { * wakes the binding without storing the snapshot. Null for another kind or a * ref the look could not read. */ -function waitFingerprint(wait: Wait | null, input: AssessmentInput): string | null { +export function waitFingerprint(wait: Wait | null, input: AssessmentInput): string | null { if (wait === null || (wait.kind !== "pull" && wait.kind !== "review")) return null; const key = waitPullKey(wait.ref); const e = key === null ? undefined : input.waitedPulls?.get(key); @@ -251,7 +252,7 @@ function waitReviewers(wait: Wait | null, input: AssessmentInput): readonly stri * workers, the other bindings, the page items and the date. The typed wait is * judged by its own kind, never by `hasLiveWakeSource`. */ -function typedWaitLive(wait: Wait, input: AssessmentInput): boolean { +export function typedWaitLive(wait: Wait, input: AssessmentInput): boolean { switch (wait.kind) { case "pull": case "review": { @@ -288,7 +289,7 @@ function typedWaitLive(wait: Wait, input: AssessmentInput): boolean { * 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 { +export 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); } @@ -433,8 +434,15 @@ const verdict = (met: boolean, missing: string | null): string => (met ? "met" : * 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. + * + * BB-380 (C2) adds the shadow composer's own surfaces: `compose.gate`, + * `compose.waits` and `compose.holds`. The composed answer is a refactor of + * today's derivation, so a row on one of them is a defect, not a fixture. The + * comparison runs only when the caller passes the composed answer; the C1 + * characterization tests call `compare` without one and see the seven surfaces + * they pin. */ -export function compare(input: AssessmentInput, assessment: Assessment): Divergence[] { +export function compare(input: AssessmentInput, assessment: Assessment, composed?: ComposedAssessment): Divergence[] { const { binding, observed, ownPulls, projectApprovals, workers } = input; const out: Divergence[] = []; const add = (surface: string, old: string, next: string, inputs: Divergence["inputs"]): void => { @@ -487,5 +495,35 @@ export function compare(input: AssessmentInput, assessment: Assessment): Diverge waitKind: binding.wait?.kind ?? null, waitLive: assessment.liveness.waitLive === true, }); + + // (5) BB-380 (C2): the shadow composer's gate, waits and holds against the + // assessment. The composed answer is computed from the same rows by the + // in-process contributors; a difference here is a defect in the refactor, so + // the row is the evidence the next slice's consumer can rely on the + // composed answer. Nothing reads the composed answer yet. + if (composed !== undefined) { + const pullText = (p: Assessment["gate"]["pulls"][number]): string => `${lc(p.pull)}:${p.met ? "met" : "unmet"}:${p.missing ?? ""}:${p.decision}`; + const composedGate = `${composed.gate.met ? "met" : "unmet"}|${composed.gate.decision}|${composed.gate.missing ?? ""}|${composed.gate.pulls.map(pullText).join(",")}`; + const assessedGate = `${assessment.gate.met ? "met" : "unmet"}|${assessment.gate.decision}|${assessment.gate.missing ?? ""}|${assessment.gate.pulls.map(pullText).join(",")}`; + if (composedGate !== assessedGate) add("compose.gate", assessedGate, composedGate, { binding: binding.id, pulls: composed.gate.pulls.length }); + + // The typed wait the assessment derived, against the composed item. A + // binding has at most one stored typed wait, so the match is by kind and ref. + const composedWait = composed.waits.find((w) => w.kind === (assessment.wait?.kind ?? "") && w.ref === (assessment.wait?.ref ?? "")) ?? null; + if (assessment.wait === null) { + if (composed.waits.length > 0) add("compose.waits", "none", composed.waits.map((w) => `${w.kind} ${w.ref}`).join(","), { binding: binding.id }); + } else if (composedWait === null) { + add("compose.waits", `${assessment.wait.kind} ${assessment.wait.ref}`, "none", { binding: binding.id }); + } else { + const composedWaitText = `${composedWait.live}|${composedWait.fingerprint ?? ""}|${composedWait.overdueMs ?? ""}`; + const assessedWaitText = `${assessment.liveness.waitLive}|${assessment.liveness.waited ?? ""}|${assessment.liveness.overdueMs ?? ""}`; + if (composedWaitText !== assessedWaitText) add("compose.waits", assessedWaitText, composedWaitText, { binding: binding.id, kind: assessment.wait.kind }); + } + + // The binding's holds: `idleInActiveStage` reads hold, ending and requeue. + const assessedHolds = [binding.hold !== null ? "hold" : null, binding.ending !== null ? "ending" : null, binding.requeueUntil !== null ? `requeue:${binding.requeueUntil > input.now}` : null].filter((x) => x !== null).join(","); + const composedHolds = composed.holds.map((h) => (h.id === "requeue" ? `requeue:${h.held}` : h.id)).join(","); + if (assessedHolds !== composedHolds) add("compose.holds", assessedHolds, composedHolds, { binding: binding.id }); + } return out; } diff --git a/plugins/stewards/contribution.test.ts b/plugins/stewards/contribution.test.ts new file mode 100644 index 00000000..0ca7864a --- /dev/null +++ b/plugins/stewards/contribution.test.ts @@ -0,0 +1,368 @@ +// BB-380 (BB-291 criterion 8, slice C2): unit tests for the per-source +// contribution interface, the github contributor and the composer, and the +// shadow equality that makes this slice a refactor: the composed gate, waits +// and holds equal today's `assess()` answer on the C1 characterization +// fixtures. Any divergence is a test failure here. +// +// The fixtures mirror the C1 characterization tests +// (`characterization-assessment.test.ts`, `characterization-wait-derivation.test.ts`): +// the BB-291 matrix (one binding kind at one stage, a gate-met own pull +// request, a second open own pull request and a parked worker), the typed +// waits, the project-approved gate and the report-time no-wake-source flag. +import { describe, expect, it } from "vitest"; +import { assess, compare, type AssessmentInput } from "./assessment.js"; +import { compose, composeAssessment, githubContributor, linearContributor, localContributor, type GateContribution, type SourceContribution } from "./contribution.js"; +import { parsePlaybook, type Playbook } from "./config.js"; +import { comment, issue, parkedWorker, pull } from "./fixtures.js"; +import { approvalMarkerLine } from "./gate.js"; +import { 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"; +import type { Wait } from "./wait.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 projectApprovalMarker = (id: string) => comment({ id, author: "trotterdylan", body: approvalMarkerLine({ sha: head, entry: null, verdict: "approved" }), signedBy: "thr_project", createdAt: "2026-10-14T16:10:00Z" }); + +/** A gate-met own pull request (no-review, green) plus the reviewer marker. */ +const gateMetPull = (key: string, url: string) => pull({ key, url, comments: [noReviewMarker] }, { headSha: head, ...green }); +/** A second, not-gate-met own pull request, so the fixture is not about a lone PR. */ +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 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, + }; +} + +/** The phase a stage sits in for the shipped `linear-tickets` playbook. */ +const PHASE: Record<"spec" | "build" | "review", string> = { spec: "Todo", build: "In Progress", review: "In Review" }; + +/** The BB-291 matrix fixture, mirroring `characterization-assessment.test.ts`. */ +function matrix(kind: "ticket" | "pr" | "review", stage: "spec" | "build" | "review"): AssessmentInput { + 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 entity = kind === "ticket" ? issue({ state: PHASE[stage] }) : first; + return input({ + binding: binding({ kind, stage, phase: PHASE[stage], entityKey: kind === "ticket" ? "ENG-12" : "acme/web#7" }), + observed: { entity, pulls: kind === "ticket" ? [first, second] : [second] }, + ownPulls: own(first, second), + decisions: new Map([ + ["acme/web#7", "user"], + ["acme/web#8", "user"], + ]), + workers: [parkedWorker()], + }); +} + +/** The matrix fixture without its second open own pull, at one stage (or none). */ +function onlyGateMetAt(stage: "spec" | "build" | "review" | null): AssessmentInput { + const first = gateMetPull("acme/web#7", "https://github.com/acme/web/pull/7"); + const phase = stage === null ? "In Progress" : PHASE[stage]; + return input({ + binding: binding({ stage, phase }), + observed: { entity: issue({ state: phase }), pulls: [first] }, + ownPulls: own(first), + decisions: new Map([["acme/web#7", "user"]]), + workers: [parkedWorker()], + }); +} + +/** A `review` binding whose project-placed pull carries a recorded `bb-approval`. */ +function projectApproved(): AssessmentInput { + const entity = pull({ comments: [ownerMarker, projectApprovalMarker("pa1")] }, { headSha: head, ...green }); + const second = secondOpenPull("acme/web#8", "https://github.com/acme/web/pull/8"); + return input({ + binding: binding({ kind: "review" }), + observed: { entity, pulls: [second] }, + ownPulls: own(entity, second), + decisions: new Map([ + [entity.key.toLowerCase(), "project"], + [second.key.toLowerCase(), "user"], + ]), + projectApprovals: [{ commentId: "pa1", verdict: "approved" }], + workers: [parkedWorker()], + }); +} + +/** The report-time `noWakeSource` flag set with no free-text wait. */ +function noWakeSourceFlag(): AssessmentInput { + const second = secondOpenPull("acme/web#8", "https://github.com/acme/web/pull/8"); + return input({ + binding: binding({ noWakeSource: true, status: null }), + observed: { entity: issue({ state: "In Progress" }), pulls: [second] }, + ownPulls: own(second), + workers: [parkedWorker()], + }); +} + +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 }); + +/** An open or merged pull request read for a `pull`/`review` wait. */ +const openPull = (key: string, over: Partial> = {}) => { + const [repo, number] = key.split("#") as [string, string]; + return pull({ key, url: `https://github.com/${repo}/pull/${number}`, state: "open" }, over); +}; +const mergedPull = (key: string) => { + const [repo, number] = key.split("#") as [string, string]; + return pull({ key, url: `https://github.com/${repo}/pull/${number}`, state: "merged" }, { merged: true }); +}; +const waited = (e: EntitySnapshot) => new Map([[e.key.toLowerCase(), e]]); +const watch = (key: string, state: string) => ({ key, state, mergeSha: null, target: "", mergedAt: null, prRepo: "acme/web", files: [], repo: "acme/web", environment: "production", deploymentId: null, deploymentState: null, ref: null, sha: null, url: null, at: 1, deadlineAt: null, note: null, workflowRuns: [] }); + +/** A binding-shaped input with one typed wait and the rows that resolve it. */ +function waitInput(wait: Wait, over: Partial = {}): AssessmentInput { + const { binding: b, ...rest } = over; + return input({ ...rest, binding: binding({ ...b, wait }) }); +} + +/** The wait fixtures, one per kind, live and not, mirroring the C1 wait tests. */ +const waitCases = (): Array<[string, AssessmentInput]> => [ + ["pull live", waitInput({ kind: "pull", ref: "acme/web#9" }, { waitedPulls: waited(openPull("acme/web#9")) })], + ["pull merged", waitInput({ kind: "pull", ref: "acme/web#9" }, { waitedPulls: waited(mergedPull("acme/web#9")) })], + ["pull unread", waitInput({ kind: "pull", ref: "acme/web#9" })], + ["review live", waitInput({ kind: "review", ref: "acme/web#9" }, { waitedPulls: waited(openPull("acme/web#9")) })], + ["review approved", waitInput({ kind: "review", ref: "acme/web#9" }, { waitedPulls: waited(openPull("acme/web#9", { reviewDecision: "APPROVED" })) })], + ["deployment live", waitInput({ kind: "deployment", ref: "acme/web#9" }, { binding: binding({ deployments: { "acme/web#9": watch("acme/web#9", "merged") as never } }) })], + ["deployment deployed", waitInput({ kind: "deployment", ref: "acme/web#9" }, { binding: binding({ deployments: { "acme/web#9": watch("acme/web#9", "deployed") as never } }) })], + ["worker live", waitInput({ kind: "worker", ref: "thr_w1" }, { workers: [{ threadId: "thr_w1", status: "running" } as never] })], + ["worker parked", waitInput({ kind: "worker", ref: "thr_w1" }, { workers: [parkedWorker({ threadId: "thr_w1" })] })], + ["binding live", waitInput({ kind: "binding", ref: "ENG-13" }, { hasOpenBinding: () => true })], + ["binding closed", waitInput({ kind: "binding", ref: "ENG-13" }, { hasOpenBinding: () => false })], + ["date ahead", waitInput({ kind: "date", ref: "2026-12-01" }, { binding: binding({ requeueUntil: 1_000_000 + 86_400_000 }) })], + ["date past", waitInput({ kind: "date", ref: "2026-12-01" }, { binding: binding({ requeueUntil: 1_000_000 - 86_400_000 }) })], + ["person live", waitInput({ kind: "person", ref: "need_1" }, { hasOpenItem: () => true })], + ["person closed", waitInput({ kind: "person", ref: "need_1" }, { hasOpenItem: () => false })], + ["external", waitInput({ kind: "external", ref: "the vendor's reply" })], +]; + +/** The C1-shaped fixtures whose composed answer must equal `assess()` with no divergence. */ +const characterizationFixtures = (): Array<[string, AssessmentInput]> => [ + ...(["ticket", "pr", "review"] as const).flatMap((kind) => (["spec", "build", "review"] as const).map((stage): [string, AssessmentInput] => [`matrix ${kind} ${stage}`, matrix(kind, stage)])), + ...(["spec", "build", "review", null] as const).map((stage): [string, AssessmentInput] => [`only-gate-met ${String(stage)}`, onlyGateMetAt(stage)]), + ["project approved", projectApproved()], + ["no-wake-source flag", noWakeSourceFlag()], + ...waitCases(), +]; + +// --------------------------------------------------------------------------- +// The composer. +// --------------------------------------------------------------------------- + +describe("the composer (BB-380)", () => { + it("rolls the gate items up and concatenates waits, resources, holds and reasons in contributor order", () => { + const i = matrix("ticket", "build"); + const contributions: SourceContribution[] = [githubContributor.contribute(i), linearContributor.contribute(i)]; + const composed = compose(contributions); + // The gate roll-up: every own pull's `met`, the first pull's lane, the first unmet pull's missing. + expect(composed.gate.pulls.map((p) => p.pull)).toEqual(["acme/web#7", "acme/web#8"]); + expect(composed.gate).toMatchObject({ met: false, decision: "user", missing: "no reviewer round yet" }); + // The rest is concatenated in contributor order. + expect(composed.waits).toEqual(contributions.flatMap((c) => c.waits)); + expect(composed.resources).toEqual(contributions.flatMap((c) => c.resources)); + expect(composed.holds).toEqual(contributions.flatMap((c) => c.holds)); + expect(composed.reasons).toEqual(contributions.flatMap((c) => c.reasons)); + // The ready gate is core, so `compose` leaves it for `composeAssessment`. + expect(composed.gate.readyPassed).toBeNull(); + }); + + it("reads a gate-met binding's roll-up as met with no missing", () => { + const composed = composeAssessment(onlyGateMetAt("build")); + expect(composed.gate).toMatchObject({ met: true, decision: "user", missing: null }); + }); + + it("rolls the gate up from the contribution fields, not the wrapped gate", () => { + const [real] = githubContributor.contribute(onlyGateMetAt("build")).gate; + // A contribution whose item fields disagree with the gate it wrapped: the + // roll-up must follow the item, or `compare` could never catch a composer + // that disagrees with today's gate (BB-380 review round 1). + const flipped: GateContribution = { ...real!, met: false, missing: "the item says unmet", lane: "project" }; + const composed = compose([{ source: "github", gate: [flipped], waits: [], resources: [], holds: [], reasons: [] }]); + expect(composed.gate).toMatchObject({ met: false, decision: "project", missing: "the item says unmet" }); + // The wrapped gate still rides along for the C3 surfaces. + expect(composed.gate.pulls).toEqual([real!.assessed]); + }); +}); + +// --------------------------------------------------------------------------- +// The github contributor. +// --------------------------------------------------------------------------- + +describe("the github contributor (BB-380)", () => { + it("wraps assessedPullGate/gateInputKey output as `merge` gate items without changing it", () => { + const i = matrix("ticket", "build"); + const a = assess(i); + const gate = githubContributor.contribute(i).gate; + expect(gate.map((g) => g.id)).toEqual(["merge", "merge"]); + expect(gate.map((g) => g.source)).toEqual(["github", "github"]); + expect(gate.map((g) => g.subject)).toEqual(a.gate.pulls.map((p) => ({ kind: "pull", id: p.pull }))); + // The wrapped gate is byte-for-byte today's per-pull assessment. + expect(gate.map((g) => g.assessed)).toEqual(a.gate.pulls); + expect(gate.map((g) => g.inputs)).toEqual(a.gate.pulls.map((p) => p.key)); + expect(gate.map((g) => [g.met, g.missing, g.lane, g.escalated, g.product])).toEqual(a.gate.pulls.map((p) => [p.met, p.missing, p.decision, p.escalated, p.reason === "product"])); + }); + + it("contributes one open-pull resource per own pull, inactive once gate-met", () => { + const resources = githubContributor.contribute(matrix("ticket", "build")).resources; + expect(resources).toEqual([ + { source: "github", id: "open-pull:acme/web#7", active: false, subject: { kind: "pull", id: "acme/web#7" } }, + { source: "github", id: "open-pull:acme/web#8", active: true, subject: { kind: "pull", id: "acme/web#8" } }, + ]); + }); + + it("contributes the pull/review/deployment typed wait for any binding and the entity's own wait and holds", () => { + const pullWait = githubContributor.contribute(waitInput({ kind: "pull", ref: "acme/web#9" }, { waitedPulls: waited(openPull("acme/web#9")) })); + expect(pullWait.waits.map((w) => `${w.source} ${w.kind} ${w.ref}`)).toEqual(["github pull acme/web#9"]); + expect(pullWait.waits[0]!.live).toBe(true); + + // A non-pull wait is the binding's own source's, so a github binding's is github's. + const githubWorker = githubContributor.contribute(waitInput({ kind: "worker", ref: "thr_w1" }, { observed: { entity: pull({}), pulls: [] }, workers: [{ threadId: "thr_w1", status: "running" } as never] })); + expect(githubWorker.waits.map((w) => `${w.source} ${w.kind}`)).toEqual(["github worker"]); + const linearWorker = linearContributor.contribute(waitInput({ kind: "worker", ref: "thr_w1" }, { workers: [{ threadId: "thr_w1", status: "running" } as never] })); + expect(linearWorker.waits.map((w) => `${w.source} ${w.kind}`)).toEqual(["linear worker"]); + + const held = githubContributor.contribute(input({ observed: { entity: pull({}), pulls: [] }, binding: binding({ hold: "a freeze", ending: "terminal", requeueUntil: 2_000_000 }) })); + expect(held.holds.map((h) => h.id)).toEqual(["hold", "ending", "requeue"]); + expect(held.holds.find((h) => h.id === "requeue")!.held).toBe(true); + }); + + it("reports a reason naming the first unmet gate's missing text", () => { + const reasons = githubContributor.contribute(matrix("ticket", "build")).reasons; + expect(reasons).toEqual([{ source: "github", code: "gate-not-met", detail: "no reviewer round yet", at: 1_000_000 }]); + }); +}); + +// --------------------------------------------------------------------------- +// The linear and local contributors. +// --------------------------------------------------------------------------- + +describe("the linear and local contributors (BB-380)", () => { + it("each contributes only for its own entity source, wrapping the binding's holds and non-pull wait", () => { + const linear = input({ binding: binding({ hold: "a freeze" }), observed: { entity: issue(), pulls: [] } }); + expect(linearContributor.contribute(linear).holds.map((h) => h.id)).toEqual(["hold"]); + expect(localContributor.contribute(linear)).toEqual({ source: "local", gate: [], waits: [], resources: [], holds: [], reasons: [] }); + + const github = input({ observed: { entity: pull({}), pulls: [] } }); + expect(githubContributor.contribute(github).holds).toEqual([]); + expect(linearContributor.contribute(github)).toEqual({ source: "linear", gate: [], waits: [], resources: [], holds: [], reasons: [] }); + }); +}); + +// --------------------------------------------------------------------------- +// The shadow equality: the composed answer equals today's assess(). +// --------------------------------------------------------------------------- + +describe("the composed answer equals today's assess() on the C1 characterization fixtures (BB-380)", () => { + it("pins the whole gate for every binding kind and stage", () => { + for (const [label, i] of characterizationFixtures()) { + expect(composeAssessment(i).gate, label).toEqual(assess(i).gate); + } + }); + + it("pins the typed wait's liveness, fingerprint and overdue age for every kind", () => { + for (const [label, i] of waitCases()) { + const a = assess(i); + const c = composeAssessment(i); + const typed = c.waits.find((w) => w.kind === (a.wait?.kind ?? "") && w.ref === (a.wait?.ref ?? "")) ?? null; + if (a.wait === null) { + expect(typed, label).toBeNull(); + } else { + expect(typed, label).not.toBeNull(); + expect(typed!.live, label).toBe(a.liveness.waitLive); + expect(typed!.fingerprint, label).toBe(a.liveness.waited); + expect(typed!.overdueMs, label).toBe(a.liveness.overdueMs); + } + } + }); + + it("pins the holds against the binding's hold, ending and requeue", () => { + const i = input({ binding: binding({ hold: "a freeze", ending: "terminal", requeueUntil: 1_000_000 + 1 }) }); + expect(composeAssessment(i).holds.map((h) => [h.id, h.held])).toEqual([ + ["hold", true], + ["ending", true], + ["requeue", true], + ]); + const past = input({ binding: binding({ requeueUntil: 1_000_000 - 1 }) }); + expect(composeAssessment(past).holds.map((h) => [h.id, h.held])).toEqual([["requeue", false]]); + }); + + it("records no compose divergence through the existing compare path", () => { + for (const [label, i] of characterizationFixtures()) { + const a = assess(i); + const rows = compare(i, a, composeAssessment(i)).filter((d) => d.surface.startsWith("compose.")); + expect(rows, label).toEqual([]); + } + }); + + it("compare still records the seven C1 surfaces when no composed answer is passed", () => { + const union = new Set(); + for (const [label, i] of characterizationFixtures()) { + for (const d of compare(i, assess(i))) union.add(d.surface); + } + expect([...union].sort()).toEqual(["approvals.gate", "approvals.pageRefusal", "hasLiveWakeSource", "idleInActiveStage", "noWakeSource", "runningWorkerReason", "workerInFlight"]); + }); +}); + +// --------------------------------------------------------------------------- +// The interface itself: the types the later consumer slices read. +// --------------------------------------------------------------------------- + +describe("the contribution interface (BB-380)", () => { + it("compose over no contributions is an empty, gate-met answer", () => { + const composed = compose([]); + expect(composed.gate).toMatchObject({ pulls: [], met: true, decision: "user", missing: null }); + expect(composed.waits).toEqual([]); + expect(composed.resources).toEqual([]); + expect(composed.holds).toEqual([]); + expect(composed.reasons).toEqual([]); + }); + + it("a gate contribution carries the source, subject, id and inputs the design names", () => { + const g: GateContribution = githubContributor.contribute(onlyGateMetAt("build")).gate[0]!; + expect(g).toMatchObject({ source: "github", subject: { kind: "pull", id: "acme/web#7" }, id: "merge", met: true, missing: null, lane: "user" }); + expect(g.inputs).toBe(g.assessed.key); + }); +}); diff --git a/plugins/stewards/contribution.ts b/plugins/stewards/contribution.ts new file mode 100644 index 00000000..b3338725 --- /dev/null +++ b/plugins/stewards/contribution.ts @@ -0,0 +1,267 @@ +// BB-380 (BB-291 criterion 8, slice C2): the per-source contribution +// interface and the composer, shadow only. +// +// A source contributes what it knows about the subjects it owns: gate items, +// waits, resources, holds and reasons. `compose()` folds those into one +// answer. Today three in-process contributors wrap the code `assess()` already +// runs — the github contributor wraps `assessedPullGate`/`gateInputKey` for +// the pull merge gate, and the binding's own source (github, linear or local) +// wraps the typed-wait derivation and the binding's holds. Nothing here adds a +// store or source read: every row comes from the `AssessmentInput` the +// reconcile already holds. +// +// This slice is shadow only. `assess()` keeps returning today's answer and no +// consumer reads the composed output; the reconcile computes it beside the +// assessment and `compare` records any divergence through the existing +// divergence log (BB-293). +import { assessedPullGate, gateInputKey } from "./assessed-gate.js"; +import { + forwardedToOwner, + ownPullEntities, + pullIsOpen, + rememberedFor, + typedWaitLive, + waitFingerprint, + waitOverdueMs, +} from "./assessment.js"; +import type { AssessedGate, Assessment, AssessmentInput, DecideMark } from "./assessment.js"; +import { waitBudgetMs } from "./config.js"; +import type { PrGate } from "./gate.js"; +import { gateState } from "./ready-gate.js"; +import type { Wait, WaitKind } from "./wait.js"; + +const lc = (s: string | null | undefined): string => (s ?? "").toLowerCase(); + +/** The source plugins a contribution can come from, as the design names them. */ +export type ContributionSource = "github" | "linear" | "local"; + +/** What a contribution is about, as the design names it. */ +export type ContributionSubject = { kind: "pull" | "artifact" | "step" | "entity"; id: string }; + +/** + * One gate item a source contributes. The merge gate is a `pull` subject's + * `merge` item; the wrapped `assessed` gate carries every field the surfaces + * read today, so the composer reproduces `assess()` exactly. + */ +export type GateContribution = { + source: ContributionSource; + /** The subject the gate is about: a pull request's key. */ + subject: ContributionSubject; + /** The item's id within its subject: `merge` for the pull request gate. */ + id: string; + met: boolean; + missing: string | null; + /** The decide-list lane the gate was computed under. */ + lane: DecideMark; + /** Whether the reviewer escalated the pull request to the owner (BB-192). */ + escalated: boolean; + /** Whether the product reason made the pull request the owner's (BB-207). */ + product: boolean; + /** The fingerprint of the gate's inputs (BB-210). */ + inputs: string; + /** The wrapped today's gate, so the composer can reproduce `assess()` exactly. */ + assessed: AssessedGate; +}; + +/** One wait a source contributes, wrapping today's typed-wait derivation. */ +export type WaitContribution = { + source: ContributionSource; + kind: WaitKind; + ref: string; + live: boolean; + /** The waited pull's field fingerprint (BB-333), or null. */ + fingerprint: string | null; + budgetMs: number | null; + since: number | null; + /** The age past the kind's budget when overdue (BB-351), else null. */ + overdueMs: number | null; +}; + +/** One resource a source contributes: something active keeps the binding from being idle. */ +export type ResourceContribution = { + source: ContributionSource; + /** `open-pull:`, `workers`, `deployment:`, … */ + id: string; + active: boolean; + subject: ContributionSubject | null; +}; + +/** One hold a source contributes, wrapping the binding's hold, ending and requeue. */ +export type HoldContribution = { + source: ContributionSource; + /** `hold`, `ending`, `requeue`, `merge-behind` or `stack`. */ + id: string; + held: boolean; + behind: readonly string[]; +}; + +/** One reason a source contributes, for the card, `show` and the digest (BB-335). */ +export type Reason = { + source: ContributionSource; + code: string; + detail: string | null; + at: number; +}; + +/** Everything one source contributes for a binding. */ +export type SourceContribution = { + source: ContributionSource; + gate: readonly GateContribution[]; + waits: readonly WaitContribution[]; + resources: readonly ResourceContribution[]; + holds: readonly HoldContribution[]; + reasons: readonly Reason[]; +}; + +/** A source's in-process view of today's assessment. */ +export type SourceContributor = { + source: ContributionSource; + contribute(input: AssessmentInput): SourceContribution; +}; + +/** The composed answer, beside `assess()`. `gate` is exactly `Assessment["gate"]`. */ +export type ComposedAssessment = { + gate: Assessment["gate"]; + waits: readonly WaitContribution[]; + resources: readonly ResourceContribution[]; + holds: readonly HoldContribution[]; + reasons: readonly Reason[]; +}; + +const empty = (source: ContributionSource): SourceContribution => ({ source, gate: [], waits: [], resources: [], holds: [], reasons: [] }); + +/** The typed wait as one contribution, wrapping today's derivation. */ +function waitContribution(source: ContributionSource, input: AssessmentInput): WaitContribution | null { + const wait: Wait | null = input.binding.wait ?? null; + if (wait === null) return null; + const budgets = input.waitBudgets ?? {}; + const live = typedWaitLive(wait, input); + const since = input.binding.waitSince ?? null; + return { + source, + kind: wait.kind, + ref: wait.ref, + live, + fingerprint: waitFingerprint(wait, input), + budgetMs: waitBudgetMs(wait.kind, budgets), + since, + overdueMs: live ? waitOverdueMs(wait, since, budgets, input.now) : null, + }; +} + +/** The pull/review/deployment kinds a pull request's source owns; the rest are the entity's. */ +const PULL_WAIT_KINDS: ReadonlySet = new Set(["pull", "review", "deployment"]); + +/** The binding's holds, wrapping the fields `idleInActiveStage` reads today. */ +function bindingHolds(source: ContributionSource, input: AssessmentInput): HoldContribution[] { + const b = input.binding; + const holds: HoldContribution[] = []; + if (b.hold !== null) holds.push({ source, id: "hold", held: true, behind: [] }); + if (b.ending !== null) holds.push({ source, id: "ending", held: true, behind: [] }); + if (b.requeueUntil !== null) holds.push({ source, id: "requeue", held: b.requeueUntil > input.now, behind: [] }); + return holds; +} + +/** What one entity source contributes: its typed wait (the non-pull kinds) and the binding's holds. */ +function entityContribution(source: ContributionSource, input: AssessmentInput): SourceContribution { + if (input.observed.entity.source !== source) return empty(source); + const wait = input.binding.wait ?? null; + const waits: WaitContribution[] = []; + if (wait !== null && !PULL_WAIT_KINDS.has(wait.kind)) { + const w = waitContribution(source, input); + if (w !== null) waits.push(w); + } + return { source, gate: [], waits, resources: [], holds: bindingHolds(source, input), reasons: [] }; +} + +/** The pull request contributions: the merge gate items, the open-pull resources and the pull/review/deployment wait. */ +function pullContributions(input: AssessmentInput): { gate: GateContribution[]; waits: WaitContribution[]; resources: ResourceContribution[]; reasons: Reason[] } { + const { binding, observed, ownPulls, decisions, projectApprovals, escalations } = input; + const gatePulls = input.gatePulls ?? ownPulls; + const gate: GateContribution[] = []; + const resources: ResourceContribution[] = []; + const reasons: Reason[] = []; + for (const e of ownPullEntities(observed, gatePulls)) { + const decideMark = decisions.get(lc(e.key)) ?? "user"; + const mark: DecideMark = decideMark === "project" && forwardedToOwner(escalations, e) ? "user" : decideMark; + const remembered = rememberedFor(input.rememberedRequesters, e); + const reRequested = rememberedFor(input.reRequestedDelegates, e); + const g: PrGate = assessedPullGate(binding, e, mark, projectApprovals, remembered, reRequested); + const inputs = gateInputKey(binding, e, g.decision, projectApprovals, remembered, reRequested); + const assessed: AssessedGate = { ...g, pull: e.key, met: g.gateMet, key: inputs }; + gate.push({ source: "github", subject: { kind: "pull", id: e.key }, id: "merge", met: g.gateMet, missing: g.missing, lane: g.decision, escalated: g.escalated, product: g.reason === "product", inputs, assessed }); + resources.push({ source: "github", id: `open-pull:${lc(e.key)}`, active: pullIsOpen(e) && !g.gateMet, subject: { kind: "pull", id: e.key } }); + if (!g.gateMet && g.missing !== null) reasons.push({ source: "github", code: "gate-not-met", detail: g.missing, at: input.now }); + } + const wait = input.binding.wait ?? null; + const waits: WaitContribution[] = []; + if (wait !== null && PULL_WAIT_KINDS.has(wait.kind)) { + const w = waitContribution("github", input); + if (w !== null) waits.push(w); + } + return { gate, waits, resources, reasons }; +} + +/** The github source: the pull merge gate, the open-pull resources and the pull waits, plus its entity's own items. */ +export const githubContributor: SourceContributor = { + source: "github", + contribute(input) { + const entity = entityContribution("github", input); + const pull = pullContributions(input); + return { + source: "github", + gate: pull.gate, + waits: [...entity.waits, ...pull.waits], + resources: pull.resources, + holds: entity.holds, + reasons: pull.reasons, + }; + }, +}; + +/** The linear source: its ticket's non-pull typed wait and the binding's holds. */ +export const linearContributor: SourceContributor = { + source: "linear", + contribute: (input) => entityContribution("linear", input), +}; + +/** The local source: its ticket's non-pull typed wait and the binding's holds. */ +export const localContributor: SourceContributor = { + source: "local", + contribute: (input) => entityContribution("local", input), +}; + +/** The in-process contributors, in the order the composer folds them. */ +export const CONTRIBUTORS: readonly SourceContributor[] = [githubContributor, linearContributor, localContributor]; + +/** + * Fold the sources' contributions into one answer. The gate roll-up is every + * item's `met`, the first item's lane, and the first unmet item's `missing`; + * the rest are concatenated in contributor order. `readyPassed` is core + * (the ready gate stays in the plugin), so `composeAssessment` fills it. + */ +export function compose(contributions: readonly SourceContribution[]): ComposedAssessment { + const gateItems = contributions.flatMap((c) => c.gate); + return { + gate: { + // The roll-up reads the contribution fields, not the wrapped gate, so a + // composer that disagrees with today's gate is visible to `compare`. + pulls: gateItems.map((g) => g.assessed), + met: gateItems.every((g) => g.met), + decision: gateItems[0]?.lane ?? "user", + missing: gateItems.find((g) => !g.met)?.missing ?? null, + readyPassed: null, + }, + waits: contributions.flatMap((c) => c.waits), + resources: contributions.flatMap((c) => c.resources), + holds: contributions.flatMap((c) => c.holds), + reasons: contributions.flatMap((c) => c.reasons), + }; +} + +/** The shadow composition for one binding, from the rows the look already holds. */ +export function composeAssessment(input: AssessmentInput): ComposedAssessment { + const composed = compose(CONTRIBUTORS.map((c) => c.contribute(input))); + composed.gate.readyPassed = gateState(input.playbook, input.binding.ready, input.currentSpecHash).passed; + return composed; +} diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 9615143d..274a2dfd 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -101,6 +101,7 @@ import { import { decideForPull, explainDecision, formatDecisionListing, globMatches, type BigDecision } from "./decisions.js"; import { ADOPTION_WHY, adoptionNeedLine, approveSpecNeedParts, forwardedQuestionParts, forwardWhy, lessonDecideParts, mergeNeedParts, mixedEvidenceDecideParts, playbookRefreshQuestionParts, repeatedObjectionQuestionParts } from "./need-parts.js"; import { ASSESSMENT_DIVERGENCE_MAX_AGE_MS, ASSESSMENT_DIVERGENCE_MAX_ROWS, assess, assessIdle, assessLiveWakeSource, assessWorker, compare, ownPullEntities, waitOverdueMs, type Assessment, type AssessmentInput } from "./assessment.js"; +import { composeAssessment } from "./contribution.js"; import { nonActionsSchema, sortedNonActions, type NonActionCode } from "./non-actions.js"; import { ASK_ON_SLACK_CHOICE, NOT_ON_SLACK_CHOICE, SLACK_PLUGIN_ID, slackCanSend, slackCandidateLabel, slackNameCandidates, slackPersonKey, slackPersonLabel, slackPersonNotOnSlack, waitSlackAskOnceWhat, waitSlackInstruction, waitSlackTerminalWhat, type SlackCandidate, type SlackPerson, type SlackStatus, type WaitSlackContext } from "./wait-slack.js"; import { assessedGate, currentStoredGate, storedGates } from "./assessed-gate.js"; @@ -5447,7 +5448,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // written and keeps its history. The other surfaces' rows still record. // The derived `noWakeSource` itself rides the reconcile's existing // binding patch, so no extra store read is added. - store.recordDivergences(compare(input, assessment).filter((d) => d.surface !== "noWakeSource")); + // BB-380 (C2): the composed answer is computed beside the assessment and + // compared through the existing divergence log. No consumer reads it. + store.recordDivergences(compare(input, assessment, composeAssessment(input)).filter((d) => d.surface !== "noWakeSource")); store.pruneDivergences(ASSESSMENT_DIVERGENCE_MAX_AGE_MS, ASSESSMENT_DIVERGENCE_MAX_ROWS, input.now); return assessment; }