diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index dd81d3d7..5677e553 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -339,6 +339,22 @@ Plugin code. No model turn. to change from, does not: the worker's own turn ending carries it, and waking on every first review would put back the wake the ticket removes. People, merges and closes still do. + + BB-52 narrows that to the worker's own pull request, and quiets three more + causes. A pull request is the worker's own when its head branch is one of + the binding's worker threads' branches, or a worker named its URL in its + final message; anything else — a teammate's pull request, a link the + plugin cannot tie to a worker — wakes the steward on the link ("Pull + request linked (not this ticket's worker)") and keeps its checks, pushes + and comments actionable. A state move between the playbook's `build` and + `review` stages (In Progress ↔ In Review) is the worker's own loop, a + quiet note; a move to any other stage, or a terminal state, still wakes. A + worker's turn ending is a quiet note unless its final message asks a + question, reports an error, or its thread is gone (a binding following + through still hears the worker, since it waits on that result). And a + terminal state the steward's own last report already named ends the + binding from the mechanical tier, with the wrap-up written from that + report and no wrap-up wake; a terminal state someone else set still wakes. 4. Otherwise the snapshot is recorded and the ring ends. Most rings end here: the steward's own comments, label churn, its workers at work. What changed is kept as a quiet note and shown with the next turn something diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 0478171e..72172a8d 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -66,9 +66,17 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. between its turns — the worker's own work on a pull request (checks finishing, description edits, pushes and comments from your account, which every thread posts as, and the reviewer's `bb-review` markers) is not a - reason to wake; a reviewer round that changes the lane is. Everything not + reason to wake; a reviewer round that changes the lane is. BB-52 scopes + that to the worker's own pull request — its head branch is one of the + binding's worker threads' branches, or a worker named its URL — and quiets + three more causes: a state move between the build and review stages, a + worker turn ending to wait (only a question, an error report or a gone + thread wakes), and a terminal state the steward's own last report already + named (the binding ends from the mechanical tier). A foreign pull request + wakes on its link and keeps its activity actionable. Everything not actionable is kept as a quiet note and shown in "What changed" at the next - turn something else makes due. + turn something else makes due, and `bb stewards show` lists it as a pending + note. - **Wakes are self-contained**: playbook instructions for the phase, the ready gate, guidance and holds, the snapshot, and what changed. Each woken turn ends with `steward_report`, the status record. A wake past diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index 4bbccc17..0b307d66 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 } from "./config.js"; +import { parsePlaybook, phaseOf } from "./config.js"; import { comment, issue, pull } from "./fixtures.js"; -import { approvalWanted, answerDiffers, anyWorkerInFlight, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, lifecycle, markerLaneChange, namesUserAsBlocker, ownerApproval, prGate, resolveChecklistItem, reviewMarker, specHash, stuckDue, unheardWait, workerInFlight } from "./reconcile.js"; +import { approvalWanted, answerDiffers, anyWorkerInFlight, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, isOwnStageMove, lifecycle, markerLaneChange, namesUserAsBlocker, ownerApproval, prGate, resolveChecklistItem, reviewMarker, specHash, stuckDue, unheardWait, workerInFlight, workerReportedTerminal } from "./reconcile.js"; import { readyStateSchema } from "./store.js"; import { GITHUB_REVIEWS, LINEAR_TICKETS } from "./templates.js"; @@ -63,7 +63,7 @@ describe("what changed", () => { it("while a worker runs, its own work on a pull request is not news, and people still are", () => { // HUB-183 on bithub: the worker pushes, edits the description, posts as // the viewer (unsigned, and its reviewer too) and waits for checks. - const running = { ...ctx, workerInFlight: true }; + const running = { ...ctx, workerInFlight: true, ownPulls: new Set(["acme/web#7"]) }; const before = { entity: issue(), pulls: [pull({ author: "jane" }, { headAuthor: "jane" })] }; const busy = { entity: issue(), @@ -107,6 +107,68 @@ describe("what changed", () => { }); }); +describe("the worker's own pull requests and state moves (BB-52)", () => { + const stageOf = (state: string) => phaseOf(tickets, state)?.stage ?? null; + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + const running = { ...ctx, workerInFlight: true, stageOf }; + const ownPulls = new Set(["acme/web#7"]); + + it("quiets the worker's own pull request activity, and treats an unknown pull request as foreign", () => { + const before = { entity: issue({ ...linked }), pulls: [pull({ author: "jane" }, { headAuthor: "jane" })] }; + const busy = { entity: issue({ ...linked }), pulls: [pull({ author: "jane", comments: [comment({ id: "r1", author: "jane" })] }, { headSha: "bbbbbbb2", headAuthor: "jane", checks: { state: "success", failing: [] } })] }; + expect(actionable(diffObserved(before, busy, { ...running, ownPulls }))).toEqual([]); + // Ownership the plugin cannot establish is foreign: the same activity wakes. + expect(actionable(diffObserved(before, busy, { ...running, ownPulls: new Set() }))).toEqual(["acme/web#7: Checks finished: success", "acme/web#7: 1 new comment from jane"]); + }); + + it("wakes for a foreign pull request linked while a worker is in flight, and keeps its activity actionable", () => { + const before = { entity: issue({ state: "In Progress", stateType: "started" }), pulls: [] }; + const after = { entity: issue({ state: "In Progress", stateType: "started", ...linked }), pulls: [pull({ author: "sam" }, { headAuthor: "sam" })] }; + const foreign = actionable(diffObserved(before, after, { ...running, ownPulls: new Set() })); + expect(foreign).toContain("Pull request linked (not this ticket's worker): acme/web#7"); + expect(foreign).toContain("acme/web#7: now followed (open)"); + // The worker's own link is a quiet note, as the BB-17 quieting always was. + expect(actionable(diffObserved(before, after, { ...running, ownPulls }))).toEqual([]); + }); + + it("quiets a build/review state move while a worker is in flight, and wakes for any other", () => { + const before = { entity: issue({ state: "In Progress", stateType: "started" }), pulls: [] }; + const review = { entity: issue({ state: "In Review", stateType: "started" }), pulls: [] }; + expect(actionable(diffObserved(before, review, running))).toEqual([]); + expect(actionable(diffObserved(review, before, running))).toEqual([]); + // A move outside the build/review pair wakes: a non-owner move to another stage. + const backlog = { entity: issue({ state: "Backlog", stateType: "backlog" }), pulls: [] }; + expect(actionable(diffObserved(before, backlog, running))).toEqual(["State: In Progress → Backlog"]); + // With no worker in flight the same build/review move wakes. + expect(actionable(diffObserved(before, review, ctx))).toEqual(["State: In Progress → In Review"]); + }); + + it("names the build/review move, so the server can hand the playbook's stages in", () => { + expect(isOwnStageMove(stageOf, "In Progress", "In Review")).toBe(true); + expect(isOwnStageMove(stageOf, "In Review", "In Progress")).toBe(true); + expect(isOwnStageMove(stageOf, "In Progress", "Backlog")).toBe(false); + expect(isOwnStageMove(stageOf, "Todo", "In Progress")).toBe(false); + expect(isOwnStageMove(undefined, "In Progress", "In Review")).toBe(false); + }); + + it("keeps a linked pull request quiet when no worker is in flight, as before", () => { + const before = { entity: issue({ state: "In Progress", stateType: "started" }), pulls: [] }; + const after = { entity: issue({ state: "In Progress", stateType: "started", ...linked }), pulls: [pull({ author: "sam" }, { headAuthor: "sam" })] }; + expect(actionable(diffObserved(before, after, { ...ctx, stageOf }))).toEqual([]); + }); + + it("reads a worker's final message that moved the entity to a terminal state", () => { + expect(workerReportedTerminal("Merged acme/web#7 and set ENG-12 to Done.", "ENG-12", tickets)).toBe(true); + expect(workerReportedTerminal("Set ENG-12 to Done", "ENG-12", tickets)).toBe(true); + expect(workerReportedTerminal("ENG-12: Done", "ENG-12", tickets)).toBe(true); + expect(workerReportedTerminal("ENG-12 is still In Review.", "ENG-12", tickets)).toBe(false); + // A prediction is not a report that the state was set. + expect(workerReportedTerminal("ENG-12 should be Done once the rollout lands.", "ENG-12", tickets)).toBe(false); + expect(workerReportedTerminal("Done for OPS-9.", "ENG-12", tickets)).toBe(false); + expect(workerReportedTerminal(null, "ENG-12", tickets)).toBe(false); + }); +}); + describe("a worker in flight between its turns (BB-11)", () => { const worker = (status: "running" | "finished" | "failed" | "stopped") => ({ status }); @@ -131,10 +193,10 @@ describe("a worker in flight between its turns (BB-11)", () => { const before = { entity: pull({ author: "jane" }), pulls: [] }; const after = { entity: pull({ author: "jane", comments: [marker(1, "no-review")] }), pulls: [] }; // In flight, the round is the worker's business. - expect(actionable(diffObserved(before, after, { ...ctx, workerInFlight: true }))).toEqual([]); + expect(actionable(diffObserved(before, after, { ...ctx, workerInFlight: true, ownPulls: new Set(["acme/web#7"]) }))).toEqual([]); // A round that changes the lane is not. const changed = { entity: pull({ author: "jane", comments: [marker(1, "no-review"), marker(2, "owner-reviewed")] }), pulls: [] }; - expect(actionable(diffObserved(after, changed, { ...ctx, workerInFlight: true }))).toEqual(["Review lane: no-review → owner-reviewed"]); + expect(actionable(diffObserved(after, changed, { ...ctx, workerInFlight: true, ownPulls: new Set(["acme/web#7"]) }))).toEqual(["Review lane: no-review → owner-reviewed"]); expect(markerLaneChange(after.entity.comments, changed.entity.comments)).toEqual({ from: "no-review", to: "owner-reviewed" }); // Once no worker is in flight, the same markers are ordinary comment news. expect(actionable(diffObserved(before, after, ctx))).toEqual(["1 new comment from jane"]); @@ -151,13 +213,13 @@ describe("a worker in flight between its turns (BB-11)", () => { entity: issue({ state: "In Progress", stateType: "started", ...linked }), pulls: [pull({ author: "jane", comments: [comment({ id: "r1", author: "jane", body: "", createdAt: "2026-10-02T00:00:00Z" })] }, { headAuthor: "jane", checks: { state: "success", failing: [] } })], }; - expect(actionable(diffObserved(before, reviewed, { ...ctx, workerInFlight: true }))).toEqual([]); + expect(actionable(diffObserved(before, reviewed, { ...ctx, workerInFlight: true, ownPulls: new Set(["acme/web#7"]) }))).toEqual([]); // The worker pushes (woken again), still in flight. const pushed = { entity: reviewed.entity, pulls: [pull({ author: "jane", comments: reviewed.pulls[0]!.comments }, { headSha: "bbbbbbb2", headAuthor: "jane", checks: { state: "success", failing: [] } })] }; - expect(actionable(diffObserved(reviewed, pushed, { ...ctx, workerInFlight: true }))).toEqual([]); + expect(actionable(diffObserved(reviewed, pushed, { ...ctx, workerInFlight: true, ownPulls: new Set(["acme/web#7"]) }))).toEqual([]); // Nothing was actionable while it was in flight, so the steward is woken // once, at the finish, with all of it as quiet notes. - const changes = diffObserved(before, pushed, { ...ctx, workerInFlight: anyWorkerInFlight([worker("stopped")]) }); + const changes = diffObserved(before, pushed, { ...ctx, workerInFlight: anyWorkerInFlight([worker("stopped")]), ownPulls: new Set(["acme/web#7"]) }); expect(actionable(changes)).toEqual(["acme/web#7: Checks finished: success", "acme/web#7: 1 new comment from jane"]); expect(changes.map((c) => c.text)).toContain("acme/web#7: Pushed bbbbbbb by jane"); }); diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index 695310c2..48bd0932 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -148,6 +148,60 @@ function same(a: readonly string[], b: readonly string[]): boolean { const descriptionHash = (e: EntitySnapshot) => createHash("sha256").update(e.description ?? "").digest("hex").slice(0, 16); const lc = (s: string | null | undefined) => (s ?? "").toLowerCase(); +const escapeRegExp = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); +/** Verbs that say the entity was moved, not that it merely ought to be. */ +const SETTING_VERB = /\b(?:set|sets|setting|moved?|moves?|moving|marked?|marks?|marking|put|puts|changed?|changes?|closed?|closes?|closing|merged?|merges?|merging)\b/iu; + +/** + * Whether a worker's final message says it moved this entity to a terminal + * state (BB-52 rule 4). The entity key and a terminal state name must be near + * each other on one line and a setting verb must introduce the move (or the + * key must run straight into the state, "ENG-12: Done"), so + * "ENG-12 should be Done once the rollout lands" is not one. + */ +export function workerReportedTerminal(result: string | null, entityKey: string, playbook: Playbook): boolean { + if (result === null || entityKey === "") return false; + const key = entityKey.toLowerCase(); + for (const line of result.split("\n")) { + const flat = line.toLowerCase(); + const ki = flat.indexOf(key); + if (ki < 0) continue; + for (const state of playbook.terminal) { + if (state === "") continue; + const term = state.toLowerCase(); + const si = flat.indexOf(term); + if (si < 0 || Math.abs(ki - si) > 60) continue; + const from = Math.max(0, Math.min(ki, si) - 30); + const span = flat.slice(from, Math.max(ki + key.length, si + term.length)); + const adjacent = new RegExp(`${escapeRegExp(key)}\\s*[:\\-—]\\s*${escapeRegExp(term)}`, "u").test(flat); + if (SETTING_VERB.test(span) || adjacent) return true; + } + } + return false; +} + +/** + * Whether a pull request is the binding's worker's own: its key or URL is in + * the set the server built from the worker's head branch and what the worker + * reported (BB-52 rule 0). A null key and empty URL never match. + */ +const ownPull = (key: string | null, url: string | null, own: ReadonlySet): boolean => + (key !== null && own.has(key.toLowerCase())) || (url !== null && url !== "" && own.has(url.toLowerCase())); + +/** The stages a worker of the binding moves an entity between: a move within them is its own (rule 1). */ +const OWN_MOVE_STAGES = new Set(["build", "review"]); +/** + * Whether a state change is the worker's own build/review loop: both states map + * to a build or review stage and they differ. A terminal state is handled by + * the lifecycle before this, and any other move still wakes the steward. + */ +export function isOwnStageMove(stageOf: ((state: string) => string | null) | undefined, before: string, after: string): boolean { + if (stageOf === undefined) return false; + const a = stageOf(before); + const b = stageOf(after); + return a !== null && b !== null && a !== b && OWN_MOVE_STAGES.has(a) && OWN_MOVE_STAGES.has(b); +} + /** * Whose pull request events are the steward's own work in progress. While any * worker of the binding is in flight (criterion 1: from its spawn until it @@ -155,9 +209,11 @@ const lc = (s: string | null | undefined) => (s ?? "").toLowerCase(); * description, posts as the viewer (every thread acts as the developer, * signed or not) and waits for checks; none of that is news to the steward, * which hears from the worker when it finishes. People and terminal states - * still wake it. + * still wake it. BB-52 narrows this to the worker's own pull requests: a + * linked pull request the plugin cannot tie to the worker keeps its activity + * actionable. */ -type DiffContext = { prefix: string; own: ReadonlySet; stewardThreadId: string | null; approved: boolean; viewer: string | null; workerInFlight: boolean; userThread?: (threadId: string) => boolean }; +type DiffContext = Omit & { prefix: string; viewer: string | null; ownPulls: ReadonlySet }; /** * The changes between two observations of one entity, each marked whether it @@ -167,7 +223,12 @@ type DiffContext = { prefix: string; own: ReadonlySet; stewardThreadId: export function diffEntity(before: EntitySnapshot, after: EntitySnapshot, ctx: DiffContext): Change[] { const changes: Change[] = []; const p = ctx.prefix; - if (before.state !== after.state) changes.push({ text: `${p}State: ${before.state} → ${after.state}`, actionable: true }); + if (before.state !== after.state) { + // BB-52 rule 1: a worker moving the entity between the playbook's build + // and review stages is its own loop, not news. + const own = ctx.workerInFlight && isOwnStageMove(ctx.stageOf, before.state, after.state); + changes.push({ text: `${p}State: ${before.state} → ${after.state}`, actionable: !own }); + } if ((before.title ?? "") !== (after.title ?? "")) changes.push({ text: `${p}Title: ${after.title ?? "(none)"}`, actionable: false }); if (!same(before.labels, after.labels)) changes.push({ text: `${p}Labels: ${after.labels.join(", ") || "(none)"}`, actionable: false }); if (!same(before.assignees, after.assignees)) changes.push({ text: `${p}Assignees: ${after.assignees.join(", ") || "(none)"}`, actionable: false }); @@ -178,7 +239,8 @@ export function diffEntity(before: EntitySnapshot, after: EntitySnapshot, ctx: D // rewriting a description it signed earlier usually keeps the line. const signer = descriptionSignedBy(after); const own = signer !== null && ctx.own.has(signer) && descriptionSignedBy(before) !== signer; - changes.push({ text: `${p}Description edited${own ? " (by this steward)" : ""}`, actionable: !(ctx.workerInFlight && after.pull !== null), ...(own ? { own } : {}) }); + const ownWork = ctx.workerInFlight && after.pull !== null && ownPull(after.key, after.url, ctx.ownPulls); + changes.push({ text: `${p}Description edited${own ? " (by this steward)" : ""}`, actionable: !ownWork, ...(own ? { own } : {}) }); } // A spec comment the steward just posted is its own doing; it only matters @@ -200,15 +262,21 @@ export function diffEntity(before: EntitySnapshot, after: EntitySnapshot, ctx: D else if (lc(was.state) !== lc(child.state)) changes.push({ text: `${p}Sub-issue ${child.key}: ${was.state ?? "?"} → ${child.state ?? "?"}`, actionable: true }); } const added = after.linkedPulls.filter((l) => !before.linkedPulls.some((b) => b.url === l.url)); - for (const l of added) changes.push({ text: `${p}Pull request linked: ${l.key ?? l.url}`, actionable: false }); + for (const l of added) { + // BB-52 rule 2: while a worker is in flight, only its own pull request is + // quiet; a foreign one wakes the steward. With no worker in flight the + // link is a quiet note as before. + const foreign = ctx.workerInFlight && !ownPull(l.key, l.url, ctx.ownPulls); + changes.push({ text: `${p}Pull request linked${foreign ? " (not this ticket's worker)" : ""}: ${l.key ?? l.url}`, actionable: foreign }); + } - if (before.pull !== null && after.pull !== null) changes.push(...diffPull(before, after, ctx)); + if (before.pull !== null && after.pull !== null) changes.push(...diffPull(before, after, ctx, ctx.workerInFlight && ownPull(after.key, after.url, ctx.ownPulls))); return changes; } const SETTLED = new Set(["success", "failure", "error"]); -function diffPull(before: EntitySnapshot, after: EntitySnapshot, ctx: DiffContext): Change[] { +function diffPull(before: EntitySnapshot, after: EntitySnapshot, ctx: DiffContext, ownWork: boolean): Change[] { const b = before.pull!; const a = after.pull!; const p = ctx.prefix; @@ -223,7 +291,7 @@ function diffPull(before: EntitySnapshot, after: EntitySnapshot, ctx: DiffContex const bChecks = b.checks?.state ?? null; const aChecks = a.checks?.state ?? null; if (aChecks !== null && SETTLED.has(aChecks) && (bChecks !== aChecks || !same(b.checks?.failing ?? [], a.checks?.failing ?? []))) { - changes.push({ text: `${p}Checks finished: ${aChecks}${a.checks!.failing.length > 0 ? ` (failing: ${a.checks!.failing.join(", ")})` : ""}`, actionable: !ctx.workerInFlight }); + changes.push({ text: `${p}Checks finished: ${aChecks}${a.checks!.failing.length > 0 ? ` (failing: ${a.checks!.failing.join(", ")})` : ""}`, actionable: !ownWork }); } const seen = new Set(b.reviews.map((r) => `${r.author}|${r.submittedAt}|${r.state}`)); for (const r of a.reviews) { @@ -248,15 +316,35 @@ export const isCommentNews = (text: string): boolean => /^(?:\S+: )?\d+ new comm * (see DiffContext), including the reviewer's `bb-review` markers, except a * change of lane (criterion 3). */ -export function diffObserved(before: Observed, after: Observed, ctx: { own: ReadonlySet; stewardThreadId: string | null; approved: boolean; cursor: string; workerInFlight: boolean; userThread?: (threadId: string) => boolean }): Change[] { +/** The context two observations are compared in, and what the server knows about the worker's own pull requests. */ +export type ObservedDiffContext = { + own: ReadonlySet; + stewardThreadId: string | null; + approved: boolean; + cursor: string; + workerInFlight: boolean; + /** Lowercased keys and URLs of the pull requests this binding's worker owns (BB-52 rule 0). */ + ownPulls?: ReadonlySet; + /** The stage an entity state maps to in this binding's playbook, for the build/review move (rule 1). */ + stageOf?: (state: string) => string | null; + userThread?: (threadId: string) => boolean; +}; + +export function diffObserved(before: Observed, after: Observed, ctx: ObservedDiffContext): Change[] { + const ownPulls = ctx.ownPulls ?? new Set(); const viewer = after.entity.viewer; - const changes = diffEntity(before.entity, after.entity, { ...ctx, prefix: "", viewer }); + const changes = diffEntity(before.entity, after.entity, { ...ctx, prefix: "", viewer, ownPulls }); const beforePulls = new Map(before.pulls.map((p) => [p.key.toLowerCase(), p])); for (const pull of after.pulls) { const was = beforePulls.get(pull.key.toLowerCase()); const prefix = `${pull.key}: `; - if (was === undefined) changes.push({ text: `${prefix}now followed (${pull.state})`, actionable: false }); - else changes.push(...diffEntity(was, pull, { ...ctx, prefix, viewer: pull.viewer })); + if (was === undefined) { + // Rule 2 again: while a worker is in flight, a first sight of its own + // pull request is quiet and a foreign one wakes (the link line already + // names it); with no worker in flight it is quiet as before. + const foreign = ctx.workerInFlight && !ownPull(pull.key, pull.url, ownPulls); + changes.push({ text: `${prefix}now followed (${pull.state})`, actionable: foreign }); + } else changes.push(...diffEntity(was, pull, { ...ctx, prefix, viewer: pull.viewer, ownPulls })); } // Comments are compared with what the steward was last shown, not with the // last ring, so a comment that arrived while the binding was held is still @@ -269,7 +357,7 @@ export function diffObserved(before: Observed, after: Observed, ctx: { own: Read // and its reviewers': they post as the developer, often unsigned. The // reviewer's markers are the worker's business too, whoever posts them; // a round that changes the lane is not. - const ownWork = ctx.workerInFlight && e.pull !== null; + const ownWork = ctx.workerInFlight && e.pull !== null && ownPull(e.key, e.url, ownPulls); const people = ownWork ? fresh.filter((c) => reviewMarker(c.body) === null && lc(c.author) !== lc(e.viewer)) : fresh; if (fresh.length > 0) changes.push({ text: commentNews(prefix, fresh), actionable: people.length > 0 }); if (ownWork) { diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 8db11ea6..cfc6d398 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -30,7 +30,7 @@ function world() { /** Every lesson merge the plugin asked multi-repo for, and what it answered. */ const mergeGuidanceCalls: Record[] = []; let mergeGuidanceResult: { ok: boolean; sha: string | null; branch: string | null; message: string } | null = null; - const threads = new Map(); + const threads = new Map(); const writes: Array<{ path: string; hostId?: string }> = []; /** Dotenv files by `${hostId}:${path}`, for `bb stewards secret import`. */ const fileContents = new Map(); @@ -170,7 +170,7 @@ function world() { if (t === undefined) throw Object.assign(new Error("not found"), { status: 404 }); return { ...makeThreadResponse({ id: threadId, title: t.title ?? null, status: t.status as never, archivedAt: t.archivedAt, visibility: (t.visibility ?? "visible") as never, environmentId: "env1", providerId: t.providerId ?? "claude-code", parentThreadId: t.parentThreadId ?? null, sectionId: t.sectionId ?? null }), - ...(t.hostId === undefined && t.environmentProviderId === undefined ? {} : { environment: { hostId: t.hostId ?? null, environmentProviderId: t.environmentProviderId ?? null } }), + ...(t.hostId === undefined && t.environmentProviderId === undefined ? {} : { environment: { hostId: t.hostId ?? null, environmentProviderId: t.environmentProviderId ?? null, branchName: t.branchName ?? null } }), }; }, // What the server answers: the thread's own execution once a turn ran, and before that the @@ -334,19 +334,22 @@ async function setup(extra: Partial = {}, settings: Record { const providerId = over.providerId ?? "claude-code"; const model = over.model === undefined ? "claude-opus-5-5" : over.model; const reasoningLevel = over.reasoningLevel === undefined ? "high" : over.reasoningLevel; const environmentProviderId = over.environmentProviderId === undefined ? "multi-repo-workspace" : over.environmentProviderId; - w.threads.set(id, { status: "active", archivedAt: null, visibility: "visible", parentThreadId: parent, sectionId: over.sectionId ?? null, providerId, ...(model === null ? {} : { model }), ...(reasoningLevel === null ? {} : { reasoningLevel }), environmentProviderId }); + // The worker's workspace branch; the pull() fixture's head is "retry", so + // a worker owns it unless a test says otherwise (BB-52 rule 0). + const branchName = over.branchName === undefined ? "retry" : over.branchName; + w.threads.set(id, { status: "active", archivedAt: null, visibility: "visible", parentThreadId: parent, sectionId: over.sectionId ?? null, providerId, ...(model === null ? {} : { model }), ...(reasoningLevel === null ? {} : { reasoningLevel }), environmentProviderId, branchName }); await harness.behavior.emitThreadEvent("thread.created", { thread: makeThreadResponse({ id, parentThreadId: parent, lifecycleOwnerThreadId: parent, title, originPluginId: null, providerId, sectionId: over.sectionId ?? null }) }); await flush(); }; /** A top-level worker a steward started with only `--lifecycle-owner-thread`: no parent. */ const createdOwned = async (id: string, owner: string, title = "Implement", sectionId: string | null = null) => { - w.threads.set(id, { status: "active", archivedAt: null, visibility: "visible", parentThreadId: null, sectionId, providerId: "claude-code", model: "claude-opus-5-5", reasoningLevel: "high", environmentProviderId: "multi-repo-workspace" }); + w.threads.set(id, { status: "active", archivedAt: null, visibility: "visible", parentThreadId: null, sectionId, providerId: "claude-code", model: "claude-opus-5-5", reasoningLevel: "high", environmentProviderId: "multi-repo-workspace", branchName: "retry" }); await harness.behavior.emitThreadEvent("thread.created", { thread: makeThreadResponse({ id, parentThreadId: null, lifecycleOwnerThreadId: owner, title, originPluginId: null, providerId: "claude-code", sectionId }) }); await flush(); }; @@ -772,7 +775,7 @@ describe("a Linear ticket 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 when one finishes", async () => { + 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" })); await t.ring("linear", "uuid-12"); @@ -780,10 +783,40 @@ describe("a Linear ticket steward", () => { await t.created("thr_w1", steward, "ENG-12: Implement"); expect(t.sends).toEqual([]); - await t.idle("thr_w1", "Opened acme/web#7."); + // BB-52 rule 3: a worker ending its turn waiting is a quiet note, not a wake. + await t.idle("thr_w1", "Opened acme/web#7; waiting on the reviewer."); + expect(t.sends).toEqual([]); + expect(t.hooks.store.open("p1")[0]!.pending).toMatchObject([{ text: 'Worker "ENG-12: Implement" finished its turn.', quiet: true }]); + + // A question wakes it, with the worker's words. + await t.idle("thr_w1", "Should I bring the reviewer back once it finishes?"); const wake = t.sends.at(-1)!.text; expect(wake).toMatch(/Worker "ENG-12: Implement" finished its turn/u); - expect(wake).toMatch(/Opened acme\/web#7\./u); + expect(wake).toMatch(/Should I bring the reviewer back once it finishes\?/u); + }); + + it("wakes when a worker ends its turn with an error report, and lists a quiet finish in bb stewards show", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + + // A waiting finish is kept as a quiet note, and show lists it with the next wake. + await t.created("thr_w1", steward, "ENG-12: Implement"); + await t.idle("thr_w1", "Waiting on the reviewer."); + const show = (await t.harness.behavior.runCli(["show", "ENG-12", "--project", "p1"])).stdout; + expect(show).toMatch(/Pending \(quiet\): Worker "ENG-12: Implement" finished its turn\./u); + + // An error report is not waiting: it wakes the steward. + const sent = t.sends.length; + await t.idle("thr_w1", "Error: the provider timed out before I could push."); + expect(t.sends).toHaveLength(sent + 1); + expect(t.sends.at(-1)!.text).toMatch(/Worker "ENG-12: Implement" finished its turn/u); + + // A line that merely names an error count is not an error report. + const afterError = t.sends.length; + await t.idle("thr_w1", "Errors: 0. Failed tests: none."); + expect(t.sends).toHaveLength(afterError); }); // BB-23: a worker is a top-level thread owned only through its lifecycle @@ -803,7 +836,7 @@ describe("a Linear ticket steward", () => { expect(t.sends).toEqual([]); // Its finish is the wake: the Workers section carries its final text. - await t.idle("thr_w1", "Opened acme/web#7."); + await t.idle("thr_w1", "Opened acme/web#7. Should I start the reviewer?"); const wake = t.sends.at(-1)!.text; const workers = wake.slice(wake.indexOf("### Workers")); expect(workers).toMatch(/ENG-12: Implement \(thread thr_w1\): finished/u); @@ -848,6 +881,53 @@ describe("a Linear ticket steward", () => { expect(t.hooks.store.open("p1")[0]!.pending).toEqual([]); }); + // BB-52 rule 0: "a worker is in flight" is not evidence that a linked pull + // request is the worker's. One on another branch is foreign, and its link, + // checks and comments all wake the steward. + it("wakes for a teammate's pull request linked while a worker is in flight, and keeps its activity actionable", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.created("thr_w1", steward, "ENG-12: Implement"); + const sent = t.sends.length; + + // A teammate's pull request, on another branch, gets linked to the ticket. + const linked = { linkedPulls: [{ key: "acme/web#9", url: "https://github.com/acme/web/pull/9" }] }; + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("acme/web#9", pull({ key: "acme/web#9", id: "acme/web#9", url: "https://github.com/acme/web/pull/9", author: "sam" }, { head: "sam-branch", headAuthor: "sam" })); + await t.ring("linear", "uuid-12"); + expect(t.sends).toHaveLength(sent + 1); + expect(t.sends.at(-1)!.text).toMatch(/Pull request linked \(not this ticket's worker\): acme\/web#9/u); + + // Its checks and a teammate's comment stay actionable, not quietened by the worker. + t.entities.set("acme/web#9", pull({ key: "acme/web#9", id: "acme/web#9", url: "https://github.com/acme/web/pull/9", author: "sam", comments: [comment({ id: "c9", author: "lee", body: "Please rebase.", createdAt: "2026-10-14T17:00:00Z" })] }, { head: "sam-branch", headSha: "bbbbbbb9", headAuthor: "sam", checks: { state: "success", failing: [] } })); + await t.ring("github", "acme/web#9"); + expect(t.sends).toHaveLength(sent + 2); + const activity = t.sends.at(-1)!.text; + expect(activity).toMatch(/acme\/web#9: Checks finished: success/u); + expect(activity).toMatch(/acme\/web#9: 1 new comment from lee/u); + }); + + it("treats a pull request as the worker's when the worker named its URL, even on another branch", async () => { + const t = await setup(); + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("acme/web#7", pull({ author: "jane" }, { head: "worker-branch", headAuthor: "jane" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + + // The worker's branch differs, but its final message names the pull request. + await t.created("thr_w1", steward, "ENG-12: Implement", { branchName: "other-branch" }); + await t.idle("thr_w1", "Opened https://github.com/acme/web/pull/7 and waiting on the reviewer."); + const sent = t.sends.length; + + // Its checks are the worker's, so they are a quiet note, not a wake. + t.entities.set("acme/web#7", pull({ author: "jane" }, { head: "worker-branch", headAuthor: "jane", checks: { state: "success", failing: [] } })); + await t.ring("github", "acme/web#7"); + expect(t.sends).toHaveLength(sent); + }); + // BB-17: BB-11's steward was woken 22 times in four hours because a worker // that had ended its turn to wait read as not running, so its reviewer's // comments, its checks and its own pushes all woke the steward. @@ -862,13 +942,10 @@ describe("a Linear ticket steward", () => { const before = toSteward().length; // The worker spawns, opens the PR and goes idle waiting on its reviewer: - // the steward is woken once, with the worker's message. + // BB-52 rule 3 keeps that a quiet note, and the PR activity is the worker's. await t.created("thr_w1", steward, "ENG-12: Implement"); await t.idle("thr_w1", "Opened acme/web#7; waiting on the reviewer."); - expect(toSteward()).toHaveLength(before + 1); - expect(toSteward().at(-1)!.text).toMatch(/Worker "ENG-12: Implement" finished its turn/u); - expect(toSteward().at(-1)!.text).toMatch(/Opened acme\/web#7; waiting on the reviewer\./u); - const woken = toSteward().length; + expect(toSteward()).toHaveLength(before); // The reviewer posts its marker as the developer (unsigned), checks // finish, and the worker pushes: all the worker's, none of it wakes. @@ -877,7 +954,16 @@ describe("a Linear ticket steward", () => { await t.ring("github", "acme/web#7"); t.entities.set("acme/web#7", pull({ author: "jane", comments: [comment({ id: "r1", author: "jane", body: marker, createdAt: "2026-10-14T16:00:00Z" })] }, { headSha: "bbbbbbb2", headAuthor: "jane", checks: { state: "success", failing: [] } })); await t.ring("github", "acme/web#7"); - expect(toSteward()).toHaveLength(woken); + expect(toSteward()).toHaveLength(before); + + // A teammate's comment is the wake, and it carries the quiet notes kept: + // the worker's finish and its own PR activity. + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked, comments: [comment({ createdAt: "2026-10-14T17:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + expect(toSteward()).toHaveLength(before + 1); + const wake = toSteward().at(-1)!.text; + expect(wake).toMatch(/Worker "ENG-12: Implement" finished its turn/u); + expect(wake).toMatch(/Opened acme\/web#7; waiting on the reviewer\./u); }); it("wakes for a reviewer round that changes the lane while a worker is in flight", async () => { @@ -1501,7 +1587,7 @@ describe("terminal states and follow-through", () => { it("counts a worker woken again as running, so a detach stops it", async () => { const t = await working(); - await t.idle("thr_w1", "Waiting on the review verdict."); + await t.idle("thr_w1", "Waiting on the review verdict. Should I ping the reviewer?"); expect(t.sends.at(-1)!.text).toMatch(/\(thread thr_w1\): finished/u); // Its own watch wakes it. await t.harness.behavior.emitThreadEvent("thread.active", { thread: makeThreadResponse({ id: "thr_w1" }) }); @@ -1511,6 +1597,49 @@ describe("terminal states and follow-through", () => { expect(t.sends.at(-1)!.text).toMatch(/this binding is detached/u); expect(t.stops()).toEqual(["thr_w1"]); }); + + // BB-52 rule 4: the steward's own last report already named the terminal + // state, so it set Done and said the work is done. The binding ends from the + // mechanical tier instead of waking for a wrap-up it has already done. + it("ends without a wrap-up wake when the steward's own last report already said Done", async () => { + const t = await working(); + await t.report({ phase: "Done" }); + const before = t.sends.length; + await t.done(); + expect(t.sends).toHaveLength(before); + expect((await t.list())[0]).toMatchObject({ ended: true }); + expect(t.archives()).toContain(t.steward); + }); + + it("still wakes for a terminal state when the steward's last report did not say Done", async () => { + const t = await working(); + await t.report({ phase: "In Review" }); + const before = t.sends.length; + await t.done(); + expect(t.sends).toHaveLength(before + 1); + expect(t.sends.at(-1)!.text).toMatch(/Terminal: Done/u); + }); + + // Criterion 2: the canonical build-tickets close, where the worker merges its + // own PR and sets Done itself. Rule 4's worker half ends the binding from the + // mechanical tier, so the Done state is never its own wrap-up wake. + it("ends without a Done wake when the worker merged and set Done itself", async () => { + const t = await working(); + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + t.entities.set("acme/web#7", pull({ author: "jane" }, { headAuthor: "jane" })); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + await t.ring("linear", "uuid-12"); + + // The worker's own PR merges, then the worker sets the ticket Done and ends. + t.entities.set("acme/web#7", pull({ author: "jane", state: "merged" }, { headAuthor: "jane" })); + await t.ring("github", "acme/web#7"); + const before = t.sends.length; + t.entities.set("uuid-12", issue({ state: "Done", stateType: "completed", ...linked })); + await t.idle("thr_w1", "Merged acme/web#7 and set ENG-12 to Done."); + await t.ring("linear", "uuid-12"); + expect((await t.list())[0]).toMatchObject({ ended: true }); + expect(t.sends.slice(before).map((s) => s.text).some((text) => /Terminal: Done/u.test(text))).toBe(false); + }); }); describe("the project steward", () => { @@ -1748,7 +1877,7 @@ describe("stewards waiting on others", () => { // worker, so a steward waiting on someone else hides even while it runs. await t.created("thr_w1", steward); await t.created("thr_w2", steward); - await t.idle("thr_w1", "Done."); + await t.idle("thr_w1", "Done. Should I start the next one?"); expect(t.sends.at(-1)!.text).toMatch(/finished its turn/u); await t.tool("steward_report", { phase: "In Progress", summary: "Implementing.", nextAction: "Wait for the second worker", actor: "other" }, steward); await t.idle(steward); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 961fb638..4d4f1552 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -34,6 +34,7 @@ import { opsTeam, parsePlaybook, parseProjectFile, + phaseOf, playbookNameFor, playbookPath, playbookStates, @@ -54,7 +55,7 @@ import { HOOKS_URL_ENV, createHooksLoop, type Lease, type Rejection } from "./ho import { nightlyDue, stillNight } from "./nightly.js"; import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type DependabotTarget, 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 { advanced, answerDiffers, anyWorkerInFlight, approvalWanted, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, latestReviewMarker, lifecycle, namesUserAsBlocker, newHumanComments, newestCommentAt, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, type Change } from "./reconcile.js"; +import { advanced, answerDiffers, anyWorkerInFlight, approvalWanted, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, latestReviewMarker, lifecycle, namesUserAsBlocker, newHumanComments, newestCommentAt, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, workerReportedTerminal, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, STEWARDS_PLUGIN_ID, @@ -74,7 +75,7 @@ import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY } from "./sidebar-provider.js"; import { NEEDS_YOU_CHANGED } from "./channels.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; -import { PROJECT_STEWARD_INTRO, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerQuestion, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerQuestion, workerReportedError, workerWaiting, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; export const MULTI_REPO_PLUGIN_ID = "multi-repo"; /** multi-repo's environment provider: where every thread of a stewards project works. */ @@ -890,6 +891,65 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); } + /** + * A thread's workspace branch, from its environment, or null when the + * environment or its branch cannot be read. Cached once known: a thread's + * branch does not change, and a null is left uncached so a worker whose + * environment is still provisioning is read again. + */ + const branchCache = new Map(); + async function threadBranch(threadId: string): Promise { + const cached = branchCache.get(threadId); + if (cached !== undefined) return cached; + try { + const info = (await bb.sdk.threads.get({ threadId, include: "environment" })) as { environment?: { branchName?: string | null } | null }; + const branch = info.environment?.branchName ?? null; + if (branch !== null && branch !== "") branchCache.set(threadId, branch); + return branch === "" ? null : branch; + } catch (error) { + bb.log.warn(`stewards: could not read the branch of ${threadId}: ${errorMessage(error)}`); + return null; + } + } + + /** + * The pull requests this binding's worker owns, as lowercased keys and + * URLs (BB-52 rule 0): its head branch is one of the binding's worker + * threads' branches, or a worker named the URL in its final message. A + * pull request the plugin cannot tie to the worker is left out, so it is + * treated as foreign and keeps its activity actionable. + */ + async function ownPullKeys(b: Binding, workers: readonly Worker[], observed: Observed): Promise> { + /** Whether a worker's message names a key or URL, without matching a longer number's prefix. */ + const mentions = (text: string, token: string): boolean => { + const at = text.indexOf(token); + return at >= 0 && (at + token.length >= text.length || !/[0-9]/u.test(text[at + token.length]!)); + }; + const branches = new Set(); + for (const w of workers) { + if (!workerInFlight(w)) continue; + const branch = await threadBranch(w.threadId); + if (branch !== null) branches.add(branch); + } + const reported = new Set(); + for (const w of workers) { + if (w.result === null || w.result === "") continue; + for (const e of [observed.entity, ...observed.pulls]) { + if (e.key !== "" && mentions(w.result, e.key)) reported.add(e.key.toLowerCase()); + if (e.url !== null && e.url !== "" && mentions(w.result, e.url)) reported.add(e.url.toLowerCase()); + } + } + const keys = new Set(); + for (const e of [observed.entity, ...observed.pulls]) { + if (e.pull === null) continue; + const own = (e.pull.head !== null && branches.has(e.pull.head)) || reported.has(e.key.toLowerCase()) || (e.url !== null && reported.has(e.url.toLowerCase())); + if (!own) continue; + keys.add(e.key.toLowerCase()); + if (e.url !== null) keys.add(e.url.toLowerCase()); + } + return keys; + } + // The interest set: what linear and github should lease and ring us // about. Sent whole, only when it changed, a moment after the change. const lastInterest = new Map(); @@ -1266,6 +1326,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (needsUser(b)) return; for (const w of store.workers(b.id)) { if (w.status !== "finished" || workerQuestion(w.result) !== null) continue; + // A worker parked on a watch or an approval is left in flight: the + // watch wakes it again, and its own pull request's activity stays quiet + // (BB-52 rule 3). + if (workerWaiting(w.result)) continue; // A worker whose reviewer is still unarchived must stay. bb core // releases a thread's unarchived children from it when it is archived, // so archiving the worker would clear the reviewer's parent: it could @@ -1675,8 +1739,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ready = { ...ready, approval: { at: now(), specHash: currentSpec, by: "linear" }, voidedAt: null }; changes.push({ text: `Approved in Linear (now ${entity.state})`, actionable: true }); } - const workerInFlight = anyWorkerInFlight(store.workers(b.id)); - const fresh = prev === null ? [] : diffObserved(prev, observed, { own: ownThreads(b), stewardThreadId: b.threadId, approved: ready.approval !== null, cursor: b.commentCursor, workerInFlight, userThread: isUserThread }); + const workers = store.workers(b.id); + const workerInFlight = anyWorkerInFlight(workers); + // Rule 0: which linked pull requests are the worker's own. Only read the + // branches and reported URLs when a worker is in flight; otherwise the + // set is empty and every pull request is foreign. + const ownPulls = workerInFlight ? await ownPullKeys(b, workers, observed) : new Set(); + const fresh = prev === null ? [] : diffObserved(prev, observed, { own: ownThreads(b), stewardThreadId: b.threadId, approved: ready.approval !== null, cursor: b.commentCursor, workerInFlight, ownPulls, stageOf: (state) => phaseOf(playbook, state)?.stage ?? null, userThread: isUserThread }); changes.push(...fresh); // BB-35 step 2: a fresh unsigned comment by the owner that differs from // the recommendation on a decision that cited lessons is a correction, @@ -2367,6 +2436,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } + /** + * How long after a worker's turn a terminal-state report in its final + * message still counts as it having set the state (BB-52 rule 4). A stale + * report from an earlier Done does not suppress a later one. + */ + const TERMINAL_WORKER_REPORT_MS = 15 * 60_000; + /** * The one wrap-up (terminal) or stop (detach) turn before the binding * ends. A detach stops the workers now: someone took the label off. A @@ -2375,6 +2451,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * watch, production to verify); they are stopped when it ends. */ async function beginEnding(b: Binding, config: ProjectConfig, playbook: Playbook, kind: "terminal" | "detach", observed: Observed): Promise { + // BB-52 rule 4: the steward's own last report already named the terminal + // state, or a worker's final message says it moved the entity there, so + // the binding's own last turn set it and said the work is done. End from + // the mechanical tier rather than waking for a wrap-up it has already + // done. A terminal state set by anyone else leaves neither signal and + // still wakes. The source contract carries no state-change actor, so + // these two reports are the attribution the plugin has. + const stewardDone = b.status !== null && isTerminal(playbook, b.status.phase); + const workerDone = + kind === "terminal" && + store.workers(b.id).some((w) => w.result !== null && (w.endedAt === null || now() - w.endedAt <= TERMINAL_WORKER_REPORT_MS) && workerReportedTerminal(w.result, observed.entity.key, playbook)); + const ownDone = kind === "terminal" && (stewardDone || workerDone); b = store.patch(b.id, { ending: kind, endingAt: now(), followThrough: null, followThroughUntil: null, lastSnapshot: observed, clearedToStart: false }); // Whatever its work was holding back can go now: landed, canceled or no longer managed, it is not merging later. await releaseBehind(b, kind === "terminal" ? `reached ${observed.entity.state}` : "was detached"); @@ -2389,6 +2477,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await finishEnding(b, kind); return; } + if (ownDone) { + bb.log.info(`stewards: ${b.entityKey} was already reported done in its own last turn; ending without a wrap-up wake`); + await finishEnding(b, "terminal"); + return; + } await wake(b, config, playbook, observed, [kind === "terminal" ? `Terminal: ${observed.entity.state}` : `The ${config.file.label} label was removed`], kind); } @@ -3306,14 +3399,25 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const worker = store.worker(thread.id); if (worker !== null) { if (worker.status === "stopped") return; - store.setWorker(thread.id, "finished", lastAssistantText === null ? null : clip(lastAssistantText, 4000)); + const result = lastAssistantText === null ? null : clip(lastAssistantText, 4000); + store.setWorker(thread.id, "finished", result); await closeRequesterNeed(thread.id); // Its turn is over: the reviewers it read (or started and then waited // on) have had their round consumed (BB-47). await archiveConsumedReviewers(thread.id); const b = store.binding(worker.bindingId); if (b === null || b.endedAt !== null) return; - store.note(b.id, `Worker "${worker.title}" finished its turn.`); + // BB-52 rule 3: a worker that ends its turn waiting on its reviewer, + // the owner or a build is a quiet note. Only a question, an error + // report or a gone thread makes the turn due; a failed turn comes + // through thread.failed and wakes on its own. A binding following + // through is waiting on this worker's result, so its finish is news. + const needsSteward = workerQuestion(result) !== null || workerReportedError(result) || followingThrough(b); + store.note(b.id, `Worker "${worker.title}" finished its turn.`, !needsSteward); + // A quiet finish is consumed here, not by a wake: archive the worker + // now (BB-47), keeping one that still has a question, a reviewer, or is + // parked waiting on something that will wake it (BB-52 rule 3). + if (!needsSteward && !workerWaiting(result)) await archiveFinishedWorkers(b); scheduleReconcile(b.id); return; } @@ -5569,6 +5673,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P lines.push(`Touches: ${b.touches.join(", ") || "not reported"}${conflicts.length === 0 ? "" : `; overlaps ${conflicts.map((c) => `${c.with.entityKey} on ${c.on.join(", ")}`).join("; ")}`}`); } for (const g of b.guidance) lines.push(`Guidance ${iso(g.at)}: ${g.text}`); + for (const n of b.pending) lines.push(`Pending${n.quiet === true ? " (quiet)" : ""}: ${n.text}`); for (const x of detail.escalations) lines.push(`Escalation ${x.id} ${x.kind} (${x.status}, ${x.route}): ${x.question}${choicesNote(x.choices)}${x.resolution === null ? "" : ` → ${x.resolution}`}`); for (const n of store.needs(b.id, true)) lines.push(`Need ${n.id} ${n.kind} (${n.status}): ${n.what}${choicesNote(needChoices(n))}${n.url === "" ? "" : ` — ${n.url}`}${n.resolution === null ? "" : ` → ${n.resolution}`}`); for (const w of detail.workers) lines.push(`Worker ${w.threadId} ${w.title}: ${w.status}`); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index c013029f..32dad04a 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -93,6 +93,29 @@ export function workerQuestion(result: string | null): string | null { return null; } +/** + * Whether a worker's final message reports an error the steward must see. A + * turn that failed outright comes through `thread.failed`; this catches a + * worker that ended its turn with an error it could not get past (BB-52 rule + * 3). Only an explicit marker at the start of a line counts, so a normal + * report that mentions an error it fixed is not one. + */ +const ERROR_REPORT = /^\s*(?:error|failed|failure|exception|traceback)\b\s*[:—-]\s*\S|^\s*(?:I (?:could not|couldn't|was unable to)|Unable to)\b/imu; +export function workerReportedError(result: string | null): boolean { + return result !== null && ERROR_REPORT.test(result); +} + +/** + * Whether a worker's final message says it is parked waiting on something + * outside it (a reviewer, the owner, a build, a GitHub watch). Such a worker + * is left in flight rather than archived: its watch can wake it again, and + * its own pull request's activity stays quiet (BB-52 rule 3). + */ +const WAITING = /\b(?:waiting|awaits?|awaiting|parked|standing by)\b/iu; +export function workerWaiting(result: string | null): boolean { + return result !== null && WAITING.test(result); +} + /** One worker's question, first under What changed, with how to answer it. */ function workerQuestionLines(q: WorkerQuestion): string[] { const asked = `- **Worker ${q.threadId} asked:** ${q.question}`;