diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index f1ada2d6..295d9354 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -265,9 +265,24 @@ plugins. (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 a worker runs or 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. + 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. - **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/server.test.ts b/plugins/stewards/server.test.ts index 1bc3f231..863f87b9 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -110,10 +110,15 @@ function world() { ...(t.hostId === undefined ? {} : { environment: { hostId: t.hostId } }), }; }, - list: async ({ sectionId, archived }: { sectionId?: string; archived?: boolean }) => + list: async ({ sectionId, archived, parentThreadId }: { sectionId?: string; archived?: boolean; parentThreadId?: string }) => [...threads.entries()] - .filter(([, t]) => (sectionId === undefined || t.sectionId === sectionId) && (archived !== false || t.archivedAt === null)) - .map(([id]) => makeThreadResponse({ id })), + .filter( + ([, t]) => + (sectionId === undefined || t.sectionId === sectionId) && + (archived !== false || t.archivedAt === null) && + (parentThreadId === undefined || (t.parentThreadId ?? null) === parentThreadId), + ) + .map(([id, t]) => makeThreadResponse({ id, status: t.status as never, archivedAt: t.archivedAt, parentThreadId: t.parentThreadId ?? null, sectionId: t.sectionId ?? null })), archive: async ({ threadId }: { threadId: string }) => { threads.get(threadId)!.archivedAt = 1; return {}; @@ -172,12 +177,14 @@ async function setup() { }; const list = async () => ((await harness.callRpc("stewardsList", { projectId: "p1", all: true })) as { bindings: Array<{ key: string; kind: string; threadId: string | null; ended: boolean; escalations: number; summary: string | null }> }).bindings; const idle = async (threadId: string, lastAssistantText: string | null = null) => { + const t = w.threads.get(threadId); + if (t !== undefined) t.status = "idle"; await harness.behavior.emitThreadEvent("thread.idle", { thread: makeThreadResponse({ id: threadId }), lastAssistantText }); await flush(); }; /** A thread a steward started with `bb thread spawn --parent-self`. */ const created = async (id: string, parent: string, title = "Implement") => { - w.threads.set(id, { status: "active", archivedAt: null }); + w.threads.set(id, { status: "active", archivedAt: null, parentThreadId: parent }); await harness.behavior.emitThreadEvent("thread.created", { thread: makeThreadResponse({ id, parentThreadId: parent, lifecycleOwnerThreadId: parent, title, originPluginId: null }) }); await flush(); }; @@ -1329,6 +1336,100 @@ describe("stewards waiting on others", () => { await t.idle(steward); expect(t.threads.get(steward)!.archivedAt).not.toBeNull(); }); + + it("does not archive 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"); + const steward = t.spawns[1]!.id; + + // The build-tickets loop: the worker ended its turn to wait, and the + // reviewer it started is still running. + await t.created("thr_w1", steward); + await t.created("thr_r1", "thr_w1", "Review the pull request"); + await t.idle("thr_w1", "The fix is pushed. Should I bring the reviewer back once it finishes?"); + 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. + 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.harness.sdk.callsTo("threads.archive").map(([args]) => (args as { threadId: string }).threadId)).not.toContain(steward); + + // 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" })] })); + await t.ring("linear", "uuid-12"); + const wake = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; + expect(wake).toMatch(/## 5\. What changed since your last turn\n\n- \*\*Worker thr_w1 asked:\*\* The fix is pushed\. Should I bring the reviewer back once it finishes\?/u); + expect(wake).toMatch(/Answer it with `bb thread tell thr_w1 `, or escalate it, before anything else\./u); + expect(wake.indexOf("Worker thr_w1 asked:")).toBeLessThan(wake.indexOf("1 new comment from Sam")); + }); + + it("does not archive over a failed worker's still-running child (criterion 1)", 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 the pull request"); + await t.idle("thr_w1", "Pushed the fix."); + // The worker failed, so it is not in flight (BB-17), but its reviewer still runs. + await t.harness.behavior.emitThreadEvent("thread.failed", { thread: makeThreadResponse({ id: "thr_w1" }), error: "provider error" }); + await t.flush(); + expect(t.hooks.store.worker("thr_w1")!.status).toBe("failed"); + + await t.tool("steward_report", { ...waiting, phase: "In Progress" }, steward); + await t.idle(steward); + expect(t.threads.get(steward)!.archivedAt).toBeNull(); + }); + + it("brings back a finished-but-archived worker whose question is surfaced, and says when the worker is gone", 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", "Done. Should I open the follow-up ticket?"); + + // Something archived the worker since it asked (a user tidying the + // sidebar, or the cascade from a manually archived steward): bb flips its + // record to stopped through the thread.archived event. The wake must still + // bring it back so the steward's `bb thread tell` can reach it. + t.threads.get("thr_w1")!.archivedAt = 1; + await t.harness.behavior.emitThreadEvent("thread.archived", { thread: makeThreadResponse({ id: "thr_w1" }) }); + await t.flush(); + expect(t.hooks.store.worker("thr_w1")!.status).toBe("stopped"); + 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("thr_w1")!.archivedAt).toBeNull(); + expect(t.hooks.store.worker("thr_w1")!.status).toBe("finished"); + const revived = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; + expect(revived).toMatch(/Worker thr_w1 asked:\*\* Done\. Should I open the follow-up ticket\?/u); + expect(revived).toMatch(/had been archived and is back now/u); + + // A worker stopped on purpose, with its thread still there, is left alone: + // its question is not waiting on an answer. + await t.created("thr_w2", steward); + await t.idle("thr_w2", "Should I file a follow-up?"); + t.hooks.store.setWorker("thr_w2", "stopped", "Should I file a follow-up?"); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", comments: [comment({ createdAt: "2026-10-14T17:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + const purposeful = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; + expect(purposeful).not.toContain("thr_w2 asked"); + expect(t.threads.get("thr_w2")!.archivedAt).toBeNull(); + + // A worker whose thread is gone is reported as gone, needing a fresh one. + t.threads.delete("thr_w1"); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", comments: [comment({ createdAt: "2026-10-14T18:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + const gone = t.sends.filter((s) => s.threadId === steward).at(-1)!.text; + expect(gone).toMatch(/Worker thr_w1 asked:\*\* Done\. Should I open the follow-up ticket\?/u); + expect(gone).toMatch(/Its thread is gone/u); + expect(gone).toMatch(/start a fresh worker/u); + }); }); describe("passes", () => { diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index e709c1d3..2a3bf9ec 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -50,7 +50,7 @@ import { } from "./source-contract.js"; import { ACTORS, MIGRATIONS, createStore, type Binding, type Escalation, type EscalationRoute, type Observed, type Question, type ReadyState, type Store } from "./store.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; -import { PROJECT_STEWARD_INTRO, formatProjectWake, formatWake, type DigestRecords, type WakeReason } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, formatProjectWake, formatWake, workerQuestion, type DigestRecords, type WakeReason, type WorkerQuestion } from "./wake.js"; export const MULTI_REPO_PLUGIN_ID = "multi-repo"; /** multi-repo's environment provider: where every thread of a stewards project works. */ @@ -860,6 +860,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 { const gate = gateState(playbook, b.ready, specHashFor(b, observed.entity)); + const workerQuestions = await collectWorkerQuestions(b); const text = formatWake({ reason, binding: b, @@ -869,6 +870,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P escalations: store.openEscalations(b.id), routedToMe: routedTo(b), workers: store.workers(b.id), + 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(" "), changes, @@ -1482,22 +1484,128 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P else if (after.archiveWhenIdle && !compacting) await archiveWaiting(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. + */ + 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 runs or an - * escalation is open, which the user should still see. + * 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 { store.patch(b.id, { archiveWhenIdle: false }); if (b.threadId === null || b.endedAt !== null || b.ending !== null) return; - if (anyWorkerInFlight(store.workers(b.id)) || store.openEscalations(b.id).length > 0) return; + if ((await workersHaveWork(b)) || store.openEscalations(b.id).length > 0) return; const info = await threadInfo(b.threadId).catch(() => null); if (info === null || info.deletedAt !== null || info.archivedAt !== null || busy(info.status)) return; await quietly(`archive ${b.entityKey}'s waiting steward`, () => bb.sdk.threads.archive({ threadId: info.id })); bb.log.info(`stewards: ${b.entityKey} waits on others; archived its steward until the next wake`); } + /** + * The questions the binding's workers ended their last turn with. A + * finished-but-archived worker is brought back so the steward's + * `bb thread tell` can reach it; one whose thread is gone is reported as + * gone, needing a fresh worker (BB-14). + * + * The plugin cannot catch the tell itself: bb rejects a message to an + * archived thread (409) before the `message.dispatch` hook runs, so the + * worker is brought back here, when its question is surfaced, instead. A + * lookup that fails for any reason but not-found is treated as live: + * claiming a live worker is gone would tell the steward to spawn a + * duplicate, while a tell to a really-gone thread just fails. + * + * An archived worker is surfaced even though BB-17's `thread.archived` + * handler has already flipped its record from `finished` to `stopped`: + * archiving is exactly the case that needs reviving, and reviving restores + * the record to `finished` so the question stays visible until answered. + * A worker stopped on purpose, with its thread still there, is not. + */ + async function collectWorkerQuestions(b: Binding): Promise { + const out: WorkerQuestion[] = []; + for (const w of store.workers(b.id)) { + if (w.status === "running" || w.status === "failed") continue; + const question = workerQuestion(w.result); + if (question === null) continue; + let info: ThreadInfo | null; + try { + info = await threadInfo(w.threadId); + } catch (error) { + if (w.status !== "finished") continue; + bb.log.warn(`stewards: could not read worker thread ${w.threadId}; treating it as live: ${errorMessage(error)}`); + out.push({ threadId: w.threadId, question, state: "live" }); + continue; + } + const gone = info === null || info.deletedAt !== null; + const archived = info !== null && info.deletedAt === null && info.archivedAt !== null; + // A worker stopped on purpose, with its thread still there, is done. + if (w.status === "stopped" && !archived && !gone) continue; + if (archived) { + await quietly(`unarchive worker ${w.threadId}`, () => bb.sdk.threads.unarchive({ threadId: w.threadId })); + store.setWorker(w.threadId, "finished", w.result); + out.push({ threadId: w.threadId, question, state: "revived" }); + continue; + } + if (gone) { + out.push({ threadId: w.threadId, question, state: "gone" }); + continue; + } + out.push({ threadId: w.threadId, question, state: "live" }); + } + return out; + } + /** * Compact a steward's context once it has grown past the setting, or once * a wake about to be sent would push it over (criterion 4), while it is diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index c3ab88de..590b2936 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -5,7 +5,7 @@ import { issue } from "./fixtures.js"; import { gateState } from "./reconcile.js"; import { MIGRATIONS, createStore } from "./store.js"; import { LINEAR_TICKETS } from "./templates.js"; -import { formatProjectWake, formatWake, type DigestRecords, type WakeInput } from "./wake.js"; +import { formatProjectWake, formatWake, workerQuestion, type DigestRecords, type WakeInput } from "./wake.js"; const T = Date.parse("2026-10-18T05:00:00Z"); const DAY = 86_400_000; @@ -35,6 +35,7 @@ function wakeInput(over: Partial = {}): WakeInput { escalations: [], routedToMe: [], workers: [], + workerQuestions: [], children: [], workerFlags: "--provider claude-code --model claude-opus-5-5 --reasoning-level high", changes: [], @@ -73,6 +74,27 @@ describe("a steward's wake", () => { expect(wake.split(note)).toHaveLength(3); expect(wake).toContain("counts like a missed report toward `stuck`"); }); + + it("takes a worker's closing question, but not one it resolved later in the message", () => { + expect(workerQuestion("Pushed the fix.\nShould I bring the reviewer back?")).toBe("Should I bring the reviewer back?"); + // A question buried above the last few lines is not what the message ended with. + expect(workerQuestion("Should I open a follow-up?\nNever mind, I did it.\nPushed.\nDone and verified.")).toBeNull(); + expect(workerQuestion("No question here.")).toBeNull(); + expect(workerQuestion(null)).toBeNull(); + }); + + it("names a worker's question ahead of every other change, with how to answer", () => { + const wake = formatWake( + wakeInput({ + workers: [{ threadId: "thr_w1", bindingId: "b1", title: "Implement", status: "finished", result: "Should I bring the reviewer back?", startedAt: T, endedAt: T }], + workerQuestions: [{ threadId: "thr_w1", question: "Should I bring the reviewer back?", state: "live" }], + changes: ["1 new comment from Sam"], + }), + ); + expect(wake).toContain("- **Worker thr_w1 asked:** Should I bring the reviewer back?"); + expect(wake).toContain("Answer it with `bb thread tell thr_w1 `, or escalate it, before anything else."); + expect(wake.indexOf("Worker thr_w1 asked:")).toBeLessThan(wake.indexOf("1 new comment from Sam")); + }); }); describe("the nightly prompt", () => { diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index b2447e08..2d5ad6cf 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -36,6 +36,35 @@ const RESULT_CHARS = 1500; const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max)}\n… (${text.length - max} more characters)`); const quote = (text: string) => text.split("\n").map((l) => `> ${l}`).join("\n"); const iso = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/u, "Z"); +const oneLine = (text: string, max = 400) => { + const flat = text.replace(/\s+/gu, " ").trim(); + return flat.length <= max ? flat : `${flat.slice(0, max)}…`; +}; + +/** + * The question a worker's final message ended with, or null when it asked + * nothing. The last line that asks is the one the steward must answer; the + * whole message is already quoted in the snapshot. Only the last few lines are + * scanned, so a question raised earlier in a long message and left behind is + * not surfaced as open. + */ +export function workerQuestion(result: string | null): string | null { + if (result === null) return null; + const lines = result.split("\n").map((l) => l.trim()).filter((l) => l !== ""); + const from = Math.max(0, lines.length - 3); + for (let i = lines.length - 1; i >= from; i--) { + if (lines[i]!.includes("?")) return oneLine(lines[i]!); + } + return null; +} + +/** One worker's question, first under What changed, with how to answer it. */ +function workerQuestionLines(q: WorkerQuestion): string[] { + const asked = `- **Worker ${q.threadId} asked:** ${q.question}`; + if (q.state === "gone") return [asked, ` Its thread is gone, so \`bb thread tell\` cannot reach it: start a fresh worker to answer it, before anything else.`]; + if (q.state === "revived") return [asked, ` It had been archived and is back now: answer it with \`bb thread tell ${q.threadId} \`, or escalate it, before anything else.`]; + return [asked, ` Answer it with \`bb thread tell ${q.threadId} \`, or escalate it, before anything else.`]; +} /** * Join a message's three parts within WAKE_MAX_CHARS, cutting the middle @@ -89,6 +118,9 @@ function lifecycleInstructions(input: WakeInput): string | undefined { export type ChildView = { binding: Binding; openEscalations: Escalation[] }; +/** A worker's final message that asked something, to answer before anything else. */ +export type WorkerQuestion = { threadId: string; question: string; state: "live" | "revived" | "gone" }; + export type WakeInput = { reason: WakeReason; binding: Binding; @@ -99,6 +131,8 @@ export type WakeInput = { escalations: Escalation[]; routedToMe: Array<{ escalation: Escalation; from: Binding }>; workers: Worker[]; + /** Questions workers ended their last turn with; rendered ahead of other changes. */ + workerQuestions: WorkerQuestion[]; children: ChildView[]; /** The worker model, as `bb thread spawn` flags. */ workerFlags: string; @@ -250,7 +284,8 @@ export function formatWake(input: WakeInput): string { const snapshot = out.splice(0); out.push("", "## 5. What changed since your last turn", ""); - if (input.changes.length === 0) out.push("Nothing actionable; this is a scheduled look."); + for (const q of input.workerQuestions) out.push(...workerQuestionLines(q)); + if (input.changes.length === 0 && input.workerQuestions.length === 0) out.push("Nothing actionable; this is a scheduled look."); for (const c of input.changes) out.push(`- ${c}`); out.push( @@ -345,10 +380,6 @@ export function formatProjectWake(input: { /** The calendar date of a moment in a time zone, so "asked" and "since" match the user's day. */ const dayIn = (timeZone: string) => (ms: number) => localParts(ms, timeZone).date; -const oneLine = (text: string, max = 400) => { - const flat = text.replace(/\s+/gu, " ").trim(); - return flat.length <= max ? flat : `${flat.slice(0, max)}…`; -}; const PREVIOUS_DIGEST_CHARS = 6000; const RECORD_LINES = 50;