diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index e80156f9..6e71e2a0 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -166,10 +166,14 @@ function world() { ...(t.hostId === undefined && t.environmentProviderId === undefined ? {} : { environment: { hostId: t.hostId ?? null, environmentProviderId: t.environmentProviderId ?? null } }), }; }, + // What the server answers: the thread's own execution once a turn ran, and before that the + // project's remembered picker defaults, which a spawn with other flags does not change. + // The plugin must not read a pending worker's model from here. 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" }; + if (t === undefined) return null; + if (t.model === undefined) return { model: "claude-fable-5-1", reasoningLevel: "medium", serviceTier: "default", permissionMode: "auto", source: "client/turn/requested" }; + return { model: t.model, reasoningLevel: t.reasoningLevel ?? "none", serviceTier: "default", permissionMode: "auto", source: "client/turn/requested" }; }, list: async ({ sectionId, archived, parentThreadId }: { sectionId?: string; archived?: boolean; parentThreadId?: string }) => [...threads.entries()] @@ -209,7 +213,12 @@ function world() { ? usage.has(threadId) ? [{ id: "u", seq: 1, threadId, createdAt: now, scope: "thread", type: "thread/contextWindowUsage/updated", data: { contextWindowUsage: { usedTokens: usage.get(threadId), modelContextWindow: 1_000_000, estimated: true } } }] : [] - : userTurns.filter((t) => t.threadId === threadId).map((t, i) => ({ id: `e${i}`, seq: i, threadId, createdAt: now, scope: "thread", type: "client/turn/start", data: { initiator: "user", request: { method: "turn/start", params: { input: [{ type: "text", text: t.text }] } } } })), + : types?.includes("client/turn/requested") + ? // The spawn's execution as the server resolved it; absent while the thread is still pending its first turn. + threads.get(threadId)?.model === undefined + ? [] + : [{ id: "t", seq: 1, threadId, createdAt: now, scope: "thread", type: "client/turn/requested", data: { execution: { model: threads.get(threadId)!.model, reasoningLevel: threads.get(threadId)!.reasoningLevel ?? "none", permissionMode: "auto", serviceTier: "default", source: "client/turn/requested" } } }] + : userTurns.filter((t) => t.threadId === threadId).map((t, i) => ({ id: `e${i}`, seq: i, threadId, createdAt: now, scope: "thread", type: "client/turn/start", data: { initiator: "user", request: { method: "turn/start", params: { input: [{ type: "text", text: t.text }] } } } })), }, }, }; @@ -4563,6 +4572,41 @@ describe("steward invariants on every turn (BB-24)", () => { expect(t.hooks.store.worker("thr_ok")!.status).not.toBe("stopped"); }); + it("checks a still-pending worker's model when it goes active, not against the project's defaults", 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; + const stopped = () => t.harness.sdk.callsTo("threads.stop").map(([args]) => (args as { threadId: string }).threadId); + const active = async (id: string) => { + await t.harness.behavior.emitThreadEvent("thread.active", { thread: makeThreadResponse({ id, parentThreadId: steward, lifecycleOwnerThreadId: steward, status: "active", originPluginId: null, providerId: "claude-code" }) }); + await t.flush(); + }; + + // No first turn yet (the spawn is queued under the concurrency limit): nothing to read, so nothing is + // stopped, whatever defaultExecutionOptions says, and the wait is on the worker row for a restart. + await t.created("thr_wait", steward, "ENG-12: Implement", { model: null, reasoningLevel: null }); + await t.created("thr_fine", steward, "ENG-12: Implement", { model: null, reasoningLevel: null }); + expect(stopped()).toEqual([]); + expect(t.hooks.store.worker("thr_wait")!.modelCheckPending).toBe(true); + expect(t.hooks.store.worker("thr_fine")!.modelCheckPending).toBe(true); + + // The first turn is dispatched with the wrong model: stopped then. + Object.assign(t.threads.get("thr_wait")!, { model: "claude-fable-5-1", reasoningLevel: "medium" }); + await active("thr_wait"); + expect(stopped()).toEqual(["thr_wait"]); + expect(t.hooks.store.worker("thr_wait")!.result).toContain("wrong model claude-fable-5-1 instead of claude-opus-5-5, reasoning level medium instead of high"); + + // Dispatched with the playbook's model: left alone, and not checked again on later turns. + Object.assign(t.threads.get("thr_fine")!, { model: "claude-opus-5-5", reasoningLevel: "high" }); + await active("thr_fine"); + Object.assign(t.threads.get("thr_fine")!, { model: "claude-fable-5-1" }); + await active("thr_fine"); + expect(stopped()).toEqual(["thr_wait"]); + expect(t.hooks.store.worker("thr_fine")!.status).toBe("running"); + expect(t.hooks.store.worker("thr_fine")!.modelCheckPending).toBe(false); + }); + 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()); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 327fbe5f..e5a492da 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -2852,7 +2852,24 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * 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. + * + * The model and reasoning level are read from the worker's own first + * `client/turn/requested` event, the spawn's request as the server + * resolved it. A freshly created thread is `pending` until its first turn + * is admitted (minutes, under the concurrency limit), and has no such + * event yet; `defaultExecutionOptions` would then fall back to the + * project's remembered defaults for the provider, the owner's own picker + * choices, and call a correct spawn wrong. So a worker whose first turn + * has not been dispatched is checked for provider and environment now and + * for model and reasoning level when it goes active. That wait is kept on + * the worker row, so a server restart in between does not lose it. */ + async function workerExecution(threadId: string): Promise<{ model: string | null; reasoningLevel: string | null } | null> { + const [row] = await bb.sdk.threads.events.list({ threadId, types: ["client/turn/requested"], order: "asc", limit: "1" }); + if (row === undefined) return null; + const execution = (row.data as { execution?: { model?: string | null; reasoningLevel?: string | null } }).execution; + return { model: execution?.model ?? null, reasoningLevel: execution?.reasoningLevel ?? null }; + } 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); @@ -2865,10 +2882,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // stop a worker over a fact the plugin could not observe. let actualModel: string | null = null; let actualReasoning: string | null = null; + let firstTurnDispatched = true; try { - const options = await bb.sdk.threads.defaultExecutionOptions({ threadId: thread.id }); - actualModel = options?.model ?? null; - actualReasoning = options?.reasoningLevel ?? null; + const execution = await workerExecution(thread.id); + if (execution === null) firstTurnDispatched = false; + else { + actualModel = execution.model; + actualReasoning = execution.reasoningLevel; + } } catch (error) { bb.log.warn(`stewards: could not read the model of worker ${thread.id} (${errorMessage(error)}); not validating it`); } @@ -2885,7 +2906,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P 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; + if (problems.length === 0) { + if (!firstTurnDispatched && (expected.model !== null || expected.reasoningLevel !== null)) store.setWorkerModelCheckPending(thread.id, true); + return; + } + store.setWorkerModelCheckPending(thread.id, false); 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 })); @@ -3133,9 +3158,16 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // A worker that ended its turn to wait (on a watch, a reviewer) is // running again when that wakes it; it is working its pull request. - bb.events.on("thread.active", ({ thread }) => { + bb.events.on("thread.active", async ({ thread }) => { const worker = store.worker(thread.id); - if (worker !== null && worker.status === "finished") store.setWorker(thread.id, "running", worker.result); + if (worker === null) return; + if (worker.status === "finished") store.setWorker(thread.id, "running", worker.result); + // The first turn is dispatched now, so the spawn's model can be read. + if (worker.modelCheckPending && worker.status !== "stopped") { + store.setWorkerModelCheckPending(thread.id, false); + const owner = store.binding(worker.bindingId); + if (owner !== null && owner.endedAt === null) await validateWorkerSpawn(thread, owner); + } }); bb.events.on("thread.failed", ({ thread, error }) => { @@ -3154,6 +3186,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.events.on("thread.archived", ({ thread }) => { const worker = store.worker(thread.id); if (worker !== null && workerInFlight(worker)) store.setWorker(thread.id, "stopped", worker.result); + if (worker?.modelCheckPending) store.setWorkerModelCheckPending(thread.id, false); // An archived requester can no longer import; drop its binding so the // page's next Provide spawns a fresh one. if (store.secretRequester(thread.id) !== null) store.clearSecretRequester(thread.id); @@ -3161,6 +3194,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.events.on("thread.deleted", ({ thread }) => { const worker = store.worker(thread.id); if (worker !== null && workerInFlight(worker)) store.setWorker(thread.id, "stopped", worker.result); + if (worker?.modelCheckPending) store.setWorkerModelCheckPending(thread.id, false); const b = store.byThread(thread.id); if (b === null || b.endedAt !== null) return; store.patch(b.id, { threadId: null, endedAt: now(), endReason: "deleted", manualDetach: true, awaitingReport: false, ending: null }); diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index 84fe5d32..636c7db4 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -1,6 +1,6 @@ import Database from "better-sqlite3"; import { describe, expect, it } from "vitest"; -import { BASE_MIGRATIONS, CHAIN_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, MIGRATIONS, createStore, lessonScope } from "./store.js"; +import { BASE_MIGRATIONS, CHAIN_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, MIGRATIONS, WORKER_CHECK_MIGRATIONS, createStore, lessonScope } from "./store.js"; function store() { const db = new Database(":memory:"); @@ -230,6 +230,7 @@ describe("lesson citation counts (BB-35 step 2)", () => { db.exec(`INSERT INTO lessons (id, project_id, binding_id, escalation_id, file, text, scope, status, branch, merge_sha, note, created_at, updated_at, resolved_at) VALUES ('lsn_old', 'p1', 'bnd_1', NULL, 'AGENTS.md', 'An old rule.', 'boundary', 'pending', 'refs/heads/guidance-thr_x', NULL, 'kept', 1000, 1100, NULL)`); for (const sql of LESSON_COUNTER_MIGRATIONS) db.exec(sql); + for (const sql of WORKER_CHECK_MIGRATIONS) db.exec(sql); const s = createStore(db, () => 2000); expect(s.lesson("lsn_old")).toMatchObject({ id: "lsn_old", @@ -254,6 +255,33 @@ describe("lesson citation counts (BB-35 step 2)", () => { }); }); +describe("a worker's pending model check", () => { + it("is kept on the row, so a store reopened after a restart still sees it", () => { + const db = new Database(":memory:"); + for (const sql of MIGRATIONS) db.exec(sql); + const first = createStore(db, () => 1000); + const b = first.create({ projectId: "p1", source: "linear", entityId: "uuid-12", entityKey: "ENG-12", url: null, title: "Fix login", kind: "ticket", playbook: "linear-tickets", playbookVersion: "v1", parentBindingId: null, phase: "Todo", stage: "spec" }); + first.addWorker("thr_w1", b.id, "ENG-12: Implement"); + expect(first.worker("thr_w1")!.modelCheckPending).toBe(false); + first.setWorkerModelCheckPending("thr_w1", true); + + const reopened = createStore(db, () => 2000); + expect(reopened.worker("thr_w1")!.modelCheckPending).toBe(true); + reopened.setWorkerModelCheckPending("thr_w1", false); + expect(reopened.worker("thr_w1")!.modelCheckPending).toBe(false); + }); + + it("reads workers from before the column existed as not pending", () => { + const db = new Database(":memory:"); + for (const sql of [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS]) db.exec(sql); + db.exec(`INSERT INTO bindings (id, project_id, source, entity_id, entity_key, kind, playbook, playbook_version, created_at) + VALUES ('bnd_1', 'p1', 'linear', 'uuid-12', 'ENG-12', 'ticket', 'linear-tickets', 'v1', 1000)`); + db.exec(`INSERT INTO workers (thread_id, binding_id, title, status, started_at) VALUES ('thr_old', 'bnd_1', 'ENG-12: Implement', 'running', 1000)`); + for (const sql of WORKER_CHECK_MIGRATIONS) db.exec(sql); + expect(createStore(db, () => 2000).worker("thr_old")!.modelCheckPending).toBe(false); + }); +}); + describe("the escalation-chain migration (BB-30)", () => { function legacy() { const db = new Database(":memory:"); @@ -282,6 +310,7 @@ describe("the escalation-chain migration (BB-30)", () => { VALUES ('need_approve', 'bnd_1', 'approve-pr', 'https://github.com/acme/web/pull/7', 'Approve the PR.', NULL, '{}', 'plugin', 'open', NULL, 1900, NULL)`); for (const sql of CHAIN_MIGRATIONS) db.exec(sql); for (const sql of LESSON_COUNTER_MIGRATIONS) db.exec(sql); + for (const sql of WORKER_CHECK_MIGRATIONS) db.exec(sql); let now = 2000; return { db, s: createStore(db, () => now) }; } diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index b9ec37b8..9b7342bc 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -335,7 +335,14 @@ export const LESSON_COUNTER_MIGRATIONS = [ `ALTER TABLE escalations ADD COLUMN corrections_counted INTEGER NOT NULL DEFAULT 0`, ]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS]; +export const WORKER_CHECK_MIGRATIONS = [ + // 1 while a worker's model and reasoning level are still to be checked: + // its first turn had not been dispatched when it was created, so the check + // waits for it to go active, and must survive a server restart in between. + `ALTER TABLE workers ADD COLUMN model_check_pending INTEGER NOT NULL DEFAULT 0`, +]; + +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -752,7 +759,7 @@ export type Lesson = { }; export type WorkerStatus = "running" | "finished" | "failed" | "stopped"; -export type Worker = { threadId: string; bindingId: string; title: string; status: WorkerStatus; result: string | null; startedAt: number; endedAt: number | null }; +export type Worker = { threadId: string; bindingId: string; title: string; status: WorkerStatus; result: string | null; startedAt: number; endedAt: number | null; modelCheckPending: boolean }; /** The requester thread the plugin spawned for an open provide-secret need (BB-22). */ export type SecretRequester = { threadId: string; needId: string; createdAt: number }; @@ -845,6 +852,7 @@ export function createStore(db: Database.Database, now: () => number) { const workersFor = db.prepare<[string], Record>("SELECT * FROM workers WHERE binding_id = ? ORDER BY started_at"); const spawnsSince = db.prepare<[string, number], { n: number }>("SELECT COUNT(*) AS n FROM workers WHERE binding_id = ? AND started_at >= ?"); const setWorker = db.prepare("UPDATE workers SET status = ?, result = ?, ended_at = ? WHERE thread_id = ?"); + const setWorkerModelCheckPending = db.prepare("UPDATE workers SET model_check_pending = ? WHERE thread_id = ?"); const insertSecretRequester = db.prepare("INSERT OR REPLACE INTO secret_requesters (thread_id, need_id, created_at) VALUES (?, ?, ?)"); const getSecretRequester = db.prepare<[string], Record>("SELECT * FROM secret_requesters WHERE thread_id = ?"); const getSecretRequesterForNeed = db.prepare<[string], Record>("SELECT * FROM secret_requesters WHERE need_id = ? ORDER BY created_at DESC LIMIT 1"); @@ -980,6 +988,7 @@ export function createStore(db: Database.Database, now: () => number) { result: r.result === null ? null : String(r.result), startedAt: Number(r.started_at), endedAt: r.ended_at === null ? null : Number(r.ended_at), + modelCheckPending: Number(r.model_check_pending ?? 0) === 1, }); const toSecretRequester = (r: Record): SecretRequester => ({ threadId: String(r.thread_id), @@ -1447,6 +1456,10 @@ export function createStore(db: Database.Database, now: () => number) { setWorker(threadId: string, status: WorkerStatus, result: string | null): void { setWorker.run(status, result, status === "running" ? null : now(), threadId); }, + /** Whether the worker's model is still to be checked when its first turn is dispatched. */ + setWorkerModelCheckPending(threadId: string, pending: boolean): void { + setWorkerModelCheckPending.run(pending ? 1 : 0, threadId); + }, // provide-secret requester threads (BB-22) setSecretRequester(threadId: string, needId: string): void { diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index 03662f29..2dd9fe17 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -102,7 +102,7 @@ describe("a steward's wake", () => { it("names a worker's question ahead of every other change, with how to answer", () => { const wake = formatWake( wakeInput({ - workers: [{ threadId: "thr_w1", bindingId: "b1", title: "Implement", status: "finished", result: "Should I bring the reviewer back?", startedAt: T, endedAt: T }], + workers: [{ threadId: "thr_w1", bindingId: "b1", title: "Implement", status: "finished", result: "Should I bring the reviewer back?", startedAt: T, endedAt: T, modelCheckPending: false }], workerQuestions: [{ threadId: "thr_w1", question: "Should I bring the reviewer back?", state: "live" }], changes: ["1 new comment from Sam"], }),