diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index bd546566..1a798e0b 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -360,6 +360,66 @@ which writes the status record: A turn that ends without a report is noted; repeated misses raise `stuck`. +#### Turns that are not wakes + +Not every turn a steward acts on is one the plugin composed. The turns it +does not compose are: + +- a plain message the user types in the steward's thread, and an `@bb` + mention (the plugin builds a session wake for a mention, but the turn + itself is the provider's); +- a `bb thread tell` from another thread, including the answer to a worker's + question; +- bb core's child-completed notice, and any other core notice a turn starts + from; +- the first turn after the provider session was reconstructed following + compaction. + +On those turns the plugin has not just handed the steward a wake, so the +invariants reach it from two durable places, not from the transcript: + +- **Per-turn system context.** The SDK exposes a per-thread system-context + hook (`bb.agents.contributeInstructions`, resolved at `thread.start` and + `turn.submit`, capped at 4096 characters), and the plugin injects the + brief there on every turn. It carries the thread id, the playbook's allowed + actions, the ready gate's "start no implementation workers" line, the + exact `bb thread spawn` command built from `models.worker` and the project + environment, the standing rules, and "end with `steward_report`". It is + built from the live binding, and because it is system context and not the + transcript, compaction cannot lose it. **This is the path taken**; the + design's fallback (a wake rule plus a preamble on every plugin-composed + message) is not needed. +- **The durable commands.** `bb stewards brief []` prints the whole + brief — thread id, allowed actions, phase instructions, ready gate, + standing guidance and holds, standing rules, the spawn command and "end + with `steward_report`" — and defaults to the binding of `$BB_THREAD_ID`. + `bb stewards spawn-flags []` prints just the runnable spawn + command. Every wake names both, so a steward whose injected context was + somehow lost still has a fixed line to follow. + +**Compaction hygiene.** The injected brief begins with a fixed prefix +pointing at `bb stewards brief` ("Your context may have been compacted … run +`bb stewards brief` before acting"). The SDK's `threads.compact` takes no +body and bb's compaction summary is provider-generated, so there is no +summary-prefix hook to write into; the fixed prefix lives in the per-turn +system context, which the provider keeps across compaction. Compaction +frequency is unchanged (the `compactAboveTokens` setting, 120k by default); +tuning it against the BB and bithub stewards is a follow-up, not this design. + +#### Post-spawn validation + +A worker is recognized by the `thread.created` handler by its lifecycle +owner first, then by its parent (for stewards spawned before BB-23). Before +the runaway guard, the handler compares the worker's provider, model, +reasoning level and environment provider with the playbook's `models.worker` +(or the binding's override) and the project's environment. On a mismatch it +stops the worker, notes the reason and the correct spawn command on the +binding, and wakes the steward. A fact the plugin cannot read (the model +before the thread has one, the environment before it is attached) is not a +mismatch: validation only acts on what it observed. This is the safety net +for every path that could spawn a worker wrong, including a compacted +steward that reconstructed the flags from memory. + ### Not repeating itself Comments and spawns are not idempotent. Before acting, a steward looks for diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 9c0d6891..bb8fe9e3 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -78,6 +78,20 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. once it holds more than **Compact a steward above this many context tokens** (120,000 by default; 0 leaves it to the provider), and before a wake that would push it over. +- **The invariants reach turns that are not wakes too.** A plain message, a + `bb thread tell`, a child notice and the first turn after compaction are + not wakes the plugin composed. On every turn the SDK resolves a + per-thread system context, and the plugin injects the brief there: thread + id, the playbook's allowed actions, the ready gate, the exact worker + spawn command, the standing rules and "end with `steward_report`". It is + system context, not transcript, so compaction cannot lose it. Every wake + also names the durable commands: `bb stewards brief []` prints + the whole brief, and `bb stewards spawn-flags []` prints the + runnable `bb thread spawn …` command from `models.worker` and the project + environment. A worker whose provider, model, reasoning level or + environment provider differs from the playbook's is stopped in the + `thread.created` handler, and the steward's next wake says why and gives + the right command. DESIGN.md §6. - **Two tools.** `steward_report` ends a turn with the status record and, when needed, an escalation; `steward_update` steers a binding (guidance, deciding or forwarding escalations, priority, holds, models, approving a diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index cee84202..496fc937 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(); @@ -135,8 +135,18 @@ function world() { threads: { spawn: async (args: Record) => { const id = `thr_${++n}`; - const environment = args.environment as { machine?: { hostId?: string } } | undefined; - threads.set(id, { status: "idle", archivedAt: null, title: (args.title as string | undefined) ?? null, sectionId: (args.sectionId as string | undefined) ?? null, ...(environment?.machine?.hostId === undefined ? {} : { hostId: environment.machine.hostId }) }); + const environment = args.environment as { machine?: { hostId?: string }; environmentProviderId?: string } | undefined; + threads.set(id, { + status: "idle", + archivedAt: null, + title: (args.title as string | undefined) ?? null, + sectionId: (args.sectionId as string | undefined) ?? null, + ...(environment?.machine?.hostId === undefined ? {} : { hostId: environment.machine.hostId }), + ...(args.providerId === undefined ? {} : { providerId: args.providerId as string }), + ...(args.model === undefined ? {} : { model: args.model as string }), + ...(args.reasoningLevel === undefined ? {} : { reasoningLevel: args.reasoningLevel as string }), + ...(environment?.environmentProviderId === undefined ? {} : { environmentProviderId: environment.environmentProviderId }), + }); metadata.set(id, { ...((args.pluginMetadata as Record | undefined) ?? {}) }); spawns.push({ ...args, id }); return makeThreadResponse({ id }); @@ -149,10 +159,15 @@ 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: "claude-code", parentThreadId: t.parentThreadId ?? null, sectionId: t.sectionId ?? null }), - ...(t.hostId === undefined ? {} : { environment: { hostId: t.hostId } }), + ...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 }), + ...(t.hostId === undefined && t.environmentProviderId === undefined ? {} : { environment: { hostId: t.hostId ?? null, environmentProviderId: t.environmentProviderId ?? null } }), }; }, + defaultExecutionOptions: async ({ threadId }: { threadId: string }) => { + const t = threads.get(threadId); + if (t === undefined || t.model === undefined) return null; + return { model: t.model, reasoningLevel: t.reasoningLevel ?? "none", serviceTier: "standard", permissionMode: "default", source: "explicit" }; + }, list: async ({ sectionId, archived, parentThreadId }: { sectionId?: string; archived?: boolean; parentThreadId?: string }) => [...threads.entries()] .filter( @@ -226,16 +241,25 @@ async function setup(extra: Partial = {}, settings: Record { - 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 }) }); + /** A thread a steward started with `bb thread spawn --parent-self` or `--lifecycle-owner-thread`. */ + const created = async ( + id: string, + parent: string, + title = "Implement", + over: { providerId?: string; model?: string | null; reasoningLevel?: string | null; environmentProviderId?: string | null } = {}, + ) => { + 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 }) }); 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 }); - await harness.behavior.emitThreadEvent("thread.created", { thread: makeThreadResponse({ id, parentThreadId: null, lifecycleOwnerThreadId: owner, title, originPluginId: null }) }); + 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" }) }); await flush(); }; return { ...w, bb, harness, hooks, flush, ring, tool, list, idle, created, createdOwned }; @@ -3891,3 +3915,167 @@ describe("the dotenv a requester imports", () => { expect(secretVariable({ what: "Enter it", data: { variable: "LINEAR_CLIENT_SECRET", setting: "sentryToken" } })).toBe("LINEAR_CLIENT_SECRET"); }); }); + +// BB-24: the invariants must reach a steward on turns the plugin did not +// compose (a plain message, a `bb thread tell`, a child notice) and after its +// 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`; + + it("prints the full runnable spawn command from the playbook's worker model and the project environment", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + + const out = await t.harness.behavior.runCli(["spawn-flags"], { threadId: steward, projectId: "p1" }); + expect(out.exitCode).toBe(0); + expect(out.stdout).toBe(spawnLine()); + expect(out.stdout).not.toContain("--parent-self"); + expect(out.stdout).not.toContain("--parent-thread"); + + // By key, without the invoking thread, and the same command. + const byKey = await t.harness.behavior.runCli(["spawn-flags", "ENG-12", "--project", "p1"]); + expect(byKey.stdout).toBe(out.stdout); + // Not from a thread that is no steward, and no binding named. + const stranger = await t.harness.behavior.runCli(["spawn-flags"], { threadId: "thr_stranger", projectId: "p1" }); + expect(stranger.exitCode).toBe(1); + expect(stranger.stderr).toMatch(/not the steward of a binding/u); + // The project steward starts no workers; its own brief still works. + const project = t.spawns[0]!.id; + const fromProject = await t.harness.behavior.runCli(["spawn-flags"], { threadId: project, projectId: "p1" }); + expect(fromProject.exitCode).toBe(1); + expect(fromProject.stderr).toMatch(/project steward starts no workers/u); + const projectBrief = await t.harness.behavior.runCli(["brief"], { threadId: project, projectId: "p1" }); + expect(projectBrief.exitCode).toBe(0); + expect(projectBrief.stdout).toContain("# Project steward brief"); + }); + + it("prints the brief: thread id, allowed actions, phase, ready gate, guidance and holds, standing rules and the spawn command", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + t.hooks.store.addGuidance(t.hooks.store.byThread(steward)!.id, "Watch the auth paths.", "user"); + + const out = await t.harness.behavior.runCli(["brief"], { threadId: steward, projectId: "p1" }); + expect(out.exitCode).toBe(0); + expect(out.stdout).toContain(`Your thread id is ${steward}.`); + expect(out.stdout).toContain("Allowed actions: comment, edit-description, set-state, set-labels, create-sub-issue, open-pr, request-review, spawn-worker."); + expect(out.stdout).toContain("## Phase: Todo"); + expect(out.stdout).toContain("start no implementation workers"); + expect(out.stdout).toContain("## Guidance and holds"); + expect(out.stdout).toContain("Watch the auth paths."); + expect(out.stdout).toContain("## Standing rules"); + expect(out.stdout).toContain("End your turn with steward_report"); + expect(out.stdout).toContain(spawnLine()); + }); + + it("injects the invariants as per-turn system context, so compaction and a plain tell do not lose them", 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" }); + + const before = instructions(); + expect(before).not.toBeNull(); + expect(before).toContain(`Your thread id is ${steward}.`); + expect(before).toContain("Allowed actions: comment, edit-description"); + expect(before).toContain("--lifecycle-owner-thread"); + expect(before).toContain("--model claude-opus-5-5"); + expect(before).toContain("End your turn with steward_report"); + expect(before).toContain("bb stewards brief"); + // The SDK truncates a contribution at 4096 characters; the brief must fit. + expect(before!.length).toBeLessThanOrEqual(4096); + expect(before).not.toContain("--parent-self"); + + // Compaction replaces the transcript, not the injected context. + t.usage.set(steward, 200_000); + await t.idle(steward); + expect(t.harness.sdk.callsTo("threads.compact").map(([args]) => (args as { threadId: string }).threadId)).toContain(steward); + expect(instructions()).toBe(before); + + // Every wake names the two durable commands, for the turns the plugin did not compose. + const wake = String(t.spawns[1]!.prompt); + expect(wake).toContain("bb stewards brief"); + expect(wake).toContain("bb stewards spawn-flags"); + }); + + it("stops a worker spawned with the wrong provider and wakes the steward with the right command", 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_bad", steward, "ENG-12: Implement", { providerId: "codex" }); + expect(t.harness.sdk.callsTo("threads.stop").map(([args]) => args)).toContainEqual({ threadId: "thr_bad" }); + 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`); + }); + + it("stops a worker on the wrong model, reasoning level or environment provider, and leaves a matching one alone", 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_model", steward, "ENG-12: Implement", { model: "claude-sonnet-5-5" }); + await t.created("thr_reasoning", steward, "ENG-12: Implement", { reasoningLevel: "low" }); + await t.created("thr_env", steward, "ENG-12: Implement", { environmentProviderId: "devbox" }); + const stopped = t.harness.sdk.callsTo("threads.stop").map(([args]) => (args as { threadId: string }).threadId); + expect(stopped).toEqual(expect.arrayContaining(["thr_model", "thr_reasoning", "thr_env"])); + expect(t.hooks.store.worker("thr_model")!.status).toBe("stopped"); + expect(t.hooks.store.worker("thr_reasoning")!.status).toBe("stopped"); + expect(t.hooks.store.worker("thr_env")!.status).toBe("stopped"); + + // A worker matching the playbook and the project environment is left alone. + await t.created("thr_ok", steward, "ENG-12: Implement"); + expect(stopped).not.toContain("thr_ok"); + expect(t.hooks.store.worker("thr_ok")!.status).not.toBe("stopped"); + }); + + it("says the gate is not passed once an approved spec changes, in the brief and the injected context", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const project = t.spawns[0]!.id; + const steward = t.spawns[1]!.id; + await t.tool( + "steward_report", + { phase: "Todo", summary: "Specified.", nextAction: "Move to In Progress", actor: "steward", ready: { checklist: [1, 2, 3, 4].map((item) => ({ item, met: true })), substantial: true } }, + steward, + ); + expect((await t.tool("steward_update", { binding: "ENG-12", approve: true }, project)).error).toBe(false); + + const brief = () => t.harness.behavior.runCli(["brief"], { threadId: steward, projectId: "p1" }); + const instructions = () => t.harness.inspection.registrations.instructionProvider!({ threadId: steward, projectId: "p1" })!; + expect((await brief()).stdout).toContain("Ready gate: PASSED"); + expect(instructions()).toContain("Ready gate: PASSED"); + + // The spec changes; the approval is stale, and a brief pinned to the + // approval's own hash would still call the gate passed. + const b = t.hooks.store.find("ENG-12")!; + t.hooks.store.patch(b.id, { lastSnapshot: { entity: issue({ description: "Users cannot log in. Also SSO." }), pulls: [] } }); + expect((await brief()).stdout).toMatch(/Ready gate: not passed/); + expect(instructions()).toMatch(/Ready gate: not passed/); + }); + + it("points the injected brief at `bb stewards spawn-flags` when the project's machine is not cached", 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("bb thread spawn --project p1 --lifecycle-owner-thread"); + + // A machine read more than a sweep ago is not trusted for a synchronous brief. + t.advance(31 * 60_000); + const stale = instructions(); + expect(stale).toContain("Run `bb stewards spawn-flags` for the exact worker spawn command"); + expect(stale).not.toContain("bb thread spawn --project p1"); + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index eb020de5..381ceaf5 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -70,12 +70,19 @@ import { ACTORS, MIGRATIONS, NEEDS_KINDS, createStore, needChoices, type Binding import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; -import { PROJECT_STEWARD_INTRO, choicesNote, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, workerQuestion, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerQuestion, type DigestRecords, type PendingRequest, 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. */ export const MULTI_REPO_ENVIRONMENT_PROVIDER_ID = "multi-repo-workspace"; +/** + * The per-turn system context the SDK injects is truncated at 4096 characters; + * build the brief to a little under that so its wrapper and the head and tail + * the clip keeps always fit. + */ +export const BRIEF_MAX_CHARS = 3800; + /** * What thread-briefs is asked to leave alone, seeded into this plugin's * metadata namespace on each thread it spawns (thread-briefs' README, "Threads @@ -889,7 +896,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * then fails every spawn with "Local host daemon is not initialized". * A connected machine is preferred, then the default source. Null when the * project has no checkout bb knows of, and core's default is all there is. + * + * The last answer is cached for the synchronous per-turn brief, which + * cannot await this. */ + const projectHostCache = new Map(); async function projectHost(projectId: string): Promise { try { const [project, hosts] = await Promise.all([bb.sdk.projects.get({ projectId }), bb.sdk.hosts.list().catch(() => [])]); @@ -900,13 +911,27 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P sources.find((source) => connected.has(source.hostId)) ?? sources.find((source) => source.isDefault) ?? sources[0]; + projectHostCache.set(projectId, { at: now(), hostId: pick?.hostId ?? null }); return pick?.hostId ?? null; } catch (error) { bb.log.warn(`stewards: could not find the machine for ${projectId} (${errorMessage(error)}); leaving it to bb's default`); + projectHostCache.set(projectId, { at: now(), hostId: null }); return null; } } + /** + * The cached project machine, or undefined when it was never read or is + * older than a sweep. The synchronous per-turn brief cannot await + * `projectHost`; when the cache cannot answer, it points at + * `bb stewards spawn-flags` rather than print a command with a machine it + * is unsure of. + */ + function cachedProjectHost(projectId: string): string | null | undefined { + const entry = projectHostCache.get(projectId); + return entry === undefined || now() - entry.at > timing.sweepMs ? undefined : entry.hostId; + } + /** A fresh environment for a project's thread: a multi-repo workspace on its machine. */ const freshEnvironment = (hostId: string | null) => hostId === null @@ -1200,6 +1225,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** The spec hash a binding's approval is pinned to, counting the user's own spec comments. */ const specHashFor = (b: Pick, entity: EntitySnapshot): string => specHash(entity, b.threadId, isUserThread); + /** + * The ready gate for a brief: the live spec hash when the binding has a + * snapshot, so an approval whose spec changed reads as not passed. The + * wake does the same; a brief pinned to the approval's own hash would call + * a stale gate passed on exactly the compacted/non-wake turns it protects. + */ + const briefGate = (b: Binding, playbook: Playbook) => + gateState(playbook, b.ready, b.lastSnapshot === null ? (b.ready.approval?.specHash ?? "") : specHashFor(b, b.lastSnapshot.entity)); + const ownThreads = (b: Binding) => new Set([b.threadId, ...store.workers(b.id).map((w) => w.threadId)].filter((t): t is string => t !== null)); function routedTo(b: Binding): Array<{ escalation: Escalation; from: Binding }> { @@ -2697,6 +2731,59 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // lifecycle owner rather than a tool of their own. A thread an older // steward made a child is still recognized by its parent. + /** + * The post-spawn safety net: a worker whose provider, model, reasoning + * level or environment provider differs from the playbook's worker model + * and the project's environment was started wrong — by a compacted + * steward, a hand-run command or an old wake. Stop it, note why on the + * binding with the command that would have been right, and wake the + * steward. A worker recognized by lifecycle owner or, for older stewards, + * by parent both come through here. + */ + async function validateWorkerSpawn(thread: { id: string; providerId: string }, owner: Binding): Promise { + const config = await loadConfig(owner.projectId); + const playbook = config === null ? null : bindingPlaybook(config, owner); + if (playbook === null || playbook.kind === "ops") return; + const expected = workerModel(owner, playbook); + if (expected === null) return; + const hostId = await projectHost(owner.projectId); + const expectedEnv = hostId === null ? null : MULTI_REPO_ENVIRONMENT_PROVIDER_ID; + // undefined means "could not read it": validate what is known, never + // stop a worker over a fact the plugin could not observe. + let actualModel: string | null = null; + let actualReasoning: string | null = null; + try { + const options = await bb.sdk.threads.defaultExecutionOptions({ threadId: thread.id }); + actualModel = options?.model ?? null; + actualReasoning = options?.reasoningLevel ?? null; + } catch (error) { + bb.log.warn(`stewards: could not read the model of worker ${thread.id} (${errorMessage(error)}); not validating it`); + } + let actualEnv: string | null | undefined; + try { + const info = (await bb.sdk.threads.get({ threadId: thread.id, include: "environment" })) as { environment?: { environmentProviderId?: string | null } | null }; + // No environment attached yet is "unknown", not "none". + actualEnv = info.environment == null ? undefined : (info.environment.environmentProviderId ?? null); + } catch (error) { + bb.log.warn(`stewards: could not read the environment of worker ${thread.id} (${errorMessage(error)}); not validating it`); + } + const problems: string[] = []; + if (thread.providerId !== expected.providerId) problems.push(`provider ${thread.providerId === "" ? "(none)" : thread.providerId} instead of ${expected.providerId}`); + if (actualModel !== null && expected.model !== null && actualModel !== expected.model) problems.push(`model ${actualModel} instead of ${expected.model}`); + if (actualReasoning !== null && expected.reasoningLevel !== null && actualReasoning !== expected.reasoningLevel) problems.push(`reasoning level ${actualReasoning} instead of ${expected.reasoningLevel}`); + if (actualEnv !== undefined && expectedEnv !== null && actualEnv !== expectedEnv) problems.push(`environment provider ${actualEnv ?? "(none)"} instead of ${expectedEnv}`); + if (problems.length === 0) return; + const flags = [environmentFlags(hostId), workerFlags(expected)].filter((f) => f !== "").join(" "); + store.setWorker(thread.id, "stopped", `Started with the wrong ${problems.join(", ")}; stopped.`); + await quietly(`stop mis-spawned worker ${thread.id}`, () => bb.sdk.threads.stop({ threadId: thread.id })); + 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 })}`, + ); + scheduleReconcile(owner.id); + } + 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; @@ -2705,7 +2792,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const limit = (await settings.get()).workerSpawnsPerHour; const runaway = store.spawnsSince(owner.id, now() - 3_600_000) >= limit; store.addWorker(thread.id, owner.id, thread.title ?? thread.titleFallback ?? thread.id); - if (!runaway) return; + if (!runaway) { + await validateWorkerSpawn(thread, owner); + return; + } // The runaway guard: not a budget, a stop for a looping steward. store.setWorker(thread.id, "stopped", null); await quietly(`stop runaway worker ${thread.id}`, () => bb.sdk.threads.stop({ threadId: thread.id })); @@ -3481,6 +3571,44 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }; }); + /** + * The invariants on every turn, not only in a wake. The SDK's per-thread + * system context (`contributeInstructions`) is resolved at thread.start and + * turn.submit, so a steward whose transcript was compacted — or which a + * plain message, a `bb thread tell` or a child notice wakes — still gets + * its thread id, allowed actions, the spawn command, the standing rules + * and the pointer at `bb stewards brief`. The role's own instructions stay + * in `configure`; this carries the live binding state, which is why the + * brief is built here and not in the skill. + */ + /** The project steward's invariants, injected per turn and printed by `bb stewards brief` in its thread. */ + const projectStewardInvariants = (threadId: string): string => + [ + "Your context may have been compacted. You are the project steward; the record, not memory, is what you decide from.", + `Your thread id is ${threadId}. Read status with \`bb stewards list\` and \`bb stewards show \`; steer with steward_update. End the nightly wake with the morning digest.`, + ].join("\n"); + + bb.agents.contributeInstructions(({ threadId }) => { + const project = store.projectByThread(threadId); + if (project !== null) return projectStewardInvariants(threadId); + const b = store.byThread(threadId); + if (b === null || b.endedAt !== null) return null; + const config = configs.get(b.projectId)?.value ?? null; + const playbook = config === null ? null : bindingPlaybook(config, b); + if (playbook === null) { + return [ + `Your context may have been compacted. Your thread id is ${threadId}, and you steward ${b.entityKey} (binding ${b.id}).`, + "The project's playbook could not be read; run `bb stewards brief` and `bb stewards check` before acting.", + ].join("\n"); + } + const hostId = cachedProjectHost(b.projectId); + const flags = hostId === undefined ? null : [environmentFlags(hostId), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "); + return formatBrief( + { binding: b, playbook, gate: briefGate(b, playbook), workerFlags: flags, escalations: store.openEscalations(b.id), conflicts: conflictsOf(b, store.open(b.projectId)) }, + BRIEF_MAX_CHARS, + ); + }); + const toolError = (error: unknown) => ({ content: [{ type: "text" as const, text: errorMessage(error) }], isError: true }); function ownBinding(threadId: string): Binding { @@ -4350,6 +4478,25 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return b; } + /** The binding `brief`/`spawn-flags` acts on: the positional, or the invoking thread's own. */ + function bindingFromCli(positional: string | undefined, option: string | undefined, ctx: { threadId?: string; projectId?: string }): Binding { + if (positional !== undefined && positional !== "") return bindingOrThrow(positional, option ?? ctx.projectId); + const own = ctx.threadId === undefined ? null : store.byThread(ctx.threadId); + if (own === null) { + const project = ctx.threadId === undefined ? null : store.projectByThread(ctx.threadId); + throw new PluginCliError("This thread is not the steward of a binding; pass one (an entity key or binding id).", { + code: "no_binding", + hint: project === null ? "bb stewards list shows the project's bindings." : "The project steward starts no workers; run `bb stewards brief` for its invariants.", + }); + } + return own; + } + + /** The worker spawn flags for a binding: the project's environment first, then the playbook's worker model. */ + async function workerFlagsFor(b: Binding, playbook: Playbook): Promise { + return [environmentFlags(await projectHost(b.projectId)), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "); + } + async function check(projectId: string): Promise<{ ok: boolean; lines: string[] }> { const config = await loadConfig(projectId, true); if (config === null) return { ok: false, lines: [`No ${PROJECT_FILE} on the project's .bb (committed HEAD). Run bb stewards init.`] }; @@ -4473,6 +4620,40 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }, }), + brief: cliCommand({ + summary: "A steward's invariants: thread id, allowed actions, phase instructions, ready gate, guidance and holds, the standing rules, and the worker spawn command", + description: + "Run this on any turn that is not a wake, and after your context was compacted. It defaults to the binding of the invoking thread. The plugin also injects a bounded form of it as per-turn system context, so it survives compaction.", + positionals: [{ name: "binding", description: "The entity key (ENG-12, owner/repo#3) or binding id; the invoking thread's binding when left out", required: false }], + options: { project: PROJECT_OPTION }, + async run(input, ctx) { + const own = input.positionals.binding === undefined || input.positionals.binding === "" ? (ctx.threadId === undefined ? null : store.projectByThread(ctx.threadId)) : null; + if (own !== null && ctx.threadId !== undefined) return { exitCode: 0, stdout: `# Project steward brief\n\n${projectStewardInvariants(ctx.threadId)}` }; + const b = bindingFromCli(input.positionals.binding, input.options.project, ctx); + 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: 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)) }), + }; + }, + }), + + "spawn-flags": cliCommand({ + summary: "The full runnable `bb thread spawn` command for a steward's workers, from the playbook's worker model and the project environment", + description: "Use these flags as they are: they are the playbook's, not the steward's to choose. Defaults to the binding of the invoking thread.", + positionals: [{ name: "binding", description: "The entity key (ENG-12, owner/repo#3) or binding id; the invoking thread's binding when left out", required: false }], + options: { project: PROJECT_OPTION }, + async run(input, ctx) { + const b = bindingFromCli(input.positionals.binding, input.options.project, ctx); + 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) }) }; + }, + }), + check: cliCommand({ summary: "Validate the project file and every playbook against Linear and GitHub, and that kubectl can read every ops target", options: { project: PROJECT_OPTION }, diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index cc27edd5..29fd4693 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -23,6 +23,22 @@ You are woken with one message in a fixed form: the phase's instructions, the ready gate, standing guidance and holds, a snapshot of the entity, and what changed. It is self-contained: act from it, not from memory. +Your invariants also arrive on turns the plugin did not compose — a plain +message, a `bb thread tell`, a child notice, or the first turn after your +context was compacted — as per-turn system context, so they survive +compaction. They are: your thread id, the playbook's allowed actions, the +ready gate, the standing rules, and "end with `steward_report`". If you ever +doubt them, the durable commands are: + +- `bb stewards brief []` — the whole brief: thread id, allowed +actions, phase instructions, ready gate, standing guidance and holds, the +standing rules, the worker spawn command, and "end with `steward_report`". +Defaults to the binding of `$BB_THREAD_ID`. +- `bb stewards spawn-flags []` — just the full runnable +`bb thread spawn …` command for your workers, built from the playbook's +`models.worker` and the project environment. Never reconstruct these flags; +copy the command. + Two tools are yours; everything else you do with the tools every thread has. - **`steward_report` ends every woken turn**: phase, a one-sentence summary, @@ -74,15 +90,20 @@ Two tools are yours; everything else you do with the tools every thread has. every later wake. With a child steward, it also decides its escalations, sets priority and holds, and overrides models. - **You decide and delegate; you do not write code.** Start a worker for one - bounded task with the `bb thread spawn … --lifecycle-owner-thread` command - the wake shows; write the task so the worker needs nothing else. Follow up - with `bb thread tell`. A worker finishing starts no turn of yours: its - final message arrives in your next wake, under Workers. + bounded task with the `bb thread spawn --lifecycle-owner-thread …` command + the wake shows (or `bb stewards spawn-flags` prints); write the task so the + worker needs nothing else. The flags are the playbook's, not yours to + choose: never ask the user for a model. Follow up with `bb thread tell`. A + worker finishing starts no turn of yours: its final message arrives in your + next wake, under Workers. While it runs you are not woken for its own work on its pull request (checks, pushes, its comments and its reviewer's, posted as the user); that shows under "What changed" at your next turn. Other people's comments and reviews, and a merge or close, still wake you. - More than the runaway guard allows in an hour are stopped. + More than the runaway guard allows in an hour are stopped. A worker started + with a provider, model, reasoning level or environment that differs from + the playbook is stopped by the plugin, and your next wake says why and + gives the right command. - **Act as the user, signed.** `linear_comment`, `linear_update_issue` and `linear_create_issue` sign for you: add no signature to what you pass them. With `gh`, end what you write with @@ -281,6 +302,8 @@ project. | Command | Does | |---|---| +| `bb stewards brief [] [--project ]` | The invariants for a steward: thread id, allowed actions, phase instructions, ready gate, guidance and holds, standing rules, and the worker spawn command. Defaults to the binding of the invoking thread | +| `bb stewards spawn-flags [] [--project ]` | The full runnable `bb thread spawn …` command for a steward's workers, from the playbook's `models.worker` and the project environment | | `bb stewards list [--all] [--json]` | Bindings and their status records | | `bb stewards show ` | One binding in full: gate, guidance, escalations, needs, workers, fingerprints | | `bb stewards needs [--all] [--json]` | What waits on the user, with links and the action each supports | diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 1b6f3dd1..d5fbedbd 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -36,6 +36,24 @@ const STANDING_RULES = [ "- **A credential is a `provide-secret` need, not a worker's job to prompt.** File it with `steward_report { needs: [{ kind: \"provide-secret\", url, what, how, variable, purpose }] }`; the plugin spawns a requester thread and opens bb's secure form there. For a dotenv on a worker's machine name `writeEnv` (or `worker`); for one of the stewards plugin's own settings name `setting` (only a declared secret setting is accepted). Never paste a secret, and never route the user to a script to run.", "- **A finding that would stop the feature working once it ships**, or that changes what the ticket needs (a credential, an access, a contract), is escalated as a `decision` in the same turn, quoting the worker's words — never relayed as a follow-up. An escalation that asks the user to pick between fixed options carries `choices` (2-6 short labels) so the page shows one button each.", ]; +/** + * The fixed first line of every brief, and of the per-turn system context the + * plugin injects: what a steward reads after its context has been compacted or + * on a turn the plugin did not compose. It is the durable pointer the design's + * "each wake is self-contained" rests on. + */ +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 { + return [ + `bb thread spawn --project ${input.projectId} --lifecycle-owner-thread "$BB_THREAD_ID"${input.workerFlags === "" ? "" : ` ${input.workerFlags}`} --title "${input.entityKey}: " --prompt-file - <<'EOF'`, + "", + "EOF", + ].join("\n"); +} + const DESCRIPTION_CHARS = 4000; const COMMENT_CHARS = 1500; const RESULT_CHARS = 1500; @@ -83,12 +101,12 @@ function workerQuestionLines(q: WorkerQuestion): string[] { * (the snapshot, the list of bindings) and keeping the head and the tail: the * tail says what changed and what to do, which a cut wake must not lose. */ -function fit(head: string[], middle: string[], tail: string[]): string { +function fit(head: string[], middle: string[], tail: string[], maxChars = WAKE_MAX_CHARS): string { const h = head.join("\n"); const t = tail.join("\n"); - const room = WAKE_MAX_CHARS - h.length - t.length - 200; + const room = maxChars - h.length - t.length - 200; const m = middle.join("\n"); - if (room <= 0) return clip([h, t].join("\n"), WAKE_MAX_CHARS); + if (room <= 0) return clip([h, t].join("\n"), maxChars); return [h, clip(m, room), t].join("\n"); } @@ -204,7 +222,7 @@ function entityLines(e: EntitySnapshot, cursor: string, own: ReadonlySet return lines; } -function gateLines(input: WakeInput): string[] { +function gateLines(input: Pick): string[] { const { gate, binding, playbook } = input; if (gate.none) return ["No ready gate in this playbook."]; const lines: string[] = []; @@ -281,12 +299,13 @@ export function formatWake(input: WakeInput): string { "", "Start a worker for one bounded task with:", "", - ` bb thread spawn --project ${binding.projectId} --lifecycle-owner-thread "$BB_THREAD_ID" ${input.workerFlags} --title "${e.key}: " --prompt-file - <<'EOF'`, - " ", - " EOF", + ...spawnCommand({ projectId: binding.projectId, entityKey: e.key, workerFlags: input.workerFlags }) + .split("\n") + .map((line) => ` ${line}`), "", "Follow it up with `bb thread tell `. A worker finishing starts no turn of yours: its final message arrives in your next wake, which lists it under Workers.", "Those `--provider`/`--model`/`--reasoning-level` flags are your workers' and reviewers' models, from the playbook or the project. They are not yours to choose: never ask the user for a model.", + "On a turn that is not a wake — a plain message, a `bb thread tell`, a child notice — run `bb stewards brief` first. It prints this thread's id, the allowed actions, the phase instructions, the ready gate, guidance and holds, the standing rules and the exact spawn command. `bb stewards spawn-flags` prints just the spawn command.", "", "**Standing rules.**", "", @@ -353,6 +372,87 @@ export function formatWake(input: WakeInput): string { return fit(head, snapshot, out); } +/** What `bb stewards brief` prints, and what the plugin injects as per-turn system context. */ +export type BriefInput = { + binding: Binding; + playbook: Playbook; + 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; + /** 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. */ + conflicts?: Conflict[]; +}; + +/** One line for the head of a brief: the gate's state, and the one action it forbids while unmet. */ +function briefGateLine(gate: GateState, escalations: Escalation[]): string { + if (gate.none) return "Ready gate: none in this playbook."; + const scheduling = escalations.find((x) => x.status === "open" && x.kind === "schedule"); + if (!gate.passed) return "Ready gate: not passed — start no implementation workers."; + if (scheduling === undefined) return "Ready gate: PASSED."; + return `Ready gate: PASSED — but scheduling is with the project steward (${scheduling.id}); start no implementation workers and do not move the ticket into a build state until it decides.`; +} + +/** + * The steward's invariants in one block: thread id, allowed actions, the + * ready gate, the spawn command, phase instructions, guidance and holds, the + * standing rules and "end with steward_report". `bb stewards brief` prints it + * whole; the per-turn system context injects it with a character budget, and + * clips the middle (phase instructions, the gate's detail and guidance), + * never the head or the tail, so a compacted steward still gets what it must + * act on. + */ +export function formatBrief(input: BriefInput, maxChars?: number): string { + const { binding: b, playbook, gate } = input; + const e = b.lastSnapshot?.entity ?? null; + const escalations = input.escalations ?? []; + const ops = b.kind === "ops"; + const head: string[] = [ + BRIEF_PREFIX, + "", + `# Steward brief: ${b.entityKey}${e?.title ? ` — ${e.title}` : ""}`, + `Binding ${b.id} · ${b.kind} · playbook ${playbook.name}@${playbook.version} · phase ${b.phase ?? e?.state ?? "?"}${b.stage === null ? "" : ` (stage ${b.stage})`}`, + "", + `${b.threadId === null ? "Your thread id is in `$BB_THREAD_ID`." : `Your thread id is ${b.threadId}.`} Use it wherever you name yourself (a worker's task, a gh signature), and never take one from your workspace's path: you share the project steward's workspace, and its path names that thread.`, + "", + `Allowed actions: ${playbook.may.join(", ") || "(none)"}.`, + ]; + 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 })); + } + + const middle: string[] = []; + if (!ops) middle.push("", ...gateLines({ gate, binding: b, playbook, escalations })); + const phase = b.phase ?? e?.state ?? null; + if (phase !== null) { + const section = phaseInstructions(playbook, phase); + middle.push("", `## Phase: ${phase}`, "", section === null ? "(The playbook has no section for this phase; use the general instructions and escalate a decision if unsure.)" : section); + } + if (playbook.general !== "") middle.push("", "## General", "", playbook.general); + middle.push("", "## Guidance and holds", ""); + if (b.guidance.length === 0) middle.push("No standing guidance."); + for (const g of b.guidance) middle.push(`- ${iso(g.at)} (${g.by}): ${g.text}`); + middle.push(`- Priority: ${b.priority ?? "normal"}`); + middle.push(holdLine(b, "take no new actions and start no workers until it is lifted.")); + middle.push(...schedulingLines(b, input.conflicts ?? [], escalations)); + + const tail: string[] = [ + "", + "## Standing rules", + "", + ...STANDING_RULES, + "", + "---", + `End your turn with steward_report; requeueAfter defaults to ${formatDuration(playbook.requeueDefaultMs)}.`, + ]; + + if (maxChars === undefined) return [...head, ...middle, ...tail].join("\n"); + return fit(head, middle, tail, maxChars); +} + export type OpsWakeInput = { reason: WakeReason; binding: Binding;