diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 98a49934..224e4f2f 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -106,7 +106,7 @@ 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 - archived between wakes too (§5, "Waiting"). thread-briefs is asked, + hidden between wakes too (§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 @@ -265,26 +265,24 @@ plugins. - **Review stewards** end when the pull request is merged or closed. - **Waiting.** A wake turn whose report names `other` as the next actor (a review posted and the author's move, a ticket in review waiting on - reviewers) archives the steward's thread when the turn ends. The binding - stays, and the next wake brings the same thread back. It stays in the - sidebar 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 — or while a worker's own thread or any thread beneath a worker is - still running or pending (a worker whose reviewer is running still has - work), or while an escalation is open, while it follows through after a - terminal state, when the user is next, and after a turn the user started, - which is theirs to read. 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 follow-through), - never to keep the steward in the sidebar. Archiving a waiting steward - would therefore archive its workers and their descendants with it, and - the rule above is what keeps that from happening while a worker still - has work. When a worker's final message asks a question, - the next wake names it (`Worker thr_… asked: …`) ahead of every other - change and tells the steward to answer it with `bb thread tell` or - escalate before 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. + reviewers) hides the steward's thread when the turn ends + (`threads.update { visibility: "hidden" }`). The binding stays, the thread + 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"; + 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 + follow-through). When a worker's final message asks a question, the next + wake names it (`Worker thr_… asked: …`) ahead of every other change and + tells the steward to answer it with `bb thread tell` or escalate before + 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. - **Parent ends first.** Promoted sub-issues still open are re-parented to the next managed ancestor, or the project steward. @@ -729,23 +727,29 @@ follow-through: 6h # how long a terminal binding may be kept open - Stewards, the project steward included, are kept out of thread-briefs' status sections (`group: false`), where one idle between wakes would read done. thread-briefs only moves threads in and out of its own sections, so - it leaves the project section alone. The project steward is titled - " project steward". + it leaves the project section alone. Workers and reviewers are tagged the + same way when the `thread.created` handler files them, so thread-briefs + never moves one out of the section or auto-archives it. The project + steward is titled " project steward". - Workers are top-level threads, owned by their steward through `--lifecycle-owner-thread` and started with `bb thread spawn --project … - --lifecycle-owner-thread "$BB_THREAD_ID" …`; the plugin recognizes them by - that owner, and still recognizes a worker an older steward made a child by - its parent. A worker is no thread's child, so finishing a turn does not - wake the steward: its final message arrives in the next wake, which lists - finished workers. The sidebar loss is accepted: a worker no longer nests - under its steward's row in the project section, because bb's list trees by - parent thread and not by lifecycle owner. Whether it should tree by - lifecycle owner too is a core question, not worked around here. Workers are - not tagged for thread-briefs: their briefs, renames and auto-archiving are - thread-briefs' as for any thread. + --lifecycle-owner-thread "$BB_THREAD_ID" --section
…`; the + plugin recognizes them by that owner, and still recognizes a worker an + older steward made a child by its parent. A worker is no thread's child, + so finishing a turn does not wake the steward: its final message arrives + in the next wake, which lists finished workers. The sidebar loss is + accepted: a worker no longer nests under its steward's row in the project + section, because bb's list trees by parent thread and not by lifecycle + 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. - Whether a steward is waiting on you, waiting on someone else, or done is - thread-briefs' judgment from its transcript. Ended bindings are archived - by this plugin, not by thread-briefs. + 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. ## 16. Architecture @@ -885,7 +889,7 @@ goes wrong there into Linear tickets for the project steward to adopt. ticket linking the old one. Every `requeue-default` the steward takes a turn whatever the look found; a healthy one is cheap, a wake that says "all healthy" and a - report with actor `other`, which archives the thread until the next + report with actor `other`, which hides the thread until the next look. A sweep's look between requeues wakes it only for a new or returned problem. - **Triage is the project steward's.** The steward files one ticket per new diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 607dad68..4a4daab1 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -133,15 +133,21 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. Reopening, or re-adding the label, wakes the same thread, bringing it back from the archive; an entity that leaves its terminal state before the binding has ended takes the ending back. A steward whose wake turn reports - `actor: other` (waiting on a reviewer or the author) is archived too, - unless a worker runs or an escalation is open; its next wake brings it - back. + `actor: other` (waiting on a reviewer or the author) is hidden rather than + archived: it leaves the sidebar's organisation and unread attention but + 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. - **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 runs"). thread-briefs then never renames a steward, whose title carries its entity key, never moves one into a status section or auto-archives it, since between wakes it reads done while its entity is still open. + Workers and reviewers a steward spawns are tagged the same way, so + thread-briefs leaves them in the project's section too. A ticket or pull request steward's row draws the stage ring like any thread's. The project steward also gets `ring: false`: it has no stage of its own, so its row keeps bb's own indicators. The project steward @@ -149,6 +155,12 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. spawned before this, lets go of stewards an earlier version made children of another steward, and renames an older project steward once. After 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 + 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 not nest under their steward's sidebar row: bb's list trees by parent diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index e80156f9..ae01543c 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -28,7 +28,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(); @@ -142,6 +142,7 @@ function world() { threads.set(id, { status: "idle", archivedAt: null, + visibility: "visible", title: (args.title as string | undefined) ?? null, sectionId: (args.sectionId as string | undefined) ?? null, ...(environment?.machine?.hostId === undefined ? {} : { hostId: environment.machine.hostId }), @@ -162,7 +163,7 @@ function world() { const t = threads.get(threadId); 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, environmentId: "env1", providerId: t.providerId ?? "claude-code", parentThreadId: t.parentThreadId ?? null, sectionId: t.sectionId ?? null }), + ...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 } }), }; }, @@ -189,13 +190,15 @@ function world() { return {}; }, stop: async () => ({}), - update: async (args: { threadId: string; title?: string; parentThreadId?: string | null; sectionId?: string | null }) => { + update: async (args: { threadId: string; title?: string; parentThreadId?: string | null; sectionId?: string | null; visibility?: string }) => { const t = threads.get(args.threadId); if (t !== undefined && args.sectionId !== undefined) t.sectionId = args.sectionId; if (t !== undefined && args.title !== undefined) t.title = args.title; if (t !== undefined && args.parentThreadId !== undefined) t.parentThreadId = args.parentThreadId; + if (t !== undefined && args.visibility !== undefined) t.visibility = args.visibility; return {}; }, + markRead: async ({ threadId }: { threadId: string }) => ({ threadId, readAt: now, unreadCount: 0 }), compact: async () => ({ ok: true }), storageLocation: async ({ threadId }: { threadId: string }) => ({ hostId: "host_on", storageRootPath: `/storage/${threadId}` }), updatePluginMetadata: async (args: { threadId: string; set?: Record }) => { @@ -295,20 +298,20 @@ 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, parentThreadId: parent, providerId, ...(model === null ? {} : { model }), ...(reasoningLevel === null ? {} : { reasoningLevel }), environmentProviderId }); - await harness.behavior.emitThreadEvent("thread.created", { thread: makeThreadResponse({ id, parentThreadId: parent, lifecycleOwnerThreadId: parent, title, originPluginId: null, providerId }) }); + w.threads.set(id, { status: "active", archivedAt: null, parentThreadId: parent, sectionId: over.sectionId ?? null, providerId, ...(model === null ? {} : { model }), ...(reasoningLevel === null ? {} : { reasoningLevel }), environmentProviderId }); + 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") => { - w.threads.set(id, { status: "active", archivedAt: null, parentThreadId: null, 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" }) }); + const createdOwned = async (id: string, owner: string, title = "Implement", sectionId: string | null = null) => { + 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" }); + await harness.behavior.emitThreadEvent("thread.created", { thread: makeThreadResponse({ id, parentThreadId: null, lifecycleOwnerThreadId: owner, title, originPluginId: null, providerId: "claude-code", sectionId }) }); await flush(); }; /** A steward-filed escalation the project steward has forwarded to the user, for tests. */ @@ -368,7 +371,7 @@ describe("a Linear ticket steward", () => { expect(prompt).toMatch(/given by the project steward/u); // The first wake is the spawn prompt, before the thread has an id. expect(prompt).toMatch(/Your thread id is in `\$BB_THREAD_ID`/u); - expect(prompt).toContain(`bb thread spawn --project p1 --lifecycle-owner-thread "$BB_THREAD_ID" --environment-provider multi-repo-workspace --machine host_on --provider claude-code --model claude-opus-5-5 --reasoning-level high --title "ENG-12: " --prompt-file - <<'EOF'\n \n EOF`); + expect(prompt).toContain(`bb thread spawn --project p1 --lifecycle-owner-thread "$BB_THREAD_ID" --section sec_1 --environment-provider multi-repo-workspace --machine host_on --provider claude-code --model claude-opus-5-5 --reasoning-level high --title "ENG-12: " --prompt-file - <<'EOF'\n \n EOF`); expect(prompt).not.toContain("--parent-self"); expect(prompt).not.toContain("--parent-thread"); expect(prompt).toContain("A worker finishing starts no turn of yours"); @@ -1640,41 +1643,60 @@ describe("pull requests", () => { describe("stewards waiting on others", () => { const waiting = { phase: "open", summary: "Reviewed.", nextAction: "Sam addresses the review", actor: "other", blockedOn: "sam" }; - it("archives a review steward after a wake turn that ends waiting, and brings it back on the next", async () => { + it("hides a review steward after a wake turn that ends waiting, and keeps it hidden until a wake needs the user", async () => { const t = await setup(); t.entities.set("acme/web#7", pull()); await t.ring("github", "acme/web#7"); const steward = t.spawns[1]!.id; const report = await t.tool("steward_report", waiting, steward); - expect(report.text).toMatch(/Your thread is archived when the turn ends/u); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(report.text).toMatch(/Your thread is hidden when the turn ends/u); + expect(t.threads.get(steward)!.visibility).toBe("visible"); await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).not.toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); expect((await t.list())[0]).toMatchObject({ ended: false, threadId: steward }); - // Sam pushes: the same thread comes back for the round, then goes again. + // Sam pushes: the same thread is woken for the round, but the wake does + // not need the user, so it stays hidden and the next report keeps it so. t.entities.set("acme/web#7", pull({}, { headSha: "bbbbbbb2" })); await t.ring("github", "acme/web#7"); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); expect(t.sends.at(-1)!.text).toMatch(/Pushed bbbbbbb/u); await t.tool("steward_report", waiting, steward); await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).not.toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); expect(t.spawns).toHaveLength(2); }); - it("archives a ticket steward waiting on reviews of its pull requests", async () => { + it("brings a hidden steward back on a wake that needs the user", async () => { + const t = await setup(); + t.entities.set("acme/web#7", pull()); + await t.ring("github", "acme/web#7"); + const steward = t.spawns[1]!.id; + await t.tool("steward_report", waiting, steward); + await t.idle(steward); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); + + // The status now says the user is next (as a report would have left it), + // so the next wake is one that needs them and the row comes back. + const b = t.hooks.store.byThread(steward)!; + t.hooks.store.patch(b.id, { status: { ...b.status!, actor: "me" } }); + t.entities.set("acme/web#7", pull({}, { headSha: "ccccccc3" })); + await t.ring("github", "acme/web#7"); + expect(t.threads.get(steward)!.visibility).toBe("visible"); + }); + + it("hides a ticket steward waiting on reviews of its pull requests", async () => { const t = await setup(); t.entities.set("uuid-12", issue({ state: "In Review", stateType: "started" })); await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; await t.tool("steward_report", { ...waiting, phase: "In Review", blockedOn: "reviewers on acme/web#7" }, steward); await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).not.toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); }); - it("leaves a steward in the sidebar when the user is next, a worker runs, or an escalation is open", async () => { + it("leaves a steward visible when the user is next, hides it with a worker in flight, and keeps an open escalation visible", async () => { const t = await setup(); t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); await t.ring("linear", "uuid-12"); @@ -1682,29 +1704,32 @@ describe("stewards waiting on others", () => { await t.tool("steward_report", { ...waiting, actor: "me" }, steward); await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("visible"); - // One worker finishes and wakes it while another still runs. + // The worker-in-flight guard is gone: hiding does not cascade to the + // 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."); 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); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); + expect(t.threads.get("thr_w1")!.archivedAt).toBeNull(); + expect(t.threads.get("thr_w2")!.archivedAt).toBeNull(); }); - it("leaves a steward with an open escalation in the sidebar", async () => { + it("keeps a steward with an open escalation visible", async () => { const t = await setup(); t.entities.set("uuid-12", issue()); await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; await t.tool("steward_report", { phase: "Todo", summary: "Spec drafted.", nextAction: "Decide on SSO", actor: "other", escalate: { kind: "decision", question: "Include SSO?", meanwhile: "Wait." } }, steward); await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("visible"); }); - it("does not archive a turn the user started", async () => { + it("does not hide a turn the user started", async () => { const t = await setup(); t.entities.set("acme/web#7", pull()); await t.ring("github", "acme/web#7"); @@ -1712,13 +1737,13 @@ describe("stewards waiting on others", () => { await t.tool("steward_report", waiting, steward); await t.idle(steward); // The user brings it back to talk to it; its report then is theirs to read. - t.threads.get(steward)!.archivedAt = null; + t.threads.get(steward)!.visibility = "visible"; await t.tool("steward_report", waiting, steward); await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("visible"); }); - it("archives after compaction rather than during it", async () => { + it("hides after compaction rather than during it", async () => { const t = await setup(); t.entities.set("acme/web#7", pull()); await t.ring("github", "acme/web#7"); @@ -1727,13 +1752,13 @@ describe("stewards waiting on others", () => { t.usage.set(steward, 500_000); await t.idle(steward); expect(t.harness.sdk.callsTo("threads.compact")).toHaveLength(1); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("visible"); // Compaction ends in another idle. await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).not.toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); }); - it("does not archive while an idle worker's child is still running, and names the worker's question next wake (BB-11)", async () => { + it("hides even while an idle worker's child is still running, and names the worker's question next wake (BB-11)", async () => { const t = await setup(); t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); await t.ring("linear", "uuid-12"); @@ -1747,13 +1772,14 @@ describe("stewards waiting on others", () => { expect(t.hooks.store.worker("thr_w1")!.status).toBe("finished"); expect(t.threads.get("thr_r1")!.status).toBe("active"); - // The steward reports that someone else is next and ends its turn: it must - // not be archived, or bb would archive the worker and, through it, the - // reviewer. + // The steward reports that someone else is next and ends its turn: it is + // hidden, not archived, and hiding does not touch the worker or reviewer. expect((await t.tool("steward_report", { ...waiting, phase: "In Progress" }, steward)).error).toBe(false); await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); expect(t.harness.sdk.callsTo("threads.archive").map(([args]) => (args as { threadId: string }).threadId)).not.toContain(steward); + expect(t.threads.get("thr_w1")!.archivedAt).toBeNull(); + expect(t.threads.get("thr_r1")!.archivedAt).toBeNull(); // The next wake names the worker's question ahead of everything else. t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", comments: [comment({ createdAt: "2026-10-14T16:00:00Z" })] })); @@ -1779,7 +1805,8 @@ describe("stewards waiting on others", () => { await t.tool("steward_report", { ...waiting, phase: "In Progress" }, steward); await t.idle(steward); - expect(t.threads.get(steward)!.archivedAt).toBeNull(); + expect(t.threads.get(steward)!.visibility).toBe("hidden"); + expect(t.threads.get("thr_r1")!.archivedAt).toBeNull(); }); it("brings back a finished-but-archived worker whose question is surfaced, and says when the worker is gone", async () => { @@ -3672,7 +3699,7 @@ describe("ops stewards", () => { expect(healthy).toMatch(/Requeue time came: a scheduled look/u); expect(healthy).not.toMatch(/#### /u); const report = await t.tool("steward_report", { phase: "watching", summary: "All healthy.", nextAction: "Look again", actor: "other" }, ops.id); - expect(report.text).toMatch(/Your thread is archived when the turn ends/u); + expect(report.text).toMatch(/Your thread is hidden when the turn ends/u); }); it("compacts the ops steward's context before a wake that would push it over the limit, and still delivers it", async () => { @@ -4446,7 +4473,7 @@ describe("the dotenv a requester imports", () => { // context was compacted, and a worker spawned wrong must be caught here. describe("steward invariants on every turn (BB-24)", () => { const spawnLine = (over = "") => - `bb thread spawn --project p1 --lifecycle-owner-thread "$BB_THREAD_ID" --environment-provider multi-repo-workspace --machine host_on --provider claude-code --model claude-opus-5-5 --reasoning-level high${over} --title "ENG-12: " --prompt-file - <<'EOF'\n\nEOF`; + `bb thread spawn --project p1 --lifecycle-owner-thread "$BB_THREAD_ID" --section sec_1 --environment-provider multi-repo-workspace --machine host_on --provider claude-code --model claude-opus-5-5 --reasoning-level high${over} --title "ENG-12: " --prompt-file - <<'EOF'\n\nEOF`; it("prints the full runnable spawn command from the playbook's worker model and the project environment", async () => { const t = await setup(); @@ -4539,7 +4566,7 @@ describe("steward invariants on every turn (BB-24)", () => { expect(t.hooks.store.worker("thr_bad")!.status).toBe("stopped"); const wake = t.sends.at(-1)!.text; expect(wake).toMatch(/Worker thr_bad was started with the wrong provider codex instead of claude-code/u); - expect(wake).toContain(`bb thread spawn --project p1 --lifecycle-owner-thread "$BB_THREAD_ID" --environment-provider multi-repo-workspace --machine host_on --provider claude-code --model claude-opus-5-5 --reasoning-level high`); + expect(wake).toContain(`bb thread spawn --project p1 --lifecycle-owner-thread "$BB_THREAD_ID" --section sec_1 --environment-provider multi-repo-workspace --machine host_on --provider claude-code --model claude-opus-5-5 --reasoning-level high`); }); it("stops a worker on the wrong model, reasoning level or environment provider, and leaves a matching one alone", async () => { @@ -4604,3 +4631,82 @@ describe("steward invariants on every turn (BB-24)", () => { expect(stale).not.toContain("bb thread spawn --project p1"); }); }); + +// BB-39: everything a steward spawns stays in the project's section, is left +// alone by thread-briefs, and the sidebar's unread dot means "needs you". +describe("steward-spawned threads and the sidebar (BB-39)", () => { + it("files an unsectioned worker or reviewer into the owner's project section, and leaves a sectioned one alone", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + expect(t.sections).toEqual([{ id: "sec_1", name: "Acme" }]); + + // A worker with no section is filed into the project's section. + await t.created("thr_w1", steward); + expect(t.threads.get("thr_w1")!.sectionId).toBe("sec_1"); + + // A worker already in a section of its own is left there. + t.sections.push({ id: "sec_mine", name: "Mine" }); + await t.created("thr_w2", steward, "Implement", { sectionId: "sec_mine" }); + expect(t.threads.get("thr_w2")!.sectionId).toBe("sec_mine"); + + // A reviewer (a child of the worker) with no section is filed too. + await t.created("thr_r1", "thr_w1", "Review the pull request"); + expect(t.threads.get("thr_r1")!.sectionId).toBe("sec_1"); + + // A top-level worker (no parent) is recognized by its lifecycle owner. + await t.createdOwned("thr_w3", steward); + expect(t.threads.get("thr_w3")!.sectionId).toBe("sec_1"); + }); + + it("tags workers and reviewers for thread-briefs, so it never moves or archives them", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.created("thr_w1", steward); + await t.created("thr_r1", "thr_w1", "Review the pull request"); + expect(t.metadata.get("thr_w1")).toEqual({ threadBriefs: { rename: false, group: false, archive: false } }); + expect(t.metadata.get("thr_r1")).toEqual({ threadBriefs: { rename: false, group: false, archive: false } }); + }); + + it("marks a steward read after a report that needs nobody, and leaves it unread when it needs the user", async () => { + const t = await setup(); + t.entities.set("acme/web#7", pull()); + await t.ring("github", "acme/web#7"); + const steward = t.spawns[1]!.id; + const marks = () => t.harness.sdk.callsTo("threads.markRead").map(([args]) => (args as { threadId: string }).threadId); + + // Waiting on someone else, nothing for the user: read. + await t.tool("steward_report", { phase: "open", summary: "Reviewed.", nextAction: "Sam addresses the review", actor: "other", blockedOn: "sam" }, steward); + expect(marks()).toContain(steward); + + // The user is next: left unread. + const before = marks().length; + await t.tool("steward_report", { phase: "open", summary: "Reviewed.", nextAction: "You decide", actor: "me" }, steward); + expect(marks()).toHaveLength(before); + + // An escalation is open: left unread. + await t.tool("steward_report", { phase: "open", summary: "Reviewed.", nextAction: "Decide", actor: "other", escalate: { kind: "decision", question: "Include SSO?", meanwhile: "Wait." } }, steward); + expect(marks()).toHaveLength(before); + }); + + it("does not print a section id deleted by hand in the injected brief", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + const instructions = () => t.harness.inspection.registrations.instructionProvider!({ threadId: steward, projectId: "p1" })!; + expect(instructions()).toContain("--section sec_1"); + + // The user deletes the section by hand. A wake resolves it to null, and the + // synchronous brief must not fall back to the dead id in the store row. + t.sections.splice(0); + t.entities.set("uuid-12", issue({ comments: [comment({ createdAt: "2026-10-14T16:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + await t.flush(); + expect(t.hooks.store.project("p1").sectionId).toBe("sec_1"); + expect(instructions()).not.toContain("--section"); + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 327fbe5f..8e44fbe0 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -977,6 +977,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return name === "" ? "Project steward" : `${name} project steward`; } + /** + * The section id `projectSection` last resolved for a project, including a + * null when it has none. The per-turn brief is synchronous and cannot call + * `projectSection`, so it reads this instead of the store row, whose + * tombstone for a section deleted by hand still holds the dead id. + */ + const sectionCache = new Map(); + /** * The sidebar section a project's stewards are put in, named after the * project; null when there is none to use. The one this plugin made is @@ -1008,6 +1016,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.log.info(`stewards: made the sidebar section ${JSON.stringify(name)} for ${projectId} (${created.id})`); sectionId = created.id; }); + sectionCache.set(projectId, sectionId); return sectionId; } @@ -1016,7 +1025,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * is the user's doing and is left there; either way, where it sits from * then on is the user's, so a steward dragged out is never pulled back. */ - async function placeOnce(projectId: string, info: ThreadInfo): Promise { + async function placeOnce(projectId: string, info: { id: string; sectionId: string | null }): Promise { if (store.placed(info.id)) return; if (info.sectionId === null) { const sectionId = await projectSection(projectId); @@ -1061,6 +1070,41 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } + /** + * The binding a newly created thread belongs to: a worker's lifecycle owner + * or parent when that is a steward, or the steward of the worker a reviewer + * is a child of. Null for a thread this plugin does not own. Local store + * lookups only, so an unrelated thread costs nothing. + */ + function spawnedOwner(thread: { lifecycleOwnerThreadId: string | null; parentThreadId: string | null }): Binding | null { + for (const id of [thread.lifecycleOwnerThreadId, thread.parentThreadId]) { + if (id === null) continue; + const b = store.byThread(id); + if (b !== null && b.endedAt === null) return b; + const w = store.worker(id); + if (w !== null) { + const owner = store.binding(w.bindingId); + if (owner !== null && owner.endedAt === null) return owner; + } + } + return null; + } + + /** + * Whether anything on a binding needs the user: the steward said the user + * acts next, an escalation is open, a question about it is unanswered, or a + * needs item is on the Stewards page. Such a steward's row stays visible + * and unread; a "nothing to do yet" turn is neither. + */ + function needsUser(b: Binding): boolean { + return ( + b.status?.actor === "me" || + store.openEscalations(b.id).length > 0 || + store.openNeeds(b.id).length > 0 || + store.openQuestions(b.projectId).some((q) => q.bindingId === b.id) + ); + } + /** * 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 @@ -1273,6 +1317,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // compact first (criterion 4). If compaction makes the thread busy, // 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" })); const sent = await sendTo(b.threadId, text); if (sent === "gone") { // The user deleted the thread: that is a detach they meant. @@ -1299,6 +1346,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P workerQuestions, children: store.children(b.id).map((c) => ({ binding: c, openEscalations: store.openEscalations(c.id) })), workerFlags: [environmentFlags(await projectHost(b.projectId)), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "), + sectionId: await projectSection(b.projectId), changes, needs: store.openNeeds(b.id), own: ownThreads(b), @@ -2892,7 +2940,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.log.warn(`stewards: stopped worker ${thread.id}: ${problems.join(", ")}`); store.note( owner.id, - `Worker ${thread.id} was started with the wrong ${problems.join(", ")} and was stopped. Start it again with:\n ${spawnCommand({ projectId: owner.projectId, entityKey: owner.entityKey, workerFlags: flags })}`, + `Worker ${thread.id} was started with the wrong ${problems.join(", ")} and was stopped. Start it again with:\n ${spawnCommand({ projectId: owner.projectId, entityKey: owner.entityKey, workerFlags: flags, sectionId: await projectSection(owner.projectId) })}`, ); scheduleReconcile(owner.id); } @@ -2900,6 +2948,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.events.on("thread.created", async ({ thread }) => { // Stewards this plugin spawned (a promoted child under its parent) are not workers. if (thread.originPluginId === bb.pluginId) return; + // A worker (its lifecycle owner or parent is a steward) or a reviewer (a + // child of a worker) is filed into its project's section and tagged for + // thread-briefs here, whichever way the skill that spawned it built the + // command. A thread already in a section is left where it is. + const spawned = spawnedOwner(thread); + if (spawned !== null) { + await placeOnce(spawned.projectId, { id: thread.id, sectionId: thread.sectionId ?? null }); + await tagThread(thread.id, STEWARD_BRIEFS); + } 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; @@ -2976,77 +3033,28 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const compacting = await compactIfLarge(thread.id); const after = store.binding(b.id)!; if (after.pending.some((n) => n.quiet !== true)) scheduleReconcile(b.id); - // Compaction ends in another idle, which archives. - else if (after.archiveWhenIdle && !compacting) await archiveWaiting(after); + // Compaction ends in another idle, which hides. + else if (after.archiveWhenIdle && !compacting) await hideWaiting(after); }); /** - * Every thread that belongs to a worker of the binding: the workers - * themselves and, recursively, the threads they started (a worker's - * reviewer). The plugin records only the workers, so their children are - * read from bb. + * Hide a steward whose wake turn ended waiting on someone else, so the + * sidebar holds only stewards with something to do. Hidden threads stay + * 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). */ - async function workerThreads(b: Binding): Promise { - const seen = new Set(); - const queue = store.workers(b.id).map((w) => w.threadId); - while (queue.length > 0) { - const id = queue.pop()!; - if (seen.has(id)) continue; - seen.add(id); - const children = await bb.sdk.threads.list({ parentThreadId: id, archived: false, limit: 200 }); - for (const c of children) queue.push(c.id); - } - return [...seen]; - } - - /** - * Whether the binding's workers still have work. Any worker in flight - * (BB-17: from its spawn until it is stopped, failed or archived, so - * `finished` still counts) blocks the archive, and a worker whose thread - * is stopped, failed or archived may still have a running or pending - * descendant: the build-tickets loop is an idle worker with a running - * reviewer, and archiving the steward would archive the worker and, - * through it, the reviewer (BB-14). A read failure fails safe: it must not - * let the archive proceed over a possibly-running descendant. - */ - async function workersHaveWork(b: Binding): Promise { - if (anyWorkerInFlight(store.workers(b.id))) return true; - let ids: string[]; - try { - ids = await workerThreads(b); - } catch (error) { - bb.log.warn(`stewards: could not list the threads under ${b.entityKey}'s workers; not archiving: ${errorMessage(error)}`); - return true; - } - for (const id of ids) { - let info: ThreadInfo | null; - try { - info = await threadInfo(id); - } catch (error) { - bb.log.warn(`stewards: could not read worker thread ${id}; not archiving ${b.entityKey}: ${errorMessage(error)}`); - return true; - } - if (info === null || info.deletedAt !== null || info.archivedAt !== null) continue; - if (busy(info.status)) return true; - } - return false; - } - - /** - * Archive a steward whose wake turn ended waiting on someone else, so the - * sidebar holds only stewards with something to do. Its binding stays: - * the next wake brings it back (sendTo). Not while a worker still has work - * (workersHaveWork), or an escalation is open, which the user should still - * see. - */ - async function archiveWaiting(b: Binding): Promise { + async function hideWaiting(b: Binding): Promise { store.patch(b.id, { archiveWhenIdle: false }); if (b.threadId === null || b.endedAt !== null || b.ending !== null) return; - if ((await workersHaveWork(b)) || store.openEscalations(b.id).length > 0) return; + if (needsUser(b)) 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 })); - bb.log.info(`stewards: ${b.entityKey} waits on others; archived its steward until the next wake`); + await quietly(`hide ${b.entityKey}'s waiting steward`, () => bb.sdk.threads.update({ threadId: info.id, visibility: "hidden" })); + bb.log.info(`stewards: ${b.entityKey} waits on others; hid its steward until the next wake`); } /** @@ -3837,8 +3845,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } const hostId = cachedProjectHost(b.projectId); const flags = hostId === undefined ? null : [environmentFlags(hostId), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "); + const cachedSection = sectionCache.get(b.projectId); + const sectionId = cachedSection === undefined ? store.project(b.projectId).sectionId : cachedSection; return formatBrief( - { binding: b, playbook, gate: briefGate(b, playbook), workerFlags: flags, escalations: store.openEscalations(b.id), conflicts: conflictsOf(b, store.open(b.projectId)) }, + { binding: b, playbook, gate: briefGate(b, playbook), workerFlags: flags, sectionId, escalations: store.openEscalations(b.id), conflicts: conflictsOf(b, store.open(b.projectId)) }, BRIEF_MAX_CHARS, ); }); @@ -4070,7 +4080,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P at: now(), }; const moved = advanced(b.status, status); - // A wake turn that ends waiting on someone else is archived when it + // A wake turn that ends waiting on someone else is hidden when it // goes idle; a turn the user started is left where they can see it. const archiveWhenIdle = input.actor === "other" && (b.awaitingReport || b.archiveWhenIdle); b = store.patch(b.id, { @@ -4131,6 +4141,16 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const requests = [requested === null ? null : "approval", scheduling === null ? null : "scheduling"].filter((r) => r !== null); if (raised !== null && !(raised.route === "project" && requests.length > 0)) await deliver(b, raised); if (requests.length > 0) await wakeProject(b.projectId, raised !== null && raised.route === "project" ? `escalation and ${requests.join(" and ")} request from ${b.entityKey}` : `${requests.join(" and ")} requested for ${b.entityKey}`, { digestDue: false }); + // The unread dot means "needs you": a turn that ends with nothing for + // the user is marked read and hidden when it goes idle, so a "nothing + // to do yet" look does not flag the sidebar like a question does. A + // turn that does need the user is made visible and left unread. A + // 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" })); + else await quietly(`mark ${b.entityKey}'s steward read`, () => bb.sdk.threads.markRead({ threadId })); + } if (moved && b.parentBindingId !== null) { const parent = store.binding(b.parentBindingId); if (parent !== null && parent.endedAt === null) tell(threadId, parent, `Child ${b.entityKey}: ${status.summary} Next: ${status.nextAction} (${status.actor})`); @@ -4162,9 +4182,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b.followThrough === null) return `Reported.${refusalNote}${escalated} The binding ends when this turn does: running workers are stopped and the thread is archived. End the turn now.`; return `Reported.${refusalNote}${escalated} The binding stays open to follow through until ${iso(followThroughUntil!)}; running workers keep going. You will be woken when a worker finishes or something actionable changes, or in ${formatDuration(requeueMs)}. End the turn now.`; } - const archived = archiveWhenIdle && store.openEscalations(b.id).length === 0 ? " Your thread is archived when the turn ends, and comes back on that wake." : ""; + const hidden = archiveWhenIdle && !needsUser(b) ? " Your thread is hidden when the turn ends, and comes back on that wake." : ""; const recorded = opsTickets.length === 0 ? "" : ` Recorded ${opsTickets.map((t) => `${t.ticket} (${t.did})`).join(", ")} against ${opsTickets.length === 1 ? "its fingerprint" : "their fingerprints"}.`; - return `Reported.${recorded}${refusalNote}${gateNote}${escalated} You will be woken when something actionable changes, or in ${formatDuration(requeueMs)}.${archived} End the turn now.`; + return `Reported.${recorded}${refusalNote}${gateNote}${escalated} You will be woken when something actionable changes, or in ${formatDuration(requeueMs)}.${hidden} End the turn now.`; } catch (error) { return toolError(error); } @@ -5007,7 +5027,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (config === null || playbook === null) throw new PluginCliError(`No playbook for ${b.entityKey}: run bb stewards check.`, { code: "playbook_missing" }); return { exitCode: 0, - stdout: formatBrief({ binding: b, playbook, gate: briefGate(b, playbook), workerFlags: await workerFlagsFor(b, playbook), escalations: store.openEscalations(b.id), conflicts: conflictsOf(b, store.open(b.projectId)) }), + stdout: formatBrief({ binding: b, playbook, gate: briefGate(b, playbook), workerFlags: await workerFlagsFor(b, playbook), sectionId: await projectSection(b.projectId), escalations: store.openEscalations(b.id), conflicts: conflictsOf(b, store.open(b.projectId)) }), }; }, }), @@ -5022,7 +5042,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const config = await loadConfig(b.projectId); const playbook = config === null ? null : bindingPlaybook(config, b); if (config === null || playbook === null) throw new PluginCliError(`No playbook for ${b.entityKey}: run bb stewards check.`, { code: "playbook_missing" }); - return { exitCode: 0, stdout: spawnCommand({ projectId: b.projectId, entityKey: b.entityKey, workerFlags: await workerFlagsFor(b, playbook) }) }; + return { exitCode: 0, stdout: spawnCommand({ projectId: b.projectId, entityKey: b.entityKey, workerFlags: await workerFlagsFor(b, playbook), sectionId: await projectSection(b.projectId) }) }; }, }), diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index a3e64542..085946fd 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -176,8 +176,10 @@ Two tools are yours; everything else you do with the tools every thread has. brings it back. If someone moves the entity out of its terminal state before then, the ending is taken back and you carry on. - **Waiting.** Report `actor: other` only when someone else really is next. - The plugin then archives your thread after a wake turn, unless a worker - runs or an escalation is open, and the next wake brings it back. + The plugin then hides your thread after a wake turn, unless an escalation, + a question or a needs item is open; the next wake still reaches it, and a + wake that needs you makes it visible again. A report that needs nobody is + also marked read, so the sidebar's unread dot means "needs you". ## If you are an ops steward diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 30ffd6de..0de3e701 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -46,9 +46,10 @@ export const BRIEF_PREFIX = "Your context may have been compacted, and this turn may not be a wake (a plain message, a `bb thread tell`, a child notice). Run `bb stewards brief` before acting: it prints your thread id, allowed actions, phase instructions, ready gate, guidance and holds, the standing rules and the exact worker spawn command."; /** The worker spawn command, shared by the wake, `bb stewards spawn-flags` and the brief. */ -export function spawnCommand(input: { projectId: string; entityKey: string; workerFlags: string }): string { +export function spawnCommand(input: { projectId: string; entityKey: string; workerFlags: string; sectionId?: string | null }): string { + const section = input.sectionId === null || input.sectionId === undefined ? "" : ` --section ${input.sectionId}`; return [ - `bb thread spawn --project ${input.projectId} --lifecycle-owner-thread "$BB_THREAD_ID"${input.workerFlags === "" ? "" : ` ${input.workerFlags}`} --title "${input.entityKey}: " --prompt-file - <<'EOF'`, + `bb thread spawn --project ${input.projectId} --lifecycle-owner-thread "$BB_THREAD_ID"${section}${input.workerFlags === "" ? "" : ` ${input.workerFlags}`} --title "${input.entityKey}: " --prompt-file - <<'EOF'`, "", "EOF", ].join("\n"); @@ -166,6 +167,8 @@ export type WakeInput = { children: ChildView[]; /** The worker model, as `bb thread spawn` flags. */ workerFlags: string; + /** The project's sidebar section id, so a worker is spawned into it; null when there is none. */ + sectionId?: string | null; changes: string[]; /** The binding's open "needs you" items, on the Stewards page. */ needs?: Need[]; @@ -301,7 +304,7 @@ export function formatWake(input: WakeInput): string { "", "Start a worker for one bounded task with:", "", - ...spawnCommand({ projectId: binding.projectId, entityKey: e.key, workerFlags: input.workerFlags }) + ...spawnCommand({ projectId: binding.projectId, entityKey: e.key, workerFlags: input.workerFlags, sectionId: input.sectionId }) .split("\n") .map((line) => ` ${line}`), "", @@ -381,6 +384,8 @@ export type BriefInput = { gate: GateState; /** The worker spawn flags, environment first, exactly as the wake and `bb stewards spawn-flags` build them; null when the project's machine is not known yet, so the brief points at the command instead of printing one it is unsure of. */ workerFlags: string | null; + /** The project's sidebar section id, so a worker is spawned into it; null when there is none. */ + sectionId?: string | null; /** Open escalations, so the gate line can say who is being asked for approval or scheduling. */ escalations?: Escalation[]; /** Open bindings at work on the same paths, for the scheduling line. */ @@ -423,7 +428,7 @@ export function formatBrief(input: BriefInput, maxChars?: number): string { if (!ops) head.push(briefGateLine(gate, escalations)); if (!ops) { if (input.workerFlags === null) head.push("", "Run `bb stewards spawn-flags` for the exact worker spawn command: the project's machine has not been read on this server yet."); - else head.push("", "Start a worker with:", "", spawnCommand({ projectId: b.projectId, entityKey: b.entityKey, workerFlags: input.workerFlags })); + else head.push("", "Start a worker with:", "", spawnCommand({ projectId: b.projectId, entityKey: b.entityKey, workerFlags: input.workerFlags, sectionId: input.sectionId })); } const middle: string[] = []; diff --git a/plugins/thread-briefs/optout.ts b/plugins/thread-briefs/optout.ts index 99e86bd9..9724798e 100644 --- a/plugins/thread-briefs/optout.ts +++ b/plugins/thread-briefs/optout.ts @@ -12,10 +12,12 @@ * ``` * * in its own metadata namespace when it spawns the thread, and this plugin - * reads it back from `thread.originPluginId`'s namespace. bb attributes a - * thread seeded with metadata to the plugin that seeded it, so the origin is - * always the namespace to look in, and this plugin never has to know which - * plugins exist. + * reads it back from the namespace of the plugin that owns the thread. For a + * thread a plugin spawned that is `thread.originPluginId`. A worker or + * reviewer a long-lived thread spawns through the CLI has no origin plugin of + * its own, so the owning plugin is the nearest ancestor's along the + * `lifecycleOwnerThreadId` chain, and the tag still lives in that plugin's + * namespace. This plugin never has to know which plugins exist. * * Each key is an opt-out: `false` turns that behaviour off for the thread, * and anything else — absent, `true`, a typo — leaves it on. The brief itself diff --git a/plugins/thread-briefs/server.test.ts b/plugins/thread-briefs/server.test.ts index 680875c9..76d10cd6 100644 --- a/plugins/thread-briefs/server.test.ts +++ b/plugins/thread-briefs/server.test.ts @@ -811,6 +811,8 @@ describe("the auto-archive sweep", () => { threads: ReturnType[]; doneArchiveHours?: number; listPluginMetadata?: ReturnType; + /** Fail every `threads.get`, as a transient read error would. */ + getFails?: boolean; }) { globalThis.fetch = fakeCompletion(SUMMARY) as unknown as typeof globalThis.fetch; const archived: string[] = []; @@ -825,8 +827,10 @@ describe("the auto-archive sweep", () => { sdk: { threads: { list: async () => options.threads, - get: async ({ threadId }) => - options.threads.find((entry) => entry.id === threadId) ?? thread, + get: async ({ threadId }) => { + if (options.getFails === true) throw new Error("503"); + return options.threads.find((entry) => entry.id === threadId) ?? thread; + }, archive: async ({ threadId }) => { archived.push(threadId); return { id: threadId, archivedAt: Date.now() }; @@ -940,6 +944,48 @@ describe("the auto-archive sweep", () => { await harness.lifecycle.dispose(); }); + it("honours a worker's opt-out keyed on its steward's namespace", async () => { + // The worker was spawned by the CLI, not the plugin, so it has no origin + // plugin of its own: its opt-out lives in its steward's namespace and is + // found through the lifecycle-owner chain. + const { bb, harness, archived } = archiveHost({ + threads: [ + coldThread("thr_steward", 9, { originPluginId: "stewards" }), + coldThread("thr_worker", 9, { lifecycleOwnerThreadId: "thr_steward" }), + ], + listPluginMetadata: metadataFrom({ + thr_steward: { role: "steward", threadBriefs: { archive: false } }, + thr_worker: { role: "worker", threadBriefs: { archive: false } }, + }), + }); + await plugin(bb); + await seedDoneBrief(bb, "thr_steward"); + await seedDoneBrief(bb, "thr_worker"); + + await harness.behavior.runSchedule("archive-done"); + expect(archived).toEqual([]); + + await harness.lifecycle.dispose(); + }); + + it("treats a failed owner lookup as unknown, keeping a worker rather than archiving it", async () => { + // A transient `threads.get` failure while resolving the chain must not be + // cached as "no plugin": that would read as opted in and let the sweep + // archive a tagged worker, cascading to its reviewer (BB-14). + const { bb, harness, archived } = archiveHost({ + threads: [coldThread("thr_worker", 9, { lifecycleOwnerThreadId: "thr_missing" })], + listPluginMetadata: metadataFrom({}), + getFails: true, + }); + await plugin(bb); + await seedDoneBrief(bb, "thr_worker"); + + await harness.behavior.runSchedule("archive-done"); + expect(archived).toEqual([]); + + await harness.lifecycle.dispose(); + }); + it("leaves a plugin's thread alone when its metadata cannot be read", async () => { const { bb, harness, archived } = archiveHost({ threads: [ @@ -1708,6 +1754,30 @@ describe("sidebar grouping by status", () => { await harness.lifecycle.dispose(); }); + it("takes a worker keyed on its steward's namespace out of the sections", async () => { + const threads = [ + groupedThread({ id: "thr_steward", sectionId: null, originPluginId: "stewards" }), + // Spawned by the CLI, so no origin plugin of its own; filed before its + // steward's opt-out reached thread-briefs. + groupedThread({ id: "thr_worker", sectionId: "sec_3", lifecycleOwnerThreadId: "thr_steward" }), + ]; + const { bb, harness } = groupingHost({ + threads, + listPluginMetadata: metadataFrom({ + thr_steward: { role: "steward", threadBriefs: { group: false } }, + thr_worker: { role: "worker", threadBriefs: { group: false } }, + }), + }); + const done = { nextStep: "", blockedOn: "" }; + await bb.storage.kv.set("brief:thr_steward", storedBrief("thr_steward", done)); + await bb.storage.kv.set("brief:thr_worker", storedBrief("thr_worker", done)); + await plugin(bb); + + await settle(() => threads[1]!.sectionId === null); + + await harness.lifecycle.dispose(); + }); + it("files each thread by its brief's status and leaves briefless ones alone", async () => { const threads = [ groupedThread({ id: "thr_wait", sectionId: null }), @@ -1957,13 +2027,23 @@ describe("renaming threads", () => { update?: (args: { threadId: string; title?: string | null }) => void; /** The spawning plugin's namespace on the thread, when a plugin spawned it. */ originMetadata?: Record; + /** The steward that owns a CLI-spawned worker: its metadata under the stewards namespace. */ + ownerMetadata?: Record; + /** The CLI-spawned worker's own opt-out under the owning plugin's namespace. */ + workerMetadata?: Record; }) { + const ownerId = "thr_steward"; + const chain = options.ownerMetadata !== undefined; + const ownerThread = chain + ? makeThreadResponse({ id: ownerId, title: "Steward", visibility: "visible", status: "idle", originPluginId: "stewards" }) + : null; const live = makeThreadResponse({ id: "thr_1", title: options.title === undefined ? "Build me a thing that does..." : options.title, visibility: "visible", status: "idle", - originPluginId: options.originMetadata === undefined ? null : "stewards", + originPluginId: options.originMetadata === undefined && !chain ? null : "stewards", + ...(chain ? { lifecycleOwnerThreadId: ownerId } : {}), }); const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => { options.onRequest?.(); @@ -1988,6 +2068,10 @@ describe("renaming threads", () => { // Mutable, so a test can change what the plugin asks for between passes. const metadata: Record> = options.originMetadata === undefined ? {} : { thr_1: options.originMetadata }; + if (chain) { + metadata[ownerId] = options.ownerMetadata!; + if (options.workerMetadata !== undefined) metadata.thr_1 = options.workerMetadata; + } // Advanced per summary so a test can wait for *that* summary's write, // rather than seeing the previous one's brief and racing ahead. let seq = 12; @@ -2002,8 +2086,9 @@ describe("renaming threads", () => { }, sdk: { threads: { - get: async () => ({ ...live }), - list: async () => [live], + get: async ({ threadId }: { threadId: string }) => + threadId === ownerId && ownerThread !== null ? { ...ownerThread } : { ...live }, + list: async () => (ownerThread === null ? [live] : [live, ownerThread]), update: async (args) => { options.update?.(args as { threadId: string; title?: string | null }); if (typeof args.title === "string") live.title = args.title; @@ -2135,6 +2220,22 @@ describe("renaming threads", () => { await current.harness.lifecycle.dispose(); }); + it("keeps the title of a CLI-spawned worker whose steward asked to keep it", async () => { + const current = renameHost({ + title: "ENG-42: Fix the flaky test", + ownerMetadata: { role: "steward", threadBriefs: { rename: false, archive: false } }, + workerMetadata: { role: "worker", threadBriefs: { rename: false, archive: false } }, + }); + await plugin(current.bb); + await summarize(current); + + // The worker has no origin plugin of its own; the opt-out is found through + // its lifecycle owner and still keeps its title. + expect(current.live.title).toBe("ENG-42: Fix the flaky test"); + expect(current.harness.sdk.callsTo("threads.update")).toHaveLength(0); + await current.harness.lifecycle.dispose(); + }); + it("brings a stored opt-out up to date in the sweep, without a summary", async () => { // A steward idle since before its plugin asked for no ring: the sidebar // draws from the stored copy, so the sweep has to refresh it. diff --git a/plugins/thread-briefs/server.ts b/plugins/thread-briefs/server.ts index 7d60518e..29a95a1a 100644 --- a/plugins/thread-briefs/server.ts +++ b/plugins/thread-briefs/server.ts @@ -401,27 +401,93 @@ export default async function plugin(bb: BbPluginApi) { // ------------------------------------------------------------- opt-outs /** - * Each thread's opt-out, read from the namespace of the plugin that spawned - * it: see `optout.ts`. + * Thread id → the plugin that owns it, memoized across passes. A thread's + * origin plugin and its lifecycle-owner chain never change, and a hidden + * steward is absent from some batches, so caching saves a read per worker. + */ + const pluginOwner = new Map(); + + /** + * Each thread's opt-out, read from the namespace of the plugin that owns + * it: its own origin plugin, or the nearest ancestor's through the + * lifecycle-owner chain when it has none (a worker or reviewer spawned by + * the CLI). See `optout.ts`. * - * A thread no plugin spawned costs nothing. The rest are batched per - * spawning plugin, so a pass over the whole sidebar is one request per - * plugin rather than one per thread. null means that namespace could not be - * read, and each caller decides what not knowing means for it. + * A thread no plugin owns costs nothing. The rest are batched per plugin, + * so a pass over the whole sidebar is one request per plugin rather than one + * per thread. null means that namespace could not be read, and each caller + * decides what not knowing means for it. */ async function optOutsFor( - threads: readonly { id: string; originPluginId: string | null }[], + threads: readonly { + id: string; + originPluginId: string | null; + lifecycleOwnerThreadId?: string | null; + }[], ): Promise> { const result = new Map(); const byPlugin = new Map(); + // A thread's owning plugin never changes, so the answer is kept across + // passes: a hidden steward is absent from some batches, and its workers + // would otherwise be re-read every reconcile. + for (const thread of threads) { + if (thread.originPluginId !== null) pluginOwner.set(thread.id, thread.originPluginId); + } + /** + * The plugin that owns a thread: its origin plugin, or the nearest + * ancestor's through the lifecycle-owner chain. A thread spawned by the + * CLI has no origin plugin of its own, so this is how its steward's + * namespace — where the stewards plugin tags its workers and reviewers — + * is found. undefined when a read failed: the caller treats the thread as + * unknown for this pass rather than opted in, and nothing is cached. + */ + const ownerPlugin = async (threadId: string, depth = 0): Promise => { + const known = pluginOwner.get(threadId); + if (known !== undefined) return known; + if (depth > 10) return null; + let info: { originPluginId?: string | null; lifecycleOwnerThreadId?: string | null }; + try { + info = (await bb.sdk.threads.get({ threadId })) as { + originPluginId?: string | null; + lifecycleOwnerThreadId?: string | null; + }; + } catch (error) { + bb.log.warn( + `could not read thread ${threadId} to find its owning plugin: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + return undefined; + } + let found: string | null; + if (info.originPluginId != null) found = info.originPluginId; + else if (info.lifecycleOwnerThreadId == null) found = null; + else { + const inherited = await ownerPlugin(info.lifecycleOwnerThreadId, depth + 1); + if (inherited === undefined) return undefined; + found = inherited; + } + pluginOwner.set(threadId, found); + return found; + }; for (const thread of threads) { - if (thread.originPluginId === null) { + let pluginId: string | null | undefined; + if (thread.originPluginId !== null) pluginId = thread.originPluginId; + else if (thread.lifecycleOwnerThreadId == null) pluginId = null; + else pluginId = await ownerPlugin(thread.lifecycleOwnerThreadId); + if (pluginId === undefined) { + // A read failed: unknown, which every caller treats fail-safe (see + // `FULL_OPT_OUT`), rather than opted in. + result.set(thread.id, null); + continue; + } + if (pluginId === null) { result.set(thread.id, NO_OPT_OUT); continue; } - const ids = byPlugin.get(thread.originPluginId) ?? []; + const ids = byPlugin.get(pluginId) ?? []; ids.push(thread.id); - byPlugin.set(thread.originPluginId, ids); + byPlugin.set(pluginId, ids); } for (const [pluginId, ids] of byPlugin) { for (let start = 0; start < ids.length; start += METADATA_PAGE_SIZE) { @@ -748,9 +814,15 @@ export default async function plugin(bb: BbPluginApi) { * written, and the sidebar is told once. */ async function syncStoredOptOuts( - threads: readonly { id: string; originPluginId: string | null }[], + threads: readonly { + id: string; + originPluginId: string | null; + lifecycleOwnerThreadId?: string | null; + }[], ): Promise { - const fromPlugins = threads.filter((thread) => thread.originPluginId !== null); + const fromPlugins = threads.filter( + (thread) => thread.originPluginId !== null || thread.lifecycleOwnerThreadId != null, + ); if (fromPlugins.length === 0) return; let changed = 0; for (const [threadId, optOut] of await optOutsFor(fromPlugins)) { @@ -1064,9 +1136,12 @@ export default async function plugin(bb: BbPluginApi) { /** Visible, live threads, in pages, capped. */ const listGroupableThreads = async (): Promise< - (SectionedThread & { originPluginId: string | null })[] + (SectionedThread & { originPluginId: string | null; lifecycleOwnerThreadId: string | null })[] > => { - const threads: (SectionedThread & { originPluginId: string | null })[] = []; + const threads: (SectionedThread & { + originPluginId: string | null; + lifecycleOwnerThreadId: string | null; + })[] = []; for (let offset = 0; offset < SECTION_THREAD_LIMIT; offset += SECTION_PAGE_SIZE) { const page = await bb.sdk.threads.list({ limit: SECTION_PAGE_SIZE, @@ -1081,6 +1156,7 @@ export default async function plugin(bb: BbPluginApi) { id: thread.id, sectionId: thread.sectionId ?? null, originPluginId: thread.originPluginId, + lifecycleOwnerThreadId: thread.lifecycleOwnerThreadId, }); } if (page.length < SECTION_PAGE_SIZE) break;