diff --git a/plugins/stewards/assessment.ts b/plugins/stewards/assessment.ts index ffc3e989..243763e4 100644 --- a/plugins/stewards/assessment.ts +++ b/plugins/stewards/assessment.ts @@ -63,6 +63,12 @@ export type AssessedLiveness = { live: boolean; /** The stored typed wait's own liveness (BB-333); null when the binding has no typed wait. */ waitLive: boolean | null; + /** + * A compact fingerprint of the freshly read waited `pull`/`review` ref + * (BB-333), so a change on it wakes the binding. Null for any other wait or + * when the ref could not be read; JSON, never the raw snapshot. + */ + waited: string | null; /** `idleInActiveStage` before the typed wait is applied: what the consumer's idle wake reads (BB-333). */ idleBase: boolean; /** `idleInActiveStage`. */ @@ -180,6 +186,28 @@ function waitPullKey(ref: string): string | null { return parsed === null ? null : `${parsed.repo}#${parsed.number}`.toLowerCase(); } +/** + * A compact, JSON fingerprint of the freshly read waited `pull`/`review` ref + * (BB-333): the fields a steward's wait is about, so any change on the ref + * 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 { + 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); + if (e === undefined) return null; + return JSON.stringify({ + key: e.key, + state: e.state, + title: e.title, + head: e.pull?.headSha ?? null, + checks: e.pull?.checks?.state ?? null, + review: reviewGiven(e), + merged: e.pull?.merged === true, + }); +} + /** * Whether the stored typed wait is live, resolved against the rows the look * holds (BB-333): the freshly read waited pull, the deployment watches, the @@ -206,10 +234,9 @@ function typedWaitLive(wait: Wait, input: AssessmentInput): boolean { case "date": // The design's rule: a `date` wait is live while the binding's own // requeue is still ahead (`requeueUntil`). `steward_report` sets - // `requeueUntil` only from `until` today, not yet from the ref, so a - // `date` wait that sent only a ref is not live. Reading the ref here - // claimed a wake the plugin never scheduled; the report-path gap (the - // design has the ref set `requeueUntil` too) is a separate fix. + // `requeueUntil` from the ref (or from `until`) in PR 3, so a `date` + // wait that sent only a ref is live while the date is ahead. Reading the + // ref here would claim a wake the plugin never scheduled. return input.binding.requeueUntil !== null && input.binding.requeueUntil > input.now; case "person": return input.hasOpenItem?.(wait.ref) ?? false; @@ -321,6 +348,7 @@ export function assess(input: AssessmentInput): Assessment { liveness: { live, waitLive, + waited: waitFingerprint(wait, input), idleBase, // A live typed wait is something the plugin waits on, so it suppresses // the idle wake; a stalled or external one does not (BB-333). diff --git a/plugins/stewards/characterization.test.ts b/plugins/stewards/characterization.test.ts index a4760421..3b6b097c 100644 --- a/plugins/stewards/characterization.test.ts +++ b/plugins/stewards/characterization.test.ts @@ -23,11 +23,9 @@ import { anyWorkerInFlight, gateKnownUnmet, idleInActiveStage, - namesUserAsBlocker, productGateOptions, runningWorkerReason, stuckDue, - unheardWait, workerInFlight, workerRunning, type IdleBinding, @@ -187,24 +185,6 @@ describe("the worker-busy predicates: workerInFlight vs runningWorkerReason", () expect(["starting", "active", "stopping"].every(isBusy)).toBe(true); expect(["idle", "finished", "failed"].some(isBusy)).toBe(false); }); - - it("pins unheardWait: a wait on the project steward or the user with no open escalation or need", () => { - const status = (waitingOn: string | null) => ({ phase: "In Progress", summary: "s", nextAction: "n", actor: "other" as const, waitingOn, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at: 1 }); - expect(unheardWait(status("the project steward's approval of the new spec"), [])).toMatch(/project steward/u); - expect(unheardWait(status("the user's answer on scope"), [])).toMatch(/the user/u); - expect(unheardWait(status("the user's answer"), [{ kind: "approval" } as never])).toBeNull(); - expect(unheardWait(status("Sam's review"), [])).toBeNull(); - expect(unheardWait(status(null), [])).toBeNull(); - }); - - it("pins namesUserAsBlocker: user/owner/human as a word, not inside another word", () => { - expect(namesUserAsBlocker("the user must choose")).toBe(true); - expect(namesUserAsBlocker("the owner's approval")).toBe(true); - expect(namesUserAsBlocker("a human review")).toBe(true); - expect(namesUserAsBlocker("the username is wrong")).toBe(false); - expect(namesUserAsBlocker("ownerless")).toBe(false); - expect(namesUserAsBlocker("waiting on the reviewer")).toBe(false); - }); }); // --------------------------------------------------------------------------- diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index 39ccb976..4000170a 100644 --- a/plugins/stewards/reconcile.test.ts +++ b/plugins/stewards/reconcile.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { parsePlaybook, phaseOf } from "./config.js"; import { comment, issue, pull } from "./fixtures.js"; -import { answerDiffers, anyWorkerInFlight, asksForOpenApproval, checksPhrase, commentDiffersFromRecommendation, compactDue, deploymentSettled, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, idleInActiveStage, isCommentNews, isOwnStageChange, isOwnStageMove, lifecycle, markerLaneChange, mechanicalStatus, namesUserAsBlocker, newestEditComment, ownChecksFinished, ownPullClosed, ownPullMerged, phaseAndStage, productGateOptions, specDiff, specHash, specText, stuckDue, unheardWait, workerInFlight, workerReportedTerminal, type IdleBinding } from "./reconcile.js"; +import { answerDiffers, anyWorkerInFlight, asksForOpenApproval, checksPhrase, commentDiffersFromRecommendation, compactDue, deploymentSettled, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, idleInActiveStage, isCommentNews, isOwnStageChange, isOwnStageMove, lifecycle, markerLaneChange, mechanicalStatus, mentionsOwnerOrUser, newestEditComment, ownChecksFinished, ownPullClosed, ownPullMerged, phaseAndStage, productGateOptions, specDiff, specHash, specText, stuckDue, workerInFlight, workerReportedTerminal, type IdleBinding } from "./reconcile.js"; import { approvalMarkerLine, classifyApproval, ownerApproval, prGate, productReason, projectApprovalMarker, reviewMarker, reviewWorkerThread, UNREADABLE_VERDICT, type ProjectApprovalRecord } from "./gate.js"; import { approvalWanted, gateState, resolveChecklistItem } from "./ready-gate.js"; import { readyStateSchema, statusRecordSchema } from "./store.js"; @@ -306,14 +306,6 @@ describe("waits nobody hears", () => { const status = (waitingOn: string | null) => ({ phase: "Todo", summary: "s", nextAction: "n", actor: "other" as const, waitingOn, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at: 1 }); const open = [{ id: "esc_1", bindingId: "b", kind: "decision" as const, question: "q", context: null, meanwhile: "m", route: "project" as const, recommendation: null, choices: [], status: "open" as const, resolution: null, createdAt: 1, resolvedAt: null, deliveredAt: null, projectId: null, origin: { threadId: null, bindingId: null, chain: [] }, resolutionKind: null, url: null, data: {}, answeredBy: null, forwardedFrom: null, headSha: null, isQuestion: false, citedLessons: [], correctionsCounted: false, rationaleWanted: null, rationaleAsked: false, rationaleGiven: false, clusterKey: null, why: null, details: null }]; - it("flags a status waiting on the project steward or the user with no escalation open", () => { - expect(unheardWait(status("project steward's approval of the new spec"), [])).toMatch(/project steward/u); - expect(unheardWait(status("the user's answer on scope"), [])).toMatch(/the user/u); - expect(unheardWait(status("project steward's approval"), open)).toBeNull(); - expect(unheardWait(status("Sam's review"), [])).toBeNull(); - expect(unheardWait(status(null), [])).toBeNull(); - }); - it("tells the steward's own signed description edit from someone else's edit of it", () => { const signed = (text: string) => issue({ description: `${text}\n\n_— from bb thread thr_s_` }); const own = (before: ReturnType, after: ReturnType) => diffObserved({ entity: before, pulls: [] }, { entity: after, pulls: [] }, ctx).find((c) => c.text.startsWith("Description edited"))!; @@ -993,12 +985,16 @@ describe("the pull request gate (build-tickets)", () => { }); describe("a waitingOn naming the user", () => { - it("is refused without an item and allowed with one", () => { - expect(namesUserAsBlocker("the user's answer on scope")).toBe(true); - expect(namesUserAsBlocker("the owner's approval")).toBe(true); - expect(namesUserAsBlocker("a human has to install it")).toBe(true); - expect(namesUserAsBlocker("the project steward's call")).toBe(false); - expect(namesUserAsBlocker("sam's review")).toBe(false); + // BB-333: the exported name is retired, but the guard is live for an + // `external`/no-kind report; its word boundaries stay pinned. + it("matches user/owner/human as a word, not inside another word", () => { + expect(mentionsOwnerOrUser("the user's answer on scope")).toBe(true); + expect(mentionsOwnerOrUser("the owner's approval")).toBe(true); + expect(mentionsOwnerOrUser("a human has to install it")).toBe(true); + expect(mentionsOwnerOrUser("the username is wrong")).toBe(false); + expect(mentionsOwnerOrUser("ownerless")).toBe(false); + expect(mentionsOwnerOrUser("the project steward's call")).toBe(false); + expect(mentionsOwnerOrUser("sam's review")).toBe(false); }); }); diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index 81383bb2..93629c73 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -560,15 +560,17 @@ export function diffObserved(before: Observed, after: Observed, ctx: ObservedDif } /** - * A `waitingOn` that names the user, the owner or a human. A status record - * naming one of them without an open `needs` item is refused: the item is what - * puts the ask on the Stewards page (BB-109 keeps the refusal for `waitingOn`). - */ -export function namesUserAsBlocker(text: string): boolean { + * A `waitingOn` that names the user, the owner or a human. Retained for a + * typed wait that is not a valid `person` wait (an `external` wait, or a + * `person` ref the plugin could not resolve) and for a no-kind report: naming + * one of them without an open `needs` item is refused, because the item is + * what puts the ask on the Stewards page. A valid `person` wait is the + * structured replacement and bypasses it (BB-333). + */ +export function mentionsOwnerOrUser(text: string): boolean { return /(?:^|[^\p{L}\p{N}])(?:user|owner|human)(?:[^\p{L}\p{N}]|$)/iu.test(text); } - /** * A steward that asks for an approval that is already open. The plugin files * the request and lists it on the Stewards page, so the playbook says not to @@ -649,17 +651,6 @@ export function gateKnownUnmet(playbook: Playbook, ready: ReadyState, currentSpe return gate.unmet.some((item) => reportedItem(ready, item)?.met === false); } -/** - * A status that says it waits on the project steward or the user while - * none of its escalations is open: a wait nobody above it hears about. - */ -export function unheardWait(status: Binding["status"], open: readonly Escalation[], needs: readonly Pick[] = []): string | null { - if (status === null || status.waitingOn === null || open.length > 0 || needs.length > 0) return null; - if (/project steward/iu.test(status.waitingOn)) return "waits on the project steward, with no open escalation"; - if (/\buser\b/iu.test(status.waitingOn)) return "waits on the user, with no open escalation"; - return null; -} - // ---- idle in an active stage (BB-83) -------------------------------------------- /** diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index fb2114f0..9222f751 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -842,15 +842,6 @@ describe("a Linear ticket steward", () => { expect(toProject()).toHaveLength(after); }); - it("flags a status that waits on the project steward with no escalation", async () => { - const t = await setup(); - t.entities.set("uuid-12", issue()); - await t.ring("linear", "uuid-12"); - const steward = t.spawns[1]!.id; - await t.tool("steward_report", { phase: "Todo", summary: "Waiting.", nextAction: "Wait", actor: "other", waitingOn: "the project steward's call on scope" }, steward); - expect((await t.harness.behavior.runCli(["list", "--project", "p1"])).stdout).toMatch(/waits on the project steward, with no open escalation/u); - }); - it("recognizes workers the steward starts with bb thread spawn, and wakes only when one asks", async () => { const t = await setup(); t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); @@ -15232,9 +15223,9 @@ describe("a typed wait (BB-333)", () => { // BB-266: a ticket with a gate-met own pull, a parked `finished` worker and a // second open own pull, waiting on the plugin auto-merge. The typed ref is // the own gate-met pull, so it is recorded as external (reference_is_self). - // TODAY the second open own pull is still a live source, so the wait is not - // marked; PR 2 derives the stall from the external wait despite it. - it("pins the BB-266 fixture: the second open own pull is a live source, so the wait is not marked", async () => { + // BB-333 PR 3: the stored flag is now the derived stall, so the external wait + // stalls despite the second open own pull. + it("pins the BB-266 fixture: the external wait stalls despite the second open own pull", async () => { const t = await setup(); t.entities.set( "uuid-12", @@ -15258,7 +15249,7 @@ describe("a typed wait (BB-333)", () => { const report = await t.tool("steward_report", { ...base, waitingOn: "the plugin auto-merge", wait: { kind: "pull", ref: "acme/web#7" } }, b.threadId!); expect(report.error).toBe(false); expect(t.hooks.store.find("ENG-12")!.wait).toEqual({ kind: "external", ref: "acme/web#7" }); - expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(false); + expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(true); }); // bb-plugins#294: a `pr` binding's own open pull with a free-text wait. The @@ -15278,9 +15269,9 @@ describe("a typed wait (BB-333)", () => { // bc-prod#422 / BCP-157: a ticket waiting on the owner's approval, with no // open approve-pr item, beside an open linked pull. The person ref is not an - // open page item, so it is recorded as external. TODAY the open pull watch is - // a live source and masks it; PR 2 derives the stall despite the mask. - it("pins the bc-prod#422/BCP-157 fixture: the open pull watch masks the person wait", async () => { + // open page item, so it is recorded as external. BB-333 PR 3: the stored flag + // is now the derived stall, so the external wait stalls despite the open pull. + it("pins the bc-prod#422/BCP-157 fixture: the external wait stalls despite the open pull watch", async () => { const t = await setup(); t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7" })); @@ -15291,7 +15282,7 @@ describe("a typed wait (BB-333)", () => { const report = await t.tool("steward_report", { ...base, waitingOn: "GitHub approval of acme/web#7", wait: { kind: "person", ref: "need_approve" } }, b.threadId!); expect(report.error).toBe(false); expect(t.hooks.store.find("ENG-12")!.wait).toEqual({ kind: "external", ref: "need_approve" }); - expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(false); + expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(true); }); // bc-prod#430 / BCP-160: a ticket waiting on a foreign pull's checks, not @@ -15336,11 +15327,12 @@ describe("the typed wait's shadow derivation (BB-333)", () => { const b = t.hooks.store.find("ENG-12")!; await t.tool("steward_report", { ...base, waitingOn: "the plugin auto-merge", wait: { kind: "pull", ref: "acme/web#7" } }, b.threadId!); await t.hooks.reconcilePass("p1"); - expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(false); + // BB-333 PR 3: the stored flag is the derived stall, so it now agrees. + expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(true); expect(derived(t, b.id)).toMatchObject({ stalled: true, waitLive: false }); - // The report-time flag agrees with the second open own pull, so the - // derived stall is a divergence and is recorded. - expect(t.hooks.store.divergences({ bindingId: b.id, surface: "noWakeSource" })).toContainEqual(expect.objectContaining({ old: "source-or-no-wait", new: "no-wake-source" })); + // The shadow's divergence table stopped being written: the flag and the + // derivation agree by construction. + expect(t.hooks.store.divergences({ bindingId: b.id, surface: "noWakeSource" })).toHaveLength(0); }); it("derives the bb-plugins#294 fixture: a pr binding's own external wait stalls", async () => { @@ -15361,7 +15353,7 @@ describe("the typed wait's shadow derivation (BB-333)", () => { const b = t.hooks.store.find("ENG-12")!; await t.tool("steward_report", { ...base, waitingOn: "GitHub approval of acme/web#7", wait: { kind: "person", ref: "need_approve" } }, b.threadId!); await t.hooks.reconcilePass("p1"); - expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(false); + expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(true); expect(derived(t, b.id)).toMatchObject({ stalled: true, waitLive: false }); }); @@ -15387,7 +15379,7 @@ describe("the typed wait's shadow derivation (BB-333)", () => { expect(github().entities).not.toContain("acme/web#430"); }); - it("a ring on a waited ref looks, sends no wake, and touches no snapshot or resource", async () => { + it("a ring on a waited ref wakes the binding on the ref's change (BB-333)", async () => { const { t, steward } = await ticket(); t.entities.set("acme/web#430", pull({ id: "acme/web#430", key: "acme/web#430", url: "https://github.com/acme/web/pull/430", state: "open" })); await t.tool("steward_report", { ...base, waitingOn: "bc-prod#430 checks", wait: { kind: "pull", ref: "acme/web#430" } }, steward); @@ -15396,17 +15388,58 @@ describe("the typed wait's shadow derivation (BB-333)", () => { const wakesBefore = t.sends.filter((s) => s.threadId === steward).length; const pullsBefore = JSON.stringify(before.lastSnapshot?.pulls ?? []); t.rpcCalls.length = 0; - // The waited pull changes; the doorbell rings it. + // The waited pull changes; the doorbell rings it. BB-333 PR 3: the change + // now wakes the binding (in PR 2 it only fed the derived result). t.entities.set("acme/web#430", pull({ id: "acme/web#430", key: "acme/web#430", url: "https://github.com/acme/web/pull/430", state: "open", title: "changed" })); await t.ring("github", "acme/web#430"); await t.flush(); - // The waiting ticket looked (it read the waited ref) but the change woke nobody. expect(t.rpcCalls.some((c) => c.method === "sourceSnapshot" && c.input.id === "acme/web#430")).toBe(true); - expect(t.sends.filter((s) => s.threadId === steward).length).toBe(wakesBefore); + expect(t.sends.filter((s) => s.threadId === steward).length).toBeGreaterThan(wakesBefore); + expect(t.sends.at(-1)!.text).toContain("The waited pull acme/web#430 changed"); + // The waited ref is still not a stored linked pull or a resource. const after = t.hooks.store.find("ENG-12")!; expect(JSON.stringify(after.lastSnapshot?.pulls ?? [])).toBe(pullsBefore); expect(after.status?.resources.pullRequests ?? []).not.toContain("acme/web#430"); }); + + it("does not wake on a re-pointed ref, a kind switch or a failed read (BB-333)", async () => { + const { t, steward } = await ticket(); + const waitedWakes = () => t.sends.filter((s) => s.threadId === steward && s.text.includes("The waited pull")).length; + t.entities.set("acme/web#430", pull({ id: "acme/web#430", key: "acme/web#430", url: "https://github.com/acme/web/pull/430", state: "open" })); + await t.tool("steward_report", { ...base, waitingOn: "the vendor's reply", wait: { kind: "date", ref: "2027-07-01" } }, steward); + await t.hooks.reconcilePass("p1"); + // A kind switch to a pull wait has no prior fingerprint for the ref, so it + // must not read as a change. + await t.tool("steward_report", { ...base, waitingOn: "bc-prod#430 checks", wait: { kind: "pull", ref: "acme/web#430" } }, steward); + await t.hooks.reconcilePass("p1"); + expect(waitedWakes()).toBe(0); + // Re-pointing the wait at an unchanged, different ref is not a change on + // the first ref. + t.entities.set("acme/web#431", pull({ id: "acme/web#431", key: "acme/web#431", url: "https://github.com/acme/web/pull/431", state: "open" })); + await t.tool("steward_report", { ...base, waitingOn: "bc-prod#431 checks", wait: { kind: "pull", ref: "acme/web#431" } }, steward); + await t.hooks.reconcilePass("p1"); + expect(waitedWakes()).toBe(0); + // A failed read (the ref is gone) and its recovery are not changes either. + t.entities.delete("acme/web#431"); + await t.hooks.reconcilePass("p1"); + t.entities.set("acme/web#431", pull({ id: "acme/web#431", key: "acme/web#431", url: "https://github.com/acme/web/pull/431", state: "open" })); + await t.hooks.reconcilePass("p1"); + expect(waitedWakes()).toBe(0); + }); + + it("a date wait with only a ref sets requeueUntil and is not a stall (BB-333)", async () => { + const { t, steward } = await ticket(); + const report = await t.tool("steward_report", { ...base, waitingOn: "the vendor's reply", wait: { kind: "date", ref: "2027-07-01" } }, steward); + expect(report.error).toBe(false); + const b = t.hooks.store.find("ENG-12")!; + expect(b.wait).toEqual({ kind: "date", ref: "2027-07-01" }); + expect(b.requeueUntil).toBe(Date.UTC(2027, 6, 1)); + // A future date is the plugin's own wake source, so the wait is not marked. + expect(b.noWakeSource).toBe(false); + await t.hooks.reconcilePass("p1"); + expect(derived(t, b.id)).toMatchObject({ stalled: false, waitLive: true }); + expect(t.hooks.store.find("ENG-12")!.noWakeSource).toBe(false); + }); }); // BB-203: the plugin writes the binding's status from events it observed diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index a1f8fa86..c9d52209 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -106,7 +106,7 @@ import { EntityCache, type EntityRecord } from "./entity-cache.js"; import { classify, hasFingerprintLine, lookChanges, opsTargetKey, parseOpsTargetKey, redactLine, scrubCredentials, ticketResolved, type AlertmanagerTarget, type BacklogLook, type BacklogTarget, type DependabotTarget, type FingerprintRow, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; import { EVENTS_PER_LOOK, NO_TOKEN, RECENT_PER_LOOK, SENTRY_API_URL, TOKEN_SCOPES, createSentryReader, emptySentryLook, issueInOrg, recentLine, sentryChanges, sentryResolveTargets, sentrySightings, sentrySummary, type SentryFinding, type SentryLook, type SentryReader } from "./sentry.js"; import { ALERTMANAGER_URL_ENV, alertmanagerChanges, alertmanagerSightings, alertmanagerSummary, createAlertmanagerReader, emptyAlertmanagerLook, resolveAlertmanagerUrl, type AlertmanagerFinding, type AlertmanagerLook, type AlertmanagerReader, type AlertmanagerRung } from "./alertmanager.js"; -import { advanced, answerDiffers, asksForOpenApproval, commentDiffersFromRecommendation, compactDue, deploymentSettled, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, hasLabel, IDLE_WAKE_TEXT, isCommentNews, isOwnStageChange, lifecycle, mechanicalStatus, namesUserAsBlocker, newHumanComments, newestCommentAt, openUserFacingItems, ownChecksFinished, ownPullClosed, ownPullMerged, phaseAndStage, productGateOptions, newestEditComment, specDiff, specHash, specText, stuckDue, unheardWait, workerInFlight, workerReportedTerminal, type Change, type MechanicalEvent, type OpenUserItem } from "./reconcile.js"; +import { advanced, answerDiffers, asksForOpenApproval, commentDiffersFromRecommendation, compactDue, deploymentSettled, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, hasLabel, IDLE_WAKE_TEXT, isCommentNews, isOwnStageChange, lifecycle, mechanicalStatus, mentionsOwnerOrUser, newHumanComments, newestCommentAt, openUserFacingItems, ownChecksFinished, ownPullClosed, ownPullMerged, phaseAndStage, productGateOptions, newestEditComment, specDiff, specHash, specText, stuckDue, workerInFlight, workerReportedTerminal, type Change, type MechanicalEvent, type OpenUserItem } from "./reconcile.js"; import { classifyApproval, latestProjectApprovalMarker, latestReviewMarker, prGate, reviewMarker } from "./gate.js"; import { approveOwnerReviewedPull, approvePrPageAction, declineOwnerReviewedPull, delegateWaitNames, deliverApproval, fileForwardedApprovePrNeed, isDelegateWait, isProjectSteward, isUserThread, markerKey, normalizeText, specApprovedByProject, syncPullApproval, userApprovedOnEntity, userSaid, type ApprovalsContext } from "./approvals.js"; import { deliverEscalation, nextRoute, routedTo, type EscalationsContext } from "./escalations.js"; @@ -3258,6 +3258,24 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return parsed === null ? [] : [`${parsed.repo}#${parsed.number}`]; } + /** + * Whether two stored waited-ref fingerprints name the same pull request + * (BB-333). A fingerprint that does not parse, or names no key, is not the + * same ref, so a change in either cannot be read as the other's. + */ + function sameWaitedRef(a: string, b: string): boolean { + const key = (fp: string): string | null => { + try { + const parsed = JSON.parse(fp) as { key?: unknown }; + return typeof parsed.key === "string" ? parsed.key : null; + } catch { + return null; + } + }; + const ka = key(a); + return ka !== null && ka === key(b); + } + /** * Read the binding's waited pull/review refs fresh, one source read each, * under the linked-pull ceiling (BB-333). A ref already in the look's linked @@ -4776,15 +4794,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } /** - * 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. + * BB-293/BB-322/BB-333: assemble the one assessment input from the rows the + * look already holds. The reconcile and the report path both call it, so + * liveness, idle and stall are derived in one place; `assessBinding` + * records the result and the report reads it for the turn it is in. */ - async function assessBinding( + async function buildAssessmentInput( b: Binding, observed: Observed, workers: readonly Worker[], @@ -4792,7 +4807,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P playbook: Playbook, currentSpecHash: string, config: ProjectConfig, - ): Promise { + ): Promise { // 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 @@ -4861,34 +4876,35 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }, hasOpenItem: (id) => needs.some((n) => n.id === id) || escalations.some((x) => x.id === id) || (id.startsWith("qst_") && store.openQuestions(b.projectId).some((q) => q.id === id)), }; + return input; + } + + /** + * BB-293/BB-322/BB-333: the binding's one assessment, from the rows the look + * already holds. BB-333 made the typed-wait derivation authoritative: the + * stored `noWakeSource` is recomputed from the assessment on every + * reconcile (never a report-time guess), and the shadow's `noWakeSource` + * divergence is retired because the flag and the derivation now agree by + * construction. The column and every surface that reads it are unchanged. + */ + async function assessBinding( + b: Binding, + observed: Observed, + workers: readonly Worker[], + ownPulls: ReadonlySet, + playbook: Playbook, + currentSpecHash: string, + config: ProjectConfig, + ): Promise { + const input = await buildAssessmentInput(b, observed, workers, ownPulls, playbook, currentSpecHash, config); const assessment = assess(input); store.recordAssessment({ bindingId: b.id, at: input.now, gate: assessment.gate, worker: assessment.worker, liveness: assessment.liveness }); - const divergences = compare(input, assessment); - // BB-333: a typed wait's divergence is written only when it starts or - // stops disagreeing, through the state table. A no-kind report keeps the - // existing deduped row, and a binding with no typed wait reads no state. - if (b.wait !== null) { - store.recordDivergences(divergences.filter((d) => d.surface !== "noWakeSource")); - store.recordWaitDivergence({ - bindingId: b.id, - derived: assessment.liveness.stalled, - reported: b.noWakeSource, - waitKind: b.wait.kind, - waitLive: assessment.liveness.waitLive === true, - inputs: { - binding: b.id, - live: assessment.liveness.live, - idle: assessment.liveness.idle, - stuck: assessment.liveness.stuck, - readyPassed: assessment.gate.readyPassed, - requeueUntil: b.requeueUntil, - phase: b.phase, - hasWait: (b.status?.waitingOn ?? "").trim() !== "", - }, - }); - } else { - store.recordDivergences(divergences); - } + // The shadow's `noWakeSource` divergence is retired with the flag: the + // two agree by construction now, so `wait_divergence_state` stops being + // 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")); store.pruneDivergences(ASSESSMENT_DIVERGENCE_MAX_AGE_MS, ASSESSMENT_DIVERGENCE_MAX_ROWS, input.now); return assessment; } @@ -5232,12 +5248,29 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // 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. + // BB-333: a change on a leased pull/review ref now wakes the binding. The + // waited ref is not in the observed snapshot, so the transition is read + // from the previous look's stored fingerprint against this look's. Only + // two fingerprints of the same ref can move: a re-pointed ref, a kind + // switch, a failed read and the first look after the rollout leave the + // pair unusable and stay quiet. + const waitedKind = b.wait?.kind ?? null; + const priorWaited = + waitedKind === "pull" || waitedKind === "review" + ? ((store.assessment(b.id)?.liveness as { waited?: string | null } | null | undefined)?.waited ?? null) + : null; let assessment: Assessment | null = null; try { assessment = await assessBinding(b, observed, workers, ownPulls, playbook, currentSpec, config); } catch (error) { bb.log.warn(`stewards: assessment failed for ${b.entityKey}: ${errorMessage(error)}`); } + if (waitedKind === "pull" || waitedKind === "review") { + const nowWaited = assessment?.liveness.waited ?? null; + if (priorWaited !== null && nowWaited !== null && sameWaitedRef(priorWaited, nowWaited) && priorWaited !== nowWaited) { + changes.push({ text: `The waited ${waitedKind} ${b.wait?.ref ?? ""} changed`, actionable: true }); + } + } // BB-329: one worker-busy predicate. Every surface reads the assessment's // worker state (assessment.ts `assessWorker`); the old `anyWorkerInFlight` // / `runningWorkerReason` call sites are gone. `inFlight` is still @@ -5343,7 +5376,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } signalNeedActionability(b, observed, ready); - b = store.patch(b.id, { lastSnapshot: observed, phase, stage, title: entity.title, url: entity.url, entityKey: entity.key, playbookVersion: playbook.version, ready }); + b = store.patch(b.id, { lastSnapshot: observed, phase, stage, title: entity.title, url: entity.url, entityKey: entity.key, playbookVersion: playbook.version, ready, ...(assessment === null ? {} : { noWakeSource: assessment.liveness.stalled }) }); // BB-54 item 4: a ticket that links a new pull request re-runs the // overlap check, even past its ready gate, and a new pull request clears // a "no more coming" report. The report path clears it too, when a @@ -12241,6 +12274,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P wait = validation.wait; if (validation.downgraded !== null) waitNote = ` ${WAIT_REFUSAL_MESSAGE[validation.downgraded]}`; } + // BB-333: a `date` wait is the structured form of `until`; its ref + // sets `requeueUntil` when the report did not also send an `until`. + // A past date is ignored with a note, exactly as `until` is. + if (wait !== null && wait.kind === "date" && untilAt === null) { + const parsed = parseUntil(wait.ref); + if (parsed === null) return toolError(new Error(WAIT_REFUSAL_MESSAGE.date_wait_without_date)); + if (parsed <= now()) { + untilNote += ` The date ${iso(parsed)} is in the past, so it was ignored; the wait requeues on the playbook default.`; + } else { + untilAt = parsed; + } + } // `until` wins over an explicit `requeueAfter` in the same report. The // deployment-deadline min below is untouched; a dated wait is not // capped by `requeue-default`. @@ -12251,9 +12296,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // An auto-filed need does not satisfy this: it is filed from prose, // not the item the user acts on, so a wait naming the user still // needs a real item or escalation (BB-213). - // Only a stored `person` wait — one that resolved to an open page item and was not downgraded — bypasses the guard: the item it names is itself what reaches the page. An `external` wait, or a `person` wait downgraded to `external`, still has to file the item. + // BB-333: a stored `person` wait is the structured replacement for + // the old free-text owner check: the open page item it names is + // itself what reaches the page. A typed wait that is not a valid + // person wait (an `external` wait, or a person ref the plugin could + // not resolve) and a no-kind report still may not name the owner + // with nothing filed (BB-213). const personWait = wait !== null && wait.kind === "person"; - if (!personWait && waitingOn !== null && namesUserAsBlocker(waitingOn) && store.openNeeds(b.id).filter((n) => !isAutoFiledNeed(n)).length === 0 && (input.needs ?? []).length === 0) { + if (!personWait && waitingOn !== null && mentionsOwnerOrUser(waitingOn) && store.openNeeds(b.id).filter((n) => !isAutoFiledNeed(n)).length === 0 && (input.needs ?? []).length === 0) { return toolError( new Error( `waitingOn names the user, the owner or a human, but nothing is filed for them. File it as a needs item (steward_report { needs: [{ kind, url, what, how }] }) — or, for a credential, a step outside the repos or a decision, raise it with steward_report { escalate: { kind, question, meanwhile } } — and it appears on the Stewards page; waitingOn stays for third parties.`, @@ -12468,11 +12518,24 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // ticket's own pull request counts as a source or not by one rule. const currentOwnPulls = current.kind === "ticket" && current.lastSnapshot !== null ? await ownPullKeys(current, store.workers(current.id), current.lastSnapshot) : new Set(); const liveSource = liveWakeSourceFor(current, currentOwnPulls); + // BB-333: liveness and stall come from the typed wait, derived by the + // one assessment on every reconcile. The report computes the same + // answer here so its reply is current in the turn the wait is set; a + // no-kind report keeps today's free-text rule exactly. + let derivedStalled: boolean | null = null; + if (current.wait !== null && current.lastSnapshot !== null && playbook !== null && config !== null) { + try { + const derived = assess(await buildAssessmentInput(current, current.lastSnapshot, store.workers(current.id), currentOwnPulls, playbook, specHashFor(current, current.lastSnapshot.entity), config)); + derivedStalled = derived.liveness.stalled; + } catch (error) { + bb.log.warn(`stewards: could not derive the typed wait's liveness for ${current.entityKey}: ${errorMessage(error)}`); + } + } // BB-247: a dated wait is the plugin's own wake source while the date // is ahead, so it is not marked waiting with no source (and is listed // as a dated wait in the digest instead). const datedFuture = current.requeueUntil !== null && current.requeueUntil > now(); - const noWakeSource = waitingOn !== null && waitingOn.trim() !== "" && !liveSource && !datedFuture; + const noWakeSource = derivedStalled ?? (waitingOn !== null && waitingOn.trim() !== "" && !liveSource && !datedFuture); // BB-339: the open bindings the free text names, in the order they // appeared, so the report reply can point the steward at the hold it // can take in this turn. A key that resolves to nothing, to an ended @@ -12485,7 +12548,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P : []; const stall = advanceStall( { count: current.requeueWakeCount, waitText: current.requeueWaitText, firstAt: current.requeueFirstAt }, - { reason: wakeReason, waitingOn, liveSource, now: now(), until: current.requeueUntil }, + { reason: wakeReason, waitingOn, liveSource: derivedStalled !== null ? !derivedStalled : liveSource, now: now(), until: current.requeueUntil }, ); b = store.patch(b.id, { noWakeSource, requeueWakeCount: stall.state.count, requeueWaitText: stall.state.waitText, requeueFirstAt: stall.state.firstAt }); const requests = [requested === null ? null : "approval", scheduling === null ? null : "scheduling"].filter((r) => r !== null); @@ -13527,7 +13590,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ? `cannot read the target: ${alertmanager.error}` : `looked ${iso(alertmanager.at)}: ${alertmanager.findings.length === 0 ? "nothing to do" : `${alertmanager.findings.length} alert(s) new, rung or resolved`}`; const needs = store.openNeeds(b.id); - const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, watch, b.adoptedBy === null ? null : `adopted by ${b.adoptedBy}`, b.priority === null ? null : `priority ${b.priority}`, b.noMorePulls === true ? "no more pull requests" : null, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}`, b.mergeBehind.length === 0 ? null : `MERGE HOLD: behind ${b.mergeBehind.join(", ")}`, b.stackedPulls.length === 0 ? null : `BASE OF: ${b.stackedPulls.join(", ")}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), ...needs.map((n) => `${n.kind} need ${n.id}${n.url === "" ? "" : ` (${n.url})`}`), unheardWait(s, open, needs), asksForOpenApproval(s, open, needs)].filter((f) => f !== null); + const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, watch, b.adoptedBy === null ? null : `adopted by ${b.adoptedBy}`, b.priority === null ? null : `priority ${b.priority}`, b.noMorePulls === true ? "no more pull requests" : null, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}`, b.mergeBehind.length === 0 ? null : `MERGE HOLD: behind ${b.mergeBehind.join(", ")}`, b.stackedPulls.length === 0 ? null : `BASE OF: ${b.stackedPulls.join(", ")}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), ...needs.map((n) => `${n.kind} need ${n.id}${n.url === "" ? "" : ` (${n.url})`}`), asksForOpenApproval(s, open, needs)].filter((f) => f !== null); return `${b.entityKey} — ${b.kind}, ${b.phase ?? "?"}${roles.length === 0 ? "" : `, role ${roles.join(", ")}`}${b.threadId === null ? "" : `, thread ${b.threadId}`}\n ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${b.noWakeSource ? "; waiting, no wake source" : s.waitingOn === null ? "" : `; waiting on ${s.waitingOn}${b.requeueUntil === null ? "" : ` until ${iso(b.requeueUntil).slice(0, 10)}`}`}`}${b.wait === null ? "" : `; typed wait: ${waitPhrase(b.wait)}`}${flags.length > 0 ? `\n [${flags.join("; ")}]` : ""}`; }) .join("\n"); diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index f551449b..79a6b24f 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -266,28 +266,42 @@ Two tools are yours; everything else you do with the tools every thread has. flagged in `bb stewards list` and the digest. A `waitingOn` naming the user, the owner or a human is refused unless an open needs item says so: raise it with `steward_report { escalate }` (or file a gate item) instead - of only saying it. `waitingOn` stays for third parties. It never marks the - effort blocked: a hold, an open `stuck` escalation or a needs item does - (BB-109). The old name `blockedOn` is accepted as an alias for one - release. -- **A wait with no wake source, and a stall (BB-154).** Every wait the - plugin understands is structured and has a clock it tracks: a - `holdBehind`, a deployment watch, a running worker, an open escalation or - need, a watched pull request. A free-text `waitingOn` beside them can name - something nothing will ever deliver. When you report a wait and none of - those sources is live, the binding is marked `noWakeSource`: the row and - `bb stewards list`/`show` read `waiting, no wake source`, and the report - reply itself flags it and tells you to name what will deliver the wait in - that same turn — a binding to hold behind (`steward_update { hold, - behind }`), a typed `wait`, or a dated `until` — not at the next wake. If - the free text names an open binding in the same project, the reply names - it and the exact `hold, behind` call. Clear the mark by - adding a real source or clearing the wait. If you wake by `requeue` twice - in a row with the same wait and no source, the plugin raises one `stall` - escalation to the project steward naming the binding, the wait, when you - first reported it and the wake count. A wake for another reason, a changed - wait or a new source resets the count, and a stall already open is not - raised again. + of only saying it. The structured form is a typed `wait: { kind: "person", + ref: "need_…" }` on an open page item (a `need_`, `esc_` or `qst_` id): + the item itself is what reaches the page, so it passes the refusal. + `waitingOn` stays for third parties. It never marks the effort blocked: a + hold, an open `stuck` escalation or a needs item does (BB-109). The old + name `blockedOn` is accepted as an alias for one release. +- **A wait with no wake source, and a stall (BB-154, BB-333).** A wait is + typed: `wait: { kind, ref }` with a closed kind set — `pull` and `review` + (a leased `owner/repo#N`), `deployment` (a watch key), `worker` (a thread + id), `binding` (an entity key), `date` (an ISO date, the structured form + of `until`), `person` (an open `need_`/`esc_`/`qst_` item) and `external` + (free text nothing the plugin tracks will deliver). Liveness, idle and + stall are derived from the kind on every reconcile, never stored at report + time: `pull` is live while the pull is open and not merged, `review` while + it is open and unreviewed at head, `deployment` while the watch is + `merged`/`deploying`, `worker` while that worker runs, `binding` while the + other binding is open and unfinished, `date` while the date is ahead, + `person` while the page item is open, and `external` never. A `waitingOn` + with no `kind` keeps the free-text rule: it is live only if a tracked + source (a `holdBehind`, a deployment watch, a running worker, an open + escalation or need, a watched pull request) is. When nothing the plugin + tracks will deliver the wait, the binding is marked `noWakeSource`, computed + from that derivation (never a flag frozen at report time): the row and `bb + stewards list`/`show` read `waiting, no wake source`, and the report reply + itself flags it and tells you to name what will deliver the wait in that + same turn — a binding to hold behind (`steward_update { hold, behind }`), a + typed `wait`, or a dated `until` — not at the next wake. A `pull` or + `review` wait is leased beside the ticket's linked pulls and read on each + look; a change on it wakes the binding. If the free text names an open + binding in the same project, the reply names it and the exact `hold, + behind` call. Clear the mark by adding a real source or clearing the wait. + If you wake by `requeue` twice in a row with the same wait and no source, + the plugin raises one `stall` escalation to the project steward naming the + binding, the wait, when you first reported it and the wake count. A wake + for another reason, a changed wait or a new source resets the count, and a + stall already open is not raised again. - **A wait with a known end is a dated wait (BB-247).** When the wait has a date — a tax year closing, a deployment window, a pilot cycle finishing, a decision promised for Monday — report it as `steward_report { waitingOn, diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index f37c41e6..513055ee 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -17,7 +17,7 @@ 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, unheardWait } from "./reconcile.js"; +import { newHumanComments } from "./reconcile.js"; import { reportedItem, type GateState } from "./ready-gate.js"; import { currentStoredGate, type StoredGate } from "./assessed-gate.js"; import { conflictsOf, openPull, type Conflict } from "./schedule.js"; @@ -1709,7 +1709,7 @@ export function formatProjectWake(input: { for (const { binding: b, openEscalations } of input.bindings.slice(0, 200)) { const s = b.status; const conflicts = conflictsOf(b, allOpen); - const flags = [initiativeProgressFlag(b), b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}`, b.touches.length === 0 ? null : `touches ${b.touches.join(", ")}`, conflicts.length === 0 ? null : `file-level overlap: ${conflicts.map((c) => { const open = c.with.lastSnapshot === null ? null : openPull(c.with, c.with.lastSnapshot); return `${c.with.entityKey} on ${c.on.join(", ")}${open === null || open.head === null || open.head === "" ? "" : ` (its pull request ${open.key} is open on ${open.head})`}`; }).join("; ")}`, openEscalations.length > 0 ? `${openEscalations.length} escalation(s): ${openEscalations.map((x) => `${x.kind}→${x.route}`).join(", ")}` : null, unheardWait(s, openEscalations)].filter((f): f is string => f !== null); + const flags = [initiativeProgressFlag(b), b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}`, b.touches.length === 0 ? null : `touches ${b.touches.join(", ")}`, conflicts.length === 0 ? null : `file-level overlap: ${conflicts.map((c) => { const open = c.with.lastSnapshot === null ? null : openPull(c.with, c.with.lastSnapshot); return `${c.with.entityKey} on ${c.on.join(", ")}${open === null || open.head === null || open.head === "" ? "" : ` (its pull request ${open.key} is open on ${open.head})`}`; }).join("; ")}`, openEscalations.length > 0 ? `${openEscalations.length} escalation(s): ${openEscalations.map((x) => `${x.kind}→${x.route}`).join(", ")}` : null].filter((f): f is string => f !== null); out.push(`- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}): ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${s.waitingOn === null ? "" : `; waiting on ${s.waitingOn}${b.requeueUntil === null ? "" : ` until ${day(b.requeueUntil)}`}`}`}${flags.length > 0 ? ` [${flags.join("; ")}]` : ""}`); } // BB-288: the guidance index sits at the end of the bindings list, so `fit`