diff --git a/plugins/github-watcher/source-contract.ts b/plugins/github-watcher/source-contract.ts index afe9dd00..aea729d3 100644 --- a/plugins/github-watcher/source-contract.ts +++ b/plugins/github-watcher/source-contract.ts @@ -273,6 +273,15 @@ export const entitySnapshotSchema = z.object({ */ children: z.array(snapshotChildSchema), childrenTotal: z.number().int().nonnegative().optional(), + /** + * BB-385: the keys of the issues that block this one (this issue is + * `blockedBy` them), keeping only blockers still open. Optional and + * additive: the linear source reads relations and sends it, an empty array + * when nothing blocks the issue; github, which has no dependency relation, + * omits it. Absent means the source did not read relations, never that none + * block it, so a caller that needs the fact refuses rather than assumes. + */ + blockedBy: z.array(z.string()).optional(), /** * True when the source could not read the entity's parent and sub-issues * (GitHub rejected the fields, or the relation read errored or was diff --git a/plugins/linear/linear.test.ts b/plugins/linear/linear.test.ts index 9b1fefd9..b1ba153a 100644 --- a/plugins/linear/linear.test.ts +++ b/plugins/linear/linear.test.ts @@ -342,6 +342,7 @@ describe("what stewards reads", () => { ], parent: { id: "uuid-100", key: "ENG-100" }, children: [{ id: "uuid-124", key: "ENG-124", title: "Add test", state: "Todo", stateType: "unstarted", labels: ["bb-managed"] }], + blockedBy: [], linkedPulls: [{ url: "https://github.com/Acme/web/pull/42", key: "Acme/web#42" }], pull: null, viewer: "jane", @@ -349,6 +350,26 @@ describe("what stewards reads", () => { expect(parseSnapshotIssue({ data: { issue: null } })).toBeNull(); }); + it("carries the open blockers from the inverse blocks relations (BB-385)", () => { + const blockers = { + ...raw, + inverseRelations: { + nodes: [ + { id: "r1", type: "blocks", issue: { identifier: "ENG-70", state: { name: "In Progress", type: "started" } } }, + // A completed or canceled blocker no longer blocks. + { id: "r2", type: "blocks", issue: { identifier: "ENG-69", state: { name: "Done", type: "completed" } } }, + { id: "r3", type: "blocks", issue: { identifier: "ENG-68", state: { name: "Canceled", type: "canceled" } } }, + // An unknown state counts as open, so nothing rides on an unread blocker. + { id: "r4", type: "blocks", issue: { identifier: "ENG-67", state: null } }, + // A non-blocks relation is not a blocker, and a duplicate is listed once. + { id: "r5", type: "related", issue: { identifier: "ENG-66", state: { name: "Todo", type: "unstarted" } } }, + { id: "r6", type: "blocks", issue: { identifier: "ENG-70", state: { name: "In Progress", type: "started" } } }, + ], + }, + }; + expect(snapshotOfIssue(parseSnapshotIssue({ data: { issue: blockers } })!, null).blockedBy).toEqual(["ENG-70", "ENG-67"]); + }); + it("orders linked pulls by attachment createdAt descending, regardless of the API's order (BB-316)", () => { const attachments = { nodes: [ diff --git a/plugins/linear/linear.ts b/plugins/linear/linear.ts index fb052f48..f5abb089 100644 --- a/plugins/linear/linear.ts +++ b/plugins/linear/linear.ts @@ -157,7 +157,7 @@ const commentSchema = z.object({ user: person, }); -const relationIssueSchema = z.object({ identifier: z.string(), state: z.object({ name: z.string() }).nullish() }); +const relationIssueSchema = z.object({ identifier: z.string(), state: z.object({ name: z.string(), type: z.string().nullish() }).nullish() }); const relationSchema = z.object({ id: z.string(), type: z.string(), issue: relationIssueSchema.nullish(), relatedIssue: relationIssueSchema.nullish() }); export type IssueRelation = z.infer; @@ -460,6 +460,7 @@ const SNAPSHOT_FIELDS = "state { name type } team { id key } assignee { name displayName email } creator { name displayName email } " + "labels { nodes { name } } parent { id identifier } " + "children { nodes { id identifier title state { name type } labels { nodes { name } } } } " + + "inverseRelations { nodes { id type issue { identifier state { name type } } } } " + `comments(last: ${SNAPSHOT_COMMENTS_MAX}) { nodes { id body createdAt url user { name displayName email } } } ` + "attachments { nodes { url sourceType createdAt } }"; @@ -516,6 +517,10 @@ const snapshotIssueSchema = z.object({ ), }) .nullish(), + // BB-385: the inverse `blocks` relations, so a snapshot can name the open + // issues that block this one. The `Issue` query already reads them for the + // `linear_issue` tool; the snapshot query now reads them too. + inverseRelations: z.object({ nodes: z.array(relationSchema) }).nullish(), comments: z.object({ nodes: z.array(commentSchema.extend({ id: z.string() })) }).nullish(), attachments: z.object({ nodes: z.array(z.object({ url: z.string().nullish(), sourceType: z.string().nullish(), createdAt: z.string().nullish() })) }).nullish(), }); @@ -535,6 +540,27 @@ export function pullKey(url: string): string | null { return m === null ? null : `${m[1]}/${m[2]}#${m[3]}`; } +/** + * BB-385: the open blockers of an issue, from its inverse relations. A + * `blocks` inverse relation names an issue that blocks this one; a blocker + * whose state type is completed or canceled no longer blocks. An unknown + * state counts as open, so a promotion never rides on a blocker it could not + * read. + */ +export function openBlockers(issue: SnapshotIssue): string[] { + const closed = new Set(["completed", "canceled"]); + const out: string[] = []; + for (const relation of issue.inverseRelations?.nodes ?? []) { + if (relation.type !== "blocks") continue; + const blocker = relation.issue; + if (blocker === null || blocker === undefined || blocker.identifier === "") continue; + const type = (blocker.state?.type ?? "").trim().toLowerCase(); + if (closed.has(type)) continue; + if (!out.includes(blocker.identifier)) out.push(blocker.identifier); + } + return out; +} + /** * The issue as stewards sees it. Comments are the newest fifty, oldest * first; each body is clipped after its signature is read, so a long @@ -593,6 +619,7 @@ export function snapshotOfIssue(issue: SnapshotIssue, viewer: string | null): En stateType: c.state?.type ?? null, labels: (c.labels?.nodes ?? []).map((l) => l.name), })), + blockedBy: openBlockers(issue), linkedPulls, pull: null, viewer, diff --git a/plugins/linear/source-contract.ts b/plugins/linear/source-contract.ts index afe9dd00..aea729d3 100644 --- a/plugins/linear/source-contract.ts +++ b/plugins/linear/source-contract.ts @@ -273,6 +273,15 @@ export const entitySnapshotSchema = z.object({ */ children: z.array(snapshotChildSchema), childrenTotal: z.number().int().nonnegative().optional(), + /** + * BB-385: the keys of the issues that block this one (this issue is + * `blockedBy` them), keeping only blockers still open. Optional and + * additive: the linear source reads relations and sends it, an empty array + * when nothing blocks the issue; github, which has no dependency relation, + * omits it. Absent means the source did not read relations, never that none + * block it, so a caller that needs the fact refuses rather than assumes. + */ + blockedBy: z.array(z.string()).optional(), /** * True when the source could not read the entity's parent and sub-issues * (GitHub rejected the fields, or the relation read errored or was diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index e6d51185..acde5dcc 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -116,7 +116,20 @@ install on a stock bb: one repository, no Linear, no hooks service. [store.ts](store.ts)); the digest lists each write and counts the refusals. The flag is re-read on every call, so turning it off refuses at once, and a ticket, ledger or configuration that cannot be read refuses and writes - nothing. The `.bb` keys land in a later, owner-reviewed pull request. + nothing. Stage 3 adds a second opt-in, `backlog.promote: true`, and with it + the gated `backlog_promote { key }` tool ([backlog-promote.ts](backlog-promote.ts)): + it moves one ticket to Todo, adds the adoption label and assigns it to this + server, then the ordinary ticket steward adopts it. The plugin, not the + model, picks the ticket — the top-ordered ready-looking un-adopted Backlog + ticket, by the owner's priority and then oldest `createdAt` first, with the + key as a final tiebreak (Linear returns newest first, so the tiebreak is + explicit) — and ignores a `key` that is not that ticket. It refuses when Todo plus In Progress is at + or over `backlog.wipLimit`, never edits a description, cancels, closes or + changes a priority, and never promotes an adopted ticket, one in a + non-Backlog state, or one with an open `blockedBy` (the linear snapshot now + carries the open blocker keys). Each promotion is its own digest line; a + WIP-full or no-candidate refusal repeated for an unchanged reason collapses + to one. The `.bb` keys land in a later, owner-reviewed pull request. - **The reconcile loop.** linear and github-watcher hold leases on the hooks service for the project's teams and repos and for every bound entity, and ring this plugin on a doorbell. A ring is debounced, the entity is snapshotted, compared with diff --git a/plugins/stewards/backlog-promote.test.ts b/plugins/stewards/backlog-promote.test.ts new file mode 100644 index 00000000..66c1a758 --- /dev/null +++ b/plugins/stewards/backlog-promote.test.ts @@ -0,0 +1,216 @@ +import { describe, expect, it } from "vitest"; +import { + backlogPromoteParamsSchema, + candidateEligible, + decidePromote, + hasOpenBlocker, + isAdopted, + isBacklogState, + isReadyLooking, + isTodoOrInProgress, + orderedCandidates, + promoteAcceptedDetail, + promotePlan, + promoteRefusedDetail, + wipCount, + type BacklogPromoteIssue, + type PromoteConfig, + type PromoteDetail, +} from "./backlog-promote.js"; + +const config = (over: Partial = {}): PromoteConfig => ({ + promote: true, + team: "BB", + wipLimit: 5, + label: "bb-managed", + adoptedLabels: ["bb-managed", "initiative"], + ...over, +}); + +const issue = (over: Partial = {}): BacklogPromoteIssue => ({ + id: "uuid-1", + key: "BB-1", + unit: "BB", + title: "Fix login", + state: "Backlog", + stateType: "backlog", + labels: [], + assignees: [], + priority: null, + createdAt: "2026-10-01T00:00:00Z", + ...over, +}); + +const detail = (over: Partial = {}): PromoteDetail => ({ description: "Users cannot log in.", blockedBy: [], ...over }); + +const detailsOf = (entries: Array<[string, Partial]>): Map => new Map(entries.map(([key, over]) => [key, detail(over)])); + +const decide = (over: Partial[0]> = {}) => decidePromote({ params: {}, issues: [issue()], details: detailsOf([["BB-1", {}]]), config: config(), ...over }); + +const reason = (result: ReturnType): string => (result.ok ? "" : result.reason); + +describe("the promotion opt-in and authority limits (BB-385)", () => { + it("refuses everything while backlog.promote is off", () => { + expect(reason(decide({ config: config({ promote: false }) }))).toMatch(/promote is off/u); + }); + + it("refuses a call carrying a description, state, assignee, cancel, close, label, priority or relation", () => { + for (const field of ["description", "state", "assignee", "cancel", "close", "addLabels", "priority", "relations"]) { + const raw = { key: "BB-1", [field]: "x" } as unknown as Parameters[0]["params"]; + expect(reason(decide({ params: raw }))).toMatch(new RegExp(`may not carry ${field}`, "u")); + } + // The tool's own schema is strict, so the same call never parses. + expect(backlogPromoteParamsSchema.safeParse({ key: "BB-1", state: "Todo" }).success).toBe(false); + expect(backlogPromoteParamsSchema.safeParse({ key: "BB-1" }).success).toBe(true); + expect(backlogPromoteParamsSchema.safeParse({}).success).toBe(true); + }); + + it("plans exactly Todo, the adoption label and this server's own login", () => { + const result = decide(); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.plan).toEqual({ key: "BB-1", state: "Todo", addLabels: ["bb-managed"], assignee: "me" }); + expect(result.candidate.key).toBe("BB-1"); + } + expect(promotePlan(issue({ key: "BB-2" }), config())).toEqual({ key: "BB-2", state: "Todo", addLabels: ["bb-managed"], assignee: "me" }); + }); +}); + +describe("the WIP limit (BB-385)", () => { + const todo = (over: Partial = {}) => issue({ key: `BB-${Math.random()}`, state: "Todo", stateType: "unstarted", ...over }); + const inProgress = (over: Partial = {}) => issue({ key: `BB-${Math.random()}`, state: "In Progress", stateType: "started", ...over }); + + it("counts only Todo and In Progress by name, not In Review or another started state", () => { + const issues = [todo(), inProgress(), issue({ state: "Backlog", stateType: "backlog" }), issue({ state: "Done", stateType: "completed" })]; + expect(wipCount(issues, config())).toBe(2); + expect(isTodoOrInProgress(issue({ state: "Todo", stateType: "unstarted" }))).toBe(true); + expect(isTodoOrInProgress(issue({ state: "In Progress", stateType: "started" }))).toBe(true); + expect(isTodoOrInProgress(issue({ state: "Todo", stateType: null }))).toBe(true); + // In Review is a `started` state in the BB team, but it is not work in progress for the ceiling. + expect(isTodoOrInProgress(issue({ state: "In Review", stateType: "started" }))).toBe(false); + expect(isTodoOrInProgress(issue({ state: "Doing", stateType: "started" }))).toBe(false); + expect(isTodoOrInProgress(issue({ state: "Ready", stateType: "unstarted" }))).toBe(false); + expect(isTodoOrInProgress(issue({ state: "Backlog", stateType: "backlog" }))).toBe(false); + }); + + it("refuses at the ceiling and promotes below it", () => { + const atLimit = [todo(), inProgress(), todo(), inProgress(), todo()]; + expect(reason(decide({ issues: atLimit, details: detailsOf([]), config: config({ wipLimit: 5 }) }))).toMatch(/WIP full/u); + const below = [todo(), inProgress(), todo(), inProgress()]; + expect(decide({ issues: below, details: detailsOf([]), config: config({ wipLimit: 5 }) }).ok).toBe(false); + // Below the ceiling but with no candidate, the refusal is "no eligible candidate". + expect(reason(decide({ issues: below, details: detailsOf([]), config: config({ wipLimit: 5 }) }))).toBe("no eligible candidate"); + }); + + it("counts only the watched team", () => { + expect(wipCount([todo({ unit: "OPS" }), todo({ unit: "BB" })], config())).toBe(1); + }); +}); + +describe("the candidate rules (BB-385)", () => { + it("never picks a ticket that is not in Backlog", () => { + expect(isBacklogState(issue({ state: "Backlog", stateType: "backlog" }))).toBe(true); + expect(isBacklogState(issue({ state: "Backlog", stateType: null }))).toBe(true); + expect(isBacklogState(issue({ state: "Todo", stateType: "unstarted" }))).toBe(false); + // A non-Backlog ticket is not a candidate even when it is the only one. + expect(reason(decide({ issues: [issue({ state: "Todo", stateType: "unstarted" })], details: detailsOf([]) }))).toBe("no eligible candidate"); + }); + + it("never picks an adopted ticket: an adoption label, an initiative or any assignee", () => { + expect(isAdopted(issue({ labels: ["bb-managed"] }), config())).toBe(true); + expect(isAdopted(issue({ labels: ["initiative"] }), config())).toBe(true); + expect(isAdopted(issue({ assignees: ["jane"] }), config())).toBe(true); + expect(isAdopted(issue(), config())).toBe(false); + expect(orderedCandidates([issue({ labels: ["bb-managed"] }), issue({ key: "BB-2", assignees: ["jane"] }), issue({ key: "BB-3" })], config()).map((i) => i.key)).toEqual(["BB-3"]); + }); + + it("never picks a ticket with an open blocker", () => { + expect(hasOpenBlocker(detail({ blockedBy: ["BB-9"] }))).toBe(true); + expect(hasOpenBlocker(detail({ blockedBy: [] }))).toBe(false); + // The only candidate is blocked, so nothing is promoted. + expect(reason(decide({ details: detailsOf([["BB-1", { blockedBy: ["BB-9"] }]]) }))).toBe("no eligible candidate"); + // A blocked top ticket is skipped for the next ready-looking one. + const result = decide({ + issues: [issue({ key: "BB-1" }), issue({ key: "BB-2" })], + details: detailsOf([ + ["BB-1", { blockedBy: ["BB-9"] }], + ["BB-2", {}], + ]), + }); + expect(result.ok).toBe(true); + if (result.ok) expect(result.plan.key).toBe("BB-2"); + }); + + it("requires a non-empty title and description, and skips a ticket that lacks one", () => { + expect(isReadyLooking(issue(), detail())).toBe(true); + expect(isReadyLooking(issue({ title: " " }), detail())).toBe(false); + expect(isReadyLooking(issue(), detail({ description: " " }))).toBe(false); + expect(isReadyLooking(issue(), detail({ description: null }))).toBe(false); + expect(candidateEligible(issue(), detail())).toBe(true); + // The top ticket is empty, so the next ready-looking one is promoted. + const result = decide({ + issues: [issue({ key: "BB-1" }), issue({ key: "BB-2" })], + details: detailsOf([ + ["BB-1", { description: " " }], + ["BB-2", {}], + ]), + }); + expect(result.ok).toBe(true); + if (result.ok) expect(result.plan.key).toBe("BB-2"); + }); + + it("skips a candidate whose detail was not read, but promotes a later read one", () => { + const result = decide({ + issues: [issue({ key: "BB-1" }), issue({ key: "BB-2" })], + details: detailsOf([["BB-2", {}]]), + }); + expect(result.ok).toBe(true); + if (result.ok) expect(result.plan.key).toBe("BB-2"); + }); +}); + +describe("the ordering (BB-385)", () => { + it("orders by the owner's priority, then oldest first, and never changes priority", () => { + const issues = [ + issue({ key: "BB-1", priority: "Low", createdAt: "2026-10-05T00:00:00Z" }), + issue({ key: "BB-2", priority: "Urgent", createdAt: "2026-10-06T00:00:00Z" }), + issue({ key: "BB-3", priority: null, createdAt: "2026-10-07T00:00:00Z" }), + // The source returns newest `createdAt` first (Linear's own order): the + // two High tickets are passed newest-first and must come out oldest-first. + issue({ key: "BB-4", priority: "High", createdAt: "2026-10-09T00:00:00Z" }), + issue({ key: "BB-5", priority: "Medium", createdAt: "2026-10-03T00:00:00Z" }), + issue({ key: "BB-6", priority: "High", createdAt: "2026-10-08T00:00:00Z" }), + ]; + expect(orderedCandidates(issues, config()).map((i) => i.key)).toEqual(["BB-2", "BB-6", "BB-4", "BB-5", "BB-1", "BB-3"]); + // The plan carries no priority, so a promotion never writes one. + const result = decide({ issues, details: detailsOf(issues.map((i) => [i.key, {}])) }); + expect(result.ok).toBe(true); + if (result.ok) expect(result.plan).toEqual({ key: "BB-2", state: "Todo", addLabels: ["bb-managed"], assignee: "me" }); + }); + + it("treats an unknown priority as unset rather than ranking above a hand-set one", () => { + const issues = [issue({ key: "BB-1", priority: "P0-ish" }), issue({ key: "BB-2", priority: "low" })]; + expect(orderedCandidates(issues, config()).map((i) => i.key)).toEqual(["BB-2", "BB-1"]); + }); +}); + +describe("the key hint (BB-385)", () => { + it("ignores a key that is not the top-ordered eligible ticket", () => { + const issues = [issue({ key: "BB-1", priority: "Urgent" }), issue({ key: "BB-2", priority: "Low" })]; + const details = detailsOf([ + ["BB-1", {}], + ["BB-2", {}], + ]); + const result = decide({ params: { key: "BB-2" }, issues, details }); + expect(result.ok).toBe(true); + if (result.ok) expect(result.plan.key).toBe("BB-1"); + }); +}); + +describe("the ledger entries (BB-385)", () => { + it("names the promoted ticket, the state, the label and the assignee", () => { + expect(promoteAcceptedDetail(issue({ key: "BB-1" }), { key: "BB-1" }, config())).toEqual({ state: "Todo", addLabels: ["bb-managed"], assignee: "me", requestedKey: "BB-1", promoted: "BB-1" }); + expect(promoteRefusedDetail({ key: "BB-2" })).toEqual({ requestedKey: "BB-2" }); + expect(promoteRefusedDetail({})).toEqual({ requestedKey: null }); + }); +}); diff --git a/plugins/stewards/backlog-promote.ts b/plugins/stewards/backlog-promote.ts new file mode 100644 index 00000000..59190f16 --- /dev/null +++ b/plugins/stewards/backlog-promote.ts @@ -0,0 +1,187 @@ +// The backlog steward's promotion write (BB-385), as pure functions: the WIP +// ceiling, the ordering, the eligibility rules, the authority limits and the +// ledger entry shape. Nothing here reads a file, a source or the store; +// server.ts hands the values in and writes the plan through the source +// contract. Keeping the limits here is the point: the playbook says them, but +// the plugin enforces them. +import { z } from "zod"; + +/** + * The one gated tool's parameters. `key` is a hint only: the plugin picks the + * top-ordered eligible ticket itself, so a `key` that is not that ticket is + * ignored (the acceptance criteria's "the plugin picks the candidate"). + */ +export const backlogPromoteParamsSchema = z.object({ key: z.string().trim().min(1).max(200).optional() }).strict(); +export type BacklogPromoteParams = z.infer; + +/** + * Fields a promotion may never carry. The plugin, not the model, decides the + * state, the label and the assignee, and it never edits a description, cancels + * or closes. The tool's schema is strict, so a call carrying one is rejected + * before it runs; this list is the second check, so the pure decision refuses + * one too (a bug in the wiring cannot smuggle a description or a state through). + */ +export const FORBIDDEN_PROMOTE_FIELDS = ["description", "state", "assignee", "cancel", "close", "addLabels", "priority", "relations"] as const; + +/** The only state a promotion sets, and the only assignee it names. */ +export const PROMOTE_STATE = "Todo"; +export const PROMOTE_ASSIGNEE = "me" as const; + +/** The priority order the owner sets by hand; anything else (unset, unknown) ranks last. */ +const PRIORITY_RANK: Record = { urgent: 0, high: 1, medium: 2, low: 3 }; + +/** The stable refusal reasons the digest collapses; anything else is one line. */ +export const PROMOTE_WIP_FULL = "WIP full"; +export const PROMOTE_NO_CANDIDATE = "no eligible candidate"; + +/** What the tool read about one open issue, from the fresh backlog read. */ +export type BacklogPromoteIssue = { + /** The source's id for the issue (Linear's UUID), what the ledger records. */ + id: string; + key: string; + /** The team key the ticket lives in, as the backlog read reports it. */ + unit: string; + title: string | null; + state: string; + stateType: string | null; + labels: string[]; + assignees: string[]; + priority: string | null; + createdAt: string | null; +}; + +/** What the issue read adds: readiness and the open blockers. */ +export type PromoteDetail = { + description: string | null; + /** The keys of the issues that still block this one; empty when none. */ + blockedBy: string[]; +}; + +/** The project's promotion limits and the fixed labels no write may touch. */ +export type PromoteConfig = { + promote: boolean; + /** The team the binding watches. */ + team: string; + /** Stage 3's Todo + In Progress ceiling. */ + wipLimit: number; + /** The project's adoption label (project.label). */ + label: string; + /** Labels a promotion may never add and that mark a ticket adopted: the adoption label, initiative, and any a playbook adopts on. */ + adoptedLabels: string[]; +}; + +/** The plan a decision accepted, ready to write through the source contract. */ +export type PromotePlan = { key: string; state: string; addLabels: string[]; assignee: "me" }; + +export type PromoteDecision = { ok: true; plan: PromotePlan; candidate: BacklogPromoteIssue } | { ok: false; reason: string }; + +const sameTeam = (issue: BacklogPromoteIssue, config: PromoteConfig): boolean => issue.unit.trim().toUpperCase() === config.team.trim().toUpperCase(); + +/** + * Whether an issue sits in Todo or In Progress, the two states the WIP + * ceiling counts. This is by state name, not state type: "In Review" is a + * `started` state in Linear's BB team, and a ticket in review is not work in + * progress for the ceiling. + */ +export function isTodoOrInProgress(issue: BacklogPromoteIssue): boolean { + const name = issue.state.trim().toLowerCase(); + return name === "todo" || name === "in progress"; +} + +/** Whether an issue sits in the team's Backlog state. */ +export function isBacklogState(issue: BacklogPromoteIssue): boolean { + const type = (issue.stateType ?? "").trim().toLowerCase(); + if (type === "backlog") return true; + return issue.state.trim().toLowerCase() === "backlog"; +} + +/** Whether an issue is already adopted: it carries an adoption label or any assignee. */ +export function isAdopted(issue: BacklogPromoteIssue, config: PromoteConfig): boolean { + if (issue.assignees.length > 0) return true; + const labels = new Set(issue.labels.map((l) => l.trim().toLowerCase())); + return config.adoptedLabels.some((l) => labels.has(l.trim().toLowerCase())); +} + +/** Whether the ticket looks ready to be worked: a title and a non-empty description. */ +export function isReadyLooking(issue: BacklogPromoteIssue, detail: PromoteDetail): boolean { + return (issue.title ?? "").trim() !== "" && (detail.description ?? "").trim() !== ""; +} + +/** Whether an issue still has an open blocker, so it is never promoted. */ +export function hasOpenBlocker(detail: PromoteDetail): boolean { + return detail.blockedBy.length > 0; +} + +/** Whether a candidate may be promoted at all: ready-looking and unblocked. */ +export function candidateEligible(issue: BacklogPromoteIssue, detail: PromoteDetail): boolean { + return isReadyLooking(issue, detail) && !hasOpenBlocker(detail); +} + +/** How many Todo or In Progress issues the team has, the WIP ceiling's numerator. */ +export function wipCount(issues: readonly BacklogPromoteIssue[], config: PromoteConfig): number { + return issues.filter((issue) => sameTeam(issue, config) && isTodoOrInProgress(issue)).length; +} + +const createdAtMs = (issue: BacklogPromoteIssue): number => { + const t = issue.createdAt === null ? Number.NaN : Date.parse(issue.createdAt); + return Number.isNaN(t) ? Number.POSITIVE_INFINITY : t; +}; + +/** + * The eligible tickets in promotion order: un-adopted Backlog tickets in the + * watched team, ordered by the owner's priority and then oldest first (the + * `createdAt` Linear already returns), with the key as a final tiebreak. The + * plugin never ranks a ticket above what the owner set by hand. + * + * The tiebreak is explicit because `sourceBacklog` sets no `orderBy` and + * Linear returns newest `createdAt` first, so keeping the source order would + * promote the newest ticket, the opposite of the criterion. + */ +export function orderedCandidates(issues: readonly BacklogPromoteIssue[], config: PromoteConfig): BacklogPromoteIssue[] { + const rank = (issue: BacklogPromoteIssue): number => PRIORITY_RANK[(issue.priority ?? "").trim().toLowerCase()] ?? 4; + return issues.filter((issue) => sameTeam(issue, config) && isBacklogState(issue) && !isAdopted(issue, config)).sort((a, b) => rank(a) - rank(b) || createdAtMs(a) - createdAtMs(b) || a.key.localeCompare(b.key)); +} + +/** The one plan a promotion writes: Todo, the adoption label, and this server's own login. */ +export function promotePlan(candidate: BacklogPromoteIssue, config: PromoteConfig): PromotePlan { + return { key: candidate.key, state: PROMOTE_STATE, addLabels: [config.label], assignee: PROMOTE_ASSIGNEE }; +} + +/** + * The whole rule set, in one pure decision. The caller reads the team's fresh + * backlog and the candidate issues' details first (a read that fails is the + * caller's to refuse); this returns the exact plan to write, or the reason it + * refused. `details` holds what the issue read added for the candidates the + * caller looked at; a candidate with no detail is skipped, so a caller that + * stopped reading at the first eligible one still gets the same pick. + */ +export function decidePromote(input: { params: BacklogPromoteParams; issues: readonly BacklogPromoteIssue[]; details: ReadonlyMap; config: PromoteConfig }): PromoteDecision { + const { params, issues, details, config } = input; + const refuse = (reason: string): PromoteDecision => ({ ok: false, reason }); + + if (!config.promote) return refuse("backlog.promote is off; the backlog steward promotes nothing"); + + for (const field of FORBIDDEN_PROMOTE_FIELDS) { + if (Object.prototype.hasOwnProperty.call(params, field)) return refuse(`a promotion may not carry ${field}; the plugin picks the ticket, the state, the label and the assignee`); + } + + if (wipCount(issues, config) >= config.wipLimit) return refuse(PROMOTE_WIP_FULL); + + for (const candidate of orderedCandidates(issues, config)) { + const detail = details.get(candidate.key); + if (detail === undefined) continue; + if (!candidateEligible(candidate, detail)) continue; + return { ok: true, plan: promotePlan(candidate, config), candidate }; + } + return refuse(PROMOTE_NO_CANDIDATE); +} + +/** The ledger detail for an accepted promotion, recorded beside the write. */ +export function promoteAcceptedDetail(candidate: BacklogPromoteIssue, params: BacklogPromoteParams, config: PromoteConfig): Record { + return { state: PROMOTE_STATE, addLabels: [config.label], assignee: PROMOTE_ASSIGNEE, requestedKey: params.key ?? null, promoted: candidate.key }; +} + +/** The ledger detail for a refused promotion, so the digest can show the reason. */ +export function promoteRefusedDetail(params: BacklogPromoteParams): Record { + return { requestedKey: params.key ?? null }; +} diff --git a/plugins/stewards/backlog-triage.ts b/plugins/stewards/backlog-triage.ts index 069d2ab8..e4e354bc 100644 --- a/plugins/stewards/backlog-triage.ts +++ b/plugins/stewards/backlog-triage.ts @@ -87,7 +87,7 @@ export const backlogWriteSchema = z.object({ issueKey: z.string(), at: z.number(), outcome: z.enum(["accepted", "refused"]), - kind: z.enum(["label", "relation", "priority", "comment", "triage"]), + kind: z.enum(["label", "relation", "priority", "comment", "triage", "promote"]), detail: z.record(z.string(), z.unknown()).default({}), reason: z.string().nullable().default(null), }); diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 62fc1d81..49e0e136 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -132,15 +132,16 @@ describe("the project file", () => { if (!absent.ok) throw new Error(absent.error); expect(absent.value.backlog).toBeUndefined(); - const explicit = parseProjectFile(JSON.stringify({ version: 1, backlog: { team: " bb ", wipLimit: 3, staleDays: 21, commentsPerWeek: 2, triage: true } })); + const explicit = parseProjectFile(JSON.stringify({ version: 1, backlog: { team: " bb ", wipLimit: 3, staleDays: 21, commentsPerWeek: 2, triage: true, promote: true } })); if (!explicit.ok) throw new Error(explicit.error); - expect(explicit.value.backlog).toEqual({ team: "BB", wipLimit: 3, staleDays: 21, commentsPerWeek: 2, triage: true }); + expect(explicit.value.backlog).toEqual({ team: "BB", wipLimit: 3, staleDays: 21, commentsPerWeek: 2, triage: true, promote: true }); const defaults = parseProjectFile(JSON.stringify({ version: 1, backlog: {} })); if (!defaults.ok) throw new Error(defaults.error); - expect(defaults.value.backlog).toEqual({ wipLimit: 5, staleDays: 14, commentsPerWeek: 1, triage: false }); + expect(defaults.value.backlog).toEqual({ wipLimit: 5, staleDays: 14, commentsPerWeek: 1, triage: false, promote: false }); expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { bogus: true } }))).toMatchObject({ ok: false }); + expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { promote: "yes" } }))).toMatchObject({ ok: false }); expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { wipLimit: 0 } }))).toMatchObject({ ok: false }); expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { staleDays: -1 } }))).toMatchObject({ ok: false }); expect(parseProjectFile(JSON.stringify({ version: 1, backlog: { commentsPerWeek: 0 } }))).toMatchObject({ ok: false }); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index 36fef20c..f722008a 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -431,6 +431,14 @@ export const backlogSchema = z * it, so turning it off refuses at once. */ triage: z.boolean().default(false), + /** + * Stage 3 (BB-385): whether the backlog steward may promote one + * ready-looking un-adopted Backlog ticket to Todo under the WIP limit. + * Off by default, so a merged plugin changes nothing until the owner + * enables it. The tool is offered only when it is true, and every call + * re-reads it, so turning it off refuses at once. + */ + promote: z.boolean().default(false), }) .strict(); export type BacklogConfig = z.infer; diff --git a/plugins/stewards/contract.test.ts b/plugins/stewards/contract.test.ts index 172d470b..c11d61ee 100644 --- a/plugins/stewards/contract.test.ts +++ b/plugins/stewards/contract.test.ts @@ -52,6 +52,37 @@ describe("source-contract.ts", () => { expect(entitySnapshotSchema.safeParse({ ...snapshot, playbook: 3 }).success).toBe(false); }); + it("carries an optional, additive blockedBy on the issue snapshot (BB-385)", () => { + const base = { + source: "linear" as const, + kind: "issue" as const, + id: "ENG-1", + key: "ENG-1", + url: null, + title: "Fix login", + state: "Backlog", + stateType: "backlog", + unit: "ENG", + labels: [], + author: null, + assignees: [], + priority: null, + estimate: null, + description: "Users cannot log in.", + createdAt: null, + updatedAt: null, + comments: [], + parent: null, + children: [], + linkedPulls: [], + pull: null, + viewer: null, + }; + expect(entitySnapshotSchema.parse({ ...base, blockedBy: ["ENG-2"] }).blockedBy).toEqual(["ENG-2"]); + // Absent by default: a source that did not read relations omits it. + expect(entitySnapshotSchema.parse(base).blockedBy).toBeUndefined(); + }); + it("reads the last signature in a body", () => { expect(signedBy(`hello\n\n${signatureLine("thr_abc")}`)).toBe("thr_abc"); expect(signedBy(`> ${signatureLine("thr_old")}\n\nreply\n\n${signatureLine("thr_new")}`)).toBe("thr_new"); diff --git a/plugins/stewards/nightly.test.ts b/plugins/stewards/nightly.test.ts index 1fdb8926..ddbc4787 100644 --- a/plugins/stewards/nightly.test.ts +++ b/plugins/stewards/nightly.test.ts @@ -5,6 +5,7 @@ import { MIGRATIONS, createStore } from "./store.js"; import { formatRecords, type DigestRecords } from "./wake.js"; import type { BacklogLook } from "./ops.js"; import type { BacklogIssue } from "./source-contract.js"; +import type { BacklogWrite } from "./backlog-triage.js"; const NY = { at: "01:00", until: "02:45", timezone: "America/New_York" }; // 2026-10-14 05:30Z is 01:30 in New York (EDT, UTC-4). @@ -302,6 +303,31 @@ describe("the backlog report (BB-334)", () => { expect(formatRecords(emptyRecords(undefined), []).join("\n")).not.toContain("### Backlog"); }); + it("lists each promotion and collapses repeated refusals by their unchanged reason (BB-385)", () => { + const writes: BacklogWrite[] = [ + { id: "w1", projectId: "p1", team: "BB", issueId: "uuid-1", issueKey: "BB-1", at: NOW, outcome: "accepted", kind: "promote", detail: {}, reason: null }, + { id: "w2", projectId: "p1", team: "BB", issueId: "", issueKey: "", at: NOW, outcome: "refused", kind: "promote", detail: {}, reason: "WIP full" }, + { id: "w3", projectId: "p1", team: "BB", issueId: "", issueKey: "", at: NOW, outcome: "refused", kind: "promote", detail: {}, reason: "WIP full" }, + { id: "w4", projectId: "p1", team: "BB", issueId: "", issueKey: "", at: NOW, outcome: "refused", kind: "promote", detail: {}, reason: "no eligible candidate" }, + { id: "w5", projectId: "p1", team: "BB", issueId: "uuid-2", issueKey: "BB-2", at: NOW, outcome: "accepted", kind: "promote", detail: {}, reason: null }, + // A triage write is still one Writes line, and is not a promotion. + { id: "w6", projectId: "p1", team: "BB", issueId: "uuid-3", issueKey: "BB-3", at: NOW, outcome: "accepted", kind: "label", detail: {}, reason: null }, + ]; + const report = backlogDigest(look([issue({ title: "Fix login" })]), null, { staleDays: 14, writes }, NOW); + expect(report.promotions.map((p) => p.issueKey)).toEqual(["BB-1", "BB-2"]); + expect(report.writes.map((w) => `${w.issueKey} ${w.kind}`)).toEqual(["BB-3 label"]); + expect(report.refusals).toBe(3); + expect(report.refusalReasons).toEqual([ + { reason: "WIP full", count: 2 }, + { reason: "no eligible candidate", count: 1 }, + ]); + const text = formatRecords(emptyRecords([report]), []).join("\n"); + expect(text).toContain(" - Writes: BB-3 label"); + expect(text).toContain(" - Promoted: BB-1"); + expect(text).toContain(" - Promoted: BB-2"); + expect(text).toContain(" - Refused: WIP full (2); no eligible candidate (1)"); + }); + it("shows a failed read as one problem line, never an empty backlog", () => { const failed = backlogDigest(look([], { error: "Linear rate limited the read" }), null, { staleDays: 14 }, NOW); const text = formatRecords(emptyRecords([failed]), []).join("\n"); diff --git a/plugins/stewards/nightly.ts b/plugins/stewards/nightly.ts index 2ac5dc40..79a161c1 100644 --- a/plugins/stewards/nightly.ts +++ b/plugins/stewards/nightly.ts @@ -262,8 +262,15 @@ export type BacklogDigest = { next: BacklogNext[]; /** BB-341: the accepted triage writes since the previous digest, each a ticket and a kind. */ writes: Array<{ issueKey: string; kind: string; at: number }>; - /** BB-341: how many triage calls were refused in the window. */ + /** BB-385: the accepted promotions, each its own digest line. */ + promotions: Array<{ issueKey: string; at: number }>; + /** BB-341: how many backlog calls were refused in the window. */ refusals: number; + /** + * BB-385: the refusals grouped by their unchanged reason, one line each, so + * a WIP-full or no-candidate refusal repeated every pass collapses to one. + */ + refusalReasons: Array<{ reason: string; count: number }>; }; const daysSince = (from: string | null, now: number): number | null => { @@ -388,7 +395,9 @@ export function backlogDigest(look: BacklogLook, previous: BacklogSnapshot | nul duplicates: duplicateBacklog(issues), stale: staleBacklog(issues, opts.staleDays, now), next: nextBacklog(issues, now), - writes: ledger.filter((w) => w.outcome === "accepted").map((w) => ({ issueKey: w.issueKey, kind: w.kind, at: w.at })), + writes: ledger.filter((w) => w.outcome === "accepted" && w.kind !== "promote").map((w) => ({ issueKey: w.issueKey, kind: w.kind, at: w.at })), + promotions: ledger.filter((w) => w.outcome === "accepted" && w.kind === "promote").map((w) => ({ issueKey: w.issueKey, at: w.at })), refusals: ledger.filter((w) => w.outcome === "refused").length, + refusalReasons: [...ledger.filter((w) => w.outcome === "refused").reduce((by, w) => by.set(w.reason ?? "refused", (by.get(w.reason ?? "refused") ?? 0) + 1), new Map())].map(([reason, count]) => ({ reason, count })), }; } diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index e167cb94..40e57af8 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -12655,7 +12655,8 @@ Watch the team's whole open backlog and triage the un-adopted tickets that need expect(wake).toContain("Comments: 1 per ticket per rolling seven days"); expect(wake).toContain("Stale window: 14 days"); expect(wake).toContain("Watch the team's whole open backlog"); - expect(wake).toContain("`backlog_triage` is the only Linear write available to you"); + expect(wake).toContain("`backlog_triage` adds labels"); + expect(wake).toContain("`backlog.promote` is off; no promotion is offered"); expect(wake).toContain("`steward_report` ends the turn"); }); }); @@ -12801,7 +12802,183 @@ describe("the backlog triage writes (BB-341)", () => { const project = t.spawns.find((s) => s.title === "Acme project steward")!.id; const digest = t.sends.filter((s) => s.threadId === project).at(-1)!.text; expect(digest).toContain("- Writes: BB-1 label"); - expect(digest).toContain("- Refused: 1"); + expect(digest).toMatch(/- Refused: size:XL .*\(1\)/u); + }); +}); + +describe("the backlog promotion write (BB-385)", () => { + const backlogIssue = (over: Record = {}) => ({ id: "uuid-1", key: "BB-1", title: "Fix login", state: "Backlog", stateType: "backlog", unit: "BB", labels: [], assignees: [], priority: null, estimate: null, createdAt: "2026-10-01T00:00:00Z", updatedAt: "2026-10-01T00:00:00Z", ...over }); + + /** A project with a backlog role and its steward thread, and the tickets the tool reads. */ + async function promoting(options: { promote?: boolean; block?: Record; backlog?: Array>; tickets?: Array<{ key: string; over?: Partial }> } = {}) { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["BB"] }, backlog: { triage: true, promote: options.promote ?? true, ...(options.block ?? {}) } }); + t.files[ROLES_FILE] = JSON.stringify({ version: 2, roles: { backlog: { backlog: { team: "BB" } } }, holders: { jane: ["backlog"] } }); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + t.setBacklog(options.backlog ?? [backlogIssue()]); + await t.hooks.sweep(); + await t.flush(); + const binding = t.hooks.store.byEntity("ops", "backlog/BB")!; + t.hooks.store.patch(binding.id, { threadId: "thr_backlog" }); + t.threads.set("thr_backlog", { status: "idle", archivedAt: null }); + for (const ticket of options.tickets ?? [{ key: "BB-1" }]) { + t.entities.set(ticket.key, issue({ id: ticket.key === "BB-1" ? "uuid-1" : `uuid-${ticket.key}`, key: ticket.key, unit: "BB", labels: [], assignees: [], state: "Backlog", stateType: "backlog", priority: null, blockedBy: [], ...(ticket.over ?? {}) })); + } + return { t, binding }; + } + + const tools = async (t: Awaited>, id: string) => (await t.harness.behavior.resolveAgentConfiguration(makePluginAgentConfigurationContext({ thread: { id, title: null, parentThreadId: null, sourceThreadId: null } }))).tools.map((x) => x.name); + + it("is offered only when backlog.promote is true, and absent writes nothing", async () => { + const readTools = ["backlog_triage", "ticket_read", "ticket_search", "steward_report", "steward_update"]; + const off = await promoting({ promote: false }); + expect(await tools(off.t, "thr_backlog")).toEqual(readTools); + const refused = await off.t.tool("backlog_promote", { key: "BB-1" }, "thr_backlog"); + expect(refused.error).toBe(true); + expect(off.t.linearWrites).toEqual([]); + + const on = await promoting({ promote: true }); + expect(await tools(on.t, "thr_backlog")).toEqual(["backlog_triage", "backlog_promote", "ticket_read", "ticket_search", "steward_report", "steward_update"]); + }); + + it("promotes the top-ordered eligible ticket to Todo with the adoption label and this server's login", async () => { + const { t } = await promoting({ backlog: [backlogIssue({ key: "BB-1" }), backlogIssue({ id: "uuid-2", key: "BB-2", priority: "Urgent" })], tickets: [{ key: "BB-1" }, { key: "BB-2", over: { priority: "Urgent", description: "Add SSO." } }] }); + const result = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(result.error).toBe(false); + expect(result.text).toMatch(/Promoted BB-2/u); + const write = t.linearWrites.find((w) => w.method === "sourceUpdateIssue")!; + expect(write.input).toMatchObject({ key: "BB-2", state: "Todo", addLabels: ["bb-managed"], assignee: "me" }); + const ledger = t.hooks.store.backlogWrites("p1", { team: "BB" }); + expect(ledger).toHaveLength(1); + expect(ledger[0]).toMatchObject({ outcome: "accepted", kind: "promote", issueKey: "BB-2" }); + }); + + it("ignores a key that is not the top-ordered eligible ticket", async () => { + const { t } = await promoting({ backlog: [backlogIssue({ key: "BB-1", priority: "Urgent" }), backlogIssue({ id: "uuid-2", key: "BB-2", priority: "Low" })], tickets: [{ key: "BB-1", over: { priority: "Urgent" } }, { key: "BB-2", over: { priority: "Low" } }] }); + const result = await t.tool("backlog_promote", { key: "BB-2" }, "thr_backlog"); + expect(result.error).toBe(false); + expect(t.linearWrites.find((w) => w.method === "sourceUpdateIssue")!.input.key).toBe("BB-1"); + }); + + it("refuses when Todo plus In Progress is at the WIP limit, records the refusal and writes nothing", async () => { + const { t } = await promoting({ block: { wipLimit: 1 }, backlog: [backlogIssue({ id: "uuid-1", key: "BB-1", state: "Todo", stateType: "unstarted" }), backlogIssue({ id: "uuid-2", key: "BB-2" })], tickets: [{ key: "BB-2" }] }); + const result = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(result.error).toBe(true); + expect(result.text).toMatch(/WIP full/u); + expect(t.linearWrites).toEqual([]); + const ledger = t.hooks.store.backlogWrites("p1", { team: "BB" }); + expect(ledger).toHaveLength(1); + expect(ledger[0]).toMatchObject({ outcome: "refused", kind: "promote", reason: "WIP full" }); + }); + + it("does not count In Review against the WIP limit, only Todo and In Progress", async () => { + const { t } = await promoting({ block: { wipLimit: 1 }, backlog: [backlogIssue({ id: "uuid-1", key: "BB-1", state: "In Review", stateType: "started" }), backlogIssue({ id: "uuid-2", key: "BB-2" })], tickets: [{ key: "BB-2" }] }); + const result = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(result.error).toBe(false); + expect(t.linearWrites.find((w) => w.method === "sourceUpdateIssue")!.input.key).toBe("BB-2"); + }); + + it("promotes at most one ticket per pass, even with room under the limit", async () => { + const { t } = await promoting({ backlog: [backlogIssue({ key: "BB-1" }), backlogIssue({ id: "uuid-2", key: "BB-2" })], tickets: [{ key: "BB-1" }, { key: "BB-2" }] }); + const first = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(first.error).toBe(false); + const second = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(second.error).toBe(true); + expect(second.text).toMatch(/already promoted one ticket this pass/u); + expect(t.linearWrites.filter((w) => w.method === "sourceUpdateIssue")).toHaveLength(1); + const ledger = t.hooks.store.backlogWrites("p1", { team: "BB" }); + expect(ledger.filter((e) => e.outcome === "accepted" && e.kind === "promote")).toHaveLength(1); + expect(ledger.filter((e) => e.outcome === "refused" && e.reason === "already promoted one ticket this pass")).toHaveLength(1); + }); + + it("refuses a truncated backlog read rather than promoting on part of it", async () => { + const { t } = await promoting({ promote: true }); + t.setBacklogTruncated(true); + const result = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(result.error).toBe(true); + expect(result.text).toMatch(/truncated/u); + expect(t.linearWrites).toEqual([]); + expect(t.hooks.store.backlogWrites("p1", { team: "BB" })[0]).toMatchObject({ outcome: "refused", kind: "promote" }); + }); + + it("fails closed when the issue read does not report blockers", async () => { + const { t } = await promoting({ tickets: [{ key: "BB-1", over: { blockedBy: undefined } }] }); + const result = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(result.error).toBe(true); + expect(result.text).toMatch(/did not report its blockers/u); + expect(t.linearWrites).toEqual([]); + }); + + it("never promotes an adopted, blocked or not-ready-looking ticket", async () => { + // Adopted: the adoption label, or any assignee. + const labelled = await promoting({ backlog: [backlogIssue({ labels: ["bb-managed"] })] }); + expect((await labelled.t.tool("backlog_promote", {}, "thr_backlog")).error).toBe(true); + expect(labelled.t.linearWrites).toEqual([]); + const assigned = await promoting({ backlog: [backlogIssue({ assignees: ["jane"] })] }); + expect((await assigned.t.tool("backlog_promote", {}, "thr_backlog")).error).toBe(true); + + // Blocked: an open blocker from the issue read. + const blocked = await promoting({ tickets: [{ key: "BB-1", over: { blockedBy: ["BB-9"] } }] }); + const blockedResult = await blocked.t.tool("backlog_promote", {}, "thr_backlog"); + expect(blockedResult.error).toBe(true); + expect(blockedResult.text).toMatch(/no eligible candidate/u); + expect(blocked.t.linearWrites).toEqual([]); + + // Not ready-looking: an empty description. + const empty = await promoting({ tickets: [{ key: "BB-1", over: { description: " " } }] }); + expect((await empty.t.tool("backlog_promote", {}, "thr_backlog")).error).toBe(true); + expect(empty.t.linearWrites).toEqual([]); + }); + + it("skips a blocked top ticket for the next ready-looking one", async () => { + const { t } = await promoting({ backlog: [backlogIssue({ key: "BB-1", priority: "Urgent" }), backlogIssue({ id: "uuid-2", key: "BB-2" })], tickets: [{ key: "BB-1", over: { priority: "Urgent", blockedBy: ["BB-9"] } }, { key: "BB-2" }] }); + const result = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(result.error).toBe(false); + expect(t.linearWrites.find((w) => w.method === "sourceUpdateIssue")!.input.key).toBe("BB-2"); + }); + + it("re-reads backlog.promote on every call, so turning it off refuses at once", async () => { + const { t } = await promoting({ promote: true }); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["BB"] }, backlog: { triage: true, promote: false } }); + t.hooks.forgetConfigs(); + const result = await t.tool("backlog_promote", {}, "thr_backlog"); + expect(result.error).toBe(true); + expect(result.text).toMatch(/promote is off/u); + expect(t.linearWrites).toEqual([]); + }); + + it("fails closed when the backlog or a candidate cannot be read", async () => { + const backlog = await promoting({ promote: true }); + backlog.t.setBacklogError("Linear rate limited the read"); + const failed = await backlog.t.tool("backlog_promote", {}, "thr_backlog"); + expect(failed.error).toBe(true); + expect(backlog.t.linearWrites).toEqual([]); + + const candidate = await promoting({ promote: true }); + candidate.t.setSnapshotError("BB-1", true); + const unreadable = await candidate.t.tool("backlog_promote", {}, "thr_backlog"); + expect(unreadable.error).toBe(true); + expect(candidate.t.linearWrites).toEqual([]); + }); + + it("shows each promotion as its own digest line", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["BB"] }, backlog: { triage: true, promote: true } }); + t.files[ROLES_FILE] = JSON.stringify({ version: 2, roles: { backlog: { backlog: { team: "BB" } } }, holders: { jane: ["backlog", "projectSteward"] } }); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + t.setBacklog([backlogIssue()]); + await t.hooks.sweep(); + await t.flush(); + const binding = t.hooks.store.byEntity("ops", "backlog/BB")!; + t.hooks.store.patch(binding.id, { threadId: "thr_backlog" }); + t.threads.set("thr_backlog", { status: "idle", archivedAt: null }); + t.entities.set("BB-1", issue({ id: "uuid-1", key: "BB-1", unit: "BB", labels: [], assignees: [], state: "Backlog", stateType: "backlog", priority: null, blockedBy: [] })); + await t.tool("backlog_promote", {}, "thr_backlog"); + await t.hooks.nightlyPass("p1", "manual"); + await t.flush(); + const project = t.spawns.find((s) => s.title === "Acme project steward")!.id; + const digest = t.sends.filter((s) => s.threadId === project).at(-1)!.text; + expect(digest).toContain("- Promoted: BB-1"); }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 87f6ab69..91c6a387 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -142,6 +142,7 @@ import { } from "./source-contract.js"; import { DEPLOY_STATES, allDeployed, applyDeployment, applyDeploymentRead, applyWorkflowRun, awaitingOnRepo, deploymentLines, deploymentReportSchema, isFinalDeploymentState, matchesTarget, matchesWorkflow, mergedPulls, pickWatch, recordMerged, reportDeployment, targetKeyOf, timeOut, timeoutsDue } from "./deploy.js"; import { backlogTriageParamsSchema, BACKLOG_COMMENT_WINDOW_MS, decideTriage, planIsEmpty, type BacklogWrite, type TriageConfig, type TriageTicket } from "./backlog-triage.js"; +import { backlogPromoteParamsSchema, candidateEligible, decidePromote, orderedCandidates, promoteAcceptedDetail, promoteRefusedDetail, wipCount, PROMOTE_WIP_FULL, type BacklogPromoteIssue, type PromoteConfig, type PromoteDetail } from "./backlog-promote.js"; import { TICKET_TOOL_NAMES, createTicketWatches, formatTicket, registerTicketTools, ticketUnits } from "./ticket-tools.js"; import { createLocalSource, isLocalState, LOCAL_PARKED, LOCAL_STATES, localStateType, type LocalSource, type LocalTicket } from "./local-source.js"; import { evaluateCarries, liveAtMergeVerdict, matchCarriesRule, noRuleNoted, type CarriesReader } from "./carries.js"; @@ -6781,6 +6782,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P playbook, look, triage: block?.triage ?? false, + promote: block?.promote ?? false, + wipLimit: block?.wipLimit ?? 5, commentsPerWeek: block?.commentsPerWeek ?? 1, staleDays: block?.staleDays ?? 14, escalations: store.openEscalations(b.id), @@ -12488,17 +12491,23 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // triage budget, the label vocabulary and the ledger, so they are not // offered to a backlog thread. The tool re-reads the flag itself, so // turning it off refuses at once even before the selection refreshes. - const backlogTriage = target?.kind === "backlog" && configs.get(b.projectId)?.value?.file.backlog?.triage === true; + const backlogBlock = configs.get(b.projectId)?.value?.file.backlog; + const backlogTriage = target?.kind === "backlog" && backlogBlock?.triage === true; + const backlogPromote = target?.kind === "backlog" && backlogBlock?.promote === true; if (target?.kind === "backlog") { + const backlogWrites = ["steward_report", "steward_update", ...(backlogTriage ? ["backlog_triage"] : []), ...(backlogPromote ? ["backlog_promote"] : []), "ticket_read", "ticket_search"]; return { - tools: backlogTriage ? ["steward_report", "steward_update", "backlog_triage", "ticket_read", "ticket_search"] : ["steward_report", "steward_update", "ticket_read", "ticket_search"], + tools: backlogWrites, skills: [...STEWARDS_SKILLS], instructions: `You are the backlog steward watching ${JSON.stringify(b.entityKey)} (binding ${b.id}, playbook ${JSON.stringify(b.playbook)}), and your thread id is ${context.thread.id}. ` + - "The plugin reads the Linear team for you and every wake carries the whole open backlog. You never adopt a ticket, start a worker, edit a description, assign one, change its state, cancel or close it. " + + "The plugin reads the Linear team for you and every wake carries the whole open backlog. You never edit a description, start a worker, cancel or close a ticket. " + (backlogTriage - ? "`backlog_triage` is your only Linear write: it adds labels, relations and a priority, or posts one comment, and the plugin enforces the comment budget, the label vocabulary and the stale window. " - : "The backlog is read-only on this project: `backlog.triage` is off, so no Linear write is offered. ") + + ? "`backlog_triage` adds labels, relations and a priority, or posts one comment, and the plugin enforces the comment budget, the label vocabulary and the stale window. " + : "The backlog is read-only for triage on this project: `backlog.triage` is off. ") + + (backlogPromote + ? "`backlog_promote` is your one promotion write: it moves the top-ordered ready-looking un-adopted Backlog ticket to Todo, adds the adoption label and assigns it to this server, one per pass, and only while Todo plus In Progress is under the WIP limit; the plugin picks the ticket, so a key that is not the top-ordered eligible one is ignored. " + : "No promotion is offered: `backlog.promote` is off. ") + "`ticket_read` and `ticket_search` are reads only. End every turn you were woken for with steward_report. Read the stewards skill for the protocol.", }; } @@ -12884,6 +12893,138 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }), }); + /** + * BB-385: the backlog steward's one promotion write. It is offered only + * when `backlog.promote` is true, and the flag is re-read on every call, + * so turning it off refuses at once. The plugin picks the ticket: it reads + * the team's fresh backlog, counts Todo plus In Progress against the WIP + * limit, orders the un-adopted Backlog tickets by the owner's priority and + * takes the first ready-looking unblocked one. Every accepted promotion + * and every refusal is appended to the ledger the digest reports from. + */ + bb.agents.registerTool({ + name: "backlog_promote", + description: + "Promote one ticket from the backlog to Todo under the WIP limit: the plugin picks the top-ordered ready-looking un-adopted Backlog ticket, adds the adoption label and assigns it to this server. It promotes at most one per pass and ignores a `key` that is not the top-ordered eligible ticket. It refuses when Todo plus In Progress is at or over backlog.wipLimit, and it never edits a description, cancels, closes or changes priority.", + presentation: { label: { pending: "Promoting a backlog ticket", completed: "Promoted a backlog ticket" } }, + parameters: backlogPromoteParamsSchema, + execute: store.coalescingTool(async (input, { threadId }) => { + const binding = store.byThread(threadId); + const target = binding === null || binding.kind !== "ops" ? null : parseOpsTargetKey(binding.entityId); + if (binding === null || target === null || target.kind !== "backlog") { + return toolError(new Error("backlog_promote is for a backlog steward's thread; this thread is not one.")); + } + const projectId = binding.projectId; + const team = target.team; + const record = (outcome: "accepted" | "refused", detail: Record, reason: string | null, issueId: string, issueKey: string) => + store.addBacklogWrite({ id: newId("btw"), projectId, team, issueId, issueKey, at: now(), outcome, kind: "promote", detail, reason }); + // Serialise promotion passes per project, so two calls cannot both read + // an under-limit WIP and both promote. + return withTriageLock(`${projectId}:promote`, async () => { + try { + const config = await loadConfig(projectId, true); + if (config === null) return toolError(new Error(`no ${PROJECT_FILE} for project ${projectId}`)); + const block = config.file.backlog; + const promoteConfig: PromoteConfig = { + promote: block?.promote === true, + team, + wipLimit: block?.wipLimit ?? 5, + label: config.file.label, + adoptedLabels: [config.file.label, INITIATIVE_LABEL, ...config.file.tickets.flatMap((t) => t.match.labels ?? [])], + }; + // The opt-in is read on every call, never only at registration. + if (!promoteConfig.promote) return toolError(new Error("backlog.promote is off; the backlog steward promotes nothing.")); + + // At most one promotion per pass: an accepted promotion recorded + // since this wake began refuses a second one, even when the WIP + // count still has room. A pass is one wake, and `wokeAt` is when + // the current one was delivered. + const passStart = binding.wokeAt ?? 0; + if (store.backlogWrites(projectId, { team }).some((w) => w.outcome === "accepted" && w.kind === "promote" && w.at >= passStart)) { + const reason = "already promoted one ticket this pass"; + record("refused", promoteRefusedDetail(input), reason, "", ""); + return toolError(new Error(reason)); + } + + // Fail closed: a backlog that cannot be read is refused, and no + // Linear write happens. + let out: z.infer; + try { + out = await sourceRpc("linear", "sourceBacklog", { team }, sourceContract.sourceBacklog.output); + } catch (error) { + const reason = `the backlog could not be read: ${errorMessage(error)}`; + record("refused", promoteRefusedDetail(input), reason, "", ""); + return toolError(new Error(reason)); + } + if (out.unsupported || out.errors.length > 0) { + const reason = `the backlog could not be read: ${out.unsupported ? "the linear source does not support sourceBacklog" : out.errors.join("; ")}`; + record("refused", promoteRefusedDetail(input), reason, "", ""); + return toolError(new Error(reason)); + } + // A truncated read is only part of the backlog, so the WIP count + // and the ordering would be wrong; refuse rather than promote on it. + if (out.truncated) { + const reason = "the backlog read was truncated; no promotion"; + record("refused", promoteRefusedDetail(input), reason, "", ""); + return toolError(new Error(reason)); + } + const issues: BacklogPromoteIssue[] = out.issues.map((i) => ({ id: i.id, key: i.key, unit: i.unit, title: i.title, state: i.state, stateType: i.stateType, labels: i.labels, assignees: i.assignees, priority: i.priority, createdAt: i.createdAt })); + + // The WIP ceiling and the ordering are pure; only a candidate needs + // the issue read that carries its description and open blockers. + if (wipCount(issues, promoteConfig) >= promoteConfig.wipLimit) { + record("refused", promoteRefusedDetail(input), PROMOTE_WIP_FULL, "", ""); + return toolError(new Error(`WIP full: Todo plus In Progress is at the limit of ${promoteConfig.wipLimit}; no promotion.`)); + } + const details = new Map(); + for (const candidate of orderedCandidates(issues, promoteConfig)) { + let snap; + try { + snap = await snapshot("linear", candidate.key); + } catch (error) { + const reason = `${candidate.key} could not be read: ${errorMessage(error)}`; + record("refused", promoteRefusedDetail(input), reason, "", candidate.key); + return toolError(new Error(reason)); + } + if (snap === null) { + const reason = `${candidate.key} could not be read: no such issue`; + record("refused", promoteRefusedDetail(input), reason, "", candidate.key); + return toolError(new Error(reason)); + } + // Fail closed on a source that did not read relations: absent + // `blockedBy` means the fact is unknown, not that there is none. + if (snap.blockedBy === undefined) { + const reason = `${candidate.key} did not report its blockers; no promotion`; + record("refused", promoteRefusedDetail(input), reason, "", candidate.key); + return toolError(new Error(reason)); + } + const detail: PromoteDetail = { description: snap.description, blockedBy: snap.blockedBy }; + details.set(candidate.key, detail); + // Read no further than the first ticket that could be promoted. + if (candidateEligible(candidate, detail)) break; + } + const decision = decidePromote({ params: input, issues, details, config: promoteConfig }); + if (!decision.ok) { + record("refused", promoteRefusedDetail(input), decision.reason, "", ""); + return toolError(new Error(decision.reason)); + } + const plan = decision.plan; + try { + await sourceRpc("linear", "sourceUpdateIssue", { key: plan.key, state: plan.state, addLabels: plan.addLabels, assignee: plan.assignee }, sourceContract.sourceUpdateIssue.output); + } catch (error) { + const reason = `the write was refused: ${errorMessage(error)}`; + record("refused", promoteRefusedDetail(input), reason, decision.candidate.key, decision.candidate.key); + return toolError(new Error(reason)); + } + record("accepted", promoteAcceptedDetail(decision.candidate, input, promoteConfig), null, decision.candidate.id, decision.candidate.key); + return `Promoted ${plan.key} to ${plan.state}, labelled ${plan.addLabels.join(", ")} and assigned to ${plan.assignee}.`; + } catch (error) { + return toolError(error); + } + }); + }), + }); + // BB-360: the source-neutral ticket tools, registered for steward and // worker threads beside steward_report/steward_update/worker_park. They // are one thin dispatch over the source contract by key shape; the watch diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index f5fc8b9e..114a2ea9 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -586,8 +586,29 @@ list a Linear team (`linear.teams`); the role's `backlog.team` names which one is read. A project with no `linear.teams` cannot run it, and `bb stewards check` reports "backlog needs a Linear team; the backlog role is Linear-only" even when the role names a team. The read is read-only -unless `backlog.triage` is on, in which case `backlog_triage` is your one -gated write. +unless `backlog.triage` is on, in which case `backlog_triage` adds labels, +relations, a priority or one signed comment, and unless `backlog.promote` is +on, in which case `backlog_promote { key }` moves one ticket forward. Both +are gated, both are re-read on every call, and the plugin — not the +playbook and not the model — enforces the limits. + +**Promotion (Stage 3, `backlog.promote`).** While Todo plus In Progress is +under `backlog.wipLimit`, `backlog_promote` moves at most one ticket per +pass to Todo, adds the adoption label and assigns it to this server's login, +so the ordinary ticket steward adopts and specifies it with no hand step. +The plugin picks the ticket: the top-ordered ready-looking un-adopted Backlog +ticket, ordered by the owner's priority (urgent, high, medium, low, then +none) and then oldest `createdAt` first, with the key as a final tiebreak, +so it never ranks a ticket above what the owner set by hand. It ignores a +`key` that is not that ticket. It never +promotes a ticket that already carries an adoption label, has any assignee or +is an initiative; one in a non-Backlog state; one with an open `blockedBy`; +or one whose title or description is empty. It never edits a description, +cancels or closes, and never changes a priority. Each accepted promotion and +each refusal is written to the ledger and shown in the digest's Backlog +section; a WIP-full or no-candidate refusal repeated for an unchanged reason +collapses to one line. Once promoted, the ticket is adopted, so triage and +promotion both refuse it: the backlog steward touches it no more. ## If you are an initiative steward diff --git a/plugins/stewards/source-contract.ts b/plugins/stewards/source-contract.ts index afe9dd00..aea729d3 100644 --- a/plugins/stewards/source-contract.ts +++ b/plugins/stewards/source-contract.ts @@ -273,6 +273,15 @@ export const entitySnapshotSchema = z.object({ */ children: z.array(snapshotChildSchema), childrenTotal: z.number().int().nonnegative().optional(), + /** + * BB-385: the keys of the issues that block this one (this issue is + * `blockedBy` them), keeping only blockers still open. Optional and + * additive: the linear source reads relations and sends it, an empty array + * when nothing blocks the issue; github, which has no dependency relation, + * omits it. Absent means the source did not read relations, never that none + * block it, so a caller that needs the fact refuses rather than assumes. + */ + blockedBy: z.array(z.string()).optional(), /** * True when the source could not read the entity's parent and sub-issues * (GitHub rejected the fields, or the relation read errored or was diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index 9211b701..194fe7e7 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -893,6 +893,8 @@ Watch the team's whole open backlog and triage the un-adopted tickets that need playbook: parsed.value, look: { at, target: "backlog/BB", team: "BB", error: null, issues: [backlogIssue()], unsupported: false, truncated: false, ...over }, triage: true, + promote: false, + wipLimit: 5, commentsPerWeek: 1, staleDays: 14, escalations: [], @@ -921,10 +923,18 @@ Watch the team's whole open backlog and triage the un-adopted tickets that need expect(text).toMatch(/Comments: 1 per ticket per rolling seven days/u); expect(text).toMatch(/Stale window: 14 days/u); expect(text).toMatch(/Watch the team's whole open backlog/u); - expect(text).toMatch(/`backlog_triage` is the only Linear write available to you/u); + expect(text).toMatch(/`backlog_triage` adds labels/u); + expect(text).toMatch(/`backlog\.promote` is off; no promotion is offered/u); expect(text).toMatch(/`steward_report` ends the turn/u); }); + it("offers backlog_promote and names the WIP limit when promotion is on (BB-385)", () => { + const text = backlogWake({}, { promote: true, wipLimit: 3 }); + expect(text).toMatch(/`backlog_promote` is the one other Linear write/u); + expect(text).toMatch(/`backlog\.promote` is on; the plugin offers `backlog_promote`, one promotion per pass while Todo plus In Progress is under 3/u); + expect(text).toMatch(/Promote one with `backlog_promote` before the report/u); + }); + it("says the backlog could not be read rather than reporting an empty one", () => { const text = backlogWake({ error: "Linear rate limited the read", issues: [] }); expect(text).toMatch(/The backlog could not be read: Linear rate limited the read/u); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index d0eb1488..13a49da8 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -1107,8 +1107,12 @@ export type BacklogWakeInput = { binding: Binding; playbook: Playbook; look: BacklogLook; - /** Whether `backlog.triage` is on, so the one gated write tool is offered. */ + /** Whether `backlog.triage` is on, so the triage write tool is offered. */ triage: boolean; + /** Whether `backlog.promote` is on, so the promotion tool is offered (BB-385). */ + promote: boolean; + /** Stage 3's Todo + In Progress ceiling, `backlog.wipLimit` (BB-385). */ + wipLimit: number; /** The comment budget, `backlog.commentsPerWeek`. */ commentsPerWeek: number; /** The stale window, `backlog.staleDays`. */ @@ -1158,7 +1162,11 @@ export function formatBacklogWake(input: BacklogWakeInput): string { out.push("", `Allowed actions: ${playbook.may.join(", ") || "(none)"}.`); out.push( "", - "`backlog_triage` is the only Linear write available to you: it adds labels, relations and a priority, or posts one comment, and it never edits a description, assigns, cancels, closes or changes state. Every write it accepts is appended to the ledger below and reported in the digest. `steward_report` ends the turn.", + "`backlog_triage` adds labels, relations and a priority, or posts one comment; it never edits a description, assigns, cancels, closes or changes state." + + (input.promote + ? " `backlog_promote` is the one other Linear write: it moves the top-ordered ready-looking un-adopted Backlog ticket to Todo, adds the adoption label and assigns it to this server, one per pass, and only while Todo plus In Progress is under the WIP limit. It never edits a description, cancels or closes." + : "") + + " Every write it accepts is appended to the ledger below and reported in the digest. `steward_report` ends the turn.", ); out.push("", "## 2. Guidance, priority and holds", ""); @@ -1184,9 +1192,10 @@ export function formatBacklogWake(input: BacklogWakeInput): string { } out.push("", "### The triage ledger (rolling seven days)", ""); if (input.ledger.length === 0) out.push("No writes in the window."); - for (const w of input.ledger) out.push(`- ${w.outcome === "accepted" ? "Accepted" : "Refused"} ${w.issueKey}: ${w.outcome === "accepted" ? w.kind : `${w.kind} — ${w.reason ?? "refused"}`}`); + for (const w of input.ledger) out.push(`- ${w.outcome === "accepted" ? "Accepted" : "Refused"}${w.issueKey === "" ? "" : ` ${w.issueKey}`}: ${w.outcome === "accepted" ? w.kind : `${w.kind} — ${w.reason ?? "refused"}`}`); out.push("", "### Limits", ""); out.push(`- \`backlog.triage\` is ${input.triage ? "on; the plugin offers `backlog_triage`" : "off; the backlog steward is read-only"}.`); + out.push(`- \`backlog.promote\` is ${input.promote ? `on; the plugin offers \`backlog_promote\`, one promotion per pass while Todo plus In Progress is under ${input.wipLimit}` : "off; no promotion is offered"}.`); out.push(`- Comments: ${input.commentsPerWeek} per ticket per rolling seven days, the stale-cancel proposal included.`); out.push(`- Stale window: ${input.staleDays} days.`); @@ -1194,7 +1203,11 @@ export function formatBacklogWake(input: BacklogWakeInput): string { out.push("", "## 4. What changed since your last look", ""); if (input.changes.length === 0) out.push("Nothing new; this is a scheduled look."); for (const c of input.changes) out.push(`- ${c}`); - out.push("", "---", "Report the look with `steward_report` and end the turn. Triage a qualifying ticket with `backlog_triage` before the report, so the ledger lists it."); + out.push( + "", + "---", + "Report the look with `steward_report` and end the turn. Triage a qualifying ticket with `backlog_triage` before the report, so the ledger lists it." + (input.promote ? " Promote one with `backlog_promote` before the report when Todo plus In Progress is under the limit." : ""), + ); return fit(head, snapshot, out); } @@ -1976,9 +1989,11 @@ function backlogLines(b: BacklogDigest): string[] { if (b.stale.length > 0) out.push(` - Stale: ${b.stale.map((s) => `${s.key} (${s.days}d)`).join(", ")}`); if (b.next.length > 0) out.push(` - Proposed next: ${b.next.map((n) => `${n.key} (${n.reason})`).join("; ")}`); // BB-341: what the steward wrote, so the owner can review it against the - // budget, and how many attempts it refused. + // budget. BB-385: each promotion is its own line, and the refusals collapse + // to one line per unchanged reason. if (b.writes.length > 0) out.push(` - Writes: ${b.writes.map((w) => `${w.issueKey} ${w.kind}`).join(", ")}`); - if (b.refusals > 0) out.push(` - Refused: ${b.refusals}`); + for (const p of b.promotions) out.push(` - Promoted: ${p.issueKey}`); + if (b.refusals > 0) out.push(` - Refused: ${b.refusalReasons.map((r) => `${r.reason} (${r.count})`).join("; ")}`); return out; }