diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 17676547..030799cf 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -164,6 +164,18 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. rather than being hidden or archived: it stays addressable, so a later wake reaches it, and its finished workers and their reviewers stay visible with it. Binding end still archives. +- **A steward whose environment is gone.** If a wake cannot be delivered — + the thread's environment is `destroyed` at wake time, or bb refuses the + send with `thread_environment_unavailable` — the plugin spawns a fresh + steward on the project steward's environment, re-points the binding, + archives the old thread (never deletes, so the binding is not marked + manually detached), and delivers the wake as the new thread's first + prompt. The respawn is logged and noted on the binding. An operator can + re-point a binding by hand with `bb stewards rebind + [--project ]`, for example at a fork of the dead thread kept with + `bb thread fork --environment `: it refuses a thread in + another project, a deleted thread, a live binding's steward or a worker, + sends the wake at once, and archives the previous thread. - **Finished workers and reviewers.** A worker whose turn ends is marked `finished`; once the reconcile that consumed its report has woken the steward, its thread is archived, so the sidebar keeps only work in flight. diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index b7759bca..64ab423f 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -34,7 +34,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(); /** Every `threads.delete` the plugin asked for; the plugin must only ever archive. */ const deletes: string[] = []; const writes: Array<{ path: string; hostId?: string }> = []; @@ -175,6 +175,8 @@ function world() { return makeThreadResponse({ id }); }, send: async (args: { threadId: string; input: Array<{ text: string }> }) => { + const t = threads.get(args.threadId); + if (t?.sendError !== undefined) throw Object.assign(new Error(t.sendError.message), { code: t.sendError.code, status: t.sendError.status }); sends.push({ threadId: args.threadId, text: args.input.map((i) => i.text).join("") }); return {}; }, @@ -182,8 +184,8 @@ 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, visibility: (t.visibility ?? "visible") as never, environmentId: "env1", providerId: t.providerId ?? "claude-code", parentThreadId: t.parentThreadId ?? null, parentNotifications: (t.parentNotifications ?? "auto") as never, sectionId: t.sectionId ?? null }), - ...(t.hostId === undefined && t.environmentProviderId === undefined ? {} : { environment: { hostId: t.hostId ?? null, environmentProviderId: t.environmentProviderId ?? null, branchName: t.branchName ?? null } }), + ...makeThreadResponse({ id: threadId, title: t.title ?? null, status: t.status as never, archivedAt: t.archivedAt, visibility: (t.visibility ?? "visible") as never, projectId: t.projectId ?? "p1", environmentId: "env1", providerId: t.providerId ?? "claude-code", parentThreadId: t.parentThreadId ?? null, parentNotifications: (t.parentNotifications ?? "auto") as never, sectionId: t.sectionId ?? null }), + ...(t.hostId === undefined && t.environmentProviderId === undefined && t.environmentStatus === undefined && t.environmentPhase === undefined ? {} : { environment: { hostId: t.hostId ?? null, environmentProviderId: t.environmentProviderId ?? null, branchName: t.branchName ?? null, status: t.environmentStatus ?? "ready", lifecycle: { phase: t.environmentPhase ?? "active" } } }), }; }, // What the server answers: the thread's own execution once a turn ran, and before that the @@ -1331,6 +1333,99 @@ describe("a Linear ticket steward", () => { }); }); +describe("recovering a steward whose environment is gone (BB-103)", () => { + it("respawns the steward and re-points the binding when the wake send reports the environment unavailable", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const [project, steward] = t.spawns.map((x) => x.id); + // The steward's environment is gone: bb refuses the next wake with 409 + // thread_environment_unavailable, as it did for the eight stuck stewards. + t.threads.get(steward!)!.sendError = { code: "thread_environment_unavailable", status: 409, message: "Thread environment is unavailable" }; + // A new comment makes the next reconcile wake the steward. + t.entities.set("uuid-12", issue({ comments: [comment({ createdAt: "2026-10-14T16:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + + // A fresh steward was spawned on the project steward's environment... + expect(t.spawns).toHaveLength(3); + const respawned = t.spawns[2]!; + expect(respawned).toMatchObject({ environment: { type: "reuse", environmentId: "env1" }, parentThreadId: project, parentNotifications: "off" }); + // ...with the wake as its first prompt, saying it was respawned... + expect(String(respawned.prompt)).toMatch(/This steward was respawned/u); + expect(String(respawned.prompt)).toMatch(/1 new comment from Sam/u); + // ...the old thread archived, never deleted... + expect(t.deletes).toEqual([]); + expect(t.threads.get(steward!)!.archivedAt).not.toBeNull(); + // ...and the binding re-pointed, with the wait open until the new thread has the wake. + const b = t.hooks.store.find("ENG-12", "p1")!; + expect(b.threadId).toBe(respawned.id); + expect(b.awaitingReport).toBe(true); + // The respawn is noted on the binding so the next report says so. + expect(b.pending.some((n) => /respawned/u.test(n.text))).toBe(true); + }); + + it("respawns the steward when its environment is destroyed at wake time", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const [project, steward] = t.spawns.map((x) => x.id); + // The environment is already destroyed before the wake is even sent: no + // send error is needed for the recovery to fire. + t.threads.get(steward!)!.environmentStatus = "destroyed"; + t.entities.set("uuid-12", issue({ comments: [comment({ createdAt: "2026-10-14T16:00:00Z" })] })); + await t.ring("linear", "uuid-12"); + + expect(t.spawns).toHaveLength(3); + const respawned = t.spawns[2]!; + expect(respawned).toMatchObject({ environment: { type: "reuse", environmentId: "env1" }, parentThreadId: project, parentNotifications: "off" }); + expect(String(respawned.prompt)).toMatch(/its environment is destroyed/u); + expect(t.deletes).toEqual([]); + expect(t.threads.get(steward!)!.archivedAt).not.toBeNull(); + const b = t.hooks.store.find("ENG-12", "p1")!; + expect(b.threadId).toBe(respawned.id); + expect(b.awaitingReport).toBe(true); + expect(b.pending.some((n) => /respawned/u.test(n.text))).toBe(true); + }); + + it("a review binding's rebind refuses a thread that is already another binding's steward", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + t.entities.set("acme/web#7", pull()); + await t.ring("linear", "uuid-12"); + await t.ring("github", "acme/web#7"); + expect(await t.list()).toEqual(expect.arrayContaining([expect.objectContaining({ key: "ENG-12", kind: "ticket" }), expect.objectContaining({ key: "acme/web#7", kind: "review" })])); + const ticketSteward = t.hooks.store.find("ENG-12", "p1")!.threadId!; + const out = await t.harness.behavior.runCli(["rebind", "acme/web#7", ticketSteward]); + expect(out.exitCode).toBe(1); + expect(out.stderr).toMatch(/already ENG-12's steward/u); + // The review binding still points at its own steward. + expect(t.hooks.store.find("acme/web#7", "p1")!.threadId).not.toBe(ticketSteward); + }); + + it("rebind re-points the binding, archives the old thread, and sends the wake at once", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.hooks.store.find("ENG-12", "p1")!.threadId!; + // A fork of the dead thread, kept with `bb thread fork`, in the same project. + t.threads.set("thr_fork", { status: "idle", archivedAt: null, projectId: "p1" }); + t.hooks.store.patch(t.hooks.store.find("ENG-12", "p1")!.id, { awaitingReport: true }); + const before = t.sends.length; + const out = await t.harness.behavior.runCli(["rebind", "ENG-12", "thr_fork"]); + expect(out).toMatchObject({ exitCode: 0 }); + const b = t.hooks.store.find("ENG-12", "p1")!; + expect(b.threadId).toBe("thr_fork"); + // The wake went to the fork at once, and it carries the rebind in the action log. + expect(t.sends.length).toBeGreaterThan(before); + expect(t.sends.at(-1)).toMatchObject({ threadId: "thr_fork" }); + expect(t.sends.at(-1)!.text).toMatch(/Rebound from/u); + expect(b.awaitingReport).toBe(true); + // The old thread is archived through the plugin, never deleted. + expect(t.threads.get(steward)!.archivedAt).not.toBeNull(); + expect(t.deletes).toEqual([]); + }); +}); + // HUB-195/196: two escalations seconds apart, and the second prompt listed // the first as if new. HUB-183: a retried steward_update recorded its answer // twice, and the escalation kept "The binding ended." instead. diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 66d9eef2..f94e3a7f 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -1320,11 +1320,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // ---- threads ---------------------------------------------------------------------------- - type ThreadInfo = { id: string; title: string | null; status: string; archivedAt: number | null; deletedAt: number | null; visibility: string | null; environmentId: string | null; environmentHostId: string | null; providerId: string; parentThreadId: string | null; parentNotifications: string; sectionId: string | null }; + type ThreadInfo = { id: string; title: string | null; status: string; archivedAt: number | null; deletedAt: number | null; visibility: string | null; projectId: string | null; environmentId: string | null; environmentHostId: string | null; environmentStatus: string | null; environmentPhase: string | null; providerId: string; parentThreadId: string | null; parentNotifications: string; sectionId: string | null }; async function threadInfo(threadId: string): Promise { try { - const t = (await bb.sdk.threads.get({ threadId })) as unknown as Partial & { environment?: { hostId?: string | null } | null }; + const t = (await bb.sdk.threads.get({ threadId, include: "environment" })) as unknown as Partial & { environment?: { hostId?: string | null; status?: string | null; lifecycle?: { phase?: string | null } | null } | null }; return { id: threadId, title: t.title ?? null, @@ -1332,9 +1332,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P archivedAt: t.archivedAt ?? null, deletedAt: t.deletedAt ?? null, visibility: t.visibility === undefined ? null : String(t.visibility), + projectId: t.projectId ?? null, environmentId: t.environmentId ?? null, - // The SDK's thread carries its machine on `environment`, not at the top level. + // The SDK's thread carries its machine and environment state on + // `environment`, not at the top level. environmentHostId: t.environment?.hostId ?? t.environmentHostId ?? null, + environmentStatus: t.environment?.status ?? t.environmentStatus ?? null, + environmentPhase: t.environment?.lifecycle?.phase ?? t.environmentPhase ?? null, providerId: String(t.providerId ?? ""), parentThreadId: t.parentThreadId ?? null, parentNotifications: String(t.parentNotifications ?? "auto"), @@ -1349,14 +1353,25 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const busy = (status: string) => status === "active" || status === "starting" || status === "pending" || status === "stopping"; - /** Message a thread; "gone" when it no longer exists. */ - async function send(threadId: string, text: string): Promise<"sent" | "gone" | "failed"> { + /** True when a thread's environment was destroyed, so it can no longer run the thread. */ + const environmentGone = (info: Pick): boolean => info.environmentStatus === "destroyed" || info.environmentPhase === "destroyed"; + + /** True when an error is bb's `thread_environment_unavailable`: the thread's environment cannot run it. */ + function isEnvironmentUnavailable(error: unknown): boolean { + const e = error as { code?: string; message?: unknown }; + if (e.code === "thread_environment_unavailable") return true; + return typeof e.message === "string" && /environment is unavailable/iu.test(e.message); + } + + /** Message a thread; "gone" when it no longer exists, "unavailable" when its environment cannot run it. */ + async function send(threadId: string, text: string): Promise<"sent" | "gone" | "failed" | "unavailable"> { try { await bb.sdk.threads.send({ threadId, input: [{ type: "text", text, mentions: [] }], mode: "auto" }); return "sent"; } catch (error) { const e = error as { code?: string; status?: number }; if (e.code === "NOT_FOUND" || e.status === 404 || e.status === 410) return "gone"; + if (isEnvironmentUnavailable(error)) return "unavailable"; bb.log.warn(`stewards: could not message thread ${threadId}: ${errorMessage(error)}`); return "failed"; } @@ -1367,7 +1382,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * waited. A function for the text is called just before the send, after * those awaits, so it reads the store as of the send. */ - async function sendTo(threadId: string, text: string | (() => string)): Promise<"sent" | "gone" | "failed"> { + async function sendTo(threadId: string, text: string | (() => string)): Promise<"sent" | "gone" | "failed" | "unavailable"> { const info = await threadInfo(threadId).catch(() => null); if (info === null || info.deletedAt !== null) return "gone"; if (info.archivedAt !== null) await quietly(`unarchive ${threadId}`, () => bb.sdk.threads.unarchive({ threadId })); @@ -1952,11 +1967,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return store.children(b.id).flatMap((child) => store.openEscalations(child.id).filter((x) => x.route === "parent").map((escalation) => ({ escalation, from: child }))); } + /** A delivered wake, and the respawn the recovery path made, when it made one (BB-103). */ + type WakeDelivery = false | { delivered: true; respawned: { from: string | null; to: string } | null }; + /** Send a wake, spawning the steward's thread on the first; false when nothing was delivered. */ - async function deliverWake(b: Binding, config: ProjectConfig, playbook: Playbook, text: string): Promise { + async function deliverWake(b: Binding, config: ProjectConfig, playbook: Playbook, text: string): Promise { if (b.threadId === null) { await spawnSteward(b, config, playbook, text); - return true; + return { delivered: true, respawned: null }; + } + // A thread whose environment was destroyed at wake time cannot run the + // wake. Respawn it rather than detach: the binding is not the user's to + // end, and `bb thread restore-environment` has no multi-repo restore. + const info = await threadInfo(b.threadId).catch(() => null); + if (info !== null && info.deletedAt === null && environmentGone(info)) { + return respawnSteward(b, config, playbook, text, `its environment is ${info.environmentStatus ?? info.environmentPhase ?? "destroyed"}`); } // A wake can be the thing that pushes the transcript over the limit; // compact first (criterion 4). If compaction makes the thread busy, @@ -1969,7 +1994,43 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P pushInterest(); return false; } - return sent === "sent"; + if (sent === "unavailable") { + // bb refused the message because the thread's environment cannot run + // it: recover the steward on a live environment (BB-103). + return respawnSteward(b, config, playbook, text, "the thread's environment is unavailable"); + } + return sent === "sent" ? { delivered: true, respawned: null } : false; + } + + /** + * A steward whose environment is gone is respawned on the project + * steward's environment (the `spawnSteward` path): the old thread is + * archived, never deleted, so `thread.deleted` never marks the binding + * manually detached; the binding is re-pointed; and the wake becomes the + * new thread's first prompt. The caller notes the respawn on the binding + * after it clears the delivered notes, so the next report says so. + */ + async function respawnSteward(b: Binding, config: ProjectConfig, playbook: Playbook, text: string, why: string): Promise { + const from = b.threadId; + const respawned = `${text}\n\n## This steward was respawned\n\nYour previous thread${from === null ? "" : ` (${from})`} could not be woken because ${why}. This is a fresh thread on the project steward's environment, and the binding now points here.`; + let to: string | null; + try { + to = await spawnSteward(b, config, playbook, respawned); + } catch (error) { + bb.log.warn(`stewards: could not respawn ${b.entityKey}'s steward: ${errorMessage(error)}`); + return false; + } + if (to === null || to === "") return false; + if (from !== null && from !== to) await quietly(`archive the unreachable steward thread ${from}`, () => bb.sdk.threads.archive({ threadId: from })); + bb.log.warn(`stewards: ${b.entityKey}'s steward ${from ?? "(none)"} could not be woken (${why}); respawned as ${to}`); + pushInterest(); + return { delivered: true, respawned: { from, to } }; + } + + /** Queue the respawn after the caller clears the delivered notes, so the next report names it. */ + function noteRespawn(b: Binding, respawned: { from: string | null; to: string } | null): void { + if (respawned === null) return; + store.note(b.id, `The steward was respawned from ${respawned.from ?? "(none)"} to ${respawned.to}: its environment could not deliver the wake.`); } /** Wake the steward, spawning its thread on the first wake. */ @@ -1999,7 +2060,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P lessons: store.lessonsByTier(b.projectId, "trial").slice(0, config.file.lessons.trial.max), now: now(), }); - if (!(await deliverWake(b, config, playbook, text))) return false; + const delivery = await deliverWake(b, config, playbook, text); + if (delivery === false) return false; const cursor = newestCommentAt(observed); const deployDeadline = deploymentDeadline(b.deployments); store.patch(b.id, { @@ -2013,6 +2075,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // deployment's timeout, so the no-deployment wake is not missed. requeueAt: deployDeadline === null ? now() + playbook.requeueDefaultMs : Math.min(now() + playbook.requeueDefaultMs, deployDeadline), }); + noteRespawn(b, delivery.respawned); return true; } @@ -2581,8 +2644,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P escalations: store.openEscalations(b.id), changes: [...new Set(changes.map((c) => c.text))], }); - if (!(await deliverWake(b, config, playbook, text))) return; + const delivery = await deliverWake(b, config, playbook, text); + if (delivery === false) return; store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); + noteRespawn(b, delivery.respawned); // The steward now has the workers' reports: archive the finished ones (BB-47). await archiveFinishedWorkers(store.binding(b.id) ?? b); } @@ -2637,8 +2702,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P escalations: store.openEscalations(b.id), changes: [...new Set(changes.map((c) => c.text))], }); - if (!(await deliverWake(b, config, playbook, text))) return; + const delivery = await deliverWake(b, config, playbook, text); + if (delivery === false) return; store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); + noteRespawn(b, delivery.respawned); // The steward now has the workers' reports: archive the finished ones (BB-47). await archiveFinishedWorkers(store.binding(b.id) ?? b); } @@ -2829,8 +2896,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P escalations: store.openEscalations(b.id), changes: [...new Set(changes.map((c) => c.text))], }); - if (!(await deliverWake(b, config, playbook, text))) return; + const delivery = await deliverWake(b, config, playbook, text); + if (delivery === false) return; store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); + noteRespawn(b, delivery.respawned); // The steward now has the workers' reports: archive the finished ones (BB-47). await archiveFinishedWorkers(store.binding(b.id) ?? b); } @@ -4692,7 +4761,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const bound = store.byEntity("linear", w.issue.id); if (bound !== null && bound.endedAt === null && bound.threadId !== null && bound.kind === "ticket") { const config = await loadConfig(bound.projectId); - const sent = { outcome: "failed" as "sent" | "gone" | "failed" }; + const sent = { outcome: "failed" as "sent" | "gone" | "failed" | "unavailable" }; await serial(`b:${bound.id}`, async () => { const b = store.binding(bound.id); if (b === null || b.endedAt !== null || b.threadId === null) return; @@ -4708,6 +4777,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.log.info(`stewards: an @bb mention on ${w.issue.key} went to its steward${confirmed === null ? "" : ` (confirmed ${confirmed.id})`}`); return { routed: "ticket", threadId: bound.threadId, projectId: bound.projectId, requestId: confirmed?.id ?? null }; } + // An "unavailable" environment is deliberately left to the + // binding's next wake: the mention is not lost (the project steward + // answers it), and the requeue or doorbell respawns the steward + // through deliverWake (BB-103). Respawning from here would need the + // binding's config and a fresh wake text anyway. bb.log.warn(`stewards: could not reach ${w.issue.key}'s steward with an @bb mention; trying the project steward`); } @@ -7302,6 +7376,66 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }, }), + rebind: cliCommand({ + summary: "Point a binding at another steward thread, for operator recovery", + description: + "Re-points a live binding at another thread (for example a fork of its dead thread, kept with `bb thread fork --environment `), sends the binding's wake to it at once, and archives the previous thread. It never deletes a thread, so the binding is not marked manually detached. It refuses a thread in another project, a deleted thread, or one that is already another binding's steward or a worker.", + positionals: [ + { name: "key", description: "The entity key or binding id", required: true }, + { name: "thread", description: "The thread that should steward the binding", required: true }, + ], + options: { project: PROJECT_OPTION }, + async run(input, ctx) { + const b = bindingOrThrow(input.positionals.key, input.options.project ?? ctx.projectId); + if (b.endedAt !== null) throw new PluginCliError(`${b.entityKey} has ended (${b.endReason}); rebind is for a live binding.`, { code: "binding_ended", hint: "bb stewards list --all shows ended bindings." }); + const threadId = input.positionals.thread.trim(); + if (threadId === "") throw new PluginCliError("No thread: pass the thread id to rebind to.", { code: "no_thread" }); + const info = await threadInfo(threadId).catch(() => null); + if (info === null || info.deletedAt !== null) throw new PluginCliError(`Thread ${threadId} does not exist.`, { code: "thread_not_found", hint: "bb thread list shows the threads." }); + if (info.projectId !== null && info.projectId !== b.projectId) throw new PluginCliError(`Thread ${threadId} is in project ${info.projectId}, not ${b.projectId}.`, { code: "thread_other_project" }); + // An ended binding's old thread is nobody's steward any more, so it + // may be re-used; a live binding's thread may not. + const other = store.byThread(threadId); + if (other !== null && other.id !== b.id && other.endedAt === null) throw new PluginCliError(`Thread ${threadId} is already ${other.entityKey}'s steward.`, { code: "thread_taken", hint: `bb stewards show ${other.entityKey} shows it.` }); + const worker = store.worker(threadId); + if (worker !== null) throw new PluginCliError(`Thread ${threadId} is a worker of ${store.binding(worker.bindingId)?.entityKey ?? worker.bindingId}.`, { code: "thread_worker" }); + const projectSteward = store.projectByThread(threadId); + if (projectSteward !== null) throw new PluginCliError(`Thread ${threadId} is the project steward of ${projectSteward.projectId}, not a binding's steward.`, { code: "thread_project_steward" }); + const result = { outcome: "sent" as "sent" | "queued" | "missing" | "gone" }; + // The whole mutation runs under the binding's lock, the same one + // every reconcile takes, so a doorbell-driven respawn cannot + // re-point the binding between the rebind and its wake. + await serial(`b:${b.id}`, async () => { + const fresh = store.binding(b.id); + if (fresh === null || fresh.endedAt !== null) { + result.outcome = "gone"; + return; + } + const previous = fresh.threadId; + // Clear the wait before the wake: the new thread has not had the + // wake yet, and the old thread's report is not coming. + store.patch(b.id, { threadId, awaitingReport: false }); + if (previous !== null && previous !== threadId) await quietly(`archive the previous steward thread ${previous}`, () => bb.sdk.threads.archive({ threadId: previous })); + // The action log: the wake carries it, so the new thread's first + // report knows where it came from. + store.note(b.id, `Rebound from ${previous ?? "(none)"} to ${threadId} with bb stewards rebind.`); + bb.log.info(`stewards: rebound ${b.entityKey} from ${previous ?? "(none)"} to ${threadId}`); + const config = await loadConfig(b.projectId); + const playbook = config === null ? null : bindingPlaybook(config, fresh); + if (config === null || playbook === null) { + result.outcome = "missing"; + return; + } + // Send the binding's wake now, not at the next requeue. + await reconcileBinding(b.id, "requeue"); + result.outcome = store.binding(b.id)?.awaitingReport === true ? "sent" : "queued"; + }); + if (result.outcome === "gone") return { exitCode: 0, stdout: `${b.entityKey} ended while rebinding; nothing was changed.` }; + if (result.outcome === "missing") return { exitCode: 0, stdout: `Rebound ${b.entityKey} to ${threadId}, but its playbook is missing so no wake was sent.` }; + return { exitCode: 0, stdout: `Rebound ${b.entityKey} to ${threadId}; ${result.outcome === "sent" ? "its wake was sent." : "its wake is queued for its next turn."}` }; + }, + }), + pass: cliCommand({ summary: "Run a pass now: the mechanical sweep, or with --nightly the full nightly pass", options: { project: PROJECT_OPTION, nightly: { type: "boolean", description: "Give every binding a judgment turn and wake the project steward for a digest" } },