diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 265fc034..eb0578c3 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -459,8 +459,11 @@ Plugin code. No model turn. `review` stages (In Progress ↔ In Review) is the worker's own loop, a quiet note; a move to any other stage, or a terminal state, still wakes. A worker's turn ending is a quiet note unless its final message asks a - question, reports an error, or its thread is gone (a binding following - through still hears the worker, since it waits on that result). And a + question or its thread is gone (a binding following through still hears + the worker, since it waits on that result). BB-329: a worker says it is + waiting with the `worker_park` tool, not with prose; a finish without that + call is a plain finish, archived like any other, whatever its final text + says. And a terminal state the steward's own last report already named ends the binding from the mechanical tier, with the wrap-up written from that report and no wrap-up wake; a terminal state someone else set still wakes. @@ -478,8 +481,8 @@ Plugin code. No model turn. grace. A worker finish that leaves such a binding is loud at once, without the grace, because the worker's final message is what the steward must read; a finish that leaves an open pull - request, a pending deployment or a message that says it is waiting stays - quiet as before. The wake fires once per idle period, not once per grace: a + request, a pending deployment or a worker that parked with `worker_park` + stays quiet as before. The wake fires once per idle period, not once per grace: a worker ending, an own pull request closing or a deployment watch changing starts a new period, and a steward that waits on something the plugin cannot observe is not woken every fifteen minutes. `idleInActiveStage` in diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 0b698075..c1178a37 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -96,7 +96,7 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. that to the worker's own pull request — its head branch is one of the binding's worker threads' branches, or a worker named its URL — and quiets three more causes: a state move between the build and review stages, a - worker turn ending to wait (only a question, an error report or a gone + worker turn ending parked with `worker_park` (only a question or a gone thread wakes), and a terminal state the steward's own last report already named (the binding ends from the mechanical tier). A foreign pull request wakes on its link and keeps its activity actionable. Everything not diff --git a/plugins/stewards/assessment.test.ts b/plugins/stewards/assessment.test.ts index 51416b74..da3ec07c 100644 --- a/plugins/stewards/assessment.test.ts +++ b/plugins/stewards/assessment.test.ts @@ -143,6 +143,15 @@ describe("the shadow assessment: the worker state (BB-266)", () => { expect(assess(input({ workers: [{ ...parkedWorker(), status: "failed" }] })).worker.state).toBe("failed"); expect(assess(input({ workers: [{ ...parkedWorker(), status: "stopped" }] })).worker.state).toBe("stopped"); }); + + // BB-329: `parked` is driven by the worker's own `worker_park` call. A + // finished worker that did not park is a plain finish, whatever its text. + it("names a finished worker that did not call worker_park `finished`, not `parked`", () => { + const plain = assess(input({ workers: [{ ...parkedWorker(), parkedWaitingOn: null, result: "Waiting on the owner's approval of acme/web#7." }] })).worker; + expect(plain).toMatchObject({ state: "finished", parked: false, running: false }); + const parked = assess(input({ workers: [parkedWorker()] })).worker; + expect(parked).toMatchObject({ state: "parked", parked: true }); + }); }); describe("the shadow assessment: the merge gate inputs (BB-292 #2)", () => { diff --git a/plugins/stewards/assessment.ts b/plugins/stewards/assessment.ts index d8d95c9e..501a3266 100644 --- a/plugins/stewards/assessment.ts +++ b/plugins/stewards/assessment.ts @@ -41,12 +41,14 @@ export type AssessedGate = PrGate & { }; /** - * The binding's worker state. `parked` is a `finished` worker between turns: - * still in flight, not running, and the state the boolean predicates collapse - * to either "busy" (`workerInFlight`) or "not mid-turn" (`runningWorkerReason`). + * The binding's worker state. `parked` is explicit: a worker that called its + * own `worker_park` tool and finished its turn, so it is kept unarchived until + * its next turn clears the park. A `finished` worker that did not park is a + * plain finish. `inFlight` is still running-or-finished (the wake quieting and + * lifecycle answer) and `reason` is `runningWorkerReason`'s text. */ export type AssessedWorker = { - state: "running" | "parked" | "failed" | "stopped" | "none"; + state: "running" | "parked" | "finished" | "failed" | "stopped" | "none"; inFlight: boolean; running: boolean; parked: boolean; @@ -160,12 +162,17 @@ export function ownPullEntities(observed: Observed, own: ReadonlySet): E return [observed.entity, ...observed.pulls].filter((e) => e.pull !== null && isOwn(e, own)); } -/** The worker state, with a parked `finished` worker distinct from a running one. */ +/** + * The worker state. `parked` is driven by the worker's own `worker_park` call + * (BB-329): a `finished` worker that did not park is a plain finish, whatever + * its final text says, and is named `finished` rather than `parked`. + */ export function assessWorker(workers: readonly Worker[]): AssessedWorker { const running = workers.some((w) => w.status === "running"); - const parked = !running && workers.some((w) => w.status === "finished"); - const failed = !running && !parked && workers.some((w) => w.status === "failed"); - const state: AssessedWorker["state"] = running ? "running" : parked ? "parked" : workers.length === 0 ? "none" : failed ? "failed" : "stopped"; + const finished = !running && workers.some((w) => w.status === "finished"); + const parked = !running && workers.some((w) => w.status === "finished" && w.parkedWaitingOn !== null); + const failed = !running && !finished && workers.some((w) => w.status === "failed"); + const state: AssessedWorker["state"] = running ? "running" : parked ? "parked" : workers.length === 0 ? "none" : finished ? "finished" : failed ? "failed" : "stopped"; return { state, inFlight: anyWorkerInFlight(workers), running, parked, reason: runningWorkerReason(workers) }; } diff --git a/plugins/stewards/characterization.test.ts b/plugins/stewards/characterization.test.ts index 20178148..a4760421 100644 --- a/plugins/stewards/characterization.test.ts +++ b/plugins/stewards/characterization.test.ts @@ -36,7 +36,6 @@ import { isBusy } from "./sidebar.js"; import { readyStateSchema, type Worker } from "./store.js"; import { LINEAR_TICKETS } from "./templates.js"; import { hasLiveWakeSource, pullWatchCounts, type WakeSourceInput } from "./wake-source.js"; -import { workerReportedError, workerWaiting } from "./wake.js"; const tickets: Playbook = (() => { const p = parsePlaybook(LINEAR_TICKETS, "linear-tickets"); @@ -189,24 +188,6 @@ describe("the worker-busy predicates: workerInFlight vs runningWorkerReason", () expect(["idle", "finished", "failed"].some(isBusy)).toBe(false); }); - it("pins WAITING: workerWaiting fires on waiting/awaits/awaiting/parked/standing by", () => { - expect(workerWaiting("Waiting on the reviewer.")).toBe(true); - expect(workerWaiting("It awaits the owner's approval.")).toBe(true); - expect(workerWaiting("Parked until the build lands.")).toBe(true); - expect(workerWaiting("Standing by.")).toBe(true); - expect(workerWaiting("Done and verified.")).toBe(false); - expect(workerWaiting(null)).toBe(false); - }); - - it("pins ERROR_REPORT: workerReportedError fires on a line-leading error marker, not a mention", () => { - expect(workerReportedError("Error: the build refused the push")).toBe(true); - expect(workerReportedError("Unable to reach GitHub")).toBe(true); - expect(workerReportedError("I could not merge it")).toBe(true); - expect(workerReportedError("Fixed the error: the retry now backs off")).toBe(false); - expect(workerReportedError("No errors here.")).toBe(false); - expect(workerReportedError(null)).toBe(false); - }); - it("pins unheardWait: a wait on the project steward or the user with no open escalation or need", () => { const status = (waitingOn: string | null) => ({ phase: "In Progress", summary: "s", nextAction: "n", actor: "other" as const, waitingOn, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at: 1 }); expect(unheardWait(status("the project steward's approval of the new spec"), [])).toMatch(/project steward/u); diff --git a/plugins/stewards/fixtures.ts b/plugins/stewards/fixtures.ts index 9a8d498e..89ff349e 100644 --- a/plugins/stewards/fixtures.ts +++ b/plugins/stewards/fixtures.ts @@ -98,7 +98,8 @@ export const comment = (over: Partial = {}): SnapshotComment => /** * A worker that has parked at the end of its turn, waiting on something that * will wake it (the build-tickets merge gate, a review round). `finished` is - * the parked status, so it is still in flight for delivery (BB-279). + * the parked status and `parkedWaitingOn` is the explicit `worker_park` call + * (BB-329), so it is still in flight for delivery (BB-279). */ export const parkedWorker = (over: Partial = {}): Worker => ({ threadId: "thr_worker", @@ -110,6 +111,7 @@ export const parkedWorker = (over: Partial = {}): Worker => ({ endedAt: 2, modelCheckPending: false, stopReason: null, + parkedWaitingOn: "the review", ...over, }); diff --git a/plugins/stewards/migrations.snapshot.json b/plugins/stewards/migrations.snapshot.json index d4e37f72..5e173a72 100644 --- a/plugins/stewards/migrations.snapshot.json +++ b/plugins/stewards/migrations.snapshot.json @@ -133,5 +133,6 @@ "3f683f67336499cdca7460d9106a2ab9f91a74e028a6f359e4ebb29a16bb8163", "dac7694ca870936e15df9f4c6837973e8d1191b271743b386b1db36427577937", "8a61e3594b695ff3b5f2f58573155bd59f7209142643e4f212fe3485a4ae80f9", - "c7dcc1c8ee819162947a9965a7fb0cb7129900a4d68f5f7f91a99184a225dea9" + "c7dcc1c8ee819162947a9965a7fb0cb7129900a4d68f5f7f91a99184a225dea9", + "ad2a7b244faee5792ca77b1f36cd80488de8f787360d03f1569e60c869845beb" ] diff --git a/plugins/stewards/read-counts.test.ts b/plugins/stewards/read-counts.test.ts index dfe22bf7..96d22deb 100644 --- a/plugins/stewards/read-counts.test.ts +++ b/plugins/stewards/read-counts.test.ts @@ -128,6 +128,9 @@ describe("a reconcile pass over a fixed binding set (BB-297)", () => { t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", state: "open" }, { head: "bb/eng-12-retry" })); t.hooks.store.addWorker("thr_w1", b1.id, "ENG-12: implement"); t.hooks.store.setWorker("thr_w1", "finished", "Watching acme/web#7 and acme/web#8 for the review."); + // BB-329: the parked worker is explicit (its own `worker_park` call), so + // the merge gate treats it as owning the landing order. + t.hooks.store.parkWorker("thr_w1", "the review"); // Binding 2: a deployment watch. The merged own pull request opens the // watch and the look reads GitHub for its deployment. @@ -174,7 +177,10 @@ describe("a reconcile pass over a fixed binding set (BB-297)", () => { // pull requests (web#7, web#8, web#9), two store reads each, and // `syncPullApproval` reads the remembered set once per pull to forget a // requester the owner withdrew without a review. - expect(reconcile).toEqual({ storeReads: 194, sourceCalls: 12, reconciles: 4, bindings: 4 }); + // BB-329 lowered them 194 → 193: the merge gate's `parkedWorkerOwnsAnother` + // now reads the parked state from the one assessment the reconcile already + // built, instead of calling `store.workers(b.id)` a second time. + expect(reconcile).toEqual({ storeReads: 193, sourceCalls: 12, reconciles: 4, bindings: 4 }); expect(wake).toEqual({ storeReads: 15, sourceCalls: 0, wakes: 1 }); }); diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 4949c06b..fd761a56 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -237,7 +237,7 @@ describe("a Linear ticket steward", () => { await expect(t.harness.callRpc("stewardsRing", { source: "linear", id: "u1" }, { experimental_caller: { kind: "plugin", pluginId: "github-watcher" } })).rejects.toThrow(/each for its own source/u); }); - it("wakes only for actionable changes, and gives two tools to stewards only", async () => { + it("wakes only for actionable changes, and gives the steward tools and a worker only worker_park", async () => { const t = await setup(); t.entities.set("uuid-12", issue()); await t.ring("linear", "uuid-12"); @@ -247,6 +247,9 @@ describe("a Linear ticket steward", () => { expect(await tools(steward!)).toEqual(["steward_report", "steward_update"]); expect(await tools(project!)).toEqual(["steward_update"]); expect(await tools("thr_other")).toEqual([]); + // BB-329: a worker gets exactly one plugin tool, its own park call. + await t.created("thr_w1", steward!, "ENG-12: Implement"); + expect(await tools("thr_w1")).toEqual(["worker_park"]); const report = await t.tool("steward_report", { phase: "Todo", summary: "Specifying.", nextAction: "Post acceptance criteria", actor: "steward", requeueAfter: "1d" }, steward!); expect(report.error).toBe(false); @@ -848,12 +851,14 @@ describe("a Linear ticket steward", () => { await t.created("thr_w1", steward, "ENG-12: Implement"); expect(t.sends).toEqual([]); - // BB-52 rule 3: a worker ending its turn waiting is a quiet note, not a wake. + // BB-329: the worker parks with the tool; its final text alone does not. + await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1"); + // BB-52 rule 3: a worker ending its turn parked is a quiet note, not a wake. await t.idle("thr_w1", "Opened acme/web#7; waiting on the reviewer."); expect(t.sends).toEqual([]); - // BB-152: the finish note carries the worker's final message. + // BB-152/BB-329: the finish note names the park and carries the final message. expect(t.hooks.store.open("p1")[0]!.pending).toMatchObject([{ quiet: true }]); - expect(t.hooks.store.open("p1")[0]!.pending[0]!.text).toBe('Worker "ENG-12: Implement" finished its turn. Its final message: Opened acme/web#7; waiting on the reviewer.'); + expect(t.hooks.store.open("p1")[0]!.pending[0]!.text).toBe('Worker "ENG-12: Implement" finished its turn. It parked, waiting on the reviewer. Its final message: Opened acme/web#7; waiting on the reviewer.'); // A question wakes it, with the worker's words. await t.idle("thr_w1", "Should I bring the reviewer back once it finishes?"); @@ -862,28 +867,65 @@ describe("a Linear ticket steward", () => { expect(wake).toMatch(/Should I bring the reviewer back once it finishes\?/u); }); - it("wakes when a worker ends its turn with an error report, and lists a quiet finish in bb stewards show", async () => { + it("keeps a parked finish quiet and treats a plain finish as done, whatever its text (BB-329)", 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; - // A waiting finish is kept as a quiet note, and show lists it with the next wake. + // A parked finish is a quiet note, and show lists it with the next wake. await t.created("thr_w1", steward, "ENG-12: Implement"); + await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1"); await t.idle("thr_w1", "Waiting on the reviewer."); const show = (await t.harness.behavior.runCli(["show", "ENG-12", "--project", "p1"])).stdout; expect(show).toMatch(/Pending \(quiet\): Worker "ENG-12: Implement" finished its turn\./u); - // An error report is not waiting: it wakes the steward. - const sent = t.sends.length; - await t.idle("thr_w1", "Error: the provider timed out before I could push."); - expect(t.sends).toHaveLength(sent + 1); - expect(t.sends.at(-1)!.text).toMatch(/Worker "ENG-12: Implement" finished its turn/u); + // BB-329 retires the error-report regex: a plain finish that says "Error:" + // is a plain finish, not a park, whatever its text. The worker did not + // call worker_park, so the finish note is a plain one (no "It parked"); a + // hard failure still comes through thread.failed. + t.hooks.store.patch(t.hooks.store.find("ENG-12", "p1")!.id, { pending: [] }); + await t.created("thr_w2", steward, "ENG-12: Implement 2"); + await t.idle("thr_w2", "Error: the provider timed out before I could push."); + const wake = t.sends.at(-1)!.text; + expect(wake).toMatch(/Error: the provider timed out/u); + expect(wake).not.toMatch(/It parked, waiting on/u); + expect(t.hooks.store.worker("thr_w2")!.parkedWaitingOn).toBeNull(); + }); - // A line that merely names an error count is not an error report. - const afterError = t.sends.length; - await t.idle("thr_w1", "Errors: 0. Failed tests: none."); - expect(t.sends).toHaveLength(afterError); + it("worker_park sets the calling worker's own state, refuses a non-worker or an ended binding, and the next turn clears it (BB-329)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.created("thr_w1", steward, "ENG-12: Implement"); + const b = t.hooks.store.find("ENG-12", "p1")!; + + // A non-worker thread is refused, never a silent no-op. + const refused = await t.tool("worker_park", { waitingOn: "the reviewer" }, steward); + expect(refused.error).toBe(true); + expect(refused.text).toMatch(/not a worker/u); + + // The worker's own park: it files nothing for the user and meets no gate. + const needsBefore = t.hooks.store.openNeeds(b.id).length; + const escalationsBefore = t.hooks.store.openEscalations(b.id).length; + expect((await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1")).error).toBe(false); + expect(t.hooks.store.worker("thr_w1")!.parkedWaitingOn).toBe("the reviewer"); + expect(t.hooks.store.openNeeds(b.id)).toHaveLength(needsBefore); + expect(t.hooks.store.openEscalations(b.id)).toHaveLength(escalationsBefore); + + // The worker's next turn clears the park. + await t.idle("thr_w1", "Waiting on the reviewer."); + expect(t.hooks.store.worker("thr_w1")).toMatchObject({ status: "finished", parkedWaitingOn: "the reviewer" }); + await t.harness.behavior.emitThreadEvent("thread.active", { thread: makeThreadResponse({ id: "thr_w1" }) }); + expect(t.hooks.store.worker("thr_w1")!.parkedWaitingOn).toBeNull(); + + // An ended binding is refused. + await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1"); + t.hooks.store.patch(b.id, { endedAt: t.now(), endReason: "done" }); + const ended = await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1"); + expect(ended.error).toBe(true); + expect(ended.text).toMatch(/has ended/u); }); // BB-72: a worker is normally a child of its steward, but a worker spawned @@ -6692,9 +6734,12 @@ describe("needs you items", () => { * gate-met tests run this variant so a parked worker is exercised, not only * a running one. */ - function parkWorker(t: { hooks: { store: { setWorker: (threadId: string, status: "finished", result: string | null) => void } } }, threadId: string, over: Partial> = {}): ReturnType { + function parkWorker(t: { hooks: { store: { setWorker: (threadId: string, status: "finished", result: string | null) => void; parkWorker: (threadId: string, waitingOn: string) => void } } }, threadId: string, over: Partial> = {}): ReturnType { const w = parkedWorker({ threadId, ...over }); t.hooks.store.setWorker(w.threadId, "finished", w.result); + // BB-329: `finished` alone is a plain finish; the explicit park is what + // keeps the worker unarchived. + t.hooks.store.parkWorker(w.threadId, w.parkedWaitingOn ?? "the review"); return w; } @@ -7142,6 +7187,7 @@ describe("needs you items", () => { const parked = await withPull([marker]); await parked.created("thr_w1", parked.steward, "ENG-12: Implement"); parked.hooks.store.setWorker("thr_w1", "finished", "Waiting on the owner's approval."); + parked.hooks.store.parkWorker("thr_w1", "the owner's approval"); parked.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); await parked.ring("linear", "uuid-12"); expect(parked.githubMerges).toHaveLength(1); @@ -7151,6 +7197,7 @@ describe("needs you items", () => { const rereport = await withPull([marker]); await rereport.created("thr_w1", rereport.steward, "ENG-12: Implement"); rereport.hooks.store.setWorker("thr_w1", "finished", "Waiting on the owner's approval."); + rereport.hooks.store.parkWorker("thr_w1", "the owner's approval"); rereport.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); await rereport.tool("steward_report", { phase: "In Progress", summary: "Watching the pull request.", nextAction: "Wait", actor: "steward" }, rereport.steward); expect(rereport.githubMerges).toHaveLength(1); @@ -7171,6 +7218,7 @@ describe("needs you items", () => { const b = t.binding(); await t.created("thr_parked", t.steward, "ENG-12: Implement"); t.hooks.store.setWorker("thr_parked", "finished", "Waiting on the owner's approval."); + t.hooks.store.parkWorker("thr_parked", "the owner's approval"); // A finished worker's turn is over: its thread is idle, not active. t.threads.get("thr_parked")!.status = "idle"; // A finished worker with an open question for the steward is left alone. @@ -7234,6 +7282,44 @@ describe("needs you items", () => { expect(t.threads.get("thr_w1")!.archivedAt).not.toBeNull(); }); + it("a plain finish, whatever its text, does not own the landing order: it is archived and the plugin merges (BB-329)", async () => { + const t = await setup(); + const noReview = comment({ id: "nr", author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); + t.entities.set("uuid-12", issue({ linkedPulls: [ + { key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }, + { key: "acme/api#8", url: "https://github.com/acme/api/pull/8" }, + ] })); + t.entities.set("acme/web#7", pull({ comments: [noReview] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + t.entities.set("acme/api#8", pull({ id: "acme/api#8", key: "acme/api#8", url: "https://github.com/acme/api/pull/8", title: "Add api retry (ENG-12)" }, { head: "bb/eng-12-api", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.created("thr_w1", steward, "ENG-12: Implement both"); + // The final text says it is waiting, but the worker did not call + // worker_park. #7 is gate-met and #8 is open, so only an explicit park + // would defer the merge. + await t.idle("thr_w1", "Waiting on the owner's approval of acme/web#7 and acme/api#8."); + await t.flush(); + // A plain finish is done: the plugin archives it, so its pull-request + // activity is no longer quieted by it, and merges #7 out of order. + expect(t.threads.get("thr_w1")!.archivedAt).not.toBeNull(); + expect(t.githubMerges).toHaveLength(1); + expect(t.githubMerges[0]).toMatchObject({ repo: "acme/web", number: 7 }); + }); + + it("a worker that calls worker_park stays unarchived even when its final text does not say it waits (BB-329)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; + await t.created("thr_w1", steward, "ENG-12: Implement"); + // The explicit park keeps it, though the old WAITING regex would have + // archived this final message. + await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1"); + await t.idle("thr_w1", "Done and verified."); + expect(t.threads.get("thr_w1")!.archivedAt).toBeNull(); + expect(t.hooks.store.worker("thr_w1")).toMatchObject({ status: "finished", parkedWaitingOn: "the reviewer" }); + }); + it("a gate-met no-review pull request with a parked worker wakes it naming the gate, not an approver (BB-279)", async () => { const t = await setup(); const noReview = comment({ id: "m1", author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); @@ -7600,6 +7686,7 @@ describe("needs you items", () => { t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); await t.ring("linear", "uuid-12"); await t.created("thr_w1", t.steward, "ENG-12: Implement"); + await t.tool("worker_park", { waitingOn: "the owner's approval" }, "thr_w1"); await t.idle("thr_w1", "Waiting on the owner's approval."); const before = t.sends.filter((s) => s.threadId === "thr_w1").length; const b = t.binding(); @@ -7638,6 +7725,7 @@ describe("needs you items", () => { t.githubFiles.set("acme/web#7", ["bb-gate/docs/hooks.md"]); await t.ring("linear", "uuid-12"); await t.created("thr_w1", t.steward, "ENG-12: Implement"); + await t.tool("worker_park", { waitingOn: "the project steward's decision" }, "thr_w1"); await t.idle("thr_w1", "Waiting on the project steward."); const b = t.binding(); const esc = t.hooks.store.openEscalations(b.id).find((x) => x.kind === "approval" && x.resolutionKind === "approve-decline")!; @@ -13004,7 +13092,8 @@ describe("a steward idle in an active stage (BB-83)", () => { await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; await t.created("thr_w1", steward, "ENG-12: Implement"); - // A waiting finish is quiet now; the idle rule catches it after the grace. + // A parked finish is quiet now; the idle rule catches it after the grace. + await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1"); await t.idle("thr_w1", "Waiting on the reviewer."); const before = t.sends.length; @@ -13040,6 +13129,7 @@ describe("a steward idle in an active stage (BB-83)", () => { await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; await t.created("thr_w1", steward, "ENG-12: Implement"); + await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1"); await t.idle("thr_w1", "Waiting on the reviewer."); const before = t.sends.length; t.advance(16 * 60_000); @@ -13060,6 +13150,7 @@ describe("a steward idle in an active stage (BB-83)", () => { await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; await t.created("thr_w1", steward, "ENG-12: Implement"); + await t.tool("worker_park", { waitingOn: "the vendor's decision" }, "thr_w1"); await t.idle("thr_w1", "Waiting on the vendor."); await t.tool("steward_report", { phase: "In Progress", summary: "Waiting.", nextAction: "Wait", actor: "other", waitingOn: "the vendor's decision", until: "2026-12-01" }, steward); const before = t.sends.length; @@ -13084,6 +13175,7 @@ describe("a steward idle in an active stage (BB-83)", () => { await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; await t.created("thr_w1", steward, "ENG-12: Implement"); + await t.tool("worker_park", { waitingOn: "the reviewer" }, "thr_w1"); await t.idle("thr_w1", "Waiting on the reviewer."); const before = t.sends.length; t.advance(16 * 60_000); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index aaea25c7..e52f0c9a 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -139,7 +139,7 @@ import { advanceStall, parseUntil, pullWatchCounts, type WakeSourceInput } from import { PROJECT_CHANGED } from "./channels.js"; import { LINEAR_TICKETS, PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; import type { DeploymentTarget } from "./config.js"; -import { PROJECT_STEWARD_INTRO, bindingMayMerge, choicesNote, formatAlertmanagerWake, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerFinishNote, workerQuestion, workerReportedError, workerWaiting, workflowRunLine, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, bindingMayMerge, choicesNote, formatAlertmanagerWake, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerFinishNote, workerQuestion, workflowRunLine, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; import { KNOWN_PLAYBOOKS, buildSurvey, formatSurvey, surveyWantedPaths, type Available, type SurveyBb, type SurveyLinear, type SurveyRepoInput, type SurveyReport } from "./survey.js"; export { MULTI_REPO_ENVIRONMENT_PROVIDER_ID, MULTI_REPO_PLUGIN_ID }; @@ -3806,7 +3806,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P async function archiveFinishedWorkers(b: Binding): Promise { const { questions, openIds } = needsUserInputs(b.projectId); if (needsUser(b, questions, openIds)) return; - await archiveWorkers(store.workers(b.id).filter((w) => w.status === "finished" && workerQuestion(w.result) === null && !workerWaiting(w.result))); + // BB-329: a plain finish (no `worker_park`) is done and archived; a + // parked worker is kept for its next turn, however its final text reads. + await archiveWorkers(store.workers(b.id).filter((w) => w.status === "finished" && w.parkedWaitingOn === null && workerQuestion(w.result) === null)); } /** @@ -3817,7 +3819,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * need nobody: the merge has settled their reason to stay. */ async function archiveParkedWorkers(b: Binding): Promise { - await archiveWorkers(store.workers(b.id).filter((w) => w.status === "finished" && workerQuestion(w.result) === null)); + await archiveWorkers(store.workers(b.id).filter((w) => w.status === "finished" && w.parkedWaitingOn !== null && workerQuestion(w.result) === null)); } /** @@ -8196,13 +8198,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // cross-repo ticket lands the consumed repo first), so the plugin must // not merge out of order or retire the worker that owns the rest. const openOwnPulls = observedPulls(b, observed).filter((p) => (ownPulls === null || pullBelongsToTicket(b, p, ownPulls)) && p.pull?.merged !== true && lc(p.state) !== "closed"); - // BB-329: left inline for the behaviour PR, not routed through `assessWorker`. - // `assessWorker(…).parked` is `!running && some(finished)`, while this - // captures `some(finished)` before the loop's awaits; a running worker that - // ends its turn inside that window would flip the answer, which is a merge - // path behaviour change. The explicit `parked` state in the behaviour PR - // reshapes it. - const parkedWorkerOwnsAnother = openOwnPulls.length > 1 && store.workers(b.id).some((w) => w.status === "finished"); + // BB-329: only a worker that called `worker_park` is parked; a plain + // finish is done and does not own the landing order. The explicit park + // does not change during this look (a worker parks in its own turn, not + // the reconcile's awaits), so reading it from the assessment the + // reconcile already built is safe and saves the second `store.workers` + // read the refactor left inline. + const parkedWorkerOwnsAnother = openOwnPulls.length > 1 && (assessment?.worker.parked ?? assessWorker(store.workers(b.id)).parked); // BB-264: the steward's own merge holds name open bindings in this // project, or a stacked base pull request by its key; the plugin's // derived stacked-PR holds are recomputed from the base pull requests on @@ -8707,14 +8709,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // happened and does it itself or escalates, never re-waiting on a // worker that is over. const waitedOn = finished !== null && waitingOnNamesWorker(finished.status?.waitingOn ?? null, worker); - // BB-52 rule 3: a worker that ends its turn waiting on its reviewer, - // the owner or a build is a quiet note. Only a question, an error - // report, a gone thread or a lost hand-off makes the turn due; a - // failed turn comes through thread.failed and wakes on its own. A - // binding following through is waiting on this worker's result, so its - // finish is news. - const needsSteward = finished !== null && (workerQuestion(result) !== null || workerReportedError(result) || followingThrough(finished) || waitedOn); - if (finished !== null && finished.endedAt === null) store.note(finished.id, workerFinishNote(worker.title, result, waitedOn), !needsSteward); + // BB-329: the park is the worker's own `worker_park` call, never a + // regex on its final text. A plain finish is done; a parked one is + // kept unarchived for its next turn. + const parked = worker.parkedWaitingOn !== null; + // BB-52 rule 3: a worker that ends its turn parked on its reviewer, + // the owner or a build is a quiet note. Only a question, a gone thread + // or a lost hand-off makes the turn due; a failed turn comes through + // thread.failed and wakes on its own. A binding following through is + // waiting on this worker's result, so its finish is news. BB-329: a + // final message that merely says "error" is a plain finish. + const needsSteward = finished !== null && (workerQuestion(result) !== null || followingThrough(finished) || waitedOn); + if (finished !== null && finished.endedAt === null) store.note(finished.id, workerFinishNote(worker.title, result, waitedOn, worker.parkedWaitingOn), !needsSteward); await closeRequesterNeed(thread.id); // Its turn is over: the reviewers it read (or started and then waited // on) have had their round consumed (BB-47). @@ -8724,14 +8730,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // A quiet finish is consumed here, not by a wake: archive the worker // now (BB-47), keeping one that still has a question, a reviewer, or is // parked waiting on something that will wake it (BB-52 rule 3). - if (!needsSteward && !workerWaiting(result)) await archiveFinishedWorkers(b); + if (!needsSteward && !parked) await archiveFinishedWorkers(b); // BB-83: a worker finish asks the idle rule to look at once, without // the grace, since its final message is what the steward needs to read. - // A message that says it is waiting stays quiet as before; the idle - // rule still catches it after the grace if nothing else does. The - // reconcile evaluates the predicate on the fresh snapshot and clears - // this again when the binding is not idle in an active stage. - if (!workerWaiting(result)) store.patch(b.id, { idleWakeNow: true }); + // A parked worker stays quiet as before; the idle rule still catches + // it after the grace if nothing else does. The reconcile evaluates the + // predicate on the fresh snapshot and clears this again when the + // binding is not idle in an active stage. + if (!parked) store.patch(b.id, { idleWakeNow: true }); scheduleReconcile(b.id); return; } @@ -10739,7 +10745,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // plugin set at spawn, before any binding lookup. if (context.pluginMetadata.role === "onboarding") return { tools: [], skills: ["onboarding"], instructions: ONBOARDING_INTRO }; const role = roleOf(context.thread.id); - if (role === null) return { tools: [], skills: ["stewards"] }; + if (role === null) { + // BB-329: a worker gets exactly one plugin tool, `worker_park`, so it + // can say it ended its turn waiting. A recorded worker, or a freshly + // spawned child of a steward whose `thread.created` record has not + // landed yet, counts; the tool itself refuses anything else. + const worker = store.worker(context.thread.id) !== null; + const parent = context.thread.parentThreadId !== null && store.byThread(context.thread.parentThreadId) !== null; + return worker || parent ? { tools: ["worker_park"], skills: ["stewards"] } : { tools: [], skills: ["stewards"] }; + } if (role.kind === "project") { return { tools: ["steward_update"], @@ -10987,6 +11001,31 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); } + /** + * BB-329: the worker's own park. One additive argument: the worker says + * what it ended its turn waiting on, and the plugin keeps its row + * unarchived and names it `parked` in the assessment. It files nothing for + * the user and meets no gate; the worker's next turn clears it. A + * non-worker thread or an ended binding is refused, never a silent no-op. + */ + bb.agents.registerTool({ + name: "worker_park", + description: + "End a worker's turn parked on something outside it: a reviewer's round, the approver, checks, a build, a deployment, the steward's answer. The plugin leaves this worker unarchived and wakes it when the thing you wait on happens. Call it as your last action before ending a turn you are not finishing; a turn that ends without it is a plain finish and the plugin treats the worker as done.", + presentation: { label: { pending: "Parking", completed: "Parked" } }, + parameters: z.object({ + waitingOn: z.string().trim().min(1).max(300).describe("What the turn waits on: a reviewer's round, the owner's approval, checks, a build, a deployment, the steward. Free text, shown on the finish note."), + }), + execute: store.coalescingTool(async (input, { threadId }) => { + const worker = store.worker(threadId); + if (worker === null) return toolError(new Error("worker_park is for a worker thread. This thread is not a worker of an open binding; a steward reports with steward_report.")); + const b = store.binding(worker.bindingId); + if (b === null || b.endedAt !== null) return toolError(new Error(`${b?.entityKey ?? "This worker's binding"} has ended; there is nothing to park.`)); + store.parkWorker(threadId, input.waitingOn); + return `Parked, waiting on ${input.waitingOn}. End the turn now; the plugin keeps this worker unarchived and wakes it when that happens.`; + }), + }); + bb.agents.registerTool({ name: "steward_report", description: diff --git a/plugins/stewards/skills/build-tickets/SKILL.md b/plugins/stewards/skills/build-tickets/SKILL.md index a1d8cf21..9ed95500 100644 --- a/plugins/stewards/skills/build-tickets/SKILL.md +++ b/plugins/stewards/skills/build-tickets/SKILL.md @@ -23,6 +23,15 @@ wait` by default). If that command is unavailable, comment the question on the ticket or pull request you were given and put it in your final message, then end the turn. +**Ending a turn to wait.** When you end a turn waiting on something that will +wake you — a reviewer's round, the approver, checks, a build, a deployment, +the steward's answer — call `worker_park { waitingOn: "" }` +as your last action. The plugin then leaves this worker unarchived, shows it +as parked, and wakes it when the thing happens. A turn that ends without the +call is a plain finish: the plugin treats the worker as done and archives it, +whatever its final message says. Do not rely on the words "waiting" or +"parked" in your final message. + The project-specific parts are the project's, not this skill's: which repos depend on which, each repo's test command, the restart note, the lane triggers and the decide list (`bigDecisions`), and the standing @@ -278,8 +287,9 @@ Bounds: stop the loop after **six rounds** or **48 hours** without a merge. Comment on the ticket what is still open and the PR URL, leave the ticket In Review, and stop. A human can prompt the thread to continue. -On an owner-reviewed PR, once the reviewer verdict is `approved`, end your -turn with the PR waiting on the approver the decide list named: the owner, +On an owner-reviewed PR, once the reviewer verdict is `approved`, park the +turn (`worker_park { waitingOn: "the approver's review" }`) and end it with the +PR waiting on the approver the decide list named: the owner, or the project steward when the matching entry is `decide: project`. When it is the owner's, the steward or a human wakes you when they review, and if 24 hours pass after the reviewer's approval with no human review, post @@ -398,8 +408,9 @@ the hand-off in your final message: the PR URL and number, the lane, the approved sha, that the merge was refused, and that the PR is ready to merge. The plugin delivers that final message to the steward, and a steward whose `waitingOn` names you is woken at once; it merges with the same command. -You do not merge it yourself later and you do not wait for the steward: end -the turn after the comment and the report. +You do not merge it yourself later and you do not wait for the steward: park +the turn (`worker_park { waitingOn: "the steward's merge" }`), then end it +after the comment and the report. Then stop the reviewer with `bb thread stop ` and **end your turn**. You do not watch the release: no `gh run list`, `gh run watch` or diff --git a/plugins/stewards/skills/pr-reviewer/SKILL.md b/plugins/stewards/skills/pr-reviewer/SKILL.md index 712971c0..fc6b64d1 100644 --- a/plugins/stewards/skills/pr-reviewer/SKILL.md +++ b/plugins/stewards/skills/pr-reviewer/SKILL.md @@ -454,3 +454,10 @@ After posting, end the turn with a one-line summary: round number, verdict, blocker count. The author reads the PR review, not your reply. If you are asked for a sixth round, review it, but add a line noting the loop is long and a human should look. + +A reviewer is not normally a worker: end the turn plainly. When the plugin +does track this thread as a worker (a review steward spawned you), call +`worker_park { waitingOn: "the author's next push" }` before ending, so the +plugin keeps the thread unarchived for the next round instead of archiving +it. An agent-authored PR's reviewer ends plainly; the author worker parks +its own turn with `worker_park` while it waits on your verdict. diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index dfb772a7..c5388cd8 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -1,7 +1,7 @@ import Database from "better-sqlite3"; import { describe, expect, it } from "vitest"; import { z } from "zod"; -import { ACTOR_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, HUDDLE_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS, ASSESSMENT_MIGRATIONS, ASSUMPTION_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, DATED_WAIT_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ENDED_READ_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_PR_MIGRATIONS, LESSON_TIER_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, MIGRATIONS, PULL_REQUESTER_MIGRATIONS, PULL_WATCH_MIGRATIONS, RATIONALE_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, STACK_MIGRATIONS, STACKED_PULLS_MIGRATIONS, VALIDATION_MIGRATIONS, WAKE_RETRY_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, WORKER_CHECK_MIGRATIONS, STANDUP_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, createStore, lessonScope, statusRecordSchema, type Binding } from "./store.js"; +import { ACTOR_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, HUDDLE_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS, ASSESSMENT_MIGRATIONS, ASSUMPTION_MIGRATIONS, BASE_MIGRATIONS, CHAIN_MIGRATIONS, DATED_WAIT_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ENDED_READ_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, GUIDANCE_MIGRATIONS, IDLE_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_PR_MIGRATIONS, LESSON_TIER_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, MIGRATIONS, PULL_REQUESTER_MIGRATIONS, PULL_WATCH_MIGRATIONS, RATIONALE_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, STACK_MIGRATIONS, STACKED_PULLS_MIGRATIONS, VALIDATION_MIGRATIONS, WAKE_RETRY_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, WORKER_CHECK_MIGRATIONS, STANDUP_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, WORKER_PARK_MIGRATIONS, createStore, lessonScope, statusRecordSchema, type Binding } from "./store.js"; /** MIGRATIONS without the groups appended after the ones these order tests assert. */ const beforeActorMigrations = MIGRATIONS.slice(0, MIGRATIONS.indexOf(ACTOR_MIGRATIONS[0]!)); @@ -740,9 +740,10 @@ describe("the actor rename migration (BB-97)", () => { // after that, its rename follows, BB-303 appended the scope column // after that, BB-307 appended the delegation log after that, BB-312 // appended the completed flag after that, BB-314 appended the - // Alertmanager look column after that, and BB-327 appended the delegate-set - // and reviewer-request tables after that. - const groups = [REVIEWER_REQUEST_MIGRATIONS, PULL_REQUESTER_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_MIGRATIONS, HUDDLE_MIGRATIONS, ENDED_READ_MIGRATIONS, ASSESSMENT_MIGRATIONS, STACKED_PULLS_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, WAKE_RETRY_MIGRATIONS, DATED_WAIT_MIGRATIONS, ASSUMPTION_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, STACK_MIGRATIONS, PULL_WATCH_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, LESSON_PR_MIGRATIONS, ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS]; + // Alertmanager look column after that, BB-327 appended the delegate-set + // and reviewer-request tables after that, and BB-329 appended the + // worker park column after that. + const groups = [WORKER_PARK_MIGRATIONS, REVIEWER_REQUEST_MIGRATIONS, PULL_REQUESTER_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, STANDUP_COMPLETED_MIGRATIONS, STANDUP_DELEGATION_MIGRATIONS, STANDUP_BINDING_MIGRATIONS, STANDUP_MIGRATIONS, HUDDLE_MIGRATIONS, ENDED_READ_MIGRATIONS, ASSESSMENT_MIGRATIONS, STACKED_PULLS_MIGRATIONS, RETARGET_PULLS_MIGRATIONS, MERGE_BEHIND_MIGRATIONS, WAKE_RETRY_MIGRATIONS, DATED_WAIT_MIGRATIONS, ASSUMPTION_MIGRATIONS, WORKER_STOP_REASON_MIGRATIONS, DEPS_DECISION_MIGRATIONS, ESCALATION_ROUTE_MIGRATIONS, STACK_MIGRATIONS, PULL_WATCH_MIGRATIONS, SERVER_SETTINGS_MIGRATIONS, WAKE_SOURCE_MIGRATIONS, REVIEWER_MODEL_MIGRATIONS, LESSON_PR_MIGRATIONS, ACTOR_MIGRATIONS, APPROVAL_MARKER_MIGRATIONS]; let end = MIGRATIONS.length; for (const group of groups) { expect(MIGRATIONS.slice(end - group.length, end)).toEqual([...group]); @@ -836,10 +837,13 @@ describe("the escalation route rename migration (BB-209)", () => { // ended-read index after that, BB-300 slice 4's huddle table after that, // its rename to the stand-up table after that, BB-303's scope column // after that, BB-307's delegation log after that, BB-312's completed - // flag after that, BB-314's Alertmanager look column after that, and - // BB-327's delegate-set and reviewer-request tables after that. - const withoutReviewerRequests = MIGRATIONS.slice(0, -REVIEWER_REQUEST_MIGRATIONS.length); - expect(MIGRATIONS.slice(-REVIEWER_REQUEST_MIGRATIONS.length)).toEqual([...REVIEWER_REQUEST_MIGRATIONS]); + // flag after that, BB-314's Alertmanager look column after that, + // BB-327's delegate-set and reviewer-request tables after that, and + // BB-329's worker park column after that. + const withoutWorkerPark = MIGRATIONS.slice(0, -WORKER_PARK_MIGRATIONS.length); + expect(MIGRATIONS.slice(-WORKER_PARK_MIGRATIONS.length)).toEqual([...WORKER_PARK_MIGRATIONS]); + const withoutReviewerRequests = withoutWorkerPark.slice(0, -REVIEWER_REQUEST_MIGRATIONS.length); + expect(withoutWorkerPark.slice(-REVIEWER_REQUEST_MIGRATIONS.length)).toEqual([...REVIEWER_REQUEST_MIGRATIONS]); const withoutPullRequesters = withoutReviewerRequests.slice(0, -PULL_REQUESTER_MIGRATIONS.length); expect(withoutReviewerRequests.slice(-PULL_REQUESTER_MIGRATIONS.length)).toEqual([...PULL_REQUESTER_MIGRATIONS]); const withoutAlertmanagerLook = withoutPullRequesters.slice(0, -ALERTMANAGER_LOOK_MIGRATIONS.length); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index adb5109e..1dd96940 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -565,6 +565,13 @@ export const DEPS_DECISION_MIGRATIONS = [ // archive case, and a pre-migration build never reads the column. export const WORKER_STOP_REASON_MIGRATIONS = [`ALTER TABLE workers ADD COLUMN stop_reason TEXT`]; +// BB-329: the worker's explicit parked state. `parked_waiting_on` is the +// `waitingOn` the worker's own `worker_park` tool call recorded; null is not +// parked. It is set only by that tool and cleared when the worker's next turn +// starts (`setWorker` to `running`). Additive and nullable: an old row reads +// as not parked, and a pre-migration build never reads the column. +export const WORKER_PARK_MIGRATIONS = [`ALTER TABLE workers ADD COLUMN parked_waiting_on TEXT`]; + // BB-251: a recorded assumption. A steward that proceeds under a question the // guidance does not settle records it here instead of asking (which blocks) or // deciding silently (which is invisible). It is not a user item: it files no @@ -726,7 +733,7 @@ export const STANDUP_COMPLETED_MIGRATIONS = [`ALTER TABLE standups ADD COLUMN co // a store from before the step reads back exactly as before. export const ALERTMANAGER_LOOK_MIGRATIONS = [`ALTER TABLE bindings ADD COLUMN alertmanager_look TEXT`]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS, ...ACTOR_MIGRATIONS, ...LESSON_PR_MIGRATIONS, ...REVIEWER_MODEL_MIGRATIONS, ...WAKE_SOURCE_MIGRATIONS, ...SERVER_SETTINGS_MIGRATIONS, ...PULL_WATCH_MIGRATIONS, ...STACK_MIGRATIONS, ...ESCALATION_ROUTE_MIGRATIONS, ...DEPS_DECISION_MIGRATIONS, ...WORKER_STOP_REASON_MIGRATIONS, ...ASSUMPTION_MIGRATIONS, ...DATED_WAIT_MIGRATIONS, ...WAKE_RETRY_MIGRATIONS, ...MERGE_BEHIND_MIGRATIONS, ...RETARGET_PULLS_MIGRATIONS, ...STACKED_PULLS_MIGRATIONS, ...ASSESSMENT_MIGRATIONS, ...ENDED_READ_MIGRATIONS, ...HUDDLE_MIGRATIONS, ...STANDUP_MIGRATIONS, ...STANDUP_BINDING_MIGRATIONS, ...STANDUP_DELEGATION_MIGRATIONS, ...STANDUP_COMPLETED_MIGRATIONS, ...ALERTMANAGER_LOOK_MIGRATIONS, ...PULL_REQUESTER_MIGRATIONS, ...REVIEWER_REQUEST_MIGRATIONS]; +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS, ...RATIONALE_MIGRATIONS, ...VALIDATION_MIGRATIONS, ...GUIDANCE_MIGRATIONS, ...IDLE_MIGRATIONS, ...APPROVAL_MARKER_MIGRATIONS, ...ACTOR_MIGRATIONS, ...LESSON_PR_MIGRATIONS, ...REVIEWER_MODEL_MIGRATIONS, ...WAKE_SOURCE_MIGRATIONS, ...SERVER_SETTINGS_MIGRATIONS, ...PULL_WATCH_MIGRATIONS, ...STACK_MIGRATIONS, ...ESCALATION_ROUTE_MIGRATIONS, ...DEPS_DECISION_MIGRATIONS, ...WORKER_STOP_REASON_MIGRATIONS, ...ASSUMPTION_MIGRATIONS, ...DATED_WAIT_MIGRATIONS, ...WAKE_RETRY_MIGRATIONS, ...MERGE_BEHIND_MIGRATIONS, ...RETARGET_PULLS_MIGRATIONS, ...STACKED_PULLS_MIGRATIONS, ...ASSESSMENT_MIGRATIONS, ...ENDED_READ_MIGRATIONS, ...HUDDLE_MIGRATIONS, ...STANDUP_MIGRATIONS, ...STANDUP_BINDING_MIGRATIONS, ...STANDUP_DELEGATION_MIGRATIONS, ...STANDUP_COMPLETED_MIGRATIONS, ...ALERTMANAGER_LOOK_MIGRATIONS, ...PULL_REQUESTER_MIGRATIONS, ...REVIEWER_REQUEST_MIGRATIONS, ...WORKER_PARK_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -1533,7 +1540,7 @@ export type WorkerStatus = "running" | "finished" | "failed" | "stopped"; * already-stopped worker is fixed by the upgrade. */ export type WorkerStopReason = "archived" | "stopped" | "runaway" | "deleted" | "misspawn"; -export type Worker = { threadId: string; bindingId: string; title: string; status: WorkerStatus; result: string | null; startedAt: number; endedAt: number | null; modelCheckPending: boolean; stopReason: WorkerStopReason | null }; +export type Worker = { threadId: string; bindingId: string; title: string; status: WorkerStatus; result: string | null; startedAt: number; endedAt: number | null; modelCheckPending: boolean; stopReason: WorkerStopReason | null; /** BB-329: the `waitingOn` the worker's own `worker_park` call recorded, or null when it did not park. Cleared when its next turn starts. */ parkedWaitingOn: string | null }; /** The sidebar's ended-list row (BB-294): the columns it renders, never `lastSnapshot`. `url` is added for the board's ended list (BB-295). */ export type EndedBindingRow = { key: string; url: string | null; kind: BindingKind; threadId: string | null; title: string | null; phase: string | null; endReason: string | null; endedAt: number }; @@ -1796,6 +1803,13 @@ export function createStore(db: Database.Database, now: () => number, options: S let setWorkerStmt: Database.Statement<[string, string | null, number | null, WorkerStopReason | null, string], unknown> | null = null; const setWorker = () => (setWorkerStmt ??= db.prepare<[string, string | null, number | null, WorkerStopReason | null, string], unknown>("UPDATE workers SET status = ?, result = ?, ended_at = ?, stop_reason = ? WHERE thread_id = ?")); const setWorkerModelCheckPending = db.prepare("UPDATE workers SET model_check_pending = ? WHERE thread_id = ?"); + // BB-329: the worker's own park call, and the clear on its next turn. Both + // are prepared on first use so a legacy store without the column is opened + // by the migration tests before either runs. + let parkWorkerStmt: Database.Statement<[string, string], unknown> | null = null; + const setWorkerPark = () => (parkWorkerStmt ??= db.prepare<[string, string], unknown>("UPDATE workers SET parked_waiting_on = ? WHERE thread_id = ?")); + let clearWorkerParkStmt: Database.Statement<[string], unknown> | null = null; + const clearWorkerPark = () => (clearWorkerParkStmt ??= db.prepare<[string], unknown>("UPDATE workers SET parked_waiting_on = NULL 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"); @@ -2051,6 +2065,8 @@ export function createStore(db: Database.Database, now: () => number, options: S // A store from before the BB-242 column reads as no reason: the legacy // fallback treats it like `archived` when the binding is open. stopReason: r.stop_reason === null || r.stop_reason === undefined ? null : (String(r.stop_reason) as WorkerStopReason), + // A store from before the BB-329 column reads as not parked. + parkedWaitingOn: r.parked_waiting_on === null || r.parked_waiting_on === undefined ? null : String(r.parked_waiting_on), }); const toSecretRequester = (r: Record): SecretRequester => ({ threadId: String(r.thread_id), @@ -3007,6 +3023,10 @@ export function createStore(db: Database.Database, now: () => number, options: S setWorker(threadId: string, status: WorkerStatus, result: string | null, stopReason: WorkerStopReason | null = null): void { const before = getWorker.get(threadId); setWorker().run(status, result, status === "running" ? null : now(), stopReason, threadId); + // BB-329: a worker's next turn clears its park. `running` is written at + // the start of a turn (thread.active, a retry), never mid-turn, so this + // is the one clear site. + if (status === "running") clearWorkerPark().run(threadId); const w = getWorker.get(threadId); // A worker finishing or being stopped moves its row at once, but a repeat // write of the same status changes nothing visible and stays silent. @@ -3016,6 +3036,17 @@ export function createStore(db: Database.Database, now: () => number, options: S setWorkerModelCheckPending(threadId: string, pending: boolean): void { setWorkerModelCheckPending.run(pending ? 1 : 0, threadId); }, + /** + * BB-329: record the calling worker's own park. The caller (the + * `worker_park` tool) has already refused a non-worker thread and an ended + * binding; this writes only the column. A worker that parks moves its row + * at once, like any visible field. + */ + parkWorker(threadId: string, waitingOn: string): void { + setWorkerPark().run(waitingOn, threadId); + const w = getWorker.get(threadId); + if (w !== undefined) projectChanged(projectIdForBinding(String(w.binding_id)), ["workers"]); + }, // 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 bfd9af62..08bce890 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -252,7 +252,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, modelCheckPending: false, stopReason: null }], + workers: [{ threadId: "thr_w1", bindingId: "b1", title: "Implement", status: "finished", result: "Should I bring the reviewer back?", startedAt: T, endedAt: T, modelCheckPending: false, stopReason: null, parkedWaitingOn: null }], workerQuestions: [{ threadId: "thr_w1", question: "Should I bring the reviewer back?", state: "live" }], changes: ["1 new comment from Sam"], }), @@ -277,6 +277,13 @@ describe("the worker finish note (BB-152)", () => { expect(note).toContain("…"); }); + // BB-329: the park is the worker's own `worker_park` call, named on the note. + it("names the worker's explicit park, from the tool call and not its text", () => { + expect(workerFinishNote("ENG-12: Implement", "Done.", false, "the reviewer")).toBe('Worker "ENG-12: Implement" finished its turn. It parked, waiting on the reviewer. Its final message: Done.'); + // The same final text without the park is a plain finish. + expect(workerFinishNote("ENG-12: Implement", "Waiting on the reviewer.", false)).toBe('Worker "ENG-12: Implement" finished its turn. Its final message: Waiting on the reviewer.'); + }); + it("prompts the steward when its waitingOn named the worker", () => { const note = workerFinishNote("ENG-12: Implement", "I posted the gate; the merge was refused.", true); expect(note).toMatch(/finished its turn while you were waiting on it/u); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index fb51a12b..5f219df3 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -146,29 +146,6 @@ export function workerQuestion(result: string | null): string | null { return null; } -/** - * Whether a worker's final message reports an error the steward must see. A - * turn that failed outright comes through `thread.failed`; this catches a - * worker that ended its turn with an error it could not get past (BB-52 rule - * 3). Only an explicit marker at the start of a line counts, so a normal - * report that mentions an error it fixed is not one. - */ -const ERROR_REPORT = /^\s*(?:error|failed|failure|exception|traceback)\b\s*[:—-]\s*\S|^\s*(?:I (?:could not|couldn't|was unable to)|Unable to)\b/imu; -export function workerReportedError(result: string | null): boolean { - return result !== null && ERROR_REPORT.test(result); -} - -/** - * Whether a worker's final message says it is parked waiting on something - * outside it (a reviewer, the owner, a build, a GitHub watch). Such a worker - * is left in flight rather than archived: its watch can wake it again, and - * its own pull request's activity stays quiet (BB-52 rule 3). - */ -const WAITING = /\b(?:waiting|awaits?|awaiting|parked|standing by)\b/iu; -export function workerWaiting(result: string | null): boolean { - return result !== null && WAITING.test(result); -} - /** How much of a worker's final message its finish note carries (BB-152). */ export const FINISH_REPORT_CHARS = 500; @@ -179,15 +156,18 @@ export const FINISH_REPORT_CHARS = 500; * the note is then the hand-off prompt, and the server queues it loud, so the * steward is woken at once and told to check whether what it waited on (a * merge, an apply) happened rather than to wait on the finished worker again. + * `parkedWaitingOn` is the worker's own `worker_park` note (BB-329): the wait + * is named from the tool call, never from the final text. */ -export function workerFinishNote(title: string, result: string | null, waitedOn: boolean): string { +export function workerFinishNote(title: string, result: string | null, waitedOn: boolean, parkedWaitingOn: string | null = null): string { const report = result === null ? "" : oneLine(result, FINISH_REPORT_CHARS); const said = report === "" ? "" : ` Its final message: ${report}`; - if (!waitedOn) return `Worker "${title}" finished its turn.${said}`; + const parked = parkedWaitingOn === null ? "" : ` It parked, waiting on ${parkedWaitingOn}.`; + if (!waitedOn) return `Worker "${title}" finished its turn.${parked}${said}`; return ( `Worker "${title}" finished its turn while you were waiting on it. ` + `Check whether what you waited on (a merge, an apply) happened; if not, do it yourself (post the gate on the pull request, then merge it with \`gh pr merge\`) or escalate. ` + - `Do not re-wait on this worker.${said}` + `Do not re-wait on this worker.${parked}${said}` ); }