diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 511341fd..f1ada2d6 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -299,11 +299,16 @@ Plugin code. No model turn. - guidance changed, an escalation resolved, an approval given or voided; - the spec changed (description edited, spec comment added); - `requeueAfter` came due. - While one of the steward's workers is running, its own work on a pull - request is not actionable: checks finishing, description edits, and - pushes and comments from the developer's account, which the worker and - the reviewers it starts post as, often unsigned. People, merges and - closes still are. + While any worker of the binding is in flight — from its spawn until it is + stopped, failed or archived, across the idle between its turns — its own + work on a pull request is not actionable: checks finishing, description + edits, and pushes and comments from the developer's account, which the + worker and the reviewers it starts post as, often unsigned, and the + reviewer's `bb-review` markers, whichever account posts them. A round + that changes the lane does wake it. A first marker, with no earlier round + 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. 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 @@ -321,10 +326,10 @@ The steward is woken with one message in a fixed form: Each wake is self-contained, so compaction can be aggressive, and it is: after a steward's or the project steward's turn the plugin compacts its context once -it holds more than a setting (120,000 tokens by default). Left to the provider, -compaction comes near the window's end, and every turn before then reads the -whole transcript. A wake too long to send is cut in its snapshot, never in -what changed. The steward acts and must end its turn with `steward_report`, +it holds more than a setting (120,000 tokens by default), and before a wake +that would push it over. Left to the provider, compaction comes near the +window's end, and every turn before then reads the whole transcript. A wake +too long to send is cut in its snapshot, never in what changed. The steward acts and must end its turn with `steward_report`, which writes the status record: | Field | Holds | diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index d563e072..b14e567e 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -23,12 +23,14 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. the last observation, and the steward is woken only for an actionable change: a phase change, a human comment, a review, checks finishing, someone else's push, a worker finishing, guidance, an approval, a spec - change, or its requeue time. While one of its workers is running, the - worker's own work on a pull request — checks finishing, description - edits, pushes and comments from your account, which every thread posts - as — is not a reason to wake. Everything not actionable is kept as a - quiet note and shown in "What changed" at the next turn something else - makes due. + change, or its requeue time. While any worker of the binding is in flight + — from its spawn until it is stopped, failed or archived, across the idle + 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 + actionable is kept as a quiet note and shown in "What changed" at the next + turn something else makes due. - **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 @@ -36,7 +38,8 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. a wake carries what the steward needs, its transcript can go: after a steward's or the project steward's turn, the plugin compacts its context once it holds more than **Compact a steward above this many context - tokens** (120,000 by default; 0 leaves it to the provider). + tokens** (120,000 by default; 0 leaves it to the provider), and before a + wake that would push it over. - **Two tools.** `steward_report` ends a turn with the status record and, when needed, an escalation; `steward_update` steers a binding (guidance, deciding or forwarding escalations, priority, holds, models, approving a diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index b6aed99a..78b89c8c 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 { comment, issue, pull } from "./fixtures.js"; -import { approvalWanted, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, lifecycle, resolveChecklistItem, specHash, stuckDue, unheardWait } from "./reconcile.js"; +import { approvalWanted, anyWorkerInFlight, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, lifecycle, markerLaneChange, resolveChecklistItem, reviewMarker, specHash, stuckDue, unheardWait, workerInFlight } from "./reconcile.js"; import { readyStateSchema } from "./store.js"; import { GITHUB_REVIEWS, LINEAR_TICKETS } from "./templates.js"; @@ -16,7 +16,7 @@ const reviews = (() => { return p.value; })(); -const ctx = { own: new Set(["thr_s", "thr_w"]), stewardThreadId: "thr_s", approved: false, cursor: "2026-10-01T12:00:00Z", workerRunning: false }; +const ctx = { own: new Set(["thr_s", "thr_w"]), stewardThreadId: "thr_s", approved: false, cursor: "2026-10-01T12:00:00Z", workerInFlight: false }; const actionable = (cs: Array<{ text: string; actionable: boolean }>) => cs.filter((c) => c.actionable).map((c) => c.text); describe("what changed", () => { @@ -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, workerRunning: true }; + const running = { ...ctx, workerInFlight: true }; const before = { entity: issue(), pulls: [pull({ author: "jane" }, { headAuthor: "jane" })] }; const busy = { entity: issue(), @@ -107,6 +107,74 @@ describe("what changed", () => { }); }); +describe("a worker in flight between its turns (BB-11)", () => { + const worker = (status: "running" | "finished" | "failed" | "stopped") => ({ status }); + + it("counts a worker in flight from spawn until it is stopped, failed or archived", () => { + expect(workerInFlight(worker("running"))).toBe(true); + // Its turn ending is a pause, not a finish: it is woken again to push. + expect(workerInFlight(worker("finished"))).toBe(true); + expect(workerInFlight(worker("failed"))).toBe(false); + expect(workerInFlight(worker("stopped"))).toBe(false); + expect(anyWorkerInFlight([worker("stopped"), worker("finished")])).toBe(true); + expect(anyWorkerInFlight([worker("stopped"), worker("failed")])).toBe(false); + expect(anyWorkerInFlight([])).toBe(false); + }); + + it("keeps the reviewer's marker comments for the worker, and wakes on a lane change", () => { + const marker = (round: number, lane: string) => comment({ id: `m${round}`, author: "jane", body: `\n\nLGTM.`, createdAt: `2026-10-02T0${round}:00:00Z` }); + expect(reviewMarker(marker(1, "no-review").body)).toEqual({ round: 1, sha: "abc1", verdict: "approved", lane: "no-review" }); + expect(reviewMarker("just a comment")).toBeNull(); + // A marker is a marker only on the first line. + expect(reviewMarker("Hello\n")).toBeNull(); + + 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([]); + // 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(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"]); + }); + + it("covers the BB-11 sequence: a worker's own PR activity stays quiet until it finishes", () => { + // Worker spawns, goes idle waiting (still in flight), the reviewer posts, + // checks finish, the worker pushes; only the finish is actionable. + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + const before = { entity: issue({ state: "In Progress", stateType: "started", ...linked }), pulls: [pull({ author: "jane" }, { headAuthor: "jane" })] }; + // Its turn ended to wait, so its status is `finished`; it is still in flight. + expect(anyWorkerInFlight([worker("finished")])).toBe(true); + const reviewed = { + 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([]); + // 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([]); + // 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")]) }); + 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"); + }); + + it("compacts when the transcript is over the limit or the wake would push it over", () => { + expect(compactDue(null, 120_000, 0)).toBe(false); + expect(compactDue(90_000, 120_000, 0)).toBe(false); + expect(compactDue(121_000, 120_000, 0)).toBe(true); + // A 115k-token steward and a 30k-character wake (the wake cap) overshoot. + expect(compactDue(115_000, 120_000, 30_000)).toBe(true); + expect(compactDue(90_000, 120_000, 30_000)).toBe(false); + expect(compactDue(90_000, 120_000, 1_000)).toBe(false); + // 0 leaves compaction to the provider. + expect(compactDue(1_000_000, 0, 1_000_000)).toBe(false); + }); +}); + describe("waits nobody hears", () => { const status = (blockedOn: string | null) => ({ phase: "Todo", summary: "s", nextAction: "n", actor: "other" as const, blockedOn, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at: 1 }); const open = [{ id: "esc_1", bindingId: "b", kind: "decision" as const, question: "q", meanwhile: "m", route: "project" as const, recommendation: null, status: "open" as const, resolution: null, createdAt: 1, resolvedAt: null, deliveredAt: null }]; diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index dc65184b..37633de6 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -8,7 +8,7 @@ import { createHash } from "node:crypto"; import { isTerminal, phaseOf, type Playbook } from "./config.js"; import type { EntitySnapshot, SnapshotComment } from "./source-contract.js"; -import type { Binding, Escalation, Observed, ReadyState } from "./store.js"; +import type { Binding, Escalation, Observed, ReadyState, Worker } from "./store.js"; /** * One line of "what changed", and whether it alone makes a judgment turn due. @@ -17,6 +17,52 @@ import type { Binding, Escalation, Observed, ReadyState } from "./store.js"; */ export type Change = { text: string; actionable: boolean; own?: boolean }; +/** + * A worker is in flight from its spawn until it is stopped, failed or + * archived. Its turn ending is a pause, not a finish: a worker waits on its + * reviewer, is woken again, and pushes again. Own-pull-request activity is + * the worker's while any worker of the binding is in flight (criterion 1). + */ +export const workerInFlight = (w: Pick): boolean => w.status === "running" || w.status === "finished"; +export const anyWorkerInFlight = (workers: readonly Pick[]): boolean => workers.some(workerInFlight); + +/** A reviewer's machine-readable verdict, as `pr-reviewer` posts it on the first line of a comment. */ +export type ReviewMarker = { round: number; sha: string; verdict: string; lane: string }; + +const REVIEW_MARKER = /^/u; + +/** The reviewer's marker on a comment, or null for any other comment. */ +export function reviewMarker(body: string): ReviewMarker | null { + const first = body.split("\n", 1)[0]!.trim(); + const m = REVIEW_MARKER.exec(first); + return m === null ? null : { round: Number(m[1]), sha: m[2]!, verdict: m[3]!, lane: m[4]! }; +} + +/** The newest reviewer marker in a comment list, by comment time. */ +function latestMarker(comments: readonly SnapshotComment[]): ReviewMarker | null { + let at = ""; + let latest: ReviewMarker | null = null; + for (const c of comments) { + const m = reviewMarker(c.body); + if (m !== null && c.createdAt >= at) { + at = c.createdAt; + latest = m; + } + } + return latest; +} + +/** + * A change in the lane a reviewer's rounds are in: the one thing about a + * `bb-review` marker the steward hears while a worker is in flight. + */ +export function markerLaneChange(before: readonly SnapshotComment[], after: readonly SnapshotComment[]): { from: string; to: string } | null { + const b = latestMarker(before); + const a = latestMarker(after); + if (b === null || a === null || b.lane === a.lane) return null; + return { from: b.lane, to: a.lane }; +} + /** A spec comment is one of the steward's own signed comments that starts by saying so. */ export const isSpecComment = (c: SnapshotComment, stewardThreadId: string | null): boolean => stewardThreadId !== null && c.signedBy === stewardThreadId && /^\s*(\*\*)?spec\b/iu.test(c.body); @@ -60,13 +106,15 @@ const descriptionHash = (e: EntitySnapshot) => createHash("sha256").update(e.des const lc = (s: string | null | undefined) => (s ?? "").toLowerCase(); /** - * Whose pull request events are the steward's own work in progress. While one - * of its workers is running, the worker pushes, edits the 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. + * 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 + * finishes, not only while its turn runs), the worker pushes, edits the + * 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. */ -type DiffContext = { prefix: string; own: ReadonlySet; stewardThreadId: string | null; approved: boolean; viewer: string | null; workerRunning: boolean }; +type DiffContext = { prefix: string; own: ReadonlySet; stewardThreadId: string | null; approved: boolean; viewer: string | null; workerInFlight: boolean }; /** * The changes between two observations of one entity, each marked whether it @@ -87,7 +135,7 @@ 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.workerRunning && after.pull !== null), ...(own ? { own } : {}) }); + changes.push({ text: `${p}Description edited${own ? " (by this steward)" : ""}`, actionable: !(ctx.workerInFlight && after.pull !== null), ...(own ? { own } : {}) }); } // A spec comment the steward just posted is its own doing; it only matters @@ -126,7 +174,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.workerRunning }); + changes.push({ text: `${p}Checks finished: ${aChecks}${a.checks!.failing.length > 0 ? ` (failing: ${a.checks!.failing.join(", ")})` : ""}`, actionable: !ctx.workerInFlight }); } const seen = new Set(b.reviews.map((r) => `${r.author}|${r.submittedAt}|${r.state}`)); for (const r of a.reviews) { @@ -147,10 +195,11 @@ export const isCommentNews = (text: string): boolean => /^(?:\S+: )?\d+ new comm /** * Every change between two observations: the entity, then each linked pull - * request. `workerRunning` quiets the steward's own work on pull requests - * (see DiffContext). + * request. `workerInFlight` quiets the steward's own work on pull requests + * (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; workerRunning: boolean }): Change[] { +export function diffObserved(before: Observed, after: Observed, ctx: { own: ReadonlySet; stewardThreadId: string | null; approved: boolean; cursor: string; workerInFlight: boolean }): Change[] { const viewer = after.entity.viewer; const changes = diffEntity(before.entity, after.entity, { ...ctx, prefix: "", viewer }); const beforePulls = new Map(before.pulls.map((p) => [p.key.toLowerCase(), p])); @@ -163,17 +212,37 @@ export function diffObserved(before: Observed, after: Observed, ctx: { own: Read // 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 // news at the next turn. + const beforeByKey = new Map([[before.entity.key.toLowerCase(), before.entity], ...before.pulls.map((p) => [p.key.toLowerCase(), p] as const)]); for (const e of [after.entity, ...after.pulls]) { + const prefix = e === after.entity ? "" : `${e.key}: `; const fresh = newHumanComments(e, ctx.cursor, ctx.own); - // On a pull request a running worker owns, the viewer's comments are the - // worker's and its reviewers': they post as the developer, often unsigned. - const ownWork = ctx.workerRunning && e.pull !== null; - const people = ownWork ? fresh.filter((c) => lc(c.author) !== lc(e.viewer)) : fresh; - if (fresh.length > 0) changes.push({ text: commentNews(e === after.entity ? "" : `${e.key}: `, fresh), actionable: people.length > 0 }); + // On a pull request a worker owns, the viewer's comments are the worker's + // 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 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) { + const lane = markerLaneChange(beforeByKey.get(e.key.toLowerCase())?.comments ?? [], e.comments); + if (lane !== null) changes.push({ text: `${prefix}Review lane: ${lane.from} → ${lane.to}`, actionable: true }); + } } return changes; } +/** + * Whether to compact a steward's context: it already holds more than the + * limit, or the wake about to be sent would push it over (criterion 4). + * Tokens are estimated from the wake's characters; the provider's reading is + * exact. A non-positive limit leaves compaction to the provider. + */ +export const CHARS_PER_TOKEN = 4; +export function compactDue(usedTokens: number | null, limit: number, incomingChars = 0): boolean { + if (!(limit > 0) || usedTokens === null) return false; + return usedTokens > limit || usedTokens + Math.ceil(incomingChars / CHARS_PER_TOKEN) > limit; +} + // ---- the ready gate ------------------------------------------------------------------ export type GateState = { diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 445f3e7c..72af17c4 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -614,6 +614,74 @@ describe("a Linear ticket steward", () => { expect(t.hooks.store.open("p1")[0]!.pending).toEqual([]); }); + // 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. + it("covers the BB-11 sequence: a worker's own PR activity is quiet until it finishes", 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" }, { headAuthor: "jane" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + const toSteward = () => t.sends.filter((s) => s.threadId === 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. + 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; + + // The reviewer posts its marker as the developer (unsigned), checks + // finish, and the worker pushes: all the worker's, none of it wakes. + const marker = ""; + t.entities.set("acme/web#7", pull({ author: "jane", comments: [comment({ id: "r1", author: "jane", body: marker, createdAt: "2026-10-14T16:00:00Z" })] }, { headAuthor: "jane", checks: { state: "success", failing: [] } })); + 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); + }); + + it("wakes for a reviewer round that changes the lane while a worker is in flight", async () => { + const t = await setup(); + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + const marker = (round: number, lane: string) => comment({ id: `r${round}`, author: "jane", body: ``, createdAt: `2026-10-14T1${round}:00:00Z` }); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("acme/web#7", pull({ author: "jane", comments: [marker(1, "no-review")] }, { headAuthor: "jane" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.created("thr_w1", steward, "ENG-12: Implement"); + await t.idle("thr_w1", "Waiting on the reviewer."); + const woken = t.sends.filter((s) => s.threadId === steward).length; + + t.entities.set("acme/web#7", pull({ author: "jane", comments: [marker(1, "no-review"), marker(2, "owner-reviewed")] }, { headAuthor: "jane" })); + await t.ring("github", "acme/web#7"); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(woken + 1); + expect(t.sends.filter((s) => s.threadId === steward).at(-1)!.text).toMatch(/Review lane: no-review → owner-reviewed/u); + }); + + it("stops suppressing a worker's PR activity once it is stopped", 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" }, { headAuthor: "jane" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.created("thr_w1", steward, "ENG-12: Implement"); + await t.idle("thr_w1", "Waiting."); + // Stopped (or archived): no longer in flight, so its work is news again. + t.hooks.store.setWorker("thr_w1", "stopped", null); + const woken = t.sends.filter((s) => s.threadId === steward).length; + + t.entities.set("acme/web#7", pull({ author: "jane", comments: [comment({ id: "w1", author: "jane", body: "Round 3: pushed.", createdAt: "2026-10-14T17:00:00Z" })] }, { headSha: "bbbbbbb2", headAuthor: "jane", checks: { state: "success", failing: [] } })); + await t.ring("github", "acme/web#7"); + expect(t.sends.filter((s) => s.threadId === steward)).toHaveLength(woken + 1); + }); + it("leases only the linked pull requests still open, and one not read yet", async () => { const t = await setup(); const link = (n: number) => ({ key: `acme/web#${n}`, url: `https://github.com/acme/web/pull/${n}` }); @@ -680,6 +748,20 @@ describe("a Linear ticket steward", () => { expect(compacted()).toEqual([steward, project]); }); + it("compacts before a wake that would push the context over the limit", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + const compacted = () => t.harness.sdk.callsTo("threads.compact").map(([args]) => (args as { threadId: string }).threadId); + + // At the limit: not yet over, but the next wake would push it over. + t.usage.set(steward, 120_000); + t.entities.set("uuid-12", issue({ comments: [comment({ createdAt: "2026-10-14T16:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + expect(compacted()).toEqual([steward]); + }); + it("stops a looping steward's workers past the runaway guard", async () => { const t = await setup(); t.entities.set("uuid-12", issue()); @@ -889,7 +971,7 @@ describe("terminal states and follow-through", () => { await t.report(); await t.idle(t.steward); expect((await t.list())[0]).toMatchObject({ ended: true }); - expect(t.stops()).toEqual(["thr_w2"]); + expect(t.stops()).toEqual(["thr_w1", "thr_w2"]); expect(t.archives()).toEqual([t.steward]); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 9c474021..c4b34449 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -37,7 +37,7 @@ import { type ProjectFile, } from "./config.js"; import { nightlyDue, stillNight } from "./nightly.js"; -import { advanced, approvalWanted, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, lifecycle, newestCommentAt, phaseAndStage, resolveChecklistItem, specHash, stuckDue, unheardWait, type Change } from "./reconcile.js"; +import { advanced, anyWorkerInFlight, approvalWanted, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, lifecycle, newestCommentAt, phaseAndStage, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, STEWARDS_PLUGIN_ID, @@ -288,7 +288,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P compactAboveTokens: { type: "number", label: "Compact a steward above this many context tokens", - description: "After a steward's or the project steward's turn, its context is compacted when it holds more than this. Every wake is self-contained, so little is lost. 0 leaves compaction to the provider.", + description: "After a steward's or the project steward's turn, and before a wake that would push it over, its context is compacted when it holds more than this. Every wake is self-contained, so little is lost. 0 leaves compaction to the provider.", default: 120_000, }, }); @@ -867,6 +867,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b.threadId === null) { await spawnSteward(b, config, playbook, text); } else { + // A wake can be the thing that pushes the transcript over the limit; + // compact first (criterion 4). If compaction makes the thread busy, + // sendTo queues the wake for the next idle. + await compactIfLarge(b.threadId, text.length); const sent = await sendTo(b.threadId, text); if (sent === "gone") { // The user deleted the thread: that is a detach they meant. @@ -969,8 +973,8 @@ 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 workerRunning = store.workers(b.id).some((w) => w.status === "running"); - const fresh = prev === null ? [] : diffObserved(prev, observed, { own: ownThreads(b), stewardThreadId: b.threadId, approved: ready.approval !== null, cursor: b.commentCursor, workerRunning }); + 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 }); changes.push(...fresh); // Only an entry into build from spec: review → build is the worker's // normal loop, and an unreported checklist is not an unmet one. @@ -1034,7 +1038,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P async function stopWorkers(b: Binding): Promise { for (const w of store.workers(b.id)) { - if (w.status !== "running") continue; + if (!workerInFlight(w)) continue; store.setWorker(w.threadId, "stopped", w.result); await quietly(`stop worker ${w.threadId}`, () => bb.sdk.threads.stop({ threadId: w.threadId })); } @@ -1258,22 +1262,24 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (threadId === null) return; const records = opts.digestDue ? digestRecords(projectId) : undefined; if (opts.digestDue) store.patchProject(projectId, { digestPending: true }); + const info = await threadInfo(threadId).catch(() => null); + if (info === null || info.deletedAt !== null) return; + if (info.archivedAt !== null) await quietly(`unarchive ${threadId}`, () => bb.sdk.threads.unarchive({ threadId })); // Read as of the send, so an escalation resolved meanwhile is left out, // and marked delivered in the same step, so a prompt sent right after // lists it as still open rather than new. The text is built before the // mark, so a throw while building it leaves nothing marked. - const delivered = { ids: [] as string[], at: 0 }; - const sent = await sendTo(threadId, () => { - const open = store.open(projectId); - const routed = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "project").map((escalation) => ({ escalation, from: b }))); - const withUser = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "me" && x.kind !== "approval").map((escalation) => ({ escalation, from: b }))); - const bindings = open.map((binding) => ({ binding, openEscalations: store.openEscalations(binding.id) })); - const questions = store.openQuestions(projectId).map((question) => ({ question, about: question.bindingId === null ? null : store.binding(question.bindingId) })); - const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, questions, timeZone: config.file.nightly.timezone, ...(records === undefined ? {} : { records }) }); - delivered.ids = routed.filter((r) => r.escalation.deliveredAt === null).map((r) => r.escalation.id); - delivered.at = store.markDelivered(delivered.ids); - return text; - }); + const open = store.open(projectId); + const routed = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "project").map((escalation) => ({ escalation, from: b }))); + const withUser = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "me" && x.kind !== "approval").map((escalation) => ({ escalation, from: b }))); + const bindings = open.map((binding) => ({ binding, openEscalations: store.openEscalations(binding.id) })); + const questions = store.openQuestions(projectId).map((question) => ({ question, about: question.bindingId === null ? null : store.binding(question.bindingId) })); + const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, questions, timeZone: config.file.nightly.timezone, ...(records === undefined ? {} : { records }) }); + const delivered = { ids: routed.filter((r) => r.escalation.deliveredAt === null).map((r) => r.escalation.id), at: 0 }; + delivered.at = store.markDelivered(delivered.ids); + // A wake can be the thing that pushes the transcript over the limit. + await compactIfLarge(threadId, text.length); + const sent = await send(threadId, text); if (sent !== "sent") store.undeliver(delivered.ids, delivered.at); } @@ -1465,7 +1471,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P async function archiveWaiting(b: Binding): Promise { store.patch(b.id, { archiveWhenIdle: false }); if (b.threadId === null || b.endedAt !== null || b.ending !== null) return; - if (store.workers(b.id).some((w) => w.status === "running") || store.openEscalations(b.id).length > 0) return; + if (anyWorkerInFlight(store.workers(b.id)) || store.openEscalations(b.id).length > 0) return; const info = await threadInfo(b.threadId).catch(() => null); if (info === null || info.deletedAt !== null || info.archivedAt !== null || busy(info.status)) return; await quietly(`archive ${b.entityKey}'s waiting steward`, () => bb.sdk.threads.archive({ threadId: info.id })); @@ -1473,20 +1479,24 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } /** - * Compact a steward's context once it has grown past the setting, while it - * is idle. Every wake carries what the steward needs (DESIGN.md §6), so - * its transcript can go; without this a steward's context only grows, and + * Compact a steward's context once it has grown past the setting, or once + * a wake about to be sent would push it over (criterion 4), while it is + * idle. Every wake carries what the steward needs (DESIGN.md §6), so its + * transcript can go; without this a steward's context only grows, and * every later turn reads all of it. A reading already compacted on is not * acted on twice, should the provider not report a new one. */ const compactedOn = new Map(); - async function compactIfLarge(threadId: string): Promise { + async function compactIfLarge(threadId: string, incomingChars = 0): Promise { const limit = (await settings.get()).compactAboveTokens; if (!(limit > 0)) return false; try { const [usage] = await bb.sdk.threads.events.list({ threadId, types: ["thread/contextWindowUsage/updated"], order: "desc", limit: "1" }); const used = (usage?.data as { contextWindowUsage?: { usedTokens?: number | null } } | undefined)?.contextWindowUsage?.usedTokens ?? null; - if (used === null || used <= limit || compactedOn.get(threadId) === used) return false; + if (used === null || !compactDue(used, limit, incomingChars) || compactedOn.get(threadId) === used) return false; + // A busy thread cannot be compacted; skip it rather than warn on every wake. + const info = await threadInfo(threadId).catch(() => null); + if (info === null || info.deletedAt !== null || busy(info.status)) return false; compactedOn.set(threadId, used); await bb.sdk.threads.compact({ threadId }); bb.log.info(`stewards: compacted ${threadId} at ${used} context tokens`); @@ -1506,7 +1516,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.events.on("thread.failed", ({ thread, error }) => { const worker = store.worker(thread.id); - if (worker === null || worker.status !== "running") return; + if (worker === null || !workerInFlight(worker)) return; store.setWorker(thread.id, "failed", error); store.note(worker.bindingId, `Worker "${worker.title}" failed: ${error ?? "no detail"}`); scheduleReconcile(worker.bindingId); @@ -1518,11 +1528,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // bring it back until it is removed and re-added. bb.events.on("thread.archived", ({ thread }) => { const worker = store.worker(thread.id); - if (worker !== null && worker.status === "running") store.setWorker(thread.id, "stopped", worker.result); + if (worker !== null && workerInFlight(worker)) store.setWorker(thread.id, "stopped", worker.result); }); bb.events.on("thread.deleted", ({ thread }) => { const worker = store.worker(thread.id); - if (worker !== null && worker.status === "running") store.setWorker(thread.id, "stopped", worker.result); + if (worker !== null && workerInFlight(worker)) store.setWorker(thread.id, "stopped", worker.result); const b = store.byThread(thread.id); if (b === null || b.endedAt !== null) return; store.patch(b.id, { threadId: null, endedAt: now(), endReason: "deleted", manualDetach: true, awaitingReport: false, ending: null });