Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions plugins/stewards/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
109 changes: 105 additions & 4 deletions plugins/stewards/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {};
Expand Down Expand Up @@ -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();
};
Expand Down Expand Up @@ -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 <answer>`, 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", () => {
Expand Down
116 changes: 112 additions & 4 deletions plugins/stewards/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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<void> {
const gate = gateState(playbook, b.ready, specHashFor(b, observed.entity));
const workerQuestions = await collectWorkerQuestions(b);
const text = formatWake({
reason,
binding: b,
Expand All @@ -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,
Expand Down Expand Up @@ -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<string[]> {
const seen = new Set<string>();
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<boolean> {
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<void> {
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<WorkerQuestion[]> {
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
Expand Down
Loading
Loading