Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 15 additions & 47 deletions plugins/stewards/assessed-gate.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,22 @@
// 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";
// BB-322 (child of BB-291, criterion 1): the read of the stored per-binding
// assessment every surface uses. `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).
//
// BB-387 (C3): the per-pull computation itself (the `pullGate`/`prGate` call,
// the `gateInputKey` fingerprint and the BB-321 forwarded-owner rule) lives in
// the github contributor's home (`contribution.ts`). This module keeps the
// store read/refresh helpers and imports the computation; `assessedPullGate` is
// re-exported for the tests that still name it here.
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 { assessedPullGate, gateInputKey } from "./contribution.js";
import type { PrGate, ProjectApprovalRecord } from "./gate.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, the product inputs and the delegate records (BB-327). */
function gateOptions(binding: Pick<Binding, "kind" | "ready">, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[], rememberedRequesters: readonly string[] = [], reRequestedDelegates: readonly string[] = []): PrGateOptions {
return { decision: mark, projectApprovals, rememberedRequesters, reRequestedDelegates, ...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<Binding, "kind" | "ready">, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[], rememberedRequesters: readonly string[] = [], reRequestedDelegates: readonly string[] = []): string {
return createHash("sha1").update(JSON.stringify({ entity, options: gateOptions(binding, entity, mark, projectApprovals, rememberedRequesters, reRequestedDelegates) })).digest("hex");
}

/**
* 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<Binding, "kind" | "ready">, entity: EntitySnapshot, mark: DecideMark, projectApprovals: readonly ProjectApprovalRecord[], rememberedRequesters: readonly string[] = [], reRequestedDelegates: readonly string[] = []): PrGate {
const options = gateOptions(binding, entity, mark, projectApprovals, rememberedRequesters, reRequestedDelegates);
const probe = pullGate(entity, options);
return mark === "project" && probe.ownerApproved && !probe.projectApproved ? pullGate(entity, { ...options, decision: "user" }) : probe;
}
export { assessedPullGate };

/** 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 };
Expand Down
80 changes: 21 additions & 59 deletions plugins/stewards/assessment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,15 @@
// 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 { assessedPullGate, gateInputKey, pullGate } from "./assessed-gate.js";
import { composeGate, pullGate, type ComposedAssessment } from "./contribution.js";
import { latestReviewMarker, type PrGate, type ProjectApprovalRecord } from "./gate.js";
import { parsePullRef } from "./github.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";
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";

Expand Down Expand Up @@ -172,12 +170,6 @@ 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). */
export function rememberedFor(map: ReadonlyMap<string, readonly string[]> | undefined, e: EntitySnapshot): readonly string[] {
if (map === undefined) return [];
return map.get(lc(e.key)) ?? (e.url === null ? [] : map.get(lc(e.url)) ?? []);
}

/** Whether an observed entity is one of the binding's own pull requests (BB-52 rule 0). */
const isOwn = (e: EntitySnapshot, own: ReadonlySet<string>): boolean =>
(e.key !== "" && own.has(lc(e.key))) || (e.url !== null && e.url !== "" && own.has(lc(e.url)));
Expand Down Expand Up @@ -283,17 +275,6 @@ export function typedWaitLive(wait: Wait, input: AssessmentInput): boolean {
}
}

/**
* 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).
*/
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);
}

/** Every own pull request the binding's workers opened, the binding's own entity first. */
export function ownPullEntities(observed: Observed, own: ReadonlySet<string>): EntitySnapshot[] {
return [observed.entity, ...observed.pulls].filter((e) => e.pull !== null && isOwn(e, own));
Expand Down Expand Up @@ -331,25 +312,14 @@ export function assessLiveWakeSource(sources: WakeSourceInput): boolean {
}

/** Derive the one assessment for a binding from the rows the reconcile already read. */
export function assess(input: AssessmentInput): Assessment {
const { binding, observed, ownPulls, decisions, projectApprovals, workers, escalations, needs, sources, playbook, currentSpecHash, now } = input;
const pulls: AssessedGate[] = [];
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 remembered = rememberedFor(input.rememberedRequesters, e);
const reRequested = rememberedFor(input.reRequestedDelegates, e);
const g = assessedPullGate(binding, e, mark, projectApprovals, remembered, reRequested);
pulls.push({ ...g, pull: e.key, met: g.gateMet, key: gateInputKey(binding, e, g.decision, projectApprovals, remembered, reRequested) });
}
export function assess(input: AssessmentInput, composed?: ComposedAssessment): Assessment {
const { binding, observed, ownPulls, workers, escalations, needs, sources, playbook, now } = input;
// BB-387 (C3): the merge gate is the github contributor's `merge` items,
// folded by core; `assess()` names no pull-specific derivation. A caller
// that already composed the answer passes it in, so the reconcile does not
// compose twice.
const gate = composed?.gate ?? composeGate(input);
const pulls = gate.pulls;
const idleBinding: IdleBinding = {
stage: binding.stage,
ending: binding.ending,
Expand All @@ -376,13 +346,7 @@ export function assess(input: AssessmentInput): Assessment {
return {
bindingId: binding.id,
entityKey: binding.entityKey,
gate: {
pulls,
met: pulls.every((p) => p.met),
decision: pulls[0]?.decision ?? "user",
missing: pulls.find((p) => !p.met)?.missing ?? null,
readyPassed: gateState(playbook, binding.ready, currentSpecHash).passed,
},
gate,
worker: assessWorker(workers),
liveness: {
live,
Expand Down Expand Up @@ -435,12 +399,13 @@ const verdict = (met: boolean, missing: string | null): string => (met ? "met" :
* 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.
* BB-380 (C2) adds the shadow composer's own surfaces: `compose.waits` and
* `compose.holds` (BB-387/C3 retired `compose.gate`, since the gate now comes
* from the composed answer and cannot diverge from it). 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, composed?: ComposedAssessment): Divergence[] {
const { binding, observed, ownPulls, projectApprovals, workers } = input;
Expand Down Expand Up @@ -496,17 +461,14 @@ export function compare(input: AssessmentInput, assessment: Assessment, composed
waitLive: assessment.liveness.waitLive === true,
});

// (5) BB-380 (C2): the shadow composer's gate, waits and holds against the
// (5) BB-380 (C2): the shadow composer's 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.
// composed answer. Nothing reads the composed answer yet. BB-387 (C3)
// retired the `compose.gate` comparison: the gate now comes from the composed
// answer, so it cannot diverge.
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;
Expand Down
65 changes: 64 additions & 1 deletion plugins/stewards/contribution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
// 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 { readFileSync, readdirSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { describe, expect, it, vi } 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";
Expand Down Expand Up @@ -366,3 +368,64 @@ describe("the contribution interface (BB-380)", () => {
expect(g.inputs).toBe(g.assessed.key);
});
});

// ---------------------------------------------------------------------------
// BB-387 (C3): the gate is the github contributor's, composed by `assess()`.
// ---------------------------------------------------------------------------

describe("the composed gate is the github contributor's (BB-387)", () => {
it("takes `assess()`'s gate from the github contributor: a stubbed contribution changes it", () => {
const i = onlyGateMetAt("build");
const real = assess(i);
expect(real.gate).toMatchObject({ met: true, decision: "user", missing: null });

const stub: GateContribution = {
source: "github",
subject: { kind: "pull", id: "acme/web#7" },
id: "merge",
met: false,
missing: "the stub says unmet",
lane: "project",
escalated: false,
product: false,
inputs: "stub",
assessed: { ...real.gate.pulls[0]!, met: false, missing: "the stub says unmet", decision: "project", key: "stub" },
};
const spy = vi.spyOn(githubContributor, "contribute").mockReturnValue({ source: "github", gate: [stub], waits: [], resources: [], holds: [], reasons: [] });
try {
const stubbed = assess(i);
expect(stubbed.gate).toMatchObject({ met: false, decision: "project", missing: "the stub says unmet" });
expect(stubbed.gate.pulls).toEqual([stub.assessed]);
} finally {
spy.mockRestore();
}
});

it("keeps assessment.ts free of the pull-specific gate computation", () => {
const source = readFileSync(fileURLToPath(new URL("./assessment.ts", import.meta.url)), "utf8");
// No import names the computation the github contributor owns. The body may
// still discuss `prGate` in the divergence-log comment, so only the import
// statements are checked.
expect(source).not.toMatch(/import\s*\{[^}]*\bassessedPullGate\b[^}]*\}/s);
expect(source).not.toMatch(/import\s*\{[^}]*\bprGate\b[^}]*\}/s);
// The gate arrives through the contributor's composer.
expect(source).toMatch(/\bcomposeGate\b/);
});

it("calls prGate from exactly one site in the plugin source, pullGate (BB-322 criterion 1)", () => {
const dir = fileURLToPath(new URL(".", import.meta.url));
const files = readdirSync(dir, { recursive: true, encoding: "utf8" }).filter((f) => (f.endsWith(".ts") || f.endsWith(".tsx")) && !f.endsWith(".test.ts") && !f.endsWith(".test.tsx") && !f.includes("node_modules"));
const calls: Array<{ file: string; line: string }> = [];
for (const file of files) {
const text = readFileSync(`${dir}${file}`, "utf8");
for (const line of text.split("\n")) {
// The gate module's own `export function prGate(` is the definition, not
// a call site.
if (/\bprGate\s*\(/.test(line) && !/function\s+prGate\s*\(/.test(line)) calls.push({ file, line: line.trim() });
}
}
expect(calls).toHaveLength(1);
expect(calls[0]!.file).toBe("contribution.ts");
expect(calls[0]!.line).toBe("return prGate(entity, options);");
});
});
Loading