From 7d34fe248861d2e865e71c2b1848f352d7aa19d3 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sat, 24 Oct 2026 19:19:06 +0000 Subject: [PATCH 1/3] stewards: archive finished workers and reviewers, and hide them with a waiting steward (BB-47) --- plugins/stewards/DESIGN.md | 39 +++++++--- plugins/stewards/README.md | 22 +++++- plugins/stewards/server.test.ts | 112 ++++++++++++++++++++++++++- plugins/stewards/server.ts | 131 +++++++++++++++++++++++++++++--- 4 files changed, 277 insertions(+), 27 deletions(-) diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 7503b345..c84c2f42 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -106,7 +106,8 @@ These were settled while designing; each changes what gets built. Stewards pin nothing and create no sidebar sections. A finished steward says so in its last turn and the plugin archives it when the binding ends; a later wake brings it back. A steward waiting on someone else is - hidden between wakes too (§5, "Waiting"). thread-briefs is asked, + hidden between wakes too, and its finished workers and their reviewers are + hidden with it (§5, "Waiting"). thread-briefs is asked, through each thread's metadata, not to archive or rename stewards and not to group the project steward: between wakes a steward reads done while its entity is still open, and its title carries the entity key. (This @@ -270,10 +271,12 @@ plugins. stays addressable, and the next wake reaches it. It is made visible again when it needs the user — the report puts the user next, an escalation is open, a question is unanswered, or a needs item is on the Stewards page — - and stays hidden across "nothing changed" wakes. Hiding does not cascade to - the workers, so a worker in flight is no reason to keep the steward - visible; the open-escalation rule stays. A report that needs nobody is also - marked read (`threads.markRead`), so the unread dot means "needs you"; + and stays hidden across "nothing changed" wakes. Hiding cascades to the + steward's finished workers and their reviewers, so a row is not left + behind without its steward; a running worker is unaffected, and showing the + steward again shows them. The open-escalation rule stays. A report that + needs nobody is also marked read (`threads.markRead`), so the unread dot + means "needs you"; binding end still archives the thread. Workers stay lifecycle-owned: they are the steward's children in bb, and the plugin stops them explicitly only when the binding ends (a detach, or a terminal state without @@ -283,6 +286,16 @@ plugins. anything else; a worker archived since it asked is brought back on that wake so the tell reaches it, and a worker whose thread is gone is reported as gone, needing a fresh one. +- **Finished workers and reviewers.** A worker's turn ending marks it + `finished`; once the reconcile that consumed its report has woken the + steward, its thread is archived, so the sidebar keeps only work in flight. + A worker that ended with a question for the steward stays visible until it + is answered, and so does a worker whose binding needs the user. A reviewer + is archived once its round is consumed — the worker's next turn ends, or a + newer round reviewer is spawned for the same worker — and the newest + reviewer for a worker is never archived while that worker is in flight. + Messaging an archived worker unarchives it first (`sendTo`), and it shows + under its effort again. - **Parent ends first.** Promoted sub-issues still open are re-parented to the next managed ancestor, or the project steward. @@ -513,6 +526,9 @@ gets a review steward. - **Rounds.** For each round the review steward starts a review worker on the pull request head with fresh context and the playbook's review instructions. The worker returns findings; the steward posts them as your review, signed. + A reviewer thread is archived once its round is consumed — the worker's + next turn ends, or a newer round reviewer is spawned for the same worker — + so six rounds do not leave six rows in the sidebar (§5). - **Later rounds** — new pushes after your review, or a re-request — cover only what changed since your last review. - **Reviews post without asking, approvals included.** The review steward @@ -743,13 +759,18 @@ follow-through: 6h # how long a terminal binding may be kept open owner. Whether it should tree by lifecycle owner too is a core question, not worked around here. The `thread.created` handler files any unsectioned worker or reviewer into the owner's project section, so a skill that - builds its own spawn command lands there too. + builds its own spawn command lands there too. A finished worker's thread is + archived once the reconcile that consumed its report has woken the steward, + and a reviewer once its round is consumed, so a long-running binding does + not leave its finished rows loose (§5). - Whether a steward is waiting on you, waiting on someone else, or done is thread-briefs' judgment from its transcript. A steward waiting on someone else is hidden (`threads.update { visibility: "hidden" }`), not archived, - so it leaves the sidebar but stays addressable; a wake that needs you makes - it visible again, and the unread dot is cleared after a report that needs - nobody. Ended bindings are archived by this plugin, not by thread-briefs. + so it leaves the sidebar but stays addressable; its finished workers and + their reviewers are hidden with it, and a wake that needs you makes them + visible again. A running worker is not hidden. The unread dot is cleared + after a report that needs nobody. Ended bindings are archived by this + plugin, not by thread-briefs. ## 16. Architecture diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index d13e422e..2bc03674 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -138,8 +138,18 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. stays addressable, so a later wake can reach it. It is made visible again when it needs you (the report puts you next, an escalation is open, or a question is unanswered) and stays hidden across "nothing changed" wakes. - Hiding does not cascade to its workers, so a worker in flight is no reason - to keep it visible; binding end still archives. + Hiding cascades to its finished workers and their reviewers, so no row is + left behind without its steward; a running worker is unaffected, and + showing the steward again shows them. Binding end still archives. +- **Finished workers and reviewers.** A worker whose turn ends is marked + `finished`; once the reconcile that consumed its report has woken the + steward, its thread is archived, so the sidebar keeps only work in flight. + A worker that ended with a question for the steward stays visible until it + is answered. A reviewer is archived once its round is consumed — the + worker's next turn ends, or a newer round reviewer is spawned for the same + worker — and the newest reviewer for a worker is never archived while that + worker is in flight. A later message to an archived worker unarchives it, + and it shows under its effort again. - **thread-briefs.** Every steward, the project steward included, is spawned with `threadBriefs: { rename: false, group: false, archive: false }` in this plugin's metadata namespace (see thread-briefs' "Threads a plugin @@ -157,12 +167,16 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. that, a project steward renamed by hand keeps its name. - **The sidebar and the unread dot.** A steward is put in its project's section when it is spawned, and a worker or reviewer the plugin did not - place is filed there by the `thread.created` handler. The unread dot + place is filed there by the `thread.created` handler. A finished worker + leaves the sidebar once its report is consumed, and a consumed reviewer + once its round is; a waiting steward's finished workers and their reviewers + hide with it and come back when it does. The unread dot means "needs you": a report that waits on someone else, with no escalation, question or needs item, is marked read. A report that needs you is left unread. - **Workers** are top-level threads with their own checkout, one per bounded - task, owned by their steward through `--lifecycle-owner-thread`. They do + task, owned by their steward through `--lifecycle-owner-thread`. A reviewer + is a child of the worker that started it, one per review round. Workers do not nest under their steward's sidebar row: bb's list trees by parent thread, not by lifecycle owner, so they show loose; whether it should tree by lifecycle owner too is a core question. A runaway guard stops a diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 95adc410..aa427270 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -339,13 +339,13 @@ async function setup(extra: Partial = {}, settings: Record { - w.threads.set(id, { status: "active", archivedAt: null, 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" }); await harness.behavior.emitThreadEvent("thread.created", { thread: makeThreadResponse({ id, parentThreadId: null, lifecycleOwnerThreadId: owner, title, originPluginId: null, providerId: "claude-code", sectionId }) }); await flush(); }; @@ -1414,7 +1414,9 @@ describe("terminal states and follow-through", () => { await t.idle(t.steward); expect((await t.list())[0]).toMatchObject({ ended: true }); expect(t.stops()).toEqual(["thr_w1", "thr_w2"]); - expect(t.archives()).toEqual([t.steward]); + // thr_w1 finished and its report was consumed by the follow-through wake, + // so it was archived then; the steward archives at the binding's end. + expect(t.archives()).toEqual(["thr_w1", t.steward]); }); it("ends a follow-through that runs out, stopping its workers and telling the project steward", async () => { @@ -1890,6 +1892,110 @@ describe("stewards waiting on others", () => { }); }); +describe("archiving finished workers and reviewers (BB-47)", () => { + it("archives a reviewer once its worker's next turn ends, but not while its round is running", 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); + await t.created("thr_r1", "thr_w1", "Review round 1"); + + // The worker ends its turn to wait on the reviewer, which is still + // running: its round is not consumed, so it stays. + t.threads.get("thr_r1")!.status = "active"; + await t.idle("thr_w1", "Should I wait for the reviewer?"); + expect(t.threads.get("thr_r1")!.archivedAt).toBeNull(); + + // The reviewer has finished and the worker's next turn ends: the round is + // consumed and the reviewer leaves the sidebar. + t.threads.get("thr_r1")!.status = "idle"; + await t.idle("thr_w1", "Addressed the review and pushed."); + expect(t.threads.get("thr_r1")!.archivedAt).not.toBeNull(); + }); + + it("archives the older reviewer when a newer round is spawned, and never the newest while its worker is in flight", 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); + await t.created("thr_r1", "thr_w1", "Review round 1"); + expect(t.threads.get("thr_w1")!.status).toBe("active"); + await t.created("thr_r2", "thr_w1", "Review round 2"); + expect(t.threads.get("thr_r1")!.archivedAt).not.toBeNull(); + expect(t.threads.get("thr_r2")!.archivedAt).toBeNull(); + }); + + it("archives a finished worker after the reconcile that consumed its report, unless it needs the user", 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); + await t.idle("thr_w1", "Implemented the fix."); + expect(t.hooks.store.worker("thr_w1")!.status).toBe("finished"); + expect(t.threads.get("thr_w1")!.archivedAt).not.toBeNull(); + + // A worker that ended with a question for the steward stays, so the + // steward can answer it. + await t.created("thr_w2", steward); + await t.idle("thr_w2", "Should I file a follow-up?"); + expect(t.threads.get("thr_w2")!.archivedAt).toBeNull(); + }); + + it("unarchives a finished worker when the plugin messages it, so it shows under its effort again", 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); + await t.idle("thr_w1", "Implemented the fix."); + expect(t.threads.get("thr_w1")!.archivedAt).not.toBeNull(); + + // An escalation the worker raised is answered: the plugin tells it through + // sendTo, which brings an archived thread back first. + const b = t.hooks.store.find("ENG-12")!; + const x = t.hooks.store.escalate({ bindingId: b.id, kind: "decision", question: "Which approach?", meanwhile: "Wait.", route: "me", recommendation: null, projectId: "p1", origin: { threadId: "thr_w1", bindingId: b.id, chain: [] } }); + t.hooks.store.resolve(x.id, "The second one.", "user"); + await t.hooks.sweep(); + await t.flush(); + expect(t.threads.get("thr_w1")!.archivedAt).toBeNull(); + expect(t.sends.find((s) => s.threadId === "thr_w1")!.text).toMatch(/The second one\./u); + }); + + it("hides a waiting steward's finished workers and their reviewers with it, and shows them again", 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); + await t.created("thr_w2", steward); + await t.created("thr_r1", "thr_w1", "Review round 1"); + // thr_w1 is finished (it asked a question, so it stays visible), its + // reviewer is still running, and thr_w2 is still running. + await t.idle("thr_w1", "Should I keep the reviewer open?"); + + await t.tool("steward_report", { phase: "In Progress", summary: "Implemented.", nextAction: "Wait for the worker", actor: "other", blockedOn: "the worker" }, steward); + await t.idle(steward); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); + expect(t.threads.get("thr_w1")!.visibility).toBe("hidden"); + expect(t.threads.get("thr_r1")!.visibility).toBe("hidden"); + // A running worker is unaffected. + expect(t.threads.get("thr_w2")!.visibility).toBe("visible"); + + // A wake that needs the user brings the steward back, and them with it. + const b = t.hooks.store.byThread(steward)!; + t.hooks.store.patch(b.id, { status: { ...b.status!, actor: "me" } }); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", comments: [comment({ createdAt: "2026-10-14T16:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + expect(t.threads.get(steward)!.visibility).toBe("visible"); + expect(t.threads.get("thr_w1")!.visibility).toBe("visible"); + expect(t.threads.get("thr_r1")!.visibility).toBe("visible"); + expect(t.threads.get("thr_w2")!.visibility).toBe("visible"); + }); +}); + describe("passes", () => { it("adopts at most perPass per sweep, oldest first", async () => { const t = await setup(); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 938ebef5..e79fe180 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -68,7 +68,7 @@ import { type SessionWake, type Source, } from "./source-contract.js"; -import { ACTORS, MIGRATIONS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store } from "./store.js"; +import { ACTORS, MIGRATIONS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store, type Worker } from "./store.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY } from "./sidebar-provider.js"; @@ -933,7 +933,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // ---- threads ---------------------------------------------------------------------------- - type ThreadInfo = { id: string; title: string | null; status: string; archivedAt: number | null; deletedAt: number | null; environmentId: string | null; environmentHostId: string | null; providerId: string; parentThreadId: string | null; sectionId: string | null }; + type ThreadInfo = { id: string; title: string | null; status: string; archivedAt: number | null; deletedAt: number | null; visibility: string | null; environmentId: string | null; environmentHostId: string | null; providerId: string; parentThreadId: string | null; sectionId: string | null }; async function threadInfo(threadId: string): Promise { try { @@ -944,6 +944,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P status: String(t.status ?? "idle"), archivedAt: t.archivedAt ?? null, deletedAt: t.deletedAt ?? null, + visibility: t.visibility === undefined ? null : String(t.visibility), environmentId: t.environmentId ?? null, // The SDK's thread carries its machine on `environment`, not at the top level. environmentHostId: t.environment?.hostId ?? t.environmentHostId ?? null, @@ -1203,6 +1204,94 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ); } + /** + * The worker a thread is a child of, if any. A reviewer is spawned with + * its worker as parent (`--parent-self`, what build-tickets uses) or as + * lifecycle owner; either way its parent is the worker, not the steward. + * Null for a worker itself and for anything else. + */ + function reviewerOwner(thread: { lifecycleOwnerThreadId: string | null; parentThreadId: string | null }): Worker | null { + for (const id of [thread.parentThreadId, thread.lifecycleOwnerThreadId]) { + if (id === null) continue; + const w = store.worker(id); + if (w !== null) return w; + } + return null; + } + + /** A worker's reviewer threads, as bb lists them: its children, hidden or not, not archived. */ + async function reviewersOf(workerThreadId: string): Promise> { + const children = await bb.sdk.threads.list({ parentThreadId: workerThreadId, includeHidden: true }).catch(() => []); + return children.filter((c) => c.archivedAt === null).map((c) => ({ id: c.id, status: String(c.status) })); + } + + /** + * Archive a reviewer whose round is consumed. A worker's turn ending means + * it has read the verdict (or ended the turn that spawned the reviewer to + * wait); a reviewer still running is left alone, so the newest round is + * never archived while its worker is in flight (BB-47). + */ + async function archiveConsumedReviewers(workerThreadId: string): Promise { + for (const r of await reviewersOf(workerThreadId)) { + if (busy(r.status)) continue; + await quietly(`archive consumed reviewer ${r.id}`, () => bb.sdk.threads.archive({ threadId: r.id })); + } + } + + /** A newer reviewer round supersedes the older ones: archive every other child of the worker. */ + async function supersedeOlderReviewers(workerThreadId: string, keep: string): Promise { + for (const r of await reviewersOf(workerThreadId)) { + if (r.id === keep) continue; + await quietly(`archive superseded reviewer ${r.id}`, () => bb.sdk.threads.archive({ threadId: r.id })); + } + } + + /** + * Archive a finished worker once the reconcile that consumed its report + * has run, so its row leaves the sidebar with the steward's next turn. A + * worker that ended with a question for the steward, or whose binding + * needs the user, stays visible; a later message to an archived worker + * unarchives it (sendTo), and it shows under its effort again (BB-47). + */ + async function archiveFinishedWorkers(b: Binding): Promise { + if (needsUser(b)) return; + for (const w of store.workers(b.id)) { + if (w.status !== "finished" || workerQuestion(w.result) !== null) continue; + const info = await threadInfo(w.threadId).catch(() => null); + if (info === null || info.deletedAt !== null || info.archivedAt !== null || busy(info.status)) continue; + await quietly(`archive finished worker ${w.threadId}`, () => bb.sdk.threads.archive({ threadId: w.threadId })); + } + } + + /** Set a thread's sidebar visibility, unless it is archived, gone, or already there. */ + async function setVisibility(threadId: string, visibility: "hidden" | "visible"): Promise { + const info = await threadInfo(threadId).catch(() => null); + if (info === null || info.deletedAt !== null || info.archivedAt !== null || info.visibility === visibility) return; + await quietly(`${visibility === "hidden" ? "hide" : "show"} ${threadId}`, () => bb.sdk.threads.update({ threadId, visibility })); + } + + /** + * A waiting steward's finished workers and their reviewers share its + * visibility: hidden with it, and shown again when it comes back. Running + * workers are unaffected (BB-47). + */ + async function cascadeVisibility(b: Binding, visibility: "hidden" | "visible"): Promise { + for (const w of store.workers(b.id)) { + if (visibility === "hidden" && w.status !== "finished") continue; + await setVisibility(w.threadId, visibility); + for (const r of await reviewersOf(w.threadId)) await setVisibility(r.id, visibility); + } + } + + /** Show a steward, and with it the finished workers and reviewers that were hidden with it. */ + async function showSteward(b: Binding): Promise { + if (b.threadId === null) return; + const info = await threadInfo(b.threadId).catch(() => null); + const wasHidden = info !== null && info.visibility === "hidden"; + await quietly(`show ${b.entityKey}'s steward`, () => bb.sdk.threads.update({ threadId: b.threadId!, visibility: "visible" })); + if (wasHidden) await cascadeVisibility(b, "visible"); + } + /** * Keep the project steward's title on its project's name, and tag it. A * title someone else put there is left alone: only one still showing what @@ -1416,8 +1505,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // sendTo queues the wake for the next idle. await compactIfLarge(b.threadId, text.length); // A wake that needs the user brings a hidden steward back into the - // sidebar; a scheduled look that found nothing leaves it hidden. - if (needsUser(b)) await quietly(`show ${b.entityKey}'s steward`, () => bb.sdk.threads.update({ threadId: b.threadId!, visibility: "visible" })); + // sidebar, with the finished workers and reviewers that were hidden with + // it; a scheduled look that found nothing leaves it hidden. + if (needsUser(b)) await showSteward(b); const sent = await sendTo(b.threadId, text); if (sent === "gone") { // The user deleted the thread: that is a detach they meant. @@ -1429,7 +1519,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } /** Wake the steward, spawning its thread on the first wake. */ - async function wake(b: Binding, config: ProjectConfig, playbook: Playbook, observed: Observed, changes: string[], reason: WakeReason): Promise { + async function wake(b: Binding, config: ProjectConfig, playbook: Playbook, observed: Observed, changes: string[], reason: WakeReason): Promise { const gate = gateState(playbook, b.ready, specHashFor(b, observed.entity)); const workerQuestions = await collectWorkerQuestions(b); const text = formatWake({ @@ -1457,7 +1547,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P conflicts: conflictsOf(b, store.open(b.projectId)), now: now(), }); - if (!(await deliverWake(b, config, playbook, text))) return; + if (!(await deliverWake(b, config, playbook, text))) return false; const cursor = newestCommentAt(observed); store.patch(b.id, { awaitingReport: true, @@ -1469,6 +1559,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // A fallback until the report names its own. requeueAt: now() + playbook.requeueDefaultMs, }); + return true; } /** @@ -1640,7 +1731,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (reason !== null && reason !== "changed") store.note(b.id, `Due: ${reason}`); return; } - await wake(b, config, playbook, observed, lines, reason ?? (followingThrough(b) ? "follow-through" : b.requeueAt !== null && b.requeueAt <= now() && loudQueued === 0 ? "requeue" : "changed")); + // The steward now has the workers' reports: archive the finished ones + // that do not need it to stay visible (BB-47). Only once the wake was + // delivered, so a failed send keeps the worker for the retry. + if (await wake(b, config, playbook, observed, lines, reason ?? (followingThrough(b) ? "follow-through" : b.requeueAt !== null && b.requeueAt <= now() && loudQueued === 0 ? "requeue" : "changed"))) await archiveFinishedWorkers(store.binding(b.id) ?? b); } // ---- ops bindings ---------------------------------------------------------------------------- @@ -1875,6 +1969,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); if (!(await deliverWake(b, config, playbook, text))) return; store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); + // The steward now has the workers' reports: archive the finished ones (BB-47). + await archiveFinishedWorkers(store.binding(b.id) ?? b); } /** The same turn for a Dependabot alert target: re-list the open alerts and wake on what changed. */ @@ -1929,6 +2025,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); if (!(await deliverWake(b, config, playbook, text))) return; store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); + // The steward now has the workers' reports: archive the finished ones (BB-47). + await archiveFinishedWorkers(store.binding(b.id) ?? b); } // ---- Sentry targets ---------------------------------------------------------------------------- @@ -2119,6 +2217,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); if (!(await deliverWake(b, config, playbook, text))) return; store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); + // The steward now has the workers' reports: archive the finished ones (BB-47). + await archiveFinishedWorkers(store.binding(b.id) ?? b); } // The subscriber: one stream to bb-gate-hooks for the `sentry` source, @@ -3080,6 +3180,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await placeOnce(spawned.projectId, { id: thread.id, sectionId: thread.sectionId ?? null }); await tagThread(thread.id, STEWARD_BRIEFS); } + // A reviewer is a child of a worker. The newest round supersedes the + // older ones, so they are archived as it is created (BB-47). + const reviewerOf = reviewerOwner(thread); + if (reviewerOf !== null) await supersedeOlderReviewers(reviewerOf.threadId, thread.id); const owner = [thread.lifecycleOwnerThreadId, thread.parentThreadId].map((t) => (t === null ? null : store.byThread(t))).find((b) => b !== null && b !== undefined && b.endedAt === null); if (owner === undefined || owner === null || store.worker(thread.id) !== null) return; const limit = (await settings.get()).workerSpawnsPerHour; @@ -3103,6 +3207,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (worker.status === "stopped") return; store.setWorker(thread.id, "finished", lastAssistantText === null ? null : clip(lastAssistantText, 4000)); 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.`); @@ -3166,9 +3273,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * out of the sidebar's organisation and unread attention while remaining * addressable; the binding stays, and the next wake brings it back * (deliverWake). Not while anything needs the user — an open escalation, a - * question, or a needs item — which they should still see. Unlike the - * archive it replaced, hiding does not cascade to the steward's workers, so - * a worker in flight is no reason to keep it visible (BB-14/BB-17). + * question, or a needs item — which they should still see. The finished + * workers and their reviewers are hidden with it, so a row without its + * steward is not left behind; a running worker is unaffected, and showing + * the steward again shows them (BB-47). */ async function hideWaiting(b: Binding): Promise { store.patch(b.id, { archiveWhenIdle: false }); @@ -3177,6 +3285,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const info = await threadInfo(b.threadId).catch(() => null); if (info === null || info.deletedAt !== null || info.archivedAt !== null || busy(info.status)) return; await quietly(`hide ${b.entityKey}'s waiting steward`, () => bb.sdk.threads.update({ threadId: info.id, visibility: "hidden" })); + await cascadeVisibility(b, "hidden"); bb.log.info(`stewards: ${b.entityKey} waits on others; hid its steward until the next wake`); } @@ -4332,7 +4441,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // terminal ending archives the thread, so there is no read state to // set. if (b.ending !== "terminal") { - if (needsUser(b)) await quietly(`show ${b.entityKey}'s steward`, () => bb.sdk.threads.update({ threadId, visibility: "visible" })); + if (needsUser(b)) await showSteward(b); else await quietly(`mark ${b.entityKey}'s steward read`, () => bb.sdk.threads.markRead({ threadId })); } if (moved && b.parentBindingId !== null) { From 60b74285216aab064cf901e12c728b0fdadf6bf2 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sat, 24 Oct 2026 19:34:17 +0000 Subject: [PATCH 2/3] stewards: keep a worker while its reviewer runs, show only what was hidden, and tell the steward to unarchive (BB-47) --- plugins/stewards/DESIGN.md | 6 ++++-- plugins/stewards/README.md | 4 +++- plugins/stewards/server.test.ts | 29 +++++++++++++++++++++-------- plugins/stewards/server.ts | 27 ++++++++++++++++----------- plugins/stewards/wake.ts | 2 +- 5 files changed, 45 insertions(+), 23 deletions(-) diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index c84c2f42..a61bb0ee 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -294,8 +294,10 @@ plugins. is archived once its round is consumed — the worker's next turn ends, or a newer round reviewer is spawned for the same worker — and the newest reviewer for a worker is never archived while that worker is in flight. - Messaging an archived worker unarchives it first (`sendTo`), and it shows - under its effort again. + Messaging an archived worker from the plugin unarchives it first (`sendTo`), + and it shows under its effort again; the steward's own `bb thread tell` + refuses an archived thread, so it brings the worker back with + `bb thread unarchive` first, or starts a fresh worker. - **Parent ends first.** Promoted sub-issues still open are re-parented to the next managed ancestor, or the project steward. diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 2bc03674..25130bd1 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -149,7 +149,9 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. worker's next turn ends, or a newer round reviewer is spawned for the same worker — and the newest reviewer for a worker is never archived while that worker is in flight. A later message to an archived worker unarchives it, - and it shows under its effort again. + and it shows under its effort again; the steward's own `bb thread tell` + refuses an archived thread, so it runs `bb thread unarchive ` first, or + starts a fresh worker. - **thread-briefs.** Every steward, the project steward included, is spawned with `threadBriefs: { rename: false, group: false, archive: false }` in this plugin's metadata namespace (see thread-briefs' "Threads a plugin diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index aa427270..4a2885c4 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -1893,7 +1893,7 @@ describe("stewards waiting on others", () => { }); describe("archiving finished workers and reviewers (BB-47)", () => { - it("archives a reviewer once its worker's next turn ends, but not while its round is running", async () => { + it("archives a reviewer once its worker's next turn ends, and keeps the worker until the round is consumed", async () => { const t = await setup(); t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); await t.ring("linear", "uuid-12"); @@ -1902,16 +1902,19 @@ describe("archiving finished workers and reviewers (BB-47)", () => { await t.created("thr_r1", "thr_w1", "Review round 1"); // The worker ends its turn to wait on the reviewer, which is still - // running: its round is not consumed, so it stays. + // running: neither is archived (archiving the worker would clear the + // reviewer's parent in bb and stall the review loop). t.threads.get("thr_r1")!.status = "active"; - await t.idle("thr_w1", "Should I wait for the reviewer?"); + await t.idle("thr_w1", "Waiting on the reviewer."); expect(t.threads.get("thr_r1")!.archivedAt).toBeNull(); + expect(t.threads.get("thr_w1")!.archivedAt).toBeNull(); // The reviewer has finished and the worker's next turn ends: the round is - // consumed and the reviewer leaves the sidebar. + // consumed, so the reviewer leaves the sidebar, and now the worker does. t.threads.get("thr_r1")!.status = "idle"; await t.idle("thr_w1", "Addressed the review and pushed."); expect(t.threads.get("thr_r1")!.archivedAt).not.toBeNull(); + expect(t.threads.get("thr_w1")!.archivedAt).not.toBeNull(); }); it("archives the older reviewer when a newer round is spawned, and never the newest while its worker is in flight", async () => { @@ -1953,8 +1956,9 @@ describe("archiving finished workers and reviewers (BB-47)", () => { await t.idle("thr_w1", "Implemented the fix."); expect(t.threads.get("thr_w1")!.archivedAt).not.toBeNull(); - // An escalation the worker raised is answered: the plugin tells it through - // sendTo, which brings an archived thread back first. + // The escalation is raised after the archive to exercise sendTo's + // unarchive directly; a real worker with an open escalation would keep + // needsUser true and not be archived in the first place. const b = t.hooks.store.find("ENG-12")!; const x = t.hooks.store.escalate({ bindingId: b.id, kind: "decision", question: "Which approach?", meanwhile: "Wait.", route: "me", recommendation: null, projectId: "p1", origin: { threadId: "thr_w1", bindingId: b.id, chain: [] } }); t.hooks.store.resolve(x.id, "The second one.", "user"); @@ -1971,9 +1975,14 @@ describe("archiving finished workers and reviewers (BB-47)", () => { const steward = t.spawns[1]!.id; await t.created("thr_w1", steward); await t.created("thr_w2", steward); + await t.created("thr_w3", steward); await t.created("thr_r1", "thr_w1", "Review round 1"); // thr_w1 is finished (it asked a question, so it stays visible), its - // reviewer is still running, and thr_w2 is still running. + // reviewer is still running, thr_w2 runs, and thr_w3's reviewer is a + // build-tickets hidden spawn (a running worker's reviewer is not hidden + // by the cascade and must stay hidden when the steward comes back). + await t.created("thr_r2", "thr_w3", "Review round 1"); + t.threads.get("thr_r2")!.visibility = "hidden"; await t.idle("thr_w1", "Should I keep the reviewer open?"); await t.tool("steward_report", { phase: "In Progress", summary: "Implemented.", nextAction: "Wait for the worker", actor: "other", blockedOn: "the worker" }, steward); @@ -1981,8 +1990,9 @@ describe("archiving finished workers and reviewers (BB-47)", () => { expect(t.threads.get(steward)!.visibility).toBe("hidden"); expect(t.threads.get("thr_w1")!.visibility).toBe("hidden"); expect(t.threads.get("thr_r1")!.visibility).toBe("hidden"); - // A running worker is unaffected. + // A running worker is unaffected, and neither is its hidden reviewer. expect(t.threads.get("thr_w2")!.visibility).toBe("visible"); + expect(t.threads.get("thr_r2")!.visibility).toBe("hidden"); // A wake that needs the user brings the steward back, and them with it. const b = t.hooks.store.byThread(steward)!; @@ -1993,6 +2003,9 @@ describe("archiving finished workers and reviewers (BB-47)", () => { expect(t.threads.get("thr_w1")!.visibility).toBe("visible"); expect(t.threads.get("thr_r1")!.visibility).toBe("visible"); expect(t.threads.get("thr_w2")!.visibility).toBe("visible"); + // The show cascade is symmetric: it does not flip a running worker's + // hidden reviewer into the sidebar. + expect(t.threads.get("thr_r2")!.visibility).toBe("hidden"); }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index e79fe180..f04695a4 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -983,6 +983,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const info = await threadInfo(threadId).catch(() => null); if (info === null || info.deletedAt !== null) return "gone"; if (info.archivedAt !== null) await quietly(`unarchive ${threadId}`, () => bb.sdk.threads.unarchive({ threadId })); + // A worker the waiting cascade hid comes back with the message, so a + // resumed worker shows under its effort again (BB-47). A steward's own + // thread keeps its hidden state: a wake that needs nobody stays hidden. + if (info.visibility === "hidden" && store.worker(threadId) !== null) await quietly(`show ${threadId}`, () => bb.sdk.threads.update({ threadId, visibility: "visible" })); return send(threadId, typeof text === "string" ? text : text()); } @@ -1206,17 +1210,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** * The worker a thread is a child of, if any. A reviewer is spawned with - * its worker as parent (`--parent-self`, what build-tickets uses) or as - * lifecycle owner; either way its parent is the worker, not the steward. - * Null for a worker itself and for anything else. + * its worker as parent (`--parent-self`, what build-tickets uses), which is + * also how the sidebar RPC and `reviewersOf` find it. Null for a worker + * itself and for anything else. */ - function reviewerOwner(thread: { lifecycleOwnerThreadId: string | null; parentThreadId: string | null }): Worker | null { - for (const id of [thread.parentThreadId, thread.lifecycleOwnerThreadId]) { - if (id === null) continue; - const w = store.worker(id); - if (w !== null) return w; - } - return null; + function reviewerOwner(thread: { parentThreadId: string | null }): Worker | null { + return thread.parentThreadId === null ? null : store.worker(thread.parentThreadId); } /** A worker's reviewer threads, as bb lists them: its children, hidden or not, not archived. */ @@ -1257,6 +1256,12 @@ 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 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 + // no longer wake the worker, and `reviewersOf` could never find it to + // archive it (BB-47). + if ((await reviewersOf(w.threadId)).length > 0) continue; const info = await threadInfo(w.threadId).catch(() => null); if (info === null || info.deletedAt !== null || info.archivedAt !== null || busy(info.status)) continue; await quietly(`archive finished worker ${w.threadId}`, () => bb.sdk.threads.archive({ threadId: w.threadId })); @@ -1277,7 +1282,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P */ async function cascadeVisibility(b: Binding, visibility: "hidden" | "visible"): Promise { for (const w of store.workers(b.id)) { - if (visibility === "hidden" && w.status !== "finished") continue; + if (w.status !== "finished") continue; await setVisibility(w.threadId, visibility); for (const r of await reviewersOf(w.threadId)) await setVisibility(r.id, visibility); } diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 0de3e701..f8592ad5 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -308,7 +308,7 @@ export function formatWake(input: WakeInput): string { .split("\n") .map((line) => ` ${line}`), "", - "Follow it up with `bb thread tell `. A worker finishing starts no turn of yours: its final message arrives in your next wake, which lists it under Workers.", + "Follow it up with `bb thread tell `. A worker finishing starts no turn of yours: its final message arrives in your next wake, which lists it under Workers. Once that report has been consumed the worker's thread is archived, and `bb thread tell` refuses an archived thread: bring it back with `bb thread unarchive ` first, or start a fresh worker.", "Those `--provider`/`--model`/`--reasoning-level` flags are your workers' and reviewers' models, from the playbook or the project. They are not yours to choose: never ask the user for a model.", "On a turn that is not a wake — a plain message, a `bb thread tell`, a child notice — run `bb stewards brief` first. It prints this thread's id, the allowed actions, the phase instructions, the ready gate, guidance and holds, the standing rules and the exact spawn command. `bb stewards spawn-flags` prints just the spawn command.", "", From 23224d742618bfc0787f40e6bbbe3e27bd5d1089 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sat, 24 Oct 2026 19:38:30 +0000 Subject: [PATCH 3/3] stewards: treat an unreadable reviewer listing as unknown, and show a hidden worker when it runs (BB-47) --- plugins/stewards/server.test.ts | 26 ++++++++++++++++++++++++++ plugins/stewards/server.ts | 32 +++++++++++++++++++++++--------- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 4a2885c4..e8f35535 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -2007,6 +2007,32 @@ describe("archiving finished workers and reviewers (BB-47)", () => { // hidden reviewer into the sidebar. expect(t.threads.get("thr_r2")!.visibility).toBe("hidden"); }); + + it("does not archive a finished worker when the reviewer listing fails, so a reviewer is never orphaned", 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); + // "Unknown" is not "no reviewers": the worker waits for a listing that works. + t.harness.sdk.stub("threads.list", async () => { + throw new Error("listing is down"); + }); + await t.idle("thr_w1", "Implemented the fix."); + expect(t.threads.get("thr_w1")!.archivedAt).toBeNull(); + }); + + it("shows a worker the waiting cascade hid once it is woken again", 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); + t.threads.get("thr_w1")!.visibility = "hidden"; + await t.harness.behavior.emitThreadEvent("thread.active", { thread: makeThreadResponse({ id: "thr_w1", visibility: "hidden" }) }); + await t.flush(); + expect(t.threads.get("thr_w1")!.visibility).toBe("visible"); + }); }); describe("passes", () => { diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index f04695a4..85e8b77c 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -1218,10 +1218,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return thread.parentThreadId === null ? null : store.worker(thread.parentThreadId); } - /** A worker's reviewer threads, as bb lists them: its children, hidden or not, not archived. */ - async function reviewersOf(workerThreadId: string): Promise> { - const children = await bb.sdk.threads.list({ parentThreadId: workerThreadId, includeHidden: true }).catch(() => []); - return children.filter((c) => c.archivedAt === null).map((c) => ({ id: c.id, status: String(c.status) })); + /** + * A worker's reviewer threads, as bb lists them: its children, hidden or + * not, not archived. Null when bb could not be asked, so a caller that must + * not guess — archiving a worker that might still have a reviewer — can + * tell "none" from "unknown". + */ + async function reviewersOf(workerThreadId: string): Promise | null> { + try { + const children = await bb.sdk.threads.list({ parentThreadId: workerThreadId, includeHidden: true }); + return children.filter((c) => c.archivedAt === null).map((c) => ({ id: c.id, status: String(c.status) })); + } catch (error) { + bb.log.warn(`stewards: could not list the reviewers of worker ${workerThreadId}: ${errorMessage(error)}`); + return null; + } } /** @@ -1231,7 +1241,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * never archived while its worker is in flight (BB-47). */ async function archiveConsumedReviewers(workerThreadId: string): Promise { - for (const r of await reviewersOf(workerThreadId)) { + for (const r of (await reviewersOf(workerThreadId)) ?? []) { if (busy(r.status)) continue; await quietly(`archive consumed reviewer ${r.id}`, () => bb.sdk.threads.archive({ threadId: r.id })); } @@ -1239,7 +1249,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** A newer reviewer round supersedes the older ones: archive every other child of the worker. */ async function supersedeOlderReviewers(workerThreadId: string, keep: string): Promise { - for (const r of await reviewersOf(workerThreadId)) { + for (const r of (await reviewersOf(workerThreadId)) ?? []) { if (r.id === keep) continue; await quietly(`archive superseded reviewer ${r.id}`, () => bb.sdk.threads.archive({ threadId: r.id })); } @@ -1260,8 +1270,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // releases a thread's unarchived children from it when it is archived, // so archiving the worker would clear the reviewer's parent: it could // no longer wake the worker, and `reviewersOf` could never find it to - // archive it (BB-47). - if ((await reviewersOf(w.threadId)).length > 0) continue; + // archive it. A listing that failed is "unknown", so the worker waits + // rather than risking the orphan (BB-47). + const reviewers = await reviewersOf(w.threadId); + if (reviewers === null || reviewers.length > 0) continue; const info = await threadInfo(w.threadId).catch(() => null); if (info === null || info.deletedAt !== null || info.archivedAt !== null || busy(info.status)) continue; await quietly(`archive finished worker ${w.threadId}`, () => bb.sdk.threads.archive({ threadId: w.threadId })); @@ -1284,7 +1296,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P for (const w of store.workers(b.id)) { if (w.status !== "finished") continue; await setVisibility(w.threadId, visibility); - for (const r of await reviewersOf(w.threadId)) await setVisibility(r.id, visibility); + for (const r of (await reviewersOf(w.threadId)) ?? []) await setVisibility(r.id, visibility); } } @@ -3381,6 +3393,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.events.on("thread.active", async ({ thread }) => { const worker = store.worker(thread.id); if (worker === null) return; + // A worker the waiting cascade hid is shown again once it runs (BB-47). + if (thread.visibility === "hidden") await quietly(`show running worker ${thread.id}`, () => bb.sdk.threads.update({ threadId: thread.id, visibility: "visible" })); if (worker.status === "finished") store.setWorker(thread.id, "running", worker.result); // The first turn is dispatched now, so the spawn's model can be read. if (worker.modelCheckPending && worker.status !== "stopped") {